Debian Codegraph @

src/panfrost/compiler/bifrost/bi_spill_ssa.c

raw
1 /*
2 * Copyright 2023-2024 Alyssa Rosenzweig
3 * Copyright 2023-2024 Valve Corporation
4 * Copyright 2022,2025 Collabora Ltd.
5 * Copyright 2025 Arm Ltd.
6 * SPDX-License-Identifier: MIT
7 */
8
9 #include "util/bitset.h"
10 #include "util/hash_table.h"
11 #include "util/ralloc.h"
12 #include "util/u_dynarray.h"
13 #include "util/u_qsort.h"
14 #include "bi_builder.h"
15 #include "bifrost_nir.h"
16 #include "compiler.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 return ((uintptr_t)ent) - 1;
98 }
99
100 #define foreach_next_use(nu, node, dist) \
101 hash_table_u64_foreach((nu)->ht, use_) \
102 for (uint32_t _terminator = 1, node = use_.key, \
103 UNUSED dist = ((uintptr_t)use_.data) - 1; \
104 _terminator != 0; _terminator = 0)
105
106 /*
107 * Calculate the minimum of two next-use sets. Values absent from one of the
108 * underlying sets are infinity so do not contribute to the minimum, instead
109 * acting like a set union.
110 */
111 static bool
112 minimum_next_uses(struct next_uses *nu, const struct next_uses *from)
113 {
114 bool progress = false;
115
116 foreach_next_use(from, node, from_dist) {
117 dist_t nu_dist = search_next_uses(nu, node);
118
119 if (from_dist < nu_dist) {
120 set_next_use(nu, node, from_dist);
121 progress = true;
122 }
123 }
124
125 return progress;
126 }
127
128 static uint32_t
129 instr_cycles(const bi_instr *I)
130 {
131 return 1;
132 }
133
134 struct spill_block {
135 /* Set of values available in the register file at the end */
136 unsigned W_exit[BI_MAX_REGS];
137 unsigned nW_exit;
138
139 unsigned W_entry[BI_MAX_REGS];
140 unsigned nW_entry;
141
142 /* Set of live-out spilled values at the end of the block */
143 unsigned *S_exit;
144 unsigned nS_exit;
145
146 unsigned *S_entry;
147 unsigned nS_entry;
148
149 /* Estimate */
150 uint32_t cycles;
151
152 /* Next-use maps at the start/end of the block */
153 struct next_uses next_use_in;
154 struct next_uses next_use_out;
155 };
156
157 struct spill_ctx {
158 void *memctx;
159 bi_context *shader;
160 bi_block *block;
161
162 /* Set of values currently available in the register file */
163 BITSET_WORD *W;
164
165 /* |W| = Current register pressure */
166 unsigned nW;
167
168 /* Local IPs of next-use */
169 dist_t *next_uses;
170
171 /* Current local IP relative to the start of the block */
172 uint32_t ip;
173
174 /* Set of live values that have been spilled. Contrary to the paper, this
175 * is not a subset of W: the definition in the paper is bogus.
176 */
177 BITSET_WORD *S;
178
179 /* Widths of vectors */
180 uint32_t *size;
181
182 /* Mapping of rematerializable values to their definitions, or NULL for nodes
183 * that are not materializable.
184 */
185 bi_instr **remat;
186
187 /* Maximum register pressure allowed */
188 unsigned k;
189
190 /* Number of variables allocated */
191 unsigned n_alloc;
192
193 /* Information on blocks indexed in source order */
194 struct spill_block *blocks;
195
196 /* first FAU index for spilled registers */
197 unsigned spill_base;
198
199 /* Max index reserved for spilled indices */
200 uint32_t spill_max;
201
202 /* count of spilled bytes */
203 uint32_t spill_bytes;
204
205 /* mapping of registers to spill locations */
206 uint32_t *spill_map;
207 /* and the reverse */
208 uint32_t *mem_map;
209 /* used to mark if a location has been stored to already. */
210 BITSET_WORD *spill_map_store;
211
212 /* Instruction that defines an SSA value. */
213 bi_instr **ssa_defs;
214
215 /* Block that defines an SSA value. */
216 bi_block **ssa_def_blocks;
217
218 /* architecture */
219 unsigned arch;
220
221 /* In cmp_dist, only prefer remats if their next_use is at least this
222 * value.
223 */
224 dist_t cmp_dist_min_remat_dst;
225 };
226
227 static inline struct spill_block *
228 spill_block(struct spill_ctx *ctx, bi_block *block)
229 {
230 return &ctx->blocks[block->index];
231 }
232
233 /* Calculate the register demand of a node. This should be rounded up to
234 * a power-of-two to match the equivalent calculations in RA.
235 */
236 static inline unsigned
237 node_size(struct spill_ctx *ctx, unsigned node)
238 {
239 return ctx->size[node];
240 }
241
242 /*
243 * Map a control flow edge to a block. Assumes no critical edges.
244 */
245 static bi_block *
246 bi_edge_to_block(bi_block *pred, bi_block *succ)
247 {
248 /* End of predecessor is unique if there's a single successor */
249 if (bi_num_successors(pred) == 1)
250 return pred;
251
252 /* The predecessor has multiple successors, meaning this is not the only
253 * edge leaving the predecessor. Therefore, it is the only edge entering
254 * the successor (otherwise the edge would be critical), so the start of
255 * the successor is unique.
256 */
257 assert(bi_num_predecessors(succ) == 1 && "critical edge detected");
258 return succ;
259 }
260
261 /*
262 * Get a cursor to insert along a control flow edge: either at the start of the
263 * successor or the end of the predecessor. This relies on the control flow
264 * graph having no critical edges.
265 */
266 static bi_cursor
267 bi_along_edge(bi_block *pred, bi_block *succ)
268 {
269 bi_block *to = bi_edge_to_block(pred, succ);
270
271 if (to == pred)
272 return bi_after_block_logical(pred);
273 else
274 return bi_before_block(succ);
275 }
276
277 static inline bool
278 bi_idx_is_memory(bi_index idx) {
279 return idx.memory;
280 }
281
282 static bi_index
283 bi_index_as_mem(bi_index idx, struct spill_ctx *ctx)
284 {
285 assert(idx.type == BI_INDEX_NORMAL);
286 assert(!idx.memory);
287 assert(idx.value <= ctx->n_alloc);
288
289 idx.memory = true;
290 idx.value = ctx->spill_base + idx.value;
291
292 return idx;
293 }
294
295 static unsigned
296 chase_mem_index(bi_index ref, struct spill_ctx *ctx)
297 {
298 return bi_idx_is_memory(ref) ? (ref.value - ctx->spill_base) : ref.value;
299 }
300
301 static bi_index
302 reconstruct_index(struct spill_ctx *ctx, unsigned node)
303 {
304 bi_index r = bi_get_index(node);
305 /* do we need to reconstruct the swizzle here? */
306 return r;
307 }
308
309 static bool
310 only_const_sources(bi_instr *I)
311 {
312 bool res = true;
313 for (uint32_t s = 0; s < I->nr_srcs && res; ++s) {
314 bi_index src = I->src[s];
315 enum bi_index_type t = src.type;
316 res &= t == BI_INDEX_CONSTANT || t == BI_INDEX_FAU;
317 }
318 return res;
319 }
320
321 static bool
322 can_remat(bi_instr *I)
323 {
324 switch (I->op) {
325 case BI_OPCODE_IADD_IMM_I32:
326 case BI_OPCODE_IADD_IMM_V2I16:
327 return only_const_sources(I);
328 case BI_OPCODE_LD_PKA_I8:
329 case BI_OPCODE_LD_PKA_I16:
330 case BI_OPCODE_LD_PKA_I24:
331 case BI_OPCODE_LD_PKA_I32:
332 /* TODO: Allow loads that write >1 reg. */
333 return only_const_sources(I);
334 case BI_OPCODE_MOV_I32:
335 assert(!I->src[0].memory);
336 assert(!I->dest[0].memory);
337 assert(I->dest[0].type == BI_INDEX_NORMAL);
338 enum bi_index_type t = I->src[0].type;
339 return t == BI_INDEX_CONSTANT || t == BI_INDEX_FAU;
340 default:
341 return false;
342 }
343 }
344
345 static bi_instr *
346 remat_to(bi_builder *b, bi_index dst, struct spill_ctx *ctx, unsigned node)
347 {
348 assert(dst.type == BI_INDEX_NORMAL);
349 assert(node < ctx->spill_max);
350 bi_instr *I = ctx->remat[node];
351 assert(can_remat(I));
352
353 switch (I->op) {
354 case BI_OPCODE_IADD_IMM_I32:
355 return bi_iadd_imm_i32_to(b, dst, I->src[0], I->index);
356 case BI_OPCODE_IADD_IMM_V2I16:
357 return bi_iadd_imm_v2i16_to(b, dst, I->src[0], I->index);
358 case BI_OPCODE_LD_PKA_I8:
359 return bi_ld_pka_i8_to(b, dst, I->src[0], I->src[1]);
360 case BI_OPCODE_LD_PKA_I16:
361 return bi_ld_pka_i16_to(b, dst, I->src[0], I->src[1]);
362 case BI_OPCODE_LD_PKA_I24:
363 return bi_ld_pka_i24_to(b, dst, I->src[0], I->src[1]);
364 case BI_OPCODE_LD_PKA_I32:
365 return bi_ld_pka_i32_to(b, dst, I->src[0], I->src[1]);
366 case BI_OPCODE_MOV_I32:
367 assert(I->src[0].type == BI_INDEX_CONSTANT ||
368 I->src[0].type == BI_INDEX_FAU);
369 return bi_mov_i32_to(b, dst, I->src[0]);
370 default:
371 UNREACHABLE("invalid remat");
372 }
373 }
374
375 /* This tries to return a cursor in the block in which 'node' is defined.
376 * Returns the fallback position if the block that defines 'node' equals
377 * 'current_block'.
378 *
379 * 'current_block' if called from:
380 * - min_algorithm: ctx->block
381 * - insert_coupling_code: current_block should be the block in which the spill
382 * is needed (i.e. not ctx->block, if ctx->block == succ, but the spill is
383 * required from pred). The reason for this is, if a value defined in succ
384 * needs to be spilled first along the backedge back to succ from pred, the
385 * spilled version can be undefined at the place of a later use.
386 */
387 static bi_cursor
388 choose_spill_position(struct spill_ctx *ctx, unsigned node, bi_cursor fallback,
389 bi_block *current_block)
390 {
391 bi_instr *producer = ctx->ssa_defs[node];
392 bi_block *block = ctx->ssa_def_blocks[node];
393
394 assert(producer);
395 assert(block);
396
397 if (current_block == block)
398 return fallback;
399
400 /* Don't insert spills in the middle of the PHI block. This breaks the
401 * assumption that phis are together at the start of each block. */
402 if (producer->op == BI_OPCODE_PHI) {
403 return bi_after_block_logical(block);
404 } else {
405 return bi_after_instr(producer);
406 }
407 }
408
409 static void
410 insert_spill(bi_builder *b, struct spill_ctx *ctx, unsigned node)
411 {
412 assert(node < ctx->n_alloc);
413
414 if (!ctx->remat[node] && !BITSET_TEST(ctx->spill_map_store, node)) {
415 bi_index idx = reconstruct_index(ctx, node);
416 bi_index mem = bi_index_as_mem(idx, ctx);
417
418 bi_memmov_to(b, mem, idx);
419
420 b->shader->spills++;
421 /* We only need the extra registers reserved if we actually spilled
422 * instead of just remat.
423 */
424 b->shader->has_spill_pcopy_reserved = true;
425
426 BITSET_SET(ctx->spill_map_store, node);
427 }
428 }
429
430 static void
431 insert_reload(struct spill_ctx *ctx, bi_block *block, bi_cursor cursor,
432 unsigned node)
433 {
434 assert(node < ctx->n_alloc);
435
436 bi_builder b = bi_init_builder(ctx->shader, cursor);
437 bi_index idx = reconstruct_index(ctx, node);
438
439 /* Reloading breaks SSA, but we're leaving SSA anyway */
440 if (ctx->remat[node]) {
441 remat_to(&b, idx, ctx, node);
442 } else {
443 bi_memmov_to(&b, idx, bi_index_as_mem(idx, ctx));
444 b.shader->fills++;
445 }
446 }
447
448 /* Insert into the register file */
449 static void
450 insert_W(struct spill_ctx *ctx, unsigned v)
451 {
452 assert(v < ctx->n_alloc);
453 assert(!BITSET_TEST(ctx->W, v));
454
455 BITSET_SET(ctx->W, v);
456 ctx->nW += node_size(ctx, v);
457 }
458
459 /* Remove from the register file */
460 static void
461 remove_W(struct spill_ctx *ctx, unsigned v)
462 {
463 assert(v < ctx->n_alloc);
464 assert(BITSET_TEST(ctx->W, v));
465
466 BITSET_CLEAR(ctx->W, v);
467 ctx->nW -= node_size(ctx, v);
468 }
469
470 static void
471 remove_W_if_present(struct spill_ctx *ctx, unsigned v)
472 {
473 assert(v < ctx->n_alloc);
474
475 if (BITSET_TEST(ctx->W, v))
476 remove_W(ctx, v);
477 }
478
479 #define bi_worklist_init(ctx, w) u_worklist_init(w, ctx->num_blocks, ctx)
480 #define bi_worklist_push_head(w, block) u_worklist_push_head(w, block, index)
481 #define bi_worklist_push_tail(w, block) u_worklist_push_tail(w, block, index)
482 #define bi_worklist_peek_head(w) u_worklist_peek_head(w, bi_block, index)
483 #define bi_worklist_pop_head(w) u_worklist_pop_head(w, bi_block, index)
484 #define bi_worklist_peek_tail(w) u_worklist_peek_tail(w, bi_block, index)
485 #define bi_worklist_pop_tail(w) u_worklist_pop_tail(w, bi_block, index)
486
487 struct candidate {
488 unsigned node;
489 dist_t dist;
490 };
491
492 static int
493 cmp_dist(const void *left_, const void *right_, void *ctx_)
494 {
495 struct spill_ctx *ctx = ctx_;
496 const struct candidate *left = left_;
497 const struct candidate *right = right_;
498 unsigned ldist = left->dist;
499 unsigned rdist = right->dist;
500 unsigned min_remat_dst = ctx->cmp_dist_min_remat_dst;
501 /* We assume that rematerializing - even before every instruction - is
502 * cheaper than spilling. As long as one of the nodes is rematerializable
503 * (with distance > 0), we choose it over spilling. Within a class of nodes
504 * (rematerializable or not), compare by next-use-distance.
505 */
506 assert(left->node < ctx->n_alloc);
507 assert(right->node < ctx->n_alloc);
508 bool remat_left = ctx->remat[left->node] != NULL && ldist > min_remat_dst;
509 bool remat_right = ctx->remat[right->node] != NULL && rdist > min_remat_dst;
510
511 if (remat_left != remat_right)
512 return remat_left ? 1 : -1;
513 else
514 return (ldist > rdist) - (ldist < rdist);
515 }
516
517 /*
518 * Insert coupling code on block boundaries. This must ensure:
519 *
520 * - anything live-in we expect to have spilled is spilled
521 * - anything live-in we expect to have filled is filled
522 * - phi sources are spilled if the destination is spilled
523 * - phi sources are filled if the destination is not spilled
524 *
525 * The latter two requirements ensure correct pressure calculations for phis.
526 */
527 static ATTRIBUTE_NOINLINE void
528 insert_coupling_code(struct spill_ctx *ctx, bi_block *pred, bi_block *succ)
529 {
530 struct spill_block *sp = spill_block(ctx, pred);
531 struct spill_block *ss = spill_block(ctx, succ);
532
533 bi_foreach_phi_in_block(succ, I) {
534 if (!bi_idx_is_memory(I->dest[0]))
535 continue;
536
537 bi_builder b =
538 bi_init_builder(ctx->shader, bi_before_function(ctx->shader));
539
540 unsigned s = bi_predecessor_index(succ, pred);
541
542 /* Copy immediate/uniform phi sources to memory variables at the start of
543 * the program, where pressure is zero and hence the copy is legal.
544 */
545 if (I->src[s].type != BI_INDEX_NORMAL) {
546 assert(I->src[s].type == BI_INDEX_CONSTANT ||
547 I->src[s].type == BI_INDEX_REGISTER ||
548 I->src[s].type == BI_INDEX_FAU);
549
550 bi_index mem = bi_temp(ctx->shader);
551 mem.memory = true;
552
553 bi_index gpr = bi_temp(ctx->shader);
554
555 assert(gpr.type == BI_INDEX_NORMAL);
556 if (ctx->arch >= 9 && I->src[s].type == BI_INDEX_CONSTANT) {
557 /* MOV of immediate needs lowering on Valhall */
558 bi_index zero = bi_fau(BIR_FAU_IMMEDIATE | 0, false);
559 bi_iadd_imm_i32_to(&b, gpr, zero, I->src[s].value);
560 } else
561 bi_mov_i32_to(&b, gpr, I->src[s]);
562
563 bi_memmov_to(&b, mem, gpr);
564 I->src[s] = mem;
565 continue;
566 }
567
568 bool spilled = false;
569 for (unsigned i = 0; i < sp->nS_exit; ++i) {
570 if (sp->S_exit[i] == I->src[s].value) {
571 spilled = true;
572 break;
573 }
574 }
575
576 if (!spilled) {
577 bi_cursor c = choose_spill_position(
578 ctx, I->src[s].value, bi_after_block_logical(pred), pred);
579 bi_builder b = bi_init_builder(ctx->shader, c);
580
581 insert_spill(&b, ctx, I->src[s].value);
582 }
583
584 if (ctx->remat[I->src[s].value]) {
585 unsigned node = I->src[s].value;
586 bi_index idx = reconstruct_index(ctx, node);
587 bi_index tmp = bi_temp(ctx->shader);
588
589 remat_to(&b, tmp, ctx, node);
590 bi_memmov_to(&b, bi_index_as_mem(idx, ctx), tmp);
591 }
592
593 /* Use the spilled version */
594 I->src[s] = bi_index_as_mem(I->src[s], ctx);
595 }
596
597 /* Anything assumed to be spilled at the start of succ must be spilled along
598 * all edges.
599 */
600 for (unsigned i = 0; i < ss->nS_entry; ++i) {
601 unsigned v = ss->S_entry[i];
602
603 bool spilled = false;
604 for (unsigned j = 0; j < sp->nS_exit; ++j) {
605 if (sp->S_exit[j] == v) {
606 spilled = true;
607 break;
608 }
609 }
610
611 /* We handle spilling phi destinations separately */
612 bi_foreach_phi_in_block(succ, phi) {
613 if (chase_mem_index(phi->dest[0], ctx) == v) {
614 spilled = true;
615 break;
616 }
617 }
618
619 if (spilled)
620 continue;
621
622 bi_cursor c = choose_spill_position(ctx, v, bi_along_edge(pred, succ),
623 bi_edge_to_block(pred, succ));
624 bi_builder b = bi_init_builder(ctx->shader, c);
625 insert_spill(&b, ctx, v);
626 }
627
628 /* Variables in W at the start of succ must be defined along the edge. */
629 for (unsigned i = 0; i < ss->nW_entry; ++i) {
630 unsigned node = ss->W_entry[i];
631 bool defined = false;
632
633 /* Variables live at the end of the predecessor are live along the edge */
634 for (unsigned j = 0; j < sp->nW_exit; ++j) {
635 if (sp->W_exit[j] == node) {
636 defined = true;
637 break;
638 }
639 }
640
641 /* Phis are defined along the edge */
642 bi_foreach_phi_in_block(succ, phi) {
643 if (phi->dest[0].value == node) {
644 defined = true;
645 break;
646 }
647 }
648
649 if (defined)
650 continue;
651
652 /* Otherwise, inserting a reload defines the variable along the edge */
653 bi_block *reload_block = bi_edge_to_block(pred, succ);
654 insert_reload(ctx, reload_block, bi_along_edge(pred, succ), node);
655 }
656
657 bi_foreach_phi_in_block(succ, I) {
658 if (bi_idx_is_memory(I->dest[0]))
659 continue;
660
661 unsigned s = bi_predecessor_index(succ, pred);
662
663 /* Treat immediate/uniform phi sources as registers for pressure
664 * accounting and phi lowering purposes. Parallel copy lowering can handle
665 * a copy from a immediate/uniform to a register, but not from an
666 * immediate/uniform directly to memory.
667 */
668 if (I->src[s].type != BI_INDEX_NORMAL && !I->src[s].memory) {
669 assert(I->src[s].type == BI_INDEX_CONSTANT ||
670 I->src[s].type == BI_INDEX_REGISTER ||
671 I->src[s].type == BI_INDEX_FAU
672 );
673
674 continue;
675 }
676
677 bool live = false;
678 for (unsigned i = 0; i < sp->nW_exit; ++i) {
679 if (sp->W_exit[i] == I->src[s].value) {
680 live = true;
681 break;
682 }
683 }
684
685 /* Fill the phi source in the predecessor */
686 if (!live) {
687 bi_block *reload_block = bi_edge_to_block(pred, succ);
688 insert_reload(ctx, reload_block, bi_along_edge(pred, succ),
689 I->src[s].value);
690 }
691
692 /* Leave as-is for the GPR version */
693 assert(!bi_idx_is_memory(I->src[s]));
694 }
695 }
696
697 /*
698 * Produce an array of next-use IPs relative to the start of the block. This is
699 * an array of dist_t scalars, representing the next-use IP of each SSA dest
700 * (right-to-left) and SSA source (left-to-right) of each instruction in the
701 * block (bottom-to-top). Its size equals the # of SSA sources in the block.
702 */
703 static ATTRIBUTE_NOINLINE void
704 calculate_local_next_use(struct spill_ctx *ctx, struct util_dynarray *out)
705 {
706 struct spill_block *sb = spill_block(ctx, ctx->block);
707 unsigned ip = sb->cycles;
708
709 *out = UTIL_DYNARRAY_INIT;
710
711 struct next_uses nu;
712 init_next_uses(&nu, NULL);
713
714 foreach_next_use(&sb->next_use_out, i, dist) {
715 set_next_use(&nu, i, dist_sum(ip, dist));
716 }
717
718 bi_foreach_instr_in_block_rev(ctx->block, I) {
719 ip -= instr_cycles(I);
720
721 if (I->op != BI_OPCODE_PHI) {
722 bi_foreach_ssa_dest_rev(I, d) {
723 unsigned v = I->dest[d].value;
724 dist_t next_dist = search_next_uses(&nu, v);
725 util_dynarray_append(out, next_dist);
726 }
727
728 bi_foreach_ssa_src(I, s) {
729 unsigned v = I->src[s].value;
730 dist_t next_dist = search_next_uses(&nu, v);
731 util_dynarray_append(out, next_dist);
732 assert((next_dist == DIST_INFINITY) == I->src[s].kill_ssa);
733 set_next_use(&nu, v, ip);
734 }
735 }
736 }
737
738 assert(ip == 0 && "cycle counting is consistent");
739 destroy_next_uses(&nu);
740 }
741
742 /*
743 * Let I_B be the set of live-in variables plus the set of variables defined
744 * by phis. Then W_entry will contain variables
745 * - I_B & <variables used in the loop>
746 * - I_B & <variables live-through the loop> (if there is space left)
747 */
748 static ATTRIBUTE_NOINLINE void
749 compute_w_entry_loop_header(struct spill_ctx *ctx)
750 {
751 bi_block *block = ctx->block;
752 struct spill_block *sb = spill_block(ctx, block);
753
754 const uint32_t flags_len = ctx->n_alloc;
755 bool *flag_mem = calloc(2 * flags_len, sizeof(bool));
756 bool *alive = flag_mem;
757 bool *used_in_loop = flag_mem + flags_len;
758
759 /* alive := live-in + defined by phis */
760 uint32_t i = 0;
761 BITSET_FOREACH_SET(i, ctx->block->ssa_live_in, ctx->n_alloc) {
762 alive[i] = true;
763 }
764 bi_foreach_phi_in_block(ctx->block, phi)
765 {
766 alive[phi->dest[0].value] = true;
767 }
768
769 /* Start with candidates := { v : v ∈ alive and used_in_loop(v) }. */
770 struct candidate *candidates =
771 calloc(ctx->n_alloc, sizeof(struct candidate));
772 uint32_t n_ca = 0;
773
774 uint32_t max_loop_pressure = 0;
775 BITSET_WORD *loop_block = BITSET_RZALLOC(NULL, ctx->shader->num_blocks);
776 bi_find_loop_blocks(ctx->shader, ctx->block, loop_block);
777
778 bi_foreach_block(ctx->shader, block) {
779 if (BITSET_TEST(loop_block, block->index)) {
780 bi_foreach_instr_in_block(block, I) {
781 max_loop_pressure = MAX2(max_loop_pressure, block->ssa_max_live);
782
783 bi_foreach_src(I, s) {
784 const uint32_t v = I->src[s].value;
785 const bool is_reg = I->src[s].type == BI_INDEX_NORMAL;
786
787 /* Only add live register values, and only add them once. */
788 if (!is_reg || !alive[v] || used_in_loop[v])
789 continue;
790
791 const dist_t d = search_next_uses(&sb->next_use_in, v);
792 candidates[n_ca++] = (struct candidate){.node = v, .dist = d};
793 used_in_loop[v] = true;
794 }
795 }
796 }
797 }
798
799 ralloc_free(loop_block);
800
801 /* Sort by next-use distance. */
802 util_qsort_r(candidates, n_ca, sizeof(struct candidate), cmp_dist, ctx);
803
804 const uint32_t n_ca_loop = n_ca;
805
806 /* Find live-through values in case we want to add any. */
807 if (n_ca < ctx->k) {
808 for (i = 0; i < ctx->n_alloc; ++i) {
809 const bool live_through = alive[i] && !used_in_loop[i];
810 if (live_through) {
811 const dist_t d = search_next_uses(&sb->next_use_in, i);
812 candidates[n_ca++] = (struct candidate){.node = i, .dist = d};
813 }
814 }
815 }
816 const uint32_t n_lt = n_ca - n_ca_loop;
817
818 /* Sort live-through variables by next-use distance. */
819 util_qsort_r(candidates + n_ca_loop, n_lt, sizeof(struct candidate),
820 cmp_dist, ctx);
821
822 assert(max_loop_pressure >= n_lt);
823 /* If the pressure caused by vars inside the loop t is < k, we have space
824 * for more variables to put in W_entry. */
825 const uint32_t t = max_loop_pressure - n_lt;
826 if (t < ctx->k)
827 n_ca = CLAMP(n_ca_loop + (ctx->k - t), 0, n_ca);
828 else
829 n_ca = n_ca_loop;
830
831 /* Take as much as we can. */
832 for (unsigned i = 0; i < n_ca; ++i) {
833 unsigned node = candidates[i].node;
834 unsigned comps = node_size(ctx, node);
835
836 if ((ctx->nW + comps) <= ctx->k) {
837 insert_W(ctx, node);
838 sb->W_entry[sb->nW_entry++] = node;
839 }
840 }
841
842 assert(ctx->nW <= ctx->k && "invariant");
843
844 free(candidates);
845 free(flag_mem);
846 }
847
848 /*
849 * The W_entry will contain variables that are W_exit in
850 * - all predecessors
851 * - some predecessors, sorted by next-use distance
852 */
853 static ATTRIBUTE_NOINLINE void
854 compute_w_entry_usual(struct spill_ctx *ctx)
855 {
856 bi_block *block = ctx->block;
857 struct spill_block *sb = spill_block(ctx, block);
858
859 unsigned *freq = calloc(ctx->n_alloc, sizeof(unsigned));
860
861 /* Record what's written at the end of each predecessor */
862 bi_foreach_predecessor(ctx->block, P) {
863 struct spill_block *sp = spill_block(ctx, *P);
864
865 for (unsigned i = 0; i < sp->nW_exit; ++i) {
866 unsigned v = sp->W_exit[i];
867 freq[v]++;
868 }
869 }
870
871 struct candidate *candidates = calloc(ctx->n_alloc, sizeof(struct candidate));
872 unsigned j = 0;
873
874 /* Variables that are in all predecessors are assumed in W_entry. Phis and
875 * variables in some predecessors are scored by next-use.
876 */
877 foreach_next_use(&sb->next_use_in, i, dist) {
878 if (freq[i] == bi_num_predecessors(ctx->block)) {
879 insert_W(ctx, i);
880 } else if (freq[i]) {
881 candidates[j++] = (struct candidate){.node = i, .dist = dist};
882 }
883 }
884
885 bi_foreach_phi_in_block(ctx->block, I) {
886 bool all_found = true;
887
888 bi_foreach_predecessor(ctx->block, pred) {
889 struct spill_block *sp = spill_block(ctx, *pred);
890 bool found = false;
891
892 bi_index src = I->src[bi_predecessor_index(ctx->block, *pred)];
893 if (src.type != BI_INDEX_NORMAL)
894 continue;
895
896 unsigned v = src.value;
897 for (unsigned i = 0; i < sp->nW_exit; ++i) {
898 if (sp->W_exit[i] == v) {
899 found = true;
900 break;
901 }
902 }
903
904 all_found &= found;
905 }
906
907 /* Heuristic: if any phi source is spilled, spill the whole phi. This is
908 * suboptimal, but it massively reduces pointless fill/spill chains with
909 * massive phi webs.
910 */
911 if (!all_found)
912 continue;
913
914 candidates[j++] = (struct candidate){
915 .node = I->dest[0].value,
916 .dist = search_next_uses(&sb->next_use_in, I->dest[0].value),
917 };
918 }
919
920 /* Sort by next-use distance */
921 util_qsort_r(candidates, j, sizeof(struct candidate), cmp_dist, ctx);
922
923 /* Take as much as we can */
924 for (unsigned i = 0; i < j; ++i) {
925 unsigned node = candidates[i].node;
926 unsigned comps = node_size(ctx, node);
927
928 if ((ctx->nW + comps) <= ctx->k) {
929 insert_W(ctx, node);
930 sb->W_entry[sb->nW_entry++] = node;
931 }
932 }
933
934 assert(ctx->nW <= ctx->k && "invariant");
935
936 free(freq);
937 free(candidates);
938 }
939
940 /*
941 * Compute W_entry for a block. Section 4.2 in the paper.
942 */
943 static ATTRIBUTE_NOINLINE void
944 compute_w_entry(struct spill_ctx *ctx)
945 {
946 bi_block *block = ctx->block;
947
948 /* Nothing to do for start blocks */
949 if (bi_num_predecessors(block) == 0)
950 return;
951
952 /* Loop headers have a different heuristic */
953 if (block->loop_header) {
954 compute_w_entry_loop_header(ctx);
955 } else {
956 compute_w_entry_usual(ctx);
957 }
958 }
959
960 /*
961 * We initialize S with the union of S at the exit of (forward edge)
962 * predecessors and the complement of W, intersected with the live-in set. The
963 * former propagates S forward. The latter ensures we spill along the edge when
964 * a live value is not selected for the entry W.
965 */
966 static ATTRIBUTE_NOINLINE void
967 compute_s_entry(struct spill_ctx *ctx)
968 {
969 unsigned v;
970
971 bi_foreach_predecessor(ctx->block, pred) {
972 struct spill_block *sp = spill_block(ctx, *pred);
973
974 for (unsigned i = 0; i < sp->nS_exit; ++i) {
975 v = sp->S_exit[i];
976
977 if (BITSET_TEST(ctx->block->ssa_live_in, v))
978 BITSET_SET(ctx->S, v);
979 }
980 }
981
982 BITSET_FOREACH_SET(v, ctx->block->ssa_live_in, ctx->n_alloc) {
983 if (!BITSET_TEST(ctx->W, v))
984 BITSET_SET(ctx->S, v);
985 }
986
987 /* Copy ctx->S to S_entry for later look-ups with coupling code */
988 struct spill_block *sb = spill_block(ctx, ctx->block);
989 unsigned nS = __bitset_count(ctx->S, BITSET_WORDS(ctx->n_alloc));
990 sb->S_entry = ralloc_array(ctx->memctx, unsigned, nS);
991
992 int i;
993 BITSET_FOREACH_SET(i, ctx->S, ctx->n_alloc)
994 sb->S_entry[sb->nS_entry++] = i;
995
996 assert(sb->nS_entry == nS);
997 }
998
999 static ATTRIBUTE_NOINLINE void
1000 global_next_use_distances(bi_context *ctx, void *memctx,
1001 struct spill_block *blocks)
1002 {
1003 u_worklist worklist;
1004 u_worklist_init(&worklist, ctx->num_blocks, NULL);
1005
1006 bi_foreach_block(ctx, block) {
1007 struct spill_block *sb = &blocks[block->index];
1008
1009 init_next_uses(&sb->next_use_in, memctx);
1010 init_next_uses(&sb->next_use_out, memctx);
1011
1012 bi_foreach_instr_in_block(block, I) {
1013 sb->cycles += instr_cycles(I);
1014 }
1015
1016 bi_worklist_push_head(&worklist, block);
1017 }
1018
1019 /* Definitions that have been seen */
1020 BITSET_WORD *defined =
1021 malloc(BITSET_WORDS(ctx->ssa_alloc) * sizeof(BITSET_WORD));
1022
1023 struct next_uses dists;
1024 init_next_uses(&dists, NULL);
1025
1026 /* Iterate the work list in reverse order since liveness is backwards */
1027 while (!u_worklist_is_empty(&worklist)) {
1028 bi_block *blk = bi_worklist_pop_head(&worklist);
1029 struct spill_block *sb = &blocks[blk->index];
1030
1031 /* Definitions that have been seen */
1032 memset(defined, 0, BITSET_WORDS(ctx->ssa_alloc) * sizeof(BITSET_WORD));
1033
1034 /* Initialize all distances to infinity */
1035 clear_next_uses(&dists);
1036
1037 uint32_t cycle = 0;
1038
1039 /* Calculate dists. Phis are handled separately. */
1040 bi_foreach_instr_in_block(blk, I) {
1041 if (I->op == BI_OPCODE_PHI) {
1042 cycle++;
1043 continue;
1044 }
1045
1046 /* Record first use before def. Phi sources are handled
1047 * above, because they logically happen in the
1048 * predecessor.
1049 */
1050 bi_foreach_ssa_src(I, s) {
1051 if (BITSET_TEST(defined, I->src[s].value))
1052 continue;
1053 if (search_next_uses(&dists, I->src[s].value) < DIST_INFINITY)
1054 continue;
1055
1056 assert(I->src[s].value < ctx->ssa_alloc);
1057 set_next_use(&dists, I->src[s].value, cycle);
1058 }
1059
1060 /* Record defs */
1061 bi_foreach_ssa_dest(I, d) {
1062 assert(I->dest[d].value < ctx->ssa_alloc);
1063 BITSET_SET(defined, I->dest[d].value);
1064 }
1065
1066 cycle += instr_cycles(I);
1067 }
1068
1069 /* Apply transfer function to get our entry state. */
1070 foreach_next_use(&sb->next_use_out, node, dist) {
1071 set_next_use(&sb->next_use_in, node, dist_sum(dist, sb->cycles));
1072 }
1073
1074 foreach_next_use(&dists, node, dist) {
1075 set_next_use(&sb->next_use_in, node, dist);
1076 }
1077
1078 int i;
1079 BITSET_FOREACH_SET(i, defined, ctx->ssa_alloc) {
1080 set_next_use(&sb->next_use_in, i, DIST_INFINITY);
1081 }
1082
1083 /* Propagate the live in of the successor (blk) to the live out of
1084 * predecessors.
1085 *
1086 * Phi nodes are logically on the control flow edge and act in parallel.
1087 * To handle when propagating, we kill writes from phis and make live the
1088 * corresponding sources.
1089 */
1090 bi_foreach_predecessor(blk, pred) {
1091 struct spill_block *sp = &blocks[(*pred)->index];
1092 copy_next_uses(&dists, &sb->next_use_in);
1093
1094 /* Kill write */
1095 bi_foreach_phi_in_block(blk, I) {
1096 assert(I->dest[0].type == BI_INDEX_NORMAL);
1097 set_next_use(&dists, I->dest[0].value, DIST_INFINITY);
1098 }
1099
1100 /* Make live the corresponding source */
1101 bi_foreach_phi_in_block(blk, I) {
1102 bi_index operand = I->src[bi_predecessor_index(blk, *pred)];
1103 if (operand.type == BI_INDEX_NORMAL)
1104 set_next_use(&dists, operand.value, 0);
1105 }
1106
1107 /* Join by taking minimum */
1108 if (minimum_next_uses(&sp->next_use_out, &dists))
1109 bi_worklist_push_tail(&worklist, *pred);
1110 }
1111 }
1112
1113 free(defined);
1114 u_worklist_fini(&worklist);
1115 destroy_next_uses(&dists);
1116 }
1117
1118 static ATTRIBUTE_NOINLINE void
1119 validate_next_use_info(UNUSED bi_context *ctx,
1120 UNUSED struct spill_block *blocks)
1121 {
1122 #ifndef NDEBUG
1123 int i;
1124
1125 bi_foreach_block(ctx, blk) {
1126 struct spill_block *sb = &blocks[blk->index];
1127
1128 /* Invariant: next-use distance is finite iff the node is live */
1129 BITSET_FOREACH_SET(i, blk->ssa_live_in, ctx->ssa_alloc)
1130 assert(search_next_uses(&sb->next_use_in, i) < DIST_INFINITY);
1131
1132 BITSET_FOREACH_SET(i, blk->ssa_live_out, ctx->ssa_alloc)
1133 assert(search_next_uses(&sb->next_use_out, i) < DIST_INFINITY);
1134
1135 foreach_next_use(&sb->next_use_in, i, _)
1136 assert(BITSET_TEST(blk->ssa_live_in, i));
1137
1138 foreach_next_use(&sb->next_use_out, i, _)
1139 assert(BITSET_TEST(blk->ssa_live_out, i));
1140 }
1141 #endif
1142 }
1143
1144 /*
1145 * Limit the register file W to maximum size m by evicting registers.
1146 */
1147 static ATTRIBUTE_NOINLINE void
1148 limit(struct spill_ctx *ctx, bi_instr *I, unsigned m)
1149 {
1150 /* Nothing to do if we're already below the limit */
1151 if (ctx->nW <= m)
1152 return;
1153
1154 /* Gather candidates for eviction. Note that next_uses gives IPs whereas
1155 * cmp_dist expects relative distances. This requires us to subtract ctx->ip
1156 * to ensure that cmp_dist works properly. Even though logically it shouldn't
1157 * affect the sorted order, practically this matters for correctness with
1158 * rematerialization. See the dist=0 test in cmp_dist.
1159 */
1160 struct candidate *candidates = alloca(ctx->nW * sizeof(struct candidate));
1161 unsigned j = 0;
1162
1163 int i;
1164 BITSET_FOREACH_SET(i, ctx->W, ctx->n_alloc) {
1165 assert(j < ctx->nW);
1166
1167 dist_t next_use = ctx->next_uses[i];
1168 if (next_use < DIST_INFINITY && next_use >= ctx->ip)
1169 next_use -= ctx->ip;
1170 else
1171 next_use = DIST_INFINITY;
1172 candidates[j++] = (struct candidate){
1173 .node = i,
1174 .dist = next_use,
1175 };
1176 }
1177
1178 dist_t dst_next_use = ctx->ip;
1179 bi_foreach_ssa_dest(I, d) {
1180 uint32_t dest = I->dest[d].value;
1181 dst_next_use = MAX2(ctx->next_uses[dest], dst_next_use);
1182 }
1183
1184 /* Sort by next-use distance */
1185 ctx->cmp_dist_min_remat_dst = dst_next_use - ctx->ip;
1186 util_qsort_r(candidates, j, sizeof(struct candidate), cmp_dist, ctx);
1187
1188 /* Restore default for everything else. */
1189 ctx->cmp_dist_min_remat_dst = 0;
1190
1191 /* Evict what doesn't fit */
1192 unsigned new_weight = 0;
1193
1194 for (i = 0; i < j; ++i) {
1195 unsigned v = candidates[i].node;
1196 unsigned comps = node_size(ctx, v);
1197
1198 if ((new_weight + comps) <= m) {
1199 new_weight += comps;
1200 } else {
1201 /* Insert a spill if we haven't spilled before and there is
1202 * another use
1203 */
1204 if (!BITSET_TEST(ctx->S, v) && candidates[i].dist < DIST_INFINITY) {
1205 bi_cursor c =
1206 choose_spill_position(ctx, v, bi_before_instr(I), ctx->block);
1207 bi_builder b = bi_init_builder(ctx->shader, c);
1208 insert_spill(&b, ctx, v);
1209 BITSET_SET(ctx->S, v);
1210 }
1211
1212 remove_W(ctx, v);
1213
1214 /* We keep going in case we can pack in a scalar */
1215 }
1216 }
1217 }
1218
1219
1220 /*
1221 * validation code for next_ip info
1222 */
1223 static void
1224 validate_next_ip(struct spill_ctx *ctx, struct util_dynarray *local_next_ip)
1225 {
1226 #ifndef NDEBUG
1227 dist_t *next_ips = util_dynarray_element(local_next_ip, dist_t, 0);
1228 unsigned next_use_cursor =
1229 util_dynarray_num_elements(local_next_ip, dist_t);
1230
1231 bi_foreach_instr_in_block(ctx->block, I) {
1232 if (I->op == BI_OPCODE_PHI)
1233 continue;
1234 bi_foreach_ssa_src_rev(I, s) {
1235 assert(next_use_cursor >= 1);
1236
1237 unsigned next_ip = next_ips[--next_use_cursor];
1238 assert((next_ip == DIST_INFINITY) == I->src[s].kill_ssa);
1239 }
1240 bi_foreach_ssa_dest(I, d) {
1241 assert(next_use_cursor >= 1);
1242 unsigned next_ip = next_ips[--next_use_cursor];
1243 (void)next_ip;
1244 }
1245 }
1246 assert(next_use_cursor == 0 && "exactly sized");
1247 #endif
1248 }
1249
1250 /*
1251 * Insert spills/fills for a single basic block, following Belady's algorithm.
1252 * Corresponds to minAlgorithm from the paper.
1253 */
1254 static ATTRIBUTE_NOINLINE void
1255 min_algorithm(struct spill_ctx *ctx)
1256 {
1257 struct spill_block *sblock = spill_block(ctx, ctx->block);
1258 struct util_dynarray local_next_ip;
1259 calculate_local_next_use(ctx, &local_next_ip);
1260
1261 validate_next_ip(ctx, &local_next_ip);
1262
1263 /* next_uses gives the distance from the start of the block, so prepopulate
1264 * with next_use_in.
1265 */
1266 foreach_next_use(&sblock->next_use_in, key, dist) {
1267 assert(key < ctx->n_alloc);
1268 ctx->next_uses[key] = dist;
1269 }
1270
1271 dist_t *next_ips = util_dynarray_element(&local_next_ip, dist_t, 0);
1272 unsigned next_use_cursor =
1273 util_dynarray_num_elements(&local_next_ip, dist_t);
1274
1275 /* Iterate each instruction in forward order */
1276 bi_foreach_instr_in_block(ctx->block, I) {
1277 assert(ctx->nW <= ctx->k && "invariant");
1278
1279 /* Debug to check against our RA demand calculations */
1280 if (0) {
1281 printf("%u: ", ctx->nW);
1282 bi_print_instr(I, stdout);
1283 }
1284
1285 /* Phis are special since they happen along the edge. When we initialized
1286 * W and S, we implicitly chose which phis are spilled. So, here we just
1287 * need to rewrite the phis to write into memory.
1288 *
1289 * Phi sources are handled later.
1290 */
1291 if (I->op == BI_OPCODE_PHI) {
1292 if (!BITSET_TEST(ctx->W, I->dest[0].value)) {
1293 I->dest[0] = bi_index_as_mem(I->dest[0], ctx);
1294 }
1295
1296 ctx->ip += instr_cycles(I);
1297 continue;
1298 }
1299
1300 /* Any source that is not in W needs to be reloaded. Gather the set R of
1301 * such values.
1302 */
1303 unsigned R[BI_MAX_SRCS];
1304 unsigned nR = 0;
1305
1306 bi_foreach_ssa_src(I, s) {
1307 unsigned node = I->src[s].value;
1308 if (BITSET_TEST(ctx->W, node))
1309 continue;
1310
1311 /* Mark this variable as needing a reload. */
1312 assert(node < ctx->n_alloc);
1313 assert(BITSET_TEST(ctx->S, node) && "must have been spilled");
1314 assert(nR < ARRAY_SIZE(R) && "maximum source count");
1315 R[nR++] = node;
1316
1317 /* The inserted reload will add the value to the register file. */
1318 insert_W(ctx, node);
1319 }
1320
1321 /* Limit W to make space for the sources we just added */
1322 limit(ctx, I, ctx->k);
1323
1324 /* Update next-use distances for this instruction. Unlike the paper, we
1325 * prune dead values from W as we go. This doesn't affect correctness, but
1326 * it speeds up limit() on average.
1327 */
1328 bi_foreach_ssa_src_rev(I, s) {
1329 assert(next_use_cursor >= 1);
1330
1331 unsigned next_ip = next_ips[--next_use_cursor];
1332 assert((next_ip == DIST_INFINITY) == I->src[s].kill_ssa);
1333
1334 if (next_ip == DIST_INFINITY)
1335 remove_W_if_present(ctx, I->src[s].value);
1336 else
1337 ctx->next_uses[I->src[s].value] = next_ip;
1338 }
1339
1340 bi_foreach_ssa_dest(I, d) {
1341 assert(next_use_cursor >= 1);
1342 unsigned next_ip = next_ips[--next_use_cursor];
1343
1344 if (next_ip == DIST_INFINITY)
1345 remove_W_if_present(ctx, I->dest[d].value);
1346 else
1347 ctx->next_uses[I->dest[d].value] = next_ip;
1348 }
1349
1350 /* Count how many registers we need for destinations. Because of
1351 * SSA form, destinations are unique.
1352 */
1353 unsigned dest_size = 0;
1354 bi_foreach_ssa_dest(I, d) {
1355 dest_size += node_size(ctx, I->dest[d].value);
1356 }
1357
1358 /* Limit W to make space for the destinations. */
1359 limit(ctx, I, ctx->k - dest_size);
1360
1361 /* Destinations are now in the register file */
1362 bi_foreach_ssa_dest(I, d) {
1363 insert_W(ctx, I->dest[d].value);
1364 }
1365
1366 /* Add reloads for the sources in front of the instruction. We need to be
1367 * careful around exports, hoisting the reloads to before all exports.
1368 *
1369 * This is legal since all exports happen in parallel and all registers
1370 * are dead after the exports. The register file
1371 * must be big enough for everything exported, so it must be big enough
1372 * for all the reloaded values right before the parallel exports.
1373 */
1374 for (unsigned i = 0; i < nR; ++i) {
1375 insert_reload(ctx, ctx->block, bi_before_instr(I),
1376 R[i]);
1377 }
1378
1379 ctx->ip += instr_cycles(I);
1380 }
1381
1382 assert(next_use_cursor == 0 && "exactly sized");
1383
1384 int i;
1385 BITSET_FOREACH_SET(i, ctx->W, ctx->n_alloc)
1386 sblock->W_exit[sblock->nW_exit++] = i;
1387
1388 unsigned nS = __bitset_count(ctx->S, BITSET_WORDS(ctx->n_alloc));
1389 sblock->S_exit = ralloc_array(ctx->memctx, unsigned, nS);
1390
1391 BITSET_FOREACH_SET(i, ctx->S, ctx->n_alloc)
1392 sblock->S_exit[sblock->nS_exit++] = i;
1393
1394 assert(nS == sblock->nS_exit);
1395 util_dynarray_fini(&local_next_ip);
1396 }
1397
1398 void
1399 bi_record_sizes(bi_context *ctx, uint32_t *sizes)
1400 {
1401 memset(sizes, 0, ctx->ssa_alloc);
1402
1403 bool progress = true;
1404
1405 while (progress) {
1406 progress = false;
1407
1408 bi_foreach_instr_global(ctx, I) {
1409 if (I->nr_dests == 0 || I->dest[0].type != BI_INDEX_NORMAL)
1410 continue;
1411
1412 bi_foreach_ssa_dest(I, d) {
1413 const uint32_t old_size = sizes[I->dest[d].value];
1414 uint32_t new_size = old_size;
1415
1416 switch (I->op) {
1417 case BI_OPCODE_PHI:
1418 case BI_OPCODE_MEMMOV:
1419 /* Output size determined by the inputs. */
1420 bi_foreach_src(I, s) {
1421 switch (I->src[s].type) {
1422 case BI_INDEX_NORMAL:
1423 new_size = MAX2(new_size, sizes[I->src[s].value]);
1424 break;
1425 case BI_INDEX_CONSTANT:
1426 case BI_INDEX_FAU:
1427 new_size = 1;
1428 break;
1429 default:
1430 UNREACHABLE("invalid index type for size calculation\n");
1431 }
1432 }
1433 break;
1434 default:
1435 /* Output size independent of the inputs. */
1436 new_size = bi_count_write_registers(I, d);
1437 break;
1438 }
1439
1440 /* Need to continue if there was a change or the dst is not yet
1441 * defined. */
1442 progress |= new_size == 0 || old_size != new_size;
1443 sizes[I->dest[d].value] = new_size;
1444 }
1445 }
1446 }
1447 }
1448
1449 static void
1450 record_ssa_defs(bi_context *ctx, bi_instr **defs, bi_block **blocks)
1451 {
1452 bi_foreach_block(ctx, b) {
1453 bi_foreach_instr_in_block(b, I) {
1454 if (I->nr_dests > 0 && bi_is_ssa(I->dest[0])) {
1455 for (uint32_t vi = 0; vi < I->nr_dests; ++vi) {
1456 const uint32_t v = I->dest[vi].value;
1457
1458 if (defs[v] != NULL || blocks[v] != NULL) {
1459 bi_print_instr(I, stderr);
1460 fprintf(stderr, "before\n");
1461 bi_print_instr(defs[v], stderr);
1462 }
1463 assert(defs[v] == NULL && "violating SSA");
1464 assert(blocks[v] == NULL && "violating SSA");
1465 defs[v] = I;
1466 blocks[v] = b;
1467 }
1468 }
1469 }
1470 }
1471 }
1472
1473 /*
1474 * spill to keep the number of registers in use
1475 * below `k`
1476 * returns number of registers spilled
1477 */
1478
1479 void
1480 bi_spill_ssa(bi_context *ctx, unsigned k)
1481 {
1482 void *memctx = ralloc_context(NULL);
1483
1484 dist_t *next_uses = rzalloc_array(memctx, dist_t, ctx->ssa_alloc);
1485 bi_instr **remat = rzalloc_array(memctx, bi_instr *, ctx->ssa_alloc);
1486 uint32_t *sizes = rzalloc_array(memctx, uint32_t, ctx->ssa_alloc);
1487
1488 /* now record instructions that can be easily re-materialized */
1489 bi_foreach_instr_global(ctx, I) {
1490 if (I->nr_dests == 0 || I->dest[0].type != BI_INDEX_NORMAL)
1491 continue;
1492 unsigned idx = I->dest[0].value;
1493 if (can_remat(I))
1494 remat[idx] = I;
1495 }
1496
1497 bi_record_sizes(ctx, sizes);
1498
1499 struct spill_block *blocks =
1500 rzalloc_array(memctx, struct spill_block, ctx->num_blocks);
1501
1502 /* Step 1. Compute global next-use distances */
1503 global_next_use_distances(ctx, memctx, blocks);
1504 validate_next_use_info(ctx, blocks);
1505
1506 /* Reserve a memory variable for every regular variable */
1507 const uint32_t n = ctx->ssa_alloc;
1508 ctx->ssa_alloc *= 2;
1509
1510 /* we may need to allocate some temporaries for spilling PHIs, hence the max_temps */
1511 BITSET_WORD *W = ralloc_array(memctx, BITSET_WORD, BITSET_WORDS(n));
1512 BITSET_WORD *S = ralloc_array(memctx, BITSET_WORD, BITSET_WORDS(n));
1513 uint32_t *spill_map = ralloc_array(memctx, uint32_t, n);
1514 uint32_t *mem_map = ralloc_array(memctx, uint32_t, n);
1515 BITSET_WORD *spill_map_store = BITSET_RZALLOC(memctx, n);
1516
1517 bi_instr **ssa_defs = rzalloc_array(memctx, bi_instr *, n);
1518 bi_block **ssa_def_blocks = rzalloc_array(memctx, bi_block *, n);
1519 record_ssa_defs(ctx, ssa_defs, ssa_def_blocks);
1520
1521 /* initialize to FFFFFFFF */
1522 memset(spill_map, 0xff, sizeof(uint32_t) * n);
1523 memset(mem_map, 0xff, sizeof(uint32_t) * n);
1524
1525 /* Required for finding blocks belonging to loops. */
1526 bi_calc_dominance(ctx);
1527
1528 bi_foreach_block(ctx, block) {
1529 memset(W, 0, BITSET_BYTES(n));
1530 memset(S, 0, BITSET_BYTES(n));
1531
1532 struct spill_ctx sctx = {
1533 .memctx = memctx,
1534 .shader = ctx,
1535 .n_alloc = n,
1536 .remat = remat,
1537 .next_uses = next_uses,
1538 .block = block,
1539 .blocks = blocks,
1540 .k = k,
1541 .W = W,
1542 .S = S,
1543 .size = sizes,
1544 .spill_max = 2*n,
1545 .spill_base = n,
1546 .spill_map = spill_map,
1547 .spill_bytes = 0,
1548 .spill_map_store = spill_map_store,
1549 .mem_map = mem_map,
1550 .ssa_defs = ssa_defs,
1551 .ssa_def_blocks = ssa_def_blocks,
1552 .arch = ctx->arch,
1553 .cmp_dist_min_remat_dst = 0,
1554 };
1555
1556 compute_w_entry(&sctx);
1557 compute_s_entry(&sctx);
1558 min_algorithm(&sctx);
1559 }
1560
1561 /* Now that all blocks are processed separately, stitch it together */
1562 bi_foreach_block(ctx, block) {
1563 struct spill_ctx sctx = {
1564 .memctx = memctx,
1565 .shader = ctx,
1566 .n_alloc = n,
1567 .remat = remat,
1568 .block = block,
1569 .blocks = blocks,
1570 .k = k,
1571 .W = W,
1572 .S = S,
1573 .size = sizes,
1574 .spill_max = 2*n,
1575 .spill_base = n,
1576 .spill_map = spill_map,
1577 .spill_bytes = 0,
1578 .spill_map_store = spill_map_store,
1579 .mem_map = mem_map,
1580 .ssa_defs = ssa_defs,
1581 .ssa_def_blocks = ssa_def_blocks,
1582 .arch = ctx->arch,
1583 .cmp_dist_min_remat_dst = 0,
1584 };
1585
1586 bi_foreach_predecessor(block, pred) {
1587 /* After spilling phi sources, insert coupling code */
1588 insert_coupling_code(&sctx, *pred, block);
1589 }
1590 }
1591
1592 ralloc_free(memctx);
1593
1594 bi_repair_ssa(ctx);
1595 }