diff --git a/src/asahi/vulkan/hk_cmd_dispatch.c b/src/asahi/vulkan/hk_cmd_dispatch.c index 309205ea5ee9..6abf7cb6b9f7 100644 --- a/src/asahi/vulkan/hk_cmd_dispatch.c +++ b/src/asahi/vulkan/hk_cmd_dispatch.c @@ -5351,6 +5351,20 @@ dispatch_grid_shader(struct hk_cmd_buffer *cmd, struct hk_shader *s, cs->sib_threads = threads > UINT64_MAX - cs->sib_threads ? UINT64_MAX : cs->sib_threads + threads; + if (selected->b.info.has_loops && loop_bound == 0 && !in_threads && + selected->pack_loop_bound.valid && + desc->root.cs.base_group[0] == 0 && + desc->root.cs.base_group[1] == 0 && + desc->root.cs.base_group[2] == 0 && + grid.count[0] <= (uint32_t)INT32_MAX && + grid.count[1] <= (uint32_t)INT32_MAX && + grid.count[2] <= (uint32_t)INT32_MAX) { + hk_pack_eval_effective_instrs_dispatch( + &selected->pack_loop_bound, selected->b.info.stats.instrs, + pack_loop_params, desc->root.push, sizeof(desc->root.push), + orig_groups, &loop_bound); + } + uint64_t work = 0; cs->pack_loops |= hk_pack_account_dispatch_work_eff_limit( threads, selected->b.info.stats.instrs, selected->b.info.has_loops, diff --git a/src/asahi/vulkan/hk_nir_loop_bound.h b/src/asahi/vulkan/hk_nir_loop_bound.h index 604832ef512f..fa8903d667a5 100644 --- a/src/asahi/vulkan/hk_nir_loop_bound.h +++ b/src/asahi/vulkan/hk_nir_loop_bound.h @@ -14,7 +14,7 @@ struct hk_nir_loop_param_binding { enum hk_pack_loop_param param; }; -#define HK_NIR_LOOP_MAX_BINDINGS 16u +#define HK_NIR_LOOP_MAX_BINDINGS 128u struct hk_nir_loop_binding_list { struct hk_nir_loop_param_binding entries[HK_NIR_LOOP_MAX_BINDINGS]; @@ -39,6 +39,7 @@ hk_nir_loop_binding_add(struct hk_nir_loop_binding_list *list, } struct hk_nir_lb_builder { + const nir_shader *nir; struct hk_pack_loop_op *ops; uint8_t *count; uint8_t max_ops; @@ -299,181 +300,1430 @@ hk_nir_lb_val_mul(struct hk_nir_lb_builder *b, struct hk_nir_lb_val a, } static inline bool -hk_nir_lb_is_simple_break_if(nir_if *nif) +hk_nir_lb_list_is_lone_break(struct exec_list *list) { - if (exec_list_is_empty(&nif->then_list) || - exec_list_get_head(&nif->then_list) != - exec_list_get_tail(&nif->then_list)) + if (exec_list_is_empty(list) || + exec_list_get_head(list) != exec_list_get_tail(list)) return false; - nir_cf_node *tn = - exec_node_data(nir_cf_node, exec_list_get_head(&nif->then_list), node); - if (tn->type != nir_cf_node_block) + nir_cf_node *n = + exec_node_data(nir_cf_node, exec_list_get_head(list), node); + if (n->type != nir_cf_node_block) return false; - nir_block *tb = nir_cf_node_as_block(tn); + nir_block *tb = nir_cf_node_as_block(n); if (exec_list_is_empty(&tb->instr_list) || exec_list_get_head(&tb->instr_list) != exec_list_get_tail(&tb->instr_list)) return false; nir_instr *ti = exec_node_data(nir_instr, exec_list_get_head(&tb->instr_list), node); - if (ti->type != nir_instr_type_jump || - nir_instr_as_jump(ti)->type != nir_jump_break) + return ti->type == nir_instr_type_jump && + nir_instr_as_jump(ti)->type == nir_jump_break; +} + +static inline bool +hk_nir_lb_list_is_empty_block(struct exec_list *list) +{ + if (exec_list_is_empty(list) || + exec_list_get_head(list) != exec_list_get_tail(list)) return false; + nir_cf_node *n = + exec_node_data(nir_cf_node, exec_list_get_head(list), node); + return n->type == nir_cf_node_block && + exec_list_is_empty(&nir_cf_node_as_block(n)->instr_list); +} + +static inline bool +hk_nir_lb_is_simple_break_if(nir_if *nif, bool *break_in_then) +{ + if (hk_nir_lb_list_is_lone_break(&nif->then_list) && + hk_nir_lb_list_is_empty_block(&nif->else_list)) { + *break_in_then = true; + return true; + } + if (hk_nir_lb_list_is_lone_break(&nif->else_list) && + hk_nir_lb_list_is_empty_block(&nif->then_list)) { + *break_in_then = false; + return true; + } + return false; +} - if (exec_list_is_empty(&nif->else_list) || - exec_list_get_head(&nif->else_list) != - exec_list_get_tail(&nif->else_list)) +static inline bool +hk_nir_lb_is_zero_when_base0(nir_scalar s, unsigned depth) +{ + s = nir_scalar_resolved(s.def, s.comp); + if (nir_scalar_is_const(s)) + return nir_scalar_as_uint(s) == 0; + if (!depth) return false; - nir_cf_node *en = - exec_node_data(nir_cf_node, exec_list_get_head(&nif->else_list), node); - if (en->type != nir_cf_node_block) + if (nir_scalar_is_intrinsic(s)) + return nir_scalar_intrinsic_op(s) == nir_intrinsic_load_base_workgroup_id; + if (!nir_scalar_is_alu(s)) return false; - return exec_list_is_empty(&nir_cf_node_as_block(en)->instr_list); + const nir_op op = nir_scalar_alu_op(s); + if (op == nir_op_ishl) + return hk_nir_lb_is_zero_when_base0(nir_scalar_chase_alu_src(s, 0), depth - 1); + if (op == nir_op_imul || op == nir_op_amul) { + return hk_nir_lb_is_zero_when_base0(nir_scalar_chase_alu_src(s, 0), depth - 1) || + hk_nir_lb_is_zero_when_base0(nir_scalar_chase_alu_src(s, 1), depth - 1); + } + return false; } -static inline struct hk_nir_lb_val -hk_nir_lb_loop_trips(struct hk_nir_lb_builder *b, nir_loop *loop) +static inline bool +hk_nir_lb_is_wg_id_axis(nir_scalar s, unsigned *axis_out, unsigned depth) +{ + s = nir_scalar_resolved(s.def, s.comp); + if (nir_scalar_is_intrinsic(s) && + nir_scalar_intrinsic_op(s) == nir_intrinsic_load_workgroup_id && + s.comp < 3) { + *axis_out = s.comp; + return true; + } + if (depth && nir_scalar_is_alu(s) && nir_scalar_alu_op(s) == nir_op_iadd) { + nir_scalar s0 = nir_scalar_chase_alu_src(s, 0); + nir_scalar s1 = nir_scalar_chase_alu_src(s, 1); + if (hk_nir_lb_is_zero_when_base0(s0, depth - 1)) + return hk_nir_lb_is_wg_id_axis(s1, axis_out, depth - 1); + if (hk_nir_lb_is_zero_when_base0(s1, depth - 1)) + return hk_nir_lb_is_wg_id_axis(s0, axis_out, depth - 1); + } + return false; +} + +static inline bool +hk_nir_lb_is_num_wg_axis(nir_scalar s, unsigned axis) +{ + s = nir_scalar_resolved(s.def, s.comp); + return nir_scalar_is_intrinsic(s) && + nir_scalar_intrinsic_op(s) == nir_intrinsic_load_num_workgroups && + s.comp == axis; +} + +static inline bool +hk_nir_lb_eval_const_u32(nir_scalar s, uint64_t *val_out, unsigned depth) +{ + s = nir_scalar_resolved(s.def, s.comp); + if (nir_scalar_is_const(s)) { + *val_out = nir_scalar_as_uint(s); + return true; + } + if (depth && nir_scalar_is_alu(s) && nir_scalar_alu_op(s) == nir_op_iadd) { + uint64_t a = 0, c = 0; + if (hk_nir_lb_eval_const_u32(nir_scalar_chase_alu_src(s, 0), &a, depth - 1) && + hk_nir_lb_eval_const_u32(nir_scalar_chase_alu_src(s, 1), &c, depth - 1)) { + *val_out = (uint32_t)(a + c); + return true; + } + } + return false; +} + +static inline bool +hk_nir_lb_push_offset(nir_scalar s, uint32_t *off_out) +{ + s = nir_scalar_resolved(s.def, s.comp); + if (!nir_scalar_is_intrinsic(s)) + return false; + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(nir_def_instr(s.def)); + if (intr->intrinsic != nir_intrinsic_load_push_constant) + return false; + uint64_t src_off = 0; + if (!hk_nir_lb_eval_const_u32(nir_get_scalar(intr->src[0].ssa, 0), &src_off, 4)) + return false; + const uint64_t off = (uint64_t)nir_intrinsic_base(intr) + src_off + + (uint64_t)s.comp * 4ull; + if (off > 252ull || (off % 4ull) != 0) + return false; + *off_out = (uint32_t)off; + return true; +} + +static inline bool +hk_nir_lb_same_scalar_or_push(nir_scalar a, nir_scalar b, unsigned depth) +{ + a = nir_scalar_resolved(a.def, a.comp); + b = nir_scalar_resolved(b.def, b.comp); + if (nir_scalar_equal(a, b)) + return true; + if (nir_scalar_is_const(a) && nir_scalar_is_const(b)) + return nir_scalar_as_uint(a) == nir_scalar_as_uint(b); + uint32_t oa = 0, ob = 0; + if (hk_nir_lb_push_offset(a, &oa) && hk_nir_lb_push_offset(b, &ob)) + return oa == ob; + if (depth && nir_scalar_is_alu(a) && nir_scalar_is_alu(b) && + nir_scalar_alu_op(a) == nir_scalar_alu_op(b)) { + const nir_op op = nir_scalar_alu_op(a); + if (op == nir_op_iadd || op == nir_op_imul || op == nir_op_amul) { + nir_scalar a0 = nir_scalar_chase_alu_src(a, 0); + nir_scalar a1 = nir_scalar_chase_alu_src(a, 1); + nir_scalar b0 = nir_scalar_chase_alu_src(b, 0); + nir_scalar b1 = nir_scalar_chase_alu_src(b, 1); + return (hk_nir_lb_same_scalar_or_push(a0, b0, depth - 1) && + hk_nir_lb_same_scalar_or_push(a1, b1, depth - 1)) || + (hk_nir_lb_same_scalar_or_push(a0, b1, depth - 1) && + hk_nir_lb_same_scalar_or_push(a1, b0, depth - 1)); + } + } + return false; +} + +/* Return true when `init_s` is guaranteed >= 0 at dispatch time (with + * base_group == 0 and grid * wg_size <= INT32_MAX). */ +static inline bool +hk_nir_lb_init_nonneg(nir_scalar init_s, nir_scalar step_s, bool is_unsigned, + unsigned depth) +{ + if (is_unsigned) + return true; + init_s = nir_scalar_resolved(init_s.def, init_s.comp); + if (nir_scalar_is_const(init_s)) + return nir_scalar_as_int(init_s) >= 0; + if (nir_scalar_is_intrinsic(init_s)) { + switch (nir_scalar_intrinsic_op(init_s)) { + case nir_intrinsic_load_local_invocation_id: + case nir_intrinsic_load_local_invocation_index: + case nir_intrinsic_load_workgroup_id: + case nir_intrinsic_load_global_invocation_id: + case nir_intrinsic_load_base_workgroup_id: + case nir_intrinsic_load_subgroup_invocation: + case nir_intrinsic_load_subgroup_id: + return true; + default: + return false; + } + } + if (!depth || !nir_scalar_is_alu(init_s)) + return false; + const nir_op op = nir_scalar_alu_op(init_s); + if (op == nir_op_iadd) { + nir_scalar s0 = nir_scalar_chase_alu_src(init_s, 0); + nir_scalar s1 = nir_scalar_chase_alu_src(init_s, 1); + if (hk_nir_lb_is_zero_when_base0(s0, depth - 1)) + return hk_nir_lb_init_nonneg(s1, step_s, false, depth - 1); + if (hk_nir_lb_is_zero_when_base0(s1, depth - 1)) + return hk_nir_lb_init_nonneg(s0, step_s, false, depth - 1); + } + /* Grid-stride scaled init: wg_id[axis] * F with step == num_wg[axis] * F. + * Since OP_CEIL_DIV_I32 verifies step = num_wg[axis] * F <= INT32_MAX and + * F >= 1, 0 <= wg_id[axis] * F < step <= INT32_MAX cannot wrap negative. */ + if (op == nir_op_imul || op == nir_op_amul) { + step_s = nir_scalar_resolved(step_s.def, step_s.comp); + if (nir_scalar_is_alu(step_s) && + (nir_scalar_alu_op(step_s) == nir_op_imul || + nir_scalar_alu_op(step_s) == nir_op_amul)) { + nir_scalar i0 = nir_scalar_chase_alu_src(init_s, 0); + nir_scalar i1 = nir_scalar_chase_alu_src(init_s, 1); + nir_scalar st0 = nir_scalar_chase_alu_src(step_s, 0); + nir_scalar st1 = nir_scalar_chase_alu_src(step_s, 1); + for (unsigned a = 0; a < 2; ++a) { + nir_scalar wg = a == 0 ? i0 : i1; + nir_scalar fac = a == 0 ? i1 : i0; + unsigned axis = 0; + if (!hk_nir_lb_is_wg_id_axis(wg, &axis, 4)) + continue; + for (unsigned c = 0; c < 2; ++c) { + nir_scalar nwg = c == 0 ? st0 : st1; + nir_scalar sfac = c == 0 ? st1 : st0; + if (hk_nir_lb_is_num_wg_axis(nwg, axis) && + hk_nir_lb_same_scalar_or_push(fac, sfac, 2)) + return true; + } + } + } + } + return false; +} + +static inline bool +hk_nir_lb_is_const_div_or_shr(nir_scalar s, nir_scalar *num_out, + uint32_t *div_out, bool *is_signed_out) +{ + s = nir_scalar_resolved(s.def, s.comp); + if (!nir_scalar_is_alu(s) || s.def->bit_size != 32) + return false; + const nir_op op = nir_scalar_alu_op(s); + if (op == nir_op_ushr || op == nir_op_ishr) { + nir_scalar v = nir_scalar_chase_alu_src(s, 0); + nir_scalar k = nir_scalar_chase_alu_src(s, 1); + if (nir_scalar_is_const(k)) { + const uint64_t sh = nir_scalar_as_uint(k); + if (sh >= 1 && sh < 31) { + /* Standard nir_opt_idiv_const lowering: + * ishr(iadd(x, iand(ishr(x, 31), (1<= 2 && dv <= UINT32_MAX) { + *num_out = v; + *div_out = (uint32_t)dv; + *is_signed_out = (op == nir_op_idiv); + return true; + } + } + return false; + } + /* Lowered signed pow2 idiv: imul(imin(imax(x, -1), 1), ushr(imax(x, ineg(x)), k)). */ + if (op == nir_op_imul || op == nir_op_amul) { + nir_scalar m0 = nir_scalar_chase_alu_src(s, 0); + nir_scalar m1 = nir_scalar_chase_alu_src(s, 1); + for (unsigned i = 0; i < 2; ++i) { + nir_scalar sgn = i == 0 ? m0 : m1; + nir_scalar mag = i == 0 ? m1 : m0; + if (!nir_scalar_is_alu(mag) || nir_scalar_alu_op(mag) != nir_op_ushr) + continue; + nir_scalar k = nir_scalar_chase_alu_src(mag, 1); + if (!nir_scalar_is_const(k)) + continue; + const uint64_t sh = nir_scalar_as_uint(k); + if (sh < 1 || sh >= 31) + continue; + nir_scalar absv = nir_scalar_chase_alu_src(mag, 0); + nir_scalar x = {0}; + if (nir_scalar_is_alu(absv) && nir_scalar_alu_op(absv) == nir_op_iabs) { + x = nir_scalar_chase_alu_src(absv, 0); + } else if (nir_scalar_is_alu(absv) && nir_scalar_alu_op(absv) == nir_op_imax) { + nir_scalar b0 = nir_scalar_chase_alu_src(absv, 0); + nir_scalar b1 = nir_scalar_chase_alu_src(absv, 1); + if (nir_scalar_is_alu(b1) && nir_scalar_alu_op(b1) == nir_op_ineg && + nir_scalar_equal(nir_scalar_chase_alu_src(b1, 0), b0)) + x = b0; + else if (nir_scalar_is_alu(b0) && nir_scalar_alu_op(b0) == nir_op_ineg && + nir_scalar_equal(nir_scalar_chase_alu_src(b0, 0), b1)) + x = b1; + } + if (!x.def) + continue; + /* Verify sgn == isign(x) = imin(imax(x, -1), 1) or isign(x). */ + bool ok_sgn = false; + if (nir_scalar_is_alu(sgn) && nir_scalar_alu_op(sgn) == nir_op_isign && + nir_scalar_equal(nir_scalar_chase_alu_src(sgn, 0), x)) { + ok_sgn = true; + } else if (nir_scalar_is_alu(sgn) && nir_scalar_alu_op(sgn) == nir_op_imin) { + nir_scalar n0 = nir_scalar_chase_alu_src(sgn, 0); + nir_scalar n1 = nir_scalar_chase_alu_src(sgn, 1); + nir_scalar inner = {0}; + if (nir_scalar_is_const(n1) && nir_scalar_as_int(n1) == 1) + inner = n0; + else if (nir_scalar_is_const(n0) && nir_scalar_as_int(n0) == 1) + inner = n1; + if (inner.def && nir_scalar_is_alu(inner) && + nir_scalar_alu_op(inner) == nir_op_imax) { + nir_scalar p0 = nir_scalar_chase_alu_src(inner, 0); + nir_scalar p1 = nir_scalar_chase_alu_src(inner, 1); + if ((nir_scalar_is_const(p1) && nir_scalar_as_int(p1) == -1 && + nir_scalar_equal(p0, x)) || + (nir_scalar_is_const(p0) && nir_scalar_as_int(p0) == -1 && + nir_scalar_equal(p1, x))) + ok_sgn = true; + } + } + if (ok_sgn) { + *num_out = x; + *div_out = 1u << sh; + *is_signed_out = true; + return true; + } + } + } + return false; +} + +static inline bool +hk_nir_lb_is_shr_of(nir_scalar cand, nir_scalar base) +{ + cand = nir_scalar_resolved(cand.def, cand.comp); + if (!nir_scalar_is_alu(cand)) + return false; + const nir_op op = nir_scalar_alu_op(cand); + if ((op == nir_op_ishr || op == nir_op_ushr) && + nir_scalar_is_const(nir_scalar_chase_alu_src(cand, 1)) && + nir_scalar_equal(nir_scalar_chase_alu_src(cand, 0), base)) + return true; + /* NIR lowers ishr(x, 16) to extract_i16(x, 1) or i2i32(unpack_32_2x16_split_y(x)). */ + if ((op == nir_op_extract_i16 || op == nir_op_extract_u16) && + nir_scalar_is_const(nir_scalar_chase_alu_src(cand, 1)) && + nir_scalar_as_uint(nir_scalar_chase_alu_src(cand, 1)) == 1 && + nir_scalar_equal(nir_scalar_chase_alu_src(cand, 0), base)) + return true; + if ((op == nir_op_i2i32 || op == nir_op_u2u32)) { + nir_scalar u = nir_scalar_chase_alu_src(cand, 0); + if (nir_scalar_is_alu(u) && + nir_scalar_alu_op(u) == nir_op_unpack_32_2x16_split_y && + nir_scalar_equal(nir_scalar_chase_alu_src(u, 0), base)) + return true; + } + return false; +} + +/* Match bit-smear `(base - 1) | (>>1) | ... | (>>16) == next_pow2(base) - 1`. */ +static inline bool +hk_nir_lb_match_pow2_smear(nir_scalar sm, nir_scalar *base_out) +{ + sm = nir_scalar_resolved(sm.def, sm.comp); + unsigned steps = 0; + while (steps < 6 && nir_scalar_is_alu(sm) && + nir_scalar_alu_op(sm) == nir_op_ior) { + nir_scalar o0 = nir_scalar_chase_alu_src(sm, 0); + nir_scalar o1 = nir_scalar_chase_alu_src(sm, 1); + if (hk_nir_lb_is_shr_of(o1, o0)) + sm = o0; + else if (hk_nir_lb_is_shr_of(o0, o1)) + sm = o1; + else + break; + steps++; + } + if (steps == 0 || !nir_scalar_is_alu(sm) || + nir_scalar_alu_op(sm) != nir_op_iadd) + return false; + nir_scalar b0 = nir_scalar_chase_alu_src(sm, 0); + nir_scalar b1 = nir_scalar_chase_alu_src(sm, 1); + if (nir_scalar_is_const(b0) && nir_scalar_as_int(b0) == -1) { + *base_out = b1; + return true; + } + if (nir_scalar_is_const(b1) && nir_scalar_as_int(b1) == -1) { + *base_out = b0; + return true; + } + return false; +} + +static inline int +hk_nir_lb_emit_push_or_grid_expr(struct hk_nir_lb_builder *b, nir_scalar s, + bool is_unsigned, bool is_limit, + bool require_nonneg, unsigned depth) +{ + if (b->failed || !depth) + return -1; + s = nir_scalar_resolved(s.def, s.comp); + if (s.def->bit_size != 32) + return -1; + + if (nir_scalar_is_const(s)) { + if (is_unsigned) { + const uint32_t u = (uint32_t)nir_scalar_as_uint(s); + if (!is_limit && u == 0) + return -1; + return hk_nir_lb_const(b, u); + } else { + const int32_t v = (int32_t)nir_scalar_as_int(s); + if (!is_limit && v <= 0) + return -1; + if (require_nonneg && v < 0) + return -1; + return hk_nir_lb_const(b, v > 0 ? (uint32_t)v : 0u); + } + } + + if (nir_scalar_is_intrinsic(s)) { + uint32_t off = 0; + if (hk_nir_lb_push_offset(s, &off)) { + return hk_nir_lb_emit(b, (struct hk_pack_loop_op){ + .kind = is_unsigned + ? HK_PACK_LOOP_OP_PUSH_U32 + : (require_nonneg ? HK_PACK_LOOP_OP_PUSH_I32_NONNEG + : HK_PACK_LOOP_OP_PUSH_I32_POS), + .imm = off, + }); + } + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(nir_def_instr(s.def)); + if (intr->intrinsic == nir_intrinsic_load_num_workgroups && s.comp < 3) { + return hk_nir_lb_emit(b, (struct hk_pack_loop_op){ + .kind = HK_PACK_LOOP_OP_GRID_GROUPS, + .imm = s.comp, + }); + } + if (intr->intrinsic == nir_intrinsic_load_workgroup_size && s.comp < 3 && + b->nir && !b->nir->info.workgroup_size_variable) { + const uint32_t wg = b->nir->info.workgroup_size[s.comp]; + if (!is_limit && wg == 0) + return -1; + return hk_nir_lb_const(b, wg); + } + return -1; + } + + if (!nir_scalar_is_alu(s)) + return -1; + const nir_op op = nir_scalar_alu_op(s); + if (op == nir_op_ishl) { + nir_scalar sh = nir_scalar_chase_alu_src(s, 1); + if (!nir_scalar_is_const(sh)) + return -1; + const uint64_t k = nir_scalar_as_uint(sh); + if (k >= 31) + return -1; + const int lhs = hk_nir_lb_emit_push_or_grid_expr( + b, nir_scalar_chase_alu_src(s, 0), is_unsigned, is_limit, + require_nonneg, depth - 1); + if (lhs < 0) + return -1; + return hk_nir_lb_mul(b, lhs, hk_nir_lb_const(b, 1u << k)); + } + /* Constant division / right shift (e.g. radius = kernel_size / 2). */ + { + nir_scalar num = {0}; + uint32_t div = 0; + bool div_signed = false; + if (hk_nir_lb_is_const_div_or_shr(s, &num, &div, &div_signed) && + div >= 2 && (!div_signed || !is_unsigned)) { + const int num_op = hk_nir_lb_emit_push_or_grid_expr( + b, num, !div_signed, is_limit, true, depth - 1); + if (num_op >= 0) { + return hk_nir_lb_emit(b, (struct hk_pack_loop_op){ + .kind = HK_PACK_LOOP_OP_DIV_CONST, + .lhs = (uint8_t)num_op, + .imm = div, + }); + } + } + } + if (op == nir_op_imul || op == nir_op_amul) { + /* Clamping either negative factor to zero could undercount their product. */ + const int lhs = hk_nir_lb_emit_push_or_grid_expr( + b, nir_scalar_chase_alu_src(s, 0), is_unsigned, is_limit, + true, depth - 1); + const int rhs = hk_nir_lb_emit_push_or_grid_expr( + b, nir_scalar_chase_alu_src(s, 1), is_unsigned, is_limit, + true, depth - 1); + if (lhs < 0 || rhs < 0) + return -1; + return hk_nir_lb_mul(b, lhs, rhs); + } + /* Upper-bound next_pow2(C) - 1 and next_pow2(C) <= 2*C (requiring C >= 0). */ + if (is_limit && !is_unsigned) { + nir_scalar base = {0}; + if (op == nir_op_ior && hk_nir_lb_match_pow2_smear(s, &base)) { + const int c_op = hk_nir_lb_emit_push_or_grid_expr( + b, base, false, true, true, depth - 1); + if (c_op >= 0) + return hk_nir_lb_mul(b, c_op, hk_nir_lb_const(b, 2)); + } + if (op == nir_op_iadd) { + nir_scalar a0 = nir_scalar_chase_alu_src(s, 0); + nir_scalar a1 = nir_scalar_chase_alu_src(s, 1); + nir_scalar sm = {0}; + if (nir_scalar_is_const(a0) && nir_scalar_as_int(a0) == 1) + sm = a1; + else if (nir_scalar_is_const(a1) && nir_scalar_as_int(a1) == 1) + sm = a0; + if (sm.def && hk_nir_lb_match_pow2_smear(sm, &base)) { + const int c_op = hk_nir_lb_emit_push_or_grid_expr( + b, base, false, true, true, depth - 1); + if (c_op >= 0) + return hk_nir_lb_mul(b, c_op, hk_nir_lb_const(b, 2)); + } + } + /* Upper-bound `A - local_invocation_id` (or `A + ineg(lid)`) by upper + * bound of `A` (since 0 <= lid < wg_size <= 1024, subtracting lid cannot + * underflow INT32_MIN when A >= -1). */ + if ((op == nir_op_isub || op == nir_op_iadd) && + b->nir && !b->nir->info.workgroup_size_variable) { + nir_scalar a = {0}, sub = {0}; + if (op == nir_op_isub) { + a = nir_scalar_chase_alu_src(s, 0); + sub = nir_scalar_chase_alu_src(s, 1); + } else { + nir_scalar s0 = nir_scalar_chase_alu_src(s, 0); + nir_scalar s1 = nir_scalar_chase_alu_src(s, 1); + if (nir_scalar_is_alu(s1) && nir_scalar_alu_op(s1) == nir_op_ineg) { + a = s0; + sub = nir_scalar_chase_alu_src(s1, 0); + } else if (nir_scalar_is_alu(s0) && nir_scalar_alu_op(s0) == nir_op_ineg) { + a = s1; + sub = nir_scalar_chase_alu_src(s0, 0); + } + } + if (sub.def && nir_scalar_is_intrinsic(sub) && + (nir_scalar_intrinsic_op(sub) == nir_intrinsic_load_local_invocation_id || + nir_scalar_intrinsic_op(sub) == nir_intrinsic_load_local_invocation_index)) { + const int a_op = hk_nir_lb_emit_push_or_grid_expr( + b, a, false, true, true, depth - 1); + if (a_op >= 0) + return a_op; + } + } + } + /* Non-negative additive limit expressions (e.g. `2 * radius + TILE_W` in + * tiled stencil loaders). Overflow is checked at dispatch evaluation time + * by HK_PACK_LOOP_OP_ADD and the enclosing CEIL_DIV_I32/U32. */ + if (is_limit && op == nir_op_iadd) { + const uint8_t saved_count = *b->count; + const bool saved_failed = b->failed; + const int lhs = hk_nir_lb_emit_push_or_grid_expr( + b, nir_scalar_chase_alu_src(s, 0), is_unsigned, true, true, depth - 1); + const int rhs = lhs >= 0 + ? hk_nir_lb_emit_push_or_grid_expr( + b, nir_scalar_chase_alu_src(s, 1), is_unsigned, + true, true, depth - 1) + : -1; + if (lhs >= 0 && rhs >= 0 && !b->failed) + return hk_nir_lb_add(b, lhs, rhs); + *b->count = saved_count; + b->failed = saved_failed; + } + return -1; +} + +static inline int +hk_nir_lb_emit_grid_coord_max(struct hk_nir_lb_builder *b, nir_scalar s, + unsigned depth) +{ + if (b->failed || !depth) + return -1; + s = nir_scalar_resolved(s.def, s.comp); + if (s.def->bit_size != 32) + return -1; + if (nir_scalar_is_const(s)) { + const int32_t v = (int32_t)nir_scalar_as_int(s); + return v >= 0 ? hk_nir_lb_const(b, (uint32_t)v) : -1; + } + if (nir_scalar_is_intrinsic(s)) { + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(nir_def_instr(s.def)); + switch (intr->intrinsic) { + case nir_intrinsic_load_workgroup_id: + if (s.comp < 3) { + return hk_nir_lb_emit(b, (struct hk_pack_loop_op){ + .kind = HK_PACK_LOOP_OP_GRID_GROUPS, + .imm = s.comp, + }); + } + return -1; + case nir_intrinsic_load_global_invocation_id: + if (s.comp < 3 && b->nir && !b->nir->info.workgroup_size_variable) { + const uint32_t wg = b->nir->info.workgroup_size[s.comp]; + const int g = hk_nir_lb_emit(b, (struct hk_pack_loop_op){ + .kind = HK_PACK_LOOP_OP_GRID_GROUPS, + .imm = s.comp, + }); + return hk_nir_lb_mul(b, g, hk_nir_lb_const(b, wg)); + } + return -1; + case nir_intrinsic_load_local_invocation_id: + if (s.comp < 3 && b->nir && !b->nir->info.workgroup_size_variable) + return hk_nir_lb_const(b, b->nir->info.workgroup_size[s.comp]); + return -1; + case nir_intrinsic_load_local_invocation_index: + if (b->nir && !b->nir->info.workgroup_size_variable) { + const uint64_t sz = (uint64_t)b->nir->info.workgroup_size[0] * + b->nir->info.workgroup_size[1] * + b->nir->info.workgroup_size[2]; + if (sz <= UINT32_MAX) + return hk_nir_lb_const(b, (uint32_t)sz); + } + return -1; + case nir_intrinsic_load_base_workgroup_id: + return hk_nir_lb_const(b, 0); + default: + return -1; + } + } + if (!nir_scalar_is_alu(s)) + return -1; + const nir_op op = nir_scalar_alu_op(s); + if (op == nir_op_iadd) { + nir_scalar s0 = nir_scalar_chase_alu_src(s, 0); + nir_scalar s1 = nir_scalar_chase_alu_src(s, 1); + if (hk_nir_lb_is_zero_when_base0(s0, depth - 1)) + return hk_nir_lb_emit_grid_coord_max(b, s1, depth - 1); + if (hk_nir_lb_is_zero_when_base0(s1, depth - 1)) + return hk_nir_lb_emit_grid_coord_max(b, s0, depth - 1); + const int m0 = hk_nir_lb_emit_grid_coord_max(b, s0, depth - 1); + const int m1 = hk_nir_lb_emit_grid_coord_max(b, s1, depth - 1); + if (m0 >= 0 && m1 >= 0) + return hk_nir_lb_add(b, m0, m1); + } + if (op == nir_op_imul || op == nir_op_amul) { + const int m0 = hk_nir_lb_emit_grid_coord_max(b, nir_scalar_chase_alu_src(s, 0), depth - 1); + const int m1 = hk_nir_lb_emit_grid_coord_max(b, nir_scalar_chase_alu_src(s, 1), depth - 1); + if (m0 >= 0 && m1 >= 0) + return hk_nir_lb_mul(b, m0, m1); + } + if (op == nir_op_ishl) { + nir_scalar sh = nir_scalar_chase_alu_src(s, 1); + if (nir_scalar_is_const(sh) && nir_scalar_as_uint(sh) < 31) { + const int m0 = hk_nir_lb_emit_grid_coord_max(b, nir_scalar_chase_alu_src(s, 0), depth - 1); + if (m0 >= 0) + return hk_nir_lb_mul(b, m0, hk_nir_lb_const(b, 1u << nir_scalar_as_uint(sh))); + } + } + return -1; +} + +static inline bool +hk_nir_lb_split_window_lo(nir_scalar s, nir_scalar *base_out, + nir_scalar *rad_out, uint32_t *const_rad_out) +{ + s = nir_scalar_resolved(s.def, s.comp); + *rad_out = (nir_scalar){0}; + *const_rad_out = 0; + if (nir_scalar_is_alu(s)) { + const nir_op op = nir_scalar_alu_op(s); + if (op == nir_op_isub) { + *base_out = nir_scalar_chase_alu_src(s, 0); + *rad_out = nir_scalar_chase_alu_src(s, 1); + return true; + } + if (op == nir_op_iadd) { + nir_scalar a0 = nir_scalar_chase_alu_src(s, 0); + nir_scalar a1 = nir_scalar_chase_alu_src(s, 1); + if (nir_scalar_is_alu(a1) && nir_scalar_alu_op(a1) == nir_op_ineg) { + *base_out = a0; + *rad_out = nir_scalar_chase_alu_src(a1, 0); + return true; + } + if (nir_scalar_is_alu(a0) && nir_scalar_alu_op(a0) == nir_op_ineg) { + *base_out = a1; + *rad_out = nir_scalar_chase_alu_src(a0, 0); + return true; + } + if (nir_scalar_is_const(a1) && nir_scalar_as_int(a1) <= 0 && + nir_scalar_as_int(a1) > INT32_MIN) { + *base_out = a0; + *const_rad_out = (uint32_t)(-nir_scalar_as_int(a1)); + return true; + } + if (nir_scalar_is_const(a0) && nir_scalar_as_int(a0) <= 0 && + nir_scalar_as_int(a0) > INT32_MIN) { + *base_out = a1; + *const_rad_out = (uint32_t)(-nir_scalar_as_int(a0)); + return true; + } + } + } + *base_out = s; + return true; +} + +/* Match a 2-source if-phi that implements signed min(A, B) (want_max=false) + * or signed max(A, B) (want_max=true) prior to nir_opt_peephole_select. */ +static inline bool +hk_nir_lb_extract_if_phi_minmax(nir_scalar s, bool want_max, + nir_scalar out_cands[2]) +{ + s = nir_scalar_resolved(s.def, s.comp); + if (nir_def_instr(s.def)->type != nir_instr_type_phi) + return false; + nir_phi_instr *phi = nir_instr_as_phi(nir_def_instr(s.def)); + nir_block *merge = phi->instr.block; + nir_cf_node *prev = nir_cf_node_prev(&merge->cf_node); + if (!prev || prev->type != nir_cf_node_if) + return false; + nir_if *nif = nir_cf_node_as_if(prev); + nir_block *then_last = nir_if_last_then_block(nif); + nir_block *else_last = nir_if_last_else_block(nif); + nir_scalar then_v = {0}, else_v = {0}; + unsigned count = 0; + nir_foreach_phi_src(ps, phi) { + count++; + if (ps->pred == then_last) + then_v = nir_scalar_resolved(ps->src.ssa, s.comp); + else if (ps->pred == else_last) + else_v = nir_scalar_resolved(ps->src.ssa, s.comp); + } + if (count != 2 || !then_v.def || !else_v.def) + return false; + + 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)) + return false; + const nir_op cop = nir_scalar_alu_op(cond); + if (cop != nir_op_ilt && cop != nir_op_ige) + return false; + nir_scalar c0 = nir_scalar_chase_alu_src(cond, 0); + nir_scalar c1 = nir_scalar_chase_alu_src(cond, 1); + /* cond_lt == true means the then-branch runs when c0 < c1. */ + const bool cond_lt = (cop == nir_op_ilt) != neg; + /* For min: when c0 < c1, then picks c0 and else picks c1 (or when c0 >= c1, then picks c1 and else picks c0). + * For max: when c0 < c1, then picks c1 and else picks c0 (or when c0 >= c1, then picks c0 and else picks c1). */ + const bool then_picks_c0 = (cond_lt != want_max); + nir_scalar expect_then = then_picks_c0 ? c0 : c1; + nir_scalar expect_else = then_picks_c0 ? c1 : c0; + if (hk_nir_lb_same_scalar_or_push(then_v, expect_then, 2) && + hk_nir_lb_same_scalar_or_push(else_v, expect_else, 2)) { + out_cands[0] = then_v; + out_cands[1] = else_v; + return true; + } + return false; +} + +/* Try bounding a signed sliding-window/stencil loop: + * init = [max(] base - rad_lo [, L)] + * lim = [min(] base + rad_hi [, U)] + * with base a non-negative grid coordinate. Verifies at dispatch time that + * neither base - rad_lo nor base + rad_hi + strict_gt + step can wrap 32-bit + * signed arithmetic, giving trips <= ceil((rad_lo + rad_hi + strict_gt) / step). */ +static inline int +hk_nir_lb_try_window_trips(struct hk_nir_lb_builder *b, nir_scalar init_s, + nir_scalar limit_s, nir_scalar step_s, + bool strict_gt, bool bottom_tested) +{ + init_s = nir_scalar_resolved(init_s.def, init_s.comp); + limit_s = nir_scalar_resolved(limit_s.def, limit_s.comp); + + nir_scalar lo_cands[2] = { init_s, {0} }; + unsigned n_lo = 1; + if (nir_scalar_is_alu(init_s) && nir_scalar_alu_op(init_s) == nir_op_imax) { + lo_cands[0] = nir_scalar_chase_alu_src(init_s, 0); + lo_cands[1] = nir_scalar_chase_alu_src(init_s, 1); + n_lo = 2; + } else if (hk_nir_lb_extract_if_phi_minmax(init_s, true, lo_cands)) { + n_lo = 2; + } + + nir_scalar hi_cands[2] = { limit_s, {0} }; + unsigned n_hi = 1; + if (nir_scalar_is_alu(limit_s) && nir_scalar_alu_op(limit_s) == nir_op_imin) { + hi_cands[0] = nir_scalar_chase_alu_src(limit_s, 0); + hi_cands[1] = nir_scalar_chase_alu_src(limit_s, 1); + n_hi = 2; + } else if (hk_nir_lb_extract_if_phi_minmax(limit_s, false, hi_cands)) { + n_hi = 2; + } + + for (unsigned li = 0; li < n_lo; ++li) { + nir_scalar lo_base = {0}, rad_lo_s = {0}; + uint32_t rad_lo_c = 0; + if (!hk_nir_lb_split_window_lo(lo_cands[li], &lo_base, &rad_lo_s, &rad_lo_c)) + continue; + lo_base = nir_scalar_resolved(lo_base.def, lo_base.comp); + + for (unsigned hi = 0; hi < n_hi; ++hi) { + nir_scalar hc = nir_scalar_resolved(hi_cands[hi].def, hi_cands[hi].comp); + nir_scalar rad_hi_s = {0}; + bool matched = false; + if (nir_scalar_equal(hc, lo_base)) { + matched = true; + } else if (nir_scalar_is_alu(hc) && nir_scalar_alu_op(hc) == nir_op_iadd) { + nir_scalar h0 = nir_scalar_chase_alu_src(hc, 0); + nir_scalar h1 = nir_scalar_chase_alu_src(hc, 1); + if (nir_scalar_equal(h0, lo_base)) { + rad_hi_s = h1; + matched = true; + } else if (nir_scalar_equal(h1, lo_base)) { + rad_hi_s = h0; + matched = true; + } + } + if (!matched) + continue; + + const uint8_t saved_count = *b->count; + const bool saved_failed = b->failed; + const int base_max = hk_nir_lb_emit_grid_coord_max(b, lo_base, 6); + const int rlo = rad_lo_s.def + ? hk_nir_lb_emit_push_or_grid_expr( + b, rad_lo_s, false, true, true, 8) + : hk_nir_lb_const(b, rad_lo_c); + const int rhi = rad_hi_s.def + ? hk_nir_lb_emit_push_or_grid_expr( + b, rad_hi_s, false, true, true, 8) + : hk_nir_lb_const(b, 0); + const int stp = hk_nir_lb_emit_push_or_grid_expr( + b, step_s, false, false, true, 8); + if (base_max >= 0 && rlo >= 0 && rhi >= 0 && stp >= 0 && !b->failed) { + const int chk_lo = hk_nir_lb_emit(b, (struct hk_pack_loop_op){ + .kind = HK_PACK_LOOP_OP_ASSERT_I32, + .lhs = (uint8_t)rlo, + }); + int hi_sum = hk_nir_lb_add(b, base_max, rhi); + if (strict_gt) + hi_sum = hk_nir_lb_add(b, hi_sum, hk_nir_lb_const(b, 1)); + hi_sum = hk_nir_lb_add(b, hi_sum, stp); + const int chk_hi = hk_nir_lb_emit(b, (struct hk_pack_loop_op){ + .kind = HK_PACK_LOOP_OP_ASSERT_I32, + .lhs = (uint8_t)hi_sum, + }); + int span = hk_nir_lb_add(b, rlo, rhi); + if (strict_gt) + span = hk_nir_lb_add(b, span, hk_nir_lb_const(b, 1)); + /* Keep both overflow assertions live in the expression DAG (each + * evaluates to 0 when in range and fails closed otherwise). */ + span = hk_nir_lb_add(b, span, chk_lo); + span = hk_nir_lb_add(b, span, chk_hi); + int trips = hk_nir_lb_emit(b, (struct hk_pack_loop_op){ + .kind = HK_PACK_LOOP_OP_CEIL_DIV_I32, + .lhs = (uint8_t)span, + .rhs = (uint8_t)stp, + }); + if (trips >= 0 && bottom_tested) + trips = hk_nir_lb_max(b, trips, hk_nir_lb_const(b, 1)); + if (trips >= 0 && !b->failed) + return trips; + } + *b->count = saved_count; + b->failed = saved_failed; + } + } + return -1; +} + +static inline bool +hk_nir_lb_is_halving_update(nir_scalar update, const nir_def *iv_def) +{ + nir_scalar num = {0}; + uint32_t div = 0; + bool is_signed = false; + if (!hk_nir_lb_is_const_div_or_shr(update, &num, &div, &is_signed)) + return false; + return num.def == iv_def && div >= 2; +} + +static inline bool +hk_nir_lb_is_halving_break(struct hk_nir_lb_builder *b, nir_scalar cond, + bool break_on_true, nir_block *hdr, nir_block *pre, + bool late_break, uint64_t *const_trips_out, int *dyn_trips_out) +{ + *const_trips_out = 0; + *dyn_trips_out = -1; + cond = nir_scalar_resolved(cond.def, cond.comp); + if (!nir_scalar_is_alu(cond)) + return false; + const nir_op op = nir_scalar_alu_op(cond); + if (op != nir_op_ilt && op != nir_op_ige && op != nir_op_ult && + op != nir_op_uge && op != nir_op_ieq && op != nir_op_ine) + return false; + nir_scalar s0 = nir_scalar_chase_alu_src(cond, 0); + nir_scalar s1 = nir_scalar_chase_alu_src(cond, 1); + if (s0.def->bit_size != 32 || s1.def->bit_size != 32) + return false; + + /* Normalize to: breaks when `cand <= 0` or `cand == 0`. */ + nir_scalar cand = {0}; + bool ok_rel = false; + if (nir_scalar_is_const(s1)) { + const int64_t c = nir_scalar_as_int(s1); + if (break_on_true) + ok_rel = (op == nir_op_ieq && c == 0) || (op == nir_op_ilt && c == 1); + else + ok_rel = (op == nir_op_ine && c == 0) || (op == nir_op_ige && c == 1); + if (ok_rel) + cand = s0; + } else if (nir_scalar_is_const(s0)) { + const int64_t c = nir_scalar_as_int(s0); + if (break_on_true) + ok_rel = (op == nir_op_ieq && c == 0) || (op == nir_op_ige && c == 0); + else + ok_rel = (op == nir_op_ine && c == 0) || (op == nir_op_ilt && c == 0); + if (ok_rel) + cand = s1; + } + if (!ok_rel || !cand.def) + return false; + + /* cand is either the header phi itself (top-tested) or its halving update (bottom-tested). */ + nir_phi_instr *iv = NULL; + const nir_src *init_src = NULL; + const nir_src *back_src = NULL; + bool bottom_tested = false; + if (nir_def_instr(cand.def)->type == nir_instr_type_phi && + nir_def_instr(cand.def)->block == hdr) { + if (late_break) + return false; + iv = nir_instr_as_phi(nir_def_instr(cand.def)); + unsigned src_count = 0; + nir_foreach_phi_src(ps, iv) { + src_count++; + if (ps->pred == pre) + init_src = &ps->src; + else + back_src = &ps->src; + } + if (src_count != 2 || !init_src || !back_src) + return false; + } else { + bottom_tested = true; + nir_foreach_phi(phi, hdr) { + const nir_src *i_s = NULL, *b_s = NULL; + unsigned src_count = 0; + nir_foreach_phi_src(ps, phi) { + src_count++; + if (ps->pred == pre) + i_s = &ps->src; + else + b_s = &ps->src; + } + if (src_count == 2 && i_s && b_s && b_s->ssa == cand.def) { + iv = phi; + init_src = i_s; + back_src = b_s; + break; + } + } + if (!iv) + return false; + } + if (!hk_nir_lb_is_halving_update(nir_get_scalar(back_src->ssa, 0), &iv->def)) + return false; + nir_scalar init_s = nir_scalar_resolved(init_src->ssa, 0); + if (nir_scalar_is_const(init_s)) { + const int64_t v = nir_scalar_as_int(init_s); + if (v > 0 && v <= INT32_MAX) { + uint64_t t = 0; + for (uint32_t u = (uint32_t)v; u > 0; u >>= 1) + t++; + *const_trips_out = t > 0 ? t : 1ull; + return true; + } + if (v <= 0) { + *const_trips_out = bottom_tested ? 1ull : 0ull; + return true; + } + } + /* Try dynamic floor(log2(init_upper)) + 1 when init is push/grid-bounded. */ + const uint8_t saved_count = *b->count; + const bool saved_failed = b->failed; + const int init_op = hk_nir_lb_emit_push_or_grid_expr( + b, init_s, false, true, true, 8); + if (init_op >= 0 && !b->failed) { + int lg = hk_nir_lb_emit(b, (struct hk_pack_loop_op){ + .kind = HK_PACK_LOOP_OP_LOG2_PLUS1, + .lhs = (uint8_t)init_op, + }); + if (lg >= 0 && bottom_tested) + lg = hk_nir_lb_max(b, lg, hk_nir_lb_const(b, 1)); + if (lg >= 0 && !b->failed) { + *dyn_trips_out = lg; + return true; + } + } + *b->count = saved_count; + b->failed = saved_failed; + *const_trips_out = 32ull; + return true; +} + +static inline int +hk_nir_lb_loop_trips_node(struct hk_nir_lb_builder *b, nir_loop *loop) { nir_cf_node *prev_cf = nir_cf_node_prev(&loop->cf_node); if (!prev_cf || prev_cf->type != nir_cf_node_block) { b->failed = true; - return hk_nir_lb_val_const(0); + return -1; } nir_block *pre = nir_cf_node_as_block(prev_cf); if (exec_list_is_empty(&loop->body)) { b->failed = true; - return hk_nir_lb_val_const(0); + return -1; } nir_cf_node *first_cf = exec_node_data(nir_cf_node, exec_list_get_head(&loop->body), node); if (first_cf->type != nir_cf_node_block) { b->failed = true; - return hk_nir_lb_val_const(0); + return -1; } nir_block *hdr = nir_cf_node_as_block(first_cf); + nir_cf_node *last_cf = + exec_node_data(nir_cf_node, exec_list_get_tail(&loop->body), node); + + /* Find the loop's single simple break-if: either immediately after the header + * block (top-tested or compact bottom-tested) or immediately before an empty + * latch block (general bottom-tested loop with inner control flow). */ + nir_if *brk_if = NULL; + bool late_break = false; + bool break_in_then = true; nir_cf_node *second_cf = nir_cf_node_next(first_cf); - if (!second_cf || second_cf->type != nir_cf_node_if) { - b->failed = true; - return hk_nir_lb_val_const(0); + if (second_cf && second_cf->type == nir_cf_node_if && + hk_nir_lb_is_simple_break_if(nir_cf_node_as_if(second_cf), + &break_in_then)) { + brk_if = nir_cf_node_as_if(second_cf); + } else if (last_cf && last_cf->type == nir_cf_node_block && + exec_list_is_empty(&nir_cf_node_as_block(last_cf)->instr_list)) { + nir_cf_node *penult = nir_cf_node_prev(last_cf); + if (penult && penult->type == nir_cf_node_if && + hk_nir_lb_is_simple_break_if(nir_cf_node_as_if(penult), + &break_in_then)) { + brk_if = nir_cf_node_as_if(penult); + late_break = true; + } } - nir_if *brk_if = nir_cf_node_as_if(second_cf); - if (!hk_nir_lb_is_simple_break_if(brk_if)) { + if (!brk_if) { b->failed = true; - return hk_nir_lb_val_const(0); + return -1; } - /* If the break condition is a disjunction (A || B), breaking occurs at least - * as soon as either disjunct becomes true, so proving a trip bound from any - * disjunct is a sound upper bound. */ - const nir_def *cands[2] = { brk_if->condition.ssa, NULL }; + nir_scalar top_cond = nir_scalar_resolved(brk_if->condition.ssa, 0); + bool break_on_true = break_in_then; + while (nir_scalar_is_alu(top_cond) && + nir_scalar_alu_op(top_cond) == nir_op_inot) { + break_on_true = !break_on_true; + top_cond = nir_scalar_chase_alu_src(top_cond, 0); + } + + /* If breaking occurs on a disjunction (A || B when break_on_true, or + * !(A && B) when !break_on_true), proving a trip bound from any disjunct + * is a sound upper bound. */ + nir_scalar cands[2] = { top_cond, {0} }; unsigned num_cands = 1; - if (cands[0] && nir_def_instr(cands[0])->type == nir_instr_type_alu) { - nir_alu_instr *top = nir_instr_as_alu(nir_def_instr(cands[0])); - if (top->op == nir_op_ior) { - cands[0] = top->src[0].src.ssa; - cands[1] = top->src[1].src.ssa; - num_cands = 2; - } + if (nir_scalar_is_alu(top_cond) && + ((break_on_true && nir_scalar_alu_op(top_cond) == nir_op_ior) || + (!break_on_true && nir_scalar_alu_op(top_cond) == nir_op_iand))) { + cands[0] = nir_scalar_chase_alu_src(top_cond, 0); + cands[1] = nir_scalar_chase_alu_src(top_cond, 1); + num_cands = 2; } bool found_canonical = false; bool found_const = false; uint64_t best_const_trips = UINT64_MAX; + int dyn_trips_op = -1; + for (unsigned ci = 0; ci < num_cands; ++ci) { - const nir_def *cond_def = cands[ci]; - if (!cond_def || nir_def_instr(cond_def)->type != nir_instr_type_alu) - continue; - nir_alu_instr *cmp = nir_instr_as_alu(nir_def_instr(cond_def)); - if (cmp->op != nir_op_ige && cmp->op != nir_op_uge) + nir_scalar cond_s = nir_scalar_resolved(cands[ci].def, cands[ci].comp); + bool bot = break_on_true; + while (nir_scalar_is_alu(cond_s) && + nir_scalar_alu_op(cond_s) == nir_op_inot) { + bot = !bot; + cond_s = nir_scalar_chase_alu_src(cond_s, 0); + } + if (!cond_s.def || !nir_scalar_is_alu(cond_s)) continue; - const nir_def *iv_def = cmp->src[0].src.ssa; - if (!iv_def || iv_def->num_components != 1 || iv_def->bit_size != 32 || - nir_def_instr(iv_def)->type != nir_instr_type_phi || - nir_def_instr(iv_def)->block != hdr) + /* Halving loops (s = s >> 1 or s = s / 2 until s <= 0) terminate in + * at most floor(log2(init)) + 1 (or 32) iterations. */ + uint64_t halving_trips = 0; + int halving_dyn_op = -1; + if (b->num_bindings == 0 && + hk_nir_lb_is_halving_break(b, cond_s, bot, hdr, pre, late_break, + &halving_trips, &halving_dyn_op)) { + found_canonical = true; + if (halving_dyn_op >= 0) { + if (dyn_trips_op < 0) + dyn_trips_op = halving_dyn_op; + } else if (halving_trips < best_const_trips) { + best_const_trips = halving_trips; + found_const = true; + } continue; - - nir_phi_instr *iv = nir_instr_as_phi(nir_def_instr(iv_def)); - const nir_src *init_src = NULL; - const nir_src *back_src = NULL; - unsigned src_count = 0; - nir_foreach_phi_src(ps, iv) { - src_count++; - if (ps->pred == pre) - init_src = &ps->src; - else - back_src = &ps->src; } - if (src_count != 2 || !init_src || !back_src || - nir_def_instr(back_src->ssa)->type != nir_instr_type_alu) - continue; - nir_alu_instr *step_alu = nir_instr_as_alu(nir_def_instr(back_src->ssa)); - if (step_alu->op != nir_op_iadd) - continue; - const nir_src *step_src = NULL; - if (step_alu->src[0].src.ssa == iv_def) - step_src = &step_alu->src[1].src; - else if (step_alu->src[1].src.ssa == iv_def) - step_src = &step_alu->src[0].src; - else + const nir_op op = nir_scalar_alu_op(cond_s); + if (op != nir_op_ige && op != nir_op_uge && + op != nir_op_ilt && op != nir_op_ult) continue; + const bool is_unsigned = (op == nir_op_uge || op == nir_op_ult); + const bool is_ge = (op == nir_op_ige || op == nir_op_uge); - found_canonical = true; - const nir_src *limit_src = &cmp->src[1].src; - if (nir_src_is_const(*init_src) && nir_src_is_const(*step_src) && - nir_src_is_const(*limit_src)) { - uint64_t trips = 0; - bool ok = true; - if (cmp->op == nir_op_ige) { - const int64_t init_i = nir_src_as_int(*init_src); - const int64_t step_i = nir_src_as_int(*step_src); - const int64_t limit_i = nir_src_as_int(*limit_src); - if (step_i <= 0) - ok = false; - else if (limit_i > init_i) - trips = ((uint64_t)(limit_i - init_i) + (uint64_t)step_i - 1ull) / (uint64_t)step_i; + nir_scalar s0 = nir_scalar_chase_alu_src(cond_s, 0); + nir_scalar s1 = nir_scalar_chase_alu_src(cond_s, 1); + + /* Try both operands as the IV (handles both counting-up `iv >= limit` / + * `iv > limit` and counting-down `iv < limit` / `iv <= limit` loops). */ + for (unsigned side = 0; side < 2; ++side) { + nir_scalar cmp_iv_s = side == 0 ? s0 : s1; + nir_scalar limit_s = side == 0 ? s1 : s0; + /* Determine whether breaking stops an increasing (counting_down=false) + * or decreasing (counting_down=true) IV, and whether the boundary is + * strict (`>` for up, `<=` for down). */ + bool counting_down = false; + bool strict_bound = false; + if (side == 0) { + /* Comparing iv limit. + * Up breaks when iv >= limit: (bot && is_ge) || (!bot && !is_ge). + * Down breaks when iv < limit: (bot && !is_ge) || (!bot && is_ge). */ + counting_down = (bot != is_ge); + strict_bound = false; } else { - const uint64_t init_u = nir_src_as_uint(*init_src); - const uint64_t step_u = nir_src_as_uint(*step_src); - const uint64_t limit_u = nir_src_as_uint(*limit_src); - if (step_u == 0) - ok = false; - else if (limit_u > init_u) { - const uint64_t span = limit_u - init_u; - if (span > UINT64_MAX - (step_u - 1ull)) - ok = false; - else - trips = (span + step_u - 1ull) / step_u; + /* Comparing limit iv. + * Up breaks when limit < iv (i.e. iv > limit): (bot && !is_ge) || (!bot && is_ge). + * Down breaks when limit >= iv (i.e. iv <= limit): (bot && is_ge) || (!bot && !is_ge). */ + counting_down = (bot == is_ge); + strict_bound = true; + } + + const nir_def *cmp_lhs = cmp_iv_s.def; + if (!cmp_lhs || cmp_lhs->num_components != 1 || cmp_lhs->bit_size != 32) + continue; + + /* Accept either a top-tested loop comparing the header IV phi directly + * or a bottom-tested loop comparing the post-update back-edge IV. */ + const nir_def *iv_def = cmp_lhs; + bool bottom_tested = false; + if (nir_def_instr(cmp_lhs)->type == nir_instr_type_alu) { + nir_alu_instr *lhs_alu = nir_instr_as_alu(nir_def_instr(cmp_lhs)); + if (lhs_alu->op != nir_op_iadd && lhs_alu->op != nir_op_isub) + continue; + const nir_def *a0 = nir_scalar_chase_alu_src(cmp_iv_s, 0).def; + const nir_def *a1 = nir_scalar_chase_alu_src(cmp_iv_s, 1).def; + if (a0 && nir_def_instr(a0)->type == nir_instr_type_phi && + nir_def_instr(a0)->block == hdr) { + iv_def = a0; + bottom_tested = true; + } else if (lhs_alu->op == nir_op_iadd && + a1 && nir_def_instr(a1)->type == nir_instr_type_phi && + nir_def_instr(a1)->block == hdr) { + iv_def = a1; + bottom_tested = true; + } else { + continue; } + } else if (nir_def_instr(iv_def)->type != nir_instr_type_phi || + nir_def_instr(iv_def)->block != hdr) { + continue; } - if (ok && trips <= UINT32_MAX && trips < best_const_trips) { - best_const_trips = trips; - found_const = true; + + /* A late break on the old IV runs the body once more. The top-test + * bound cannot account for that final iteration. + */ + if (late_break && !bottom_tested) + continue; + + nir_phi_instr *iv = nir_instr_as_phi(nir_def_instr(iv_def)); + const nir_src *init_src = NULL; + const nir_src *back_src = NULL; + unsigned src_count = 0; + nir_foreach_phi_src(ps, iv) { + src_count++; + if (ps->pred == pre) + init_src = &ps->src; + else + back_src = &ps->src; + } + if (src_count != 2 || !init_src || !back_src) + continue; + nir_scalar back_s = nir_scalar_resolved(back_src->ssa, 0); + if (!nir_scalar_is_alu(back_s)) + continue; + if (bottom_tested && back_s.def != cmp_lhs) + continue; + + nir_alu_instr *step_alu = nir_instr_as_alu(nir_def_instr(back_s.def)); + if (step_alu->op != nir_op_iadd && step_alu->op != nir_op_isub) + continue; + bool step_negated = false; + nir_scalar step_s = {0}; + if (nir_scalar_chase_alu_src(back_s, 0).def == iv_def) { + step_s = nir_scalar_chase_alu_src(back_s, 1); + step_negated = (step_alu->op == nir_op_isub); + } else if (step_alu->op == nir_op_iadd && + nir_scalar_chase_alu_src(back_s, 1).def == iv_def) { + step_s = nir_scalar_chase_alu_src(back_s, 0); + } else { + continue; + } + + nir_scalar init_s = nir_scalar_resolved(init_src->ssa, 0); + limit_s = nir_scalar_resolved(limit_s.def, limit_s.comp); + step_s = nir_scalar_resolved(step_s.def, step_s.comp); + + if (counting_down) { + if (is_unsigned || b->num_bindings != 0 || !nir_scalar_is_const(step_s)) + continue; + const int64_t raw_step = nir_scalar_as_int(step_s); + const int64_t mag = step_negated ? raw_step : -raw_step; + if (mag <= 0 || mag > INT32_MAX) + continue; + found_canonical = true; + if (nir_scalar_is_const(init_s) && nir_scalar_is_const(limit_s)) { + const int64_t init_i = nir_scalar_as_int(init_s); + const int64_t lim_i = nir_scalar_as_int(limit_s); + /* Breaks when iv < lim_i (strict_bound=false) or iv <= lim_i (strict_bound=true). */ + const int64_t stop_i = lim_i + (strict_bound ? 1 : 0); + if (stop_i >= (int64_t)INT32_MIN + mag) { + uint64_t trips = 0; + if (init_i >= stop_i) + trips = ((uint64_t)(init_i - stop_i) + (uint64_t)mag) / (uint64_t)mag; + if (bottom_tested && trips == 0) + trips = 1; + if (trips <= UINT32_MAX && trips < best_const_trips) { + best_const_trips = trips; + found_const = true; + } + } + } else if (dyn_trips_op < 0) { + const uint8_t saved_count = *b->count; + const bool saved_failed = b->failed; + /* Require limit >= 0 (prevents signed underflow below INT32_MIN). */ + int lim_chk = -1; + if (hk_nir_lb_init_nonneg(limit_s, step_s, false, 4)) { + lim_chk = hk_nir_lb_const(b, 0); + } else { + const int l_op = hk_nir_lb_emit_push_or_grid_expr( + b, limit_s, false, true, true, 8); + if (l_op >= 0) { + lim_chk = hk_nir_lb_emit(b, (struct hk_pack_loop_op){ + .kind = HK_PACK_LOOP_OP_ASSERT_I32, + .lhs = (uint8_t)l_op, + }); + } + } + int init_op = lim_chk >= 0 + ? hk_nir_lb_emit_push_or_grid_expr( + b, init_s, false, true, true, 8) + : -1; + if (lim_chk >= 0 && init_op >= 0 && !b->failed) { + int span = strict_bound + ? init_op + : hk_nir_lb_add(b, init_op, hk_nir_lb_const(b, 1)); + span = hk_nir_lb_add(b, span, lim_chk); + int cdiv = hk_nir_lb_emit(b, (struct hk_pack_loop_op){ + .kind = HK_PACK_LOOP_OP_CEIL_DIV_I32, + .lhs = (uint8_t)span, + .rhs = (uint8_t)hk_nir_lb_const(b, (uint32_t)mag), + }); + if (cdiv >= 0 && bottom_tested) + cdiv = hk_nir_lb_max(b, cdiv, hk_nir_lb_const(b, 1)); + if (cdiv >= 0 && !b->failed) + dyn_trips_op = cdiv; + } + if (dyn_trips_op < 0) { + *b->count = saved_count; + b->failed = saved_failed; + } + } + continue; + } + + /* Counting-up loop (`step > 0`). */ + if (step_negated) + continue; + const bool strict_gt = strict_bound; + found_canonical = true; + + if (nir_scalar_is_const(init_s) && nir_scalar_is_const(step_s) && + nir_scalar_is_const(limit_s)) { + uint64_t trips = 0; + bool ok = true; + if (!is_unsigned) { + const int64_t init_i = nir_scalar_as_int(init_s); + const int64_t step_i = nir_scalar_as_int(step_s); + const int64_t limit_i = nir_scalar_as_int(limit_s) + (strict_gt ? 1 : 0); + if (step_i <= 0 || limit_i > (int64_t)INT32_MAX + 1) + ok = false; + else if (limit_i > init_i) + trips = ((uint64_t)(limit_i - init_i) + (uint64_t)step_i - 1ull) / (uint64_t)step_i; + } else { + const uint64_t init_u = nir_scalar_as_uint(init_s); + const uint64_t step_u = nir_scalar_as_uint(step_s); + const uint64_t limit_u = nir_scalar_as_uint(limit_s) + (strict_gt ? 1ull : 0ull); + if (step_u == 0 || (strict_gt && nir_scalar_as_uint(limit_s) == UINT32_MAX)) + ok = false; + else if (limit_u > init_u) { + const uint64_t span = limit_u - init_u; + if (span > UINT64_MAX - (step_u - 1ull)) + ok = false; + else + trips = (span + step_u - 1ull) / step_u; + } + } + if (ok && bottom_tested && trips == 0) + trips = 1; + if (ok && trips <= UINT32_MAX && trips < best_const_trips) { + best_const_trips = trips; + found_const = true; + } + } else if (b->num_bindings == 0 && dyn_trips_op < 0) { + /* Prefer tight sliding-window / stencil span bound (base - rad_lo .. base + rad_hi) + * when applicable, before falling back to 0..limit. */ + if (!is_unsigned) { + const int win_op = hk_nir_lb_try_window_trips( + b, init_s, limit_s, step_s, strict_gt, bottom_tested); + if (win_op >= 0) { + dyn_trips_op = win_op; + continue; + } + } + if (hk_nir_lb_init_nonneg(init_s, step_s, is_unsigned, 4)) { + const uint8_t saved_count = *b->count; + const bool saved_failed = b->failed; + int lim_op = hk_nir_lb_emit_push_or_grid_expr( + b, limit_s, is_unsigned, true, false, 8); + int stp_op = lim_op >= 0 + ? hk_nir_lb_emit_push_or_grid_expr( + b, step_s, is_unsigned, false, true, 8) + : -1; + if (lim_op >= 0 && stp_op >= 0 && !b->failed) { + if (strict_gt) + lim_op = hk_nir_lb_add(b, lim_op, hk_nir_lb_const(b, 1)); + int cdiv = hk_nir_lb_emit(b, (struct hk_pack_loop_op){ + .kind = is_unsigned ? HK_PACK_LOOP_OP_CEIL_DIV_U32 + : HK_PACK_LOOP_OP_CEIL_DIV_I32, + .lhs = (uint8_t)lim_op, + .rhs = (uint8_t)stp_op, + }); + if (cdiv >= 0 && bottom_tested) + cdiv = hk_nir_lb_max(b, cdiv, hk_nir_lb_const(b, 1)); + if (cdiv >= 0 && !b->failed) + dyn_trips_op = cdiv; + } + if (dyn_trips_op < 0) { + *b->count = saved_count; + b->failed = saved_failed; + } + } } } } if (!found_canonical) { b->failed = true; - return hk_nir_lb_val_const(0); + return -1; } /* Check explicit dynamic parameter binding first (structure already verified). */ for (unsigned i = 0; i < b->num_bindings; ++i) { - if (b->bindings[i].loop == loop) { - return (struct hk_nir_lb_val){ - .node = hk_nir_lb_param(b, b->bindings[i].param), - .c = 0, - }; - } + if (b->bindings[i].loop == loop) + return hk_nir_lb_param(b, b->bindings[i].param); } - if (!found_const) { - b->failed = true; + if (found_const) + return hk_nir_lb_const(b, (uint32_t)best_const_trips); + if (dyn_trips_op >= 0) + return dyn_trips_op; + + b->failed = true; + return -1; +} + +static inline struct hk_nir_lb_val +hk_nir_lb_loop_trips(struct hk_nir_lb_builder *b, nir_loop *loop) +{ + const int node = hk_nir_lb_loop_trips_node(b, loop); + if (node < 0 || b->failed) return hk_nir_lb_val_const(0); - } - return hk_nir_lb_val_const(best_const_trips); + uint32_t c = 0; + if (hk_nir_lb_is_const(b, node, &c)) + return hk_nir_lb_val_const(c); + return (struct hk_nir_lb_val){ .node = node, .c = 0 }; } static inline struct hk_nir_lb_val @@ -591,6 +1841,7 @@ hk_nir_compute_pack_loop_bound(nir_shader *nir, return false; struct hk_nir_lb_builder b = { + .nir = nir, .ops = out->ops, .count = &out->count, .max_ops = HK_PACK_LOOP_MAX_OPS, @@ -626,6 +1877,7 @@ hk_nir_compute_pack_loop_bound(nir_shader *nir, } if (static_ops > 0 && static_ops <= UINT32_MAX) { struct hk_nir_lb_builder wb = { + .nir = nir, .ops = out->work_ops, .count = &out->work_count, .max_ops = HK_PACK_LOOP_WORK_MAX_OPS, diff --git a/src/asahi/vulkan/hk_pack_loop_bound.h b/src/asahi/vulkan/hk_pack_loop_bound.h index eb5ca9e67421..33a990fa6151 100644 --- a/src/asahi/vulkan/hk_pack_loop_bound.h +++ b/src/asahi/vulkan/hk_pack_loop_bound.h @@ -7,6 +7,7 @@ #include #include +#include enum hk_pack_loop_param { HK_PACK_LOOP_PARAM_IM2COL_KH = 0, @@ -26,6 +27,15 @@ enum hk_pack_loop_op_kind { HK_PACK_LOOP_OP_ADD, HK_PACK_LOOP_OP_MUL, HK_PACK_LOOP_OP_MAX, + HK_PACK_LOOP_OP_PUSH_U32, + HK_PACK_LOOP_OP_PUSH_I32_POS, + HK_PACK_LOOP_OP_PUSH_I32_NONNEG, + HK_PACK_LOOP_OP_GRID_GROUPS, + HK_PACK_LOOP_OP_DIV_CONST, + HK_PACK_LOOP_OP_LOG2_PLUS1, + HK_PACK_LOOP_OP_ASSERT_I32, + HK_PACK_LOOP_OP_CEIL_DIV_U32, + HK_PACK_LOOP_OP_CEIL_DIV_I32, }; struct hk_pack_loop_op { @@ -57,10 +67,11 @@ struct hk_pack_loop_bound { }; static inline bool -hk_pack_eval_ops(const struct hk_pack_loop_op *ops, uint8_t count, - uint8_t max_ops, - const uint64_t params[HK_PACK_LOOP_PARAM_COUNT], - uint64_t *val_out) +hk_pack_eval_ops_dispatch(const struct hk_pack_loop_op *ops, uint8_t count, + uint8_t max_ops, + const uint64_t params[HK_PACK_LOOP_PARAM_COUNT], + const void *push_data, uint32_t push_size, + const uint32_t grid_groups[3], uint64_t *val_out) { *val_out = 0; if (!ops || count == 0 || count > max_ops || max_ops > HK_PACK_LOOP_WORK_MAX_OPS) @@ -94,6 +105,77 @@ hk_pack_eval_ops(const struct hk_pack_loop_op *ops, uint8_t count, return false; v = vals[op.lhs] >= vals[op.rhs] ? vals[op.lhs] : vals[op.rhs]; break; + case HK_PACK_LOOP_OP_PUSH_U32: { + if (!push_data || op.imm > push_size || push_size - op.imm < 4u) + return false; + uint32_t u = 0; + memcpy(&u, (const uint8_t *)push_data + op.imm, sizeof(u)); + v = u; + break; + } + case HK_PACK_LOOP_OP_PUSH_I32_POS: { + if (!push_data || op.imm > push_size || push_size - op.imm < 4u) + return false; + int32_t s = 0; + memcpy(&s, (const uint8_t *)push_data + op.imm, sizeof(s)); + v = s > 0 ? (uint64_t)s : 0ull; + break; + } + case HK_PACK_LOOP_OP_PUSH_I32_NONNEG: { + if (!push_data || op.imm > push_size || push_size - op.imm < 4u) + return false; + int32_t s = 0; + memcpy(&s, (const uint8_t *)push_data + op.imm, sizeof(s)); + if (s < 0) + return false; + v = (uint64_t)s; + break; + } + case HK_PACK_LOOP_OP_GRID_GROUPS: + if (!grid_groups || op.imm >= 3u) + return false; + v = grid_groups[op.imm]; + break; + case HK_PACK_LOOP_OP_DIV_CONST: + if (op.lhs >= i || op.imm == 0) + return false; + v = vals[op.lhs] / op.imm; + break; + case HK_PACK_LOOP_OP_LOG2_PLUS1: + if (op.lhs >= i) + return false; + v = vals[op.lhs] == 0 ? 0ull + : (uint64_t)(64 - __builtin_clzll(vals[op.lhs])); + break; + case HK_PACK_LOOP_OP_ASSERT_I32: + if (op.lhs >= i || vals[op.lhs] > (uint64_t)INT32_MAX) + return false; + v = 0; + break; + case HK_PACK_LOOP_OP_CEIL_DIV_U32: { + if (op.lhs >= i || op.rhs >= i) + return false; + const uint64_t lim = vals[op.lhs]; + const uint64_t stp = vals[op.rhs]; + /* Fail closed if step == 0 or lim + step could wrap 32-bit unsigned. */ + if (stp == 0 || lim > UINT32_MAX || stp > UINT32_MAX || + lim + stp > UINT32_MAX) + return false; + v = lim == 0 ? 0 : (lim + stp - 1ull) / stp; + break; + } + case HK_PACK_LOOP_OP_CEIL_DIV_I32: { + if (op.lhs >= i || op.rhs >= i) + return false; + const uint64_t lim = vals[op.lhs]; + const uint64_t stp = vals[op.rhs]; + /* Fail closed if step == 0 or lim + step could wrap 32-bit signed. */ + if (stp == 0 || lim > (uint64_t)INT32_MAX || stp > (uint64_t)INT32_MAX || + lim + stp > (uint64_t)INT32_MAX) + return false; + v = lim == 0 ? 0 : (lim + stp - 1ull) / stp; + break; + } default: return false; } @@ -105,15 +187,29 @@ hk_pack_eval_ops(const struct hk_pack_loop_op *ops, uint8_t count, } static inline bool -hk_pack_eval_loop_bound(const struct hk_pack_loop_bound *lb, - const uint64_t params[HK_PACK_LOOP_PARAM_COUNT], - uint64_t *bound_out) +hk_pack_eval_ops(const struct hk_pack_loop_op *ops, uint8_t count, + uint8_t max_ops, + const uint64_t params[HK_PACK_LOOP_PARAM_COUNT], + uint64_t *val_out) +{ + return hk_pack_eval_ops_dispatch(ops, count, max_ops, params, NULL, 0, NULL, + val_out); +} + +static inline bool +hk_pack_eval_loop_bound_dispatch(const struct hk_pack_loop_bound *lb, + const uint64_t params[HK_PACK_LOOP_PARAM_COUNT], + const void *push_data, uint32_t push_size, + const uint32_t grid_groups[3], + uint64_t *bound_out) { *bound_out = 0; if (!lb || !lb->valid) return false; uint64_t res = 0; - if (!hk_pack_eval_ops(lb->ops, lb->count, HK_PACK_LOOP_MAX_OPS, params, &res) || + if (!hk_pack_eval_ops_dispatch(lb->ops, lb->count, HK_PACK_LOOP_MAX_OPS, + params, push_data, push_size, grid_groups, + &res) || res == 0) return false; *bound_out = res; @@ -121,22 +217,43 @@ hk_pack_eval_loop_bound(const struct hk_pack_loop_bound *lb, } static inline bool -hk_pack_eval_work_bound(const struct hk_pack_loop_bound *lb, +hk_pack_eval_loop_bound(const struct hk_pack_loop_bound *lb, const uint64_t params[HK_PACK_LOOP_PARAM_COUNT], - uint64_t *dyn_nir_ops_out) + uint64_t *bound_out) +{ + return hk_pack_eval_loop_bound_dispatch(lb, params, NULL, 0, NULL, + bound_out); +} + +static inline bool +hk_pack_eval_work_bound_dispatch(const struct hk_pack_loop_bound *lb, + const uint64_t params[HK_PACK_LOOP_PARAM_COUNT], + const void *push_data, uint32_t push_size, + const uint32_t grid_groups[3], + uint64_t *dyn_nir_ops_out) { *dyn_nir_ops_out = 0; if (!lb || !lb->valid || !lb->work_valid || lb->static_nir_ops == 0) return false; uint64_t res = 0; - if (!hk_pack_eval_ops(lb->work_ops, lb->work_count, HK_PACK_LOOP_WORK_MAX_OPS, - params, &res) || + if (!hk_pack_eval_ops_dispatch(lb->work_ops, lb->work_count, + HK_PACK_LOOP_WORK_MAX_OPS, params, push_data, + push_size, grid_groups, &res) || res == 0) return false; *dyn_nir_ops_out = res; return true; } +static inline bool +hk_pack_eval_work_bound(const struct hk_pack_loop_bound *lb, + const uint64_t params[HK_PACK_LOOP_PARAM_COUNT], + uint64_t *dyn_nir_ops_out) +{ + return hk_pack_eval_work_bound_dispatch(lb, params, NULL, 0, NULL, + dyn_nir_ops_out); +} + /* Match the unsigned 128-bit numerator, including wraparound, on targets * without a native 128-bit integer type. The divisor is nonzero. */ static inline bool @@ -172,24 +289,26 @@ hk_pack_scale_instrs_portable(uint64_t instrs, uint64_t work, uint32_t divisor, * ceil(2 * dyn_nir_ops / static_nir_ops) (clamped to [agx_instrs, agx_instrs * * loop_bound]) so cold mutually-exclusive paths do not multiply loop trips. */ static inline bool -hk_pack_eval_effective_instrs(const struct hk_pack_loop_bound *lb, - uint64_t agx_instrs, - const uint64_t params[HK_PACK_LOOP_PARAM_COUNT], - uint64_t *eff_instrs_out) +hk_pack_eval_effective_instrs_dispatch( + const struct hk_pack_loop_bound *lb, uint64_t agx_instrs, + const uint64_t params[HK_PACK_LOOP_PARAM_COUNT], const void *push_data, + uint32_t push_size, const uint32_t grid_groups[3], uint64_t *eff_instrs_out) { *eff_instrs_out = 0; if (!agx_instrs) return false; uint64_t loop_bound = 0; - if (!hk_pack_eval_loop_bound(lb, params, &loop_bound)) + if (!hk_pack_eval_loop_bound_dispatch(lb, params, push_data, push_size, + grid_groups, &loop_bound)) return false; uint64_t naive = 0; const bool naive_ok = !__builtin_mul_overflow(agx_instrs, loop_bound, &naive); uint64_t dyn_nir_ops = 0; - if (hk_pack_eval_work_bound(lb, params, &dyn_nir_ops)) { + if (hk_pack_eval_work_bound_dispatch(lb, params, push_data, push_size, + grid_groups, &dyn_nir_ops)) { #if defined(__SIZEOF_INT128__) const __uint128_t num = (__uint128_t)2u * (__uint128_t)agx_instrs * (__uint128_t)dyn_nir_ops; @@ -217,3 +336,13 @@ hk_pack_eval_effective_instrs(const struct hk_pack_loop_bound *lb, *eff_instrs_out = naive; return true; } + +static inline bool +hk_pack_eval_effective_instrs(const struct hk_pack_loop_bound *lb, + uint64_t agx_instrs, + const uint64_t params[HK_PACK_LOOP_PARAM_COUNT], + uint64_t *eff_instrs_out) +{ + return hk_pack_eval_effective_instrs_dispatch( + lb, agx_instrs, params, NULL, 0, NULL, eff_instrs_out); +} diff --git a/src/asahi/vulkan/hk_shader.c b/src/asahi/vulkan/hk_shader.c index 9609c74f760e..63c28eda7e58 100644 --- a/src/asahi/vulkan/hk_shader.c +++ b/src/asahi/vulkan/hk_shader.c @@ -7,6 +7,7 @@ * SPDX-License-Identifier: MIT */ #include "hk_shader.h" +#include "hk_nir_loop_bound.h" #include "hk_compute_pair.h" #include "hk_identity_copy4.h" #include "hk_nir_match_pointwise_clamp.h" @@ -4220,7 +4221,8 @@ hk_lower_nir_ex(struct hk_device *dev, nir_shader *nir, bool is_multiview, VkShaderStageFlags next_stage_mask, uint32_t set_layout_count, struct vk_descriptor_set_layout *const *set_layouts, - enum hk_feature_key features, bool defer_min_lod) + enum hk_feature_key features, bool defer_min_lod, + struct hk_pack_loop_bound *pack_loop_bound) { const bool already_preprocessed = nir->info.io_lowered; bool lowered_complex = false; @@ -4458,6 +4460,11 @@ hk_lower_nir_ex(struct hk_device *dev, nir_shader *nir, dev->vk.enabled_features.sparseResidencyBuffer && hk_sparse_buffer_unmapped(&dev->dev); + /* Push constants and grid intrinsics still have their canonical NIR form. */ + if (nir->info.stage == MESA_SHADER_COMPUTE && pack_loop_bound && + !pack_loop_bound->valid && !nir->info.internal) + hk_nir_compute_pack_loop_bound(nir, NULL, 0, pack_loop_bound); + bool lowered_desc = false; NIR_PASS(lowered_desc, nir, hk_nir_lower_descriptors, rs, set_layout_count, set_layouts, sparse_store_guards, sparse_store_guards, @@ -4772,7 +4779,7 @@ hk_lower_nir(struct hk_device *dev, nir_shader *nir, enum hk_feature_key features) { hk_lower_nir_ex(dev, nir, rs, is_multiview, next_stage_mask, - set_layout_count, set_layouts, features, false); + set_layout_count, set_layouts, features, false, NULL); } /* Upload the part of the binary the GPU reads from the shader itself: its @@ -9694,6 +9701,7 @@ hk_compile_shader_impl(struct hk_device *dev, struct vk_shader_compile_info *inf bool deferred_min_lod_in, bool min_lod_lowered_in, bool twin_for_min_lod, + const struct hk_pack_loop_bound *pack_loop_bound, struct hk_api_shader **shader_out) { VkResult result; @@ -9750,6 +9758,9 @@ hk_compile_shader_impl(struct hk_device *dev, struct vk_shader_compile_info *inf return vk_errorf(dev, VK_ERROR_FEATURE_NOT_PRESENT, "mesh gl_NumWorkGroups under a task stage needs the task record"); } + struct hk_pack_loop_bound local_pack_lb = {0}; + if (pack_loop_bound && pack_loop_bound->valid) + local_pack_lb = *pack_loop_bound; bool deferred_min_lod = deferred_min_lod_in; bool min_lod_emulating = min_lod_lowered_in; if (!nir->info.io_lowered) { @@ -9774,7 +9785,7 @@ hk_compile_shader_impl(struct hk_device *dev, struct vk_shader_compile_info *inf hk_nir_lower_input_attachments_to_outputs(lr_nir); hk_lower_nir_ex(dev, lr_nir, info->robustness, false, info->next_stage_mask, info->set_layout_count, - info->set_layouts, features, deferred_min_lod); + info->set_layouts, features, deferred_min_lod, NULL); if (deferred_min_lod) hk_lower_nir_post_tex(dev, lr_nir, info->robustness, false, false); @@ -9787,7 +9798,7 @@ hk_compile_shader_impl(struct hk_device *dev, struct vk_shader_compile_info *inf } hk_lower_nir_ex(dev, nir, info->robustness, false, info->next_stage_mask, info->set_layout_count, info->set_layouts, features, - deferred_min_lod); + deferred_min_lod, &local_pack_lb); } /* Defer image-view minLod emulation until the physical device creates an @@ -10785,15 +10796,18 @@ hk_compile_shader_impl(struct hk_device *dev, struct vk_shader_compile_info *inf hk_api_shader_destroy(&dev->vk, &obj->vk, pAllocator); return result; } + if (sw_stage == MESA_SHADER_COMPUTE && local_pack_lb.valid) + shader->pack_loop_bound = local_pack_lb; if (bs_cand && bs_cand->tiled_nir && sw_stage == MESA_SHADER_COMPUTE) { nir_shader *tiled_nir = bs_cand->tiled_nir; bs_cand->tiled_nir = NULL; struct hk_byte_stencil_variant *bs = calloc(1, sizeof(*bs)); if (bs) { bs->plan = bs_cand->plan; - hk_lower_nir(dev, tiled_nir, info->robustness, false, + hk_lower_nir_ex(dev, tiled_nir, info->robustness, false, info->next_stage_mask, info->set_layout_count, - info->set_layouts, features); + info->set_layouts, features, false, + &bs->shader.pack_loop_bound); VkResult bs_res = hk_compile_nir( dev, pAllocator, tiled_nir, info->flags, info->robustness, key, features, &bs->shader, sw_stage, true, NULL, @@ -10818,9 +10832,10 @@ hk_compile_shader_impl(struct hk_device *dev, struct vk_shader_compile_info *inf struct hk_2d_stencil_variant *s2d = calloc(1, sizeof(*s2d)); if (s2d) { s2d->plan = s2d_cand->plan; - hk_lower_nir(dev, tiled_nir, info->robustness, false, + hk_lower_nir_ex(dev, tiled_nir, info->robustness, false, info->next_stage_mask, info->set_layout_count, - info->set_layouts, features); + info->set_layouts, features, false, + &s2d->shader.pack_loop_bound); VkResult s2d_res = hk_compile_nir( dev, pAllocator, tiled_nir, info->flags, info->robustness, key, features, &s2d->shader, sw_stage, true, NULL, @@ -10862,9 +10877,10 @@ hk_compile_shader_impl(struct hk_device *dev, struct vk_shader_compile_info *inf struct hk_compute_opt_variant *co = calloc(1, sizeof(*co)); if (co) { co->plan = co_cand->plan; - hk_lower_nir(dev, opt_nir, info->robustness, false, + hk_lower_nir_ex(dev, opt_nir, info->robustness, false, info->next_stage_mask, info->set_layout_count, - info->set_layouts, features); + info->set_layouts, features, false, + &co->shader.pack_loop_bound); VkResult co_res = hk_compile_nir( dev, pAllocator, opt_nir, info->flags, info->robustness, key, features, &co->shader, sw_stage, true, NULL, @@ -10935,7 +10951,7 @@ hk_compile_shader(struct hk_device *dev, struct vk_shader_compile_info *info, allocator, NULL, NULL, false, false, -1, false, false, bs_ptr, s2d_ptr, co_ptr, NULL, NULL, false, false, - false, false, shader_out); + false, false, NULL, shader_out); if (bs_cand.tiled_nir) ralloc_free(bs_cand.tiled_nir); if (s2d_cand.tiled_nir) @@ -10983,7 +10999,7 @@ hk_compile_twin(struct hk_device *dev, const struct hk_api_shader *obj, m5_no_grid_record, twin_has_vertex_robustness, NULL, NULL, NULL, NULL, NULL, has_ia, - false, false, for_min_lod, + false, false, for_min_lod, NULL, &shader); if (result == VK_SUCCESS && !for_min_lod && obj->min_lod_source && !shader->min_lod_source) { @@ -11873,6 +11889,8 @@ hk_compile_shaders(struct vk_device *vk_dev, uint32_t shader_count, memset(lr_nirs, 0, sizeof(lr_nirs)); memset(lr_infos, 0, sizeof(lr_infos)); memset(has_ias, 0, sizeof(has_ias)); + struct hk_pack_loop_bound pack_loop_bounds[shader_count]; + memset(pack_loop_bounds, 0, sizeof(pack_loop_bounds)); bool deferred_min_lod[shader_count]; bool min_lod_lowered[shader_count]; memset(deferred_min_lod, 0, sizeof(deferred_min_lod)); @@ -11976,7 +11994,7 @@ hk_compile_shaders(struct vk_device *vk_dev, uint32_t shader_count, hk_lower_nir_ex(dev, lr_nirs[i], info->robustness, is_multiview, info->next_stage_mask, info->set_layout_count, info->set_layouts, hk_features, - deferred_min_lod[i]); + deferred_min_lod[i], NULL); if (deferred_min_lod[i]) hk_lower_nir_post_tex(dev, lr_nirs[i], info->robustness, false, false); @@ -12053,7 +12071,8 @@ hk_compile_shaders(struct vk_device *vk_dev, uint32_t shader_count, hk_lower_nir_ex(dev, nir, info->robustness, is_multiview, info->next_stage_mask, info->set_layout_count, - info->set_layouts, hk_features, deferred_min_lod[i]); + info->set_layouts, hk_features, deferred_min_lod[i], + &pack_loop_bounds[i]); if (nir->info.stage == MESA_SHADER_FRAGMENT && has_mesh) NIR_PASS(_, nir, nir_shader_intrinsics_pass, hk_fs_mesh_builtin_per_primitive, nir_metadata_control_flow, @@ -12242,7 +12261,7 @@ hk_compile_shaders(struct vk_device *vk_dev, uint32_t shader_count, s2d_cands[i].tiled_nir ? &s2d_cands[i] : NULL, co_cands[i].opt_nir ? &co_cands[i] : NULL, lr_nirs[i], &lr_infos[i], has_ias[i], - deferred_min_lod[i], min_lod_lowered[i], false, + deferred_min_lod[i], min_lod_lowered[i], false, &pack_loop_bounds[i], (struct hk_api_shader **)&shaders_out[i]); if (bs_cands[i].tiled_nir) { ralloc_free(bs_cands[i].tiled_nir); diff --git a/src/asahi/vulkan/tests/test-hk-compute-pair.c b/src/asahi/vulkan/tests/test-hk-compute-pair.c index 1746d9bf0c06..b80b95e4beed 100644 --- a/src/asahi/vulkan/tests/test-hk-compute-pair.c +++ b/src/asahi/vulkan/tests/test-hk-compute-pair.c @@ -5933,6 +5933,322 @@ test_gemm_dw_proj_fusion(void) ralloc_free(ug_pre); } +static void +test_general_pack_loop_bounds(void) +{ + /* 1. 2D grid-stride + inner push-bounded loop. */ + { + nir_shader *s = new_compute_shader("grid_stride_2d", 32, 1, 1); + nir_builder b = nir_builder_at(nir_before_impl(nir_shader_get_entrypoint(s))); + nir_def *zero = nir_imm_int(&b, 0); + nir_def *off_h = nir_iadd(&b, zero, nir_imm_int(&b, 0)); + nir_def *off_w = nir_iadd(&b, zero, nir_imm_int(&b, 4)); + nir_def *off_k = nir_iadd(&b, zero, nir_imm_int(&b, 8)); + nir_def *H = nir_load_push_constant(&b, 1, 32, off_h, .base = 0, .range = 16); + nir_def *W = nir_load_push_constant(&b, 1, 32, off_w, .base = 0, .range = 16); + nir_def *K = nir_load_push_constant(&b, 1, 32, off_k, .base = 0, .range = 16); + nir_def *wg = nir_load_workgroup_id(&b); + nir_def *nwg = nir_load_num_workgroups(&b); + nir_def *gid = nir_load_global_invocation_id(&b, 32); + nir_def *step_x = nir_imul_imm(&b, nir_channel(&b, nwg, 0), 32); + + nir_variable *vy = nir_local_variable_create(b.impl, glsl_int_type(), "y"); + nir_variable *vx = nir_local_variable_create(b.impl, glsl_int_type(), "x"); + nir_variable *vk = nir_local_variable_create(b.impl, glsl_int_type(), "k"); + nir_store_var(&b, vy, nir_channel(&b, wg, 1), 1); + nir_push_loop(&b); + { + nir_def *y = nir_load_var(&b, vy); + nir_push_if(&b, nir_ige(&b, y, H)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + + nir_store_var(&b, vx, nir_channel(&b, gid, 0), 1); + nir_push_loop(&b); + { + nir_def *x = nir_load_var(&b, vx); + nir_push_if(&b, nir_ige(&b, x, W)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + + nir_store_var(&b, vk, zero, 1); + nir_push_loop(&b); + { + nir_def *k = nir_load_var(&b, vk); + nir_push_if(&b, nir_ige(&b, k, K)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + nir_store_var(&b, vk, nir_iadd_imm(&b, k, 1), 1); + } + nir_pop_loop(&b, NULL); + nir_store_var(&b, vx, nir_iadd(&b, x, step_x), 1); + } + nir_pop_loop(&b, NULL); + nir_store_var(&b, vy, nir_iadd(&b, y, nir_channel(&b, nwg, 1)), 1); + } + nir_pop_loop(&b, NULL); + nir_lower_vars_to_ssa(s); + nir_validate_shader(s, "grid_stride_2d"); + + struct hk_pack_loop_bound lb = {0}; + HK_EVAL_CHECK(hk_nir_compute_pack_loop_bound(s, NULL, 0, &lb) && lb.valid); + int32_t push[4] = { 128, 320, 7, 0 }; + uint32_t grid[3] = { 5, 64, 1 }; + uint64_t val = 0; + /* y_trips = ceil(128/64)=2, x_trips = ceil(320/160)=2, k_trips = 7 + * total = 1 + 2 * (1 + 2 * (1 + 7)) = 1 + 2 * 17 = 35 */ + HK_EVAL_CHECK(hk_pack_eval_loop_bound_dispatch(&lb, NULL, push, sizeof(push), grid, &val)); + HK_EVAL_CHECK(val == 35); + /* Wrap hazard fails closed */ + push[1] = INT32_MAX - 10; + HK_EVAL_CHECK(!hk_pack_eval_loop_bound_dispatch(&lb, NULL, push, sizeof(push), grid, &val)); + ralloc_free(s); + } + + /* 2. Softmax pattern: next_pow2(C) bit-smear + countdown + halving loop. */ + { + nir_shader *s = new_compute_shader("softmax_bounds", 32, 1, 1); + nir_builder b = nir_builder_at(nir_before_impl(nir_shader_get_entrypoint(s))); + nir_def *lid = nir_channel(&b, nir_load_local_invocation_id(&b), 0); + nir_def *C = nir_load_push_constant(&b, 1, 32, nir_iadd(&b, nir_imm_int(&b, 0), nir_imm_int(&b, 4)), + .base = 0, .range = 8); + nir_def *sm = nir_iadd_imm(&b, C, -1); + sm = nir_ior(&b, sm, nir_ishr_imm(&b, sm, 1)); + sm = nir_ior(&b, sm, nir_ishr_imm(&b, sm, 2)); + sm = nir_ior(&b, sm, nir_ishr_imm(&b, sm, 4)); + sm = nir_ior(&b, sm, nir_ishr_imm(&b, sm, 8)); + sm = nir_ior(&b, sm, nir_extract_i16(&b, sm, nir_imm_int(&b, 1))); + nir_def *np2 = nir_iadd_imm(&b, sm, 1); + + /* Countdown loop: i = (next_pow2(C) - 1) - lid; while (i >= C) i -= 32 */ + nir_variable *vi = nir_local_variable_create(b.impl, glsl_int_type(), "i"); + nir_store_var(&b, vi, nir_iadd(&b, sm, nir_ineg(&b, lid)), 1); + nir_push_loop(&b); + { + nir_def *i = nir_load_var(&b, vi); + nir_push_if(&b, nir_ige(&b, i, C)); + nir_push_else(&b, NULL); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + nir_store_var(&b, vi, nir_iadd_imm(&b, i, -32), 1); + } + nir_pop_loop(&b, NULL); + + /* Halving loop: s = next_pow2(C) / 2; while (0 < s) s = isign(s)*(|s|>>1) */ + nir_variable *vs = nir_local_variable_create(b.impl, glsl_int_type(), "s"); + nir_def *s_init = nir_idiv(&b, np2, nir_imm_int(&b, 2)); + nir_store_var(&b, vs, s_init, 1); + nir_push_loop(&b); + { + nir_def *sv = nir_load_var(&b, vs); + nir_push_if(&b, nir_ilt(&b, nir_imm_int(&b, 0), sv)); + nir_push_else(&b, NULL); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + nir_def *mag = nir_ushr_imm(&b, nir_iabs(&b, sv), 1); + nir_def *sgn = nir_imin(&b, nir_imax(&b, sv, nir_imm_int(&b, -1)), nir_imm_int(&b, 1)); + nir_store_var(&b, vs, nir_imul(&b, sgn, mag), 1); + } + nir_pop_loop(&b, NULL); + nir_lower_vars_to_ssa(s); + nir_validate_shader(s, "softmax_bounds"); + + struct hk_pack_loop_bound lb = {0}; + HK_EVAL_CHECK(hk_nir_compute_pack_loop_bound(s, NULL, 0, &lb) && lb.valid); + int32_t push[2] = { 48384, 2 }; + uint32_t grid[3] = { 24192, 1, 1 }; + uint64_t val = 0; + /* countdown: ceil((2*2 + 1)/32) = 1; halving: log2(2*2/2)+1 = 2; total = 1 + 1 + 2 = 4 */ + HK_EVAL_CHECK(hk_pack_eval_loop_bound_dispatch(&lb, NULL, push, sizeof(push), grid, &val)); + HK_EVAL_CHECK(val == 4); + /* Negative C must fail closed */ + push[1] = -1; + HK_EVAL_CHECK(!hk_pack_eval_loop_bound_dispatch(&lb, NULL, push, sizeof(push), grid, &val)); + ralloc_free(s); + } + + /* 3. Sliding-window stencil with if-phi min (Gaussian Blur H/V pattern). */ + { + nir_shader *s = new_compute_shader("stencil_window", 32, 1, 1); + nir_builder b = nir_builder_at(nir_before_impl(nir_shader_get_entrypoint(s))); + nir_def *x = nir_channel(&b, nir_load_global_invocation_id(&b, 32), 0); + nir_def *W0 = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .base = 0, .range = 16); + nir_def *W1 = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .base = 0, .range = 16); + nir_def *K = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 12), .base = 0, .range = 16); + nir_def *rad = nir_idiv(&b, K, nir_imm_int(&b, 2)); + nir_def *start = nir_imax(&b, nir_iadd(&b, x, nir_ineg(&b, rad)), nir_imm_int(&b, 0)); + nir_def *x_hi = nir_iadd(&b, x, rad); + nir_def *w_m1_a = nir_iadd_imm(&b, W0, -1); + + nir_variable *vend = nir_local_variable_create(b.impl, glsl_int_type(), "end"); + nir_push_if(&b, nir_ilt(&b, w_m1_a, x_hi)); + { + nir_store_var(&b, vend, nir_iadd_imm(&b, W1, -1), 1); + } + nir_push_else(&b, NULL); + { + nir_store_var(&b, vend, x_hi, 1); + } + nir_pop_if(&b, NULL); + nir_def *end = nir_load_var(&b, vend); + + nir_variable *vi = nir_local_variable_create(b.impl, glsl_int_type(), "i"); + nir_store_var(&b, vi, start, 1); + nir_push_loop(&b); + { + nir_def *i = nir_load_var(&b, vi); + nir_push_if(&b, nir_ige(&b, end, i)); + nir_push_else(&b, NULL); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + nir_store_var(&b, vi, nir_iadd_imm(&b, i, 1), 1); + } + nir_pop_loop(&b, NULL); + nir_lower_vars_to_ssa(s); + nir_validate_shader(s, "stencil_window"); + + struct hk_pack_loop_bound lb = {0}; + HK_EVAL_CHECK(hk_nir_compute_pack_loop_bound(s, NULL, 0, &lb) && lb.valid); + int32_t push[4] = { 1920, 1088, 1920, 113 }; + uint32_t grid[3] = { 60, 1088, 1 }; + uint64_t val = 0; + /* rad = 56 -> span = 56 + 56 + 1 = 113 -> total = 114 */ + HK_EVAL_CHECK(hk_pack_eval_loop_bound_dispatch(&lb, NULL, push, sizeof(push), grid, &val)); + HK_EVAL_CHECK(val == 114); + /* Negative kernel size fails closed */ + push[3] = -4; + HK_EVAL_CHECK(!hk_pack_eval_loop_bound_dispatch(&lb, NULL, push, sizeof(push), grid, &val)); + /* Grid + rad + 2 overflowing INT32_MAX fails closed */ + push[3] = 113; + grid[0] = (uint32_t)INT32_MAX / 32u; + HK_EVAL_CHECK(!hk_pack_eval_loop_bound_dispatch(&lb, NULL, push, sizeof(push), grid, &val)); + ralloc_free(s); + } + + /* 4. Bottom-tested loop with additive limit expression (`2 * radius + 32`). */ + { + nir_shader *s = new_compute_shader("bottom_tested_additive", 32, 1, 1); + nir_builder b = nir_builder_at(nir_before_impl(nir_shader_get_entrypoint(s))); + nir_def *rad = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .base = 0, .range = 4); + nir_def *lim = nir_iadd_imm(&b, nir_imul_imm(&b, rad, 2), 32); + nir_variable *vi = nir_local_variable_create(b.impl, glsl_int_type(), "i"); + nir_store_var(&b, vi, nir_imm_int(&b, 0), 1); + nir_push_loop(&b); + { + nir_def *i_next = nir_iadd_imm(&b, nir_load_var(&b, vi), 32); + nir_store_var(&b, vi, i_next, 1); + nir_push_if(&b, nir_ige(&b, i_next, lim)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + } + nir_pop_loop(&b, NULL); + nir_lower_vars_to_ssa(s); + nir_validate_shader(s, "bottom_tested_additive"); + + struct hk_pack_loop_bound lb = {0}; + HK_EVAL_CHECK(hk_nir_compute_pack_loop_bound(s, NULL, 0, &lb) && lb.valid); + int32_t push[1] = { 16 }; + uint32_t grid[3] = { 1, 1, 1 }; + uint64_t val = 0; + /* lim = 64, step = 32 -> trips = 2 -> total = 3 */ + HK_EVAL_CHECK(hk_pack_eval_loop_bound_dispatch(&lb, NULL, push, sizeof(push), grid, &val)); + HK_EVAL_CHECK(val == 3); + ralloc_free(s); + } + + /* Two negative signed factors give a positive loop limit. */ + { + nir_shader *s = new_compute_shader("signed_product_limit", 32, 1, 1); + nir_builder b = nir_builder_at(nir_before_impl(nir_shader_get_entrypoint(s))); + nir_def *a = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), + .base = 0, .range = 8); + nir_def *c = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 4), + .base = 0, .range = 8); + nir_def *limit = nir_imul(&b, a, c); + nir_variable *iv = nir_local_variable_create(b.impl, glsl_int_type(), "i"); + nir_store_var(&b, iv, nir_imm_int(&b, 0), 1); + nir_push_loop(&b); + nir_def *i = nir_load_var(&b, iv); + nir_push_if(&b, nir_ige(&b, i, limit)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + nir_store_var(&b, iv, nir_iadd_imm(&b, i, 1), 1); + nir_pop_loop(&b, NULL); + nir_lower_vars_to_ssa(s); + nir_validate_shader(s, "signed_product_limit"); + + struct hk_pack_loop_bound lb = {0}; + HK_EVAL_CHECK(hk_nir_compute_pack_loop_bound(s, NULL, 0, &lb) && lb.valid); + int32_t push[2] = {4, 5}; + uint32_t grid[3] = {1, 1, 1}; + uint64_t val = 0; + HK_EVAL_CHECK(hk_pack_eval_loop_bound_dispatch(&lb, NULL, push, sizeof(push), grid, &val)); + HK_EVAL_CHECK(val >= 20); + push[0] = push[1] = -1000; + HK_EVAL_CHECK(!hk_pack_eval_loop_bound_dispatch(&lb, NULL, push, sizeof(push), grid, &val)); + ralloc_free(s); + } + + /* The inner body runs even on the final iteration of a post-increment outer loop. */ + { + nir_shader *s = new_compute_shader("late_break_old_phi", 32, 1, 1); + nir_builder b = nir_builder_at(nir_before_impl(nir_shader_get_entrypoint(s))); + nir_def *limit = nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), + .base = 0, .range = 4); + nir_variable *outer = nir_local_variable_create(b.impl, glsl_int_type(), "outer"); + nir_variable *inner = nir_local_variable_create(b.impl, glsl_int_type(), "inner"); + nir_store_var(&b, outer, nir_imm_int(&b, 0), 1); + nir_push_loop(&b); + nir_def *i = nir_load_var(&b, outer); + nir_store_var(&b, inner, nir_imm_int(&b, 0), 1); + nir_push_loop(&b); + nir_def *j = nir_load_var(&b, inner); + nir_push_if(&b, nir_ige_imm(&b, j, 1000)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + nir_store_var(&b, inner, nir_iadd_imm(&b, j, 1), 1); + nir_pop_loop(&b, NULL); + nir_store_var(&b, outer, nir_iadd_imm(&b, i, 1), 1); + nir_push_if(&b, nir_ige(&b, i, limit)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + nir_pop_loop(&b, NULL); + nir_lower_vars_to_ssa(s); + nir_opt_copy_prop(s); + nir_opt_dce(s); + nir_validate_shader(s, "late_break_old_phi"); + + struct hk_pack_loop_bound lb = {0}; + HK_EVAL_CHECK(!hk_nir_compute_pack_loop_bound(s, NULL, 0, &lb) || !lb.valid); + ralloc_free(s); + } + + /* 5. SSBO-bounded loop must fail closed (valid == false). */ + { + nir_shader *s = new_compute_shader("ssbo_unbounded", 32, 1, 1); + nir_builder b = nir_builder_at(nir_before_impl(nir_shader_get_entrypoint(s))); + nir_def *lim = nir_load_ssbo(&b, 1, 32, nir_imm_int(&b, 0), nir_imm_int(&b, 0)); + nir_variable *vi = nir_local_variable_create(b.impl, glsl_int_type(), "i"); + nir_store_var(&b, vi, nir_imm_int(&b, 0), 1); + nir_push_loop(&b); + { + nir_def *i = nir_load_var(&b, vi); + nir_push_if(&b, nir_ige(&b, i, lim)); + nir_jump(&b, nir_jump_break); + nir_pop_if(&b, NULL); + nir_store_var(&b, vi, nir_iadd_imm(&b, i, 1), 1); + } + nir_pop_loop(&b, NULL); + nir_lower_vars_to_ssa(s); + nir_validate_shader(s, "ssbo_unbounded"); + + struct hk_pack_loop_bound lb = {0}; + HK_EVAL_CHECK(!hk_nir_compute_pack_loop_bound(s, NULL, 0, &lb) && !lb.valid); + ralloc_free(s); + } +} + + int main(void) { @@ -5946,6 +6262,7 @@ main(void) test_gemm_cmat_certify_and_build(); test_gemm_cmat_guarded_specialize_and_shape_sweep(); test_gemm_cmat_k32_small_tiles(); + test_general_pack_loop_bounds(); test_dual_write_fusion(); test_gemm_dual_fadd_fusion(); test_dual_copy2_fusion(); diff --git a/src/asahi/vulkan/tests/test-hk-pack.c b/src/asahi/vulkan/tests/test-hk-pack.c index 3bd5afbaf161..ab5b5f9c1253 100644 --- a/src/asahi/vulkan/tests/test-hk-pack.c +++ b/src/asahi/vulkan/tests/test-hk-pack.c @@ -2396,6 +2396,89 @@ main(int argc, char **argv) T("two bounded looping members pack into one packet", rc == 1 && runs[0].count == 2); + /* General dispatch-time loop-bound ops (push constants, grid dims, + * ceil-div, div-const, log2+1, i32 overflow assertions). */ + { + struct hk_pack_loop_bound dlb = { + .valid = true, + .count = 6, + .ops = { + [0] = { .kind = HK_PACK_LOOP_OP_PUSH_I32_POS, .imm = 0 }, + [1] = { .kind = HK_PACK_LOOP_OP_GRID_GROUPS, .imm = 0 }, + [2] = { .kind = HK_PACK_LOOP_OP_CONST, .imm = 32 }, + [3] = { .kind = HK_PACK_LOOP_OP_MUL, .lhs = 1, .rhs = 2 }, + [4] = { .kind = HK_PACK_LOOP_OP_CEIL_DIV_I32, .lhs = 0, .rhs = 3 }, + [5] = { .kind = HK_PACK_LOOP_OP_ADD, .lhs = 4, .rhs = 2 }, + }, + }; + int32_t push[4] = { 1000, 113, 0, 0 }; + uint32_t grid[3] = { 10, 1, 1 }; + uint64_t out = 0; + /* ceil(1000 / 320) + 32 = 4 + 32 = 36 */ + T("dispatch eval push i32 + grid groups ceil_div", + hk_pack_eval_loop_bound_dispatch(&dlb, NULL, push, sizeof(push), grid, &out) && + out == 36); + /* Negative push -> clamped to 0 for PUSH_I32_POS -> 0 + 32 = 32 */ + push[0] = -50; + T("dispatch eval PUSH_I32_POS clamps negative to 0", + hk_pack_eval_loop_bound_dispatch(&dlb, NULL, push, sizeof(push), grid, &out) && + out == 32); + /* Wrap hazard: lim + step > INT32_MAX fails closed */ + push[0] = INT32_MAX - 100; + T("dispatch eval CEIL_DIV_I32 fails closed on 32-bit wrap hazard", + !hk_pack_eval_loop_bound_dispatch(&dlb, NULL, push, sizeof(push), grid, &out)); + /* Zero step fails closed */ + push[0] = 100; + grid[0] = 0; + T("dispatch eval CEIL_DIV_I32 fails closed on zero step", + !hk_pack_eval_loop_bound_dispatch(&dlb, NULL, push, sizeof(push), grid, &out)); + /* Out-of-bounds push offset fails closed */ + grid[0] = 10; + T("dispatch eval fails closed when push buffer is too small", + !hk_pack_eval_loop_bound_dispatch(&dlb, NULL, push, 2, grid, &out)); + + /* PUSH_I32_NONNEG + DIV_CONST + LOG2_PLUS1 + ASSERT_I32 */ + struct hk_pack_loop_bound slb = { + .valid = true, + .count = 6, + .ops = { + [0] = { .kind = HK_PACK_LOOP_OP_PUSH_I32_NONNEG, .imm = 4 }, + [1] = { .kind = HK_PACK_LOOP_OP_DIV_CONST, .lhs = 0, .imm = 2 }, + [2] = { .kind = HK_PACK_LOOP_OP_ASSERT_I32, .lhs = 1 }, + [3] = { .kind = HK_PACK_LOOP_OP_LOG2_PLUS1, .lhs = 1 }, + [4] = { .kind = HK_PACK_LOOP_OP_ADD, .lhs = 3, .rhs = 2 }, + [5] = { .kind = HK_PACK_LOOP_OP_ADD, .lhs = 4, .rhs = 1 }, + }, + }; + /* push[1]=113 -> div 2 = 56, log2(56)+1 = 6, + 56 = 62 */ + T("dispatch eval PUSH_I32_NONNEG + DIV_CONST + LOG2_PLUS1 + ASSERT_I32", + hk_pack_eval_loop_bound_dispatch(&slb, NULL, push, sizeof(push), grid, &out) && + out == 62); + /* Negative push fails closed on PUSH_I32_NONNEG */ + push[1] = -1; + T("dispatch eval PUSH_I32_NONNEG fails closed on negative input", + !hk_pack_eval_loop_bound_dispatch(&slb, NULL, push, sizeof(push), grid, &out)); + + /* Unsigned wrap hazard on CEIL_DIV_U32 */ + struct hk_pack_loop_bound ulb = { + .valid = true, + .count = 3, + .ops = { + [0] = { .kind = HK_PACK_LOOP_OP_PUSH_U32, .imm = 0 }, + [1] = { .kind = HK_PACK_LOOP_OP_CONST, .imm = 32 }, + [2] = { .kind = HK_PACK_LOOP_OP_CEIL_DIV_U32, .lhs = 0, .rhs = 1 }, + }, + }; + uint32_t upush[2] = { UINT32_MAX - 10u, 0 }; + T("dispatch eval CEIL_DIV_U32 fails closed on uint32 wrap hazard", + !hk_pack_eval_loop_bound_dispatch(&ulb, NULL, upush, sizeof(upush), grid, &out)); + upush[0] = 65u; + T("dispatch eval CEIL_DIV_U32 computes exact ceil", + hk_pack_eval_loop_bound_dispatch(&ulb, NULL, upush, sizeof(upush), grid, &out) && + out == 3); + } + + /* Core-count-scaled static-work budget (1x at <=20, 2x at 40, 4x at >=80). */ T("work budget stays 1x for <=20 cores", hk_pack_max_static_work_for_cores(10) == HK_PACK_MAX_STATIC_WORK &&