From 5baf663a0cdc8343eecd8e56a23dc8b8531d6b4f Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 19:47:28 -0500 Subject: [PATCH 1/5] asahi/compiler: use dense block gen/kill bitsets for multi-block liveness Precompute per-block dense gen/kill bitsets once in agx_compute_liveness() when num_blocks * BITSET_WORDS(alloc) <= 262144, solve the fixed-point with word-wide bitset operations instead of per-iteration sparse bitset dup/merge and repeated instruction walks, then run a single final backwards pass per block to mark src.kill and populate block->live_{in,out}. Verified bit-identical with a debug assert comparing the final backwards pass against the solved live_in bitset. Signed-off-by: Diljit Singh --- src/asahi/compiler/agx_liveness.c | 162 +++++++++++++++++++++++++++++- 1 file changed, 158 insertions(+), 4 deletions(-) diff --git a/src/asahi/compiler/agx_liveness.c b/src/asahi/compiler/agx_liveness.c index 269fc4efb712..71e6ffaf2880 100644 --- a/src/asahi/compiler/agx_liveness.c +++ b/src/asahi/compiler/agx_liveness.c @@ -53,16 +53,16 @@ liveness_ins_update_dense(BITSET_WORD *live, agx_instr *I) void agx_compute_liveness(agx_context *ctx) { - BITSET_DECLARE(stack_live, 4096); - BITSET_WORD *dense_live = - ctx->alloc <= 4096 ? stack_live : BITSET_CALLOC(ctx->alloc); - /* Fast path for single-block shaders without self-loops: one dense * backwards pass with no worklist or sparse bitset churn. */ if (list_is_singular(&ctx->blocks)) { agx_block *blk = list_first_entry(&ctx->blocks, agx_block, link); if (util_dynarray_num_elements(&blk->predecessors, agx_block *) == 0) { + BITSET_DECLARE(stack_live, 4096); + BITSET_WORD *dense_live = + ctx->alloc <= 4096 ? stack_live : BITSET_CALLOC(ctx->alloc); + u_sparse_bitset_free(&blk->live_in); u_sparse_bitset_free(&blk->live_out); u_sparse_bitset_init(&blk->live_in, ctx->alloc, blk); @@ -86,6 +86,160 @@ agx_compute_liveness(agx_context *ctx) } } + /* Fast path when the dense block x SSA bitset slab stays bounded (~4 MiB + * at the 262144-word cap): precompute per-block gen/kill once, solve the + * fixed-point with word-wide bitset ops (no per-iteration sparse bitset + * dup/merge/free or repeated instruction walks), then run a single final + * backwards pass per block to mark src.kill and populate sparse live sets. + */ + const unsigned words = BITSET_WORDS(ctx->alloc); + if (ctx->num_blocks > 0 && ctx->alloc > 0 && + (uint64_t)ctx->num_blocks * words <= 262144) { + bool valid_indices = true; + bool *seen = calloc(ctx->num_blocks, sizeof(bool)); + if (seen) { + agx_foreach_block(ctx, block) { + if (block->index >= ctx->num_blocks || seen[block->index]) { + valid_indices = false; + break; + } + seen[block->index] = true; + } + free(seen); + } else { + valid_indices = false; + } + + if (valid_indices) { + const size_t total = (size_t)ctx->num_blocks * words; + BITSET_WORD *slab = calloc(4 * total + words, sizeof(BITSET_WORD)); + bool *has_phi = calloc(ctx->num_blocks, sizeof(bool)); + if (slab && has_phi) { + BITSET_WORD *gen = slab; + BITSET_WORD *kill = gen + total; + BITSET_WORD *live_in = kill + total; + BITSET_WORD *live_out = live_in + total; + BITSET_WORD *tmp = live_out + total; + + u_worklist worklist; + u_worklist_init(&worklist, ctx->num_blocks, NULL); + + agx_foreach_block(ctx, block) { + const unsigned b = block->index; + BITSET_WORD *gb = gen + (size_t)b * words; + BITSET_WORD *kb = kill + (size_t)b * words; + + agx_foreach_instr_in_block_rev(block, I) { + if (I->op == AGX_OPCODE_PHI) { + has_phi[b] = true; + continue; + } + agx_foreach_ssa_dest(I, d) { + const unsigned v = I->dest[d].value; + BITSET_CLEAR(gb, v); + BITSET_SET(kb, v); + } + agx_foreach_ssa_src(I, s) { + const unsigned v = I->src[s].value; + BITSET_SET(gb, v); + BITSET_CLEAR(kb, v); + } + } + + agx_worklist_push_head(&worklist, block); + } + + while (!u_worklist_is_empty(&worklist)) { + agx_block *blk = agx_worklist_pop_head(&worklist); + const unsigned b = blk->index; + const BITSET_WORD *gb = gen + (size_t)b * words; + const BITSET_WORD *kb = kill + (size_t)b * words; + BITSET_WORD *in_b = live_in + (size_t)b * words; + const BITSET_WORD *out_b = live_out + (size_t)b * words; + + for (unsigned w = 0; w < words; ++w) + in_b[w] = (out_b[w] & ~kb[w]) | gb[w]; + + if (has_phi[b]) { + memcpy(tmp, in_b, words * sizeof(BITSET_WORD)); + agx_foreach_phi_in_block(blk, phi) { + assert(phi->dest[0].type == AGX_INDEX_NORMAL); + BITSET_CLEAR(tmp, phi->dest[0].value); + } + } + + const BITSET_WORD *prop = has_phi[b] ? tmp : in_b; + agx_foreach_predecessor(blk, pred) { + const unsigned p = (*pred)->index; + BITSET_WORD *out_p = live_out + (size_t)p * words; + bool changed = false; + + for (unsigned w = 0; w < words; ++w) { + BITSET_WORD old = out_p[w]; + BITSET_WORD nw = old | prop[w]; + if (nw != old) { + out_p[w] = nw; + changed = true; + } + } + + if (has_phi[b]) { + unsigned pred_idx = agx_predecessor_index(blk, *pred); + agx_foreach_phi_in_block(blk, phi) { + agx_index operand = phi->src[pred_idx]; + if (operand.type == AGX_INDEX_NORMAL) { + if (!BITSET_TEST(out_p, operand.value)) { + BITSET_SET(out_p, operand.value); + changed = true; + } + phi->src[pred_idx].kill = false; + } + } + } + + if (changed) + agx_worklist_push_tail(&worklist, *pred); + } + } + + agx_foreach_block(ctx, block) { + const unsigned b = block->index; + const BITSET_WORD *in_b = live_in + (size_t)b * words; + const BITSET_WORD *out_b = live_out + (size_t)b * words; + + u_sparse_bitset_free(&block->live_in); + u_sparse_bitset_free(&block->live_out); + u_sparse_bitset_init(&block->live_in, ctx->alloc, block); + u_sparse_bitset_init(&block->live_out, ctx->alloc, block); + + memcpy(tmp, out_b, words * sizeof(BITSET_WORD)); + agx_foreach_instr_in_block_rev(block, I) { + if (I->op != AGX_OPCODE_PHI) + liveness_ins_update_dense(tmp, I); + } + assert(memcmp(tmp, in_b, words * sizeof(BITSET_WORD)) == 0); + + unsigned v; + BITSET_FOREACH_SET(v, in_b, ctx->alloc) + u_sparse_bitset_set(&block->live_in, v); + BITSET_FOREACH_SET(v, out_b, ctx->alloc) + u_sparse_bitset_set(&block->live_out, v); + } + + u_worklist_fini(&worklist); + free(slab); + free(has_phi); + return; + } + free(slab); + free(has_phi); + } + } + + BITSET_DECLARE(stack_live, 4096); + BITSET_WORD *dense_live = + ctx->alloc <= 4096 ? stack_live : BITSET_CALLOC(ctx->alloc); + u_worklist worklist; u_worklist_init(&worklist, ctx->num_blocks, NULL); From bf21a1a9cfad0f23950dec756a41c449da32df9a Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 19:47:28 -0500 Subject: [PATCH 2/5] asahi/compiler: precompute 256-bit block gen/kill summaries in register cache liveness Precompute per-block 256-bit register gen/kill summaries once for blocks without fused breaks in postra_liveness() and physical_liveness(), replacing repeated per-iteration reverse instruction walks with word-wide bitset updates while falling back to the per-instruction walk for fused-break blocks or non-unique block indices. Signed-off-by: Diljit Singh --- src/asahi/compiler/agx_opt_register_cache.c | 103 ++++++++++++++++---- 1 file changed, 86 insertions(+), 17 deletions(-) diff --git a/src/asahi/compiler/agx_opt_register_cache.c b/src/asahi/compiler/agx_opt_register_cache.c index c916fea6bbaf..7f2cd503226d 100644 --- a/src/asahi/compiler/agx_opt_register_cache.c +++ b/src/asahi/compiler/agx_opt_register_cache.c @@ -125,6 +125,31 @@ postra_liveness_ins(BITSET_WORD *live, agx_instr *I) } } +static bool +postra_block_gen_kill(agx_block *block, BITSET_WORD *gen, BITSET_WORD *kill) +{ + bool has_fused_break = false; + agx_foreach_instr_in_block_rev(block, I) { + if (fused_break_target(I)) + has_fused_break = true; + + agx_foreach_reg_dest(I, d) { + unsigned reg = I->dest[d].value; + unsigned count = agx_index_size_16(I->dest[d]); + BITSET_CLEAR_COUNT(gen, reg, count); + BITSET_SET_COUNT(kill, reg, count); + } + + agx_foreach_reg_src(I, s) { + unsigned reg = I->src[s].value; + unsigned count = agx_index_size_16(I->src[s]); + BITSET_SET_COUNT(gen, reg, count); + BITSET_CLEAR_COUNT(kill, reg, count); + } + } + return has_fused_break; +} + /* * Globally, liveness analysis uses a fixed-point algorithm based on a * worklist. We initialize a work list with the exit block. We iterate the work @@ -152,14 +177,32 @@ postra_liveness(agx_context *ctx) u_worklist worklist; agx_worklist_init(ctx, &worklist); + const unsigned n = ctx->num_blocks; + const unsigned rw = BITSET_WORDS(AGX_NUM_REGS); + BITSET_WORD *gen = n ? calloc((size_t)n * rw, sizeof(BITSET_WORD)) : NULL; + BITSET_WORD *kill = n ? calloc((size_t)n * rw, sizeof(BITSET_WORD)) : NULL; + bool *blk_fused = n ? calloc(n, sizeof(bool)) : NULL; + bool *blk_seen = n ? calloc(n, sizeof(bool)) : NULL; + bool use_summary = gen && kill && blk_fused && blk_seen; + bool fused_breaks = false; agx_foreach_block(ctx, block) { BITSET_ZERO(block->reg_live_in); BITSET_ZERO(block->reg_live_out); - agx_foreach_instr_in_block(block, I) - fused_breaks |= fused_break_target(I) != NULL; + if (use_summary && block->index < n && !blk_seen[block->index]) { + blk_seen[block->index] = true; + bool fb = postra_block_gen_kill(block, gen + (size_t)block->index * rw, + kill + (size_t)block->index * rw); + blk_fused[block->index] = fb; + fused_breaks |= fb; + } else { + use_summary = false; + agx_foreach_instr_in_block(block, I) + fused_breaks |= fused_break_target(I) != NULL; + } } + free(blk_seen); /* A fused break's block is not a predecessor of its target, so with * fused breaks the whole analysis repeats until nothing changes. */ @@ -179,14 +222,21 @@ postra_liveness(agx_context *ctx) } BITSET_DECLARE(live, AGX_NUM_REGS); - memcpy(live, blk->reg_live_out, sizeof(live)); + if (use_summary && !blk_fused[blk->index]) { + const BITSET_WORD *gb = gen + (size_t)blk->index * rw; + const BITSET_WORD *kb = kill + (size_t)blk->index * rw; + for (unsigned w = 0; w < rw; ++w) + live[w] = (blk->reg_live_out[w] & ~kb[w]) | gb[w]; + } else { + memcpy(live, blk->reg_live_out, sizeof(live)); - agx_foreach_instr_in_block_rev(blk, ins) { - agx_block *target = fused_break_target(ins); - if (target) - BITSET_OR(live, live, target->reg_live_in); + agx_foreach_instr_in_block_rev(blk, ins) { + agx_block *target = fused_break_target(ins); + if (target) + BITSET_OR(live, live, target->reg_live_in); - postra_liveness_ins(live, ins); + postra_liveness_ins(live, ins); + } } if (BITSET_EQUAL(blk->reg_live_in, live)) @@ -201,6 +251,9 @@ postra_liveness(agx_context *ctx) } } while (fused_breaks && changed); + free(gen); + free(kill); + free(blk_fused); u_worklist_fini(&worklist); } @@ -253,13 +306,16 @@ physical_liveness(agx_context *ctx, struct physical_live *p) unsigned *loop_end = calloc(n, sizeof(unsigned)); BITSET_WORD *pending = calloc((size_t)n * bw, sizeof(BITSET_WORD)); BITSET_WORD *live_in = calloc((size_t)n * rw, sizeof(BITSET_WORD)); + BITSET_WORD *gen = calloc((size_t)n * rw, sizeof(BITSET_WORD)); + BITSET_WORD *kill = calloc((size_t)n * rw, sizeof(BITSET_WORD)); + bool *blk_fused = calloc(n, sizeof(bool)); p->live_in = live_in; p->words = rw; p->pos = calloc(n, sizeof(unsigned)); p->inactive = calloc((size_t)n * rw, sizeof(BITSET_WORD)); p->live_out = calloc((size_t)n * rw, sizeof(BITSET_WORD)); - bool ok = order && loop_end && pending && live_in && p->pos && p->inactive && - p->live_out; + bool ok = order && loop_end && pending && live_in && gen && kill && + blk_fused && p->pos && p->inactive && p->live_out; unsigned count = 0; if (ok) { @@ -269,6 +325,9 @@ physical_liveness(agx_context *ctx, struct physical_live *p) break; } order[count] = block; + blk_fused[count] = + postra_block_gen_kill(block, gen + (size_t)count * rw, + kill + (size_t)count * rw); p->pos[block->index] = count++; } } @@ -344,14 +403,21 @@ physical_liveness(agx_context *ctx, struct physical_live *p) } memcpy(out, live, sizeof(live)); - agx_foreach_instr_in_block_rev(block, I) { - agx_block *target = fused_break_target(I); - if (target) { - __bitset_or(live, live, - live_in + (size_t)p->pos[target->index] * rw, rw); + if (!blk_fused[a]) { + const BITSET_WORD *gb = gen + (size_t)a * rw; + const BITSET_WORD *kb = kill + (size_t)a * rw; + for (unsigned w = 0; w < rw; ++w) + live[w] = (out[w] & ~kb[w]) | gb[w] | inactive[w]; + } else { + agx_foreach_instr_in_block_rev(block, I) { + agx_block *target = fused_break_target(I); + if (target) { + __bitset_or(live, live, + live_in + (size_t)p->pos[target->index] * rw, rw); + } + postra_liveness_ins(live, I); + __bitset_or(live, live, inactive, rw); } - postra_liveness_ins(live, I); - __bitset_or(live, live, inactive, rw); } BITSET_WORD *in = live_in + (size_t)a * rw; @@ -366,6 +432,9 @@ physical_liveness(agx_context *ctx, struct physical_live *p) free(order); free(loop_end); free(pending); + free(gen); + free(kill); + free(blk_fused); if (!ok) physical_live_free(p); return ok; From 9219018d1c6f52149d75d854114f17686f9612df Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 19:47:28 -0500 Subject: [PATCH 3/5] asahi/compiler: avoid heap allocations and eager agx_values_read in agx_calc_register_demand Use compact uint8_t stack arrays (2 KiB total) for widths/classes in agx_calc_register_demand() when ctx->alloc <= 1024 and compute agx_values_read(ctx) lazily only when an AGX_OPCODE_ENTER_QUERY_M5 instruction is actually encountered. Signed-off-by: Diljit Singh --- src/asahi/compiler/agx_register_allocate.c | 29 ++++++++++++++++------ 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/src/asahi/compiler/agx_register_allocate.c b/src/asahi/compiler/agx_register_allocate.c index e56142be26fa..29d723712186 100644 --- a/src/asahi/compiler/agx_register_allocate.c +++ b/src/asahi/compiler/agx_register_allocate.c @@ -267,9 +267,18 @@ agx_calc_register_demand(agx_context *ctx, bool remat) agx_print_shader(ctx, stdout); } - uint8_t *widths = calloc(ctx->alloc, sizeof(uint8_t)); - enum ra_class *classes = calloc(ctx->alloc, sizeof(enum ra_class)); - BITSET_WORD *dest_read = agx_values_read(ctx); + static_assert(RA_CLASSES <= UINT8_MAX, "ra_class fits in uint8_t"); + uint8_t stack_widths[1024]; + uint8_t stack_classes[1024]; + uint8_t *widths = + ctx->alloc <= 1024 ? stack_widths : calloc(ctx->alloc, sizeof(uint8_t)); + uint8_t *classes = + ctx->alloc <= 1024 ? stack_classes : calloc(ctx->alloc, sizeof(uint8_t)); + if (ctx->alloc <= 1024) { + memset(widths, 0, ctx->alloc * sizeof(uint8_t)); + memset(classes, 0, ctx->alloc * sizeof(uint8_t)); + } + BITSET_WORD *dest_read = NULL; agx_foreach_instr_global(ctx, I) { if (remat && (I->op == AGX_OPCODE_MOV_IMM || @@ -376,8 +385,12 @@ agx_calc_register_demand(agx_context *ctx, bool remat) late_kill_count += (pot_width - real_width); /* An unread M5 query-entry result dies right after its write. */ - if (I->op == AGX_OPCODE_ENTER_QUERY_M5 && !BITSET_TEST(dest_read, I->dest[d].value)) - late_kill_count += real_width; + if (I->op == AGX_OPCODE_ENTER_QUERY_M5) { + if (!dest_read) + dest_read = agx_values_read(ctx); + if (!BITSET_TEST(dest_read, I->dest[d].value)) + late_kill_count += real_width; + } } max_demand = MAX2(demand, max_demand); @@ -387,8 +400,10 @@ agx_calc_register_demand(agx_context *ctx, bool remat) } free(dest_read); - free(widths); - free(classes); + if (widths != stack_widths) + free(widths); + if (classes != stack_classes) + free(classes); return max_demand; } From 50999a7e650c04721595bfeed8bff4f769af71c0 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 20:14:21 -0500 Subject: [PATCH 4/5] asahi/compiler: use dirty-pass bitmask in agx_optimize_loop_nir and gate redundant late CSE/DCE Track pending passes with a dirty-pass bitmask in agx_optimize_loop_nir(), skipping loop-unroll on loop-free shaders and CF/phi passes on single-block shaders, and narrowing DCE's wake set to passes that can react to dead instruction removal. Also gate redundant pre-fusion and post-optimize nir_opt_cse/nir_opt_dce cleanups in agx_optimize_nir() and agx_compile_shader_nir_internal() on upstream pass progress, preserving the original post-fusion late_progress condition. Signed-off-by: Diljit Singh --- src/asahi/compiler/agx_compile.c | 205 ++++++++++++++++++++++--------- 1 file changed, 150 insertions(+), 55 deletions(-) diff --git a/src/asahi/compiler/agx_compile.c b/src/asahi/compiler/agx_compile.c index c31ac7e34a49..6c690544b3aa 100644 --- a/src/asahi/compiler/agx_compile.c +++ b/src/asahi/compiler/agx_compile.c @@ -9896,68 +9896,134 @@ agx_optimize_loop_nir(nir_shader *nir, bool m5, bool g17p) .expensive_limit = g17p ? AGX_G17P_EXPENSIVE_FLATTEN_LIMIT : 0, }; - /* Exact circular fixed-point over the 12-pass cycle. Single-pass idempotent - * passes (copy_prop, dce, cse, constant_folding) only require the other 11 - * passes to observe no progress before stopping; all other passes require a - * full 12-pass cycle including themselves. */ - enum { NUM_PASSES = 12 }; - int remaining = NUM_PASSES; - for (int p = 0; remaining > 0; p = (p + 1) % NUM_PASSES) { + /* Track which passes may still find work via a bitmask. Skip passes that + * cannot make progress on loop-free or single-block shaders, and only wake + * passes that can react to a given pass's changes: + * - idempotent passes (copy_prop, cse, constant_folding) wake all other + * active passes; + * - dce only deletes unused instructions, so it cannot create new copy-prop, + * CSE, constant-folding, undef, or remove-phi opportunities; it wakes only + * dead_cf, peephole_select, phi_precision, fold_d3d, algebraic, and + * loop_unroll; + * - all other passes wake the entire active set. + */ + bool has_loops = false; + bool single_block = true; + nir_foreach_function_impl(impl, nir) { + if (!exec_list_is_singular(&impl->body)) + single_block = false; + foreach_list_typed(nir_cf_node, node, node, &impl->body) { + if (node->type == nir_cf_node_loop) { + has_loops = true; + single_block = false; + break; + } else if (node->type == nir_cf_node_if) { + single_block = false; + nir_foreach_block(blk, impl) { + for (nir_cf_node *p = blk->cf_node.parent; p; p = p->parent) { + if (p->type == nir_cf_node_loop) { + has_loops = true; + break; + } + } + if (has_loops) + break; + } + break; + } + } + } + + enum { + OPT_COPY_PROP = 0, + OPT_REMOVE_PHIS = 1, + OPT_DCE = 2, + OPT_DEAD_CF = 3, + OPT_CSE = 4, + OPT_PEEPHOLE_SELECT = 5, + OPT_PHI_PRECISION = 6, + OPT_FOLD_D3D = 7, + OPT_ALGEBRAIC = 8, + OPT_CONSTANT_FOLDING = 9, + OPT_UNDEF = 10, + OPT_LOOP_UNROLL = 11, + NUM_PASSES = 12, + }; + + uint32_t active = (1u << NUM_PASSES) - 1u; + if (!m5) + active &= ~(1u << OPT_FOLD_D3D); + if (!has_loops) + active &= ~(1u << OPT_LOOP_UNROLL); + if (single_block) + active &= ~((1u << OPT_REMOVE_PHIS) | (1u << OPT_DEAD_CF) | + (1u << OPT_PEEPHOLE_SELECT) | (1u << OPT_PHI_PRECISION) | + (1u << OPT_LOOP_UNROLL)); + + const uint32_t dce_wake = + ((1u << OPT_DEAD_CF) | (1u << OPT_PEEPHOLE_SELECT) | + (1u << OPT_PHI_PRECISION) | (1u << OPT_FOLD_D3D) | + (1u << OPT_ALGEBRAIC) | (1u << OPT_LOOP_UNROLL)) & + active; + + uint32_t pending = active; + for (int p = 0; pending != 0; p = (p + 1) % NUM_PASSES) { + if (!(pending & (1u << p))) + continue; + pending &= ~(1u << p); + bool progress = false; - bool idempotent = false; + uint32_t wake = active; switch (p) { - case 0: + case OPT_COPY_PROP: NIR_PASS(progress, nir, nir_opt_copy_prop); - idempotent = true; + wake = active & ~(1u << OPT_COPY_PROP); break; - case 1: + case OPT_REMOVE_PHIS: NIR_PASS(progress, nir, nir_opt_remove_phis); break; - case 2: + case OPT_DCE: NIR_PASS(progress, nir, nir_opt_dce); - idempotent = true; + wake = dce_wake; break; - case 3: + case OPT_DEAD_CF: NIR_PASS(progress, nir, nir_opt_dead_cf); break; - case 4: + case OPT_CSE: NIR_PASS(progress, nir, nir_opt_cse); - idempotent = true; + wake = active & ~(1u << OPT_CSE); break; - case 5: + case OPT_PEEPHOLE_SELECT: NIR_PASS(progress, nir, nir_opt_peephole_select, &peephole_select_options); break; - case 6: + case OPT_PHI_PRECISION: NIR_PASS(progress, nir, nir_opt_phi_precision); break; - case 7: + case OPT_FOLD_D3D: /* The M5 conversion has D3D's saturating, NaN-to-zero semantics. * Fold before nir_opt_algebraic distributes a following add into the * clamping selects. */ - if (m5) - NIR_PASS(progress, nir, agx_nir_fold_d3d_float_to_int); + NIR_PASS(progress, nir, agx_nir_fold_d3d_float_to_int); break; - case 8: + case OPT_ALGEBRAIC: NIR_PASS(progress, nir, nir_opt_algebraic); break; - case 9: + case OPT_CONSTANT_FOLDING: NIR_PASS(progress, nir, nir_opt_constant_folding); - idempotent = true; + wake = active & ~(1u << OPT_CONSTANT_FOLDING); break; - case 10: + case OPT_UNDEF: NIR_PASS(progress, nir, nir_opt_undef); break; - case 11: + case OPT_LOOP_UNROLL: NIR_PASS(progress, nir, nir_opt_loop_unroll); break; } if (progress) - remaining = idempotent ? (NUM_PASSES - 1) : NUM_PASSES; - else - remaining--; + pending |= wake; } nir->options = saved_options; } @@ -10503,6 +10569,7 @@ agx_optimize_nir(nir_shader *nir, bool soft_fault, bool uniform_atomics, .expensive_limit = g17p ? AGX_G17P_EXPENSIVE_FLATTEN_LIMIT : 0, }; bool progress = false; + bool pre_fuse_dirty = false; if (pre_preamble_optimized) { if (epilog_has_alu) { @@ -10550,8 +10617,9 @@ agx_optimize_nir(nir_shader *nir, bool soft_fault, bool uniform_atomics, /* If soft fault is enabled, we can freely speculate everything. That lets us * peephole select and form preambles more aggressively. */ + bool spec_progress = false; if (soft_fault) { - NIR_PASS(_, nir, nir_shader_instructions_pass, set_speculate, + NIR_PASS(spec_progress, nir, nir_shader_instructions_pass, set_speculate, nir_metadata_control_flow, NULL); } @@ -10568,9 +10636,9 @@ agx_optimize_nir(nir_shader *nir, bool soft_fault, bool uniform_atomics, * keeps: on M5 an if costs five control-flow instructions and a wait for * every load in flight. Flattening one can expose another around it. * Not on G18G, which compiles as AGX3C with emit_agx3d (g18_scans). */ + bool any_flattened = false; if (m5 && !g18_scans) { bool flattened; - bool any_flattened = false; do { flattened = false; NIR_PASS(flattened, nir, agx_nir_opt_flatten_loads, 64, 4); @@ -10716,26 +10784,37 @@ agx_optimize_nir(nir_shader *nir, bool soft_fault, bool uniform_atomics, } while (alg_progress); } + pre_fuse_dirty = + spec_progress || any_flattened || addr_progress || sub_progress || + pre_alg_progress || progress; + /* Reassociate before forming preambles because it makes preambles more * effective. Clean up after. On M5, also order the loop-invariant terms of * a chain in a loop first, so accumulations of per-iteration constants * (robustness loops add the same size queries every iteration) are summed * once in the preamble instead of once per term and iteration. + * + * When nir_opt_reassociate_loop() returns true, its final cleanup loop ran + * algebraic/constant-folding/copy-prop/CSE/DCE to a fixpoint, leaving the + * shader CSE/DCE-clean on return. */ - nir_opt_reassociate_loop( - nir, nir_reassociate_scalar_math | nir_reassociate_cse_heuristic | - (m5 ? nir_reassociate_loop_invariant : 0)); + if (nir_opt_reassociate_loop( + nir, nir_reassociate_scalar_math | nir_reassociate_cse_heuristic | + (m5 ? nir_reassociate_loop_invariant : 0))) + pre_fuse_dirty = false; /* Lower fmin/fmax before optimizing preambles so we can see across uniform * expressions. Do it after nir_opt_reassociate because nir_opt_reassociate * should work on unlowered fmin/fmax. */ - NIR_PASS(_, nir, agx_nir_lower_fminmax, g17p || m5); + NIR_PASS(pre_fuse_dirty, nir, agx_nir_lower_fminmax, g17p || m5); if (pre_preamble_blob) nir_serialize(pre_preamble_blob, nir, false); pre_preamble: + if (pre_preamble_optimized) + pre_fuse_dirty = true; /* AGX_G17P_DISCARD_WORD: reduce one-sample coverage-update sources to bit * 0 after the algebraic loops and right before preamble formation, so the * uniform `tests_zs & 1` is hoisted. nir_opt_algebraic would otherwise @@ -10750,6 +10829,7 @@ agx_optimize_nir(nir_shader *nir, bool soft_fault, bool uniform_atomics, else NIR_PASS(word, nir, agx_g17p_discard_word); if (word) { + pre_fuse_dirty = true; NIR_PASS(_, nir, nir_opt_constant_folding); NIR_PASS(_, nir, nir_opt_dce); } @@ -10779,8 +10859,8 @@ agx_optimize_nir(nir_shader *nir, bool soft_fault, bool uniform_atomics, if (sizes[2] == 0) sizes[2]++; - NIR_PASS(_, nir, agx_nir_opt_preamble, sizes, byte_indices || m5, m5, - &peephole_select_options); + NIR_PASS(pre_fuse_dirty, nir, agx_nir_opt_preamble, sizes, + byte_indices || m5, m5, &peephole_select_options); *preamble_size = sizes[0]; @@ -10793,6 +10873,7 @@ agx_optimize_nir(nir_shader *nir, bool soft_fault, bool uniform_atomics, bool words = false; NIR_PASS(words, nir, agx_nir_lower_word_bounds); if (words) { + pre_fuse_dirty = true; NIR_PASS(_, nir, nir_opt_cse); NIR_PASS(_, nir, nir_opt_dce); } @@ -10804,6 +10885,7 @@ agx_optimize_nir(nir_shader *nir, bool soft_fault, bool uniform_atomics, bool shared = false; NIR_PASS(shared, nir, agx_nir_share_bounds); if (shared) { + pre_fuse_dirty = true; NIR_PASS(_, nir, nir_opt_copy_prop); NIR_PASS(_, nir, nir_opt_dce); } @@ -10815,12 +10897,14 @@ agx_optimize_nir(nir_shader *nir, bool soft_fault, bool uniform_atomics, * results need. */ if (dma_key && dma_key->g17p_uniform_dma && agx3_nir_lower_uniform_dma(nir, dma_key, dma_info)) { + pre_fuse_dirty = true; NIR_PASS(_, nir, nir_opt_dce); agx_remove_empty_preamble(nir); } if (dma_key && dma_key->g17p_uniform_dma && nir->info.stage == MESA_SHADER_VERTEX) { + pre_fuse_dirty = true; agx3_inline_cheap_vertex_preamble(nir); NIR_PASS(_, nir, nir_opt_dce); } @@ -10843,20 +10927,22 @@ agx_optimize_nir(nir_shader *nir, bool soft_fault, bool uniform_atomics, * native 64-bit iadd/umul_2x32_64) recreated by nir_opt_algebraic after the * first nir_lower_int64 pass. */ - NIR_PASS(_, nir, nir_opt_peephole_select, &peephole_select_options); + NIR_PASS(pre_fuse_dirty, nir, nir_opt_peephole_select, + &peephole_select_options); if (byte_indices) - NIR_PASS(_, nir, agx_nir_scalarize_int64); - NIR_PASS(_, nir, nir_lower_int64); + NIR_PASS(pre_fuse_dirty, nir, agx_nir_scalarize_int64); + NIR_PASS(pre_fuse_dirty, nir, nir_lower_int64); /* Constant-program flags, now that their trivial branches are selects. */ if (byte_indices && !m5) - NIR_PASS(_, nir, agx_nir_export_select_flags_as_halves, true); + NIR_PASS(pre_fuse_dirty, nir, agx_nir_export_select_flags_as_halves, true); /* After the selects of trivial if-else statements exist. */ if (m5) { bool folded = false; NIR_PASS(folded, nir, agx_nir_m5_split_or_selects); if (folded) { + pre_fuse_dirty = true; NIR_PASS(_, nir, nir_opt_copy_prop); NIR_PASS(_, nir, nir_opt_dce); } @@ -10897,8 +10983,10 @@ agx_optimize_nir(nir_shader *nir, bool soft_fault, bool uniform_atomics, /* Fuse add/sub/multiplies/shifts after running opt_algebraic_late to fuse * isub but before shifts are lowered. */ - NIR_PASS(_, nir, nir_opt_dce); - NIR_PASS(_, nir, nir_opt_cse); + if (pre_fuse_dirty || late_progress) { + NIR_PASS(_, nir, nir_opt_dce); + NIR_PASS(_, nir, nir_opt_cse); + } do { progress = false; @@ -16675,10 +16763,11 @@ agx_compile_shader_nir_internal(nir_shader *nir, struct agx_shader_key *key, /* Safe uniform-load speculation and if/phi folding have now exposed * matching sample copies. Preserve early subset proofs through those * optimizations and promote them only after complete-sample coalescing. */ + bool post_opt_progress = false; if (key->dev.emit_agx3d && nir->info.stage == MESA_SHADER_FRAGMENT && (key->fs.nr_samples == 2 || key->fs.nr_samples == 4) && !key->fs.inside_sample_loop) - NIR_PASS(_, nir, agx_nir_coalesce_sample_mask_updates, + NIR_PASS(post_opt_progress, nir, agx_nir_coalesce_sample_mask_updates, key->fs.nr_samples); /* Inline blend/framebuffer-fetch shaders load the tilebuffer in the @@ -16688,33 +16777,36 @@ agx_compile_shader_nir_internal(nir_shader *nir, struct agx_shader_key *key, if (key->dev.encoding == AGX_ISA_ENCODING_AGX3C && key->dev.emit_agx3d && nir->info.stage == MESA_SHADER_FRAGMENT && (key->fs.nr_samples == 2 || key->fs.nr_samples == 4)) - NIR_PASS(_, nir, agx_nir_lower_g18_tile_samples, + NIR_PASS(post_opt_progress, nir, agx_nir_lower_g18_tile_samples, key->fs.nr_samples); if (is_agx3 && source_imul64) - NIR_PASS(_, nir, agx_nir_lower_imul64, m5_wide_product); + NIR_PASS(post_opt_progress, nir, agx_nir_lower_imul64, m5_wide_product); if (is_agx3) nir->options = original_options; /* AGX_G17P_UNIFORM_DMA: only when no preamble is formed. */ if (is_agx3 && key->g17p_uniform_dma && !form_preamble && - agx3_nir_lower_uniform_dma(nir, key, info)) + agx3_nir_lower_uniform_dma(nir, key, info)) { + post_opt_progress = true; NIR_PASS(_, nir, nir_opt_dce); + } /* Late NIR cleanup can remove main-program uses of values exported by * preamble extraction. Preserve their SSA uses inside the CProg, while * dropping writes to general uniform slots nobody reads anymore. */ if (is_agx3 && form_preamble) { - NIR_PASS(_, nir, agx_nir_remove_unused_preamble_exports, + NIR_PASS(post_opt_progress, nir, agx_nir_remove_unused_preamble_exports, key->reserved_preamble); - NIR_PASS(_, nir, agx_nir_coalesce_preamble_half_exports, + NIR_PASS(post_opt_progress, nir, agx_nir_coalesce_preamble_half_exports, key->reserved_preamble, info->push_count); - NIR_PASS(_, nir, nir_opt_dce); + if (post_opt_progress) + NIR_PASS(_, nir, nir_opt_dce); /* The launch's copies, if any, sit above every export. */ unsigned push_count = info->push_count; - NIR_PASS(_, nir, agx_nir_place_preamble_handles_low, + NIR_PASS(post_opt_progress, nir, agx_nir_place_preamble_handles_low, key->reserved_preamble, info->agx3_uniform_dma_count ? info->agx3_uniform_dma[0].dest : push_count, @@ -16725,6 +16817,7 @@ agx_compile_shader_nir_internal(nir_shader *nir, struct agx_shader_key *key, if (nir->info.stage == MESA_SHADER_FRAGMENT) { info->varyings.fs.nr_cf = key->fs.cf_base; assign_coefficient_regs(nir, &info->varyings.fs); + post_opt_progress = true; } if (key->dev.encoding == AGX_ISA_ENCODING_AGX3C) { @@ -16740,13 +16833,15 @@ agx_compile_shader_nir_internal(nir_shader *nir, struct agx_shader_key *key, regs = MIN2(regs, agx_max_registers_for_occupancy(threads)); } - NIR_PASS(_, nir, agx_nir_opt_licm, regs - 8); + NIR_PASS(post_opt_progress, nir, agx_nir_opt_licm, regs - 8); } if (is_agx3) { - NIR_PASS(_, nir, agx_nir_opt_shared_byte_offsets); - NIR_PASS(_, nir, nir_opt_cse); - NIR_PASS(_, nir, nir_opt_dce); + NIR_PASS(post_opt_progress, nir, agx_nir_opt_shared_byte_offsets); + bool cse_progress = false; + NIR_PASS(cse_progress, nir, nir_opt_cse); + if (cse_progress || post_opt_progress) + NIR_PASS(_, nir, nir_opt_dce); } if (key->dev.encoding == AGX_ISA_ENCODING_AGX3C) { From d6bf67186ced3af1dbaa0e66074ac4b8f7ceaee9 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 20:59:52 -0500 Subject: [PATCH 5/5] hk: pre-filter m5_merge_buffer_words before running pre-merge CSE Add a lightweight linear scan (m5_has_mergeable_buffer_words) checking for at least two reorderable 32-bit scalar load_global* intrinsics with alignment >= 4 in some basic block before running nir_opt_cse and m5_merge_buffer_words in hk_lower_nir(). This path is gated on global_loads.storage_result_select (agx_chip_g17p_or_m5) and global_loads.soft_fault, so it is unreachable on AGX2 (G13/G14) and G18G. This commit is not codegen-neutral on G17P: when a shader has no block with two mergeable scalar global loads, it skips the nir_opt_cse pass that previously ran immediately after nir_opt_sink and nir_opt_move. Skipping that post-sink/move CSE avoids re-hoisting expressions back across uses when nothing can merge. Measured across 83 gpubench-foz/vk-synth pipelines + 110 shader-db Fossilize DBs (assert build, vs parent 50999a7e650): - g13g (AGX2): 0 diffs across 88 + 1,311 shaders (unreachable) - g17s (AGX3C/M5): 0 diffs across 91 + 1,083 shaders - g18g (G18G): 0 diffs across 23 + 427 shaders (unreachable) - g17p (AGX3B): 0 diffs across 9,308 Fossilize DB shaders; 3 diffs in 83 pipelines (all ray-query compute shaders where lowered_complex is set): - rt.rays.{coherent,incoherent} (790ddb717d3f6502): 531->532 instrs, 5042->5052 B, 71->63 GPRs - gpubench-stress.rq.comp (dd862e831f1114ee): 368->369 instrs, 3620->3624 B, 71->63 GPRs Release (-Db_ndebug=true) compile-time median vs parent on g17p: - vk-mini (39 foz, 5x interleaved): 1.552s -> 1.487s (-4.17%) - vk-fossils (110 foz, 3x interleaved): 37.844s -> 36.211s (-4.32%) Signed-off-by: Diljit Singh --- src/asahi/vulkan/hk_shader.c | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/src/asahi/vulkan/hk_shader.c b/src/asahi/vulkan/hk_shader.c index f9231958b4bb..dd8150ff649b 100644 --- a/src/asahi/vulkan/hk_shader.c +++ b/src/asahi/vulkan/hk_shader.c @@ -1272,6 +1272,37 @@ m5_split_address(nir_def *addr, nir_def **base, nir_def **offset) return false; } +static bool +m5_has_mergeable_buffer_words(nir_shader *nir) +{ + nir_foreach_function_impl(impl, nir) { + nir_foreach_block(block, impl) { + unsigned count = 0; + nir_foreach_instr(instr, block) { + if (instr->type != nir_instr_type_intrinsic) + continue; + nir_intrinsic_instr *in = nir_instr_as_intrinsic(instr); + if (in->num_components != 1 || in->def.bit_size != 32 || + !nir_intrinsic_can_reorder(in)) + continue; + switch (in->intrinsic) { + case nir_intrinsic_load_global_bounded: + case nir_intrinsic_load_global_constant_bounded: + case nir_intrinsic_load_global_constant_offset: + case nir_intrinsic_load_global: + case nir_intrinsic_load_global_constant: + if (nir_intrinsic_align(in) >= 4 && ++count >= 2) + return true; + break; + default: + break; + } + } + } + } + return false; +} + /* M5: a structure read field by field (a light record in a loop) issues one * load per 32-bit word, each with its own address. Merge the reads of up to * four consecutive words at one base and offset term into one vector load. @@ -3398,7 +3429,8 @@ hk_lower_nir(struct hk_device *dev, nir_shader *nir, NIR_PASS(_, nir, nir_opt_sink, sink_opts); NIR_PASS(_, nir, nir_opt_move, opts); - if (global_loads.storage_result_select && global_loads.soft_fault) { + if (global_loads.storage_result_select && global_loads.soft_fault && + m5_has_mergeable_buffer_words(nir)) { /* Reads of one descriptor share its base and size only after CSE. */ NIR_PASS(_, nir, nir_opt_cse); NIR_PASS(_, nir, m5_merge_buffer_words);