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