From ac5e53a157bb8a4f8b442be16d8c97001ba81079 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 23:34:15 -0500 Subject: [PATCH 1/2] asahi/compiler: fold proven zext byte offsets and unroll compact guarded loops 8x Enable three general AGX3 compute loop optimizations that compose cleanly across compute workloads without chip allowlists or signed-index assumptions: 1. Zero-extended constant byte-offset folding (agx_nir_lower_address): AGX3B supports native signed 16-bit byte offsets on device loads and stores while exposing full 4 GiB storage buffers (UINT32_MAX), so unrolled loop indices cannot blindly sign-extend. Prove that (uint32_t)idx + c cannot wrap modulo 2^32 from unsigned range bounds, constant left shifts, or enclosing top-tested loop guards (unsigned and non-negative signed IVs), and fold c into byte_off while keeping sign_extend = 0. 2. Compact-prefix guarded loop 8x unrolling & 8-wide guard coalescing (agx_nir_unroll_runtime_loops, agx_nir_opt_guard_chains, agx_compile): Count only unconditional top-level loads toward the >4x in-flight read budget, allow guarded loops with a compact unconditional prefix (top_size * f <= max_instrs / 2, size * 4 <= max_instrs) to unroll 8x up to 2x total size, raise guard-chain coalescing to 8 ifs (48 live dwords) and unwrap fneg(fneg(x)) -> x in try_unwrap_zero_fadd_bias, and retry factor 4 before factor 1 on AGX3B when 8x exceeds half the register file (96 halves). 3. Scalar branch-compare LICM (agx_opt_licm): Treat IF/ELSE/WHILE/BREAK_IF scalar compares as plain register uses so loop-invariant uniform copies feeding branch compares hoist and merge with ALU copies in the loop preheader. Signed-off-by: DjDeveloperr --- src/asahi/compiler/agx_compile.c | 27 +- src/asahi/compiler/agx_nir_lower_address.c | 409 +++++++++++++++++- src/asahi/compiler/agx_nir_opt_guard_chains.c | 19 +- .../compiler/agx_nir_unroll_runtime_loops.c | 65 ++- src/asahi/compiler/agx_opt_licm.c | 9 + src/asahi/compiler/test/test-guard-chains.cpp | 111 +++++ .../test-lower-address-checked-offsets.cpp | 122 ++++++ src/asahi/compiler/test/test-opt-licm.cpp | 28 ++ 8 files changed, 758 insertions(+), 32 deletions(-) diff --git a/src/asahi/compiler/agx_compile.c b/src/asahi/compiler/agx_compile.c index 49fa3db6878b..0dce031e68ab 100644 --- a/src/asahi/compiler/agx_compile.c +++ b/src/asahi/compiler/agx_compile.c @@ -19862,19 +19862,30 @@ agx_compile_shader_nir_unrolled(nir_shader *nir, struct agx_shader_key *key, const unsigned full = agx_occupancy_for_register_count(0).max_threads; const unsigned first = ok ? agx_occupancy_for_register_count(out->info.nr_gprs).max_threads : 0; - /* Also when the wider unroll did not compile at all. */ - if (widest > 4 && first < full) { + const bool agx3b_over_half = + key->dev.encoding == AGX_ISA_ENCODING_AGX3B && + (!ok || out->info.nr_gprs > AGX3B_NUM_REGS / 2); + /* Also when the wider unroll did not compile at all, or exceeded half the + * AGX3B register file (try factor 4 before falling back to factor 1). */ + if (widest > 4 && (first < full || agx3b_over_half)) { nir_shader *narrow_nir = nir_shader_clone(NULL, clone); struct agx_shader_part narrow = {0}; struct blob narrow_blob; blob_init(&narrow_blob); *key = saved_key; - if (agx_compile_shader_nir_internal(narrow_nir, key, &narrow, - pre_preamble_blob ? &narrow_blob - : NULL, - false, false, false, 4, NULL) && - agx_occupancy_for_register_count(narrow.info.nr_gprs).max_threads > - first) { + const bool narrow_ok = + agx_compile_shader_nir_internal(narrow_nir, key, &narrow, + pre_preamble_blob ? &narrow_blob + : NULL, + false, false, false, 4, NULL); + const unsigned narrow_occ = + narrow_ok + ? agx_occupancy_for_register_count(narrow.info.nr_gprs).max_threads + : 0; + if (narrow_ok && + (narrow_occ > first || + (agx3b_over_half && narrow_occ >= first && + (!ok || narrow.info.nr_gprs < out->info.nr_gprs)))) { if (ok) free(out->binary); *out = narrow; diff --git a/src/asahi/compiler/agx_nir_lower_address.c b/src/asahi/compiler/agx_nir_lower_address.c index 47249739ae1c..d3c872171428 100644 --- a/src/asahi/compiler/agx_nir_lower_address.c +++ b/src/asahi/compiler/agx_nir_lower_address.c @@ -305,6 +305,399 @@ existing_index_multiple(nir_intrinsic_instr *access, nir_scalar index, return false; } +static bool +block_is_lone_break(const nir_block *block) +{ + const nir_instr *last = nir_block_last_instr((nir_block *)block); + return last && last == nir_block_first_instr((nir_block *)block) && + last->type == nir_instr_type_jump && + nir_instr_as_jump(last)->type == nir_jump_break; +} + +static bool +cf_list_is_lone_break(const struct exec_list *list) +{ + if (!exec_list_is_singular(list)) + return false; + const nir_cf_node *node = + exec_node_data(nir_cf_node, exec_list_get_head_const(list), node); + return node->type == nir_cf_node_block && + block_is_lone_break(nir_cf_node_as_block(node)); +} + +static bool +cf_list_is_empty_block(const struct exec_list *list) +{ + if (!exec_list_is_singular(list)) + return false; + const nir_cf_node *node = + exec_node_data(nir_cf_node, exec_list_get_head_const(list), node); + return node->type == nir_cf_node_block && + exec_list_is_empty(&nir_cf_node_as_block(node)->instr_list); +} + +static bool +scalars_equal(nir_scalar a, nir_scalar b) +{ + a = nir_scalar_chase_movs(a); + b = nir_scalar_chase_movs(b); + return a.def == b.def && a.comp == b.comp; +} + +/* Match `bcsel(uge(N, K), iadd(N, -M), 0)` or `bcsel(ult(N, K), 0, iadd(N, -M))` + * with `0 < M <= K`: when N >= K, N - M does not underflow and is at most + * UINT32_MAX - M; when N < K, the result is 0. */ +static bool +u32_limit_upper_bound(nir_scalar limit, uint32_t *max_out) +{ + limit = nir_scalar_chase_movs(limit); + if (limit.def->bit_size != 32) + return false; + + if (nir_scalar_is_const(limit)) { + *max_out = (uint32_t)nir_scalar_as_uint(limit); + return true; + } + + if (!nir_scalar_is_alu(limit)) + return false; + + const nir_op op = nir_scalar_alu_op(limit); + if (op == nir_op_iand) { + for (unsigned i = 0; i < 2; ++i) { + nir_scalar k = nir_scalar_chase_alu_src(limit, i); + if (nir_scalar_is_const(k)) { + *max_out = (uint32_t)nir_scalar_as_uint(k); + return true; + } + } + return false; + } + + if (op == nir_op_ushr) { + nir_scalar s = nir_scalar_chase_alu_src(limit, 1); + if (nir_scalar_is_const(s)) { + unsigned sh = (unsigned)nir_scalar_as_uint(s) & 31u; + if (sh > 0) { + *max_out = UINT32_MAX >> sh; + return true; + } + } + return false; + } + + if (op == nir_op_usub_sat) { + nir_scalar m = nir_scalar_chase_alu_src(limit, 1); + if (nir_scalar_is_const(m)) { + *max_out = UINT32_MAX - (uint32_t)nir_scalar_as_uint(m); + return true; + } + return false; + } + + if (op != nir_op_bcsel) + return false; + + nir_scalar cond = nir_scalar_chase_movs(nir_scalar_chase_alu_src(limit, 0)); + nir_scalar tval = nir_scalar_chase_movs(nir_scalar_chase_alu_src(limit, 1)); + nir_scalar fval = nir_scalar_chase_movs(nir_scalar_chase_alu_src(limit, 2)); + if (!nir_scalar_is_alu(cond)) + return false; + + nir_op cop = nir_scalar_alu_op(cond); + nir_scalar adj, zero; + if (cop == nir_op_uge) { + adj = tval; + zero = fval; + } else if (cop == nir_op_ult) { + adj = fval; + zero = tval; + } else { + return false; + } + + if (!nir_scalar_is_const(zero) || nir_scalar_as_uint(zero) != 0) + return false; + + nir_scalar n_cmp = nir_scalar_chase_movs(nir_scalar_chase_alu_src(cond, 0)); + nir_scalar k_cmp = nir_scalar_chase_movs(nir_scalar_chase_alu_src(cond, 1)); + if (n_cmp.def->bit_size != 32 || !nir_scalar_is_const(k_cmp) || + !nir_scalar_is_alu(adj) || nir_scalar_alu_op(adj) != nir_op_iadd) + return false; + + const uint32_t k_val = (uint32_t)nir_scalar_as_uint(k_cmp); + for (unsigned i = 0; i < 2; ++i) { + nir_scalar add_n = nir_scalar_chase_alu_src(adj, i); + nir_scalar add_c = nir_scalar_chase_alu_src(adj, 1 - i); + if (!scalars_equal(add_n, n_cmp) || !nir_scalar_is_const(add_c)) + continue; + const int64_t add_signed = nir_scalar_as_int(add_c); + if (add_signed < 0) { + const uint64_t m_val = (uint64_t)(-add_signed); + if (m_val > 0 && m_val <= k_val) { + *max_out = UINT32_MAX - (uint32_t)m_val; + return true; + } + } + } + return false; +} + +static bool +s32_limit_upper_bound(nir_scalar limit, int32_t *max_out) +{ + limit = nir_scalar_chase_movs(limit); + if (limit.def->bit_size != 32) + return false; + + if (nir_scalar_is_const(limit)) { + *max_out = (int32_t)nir_scalar_as_int(limit); + return true; + } + + if (!nir_scalar_is_alu(limit)) + return false; + + const nir_op op = nir_scalar_alu_op(limit); + if (op == nir_op_ishr) { + nir_scalar s = nir_scalar_chase_alu_src(limit, 1); + if (nir_scalar_is_const(s)) { + unsigned sh = (unsigned)nir_scalar_as_uint(s) & 31u; + if (sh > 0) { + *max_out = INT32_MAX >> sh; + return true; + } + } + return false; + } + + if (op == nir_op_ushr) { + nir_scalar s = nir_scalar_chase_alu_src(limit, 1); + if (nir_scalar_is_const(s)) { + unsigned sh = (unsigned)nir_scalar_as_uint(s) & 31u; + if (sh > 0) { + *max_out = (int32_t)(UINT32_MAX >> sh); + return true; + } + } + return false; + } + + if (op != nir_op_bcsel) + return false; + + nir_scalar cond = nir_scalar_chase_movs(nir_scalar_chase_alu_src(limit, 0)); + nir_scalar tval = nir_scalar_chase_movs(nir_scalar_chase_alu_src(limit, 1)); + nir_scalar fval = nir_scalar_chase_movs(nir_scalar_chase_alu_src(limit, 2)); + if (!nir_scalar_is_alu(cond)) + return false; + + nir_op cop = nir_scalar_alu_op(cond); + nir_scalar adj, minv; + if (cop == nir_op_ige) { + adj = tval; + minv = fval; + } else if (cop == nir_op_ilt) { + adj = fval; + minv = tval; + } else { + return false; + } + + if (!nir_scalar_is_const(minv) || nir_scalar_as_int(minv) != INT32_MIN) + return false; + + nir_scalar n_cmp = nir_scalar_chase_movs(nir_scalar_chase_alu_src(cond, 0)); + nir_scalar k_cmp = nir_scalar_chase_movs(nir_scalar_chase_alu_src(cond, 1)); + if (n_cmp.def->bit_size != 32 || !nir_scalar_is_const(k_cmp) || + !nir_scalar_is_alu(adj) || nir_scalar_alu_op(adj) != nir_op_iadd) + return false; + + const int64_t k_bound = nir_scalar_as_int(k_cmp); + for (unsigned i = 0; i < 2; ++i) { + nir_scalar add_n = nir_scalar_chase_alu_src(adj, i); + nir_scalar add_c = nir_scalar_chase_alu_src(adj, 1 - i); + if (!scalars_equal(add_n, n_cmp) || !nir_scalar_is_const(add_c)) + continue; + const int64_t add_signed = nir_scalar_as_int(add_c); + if (add_signed < 0) { + const int64_t m_val = -add_signed; + if (m_val > 0 && k_bound >= (int64_t)INT32_MIN + m_val) { + *max_out = (int32_t)((int64_t)INT32_MAX - m_val); + return true; + } + } + } + return false; +} + +static bool +loop_iv_nonneg_step(nir_loop *loop, nir_scalar rest, uint32_t *step_out) +{ + nir_block *header = nir_loop_first_block(loop); + nir_instr *def_instr = nir_def_instr(rest.def); + if (def_instr->type != nir_instr_type_phi || def_instr->block != header) + return false; + + nir_phi_instr *phi = nir_instr_as_phi(def_instr); + if (exec_list_length(&phi->srcs) != 2) + return false; + nir_block *pre = nir_cf_node_as_block(nir_cf_node_prev(&loop->cf_node)); + nir_block *latch = nir_loop_last_block(loop); + nir_phi_src *init_src = nir_phi_get_src_from_block(phi, pre); + nir_phi_src *back_src = nir_phi_get_src_from_block(phi, latch); + if (!init_src || !back_src) + return false; + + nir_scalar init = + nir_scalar_chase_movs(nir_get_scalar(init_src->src.ssa, rest.comp)); + if (!nir_scalar_is_const(init) || nir_scalar_as_int(init) < 0) + return false; + + nir_scalar back = + nir_scalar_chase_movs(nir_get_scalar(back_src->src.ssa, rest.comp)); + if (!nir_scalar_is_alu(back) || nir_scalar_alu_op(back) != nir_op_iadd) + return false; + + for (unsigned i = 0; i < 2; ++i) { + nir_scalar s_iv = nir_scalar_chase_alu_src(back, i); + nir_scalar s_step = nir_scalar_chase_alu_src(back, 1 - i); + if (scalars_equal(s_iv, rest) && nir_scalar_is_const(s_step)) { + int64_t st = nir_scalar_as_int(s_step); + if (st > 0 && st <= INT32_MAX) { + *step_out = (uint32_t)st; + return true; + } + } + } + return false; +} + +/* Prove that `(uint32_t)rest + uc` cannot wrap modulo 2^32 at `access`, so + * `zext(rest + uc) * scale == zext(rest) * scale + uc * scale` holds even for + * full 4 GiB (`UINT32_MAX`) buffer ranges without sign-extending `rest`. */ +static bool +u32_add_no_wrap(const struct lower_address_options *options, + nir_intrinsic_instr *access, nir_scalar add_scalar, + nir_scalar rest, uint32_t uc) +{ + if (uc == 0) + return true; + + if (options->checked_offsets) + return false; + + if (nir_def_as_alu(add_scalar.def)->no_unsigned_wrap) + return true; + + uint32_t max_rest = 0; + if (u32_limit_upper_bound(rest, &max_rest) && max_rest <= UINT32_MAX - uc) + return true; + + /* Narrow unsigned extensions (u8/u16 -> u32) cannot wrap when adding small c. */ + if (nir_scalar_is_alu(rest) && nir_scalar_alu_op(rest) == nir_op_u2u32) { + nir_scalar narrow = nir_scalar_chase_alu_src(rest, 0); + if (narrow.def->bit_size < 32 && + BITFIELD_MASK(narrow.def->bit_size) <= UINT32_MAX - uc) + return true; + } + + /* Low zero bits from a constant left shift cannot carry out of bit 31. */ + if (nir_scalar_is_alu(rest) && nir_scalar_alu_op(rest) == nir_op_ishl) { + nir_scalar sh = nir_scalar_chase_alu_src(rest, 1); + if (nir_scalar_is_const(sh)) { + unsigned s = (unsigned)nir_scalar_as_uint(sh) & 31u; + if (s > 0 && uc < (1u << s)) + return true; + } + } + + /* Walk enclosing loops looking for a top-tested exit guard that bounds + * `rest` below a limit guaranteeing `rest + uc <= UINT32_MAX`. */ + for (nir_cf_node *node = access->instr.block->cf_node.parent; node; + node = node->parent) { + if (node->type != nir_cf_node_loop) + continue; + + nir_loop *loop = nir_cf_node_as_loop(node); + nir_block *header = nir_loop_first_block(loop); + if (access->instr.block == header) + continue; + + nir_cf_node *first = nir_cf_node_next(&header->cf_node); + if (!first || first->type != nir_cf_node_if) + continue; + + nir_if *nif = nir_cf_node_as_if(first); + bool break_in_then; + if (cf_list_is_lone_break(&nif->then_list) && + cf_list_is_empty_block(&nif->else_list)) + break_in_then = true; + else if (cf_list_is_lone_break(&nif->else_list) && + cf_list_is_empty_block(&nif->then_list)) + break_in_then = false; + else + continue; + + /* Ensure `access` is not inside the break `if` itself. */ + bool in_break_if = false; + for (nir_cf_node *p = &access->instr.block->cf_node; p && p != node; + p = p->parent) { + if (p == &nif->cf_node) { + in_break_if = true; + break; + } + } + if (in_break_if) + continue; + + nir_scalar cond = nir_scalar_resolved(nif->condition.ssa, 0); + bool neg = false; + while (nir_scalar_is_alu(cond) && nir_scalar_alu_op(cond) == nir_op_inot) { + neg = !neg; + cond = nir_scalar_chase_alu_src(cond, 0); + } + if (!nir_scalar_is_alu(cond)) + continue; + + /* `continue_on_true`: loop body runs when `cond` is true. */ + const bool continue_on_true = (break_in_then == neg); + const nir_op cop = nir_scalar_alu_op(cond); + nir_scalar lhs = nir_scalar_chase_alu_src(cond, 0); + nir_scalar rhs = nir_scalar_chase_alu_src(cond, 1); + + /* Check unsigned `rest < limit`. */ + bool is_ult = (continue_on_true && cop == nir_op_ult) || + (!continue_on_true && cop == nir_op_uge); + if (is_ult && scalars_equal(lhs, rest)) { + uint32_t max_limit = 0; + if (u32_limit_upper_bound(rhs, &max_limit)) { + if (max_limit == 0 || uc <= UINT32_MAX - (max_limit - 1u)) + return true; + } + } + + /* Check signed non-negative IV `0 <= rest < limit`. */ + bool is_ilt = (continue_on_true && cop == nir_op_ilt) || + (!continue_on_true && cop == nir_op_ige); + if (is_ilt && scalars_equal(lhs, rest)) { + uint32_t step = 0; + int32_t max_s32 = 0; + if (loop_iv_nonneg_step(loop, rest, &step) && + s32_limit_upper_bound(rhs, &max_s32)) { + if (max_s32 <= 0) + return true; + const int64_t max_rest = (int64_t)max_s32 - 1; + if (max_rest + (int64_t)step <= INT32_MAX && + max_rest + (int64_t)uc <= INT32_MAX) + return true; + } + } + } + + return false; +} + /* AGX3C loads and stores add a signed 16-bit byte offset after scaling the * index, so a constant addend in the index -- a struct member or a constant * array element -- needs no ALU. The split must not change any valid address: @@ -313,7 +706,8 @@ existing_index_multiple(nir_intrinsic_instr *access, nir_scalar index, * overflows, which no valid signed index does. * - A zero-extended index gives zext(x + c) = zext(x) + c only if x + c does * not wrap. An amul sum x is nonnegative and below 2^31 for a valid access, - * so this holds for c >= 0. Any other x may be negative (a reversed index + * so this holds for c >= 0; likewise when u32_add_no_wrap() proves x + c + * cannot wrap 32-bit unsigned. Any other x may be negative (a reversed index * N - i folds to c + -i), so leave it alone. * - An array index i + c scaled by amul is, for a valid access, nonnegative * and below 2^31 / stride, so as signed integers (i + c) * stride equals @@ -327,9 +721,9 @@ existing_index_multiple(nir_intrinsic_instr *access, nir_scalar index, * The same bounds let a power-of-two stride move into the index scale. */ static void -fold_byte_offset(nir_builder *b, nir_intrinsic_instr *access, - struct match *match, unsigned format_shift, - unsigned max_shift) +fold_byte_offset(nir_builder *b, const struct lower_address_options *options, + nir_intrinsic_instr *access, struct match *match, + unsigned format_shift, unsigned max_shift) { if (match->offset.def == NULL) return; @@ -351,7 +745,10 @@ fold_byte_offset(nir_builder *b, nir_intrinsic_instr *access, continue; const int64_t c = nir_scalar_as_int(k); - if (!sign_extend && (c < 0 || !is_amul_sum(rest, 0))) + if (!sign_extend && + (c < 0 || (!is_amul_sum(rest, 0) && + !u32_add_no_wrap(options, access, offset, rest, + (uint32_t)c)))) return; byte_offset = c * (INT64_C(1) << scale); @@ -569,7 +966,7 @@ pass(struct nir_builder *b, nir_intrinsic_instr *intr, void *data) if (options->byte_offsets && !shift_must_match && intr->intrinsic != nir_intrinsic_global_atomic && intr->intrinsic != nir_intrinsic_global_atomic_swap) { - fold_byte_offset(b, intr, &match, format_shift, max_shift); + fold_byte_offset(b, options, intr, &match, format_shift, max_shift); /* A constant added to the base, as to a pointer before it is indexed * ((p + 16) + i): the byte offset adds it after the index in the same diff --git a/src/asahi/compiler/agx_nir_opt_guard_chains.c b/src/asahi/compiler/agx_nir_opt_guard_chains.c index 599303400f88..067e150ec321 100644 --- a/src/asahi/compiler/agx_nir_opt_guard_chains.c +++ b/src/asahi/compiler/agx_nir_opt_guard_chains.c @@ -72,8 +72,8 @@ #define MAX_PREFIX_INSTRS 24u #define MAX_PREFIX_LOADS 4u -#define MAX_GROUP_IFS 4u -#define MAX_LIVE_HOISTED_DWORDS 24u +#define MAX_GROUP_IFS 8u +#define MAX_LIVE_HOISTED_DWORDS 48u #define MIN_COALESCE_BODY_INSTRS 12u static unsigned @@ -1358,7 +1358,20 @@ try_unwrap_zero_fadd_bias(nir_builder *b, nir_block *prev_block, for (unsigned m = 0; m < k; ++m) vals[m] = unwrapped[m]; - *thresh_inout = nir_fneg(b, bias); + + /* Unwrap fneg(fneg(x)) -> x (IEEE-754 bit-exact including signed zeros, + * infinities, and NaN payloads) so downstream passes see the original + * uniform/SSA value instead of a redundant double negation. */ + nir_alu_instr *bias_alu = nir_def_as_alu_or_null(bias); + if (bias_alu && bias_alu->op == nir_op_fneg && + bias_alu->def.num_components == 1 && bias_alu->def.bit_size == 32 && + bias_alu->src[0].swizzle[0] == 0 && + bias_alu->src[0].src.ssa->num_components == 1 && + nir_block_dominates(nir_def_block(bias_alu->src[0].src.ssa), prev_block)) { + *thresh_inout = bias_alu->src[0].src.ssa; + } else { + *thresh_inout = nir_fneg(b, bias); + } return true; } diff --git a/src/asahi/compiler/agx_nir_unroll_runtime_loops.c b/src/asahi/compiler/agx_nir_unroll_runtime_loops.c index e0a3546fbf1b..efde76facc96 100644 --- a/src/asahi/compiler/agx_nir_unroll_runtime_loops.c +++ b/src/asahi/compiler/agx_nir_unroll_runtime_loops.c @@ -206,12 +206,16 @@ lane_dependent(const nir_intrinsic_instr *intr) } /* Everything in the loop that is safe to execute F times in a row per - * main-loop iteration. Returns the number of instructions, or -1. */ + * main-loop iteration. Returns the number of instructions, or -1. When + * `top_level_out` is non-NULL, stores the number of instructions directly in + * the loop's unconditional top-level blocks (excluding nested `if` bodies). */ static int -count_unrollable(nir_loop *loop, nir_if *terminator) +count_unrollable(nir_loop *loop, nir_if *terminator, int *top_level_out) { int count = 0; + int top_level = 0; nir_foreach_block_in_cf_node(block, &loop->cf_node) { + const bool is_top = block->cf_node.parent == &loop->cf_node; nir_foreach_instr(instr, block) { switch (instr->type) { case nir_instr_type_jump: @@ -250,10 +254,15 @@ count_unrollable(nir_loop *loop, nir_if *terminator) default: break; } - if (instr->type != nir_instr_type_phi) + if (instr->type != nir_instr_type_phi) { count++; + if (is_top) + top_level++; + } } } + if (top_level_out) + *top_level_out = top_level; return count; } @@ -270,18 +279,17 @@ src_varies(nir_src *src, void *data) return true; } -/* 32-bit registers one iteration's memory and texture reads fill, counting - * the reads whose address depends on a value the loop carries (reads of - * addresses that are the same every iteration, such as descriptors and the - * bound's parameters, are shared by the unrolled copies). */ static unsigned -loaded_dwords(nir_function_impl *impl, nir_loop *loop) +loaded_dwords_in_loop(nir_function_impl *impl, nir_loop *loop, + bool top_level_only) { BITSET_WORD *varying = calloc(BITSET_WORDS(impl->ssa_alloc), sizeof(BITSET_WORD)); nir_block *header = nir_loop_first_block(loop); unsigned dwords = 0; nir_foreach_block_in_cf_node(block, &loop->cf_node) { + const bool count_block = + !top_level_only || block->cf_node.parent == &loop->cf_node; nir_foreach_instr(instr, block) { nir_def *def = nir_instr_def(instr); if (!def) @@ -295,6 +303,8 @@ loaded_dwords(nir_function_impl *impl, nir_loop *loop) continue; BITSET_SET(varying, def->index); + if (!count_block) + continue; bool load = instr->type == nir_instr_type_tex; if (instr->type == nir_instr_type_intrinsic) { nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); @@ -310,6 +320,16 @@ loaded_dwords(nir_function_impl *impl, nir_loop *loop) return dwords; } +/* 32-bit registers one iteration's memory and texture reads fill, counting + * the reads whose address depends on a value the loop carries (reads of + * addresses that are the same every iteration, such as descriptors and the + * bound's parameters, are shared by the unrolled copies). */ +static unsigned +loaded_dwords(nir_function_impl *impl, nir_loop *loop) +{ + return loaded_dwords_in_loop(impl, loop, false); +} + static bool analyze_loop(nir_loop *loop, struct counted_loop *out) { @@ -886,23 +906,38 @@ choose_factor(nir_function_impl *impl, nir_loop *loop, struct counted_loop *cl, if (nested_workgroup_stripe(impl->function->shader, cl)) return 0; - int size = count_unrollable(loop, cl->nif); + int top_size = 0; + int size = count_unrollable(loop, cl->nif, &top_size); if (size < 0) return 0; + /* A guarded loop with a compact unconditional prefix and a larger nested + * conditional body executes only the prefix unconditionally per iteration. + * When 4x already fits the standard budget, allow 8x up to 2x total code + * size as long as the unconditional hot path stays within half the budget + * and unconditional in-flight loads stay within 16 dwords; backend + * occupancy / register-file checks fall back to 4x if pressure grows. */ + const bool compact_guarded_prefix = + top_size < size && (unsigned)size * 4 <= max_instrs && + (unsigned)top_size * factor <= max_instrs / 2 && + (unsigned)size * factor <= max_instrs * 2; + const unsigned budget = compact_guarded_prefix ? max_instrs * 2 : max_instrs; + /* A body too large for the full factor still gains from two * iterations per test when it fits the budget at half the factor. */ unsigned f = factor; - while (f > 2 && (unsigned)size * f > max_instrs) + while (f > 2 && (unsigned)size * f > budget) f /= 2; - /* Beyond four iterations, keep the reads the unrolled body has in - * flight within 16 registers: more only raises register pressure - * (the scheduler issues them together) and can cost occupancy. */ + /* Beyond four iterations, keep the unconditional reads the unrolled body + * has in flight within 16 registers: more only raises register pressure + * (the scheduler issues them together) and can cost occupancy. Loads inside + * nested `if` bodies are guarded and do not issue together across + * iterations. */ if (f > 4) { - const unsigned dwords = loaded_dwords(impl, loop); + const unsigned dwords = loaded_dwords_in_loop(impl, loop, true); while (f > 4 && dwords * f > 16) f /= 2; } - return (unsigned)size * f > max_instrs ? 0 : f; + return (unsigned)size * f > budget ? 0 : f; } /* Computable before `outer` from values defined before it, without memory diff --git a/src/asahi/compiler/agx_opt_licm.c b/src/asahi/compiler/agx_opt_licm.c index 1f0ca4667e8c..8c8e3cdf088d 100644 --- a/src/asahi/compiler/agx_opt_licm.c +++ b/src/asahi/compiler/agx_opt_licm.c @@ -61,6 +61,15 @@ plain_use(const agx_instr *I) case AGX_OPCODE_PHI: case AGX_OPCODE_EXPORT: return false; + case AGX_OPCODE_IF_FCMP: + case AGX_OPCODE_IF_ICMP: + case AGX_OPCODE_ELSE_FCMP: + case AGX_OPCODE_ELSE_ICMP: + case AGX_OPCODE_WHILE_FCMP: + case AGX_OPCODE_WHILE_ICMP: + case AGX_OPCODE_BREAK_IF_FCMP: + case AGX_OPCODE_BREAK_IF_ICMP: + return true; default: return agx_opcodes_info[I->op].schedule_class == AGX_SCHEDULE_CLASS_NONE; } diff --git a/src/asahi/compiler/test/test-guard-chains.cpp b/src/asahi/compiler/test/test-guard-chains.cpp index 8090322765eb..128d0de6473a 100644 --- a/src/asahi/compiler/test/test-guard-chains.cpp +++ b/src/asahi/compiler/test/test-guard-chains.cpp @@ -898,8 +898,119 @@ TEST(GuardChains, CoalesceFloatThreshTreeVariantsAndRefusals) nir_block *entry = nir_start_block(nir_shader_get_entrypoint(b.shader)); EXPECT_EQ(count_alu_op_in_block(entry, nir_op_bcsel), 3u); EXPECT_EQ(count_alu_op_in_block(entry, nir_op_fadd), 0u); + /* Only the original hoisted neg_thr fneg remains; no double-fneg emitted. */ + EXPECT_EQ(count_alu_op_in_block(entry, nir_op_fneg), 1u); ralloc_free(b.shader); } } +/* Eight adjacent guarded ifs coalesce into one outer fast-path guard with a + * 7-bcsel balanced float-threshold tree, and a compact-prefix guarded loop + * unrolls by 8 (while >2 unconditional dwords/iter or unguarded bodies stay 4). */ +TEST(GuardChains, CoalescesEightGuardedIfsAndCompactPrefixLoopUnrollsByEight) +{ + { + nir_builder b = nir_builder_init_simple_shader( + MESA_SHADER_COMPUTE, &agx_nir_options, "coalesce-8"); + b.shader->info.workgroup_size[0] = 32; + + nir_def *tid = nir_channel(&b, nir_load_local_invocation_id(&b), 0); + nir_def *base = agx_test_load_preamble(&b, 1, 64, 0); + nir_def *thr = agx_test_load_preamble(&b, 1, 32, 4); + nir_def *neg_thr = nir_fneg(&b, thr); + nir_def *zero = nir_imm_float(&b, 0.0f); + + nir_def *vals[8]; + nir_def *conds[8]; + for (unsigned k = 0; k < 8; ++k) { + nir_def *idx = nir_iadd_imm(&b, tid, 32 * k); + nir_def *addr = + nir_iadd(&b, base, nir_ishl_imm(&b, nir_u2u64(&b, idx), 2)); + vals[k] = make_load_global(&b, 1, 32, addr, 4, (gl_access_qualifier)0); + nir_def *diff = nir_fadd(&b, vals[k], neg_thr); + conds[k] = nir_inot(&b, nir_fge(&b, diff, zero)); + } + + nir_def *acc = nir_imm_float(&b, 0.0f); + for (unsigned k = 0; k < 8; ++k) { + nir_push_if(&b, conds[k]); + nir_def *r = nir_fadd(&b, acc, nir_frsq(&b, vals[k])); + nir_pop_if(&b, NULL); + acc = nir_if_phi(&b, r, acc); + } + make_store_global( + &b, acc, nir_iadd(&b, base, nir_ishl_imm(&b, nir_u2u64(&b, tid), 2)), + 4); + + EXPECT_TRUE(agx_nir_opt_guard_chains(b.shader)); + nir_validate_shader(b.shader, "after coalesce-8"); + EXPECT_EQ(count_ifs(b.shader), 9u); + nir_block *entry = nir_start_block(nir_shader_get_entrypoint(b.shader)); + EXPECT_EQ(count_alu_op_in_block(entry, nir_op_bcsel), 7u); + EXPECT_EQ(count_alu_op_in_block(entry, nir_op_fadd), 0u); + ralloc_free(b.shader); + } + + auto run_loop_unroll = [](bool nested_if, unsigned top_load_comps) -> unsigned { + nir_builder b = nir_builder_init_simple_shader( + MESA_SHADER_COMPUTE, &agx_nir_options, "guarded-unroll8"); + b.shader->info.workgroup_size[0] = 32; + nir_def *tid = nir_channel(&b, nir_load_local_invocation_id(&b), 0); + nir_def *base = agx_test_load_preamble(&b, 1, 64, 0); + nir_def *base2 = agx_test_load_preamble(&b, 1, 64, 4); + nir_def *n = agx_test_load_preamble(&b, 1, 32, 8); + nir_def *thr = agx_test_load_preamble(&b, 1, 32, 10); + nir_def *one = nir_imm_float(&b, 1.0f); + + nir_variable *iv_var = + nir_local_variable_create(b.impl, glsl_uint_type(), "iv"); + nir_variable *acc_var = + nir_local_variable_create(b.impl, glsl_float_type(), "acc"); + nir_store_var(&b, iv_var, tid, 1); + nir_store_var(&b, acc_var, nir_imm_float(&b, 0.0f), 1); + + nir_loop *loop = nir_push_loop(&b); + nir_def *iv = nir_load_var(&b, iv_var); + nir_break_if(&b, nir_uge(&b, iv, n)); + nir_def *addr = + nir_iadd(&b, base, nir_ishl_imm(&b, nir_u2u64(&b, iv), 4)); + nir_def *v = make_load_global(&b, top_load_comps, 32, addr, 4, + (gl_access_qualifier)0); + nir_def *x = nir_channel(&b, v, 0); + if (nested_if) + nir_push_if(&b, nir_flt(&b, x, thr)); + nir_def *addr2 = + nir_iadd(&b, base2, nir_ishl_imm(&b, nir_u2u64(&b, iv), 3)); + nir_def *v2 = + make_load_global(&b, 2, 32, addr2, 8, (gl_access_qualifier)0); + nir_def *v2x = nir_channel(&b, v2, 0); + nir_def *v2y = nir_channel(&b, v2, 1); + nir_def *t = nir_frsq(&b, x); + for (unsigned i = 0; i < 32; ++i) + t = nir_ffma(&b, t, (i & 1) ? v2y : v2x, one); + nir_store_var(&b, acc_var, nir_fadd(&b, nir_load_var(&b, acc_var), t), 1); + if (nested_if) + nir_pop_if(&b, NULL); + nir_store_var(&b, iv_var, nir_iadd_imm(&b, iv, 32), 1); + nir_pop_loop(&b, loop); + + make_store_global( + &b, nir_load_var(&b, acc_var), + nir_iadd(&b, base, nir_ishl_imm(&b, nir_u2u64(&b, tid), 2)), 4); + nir_lower_vars_to_ssa(b.shader); + unsigned widest = 0; + EXPECT_TRUE(agx_nir_unroll_runtime_loops(b.shader, 8, 320, &widest)); + nir_validate_shader(b.shader, "after guarded-unroll8"); + ralloc_free(b.shader); + return widest; + }; + + /* Positive: compact guarded prefix (2 top-level dwords, ~48 total instrs) -> 8x. */ + EXPECT_EQ(run_loop_unroll(true, 2), 8u); + /* Negative control: >2 unconditional top-level loaded dwords/iter stays at 4x. */ + EXPECT_EQ(run_loop_unroll(true, 3), 4u); + /* Negative control: same size without a nested if stays at 4x. */ + EXPECT_EQ(run_loop_unroll(false, 2), 4u); +} + } // namespace diff --git a/src/asahi/compiler/test/test-lower-address-checked-offsets.cpp b/src/asahi/compiler/test/test-lower-address-checked-offsets.cpp index 5f7afc385aef..4b76be43a261 100644 --- a/src/asahi/compiler/test/test-lower-address-checked-offsets.cpp +++ b/src/asahi/compiler/test/test-lower-address-checked-offsets.cpp @@ -367,4 +367,126 @@ TEST(LowerAddressCheckedOffsets, ProvenIndicesStayFolded) } } +/* Where the loop guard proves `i + c <= UINT32_MAX`, zero-extended AGX3B + * loads fold `c` into the signed 16-bit byte offset without sign-extending + * `i`; offsets that could wrap (or negative signed IV starts) stay unfolded. */ +TEST(LowerAddressCheckedOffsets, ZeroExtendedByteOffsetGuardProof) +{ + auto run_u32_loop = [](uint32_t c, bool checked) -> int16_t { + nir_builder b = nir_builder_init_simple_shader( + MESA_SHADER_COMPUTE, &agx_nir_options, "zext-u32-guard"); + nir_def *base = nir_load_preamble(&b, 1, 64, .base = 0); + nir_def *out = nir_load_preamble(&b, 1, 64, .base = 4); + nir_def *n = nir_load_preamble(&b, 1, 32, .base = 8); + nir_def *limit = nir_bcsel(&b, nir_uge(&b, n, nir_imm_int(&b, 224)), + nir_iadd_imm(&b, n, -224), nir_imm_int(&b, 0)); + + nir_variable *iv_var = + nir_local_variable_create(b.impl, glsl_uint_type(), "iv"); + nir_variable *sum_var = + nir_local_variable_create(b.impl, glsl_uint_type(), "sum"); + nir_store_var(&b, iv_var, nir_imm_int(&b, 0), 1); + nir_store_var(&b, sum_var, nir_imm_int(&b, 0), 1); + + nir_loop *loop = nir_push_loop(&b); + nir_def *iv = nir_load_var(&b, iv_var); + nir_break_if(&b, nir_uge(&b, iv, limit)); + nir_def *idx = nir_iadd_imm(&b, iv, c); + nir_def *addr = + nir_iadd(&b, base, nir_ishl_imm(&b, nir_u2u64(&b, idx), 3)); + nir_def *v = nir_load_global(&b, 2, 32, addr, .align_mul = 8); + nir_store_var(&b, sum_var, + nir_iadd(&b, nir_load_var(&b, sum_var), nir_channel(&b, v, 0)), + 1); + nir_store_var(&b, iv_var, nir_iadd_imm(&b, iv, 256), 1); + nir_pop_loop(&b, loop); + + nir_store_global(&b, nir_load_var(&b, sum_var), out, .align_mul = 4); + nir_lower_vars_to_ssa(b.shader); + agx_nir_lower_address(b.shader, true, true, checked); + + int16_t folded = 0; + bool found = false; + nir_foreach_block(block, b.impl) { + nir_foreach_instr(instr, block) { + if (instr->type != nir_instr_type_intrinsic || + nir_instr_as_intrinsic(instr)->intrinsic != + nir_intrinsic_load_agx) + continue; + nir_intrinsic_instr *ld = nir_instr_as_intrinsic(instr); + EXPECT_FALSE(nir_intrinsic_sign_extend(ld)); + folded = (int16_t)(nir_intrinsic_base(ld) >> + AGX_NIR_MEMORY_BYTE_OFFSET_SHIFT); + found = true; + } + } + EXPECT_TRUE(found); + ralloc_free(b.shader); + return folded; + }; + + /* max(iv) <= UINT32_MAX - 225, so +224 (+1792B) cannot wrap 32-bit unsigned. */ + EXPECT_EQ(run_u32_loop(224u, false), 1792); + /* Exact boundary: +226 can wrap when n == UINT32_MAX and iv == UINT32_MAX - 225. */ + EXPECT_EQ(run_u32_loop(226u, false), 0); + /* Checked offsets keep constant byte-offset folding disabled. */ + EXPECT_EQ(run_u32_loop(224u, true), 0); + + auto run_s32_loop = [](int32_t init_val, int32_t step_val, uint32_t c) -> int16_t { + nir_builder b = nir_builder_init_simple_shader( + MESA_SHADER_COMPUTE, &agx_nir_options, "zext-s32-guard"); + nir_def *base = nir_load_preamble(&b, 1, 64, .base = 0); + nir_def *out = nir_load_preamble(&b, 1, 64, .base = 4); + nir_def *n = nir_load_preamble(&b, 1, 32, .base = 8); + nir_def *limit = + nir_bcsel(&b, nir_ige(&b, n, nir_imm_int(&b, INT32_MIN + 16)), + nir_iadd_imm(&b, n, -16), nir_imm_int(&b, INT32_MIN)); + + nir_variable *iv_var = + nir_local_variable_create(b.impl, glsl_int_type(), "iv"); + nir_variable *sum_var = + nir_local_variable_create(b.impl, glsl_uint_type(), "sum"); + nir_store_var(&b, iv_var, nir_imm_int(&b, init_val), 1); + nir_store_var(&b, sum_var, nir_imm_int(&b, 0), 1); + + nir_loop *loop = nir_push_loop(&b); + nir_def *iv = nir_load_var(&b, iv_var); + nir_break_if(&b, nir_ige(&b, iv, limit)); + nir_def *idx = nir_iadd_imm(&b, iv, c); + nir_def *addr = + nir_iadd(&b, base, nir_ishl_imm(&b, nir_u2u64(&b, idx), 2)); + nir_def *v = nir_load_global(&b, 1, 32, addr, .align_mul = 4); + nir_store_var(&b, sum_var, nir_iadd(&b, nir_load_var(&b, sum_var), v), 1); + nir_store_var(&b, iv_var, nir_iadd_imm(&b, iv, step_val), 1); + nir_pop_loop(&b, loop); + + nir_store_global(&b, nir_load_var(&b, sum_var), out, .align_mul = 4); + nir_lower_vars_to_ssa(b.shader); + agx_nir_lower_address(b.shader, true, true, false); + + int16_t folded = 0; + nir_foreach_block(block, b.impl) { + nir_foreach_instr(instr, block) { + if (instr->type != nir_instr_type_intrinsic || + nir_instr_as_intrinsic(instr)->intrinsic != + nir_intrinsic_load_agx) + continue; + nir_intrinsic_instr *ld = nir_instr_as_intrinsic(instr); + EXPECT_FALSE(nir_intrinsic_sign_extend(ld)); + folded = (int16_t)(nir_intrinsic_base(ld) >> + AGX_NIR_MEMORY_BYTE_OFFSET_SHIFT); + } + } + ralloc_free(b.shader); + return folded; + }; + + /* Positive: 0 <= iv <= INT32_MAX - 17, step 4 cannot wrap negative, +16 folds. */ + EXPECT_EQ(run_s32_loop(0, 4, 16u), 64); + /* Negative control: negative init can wrap u32 on +16. */ + EXPECT_EQ(run_s32_loop(-4, 4, 16u), 0); + /* Negative control: step 32 can wrap INT32_MAX to negative on next iteration. */ + EXPECT_EQ(run_s32_loop(0, 32, 16u), 0); +} + } // namespace diff --git a/src/asahi/compiler/test/test-opt-licm.cpp b/src/asahi/compiler/test/test-opt-licm.cpp index bf12c39e69bd..215e2b2a66dc 100644 --- a/src/asahi/compiler/test/test-opt-licm.cpp +++ b/src/asahi/compiler/test/test-opt-licm.cpp @@ -342,3 +342,31 @@ TEST(OptLicm, KeepsM5UnpackedScalarLodInLoop) EXPECT_EQ(count(l.body, AGX_OPCODE_MOV), 1u); EXPECT_EQ(count(l.entry, AGX_OPCODE_MOV), 1u); } + +/* Uniform copies consumed by scalar branch compares (IF_FCMP) hoist and merge + * with identical ALU copies in the loop; written uniforms stay pinned. */ +TEST(OptLicm, HoistsUniformUsedByBranchCompare) +{ + for (bool uniforms_written : {false, true}) { + Loop l; + agx_builder *b = l.b; + b->shader->uniforms_written = uniforms_written; + b->cursor = agx_after_block(l.entry); + agx_index w = busy_preheader(b); + + b->cursor = agx_after_block(l.body); + agx_index u1 = agx_mov(b, agx_uniform(22, AGX_SIZE_32)); + agx_index u2 = agx_mov(b, agx_uniform(22, AGX_SIZE_32)); + agx_instr *alu = agx_fadd_to(b, agx_temp(b->shader, AGX_SIZE_32), w, u2); + agx_instr *br = agx_if_fcmp(b, w, u1, 1, AGX_FCOND_GE, true, l.exit); + + b->cursor = agx_after_block(l.exit); + agx_unit_test(b, alu->dest[0]); + + EXPECT_EQ(licm(b->shader, 64), !uniforms_written); + EXPECT_EQ(count(l.body, AGX_OPCODE_MOV), uniforms_written ? 2u : 0u); + EXPECT_EQ(count(l.entry, AGX_OPCODE_MOV), uniforms_written ? 0u : 1u); + if (!uniforms_written) + EXPECT_EQ(br->src[1].value, alu->src[1].value); + } +} From 3ea292e40fc136a55af00d6440bdee1369efdd5c Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Fri, 27 Nov 2026 02:02:55 -0500 Subject: [PATCH 2/2] asahi/compiler: pass NULL top_level_out to aurora-wip count_unrollable caller Fix the 1-line compile break after merging aurora-wip's new count_unrollable() call site in agx_nir_unroll_runtime_loops.c. Signed-off-by: DjDeveloperr --- src/asahi/compiler/agx_nir_unroll_runtime_loops.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/asahi/compiler/agx_nir_unroll_runtime_loops.c b/src/asahi/compiler/agx_nir_unroll_runtime_loops.c index 588691f11096..82d25c09d4ef 100644 --- a/src/asahi/compiler/agx_nir_unroll_runtime_loops.c +++ b/src/asahi/compiler/agx_nir_unroll_runtime_loops.c @@ -1497,7 +1497,7 @@ peel_straight_prefix(nir_function_impl *impl, nir_loop *loop, unsigned count, struct counted_loop cl; if (!analyze_loop(loop, &cl) || cl.bottom) return false; - if (count_unrollable(loop, cl.nif) < 0) + if (count_unrollable(loop, cl.nif, NULL) < 0) return false; nir_foreach_block_in_cf_node(block, &loop->cf_node)