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