Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mesa
Path: blob/21.2-virgl/src/amd/compiler/aco_register_allocation.cpp
7086 views
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 "aco_ir.h"
26
27
#include <algorithm>
28
#include <array>
29
#include <bitset>
30
#include <map>
31
#include <set>
32
#include <unordered_map>
33
#include <vector>
34
35
namespace aco {
36
namespace {
37
38
struct ra_ctx;
39
40
unsigned get_subdword_operand_stride(chip_class chip, const aco_ptr<Instruction>& instr,
41
unsigned idx, RegClass rc);
42
void add_subdword_operand(ra_ctx& ctx, aco_ptr<Instruction>& instr, unsigned idx, unsigned byte,
43
RegClass rc);
44
std::pair<unsigned, unsigned>
45
get_subdword_definition_info(Program* program, const aco_ptr<Instruction>& instr, RegClass rc);
46
void add_subdword_definition(Program* program, aco_ptr<Instruction>& instr, unsigned idx,
47
PhysReg reg);
48
49
struct assignment {
50
PhysReg reg;
51
RegClass rc;
52
uint8_t assigned = 0;
53
assignment() = default;
54
assignment(PhysReg reg_, RegClass rc_) : reg(reg_), rc(rc_), assigned(-1) {}
55
};
56
57
struct ra_ctx {
58
59
Program* program;
60
std::vector<assignment> assignments;
61
std::vector<std::unordered_map<unsigned, Temp>> renames;
62
std::vector<uint32_t> loop_header;
63
std::unordered_map<unsigned, Temp> orig_names;
64
std::unordered_map<unsigned, unsigned> affinities;
65
std::unordered_map<unsigned, Instruction*> vectors;
66
std::unordered_map<unsigned, Instruction*> split_vectors;
67
aco_ptr<Instruction> pseudo_dummy;
68
uint16_t max_used_sgpr = 0;
69
uint16_t max_used_vgpr = 0;
70
uint16_t sgpr_limit;
71
uint16_t vgpr_limit;
72
std::bitset<512> war_hint;
73
std::bitset<64> defs_done; /* see MAX_ARGS in aco_instruction_selection_setup.cpp */
74
75
ra_test_policy policy;
76
77
ra_ctx(Program* program_, ra_test_policy policy_)
78
: program(program_), assignments(program->peekAllocationId()),
79
renames(program->blocks.size()), policy(policy_)
80
{
81
pseudo_dummy.reset(
82
create_instruction<Instruction>(aco_opcode::p_parallelcopy, Format::PSEUDO, 0, 0));
83
sgpr_limit = get_addr_sgpr_from_waves(program, program->min_waves);
84
vgpr_limit = get_addr_sgpr_from_waves(program, program->min_waves);
85
}
86
};
87
88
/* Iterator type for making PhysRegInterval compatible with range-based for */
89
struct PhysRegIterator {
90
using difference_type = int;
91
using value_type = unsigned;
92
using reference = const unsigned&;
93
using pointer = const unsigned*;
94
using iterator_category = std::bidirectional_iterator_tag;
95
96
PhysReg reg;
97
98
PhysReg operator*() const { return reg; }
99
100
PhysRegIterator& operator++()
101
{
102
reg.reg_b += 4;
103
return *this;
104
}
105
106
PhysRegIterator& operator--()
107
{
108
reg.reg_b -= 4;
109
return *this;
110
}
111
112
bool operator==(PhysRegIterator oth) const { return reg == oth.reg; }
113
114
bool operator!=(PhysRegIterator oth) const { return reg != oth.reg; }
115
116
bool operator<(PhysRegIterator oth) const { return reg < oth.reg; }
117
};
118
119
/* Half-open register interval used in "sliding window"-style for-loops */
120
struct PhysRegInterval {
121
PhysReg lo_;
122
unsigned size;
123
124
/* Inclusive lower bound */
125
PhysReg lo() const { return lo_; }
126
127
/* Exclusive upper bound */
128
PhysReg hi() const { return PhysReg{lo() + size}; }
129
130
PhysRegInterval& operator+=(uint32_t stride)
131
{
132
lo_ = PhysReg{lo_.reg() + stride};
133
return *this;
134
}
135
136
bool operator!=(const PhysRegInterval& oth) const { return lo_ != oth.lo_ || size != oth.size; }
137
138
/* Construct a half-open interval, excluding the end register */
139
static PhysRegInterval from_until(PhysReg first, PhysReg end) { return {first, end - first}; }
140
141
bool contains(PhysReg reg) const { return lo() <= reg && reg < hi(); }
142
143
bool contains(const PhysRegInterval& needle) const
144
{
145
return needle.lo() >= lo() && needle.hi() <= hi();
146
}
147
148
PhysRegIterator begin() const { return {lo_}; }
149
150
PhysRegIterator end() const { return {PhysReg{lo_ + size}}; }
151
};
152
153
bool
154
intersects(const PhysRegInterval& a, const PhysRegInterval& b)
155
{
156
return ((a.lo() >= b.lo() && a.lo() < b.hi()) || (a.hi() > b.lo() && a.hi() <= b.hi()));
157
}
158
159
/* Gets the stride for full (non-subdword) registers */
160
uint32_t
161
get_stride(RegClass rc)
162
{
163
if (rc.type() == RegType::vgpr) {
164
return 1;
165
} else {
166
uint32_t size = rc.size();
167
if (size == 2) {
168
return 2;
169
} else if (size >= 4) {
170
return 4;
171
} else {
172
return 1;
173
}
174
}
175
}
176
177
PhysRegInterval
178
get_reg_bounds(Program* program, RegType type)
179
{
180
if (type == RegType::vgpr) {
181
return {PhysReg{256}, (unsigned)program->max_reg_demand.vgpr};
182
} else {
183
return {PhysReg{0}, (unsigned)program->max_reg_demand.sgpr};
184
}
185
}
186
187
struct DefInfo {
188
PhysRegInterval bounds;
189
uint8_t size;
190
uint8_t stride;
191
RegClass rc;
192
193
DefInfo(ra_ctx& ctx, aco_ptr<Instruction>& instr, RegClass rc_, int operand) : rc(rc_)
194
{
195
size = rc.size();
196
stride = get_stride(rc);
197
198
bounds = get_reg_bounds(ctx.program, rc.type());
199
200
if (rc.is_subdword() && operand >= 0) {
201
/* stride in bytes */
202
stride = get_subdword_operand_stride(ctx.program->chip_class, instr, operand, rc);
203
} else if (rc.is_subdword()) {
204
std::pair<unsigned, unsigned> info = get_subdword_definition_info(ctx.program, instr, rc);
205
stride = info.first;
206
if (info.second > rc.bytes()) {
207
rc = RegClass::get(rc.type(), info.second);
208
size = rc.size();
209
/* we might still be able to put the definition in the high half,
210
* but that's only useful for affinities and this information isn't
211
* used for them */
212
stride = align(stride, info.second);
213
if (!rc.is_subdword())
214
stride = DIV_ROUND_UP(stride, 4);
215
}
216
assert(stride > 0);
217
}
218
}
219
};
220
221
class RegisterFile {
222
public:
223
RegisterFile() { regs.fill(0); }
224
225
std::array<uint32_t, 512> regs;
226
std::map<uint32_t, std::array<uint32_t, 4>> subdword_regs;
227
228
const uint32_t& operator[](PhysReg index) const { return regs[index]; }
229
230
uint32_t& operator[](PhysReg index) { return regs[index]; }
231
232
unsigned count_zero(PhysRegInterval reg_interval)
233
{
234
unsigned res = 0;
235
for (PhysReg reg : reg_interval)
236
res += !regs[reg];
237
return res;
238
}
239
240
/* Returns true if any of the bytes in the given range are allocated or blocked */
241
bool test(PhysReg start, unsigned num_bytes)
242
{
243
for (PhysReg i = start; i.reg_b < start.reg_b + num_bytes; i = PhysReg(i + 1)) {
244
assert(i <= 511);
245
if (regs[i] & 0x0FFFFFFF)
246
return true;
247
if (regs[i] == 0xF0000000) {
248
assert(subdword_regs.find(i) != subdword_regs.end());
249
for (unsigned j = i.byte(); i * 4 + j < start.reg_b + num_bytes && j < 4; j++) {
250
if (subdword_regs[i][j])
251
return true;
252
}
253
}
254
}
255
return false;
256
}
257
258
void block(PhysReg start, RegClass rc)
259
{
260
if (rc.is_subdword())
261
fill_subdword(start, rc.bytes(), 0xFFFFFFFF);
262
else
263
fill(start, rc.size(), 0xFFFFFFFF);
264
}
265
266
bool is_blocked(PhysReg start)
267
{
268
if (regs[start] == 0xFFFFFFFF)
269
return true;
270
if (regs[start] == 0xF0000000) {
271
for (unsigned i = start.byte(); i < 4; i++)
272
if (subdword_regs[start][i] == 0xFFFFFFFF)
273
return true;
274
}
275
return false;
276
}
277
278
bool is_empty_or_blocked(PhysReg start)
279
{
280
/* Empty is 0, blocked is 0xFFFFFFFF, so to check both we compare the
281
* incremented value to 1 */
282
if (regs[start] == 0xF0000000) {
283
return subdword_regs[start][start.byte()] + 1 <= 1;
284
}
285
return regs[start] + 1 <= 1;
286
}
287
288
void clear(PhysReg start, RegClass rc)
289
{
290
if (rc.is_subdword())
291
fill_subdword(start, rc.bytes(), 0);
292
else
293
fill(start, rc.size(), 0);
294
}
295
296
void fill(Operand op)
297
{
298
if (op.regClass().is_subdword())
299
fill_subdword(op.physReg(), op.bytes(), op.tempId());
300
else
301
fill(op.physReg(), op.size(), op.tempId());
302
}
303
304
void clear(Operand op) { clear(op.physReg(), op.regClass()); }
305
306
void fill(Definition def)
307
{
308
if (def.regClass().is_subdword())
309
fill_subdword(def.physReg(), def.bytes(), def.tempId());
310
else
311
fill(def.physReg(), def.size(), def.tempId());
312
}
313
314
void clear(Definition def) { clear(def.physReg(), def.regClass()); }
315
316
unsigned get_id(PhysReg reg)
317
{
318
return regs[reg] == 0xF0000000 ? subdword_regs[reg][reg.byte()] : regs[reg];
319
}
320
321
private:
322
void fill(PhysReg start, unsigned size, uint32_t val)
323
{
324
for (unsigned i = 0; i < size; i++)
325
regs[start + i] = val;
326
}
327
328
void fill_subdword(PhysReg start, unsigned num_bytes, uint32_t val)
329
{
330
fill(start, DIV_ROUND_UP(num_bytes, 4), 0xF0000000);
331
for (PhysReg i = start; i.reg_b < start.reg_b + num_bytes; i = PhysReg(i + 1)) {
332
/* emplace or get */
333
std::array<uint32_t, 4>& sub =
334
subdword_regs.emplace(i, std::array<uint32_t, 4>{0, 0, 0, 0}).first->second;
335
for (unsigned j = i.byte(); i * 4 + j < start.reg_b + num_bytes && j < 4; j++)
336
sub[j] = val;
337
338
if (sub == std::array<uint32_t, 4>{0, 0, 0, 0}) {
339
subdword_regs.erase(i);
340
regs[i] = 0;
341
}
342
}
343
}
344
};
345
346
std::set<std::pair<unsigned, unsigned>> find_vars(ra_ctx& ctx, RegisterFile& reg_file,
347
const PhysRegInterval reg_interval);
348
349
/* helper function for debugging */
350
UNUSED void
351
print_reg(const RegisterFile& reg_file, PhysReg reg, bool has_adjacent_variable)
352
{
353
if (reg_file[reg] == 0xFFFFFFFF) {
354
printf("☐");
355
} else if (reg_file[reg]) {
356
const bool show_subdword_alloc = (reg_file[reg] == 0xF0000000);
357
if (show_subdword_alloc) {
358
const char* block_chars[] = {
359
// clang-format off
360
"?", "▘", "▝", "▀",
361
"▖", "▌", "▞", "▛",
362
"▗", "▚", "▐", "▜",
363
"▄", "▙", "▟", "▉"
364
// clang-format on
365
};
366
unsigned index = 0;
367
for (int i = 0; i < 4; ++i) {
368
if (reg_file.subdword_regs.at(reg)[i]) {
369
index |= 1 << i;
370
}
371
}
372
printf("%s", block_chars[index]);
373
} else {
374
/* Indicate filled register slot */
375
if (!has_adjacent_variable) {
376
printf("█");
377
} else {
378
/* Use a slightly shorter box to leave a small gap between adjacent variables */
379
printf("▉");
380
}
381
}
382
} else {
383
printf("·");
384
}
385
}
386
387
/* helper function for debugging */
388
UNUSED void
389
print_regs(ra_ctx& ctx, bool vgprs, RegisterFile& reg_file)
390
{
391
PhysRegInterval regs = get_reg_bounds(ctx.program, vgprs ? RegType::vgpr : RegType::sgpr);
392
char reg_char = vgprs ? 'v' : 's';
393
const int max_regs_per_line = 64;
394
395
/* print markers */
396
printf(" ");
397
for (int i = 0; i < std::min<int>(max_regs_per_line, ROUND_DOWN_TO(regs.size, 4)); i += 4) {
398
printf("%-3.2u ", i);
399
}
400
printf("\n");
401
402
/* print usage */
403
auto line_begin_it = regs.begin();
404
while (line_begin_it != regs.end()) {
405
const int regs_in_line =
406
std::min<int>(max_regs_per_line, std::distance(line_begin_it, regs.end()));
407
408
if (line_begin_it == regs.begin()) {
409
printf("%cgprs: ", reg_char);
410
} else {
411
printf(" %+4d ", std::distance(regs.begin(), line_begin_it));
412
}
413
const auto line_end_it = std::next(line_begin_it, regs_in_line);
414
415
for (auto reg_it = line_begin_it; reg_it != line_end_it; ++reg_it) {
416
bool has_adjacent_variable =
417
(std::next(reg_it) != line_end_it &&
418
reg_file[*reg_it] != reg_file[*std::next(reg_it)] && reg_file[*std::next(reg_it)]);
419
print_reg(reg_file, *reg_it, has_adjacent_variable);
420
}
421
422
line_begin_it = line_end_it;
423
printf("\n");
424
}
425
426
const unsigned free_regs =
427
std::count_if(regs.begin(), regs.end(), [&](auto reg) { return !reg_file[reg]; });
428
printf("%u/%u used, %u/%u free\n", regs.size - free_regs, regs.size, free_regs, regs.size);
429
430
/* print assignments ordered by registers */
431
std::map<PhysReg, std::pair<unsigned, unsigned>>
432
regs_to_vars; /* maps to byte size and temp id */
433
for (const auto& size_id : find_vars(ctx, reg_file, regs)) {
434
auto reg = ctx.assignments[size_id.second].reg;
435
ASSERTED auto inserted = regs_to_vars.emplace(reg, size_id);
436
assert(inserted.second);
437
}
438
439
for (const auto& reg_and_var : regs_to_vars) {
440
const auto& first_reg = reg_and_var.first;
441
const auto& size_id = reg_and_var.second;
442
443
printf("%%%u ", size_id.second);
444
if (ctx.orig_names.count(size_id.second) &&
445
ctx.orig_names[size_id.second].id() != size_id.second) {
446
printf("(was %%%d) ", ctx.orig_names[size_id.second].id());
447
}
448
printf("= %c[%d", reg_char, first_reg.reg() - regs.lo());
449
PhysReg last_reg = first_reg.advance(size_id.first - 1);
450
if (first_reg.reg() != last_reg.reg()) {
451
assert(first_reg.byte() == 0 && last_reg.byte() == 3);
452
printf("-%d", last_reg.reg() - regs.lo());
453
}
454
printf("]");
455
if (first_reg.byte() != 0 || last_reg.byte() != 3) {
456
printf("[%d:%d]", first_reg.byte() * 8, (last_reg.byte() + 1) * 8);
457
}
458
printf("\n");
459
}
460
}
461
462
unsigned
463
get_subdword_operand_stride(chip_class chip, const aco_ptr<Instruction>& instr, unsigned idx,
464
RegClass rc)
465
{
466
/* v_readfirstlane_b32 cannot use SDWA */
467
if (instr->opcode == aco_opcode::p_as_uniform)
468
return 4;
469
if (instr->isPseudo() && chip >= GFX8)
470
return rc.bytes() % 2 == 0 ? 2 : 1;
471
472
if (instr->opcode == aco_opcode::v_cvt_f32_ubyte0) {
473
return 1;
474
} else if (can_use_SDWA(chip, instr, false)) {
475
return rc.bytes() % 2 == 0 ? 2 : 1;
476
} else if (rc.bytes() == 2 && can_use_opsel(chip, instr->opcode, idx, 1)) {
477
return 2;
478
} else if (instr->isVOP3P()) {
479
return 2;
480
}
481
482
switch (instr->opcode) {
483
case aco_opcode::ds_write_b8:
484
case aco_opcode::ds_write_b16: return chip >= GFX8 ? 2 : 4;
485
case aco_opcode::buffer_store_byte:
486
case aco_opcode::buffer_store_short:
487
case aco_opcode::flat_store_byte:
488
case aco_opcode::flat_store_short:
489
case aco_opcode::scratch_store_byte:
490
case aco_opcode::scratch_store_short:
491
case aco_opcode::global_store_byte:
492
case aco_opcode::global_store_short: return chip >= GFX9 ? 2 : 4;
493
default: break;
494
}
495
496
return 4;
497
}
498
499
void
500
add_subdword_operand(ra_ctx& ctx, aco_ptr<Instruction>& instr, unsigned idx, unsigned byte,
501
RegClass rc)
502
{
503
chip_class chip = ctx.program->chip_class;
504
if (instr->isPseudo() || byte == 0)
505
return;
506
507
assert(rc.bytes() <= 2);
508
509
if (!instr->usesModifiers() && instr->opcode == aco_opcode::v_cvt_f32_ubyte0) {
510
switch (byte) {
511
case 0: instr->opcode = aco_opcode::v_cvt_f32_ubyte0; break;
512
case 1: instr->opcode = aco_opcode::v_cvt_f32_ubyte1; break;
513
case 2: instr->opcode = aco_opcode::v_cvt_f32_ubyte2; break;
514
case 3: instr->opcode = aco_opcode::v_cvt_f32_ubyte3; break;
515
}
516
return;
517
} else if (can_use_SDWA(chip, instr, false)) {
518
aco_ptr<Instruction> tmp = convert_to_SDWA(chip, instr);
519
return;
520
} else if (rc.bytes() == 2 && can_use_opsel(chip, instr->opcode, idx, byte / 2)) {
521
instr->vop3().opsel |= (byte / 2) << idx;
522
return;
523
} else if (instr->isVOP3P() && byte == 2) {
524
VOP3P_instruction& vop3p = instr->vop3p();
525
assert(!(vop3p.opsel_lo & (1 << idx)));
526
vop3p.opsel_lo |= 1 << idx;
527
vop3p.opsel_hi |= 1 << idx;
528
return;
529
}
530
531
if (chip >= GFX8 && instr->opcode == aco_opcode::ds_write_b8 && byte == 2) {
532
instr->opcode = aco_opcode::ds_write_b8_d16_hi;
533
return;
534
}
535
if (chip >= GFX8 && instr->opcode == aco_opcode::ds_write_b16 && byte == 2) {
536
instr->opcode = aco_opcode::ds_write_b16_d16_hi;
537
return;
538
}
539
540
if (chip >= GFX9 && byte == 2) {
541
if (instr->opcode == aco_opcode::buffer_store_byte)
542
instr->opcode = aco_opcode::buffer_store_byte_d16_hi;
543
else if (instr->opcode == aco_opcode::buffer_store_short)
544
instr->opcode = aco_opcode::buffer_store_short_d16_hi;
545
else if (instr->opcode == aco_opcode::flat_store_byte)
546
instr->opcode = aco_opcode::flat_store_byte_d16_hi;
547
else if (instr->opcode == aco_opcode::flat_store_short)
548
instr->opcode = aco_opcode::flat_store_short_d16_hi;
549
else if (instr->opcode == aco_opcode::scratch_store_byte)
550
instr->opcode = aco_opcode::scratch_store_byte_d16_hi;
551
else if (instr->opcode == aco_opcode::scratch_store_short)
552
instr->opcode = aco_opcode::scratch_store_short_d16_hi;
553
else if (instr->opcode == aco_opcode::global_store_byte)
554
instr->opcode = aco_opcode::global_store_byte_d16_hi;
555
else if (instr->opcode == aco_opcode::global_store_short)
556
instr->opcode = aco_opcode::global_store_short_d16_hi;
557
else
558
unreachable("Something went wrong: Impossible register assignment.");
559
}
560
}
561
562
/* minimum_stride, bytes_written */
563
std::pair<unsigned, unsigned>
564
get_subdword_definition_info(Program* program, const aco_ptr<Instruction>& instr, RegClass rc)
565
{
566
chip_class chip = program->chip_class;
567
568
if (instr->isPseudo() && chip >= GFX8)
569
return std::make_pair(rc.bytes() % 2 == 0 ? 2 : 1, rc.bytes());
570
else if (instr->isPseudo())
571
return std::make_pair(4, rc.size() * 4u);
572
573
unsigned bytes_written = chip >= GFX10 ? rc.bytes() : 4u;
574
switch (instr->opcode) {
575
case aco_opcode::v_mad_f16:
576
case aco_opcode::v_mad_u16:
577
case aco_opcode::v_mad_i16:
578
case aco_opcode::v_fma_f16:
579
case aco_opcode::v_div_fixup_f16:
580
case aco_opcode::v_interp_p2_f16: bytes_written = chip >= GFX9 ? rc.bytes() : 4u; break;
581
default: break;
582
}
583
bytes_written = bytes_written > 4 ? align(bytes_written, 4) : bytes_written;
584
bytes_written = MAX2(bytes_written, instr_info.definition_size[(int)instr->opcode] / 8u);
585
586
if (can_use_SDWA(chip, instr, false)) {
587
return std::make_pair(rc.bytes(), rc.bytes());
588
} else if (rc.bytes() == 2 && can_use_opsel(chip, instr->opcode, -1, 1)) {
589
return std::make_pair(2u, bytes_written);
590
}
591
592
switch (instr->opcode) {
593
case aco_opcode::buffer_load_ubyte_d16:
594
case aco_opcode::buffer_load_short_d16:
595
case aco_opcode::flat_load_ubyte_d16:
596
case aco_opcode::flat_load_short_d16:
597
case aco_opcode::scratch_load_ubyte_d16:
598
case aco_opcode::scratch_load_short_d16:
599
case aco_opcode::global_load_ubyte_d16:
600
case aco_opcode::global_load_short_d16:
601
case aco_opcode::ds_read_u8_d16:
602
case aco_opcode::ds_read_u16_d16:
603
if (chip >= GFX9 && !program->dev.sram_ecc_enabled)
604
return std::make_pair(2u, 2u);
605
else
606
return std::make_pair(2u, 4u);
607
case aco_opcode::v_fma_mixlo_f16: return std::make_pair(2u, 2u);
608
default: break;
609
}
610
611
return std::make_pair(4u, bytes_written);
612
}
613
614
void
615
add_subdword_definition(Program* program, aco_ptr<Instruction>& instr, unsigned idx, PhysReg reg)
616
{
617
RegClass rc = instr->definitions[idx].regClass();
618
chip_class chip = program->chip_class;
619
620
if (instr->isPseudo()) {
621
return;
622
} else if (can_use_SDWA(chip, instr, false)) {
623
unsigned def_size = instr_info.definition_size[(int)instr->opcode];
624
if (reg.byte() || chip < GFX10 || def_size > rc.bytes() * 8u)
625
convert_to_SDWA(chip, instr);
626
return;
627
} else if (reg.byte() && rc.bytes() == 2 &&
628
can_use_opsel(chip, instr->opcode, -1, reg.byte() / 2)) {
629
VOP3_instruction& vop3 = instr->vop3();
630
if (reg.byte() == 2)
631
vop3.opsel |= (1 << 3); /* dst in high half */
632
return;
633
}
634
635
if (reg.byte() == 2) {
636
if (instr->opcode == aco_opcode::v_fma_mixlo_f16)
637
instr->opcode = aco_opcode::v_fma_mixhi_f16;
638
else if (instr->opcode == aco_opcode::buffer_load_ubyte_d16)
639
instr->opcode = aco_opcode::buffer_load_ubyte_d16_hi;
640
else if (instr->opcode == aco_opcode::buffer_load_short_d16)
641
instr->opcode = aco_opcode::buffer_load_short_d16_hi;
642
else if (instr->opcode == aco_opcode::flat_load_ubyte_d16)
643
instr->opcode = aco_opcode::flat_load_ubyte_d16_hi;
644
else if (instr->opcode == aco_opcode::flat_load_short_d16)
645
instr->opcode = aco_opcode::flat_load_short_d16_hi;
646
else if (instr->opcode == aco_opcode::scratch_load_ubyte_d16)
647
instr->opcode = aco_opcode::scratch_load_ubyte_d16_hi;
648
else if (instr->opcode == aco_opcode::scratch_load_short_d16)
649
instr->opcode = aco_opcode::scratch_load_short_d16_hi;
650
else if (instr->opcode == aco_opcode::global_load_ubyte_d16)
651
instr->opcode = aco_opcode::global_load_ubyte_d16_hi;
652
else if (instr->opcode == aco_opcode::global_load_short_d16)
653
instr->opcode = aco_opcode::global_load_short_d16_hi;
654
else if (instr->opcode == aco_opcode::ds_read_u8_d16)
655
instr->opcode = aco_opcode::ds_read_u8_d16_hi;
656
else if (instr->opcode == aco_opcode::ds_read_u16_d16)
657
instr->opcode = aco_opcode::ds_read_u16_d16_hi;
658
else
659
unreachable("Something went wrong: Impossible register assignment.");
660
}
661
}
662
663
void
664
adjust_max_used_regs(ra_ctx& ctx, RegClass rc, unsigned reg)
665
{
666
uint16_t max_addressible_sgpr = ctx.sgpr_limit;
667
unsigned size = rc.size();
668
if (rc.type() == RegType::vgpr) {
669
assert(reg >= 256);
670
uint16_t hi = reg - 256 + size - 1;
671
ctx.max_used_vgpr = std::max(ctx.max_used_vgpr, hi);
672
} else if (reg + rc.size() <= max_addressible_sgpr) {
673
uint16_t hi = reg + size - 1;
674
ctx.max_used_sgpr = std::max(ctx.max_used_sgpr, std::min(hi, max_addressible_sgpr));
675
}
676
}
677
678
enum UpdateRenames {
679
rename_not_killed_ops = 0x1,
680
fill_killed_ops = 0x2,
681
};
682
MESA_DEFINE_CPP_ENUM_BITFIELD_OPERATORS(UpdateRenames);
683
684
void
685
update_renames(ra_ctx& ctx, RegisterFile& reg_file,
686
std::vector<std::pair<Operand, Definition>>& parallelcopies,
687
aco_ptr<Instruction>& instr, UpdateRenames flags)
688
{
689
/* clear operands */
690
for (std::pair<Operand, Definition>& copy : parallelcopies) {
691
/* the definitions with id are not from this function and already handled */
692
if (copy.second.isTemp())
693
continue;
694
reg_file.clear(copy.first);
695
}
696
697
/* allocate id's and rename operands: this is done transparently here */
698
auto it = parallelcopies.begin();
699
while (it != parallelcopies.end()) {
700
if (it->second.isTemp()) {
701
++it;
702
continue;
703
}
704
705
/* check if we moved a definition: change the register and remove copy */
706
bool is_def = false;
707
for (Definition& def : instr->definitions) {
708
if (def.isTemp() && def.getTemp() == it->first.getTemp()) {
709
// FIXME: ensure that the definition can use this reg
710
def.setFixed(it->second.physReg());
711
reg_file.fill(def);
712
ctx.assignments[def.tempId()].reg = def.physReg();
713
it = parallelcopies.erase(it);
714
is_def = true;
715
break;
716
}
717
}
718
if (is_def)
719
continue;
720
721
/* check if we moved another parallelcopy definition */
722
for (std::pair<Operand, Definition>& other : parallelcopies) {
723
if (!other.second.isTemp())
724
continue;
725
if (it->first.getTemp() == other.second.getTemp()) {
726
other.second.setFixed(it->second.physReg());
727
ctx.assignments[other.second.tempId()].reg = other.second.physReg();
728
it = parallelcopies.erase(it);
729
is_def = true;
730
/* check if we moved an operand, again */
731
bool fill = true;
732
for (Operand& op : instr->operands) {
733
if (op.isTemp() && op.tempId() == other.second.tempId()) {
734
// FIXME: ensure that the operand can use this reg
735
op.setFixed(other.second.physReg());
736
fill = (flags & fill_killed_ops) || !op.isKillBeforeDef();
737
}
738
}
739
if (fill)
740
reg_file.fill(other.second);
741
break;
742
}
743
}
744
if (is_def)
745
continue;
746
747
std::pair<Operand, Definition>& copy = *it;
748
copy.second.setTemp(ctx.program->allocateTmp(copy.second.regClass()));
749
ctx.assignments.emplace_back(copy.second.physReg(), copy.second.regClass());
750
assert(ctx.assignments.size() == ctx.program->peekAllocationId());
751
752
/* check if we moved an operand */
753
bool first = true;
754
bool fill = true;
755
for (unsigned i = 0; i < instr->operands.size(); i++) {
756
Operand& op = instr->operands[i];
757
if (!op.isTemp())
758
continue;
759
if (op.tempId() == copy.first.tempId()) {
760
bool omit_renaming = !(flags & rename_not_killed_ops) && !op.isKillBeforeDef();
761
for (std::pair<Operand, Definition>& pc : parallelcopies) {
762
PhysReg def_reg = pc.second.physReg();
763
omit_renaming &= def_reg > copy.first.physReg()
764
? (copy.first.physReg() + copy.first.size() <= def_reg.reg())
765
: (def_reg + pc.second.size() <= copy.first.physReg().reg());
766
}
767
if (omit_renaming) {
768
if (first)
769
op.setFirstKill(true);
770
else
771
op.setKill(true);
772
first = false;
773
continue;
774
}
775
op.setTemp(copy.second.getTemp());
776
op.setFixed(copy.second.physReg());
777
778
fill = (flags & fill_killed_ops) || !op.isKillBeforeDef();
779
}
780
}
781
782
if (fill)
783
reg_file.fill(copy.second);
784
785
++it;
786
}
787
}
788
789
std::pair<PhysReg, bool>
790
get_reg_simple(ra_ctx& ctx, RegisterFile& reg_file, DefInfo info)
791
{
792
const PhysRegInterval& bounds = info.bounds;
793
uint32_t size = info.size;
794
uint32_t stride = info.rc.is_subdword() ? DIV_ROUND_UP(info.stride, 4) : info.stride;
795
RegClass rc = info.rc;
796
797
DefInfo new_info = info;
798
new_info.rc = RegClass(rc.type(), size);
799
for (unsigned new_stride = 16; new_stride > stride; new_stride /= 2) {
800
if (size % new_stride)
801
continue;
802
new_info.stride = new_stride;
803
std::pair<PhysReg, bool> res = get_reg_simple(ctx, reg_file, new_info);
804
if (res.second)
805
return res;
806
}
807
808
auto is_free = [&](PhysReg reg_index)
809
{ return reg_file[reg_index] == 0 && !ctx.war_hint[reg_index]; };
810
811
if (stride == 1) {
812
/* best fit algorithm: find the smallest gap to fit in the variable */
813
PhysRegInterval best_gap{PhysReg{0}, UINT_MAX};
814
const unsigned max_gpr =
815
(rc.type() == RegType::vgpr) ? (256 + ctx.max_used_vgpr) : ctx.max_used_sgpr;
816
817
PhysRegIterator reg_it = bounds.begin();
818
const PhysRegIterator end_it =
819
std::min(bounds.end(), std::max(PhysRegIterator{PhysReg{max_gpr + 1}}, reg_it));
820
while (reg_it != bounds.end()) {
821
/* Find the next chunk of available register slots */
822
reg_it = std::find_if(reg_it, end_it, is_free);
823
auto next_nonfree_it = std::find_if_not(reg_it, end_it, is_free);
824
if (reg_it == bounds.end()) {
825
break;
826
}
827
828
if (next_nonfree_it == end_it) {
829
/* All registers past max_used_gpr are free */
830
next_nonfree_it = bounds.end();
831
}
832
833
PhysRegInterval gap = PhysRegInterval::from_until(*reg_it, *next_nonfree_it);
834
835
/* early return on exact matches */
836
if (size == gap.size) {
837
adjust_max_used_regs(ctx, rc, gap.lo());
838
return {gap.lo(), true};
839
}
840
841
/* check if it fits and the gap size is smaller */
842
if (size < gap.size && gap.size < best_gap.size) {
843
best_gap = gap;
844
}
845
846
/* Move past the processed chunk */
847
reg_it = next_nonfree_it;
848
}
849
850
if (best_gap.size == UINT_MAX)
851
return {{}, false};
852
853
/* find best position within gap by leaving a good stride for other variables*/
854
unsigned buffer = best_gap.size - size;
855
if (buffer > 1) {
856
if (((best_gap.lo() + size) % 8 != 0 && (best_gap.lo() + buffer) % 8 == 0) ||
857
((best_gap.lo() + size) % 4 != 0 && (best_gap.lo() + buffer) % 4 == 0) ||
858
((best_gap.lo() + size) % 2 != 0 && (best_gap.lo() + buffer) % 2 == 0))
859
best_gap = {PhysReg{best_gap.lo() + buffer}, best_gap.size - buffer};
860
}
861
862
adjust_max_used_regs(ctx, rc, best_gap.lo());
863
return {best_gap.lo(), true};
864
}
865
866
for (PhysRegInterval reg_win = {bounds.lo(), size}; reg_win.hi() <= bounds.hi();
867
reg_win += stride) {
868
if (reg_file[reg_win.lo()] != 0) {
869
continue;
870
}
871
872
bool is_valid = std::all_of(std::next(reg_win.begin()), reg_win.end(), is_free);
873
if (is_valid) {
874
adjust_max_used_regs(ctx, rc, reg_win.lo());
875
return {reg_win.lo(), true};
876
}
877
}
878
879
/* do this late because using the upper bytes of a register can require
880
* larger instruction encodings or copies
881
* TODO: don't do this in situations where it doesn't benefit */
882
if (rc.is_subdword()) {
883
for (std::pair<const uint32_t, std::array<uint32_t, 4>>& entry : reg_file.subdword_regs) {
884
assert(reg_file[PhysReg{entry.first}] == 0xF0000000);
885
if (!bounds.contains(PhysReg{entry.first}))
886
continue;
887
888
for (unsigned i = 0; i < 4; i += info.stride) {
889
/* check if there's a block of free bytes large enough to hold the register */
890
bool reg_found =
891
std::all_of(&entry.second[i], &entry.second[std::min(4u, i + rc.bytes())],
892
[](unsigned v) { return v == 0; });
893
894
/* check if also the neighboring reg is free if needed */
895
if (reg_found && i + rc.bytes() > 4)
896
reg_found = (reg_file[PhysReg{entry.first + 1}] == 0);
897
898
if (reg_found) {
899
PhysReg res{entry.first};
900
res.reg_b += i;
901
adjust_max_used_regs(ctx, rc, entry.first);
902
return {res, true};
903
}
904
}
905
}
906
}
907
908
return {{}, false};
909
}
910
911
/* collect variables from a register area and clear reg_file */
912
std::set<std::pair<unsigned, unsigned>>
913
find_vars(ra_ctx& ctx, RegisterFile& reg_file, const PhysRegInterval reg_interval)
914
{
915
std::set<std::pair<unsigned, unsigned>> vars;
916
for (PhysReg j : reg_interval) {
917
if (reg_file.is_blocked(j))
918
continue;
919
if (reg_file[j] == 0xF0000000) {
920
for (unsigned k = 0; k < 4; k++) {
921
unsigned id = reg_file.subdword_regs[j][k];
922
if (id) {
923
assignment& var = ctx.assignments[id];
924
vars.emplace(var.rc.bytes(), id);
925
}
926
}
927
} else if (reg_file[j] != 0) {
928
unsigned id = reg_file[j];
929
assignment& var = ctx.assignments[id];
930
vars.emplace(var.rc.bytes(), id);
931
}
932
}
933
return vars;
934
}
935
936
/* collect variables from a register area and clear reg_file */
937
std::set<std::pair<unsigned, unsigned>>
938
collect_vars(ra_ctx& ctx, RegisterFile& reg_file, const PhysRegInterval reg_interval)
939
{
940
std::set<std::pair<unsigned, unsigned>> vars = find_vars(ctx, reg_file, reg_interval);
941
for (std::pair<unsigned, unsigned> size_id : vars) {
942
assignment& var = ctx.assignments[size_id.second];
943
reg_file.clear(var.reg, var.rc);
944
}
945
return vars;
946
}
947
948
bool
949
get_regs_for_copies(ra_ctx& ctx, RegisterFile& reg_file,
950
std::vector<std::pair<Operand, Definition>>& parallelcopies,
951
const std::set<std::pair<unsigned, unsigned>>& vars,
952
const PhysRegInterval bounds, aco_ptr<Instruction>& instr,
953
const PhysRegInterval def_reg)
954
{
955
/* variables are sorted from small sized to large */
956
/* NOTE: variables are also sorted by ID. this only affects a very small number of shaders
957
* slightly though. */
958
for (std::set<std::pair<unsigned, unsigned>>::const_reverse_iterator it = vars.rbegin();
959
it != vars.rend(); ++it) {
960
unsigned id = it->second;
961
assignment& var = ctx.assignments[id];
962
DefInfo info = DefInfo(ctx, ctx.pseudo_dummy, var.rc, -1);
963
uint32_t size = info.size;
964
965
/* check if this is a dead operand, then we can re-use the space from the definition
966
* also use the correct stride for sub-dword operands */
967
bool is_dead_operand = false;
968
for (unsigned i = 0; !is_phi(instr) && i < instr->operands.size(); i++) {
969
if (instr->operands[i].isTemp() && instr->operands[i].tempId() == id) {
970
if (instr->operands[i].isKillBeforeDef())
971
is_dead_operand = true;
972
info = DefInfo(ctx, instr, var.rc, i);
973
break;
974
}
975
}
976
977
std::pair<PhysReg, bool> res;
978
if (is_dead_operand) {
979
if (instr->opcode == aco_opcode::p_create_vector) {
980
PhysReg reg(def_reg.lo());
981
for (unsigned i = 0; i < instr->operands.size(); i++) {
982
if (instr->operands[i].isTemp() && instr->operands[i].tempId() == id) {
983
res = {reg, (!var.rc.is_subdword() || (reg.byte() % info.stride == 0)) &&
984
!reg_file.test(reg, var.rc.bytes())};
985
break;
986
}
987
reg.reg_b += instr->operands[i].bytes();
988
}
989
if (!res.second)
990
res = {var.reg, !reg_file.test(var.reg, var.rc.bytes())};
991
} else {
992
info.bounds = def_reg;
993
res = get_reg_simple(ctx, reg_file, info);
994
}
995
} else {
996
/* Try to find space within the bounds but outside of the definition */
997
info.bounds = PhysRegInterval::from_until(bounds.lo(), MIN2(def_reg.lo(), bounds.hi()));
998
res = get_reg_simple(ctx, reg_file, info);
999
if (!res.second && def_reg.hi() <= bounds.hi()) {
1000
unsigned lo = (def_reg.hi() + info.stride - 1) & ~(info.stride - 1);
1001
info.bounds = PhysRegInterval::from_until(PhysReg{lo}, bounds.hi());
1002
res = get_reg_simple(ctx, reg_file, info);
1003
}
1004
}
1005
1006
if (res.second) {
1007
/* mark the area as blocked */
1008
reg_file.block(res.first, var.rc);
1009
1010
/* create parallelcopy pair (without definition id) */
1011
Temp tmp = Temp(id, var.rc);
1012
Operand pc_op = Operand(tmp);
1013
pc_op.setFixed(var.reg);
1014
Definition pc_def = Definition(res.first, pc_op.regClass());
1015
parallelcopies.emplace_back(pc_op, pc_def);
1016
continue;
1017
}
1018
1019
PhysReg best_pos = bounds.lo();
1020
unsigned num_moves = 0xFF;
1021
unsigned num_vars = 0;
1022
1023
/* we use a sliding window to find potential positions */
1024
unsigned stride = var.rc.is_subdword() ? 1 : info.stride;
1025
for (PhysRegInterval reg_win{bounds.lo(), size}; reg_win.hi() <= bounds.hi();
1026
reg_win += stride) {
1027
if (!is_dead_operand && intersects(reg_win, def_reg))
1028
continue;
1029
1030
/* second, check that we have at most k=num_moves elements in the window
1031
* and no element is larger than the currently processed one */
1032
unsigned k = 0;
1033
unsigned n = 0;
1034
unsigned last_var = 0;
1035
bool found = true;
1036
for (PhysReg j : reg_win) {
1037
if (reg_file[j] == 0 || reg_file[j] == last_var)
1038
continue;
1039
1040
if (reg_file.is_blocked(j) || k > num_moves) {
1041
found = false;
1042
break;
1043
}
1044
if (reg_file[j] == 0xF0000000) {
1045
k += 1;
1046
n++;
1047
continue;
1048
}
1049
/* we cannot split live ranges of linear vgprs */
1050
if (ctx.assignments[reg_file[j]].rc & (1 << 6)) {
1051
found = false;
1052
break;
1053
}
1054
bool is_kill = false;
1055
for (const Operand& op : instr->operands) {
1056
if (op.isTemp() && op.isKillBeforeDef() && op.tempId() == reg_file[j]) {
1057
is_kill = true;
1058
break;
1059
}
1060
}
1061
if (!is_kill && ctx.assignments[reg_file[j]].rc.size() >= size) {
1062
found = false;
1063
break;
1064
}
1065
1066
k += ctx.assignments[reg_file[j]].rc.size();
1067
last_var = reg_file[j];
1068
n++;
1069
if (k > num_moves || (k == num_moves && n <= num_vars)) {
1070
found = false;
1071
break;
1072
}
1073
}
1074
1075
if (found) {
1076
best_pos = reg_win.lo();
1077
num_moves = k;
1078
num_vars = n;
1079
}
1080
}
1081
1082
/* FIXME: we messed up and couldn't find space for the variables to be copied */
1083
if (num_moves == 0xFF)
1084
return false;
1085
1086
PhysRegInterval reg_win{best_pos, size};
1087
1088
/* collect variables and block reg file */
1089
std::set<std::pair<unsigned, unsigned>> new_vars = collect_vars(ctx, reg_file, reg_win);
1090
1091
/* mark the area as blocked */
1092
reg_file.block(reg_win.lo(), var.rc);
1093
adjust_max_used_regs(ctx, var.rc, reg_win.lo());
1094
1095
if (!get_regs_for_copies(ctx, reg_file, parallelcopies, new_vars, bounds, instr, def_reg))
1096
return false;
1097
1098
/* create parallelcopy pair (without definition id) */
1099
Temp tmp = Temp(id, var.rc);
1100
Operand pc_op = Operand(tmp);
1101
pc_op.setFixed(var.reg);
1102
Definition pc_def = Definition(reg_win.lo(), pc_op.regClass());
1103
parallelcopies.emplace_back(pc_op, pc_def);
1104
}
1105
1106
return true;
1107
}
1108
1109
std::pair<PhysReg, bool>
1110
get_reg_impl(ra_ctx& ctx, RegisterFile& reg_file,
1111
std::vector<std::pair<Operand, Definition>>& parallelcopies, const DefInfo& info,
1112
aco_ptr<Instruction>& instr)
1113
{
1114
const PhysRegInterval& bounds = info.bounds;
1115
uint32_t size = info.size;
1116
uint32_t stride = info.stride;
1117
RegClass rc = info.rc;
1118
1119
/* check how many free regs we have */
1120
unsigned regs_free = reg_file.count_zero(bounds);
1121
1122
/* mark and count killed operands */
1123
unsigned killed_ops = 0;
1124
std::bitset<256> is_killed_operand; /* per-register */
1125
for (unsigned j = 0; !is_phi(instr) && j < instr->operands.size(); j++) {
1126
Operand& op = instr->operands[j];
1127
if (op.isTemp() && op.isFirstKillBeforeDef() && bounds.contains(op.physReg()) &&
1128
!reg_file.test(PhysReg{op.physReg().reg()}, align(op.bytes() + op.physReg().byte(), 4))) {
1129
assert(op.isFixed());
1130
1131
for (unsigned i = 0; i < op.size(); ++i) {
1132
is_killed_operand[(op.physReg() & 0xff) + i] = true;
1133
}
1134
1135
killed_ops += op.getTemp().size();
1136
}
1137
}
1138
1139
assert(regs_free >= size);
1140
/* we might have to move dead operands to dst in order to make space */
1141
unsigned op_moves = 0;
1142
1143
if (size > (regs_free - killed_ops))
1144
op_moves = size - (regs_free - killed_ops);
1145
1146
/* find the best position to place the definition */
1147
PhysRegInterval best_win = {bounds.lo(), size};
1148
unsigned num_moves = 0xFF;
1149
unsigned num_vars = 0;
1150
1151
/* we use a sliding window to check potential positions */
1152
for (PhysRegInterval reg_win = {bounds.lo(), size}; reg_win.hi() <= bounds.hi();
1153
reg_win += stride) {
1154
/* first check if the register window starts in the middle of an
1155
* allocated variable: this is what we have to fix to allow for
1156
* num_moves > size */
1157
if (reg_win.lo() > bounds.lo() && !reg_file.is_empty_or_blocked(reg_win.lo()) &&
1158
reg_file.get_id(reg_win.lo()) == reg_file.get_id(reg_win.lo().advance(-1)))
1159
continue;
1160
if (reg_win.hi() < bounds.hi() && !reg_file.is_empty_or_blocked(reg_win.hi().advance(-1)) &&
1161
reg_file.get_id(reg_win.hi().advance(-1)) == reg_file.get_id(reg_win.hi()))
1162
continue;
1163
1164
/* second, check that we have at most k=num_moves elements in the window
1165
* and no element is larger than the currently processed one */
1166
unsigned k = op_moves;
1167
unsigned n = 0;
1168
unsigned remaining_op_moves = op_moves;
1169
unsigned last_var = 0;
1170
bool found = true;
1171
bool aligned = rc == RegClass::v4 && reg_win.lo() % 4 == 0;
1172
for (const PhysReg j : reg_win) {
1173
/* dead operands effectively reduce the number of estimated moves */
1174
if (is_killed_operand[j & 0xFF]) {
1175
if (remaining_op_moves) {
1176
k--;
1177
remaining_op_moves--;
1178
}
1179
continue;
1180
}
1181
1182
if (reg_file[j] == 0 || reg_file[j] == last_var)
1183
continue;
1184
1185
if (reg_file[j] == 0xF0000000) {
1186
k += 1;
1187
n++;
1188
continue;
1189
}
1190
1191
if (ctx.assignments[reg_file[j]].rc.size() >= size) {
1192
found = false;
1193
break;
1194
}
1195
1196
/* we cannot split live ranges of linear vgprs */
1197
if (ctx.assignments[reg_file[j]].rc & (1 << 6)) {
1198
found = false;
1199
break;
1200
}
1201
1202
k += ctx.assignments[reg_file[j]].rc.size();
1203
n++;
1204
last_var = reg_file[j];
1205
}
1206
1207
if (!found || k > num_moves)
1208
continue;
1209
if (k == num_moves && n < num_vars)
1210
continue;
1211
if (!aligned && k == num_moves && n == num_vars)
1212
continue;
1213
1214
if (found) {
1215
best_win = reg_win;
1216
num_moves = k;
1217
num_vars = n;
1218
}
1219
}
1220
1221
if (num_moves == 0xFF)
1222
return {{}, false};
1223
1224
/* now, we figured the placement for our definition */
1225
RegisterFile tmp_file(reg_file);
1226
std::set<std::pair<unsigned, unsigned>> vars = collect_vars(ctx, tmp_file, best_win);
1227
1228
if (instr->opcode == aco_opcode::p_create_vector) {
1229
/* move killed operands which aren't yet at the correct position (GFX9+)
1230
* or which are in the definition space */
1231
PhysReg reg = best_win.lo();
1232
for (Operand& op : instr->operands) {
1233
if (op.isTemp() && op.isFirstKillBeforeDef() && op.getTemp().type() == rc.type()) {
1234
if (op.physReg() != reg && (ctx.program->chip_class >= GFX9 ||
1235
(op.physReg().advance(op.bytes()) > best_win.lo() &&
1236
op.physReg() < best_win.hi()))) {
1237
vars.emplace(op.bytes(), op.tempId());
1238
tmp_file.clear(op);
1239
} else {
1240
tmp_file.fill(op);
1241
}
1242
}
1243
reg.reg_b += op.bytes();
1244
}
1245
} else if (!is_phi(instr)) {
1246
/* re-enable killed operands */
1247
for (Operand& op : instr->operands) {
1248
if (op.isTemp() && op.isFirstKillBeforeDef())
1249
tmp_file.fill(op);
1250
}
1251
}
1252
1253
std::vector<std::pair<Operand, Definition>> pc;
1254
if (!get_regs_for_copies(ctx, tmp_file, pc, vars, bounds, instr, best_win))
1255
return {{}, false};
1256
1257
parallelcopies.insert(parallelcopies.end(), pc.begin(), pc.end());
1258
1259
adjust_max_used_regs(ctx, rc, best_win.lo());
1260
return {best_win.lo(), true};
1261
}
1262
1263
bool
1264
get_reg_specified(ra_ctx& ctx, RegisterFile& reg_file, RegClass rc, aco_ptr<Instruction>& instr,
1265
PhysReg reg)
1266
{
1267
/* catch out-of-range registers */
1268
if (reg >= PhysReg{512})
1269
return false;
1270
1271
std::pair<unsigned, unsigned> sdw_def_info;
1272
if (rc.is_subdword())
1273
sdw_def_info = get_subdword_definition_info(ctx.program, instr, rc);
1274
1275
if (rc.is_subdword() && reg.byte() % sdw_def_info.first)
1276
return false;
1277
if (!rc.is_subdword() && reg.byte())
1278
return false;
1279
1280
if (rc.type() == RegType::sgpr && reg % get_stride(rc) != 0)
1281
return false;
1282
1283
PhysRegInterval reg_win = {reg, rc.size()};
1284
PhysRegInterval bounds = get_reg_bounds(ctx.program, rc.type());
1285
PhysRegInterval vcc_win = {vcc, 2};
1286
/* VCC is outside the bounds */
1287
bool is_vcc = rc.type() == RegType::sgpr && vcc_win.contains(reg_win);
1288
bool is_m0 = rc == s1 && reg == m0;
1289
if (!bounds.contains(reg_win) && !is_vcc && !is_m0)
1290
return false;
1291
1292
if (rc.is_subdword()) {
1293
PhysReg test_reg;
1294
test_reg.reg_b = reg.reg_b & ~(sdw_def_info.second - 1);
1295
if (reg_file.test(test_reg, sdw_def_info.second))
1296
return false;
1297
} else {
1298
if (reg_file.test(reg, rc.bytes()))
1299
return false;
1300
}
1301
1302
adjust_max_used_regs(ctx, rc, reg_win.lo());
1303
return true;
1304
}
1305
1306
bool
1307
increase_register_file(ra_ctx& ctx, RegType type)
1308
{
1309
if (type == RegType::vgpr && ctx.program->max_reg_demand.vgpr < ctx.vgpr_limit) {
1310
update_vgpr_sgpr_demand(ctx.program, RegisterDemand(ctx.program->max_reg_demand.vgpr + 1,
1311
ctx.program->max_reg_demand.sgpr));
1312
} else if (type == RegType::sgpr && ctx.program->max_reg_demand.sgpr < ctx.sgpr_limit) {
1313
update_vgpr_sgpr_demand(ctx.program, RegisterDemand(ctx.program->max_reg_demand.vgpr,
1314
ctx.program->max_reg_demand.sgpr + 1));
1315
} else {
1316
return false;
1317
}
1318
return true;
1319
}
1320
1321
struct IDAndRegClass {
1322
IDAndRegClass(unsigned id_, RegClass rc_) : id(id_), rc(rc_) {}
1323
1324
unsigned id;
1325
RegClass rc;
1326
};
1327
1328
struct IDAndInfo {
1329
IDAndInfo(unsigned id_, DefInfo info_) : id(id_), info(info_) {}
1330
1331
unsigned id;
1332
DefInfo info;
1333
};
1334
1335
/* Reallocates vars by sorting them and placing each variable after the previous
1336
* one. If one of the variables has 0xffffffff as an ID, the register assigned
1337
* for that variable will be returned.
1338
*/
1339
PhysReg
1340
compact_relocate_vars(ra_ctx& ctx, const std::vector<IDAndRegClass>& vars,
1341
std::vector<std::pair<Operand, Definition>>& parallelcopies, PhysReg start)
1342
{
1343
/* This function assumes RegisterDemand/live_var_analysis rounds up sub-dword
1344
* temporary sizes to dwords.
1345
*/
1346
std::vector<IDAndInfo> sorted;
1347
for (IDAndRegClass var : vars) {
1348
DefInfo info(ctx, ctx.pseudo_dummy, var.rc, -1);
1349
sorted.emplace_back(var.id, info);
1350
}
1351
1352
std::sort(
1353
sorted.begin(), sorted.end(),
1354
[&ctx](const IDAndInfo& a, const IDAndInfo& b)
1355
{
1356
unsigned a_stride = a.info.stride * (a.info.rc.is_subdword() ? 1 : 4);
1357
unsigned b_stride = b.info.stride * (b.info.rc.is_subdword() ? 1 : 4);
1358
if (a_stride > b_stride)
1359
return true;
1360
if (a_stride < b_stride)
1361
return false;
1362
if (a.id == 0xffffffff || b.id == 0xffffffff)
1363
return a.id ==
1364
0xffffffff; /* place 0xffffffff before others if possible, not for any reason */
1365
return ctx.assignments[a.id].reg < ctx.assignments[b.id].reg;
1366
});
1367
1368
PhysReg next_reg = start;
1369
PhysReg space_reg;
1370
for (IDAndInfo& var : sorted) {
1371
unsigned stride = var.info.rc.is_subdword() ? var.info.stride : var.info.stride * 4;
1372
next_reg.reg_b = align(next_reg.reg_b, MAX2(stride, 4));
1373
1374
/* 0xffffffff is a special variable ID used reserve a space for killed
1375
* operands and definitions.
1376
*/
1377
if (var.id != 0xffffffff) {
1378
if (next_reg != ctx.assignments[var.id].reg) {
1379
RegClass rc = ctx.assignments[var.id].rc;
1380
Temp tmp(var.id, rc);
1381
1382
Operand pc_op(tmp);
1383
pc_op.setFixed(ctx.assignments[var.id].reg);
1384
Definition pc_def(next_reg, rc);
1385
parallelcopies.emplace_back(pc_op, pc_def);
1386
}
1387
} else {
1388
space_reg = next_reg;
1389
}
1390
1391
adjust_max_used_regs(ctx, var.info.rc, next_reg);
1392
1393
next_reg = next_reg.advance(var.info.rc.size() * 4);
1394
}
1395
1396
return space_reg;
1397
}
1398
1399
bool
1400
is_mimg_vaddr_intact(ra_ctx& ctx, RegisterFile& reg_file, Instruction* instr)
1401
{
1402
PhysReg first{512};
1403
for (unsigned i = 0; i < instr->operands.size() - 3u; i++) {
1404
Operand op = instr->operands[i + 3];
1405
1406
if (ctx.assignments[op.tempId()].assigned) {
1407
PhysReg reg = ctx.assignments[op.tempId()].reg;
1408
1409
if (first.reg() != 512 && reg != first.advance(i * 4))
1410
return false; /* not at the best position */
1411
1412
if ((reg.reg() - 256) < i)
1413
return false; /* no space for previous operands */
1414
1415
first = reg.advance(i * -4);
1416
} else if (first.reg() != 512) {
1417
/* If there's an unexpected temporary, this operand is unlikely to be
1418
* placed in the best position.
1419
*/
1420
unsigned id = reg_file.get_id(first.advance(i * 4));
1421
if (id && id != op.tempId())
1422
return false;
1423
}
1424
}
1425
1426
return true;
1427
}
1428
1429
std::pair<PhysReg, bool>
1430
get_reg_vector(ra_ctx& ctx, RegisterFile& reg_file, Temp temp, aco_ptr<Instruction>& instr)
1431
{
1432
Instruction* vec = ctx.vectors[temp.id()];
1433
unsigned first_operand = vec->format == Format::MIMG ? 3 : 0;
1434
unsigned our_offset = 0;
1435
for (unsigned i = first_operand; i < vec->operands.size(); i++) {
1436
Operand& op = vec->operands[i];
1437
if (op.isTemp() && op.tempId() == temp.id())
1438
break;
1439
else
1440
our_offset += op.bytes();
1441
}
1442
1443
if (vec->format != Format::MIMG || is_mimg_vaddr_intact(ctx, reg_file, vec)) {
1444
unsigned their_offset = 0;
1445
/* check for every operand of the vector
1446
* - whether the operand is assigned and
1447
* - we can use the register relative to that operand
1448
*/
1449
for (unsigned i = first_operand; i < vec->operands.size(); i++) {
1450
Operand& op = vec->operands[i];
1451
if (op.isTemp() && op.tempId() != temp.id() && op.getTemp().type() == temp.type() &&
1452
ctx.assignments[op.tempId()].assigned) {
1453
PhysReg reg = ctx.assignments[op.tempId()].reg;
1454
reg.reg_b += (our_offset - their_offset);
1455
if (get_reg_specified(ctx, reg_file, temp.regClass(), instr, reg))
1456
return {reg, true};
1457
}
1458
their_offset += op.bytes();
1459
}
1460
1461
/* We didn't find a register relative to other vector operands.
1462
* Try to find new space which fits the whole vector.
1463
*/
1464
RegClass vec_rc = RegClass::get(temp.type(), their_offset);
1465
DefInfo info(ctx, ctx.pseudo_dummy, vec_rc, -1);
1466
std::pair<PhysReg, bool> res = get_reg_simple(ctx, reg_file, info);
1467
PhysReg reg = res.first;
1468
if (res.second) {
1469
reg.reg_b += our_offset;
1470
/* make sure to only use byte offset if the instruction supports it */
1471
if (get_reg_specified(ctx, reg_file, temp.regClass(), instr, reg))
1472
return {reg, true};
1473
}
1474
}
1475
return {{}, false};
1476
}
1477
1478
PhysReg
1479
get_reg(ra_ctx& ctx, RegisterFile& reg_file, Temp temp,
1480
std::vector<std::pair<Operand, Definition>>& parallelcopies, aco_ptr<Instruction>& instr,
1481
int operand_index = -1)
1482
{
1483
auto split_vec = ctx.split_vectors.find(temp.id());
1484
if (split_vec != ctx.split_vectors.end()) {
1485
unsigned offset = 0;
1486
for (Definition def : split_vec->second->definitions) {
1487
auto affinity_it = ctx.affinities.find(def.tempId());
1488
if (affinity_it != ctx.affinities.end() && ctx.assignments[affinity_it->second].assigned) {
1489
PhysReg reg = ctx.assignments[affinity_it->second].reg;
1490
reg.reg_b -= offset;
1491
if (get_reg_specified(ctx, reg_file, temp.regClass(), instr, reg))
1492
return reg;
1493
}
1494
offset += def.bytes();
1495
}
1496
}
1497
1498
if (ctx.affinities.find(temp.id()) != ctx.affinities.end() &&
1499
ctx.assignments[ctx.affinities[temp.id()]].assigned) {
1500
PhysReg reg = ctx.assignments[ctx.affinities[temp.id()]].reg;
1501
if (get_reg_specified(ctx, reg_file, temp.regClass(), instr, reg))
1502
return reg;
1503
}
1504
1505
std::pair<PhysReg, bool> res;
1506
1507
if (ctx.vectors.find(temp.id()) != ctx.vectors.end()) {
1508
res = get_reg_vector(ctx, reg_file, temp, instr);
1509
if (res.second)
1510
return res.first;
1511
}
1512
1513
DefInfo info(ctx, instr, temp.regClass(), operand_index);
1514
1515
if (!ctx.policy.skip_optimistic_path) {
1516
/* try to find space without live-range splits */
1517
res = get_reg_simple(ctx, reg_file, info);
1518
1519
if (res.second)
1520
return res.first;
1521
}
1522
1523
/* try to find space with live-range splits */
1524
res = get_reg_impl(ctx, reg_file, parallelcopies, info, instr);
1525
1526
if (res.second)
1527
return res.first;
1528
1529
/* try using more registers */
1530
1531
/* We should only fail here because keeping under the limit would require
1532
* too many moves. */
1533
assert(reg_file.count_zero(info.bounds) >= info.size);
1534
1535
if (!increase_register_file(ctx, info.rc.type())) {
1536
/* fallback algorithm: reallocate all variables at once */
1537
unsigned def_size = info.rc.size();
1538
for (Definition def : instr->definitions) {
1539
if (ctx.assignments[def.tempId()].assigned && def.regClass().type() == info.rc.type())
1540
def_size += def.regClass().size();
1541
}
1542
1543
unsigned killed_op_size = 0;
1544
for (Operand op : instr->operands) {
1545
if (op.isTemp() && op.isKillBeforeDef() && op.regClass().type() == info.rc.type())
1546
killed_op_size += op.regClass().size();
1547
}
1548
1549
const PhysRegInterval regs = get_reg_bounds(ctx.program, info.rc.type());
1550
1551
/* reallocate passthrough variables and non-killed operands */
1552
std::vector<IDAndRegClass> vars;
1553
for (const std::pair<unsigned, unsigned>& var : find_vars(ctx, reg_file, regs))
1554
vars.emplace_back(var.second, ctx.assignments[var.second].rc);
1555
vars.emplace_back(0xffffffff, RegClass(info.rc.type(), MAX2(def_size, killed_op_size)));
1556
1557
PhysReg space = compact_relocate_vars(ctx, vars, parallelcopies, regs.lo());
1558
1559
/* reallocate killed operands */
1560
std::vector<IDAndRegClass> killed_op_vars;
1561
for (Operand op : instr->operands) {
1562
if (op.isKillBeforeDef() && op.regClass().type() == info.rc.type())
1563
killed_op_vars.emplace_back(op.tempId(), op.regClass());
1564
}
1565
compact_relocate_vars(ctx, killed_op_vars, parallelcopies, space);
1566
1567
/* reallocate definitions */
1568
std::vector<IDAndRegClass> def_vars;
1569
for (Definition def : instr->definitions) {
1570
if (ctx.assignments[def.tempId()].assigned && def.regClass().type() == info.rc.type())
1571
def_vars.emplace_back(def.tempId(), def.regClass());
1572
}
1573
def_vars.emplace_back(0xffffffff, info.rc);
1574
return compact_relocate_vars(ctx, def_vars, parallelcopies, space);
1575
}
1576
1577
return get_reg(ctx, reg_file, temp, parallelcopies, instr, operand_index);
1578
}
1579
1580
PhysReg
1581
get_reg_create_vector(ra_ctx& ctx, RegisterFile& reg_file, Temp temp,
1582
std::vector<std::pair<Operand, Definition>>& parallelcopies,
1583
aco_ptr<Instruction>& instr)
1584
{
1585
RegClass rc = temp.regClass();
1586
/* create_vector instructions have different costs w.r.t. register coalescing */
1587
uint32_t size = rc.size();
1588
uint32_t bytes = rc.bytes();
1589
uint32_t stride = get_stride(rc);
1590
PhysRegInterval bounds = get_reg_bounds(ctx.program, rc.type());
1591
1592
// TODO: improve p_create_vector for sub-dword vectors
1593
1594
PhysReg best_pos{0xFFF};
1595
unsigned num_moves = 0xFF;
1596
bool best_war_hint = true;
1597
1598
/* test for each operand which definition placement causes the least shuffle instructions */
1599
for (unsigned i = 0, offset = 0; i < instr->operands.size();
1600
offset += instr->operands[i].bytes(), i++) {
1601
// TODO: think about, if we can alias live operands on the same register
1602
if (!instr->operands[i].isTemp() || !instr->operands[i].isKillBeforeDef() ||
1603
instr->operands[i].getTemp().type() != rc.type())
1604
continue;
1605
1606
if (offset > instr->operands[i].physReg().reg_b)
1607
continue;
1608
1609
unsigned reg_lower = instr->operands[i].physReg().reg_b - offset;
1610
if (reg_lower % 4)
1611
continue;
1612
PhysRegInterval reg_win = {PhysReg{reg_lower / 4}, size};
1613
unsigned k = 0;
1614
1615
/* no need to check multiple times */
1616
if (reg_win.lo() == best_pos)
1617
continue;
1618
1619
/* check borders */
1620
// TODO: this can be improved */
1621
if (!bounds.contains(reg_win) || reg_win.lo() % stride != 0)
1622
continue;
1623
if (reg_win.lo() > bounds.lo() && reg_file[reg_win.lo()] != 0 &&
1624
reg_file.get_id(reg_win.lo()) == reg_file.get_id(reg_win.lo().advance(-1)))
1625
continue;
1626
if (reg_win.hi() < bounds.hi() && reg_file[reg_win.hi().advance(-4)] != 0 &&
1627
reg_file.get_id(reg_win.hi().advance(-1)) == reg_file.get_id(reg_win.hi()))
1628
continue;
1629
1630
/* count variables to be moved and check war_hint */
1631
bool war_hint = false;
1632
bool linear_vgpr = false;
1633
for (PhysReg j : reg_win) {
1634
if (linear_vgpr) {
1635
break;
1636
}
1637
1638
if (reg_file[j] != 0) {
1639
if (reg_file[j] == 0xF0000000) {
1640
PhysReg reg;
1641
reg.reg_b = j * 4;
1642
unsigned bytes_left = bytes - ((unsigned)j - reg_win.lo()) * 4;
1643
for (unsigned byte_idx = 0; byte_idx < MIN2(bytes_left, 4); byte_idx++, reg.reg_b++)
1644
k += reg_file.test(reg, 1);
1645
} else {
1646
k += 4;
1647
/* we cannot split live ranges of linear vgprs */
1648
if (ctx.assignments[reg_file[j]].rc & (1 << 6))
1649
linear_vgpr = true;
1650
}
1651
}
1652
war_hint |= ctx.war_hint[j];
1653
}
1654
if (linear_vgpr || (war_hint && !best_war_hint))
1655
continue;
1656
1657
/* count operands in wrong positions */
1658
for (unsigned j = 0, offset2 = 0; j < instr->operands.size();
1659
offset2 += instr->operands[j].bytes(), j++) {
1660
if (j == i || !instr->operands[j].isTemp() ||
1661
instr->operands[j].getTemp().type() != rc.type())
1662
continue;
1663
if (instr->operands[j].physReg().reg_b != reg_win.lo() * 4 + offset2)
1664
k += instr->operands[j].bytes();
1665
}
1666
bool aligned = rc == RegClass::v4 && reg_win.lo() % 4 == 0;
1667
if (k > num_moves || (!aligned && k == num_moves))
1668
continue;
1669
1670
best_pos = reg_win.lo();
1671
num_moves = k;
1672
best_war_hint = war_hint;
1673
}
1674
1675
if (num_moves >= bytes)
1676
return get_reg(ctx, reg_file, temp, parallelcopies, instr);
1677
1678
/* re-enable killed operands which are in the wrong position */
1679
RegisterFile tmp_file(reg_file);
1680
for (unsigned i = 0, offset = 0; i < instr->operands.size();
1681
offset += instr->operands[i].bytes(), i++) {
1682
if (instr->operands[i].isTemp() && instr->operands[i].isFirstKillBeforeDef() &&
1683
instr->operands[i].physReg().reg_b != best_pos.reg_b + offset)
1684
tmp_file.fill(instr->operands[i]);
1685
}
1686
1687
/* collect variables to be moved */
1688
std::set<std::pair<unsigned, unsigned>> vars =
1689
collect_vars(ctx, tmp_file, PhysRegInterval{best_pos, size});
1690
1691
for (unsigned i = 0, offset = 0; i < instr->operands.size();
1692
offset += instr->operands[i].bytes(), i++) {
1693
if (!instr->operands[i].isTemp() || !instr->operands[i].isFirstKillBeforeDef() ||
1694
instr->operands[i].getTemp().type() != rc.type())
1695
continue;
1696
bool correct_pos = instr->operands[i].physReg().reg_b == best_pos.reg_b + offset;
1697
/* GFX9+: move killed operands which aren't yet at the correct position
1698
* Moving all killed operands generally leads to more register swaps.
1699
* This is only done on GFX9+ because of the cheap v_swap instruction.
1700
*/
1701
if (ctx.program->chip_class >= GFX9 && !correct_pos) {
1702
vars.emplace(instr->operands[i].bytes(), instr->operands[i].tempId());
1703
tmp_file.clear(instr->operands[i]);
1704
/* fill operands which are in the correct position to avoid overwriting */
1705
} else if (correct_pos) {
1706
tmp_file.fill(instr->operands[i]);
1707
}
1708
}
1709
bool success = false;
1710
std::vector<std::pair<Operand, Definition>> pc;
1711
success =
1712
get_regs_for_copies(ctx, tmp_file, pc, vars, bounds, instr, PhysRegInterval{best_pos, size});
1713
1714
if (!success) {
1715
if (!increase_register_file(ctx, temp.type())) {
1716
/* use the fallback algorithm in get_reg() */
1717
return get_reg(ctx, reg_file, temp, parallelcopies, instr);
1718
}
1719
return get_reg_create_vector(ctx, reg_file, temp, parallelcopies, instr);
1720
}
1721
1722
parallelcopies.insert(parallelcopies.end(), pc.begin(), pc.end());
1723
adjust_max_used_regs(ctx, rc, best_pos);
1724
1725
return best_pos;
1726
}
1727
1728
void
1729
handle_pseudo(ra_ctx& ctx, const RegisterFile& reg_file, Instruction* instr)
1730
{
1731
if (instr->format != Format::PSEUDO)
1732
return;
1733
1734
/* all instructions which use handle_operands() need this information */
1735
switch (instr->opcode) {
1736
case aco_opcode::p_extract_vector:
1737
case aco_opcode::p_create_vector:
1738
case aco_opcode::p_split_vector:
1739
case aco_opcode::p_parallelcopy:
1740
case aco_opcode::p_wqm: break;
1741
default: return;
1742
}
1743
1744
/* if all definitions are vgpr, no need to care for SCC */
1745
bool writes_sgpr = false;
1746
for (Definition& def : instr->definitions) {
1747
if (def.getTemp().type() == RegType::sgpr) {
1748
writes_sgpr = true;
1749
break;
1750
}
1751
}
1752
/* if all operands are constant, no need to care either */
1753
bool reads_sgpr = false;
1754
bool reads_subdword = false;
1755
for (Operand& op : instr->operands) {
1756
if (op.isTemp() && op.getTemp().type() == RegType::sgpr) {
1757
reads_sgpr = true;
1758
break;
1759
}
1760
if (op.isTemp() && op.regClass().is_subdword())
1761
reads_subdword = true;
1762
}
1763
bool needs_scratch_reg =
1764
(writes_sgpr && reads_sgpr) || (ctx.program->chip_class <= GFX7 && reads_subdword);
1765
if (!needs_scratch_reg)
1766
return;
1767
1768
if (reg_file[scc]) {
1769
instr->pseudo().tmp_in_scc = true;
1770
1771
int reg = ctx.max_used_sgpr;
1772
for (; reg >= 0 && reg_file[PhysReg{(unsigned)reg}]; reg--)
1773
;
1774
if (reg < 0) {
1775
reg = ctx.max_used_sgpr + 1;
1776
for (; reg < ctx.program->max_reg_demand.sgpr && reg_file[PhysReg{(unsigned)reg}]; reg++)
1777
;
1778
if (reg == ctx.program->max_reg_demand.sgpr) {
1779
assert(reads_subdword && reg_file[m0] == 0);
1780
reg = m0;
1781
}
1782
}
1783
1784
adjust_max_used_regs(ctx, s1, reg);
1785
instr->pseudo().scratch_sgpr = PhysReg{(unsigned)reg};
1786
} else {
1787
instr->pseudo().tmp_in_scc = false;
1788
}
1789
}
1790
1791
bool
1792
operand_can_use_reg(chip_class chip, aco_ptr<Instruction>& instr, unsigned idx, PhysReg reg,
1793
RegClass rc)
1794
{
1795
if (instr->operands[idx].isFixed())
1796
return instr->operands[idx].physReg() == reg;
1797
1798
bool is_writelane = instr->opcode == aco_opcode::v_writelane_b32 ||
1799
instr->opcode == aco_opcode::v_writelane_b32_e64;
1800
if (chip <= GFX9 && is_writelane && idx <= 1) {
1801
/* v_writelane_b32 can take two sgprs but only if one is m0. */
1802
bool is_other_sgpr =
1803
instr->operands[!idx].isTemp() &&
1804
(!instr->operands[!idx].isFixed() || instr->operands[!idx].physReg() != m0);
1805
if (is_other_sgpr && instr->operands[!idx].tempId() != instr->operands[idx].tempId()) {
1806
instr->operands[idx].setFixed(m0);
1807
return reg == m0;
1808
}
1809
}
1810
1811
if (reg.byte()) {
1812
unsigned stride = get_subdword_operand_stride(chip, instr, idx, rc);
1813
if (reg.byte() % stride)
1814
return false;
1815
}
1816
1817
switch (instr->format) {
1818
case Format::SMEM:
1819
return reg != scc && reg != exec &&
1820
(reg != m0 || idx == 1 || idx == 3) && /* offset can be m0 */
1821
(reg != vcc || (instr->definitions.empty() && idx == 2) ||
1822
chip >= GFX10); /* sdata can be vcc */
1823
default:
1824
// TODO: there are more instructions with restrictions on registers
1825
return true;
1826
}
1827
}
1828
1829
void
1830
get_reg_for_operand(ra_ctx& ctx, RegisterFile& register_file,
1831
std::vector<std::pair<Operand, Definition>>& parallelcopy,
1832
aco_ptr<Instruction>& instr, Operand& operand, unsigned operand_index)
1833
{
1834
/* check if the operand is fixed */
1835
PhysReg src = ctx.assignments[operand.tempId()].reg;
1836
PhysReg dst;
1837
if (operand.isFixed()) {
1838
assert(operand.physReg() != src);
1839
1840
/* check if target reg is blocked, and move away the blocking var */
1841
if (register_file.test(operand.physReg(), operand.bytes())) {
1842
PhysRegInterval target{operand.physReg(), operand.size()};
1843
1844
RegisterFile tmp_file(register_file);
1845
1846
std::set<std::pair<unsigned, unsigned>> blocking_vars =
1847
collect_vars(ctx, tmp_file, target);
1848
1849
tmp_file.clear(src, operand.regClass()); // TODO: try to avoid moving block vars to src
1850
tmp_file.block(operand.physReg(), operand.regClass());
1851
1852
DefInfo info(ctx, instr, operand.regClass(), -1);
1853
get_regs_for_copies(ctx, tmp_file, parallelcopy, blocking_vars, info.bounds, instr,
1854
PhysRegInterval());
1855
}
1856
dst = operand.physReg();
1857
1858
} else {
1859
dst = get_reg(ctx, register_file, operand.getTemp(), parallelcopy, instr, operand_index);
1860
update_renames(
1861
ctx, register_file, parallelcopy, instr,
1862
instr->opcode != aco_opcode::p_create_vector ? rename_not_killed_ops : (UpdateRenames)0);
1863
}
1864
1865
Operand pc_op = operand;
1866
pc_op.setFixed(src);
1867
Definition pc_def = Definition(dst, pc_op.regClass());
1868
parallelcopy.emplace_back(pc_op, pc_def);
1869
update_renames(ctx, register_file, parallelcopy, instr, rename_not_killed_ops | fill_killed_ops);
1870
}
1871
1872
Temp
1873
read_variable(ra_ctx& ctx, Temp val, unsigned block_idx)
1874
{
1875
std::unordered_map<unsigned, Temp>::iterator it = ctx.renames[block_idx].find(val.id());
1876
if (it == ctx.renames[block_idx].end())
1877
return val;
1878
else
1879
return it->second;
1880
}
1881
1882
Temp
1883
handle_live_in(ra_ctx& ctx, Temp val, Block* block)
1884
{
1885
std::vector<unsigned>& preds = val.is_linear() ? block->linear_preds : block->logical_preds;
1886
if (preds.size() == 0 || val.regClass() == val.regClass().as_linear())
1887
return val;
1888
1889
if (preds.size() == 1) {
1890
/* if the block has only one predecessor, just look there for the name */
1891
return read_variable(ctx, val, preds[0]);
1892
}
1893
1894
/* there are multiple predecessors and the block is sealed */
1895
Temp* const ops = (Temp*)alloca(preds.size() * sizeof(Temp));
1896
1897
/* get the rename from each predecessor and check if they are the same */
1898
Temp new_val;
1899
bool needs_phi = false;
1900
for (unsigned i = 0; i < preds.size(); i++) {
1901
ops[i] = read_variable(ctx, val, preds[i]);
1902
if (i == 0)
1903
new_val = ops[i];
1904
else
1905
needs_phi |= !(new_val == ops[i]);
1906
}
1907
1908
if (needs_phi) {
1909
/* the variable has been renamed differently in the predecessors: we need to insert a phi */
1910
aco_opcode opcode = val.is_linear() ? aco_opcode::p_linear_phi : aco_opcode::p_phi;
1911
aco_ptr<Instruction> phi{
1912
create_instruction<Pseudo_instruction>(opcode, Format::PSEUDO, preds.size(), 1)};
1913
new_val = ctx.program->allocateTmp(val.regClass());
1914
phi->definitions[0] = Definition(new_val);
1915
for (unsigned i = 0; i < preds.size(); i++) {
1916
/* update the operands so that it uses the new affinity */
1917
phi->operands[i] = Operand(ops[i]);
1918
assert(ctx.assignments[ops[i].id()].assigned);
1919
phi->operands[i].setFixed(ctx.assignments[ops[i].id()].reg);
1920
if (ops[i].regClass() == new_val.regClass())
1921
ctx.affinities[new_val.id()] = ops[i].id();
1922
}
1923
ctx.assignments.emplace_back();
1924
assert(ctx.assignments.size() == ctx.program->peekAllocationId());
1925
block->instructions.insert(block->instructions.begin(), std::move(phi));
1926
}
1927
1928
return new_val;
1929
}
1930
1931
void
1932
handle_loop_phis(ra_ctx& ctx, const IDSet& live_in, uint32_t loop_header_idx,
1933
uint32_t loop_exit_idx)
1934
{
1935
Block& loop_header = ctx.program->blocks[loop_header_idx];
1936
std::unordered_map<unsigned, Temp> renames;
1937
1938
/* create phis for variables renamed during the loop */
1939
for (unsigned t : live_in) {
1940
Temp val = Temp(t, ctx.program->temp_rc[t]);
1941
Temp prev = read_variable(ctx, val, loop_header_idx - 1);
1942
Temp renamed = handle_live_in(ctx, val, &loop_header);
1943
if (renamed == prev)
1944
continue;
1945
1946
/* insert additional renames at block end, but don't overwrite */
1947
renames[prev.id()] = renamed;
1948
ctx.orig_names[renamed.id()] = val;
1949
for (unsigned idx = loop_header_idx; idx < loop_exit_idx; idx++) {
1950
auto it = ctx.renames[idx].emplace(val.id(), renamed);
1951
/* if insertion is unsuccessful, update if necessary */
1952
if (!it.second && it.first->second == prev)
1953
it.first->second = renamed;
1954
}
1955
1956
/* update loop-carried values of the phi created by handle_live_in() */
1957
for (unsigned i = 1; i < loop_header.instructions[0]->operands.size(); i++) {
1958
Operand& op = loop_header.instructions[0]->operands[i];
1959
if (op.getTemp() == prev)
1960
op.setTemp(renamed);
1961
}
1962
1963
/* use the assignment from the loop preheader and fix def reg */
1964
assignment& var = ctx.assignments[prev.id()];
1965
ctx.assignments[renamed.id()] = var;
1966
loop_header.instructions[0]->definitions[0].setFixed(var.reg);
1967
}
1968
1969
/* rename loop carried phi operands */
1970
for (unsigned i = renames.size(); i < loop_header.instructions.size(); i++) {
1971
aco_ptr<Instruction>& phi = loop_header.instructions[i];
1972
if (!is_phi(phi))
1973
break;
1974
const std::vector<unsigned>& preds =
1975
phi->opcode == aco_opcode::p_phi ? loop_header.logical_preds : loop_header.linear_preds;
1976
for (unsigned j = 1; j < phi->operands.size(); j++) {
1977
Operand& op = phi->operands[j];
1978
if (!op.isTemp())
1979
continue;
1980
1981
/* Find the original name, since this operand might not use the original name if the phi
1982
* was created after init_reg_file().
1983
*/
1984
std::unordered_map<unsigned, Temp>::iterator it = ctx.orig_names.find(op.tempId());
1985
Temp orig = it != ctx.orig_names.end() ? it->second : op.getTemp();
1986
1987
op.setTemp(read_variable(ctx, orig, preds[j]));
1988
op.setFixed(ctx.assignments[op.tempId()].reg);
1989
}
1990
}
1991
1992
/* return early if no new phi was created */
1993
if (renames.empty())
1994
return;
1995
1996
/* propagate new renames through loop */
1997
for (unsigned idx = loop_header_idx; idx < loop_exit_idx; idx++) {
1998
Block& current = ctx.program->blocks[idx];
1999
/* rename all uses in this block */
2000
for (aco_ptr<Instruction>& instr : current.instructions) {
2001
/* phis are renamed after RA */
2002
if (idx == loop_header_idx && is_phi(instr))
2003
continue;
2004
2005
for (Operand& op : instr->operands) {
2006
if (!op.isTemp())
2007
continue;
2008
2009
auto rename = renames.find(op.tempId());
2010
if (rename != renames.end()) {
2011
assert(rename->second.id());
2012
op.setTemp(rename->second);
2013
}
2014
}
2015
}
2016
}
2017
}
2018
2019
/**
2020
* This function serves the purpose to correctly initialize the register file
2021
* at the beginning of a block (before any existing phis).
2022
* In order to do so, all live-in variables are entered into the RegisterFile.
2023
* Reg-to-reg moves (renames) from previous blocks are taken into account and
2024
* the SSA is repaired by inserting corresponding phi-nodes.
2025
*/
2026
RegisterFile
2027
init_reg_file(ra_ctx& ctx, const std::vector<IDSet>& live_out_per_block, Block& block)
2028
{
2029
if (block.kind & block_kind_loop_exit) {
2030
uint32_t header = ctx.loop_header.back();
2031
ctx.loop_header.pop_back();
2032
handle_loop_phis(ctx, live_out_per_block[header], header, block.index);
2033
}
2034
2035
RegisterFile register_file;
2036
const IDSet& live_in = live_out_per_block[block.index];
2037
assert(block.index != 0 || live_in.empty());
2038
2039
if (block.kind & block_kind_loop_header) {
2040
ctx.loop_header.emplace_back(block.index);
2041
/* already rename phis incoming value */
2042
for (aco_ptr<Instruction>& instr : block.instructions) {
2043
if (!is_phi(instr))
2044
break;
2045
Operand& operand = instr->operands[0];
2046
if (operand.isTemp()) {
2047
operand.setTemp(read_variable(ctx, operand.getTemp(), block.index - 1));
2048
operand.setFixed(ctx.assignments[operand.tempId()].reg);
2049
}
2050
}
2051
for (unsigned t : live_in) {
2052
Temp val = Temp(t, ctx.program->temp_rc[t]);
2053
Temp renamed = read_variable(ctx, val, block.index - 1);
2054
if (renamed != val)
2055
ctx.renames[block.index][val.id()] = renamed;
2056
assignment& var = ctx.assignments[renamed.id()];
2057
assert(var.assigned);
2058
register_file.fill(Definition(renamed.id(), var.reg, var.rc));
2059
}
2060
} else {
2061
/* rename phi operands */
2062
for (aco_ptr<Instruction>& instr : block.instructions) {
2063
if (!is_phi(instr))
2064
break;
2065
const std::vector<unsigned>& preds =
2066
instr->opcode == aco_opcode::p_phi ? block.logical_preds : block.linear_preds;
2067
2068
for (unsigned i = 0; i < instr->operands.size(); i++) {
2069
Operand& operand = instr->operands[i];
2070
if (!operand.isTemp())
2071
continue;
2072
operand.setTemp(read_variable(ctx, operand.getTemp(), preds[i]));
2073
operand.setFixed(ctx.assignments[operand.tempId()].reg);
2074
}
2075
}
2076
for (unsigned t : live_in) {
2077
Temp val = Temp(t, ctx.program->temp_rc[t]);
2078
Temp renamed = handle_live_in(ctx, val, &block);
2079
assignment& var = ctx.assignments[renamed.id()];
2080
/* due to live-range splits, the live-in might be a phi, now */
2081
if (var.assigned) {
2082
register_file.fill(Definition(renamed.id(), var.reg, var.rc));
2083
}
2084
if (renamed != val) {
2085
ctx.renames[block.index].emplace(t, renamed);
2086
ctx.orig_names[renamed.id()] = val;
2087
}
2088
}
2089
}
2090
2091
return register_file;
2092
}
2093
2094
void
2095
get_affinities(ra_ctx& ctx, std::vector<IDSet>& live_out_per_block)
2096
{
2097
std::vector<std::vector<Temp>> phi_ressources;
2098
std::unordered_map<unsigned, unsigned> temp_to_phi_ressources;
2099
2100
for (auto block_rit = ctx.program->blocks.rbegin(); block_rit != ctx.program->blocks.rend();
2101
block_rit++) {
2102
Block& block = *block_rit;
2103
2104
/* first, compute the death points of all live vars within the block */
2105
IDSet& live = live_out_per_block[block.index];
2106
2107
std::vector<aco_ptr<Instruction>>::reverse_iterator rit;
2108
for (rit = block.instructions.rbegin(); rit != block.instructions.rend(); ++rit) {
2109
aco_ptr<Instruction>& instr = *rit;
2110
if (is_phi(instr)) {
2111
if (instr->definitions[0].isKill() || instr->definitions[0].isFixed()) {
2112
live.erase(instr->definitions[0].tempId());
2113
continue;
2114
}
2115
/* collect information about affinity-related temporaries */
2116
std::vector<Temp> affinity_related;
2117
/* affinity_related[0] is the last seen affinity-related temp */
2118
affinity_related.emplace_back(instr->definitions[0].getTemp());
2119
affinity_related.emplace_back(instr->definitions[0].getTemp());
2120
for (const Operand& op : instr->operands) {
2121
if (op.isTemp() && op.isKill() &&
2122
op.regClass() == instr->definitions[0].regClass()) {
2123
affinity_related.emplace_back(op.getTemp());
2124
temp_to_phi_ressources[op.tempId()] = phi_ressources.size();
2125
}
2126
}
2127
phi_ressources.emplace_back(std::move(affinity_related));
2128
} else {
2129
/* add vector affinities */
2130
if (instr->opcode == aco_opcode::p_create_vector) {
2131
for (const Operand& op : instr->operands) {
2132
if (op.isTemp() && op.isFirstKill() &&
2133
op.getTemp().type() == instr->definitions[0].getTemp().type())
2134
ctx.vectors[op.tempId()] = instr.get();
2135
}
2136
} else if (instr->format == Format::MIMG && instr->operands.size() > 4) {
2137
for (unsigned i = 3; i < instr->operands.size(); i++)
2138
ctx.vectors[instr->operands[i].tempId()] = instr.get();
2139
}
2140
2141
if (instr->opcode == aco_opcode::p_split_vector &&
2142
instr->operands[0].isFirstKillBeforeDef())
2143
ctx.split_vectors[instr->operands[0].tempId()] = instr.get();
2144
2145
/* add operands to live variables */
2146
for (const Operand& op : instr->operands) {
2147
if (op.isTemp())
2148
live.insert(op.tempId());
2149
}
2150
}
2151
2152
/* erase definitions from live */
2153
for (unsigned i = 0; i < instr->definitions.size(); i++) {
2154
const Definition& def = instr->definitions[i];
2155
if (!def.isTemp())
2156
continue;
2157
live.erase(def.tempId());
2158
/* mark last-seen phi operand */
2159
std::unordered_map<unsigned, unsigned>::iterator it =
2160
temp_to_phi_ressources.find(def.tempId());
2161
if (it != temp_to_phi_ressources.end() &&
2162
def.regClass() == phi_ressources[it->second][0].regClass()) {
2163
phi_ressources[it->second][0] = def.getTemp();
2164
/* try to coalesce phi affinities with parallelcopies */
2165
Operand op = Operand();
2166
switch (instr->opcode) {
2167
case aco_opcode::p_parallelcopy: op = instr->operands[i]; break;
2168
2169
case aco_opcode::v_interp_p2_f32:
2170
case aco_opcode::v_writelane_b32:
2171
case aco_opcode::v_writelane_b32_e64: op = instr->operands[2]; break;
2172
2173
case aco_opcode::v_fma_f32:
2174
case aco_opcode::v_fma_f16:
2175
case aco_opcode::v_pk_fma_f16:
2176
if (ctx.program->chip_class < GFX10)
2177
continue;
2178
FALLTHROUGH;
2179
case aco_opcode::v_mad_f32:
2180
case aco_opcode::v_mad_f16:
2181
if (instr->usesModifiers())
2182
continue;
2183
op = instr->operands[2];
2184
break;
2185
2186
default: continue;
2187
}
2188
2189
if (op.isTemp() && op.isFirstKillBeforeDef() && def.regClass() == op.regClass()) {
2190
phi_ressources[it->second].emplace_back(op.getTemp());
2191
temp_to_phi_ressources[op.tempId()] = it->second;
2192
}
2193
}
2194
}
2195
}
2196
}
2197
/* create affinities */
2198
for (std::vector<Temp>& vec : phi_ressources) {
2199
assert(vec.size() > 1);
2200
for (unsigned i = 1; i < vec.size(); i++)
2201
if (vec[i].id() != vec[0].id())
2202
ctx.affinities[vec[i].id()] = vec[0].id();
2203
}
2204
}
2205
2206
} /* end namespace */
2207
2208
void
2209
register_allocation(Program* program, std::vector<IDSet>& live_out_per_block, ra_test_policy policy)
2210
{
2211
ra_ctx ctx(program, policy);
2212
get_affinities(ctx, live_out_per_block);
2213
2214
/* state of register file after phis */
2215
std::vector<std::bitset<128>> sgpr_live_in(program->blocks.size());
2216
2217
for (Block& block : program->blocks) {
2218
/* initialize register file */
2219
RegisterFile register_file = init_reg_file(ctx, live_out_per_block, block);
2220
ctx.war_hint.reset();
2221
2222
std::vector<aco_ptr<Instruction>> instructions;
2223
std::vector<aco_ptr<Instruction>>::iterator instr_it;
2224
2225
/* this is a slight adjustment from the paper as we already have phi nodes:
2226
* We consider them incomplete phis and only handle the definition. */
2227
2228
/* look up the affinities */
2229
for (instr_it = block.instructions.begin(); instr_it != block.instructions.end();
2230
++instr_it) {
2231
aco_ptr<Instruction>& phi = *instr_it;
2232
if (!is_phi(phi))
2233
break;
2234
Definition& definition = phi->definitions[0];
2235
if (definition.isKill() || definition.isFixed())
2236
continue;
2237
2238
if (ctx.affinities.find(definition.tempId()) != ctx.affinities.end() &&
2239
ctx.assignments[ctx.affinities[definition.tempId()]].assigned) {
2240
assert(ctx.assignments[ctx.affinities[definition.tempId()]].rc ==
2241
definition.regClass());
2242
PhysReg reg = ctx.assignments[ctx.affinities[definition.tempId()]].reg;
2243
if (reg == scc) {
2244
/* only use scc if all operands are already placed there */
2245
bool use_scc =
2246
std::all_of(phi->operands.begin(), phi->operands.end(),
2247
[](const Operand& op)
2248
{ return op.isTemp() && op.isFixed() && op.physReg() == scc; });
2249
if (!use_scc)
2250
continue;
2251
}
2252
2253
/* only assign if register is still free */
2254
if (!register_file.test(reg, definition.bytes())) {
2255
definition.setFixed(reg);
2256
register_file.fill(definition);
2257
ctx.assignments[definition.tempId()] = {definition.physReg(), definition.regClass()};
2258
}
2259
}
2260
}
2261
2262
/* find registers for phis without affinity or where the register was blocked */
2263
for (instr_it = block.instructions.begin(); instr_it != block.instructions.end();
2264
++instr_it) {
2265
aco_ptr<Instruction>& phi = *instr_it;
2266
if (!is_phi(phi))
2267
break;
2268
2269
Definition& definition = phi->definitions[0];
2270
if (definition.isKill())
2271
continue;
2272
2273
if (!definition.isFixed()) {
2274
std::vector<std::pair<Operand, Definition>> parallelcopy;
2275
/* try to find a register that is used by at least one operand */
2276
for (int i = phi->operands.size() - 1; i >= 0; i--) {
2277
/* by going backwards, we aim to avoid copies in else-blocks */
2278
const Operand& op = phi->operands[i];
2279
if (!op.isTemp() || !op.isFixed())
2280
continue;
2281
PhysReg reg = op.physReg();
2282
/* we tried this already on the previous loop */
2283
if (reg == scc)
2284
continue;
2285
if (get_reg_specified(ctx, register_file, definition.regClass(), phi, reg)) {
2286
definition.setFixed(reg);
2287
break;
2288
}
2289
}
2290
if (!definition.isFixed()) {
2291
definition.setFixed(
2292
get_reg(ctx, register_file, definition.getTemp(), parallelcopy, phi));
2293
update_renames(ctx, register_file, parallelcopy, phi, rename_not_killed_ops);
2294
}
2295
2296
/* process parallelcopy */
2297
for (std::pair<Operand, Definition> pc : parallelcopy) {
2298
/* see if it's a copy from a different phi */
2299
// TODO: prefer moving some previous phis over live-ins
2300
// TODO: somehow prevent phis fixed before the RA from being updated (shouldn't be a
2301
// problem in practice since they can only be fixed to exec)
2302
Instruction* prev_phi = NULL;
2303
std::vector<aco_ptr<Instruction>>::iterator phi_it;
2304
for (phi_it = instructions.begin(); phi_it != instructions.end(); ++phi_it) {
2305
if ((*phi_it)->definitions[0].tempId() == pc.first.tempId())
2306
prev_phi = phi_it->get();
2307
}
2308
phi_it = instr_it;
2309
while (!prev_phi && is_phi(*++phi_it)) {
2310
if ((*phi_it)->definitions[0].tempId() == pc.first.tempId())
2311
prev_phi = phi_it->get();
2312
}
2313
if (prev_phi) {
2314
/* if so, just update that phi's register */
2315
register_file.clear(prev_phi->definitions[0]);
2316
prev_phi->definitions[0].setFixed(pc.second.physReg());
2317
ctx.assignments[prev_phi->definitions[0].tempId()] = {pc.second.physReg(),
2318
pc.second.regClass()};
2319
register_file.fill(prev_phi->definitions[0]);
2320
continue;
2321
}
2322
2323
/* rename */
2324
std::unordered_map<unsigned, Temp>::iterator orig_it =
2325
ctx.orig_names.find(pc.first.tempId());
2326
Temp orig = pc.first.getTemp();
2327
if (orig_it != ctx.orig_names.end())
2328
orig = orig_it->second;
2329
else
2330
ctx.orig_names[pc.second.tempId()] = orig;
2331
ctx.renames[block.index][orig.id()] = pc.second.getTemp();
2332
2333
/* otherwise, this is a live-in and we need to create a new phi
2334
* to move it in this block's predecessors */
2335
aco_opcode opcode =
2336
pc.first.getTemp().is_linear() ? aco_opcode::p_linear_phi : aco_opcode::p_phi;
2337
std::vector<unsigned>& preds =
2338
pc.first.getTemp().is_linear() ? block.linear_preds : block.logical_preds;
2339
aco_ptr<Instruction> new_phi{
2340
create_instruction<Pseudo_instruction>(opcode, Format::PSEUDO, preds.size(), 1)};
2341
new_phi->definitions[0] = pc.second;
2342
for (unsigned i = 0; i < preds.size(); i++)
2343
new_phi->operands[i] = Operand(pc.first);
2344
instructions.emplace_back(std::move(new_phi));
2345
2346
/* Remove from live_out_per_block (now used for live-in), because handle_loop_phis()
2347
* would re-create this phi later if this is a loop header.
2348
*/
2349
live_out_per_block[block.index].erase(orig.id());
2350
}
2351
2352
register_file.fill(definition);
2353
ctx.assignments[definition.tempId()] = {definition.physReg(), definition.regClass()};
2354
}
2355
2356
/* update phi affinities */
2357
for (const Operand& op : phi->operands) {
2358
if (op.isTemp() && op.regClass() == phi->definitions[0].regClass())
2359
ctx.affinities[op.tempId()] = definition.tempId();
2360
}
2361
2362
instructions.emplace_back(std::move(*instr_it));
2363
}
2364
2365
/* fill in sgpr_live_in */
2366
for (unsigned i = 0; i <= ctx.max_used_sgpr; i++)
2367
sgpr_live_in[block.index][i] = register_file[PhysReg{i}];
2368
sgpr_live_in[block.index][127] = register_file[scc];
2369
2370
/* Handle all other instructions of the block */
2371
for (; instr_it != block.instructions.end(); ++instr_it) {
2372
aco_ptr<Instruction>& instr = *instr_it;
2373
2374
/* parallelcopies from p_phi are inserted here which means
2375
* live ranges of killed operands end here as well */
2376
if (instr->opcode == aco_opcode::p_logical_end) {
2377
/* no need to process this instruction any further */
2378
if (block.logical_succs.size() != 1) {
2379
instructions.emplace_back(std::move(instr));
2380
continue;
2381
}
2382
2383
Block& succ = program->blocks[block.logical_succs[0]];
2384
unsigned idx = 0;
2385
for (; idx < succ.logical_preds.size(); idx++) {
2386
if (succ.logical_preds[idx] == block.index)
2387
break;
2388
}
2389
for (aco_ptr<Instruction>& phi : succ.instructions) {
2390
if (phi->opcode == aco_opcode::p_phi) {
2391
if (phi->operands[idx].isTemp() &&
2392
phi->operands[idx].getTemp().type() == RegType::sgpr &&
2393
phi->operands[idx].isFirstKillBeforeDef()) {
2394
Definition phi_op(
2395
read_variable(ctx, phi->operands[idx].getTemp(), block.index));
2396
phi_op.setFixed(ctx.assignments[phi_op.tempId()].reg);
2397
register_file.clear(phi_op);
2398
}
2399
} else if (phi->opcode != aco_opcode::p_linear_phi) {
2400
break;
2401
}
2402
}
2403
instructions.emplace_back(std::move(instr));
2404
continue;
2405
}
2406
2407
std::vector<std::pair<Operand, Definition>> parallelcopy;
2408
2409
assert(!is_phi(instr));
2410
2411
bool temp_in_scc = register_file[scc];
2412
2413
/* handle operands */
2414
for (unsigned i = 0; i < instr->operands.size(); ++i) {
2415
auto& operand = instr->operands[i];
2416
if (!operand.isTemp())
2417
continue;
2418
2419
/* rename operands */
2420
operand.setTemp(read_variable(ctx, operand.getTemp(), block.index));
2421
assert(ctx.assignments[operand.tempId()].assigned);
2422
2423
PhysReg reg = ctx.assignments[operand.tempId()].reg;
2424
if (operand_can_use_reg(program->chip_class, instr, i, reg, operand.regClass()))
2425
operand.setFixed(reg);
2426
else
2427
get_reg_for_operand(ctx, register_file, parallelcopy, instr, operand, i);
2428
2429
if (instr->isEXP() || (instr->isVMEM() && i == 3 && ctx.program->chip_class == GFX6) ||
2430
(instr->isDS() && instr->ds().gds)) {
2431
for (unsigned j = 0; j < operand.size(); j++)
2432
ctx.war_hint.set(operand.physReg().reg() + j);
2433
}
2434
}
2435
2436
/* remove dead vars from register file */
2437
for (const Operand& op : instr->operands) {
2438
if (op.isTemp() && op.isFirstKillBeforeDef())
2439
register_file.clear(op);
2440
}
2441
2442
/* try to optimize v_mad_f32 -> v_mac_f32 */
2443
if ((instr->opcode == aco_opcode::v_mad_f32 ||
2444
(instr->opcode == aco_opcode::v_fma_f32 && program->chip_class >= GFX10) ||
2445
instr->opcode == aco_opcode::v_mad_f16 ||
2446
instr->opcode == aco_opcode::v_mad_legacy_f16 ||
2447
(instr->opcode == aco_opcode::v_fma_f16 && program->chip_class >= GFX10) ||
2448
(instr->opcode == aco_opcode::v_pk_fma_f16 && program->chip_class >= GFX10)) &&
2449
instr->operands[2].isTemp() && instr->operands[2].isKillBeforeDef() &&
2450
instr->operands[2].getTemp().type() == RegType::vgpr && instr->operands[1].isTemp() &&
2451
instr->operands[1].getTemp().type() == RegType::vgpr && !instr->usesModifiers() &&
2452
instr->operands[0].physReg().byte() == 0 && instr->operands[1].physReg().byte() == 0 &&
2453
instr->operands[2].physReg().byte() == 0) {
2454
unsigned def_id = instr->definitions[0].tempId();
2455
auto it = ctx.affinities.find(def_id);
2456
if (it == ctx.affinities.end() || !ctx.assignments[it->second].assigned ||
2457
instr->operands[2].physReg() == ctx.assignments[it->second].reg ||
2458
register_file.test(ctx.assignments[it->second].reg, instr->operands[2].bytes())) {
2459
instr->format = Format::VOP2;
2460
switch (instr->opcode) {
2461
case aco_opcode::v_mad_f32: instr->opcode = aco_opcode::v_mac_f32; break;
2462
case aco_opcode::v_fma_f32: instr->opcode = aco_opcode::v_fmac_f32; break;
2463
case aco_opcode::v_mad_f16:
2464
case aco_opcode::v_mad_legacy_f16: instr->opcode = aco_opcode::v_mac_f16; break;
2465
case aco_opcode::v_fma_f16: instr->opcode = aco_opcode::v_fmac_f16; break;
2466
case aco_opcode::v_pk_fma_f16: instr->opcode = aco_opcode::v_pk_fmac_f16; break;
2467
default: break;
2468
}
2469
}
2470
}
2471
2472
/* handle definitions which must have the same register as an operand */
2473
if (instr->opcode == aco_opcode::v_interp_p2_f32 ||
2474
instr->opcode == aco_opcode::v_mac_f32 || instr->opcode == aco_opcode::v_fmac_f32 ||
2475
instr->opcode == aco_opcode::v_mac_f16 || instr->opcode == aco_opcode::v_fmac_f16 ||
2476
instr->opcode == aco_opcode::v_pk_fmac_f16 ||
2477
instr->opcode == aco_opcode::v_writelane_b32 ||
2478
instr->opcode == aco_opcode::v_writelane_b32_e64) {
2479
instr->definitions[0].setFixed(instr->operands[2].physReg());
2480
} else if (instr->opcode == aco_opcode::s_addk_i32 ||
2481
instr->opcode == aco_opcode::s_mulk_i32) {
2482
instr->definitions[0].setFixed(instr->operands[0].physReg());
2483
} else if (instr->isMUBUF() && instr->definitions.size() == 1 &&
2484
instr->operands.size() == 4) {
2485
instr->definitions[0].setFixed(instr->operands[3].physReg());
2486
} else if (instr->isMIMG() && instr->definitions.size() == 1 &&
2487
!instr->operands[2].isUndefined()) {
2488
instr->definitions[0].setFixed(instr->operands[2].physReg());
2489
}
2490
2491
ctx.defs_done.reset();
2492
2493
/* handle fixed definitions first */
2494
for (unsigned i = 0; i < instr->definitions.size(); ++i) {
2495
auto& definition = instr->definitions[i];
2496
if (!definition.isFixed())
2497
continue;
2498
2499
adjust_max_used_regs(ctx, definition.regClass(), definition.physReg());
2500
/* check if the target register is blocked */
2501
if (register_file.test(definition.physReg(), definition.bytes())) {
2502
const PhysRegInterval def_regs{definition.physReg(), definition.size()};
2503
2504
/* create parallelcopy pair to move blocking vars */
2505
std::set<std::pair<unsigned, unsigned>> vars =
2506
collect_vars(ctx, register_file, def_regs);
2507
2508
RegisterFile tmp_file(register_file);
2509
/* re-enable the killed operands, so that we don't move the blocking vars there */
2510
for (const Operand& op : instr->operands) {
2511
if (op.isTemp() && op.isFirstKillBeforeDef())
2512
tmp_file.fill(op);
2513
}
2514
2515
ASSERTED bool success = false;
2516
DefInfo info(ctx, instr, definition.regClass(), -1);
2517
success = get_regs_for_copies(ctx, tmp_file, parallelcopy, vars, info.bounds, instr,
2518
def_regs);
2519
assert(success);
2520
2521
update_renames(ctx, register_file, parallelcopy, instr, (UpdateRenames)0);
2522
}
2523
ctx.defs_done.set(i);
2524
2525
if (!definition.isTemp())
2526
continue;
2527
2528
ctx.assignments[definition.tempId()] = {definition.physReg(), definition.regClass()};
2529
register_file.fill(definition);
2530
}
2531
2532
/* handle all other definitions */
2533
for (unsigned i = 0; i < instr->definitions.size(); ++i) {
2534
Definition* definition = &instr->definitions[i];
2535
2536
if (definition->isFixed() || !definition->isTemp())
2537
continue;
2538
2539
/* find free reg */
2540
if (definition->hasHint() &&
2541
get_reg_specified(ctx, register_file, definition->regClass(), instr,
2542
definition->physReg())) {
2543
definition->setFixed(definition->physReg());
2544
} else if (instr->opcode == aco_opcode::p_split_vector) {
2545
PhysReg reg = instr->operands[0].physReg();
2546
for (unsigned j = 0; j < i; j++)
2547
reg.reg_b += instr->definitions[j].bytes();
2548
if (get_reg_specified(ctx, register_file, definition->regClass(), instr, reg))
2549
definition->setFixed(reg);
2550
} else if (instr->opcode == aco_opcode::p_wqm ||
2551
instr->opcode == aco_opcode::p_parallelcopy) {
2552
PhysReg reg = instr->operands[i].physReg();
2553
if (instr->operands[i].isTemp() &&
2554
instr->operands[i].getTemp().type() == definition->getTemp().type() &&
2555
!register_file.test(reg, definition->bytes()))
2556
definition->setFixed(reg);
2557
} else if (instr->opcode == aco_opcode::p_extract_vector) {
2558
PhysReg reg = instr->operands[0].physReg();
2559
reg.reg_b += definition->bytes() * instr->operands[1].constantValue();
2560
if (get_reg_specified(ctx, register_file, definition->regClass(), instr, reg))
2561
definition->setFixed(reg);
2562
} else if (instr->opcode == aco_opcode::p_create_vector) {
2563
PhysReg reg = get_reg_create_vector(ctx, register_file, definition->getTemp(),
2564
parallelcopy, instr);
2565
update_renames(ctx, register_file, parallelcopy, instr, (UpdateRenames)0);
2566
definition->setFixed(reg);
2567
}
2568
2569
if (!definition->isFixed()) {
2570
Temp tmp = definition->getTemp();
2571
if (definition->regClass().is_subdword() && definition->bytes() < 4) {
2572
PhysReg reg = get_reg(ctx, register_file, tmp, parallelcopy, instr);
2573
definition->setFixed(reg);
2574
if (reg.byte() || register_file.test(reg, 4)) {
2575
add_subdword_definition(program, instr, i, reg);
2576
definition = &instr->definitions[i]; /* add_subdword_definition can invalidate
2577
the reference */
2578
}
2579
} else {
2580
definition->setFixed(get_reg(ctx, register_file, tmp, parallelcopy, instr));
2581
}
2582
update_renames(ctx, register_file, parallelcopy, instr,
2583
instr->opcode != aco_opcode::p_create_vector ? rename_not_killed_ops
2584
: (UpdateRenames)0);
2585
}
2586
2587
assert(
2588
definition->isFixed() &&
2589
((definition->getTemp().type() == RegType::vgpr && definition->physReg() >= 256) ||
2590
(definition->getTemp().type() != RegType::vgpr && definition->physReg() < 256)));
2591
ctx.defs_done.set(i);
2592
ctx.assignments[definition->tempId()] = {definition->physReg(), definition->regClass()};
2593
register_file.fill(*definition);
2594
}
2595
2596
handle_pseudo(ctx, register_file, instr.get());
2597
2598
/* kill definitions and late-kill operands and ensure that sub-dword operands can actually
2599
* be read */
2600
for (const Definition& def : instr->definitions) {
2601
if (def.isTemp() && def.isKill())
2602
register_file.clear(def);
2603
}
2604
for (unsigned i = 0; i < instr->operands.size(); i++) {
2605
const Operand& op = instr->operands[i];
2606
if (op.isTemp() && op.isFirstKill() && op.isLateKill())
2607
register_file.clear(op);
2608
if (op.isTemp() && op.physReg().byte() != 0)
2609
add_subdword_operand(ctx, instr, i, op.physReg().byte(), op.regClass());
2610
}
2611
2612
/* emit parallelcopy */
2613
if (!parallelcopy.empty()) {
2614
aco_ptr<Pseudo_instruction> pc;
2615
pc.reset(create_instruction<Pseudo_instruction>(aco_opcode::p_parallelcopy,
2616
Format::PSEUDO, parallelcopy.size(),
2617
parallelcopy.size()));
2618
bool sgpr_operands_alias_defs = false;
2619
uint64_t sgpr_operands[4] = {0, 0, 0, 0};
2620
for (unsigned i = 0; i < parallelcopy.size(); i++) {
2621
if (temp_in_scc && parallelcopy[i].first.isTemp() &&
2622
parallelcopy[i].first.getTemp().type() == RegType::sgpr) {
2623
if (!sgpr_operands_alias_defs) {
2624
unsigned reg = parallelcopy[i].first.physReg().reg();
2625
unsigned size = parallelcopy[i].first.getTemp().size();
2626
sgpr_operands[reg / 64u] |= u_bit_consecutive64(reg % 64u, size);
2627
2628
reg = parallelcopy[i].second.physReg().reg();
2629
size = parallelcopy[i].second.getTemp().size();
2630
if (sgpr_operands[reg / 64u] & u_bit_consecutive64(reg % 64u, size))
2631
sgpr_operands_alias_defs = true;
2632
}
2633
}
2634
2635
pc->operands[i] = parallelcopy[i].first;
2636
pc->definitions[i] = parallelcopy[i].second;
2637
assert(pc->operands[i].size() == pc->definitions[i].size());
2638
2639
/* it might happen that the operand is already renamed. we have to restore the
2640
* original name. */
2641
std::unordered_map<unsigned, Temp>::iterator it =
2642
ctx.orig_names.find(pc->operands[i].tempId());
2643
Temp orig = it != ctx.orig_names.end() ? it->second : pc->operands[i].getTemp();
2644
ctx.orig_names[pc->definitions[i].tempId()] = orig;
2645
ctx.renames[block.index][orig.id()] = pc->definitions[i].getTemp();
2646
}
2647
2648
if (temp_in_scc && sgpr_operands_alias_defs) {
2649
/* disable definitions and re-enable operands */
2650
RegisterFile tmp_file(register_file);
2651
for (const Definition& def : instr->definitions) {
2652
if (def.isTemp() && !def.isKill())
2653
tmp_file.clear(def);
2654
}
2655
for (const Operand& op : instr->operands) {
2656
if (op.isTemp() && op.isFirstKill())
2657
tmp_file.block(op.physReg(), op.regClass());
2658
}
2659
2660
handle_pseudo(ctx, tmp_file, pc.get());
2661
} else {
2662
pc->tmp_in_scc = false;
2663
}
2664
2665
instructions.emplace_back(std::move(pc));
2666
}
2667
2668
/* some instructions need VOP3 encoding if operand/definition is not assigned to VCC */
2669
bool instr_needs_vop3 =
2670
!instr->isVOP3() &&
2671
((instr->format == Format::VOPC && !(instr->definitions[0].physReg() == vcc)) ||
2672
(instr->opcode == aco_opcode::v_cndmask_b32 &&
2673
!(instr->operands[2].physReg() == vcc)) ||
2674
((instr->opcode == aco_opcode::v_add_co_u32 ||
2675
instr->opcode == aco_opcode::v_addc_co_u32 ||
2676
instr->opcode == aco_opcode::v_sub_co_u32 ||
2677
instr->opcode == aco_opcode::v_subb_co_u32 ||
2678
instr->opcode == aco_opcode::v_subrev_co_u32 ||
2679
instr->opcode == aco_opcode::v_subbrev_co_u32) &&
2680
!(instr->definitions[1].physReg() == vcc)) ||
2681
((instr->opcode == aco_opcode::v_addc_co_u32 ||
2682
instr->opcode == aco_opcode::v_subb_co_u32 ||
2683
instr->opcode == aco_opcode::v_subbrev_co_u32) &&
2684
!(instr->operands[2].physReg() == vcc)));
2685
if (instr_needs_vop3) {
2686
2687
/* if the first operand is a literal, we have to move it to a reg */
2688
if (instr->operands.size() && instr->operands[0].isLiteral() &&
2689
program->chip_class < GFX10) {
2690
bool can_sgpr = true;
2691
/* check, if we have to move to vgpr */
2692
for (const Operand& op : instr->operands) {
2693
if (op.isTemp() && op.getTemp().type() == RegType::sgpr) {
2694
can_sgpr = false;
2695
break;
2696
}
2697
}
2698
/* disable definitions and re-enable operands */
2699
RegisterFile tmp_file(register_file);
2700
for (const Definition& def : instr->definitions)
2701
tmp_file.clear(def);
2702
for (const Operand& op : instr->operands) {
2703
if (op.isTemp() && op.isFirstKill())
2704
tmp_file.block(op.physReg(), op.regClass());
2705
}
2706
Temp tmp = program->allocateTmp(can_sgpr ? s1 : v1);
2707
ctx.assignments.emplace_back();
2708
PhysReg reg = get_reg(ctx, tmp_file, tmp, parallelcopy, instr);
2709
update_renames(ctx, register_file, parallelcopy, instr, rename_not_killed_ops);
2710
2711
aco_ptr<Instruction> mov;
2712
if (can_sgpr)
2713
mov.reset(create_instruction<SOP1_instruction>(aco_opcode::s_mov_b32,
2714
Format::SOP1, 1, 1));
2715
else
2716
mov.reset(create_instruction<VOP1_instruction>(aco_opcode::v_mov_b32,
2717
Format::VOP1, 1, 1));
2718
mov->operands[0] = instr->operands[0];
2719
mov->definitions[0] = Definition(tmp);
2720
mov->definitions[0].setFixed(reg);
2721
2722
instr->operands[0] = Operand(tmp);
2723
instr->operands[0].setFixed(reg);
2724
instr->operands[0].setFirstKill(true);
2725
2726
instructions.emplace_back(std::move(mov));
2727
}
2728
2729
/* change the instruction to VOP3 to enable an arbitrary register pair as dst */
2730
aco_ptr<Instruction> tmp = std::move(instr);
2731
Format format = asVOP3(tmp->format);
2732
instr.reset(create_instruction<VOP3_instruction>(
2733
tmp->opcode, format, tmp->operands.size(), tmp->definitions.size()));
2734
std::copy(tmp->operands.begin(), tmp->operands.end(), instr->operands.begin());
2735
std::copy(tmp->definitions.begin(), tmp->definitions.end(), instr->definitions.begin());
2736
}
2737
2738
instructions.emplace_back(std::move(*instr_it));
2739
2740
} /* end for Instr */
2741
2742
block.instructions = std::move(instructions);
2743
} /* end for BB */
2744
2745
/* find scc spill registers which may be needed for parallelcopies created by phis */
2746
for (Block& block : program->blocks) {
2747
if (block.linear_preds.size() <= 1)
2748
continue;
2749
2750
std::bitset<128> regs = sgpr_live_in[block.index];
2751
if (!regs[127])
2752
continue;
2753
2754
/* choose a register */
2755
int16_t reg = 0;
2756
for (; reg < ctx.program->max_reg_demand.sgpr && regs[reg]; reg++)
2757
;
2758
assert(reg < ctx.program->max_reg_demand.sgpr);
2759
adjust_max_used_regs(ctx, s1, reg);
2760
2761
/* update predecessors */
2762
for (unsigned& pred_index : block.linear_preds) {
2763
Block& pred = program->blocks[pred_index];
2764
pred.scc_live_out = true;
2765
pred.scratch_sgpr = PhysReg{(uint16_t)reg};
2766
}
2767
}
2768
2769
/* num_gpr = rnd_up(max_used_gpr + 1) */
2770
program->config->num_vgprs = get_vgpr_alloc(program, ctx.max_used_vgpr + 1);
2771
program->config->num_sgprs = get_sgpr_alloc(program, ctx.max_used_sgpr + 1);
2772
2773
program->progress = CompilationProgress::after_ra;
2774
}
2775
2776
} // namespace aco
2777
2778