aco: set tcs_in_out_eq=false if float controls of VS and TCS stages differ
[mesa.git] / src / amd / compiler / aco_register_allocation.cpp
1 /*
2 * Copyright © 2018 Valve Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * Authors:
24 * Daniel Schürmann (daniel.schuermann@campus.tu-berlin.de)
25 * Bas Nieuwenhuizen (bas@basnieuwenhuizen.nl)
26 *
27 */
28
29 #include <algorithm>
30 #include <array>
31 #include <map>
32 #include <unordered_map>
33
34 #include "aco_ir.h"
35 #include "sid.h"
36 #include "util/u_math.h"
37
38 namespace aco {
39 namespace {
40
41 unsigned get_subdword_operand_stride(chip_class chip, const aco_ptr<Instruction>& instr, unsigned idx, RegClass rc);
42 void add_subdword_operand(chip_class chip, aco_ptr<Instruction>& instr, unsigned idx, unsigned byte, RegClass rc);
43 std::pair<unsigned, unsigned> get_subdword_definition_info(Program *program, const aco_ptr<Instruction>& instr, RegClass rc);
44 void add_subdword_definition(Program *program, aco_ptr<Instruction>& instr, unsigned idx, PhysReg reg, bool is_partial);
45
46 struct assignment {
47 PhysReg reg;
48 RegClass rc;
49 uint8_t assigned = 0;
50 assignment() = default;
51 assignment(PhysReg reg, RegClass rc) : reg(reg), rc(rc), assigned(-1) {}
52 };
53
54 struct phi_info {
55 Instruction* phi;
56 unsigned block_idx;
57 std::set<Instruction*> uses;
58 };
59
60 struct ra_ctx {
61 std::bitset<512> war_hint;
62 Program* program;
63 std::vector<assignment> assignments;
64 std::vector<std::unordered_map<unsigned, Temp>> renames;
65 std::vector<std::vector<Instruction*>> incomplete_phis;
66 std::vector<bool> filled;
67 std::vector<bool> sealed;
68 std::unordered_map<unsigned, Temp> orig_names;
69 std::unordered_map<unsigned, phi_info> phi_map;
70 std::unordered_map<unsigned, unsigned> affinities;
71 std::unordered_map<unsigned, Instruction*> vectors;
72 std::unordered_map<unsigned, Instruction*> split_vectors;
73 aco_ptr<Instruction> pseudo_dummy;
74 unsigned max_used_sgpr = 0;
75 unsigned max_used_vgpr = 0;
76 std::bitset<64> defs_done; /* see MAX_ARGS in aco_instruction_selection_setup.cpp */
77
78 ra_ctx(Program* program) : program(program),
79 assignments(program->peekAllocationId()),
80 renames(program->blocks.size()),
81 incomplete_phis(program->blocks.size()),
82 filled(program->blocks.size()),
83 sealed(program->blocks.size())
84 {
85 pseudo_dummy.reset(create_instruction<Instruction>(aco_opcode::p_parallelcopy, Format::PSEUDO, 0, 0));
86 }
87 };
88
89 struct DefInfo {
90 uint16_t lb;
91 uint16_t ub;
92 uint8_t size;
93 uint8_t stride;
94 RegClass rc;
95
96 DefInfo(ra_ctx& ctx, aco_ptr<Instruction>& instr, RegClass rc_, int operand) : rc(rc_) {
97 size = rc.size();
98 stride = 1;
99
100 if (rc.type() == RegType::vgpr) {
101 lb = 256;
102 ub = 256 + ctx.program->max_reg_demand.vgpr;
103 } else {
104 lb = 0;
105 ub = ctx.program->max_reg_demand.sgpr;
106 if (size == 2)
107 stride = 2;
108 else if (size >= 4)
109 stride = 4;
110 }
111
112 if (rc.is_subdword() && operand >= 0) {
113 /* stride in bytes */
114 stride = get_subdword_operand_stride(ctx.program->chip_class, instr, operand, rc);
115 } else if (rc.is_subdword()) {
116 std::pair<unsigned, unsigned> info = get_subdword_definition_info(ctx.program, instr, rc);
117 stride = info.first;
118 if (info.second > rc.bytes()) {
119 rc = RegClass::get(rc.type(), info.second);
120 size = rc.size();
121 /* we might still be able to put the definition in the high half,
122 * but that's only useful for affinities and this information isn't
123 * used for them */
124 stride = align(stride, info.second);
125 if (!rc.is_subdword())
126 stride = DIV_ROUND_UP(stride, 4);
127 }
128 assert(stride > 0);
129 }
130 }
131 };
132
133 class RegisterFile {
134 public:
135 RegisterFile() {regs.fill(0);}
136
137 std::array<uint32_t, 512> regs;
138 std::map<uint32_t, std::array<uint32_t, 4>> subdword_regs;
139
140 const uint32_t& operator [] (unsigned index) const {
141 return regs[index];
142 }
143
144 uint32_t& operator [] (unsigned index) {
145 return regs[index];
146 }
147
148 unsigned count_zero(PhysReg start, unsigned size) {
149 unsigned res = 0;
150 for (unsigned i = 0; i < size; i++)
151 res += !regs[start + i];
152 return res;
153 }
154
155 bool test(PhysReg start, unsigned num_bytes) {
156 for (PhysReg i = start; i.reg_b < start.reg_b + num_bytes; i = PhysReg(i + 1)) {
157 if (regs[i] & 0x0FFFFFFF)
158 return true;
159 if (regs[i] == 0xF0000000) {
160 assert(subdword_regs.find(i) != subdword_regs.end());
161 for (unsigned j = i.byte(); i * 4 + j < start.reg_b + num_bytes && j < 4; j++) {
162 if (subdword_regs[i][j])
163 return true;
164 }
165 }
166 }
167 return false;
168 }
169
170 void block(PhysReg start, RegClass rc) {
171 if (rc.is_subdword())
172 fill_subdword(start, rc.bytes(), 0xFFFFFFFF);
173 else
174 fill(start, rc.size(), 0xFFFFFFFF);
175 }
176
177 bool is_blocked(PhysReg start) {
178 if (regs[start] == 0xFFFFFFFF)
179 return true;
180 if (regs[start] == 0xF0000000) {
181 for (unsigned i = start.byte(); i < 4; i++)
182 if (subdword_regs[start][i] == 0xFFFFFFFF)
183 return true;
184 }
185 return false;
186 }
187
188 bool is_empty_or_blocked(PhysReg start) {
189 if (regs[start] == 0xF0000000) {
190 return subdword_regs[start][start.byte()] + 1 <= 1;
191 }
192 return regs[start] + 1 <= 1;
193 }
194
195 void clear(PhysReg start, RegClass rc) {
196 if (rc.is_subdword())
197 fill_subdword(start, rc.bytes(), 0);
198 else
199 fill(start, rc.size(), 0);
200 }
201
202 void fill(Operand op) {
203 if (op.regClass().is_subdword())
204 fill_subdword(op.physReg(), op.bytes(), op.tempId());
205 else
206 fill(op.physReg(), op.size(), op.tempId());
207 }
208
209 void clear(Operand op) {
210 clear(op.physReg(), op.regClass());
211 }
212
213 void fill(Definition def) {
214 if (def.regClass().is_subdword())
215 fill_subdword(def.physReg(), def.bytes(), def.tempId());
216 else
217 fill(def.physReg(), def.size(), def.tempId());
218 }
219
220 void clear(Definition def) {
221 clear(def.physReg(), def.regClass());
222 }
223
224 unsigned get_id(PhysReg reg) {
225 return regs[reg] == 0xF0000000 ? subdword_regs[reg][reg.byte()] : regs[reg];
226 }
227
228 private:
229 void fill(PhysReg start, unsigned size, uint32_t val) {
230 for (unsigned i = 0; i < size; i++)
231 regs[start + i] = val;
232 }
233
234 void fill_subdword(PhysReg start, unsigned num_bytes, uint32_t val) {
235 fill(start, DIV_ROUND_UP(num_bytes, 4), 0xF0000000);
236 for (PhysReg i = start; i.reg_b < start.reg_b + num_bytes; i = PhysReg(i + 1)) {
237 /* emplace or get */
238 std::array<uint32_t, 4>& sub = subdword_regs.emplace(i, std::array<uint32_t, 4>{0, 0, 0, 0}).first->second;
239 for (unsigned j = i.byte(); i * 4 + j < start.reg_b + num_bytes && j < 4; j++)
240 sub[j] = val;
241
242 if (sub == std::array<uint32_t, 4>{0, 0, 0, 0}) {
243 subdword_regs.erase(i);
244 regs[i] = 0;
245 }
246 }
247 }
248 };
249
250
251 /* helper function for debugging */
252 #if 0
253 void print_regs(ra_ctx& ctx, bool vgprs, RegisterFile& reg_file)
254 {
255 unsigned max = vgprs ? ctx.program->max_reg_demand.vgpr : ctx.program->max_reg_demand.sgpr;
256 unsigned lb = vgprs ? 256 : 0;
257 unsigned ub = lb + max;
258 char reg_char = vgprs ? 'v' : 's';
259
260 /* print markers */
261 printf(" ");
262 for (unsigned i = lb; i < ub; i += 3) {
263 printf("%.2u ", i - lb);
264 }
265 printf("\n");
266
267 /* print usage */
268 printf("%cgprs: ", reg_char);
269 unsigned free_regs = 0;
270 unsigned prev = 0;
271 bool char_select = false;
272 for (unsigned i = lb; i < ub; i++) {
273 if (reg_file[i] == 0xFFFF) {
274 printf("~");
275 } else if (reg_file[i]) {
276 if (reg_file[i] != prev) {
277 prev = reg_file[i];
278 char_select = !char_select;
279 }
280 printf(char_select ? "#" : "@");
281 } else {
282 free_regs++;
283 printf(".");
284 }
285 }
286 printf("\n");
287
288 printf("%u/%u used, %u/%u free\n", max - free_regs, max, free_regs, max);
289
290 /* print assignments */
291 prev = 0;
292 unsigned size = 0;
293 for (unsigned i = lb; i < ub; i++) {
294 if (reg_file[i] != prev) {
295 if (prev && size > 1)
296 printf("-%d]\n", i - 1 - lb);
297 else if (prev)
298 printf("]\n");
299 prev = reg_file[i];
300 if (prev && prev != 0xFFFF) {
301 if (ctx.orig_names.count(reg_file[i]) && ctx.orig_names[reg_file[i]].id() != reg_file[i])
302 printf("%%%u (was %%%d) = %c[%d", reg_file[i], ctx.orig_names[reg_file[i]].id(), reg_char, i - lb);
303 else
304 printf("%%%u = %c[%d", reg_file[i], reg_char, i - lb);
305 }
306 size = 1;
307 } else {
308 size++;
309 }
310 }
311 if (prev && size > 1)
312 printf("-%d]\n", ub - lb - 1);
313 else if (prev)
314 printf("]\n");
315 }
316 #endif
317
318
319 unsigned get_subdword_operand_stride(chip_class chip, const aco_ptr<Instruction>& instr, unsigned idx, RegClass rc)
320 {
321 if (instr->format == Format::PSEUDO && chip >= GFX8)
322 return rc.bytes() % 2 == 0 ? 2 : 1;
323
324 if (instr->opcode == aco_opcode::v_cvt_f32_ubyte0) {
325 return 1;
326 } else if (can_use_SDWA(chip, instr)) {
327 return rc.bytes() % 2 == 0 ? 2 : 1;
328 } else if (rc.bytes() == 2 && can_use_opsel(chip, instr->opcode, idx, 1)) {
329 return 2;
330 }
331
332 switch (instr->opcode) {
333 case aco_opcode::ds_write_b8:
334 case aco_opcode::ds_write_b16:
335 return chip >= GFX8 ? 2 : 4;
336 case aco_opcode::buffer_store_byte:
337 case aco_opcode::buffer_store_short:
338 case aco_opcode::flat_store_byte:
339 case aco_opcode::flat_store_short:
340 case aco_opcode::scratch_store_byte:
341 case aco_opcode::scratch_store_short:
342 case aco_opcode::global_store_byte:
343 case aco_opcode::global_store_short:
344 return chip >= GFX9 ? 2 : 4;
345 default:
346 break;
347 }
348
349 return 4;
350 }
351
352 void add_subdword_operand(chip_class chip, aco_ptr<Instruction>& instr, unsigned idx, unsigned byte, RegClass rc)
353 {
354 if (instr->format == Format::PSEUDO || byte == 0)
355 return;
356
357 assert(rc.bytes() <= 2);
358
359 if (!instr->usesModifiers() && instr->opcode == aco_opcode::v_cvt_f32_ubyte0) {
360 switch (byte) {
361 case 0:
362 instr->opcode = aco_opcode::v_cvt_f32_ubyte0;
363 break;
364 case 1:
365 instr->opcode = aco_opcode::v_cvt_f32_ubyte1;
366 break;
367 case 2:
368 instr->opcode = aco_opcode::v_cvt_f32_ubyte2;
369 break;
370 case 3:
371 instr->opcode = aco_opcode::v_cvt_f32_ubyte3;
372 break;
373 }
374 return;
375 } else if (can_use_SDWA(chip, instr)) {
376 convert_to_SDWA(chip, instr);
377 return;
378 } else if (rc.bytes() == 2 && can_use_opsel(chip, instr->opcode, idx, byte / 2)) {
379 VOP3A_instruction *vop3 = static_cast<VOP3A_instruction *>(instr.get());
380 vop3->opsel |= (byte / 2) << idx;
381 return;
382 }
383
384 if (chip >= GFX8 && instr->opcode == aco_opcode::ds_write_b8 && byte == 2) {
385 instr->opcode = aco_opcode::ds_write_b8_d16_hi;
386 return;
387 }
388 if (chip >= GFX8 && instr->opcode == aco_opcode::ds_write_b16 && byte == 2) {
389 instr->opcode = aco_opcode::ds_write_b16_d16_hi;
390 return;
391 }
392
393 if (chip >= GFX9 && byte == 2) {
394 if (instr->opcode == aco_opcode::buffer_store_byte)
395 instr->opcode = aco_opcode::buffer_store_byte_d16_hi;
396 else if (instr->opcode == aco_opcode::buffer_store_short)
397 instr->opcode = aco_opcode::buffer_store_short_d16_hi;
398 else if (instr->opcode == aco_opcode::flat_store_byte)
399 instr->opcode = aco_opcode::flat_store_byte_d16_hi;
400 else if (instr->opcode == aco_opcode::flat_store_short)
401 instr->opcode = aco_opcode::flat_store_short_d16_hi;
402 else if (instr->opcode == aco_opcode::scratch_store_byte)
403 instr->opcode = aco_opcode::scratch_store_byte_d16_hi;
404 else if (instr->opcode == aco_opcode::scratch_store_short)
405 instr->opcode = aco_opcode::scratch_store_short_d16_hi;
406 else if (instr->opcode == aco_opcode::global_store_byte)
407 instr->opcode = aco_opcode::global_store_byte_d16_hi;
408 else if (instr->opcode == aco_opcode::global_store_short)
409 instr->opcode = aco_opcode::global_store_short_d16_hi;
410 else
411 unreachable("Something went wrong: Impossible register assignment.");
412 }
413 }
414
415 /* minimum_stride, bytes_written */
416 std::pair<unsigned, unsigned> get_subdword_definition_info(Program *program, const aco_ptr<Instruction>& instr, RegClass rc)
417 {
418 chip_class chip = program->chip_class;
419
420 if (instr->format == Format::PSEUDO && chip >= GFX8)
421 return std::make_pair(rc.bytes() % 2 == 0 ? 2 : 1, rc.bytes());
422 else if (instr->format == Format::PSEUDO)
423 return std::make_pair(4, rc.size() * 4u);
424
425 unsigned bytes_written = chip >= GFX10 ? rc.bytes() : 4u;
426 switch (instr->opcode) {
427 case aco_opcode::v_mad_f16:
428 case aco_opcode::v_mad_u16:
429 case aco_opcode::v_mad_i16:
430 case aco_opcode::v_fma_f16:
431 case aco_opcode::v_div_fixup_f16:
432 case aco_opcode::v_interp_p2_f16:
433 bytes_written = chip >= GFX9 ? rc.bytes() : 4u;
434 break;
435 default:
436 break;
437 }
438 bytes_written = MAX2(bytes_written, instr_info.definition_size[(int)instr->opcode] / 8u);
439
440 if (can_use_SDWA(chip, instr)) {
441 return std::make_pair(rc.bytes(), rc.bytes());
442 } else if (rc.bytes() == 2 && can_use_opsel(chip, instr->opcode, -1, 1)) {
443 return std::make_pair(2u, bytes_written);
444 }
445
446 switch (instr->opcode) {
447 case aco_opcode::buffer_load_ubyte_d16:
448 case aco_opcode::buffer_load_short_d16:
449 case aco_opcode::flat_load_ubyte_d16:
450 case aco_opcode::flat_load_short_d16:
451 case aco_opcode::scratch_load_ubyte_d16:
452 case aco_opcode::scratch_load_short_d16:
453 case aco_opcode::global_load_ubyte_d16:
454 case aco_opcode::global_load_short_d16:
455 case aco_opcode::ds_read_u8_d16:
456 case aco_opcode::ds_read_u16_d16:
457 if (chip >= GFX9 && !program->sram_ecc_enabled)
458 return std::make_pair(2u, 2u);
459 else
460 return std::make_pair(2u, 4u);
461 default:
462 break;
463 }
464
465 return std::make_pair(4u, bytes_written);
466 }
467
468 void add_subdword_definition(Program *program, aco_ptr<Instruction>& instr, unsigned idx, PhysReg reg, bool is_partial)
469 {
470 RegClass rc = instr->definitions[idx].regClass();
471 chip_class chip = program->chip_class;
472
473 instr->definitions[idx].setFixed(reg);
474
475 if (instr->format == Format::PSEUDO) {
476 return;
477 } else if (can_use_SDWA(chip, instr)) {
478 if (reg.byte() || (is_partial && chip < GFX10))
479 convert_to_SDWA(chip, instr);
480 return;
481 } else if (reg.byte() && rc.bytes() == 2 && can_use_opsel(chip, instr->opcode, -1, reg.byte() / 2)) {
482 VOP3A_instruction *vop3 = static_cast<VOP3A_instruction *>(instr.get());
483 if (reg.byte() == 2)
484 vop3->opsel |= (1 << 3); /* dst in high half */
485 return;
486 }
487
488 if (reg.byte() == 2) {
489 if (instr->opcode == aco_opcode::buffer_load_ubyte_d16)
490 instr->opcode = aco_opcode::buffer_load_ubyte_d16_hi;
491 else if (instr->opcode == aco_opcode::buffer_load_short_d16)
492 instr->opcode = aco_opcode::buffer_load_short_d16_hi;
493 else if (instr->opcode == aco_opcode::flat_load_ubyte_d16)
494 instr->opcode = aco_opcode::flat_load_ubyte_d16_hi;
495 else if (instr->opcode == aco_opcode::flat_load_short_d16)
496 instr->opcode = aco_opcode::flat_load_short_d16_hi;
497 else if (instr->opcode == aco_opcode::scratch_load_ubyte_d16)
498 instr->opcode = aco_opcode::scratch_load_ubyte_d16_hi;
499 else if (instr->opcode == aco_opcode::scratch_load_short_d16)
500 instr->opcode = aco_opcode::scratch_load_short_d16_hi;
501 else if (instr->opcode == aco_opcode::global_load_ubyte_d16)
502 instr->opcode = aco_opcode::global_load_ubyte_d16_hi;
503 else if (instr->opcode == aco_opcode::global_load_short_d16)
504 instr->opcode = aco_opcode::global_load_short_d16_hi;
505 else if (instr->opcode == aco_opcode::ds_read_u8_d16)
506 instr->opcode = aco_opcode::ds_read_u8_d16_hi;
507 else if (instr->opcode == aco_opcode::ds_read_u16_d16)
508 instr->opcode = aco_opcode::ds_read_u16_d16_hi;
509 else
510 unreachable("Something went wrong: Impossible register assignment.");
511 }
512 }
513
514 void adjust_max_used_regs(ra_ctx& ctx, RegClass rc, unsigned reg)
515 {
516 unsigned max_addressible_sgpr = ctx.program->sgpr_limit;
517 unsigned size = rc.size();
518 if (rc.type() == RegType::vgpr) {
519 assert(reg >= 256);
520 unsigned hi = reg - 256 + size - 1;
521 ctx.max_used_vgpr = std::max(ctx.max_used_vgpr, hi);
522 } else if (reg + rc.size() <= max_addressible_sgpr) {
523 unsigned hi = reg + size - 1;
524 ctx.max_used_sgpr = std::max(ctx.max_used_sgpr, std::min(hi, max_addressible_sgpr));
525 }
526 }
527
528
529 void update_renames(ra_ctx& ctx, RegisterFile& reg_file,
530 std::vector<std::pair<Operand, Definition>>& parallelcopies,
531 aco_ptr<Instruction>& instr, bool rename_not_killed_ops)
532 {
533 /* allocate id's and rename operands: this is done transparently here */
534 for (std::pair<Operand, Definition>& copy : parallelcopies) {
535 /* the definitions with id are not from this function and already handled */
536 if (copy.second.isTemp())
537 continue;
538
539 /* check if we we moved another parallelcopy definition */
540 for (std::pair<Operand, Definition>& other : parallelcopies) {
541 if (!other.second.isTemp())
542 continue;
543 if (copy.first.getTemp() == other.second.getTemp()) {
544 copy.first.setTemp(other.first.getTemp());
545 copy.first.setFixed(other.first.physReg());
546 }
547 }
548 // FIXME: if a definition got moved, change the target location and remove the parallelcopy
549 copy.second.setTemp(Temp(ctx.program->allocateId(), copy.second.regClass()));
550 ctx.assignments.emplace_back(copy.second.physReg(), copy.second.regClass());
551 assert(ctx.assignments.size() == ctx.program->peekAllocationId());
552 reg_file.fill(copy.second);
553
554 /* check if we moved an operand */
555 bool first = true;
556 for (unsigned i = 0; i < instr->operands.size(); i++) {
557 Operand& op = instr->operands[i];
558 if (!op.isTemp())
559 continue;
560 if (op.tempId() == copy.first.tempId()) {
561 bool omit_renaming = !rename_not_killed_ops && !op.isKillBeforeDef();
562 for (std::pair<Operand, Definition>& pc : parallelcopies) {
563 PhysReg def_reg = pc.second.physReg();
564 omit_renaming &= def_reg > copy.first.physReg() ?
565 (copy.first.physReg() + copy.first.size() <= def_reg.reg()) :
566 (def_reg + pc.second.size() <= copy.first.physReg().reg());
567 }
568 if (omit_renaming) {
569 if (first)
570 op.setFirstKill(true);
571 else
572 op.setKill(true);
573 first = false;
574 continue;
575 }
576 op.setTemp(copy.second.getTemp());
577 op.setFixed(copy.second.physReg());
578 }
579 }
580 }
581 }
582
583 std::pair<PhysReg, bool> get_reg_simple(ra_ctx& ctx,
584 RegisterFile& reg_file,
585 DefInfo info)
586 {
587 uint32_t lb = info.lb;
588 uint32_t ub = info.ub;
589 uint32_t size = info.size;
590 uint32_t stride = info.rc.is_subdword() ? DIV_ROUND_UP(info.stride, 4) : info.stride;
591 RegClass rc = info.rc;
592
593 if (stride == 1) {
594
595 for (unsigned stride = 8; stride > 1; stride /= 2) {
596 if (size % stride)
597 continue;
598 info.stride = stride;
599 std::pair<PhysReg, bool> res = get_reg_simple(ctx, reg_file, info);
600 if (res.second)
601 return res;
602 }
603
604 /* best fit algorithm: find the smallest gap to fit in the variable */
605 unsigned best_pos = 0xFFFF;
606 unsigned gap_size = 0xFFFF;
607 unsigned last_pos = 0xFFFF;
608
609 for (unsigned current_reg = lb; current_reg < ub; current_reg++) {
610
611 if (reg_file[current_reg] == 0 && !ctx.war_hint[current_reg]) {
612 if (last_pos == 0xFFFF)
613 last_pos = current_reg;
614
615 /* stop searching after max_used_gpr */
616 if (current_reg == ctx.max_used_sgpr + 1 || current_reg == 256 + ctx.max_used_vgpr + 1)
617 break;
618 else
619 continue;
620 }
621
622 if (last_pos == 0xFFFF)
623 continue;
624
625 /* early return on exact matches */
626 if (last_pos + size == current_reg) {
627 adjust_max_used_regs(ctx, rc, last_pos);
628 return {PhysReg{last_pos}, true};
629 }
630
631 /* check if it fits and the gap size is smaller */
632 if (last_pos + size < current_reg && current_reg - last_pos < gap_size) {
633 best_pos = last_pos;
634 gap_size = current_reg - last_pos;
635 }
636 last_pos = 0xFFFF;
637 }
638
639 /* final check */
640 if (last_pos + size <= ub && ub - last_pos < gap_size) {
641 best_pos = last_pos;
642 gap_size = ub - last_pos;
643 }
644
645 if (best_pos == 0xFFFF)
646 return {{}, false};
647
648 /* find best position within gap by leaving a good stride for other variables*/
649 unsigned buffer = gap_size - size;
650 if (buffer > 1) {
651 if (((best_pos + size) % 8 != 0 && (best_pos + buffer) % 8 == 0) ||
652 ((best_pos + size) % 4 != 0 && (best_pos + buffer) % 4 == 0) ||
653 ((best_pos + size) % 2 != 0 && (best_pos + buffer) % 2 == 0))
654 best_pos = best_pos + buffer;
655 }
656
657 adjust_max_used_regs(ctx, rc, best_pos);
658 return {PhysReg{best_pos}, true};
659 }
660
661 bool found = false;
662 unsigned reg_lo = lb;
663 unsigned reg_hi = lb + size - 1;
664 while (!found && reg_lo + size <= ub) {
665 if (reg_file[reg_lo] != 0) {
666 reg_lo += stride;
667 continue;
668 }
669 reg_hi = reg_lo + size - 1;
670 found = true;
671 for (unsigned reg = reg_lo + 1; found && reg <= reg_hi; reg++) {
672 if (reg_file[reg] != 0 || ctx.war_hint[reg])
673 found = false;
674 }
675 if (found) {
676 adjust_max_used_regs(ctx, rc, reg_lo);
677 return {PhysReg{reg_lo}, true};
678 }
679
680 reg_lo += stride;
681 }
682
683 /* do this late because using the upper bytes of a register can require
684 * larger instruction encodings or copies
685 * TODO: don't do this in situations where it doesn't benefit */
686 if (rc.is_subdword()) {
687 for (std::pair<uint32_t, std::array<uint32_t, 4>> entry : reg_file.subdword_regs) {
688 assert(reg_file[entry.first] == 0xF0000000);
689 if (lb > entry.first || entry.first >= ub)
690 continue;
691
692 for (unsigned i = 0; i < 4; i+= info.stride) {
693 if (entry.second[i] != 0)
694 continue;
695
696 bool reg_found = true;
697 for (unsigned j = 1; reg_found && i + j < 4 && j < rc.bytes(); j++)
698 reg_found &= entry.second[i + j] == 0;
699
700 /* check neighboring reg if needed */
701 reg_found &= ((int)i <= 4 - (int)rc.bytes() || reg_file[entry.first + 1] == 0);
702 if (reg_found) {
703 PhysReg res{entry.first};
704 res.reg_b += i;
705 adjust_max_used_regs(ctx, rc, entry.first);
706 return {res, true};
707 }
708 }
709 }
710 }
711
712 return {{}, false};
713 }
714
715 /* collect variables from a register area and clear reg_file */
716 std::set<std::pair<unsigned, unsigned>> collect_vars(ra_ctx& ctx, RegisterFile& reg_file,
717 PhysReg reg, unsigned size)
718 {
719 std::set<std::pair<unsigned, unsigned>> vars;
720 for (unsigned j = reg; j < reg + size; j++) {
721 if (reg_file.is_blocked(PhysReg{j}))
722 continue;
723 if (reg_file[j] == 0xF0000000) {
724 for (unsigned k = 0; k < 4; k++) {
725 unsigned id = reg_file.subdword_regs[j][k];
726 if (id) {
727 assignment& var = ctx.assignments[id];
728 vars.emplace(var.rc.bytes(), id);
729 reg_file.clear(var.reg, var.rc);
730 if (!reg_file[j])
731 break;
732 }
733 }
734 } else if (reg_file[j] != 0) {
735 unsigned id = reg_file[j];
736 assignment& var = ctx.assignments[id];
737 vars.emplace(var.rc.bytes(), id);
738 reg_file.clear(var.reg, var.rc);
739 }
740 }
741 return vars;
742 }
743
744 bool get_regs_for_copies(ra_ctx& ctx,
745 RegisterFile& reg_file,
746 std::vector<std::pair<Operand, Definition>>& parallelcopies,
747 const std::set<std::pair<unsigned, unsigned>> &vars,
748 uint32_t lb, uint32_t ub,
749 aco_ptr<Instruction>& instr,
750 uint32_t def_reg_lo,
751 uint32_t def_reg_hi)
752 {
753
754 /* variables are sorted from small sized to large */
755 /* NOTE: variables are also sorted by ID. this only affects a very small number of shaders slightly though. */
756 for (std::set<std::pair<unsigned, unsigned>>::const_reverse_iterator it = vars.rbegin(); it != vars.rend(); ++it) {
757 unsigned id = it->second;
758 assignment& var = ctx.assignments[id];
759 DefInfo info = DefInfo(ctx, ctx.pseudo_dummy, var.rc, -1);
760 uint32_t size = info.size;
761
762 /* check if this is a dead operand, then we can re-use the space from the definition
763 * also use the correct stride for sub-dword operands */
764 bool is_dead_operand = false;
765 for (unsigned i = 0; !is_phi(instr) && i < instr->operands.size(); i++) {
766 if (instr->operands[i].isTemp() && instr->operands[i].tempId() == id) {
767 if (instr->operands[i].isKillBeforeDef())
768 is_dead_operand = true;
769 info = DefInfo(ctx, instr, var.rc, i);
770 break;
771 }
772 }
773
774 std::pair<PhysReg, bool> res;
775 if (is_dead_operand) {
776 if (instr->opcode == aco_opcode::p_create_vector) {
777 PhysReg reg(def_reg_lo);
778 for (unsigned i = 0; i < instr->operands.size(); i++) {
779 if (instr->operands[i].isTemp() && instr->operands[i].tempId() == id) {
780 res = {reg, (!var.rc.is_subdword() || (reg.byte() % info.stride == 0)) && !reg_file.test(reg, var.rc.bytes())};
781 break;
782 }
783 reg.reg_b += instr->operands[i].bytes();
784 }
785 if (!res.second)
786 res = {var.reg, !reg_file.test(var.reg, var.rc.bytes())};
787 } else {
788 info.lb = def_reg_lo;
789 info.ub = def_reg_hi + 1;
790 res = get_reg_simple(ctx, reg_file, info);
791 }
792 } else {
793 info.lb = lb;
794 info.ub = MIN2(def_reg_lo, ub);
795 res = get_reg_simple(ctx, reg_file, info);
796 if (!res.second && def_reg_hi < ub) {
797 info.lb = (def_reg_hi + info.stride) & ~(info.stride - 1);
798 info.ub = ub;
799 res = get_reg_simple(ctx, reg_file, info);
800 }
801 }
802
803 if (res.second) {
804 /* mark the area as blocked */
805 reg_file.block(res.first, var.rc);
806
807 /* create parallelcopy pair (without definition id) */
808 Temp tmp = Temp(id, var.rc);
809 Operand pc_op = Operand(tmp);
810 pc_op.setFixed(var.reg);
811 Definition pc_def = Definition(res.first, pc_op.regClass());
812 parallelcopies.emplace_back(pc_op, pc_def);
813 continue;
814 }
815
816 unsigned best_pos = lb;
817 unsigned num_moves = 0xFF;
818 unsigned num_vars = 0;
819
820 /* we use a sliding window to find potential positions */
821 unsigned reg_lo = lb;
822 unsigned reg_hi = lb + size - 1;
823 unsigned stride = var.rc.is_subdword() ? 1 : info.stride;
824 for (reg_lo = lb, reg_hi = lb + size - 1; reg_hi < ub; reg_lo += stride, reg_hi += stride) {
825 if (!is_dead_operand && ((reg_lo >= def_reg_lo && reg_lo <= def_reg_hi) ||
826 (reg_hi >= def_reg_lo && reg_hi <= def_reg_hi)))
827 continue;
828
829 /* second, check that we have at most k=num_moves elements in the window
830 * and no element is larger than the currently processed one */
831 unsigned k = 0;
832 unsigned n = 0;
833 unsigned last_var = 0;
834 bool found = true;
835 for (unsigned j = reg_lo; found && j <= reg_hi; j++) {
836 if (reg_file[j] == 0 || reg_file[j] == last_var)
837 continue;
838
839 if (reg_file.is_blocked(PhysReg{j}) || k > num_moves) {
840 found = false;
841 break;
842 }
843 if (reg_file[j] == 0xF0000000) {
844 k += 1;
845 n++;
846 continue;
847 }
848 /* we cannot split live ranges of linear vgprs */
849 if (ctx.assignments[reg_file[j]].rc & (1 << 6)) {
850 found = false;
851 break;
852 }
853 bool is_kill = false;
854 for (const Operand& op : instr->operands) {
855 if (op.isTemp() && op.isKillBeforeDef() && op.tempId() == reg_file[j]) {
856 is_kill = true;
857 break;
858 }
859 }
860 if (!is_kill && ctx.assignments[reg_file[j]].rc.size() >= size) {
861 found = false;
862 break;
863 }
864
865 k += ctx.assignments[reg_file[j]].rc.size();
866 last_var = reg_file[j];
867 n++;
868 if (k > num_moves || (k == num_moves && n <= num_vars)) {
869 found = false;
870 break;
871 }
872 }
873
874 if (found) {
875 best_pos = reg_lo;
876 num_moves = k;
877 num_vars = n;
878 }
879 }
880
881 /* FIXME: we messed up and couldn't find space for the variables to be copied */
882 if (num_moves == 0xFF)
883 return false;
884
885 reg_lo = best_pos;
886 reg_hi = best_pos + size - 1;
887
888 /* collect variables and block reg file */
889 std::set<std::pair<unsigned, unsigned>> new_vars = collect_vars(ctx, reg_file, PhysReg{reg_lo}, size);
890
891 /* mark the area as blocked */
892 reg_file.block(PhysReg{reg_lo}, var.rc);
893
894 if (!get_regs_for_copies(ctx, reg_file, parallelcopies, new_vars, lb, ub, instr, def_reg_lo, def_reg_hi))
895 return false;
896
897 adjust_max_used_regs(ctx, var.rc, reg_lo);
898
899 /* create parallelcopy pair (without definition id) */
900 Temp tmp = Temp(id, var.rc);
901 Operand pc_op = Operand(tmp);
902 pc_op.setFixed(var.reg);
903 Definition pc_def = Definition(PhysReg{reg_lo}, pc_op.regClass());
904 parallelcopies.emplace_back(pc_op, pc_def);
905 }
906
907 return true;
908 }
909
910
911 std::pair<PhysReg, bool> get_reg_impl(ra_ctx& ctx,
912 RegisterFile& reg_file,
913 std::vector<std::pair<Operand, Definition>>& parallelcopies,
914 DefInfo info,
915 aco_ptr<Instruction>& instr)
916 {
917 uint32_t lb = info.lb;
918 uint32_t ub = info.ub;
919 uint32_t size = info.size;
920 uint32_t stride = info.stride;
921 RegClass rc = info.rc;
922
923 /* check how many free regs we have */
924 unsigned regs_free = reg_file.count_zero(PhysReg{lb}, ub-lb);
925
926 /* mark and count killed operands */
927 unsigned killed_ops = 0;
928 for (unsigned j = 0; !is_phi(instr) && j < instr->operands.size(); j++) {
929 if (instr->operands[j].isTemp() &&
930 instr->operands[j].isFirstKillBeforeDef() &&
931 instr->operands[j].physReg() >= lb &&
932 instr->operands[j].physReg() < ub &&
933 !reg_file.test(instr->operands[j].physReg(), instr->operands[j].bytes())) {
934 assert(instr->operands[j].isFixed());
935 reg_file.block(instr->operands[j].physReg(), instr->operands[j].regClass());
936 killed_ops += instr->operands[j].getTemp().size();
937 }
938 }
939
940 assert(regs_free >= size);
941 /* we might have to move dead operands to dst in order to make space */
942 unsigned op_moves = 0;
943
944 if (size > (regs_free - killed_ops))
945 op_moves = size - (regs_free - killed_ops);
946
947 /* find the best position to place the definition */
948 unsigned best_pos = lb;
949 unsigned num_moves = 0xFF;
950 unsigned num_vars = 0;
951
952 /* we use a sliding window to check potential positions */
953 unsigned reg_lo = lb;
954 unsigned reg_hi = lb + size - 1;
955 for (reg_lo = lb, reg_hi = lb + size - 1; reg_hi < ub; reg_lo += stride, reg_hi += stride) {
956 /* first check the edges: this is what we have to fix to allow for num_moves > size */
957 if (reg_lo > lb && !reg_file.is_empty_or_blocked(PhysReg(reg_lo)) &&
958 reg_file.get_id(PhysReg(reg_lo)) == reg_file.get_id(PhysReg(reg_lo).advance(-1)))
959 continue;
960 if (reg_hi < ub - 1 && !reg_file.is_empty_or_blocked(PhysReg(reg_hi).advance(3)) &&
961 reg_file.get_id(PhysReg(reg_hi).advance(3)) == reg_file.get_id(PhysReg(reg_hi).advance(4)))
962 continue;
963
964 /* second, check that we have at most k=num_moves elements in the window
965 * and no element is larger than the currently processed one */
966 unsigned k = op_moves;
967 unsigned n = 0;
968 unsigned remaining_op_moves = op_moves;
969 unsigned last_var = 0;
970 bool found = true;
971 bool aligned = rc == RegClass::v4 && reg_lo % 4 == 0;
972 for (unsigned j = reg_lo; found && j <= reg_hi; j++) {
973 if (reg_file[j] == 0 || reg_file[j] == last_var)
974 continue;
975
976 /* dead operands effectively reduce the number of estimated moves */
977 if (reg_file.is_blocked(PhysReg{j})) {
978 if (remaining_op_moves) {
979 k--;
980 remaining_op_moves--;
981 }
982 continue;
983 }
984
985 if (reg_file[j] == 0xF0000000) {
986 k += 1;
987 n++;
988 continue;
989 }
990
991 if (ctx.assignments[reg_file[j]].rc.size() >= size) {
992 found = false;
993 break;
994 }
995
996 /* we cannot split live ranges of linear vgprs */
997 if (ctx.assignments[reg_file[j]].rc & (1 << 6)) {
998 found = false;
999 break;
1000 }
1001
1002 k += ctx.assignments[reg_file[j]].rc.size();
1003 n++;
1004 last_var = reg_file[j];
1005 }
1006
1007 if (!found || k > num_moves)
1008 continue;
1009 if (k == num_moves && n < num_vars)
1010 continue;
1011 if (!aligned && k == num_moves && n == num_vars)
1012 continue;
1013
1014 if (found) {
1015 best_pos = reg_lo;
1016 num_moves = k;
1017 num_vars = n;
1018 }
1019 }
1020
1021 if (num_moves == 0xFF) {
1022 /* remove killed operands from reg_file once again */
1023 for (unsigned i = 0; !is_phi(instr) && i < instr->operands.size(); i++) {
1024 if (instr->operands[i].isTemp() && instr->operands[i].isFirstKillBeforeDef())
1025 reg_file.clear(instr->operands[i]);
1026 }
1027 for (unsigned i = 0; i < instr->definitions.size(); i++) {
1028 Definition def = instr->definitions[i];
1029 if (def.isTemp() && def.isFixed() && ctx.defs_done.test(i))
1030 reg_file.fill(def);
1031 }
1032 return {{}, false};
1033 }
1034
1035 RegisterFile register_file = reg_file;
1036
1037 /* now, we figured the placement for our definition */
1038 std::set<std::pair<unsigned, unsigned>> vars = collect_vars(ctx, reg_file, PhysReg{best_pos}, size);
1039
1040 if (instr->opcode == aco_opcode::p_create_vector) {
1041 /* move killed operands which aren't yet at the correct position (GFX9+)
1042 * or which are in the definition space */
1043 PhysReg reg = PhysReg{best_pos};
1044 for (Operand& op : instr->operands) {
1045 if (op.isTemp() && op.isFirstKillBeforeDef() &&
1046 op.getTemp().type() == rc.type()) {
1047 if (op.physReg() != reg &&
1048 (ctx.program->chip_class >= GFX9 ||
1049 (op.physReg().advance(op.bytes()) > PhysReg{best_pos} &&
1050 op.physReg() < PhysReg{best_pos + size}))) {
1051 vars.emplace(op.bytes(), op.tempId());
1052 reg_file.clear(op);
1053 } else {
1054 reg_file.fill(op);
1055 }
1056 }
1057 reg.reg_b += op.bytes();
1058 }
1059 } else if (!is_phi(instr)) {
1060 /* re-enable killed operands */
1061 for (Operand& op : instr->operands) {
1062 if (op.isTemp() && op.isFirstKillBeforeDef())
1063 reg_file.fill(op);
1064 }
1065 }
1066
1067 std::vector<std::pair<Operand, Definition>> pc;
1068 if (!get_regs_for_copies(ctx, reg_file, pc, vars, lb, ub, instr, best_pos, best_pos + size - 1)) {
1069 reg_file = std::move(register_file);
1070 /* remove killed operands from reg_file once again */
1071 if (!is_phi(instr)) {
1072 for (const Operand& op : instr->operands) {
1073 if (op.isTemp() && op.isFirstKillBeforeDef())
1074 reg_file.clear(op);
1075 }
1076 }
1077 for (unsigned i = 0; i < instr->definitions.size(); i++) {
1078 Definition& def = instr->definitions[i];
1079 if (def.isTemp() && def.isFixed() && ctx.defs_done.test(i))
1080 reg_file.fill(def);
1081 }
1082 return {{}, false};
1083 }
1084
1085 parallelcopies.insert(parallelcopies.end(), pc.begin(), pc.end());
1086
1087 /* we set the definition regs == 0. the actual caller is responsible for correct setting */
1088 reg_file.clear(PhysReg{best_pos}, rc);
1089
1090 update_renames(ctx, reg_file, parallelcopies, instr, instr->opcode != aco_opcode::p_create_vector);
1091
1092 /* remove killed operands from reg_file once again */
1093 for (unsigned i = 0; !is_phi(instr) && i < instr->operands.size(); i++) {
1094 if (!instr->operands[i].isTemp() || !instr->operands[i].isFixed())
1095 continue;
1096 assert(!instr->operands[i].isUndefined());
1097 if (instr->operands[i].isFirstKillBeforeDef())
1098 reg_file.clear(instr->operands[i]);
1099 }
1100 for (unsigned i = 0; i < instr->definitions.size(); i++) {
1101 Definition def = instr->definitions[i];
1102 if (def.isTemp() && def.isFixed() && ctx.defs_done.test(i))
1103 reg_file.fill(def);
1104 }
1105
1106 adjust_max_used_regs(ctx, rc, best_pos);
1107 return {PhysReg{best_pos}, true};
1108 }
1109
1110 bool get_reg_specified(ra_ctx& ctx,
1111 RegisterFile& reg_file,
1112 RegClass rc,
1113 std::vector<std::pair<Operand, Definition>>& parallelcopies,
1114 aco_ptr<Instruction>& instr,
1115 PhysReg reg)
1116 {
1117 std::pair<unsigned, unsigned> sdw_def_info;
1118 if (rc.is_subdword())
1119 sdw_def_info = get_subdword_definition_info(ctx.program, instr, rc);
1120
1121 if (rc.is_subdword() && reg.byte() % sdw_def_info.first)
1122 return false;
1123 if (!rc.is_subdword() && reg.byte())
1124 return false;
1125
1126 uint32_t size = rc.size();
1127 uint32_t stride = 1;
1128 uint32_t lb, ub;
1129
1130 if (rc.type() == RegType::vgpr) {
1131 lb = 256;
1132 ub = 256 + ctx.program->max_reg_demand.vgpr;
1133 } else {
1134 if (size == 2)
1135 stride = 2;
1136 else if (size >= 4)
1137 stride = 4;
1138 if (reg % stride != 0)
1139 return false;
1140 lb = 0;
1141 ub = ctx.program->max_reg_demand.sgpr;
1142 }
1143
1144 uint32_t reg_lo = reg.reg();
1145 uint32_t reg_hi = reg + (size - 1);
1146
1147 if (reg_lo < lb || reg_hi >= ub || reg_lo > reg_hi)
1148 return false;
1149
1150 if (rc.is_subdword()) {
1151 PhysReg test_reg;
1152 test_reg.reg_b = reg.reg_b & ~(sdw_def_info.second - 1);
1153 if (reg_file.test(test_reg, sdw_def_info.second))
1154 return false;
1155 } else {
1156 if (reg_file.test(reg, rc.bytes()))
1157 return false;
1158 }
1159
1160 adjust_max_used_regs(ctx, rc, reg_lo);
1161 return true;
1162 }
1163
1164 PhysReg get_reg(ra_ctx& ctx,
1165 RegisterFile& reg_file,
1166 Temp temp,
1167 std::vector<std::pair<Operand, Definition>>& parallelcopies,
1168 aco_ptr<Instruction>& instr,
1169 int operand_index=-1)
1170 {
1171 auto split_vec = ctx.split_vectors.find(temp.id());
1172 if (split_vec != ctx.split_vectors.end()) {
1173 unsigned offset = 0;
1174 for (Definition def : split_vec->second->definitions) {
1175 auto affinity_it = ctx.affinities.find(def.tempId());
1176 if (affinity_it != ctx.affinities.end() && ctx.assignments[affinity_it->second].assigned) {
1177 PhysReg reg = ctx.assignments[affinity_it->second].reg;
1178 reg.reg_b -= offset;
1179 if (get_reg_specified(ctx, reg_file, temp.regClass(), parallelcopies, instr, reg))
1180 return reg;
1181 }
1182 offset += def.bytes();
1183 }
1184 }
1185
1186 if (ctx.affinities.find(temp.id()) != ctx.affinities.end() &&
1187 ctx.assignments[ctx.affinities[temp.id()]].assigned) {
1188 PhysReg reg = ctx.assignments[ctx.affinities[temp.id()]].reg;
1189 if (get_reg_specified(ctx, reg_file, temp.regClass(), parallelcopies, instr, reg))
1190 return reg;
1191 }
1192
1193 if (ctx.vectors.find(temp.id()) != ctx.vectors.end()) {
1194 Instruction* vec = ctx.vectors[temp.id()];
1195 unsigned byte_offset = 0;
1196 for (const Operand& op : vec->operands) {
1197 if (op.isTemp() && op.tempId() == temp.id())
1198 break;
1199 else
1200 byte_offset += op.bytes();
1201 }
1202 unsigned k = 0;
1203 for (const Operand& op : vec->operands) {
1204 if (op.isTemp() &&
1205 op.tempId() != temp.id() &&
1206 op.getTemp().type() == temp.type() &&
1207 ctx.assignments[op.tempId()].assigned) {
1208 PhysReg reg = ctx.assignments[op.tempId()].reg;
1209 reg.reg_b += (byte_offset - k);
1210 if (get_reg_specified(ctx, reg_file, temp.regClass(), parallelcopies, instr, reg))
1211 return reg;
1212 }
1213 k += op.bytes();
1214 }
1215
1216 DefInfo info(ctx, ctx.pseudo_dummy, vec->definitions[0].regClass(), -1);
1217 std::pair<PhysReg, bool> res = get_reg_simple(ctx, reg_file, info);
1218 PhysReg reg = res.first;
1219 if (res.second) {
1220 reg.reg_b += byte_offset;
1221 /* make sure to only use byte offset if the instruction supports it */
1222 if (get_reg_specified(ctx, reg_file, temp.regClass(), parallelcopies, instr, reg))
1223 return reg;
1224 }
1225 }
1226
1227 DefInfo info(ctx, instr, temp.regClass(), operand_index);
1228
1229 /* try to find space without live-range splits */
1230 std::pair<PhysReg, bool> res = get_reg_simple(ctx, reg_file, info);
1231
1232 if (res.second)
1233 return res.first;
1234
1235 /* try to find space with live-range splits */
1236 res = get_reg_impl(ctx, reg_file, parallelcopies, info, instr);
1237
1238 if (res.second)
1239 return res.first;
1240
1241 /* try using more registers */
1242
1243 /* We should only fail here because keeping under the limit would require
1244 * too many moves. */
1245 assert(reg_file.count_zero(PhysReg{info.lb}, info.ub-info.lb) >= info.size);
1246
1247 uint16_t max_addressible_sgpr = ctx.program->sgpr_limit;
1248 uint16_t max_addressible_vgpr = ctx.program->vgpr_limit;
1249 if (info.rc.type() == RegType::vgpr && ctx.program->max_reg_demand.vgpr < max_addressible_vgpr) {
1250 update_vgpr_sgpr_demand(ctx.program, RegisterDemand(ctx.program->max_reg_demand.vgpr + 1, ctx.program->max_reg_demand.sgpr));
1251 return get_reg(ctx, reg_file, temp, parallelcopies, instr, operand_index);
1252 } else if (info.rc.type() == RegType::sgpr && ctx.program->max_reg_demand.sgpr < max_addressible_sgpr) {
1253 update_vgpr_sgpr_demand(ctx.program, RegisterDemand(ctx.program->max_reg_demand.vgpr, ctx.program->max_reg_demand.sgpr + 1));
1254 return get_reg(ctx, reg_file, temp, parallelcopies, instr, operand_index);
1255 }
1256
1257 //FIXME: if nothing helps, shift-rotate the registers to make space
1258
1259 fprintf(stderr, "ACO: failed to allocate registers during shader compilation\n");
1260 abort();
1261 }
1262
1263 PhysReg get_reg_create_vector(ra_ctx& ctx,
1264 RegisterFile& reg_file,
1265 Temp temp,
1266 std::vector<std::pair<Operand, Definition>>& parallelcopies,
1267 aco_ptr<Instruction>& instr)
1268 {
1269 RegClass rc = temp.regClass();
1270 /* create_vector instructions have different costs w.r.t. register coalescing */
1271 uint32_t size = rc.size();
1272 uint32_t bytes = rc.bytes();
1273 uint32_t stride = 1;
1274 uint32_t lb, ub;
1275 if (rc.type() == RegType::vgpr) {
1276 lb = 256;
1277 ub = 256 + ctx.program->max_reg_demand.vgpr;
1278 } else {
1279 lb = 0;
1280 ub = ctx.program->max_reg_demand.sgpr;
1281 if (size == 2)
1282 stride = 2;
1283 else if (size >= 4)
1284 stride = 4;
1285 }
1286
1287 //TODO: improve p_create_vector for sub-dword vectors
1288
1289 unsigned best_pos = -1;
1290 unsigned num_moves = 0xFF;
1291 bool best_war_hint = true;
1292
1293 /* test for each operand which definition placement causes the least shuffle instructions */
1294 for (unsigned i = 0, offset = 0; i < instr->operands.size(); offset += instr->operands[i].bytes(), i++) {
1295 // TODO: think about, if we can alias live operands on the same register
1296 if (!instr->operands[i].isTemp() || !instr->operands[i].isKillBeforeDef() || instr->operands[i].getTemp().type() != rc.type())
1297 continue;
1298
1299 if (offset > instr->operands[i].physReg().reg_b)
1300 continue;
1301
1302 unsigned reg_lo = instr->operands[i].physReg().reg_b - offset;
1303 if (reg_lo % 4)
1304 continue;
1305 reg_lo /= 4;
1306 unsigned reg_hi = reg_lo + size - 1;
1307 unsigned k = 0;
1308
1309 /* no need to check multiple times */
1310 if (reg_lo == best_pos)
1311 continue;
1312
1313 /* check borders */
1314 // TODO: this can be improved */
1315 if (reg_lo < lb || reg_hi >= ub || reg_lo % stride != 0)
1316 continue;
1317 if (reg_lo > lb && reg_file[reg_lo] != 0 && reg_file.get_id(PhysReg(reg_lo)) == reg_file.get_id(PhysReg(reg_lo).advance(-1)))
1318 continue;
1319 if (reg_hi < ub - 1 && reg_file[reg_hi] != 0 && reg_file.get_id(PhysReg(reg_hi).advance(3)) == reg_file.get_id(PhysReg(reg_hi).advance(4)))
1320 continue;
1321
1322 /* count variables to be moved and check war_hint */
1323 bool war_hint = false;
1324 bool linear_vgpr = false;
1325 for (unsigned j = reg_lo; j <= reg_hi && !linear_vgpr; j++) {
1326 if (reg_file[j] != 0) {
1327 if (reg_file[j] == 0xF0000000) {
1328 PhysReg reg;
1329 reg.reg_b = j * 4;
1330 unsigned bytes_left = bytes - (j - reg_lo) * 4;
1331 for (unsigned k = 0; k < MIN2(bytes_left, 4); k++, reg.reg_b++)
1332 k += reg_file.test(reg, 1);
1333 } else {
1334 k += 4;
1335 /* we cannot split live ranges of linear vgprs */
1336 if (ctx.assignments[reg_file[j]].rc & (1 << 6))
1337 linear_vgpr = true;
1338 }
1339 }
1340 war_hint |= ctx.war_hint[j];
1341 }
1342 if (linear_vgpr || (war_hint && !best_war_hint))
1343 continue;
1344
1345 /* count operands in wrong positions */
1346 for (unsigned j = 0, offset = 0; j < instr->operands.size(); offset += instr->operands[j].bytes(), j++) {
1347 if (j == i ||
1348 !instr->operands[j].isTemp() ||
1349 instr->operands[j].getTemp().type() != rc.type())
1350 continue;
1351 if (instr->operands[j].physReg().reg_b != reg_lo * 4 + offset)
1352 k += instr->operands[j].bytes();
1353 }
1354 bool aligned = rc == RegClass::v4 && reg_lo % 4 == 0;
1355 if (k > num_moves || (!aligned && k == num_moves))
1356 continue;
1357
1358 best_pos = reg_lo;
1359 num_moves = k;
1360 best_war_hint = war_hint;
1361 }
1362
1363 if (num_moves >= bytes)
1364 return get_reg(ctx, reg_file, temp, parallelcopies, instr);
1365
1366 /* re-enable killed operands which are in the wrong position */
1367 for (unsigned i = 0, offset = 0; i < instr->operands.size(); offset += instr->operands[i].bytes(), i++) {
1368 if (instr->operands[i].isTemp() &&
1369 instr->operands[i].isFirstKillBeforeDef() &&
1370 instr->operands[i].physReg().reg_b != best_pos * 4 + offset)
1371 reg_file.fill(instr->operands[i]);
1372 }
1373
1374 /* collect variables to be moved */
1375 std::set<std::pair<unsigned, unsigned>> vars = collect_vars(ctx, reg_file, PhysReg{best_pos}, size);
1376
1377 for (unsigned i = 0, offset = 0; i < instr->operands.size(); offset += instr->operands[i].bytes(), i++) {
1378 if (!instr->operands[i].isTemp() || !instr->operands[i].isFirstKillBeforeDef() ||
1379 instr->operands[i].getTemp().type() != rc.type())
1380 continue;
1381 bool correct_pos = instr->operands[i].physReg().reg_b == best_pos * 4 + offset;
1382 /* GFX9+: move killed operands which aren't yet at the correct position
1383 * Moving all killed operands generally leads to more register swaps.
1384 * This is only done on GFX9+ because of the cheap v_swap instruction.
1385 */
1386 if (ctx.program->chip_class >= GFX9 && !correct_pos) {
1387 vars.emplace(instr->operands[i].bytes(), instr->operands[i].tempId());
1388 reg_file.clear(instr->operands[i]);
1389 /* fill operands which are in the correct position to avoid overwriting */
1390 } else if (correct_pos) {
1391 reg_file.fill(instr->operands[i]);
1392 }
1393 }
1394 ASSERTED bool success = false;
1395 success = get_regs_for_copies(ctx, reg_file, parallelcopies, vars, lb, ub, instr, best_pos, best_pos + size - 1);
1396 assert(success);
1397
1398 update_renames(ctx, reg_file, parallelcopies, instr, false);
1399 adjust_max_used_regs(ctx, rc, best_pos);
1400
1401 /* remove killed operands from reg_file once again */
1402 for (unsigned i = 0; i < instr->operands.size(); i++) {
1403 if (!instr->operands[i].isTemp() || !instr->operands[i].isFixed())
1404 continue;
1405 assert(!instr->operands[i].isUndefined());
1406 if (instr->operands[i].isFirstKillBeforeDef())
1407 reg_file.clear(instr->operands[i]);
1408 }
1409
1410 return PhysReg{best_pos};
1411 }
1412
1413 void handle_pseudo(ra_ctx& ctx,
1414 const RegisterFile& reg_file,
1415 Instruction* instr)
1416 {
1417 if (instr->format != Format::PSEUDO)
1418 return;
1419
1420 /* all instructions which use handle_operands() need this information */
1421 switch (instr->opcode) {
1422 case aco_opcode::p_extract_vector:
1423 case aco_opcode::p_create_vector:
1424 case aco_opcode::p_split_vector:
1425 case aco_opcode::p_parallelcopy:
1426 case aco_opcode::p_wqm:
1427 break;
1428 default:
1429 return;
1430 }
1431
1432 /* if all definitions are vgpr, no need to care for SCC */
1433 bool writes_sgpr = false;
1434 for (Definition& def : instr->definitions) {
1435 if (def.getTemp().type() == RegType::sgpr) {
1436 writes_sgpr = true;
1437 break;
1438 }
1439 }
1440 /* if all operands are constant, no need to care either */
1441 bool reads_sgpr = false;
1442 bool reads_subdword = false;
1443 for (Operand& op : instr->operands) {
1444 if (op.isTemp() && op.getTemp().type() == RegType::sgpr) {
1445 reads_sgpr = true;
1446 break;
1447 }
1448 if (op.isTemp() && op.regClass().is_subdword())
1449 reads_subdword = true;
1450 }
1451 bool needs_scratch_reg = (writes_sgpr && reads_sgpr) ||
1452 (ctx.program->chip_class <= GFX7 && reads_subdword);
1453 if (!needs_scratch_reg)
1454 return;
1455
1456 Pseudo_instruction *pi = (Pseudo_instruction *)instr;
1457 if (reg_file[scc.reg()]) {
1458 pi->tmp_in_scc = true;
1459
1460 int reg = ctx.max_used_sgpr;
1461 for (; reg >= 0 && reg_file[reg]; reg--)
1462 ;
1463 if (reg < 0) {
1464 reg = ctx.max_used_sgpr + 1;
1465 for (; reg < ctx.program->max_reg_demand.sgpr && reg_file[reg]; reg++)
1466 ;
1467 if (reg == ctx.program->max_reg_demand.sgpr) {
1468 assert(reads_subdword && reg_file[m0] == 0);
1469 reg = m0;
1470 }
1471 }
1472
1473 adjust_max_used_regs(ctx, s1, reg);
1474 pi->scratch_sgpr = PhysReg{(unsigned)reg};
1475 } else {
1476 pi->tmp_in_scc = false;
1477 }
1478 }
1479
1480 bool operand_can_use_reg(chip_class chip, aco_ptr<Instruction>& instr, unsigned idx, PhysReg reg, RegClass rc)
1481 {
1482 if (instr->operands[idx].isFixed())
1483 return instr->operands[idx].physReg() == reg;
1484
1485 if (reg.byte()) {
1486 unsigned stride = get_subdword_operand_stride(chip, instr, idx, rc);
1487 if (reg.byte() % stride)
1488 return false;
1489 }
1490
1491 switch (instr->format) {
1492 case Format::SMEM:
1493 return reg != scc &&
1494 reg != exec &&
1495 (reg != m0 || idx == 1 || idx == 3) && /* offset can be m0 */
1496 (reg != vcc || (instr->definitions.empty() && idx == 2)); /* sdata can be vcc */
1497 default:
1498 // TODO: there are more instructions with restrictions on registers
1499 return true;
1500 }
1501 }
1502
1503 void get_reg_for_operand(ra_ctx& ctx, RegisterFile& register_file,
1504 std::vector<std::pair<Operand, Definition>>& parallelcopy,
1505 aco_ptr<Instruction>& instr, Operand& operand, unsigned operand_index)
1506 {
1507 /* check if the operand is fixed */
1508 PhysReg dst;
1509 if (operand.isFixed()) {
1510 assert(operand.physReg() != ctx.assignments[operand.tempId()].reg);
1511
1512 /* check if target reg is blocked, and move away the blocking var */
1513 if (register_file[operand.physReg().reg()]) {
1514 assert(register_file[operand.physReg()] != 0xF0000000);
1515 uint32_t blocking_id = register_file[operand.physReg().reg()];
1516 RegClass rc = ctx.assignments[blocking_id].rc;
1517 Operand pc_op = Operand(Temp{blocking_id, rc});
1518 pc_op.setFixed(operand.physReg());
1519
1520 /* find free reg */
1521 PhysReg reg = get_reg(ctx, register_file, pc_op.getTemp(), parallelcopy, ctx.pseudo_dummy);
1522 Definition pc_def = Definition(PhysReg{reg}, pc_op.regClass());
1523 register_file.clear(pc_op);
1524 parallelcopy.emplace_back(pc_op, pc_def);
1525 }
1526 dst = operand.physReg();
1527
1528 } else {
1529 dst = get_reg(ctx, register_file, operand.getTemp(), parallelcopy, instr, operand_index);
1530 }
1531
1532 Operand pc_op = operand;
1533 pc_op.setFixed(ctx.assignments[operand.tempId()].reg);
1534 Definition pc_def = Definition(dst, pc_op.regClass());
1535 register_file.clear(pc_op);
1536 parallelcopy.emplace_back(pc_op, pc_def);
1537 update_renames(ctx, register_file, parallelcopy, instr, true);
1538 }
1539
1540 Temp read_variable(ra_ctx& ctx, Temp val, unsigned block_idx)
1541 {
1542 std::unordered_map<unsigned, Temp>::iterator it = ctx.renames[block_idx].find(val.id());
1543 if (it == ctx.renames[block_idx].end())
1544 return val;
1545 else
1546 return it->second;
1547 }
1548
1549 Temp handle_live_in(ra_ctx& ctx, Temp val, Block* block)
1550 {
1551 std::vector<unsigned>& preds = val.is_linear() ? block->linear_preds : block->logical_preds;
1552 if (preds.size() == 0 || val.regClass() == val.regClass().as_linear())
1553 return val;
1554
1555 assert(preds.size() > 0);
1556
1557 Temp new_val;
1558 if (!ctx.sealed[block->index]) {
1559 /* consider rename from already processed predecessor */
1560 Temp tmp = read_variable(ctx, val, preds[0]);
1561
1562 /* if the block is not sealed yet, we create an incomplete phi (which might later get removed again) */
1563 new_val = Temp{ctx.program->allocateId(), val.regClass()};
1564 ctx.assignments.emplace_back();
1565 aco_opcode opcode = val.is_linear() ? aco_opcode::p_linear_phi : aco_opcode::p_phi;
1566 aco_ptr<Instruction> phi{create_instruction<Pseudo_instruction>(opcode, Format::PSEUDO, preds.size(), 1)};
1567 phi->definitions[0] = Definition(new_val);
1568 for (unsigned i = 0; i < preds.size(); i++)
1569 phi->operands[i] = Operand(val);
1570 if (tmp.regClass() == new_val.regClass())
1571 ctx.affinities[new_val.id()] = tmp.id();
1572
1573 ctx.phi_map.emplace(new_val.id(), phi_info{phi.get(), block->index});
1574 ctx.incomplete_phis[block->index].emplace_back(phi.get());
1575 block->instructions.insert(block->instructions.begin(), std::move(phi));
1576
1577 } else if (preds.size() == 1) {
1578 /* if the block has only one predecessor, just look there for the name */
1579 new_val = read_variable(ctx, val, preds[0]);
1580 } else {
1581 /* there are multiple predecessors and the block is sealed */
1582 Temp ops[preds.size()];
1583
1584 /* get the rename from each predecessor and check if they are the same */
1585 bool needs_phi = false;
1586 for (unsigned i = 0; i < preds.size(); i++) {
1587 ops[i] = read_variable(ctx, val, preds[i]);
1588 if (i == 0)
1589 new_val = ops[i];
1590 else
1591 needs_phi |= !(new_val == ops[i]);
1592 }
1593
1594 if (needs_phi) {
1595 /* the variable has been renamed differently in the predecessors: we need to insert a phi */
1596 aco_opcode opcode = val.is_linear() ? aco_opcode::p_linear_phi : aco_opcode::p_phi;
1597 aco_ptr<Instruction> phi{create_instruction<Pseudo_instruction>(opcode, Format::PSEUDO, preds.size(), 1)};
1598 new_val = Temp{ctx.program->allocateId(), val.regClass()};
1599 phi->definitions[0] = Definition(new_val);
1600 for (unsigned i = 0; i < preds.size(); i++) {
1601 phi->operands[i] = Operand(ops[i]);
1602 phi->operands[i].setFixed(ctx.assignments[ops[i].id()].reg);
1603 if (ops[i].regClass() == new_val.regClass())
1604 ctx.affinities[new_val.id()] = ops[i].id();
1605 }
1606 ctx.assignments.emplace_back();
1607 assert(ctx.assignments.size() == ctx.program->peekAllocationId());
1608 ctx.phi_map.emplace(new_val.id(), phi_info{phi.get(), block->index});
1609 block->instructions.insert(block->instructions.begin(), std::move(phi));
1610 }
1611 }
1612
1613 if (new_val != val) {
1614 ctx.renames[block->index][val.id()] = new_val;
1615 ctx.orig_names[new_val.id()] = val;
1616 }
1617 return new_val;
1618 }
1619
1620 void try_remove_trivial_phi(ra_ctx& ctx, Temp temp)
1621 {
1622 std::unordered_map<unsigned, phi_info>::iterator info = ctx.phi_map.find(temp.id());
1623
1624 if (info == ctx.phi_map.end() || !ctx.sealed[info->second.block_idx])
1625 return;
1626
1627 assert(info->second.block_idx != 0);
1628 Instruction* phi = info->second.phi;
1629 Temp same = Temp();
1630 Definition def = phi->definitions[0];
1631
1632 /* a phi node is trivial if all operands are the same as the definition of the phi */
1633 for (const Operand& op : phi->operands) {
1634 const Temp t = op.getTemp();
1635 if (t == same || t == def.getTemp()) {
1636 assert(t == same || op.physReg() == def.physReg());
1637 continue;
1638 }
1639 if (same != Temp())
1640 return;
1641
1642 same = t;
1643 }
1644 assert(same != Temp() || same == def.getTemp());
1645
1646 /* reroute all uses to same and remove phi */
1647 std::vector<Temp> phi_users;
1648 std::unordered_map<unsigned, phi_info>::iterator same_phi_info = ctx.phi_map.find(same.id());
1649 for (Instruction* instr : info->second.uses) {
1650 assert(phi != instr);
1651 /* recursively try to remove trivial phis */
1652 if (is_phi(instr)) {
1653 /* ignore if the phi was already flagged trivial */
1654 if (instr->definitions.empty())
1655 continue;
1656
1657 if (instr->definitions[0].getTemp() != temp)
1658 phi_users.emplace_back(instr->definitions[0].getTemp());
1659 }
1660 for (Operand& op : instr->operands) {
1661 if (op.isTemp() && op.tempId() == def.tempId()) {
1662 op.setTemp(same);
1663 if (same_phi_info != ctx.phi_map.end())
1664 same_phi_info->second.uses.emplace(instr);
1665 }
1666 }
1667 }
1668
1669 auto it = ctx.orig_names.find(same.id());
1670 unsigned orig_var = it != ctx.orig_names.end() ? it->second.id() : same.id();
1671 for (unsigned i = 0; i < ctx.program->blocks.size(); i++) {
1672 auto it = ctx.renames[i].find(orig_var);
1673 if (it != ctx.renames[i].end() && it->second == def.getTemp())
1674 ctx.renames[i][orig_var] = same;
1675 }
1676
1677 phi->definitions.clear(); /* this indicates that the phi can be removed */
1678 ctx.phi_map.erase(info);
1679 for (Temp t : phi_users)
1680 try_remove_trivial_phi(ctx, t);
1681
1682 return;
1683 }
1684
1685 } /* end namespace */
1686
1687
1688 void register_allocation(Program *program, std::vector<TempSet>& live_out_per_block)
1689 {
1690 ra_ctx ctx(program);
1691 std::vector<std::vector<Temp>> phi_ressources;
1692 std::unordered_map<unsigned, unsigned> temp_to_phi_ressources;
1693
1694 for (std::vector<Block>::reverse_iterator it = program->blocks.rbegin(); it != program->blocks.rend(); it++) {
1695 Block& block = *it;
1696
1697 /* first, compute the death points of all live vars within the block */
1698 TempSet& live = live_out_per_block[block.index];
1699
1700 std::vector<aco_ptr<Instruction>>::reverse_iterator rit;
1701 for (rit = block.instructions.rbegin(); rit != block.instructions.rend(); ++rit) {
1702 aco_ptr<Instruction>& instr = *rit;
1703 if (is_phi(instr)) {
1704 if (instr->definitions[0].isKill() || instr->definitions[0].isFixed()) {
1705 live.erase(instr->definitions[0].getTemp());
1706 continue;
1707 }
1708 /* collect information about affinity-related temporaries */
1709 std::vector<Temp> affinity_related;
1710 /* affinity_related[0] is the last seen affinity-related temp */
1711 affinity_related.emplace_back(instr->definitions[0].getTemp());
1712 affinity_related.emplace_back(instr->definitions[0].getTemp());
1713 for (const Operand& op : instr->operands) {
1714 if (op.isTemp() && op.regClass() == instr->definitions[0].regClass()) {
1715 affinity_related.emplace_back(op.getTemp());
1716 temp_to_phi_ressources[op.tempId()] = phi_ressources.size();
1717 }
1718 }
1719 phi_ressources.emplace_back(std::move(affinity_related));
1720 } else {
1721 /* add vector affinities */
1722 if (instr->opcode == aco_opcode::p_create_vector) {
1723 for (const Operand& op : instr->operands) {
1724 if (op.isTemp() && op.isFirstKill() && op.getTemp().type() == instr->definitions[0].getTemp().type())
1725 ctx.vectors[op.tempId()] = instr.get();
1726 }
1727 }
1728
1729 if (instr->opcode == aco_opcode::p_split_vector && instr->operands[0].isFirstKillBeforeDef())
1730 ctx.split_vectors[instr->operands[0].tempId()] = instr.get();
1731
1732 /* add operands to live variables */
1733 for (const Operand& op : instr->operands) {
1734 if (op.isTemp())
1735 live.emplace(op.getTemp());
1736 }
1737 }
1738
1739 /* erase definitions from live */
1740 for (unsigned i = 0; i < instr->definitions.size(); i++) {
1741 const Definition& def = instr->definitions[i];
1742 if (!def.isTemp())
1743 continue;
1744 live.erase(def.getTemp());
1745 /* mark last-seen phi operand */
1746 std::unordered_map<unsigned, unsigned>::iterator it = temp_to_phi_ressources.find(def.tempId());
1747 if (it != temp_to_phi_ressources.end() && def.regClass() == phi_ressources[it->second][0].regClass()) {
1748 phi_ressources[it->second][0] = def.getTemp();
1749 /* try to coalesce phi affinities with parallelcopies */
1750 Operand op = Operand();
1751 if (!def.isFixed() && instr->opcode == aco_opcode::p_parallelcopy)
1752 op = instr->operands[i];
1753 else if ((instr->opcode == aco_opcode::v_mad_f32 ||
1754 (instr->opcode == aco_opcode::v_fma_f32 && program->chip_class >= GFX10) ||
1755 instr->opcode == aco_opcode::v_mad_f16 ||
1756 instr->opcode == aco_opcode::v_mad_legacy_f16 ||
1757 (instr->opcode == aco_opcode::v_fma_f16 && program->chip_class >= GFX10)) && !instr->usesModifiers())
1758 op = instr->operands[2];
1759
1760 if (op.isTemp() && op.isFirstKillBeforeDef() && def.regClass() == op.regClass()) {
1761 phi_ressources[it->second].emplace_back(op.getTemp());
1762 temp_to_phi_ressources[op.tempId()] = it->second;
1763 }
1764 }
1765 }
1766 }
1767 }
1768 /* create affinities */
1769 for (std::vector<Temp>& vec : phi_ressources) {
1770 assert(vec.size() > 1);
1771 for (unsigned i = 1; i < vec.size(); i++)
1772 if (vec[i].id() != vec[0].id())
1773 ctx.affinities[vec[i].id()] = vec[0].id();
1774 }
1775
1776 /* state of register file after phis */
1777 std::vector<std::bitset<128>> sgpr_live_in(program->blocks.size());
1778
1779 for (Block& block : program->blocks) {
1780 TempSet& live = live_out_per_block[block.index];
1781 /* initialize register file */
1782 assert(block.index != 0 || live.empty());
1783 RegisterFile register_file;
1784 ctx.war_hint.reset();
1785
1786 for (Temp t : live) {
1787 Temp renamed = handle_live_in(ctx, t, &block);
1788 assignment& var = ctx.assignments[renamed.id()];
1789 /* due to live-range splits, the live-in might be a phi, now */
1790 if (var.assigned)
1791 register_file.fill(Definition(renamed.id(), var.reg, var.rc));
1792 }
1793
1794 std::vector<aco_ptr<Instruction>> instructions;
1795 std::vector<aco_ptr<Instruction>>::iterator it;
1796
1797 /* this is a slight adjustment from the paper as we already have phi nodes:
1798 * We consider them incomplete phis and only handle the definition. */
1799
1800 /* handle fixed phi definitions */
1801 for (it = block.instructions.begin(); it != block.instructions.end(); ++it) {
1802 aco_ptr<Instruction>& phi = *it;
1803 if (!is_phi(phi))
1804 break;
1805 Definition& definition = phi->definitions[0];
1806 if (!definition.isFixed())
1807 continue;
1808
1809 /* check if a dead exec mask phi is needed */
1810 if (definition.isKill()) {
1811 for (Operand& op : phi->operands) {
1812 assert(op.isTemp());
1813 if (!ctx.assignments[op.tempId()].assigned ||
1814 ctx.assignments[op.tempId()].reg != exec) {
1815 definition.setKill(false);
1816 break;
1817 }
1818 }
1819 }
1820
1821 if (definition.isKill())
1822 continue;
1823
1824 assert(definition.physReg() == exec);
1825 assert(!register_file.test(definition.physReg(), definition.bytes()));
1826 register_file.fill(definition);
1827 ctx.assignments[definition.tempId()] = {definition.physReg(), definition.regClass()};
1828 }
1829
1830 /* look up the affinities */
1831 for (it = block.instructions.begin(); it != block.instructions.end(); ++it) {
1832 aco_ptr<Instruction>& phi = *it;
1833 if (!is_phi(phi))
1834 break;
1835 Definition& definition = phi->definitions[0];
1836 if (definition.isKill() || definition.isFixed())
1837 continue;
1838
1839 if (ctx.affinities.find(definition.tempId()) != ctx.affinities.end() &&
1840 ctx.assignments[ctx.affinities[definition.tempId()]].assigned) {
1841 assert(ctx.assignments[ctx.affinities[definition.tempId()]].rc == definition.regClass());
1842 PhysReg reg = ctx.assignments[ctx.affinities[definition.tempId()]].reg;
1843 bool try_use_special_reg = reg == scc || reg == exec;
1844 if (try_use_special_reg) {
1845 for (const Operand& op : phi->operands) {
1846 if (!(op.isTemp() && ctx.assignments[op.tempId()].assigned &&
1847 ctx.assignments[op.tempId()].reg == reg)) {
1848 try_use_special_reg = false;
1849 break;
1850 }
1851 }
1852 if (!try_use_special_reg)
1853 continue;
1854 }
1855 /* only assign if register is still free */
1856 if (!register_file.test(reg, definition.bytes())) {
1857 definition.setFixed(reg);
1858 register_file.fill(definition);
1859 ctx.assignments[definition.tempId()] = {definition.physReg(), definition.regClass()};
1860 }
1861 }
1862 }
1863
1864 /* find registers for phis without affinity or where the register was blocked */
1865 for (it = block.instructions.begin();it != block.instructions.end(); ++it) {
1866 aco_ptr<Instruction>& phi = *it;
1867 if (!is_phi(phi))
1868 break;
1869
1870 Definition& definition = phi->definitions[0];
1871 if (definition.isKill())
1872 continue;
1873
1874 if (!definition.isFixed()) {
1875 std::vector<std::pair<Operand, Definition>> parallelcopy;
1876 /* try to find a register that is used by at least one operand */
1877 for (const Operand& op : phi->operands) {
1878 if (!(op.isTemp() && ctx.assignments[op.tempId()].assigned))
1879 continue;
1880 PhysReg reg = ctx.assignments[op.tempId()].reg;
1881 /* we tried this already on the previous loop */
1882 if (reg == scc || reg == exec)
1883 continue;
1884 if (get_reg_specified(ctx, register_file, definition.regClass(), parallelcopy, phi, reg)) {
1885 definition.setFixed(reg);
1886 break;
1887 }
1888 }
1889 if (!definition.isFixed())
1890 definition.setFixed(get_reg(ctx, register_file, definition.getTemp(), parallelcopy, phi));
1891
1892 /* process parallelcopy */
1893 for (std::pair<Operand, Definition> pc : parallelcopy) {
1894 /* see if it's a copy from a different phi */
1895 //TODO: prefer moving some previous phis over live-ins
1896 //TODO: somehow prevent phis fixed before the RA from being updated (shouldn't be a problem in practice since they can only be fixed to exec)
1897 Instruction *prev_phi = NULL;
1898 std::vector<aco_ptr<Instruction>>::iterator phi_it;
1899 for (phi_it = instructions.begin(); phi_it != instructions.end(); ++phi_it) {
1900 if ((*phi_it)->definitions[0].tempId() == pc.first.tempId())
1901 prev_phi = phi_it->get();
1902 }
1903 phi_it = it;
1904 while (!prev_phi && is_phi(*++phi_it)) {
1905 if ((*phi_it)->definitions[0].tempId() == pc.first.tempId())
1906 prev_phi = phi_it->get();
1907 }
1908 if (prev_phi) {
1909 /* if so, just update that phi's register */
1910 register_file.clear(prev_phi->definitions[0]);
1911 prev_phi->definitions[0].setFixed(pc.second.physReg());
1912 ctx.assignments[prev_phi->definitions[0].tempId()] = {pc.second.physReg(), pc.second.regClass()};
1913 register_file.fill(prev_phi->definitions[0]);
1914 continue;
1915 }
1916
1917 /* rename */
1918 std::unordered_map<unsigned, Temp>::iterator orig_it = ctx.orig_names.find(pc.first.tempId());
1919 Temp orig = pc.first.getTemp();
1920 if (orig_it != ctx.orig_names.end())
1921 orig = orig_it->second;
1922 else
1923 ctx.orig_names[pc.second.tempId()] = orig;
1924 ctx.renames[block.index][orig.id()] = pc.second.getTemp();
1925
1926 /* otherwise, this is a live-in and we need to create a new phi
1927 * to move it in this block's predecessors */
1928 aco_opcode opcode = pc.first.getTemp().is_linear() ? aco_opcode::p_linear_phi : aco_opcode::p_phi;
1929 std::vector<unsigned>& preds = pc.first.getTemp().is_linear() ? block.linear_preds : block.logical_preds;
1930 aco_ptr<Instruction> new_phi{create_instruction<Pseudo_instruction>(opcode, Format::PSEUDO, preds.size(), 1)};
1931 new_phi->definitions[0] = pc.second;
1932 for (unsigned i = 0; i < preds.size(); i++)
1933 new_phi->operands[i] = Operand(pc.first);
1934 instructions.emplace_back(std::move(new_phi));
1935 }
1936
1937 register_file.fill(definition);
1938 ctx.assignments[definition.tempId()] = {definition.physReg(), definition.regClass()};
1939 }
1940 live.emplace(definition.getTemp());
1941
1942 /* update phi affinities */
1943 for (const Operand& op : phi->operands) {
1944 if (op.isTemp() && op.regClass() == phi->definitions[0].regClass())
1945 ctx.affinities[op.tempId()] = definition.tempId();
1946 }
1947
1948 instructions.emplace_back(std::move(*it));
1949 }
1950
1951 /* fill in sgpr_live_in */
1952 for (unsigned i = 0; i <= ctx.max_used_sgpr; i++)
1953 sgpr_live_in[block.index][i] = register_file[i];
1954 sgpr_live_in[block.index][127] = register_file[scc.reg()];
1955
1956 /* Handle all other instructions of the block */
1957 for (; it != block.instructions.end(); ++it) {
1958 aco_ptr<Instruction>& instr = *it;
1959
1960 /* parallelcopies from p_phi are inserted here which means
1961 * live ranges of killed operands end here as well */
1962 if (instr->opcode == aco_opcode::p_logical_end) {
1963 /* no need to process this instruction any further */
1964 if (block.logical_succs.size() != 1) {
1965 instructions.emplace_back(std::move(instr));
1966 continue;
1967 }
1968
1969 Block& succ = program->blocks[block.logical_succs[0]];
1970 unsigned idx = 0;
1971 for (; idx < succ.logical_preds.size(); idx++) {
1972 if (succ.logical_preds[idx] == block.index)
1973 break;
1974 }
1975 for (aco_ptr<Instruction>& phi : succ.instructions) {
1976 if (phi->opcode == aco_opcode::p_phi) {
1977 if (phi->operands[idx].isTemp() &&
1978 phi->operands[idx].getTemp().type() == RegType::sgpr &&
1979 phi->operands[idx].isFirstKillBeforeDef()) {
1980 Temp phi_op = read_variable(ctx, phi->operands[idx].getTemp(), block.index);
1981 PhysReg reg = ctx.assignments[phi_op.id()].reg;
1982 assert(register_file[reg] == phi_op.id());
1983 register_file[reg] = 0;
1984 }
1985 } else if (phi->opcode != aco_opcode::p_linear_phi) {
1986 break;
1987 }
1988 }
1989 instructions.emplace_back(std::move(instr));
1990 continue;
1991 }
1992
1993 std::vector<std::pair<Operand, Definition>> parallelcopy;
1994
1995 assert(!is_phi(instr));
1996
1997 /* handle operands */
1998 for (unsigned i = 0; i < instr->operands.size(); ++i) {
1999 auto& operand = instr->operands[i];
2000 if (!operand.isTemp())
2001 continue;
2002
2003 /* rename operands */
2004 operand.setTemp(read_variable(ctx, operand.getTemp(), block.index));
2005 assert(ctx.assignments[operand.tempId()].assigned);
2006
2007 PhysReg reg = ctx.assignments[operand.tempId()].reg;
2008 if (operand_can_use_reg(program->chip_class, instr, i, reg, operand.regClass()))
2009 operand.setFixed(reg);
2010 else
2011 get_reg_for_operand(ctx, register_file, parallelcopy, instr, operand, i);
2012
2013 if (instr->format == Format::EXP ||
2014 (instr->isVMEM() && i == 3 && ctx.program->chip_class == GFX6) ||
2015 (instr->format == Format::DS && static_cast<DS_instruction*>(instr.get())->gds)) {
2016 for (unsigned j = 0; j < operand.size(); j++)
2017 ctx.war_hint.set(operand.physReg().reg() + j);
2018 }
2019
2020 std::unordered_map<unsigned, phi_info>::iterator phi = ctx.phi_map.find(operand.getTemp().id());
2021 if (phi != ctx.phi_map.end())
2022 phi->second.uses.emplace(instr.get());
2023 }
2024
2025 /* remove dead vars from register file */
2026 for (const Operand& op : instr->operands) {
2027 if (op.isTemp() && op.isFirstKillBeforeDef())
2028 register_file.clear(op);
2029 }
2030
2031 /* try to optimize v_mad_f32 -> v_mac_f32 */
2032 if ((instr->opcode == aco_opcode::v_mad_f32 ||
2033 (instr->opcode == aco_opcode::v_fma_f32 && program->chip_class >= GFX10) ||
2034 instr->opcode == aco_opcode::v_mad_f16 ||
2035 instr->opcode == aco_opcode::v_mad_legacy_f16 ||
2036 (instr->opcode == aco_opcode::v_fma_f16 && program->chip_class >= GFX10)) &&
2037 instr->operands[2].isTemp() &&
2038 instr->operands[2].isKillBeforeDef() &&
2039 instr->operands[2].getTemp().type() == RegType::vgpr &&
2040 instr->operands[1].isTemp() &&
2041 instr->operands[1].getTemp().type() == RegType::vgpr &&
2042 !instr->usesModifiers() &&
2043 instr->operands[0].physReg().byte() == 0 &&
2044 instr->operands[1].physReg().byte() == 0 &&
2045 instr->operands[2].physReg().byte() == 0) {
2046 unsigned def_id = instr->definitions[0].tempId();
2047 auto it = ctx.affinities.find(def_id);
2048 if (it == ctx.affinities.end() || !ctx.assignments[it->second].assigned ||
2049 instr->operands[2].physReg() == ctx.assignments[it->second].reg ||
2050 register_file.test(ctx.assignments[it->second].reg, instr->operands[2].bytes())) {
2051 instr->format = Format::VOP2;
2052 switch (instr->opcode) {
2053 case aco_opcode::v_mad_f32:
2054 instr->opcode = aco_opcode::v_mac_f32;
2055 break;
2056 case aco_opcode::v_fma_f32:
2057 instr->opcode = aco_opcode::v_fmac_f32;
2058 break;
2059 case aco_opcode::v_mad_f16:
2060 case aco_opcode::v_mad_legacy_f16:
2061 instr->opcode = aco_opcode::v_mac_f16;
2062 break;
2063 case aco_opcode::v_fma_f16:
2064 instr->opcode = aco_opcode::v_fmac_f16;
2065 break;
2066 default:
2067 break;
2068 }
2069 }
2070 }
2071
2072 /* handle definitions which must have the same register as an operand */
2073 if (instr->opcode == aco_opcode::v_interp_p2_f32 ||
2074 instr->opcode == aco_opcode::v_mac_f32 ||
2075 instr->opcode == aco_opcode::v_fmac_f32 ||
2076 instr->opcode == aco_opcode::v_mac_f16 ||
2077 instr->opcode == aco_opcode::v_fmac_f16 ||
2078 instr->opcode == aco_opcode::v_writelane_b32 ||
2079 instr->opcode == aco_opcode::v_writelane_b32_e64) {
2080 instr->definitions[0].setFixed(instr->operands[2].physReg());
2081 } else if (instr->opcode == aco_opcode::s_addk_i32 ||
2082 instr->opcode == aco_opcode::s_mulk_i32) {
2083 instr->definitions[0].setFixed(instr->operands[0].physReg());
2084 } else if (instr->format == Format::MUBUF &&
2085 instr->definitions.size() == 1 &&
2086 instr->operands.size() == 4) {
2087 instr->definitions[0].setFixed(instr->operands[3].physReg());
2088 } else if (instr->format == Format::MIMG &&
2089 instr->definitions.size() == 1 &&
2090 instr->operands[1].regClass().type() == RegType::vgpr) {
2091 instr->definitions[0].setFixed(instr->operands[1].physReg());
2092 }
2093
2094 ctx.defs_done.reset();
2095
2096 /* handle fixed definitions first */
2097 for (unsigned i = 0; i < instr->definitions.size(); ++i) {
2098 auto& definition = instr->definitions[i];
2099 if (!definition.isFixed())
2100 continue;
2101
2102 adjust_max_used_regs(ctx, definition.regClass(), definition.physReg());
2103 /* check if the target register is blocked */
2104 if (register_file.test(definition.physReg(), definition.bytes())) {
2105 /* create parallelcopy pair to move blocking vars */
2106 std::set<std::pair<unsigned, unsigned>> vars = collect_vars(ctx, register_file, definition.physReg(), definition.size());
2107
2108 /* re-enable the killed operands, so that we don't move the blocking vars there */
2109 for (const Operand& op : instr->operands) {
2110 if (op.isTemp() && op.isFirstKillBeforeDef())
2111 register_file.fill(op);
2112 }
2113
2114 ASSERTED bool success = false;
2115 DefInfo info(ctx, instr, definition.regClass(), -1);
2116 success = get_regs_for_copies(ctx, register_file, parallelcopy,
2117 vars, info.lb, info.ub, instr,
2118 definition.physReg(),
2119 definition.physReg() + definition.size() - 1);
2120 assert(success);
2121
2122 update_renames(ctx, register_file, parallelcopy, instr, false);
2123
2124 /* once again, disable killed operands */
2125 for (const Operand& op : instr->operands) {
2126 if (op.isTemp() && op.isFirstKillBeforeDef())
2127 register_file.clear(op);
2128 }
2129 for (unsigned k = 0; k < i; k++) {
2130 if (instr->definitions[k].isTemp() && ctx.defs_done.test(k) && !instr->definitions[k].isKill())
2131 register_file.fill(instr->definitions[k]);
2132 }
2133 }
2134 ctx.defs_done.set(i);
2135
2136 if (!definition.isTemp())
2137 continue;
2138
2139 /* set live if it has a kill point */
2140 if (!definition.isKill())
2141 live.emplace(definition.getTemp());
2142
2143 ctx.assignments[definition.tempId()] = {definition.physReg(), definition.regClass()};
2144 register_file.fill(definition);
2145 }
2146
2147 /* handle all other definitions */
2148 for (unsigned i = 0; i < instr->definitions.size(); ++i) {
2149 Definition *definition = &instr->definitions[i];
2150
2151 if (definition->isFixed() || !definition->isTemp())
2152 continue;
2153
2154 /* find free reg */
2155 if (definition->hasHint() && register_file[definition->physReg().reg()] == 0)
2156 definition->setFixed(definition->physReg());
2157 else if (instr->opcode == aco_opcode::p_split_vector) {
2158 PhysReg reg = instr->operands[0].physReg();
2159 for (unsigned j = 0; j < i; j++)
2160 reg.reg_b += instr->definitions[j].bytes();
2161 if (get_reg_specified(ctx, register_file, definition->regClass(), parallelcopy, instr, reg))
2162 definition->setFixed(reg);
2163 } else if (instr->opcode == aco_opcode::p_wqm || instr->opcode == aco_opcode::p_parallelcopy) {
2164 PhysReg reg = instr->operands[i].physReg();
2165 if (instr->operands[i].isTemp() &&
2166 instr->operands[i].getTemp().type() == definition->getTemp().type() &&
2167 !register_file.test(reg, definition->bytes()))
2168 definition->setFixed(reg);
2169 } else if (instr->opcode == aco_opcode::p_extract_vector) {
2170 PhysReg reg;
2171 if (instr->operands[0].isKillBeforeDef() &&
2172 instr->operands[0].getTemp().type() == definition->getTemp().type()) {
2173 reg = instr->operands[0].physReg();
2174 reg.reg_b += definition->bytes() * instr->operands[1].constantValue();
2175 assert(!register_file.test(reg, definition->bytes()));
2176 definition->setFixed(reg);
2177 }
2178 } else if (instr->opcode == aco_opcode::p_create_vector) {
2179 PhysReg reg = get_reg_create_vector(ctx, register_file, definition->getTemp(),
2180 parallelcopy, instr);
2181 definition->setFixed(reg);
2182 }
2183
2184 if (!definition->isFixed()) {
2185 Temp tmp = definition->getTemp();
2186 if (definition->regClass().is_subdword() && definition->bytes() < 4) {
2187 PhysReg reg = get_reg(ctx, register_file, tmp, parallelcopy, instr);
2188 bool partial = !(tmp.bytes() <= 4 && reg.byte() == 0 && !register_file.test(reg, 4));
2189 add_subdword_definition(program, instr, i, reg, partial);
2190 definition = &instr->definitions[i]; /* add_subdword_definition can invalidate the reference */
2191 } else {
2192 definition->setFixed(get_reg(ctx, register_file, tmp, parallelcopy, instr));
2193 }
2194 }
2195
2196 assert(definition->isFixed() && ((definition->getTemp().type() == RegType::vgpr && definition->physReg() >= 256) ||
2197 (definition->getTemp().type() != RegType::vgpr && definition->physReg() < 256)));
2198 ctx.defs_done.set(i);
2199
2200 /* set live if it has a kill point */
2201 if (!definition->isKill())
2202 live.emplace(definition->getTemp());
2203
2204 ctx.assignments[definition->tempId()] = {definition->physReg(), definition->regClass()};
2205 register_file.fill(*definition);
2206 }
2207
2208 handle_pseudo(ctx, register_file, instr.get());
2209
2210 /* kill definitions and late-kill operands and ensure that sub-dword operands can actually be read */
2211 for (const Definition& def : instr->definitions) {
2212 if (def.isTemp() && def.isKill())
2213 register_file.clear(def);
2214 }
2215 for (unsigned i = 0; i < instr->operands.size(); i++) {
2216 const Operand& op = instr->operands[i];
2217 if (op.isTemp() && op.isFirstKill() && op.isLateKill())
2218 register_file.clear(op);
2219 if (op.isTemp() && op.physReg().byte() != 0)
2220 add_subdword_operand(program->chip_class, instr, i, op.physReg().byte(), op.regClass());
2221 }
2222
2223 /* emit parallelcopy */
2224 if (!parallelcopy.empty()) {
2225 aco_ptr<Pseudo_instruction> pc;
2226 pc.reset(create_instruction<Pseudo_instruction>(aco_opcode::p_parallelcopy, Format::PSEUDO, parallelcopy.size(), parallelcopy.size()));
2227 bool temp_in_scc = register_file[scc.reg()];
2228 bool sgpr_operands_alias_defs = false;
2229 uint64_t sgpr_operands[4] = {0, 0, 0, 0};
2230 for (unsigned i = 0; i < parallelcopy.size(); i++) {
2231 if (temp_in_scc && parallelcopy[i].first.isTemp() && parallelcopy[i].first.getTemp().type() == RegType::sgpr) {
2232 if (!sgpr_operands_alias_defs) {
2233 unsigned reg = parallelcopy[i].first.physReg().reg();
2234 unsigned size = parallelcopy[i].first.getTemp().size();
2235 sgpr_operands[reg / 64u] |= ((1u << size) - 1) << (reg % 64u);
2236
2237 reg = parallelcopy[i].second.physReg().reg();
2238 size = parallelcopy[i].second.getTemp().size();
2239 if (sgpr_operands[reg / 64u] & ((1u << size) - 1) << (reg % 64u))
2240 sgpr_operands_alias_defs = true;
2241 }
2242 }
2243
2244 pc->operands[i] = parallelcopy[i].first;
2245 pc->definitions[i] = parallelcopy[i].second;
2246 assert(pc->operands[i].size() == pc->definitions[i].size());
2247
2248 /* it might happen that the operand is already renamed. we have to restore the original name. */
2249 std::unordered_map<unsigned, Temp>::iterator it = ctx.orig_names.find(pc->operands[i].tempId());
2250 Temp orig = it != ctx.orig_names.end() ? it->second : pc->operands[i].getTemp();
2251 ctx.orig_names[pc->definitions[i].tempId()] = orig;
2252 ctx.renames[block.index][orig.id()] = pc->definitions[i].getTemp();
2253
2254 std::unordered_map<unsigned, phi_info>::iterator phi = ctx.phi_map.find(pc->operands[i].tempId());
2255 if (phi != ctx.phi_map.end())
2256 phi->second.uses.emplace(pc.get());
2257 }
2258
2259 if (temp_in_scc && sgpr_operands_alias_defs) {
2260 /* disable definitions and re-enable operands */
2261 for (const Definition& def : instr->definitions) {
2262 if (def.isTemp() && !def.isKill())
2263 register_file.clear(def);
2264 }
2265 for (const Operand& op : instr->operands) {
2266 if (op.isTemp() && op.isFirstKill())
2267 register_file.block(op.physReg(), op.regClass());
2268 }
2269
2270 handle_pseudo(ctx, register_file, pc.get());
2271
2272 /* re-enable live vars */
2273 for (const Operand& op : instr->operands) {
2274 if (op.isTemp() && op.isFirstKill())
2275 register_file.clear(op);
2276 }
2277 for (const Definition& def : instr->definitions) {
2278 if (def.isTemp() && !def.isKill())
2279 register_file.fill(def);
2280 }
2281 } else {
2282 pc->tmp_in_scc = false;
2283 }
2284
2285 instructions.emplace_back(std::move(pc));
2286 }
2287
2288 /* some instructions need VOP3 encoding if operand/definition is not assigned to VCC */
2289 bool instr_needs_vop3 = !instr->isVOP3() &&
2290 ((instr->format == Format::VOPC && !(instr->definitions[0].physReg() == vcc)) ||
2291 (instr->opcode == aco_opcode::v_cndmask_b32 && !(instr->operands[2].physReg() == vcc)) ||
2292 ((instr->opcode == aco_opcode::v_add_co_u32 ||
2293 instr->opcode == aco_opcode::v_addc_co_u32 ||
2294 instr->opcode == aco_opcode::v_sub_co_u32 ||
2295 instr->opcode == aco_opcode::v_subb_co_u32 ||
2296 instr->opcode == aco_opcode::v_subrev_co_u32 ||
2297 instr->opcode == aco_opcode::v_subbrev_co_u32) &&
2298 !(instr->definitions[1].physReg() == vcc)) ||
2299 ((instr->opcode == aco_opcode::v_addc_co_u32 ||
2300 instr->opcode == aco_opcode::v_subb_co_u32 ||
2301 instr->opcode == aco_opcode::v_subbrev_co_u32) &&
2302 !(instr->operands[2].physReg() == vcc)));
2303 if (instr_needs_vop3) {
2304
2305 /* if the first operand is a literal, we have to move it to a reg */
2306 if (instr->operands.size() && instr->operands[0].isLiteral() && program->chip_class < GFX10) {
2307 bool can_sgpr = true;
2308 /* check, if we have to move to vgpr */
2309 for (const Operand& op : instr->operands) {
2310 if (op.isTemp() && op.getTemp().type() == RegType::sgpr) {
2311 can_sgpr = false;
2312 break;
2313 }
2314 }
2315 /* disable definitions and re-enable operands */
2316 for (const Definition& def : instr->definitions)
2317 register_file.clear(def);
2318 for (const Operand& op : instr->operands) {
2319 if (op.isTemp() && op.isFirstKill())
2320 register_file.block(op.physReg(), op.regClass());
2321 }
2322 Temp tmp = {program->allocateId(), can_sgpr ? s1 : v1};
2323 ctx.assignments.emplace_back();
2324 PhysReg reg = get_reg(ctx, register_file, tmp, parallelcopy, instr);
2325
2326 aco_ptr<Instruction> mov;
2327 if (can_sgpr)
2328 mov.reset(create_instruction<SOP1_instruction>(aco_opcode::s_mov_b32, Format::SOP1, 1, 1));
2329 else
2330 mov.reset(create_instruction<VOP1_instruction>(aco_opcode::v_mov_b32, Format::VOP1, 1, 1));
2331 mov->operands[0] = instr->operands[0];
2332 mov->definitions[0] = Definition(tmp);
2333 mov->definitions[0].setFixed(reg);
2334
2335 instr->operands[0] = Operand(tmp);
2336 instr->operands[0].setFixed(reg);
2337 instructions.emplace_back(std::move(mov));
2338 /* re-enable live vars */
2339 for (const Operand& op : instr->operands) {
2340 if (op.isTemp() && op.isFirstKill())
2341 register_file.clear(op);
2342 }
2343 for (const Definition& def : instr->definitions) {
2344 if (def.isTemp() && !def.isKill())
2345 register_file.fill(def);
2346 }
2347 }
2348
2349 /* change the instruction to VOP3 to enable an arbitrary register pair as dst */
2350 aco_ptr<Instruction> tmp = std::move(instr);
2351 Format format = asVOP3(tmp->format);
2352 instr.reset(create_instruction<VOP3A_instruction>(tmp->opcode, format, tmp->operands.size(), tmp->definitions.size()));
2353 for (unsigned i = 0; i < instr->operands.size(); i++) {
2354 Operand& operand = tmp->operands[i];
2355 instr->operands[i] = operand;
2356 /* keep phi_map up to date */
2357 if (operand.isTemp()) {
2358 std::unordered_map<unsigned, phi_info>::iterator phi = ctx.phi_map.find(operand.tempId());
2359 if (phi != ctx.phi_map.end()) {
2360 phi->second.uses.erase(tmp.get());
2361 phi->second.uses.emplace(instr.get());
2362 }
2363 }
2364 }
2365 std::copy(tmp->definitions.begin(), tmp->definitions.end(), instr->definitions.begin());
2366 }
2367
2368 instructions.emplace_back(std::move(*it));
2369
2370 } /* end for Instr */
2371
2372 block.instructions = std::move(instructions);
2373
2374 ctx.filled[block.index] = true;
2375 for (unsigned succ_idx : block.linear_succs) {
2376 Block& succ = program->blocks[succ_idx];
2377 /* seal block if all predecessors are filled */
2378 bool all_filled = true;
2379 for (unsigned pred_idx : succ.linear_preds) {
2380 if (!ctx.filled[pred_idx]) {
2381 all_filled = false;
2382 break;
2383 }
2384 }
2385 if (all_filled) {
2386 ctx.sealed[succ_idx] = true;
2387
2388 /* finish incomplete phis and check if they became trivial */
2389 for (Instruction* phi : ctx.incomplete_phis[succ_idx]) {
2390 std::vector<unsigned> preds = phi->definitions[0].getTemp().is_linear() ? succ.linear_preds : succ.logical_preds;
2391 for (unsigned i = 0; i < phi->operands.size(); i++) {
2392 phi->operands[i].setTemp(read_variable(ctx, phi->operands[i].getTemp(), preds[i]));
2393 phi->operands[i].setFixed(ctx.assignments[phi->operands[i].tempId()].reg);
2394 }
2395 try_remove_trivial_phi(ctx, phi->definitions[0].getTemp());
2396 }
2397 /* complete the original phi nodes, but no need to check triviality */
2398 for (aco_ptr<Instruction>& instr : succ.instructions) {
2399 if (!is_phi(instr))
2400 break;
2401 std::vector<unsigned> preds = instr->opcode == aco_opcode::p_phi ? succ.logical_preds : succ.linear_preds;
2402
2403 for (unsigned i = 0; i < instr->operands.size(); i++) {
2404 auto& operand = instr->operands[i];
2405 if (!operand.isTemp())
2406 continue;
2407 operand.setTemp(read_variable(ctx, operand.getTemp(), preds[i]));
2408 operand.setFixed(ctx.assignments[operand.tempId()].reg);
2409 std::unordered_map<unsigned, phi_info>::iterator phi = ctx.phi_map.find(operand.getTemp().id());
2410 if (phi != ctx.phi_map.end())
2411 phi->second.uses.emplace(instr.get());
2412 }
2413 }
2414 }
2415 }
2416 } /* end for BB */
2417
2418 /* remove trivial phis */
2419 for (Block& block : program->blocks) {
2420 auto end = std::find_if(block.instructions.begin(), block.instructions.end(),
2421 [](aco_ptr<Instruction>& instr) { return !is_phi(instr);});
2422 auto middle = std::remove_if(block.instructions.begin(), end,
2423 [](const aco_ptr<Instruction>& instr) { return instr->definitions.empty();});
2424 block.instructions.erase(middle, end);
2425 }
2426
2427 /* find scc spill registers which may be needed for parallelcopies created by phis */
2428 for (Block& block : program->blocks) {
2429 if (block.linear_preds.size() <= 1)
2430 continue;
2431
2432 std::bitset<128> regs = sgpr_live_in[block.index];
2433 if (!regs[127])
2434 continue;
2435
2436 /* choose a register */
2437 int16_t reg = 0;
2438 for (; reg < ctx.program->max_reg_demand.sgpr && regs[reg]; reg++)
2439 ;
2440 assert(reg < ctx.program->max_reg_demand.sgpr);
2441 adjust_max_used_regs(ctx, s1, reg);
2442
2443 /* update predecessors */
2444 for (unsigned& pred_index : block.linear_preds) {
2445 Block& pred = program->blocks[pred_index];
2446 pred.scc_live_out = true;
2447 pred.scratch_sgpr = PhysReg{(uint16_t)reg};
2448 }
2449 }
2450
2451 /* num_gpr = rnd_up(max_used_gpr + 1) */
2452 program->config->num_vgprs = align(ctx.max_used_vgpr + 1, 4);
2453 if (program->family == CHIP_TONGA || program->family == CHIP_ICELAND) /* workaround hardware bug */
2454 program->config->num_sgprs = get_sgpr_alloc(program, program->sgpr_limit);
2455 else
2456 program->config->num_sgprs = align(ctx.max_used_sgpr + 1 + get_extra_sgprs(program), 8);
2457 }
2458
2459 }