Debian Codegraph @

src/asahi/compiler/agx_spill.c

raw
1 /*
2 * Copyright 2023-2024 Alyssa Rosenzweig
3 * Copyright 2023-2024 Valve Corporation
4 * Copyright 2022 Collabora Ltd.
5 * SPDX-License-Identifier: MIT
6 */
7
8 #include "util/bitset.h"
9 #include "util/hash_table.h"
10 #include "util/ralloc.h"
11 #include "util/sparse_bitset.h"
12 #include "util/u_dynarray.h"
13 #include "util/u_qsort.h"
14 #include "agx_builder.h"
15 #include "agx_compiler.h"
16 #include "agx_opcodes.h"
17
18 /*
19 * An implementation of "Register Spilling and Live-Range Splitting for SSA-Form
20 * Programs" by Braun and Hack.
21 */
22
23 /*
24 * Next-use distances are logically in ℤ ∪ {∞}. Modeled as saturating uint32 and
25 * referred to as dist_t.
26 *
27 * next_uses represents a next-use map. This is a sparse data structure mapping
28 * variable names to next-use dist_t's. Variables with no later use (infinite
29 * next-use distance) are not stored explicitly, making the time/space
30 * requirements O(live variables). This is important for performance and memory
31 * usage on big shaders with many blocks.
32 *
33 * For now, next_uses is backed by a Mesa hash table, but it could be optimized
34 * to something more specialized in the future.
35 */
36 #define DIST_INFINITY (UINT32_MAX)
37 typedef uint32_t dist_t;
38
39 static dist_t
40 dist_sum(dist_t A, dist_t B)
41 {
42 return (A + B < A) ? DIST_INFINITY : (A + B);
43 }
44
45 struct next_uses {
46 struct hash_table_u64 *ht;
47 };
48
49 static void
50 init_next_uses(struct next_uses *nu, void *memctx)
51 {
52 nu->ht = _mesa_hash_table_u64_create(memctx);
53 }
54
55 static void
56 destroy_next_uses(struct next_uses *nu)
57 {
58 _mesa_hash_table_u64_destroy(nu->ht);
59 }
60
61 static void
62 clear_next_uses(struct next_uses *nu)
63 {
64 _mesa_hash_table_u64_clear(nu->ht);
65 }
66
67 static void
68 copy_next_uses(struct next_uses *nu, const struct next_uses *from)
69 {
70 clear_next_uses(nu);
71
72 hash_table_u64_foreach(from->ht, use) {
73 _mesa_hash_table_u64_insert(nu->ht, use.key, use.data);
74 }
75 }
76
77 static void
78 set_next_use(struct next_uses *nu, unsigned node, dist_t dist)
79 {
80 if (dist == DIST_INFINITY) {
81 _mesa_hash_table_u64_remove(nu->ht, node);
82 } else {
83 uintptr_t as_ptr = (uintptr_t)(dist + 1);
84 assert(as_ptr != 0 && "non-NULL");
85
86 _mesa_hash_table_u64_insert(nu->ht, node, (void *)as_ptr);
87 }
88 }
89
90 static dist_t
91 search_next_uses(const struct next_uses *nu, unsigned node)
92 {
93 void *ent = _mesa_hash_table_u64_search(nu->ht, node);
94 if (!ent)
95 return DIST_INFINITY;
96
97 uintptr_t raw = (uintptr_t)ent;
98 return raw - 1;
99 }
100
101 #define foreach_next_use(nu, node, dist) \
102 hash_table_u64_foreach((nu)->ht, use_) \
103 for (uint32_t _terminator = 1, node = use_.key, \
104 UNUSED dist = ((uintptr_t)use_.data) - 1; \
105 _terminator != 0; _terminator = 0)
106
107 /*
108 * Calculate the minimum of two next-use sets. Values absent from one of the
109 * underlying sets are infinity so do not contribute to the minimum, instead
110 * acting like a set union.
111 */
112 static bool
113 minimum_next_uses(struct next_uses *nu, const struct next_uses *from)
114 {
115 bool progress = false;
116
117 foreach_next_use(from, node, from_dist) {
118 dist_t nu_dist = search_next_uses(nu, node);
119
120 if (from_dist < nu_dist) {
121 set_next_use(nu, node, from_dist);
122 progress = true;
123 }
124 }
125
126 return progress;
127 }
128
129 static uint32_t
130 instr_cycles(const agx_instr *I)
131 {
132 return 1;
133 }
134
135 struct spill_block {
136 /* Set of values available in the register file at the end */
137 unsigned W_exit[AGX_NUM_REGS];
138 unsigned nW_exit;
139
140 unsigned W_entry[AGX_NUM_REGS];
141 unsigned nW_entry;
142
143 /* Set of live-out spilled values at the end of the block */
144 unsigned *S_exit;
145 unsigned nS_exit;
146
147 unsigned *S_entry;
148 unsigned nS_entry;
149
150 /* Estimate */
151 uint32_t cycles;
152
153 /* Next-use maps at the start/end of the block */
154 struct next_uses next_use_in;
155 struct next_uses next_use_out;
156 };
157
158 struct spill_ctx {
159 void *memctx;
160 agx_context *shader;
161 agx_block *block;
162
163 /* Set of values currently available in the register file */
164 BITSET_WORD *W;
165
166 /* |W| = Current register pressure */
167 unsigned nW;
168
169 /* Local IPs of next-use */
170 dist_t *next_uses;
171
172 /* Current local IP relative to the start of the block */
173 uint32_t ip;
174
175 /* Set of live values that have been spilled. Contrary to the paper, this
176 * is not a subset of W: the definition in the paper is bogus.
177 */
178 BITSET_WORD *S;
179
180 /* Widths of vectors */
181 uint8_t *channels;
182 enum agx_size *size;
183
184 /* Mapping of rematerializable values to their definitions, or NULL for nodes
185 * that are not materializable.
186 */
187 agx_instr **remat;
188
189 /* Maximum register pressure allowed */
190 unsigned k;
191
192 /* Number of variables */
193 unsigned n;
194
195 /* Information on blocks indexed in source order */
196 struct spill_block *blocks;
197
198 /* Base memory index reserved for spilled indices */
199 unsigned spill_base;
200
201 /* If true, we cannot use scratch and must only rematerialize. */
202 bool remat_only;
203 };
204
205 static inline struct spill_block *
206 spill_block(struct spill_ctx *ctx, agx_block *block)
207 {
208 return &ctx->blocks[block->index];
209 }
210
211 /* Calculate the register demand of a node. This is rounded up to a power-of-two
212 * to match the equivalent calculations in RA.
213 */
214 static unsigned
215 node_size(struct spill_ctx *ctx, unsigned node)
216 {
217 return util_next_power_of_two(ctx->channels[node]) *
218 agx_size_align_16(ctx->size[node]);
219 }
220
221 /*
222 * Map a control flow edge to a block. Assumes no critical edges.
223 */
224 static agx_block *
225 agx_edge_to_block(agx_block *pred, agx_block *succ)
226 {
227 /* End of predecessor is unique if there's a single successor */
228 if (agx_num_successors(pred) == 1)
229 return pred;
230
231 /* The predecessor has multiple successors, meaning this is not the only
232 * edge leaving the predecessor. Therefore, it is the only edge entering
233 * the successor (otherwise the edge would be critical), so the start of
234 * the successor is unique.
235 */
236 assert(agx_num_predecessors(succ) == 1 && "critical edge detected");
237 return succ;
238 }
239
240 /*
241 * Get a cursor to insert along a control flow edge: either at the start of the
242 * successor or the end of the predecessor. This relies on the control flow
243 * graph having no critical edges.
244 */
245 static agx_cursor
246 agx_along_edge(agx_block *pred, agx_block *succ)
247 {
248 agx_block *to = agx_edge_to_block(pred, succ);
249
250 if (to == pred)
251 return agx_after_block_logical(pred);
252 else
253 return agx_before_block(succ);
254 }
255
256 static inline agx_index
257 agx_index_as_mem(agx_index idx, unsigned mem_base)
258 {
259 assert(idx.type == AGX_INDEX_NORMAL);
260 assert(!idx.memory);
261 idx.memory = true;
262 idx.value = mem_base + idx.value;
263 return idx;
264 }
265
266 static unsigned
267 chase_mem_index(agx_index ref, unsigned mem_base)
268 {
269 assert(ref.type == AGX_INDEX_NORMAL);
270 return ref.memory ? (ref.value - mem_base) : ref.value;
271 }
272
273 static agx_index
274 reconstruct_index(struct spill_ctx *ctx, unsigned node)
275 {
276 return agx_get_vec_index(node, ctx->size[node], ctx->channels[node]);
277 }
278
279 static bool
280 can_remat(agx_instr *I)
281 {
282 switch (I->op) {
283 case AGX_OPCODE_MOV_IMM:
284 case AGX_OPCODE_GET_SR:
285 return true;
286 default:
287 return false;
288 }
289 }
290
291 static agx_instr *
292 remat_to(agx_builder *b, agx_index dst, struct spill_ctx *ctx, unsigned node)
293 {
294 agx_instr *I = ctx->remat[node];
295 assert(can_remat(I));
296
297 switch (I->op) {
298 case AGX_OPCODE_MOV_IMM:
299 return agx_mov_imm_to(b, dst, I->imm);
300 case AGX_OPCODE_GET_SR:
301 return agx_get_sr_to(b, dst, I->sr);
302 default:
303 UNREACHABLE("invalid remat");
304 }
305 }
306
307 static void
308 insert_spill(agx_builder *b, struct spill_ctx *ctx, unsigned node)
309 {
310 if (!ctx->remat[node]) {
311 assert(!ctx->remat_only && "must have remat something");
312
313 agx_index idx = reconstruct_index(ctx, node);
314 agx_mov_to(b, agx_index_as_mem(idx, ctx->spill_base), idx);
315
316 /* We only need the extra registers reserved if we actually spilled
317 * instead of just remat.
318 */
319 b->shader->has_spill_pcopy_reserved = true;
320 }
321 }
322
323 static void
324 insert_reload(struct spill_ctx *ctx, agx_block *block, agx_cursor cursor,
325 unsigned node)
326 {
327 agx_builder b = agx_init_builder(ctx->shader, cursor);
328 agx_index idx = reconstruct_index(ctx, node);
329
330 /* Reloading breaks SSA, but agx_repair_ssa will repair */
331 if (ctx->remat[node]) {
332 remat_to(&b, idx, ctx, node);
333 } else {
334 agx_mov_to(&b, idx, agx_index_as_mem(idx, ctx->spill_base));
335 }
336 }
337
338 /* Insert into the register file */
339 static void
340 insert_W(struct spill_ctx *ctx, unsigned v)
341 {
342 assert(v < ctx->n);
343 assert(!BITSET_TEST(ctx->W, v));
344
345 BITSET_SET(ctx->W, v);
346 ctx->nW += node_size(ctx, v);
347 }
348
349 /* Remove from the register file */
350 static void
351 remove_W(struct spill_ctx *ctx, unsigned v)
352 {
353 assert(v < ctx->n);
354 assert(BITSET_TEST(ctx->W, v));
355
356 BITSET_CLEAR(ctx->W, v);
357 ctx->nW -= node_size(ctx, v);
358 }
359
360 static void
361 remove_W_if_present(struct spill_ctx *ctx, unsigned v)
362 {
363 assert(v < ctx->n);
364
365 if (BITSET_TEST(ctx->W, v))
366 remove_W(ctx, v);
367 }
368
369 struct candidate {
370 unsigned node;
371 dist_t dist;
372 };
373
374 static int
375 cmp_dist(const void *left_, const void *right_, void *ctx_)
376 {
377 struct spill_ctx *ctx = ctx_;
378 const struct candidate *left = left_;
379 const struct candidate *right = right_;
380
381 /* We assume that rematerializing - even before every instruction - is
382 * cheaper than spilling. As long as one of the nodes is rematerializable
383 * (with distance > 0), we choose it over spilling. Within a class of nodes
384 * (rematerializable or not), compare by next-use-distance.
385 */
386 bool remat_left = ctx->remat[left->node] != NULL && left->dist > 0;
387 bool remat_right = ctx->remat[right->node] != NULL && right->dist > 0;
388
389 if (remat_left != remat_right)
390 return remat_left ? 1 : -1;
391 else
392 return (left->dist > right->dist) - (left->dist < right->dist);
393 }
394
395 /*
396 * Limit the register file W to maximum size m by evicting registers.
397 */
398 static ATTRIBUTE_NOINLINE void
399 limit(struct spill_ctx *ctx, agx_instr *I, unsigned m)
400 {
401 /* Nothing to do if we're already below the limit */
402 if (ctx->nW <= m)
403 return;
404
405 /* Gather candidates for eviction. Note that next_uses gives IPs whereas
406 * cmp_dist expects relative distances. This requires us to subtract ctx->ip
407 * to ensure that cmp_dist works properly. Even though logically it shouldn't
408 * affect the sorted order, practically this matters for correctness with
409 * rematerialization. See the dist=0 test in cmp_dist.
410 */
411 struct candidate *candidates = alloca(ctx->nW * sizeof(struct candidate));
412 unsigned j = 0;
413
414 int i;
415 BITSET_FOREACH_SET(i, ctx->W, ctx->n) {
416 assert(j < ctx->nW);
417
418 candidates[j++] = (struct candidate){
419 .node = i,
420 .dist = ctx->next_uses[i] - ctx->ip,
421 };
422 }
423
424 /* Sort by next-use distance */
425 util_qsort_r(candidates, j, sizeof(struct candidate), cmp_dist, ctx);
426
427 /* Evict what doesn't fit */
428 unsigned new_weight = 0;
429
430 for (i = 0; i < j; ++i) {
431 unsigned v = candidates[i].node;
432 unsigned comps = node_size(ctx, v);
433
434 if ((new_weight + comps) <= m) {
435 new_weight += comps;
436 } else {
437 /* Insert a spill if we haven't spilled before and there is
438 * another use
439 */
440 if (!BITSET_TEST(ctx->S, v) && candidates[i].dist < DIST_INFINITY) {
441 agx_builder b = agx_init_builder(ctx->shader, agx_before_instr(I));
442 insert_spill(&b, ctx, v);
443 BITSET_SET(ctx->S, v);
444 }
445
446 remove_W(ctx, v);
447
448 /* We keep going in case we can pack in a scalar */
449 }
450 }
451 }
452
453 /*
454 * Insert coupling code on block boundaries. This must ensure:
455 *
456 * - anything live-in we expect to have spilled is spilled
457 * - anything live-in we expect to have filled is filled
458 * - phi sources are spilled if the destination is spilled
459 * - phi sources are filled if the destination is not spilled
460 *
461 * The latter two requirements ensure correct pressure calculations for phis.
462 */
463 static ATTRIBUTE_NOINLINE void
464 insert_coupling_code(struct spill_ctx *ctx, agx_block *pred, agx_block *succ)
465 {
466 struct spill_block *sp = spill_block(ctx, pred);
467 struct spill_block *ss = spill_block(ctx, succ);
468
469 agx_foreach_phi_in_block(succ, I) {
470 if (!I->dest[0].memory)
471 continue;
472
473 agx_builder b =
474 agx_init_builder(ctx->shader, agx_before_function(ctx->shader));
475
476 unsigned s = agx_predecessor_index(succ, pred);
477
478 /* Copy immediate/uniform phi sources to memory variables at the start of
479 * the program, where pressure is zero and hence the copy is legal.
480 */
481 if (I->src[s].type != AGX_INDEX_NORMAL) {
482 assert(I->src[s].type == AGX_INDEX_IMMEDIATE ||
483 I->src[s].type == AGX_INDEX_UNIFORM);
484
485 agx_index mem = agx_temp_like(ctx->shader, I->dest[0]);
486 assert(mem.memory);
487
488 agx_index gpr = agx_temp_like(ctx->shader, I->dest[0]);
489 gpr.memory = false;
490
491 if (I->src[s].type == AGX_INDEX_IMMEDIATE)
492 agx_mov_imm_to(&b, gpr, I->src[s].value);
493 else
494 agx_mov_to(&b, gpr, I->src[s]);
495
496 agx_mov_to(&b, mem, gpr);
497 I->src[s] = mem;
498 continue;
499 }
500
501 bool spilled = false;
502 for (unsigned i = 0; i < sp->nS_exit; ++i) {
503 if (sp->S_exit[i] == I->src[s].value) {
504 spilled = true;
505 break;
506 }
507 }
508
509 if (!spilled) {
510 /* Spill the phi source. TODO: avoid redundant spills here */
511 agx_builder b =
512 agx_init_builder(ctx->shader, agx_after_block_logical(pred));
513
514 insert_spill(&b, ctx, I->src[s].value);
515 }
516
517 if (ctx->remat[I->src[s].value]) {
518 unsigned node = I->src[s].value;
519 agx_index idx = reconstruct_index(ctx, node);
520 agx_index tmp = agx_temp_like(ctx->shader, idx);
521
522 remat_to(&b, tmp, ctx, node);
523 agx_mov_to(&b, agx_index_as_mem(idx, ctx->spill_base), tmp);
524 }
525
526 /* Use the spilled version */
527 I->src[s] = agx_index_as_mem(I->src[s], ctx->spill_base);
528 }
529
530 /* Anything assumed to be spilled at the start of succ must be spilled along
531 * all edges.
532 */
533 for (unsigned i = 0; i < ss->nS_entry; ++i) {
534 unsigned v = ss->S_entry[i];
535
536 bool spilled = false;
537 for (unsigned j = 0; j < sp->nS_exit; ++j) {
538 if (sp->S_exit[j] == v) {
539 spilled = true;
540 break;
541 }
542 }
543
544 /* We handle spilling phi destinations separately */
545 agx_foreach_phi_in_block(succ, phi) {
546 if (chase_mem_index(phi->dest[0], ctx->spill_base) == v) {
547 spilled = true;
548 break;
549 }
550 }
551
552 if (spilled)
553 continue;
554
555 agx_builder b = agx_init_builder(ctx->shader, agx_along_edge(pred, succ));
556 insert_spill(&b, ctx, v);
557 }
558
559 /* Variables in W at the start of succ must be defined along the edge. */
560 for (unsigned i = 0; i < ss->nW_entry; ++i) {
561 unsigned node = ss->W_entry[i];
562 bool defined = false;
563
564 /* Variables live at the end of the predecessor are live along the edge */
565 for (unsigned j = 0; j < sp->nW_exit; ++j) {
566 if (sp->W_exit[j] == node) {
567 defined = true;
568 break;
569 }
570 }
571
572 /* Phis are defined along the edge */
573 agx_foreach_phi_in_block(succ, phi) {
574 if (phi->dest[0].value == node) {
575 defined = true;
576 break;
577 }
578 }
579
580 if (defined)
581 continue;
582
583 /* Otherwise, inserting a reload defines the variable along the edge */
584 agx_block *reload_block = agx_edge_to_block(pred, succ);
585 insert_reload(ctx, reload_block, agx_along_edge(pred, succ), node);
586 }
587
588 agx_foreach_phi_in_block(succ, I) {
589 if (I->dest[0].memory)
590 continue;
591
592 unsigned s = agx_predecessor_index(succ, pred);
593
594 /* Treat immediate/uniform phi sources as registers for pressure
595 * accounting and phi lowering purposes. Parallel copy lowering can handle
596 * a copy from a immediate/uniform to a register, but not from an
597 * immediate/uniform directly to memory.
598 */
599 if (I->src[s].type != AGX_INDEX_NORMAL) {
600 assert(I->src[s].type == AGX_INDEX_IMMEDIATE ||
601 I->src[s].type == AGX_INDEX_UNIFORM);
602
603 continue;
604 }
605
606 bool live = false;
607 for (unsigned i = 0; i < sp->nW_exit; ++i) {
608 if (sp->W_exit[i] == I->src[s].value) {
609 live = true;
610 break;
611 }
612 }
613
614 /* Fill the phi source in the predecessor */
615 if (!live) {
616 agx_block *reload_block = agx_edge_to_block(pred, succ);
617 insert_reload(ctx, reload_block, agx_along_edge(pred, succ),
618 I->src[s].value);
619 }
620
621 /* Leave as-is for the GPR version */
622 assert(!I->src[s].memory);
623 }
624 }
625
626 /*
627 * Produce an array of next-use IPs relative to the start of the block. This is
628 * an array of dist_t scalars, representing the next-use IP of each SSA dest
629 * (right-to-left) and SSA source (left-to-right) of each instruction in the
630 * block (bottom-to-top). Its size equals the # of SSA sources in the block.
631 */
632 static ATTRIBUTE_NOINLINE void
633 calculate_local_next_use(struct spill_ctx *ctx, struct util_dynarray *out)
634 {
635 struct spill_block *sb = spill_block(ctx, ctx->block);
636 unsigned ip = sb->cycles;
637
638 *out = UTIL_DYNARRAY_INIT;
639
640 struct next_uses nu;
641 init_next_uses(&nu, NULL);
642
643 foreach_next_use(&sb->next_use_out, i, dist) {
644 set_next_use(&nu, i, dist_sum(ip, dist));
645 }
646
647 agx_foreach_instr_in_block_rev(ctx->block, I) {
648 ip -= instr_cycles(I);
649
650 if (I->op != AGX_OPCODE_PHI) {
651 agx_foreach_ssa_src(I, s) {
652 unsigned v = I->src[s].value;
653
654 util_dynarray_append(out, search_next_uses(&nu, v));
655 set_next_use(&nu, v, ip);
656 }
657
658 agx_foreach_ssa_dest_rev(I, d) {
659 unsigned v = I->dest[d].value;
660
661 util_dynarray_append(out, search_next_uses(&nu, v));
662 }
663 }
664 }
665
666 assert(ip == 0 && "cycle counting is consistent");
667 destroy_next_uses(&nu);
668 }
669
670 static agx_cursor
671 agx_before_instr_logical(agx_block *block, agx_instr *I)
672 {
673 if (I->op == AGX_OPCODE_EXPORT) {
674 agx_instr *first = agx_first_instr(block);
675
676 while (I != first && I->op == AGX_OPCODE_EXPORT) {
677 I = agx_prev_op(I);
678 }
679
680 if (I == first && first->op == AGX_OPCODE_EXPORT) {
681 return agx_before_block(block);
682 } else {
683 return agx_after_instr(I);
684 }
685 } else {
686 return agx_before_instr(I);
687 }
688 }
689
690 /*
691 * Insert spills/fills for a single basic block, following Belady's algorithm.
692 * Corresponds to minAlgorithm from the paper.
693 */
694 static ATTRIBUTE_NOINLINE void
695 min_algorithm(struct spill_ctx *ctx)
696 {
697 struct spill_block *sblock = spill_block(ctx, ctx->block);
698 struct util_dynarray local_next_ip;
699 calculate_local_next_use(ctx, &local_next_ip);
700
701 /* next_uses gives the distance from the start of the block, so prepopulate
702 * with next_use_in.
703 */
704 foreach_next_use(&sblock->next_use_in, key, dist) {
705 assert(key < ctx->n);
706 ctx->next_uses[key] = dist;
707 }
708
709 dist_t *next_ips = util_dynarray_element(&local_next_ip, dist_t, 0);
710 unsigned next_use_cursor =
711 util_dynarray_num_elements(&local_next_ip, dist_t);
712
713 /* Iterate each instruction in forward order */
714 agx_foreach_instr_in_block(ctx->block, I) {
715 assert(ctx->nW <= ctx->k && "invariant");
716
717 /* Debug to check against our RA demand calculations */
718 if (0) {
719 printf("%u: ", ctx->nW);
720 agx_print_instr(I, stdout);
721 }
722
723 /* Phis are special since they happen along the edge. When we initialized
724 * W and S, we implicitly chose which phis are spilled. So, here we just
725 * need to rewrite the phis to write into memory.
726 *
727 * Phi sources are handled later.
728 */
729 if (I->op == AGX_OPCODE_PHI) {
730 if (!BITSET_TEST(ctx->W, I->dest[0].value)) {
731 I->dest[0] = agx_index_as_mem(I->dest[0], ctx->spill_base);
732 }
733
734 ctx->ip += instr_cycles(I);
735 continue;
736 }
737
738 /* Any source that is not in W needs to be reloaded. Gather the set R of
739 * such values.
740 */
741 unsigned R[AGX_MAX_NORMAL_SOURCES];
742 unsigned nR = 0;
743
744 agx_foreach_ssa_src(I, s) {
745 unsigned node = I->src[s].value;
746 if (BITSET_TEST(ctx->W, node))
747 continue;
748
749 /* Mark this variable as needing a reload. */
750 assert(node < ctx->n);
751 assert(BITSET_TEST(ctx->S, node) && "must have been spilled");
752 assert(nR < ARRAY_SIZE(R) && "maximum source count");
753 R[nR++] = node;
754
755 /* The inserted reload will add the value to the register file. */
756 insert_W(ctx, node);
757 }
758
759 /* Limit W to make space for the sources we just added */
760 limit(ctx, I, ctx->k);
761
762 agx_foreach_ssa_dest(I, d) {
763 assert(next_use_cursor >= 1);
764 unsigned next_ip = next_ips[--next_use_cursor];
765
766 if (next_ip == DIST_INFINITY)
767 remove_W_if_present(ctx, I->dest[d].value);
768 else
769 ctx->next_uses[I->dest[d].value] = next_ip;
770 }
771
772 /* Count how many registers we need for destinations. Because of
773 * SSA form, destinations are unique.
774 */
775 unsigned dest_size = 0;
776 agx_foreach_ssa_dest(I, d) {
777 dest_size += node_size(ctx, I->dest[d].value);
778 }
779
780 /* Limit W to make space for the destinations. */
781 limit(ctx, I, ctx->k - dest_size);
782
783 /* Destinations are now in the register file */
784 agx_foreach_ssa_dest(I, d) {
785 insert_W(ctx, I->dest[d].value);
786 }
787
788 /* Update next-use distances for this instruction. Unlike the paper, we
789 * prune dead values from W as we go. This doesn't affect correctness, but
790 * it speeds up limit() on average.
791 *
792 * This happens after the above limit() calls to model sources as
793 * late-kill. This is conservative and could be improved, but it matches
794 * how we currently estimate register demand.
795 */
796 agx_foreach_ssa_src_rev(I, s) {
797 assert(next_use_cursor >= 1);
798
799 unsigned next_ip = next_ips[--next_use_cursor];
800 assert((next_ip == DIST_INFINITY) == I->src[s].kill);
801
802 if (I->src[s].kill) {
803 remove_W_if_present(ctx, I->src[s].value);
804 } else {
805 ctx->next_uses[I->src[s].value] = next_ip;
806 }
807 }
808
809 /* Add reloads for the sources in front of the instruction. We need to be
810 * careful around exports, hoisting the reloads to before all exports.
811 *
812 * This is legal since all exports happen in parallel and all registers
813 * are dead after the exports. The register file
814 * must be big enough for everything exported, so it must be big enough
815 * for all the reloaded values right before the parallel exports.
816 */
817 for (unsigned i = 0; i < nR; ++i) {
818 insert_reload(ctx, ctx->block, agx_before_instr_logical(ctx->block, I),
819 R[i]);
820 }
821
822 ctx->ip += instr_cycles(I);
823 }
824
825 assert(next_use_cursor == 0 && "exactly sized");
826
827 int i;
828 BITSET_FOREACH_SET(i, ctx->W, ctx->n)
829 sblock->W_exit[sblock->nW_exit++] = i;
830
831 unsigned nS = __bitset_count(ctx->S, BITSET_WORDS(ctx->n));
832 sblock->S_exit = ralloc_array(ctx->memctx, unsigned, nS);
833
834 BITSET_FOREACH_SET(i, ctx->S, ctx->n)
835 sblock->S_exit[sblock->nS_exit++] = i;
836
837 assert(nS == sblock->nS_exit);
838 util_dynarray_fini(&local_next_ip);
839 }
840
841 /*
842 * TODO: Implement section 4.2 of the paper.
843 *
844 * For now, we implement the simpler heuristic in Hack's thesis: sort
845 * the live-in set (+ destinations of phis) by next-use distance.
846 */
847 static ATTRIBUTE_NOINLINE void
848 compute_w_entry_loop_header(struct spill_ctx *ctx)
849 {
850 agx_block *block = ctx->block;
851 struct spill_block *sb = spill_block(ctx, block);
852
853 unsigned nP = u_sparse_bitset_count(&block->live_in);
854 struct candidate *candidates = calloc(nP, sizeof(struct candidate));
855 unsigned j = 0;
856
857 foreach_next_use(&sb->next_use_in, i, dist) {
858 assert(j < nP);
859 candidates[j++] = (struct candidate){.node = i, .dist = dist};
860 }
861
862 assert(j == nP);
863
864 /* Sort by next-use distance */
865 util_qsort_r(candidates, j, sizeof(struct candidate), cmp_dist, ctx);
866
867 /* Take as much as we can */
868 for (unsigned i = 0; i < j; ++i) {
869 unsigned node = candidates[i].node;
870 unsigned comps = node_size(ctx, node);
871
872 if ((ctx->nW + comps) <= ctx->k) {
873 insert_W(ctx, node);
874 sb->W_entry[sb->nW_entry++] = node;
875 }
876 }
877
878 assert(ctx->nW <= ctx->k);
879 free(candidates);
880 }
881
882 /*
883 * Compute W_entry for a block. Section 4.2 in the paper.
884 */
885 static ATTRIBUTE_NOINLINE void
886 compute_w_entry(struct spill_ctx *ctx)
887 {
888 agx_block *block = ctx->block;
889 struct spill_block *sb = spill_block(ctx, block);
890
891 /* Nothing to do for start blocks */
892 if (agx_num_predecessors(block) == 0)
893 return;
894
895 /* Loop headers have a different heuristic */
896 if (block->loop_header) {
897 compute_w_entry_loop_header(ctx);
898 return;
899 }
900
901 /* Usual blocks follow */
902 unsigned *freq = calloc(ctx->n, sizeof(unsigned));
903
904 /* Record what's written at the end of each predecessor */
905 agx_foreach_predecessor(ctx->block, P) {
906 struct spill_block *sp = spill_block(ctx, *P);
907
908 for (unsigned i = 0; i < sp->nW_exit; ++i) {
909 unsigned v = sp->W_exit[i];
910 freq[v]++;
911 }
912 }
913
914 struct candidate *candidates = calloc(ctx->n, sizeof(struct candidate));
915 unsigned j = 0;
916
917 /* Variables that are in all predecessors are assumed in W_entry. Phis and
918 * variables in some predecessors are scored by next-use.
919 */
920 foreach_next_use(&sb->next_use_in, i, dist) {
921 if (freq[i] == agx_num_predecessors(ctx->block)) {
922 insert_W(ctx, i);
923 } else if (freq[i]) {
924 candidates[j++] = (struct candidate){.node = i, .dist = dist};
925 }
926 }
927
928 agx_foreach_phi_in_block(ctx->block, I) {
929 bool all_found = true;
930
931 agx_foreach_predecessor(ctx->block, pred) {
932 struct spill_block *sp = spill_block(ctx, *pred);
933 bool found = false;
934
935 agx_index src = I->src[agx_predecessor_index(ctx->block, *pred)];
936 if (src.type != AGX_INDEX_NORMAL)
937 continue;
938
939 unsigned v = src.value;
940 for (unsigned i = 0; i < sp->nW_exit; ++i) {
941 if (sp->W_exit[i] == v) {
942 found = true;
943 break;
944 }
945 }
946
947 all_found &= found;
948 }
949
950 /* Heuristic: if any phi source is spilled, spill the whole phi. This is
951 * suboptimal, but it massively reduces pointless fill/spill chains with
952 * massive phi webs.
953 */
954 if (!all_found)
955 continue;
956
957 candidates[j++] = (struct candidate){
958 .node = I->dest[0].value,
959 .dist = search_next_uses(&sb->next_use_in, I->dest[0].value),
960 };
961 }
962
963 /* Sort by next-use distance */
964 util_qsort_r(candidates, j, sizeof(struct candidate), cmp_dist, ctx);
965
966 /* Take as much as we can */
967 for (unsigned i = 0; i < j; ++i) {
968 unsigned node = candidates[i].node;
969 unsigned comps = node_size(ctx, node);
970
971 if ((ctx->nW + comps) <= ctx->k) {
972 insert_W(ctx, node);
973 sb->W_entry[sb->nW_entry++] = node;
974 }
975 }
976
977 assert(ctx->nW <= ctx->k && "invariant");
978
979 free(freq);
980 free(candidates);
981 }
982
983 /*
984 * We initialize S with the union of S at the exit of (forward edge)
985 * predecessors and the complement of W, intersected with the live-in set. The
986 * former propagates S forward. The latter ensures we spill along the edge when
987 * a live value is not selected for the entry W.
988 */
989 static ATTRIBUTE_NOINLINE void
990 compute_s_entry(struct spill_ctx *ctx)
991 {
992 unsigned v;
993
994 agx_foreach_predecessor(ctx->block, pred) {
995 struct spill_block *sp = spill_block(ctx, *pred);
996
997 for (unsigned i = 0; i < sp->nS_exit; ++i) {
998 v = sp->S_exit[i];
999
1000 if (u_sparse_bitset_test(&ctx->block->live_in, v))
1001 BITSET_SET(ctx->S, v);
1002 }
1003 }
1004
1005 U_SPARSE_BITSET_FOREACH_SET(&ctx->block->live_in, v) {
1006 if (!BITSET_TEST(ctx->W, v))
1007 BITSET_SET(ctx->S, v);
1008 }
1009
1010 /* Copy ctx->S to S_entry for later look-ups with coupling code */
1011 struct spill_block *sb = spill_block(ctx, ctx->block);
1012 unsigned nS = __bitset_count(ctx->S, BITSET_WORDS(ctx->n));
1013 sb->S_entry = ralloc_array(ctx->memctx, unsigned, nS);
1014
1015 int i;
1016 BITSET_FOREACH_SET(i, ctx->S, ctx->n)
1017 sb->S_entry[sb->nS_entry++] = i;
1018
1019 assert(sb->nS_entry == nS);
1020 }
1021
1022 static ATTRIBUTE_NOINLINE void
1023 global_next_use_distances(agx_context *ctx, void *memctx,
1024 struct spill_block *blocks)
1025 {
1026 u_worklist worklist;
1027 u_worklist_init(&worklist, ctx->num_blocks, NULL);
1028
1029 agx_foreach_block(ctx, block) {
1030 struct spill_block *sb = &blocks[block->index];
1031
1032 init_next_uses(&sb->next_use_in, memctx);
1033 init_next_uses(&sb->next_use_out, memctx);
1034
1035 agx_foreach_instr_in_block(block, I) {
1036 sb->cycles += instr_cycles(I);
1037 }
1038
1039 agx_worklist_push_head(&worklist, block);
1040 }
1041
1042 /* Definitions that have been seen */
1043 BITSET_WORD *defined =
1044 malloc(BITSET_WORDS(ctx->alloc) * sizeof(BITSET_WORD));
1045
1046 struct next_uses dists;
1047 init_next_uses(&dists, NULL);
1048
1049 /* Iterate the work list in reverse order since liveness is backwards */
1050 while (!u_worklist_is_empty(&worklist)) {
1051 agx_block *blk = agx_worklist_pop_head(&worklist);
1052 struct spill_block *sb = &blocks[blk->index];
1053
1054 /* Definitions that have been seen */
1055 memset(defined, 0, BITSET_WORDS(ctx->alloc) * sizeof(BITSET_WORD));
1056
1057 /* Initialize all distances to infinity */
1058 clear_next_uses(&dists);
1059
1060 uint32_t cycle = 0;
1061
1062 /* Calculate dists. Phis are handled separately. */
1063 agx_foreach_instr_in_block(blk, I) {
1064 if (I->op == AGX_OPCODE_PHI) {
1065 cycle++;
1066 continue;
1067 }
1068
1069 /* Record first use before def. Phi sources are handled
1070 * above, because they logically happen in the
1071 * predecessor.
1072 */
1073 agx_foreach_ssa_src(I, s) {
1074 if (BITSET_TEST(defined, I->src[s].value))
1075 continue;
1076 if (search_next_uses(&dists, I->src[s].value) < DIST_INFINITY)
1077 continue;
1078
1079 assert(I->src[s].value < ctx->alloc);
1080 set_next_use(&dists, I->src[s].value, cycle);
1081 }
1082
1083 /* Record defs */
1084 agx_foreach_ssa_dest(I, d) {
1085 assert(I->dest[d].value < ctx->alloc);
1086 BITSET_SET(defined, I->dest[d].value);
1087 }
1088
1089 cycle += instr_cycles(I);
1090 }
1091
1092 /* Apply transfer function to get our entry state. */
1093 foreach_next_use(&sb->next_use_out, node, dist) {
1094 set_next_use(&sb->next_use_in, node, dist_sum(dist, sb->cycles));
1095 }
1096
1097 foreach_next_use(&dists, node, dist) {
1098 set_next_use(&sb->next_use_in, node, dist);
1099 }
1100
1101 int i;
1102 BITSET_FOREACH_SET(i, defined, ctx->alloc) {
1103 set_next_use(&sb->next_use_in, i, DIST_INFINITY);
1104 }
1105
1106 /* Propagate the live in of the successor (blk) to the live out of
1107 * predecessors.
1108 *
1109 * Phi nodes are logically on the control flow edge and act in parallel.
1110 * To handle when propagating, we kill writes from phis and make live the
1111 * corresponding sources.
1112 */
1113 agx_foreach_predecessor(blk, pred) {
1114 struct spill_block *sp = &blocks[(*pred)->index];
1115 copy_next_uses(&dists, &sb->next_use_in);
1116
1117 /* Kill write */
1118 agx_foreach_phi_in_block(blk, I) {
1119 assert(I->dest[0].type == AGX_INDEX_NORMAL);
1120 set_next_use(&dists, I->dest[0].value, DIST_INFINITY);
1121 }
1122
1123 /* Make live the corresponding source */
1124 agx_foreach_phi_in_block(blk, I) {
1125 agx_index operand = I->src[agx_predecessor_index(blk, *pred)];
1126 if (operand.type == AGX_INDEX_NORMAL)
1127 set_next_use(&dists, operand.value, 0);
1128 }
1129
1130 /* Join by taking minimum */
1131 if (minimum_next_uses(&sp->next_use_out, &dists))
1132 agx_worklist_push_tail(&worklist, *pred);
1133 }
1134 }
1135
1136 free(defined);
1137 u_worklist_fini(&worklist);
1138 destroy_next_uses(&dists);
1139 }
1140
1141 static ATTRIBUTE_NOINLINE void
1142 validate_next_use_info(UNUSED agx_context *ctx,
1143 UNUSED struct spill_block *blocks)
1144 {
1145 #ifndef NDEBUG
1146 agx_foreach_block(ctx, blk) {
1147 struct spill_block *sb = &blocks[blk->index];
1148
1149 /* Invariant: next-use distance is finite iff the node is live */
1150 U_SPARSE_BITSET_FOREACH_SET(&blk->live_in, i)
1151 assert(search_next_uses(&sb->next_use_in, i) < DIST_INFINITY);
1152
1153 U_SPARSE_BITSET_FOREACH_SET(&blk->live_out, i)
1154 assert(search_next_uses(&sb->next_use_out, i) < DIST_INFINITY);
1155
1156 foreach_next_use(&sb->next_use_in, i, _)
1157 assert(u_sparse_bitset_test(&blk->live_in, i));
1158
1159 foreach_next_use(&sb->next_use_out, i, _)
1160 assert(u_sparse_bitset_test(&blk->live_out, i));
1161 }
1162 #endif
1163 }
1164
1165 void
1166 agx_spill(agx_context *ctx, unsigned k, bool remat_only)
1167 {
1168 void *memctx = ralloc_context(NULL);
1169
1170 /* We need extra registers for memory-memory swaps */
1171 k -= remat_only ? 2 : 8;
1172
1173 uint8_t *channels = rzalloc_array(memctx, uint8_t, ctx->alloc);
1174 dist_t *next_uses = rzalloc_array(memctx, dist_t, ctx->alloc);
1175 enum agx_size *sizes = rzalloc_array(memctx, enum agx_size, ctx->alloc);
1176 agx_instr **remat = rzalloc_array(memctx, agx_instr *, ctx->alloc);
1177
1178 agx_foreach_instr_global(ctx, I) {
1179 if (can_remat(I))
1180 remat[I->dest[0].value] = I;
1181
1182 /* Measure vectors */
1183 agx_foreach_ssa_dest(I, d) {
1184 assert(sizes[I->dest[d].value] == 0 && "broken SSA");
1185 assert(channels[I->dest[d].value] == 0 && "broken SSA");
1186
1187 sizes[I->dest[d].value] = I->dest[d].size;
1188 channels[I->dest[d].value] = agx_channels(I->dest[d]);
1189 }
1190 }
1191
1192 struct spill_block *blocks =
1193 rzalloc_array(memctx, struct spill_block, ctx->num_blocks);
1194
1195 /* Step 1. Compute global next-use distances */
1196 global_next_use_distances(ctx, memctx, blocks);
1197 validate_next_use_info(ctx, blocks);
1198
1199 /* Reserve a memory variable for every regular variable */
1200 unsigned n = ctx->alloc;
1201 ctx->alloc *= 2;
1202
1203 BITSET_WORD *W = ralloc_array(memctx, BITSET_WORD, BITSET_WORDS(n));
1204 BITSET_WORD *S = ralloc_array(memctx, BITSET_WORD, BITSET_WORDS(n));
1205
1206 agx_foreach_block(ctx, block) {
1207 memset(W, 0, BITSET_BYTES(n));
1208 memset(S, 0, BITSET_BYTES(n));
1209
1210 struct spill_ctx sctx = {
1211 .memctx = memctx,
1212 .shader = ctx,
1213 .n = n,
1214 .channels = channels,
1215 .size = sizes,
1216 .remat = remat,
1217 .next_uses = next_uses,
1218 .block = block,
1219 .blocks = blocks,
1220 .k = k,
1221 .W = W,
1222 .S = S,
1223 .spill_base = n,
1224 .remat_only = remat_only,
1225 };
1226
1227 compute_w_entry(&sctx);
1228 compute_s_entry(&sctx);
1229 min_algorithm(&sctx);
1230 }
1231
1232 /* Now that all blocks are processed separately, stitch it together */
1233 agx_foreach_block(ctx, block) {
1234 struct spill_ctx sctx = {
1235 .memctx = memctx,
1236 .shader = ctx,
1237 .n = n,
1238 .channels = channels,
1239 .size = sizes,
1240 .remat = remat,
1241 .block = block,
1242 .blocks = blocks,
1243 .k = k,
1244 .W = W,
1245 .S = S,
1246 .spill_base = n,
1247 };
1248
1249 agx_foreach_predecessor(block, pred) {
1250 /* After spilling phi sources, insert coupling code */
1251 insert_coupling_code(&sctx, *pred, block);
1252 }
1253 }
1254
1255 ralloc_free(memctx);
1256
1257 /* Spilling breaks SSA, so we need to repair before validating */
1258 agx_repair_ssa(ctx);
1259 agx_validate(ctx, "Spilling");
1260
1261 /* Remat can introduce dead code */
1262 agx_dce(ctx, false);
1263 }