diff --git a/src/asahi/compiler/agx_compile.c b/src/asahi/compiler/agx_compile.c index 2805b56a4611..faec002e0362 100644 --- a/src/asahi/compiler/agx_compile.c +++ b/src/asahi/compiler/agx_compile.c @@ -15442,7 +15442,8 @@ agx_assert_post_lower_invariants(const nir_shader *nir, bool g17p, bool m5, static void agx_preprocess_nir_internal(nir_shader *nir, bool g17p, bool native_fragment_depth, - bool g18g, bool m5, bool chip_g17p, bool post_lower) + bool g18g, bool m5, bool chip_g17p, bool post_lower, + bool defer_idiv) { if (!nir) return; @@ -15548,10 +15549,15 @@ agx_preprocess_nir_internal(nir_shader *nir, bool g17p, bool native_fragment_dep * provably nonnegative operands first so the remaining lowering drops * redundant sign fixups. Other integer division waits for the shader key * (agx_nir_lower_integer_division), which decides whether a preamble forms. + * The first preprocessing of a Vulkan compute shader may defer these passes + * so compute-kernel matchers see the raw idiv/udiv/irem/imod/umod by a + * constant; hk_lower_nir() preprocesses it again before backend compilation. */ - NIR_PASS(_, nir, agx_nir_opt_iv_divmod); - NIR_PASS(_, nir, agx_nir_opt_nonneg_idiv); - NIR_PASS(_, nir, nir_opt_idiv_const, 16); + if (!defer_idiv) { + NIR_PASS(_, nir, agx_nir_opt_iv_divmod); + NIR_PASS(_, nir, agx_nir_opt_nonneg_idiv); + NIR_PASS(_, nir, nir_opt_idiv_const, 16); + } NIR_PASS(_, nir, nir_opt_deref); NIR_PASS(_, nir, nir_lower_vars_to_ssa); @@ -15631,14 +15637,22 @@ agx_preprocess_nir_internal(nir_shader *nir, bool g17p, bool native_fragment_dep void agx_preprocess_nir(nir_shader *nir) { - agx_preprocess_nir_internal(nir, false, false, false, false, false, false); + agx_preprocess_nir_internal(nir, false, false, false, false, false, false, + false); } void agx_preprocess_nir_native(nir_shader *nir, enum agx_chip chip) { agx_preprocess_nir_internal(nir, true, true, false, false, - chip == AGX_CHIP_G17P, false); + chip == AGX_CHIP_G17P, false, false); +} + +void +agx_preprocess_nir_native_defer_idiv(nir_shader *nir, enum agx_chip chip) +{ + agx_preprocess_nir_internal(nir, true, true, false, false, + chip == AGX_CHIP_G17P, false, true); } void @@ -15651,7 +15665,8 @@ void agx_preprocess_nir_g18g(nir_shader *nir) { /* Select G18 trig without inheriting G17P subgroup/shared-memory rules. */ - agx_preprocess_nir_internal(nir, false, false, true, false, false, false); + agx_preprocess_nir_internal(nir, false, false, true, false, false, false, + false); } void @@ -15664,7 +15679,7 @@ agx_preprocess_nir_post_lower(nir_shader *nir, enum agx_chip chip) const bool chip_g17p = chip == AGX_CHIP_G17P; agx_preprocess_nir_internal(nir, g17p, native_fragment_depth, g18g, m5, - chip_g17p, true); + chip_g17p, true, false); } static bool @@ -18459,5 +18474,13 @@ agx_compile_shader_nir_preoptimized(nir_shader *nir, struct agx_shader_key *key, void agx_preprocess_nir_m5(nir_shader *nir) { - agx_preprocess_nir_internal(nir, false, true, false, true, false, false); + agx_preprocess_nir_internal(nir, false, true, false, true, false, false, + false); +} + +void +agx_preprocess_nir_m5_defer_idiv(nir_shader *nir) +{ + agx_preprocess_nir_internal(nir, false, true, false, true, false, false, + true); } diff --git a/src/asahi/compiler/agx_compile.h b/src/asahi/compiler/agx_compile.h index d7f6e438731a..dce18491c2d7 100644 --- a/src/asahi/compiler/agx_compile.h +++ b/src/asahi/compiler/agx_compile.h @@ -761,6 +761,7 @@ void agx_preprocess_nir_g17p(nir_shader *nir); /* For any native AGX3 chip (agx_chip_native_agx3); passes validated on G17P * alone check chip. */ void agx_preprocess_nir_native(nir_shader *nir, enum agx_chip chip); +void agx_preprocess_nir_native_defer_idiv(nir_shader *nir, enum agx_chip chip); void agx_preprocess_nir_g18g(nir_shader *nir); /* Fast second-stage preprocessing for shaders already preprocessed once before * simple I/O or push-constant lowering. Falls back to full preprocessing if any @@ -771,6 +772,7 @@ void agx_preprocess_nir_post_lower(nir_shader *nir, enum agx_chip chip); * AGX3 stack protocol encodes. agx_preprocess_nir_g17p() runs it. */ bool agx3_nir_lower_scratch_words(nir_shader *nir); void agx_preprocess_nir_m5(nir_shader *nir); +void agx_preprocess_nir_m5_defer_idiv(nir_shader *nir); bool agx_nir_lower_discard_zs_emit(nir_shader *s); bool agx_nir_lower_sample_mask(nir_shader *s); /* TARGET/LIVE retain their normal semantics. This flag records the proof that diff --git a/src/asahi/vulkan/hk_agx3_vdm_decode.h b/src/asahi/vulkan/hk_agx3_vdm_decode.h index ebe17eea6038..d9fbe3c05896 100644 --- a/src/asahi/vulkan/hk_agx3_vdm_decode.h +++ b/src/asahi/vulkan/hk_agx3_vdm_decode.h @@ -34,9 +34,10 @@ extern "C" { * attachmentless layer-zero root lowering and fs.reads_layer, to 46 when * AGX3 fragment binaries carry on-chip local_read NIR payloads, to 47 * when agx_shader_info gains AGX3 vertex preamble hoist metadata and - * vertex binaries may carry extracted preamble NIR, and to 48 when - * hk_shader_info.vs records per-pipeline vertex input robustness. */ -#define HK_AGX3_SHADER_BINARY_VERSION 48u + * vertex binaries may carry extracted preamble NIR, to 48 when + * hk_shader_info.vs records per-pipeline vertex input robustness, and to 49 + * when compute shaders carry packed vec4 alternates. */ +#define HK_AGX3_SHADER_BINARY_VERSION 49u #define HK_CLASSIC_SHADER_BINARY_VERSION 37u /* AGX2 binaries include attachmentless layer-zero root lowering, fs.reads_layer, * and per-pipeline vertex input robustness in hk_shader_info.vs. */ diff --git a/src/asahi/vulkan/hk_buffer.c b/src/asahi/vulkan/hk_buffer.c index d8a9a0814398..368f01bd2ad7 100644 --- a/src/asahi/vulkan/hk_buffer.c +++ b/src/asahi/vulkan/hk_buffer.c @@ -618,6 +618,11 @@ hk_BindBufferMemory2(VkDevice device, uint32_t bindInfoCount, assert(buffer->vk.device_address == 0); buffer->vk.device_address = hk_device_memory_addr(mem) + pBindInfos[i].memoryOffset; + if (!mem->replay_va && + !(mem->bo->flags & (AGX_BO_SHARED | AGX_BO_SHAREABLE | AGX_BO_HOST_PTR))) { + buffer->storage_backing_handle = mem->bo->handle; + buffer->storage_backing_offset = pBindInfos[i].memoryOffset; + } } VK_FROM_HANDLE(hk_device, dev, device); diff --git a/src/asahi/vulkan/hk_buffer.h b/src/asahi/vulkan/hk_buffer.h index 60069a073f21..1fbf4a2c7481 100644 --- a/src/asahi/vulkan/hk_buffer.h +++ b/src/asahi/vulkan/hk_buffer.h @@ -19,6 +19,9 @@ struct hk_physical_device; struct hk_buffer { struct vk_buffer vk; + uint32_t storage_backing_handle; + uint64_t storage_backing_offset; + /** Reserved VA for sparse buffers, NULL otherwise. */ struct agx_va *va; diff --git a/src/asahi/vulkan/hk_cmd_buffer.c b/src/asahi/vulkan/hk_cmd_buffer.c index 426329590177..cfab3c9682ec 100644 --- a/src/asahi/vulkan/hk_cmd_buffer.c +++ b/src/asahi/vulkan/hk_cmd_buffer.c @@ -5,6 +5,7 @@ * SPDX-License-Identifier: MIT */ #include "hk_cmd_buffer.h" +#include "hk_identity_copy4.h" #include "util/format/u_format.h" #include "hk_frame_anatomy.h" #include "hk_ppp_state.h" @@ -1651,7 +1652,7 @@ hk_CmdBindDescriptorSets2KHR( } static void -hk_push_constants(UNUSED struct hk_cmd_buffer *cmd, +hk_push_constants(struct hk_cmd_buffer *cmd, struct hk_descriptor_state *desc, const VkPushConstantsInfoKHR *info) { @@ -1664,6 +1665,12 @@ hk_push_constants(UNUSED struct hk_cmd_buffer *cmd, desc->push_written_dwords |= mask << first_dw; } + if (!cmd->in_meta && desc == &cmd->state.cs.descriptors && + info->offset < HK_COMPUTE_OPT_PUSH_BYTES) { + unsigned size = MIN2(info->size, HK_COMPUTE_OPT_PUSH_BYTES - info->offset); + desc->identity_copy4_push_mask |= BITFIELD64_MASK(size) << info->offset; + } + /* D3D translation layers re-push unchanged constants before most draws. * While the root is clean the uploaded root holds exactly these bytes, so * an identical push changes nothing; keep the root and every preparation diff --git a/src/asahi/vulkan/hk_cmd_buffer.h b/src/asahi/vulkan/hk_cmd_buffer.h index a675748fed2b..48d4deeef962 100644 --- a/src/asahi/vulkan/hk_cmd_buffer.h +++ b/src/asahi/vulkan/hk_cmd_buffer.h @@ -511,6 +511,7 @@ static_assert(hk_root_descriptor_offset(set_dynamic_buffer_start) == struct hk_descriptor_state { bool root_dirty; uint64_t generation; + uint64_t identity_copy4_push_mask; struct hk_root_descriptor_table root; /* Immutable command-buffer storage; reset with descriptor state. Only the * uploaded head and tail are compared, excluding unused dynamic slots. */ diff --git a/src/asahi/vulkan/hk_cmd_dispatch.c b/src/asahi/vulkan/hk_cmd_dispatch.c index 85e9b43944eb..08bb72cbffe6 100644 --- a/src/asahi/vulkan/hk_cmd_dispatch.c +++ b/src/asahi/vulkan/hk_cmd_dispatch.c @@ -3105,6 +3105,334 @@ hk_dispatch_g17g_native(struct hk_cmd_buffer *cmd, struct hk_cs *cs, cs->stats.cmds++; } +static bool +hk_read_push_i32(const struct hk_descriptor_state *desc, uint32_t off, int32_t *out) +{ + if (off + 4 > HK_COMPUTE_OPT_PUSH_BYTES) + return false; + const uint64_t mask = BITFIELD64_MASK(4) << off; + if ((desc->identity_copy4_push_mask & mask) != mask) + return false; + memcpy(out, desc->root.push + off, sizeof(*out)); + return true; +} + +static bool +hk_identity_copy4_required_bytes(const struct hk_descriptor_state *desc, + const struct hk_identity_copy4 *info, + struct agx_grid grid, const uint16_t local[3], + uint64_t *bytes, uint32_t *k_out) +{ + int32_t bw = 0, bh = 0, iw = 0, ih = 0, kw = 0, k = 0, m = 0, sw = 0, sh = 0, channels = 0; + if (!hk_read_push_i32(desc, info->border_width_offset, &bw) || + !hk_read_push_i32(desc, info->border_height_offset, &bh) || + !hk_read_push_i32(desc, info->input_width_offset, &iw) || + !hk_read_push_i32(desc, info->input_height_offset, &ih) || + !hk_read_push_i32(desc, info->kernel_width_offset, &kw) || + !hk_read_push_i32(desc, info->patches_width_offset, &k) || + !hk_read_push_i32(desc, info->patches_height_offset, &m) || + !hk_read_push_i32(desc, info->stride_width_offset, &sw) || + !hk_read_push_i32(desc, info->stride_height_offset, &sh) || + !hk_read_push_i32(desc, info->channels_offset, &channels)) + return false; + + if (bw || bh || sw != 1 || sh != 1 || + iw <= 0 || ih <= 0 || channels <= 0 || kw != channels || k != channels || + k % 4 || iw % channels || m <= 0 || (uint64_t)(iw / channels) * ih != (uint64_t)m) + return false; + + if (grid.count[0] != DIV_ROUND_UP((uint32_t)k, local[0]) || + grid.count[1] != DIV_ROUND_UP((uint32_t)m, local[1]) || grid.count[2] != 1) + return false; + + const uint64_t extent = (uint64_t)m * k * sizeof(uint32_t); + if (extent > (uint64_t)INT32_MAX + 1) + return false; + *bytes = extent; + *k_out = (uint32_t)k; + return true; +} + +static bool +hk_intervals_disjoint(const struct hk_storage_backing *a, uint64_t a_start, uint64_t a_bytes, + const struct hk_storage_backing *b, uint64_t b_start, uint64_t b_bytes) +{ + if (!a_bytes || !b_bytes) + return true; + const uint64_t a_bo0 = a->offset + a_start, a_bo1 = a_bo0 + a_bytes; + const uint64_t b_bo0 = b->offset + b_start, b_bo1 = b_bo0 + b_bytes; + const uint64_t a_va0 = a->address + a_start, a_va1 = a_va0 + a_bytes; + const uint64_t b_va0 = b->address + b_start, b_va1 = b_va0 + b_bytes; + const bool bo_overlap = + a->handle == b->handle && a_bo0 < b_bo1 && b_bo0 < a_bo1; + const bool va_overlap = a_va0 < b_va1 && b_va0 < a_va1; + return !bo_overlap && !va_overlap; +} + +static bool +hk_copy4_intervals_safe(const struct hk_storage_backing *src, uint64_t src_start, + const struct hk_storage_backing *dst, uint64_t dst_start, + uint64_t bytes, bool allow_exact_inplace) +{ + const uint64_t s_bo0 = src->offset + src_start, s_bo1 = s_bo0 + bytes; + const uint64_t d_bo0 = dst->offset + dst_start, d_bo1 = d_bo0 + bytes; + const uint64_t s_va0 = src->address + src_start, s_va1 = s_va0 + bytes; + const uint64_t d_va0 = dst->address + dst_start, d_va1 = d_va0 + bytes; + + if (allow_exact_inplace && + src->handle == dst->handle && s_bo0 == d_bo0 && s_va0 == d_va0) + return true; + + const bool bo_overlap = + src->handle == dst->handle && s_bo0 < d_bo1 && d_bo0 < s_bo1; + const bool va_overlap = s_va0 < d_va1 && d_va0 < s_va1; + return !bo_overlap && !va_overlap; +} + +static bool +hk_check_storage_backing(const struct hk_descriptor_state *desc, + unsigned set, unsigned binding, + uint64_t start, uint64_t bytes, unsigned align, + struct hk_storage_backing *backing) +{ + if (set >= HK_MAX_SETS || ((desc->buffer_active | desc->push_active) & BITFIELD_BIT(set))) + return false; + if (!hk_descriptor_set_storage_backing(desc->sets[set], binding, backing)) + return false; + if (desc->root.sets[set] != hk_descriptor_set_addr(desc->sets[set])) + return false; + if (!backing->address || (backing->address | backing->offset) % align) + return false; + const uint64_t end = start + bytes; + if (end < bytes || backing->size < end || + backing->address > UINT64_MAX - end || + backing->offset > UINT64_MAX - end) + return false; + return true; +} + +static struct hk_shader * +hk_select_im2col_vec4(struct hk_cmd_buffer *cmd, struct hk_api_shader *api, + struct hk_shader *normal, struct agx_grid *grid) +{ + struct hk_shader *alt = api->im2col_vec4; + const struct hk_descriptor_state *desc = &cmd->state.cs.descriptors; + struct hk_device *dev = hk_cmd_buffer_device(cmd); + const struct hk_identity_copy4 *info = &api->identity_copy4_info; + if (!alt || !info->im2col_vec4_ok || + !hk_g17p_compute_shader_supported(dev->dev.chip, alt, alt->only_linked, 1u << 16) || + alt->b.info.workgroup_size[0] == 0 || alt->b.info.workgroup_size[1] == 0 || + alt->b.info.workgroup_size[2] != 1) + return normal; + + int32_t bw = 0, bh = 0, iw = 0, ih = 0, kw = 0, pw = 0, ph = 0, sw = 0, sh = 0, ch = 0; + if (!hk_read_push_i32(desc, info->border_width_offset, &bw) || + !hk_read_push_i32(desc, info->border_height_offset, &bh) || + !hk_read_push_i32(desc, info->input_width_offset, &iw) || + !hk_read_push_i32(desc, info->input_height_offset, &ih) || + !hk_read_push_i32(desc, info->kernel_width_offset, &kw) || + !hk_read_push_i32(desc, info->patches_width_offset, &pw) || + !hk_read_push_i32(desc, info->patches_height_offset, &ph) || + !hk_read_push_i32(desc, info->stride_width_offset, &sw) || + !hk_read_push_i32(desc, info->stride_height_offset, &sh) || + !hk_read_push_i32(desc, info->channels_offset, &ch)) + return normal; + if (bw < 0 || bh < 0 || iw <= 0 || ih <= 0 || kw <= 0 || + pw <= 0 || ph <= 0 || sw <= 0 || sh <= 0 || ch <= 0) + return normal; + if ((ch % 4) != 0 || (iw % 4) != 0 || (kw % 4) != 0 || (pw % 4) != 0) + return normal; + if ((iw % ch) != 0 || (kw % ch) != 0) + return normal; + const bool unit = (sw == 1 && sh == 1); + const uint64_t pad_x = (uint64_t)(uint32_t)bw * (uint32_t)ch; + const uint64_t pad_x_tot = unit ? pad_x * 2 : pad_x; + if (pad_x_tot > (uint64_t)INT32_MAX - (uint32_t)iw || + (uint32_t)bh > 0x3fffffffu || (pad_x / 4) > 0x3fffffffu) + return normal; + const uint64_t bordered_iw = (uint32_t)iw + pad_x_tot; + if (bordered_iw < (uint32_t)kw) + return normal; + + if (grid->count[2] != 1 || + grid->count[0] < DIV_ROUND_UP((uint32_t)pw, info->local[0]) || + grid->count[1] < DIV_ROUND_UP((uint32_t)ph, info->local[1]) || + (uint64_t)grid->count[0] * info->local[0] > (uint64_t)INT32_MAX || + (uint64_t)grid->count[1] * info->local[1] > (uint64_t)INT32_MAX) + return normal; + + const uint64_t src_bytes = (uint64_t)(uint32_t)iw * (uint32_t)ih * sizeof(uint32_t); + const uint64_t dst_bytes = (uint64_t)(uint32_t)pw * (uint32_t)ph * sizeof(uint32_t); + if (src_bytes > (uint64_t)INT32_MAX + 1 || dst_bytes > (uint64_t)INT32_MAX + 1) + return normal; + + struct hk_storage_backing src_b, dst_b; + if (!hk_check_storage_backing(desc, info->src_set, info->src_binding, 0, src_bytes, 16, &src_b) || + !hk_check_storage_backing(desc, info->dst_set, info->dst_binding, 0, dst_bytes, 16, &dst_b)) + return normal; + + /* Reject overlap between source and destination buffers. */ + if (!hk_intervals_disjoint(&src_b, 0, src_bytes, &dst_b, 0, dst_bytes)) + return normal; + + grid->count[0] = DIV_ROUND_UP((uint32_t)pw / 4, alt->b.info.workgroup_size[0]); + grid->count[1] = DIV_ROUND_UP((uint32_t)ph, alt->b.info.workgroup_size[1]); + grid->count[2] = 1; + return alt; +} + +static struct hk_shader * +hk_select_identity_copy4(struct hk_cmd_buffer *cmd, struct hk_api_shader *api, + struct hk_shader *normal, struct agx_grid *grid) +{ + struct hk_shader *copy = api->identity_copy4; + const struct hk_descriptor_state *desc = &cmd->state.cs.descriptors; + struct hk_device *dev = hk_cmd_buffer_device(cmd); + if (!copy) + return normal; + if (!agx_chip_native_or_m5(dev->dev.chip) || + cmd->in_meta || cmd->vk.level != VK_COMMAND_BUFFER_LEVEL_PRIMARY) + return normal; + if (grid->mode != AGX_CDM_MODE_DIRECT || desc->root.cs.base_group[0] || + desc->root.cs.base_group[1] || desc->root.cs.base_group[2]) + return normal; + if (!hk_g17p_compute_shader_supported(dev->dev.chip, copy, copy->only_linked, 1u << 16)) + return normal; + + const struct hk_identity_copy4 *info = &api->identity_copy4_info; + if (!hk_identity_copy4_supported_local(info->local) || + memcmp(info->local, normal->b.info.workgroup_size, sizeof(info->local)) || + copy->b.info.workgroup_size[0] == 0 || + copy->b.info.workgroup_size[1] == 0 || + copy->b.info.workgroup_size[2] != 1) + return normal; + + if (info->kind == HK_IDENTITY_COPY4_PAD4) { + int32_t in_s[4], out_s[4]; + for (unsigned d = 0; d < 4; ++d) { + if (!hk_read_push_i32(desc, info->in_shape_off[d], &in_s[d]) || + !hk_read_push_i32(desc, info->out_shape_off[d], &out_s[d]) || + in_s[d] <= 0 || out_s[d] <= 0) + return normal; + } + if ((in_s[3] % 4) != 0 || (out_s[3] % 4) != 0) + return normal; + uint64_t in_elems = 1, out_elems = 1; + for (unsigned d = 0; d < 4; ++d) { + if (__builtin_mul_overflow(in_elems, (uint64_t)(uint32_t)in_s[d], &in_elems) || + __builtin_mul_overflow(out_elems, (uint64_t)(uint32_t)out_s[d], &out_elems)) + return normal; + } + const uint64_t in_bytes = in_elems * sizeof(uint32_t); + const uint64_t out_bytes = out_elems * sizeof(uint32_t); + if (in_elems > (uint64_t)INT32_MAX / 4 || out_elems > (uint64_t)INT32_MAX / 4) + return normal; + const uint64_t orig_x = (uint64_t)(uint32_t)out_s[2] * (uint32_t)out_s[3]; + const uint64_t orig_y = (uint64_t)(uint32_t)out_s[0] * (uint32_t)out_s[1]; + if (grid->count[2] != 1 || + orig_x > (uint64_t)INT32_MAX || orig_y > (uint64_t)INT32_MAX || + grid->count[0] < DIV_ROUND_UP((uint32_t)orig_x, info->local[0]) || + grid->count[1] < DIV_ROUND_UP((uint32_t)orig_y, info->local[1]) || + (uint64_t)grid->count[0] * info->local[0] > (uint64_t)INT32_MAX || + (uint64_t)grid->count[1] * info->local[1] > (uint64_t)INT32_MAX) + return normal; + uint32_t max_pad_idx = 0; + for (unsigned d = 0; d < 4; ++d) + max_pad_idx = MAX2(max_pad_idx, info->pad_idx[d]); + const uint64_t pad_bytes = ((uint64_t)max_pad_idx + 1) * sizeof(uint32_t); + struct hk_storage_backing src_b, pad_b, dst_b; + if (!hk_check_storage_backing(desc, info->src_set, info->src_binding, 0, in_bytes, 16, &src_b) || + !hk_check_storage_backing(desc, info->pad_set, info->pad_binding, 0, pad_bytes, 4, &pad_b) || + !hk_check_storage_backing(desc, info->dst_set, info->dst_binding, 0, out_bytes, 16, &dst_b)) + return normal; + if (!hk_intervals_disjoint(&src_b, 0, in_bytes, &dst_b, 0, out_bytes) || + !hk_intervals_disjoint(&pad_b, 0, pad_bytes, &dst_b, 0, out_bytes)) + return normal; + + const uint64_t out_x = (uint64_t)(uint32_t)out_s[2] * ((uint32_t)out_s[3] / 4); + const uint64_t out_y = (uint64_t)(uint32_t)out_s[0] * (uint32_t)out_s[1]; + if (out_x > UINT32_MAX || out_y > UINT32_MAX) + return normal; + grid->count[0] = DIV_ROUND_UP((uint32_t)out_x, copy->b.info.workgroup_size[0]); + grid->count[1] = DIV_ROUND_UP((uint32_t)out_y, copy->b.info.workgroup_size[1]); + grid->count[2] = 1; + return copy; + } + + if (copy->b.info.workgroup_size[1] != 1) + return normal; + + uint64_t bytes = 0; + uint64_t src_start = 0, dst_start = 0; + if (info->kind == HK_IDENTITY_COPY4_IM2COL_1X1) { + uint32_t k; + if (!hk_identity_copy4_required_bytes(desc, info, *grid, info->local, &bytes, &k)) + return hk_select_im2col_vec4(cmd, api, normal, grid); + } else if (info->kind == HK_IDENTITY_COPY4_LINEAR_COPY || + info->kind == HK_IDENTITY_COPY4_LINEAR_OFFSET || + info->kind == HK_IDENTITY_COPY4_LINEAR_FADD) { + int32_t count = 0; + if (!hk_read_push_i32(desc, info->count_offset, &count)) + return normal; + if (count <= 0 || (count % 4) != 0) + return normal; + if (grid->count[1] != 1 || grid->count[2] != 1 || + grid->count[0] < DIV_ROUND_UP((uint32_t)count, info->local[0]) || + (uint64_t)grid->count[0] * info->local[0] > (uint64_t)INT32_MAX) + return normal; + bytes = (uint64_t)(uint32_t)count * sizeof(uint32_t); + if (bytes > (uint64_t)INT32_MAX + 1) + return normal; + if (info->kind == HK_IDENTITY_COPY4_LINEAR_OFFSET) { + int32_t so = 0, doff = 0; + if (!hk_read_push_i32(desc, info->src_offset_offset, &so) || + !hk_read_push_i32(desc, info->dst_offset_offset, &doff)) + return normal; + if (so < 0 || doff < 0 || (so % 4) != 0 || (doff % 4) != 0 || + (uint64_t)(uint32_t)so + (uint32_t)count > (uint64_t)INT32_MAX || + (uint64_t)(uint32_t)doff + (uint32_t)count > (uint64_t)INT32_MAX) + return normal; + src_start = (uint64_t)(uint32_t)so * sizeof(uint32_t); + dst_start = (uint64_t)(uint32_t)doff * sizeof(uint32_t); + } + } else { + return normal; + } + + const unsigned nsrc = info->src_count ? info->src_count : 1; + if (nsrc > 2) + return normal; + const uint8_t sets[3] = {info->src_set, info->src1_set, info->dst_set}; + const uint16_t bindings[3] = {info->src_binding, info->src1_binding, info->dst_binding}; + const uint64_t starts[3] = {src_start, src_start, dst_start}; + struct hk_storage_backing backings[3]; + for (unsigned i = 0; i < 3; i++) { + if (i == 1 && nsrc < 2) + continue; + if (!hk_check_storage_backing(desc, sets[i], bindings[i], starts[i], bytes, 16, &backings[i])) + return normal; + } + + const bool allow_inplace = + (info->kind == HK_IDENTITY_COPY4_LINEAR_COPY || + info->kind == HK_IDENTITY_COPY4_LINEAR_FADD); + if (!hk_copy4_intervals_safe(&backings[0], src_start, &backings[2], dst_start, + bytes, allow_inplace)) + return normal; + if (nsrc == 2 && + !hk_copy4_intervals_safe(&backings[1], src_start, &backings[2], dst_start, + bytes, allow_inplace)) + return normal; + + /* Flattened 1D vec4 grid: each invocation transfers up to 4 coalesced vec4s. */ + const uint32_t total_vec4 = (uint32_t)(bytes / 16); + const uint32_t wg_vec4 = (uint32_t)copy->b.info.workgroup_size[0] * 4; + grid->count[0] = DIV_ROUND_UP(total_vec4, wg_vec4); + grid->count[1] = 1; + grid->count[2] = 1; + return copy; +} + static void dispatch_grid_shader(struct hk_cmd_buffer *cmd, struct hk_shader *s, struct agx_grid grid, bool in_threads) @@ -3137,6 +3465,7 @@ dispatch_grid_shader(struct hk_cmd_buffer *cmd, struct hk_shader *s, agx_workgroup(s->b.info.workgroup_size[0], s->b.info.workgroup_size[1], s->b.info.workgroup_size[2]); + bool invocation_stat = false; /* Internal compute work must not contribute to the application's active * pipeline query. This also honours hk_pipeline_stat_addr's !in_meta * contract in debug builds; graphics meta pauses its own counters. */ @@ -3145,6 +3474,7 @@ dispatch_grid_shader(struct hk_cmd_buffer *cmd, struct hk_shader *s, cmd, VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT); if (hk_stat_enabled(stat)) { + invocation_stat = true; perf_debug(cmd, "CS invocation statistic"); uint64_t grid = cmd->state.cs.descriptors.root.cs.group_count_addr; @@ -3153,6 +3483,15 @@ dispatch_grid_shader(struct hk_cmd_buffer *cmd, struct hk_shader *s, } } + struct hk_api_shader *api = cmd->state.cs.shader; + struct hk_shader *selected = s; + if (api && api->identity_copy4 && !in_threads && !invocation_stat) { + selected = hk_select_identity_copy4(cmd, api, s, &grid); + local_size = agx_workgroup(selected->b.info.workgroup_size[0], + selected->b.info.workgroup_size[1], + selected->b.info.workgroup_size[2]); + } + if (!agx_is_indirect(grid) && !in_threads) { grid.count[0] *= local_size.x; grid.count[1] *= local_size.y; @@ -3163,27 +3502,27 @@ dispatch_grid_shader(struct hk_cmd_buffer *cmd, struct hk_shader *s, * launch of a shader whose builtins do not depend on the hardware * workgroup uses its smaller hardware workgroup * (agx_nir_lower_workgroup_split). */ - if (!agx_is_indirect(grid) && !in_threads && s->b.info.launch_size[0]) { - local_size = agx_workgroup(s->b.info.launch_size[0], - s->b.info.launch_size[1], - s->b.info.launch_size[2]); + if (!agx_is_indirect(grid) && !in_threads && selected->b.info.launch_size[0]) { + local_size = agx_workgroup(selected->b.info.launch_size[0], + selected->b.info.launch_size[1], + selected->b.info.launch_size[2]); } else if (!agx_is_indirect(grid) && !in_threads && agx_chip_has_cap(hk_cmd_buffer_device(cmd)->dev.chip, AGX_CAP_COALESCE_PURE_GLOBAL_WORKGROUPS) && - (s->info.agx3_root_reads & HK_ROOT_PROVEN_WG_COALESCE_SAFE) && - !s->b.info.uses_ray_traversal && !s->b.info.local_size && - !s->b.info.scratch_size && - !s->b.info.agx3_spectpr_scratch_size && - !s->b.info.uses_matrix16 && + (selected->info.agx3_root_reads & HK_ROOT_PROVEN_WG_COALESCE_SAFE) && + !selected->b.info.uses_ray_traversal && !selected->b.info.local_size && + !selected->b.info.scratch_size && + !selected->b.info.agx3_spectpr_scratch_size && + !selected->b.info.uses_matrix16 && !desc->root.cs.trace_rays_addr && hk_nir_dispatch_zero_base(desc->root.cs.base_group)) { struct hk_device *dev = hk_cmd_buffer_device(cmd); - const uint32_t eff_gprs = MAX2((uint32_t)s->b.info.nr_gprs, - (uint32_t)s->b.info.nr_preamble_gprs); + const uint32_t eff_gprs = MAX2((uint32_t)selected->b.info.nr_gprs, + (uint32_t)selected->b.info.nr_preamble_gprs); uint32_t max_wg = dev->vk.physical->properties.maxComputeWorkGroupInvocations; - if (s->b.info.stats.threads) - max_wg = MIN2(max_wg, s->b.info.stats.threads); + if (selected->b.info.stats.threads) + max_wg = MIN2(max_wg, selected->b.info.stats.threads); if (eff_gprs > 256u) max_wg = 0; else if (eff_gprs) @@ -3196,7 +3535,7 @@ dispatch_grid_shader(struct hk_cmd_buffer *cmd, struct hk_shader *s, * cap at 256 (>= 256 WGs, and always >= 4 * num_cores so wide GPUs * never lose core saturation); never 1024, which regresses on AGX3. */ const uint32_t target_wg = - (!s->b.info.has_loops && s->b.info.stats.instrs <= 64u && + (!selected->b.info.has_loops && selected->b.info.stats.instrs <= 64u && eff_gprs <= 24u) ? 512u : 256u; @@ -3204,7 +3543,7 @@ dispatch_grid_shader(struct hk_cmd_buffer *cmd, struct hk_shader *s, MAX2(256ull, 4ull * agx_get_num_cores(&dev->dev)); uint16_t coalesced[3]; if (hk_coalesce_workgroup_size_ex( - s->b.info.workgroup_size, grid.count, + selected->b.info.workgroup_size, grid.count, dev->vk.physical->properties.maxComputeWorkGroupSize, max_wg, target_wg, min_wgs, coalesced)) { local_size = agx_workgroup(coalesced[0], coalesced[1], coalesced[2]); @@ -3216,9 +3555,9 @@ dispatch_grid_shader(struct hk_cmd_buffer *cmd, struct hk_shader *s, if (!cs) return; } - hk_dispatch_with_local_size(cmd, cs, s, grid, local_size); - cs->uses_global_atomics |= s->b.info.uses_global_atomics; - cs->pack_loops |= s->b.info.has_loops; + hk_dispatch_with_local_size(cmd, cs, selected, grid, local_size); + cs->uses_global_atomics |= selected->b.info.uses_global_atomics; + cs->pack_loops |= selected->b.info.has_loops; if (agx_is_indirect(grid)) { cs->sib_indirect = true; } else { @@ -3231,7 +3570,7 @@ dispatch_grid_shader(struct hk_cmd_buffer *cmd, struct hk_shader *s, * instruction counts bound a program without loops; pack_loops marks * the others, at most one of which a packet holds. */ uint64_t work; - if (__builtin_mul_overflow(threads, (uint64_t)s->b.info.stats.instrs, + if (__builtin_mul_overflow(threads, (uint64_t)selected->b.info.stats.instrs, &work)) work = UINT64_MAX; cs->pack_threads = threads > UINT64_MAX - cs->pack_threads @@ -3241,11 +3580,11 @@ dispatch_grid_shader(struct hk_cmd_buffer *cmd, struct hk_shader *s, cs->pack_dispatches++; } if (unlikely(hk_cmd_buffer_device(cmd)->frame_anatomy)) { - hk_frame_anatomy_note_fs(cs, s); + hk_frame_anatomy_note_fs(cs, selected); const uint64_t wg = agx_workgroup_threads(local_size); const uint64_t threads = agx_is_indirect(grid) ? 0 : (uint64_t)grid.count[0] * grid.count[1] * grid.count[2]; - hk_frame_anatomy_note_grid(cs, s, threads, wg ? threads / wg : 0, + hk_frame_anatomy_note_grid(cs, selected, threads, wg ? threads / wg : 0, agx_is_indirect(grid)); } cs->stats.calls++; diff --git a/src/asahi/vulkan/hk_descriptor_set.c b/src/asahi/vulkan/hk_descriptor_set.c index c86eff0dcfad..84ef37739d97 100644 --- a/src/asahi/vulkan/hk_descriptor_set.c +++ b/src/asahi/vulkan/hk_descriptor_set.c @@ -560,12 +560,50 @@ get_buffer_address(const VkDescriptorBufferInfo *const info, bool read_only) }; } +static bool +ordinary_storage_binding(const struct hk_descriptor_set *set, uint32_t binding) +{ + if (!set || !set->storage_backings || binding >= set->layout->binding_count) + return false; + + const struct hk_descriptor_set_binding_layout *b = &set->layout->binding[binding]; + return b->type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER && !b->flags && + b->array_size == 1 && b->stride == sizeof(struct hk_buffer_address); +} + +bool +hk_descriptor_set_storage_backing(const struct hk_descriptor_set *set, + uint32_t binding, struct hk_storage_backing *backing) +{ + if (!ordinary_storage_binding(set, binding)) + return false; + if (!set->storage_backings[binding].handle) + return false; + + *backing = set->storage_backings[binding]; + return true; +} + static void write_buffer_desc(struct hk_descriptor_set *set, const VkDescriptorBufferInfo *const info, uint32_t binding, uint32_t elem, bool read_only) { const struct hk_buffer_address desc = get_buffer_address(info, read_only); + if (ordinary_storage_binding(set, binding) && elem == 0) { + VK_FROM_HANDLE(hk_buffer, buffer, info->buffer); + struct hk_storage_backing *backing = &set->storage_backings[binding]; + *backing = (struct hk_storage_backing){0}; + if (!read_only && buffer && buffer->storage_backing_handle && + info->offset <= UINT64_MAX - buffer->storage_backing_offset) { + *backing = (struct hk_storage_backing){ + .address = desc.base_addr, + .offset = buffer->storage_backing_offset + info->offset, + .size = desc.size, + .handle = buffer->storage_backing_handle, + }; + } + } /* A null descriptor in a mutable slot reads as null through any type, so it * must not keep the previous descriptor's heap index past the buffer @@ -591,6 +629,10 @@ write_buffer_desc_array(struct hk_descriptor_set *set, const void *data, size_t data_stride, uint32_t binding, uint32_t first_elem, uint32_t count, bool read_only) { + if (count > 1 && set->storage_backings) { + memset(set->storage_backings, 0, + set->layout->binding_count * sizeof(*set->storage_backings)); + } if (count <= 1 || !set->cpu_cached || set->layout->binding[binding].stride != sizeof(struct hk_buffer_address)) { for (uint32_t i = 0; i < count; ++i) { @@ -726,6 +768,17 @@ hk_copy_descriptor_sets(uint32_t descriptorCopyCount, const struct hk_descriptor_set_binding_layout *dst_binding_layout = &dst->layout->binding[copy->dstBinding]; + if (dst->storage_backings && copy->descriptorCount > 1) { + memset(dst->storage_backings, 0, + dst->layout->binding_count * sizeof(*dst->storage_backings)); + } else if (copy->descriptorCount == 1 && + ordinary_storage_binding(dst, copy->dstBinding) && !copy->dstArrayElement) { + struct hk_storage_backing backing = {0}; + if (!copy->srcArrayElement) + hk_descriptor_set_storage_backing(src, copy->srcBinding, &backing); + dst->storage_backings[copy->dstBinding] = backing; + } + /* Equal strides make the existing per-record copies contiguous. Vulkan * requires source and destination descriptor ranges not to overlap, * including when they belong to the same descriptor set. @@ -991,6 +1044,7 @@ hk_descriptor_set_destroy(struct hk_device *dev, if (set->size > 0) hk_descriptor_pool_free(pool, set->addr, set->size); vk_descriptor_set_layout_unref(&dev->vk, &set->layout->vk); + free(set->storage_backings); vk_object_free(&dev->vk, NULL, set); } @@ -1211,6 +1265,18 @@ hk_descriptor_set_create(struct hk_device *dev, struct hk_descriptor_pool *pool, vk_descriptor_set_layout_ref(&layout->vk); set->layout = layout; + if (layout->binding_count && !layout->vk.flags && + agx_chip_native_or_m5(dev->dev.chip)) { + for (uint32_t b = 0; b < layout->binding_count; ++b) { + const struct hk_descriptor_set_binding_layout *binding = &layout->binding[b]; + if (binding->type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER && !binding->flags && + binding->array_size == 1) { + set->storage_backings = calloc(layout->binding_count, sizeof(*set->storage_backings)); + break; + } + } + } + for (uint32_t b = 0; b < layout->binding_count; b++) { if (layout->binding[b].type != VK_DESCRIPTOR_TYPE_SAMPLER && layout->binding[b].type != VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER) diff --git a/src/asahi/vulkan/hk_descriptor_set.h b/src/asahi/vulkan/hk_descriptor_set.h index d090dff6353e..98e1cc85deef 100644 --- a/src/asahi/vulkan/hk_descriptor_set.h +++ b/src/asahi/vulkan/hk_descriptor_set.h @@ -119,6 +119,13 @@ struct hk_descriptor_pool { VK_DEFINE_NONDISP_HANDLE_CASTS(hk_descriptor_pool, base, VkDescriptorPool, VK_OBJECT_TYPE_DESCRIPTOR_POOL) +struct hk_storage_backing { + uint64_t address; + uint64_t offset; + uint32_t size; + uint32_t handle; +}; + struct hk_descriptor_set { struct vk_object_base base; @@ -132,9 +139,15 @@ struct hk_descriptor_set { /* mapped_ptr is in a CPU-cached pool BO (hk_descriptor_pool::cpu_cached). */ bool cpu_cached; + /* Optional CPU provenance, for ordinary single-element storage bindings. */ + struct hk_storage_backing *storage_backings; + struct hk_buffer_address dynamic_buffers[]; }; +bool hk_descriptor_set_storage_backing(const struct hk_descriptor_set *set, + uint32_t binding, struct hk_storage_backing *backing); + VK_DEFINE_NONDISP_HANDLE_CASTS(hk_descriptor_set, base, VkDescriptorSet, VK_OBJECT_TYPE_DESCRIPTOR_SET) diff --git a/src/asahi/vulkan/hk_identity_copy4.h b/src/asahi/vulkan/hk_identity_copy4.h new file mode 100644 index 000000000000..2481f0c11a21 --- /dev/null +++ b/src/asahi/vulkan/hk_identity_copy4.h @@ -0,0 +1,57 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef HK_IDENTITY_COPY4_H +#define HK_IDENTITY_COPY4_H + +#include +#include + +struct nir_shader; + +#define HK_COMPUTE_OPT_PUSH_BYTES 64 + +static inline bool +hk_identity_copy4_supported_local(const uint16_t local[3]) +{ + return local[0] > 0 && local[1] > 0 && local[2] == 1 && + (uint32_t)local[0] * local[1] <= 1024; +} + +enum hk_identity_copy4_kind { + HK_IDENTITY_COPY4_IM2COL_1X1 = 0, + HK_IDENTITY_COPY4_LINEAR_COPY = 1, + HK_IDENTITY_COPY4_LINEAR_OFFSET = 2, + HK_IDENTITY_COPY4_LINEAR_FADD = 3, + HK_IDENTITY_COPY4_PAD4 = 4, +}; + +struct hk_identity_copy4 { + uint8_t kind; + uint8_t src_count; + uint8_t src_set, src1_set, dst_set, pad_set; + uint16_t src_binding, src1_binding, dst_binding, pad_binding; + uint16_t border_width_offset, border_height_offset; + uint16_t input_width_offset, input_height_offset, kernel_width_offset; + uint16_t patches_width_offset, patches_height_offset; + uint16_t stride_width_offset, stride_height_offset, channels_offset; + uint16_t count_offset, src_offset_offset, dst_offset_offset, push_bytes; + uint16_t in_shape_off[4]; + uint16_t out_shape_off[4]; + uint32_t pad_idx[4]; + uint16_t local[3]; + bool im2col_vec4_ok; +}; + +/* Pre-descriptor NIR after explicit push IO. The returned alternate requires + * the direct, zero-base, packed-vec4 dispatch and storage certificate external + * to this matcher. The original and unsuccessful metadata remain unchanged. + */ +struct nir_shader *hk_nir_copy_identity4(const struct nir_shader *orig, + struct hk_identity_copy4 *info); + +/* Packed vec4 alternate for certified 2D im2col shaders (both unit-stride and + * non-unit-stride paths) when channels, kernel_width, input_width, and + * patches_width are multiples of 4. + */ +struct nir_shader *hk_nir_im2col_vec4(const struct nir_shader *orig); + +#endif diff --git a/src/asahi/vulkan/hk_nir_copy_identity4.c b/src/asahi/vulkan/hk_nir_copy_identity4.c new file mode 100644 index 000000000000..c77eb353b307 --- /dev/null +++ b/src/asahi/vulkan/hk_nir_copy_identity4.c @@ -0,0 +1,2127 @@ +/* SPDX-License-Identifier: MIT */ +#include "hk_identity_copy4.h" +#include "compiler/nir/nir_builder.h" + +static nir_scalar +scalar(nir_def *def) +{ + return nir_get_scalar(def, 0); +} + +static bool +imm(nir_scalar s, uint32_t n) +{ + s = nir_scalar_chase_movs(s); + return s.def && nir_scalar_is_const(s) && nir_scalar_as_uint(s) == n; +} + +static nir_alu_instr * +alu(nir_scalar s, nir_op op) +{ + s = nir_scalar_chase_movs(s); + if (!s.def) + return NULL; + nir_instr *instr = nir_def_instr(s.def); + if (instr->type != nir_instr_type_alu) + return NULL; + nir_alu_instr *a = nir_instr_as_alu(instr); + return a->op == op ? a : NULL; +} + +static nir_scalar +arg(nir_scalar s, unsigned i) +{ + s = nir_scalar_chase_movs(s); + return nir_scalar_chase_alu_src(s, i); +} + +static bool +same(nir_scalar a, nir_scalar b) +{ + a = nir_scalar_chase_movs(a); + b = nir_scalar_chase_movs(b); + return a.def && b.def && nir_scalar_equal(a, b); +} + +static nir_scalar +strip_zero_add(nir_scalar s) +{ + s = nir_scalar_chase_movs(s); + for (unsigned i = 0; i < 3 && alu(s, nir_op_iadd); ++i) { + if (imm(arg(s, 0), 0)) + s = nir_scalar_chase_movs(arg(s, 1)); + else if (imm(arg(s, 1), 0)) + s = nir_scalar_chase_movs(arg(s, 0)); + else + break; + } + return s; +} + +static nir_intrinsic_instr * +intr(nir_def *def, nir_intrinsic_op op) +{ + if (!def || nir_def_instr(def)->type != nir_instr_type_intrinsic) + return NULL; + nir_intrinsic_instr *i = nir_instr_as_intrinsic(nir_def_instr(def)); + return i->intrinsic == op ? i : NULL; +} + +static nir_phi_instr * +phi(nir_scalar s) +{ + s = nir_scalar_chase_movs(s); + return s.def && !s.comp && s.def->num_components == 1 && + nir_def_instr(s.def)->type == nir_instr_type_phi ? + nir_instr_as_phi(nir_def_instr(s.def)) : NULL; +} + +static nir_scalar +phi_in(nir_phi_instr *p, nir_block *block) +{ + nir_phi_src *edge = p ? nir_phi_get_src_from_block(p, block) : NULL; + return edge ? scalar(edge->src.ssa) : (nir_scalar){0}; +} + +static bool +const_arg(nir_scalar s, nir_op op, unsigned pos, uint32_t bits) +{ + return alu(s, op) && imm(arg(s, pos), bits); +} + +static bool +unary(nir_scalar s, nir_op op, nir_scalar v) +{ + return alu(s, op) && same(arg(s, 0), v); +} + +/* Match un-lowered integer division (idiv/udiv). Non-internal Vulkan compute + * shaders on native AGX3 defer nir_lower_idiv until hk_lower_nir(), so + * matchers inspect exact NIR division semantics rather than lowered sequences. + */ +static bool +match_div(nir_scalar div, nir_scalar *numerator, nir_scalar *denominator) +{ + div = nir_scalar_chase_movs(div); + if (alu(div, nir_op_idiv) || alu(div, nir_op_udiv)) { + *numerator = arg(div, 0); + *denominator = arg(div, 1); + return true; + } + return false; +} + +static bool +match_mul_pair(nir_scalar s, nir_scalar a, nir_scalar b) +{ + if (!alu(s, nir_op_imul)) + return false; + nir_scalar x = arg(s, 0), y = arg(s, 1); + return (same(x, a) && same(y, b)) || (same(x, b) && same(y, a)); +} + +static bool +match_div_mul(nir_scalar prod, nir_scalar numerator, nir_scalar *denominator) +{ + if (!alu(prod, nir_op_imul)) + return false; + nir_scalar a = arg(prod, 0), b = arg(prod, 1); + nir_scalar qn, qd; + if (match_div(a, &qn, &qd) && same(qn, numerator) && same(qd, b)) { + *denominator = qd; + return true; + } + if (match_div(b, &qn, &qd) && same(qn, numerator) && same(qd, a)) { + *denominator = qd; + return true; + } + return false; +} + +static bool +match_mod(nir_scalar rem, nir_scalar numerator, nir_scalar *denominator) +{ + rem = nir_scalar_chase_movs(rem); + if (alu(rem, nir_op_irem) || alu(rem, nir_op_imod) || alu(rem, nir_op_umod)) { + if (!same(arg(rem, 0), numerator)) + return false; + *denominator = arg(rem, 1); + return true; + } + if (alu(rem, nir_op_isub)) { + return same(arg(rem, 0), numerator) && + match_div_mul(arg(rem, 1), numerator, denominator); + } + if (alu(rem, nir_op_iadd)) { + nir_scalar a = arg(rem, 0), b = arg(rem, 1); + if (same(a, numerator) && alu(b, nir_op_ineg) && + match_div_mul(arg(b, 0), numerator, denominator)) + return true; + if (same(b, numerator) && alu(a, nir_op_ineg) && + match_div_mul(arg(a, 0), numerator, denominator)) + return true; + } + return false; +} + +static bool +match_push_any(nir_scalar s, uint16_t *off_out, uint16_t *range_out) +{ + s = nir_scalar_chase_movs(s); + nir_intrinsic_instr *op = intr(s.def, nir_intrinsic_load_push_constant); + if (!op || s.comp || op->def.bit_size != 32 || op->def.num_components != 1 || + nir_intrinsic_access(op) != 0) + return false; + nir_scalar off = scalar(op->src[0].ssa); + if (!nir_scalar_is_const(off)) + return false; + uint64_t byte_off = nir_intrinsic_base(op) + nir_scalar_as_uint(off); + if ((byte_off & 3) || byte_off + 4 > HK_COMPUTE_OPT_PUSH_BYTES) + return false; + *off_out = (uint16_t)byte_off; + if (range_out) { + uint32_t r = MAX2(nir_intrinsic_base(op) + nir_intrinsic_range(op), + (uint32_t)(byte_off + 4)); + if (r > HK_COMPUTE_OPT_PUSH_BYTES) + r = (uint32_t)(byte_off + 4); + *range_out = (uint16_t)r; + } + return true; +} + +static bool +match_push_eq(nir_scalar s, uint16_t expected_off) +{ + uint16_t off = 0; + return match_push_any(s, &off, NULL) && off == expected_off; +} + +static bool +match_mul_push_eq(nir_scalar s, uint16_t expected_off, nir_scalar *other_out) +{ + s = nir_scalar_chase_movs(s); + if (!alu(s, nir_op_imul)) + return false; + nir_scalar a = arg(s, 0), b = arg(s, 1); + if (match_push_eq(b, expected_off)) { + *other_out = a; + return true; + } + if (match_push_eq(a, expected_off)) { + *other_out = b; + return true; + } + return false; +} + +enum im2col_param_id { + IM2COL_BORDER_WIDTH, + IM2COL_BORDER_HEIGHT, + IM2COL_INPUT_WIDTH, + IM2COL_INPUT_HEIGHT, + IM2COL_KERNEL_WIDTH, + IM2COL_PATCHES_WIDTH, + IM2COL_PATCHES_HEIGHT, + IM2COL_STRIDE_WIDTH, + IM2COL_STRIDE_HEIGHT, + IM2COL_CHANNELS, + IM2COL_PARAM_COUNT, +}; + +struct im2col_params { + uint16_t off[IM2COL_PARAM_COUNT]; + bool bound[IM2COL_PARAM_COUNT]; + uint16_t push_bytes; +}; + +static bool +bind_im2col_param(struct im2col_params *p, enum im2col_param_id id, nir_scalar s) +{ + uint16_t off = 0, rng = 0; + if (!match_push_any(s, &off, &rng)) + return false; + if (p->bound[id]) { + if (p->off[id] != off) + return false; + } else { + p->bound[id] = true; + p->off[id] = off; + } + p->push_bytes = MAX2(p->push_bytes, MAX2(rng, (uint16_t)(off + 4))); + return true; +} + +static bool +bind_im2col_mul(struct im2col_params *p, enum im2col_param_id id, + nir_scalar s, nir_scalar *other_out) +{ + if (!alu(s, nir_op_imul)) + return false; + nir_scalar a = arg(s, 0), b = arg(s, 1); + if (p->bound[id]) { + if (match_push_eq(b, p->off[id])) { + *other_out = a; + return true; + } + if (match_push_eq(a, p->off[id])) { + *other_out = b; + return true; + } + return false; + } + if (bind_im2col_param(p, id, b)) { + *other_out = a; + return true; + } + if (bind_im2col_param(p, id, a)) { + *other_out = b; + return true; + } + return false; +} + +static bool +coord(nir_scalar s, unsigned axis, unsigned local_size) +{ + s = strip_zero_add(s); + if (s.comp == axis && intr(s.def, nir_intrinsic_load_global_invocation_id)) + return true; + if (!alu(s, nir_op_iadd)) + return false; + + nir_scalar g = arg(s, 0), base = arg(s, 1); + if (g.comp == axis && intr(g.def, nir_intrinsic_load_global_invocation_id) && + const_arg(base, nir_op_imul, 1, local_size) && arg(base, 0).comp == axis && + intr(arg(base, 0).def, nir_intrinsic_load_base_workgroup_id)) + return true; + if (base.comp == axis && intr(base.def, nir_intrinsic_load_global_invocation_id) && + const_arg(g, nir_op_imul, 1, local_size) && arg(g, 0).comp == axis && + intr(arg(g, 0).def, nir_intrinsic_load_base_workgroup_id)) + return true; + return false; +} + +static nir_if * +as_if(nir_cf_node *node) +{ + return node && node->type == nir_cf_node_if ? nir_cf_node_as_if(node) : NULL; +} + +static nir_if * +value_branch(nir_scalar s) +{ + nir_phi_instr *p = phi(s); + if (!p || !p->instr.block || exec_list_length(&p->srcs) != 2) + return NULL; + return as_if(nir_cf_node_prev(&p->instr.block->cf_node)); +} + +/* A meet value selects exactly the branch's last THEN or ELSE block. + * Every matching branch is also verified to be acyclic without jumps. + */ +static bool +branch_value(nir_scalar s, nir_scalar *cond, nir_scalar *yes, nir_scalar *no) +{ + nir_if *branch = value_branch(s); + if (!branch) + return false; + + nir_phi_instr *p = phi(s); + *yes = phi_in(p, nir_if_last_then_block(branch)); + *no = phi_in(p, nir_if_last_else_block(branch)); + *cond = scalar(branch->condition.ssa); + return yes->def && no->def && cond->def; +} + +static bool +match_short_or(nir_scalar s, nir_scalar *lhs, nir_scalar *rhs) +{ + if (alu(s, nir_op_ior)) { + *lhs = arg(s, 0); + *rhs = arg(s, 1); + return true; + } + nir_scalar cond, yes, no; + if (branch_value(s, &cond, &yes, &no) && unary(cond, nir_op_inot, no)) { + *lhs = no; + *rhs = yes; + return true; + } + return false; +} + +static bool +inside_arm(nir_cf_node *node, nir_if *branch, bool then) +{ + if (!branch) + return false; + while (node->parent && node->parent != &branch->cf_node) + node = node->parent; + if (!node->parent) + return false; + + struct exec_list *list = then ? &branch->then_list : &branch->else_list; + foreach_list_typed(nir_cf_node, member, node, list) { + if (member == node) + return true; + } + return false; +} + +static bool +match_eq_one_push(nir_scalar s, uint16_t *off_out, uint16_t *rng_out) +{ + if (!alu(s, nir_op_ieq)) + return false; + nir_scalar a = arg(s, 0), b = arg(s, 1); + if (imm(b, 1) && match_push_any(a, off_out, rng_out)) + return true; + if (imm(a, 1) && match_push_any(b, off_out, rng_out)) + return true; + return false; +} + +static bool +match_unit_strides(nir_scalar value, uint16_t *s0_out, uint16_t *s1_out, + uint16_t *pb) +{ + nir_scalar a, b; + if (alu(value, nir_op_iand)) { + a = arg(value, 0); + b = arg(value, 1); + } else { + nir_scalar test, w, h; + if (!branch_value(value, &test, &w, &h) || !same(test, h)) + return false; + a = h; + b = w; + } + uint16_t r0 = 0, r1 = 0; + if (!match_eq_one_push(a, s0_out, &r0) || !match_eq_one_push(b, s1_out, &r1)) + return false; + if (*s0_out == *s1_out) + return false; + *pb = MAX2(*pb, MAX2(r0, r1)); + return true; +} + +static bool +check_unit_stride_pair(const struct im2col_params *p, uint16_t s0, uint16_t s1) +{ + if (!p->bound[IM2COL_STRIDE_WIDTH] || !p->bound[IM2COL_STRIDE_HEIGHT]) + return false; + const uint16_t sw = p->off[IM2COL_STRIDE_WIDTH]; + const uint16_t sh = p->off[IM2COL_STRIDE_HEIGHT]; + return (s0 == sw && s1 == sh) || (s0 == sh && s1 == sw); +} + +static bool +padding_x(struct im2col_params *p, nir_scalar s) +{ + if (!p->bound[IM2COL_CHANNELS] || !alu(s, nir_op_imul)) + return false; + nir_scalar a = arg(s, 0), b = arg(s, 1); + if (match_push_eq(b, p->off[IM2COL_CHANNELS])) + return bind_im2col_param(p, IM2COL_BORDER_WIDTH, a); + if (match_push_eq(a, p->off[IM2COL_CHANNELS])) + return bind_im2col_param(p, IM2COL_BORDER_WIDTH, b); + return false; +} + +static bool +bordered_width(struct im2col_params *p, nir_scalar s) +{ + if (!alu(s, nir_op_iadd)) + return false; + nir_scalar a = arg(s, 0), b = arg(s, 1); + if (padding_x(p, b) && bind_im2col_param(p, IM2COL_INPUT_WIDTH, a)) + return true; + if (padding_x(p, a) && bind_im2col_param(p, IM2COL_INPUT_WIDTH, b)) + return true; + return false; +} + +static bool +match_sub_expr(nir_scalar s, nir_scalar lhs, nir_scalar *rhs_out) +{ + if (alu(s, nir_op_isub) && same(arg(s, 0), lhs)) { + *rhs_out = arg(s, 1); + return true; + } + if (alu(s, nir_op_iadd)) { + nir_scalar a = arg(s, 0), b = arg(s, 1); + if (same(a, lhs) && alu(b, nir_op_ineg)) { + *rhs_out = arg(b, 0); + return true; + } + if (same(b, lhs) && alu(a, nir_op_ineg)) { + *rhs_out = arg(a, 0); + return true; + } + } + return false; +} + +/* The exact signed output-column count becomes IW/C when pads are zero, + * both strides are one, and KW equals C. + */ +static bool +columns(struct im2col_params *p, nir_scalar s) +{ + nir_scalar body; + if (const_arg(s, nir_op_iadd, 1, 1)) + body = arg(s, 0); + else if (const_arg(s, nir_op_iadd, 0, 1)) + body = arg(s, 1); + else + return false; + + nir_scalar diff, stride, iw, ic, kw, kc; + if (!match_div(body, &diff, &stride) || + !bind_im2col_param(p, IM2COL_STRIDE_WIDTH, stride)) + return false; + + nir_scalar term0, term1; + if (alu(diff, nir_op_isub)) { + term0 = arg(diff, 0); + term1 = arg(diff, 1); + } else if (alu(diff, nir_op_iadd) && alu(arg(diff, 1), nir_op_ineg)) { + term0 = arg(diff, 0); + term1 = arg(arg(diff, 1), 0); + } else if (alu(diff, nir_op_iadd) && alu(arg(diff, 0), nir_op_ineg)) { + term0 = arg(diff, 1); + term1 = arg(arg(diff, 0), 0); + } else { + return false; + } + + if (!match_div(term0, &iw, &ic) || + !bind_im2col_param(p, IM2COL_CHANNELS, ic) || + !match_div(term1, &kw, &kc) || + !bind_im2col_param(p, IM2COL_KERNEL_WIDTH, kw) || + !bind_im2col_param(p, IM2COL_CHANNELS, kc)) + return false; + + /* Match `iw_pad = is_unit ? (iw + 2*pad_x) : (iw + pad_x)` across + * phi/bcsel and algebraic hoisting of common addends (`one_pad`, `pad_x`, + * or `iw`). */ + if (alu(iw, nir_op_iadd)) { + nir_scalar a = arg(iw, 0), b = arg(iw, 1); + nir_scalar base = {0}, sel = {0}; + if (alu(b, nir_op_bcsel)) { + base = a; + sel = b; + } else if (alu(a, nir_op_bcsel)) { + base = b; + sel = a; + } + if (sel.def) { + uint16_t s0 = 0, s1 = 0; + nir_scalar is_unit = arg(sel, 0), tval = arg(sel, 1), fval = arg(sel, 2); + if (match_unit_strides(is_unit, &s0, &s1, &p->push_bytes) && + check_unit_stride_pair(p, s0, s1)) { + /* Form A: one_pad + bcsel(is_unit, pad_x, 0) */ + if (bordered_width(p, base) && padding_x(p, tval) && imm(fval, 0)) + return true; + /* Form B: pad_x + bcsel(is_unit, one_pad, iw) */ + if (padding_x(p, base) && bordered_width(p, tval) && + match_push_eq(fval, p->off[IM2COL_INPUT_WIDTH])) + return true; + /* Form C: iw + bcsel(is_unit, 2*pad_x, pad_x) */ + if (match_push_eq(base, p->off[IM2COL_INPUT_WIDTH]) && padding_x(p, fval)) { + if (const_arg(tval, nir_op_ishl, 1, 1) && padding_x(p, arg(tval, 0))) + return true; + if (alu(tval, nir_op_imul)) { + nir_scalar m0 = arg(tval, 0), m1 = arg(tval, 1); + if ((imm(m0, 2) && padding_x(p, m1)) || + (imm(m1, 2) && padding_x(p, m0))) + return true; + } + } + } + } + } + + nir_scalar is_unit, both_pads, one_pad; + uint16_t s0 = 0, s1 = 0; + if (alu(iw, nir_op_bcsel)) { + is_unit = arg(iw, 0); + both_pads = arg(iw, 1); + one_pad = arg(iw, 2); + } else if (!branch_value(iw, &is_unit, &both_pads, &one_pad)) { + return false; + } + if (!match_unit_strides(is_unit, &s0, &s1, &p->push_bytes) || + !check_unit_stride_pair(p, s0, s1) || + !bordered_width(p, one_pad) || + !alu(both_pads, nir_op_iadd)) + return false; + + nir_scalar ba = arg(both_pads, 0), bb = arg(both_pads, 1); + if ((same(ba, one_pad) && padding_x(p, bb)) || + (same(bb, one_pad) && padding_x(p, ba))) + return true; + + /* nir_opt_algebraic may fold (iw + pad_x) + pad_x into iw + (pad_x << 1) + * or iw + (pad_x * 2) or iw + ((bw << 1) * ch). */ + nir_scalar two_pad = {0}; + if (match_push_eq(ba, p->off[IM2COL_INPUT_WIDTH])) + two_pad = bb; + else if (match_push_eq(bb, p->off[IM2COL_INPUT_WIDTH])) + two_pad = ba; + else + return false; + + if (const_arg(two_pad, nir_op_ishl, 1, 1) && padding_x(p, arg(two_pad, 0))) + return true; + if (alu(two_pad, nir_op_imul)) { + nir_scalar m0 = arg(two_pad, 0), m1 = arg(two_pad, 1); + if ((imm(m0, 2) && padding_x(p, m1)) || (imm(m1, 2) && padding_x(p, m0))) + return true; + if (const_arg(m0, nir_op_ishl, 1, 1) && + ((match_push_eq(arg(m0, 0), p->off[IM2COL_BORDER_WIDTH]) && + match_push_eq(m1, p->off[IM2COL_CHANNELS])) || + (match_push_eq(arg(m0, 0), p->off[IM2COL_CHANNELS]) && + match_push_eq(m1, p->off[IM2COL_BORDER_WIDTH])))) + return true; + if (const_arg(m1, nir_op_ishl, 1, 1) && + ((match_push_eq(arg(m1, 0), p->off[IM2COL_BORDER_WIDTH]) && + match_push_eq(m0, p->off[IM2COL_CHANNELS])) || + (match_push_eq(arg(m1, 0), p->off[IM2COL_CHANNELS]) && + match_push_eq(m0, p->off[IM2COL_BORDER_WIDTH])))) + return true; + } + return false; +} + +static bool +original_coords(struct im2col_params *p, nir_scalar tap, nir_scalar row, + nir_scalar x, nir_scalar y, nir_scalar *cols_out) +{ + if (!alu(y, nir_op_iadd) || !alu(x, nir_op_iadd)) + return false; + + /* y = (row / cols) * stride_height + (tap / kernel_width) */ + nir_scalar ya = arg(y, 0), yb = arg(y, 1); + nir_scalar y_row_mul = ya, y_tap_div = yb; + nir_scalar tap_n, tap_d; + if (!match_div(y_tap_div, &tap_n, &tap_d) || !same(tap_n, tap)) { + y_row_mul = yb; + y_tap_div = ya; + if (!match_div(y_tap_div, &tap_n, &tap_d) || !same(tap_n, tap)) + return false; + } + if (!bind_im2col_param(p, IM2COL_KERNEL_WIDTH, tap_d)) + return false; + + nir_scalar row_div; + if (!bind_im2col_mul(p, IM2COL_STRIDE_HEIGHT, y_row_mul, &row_div)) + return false; + nir_scalar row_n, row_divisor; + if (!match_div(row_div, &row_n, &row_divisor) || !same(row_n, row)) + return false; + + /* x = ((row % cols) * stride_width) * channels + (tap % kernel_width) */ + nir_scalar xa = arg(x, 0), xb = arg(x, 1); + nir_scalar x_row_term = xa, x_tap_mod = xb; + nir_scalar mod_d; + if (!match_mod(x_tap_mod, tap, &mod_d) || + !bind_im2col_param(p, IM2COL_KERNEL_WIDTH, mod_d)) { + x_row_term = xb; + x_tap_mod = xa; + if (!match_mod(x_tap_mod, tap, &mod_d) || + !bind_im2col_param(p, IM2COL_KERNEL_WIDTH, mod_d)) + return false; + } + + /* Accept either ((row % cols) * sw) * ch or (row % cols) * (sw * ch). */ + nir_scalar row_mod = {0}, sw_s = {0}, ch_s = {0}; + if (!alu(x_row_term, nir_op_imul)) + return false; + nir_scalar m0 = arg(x_row_term, 0), m1 = arg(x_row_term, 1); + if (alu(m0, nir_op_imul)) { + ch_s = m1; + nir_scalar i0 = arg(m0, 0), i1 = arg(m0, 1); + if (match_mod(i0, row, &mod_d) && same(mod_d, row_divisor)) { + row_mod = i0; + sw_s = i1; + } else if (match_mod(i1, row, &mod_d) && same(mod_d, row_divisor)) { + row_mod = i1; + sw_s = i0; + } else { + return false; + } + } else if (alu(m1, nir_op_imul)) { + ch_s = m0; + nir_scalar i0 = arg(m1, 0), i1 = arg(m1, 1); + if (match_mod(i0, row, &mod_d) && same(mod_d, row_divisor)) { + row_mod = i0; + sw_s = i1; + } else if (match_mod(i1, row, &mod_d) && same(mod_d, row_divisor)) { + row_mod = i1; + sw_s = i0; + } else { + return false; + } + } else { + return false; + } + (void)row_mod; + + if (!bind_im2col_param(p, IM2COL_STRIDE_WIDTH, sw_s) || + !bind_im2col_param(p, IM2COL_CHANNELS, ch_s)) + return false; + + *cols_out = row_divisor; + return true; +} + +struct copy_buffer { + uint8_t set; + uint8_t desc_comps; + uint16_t binding; + unsigned resource; +}; + +static bool +match_buffer_typed(nir_intrinsic_instr *op, struct copy_buffer *out, + nir_scalar *index, bool allow_int) +{ + nir_def *ptr = op->src[0].ssa; + if (nir_def_instr(ptr)->type != nir_instr_type_deref) + return false; + + nir_deref_instr *element = nir_instr_as_deref(nir_def_instr(ptr)); + nir_deref_instr *array = nir_deref_instr_parent(element); + nir_deref_instr *root = array ? nir_deref_instr_parent(array) : NULL; + if (element->deref_type != nir_deref_type_array || + element->modes != nir_var_mem_ssbo || !element->arr.in_bounds || + !(element->type == glsl_float_type() || + (allow_int && (element->type == glsl_int_type() || + element->type == glsl_uint_type()))) || + !array || array->deref_type != nir_deref_type_struct || + array->modes != nir_var_mem_ssbo || array->strct.index != 0 || + !glsl_type_is_unsized_array(array->type) || + glsl_get_explicit_stride(array->type) != 4 || + !root || root->deref_type != nir_deref_type_cast || + root->modes != nir_var_mem_ssbo || root->cast.ptr_stride != 0 || + root->cast.align_offset != 0 || !glsl_type_is_struct_or_ifc(root->type) || + glsl_get_length(root->type) != 1 || glsl_get_struct_field_offset(root->type, 0) != 0) + return false; + + nir_intrinsic_instr *load = intr(root->parent.ssa, nir_intrinsic_load_vulkan_descriptor); + nir_intrinsic_instr *resource = load ? + intr(load->src[0].ssa, nir_intrinsic_vulkan_resource_index) : NULL; + const unsigned comps = root->def.num_components; + if (comps < 3 || comps > 5 || root->def.bit_size != 32 || + root->cast.align_mul != 4 || + !resource || resource->def.num_components != comps || + load->def.num_components != comps || resource->def.bit_size != 32 || + load->def.bit_size != 32 || !imm(scalar(resource->src[0].ssa), 0) || + nir_intrinsic_desc_type(resource) != nir_descriptor_type_storage_buffer || + nir_intrinsic_desc_type(load) != nir_descriptor_type_storage_buffer || + nir_intrinsic_desc_set(resource) > UINT8_MAX || + nir_intrinsic_binding(resource) > UINT16_MAX) + return false; + + const unsigned type = nir_intrinsic_resource_type(resource); + if (type != nir_resource_type_read_only_storage_buffer && + type != nir_resource_type_read_write_storage_buffer) + return false; + + nir_def *offset = element->arr.index.ssa; + if (offset->bit_size != 32 || offset->num_components != 1) + return false; + + *index = nir_scalar_resolved(offset, 0); + *out = (struct copy_buffer) { + .set = nir_intrinsic_desc_set(resource), + .desc_comps = comps, + .binding = nir_intrinsic_binding(resource), + .resource = type, + }; + return true; +} + +static bool +match_buffer(nir_intrinsic_instr *op, struct copy_buffer *out, nir_scalar *index) +{ + return match_buffer_typed(op, out, index, false); +} + +static bool +same_binding(struct copy_buffer a, struct copy_buffer b) +{ + return a.set == b.set && a.binding == b.binding; +} + +static bool +zero_then(nir_scalar val, nir_scalar *cond, nir_scalar *next) +{ + nir_scalar zero; + return branch_value(val, cond, &zero, next) && imm(zero, 0); +} + +static bool +out_of_bounds(struct im2col_params *p, nir_scalar test, + nir_scalar tap, nir_scalar row) +{ + nir_scalar oob_x, oob_y; + if (!match_short_or(test, &oob_x, &oob_y)) + return false; + if (alu(oob_x, nir_op_ige) && alu(oob_y, nir_op_ige)) { + if (same(arg(oob_x, 0), tap) && same(arg(oob_y, 0), row)) { + return bind_im2col_param(p, IM2COL_PATCHES_WIDTH, arg(oob_x, 1)) && + bind_im2col_param(p, IM2COL_PATCHES_HEIGHT, arg(oob_y, 1)); + } + if (same(arg(oob_x, 0), row) && same(arg(oob_y, 0), tap)) { + return bind_im2col_param(p, IM2COL_PATCHES_HEIGHT, arg(oob_x, 1)) && + bind_im2col_param(p, IM2COL_PATCHES_WIDTH, arg(oob_y, 1)); + } + } + return false; +} + +static bool +safe_unit_read(struct im2col_params *p, nir_scalar value, nir_scalar tap, + nir_scalar row, nir_scalar index, nir_intrinsic_instr *copy) +{ + nir_scalar cutoff[4]; + for (unsigned i = 0; i < ARRAY_SIZE(cutoff); ++i) { + if (!inside_arm(©->instr.block->cf_node, value_branch(value), false) || + !zero_then(value, &cutoff[i], &value)) + return false; + } + nir_scalar xlo = cutoff[0], ylo = cutoff[1], xhi = cutoff[2], yhi = cutoff[3]; + if (value.def != ©->def || + !alu(xlo, nir_op_ilt) || !alu(ylo, nir_op_ilt)) + return false; + + nir_scalar x = arg(xlo, 0), y = arg(ylo, 0); + nir_scalar cols_s = {0}; + /* Bind STRIDE_WIDTH, STRIDE_HEIGHT, CHANNELS, KERNEL_WIDTH first so + * padding_x and bordered_width unambiguously identify BORDER_WIDTH and + * INPUT_WIDTH. + */ + if (!original_coords(p, tap, row, x, y, &cols_s)) + return false; + + if (!padding_x(p, arg(xlo, 1)) || + !bind_im2col_param(p, IM2COL_BORDER_HEIGHT, arg(ylo, 1))) + return false; + + if (!alu(xhi, nir_op_ige) || !same(arg(xhi, 0), x) || + !bordered_width(p, arg(xhi, 1))) + return false; + + if (!alu(yhi, nir_op_ige) || !same(arg(yhi, 0), y) || + !alu(arg(yhi, 1), nir_op_iadd)) + return false; + nir_scalar yhi_a = arg(arg(yhi, 1), 0), yhi_b = arg(arg(yhi, 1), 1); + if (match_push_eq(yhi_b, p->off[IM2COL_BORDER_HEIGHT])) { + if (!bind_im2col_param(p, IM2COL_INPUT_HEIGHT, yhi_a)) + return false; + } else if (match_push_eq(yhi_a, p->off[IM2COL_BORDER_HEIGHT])) { + if (!bind_im2col_param(p, IM2COL_INPUT_HEIGHT, yhi_b)) + return false; + } else { + return false; + } + + if (!columns(p, cols_s)) + return false; + + /* index = (y - BORDER_HEIGHT) * INPUT_WIDTH + (x - padding_x) */ + if (!alu(index, nir_op_iadd)) + return false; + nir_scalar ia = arg(index, 0), ib = arg(index, 1); + nir_scalar src_y = {0}, src_x = {0}; + if (bind_im2col_mul(p, IM2COL_INPUT_WIDTH, ia, &src_y)) { + src_x = ib; + } else if (bind_im2col_mul(p, IM2COL_INPUT_WIDTH, ib, &src_y)) { + src_x = ia; + } else { + return false; + } + + nir_scalar bh_sub = {0}, px_sub = {0}; + return match_sub_expr(src_y, y, &bh_sub) && + match_push_eq(bh_sub, p->off[IM2COL_BORDER_HEIGHT]) && + match_sub_expr(src_x, x, &px_sub) && + padding_x(p, px_sub); +} + +static bool +acyclic(const struct exec_list *list, unsigned depth) +{ + if (!depth) + return false; + + foreach_list_typed(nir_cf_node, cf, node, list) { + if (cf->type == nir_cf_node_block) + continue; + nir_if *branch = as_if(cf); + if (!branch || !acyclic(&branch->then_list, depth - 1) || + !acyclic(&branch->else_list, depth - 1)) + return false; + } + return true; +} + +struct access_set { + nir_intrinsic_instr *store; + nir_intrinsic_instr *load[2]; +}; + +static bool +collect_accesses(nir_function_impl *impl, struct access_set *accesses) +{ + unsigned count = 0; + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + switch (instr->type) { + case nir_instr_type_deref: + case nir_instr_type_phi: + case nir_instr_type_load_const: + case nir_instr_type_alu: + continue; + case nir_instr_type_intrinsic: + break; + default: + return false; + } + + nir_intrinsic_instr *op = nir_instr_as_intrinsic(instr); + switch (op->intrinsic) { + case nir_intrinsic_load_global_invocation_id: + case nir_intrinsic_load_base_workgroup_id: + case nir_intrinsic_load_push_constant: + case nir_intrinsic_vulkan_resource_index: + case nir_intrinsic_load_vulkan_descriptor: + break; + case nir_intrinsic_load_deref: + if (count == ARRAY_SIZE(accesses->load) || op->def.bit_size != 32 || + op->def.num_components != 1 || + (nir_intrinsic_access(op) & ~ACCESS_CAN_REORDER) != ACCESS_NON_WRITEABLE) + return false; + accesses->load[count++] = op; + break; + case nir_intrinsic_store_deref: + if (accesses->store || nir_intrinsic_write_mask(op) != 1 || + nir_intrinsic_access(op) != ACCESS_NON_READABLE || + op->src[1].ssa->bit_size != 32 || op->src[1].ssa->num_components != 1) + return false; + accesses->store = op; + break; + default: + return false; + } + } + } + return accesses->store && count == ARRAY_SIZE(accesses->load); +} + +static bool +safe_nonunit_read(struct im2col_params *p, nir_scalar value, nir_scalar tap, + nir_scalar row, nir_scalar index, nir_intrinsic_instr *read_op) +{ + nir_scalar cond, inner; + if (!inside_arm(&read_op->instr.block->cf_node, value_branch(value), false) || + !zero_then(value, &cond, &inner) || inner.def != &read_op->def) + return false; + + /* cond is (x >= input_width || y >= input_height). */ + nir_scalar oob_x, oob_y; + if (!match_short_or(cond, &oob_x, &oob_y) || + !alu(oob_x, nir_op_ige) || !alu(oob_y, nir_op_ige)) + return false; + + nir_scalar x, y; + if (match_push_eq(arg(oob_x, 1), p->off[IM2COL_INPUT_WIDTH]) && + match_push_eq(arg(oob_y, 1), p->off[IM2COL_INPUT_HEIGHT])) { + x = arg(oob_x, 0); + y = arg(oob_y, 0); + } else if (match_push_eq(arg(oob_y, 1), p->off[IM2COL_INPUT_WIDTH]) && + match_push_eq(arg(oob_x, 1), p->off[IM2COL_INPUT_HEIGHT])) { + x = arg(oob_y, 0); + y = arg(oob_x, 0); + } else { + return false; + } + + nir_scalar cols_s = {0}; + if (!original_coords(p, tap, row, x, y, &cols_s) || !columns(p, cols_s)) + return false; + + if (!alu(index, nir_op_iadd)) + return false; + nir_scalar ia = arg(index, 0), ib = arg(index, 1), y_chk = {0}; + if (bind_im2col_mul(p, IM2COL_INPUT_WIDTH, ia, &y_chk) && + same(y_chk, y) && same(ib, x)) + return true; + if (bind_im2col_mul(p, IM2COL_INPUT_WIDTH, ib, &y_chk) && + same(y_chk, y) && same(ia, x)) + return true; + return false; +} + +static bool +match_im2col(nir_shader *nir, struct copy_buffer *src, struct copy_buffer *dst, + struct im2col_params *params, bool *im2col_vec4_ok) +{ + memset(params, 0, sizeof(*params)); + if (nir->info.stage != MESA_SHADER_COMPUTE || nir->info.workgroup_size_variable || + !hk_identity_copy4_supported_local(nir->info.workgroup_size) || + nir->info.num_ssbos != 2 || + nir->num_uniforms > HK_COMPUTE_OPT_PUSH_BYTES) + return false; + + nir_function_impl *impl = nir_shader_get_entrypoint(nir); + nir_foreach_function_impl(other, nir) { + if (other != impl) + return false; + } + if (!acyclic(&impl->body, 16)) + return false; + + struct access_set ops = {0}; + if (!collect_accesses(impl, &ops)) + return false; + + nir_scalar dst_index; + if (!match_buffer(ops.store, dst, &dst_index) || + dst->resource != nir_resource_type_read_write_storage_buffer || + !alu(dst_index, nir_op_iadd)) + return false; + + nir_scalar tap = {0}, row = {0}; + nir_scalar da = arg(dst_index, 0), db = arg(dst_index, 1); + if (coord(db, 0, nir->info.workgroup_size[0]) && + bind_im2col_mul(params, IM2COL_PATCHES_WIDTH, da, &row) && + coord(row, 1, nir->info.workgroup_size[1])) { + tap = db; + } else if (coord(da, 0, nir->info.workgroup_size[0]) && + bind_im2col_mul(params, IM2COL_PATCHES_WIDTH, db, &row) && + coord(row, 1, nir->info.workgroup_size[1])) { + tap = da; + } else { + return false; + } + + nir_block *write_block = ops.store->instr.block; + nir_if *bounds = as_if(write_block->cf_node.parent); + if (!bounds || bounds->cf_node.parent != &impl->cf_node || + write_block != nir_if_last_else_block(bounds) || + !out_of_bounds(params, scalar(bounds->condition.ssa), tap, row)) + return false; + + nir_scalar payload = scalar(ops.store->src[1].ssa); + nir_if *stride_branch = value_branch(payload); + nir_scalar is_unit, unit_value, other_value; + uint16_t s0 = 0, s1 = 0; + if (!stride_branch || !inside_arm(&stride_branch->cf_node, bounds, false) || + !branch_value(payload, &is_unit, &unit_value, &other_value) || + !match_unit_strides(is_unit, &s0, &s1, ¶ms->push_bytes)) + return false; + + nir_scalar discarded_cond, other_read; + if (!zero_then(other_value, &discarded_cond, &other_read)) + return false; + nir_intrinsic_instr *unused = intr(other_read.def, nir_intrinsic_load_deref); + if (unused != ops.load[0] && unused != ops.load[1]) + return false; + nir_intrinsic_instr *copy = unused == ops.load[0] ? ops.load[1] : ops.load[0]; + if (!inside_arm(&unused->instr.block->cf_node, stride_branch, false) || + !inside_arm(©->instr.block->cf_node, stride_branch, true)) + return false; + + struct copy_buffer other; + nir_scalar src_index, unused_index; + if (!match_buffer(copy, src, &src_index) || + !match_buffer(unused, &other, &unused_index) || !same_binding(*src, other) || + same_binding(*src, *dst) || + !safe_unit_read(params, unit_value, tap, row, src_index, copy) || + !check_unit_stride_pair(params, s0, s1)) + return false; + + for (unsigned i = 0; i < IM2COL_PARAM_COUNT; ++i) { + if (!params->bound[i]) + return false; + } + + if (im2col_vec4_ok) + *im2col_vec4_ok = safe_nonunit_read(params, other_value, tap, row, unused_index, unused); + return true; +} + +static nir_def * +address(nir_builder *b, struct copy_buffer loc, nir_def *index, + enum gl_access_qualifier access) +{ + nir_def *resource = nir_vulkan_resource_index( + b, loc.desc_comps, 32, nir_imm_int(b, 0), + .desc_type = nir_descriptor_type_storage_buffer, .resource_type = loc.resource, + .desc_set = loc.set, .binding = loc.binding); + nir_def *descriptor = nir_load_vulkan_descriptor( + b, loc.desc_comps, 32, resource, .desc_type = nir_descriptor_type_storage_buffer); + const glsl_type *array_type = glsl_array_type(glsl_vec4_type(), 0, 16); + nir_deref_instr *array = nir_build_deref_cast_with_alignment( + b, descriptor, nir_var_mem_ssbo, array_type, 0, 16, 0); + nir_deref_instr *element = nir_build_deref_array(b, array, index); + element->arr.in_bounds = true; + return nir_deref_buffer_address(b, 1, 64, &element->def, .access = access); +} + +static nir_def * +address_scalar(nir_builder *b, struct copy_buffer loc, nir_def *index, + enum gl_access_qualifier access, bool is_int) +{ + nir_def *resource = nir_vulkan_resource_index( + b, loc.desc_comps, 32, nir_imm_int(b, 0), + .desc_type = nir_descriptor_type_storage_buffer, .resource_type = loc.resource, + .desc_set = loc.set, .binding = loc.binding); + nir_def *descriptor = nir_load_vulkan_descriptor( + b, loc.desc_comps, 32, resource, .desc_type = nir_descriptor_type_storage_buffer); + const glsl_type *elem = is_int ? glsl_int_type() : glsl_float_type(); + const glsl_type *array_type = glsl_array_type(elem, 0, 4); + nir_deref_instr *array = nir_build_deref_cast_with_alignment( + b, descriptor, nir_var_mem_ssbo, array_type, 0, 4, 0); + nir_deref_instr *element = nir_build_deref_array(b, array, index); + element->arr.in_bounds = true; + return nir_deref_buffer_address(b, 1, 64, &element->def, .access = access); +} + +static nir_def * +push_at(nir_builder *b, uint16_t offset, uint16_t range) +{ + return nir_load_push_constant(b, 1, 32, nir_imm_int(b, offset), + .base = 0, .range = range, .align_mul = 4); +} + +static bool +match_linear_add_offset(nir_scalar idx, nir_scalar base_coord, + uint16_t *off_out, uint16_t *range_out) +{ + idx = strip_zero_add(idx); + if (!alu(idx, nir_op_iadd)) + return false; + nir_scalar a = strip_zero_add(arg(idx, 0)); + nir_scalar b = strip_zero_add(arg(idx, 1)); + if (same(a, base_coord) && match_push_any(b, off_out, range_out)) + return true; + if (same(b, base_coord) && match_push_any(a, off_out, range_out)) + return true; + return false; +} + +static bool +match_linear_1d(nir_shader *nir, enum hk_identity_copy4_kind *kind_out, + struct copy_buffer srcs[2], struct copy_buffer *dst, + uint16_t *count_off, uint16_t *src_off, uint16_t *dst_off, + uint16_t *push_bytes, unsigned *fadd_fp_ctrl) +{ + if (nir->info.stage != MESA_SHADER_COMPUTE || nir->info.workgroup_size_variable || + nir->info.workgroup_size[0] == 0 || nir->info.workgroup_size[0] > 1024 || + nir->info.workgroup_size[1] != 1 || nir->info.workgroup_size[2] != 1 || + nir->info.shared_size != 0 || + (nir->info.num_ssbos != 2 && nir->info.num_ssbos != 3)) + return false; + + nir_function_impl *impl = nir_shader_get_entrypoint(nir); + nir_foreach_function_impl(other, nir) { + if (other != impl) + return false; + } + if (!acyclic(&impl->body, 4)) + return false; + + nir_intrinsic_instr *store = NULL; + nir_intrinsic_instr *loads[2] = {NULL, NULL}; + unsigned load_count = 0; + + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + switch (instr->type) { + case nir_instr_type_deref: + case nir_instr_type_phi: + case nir_instr_type_load_const: + case nir_instr_type_alu: + continue; + case nir_instr_type_intrinsic: + break; + default: + return false; + } + + nir_intrinsic_instr *op = nir_instr_as_intrinsic(instr); + switch (op->intrinsic) { + case nir_intrinsic_load_global_invocation_id: + case nir_intrinsic_load_base_workgroup_id: + case nir_intrinsic_load_push_constant: + case nir_intrinsic_vulkan_resource_index: + case nir_intrinsic_load_vulkan_descriptor: + break; + case nir_intrinsic_load_deref: + if (load_count == 2 || op->def.bit_size != 32 || + op->def.num_components != 1 || + (nir_intrinsic_access(op) & ~ACCESS_CAN_REORDER) != ACCESS_NON_WRITEABLE) + return false; + loads[load_count++] = op; + break; + case nir_intrinsic_store_deref: + if (store || nir_intrinsic_write_mask(op) != 1 || + nir_intrinsic_access(op) != ACCESS_NON_READABLE || + op->src[1].ssa->bit_size != 32 || op->src[1].ssa->num_components != 1) + return false; + store = op; + break; + default: + return false; + } + } + } + + if (!store || load_count == 0) + return false; + + nir_block *write_block = store->instr.block; + nir_if *bounds = as_if(write_block->cf_node.parent); + if (!bounds || bounds->cf_node.parent != &impl->cf_node) + return false; + + const bool in_then = inside_arm(&write_block->cf_node, bounds, true); + const bool in_else = inside_arm(&write_block->cf_node, bounds, false); + if (in_then == in_else) + return false; + for (unsigned i = 0; i < load_count; ++i) { + if (!inside_arm(&loads[i]->instr.block->cf_node, bounds, in_then)) + return false; + } + + /* Match guard: `if (idx < count) { ... }` or `if (idx >= count) return;`. */ + nir_scalar cond = scalar(bounds->condition.ssa); + nir_scalar idx = {0}, cnt = {0}; + if (in_then && alu(cond, nir_op_ilt)) { + idx = arg(cond, 0); + cnt = arg(cond, 1); + } else if (in_else && alu(cond, nir_op_ige)) { + idx = arg(cond, 0); + cnt = arg(cond, 1); + } else { + return false; + } + idx = strip_zero_add(idx); + if (!coord(idx, 0, nir->info.workgroup_size[0])) + return false; + + uint16_t cnt_off = 0, cnt_range = 0; + if (!match_push_any(cnt, &cnt_off, &cnt_range)) + return false; + + const bool allow_int = (load_count == 1); + nir_scalar dst_idx; + if (!match_buffer_typed(store, dst, &dst_idx, allow_int) || + dst->resource != nir_resource_type_read_write_storage_buffer) + return false; + dst_idx = strip_zero_add(dst_idx); + + nir_scalar val = scalar(store->src[1].ssa); + if (load_count == 1) { + if (val.def != &loads[0]->def || val.comp != 0) + return false; + nir_scalar src_idx; + if (!match_buffer_typed(loads[0], &srcs[0], &src_idx, allow_int)) + return false; + src_idx = strip_zero_add(src_idx); + if (same(src_idx, idx) && same(dst_idx, idx)) { + *kind_out = HK_IDENTITY_COPY4_LINEAR_COPY; + *count_off = cnt_off; + *src_off = 0; + *dst_off = 0; + *push_bytes = cnt_range; + *fadd_fp_ctrl = 0; + return true; + } + uint16_t s_off = 0, s_rng = 0, d_off = 0, d_rng = 0; + if (match_linear_add_offset(src_idx, idx, &s_off, &s_rng) && + match_linear_add_offset(dst_idx, idx, &d_off, &d_rng)) { + *kind_out = HK_IDENTITY_COPY4_LINEAR_OFFSET; + *count_off = cnt_off; + *src_off = s_off; + *dst_off = d_off; + *push_bytes = MAX2(cnt_range, MAX2(s_rng, d_rng)); + *fadd_fp_ctrl = 0; + return true; + } + return false; + } + + /* load_count == 2: dst[idx] = src0[idx] + src1[idx] (FP32 fadd). */ + if (!same(dst_idx, idx)) + return false; + nir_alu_instr *add = alu(val, nir_op_fadd); + if (!add || add->def.bit_size != 32 || add->def.num_components != 1) + return false; + nir_scalar a0 = arg(val, 0), a1 = arg(val, 1); + if (!((a0.def == &loads[0]->def && a1.def == &loads[1]->def) || + (a0.def == &loads[1]->def && a1.def == &loads[0]->def))) + return false; + + nir_scalar s0_idx, s1_idx; + if (!match_buffer_typed(loads[0], &srcs[0], &s0_idx, false) || + !match_buffer_typed(loads[1], &srcs[1], &s1_idx, false)) + return false; + if (!same(strip_zero_add(s0_idx), idx) || !same(strip_zero_add(s1_idx), idx)) + return false; + + *kind_out = HK_IDENTITY_COPY4_LINEAR_FADD; + *count_off = cnt_off; + *src_off = 0; + *dst_off = 0; + *push_bytes = cnt_range; + *fadd_fp_ctrl = add->fp_math_ctrl; + return true; +} + +struct pad4d_match { + struct copy_buffer in_buf; + struct copy_buffer out_buf; + struct copy_buffer pad_buf; + uint16_t in_shape_off[4]; + uint16_t out_shape_off[4]; + uint32_t pad_idx[4]; + uint16_t push_bytes; +}; + +static bool +match_pad_load(nir_scalar s, struct copy_buffer *pad_buf, bool *have_pad_buf, + uint32_t *idx_out) +{ + s = nir_scalar_chase_movs(s); + nir_intrinsic_instr *op = intr(s.def, nir_intrinsic_load_deref); + if (!op || s.comp || op->def.bit_size != 32 || op->def.num_components != 1) + return false; + struct copy_buffer buf = {0}; + nir_scalar idx; + if (!match_buffer_typed(op, &buf, &idx, true) || !nir_scalar_is_const(idx)) + return false; + uint32_t ci = (uint32_t)nir_scalar_as_uint(idx); + if (ci > 64) + return false; + if (*have_pad_buf) { + if (!same_binding(*pad_buf, buf)) + return false; + } else { + *pad_buf = buf; + *have_pad_buf = true; + } + *idx_out = ci; + return true; +} + +static bool +match_pad_sub(nir_scalar s, nir_scalar coord_v, struct copy_buffer *pad_buf, + bool *have_pad_buf, uint32_t expected_idx) +{ + nir_scalar sub = {0}; + uint32_t ci = 0; + return match_sub_expr(s, coord_v, &sub) && + match_pad_load(sub, pad_buf, have_pad_buf, &ci) && + ci == expected_idx; +} + +struct rm4d_term { + nir_scalar leaf; + uint16_t factors[4]; + unsigned nfactors; +}; + +static bool +match_push_factors(nir_scalar s, uint16_t factors[4], unsigned *nfactors, + unsigned depth) +{ + if (depth > 4) + return false; + s = nir_scalar_chase_movs(s); + uint16_t off = 0; + if (match_push_any(s, &off, NULL)) { + if (*nfactors >= 4) + return false; + factors[(*nfactors)++] = off; + return true; + } + if (alu(s, nir_op_imul)) { + unsigned saved = *nfactors; + if (match_push_factors(arg(s, 0), factors, nfactors, depth + 1) && + match_push_factors(arg(s, 1), factors, nfactors, depth + 1)) + return true; + *nfactors = saved; + } + return false; +} + +static bool +expand_rm4d(nir_scalar s, struct rm4d_term *terms, unsigned *count, + unsigned max_terms, unsigned depth) +{ + if (depth > 12) + return false; + s = nir_scalar_chase_movs(s); + if (alu(s, nir_op_iadd)) { + /* Stop at (coord - pad) leaves so subtractions remain intact. */ + nir_scalar a = arg(s, 0), b = arg(s, 1); + if (alu(a, nir_op_ineg) || alu(b, nir_op_ineg)) { + if (*count >= max_terms) + return false; + terms[(*count)++] = (struct rm4d_term){ .leaf = s }; + return true; + } + return expand_rm4d(a, terms, count, max_terms, depth + 1) && + expand_rm4d(b, terms, count, max_terms, depth + 1); + } + if (alu(s, nir_op_imul)) { + uint16_t f[4]; + unsigned nf = 0; + nir_scalar other; + if (match_push_factors(arg(s, 1), f, &nf, 0)) { + other = arg(s, 0); + } else if (match_push_factors(arg(s, 0), f, &nf, 0)) { + other = arg(s, 1); + } else { + return false; + } + unsigned start = *count; + if (!expand_rm4d(other, terms, count, max_terms, depth + 1)) + return false; + for (unsigned i = start; i < *count; ++i) { + if (terms[i].nfactors + nf > 4) + return false; + for (unsigned k = 0; k < nf; ++k) + terms[i].factors[terms[i].nfactors++] = f[k]; + } + return true; + } + if (*count >= max_terms) + return false; + terms[(*count)++] = (struct rm4d_term){ .leaf = s }; + return true; +} + +static bool +factors_match_multiset(const uint16_t *got, unsigned ngot, + const uint16_t *want, unsigned nwant) +{ + if (ngot != nwant) + return false; + bool used[4] = {false}; + for (unsigned i = 0; i < nwant; ++i) { + bool found = false; + for (unsigned j = 0; j < ngot; ++j) { + if (!used[j] && got[j] == want[i]) { + used[j] = true; + found = true; + break; + } + } + if (!found) + return false; + } + return true; +} + +static bool +match_pad4d_out_idx(nir_scalar expr, const nir_scalar coords[4], + nir_scalar gx, nir_scalar gy, + uint16_t oh_off, uint16_t ow_off, uint16_t oc_off) +{ + struct rm4d_term terms[4]; + unsigned count = 0; + if (!expand_rm4d(expr, terms, &count, 4, 0)) + return false; + + const uint16_t f0[3] = {oh_off, ow_off, oc_off}; + const uint16_t f1[2] = {ow_off, oc_off}; + const uint16_t f2[1] = {oc_off}; + bool have[4] = {false}; + + for (unsigned i = 0; i < count; ++i) { + if (same(terms[i].leaf, coords[0]) && + factors_match_multiset(terms[i].factors, terms[i].nfactors, f0, 3)) { + if (have[0]) return false; + have[0] = true; + } else if (same(terms[i].leaf, coords[1]) && + factors_match_multiset(terms[i].factors, terms[i].nfactors, f1, 2)) { + if (have[1]) return false; + have[1] = true; + } else if (same(terms[i].leaf, coords[2]) && + factors_match_multiset(terms[i].factors, terms[i].nfactors, f2, 1)) { + if (have[2]) return false; + have[2] = true; + } else if (same(terms[i].leaf, coords[3]) && terms[i].nfactors == 0) { + if (have[3]) return false; + have[3] = true; + } else if (same(terms[i].leaf, gy) && + factors_match_multiset(terms[i].factors, terms[i].nfactors, f1, 2)) { + if (have[0] || have[1]) return false; + have[0] = have[1] = true; + } else if (same(terms[i].leaf, gx) && terms[i].nfactors == 0) { + if (have[2] || have[3]) return false; + have[2] = have[3] = true; + } else { + return false; + } + } + return have[0] && have[1] && have[2] && have[3]; +} + +static bool +match_pad4d_in_idx(nir_scalar expr, const nir_scalar coords[4], + struct copy_buffer *pad_buf, bool *have_pad, + const uint32_t pad_idx[4], const uint16_t in_off[4]) +{ + struct rm4d_term terms[4]; + unsigned count = 0; + if (!expand_rm4d(expr, terms, &count, 4, 0) || count != 4) + return false; + + const uint16_t f0[3] = {in_off[1], in_off[2], in_off[3]}; + const uint16_t f1[2] = {in_off[2], in_off[3]}; + const uint16_t f2[1] = {in_off[3]}; + bool have[4] = {false}; + + for (unsigned i = 0; i < count; ++i) { + if (match_pad_sub(terms[i].leaf, coords[0], pad_buf, have_pad, pad_idx[0]) && + factors_match_multiset(terms[i].factors, terms[i].nfactors, f0, 3)) { + if (have[0]) return false; + have[0] = true; + } else if (match_pad_sub(terms[i].leaf, coords[1], pad_buf, have_pad, pad_idx[1]) && + factors_match_multiset(terms[i].factors, terms[i].nfactors, f1, 2)) { + if (have[1]) return false; + have[1] = true; + } else if (match_pad_sub(terms[i].leaf, coords[2], pad_buf, have_pad, pad_idx[2]) && + factors_match_multiset(terms[i].factors, terms[i].nfactors, f2, 1)) { + if (have[2]) return false; + have[2] = true; + } else if (match_pad_sub(terms[i].leaf, coords[3], pad_buf, have_pad, pad_idx[3]) && + terms[i].nfactors == 0) { + if (have[3]) return false; + have[3] = true; + } else { + return false; + } + } + return have[0] && have[1] && have[2] && have[3]; +} + +static bool +match_pad4d(nir_shader *nir, struct pad4d_match *out) +{ + if (nir->info.stage != MESA_SHADER_COMPUTE || nir->info.workgroup_size_variable || + !hk_identity_copy4_supported_local(nir->info.workgroup_size) || + nir->info.num_ssbos != 3 || nir->num_uniforms > HK_COMPUTE_OPT_PUSH_BYTES) + return false; + + nir_function_impl *impl = nir_shader_get_entrypoint(nir); + nir_foreach_function_impl(other, nir) { + if (other != impl) + return false; + } + if (!acyclic(&impl->body, 16)) + return false; + + nir_intrinsic_instr *stores[2] = {NULL, NULL}; + unsigned nstores = 0; + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + switch (instr->type) { + case nir_instr_type_deref: + case nir_instr_type_phi: + case nir_instr_type_load_const: + case nir_instr_type_alu: + continue; + case nir_instr_type_intrinsic: + break; + default: + return false; + } + nir_intrinsic_instr *op = nir_instr_as_intrinsic(instr); + switch (op->intrinsic) { + case nir_intrinsic_load_global_invocation_id: + case nir_intrinsic_load_base_workgroup_id: + case nir_intrinsic_load_push_constant: + case nir_intrinsic_vulkan_resource_index: + case nir_intrinsic_load_vulkan_descriptor: + break; + case nir_intrinsic_load_deref: + if (op->def.bit_size != 32 || op->def.num_components != 1 || + (nir_intrinsic_access(op) & ~(ACCESS_CAN_REORDER | ACCESS_RESTRICT | ACCESS_IN_BOUNDS)) != + ACCESS_NON_WRITEABLE) + return false; + break; + case nir_intrinsic_store_deref: + if (nstores >= 2 || op->num_components != 1 || + op->src[1].ssa->bit_size != 32 || nir_intrinsic_write_mask(op) != 1 || + (nir_intrinsic_access(op) & ~(ACCESS_NON_READABLE | ACCESS_RESTRICT | ACCESS_IN_BOUNDS))) + return false; + stores[nstores++] = op; + break; + default: + return false; + } + } + } + if (nstores != 2) + return false; + + nir_intrinsic_instr *zero_st = NULL, *copy_st = NULL; + for (unsigned i = 0; i < 2; ++i) { + nir_scalar v = scalar(stores[i]->src[1].ssa); + if (imm(v, 0)) + zero_st = stores[i]; + else if (intr(v.def, nir_intrinsic_load_deref)) + copy_st = stores[i]; + } + if (!zero_st || !copy_st) + return false; + + nir_if *pad_if = as_if(zero_st->instr.block->cf_node.parent); + if (!pad_if || pad_if != as_if(copy_st->instr.block->cf_node.parent) || + !inside_arm(&zero_st->instr.block->cf_node, pad_if, true) || + !inside_arm(©_st->instr.block->cf_node, pad_if, false)) + return false; + + nir_if *outer_if = as_if(pad_if->cf_node.parent); + if (!outer_if || outer_if->cf_node.parent != &impl->cf_node || + !inside_arm(&pad_if->cf_node, outer_if, false)) + return false; + + nir_scalar o_x, o_y; + if (!match_short_or(scalar(outer_if->condition.ssa), &o_x, &o_y) || + !alu(o_x, nir_op_ige) || !alu(o_y, nir_op_ige)) + return false; + + nir_scalar gx = arg(o_x, 0), gy = arg(o_y, 0); + if (!coord(gx, 0, nir->info.workgroup_size[0]) || + !coord(gy, 1, nir->info.workgroup_size[1])) + return false; + + nir_scalar x_lim = arg(o_x, 1), y_lim = arg(o_y, 1); + if (!alu(x_lim, nir_op_imul) || !alu(y_lim, nir_op_imul)) + return false; + uint16_t ow_off = 0, oc_off = 0, on_off = 0, oh_off = 0, pb = 0, rtmp = 0; + if (!match_push_any(arg(x_lim, 0), &ow_off, &rtmp)) return false; + pb = MAX2(pb, rtmp); + if (!match_push_any(arg(x_lim, 1), &oc_off, &rtmp)) return false; + pb = MAX2(pb, rtmp); + if (!match_push_any(arg(y_lim, 0), &on_off, &rtmp)) return false; + pb = MAX2(pb, rtmp); + if (!match_push_any(arg(y_lim, 1), &oh_off, &rtmp)) return false; + pb = MAX2(pb, rtmp); + + struct copy_buffer out_b0 = {0}, out_b1 = {0}; + nir_scalar out_idx0, out_idx1; + if (!match_buffer(zero_st, &out_b0, &out_idx0) || + !match_buffer(copy_st, &out_b1, &out_idx1) || + !same_binding(out_b0, out_b1) || !same(out_idx0, out_idx1)) + return false; + + nir_scalar terms[8]; + nir_scalar cur = scalar(pad_if->condition.ssa); + for (int k = 7; k >= 1; --k) { + nir_scalar prev, rhs; + if (!match_short_or(cur, &prev, &rhs)) + return false; + terms[k] = rhs; + cur = prev; + } + terms[0] = cur; + + struct copy_buffer pad_buf = {0}; + bool have_pad = false; + nir_scalar coords[4]; + uint32_t pad_idx[4] = {0}; + uint16_t in_off[4] = {0}; + for (unsigned d = 0; d < 4; ++d) { + if (!alu(terms[d], nir_op_ilt)) + return false; + coords[d] = arg(terms[d], 0); + if (!match_pad_load(arg(terms[d], 1), &pad_buf, &have_pad, &pad_idx[d])) + return false; + } + for (unsigned d = 0; d < 4; ++d) { + if (!alu(terms[4 + d], nir_op_ige)) + return false; + if (!match_pad_sub(arg(terms[4 + d], 0), coords[d], &pad_buf, &have_pad, pad_idx[d])) + return false; + if (!match_push_any(arg(terms[4 + d], 1), &in_off[d], &rtmp)) + return false; + pb = MAX2(pb, rtmp); + } + + nir_scalar dn, dd; + if (!match_div(coords[0], &dn, &dd) || !same(dn, gy)) + return false; + uint16_t div_oh = 0; + if (!match_push_any(dd, &div_oh, NULL)) + return false; + if (div_oh == on_off) { + uint16_t tmp = on_off; on_off = oh_off; oh_off = tmp; + } else if (div_oh != oh_off) { + return false; + } + nir_scalar md; + if (!match_mod(coords[1], gy, &md) || !match_push_eq(md, oh_off)) + return false; + + if (!match_div(coords[2], &dn, &dd) || !same(dn, gx)) + return false; + uint16_t div_oc = 0; + if (!match_push_any(dd, &div_oc, NULL)) + return false; + if (div_oc == ow_off) { + uint16_t tmp = ow_off; ow_off = oc_off; oc_off = tmp; + } else if (div_oc != oc_off) { + return false; + } + if (!match_mod(coords[3], gx, &md) || !match_push_eq(md, oc_off)) + return false; + + if (!match_pad4d_out_idx(out_idx0, coords, gx, gy, oh_off, ow_off, oc_off)) + return false; + + nir_intrinsic_instr *in_ld = intr(copy_st->src[1].ssa, nir_intrinsic_load_deref); + struct copy_buffer in_buf = {0}; + nir_scalar in_idx; + if (!in_ld || !match_buffer(in_ld, &in_buf, &in_idx) || + same_binding(in_buf, out_b0) || same_binding(pad_buf, out_b0) || + same_binding(in_buf, pad_buf)) + return false; + + if (!match_pad4d_in_idx(in_idx, coords, &pad_buf, &have_pad, pad_idx, in_off)) + return false; + + *out = (struct pad4d_match) { + .in_buf = in_buf, + .out_buf = out_b0, + .pad_buf = pad_buf, + .in_shape_off = {in_off[0], in_off[1], in_off[2], in_off[3]}, + .out_shape_off = {on_off, oh_off, ow_off, oc_off}, + .pad_idx = {pad_idx[0], pad_idx[1], pad_idx[2], pad_idx[3]}, + .push_bytes = pb, + }; + return true; +} + +static nir_shader * +build_pad4d_vec4(nir_shader *nir, const struct pad4d_match *m, + const uint16_t orig_local[3], struct hk_identity_copy4 *info) +{ + nir_function_impl *impl = nir_shader_get_entrypoint(nir); + nir_cf_list old; + nir_cf_extract(&old, nir_before_impl(impl), nir_after_impl(impl)); + nir_cf_delete(&old); + nir_builder b = nir_builder_at(nir_after_block(nir_start_block(impl))); + + nir->info.workgroup_size[0] = 64; + nir->info.workgroup_size[1] = 2; + nir->info.workgroup_size[2] = 1; + + nir_def *gid = nir_load_global_invocation_id(&b, 32); + nir_def *gx = nir_channel(&b, gid, 0); + nir_def *gy = nir_channel(&b, gid, 1); + + nir_def *in_n = push_at(&b, m->in_shape_off[0], m->push_bytes); + nir_def *in_h = push_at(&b, m->in_shape_off[1], m->push_bytes); + nir_def *in_w = push_at(&b, m->in_shape_off[2], m->push_bytes); + nir_def *in_c = push_at(&b, m->in_shape_off[3], m->push_bytes); + nir_def *out_n = push_at(&b, m->out_shape_off[0], m->push_bytes); + nir_def *out_h = push_at(&b, m->out_shape_off[1], m->push_bytes); + nir_def *out_w = push_at(&b, m->out_shape_off[2], m->push_bytes); + nir_def *out_c = push_at(&b, m->out_shape_off[3], m->push_bytes); + + nir_def *in_c4 = nir_ushr_imm(&b, in_c, 2); + nir_def *out_c4 = nir_ushr_imm(&b, out_c, 2); + nir_def *out_x_lim = nir_imul(&b, out_w, out_c4); + nir_def *out_y_lim = nir_imul(&b, out_n, out_h); + + nir_if *active = nir_push_if(&b, nir_iand(&b, nir_ult(&b, gx, out_x_lim), + nir_ult(&b, gy, out_y_lim))); + { + const enum gl_access_qualifier read = ACCESS_NON_WRITEABLE | ACCESS_CAN_REORDER; + nir_def *p[4]; + for (unsigned d = 0; d < 4; ++d) { + nir_def *pa = address_scalar(&b, m->pad_buf, nir_imm_int(&b, m->pad_idx[d]), read, true); + p[d] = nir_load_global(&b, 1, 32, pa, .align_mul = 4, .access = read); + } + + nir_def *zero_n = nir_imm_int(&b, 0); + nir_def *n_div = NULL, *h_div = NULL; + nir_if *n1_if = nir_push_if(&b, nir_ieq_imm(&b, out_n, 1)); + { + /* Uniform out_n == 1: avoid udiv/umod on gy. */ + } + nir_push_else(&b, n1_if); + { + n_div = nir_udiv(&b, gy, out_h); + h_div = nir_umod(&b, gy, out_h); + } + nir_pop_if(&b, n1_if); + nir_def *n = nir_if_phi(&b, zero_n, n_div); + nir_def *h = nir_if_phi(&b, gy, h_div); + nir_def *w = nir_udiv(&b, gx, out_c4); + nir_def *c4 = nir_umod(&b, gx, out_c4); + + nir_def *in_n_i = nir_isub(&b, n, p[0]); + nir_def *in_h_i = nir_isub(&b, h, p[1]); + nir_def *in_w_i = nir_isub(&b, w, p[2]); + nir_def *n_ok = nir_iand(&b, nir_ige(&b, n, p[0]), nir_ilt(&b, in_n_i, in_n)); + nir_def *h_ok = nir_iand(&b, nir_ige(&b, h, p[1]), nir_ilt(&b, in_h_i, in_h)); + nir_def *w_ok = nir_iand(&b, nir_ige(&b, w, p[2]), nir_ilt(&b, in_w_i, in_w)); + nir_def *spatial_ok = nir_iand(&b, nir_iand(&b, n_ok, h_ok), w_ok); + + nir_def *zero_f = nir_imm_float(&b, 0.0f); + nir_def *zero_v4 = nir_vec4(&b, zero_f, zero_f, zero_f, zero_f); + + nir_def *val_spatial = NULL; + nir_if *sp_if = nir_push_if(&b, spatial_ok); + { + nir_def *in_sp4 = + nir_imul(&b, nir_iadd(&b, nir_imul(&b, nir_iadd(&b, nir_imul(&b, in_n_i, in_h), in_h_i), in_w), in_w_i), in_c4); + nir_def *v_fast = NULL, *v_slow = NULL; + nir_if *p3_zero = nir_push_if(&b, nir_ieq_imm(&b, p[3], 0)); + { + nir_def *v_ld = NULL; + nir_if *c_ok = nir_push_if(&b, nir_ult(&b, c4, in_c4)); + { + nir_def *in_addr = address(&b, m->in_buf, nir_iadd(&b, in_sp4, c4), read); + v_ld = nir_load_global(&b, 4, 32, in_addr, .align_mul = 16, .access = read); + } + nir_push_else(&b, c_ok); + nir_pop_if(&b, c_ok); + v_fast = nir_if_phi(&b, v_ld, zero_v4); + } + nir_push_else(&b, p3_zero); + { + nir_def *in_sp = nir_ishl_imm(&b, in_sp4, 2); + nir_def *c_base = nir_ishl_imm(&b, c4, 2); + nir_def *ch_vals[4]; + for (unsigned k = 0; k < 4; ++k) { + nir_def *c_k = nir_iadd_imm(&b, c_base, k); + nir_def *ci = nir_isub(&b, c_k, p[3]); + nir_def *v_k = NULL; + nir_def *ci_ok = nir_iand(&b, nir_ige(&b, c_k, p[3]), nir_ilt(&b, ci, in_c)); + nir_if *ck = nir_push_if(&b, ci_ok); + { + nir_def *sa = address_scalar(&b, m->in_buf, nir_iadd(&b, in_sp, ci), read, false); + v_k = nir_load_global(&b, 1, 32, sa, .align_mul = 4, .access = read); + } + nir_push_else(&b, ck); + nir_pop_if(&b, ck); + ch_vals[k] = nir_if_phi(&b, v_k, zero_f); + } + v_slow = nir_vec4(&b, ch_vals[0], ch_vals[1], ch_vals[2], ch_vals[3]); + } + nir_pop_if(&b, p3_zero); + val_spatial = nir_if_phi(&b, v_fast, v_slow); + } + nir_push_else(&b, sp_if); + nir_pop_if(&b, sp_if); + nir_def *val = nir_if_phi(&b, val_spatial, zero_v4); + + nir_def *out_idx4 = nir_iadd(&b, nir_imul(&b, gy, out_x_lim), gx); + nir_def *out_addr = address(&b, m->out_buf, out_idx4, ACCESS_NON_READABLE); + nir_store_global(&b, val, out_addr, .align_mul = 16, .write_mask = 0xf, + .access = ACCESS_NON_READABLE); + } + nir_pop_if(&b, active); + + nir_opt_dce(nir); + nir_shader_gather_info(nir, impl); + memset(info, 0, sizeof(*info)); + info->kind = HK_IDENTITY_COPY4_PAD4; + info->src_count = 1; + info->src_set = m->in_buf.set; + info->dst_set = m->out_buf.set; + info->pad_set = m->pad_buf.set; + info->src_binding = m->in_buf.binding; + info->dst_binding = m->out_buf.binding; + info->pad_binding = m->pad_buf.binding; + info->push_bytes = m->push_bytes; + for (unsigned d = 0; d < 4; ++d) { + info->in_shape_off[d] = m->in_shape_off[d]; + info->out_shape_off[d] = m->out_shape_off[d]; + info->pad_idx[d] = m->pad_idx[d]; + } + for (unsigned d = 0; d < 3; ++d) + info->local[d] = orig_local[d]; + return nir; +} + +nir_shader * +hk_nir_im2col_vec4(const nir_shader *orig) +{ + nir_shader *nir = nir_shader_clone(NULL, orig); + nir_opt_constant_folding(nir); + + struct copy_buffer src = {0}, dst = {0}; + struct im2col_params p = {0}; + bool vec4_ok = false; + if (!match_im2col(nir, &src, &dst, &p, &vec4_ok) || !vec4_ok) { + ralloc_free(nir); + return NULL; + } + + nir_function_impl *impl = nir_shader_get_entrypoint(nir); + nir_cf_list old; + nir_cf_extract(&old, nir_before_impl(impl), nir_after_impl(impl)); + nir_cf_delete(&old); + nir_builder b = nir_builder_at(nir_after_block(nir_start_block(impl))); + + nir->info.workgroup_size[0] = 32; + nir->info.workgroup_size[1] = 4; + nir->info.workgroup_size[2] = 1; + + nir_def *gid = nir_load_global_invocation_id(&b, 32); + nir_def *tap4 = nir_channel(&b, gid, 0); + nir_def *row = nir_channel(&b, gid, 1); + + nir_def *bw = push_at(&b, p.off[IM2COL_BORDER_WIDTH], p.push_bytes); + nir_def *bh = push_at(&b, p.off[IM2COL_BORDER_HEIGHT], p.push_bytes); + nir_def *iw = push_at(&b, p.off[IM2COL_INPUT_WIDTH], p.push_bytes); + nir_def *ih = push_at(&b, p.off[IM2COL_INPUT_HEIGHT], p.push_bytes); + nir_def *kw = push_at(&b, p.off[IM2COL_KERNEL_WIDTH], p.push_bytes); + nir_def *pw = push_at(&b, p.off[IM2COL_PATCHES_WIDTH], p.push_bytes); + nir_def *ph = push_at(&b, p.off[IM2COL_PATCHES_HEIGHT], p.push_bytes); + nir_def *sw = push_at(&b, p.off[IM2COL_STRIDE_WIDTH], p.push_bytes); + nir_def *sh = push_at(&b, p.off[IM2COL_STRIDE_HEIGHT], p.push_bytes); + nir_def *ch = push_at(&b, p.off[IM2COL_CHANNELS], p.push_bytes); + + nir_def *pw4 = nir_ushr_imm(&b, pw, 2); + nir_if *active = nir_push_if(&b, nir_iand(&b, nir_ult(&b, tap4, pw4), + nir_ult(&b, row, ph))); + { + const enum gl_access_qualifier read = ACCESS_NON_WRITEABLE | ACCESS_CAN_REORDER; + nir_def *c4 = nir_ushr_imm(&b, ch, 2); + nir_def *iw4 = nir_ushr_imm(&b, iw, 2); + nir_def *kw4 = nir_ushr_imm(&b, kw, 2); + nir_def *unit = nir_iand(&b, nir_ieq_imm(&b, sw, 1), nir_ieq_imm(&b, sh, 1)); + + nir_def *pad_x = nir_imul(&b, bw, ch); + nir_def *pad_x_tot = nir_bcsel(&b, unit, nir_ishl_imm(&b, pad_x, 1), pad_x); + nir_def *bordered_iw = nir_iadd(&b, iw, pad_x_tot); + nir_def *diff = nir_isub(&b, nir_udiv(&b, bordered_iw, ch), nir_udiv(&b, kw, ch)); + nir_def *cols = nir_iadd_imm(&b, nir_udiv(&b, diff, sw), 1); + + nir_def *out_x = nir_umod(&b, row, cols); + nir_def *out_y = nir_udiv(&b, row, cols); + nir_def *kx4 = nir_umod(&b, tap4, kw4); + nir_def *ky = nir_udiv(&b, tap4, kw4); + + nir_def *x4 = nir_iadd(&b, nir_imul(&b, out_x, nir_imul(&b, sw, c4)), kx4); + nir_def *y = nir_iadd(&b, nir_imul(&b, out_y, sh), ky); + + nir_def *zero_f = nir_imm_float(&b, 0.0f); + nir_def *zero_v4 = nir_vec4(&b, zero_f, zero_f, zero_f, zero_f); + + nir_def *v_unit = NULL, *v_other = NULL; + nir_if *u_if = nir_push_if(&b, unit); + { + nir_def *pad_x4 = nir_imul(&b, bw, c4); + nir_def *x_in4 = nir_isub(&b, x4, pad_x4); + nir_def *y_in = nir_isub(&b, y, bh); + nir_def *in_b = nir_iand(&b, nir_ult(&b, x_in4, iw4), nir_ult(&b, y_in, ih)); + nir_def *v_ld = NULL; + nir_if *ok_if = nir_push_if(&b, in_b); + { + nir_def *s_idx4 = nir_iadd(&b, nir_imul(&b, y_in, iw4), x_in4); + nir_def *sa = address(&b, src, s_idx4, read); + v_ld = nir_load_global(&b, 4, 32, sa, .align_mul = 16, .access = read); + } + nir_push_else(&b, ok_if); + nir_pop_if(&b, ok_if); + v_unit = nir_if_phi(&b, v_ld, zero_v4); + } + nir_push_else(&b, u_if); + { + nir_def *in_b = nir_iand(&b, nir_ult(&b, x4, iw4), nir_ult(&b, y, ih)); + nir_def *v_ld = NULL; + nir_if *ok_if = nir_push_if(&b, in_b); + { + nir_def *s_idx4 = nir_iadd(&b, nir_imul(&b, y, iw4), x4); + nir_def *sa = address(&b, src, s_idx4, read); + v_ld = nir_load_global(&b, 4, 32, sa, .align_mul = 16, .access = read); + } + nir_push_else(&b, ok_if); + nir_pop_if(&b, ok_if); + v_other = nir_if_phi(&b, v_ld, zero_v4); + } + nir_pop_if(&b, u_if); + nir_def *val = nir_if_phi(&b, v_unit, v_other); + + nir_def *dst_idx4 = nir_iadd(&b, nir_imul(&b, row, pw4), tap4); + nir_def *da = address(&b, dst, dst_idx4, ACCESS_NON_READABLE); + nir_store_global(&b, val, da, .align_mul = 16, .write_mask = 0xf, + .access = ACCESS_NON_READABLE); + } + nir_pop_if(&b, active); + + nir_opt_dce(nir); + nir_shader_gather_info(nir, impl); + return nir; +} + +nir_shader * +hk_nir_copy_identity4(const nir_shader *orig, struct hk_identity_copy4 *info) +{ + nir_shader *nir = nir_shader_clone(NULL, orig); + nir_opt_constant_folding(nir); + + const uint16_t orig_local[3] = { + nir->info.workgroup_size[0], + nir->info.workgroup_size[1], + nir->info.workgroup_size[2], + }; + + struct copy_buffer srcs[2] = {{0}}; + struct copy_buffer dst = {0}; + struct im2col_params im2col_p = {0}; + enum hk_identity_copy4_kind kind = HK_IDENTITY_COPY4_IM2COL_1X1; + uint16_t count_off = 0, src_off = 0, dst_off = 0, push_bytes = 0; + unsigned fadd_fp_ctrl = 0; + bool im2col_vec4_ok = false; + + if (match_im2col(nir, &srcs[0], &dst, &im2col_p, &im2col_vec4_ok)) { + kind = HK_IDENTITY_COPY4_IM2COL_1X1; + push_bytes = im2col_p.push_bytes; + } else { + struct pad4d_match pad4 = {0}; + if (match_pad4d(nir, &pad4)) + return build_pad4d_vec4(nir, &pad4, orig_local, info); + if (!match_linear_1d(nir, &kind, srcs, &dst, &count_off, &src_off, + &dst_off, &push_bytes, &fadd_fp_ctrl)) { + ralloc_free(nir); + return NULL; + } + } + + nir_function_impl *impl = nir_shader_get_entrypoint(nir); + nir_cf_list old; + nir_cf_extract(&old, nir_before_impl(impl), nir_after_impl(impl)); + nir_cf_delete(&old); + nir_builder b = nir_builder_at(nir_after_block(nir_start_block(impl))); + + /* Flatten to a 1D packed vec4 workgroup, transferring 4 coalesced vec4s + * (64B) per lane to expose memory-level parallelism and cut WG count 4x. */ + const uint16_t wg_x = 128; + const uint32_t wg_chunk = (uint32_t)wg_x * 4; + nir->info.workgroup_size[0] = wg_x; + nir->info.workgroup_size[1] = 1; + nir->info.workgroup_size[2] = 1; + + nir_def *wg_id = nir_channel(&b, nir_load_workgroup_id(&b), 0); + nir_def *lid = nir_channel(&b, nir_load_local_invocation_id(&b), 0); + nir_def *wg_base = nir_imul_imm(&b, wg_id, wg_chunk); + nir_def *base = nir_iadd(&b, wg_base, lid); + nir_def *total4 = NULL; + if (kind == HK_IDENTITY_COPY4_IM2COL_1X1) { + nir_def *width4 = + nir_ushr_imm(&b, push_at(&b, im2col_p.off[IM2COL_PATCHES_WIDTH], push_bytes), 2); + total4 = nir_imul(&b, push_at(&b, im2col_p.off[IM2COL_PATCHES_HEIGHT], push_bytes), width4); + } else { + total4 = nir_ushr_imm(&b, push_at(&b, count_off, push_bytes), 2); + } + + const enum gl_access_qualifier read = ACCESS_NON_WRITEABLE | ACCESS_CAN_REORDER; + nir_def *src_off4 = NULL, *dst_off4 = NULL; + if (kind == HK_IDENTITY_COPY4_LINEAR_OFFSET) { + src_off4 = nir_ushr_imm(&b, push_at(&b, src_off, push_bytes), 2); + dst_off4 = nir_ushr_imm(&b, push_at(&b, dst_off, push_bytes), 2); + } + + /* Workgroup-uniform interior check without uint32 underflow. */ + nir_def *full_wg = nir_iand( + &b, nir_uge(&b, total4, nir_imm_int(&b, wg_chunk)), + nir_uge(&b, nir_iadd_imm(&b, total4, -(int32_t)wg_chunk), wg_base)); + nir_if *fast = nir_push_if(&b, full_wg); + { + nir_def *vals[4]; + nir_def *dst_idxs[4]; + for (unsigned k = 0; k < 4; ++k) { + nir_def *idx = k ? nir_iadd_imm(&b, base, (int32_t)(k * wg_x)) : base; + nir_def *s_idx = src_off4 ? nir_iadd(&b, idx, src_off4) : idx; + dst_idxs[k] = dst_off4 ? nir_iadd(&b, idx, dst_off4) : idx; + nir_def *in0 = address(&b, srcs[0], s_idx, read); + nir_def *p0 = nir_load_global(&b, 4, 32, in0, .align_mul = 16, .access = read); + if (kind == HK_IDENTITY_COPY4_LINEAR_FADD) { + nir_def *in1 = address(&b, srcs[1], s_idx, read); + nir_def *p1 = nir_load_global(&b, 4, 32, in1, .align_mul = 16, .access = read); + b.fp_math_ctrl = fadd_fp_ctrl; + p0 = nir_fadd(&b, p0, p1); + b.fp_math_ctrl = 0; + } + vals[k] = p0; + } + for (unsigned k = 0; k < 4; ++k) { + nir_def *out = address(&b, dst, dst_idxs[k], ACCESS_NON_READABLE); + nir_store_global(&b, vals[k], out, .align_mul = 16, .write_mask = 0xf, + .access = ACCESS_NON_READABLE); + } + } + nir_push_else(&b, fast); + { + for (unsigned k = 0; k < 4; ++k) { + nir_def *idx = k ? nir_iadd_imm(&b, base, (int32_t)(k * wg_x)) : base; + nir_if *ok = nir_push_if(&b, nir_ult(&b, idx, total4)); + { + nir_def *s_idx = src_off4 ? nir_iadd(&b, idx, src_off4) : idx; + nir_def *d_idx = dst_off4 ? nir_iadd(&b, idx, dst_off4) : idx; + nir_def *in0 = address(&b, srcs[0], s_idx, read); + nir_def *p0 = nir_load_global(&b, 4, 32, in0, .align_mul = 16, .access = read); + if (kind == HK_IDENTITY_COPY4_LINEAR_FADD) { + nir_def *in1 = address(&b, srcs[1], s_idx, read); + nir_def *p1 = nir_load_global(&b, 4, 32, in1, .align_mul = 16, .access = read); + b.fp_math_ctrl = fadd_fp_ctrl; + p0 = nir_fadd(&b, p0, p1); + b.fp_math_ctrl = 0; + } + nir_def *out = address(&b, dst, d_idx, ACCESS_NON_READABLE); + nir_store_global(&b, p0, out, .align_mul = 16, .write_mask = 0xf, + .access = ACCESS_NON_READABLE); + } + nir_pop_if(&b, ok); + } + } + nir_pop_if(&b, fast); + + nir_opt_dce(nir); + nir_shader_gather_info(nir, impl); + memset(info, 0, sizeof(*info)); + info->kind = (uint8_t)kind; + info->src_count = (kind == HK_IDENTITY_COPY4_LINEAR_FADD) ? 2 : 1; + info->src_set = srcs[0].set; + info->src1_set = srcs[1].set; + info->dst_set = dst.set; + info->src_binding = srcs[0].binding; + info->src1_binding = srcs[1].binding; + info->dst_binding = dst.binding; + if (kind == HK_IDENTITY_COPY4_IM2COL_1X1) { + info->border_width_offset = im2col_p.off[IM2COL_BORDER_WIDTH]; + info->border_height_offset = im2col_p.off[IM2COL_BORDER_HEIGHT]; + info->input_width_offset = im2col_p.off[IM2COL_INPUT_WIDTH]; + info->input_height_offset = im2col_p.off[IM2COL_INPUT_HEIGHT]; + info->kernel_width_offset = im2col_p.off[IM2COL_KERNEL_WIDTH]; + info->patches_width_offset = im2col_p.off[IM2COL_PATCHES_WIDTH]; + info->patches_height_offset = im2col_p.off[IM2COL_PATCHES_HEIGHT]; + info->stride_width_offset = im2col_p.off[IM2COL_STRIDE_WIDTH]; + info->stride_height_offset = im2col_p.off[IM2COL_STRIDE_HEIGHT]; + info->channels_offset = im2col_p.off[IM2COL_CHANNELS]; + info->im2col_vec4_ok = im2col_vec4_ok; + } + info->count_offset = count_off; + info->src_offset_offset = src_off; + info->dst_offset_offset = dst_off; + info->push_bytes = push_bytes; + for (unsigned d = 0; d < 3; ++d) + info->local[d] = orig_local[d]; + return nir; +} diff --git a/src/asahi/vulkan/hk_shader.c b/src/asahi/vulkan/hk_shader.c index 7ef012cae73c..0f0387d3a1cc 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_identity_copy4.h" #include "hk_buffer.h" #include "hk_frame_anatomy.h" #include "hk_agx3_ioto_program_core.h" @@ -565,14 +566,22 @@ hk_preprocess_nir_internal(struct vk_physical_device *vk_pdev, nir_shader *nir) ((struct hk_physical_device *)vk_pdev)->dev.chip); /* Optimize but allow copies because we haven't lowered them yet */ - if (agx_chip_native_agx3(((struct hk_physical_device *)vk_pdev)->dev.chip) && - nir->info.stage != MESA_SHADER_MESH) - agx_preprocess_nir_native( - nir, ((struct hk_physical_device *)vk_pdev)->dev.chip); + const enum agx_chip pre_chip = ((struct hk_physical_device *)vk_pdev)->dev.chip; + if (agx_chip_native_agx3(pre_chip) && + nir->info.stage != MESA_SHADER_MESH) { + if (nir->info.stage == MESA_SHADER_COMPUTE && !nir->info.internal) + agx_preprocess_nir_native_defer_idiv(nir, pre_chip); + else + agx_preprocess_nir_native(nir, pre_chip); + } else if (((struct hk_physical_device *)vk_pdev)->dev.chip == AGX_CHIP_G18G) agx_preprocess_nir_g18g(nir); - else if (agx_chip_g17_m5(((struct hk_physical_device *)vk_pdev)->dev.chip)) - agx_preprocess_nir_m5(nir); + else if (agx_chip_g17_m5(pre_chip)) { + if (nir->info.stage == MESA_SHADER_COMPUTE && !nir->info.internal) + agx_preprocess_nir_m5_defer_idiv(nir); + else + agx_preprocess_nir_m5(nir); + } else agx_preprocess_nir(nir); @@ -6457,6 +6466,15 @@ hk_api_shader_destroy(struct vk_device *vk_dev, struct vk_shader *vk_shader, free(obj->byte_stencil); } + if (obj->identity_copy4) { + hk_shader_destroy(dev, obj->identity_copy4, true); + free(obj->identity_copy4); + } + if (obj->im2col_vec4) { + hk_shader_destroy(dev, obj->im2col_vec4, true); + free(obj->im2col_vec4); + } + if (obj->binary_cache_entry) hk_shader_binary_cache_entry_unref(dev, obj->binary_cache_entry); @@ -9454,6 +9472,83 @@ hk_m5_no_grid_record(const struct hk_device *dev, uint32_t shader_count, !hk_nir_reads_intrinsic(mesh->nir, nir_intrinsic_load_num_workgroups); } +static struct hk_shader * +hk_compile_compute_alt_nir(struct hk_device *dev, + const struct vk_shader_compile_info *info, + const VkAllocationCallbacks *allocator, + enum hk_feature_key features, + nir_shader *nir) +{ + struct hk_shader *alternate = calloc(1, sizeof(*alternate)); + if (!alternate) { + ralloc_free(nir); + return NULL; + } + + hk_lower_nir(dev, nir, info->robustness, false, info->next_stage_mask, + info->set_layout_count, info->set_layouts, features); + const VkResult result = + hk_compile_nir(dev, allocator, nir, info->flags, info->robustness, NULL, + features, alternate, MESA_SHADER_COMPUTE, true, NULL, + info->set_layout_count, + hk_static_set_mask(info->set_layout_count, info->set_layouts)); + if (result == VK_SUCCESS && alternate->only_linked) + return alternate; + + hk_shader_destroy(dev, alternate, true); + free(alternate); + return NULL; +} + +static struct hk_shader * +hk_compile_identity_copy4(struct hk_device *dev, + const struct vk_shader_compile_info *info, + const VkAllocationCallbacks *allocator, + enum hk_feature_key features, + struct hk_identity_copy4 *path_out, + struct hk_shader **im2col_vec4_out) +{ + *im2col_vec4_out = NULL; + if (!agx_chip_native_or_m5(dev->dev.chip) || + info->stage != MESA_SHADER_COMPUTE || info->nir->info.internal || + hk_set_layouts_use_buffers(info->set_layout_count, info->set_layouts)) + return NULL; + + nir_shader *candidate = nir_shader_clone(NULL, info->nir); + if (!candidate) + return NULL; + + const nir_opt_access_options access_options = {.is_vulkan = true}; + NIR_PASS(_, candidate, nir_opt_access, &access_options); + NIR_PASS(_, candidate, nir_lower_explicit_io, nir_var_mem_push_const, + nir_address_format_32bit_offset); + + struct hk_identity_copy4 path = {0}; + nir_shader *copy = hk_nir_copy_identity4(candidate, &path); + nir_shader *im2col4 = NULL; + if (copy && path.kind == HK_IDENTITY_COPY4_IM2COL_1X1 && path.im2col_vec4_ok) + im2col4 = hk_nir_im2col_vec4(candidate); + ralloc_free(candidate); + if (!copy) { + ralloc_free(im2col4); + return NULL; + } + + struct hk_shader *alternate = + hk_compile_compute_alt_nir(dev, info, allocator, features, copy); + if (!alternate) { + ralloc_free(im2col4); + return NULL; + } + + if (im2col4) + *im2col_vec4_out = + hk_compile_compute_alt_nir(dev, info, allocator, features, im2col4); + + *path_out = path; + return alternate; +} + static VkResult hk_compile_shaders(struct vk_device *vk_dev, uint32_t shader_count, struct vk_shader_compile_info *infos, @@ -9463,6 +9558,9 @@ hk_compile_shaders(struct vk_device *vk_dev, uint32_t shader_count, struct vk_shader **shaders_out) { struct hk_device *dev = container_of(vk_dev, struct hk_device, vk); + struct hk_shader *identity_copy4 = NULL; + struct hk_shader *im2col_vec4 = NULL; + struct hk_identity_copy4 identity_copy4_info = {0}; nir_shader *shaders[shader_count]; nir_shader *lr_nirs[shader_count]; struct hk_local_read_info lr_infos[shader_count]; @@ -9564,6 +9662,12 @@ hk_compile_shaders(struct vk_device *vk_dev, uint32_t shader_count, } } } + + if (shader_count == 1) + identity_copy4 = hk_compile_identity_copy4(dev, info, pAllocator, + hk_features, &identity_copy4_info, + &im2col_vec4); + hk_lower_nir(dev, nir, info->robustness, is_multiview, info->next_stage_mask, info->set_layout_count, info->set_layouts, hk_features); @@ -9755,6 +9859,14 @@ hk_compile_shaders(struct vk_device *vk_dev, uint32_t shader_count, } lr_nirs[i] = NULL; if (result != VK_SUCCESS) { + if (identity_copy4) { + hk_shader_destroy(dev, identity_copy4, true); + free(identity_copy4); + } + if (im2col_vec4) { + hk_shader_destroy(dev, im2col_vec4, true); + free(im2col_vec4); + } /* Clean up all the shaders before this point */ for (uint32_t j = 0; j < i; j++) hk_api_shader_destroy(&dev->vk, shaders_out[j], pAllocator); @@ -9773,6 +9885,14 @@ hk_compile_shaders(struct vk_device *vk_dev, uint32_t shader_count, } } + if (identity_copy4) { + struct hk_api_shader *obj = + container_of(shaders_out[0], struct hk_api_shader, vk); + obj->identity_copy4 = identity_copy4; + obj->identity_copy4_info = identity_copy4_info; + obj->im2col_vec4 = im2col_vec4; + } + /* G17P and M5 link a fragment shader with its epilog into one program, a * full compile, and a vertex prolog is compiled on its first use. Do both * now rather than at the first draw on the recording thread: for the state @@ -9995,6 +10115,112 @@ hk_border_source_deserialize(struct hk_border_source **out, return VK_SUCCESS; } +static void +hk_identity_copy4_serialize(struct blob *blob, + const struct hk_identity_copy4 *info) +{ + blob_write_uint8(blob, info->kind); + blob_write_uint8(blob, info->src_count); + blob_write_uint8(blob, info->src_set); + blob_write_uint8(blob, info->src1_set); + blob_write_uint8(blob, info->dst_set); + blob_write_uint8(blob, info->pad_set); + blob_write_uint16(blob, info->src_binding); + blob_write_uint16(blob, info->src1_binding); + blob_write_uint16(blob, info->dst_binding); + blob_write_uint16(blob, info->pad_binding); + blob_write_uint16(blob, info->border_width_offset); + blob_write_uint16(blob, info->border_height_offset); + blob_write_uint16(blob, info->input_width_offset); + blob_write_uint16(blob, info->input_height_offset); + blob_write_uint16(blob, info->kernel_width_offset); + blob_write_uint16(blob, info->patches_width_offset); + blob_write_uint16(blob, info->patches_height_offset); + blob_write_uint16(blob, info->stride_width_offset); + blob_write_uint16(blob, info->stride_height_offset); + blob_write_uint16(blob, info->channels_offset); + blob_write_uint16(blob, info->count_offset); + blob_write_uint16(blob, info->src_offset_offset); + blob_write_uint16(blob, info->dst_offset_offset); + blob_write_uint16(blob, info->push_bytes); + for (unsigned i = 0; i < 4; ++i) + blob_write_uint16(blob, info->in_shape_off[i]); + for (unsigned i = 0; i < 4; ++i) + blob_write_uint16(blob, info->out_shape_off[i]); + for (unsigned i = 0; i < 4; ++i) + blob_write_uint32(blob, info->pad_idx[i]); + for (unsigned i = 0; i < 3; ++i) + blob_write_uint16(blob, info->local[i]); + blob_write_uint8(blob, info->im2col_vec4_ok ? 1 : 0); +} + +static void +hk_identity_copy4_deserialize(struct blob_reader *blob, + struct hk_identity_copy4 *info) +{ + *info = (struct hk_identity_copy4){0}; + info->kind = blob_read_uint8(blob); + info->src_count = blob_read_uint8(blob); + info->src_set = blob_read_uint8(blob); + info->src1_set = blob_read_uint8(blob); + info->dst_set = blob_read_uint8(blob); + info->pad_set = blob_read_uint8(blob); + info->src_binding = blob_read_uint16(blob); + info->src1_binding = blob_read_uint16(blob); + info->dst_binding = blob_read_uint16(blob); + info->pad_binding = blob_read_uint16(blob); + info->border_width_offset = blob_read_uint16(blob); + info->border_height_offset = blob_read_uint16(blob); + info->input_width_offset = blob_read_uint16(blob); + info->input_height_offset = blob_read_uint16(blob); + info->kernel_width_offset = blob_read_uint16(blob); + info->patches_width_offset = blob_read_uint16(blob); + info->patches_height_offset = blob_read_uint16(blob); + info->stride_width_offset = blob_read_uint16(blob); + info->stride_height_offset = blob_read_uint16(blob); + info->channels_offset = blob_read_uint16(blob); + info->count_offset = blob_read_uint16(blob); + info->src_offset_offset = blob_read_uint16(blob); + info->dst_offset_offset = blob_read_uint16(blob); + info->push_bytes = blob_read_uint16(blob); + for (unsigned i = 0; i < 4; ++i) + info->in_shape_off[i] = blob_read_uint16(blob); + for (unsigned i = 0; i < 4; ++i) + info->out_shape_off[i] = blob_read_uint16(blob); + for (unsigned i = 0; i < 4; ++i) + info->pad_idx[i] = blob_read_uint32(blob); + for (unsigned i = 0; i < 3; ++i) + info->local[i] = blob_read_uint16(blob); + info->im2col_vec4_ok = blob_read_uint8(blob) != 0; +} + +static VkResult +hk_deserialize_optional_compute_alt(struct hk_device *dev, + struct blob_reader *blob, + struct hk_shader **out) +{ + const uint32_t size = blob_read_uint32(blob); + const void *payload = blob_read_bytes(blob, size); + if (blob->overrun || !size) + return VK_ERROR_INCOMPATIBLE_SHADER_BINARY_EXT; + + struct blob_reader sub; + blob_reader_init(&sub, payload, size); + struct hk_shader *alternate = calloc(1, sizeof(*alternate)); + if (!alternate) + return vk_error(dev, VK_ERROR_OUT_OF_HOST_MEMORY); + + VkResult result = hk_deserialize_shader(dev, &sub, alternate, false, false); + if (result != VK_SUCCESS || sub.current != sub.end) { + hk_shader_destroy(dev, alternate, true); + free(alternate); + return result == VK_SUCCESS ? VK_ERROR_INCOMPATIBLE_SHADER_BINARY_EXT : result; + } + + *out = alternate; + return VK_SUCCESS; +} + static VkResult hk_deserialize_api_shader_impl(struct vk_device *vk_dev, struct blob_reader *blob, @@ -10027,13 +10253,17 @@ hk_deserialize_api_shader_impl(struct vk_device *vk_dev, const bool has_local_read = variant_flags2 & 4; const bool has_sample_lr = variant_flags2 & 8; const bool has_preamble_nir = (variant_flags2 & 16) != 0; + const bool has_identity_copy4 = (variant_flags2 & 32) != 0; + const bool has_im2col_vec4 = (variant_flags2 & 64) != 0; /* Graphics, compute, task and mesh stages. */ if (blob->overrun || stage >= MESA_SHADER_MESH_STAGES || (clip_z ? !dev->vk.physical->supported_features.depthClipControl : dev->vk.enabled_features.depthClipControl) || (has_mesh_source && (stage != MESA_SHADER_FRAGMENT || dev->dev.chip != AGX_CHIP_G17P)) || - (variant_flags2 & ~31u) || + (variant_flags2 & ~127u) || + (has_identity_copy4 && stage != MESA_SHADER_COMPUTE) || + (has_im2col_vec4 && !has_identity_copy4) || (has_fbl_source && stage != MESA_SHADER_FRAGMENT) || (has_byte_stencil && stage != MESA_SHADER_COMPUTE) || (has_local_read && (stage != MESA_SHADER_FRAGMENT || @@ -10060,6 +10290,9 @@ hk_deserialize_api_shader_impl(struct vk_device *vk_dev, !p_atomic_read(&hk_device_physical(dev)->border_emulation)) return VK_ERROR_INCOMPATIBLE_SHADER_BINARY_EXT; + if (cache_candidate && has_identity_copy4) + return VK_NOT_READY; + const unsigned sample_variant_count = sample_variants ? (m5_sample_variants ? 4 : 3) : 0; size_t size = hk_api_shader_size(stage, sample_variant_count); @@ -10074,6 +10307,14 @@ hk_deserialize_api_shader_impl(struct vk_device *vk_dev, obj->border_emulating = border_emulating; obj->clip_m1_1 = clip_z; + if (has_identity_copy4) { + hk_identity_copy4_deserialize(blob, &obj->identity_copy4_info); + if (blob->overrun || !hk_identity_copy4_supported_local(obj->identity_copy4_info.local)) { + hk_api_shader_destroy(&dev->vk, &obj->vk, pAllocator); + return vk_error(dev, VK_ERROR_INCOMPATIBLE_SHADER_BINARY_EXT); + } + } + hk_foreach_variant(obj, shader) { VkResult result; const uint8_t marker = blob_read_uint8(blob); @@ -10092,6 +10333,24 @@ hk_deserialize_api_shader_impl(struct vk_device *vk_dev, } } + if (has_identity_copy4) { + VkResult result = hk_deserialize_optional_compute_alt( + dev, blob, &obj->identity_copy4); + if (result != VK_SUCCESS) { + hk_api_shader_destroy(&dev->vk, &obj->vk, pAllocator); + return result; + } + } + + if (has_im2col_vec4) { + VkResult result = hk_deserialize_optional_compute_alt( + dev, blob, &obj->im2col_vec4); + if (result != VK_SUCCESS) { + hk_api_shader_destroy(&dev->vk, &obj->vk, pAllocator); + return result; + } + } + /* Restore what the compile set on the composed passthrough object. */ if (stage == MESA_SHADER_MESH && agx_chip_g17_m5(dev->dev.chip)) { struct hk_shader *object = &obj->variants[HK_MESH_VARIANT_RAST]; @@ -10668,7 +10927,11 @@ hk_api_shader_serialize(struct vk_device *vk_dev, (obj->byte_stencil ? 2 : 0) | (local_read ? 4 : 0) | (sample_lr ? 8 : 0) | - (preamble_nir ? 16 : 0)); + (preamble_nir ? 16 : 0) | + (obj->identity_copy4 ? 32 : 0) | + (obj->im2col_vec4 ? 64 : 0)); + if (obj->identity_copy4) + hk_identity_copy4_serialize(blob, &obj->identity_copy4_info); hk_foreach_variant(obj, shader) { const unsigned i = shader - obj->variants; @@ -10719,6 +10982,30 @@ hk_api_shader_serialize(struct vk_device *vk_dev, } } + if (obj->identity_copy4) { + struct blob alternate; + blob_init(&alternate); + hk_shader_serialize(vk_dev, obj->identity_copy4, &alternate); + const bool encoded = !alternate.out_of_memory && alternate.size <= UINT32_MAX && + blob_write_uint32(blob, alternate.size) && + blob_write_bytes(blob, alternate.data, alternate.size); + blob_finish(&alternate); + if (!encoded) + return false; + } + + if (obj->im2col_vec4) { + struct blob alternate; + blob_init(&alternate); + hk_shader_serialize(vk_dev, obj->im2col_vec4, &alternate); + const bool encoded = !alternate.out_of_memory && alternate.size <= UINT32_MAX && + blob_write_uint32(blob, alternate.size) && + blob_write_bytes(blob, alternate.data, alternate.size); + blob_finish(&alternate); + if (!encoded) + return false; + } + /* A shader compiled without custom-border emulation keeps what its * emulating twin compiles from, a G17P fragment shader compiled without * its mesh shader what its mesh twins compile from, and a fragment shader diff --git a/src/asahi/vulkan/hk_shader.h b/src/asahi/vulkan/hk_shader.h index fed9d69cce4e..afbb31e1a1d1 100644 --- a/src/asahi/vulkan/hk_shader.h +++ b/src/asahi/vulkan/hk_shader.h @@ -20,6 +20,7 @@ #include "hk_device.h" #include "hk_device_memory.h" +#include "hk_identity_copy4.h" #include "hk_private.h" #include "hk_nir_lower_mesh.h" @@ -516,6 +517,12 @@ struct hk_api_shader { * code/data from the device's bounded binary cache. */ struct hk_shader_binary_cache_entry *binary_cache_entry; + /* Optional compile-time packed vec4 alternates for eligible AGX3 compute + * shaders. */ + struct hk_shader *identity_copy4; + struct hk_shader *im2col_vec4; + struct hk_identity_copy4 identity_copy4_info; + /* Is this an internal passthrough geometry shader? */ bool is_passthrough; diff --git a/src/asahi/vulkan/meson.build b/src/asahi/vulkan/meson.build index 5be3855649c3..b88149a47878 100644 --- a/src/asahi/vulkan/meson.build +++ b/src/asahi/vulkan/meson.build @@ -63,7 +63,9 @@ hk_files = files( 'hk_image.h', 'hk_image_layout_core.c', 'hk_image_layout_core.h', + 'hk_identity_copy4.h', 'hk_image_view.c', + 'hk_nir_copy_identity4.c', 'hk_image_view.h', 'hk_instance.c', 'hk_instance.h', @@ -1497,3 +1499,14 @@ if with_tests '-Wl,--wrap=os_get_total_physical_memory']), timeout : 30, suite : ['asahi']) endif + +if with_tests + test('hk_identity_copy4', executable('hk_identity_copy4_test', + files('tests/test-hk-identity-copy4.c', 'hk_nir_copy_identity4.c'), + include_directories : [include_directories('.'), inc_gallium, inc_gallium_aux, + inc_include, inc_src, inc_asahi], + dependencies : [idep_nir, idep_mesautil, idep_libagx, dep_m], + link_with : [libasahi_compiler], + link_args : [ld_args_gc_sections]), + timeout : 30, suite : ['asahi']) +endif diff --git a/src/asahi/vulkan/tests/hk_nir_eval_test.h b/src/asahi/vulkan/tests/hk_nir_eval_test.h new file mode 100644 index 000000000000..a620b8989e59 --- /dev/null +++ b/src/asahi/vulkan/tests/hk_nir_eval_test.h @@ -0,0 +1,644 @@ +/* + * Copyright 2026 Aurora Silicon + * SPDX-License-Identifier: MIT + */ +#ifndef HK_NIR_EVAL_TEST_H +#define HK_NIR_EVAL_TEST_H + +#include +#include + +#define HK_EVAL_CHECK(cond) \ + do { \ + if (!(cond)) { \ + fprintf(stderr, "%s:%d: check failed: %s\n", __FILE__, __LINE__, \ + #cond); \ + abort(); \ + } \ + } while (0) +#include +#include +#include +#include +#include + +#include "compiler/glsl_types.h" +#include "compiler/nir/nir.h" + +struct hk_eval_ssbo { + unsigned set; + unsigned binding; + void *data; + size_t size; +}; + +struct hk_eval_env { + const struct hk_eval_ssbo *ssbos; + unsigned num_ssbos; + const void *push; + size_t push_size; + uint32_t wg_id[3]; + uint32_t lid[3]; + uint32_t gid[3]; + uint32_t base_wg[3]; + uint64_t (*ssa)[4]; + unsigned num_ssa; +}; + +static inline float +hk_eval_u2f(uint32_t u) +{ + float f; + memcpy(&f, &u, sizeof(f)); + return f; +} + +static inline uint32_t +hk_eval_f2u(float f) +{ + uint32_t u; + memcpy(&u, &f, sizeof(u)); + return u; +} + +static inline uint64_t +hk_eval_read_ssa(const struct hk_eval_env *env, nir_def *def, unsigned comp) +{ + HK_EVAL_CHECK(def && def->index < env->num_ssa && comp < 4); + return env->ssa[def->index][comp]; +} + +static inline uint64_t +hk_eval_alu_src(const struct hk_eval_env *env, const nir_alu_src *src, + unsigned comp) +{ + return hk_eval_read_ssa(env, src->src.ssa, src->swizzle[comp]); +} + +static inline int +hk_eval_find_ssbo(const struct hk_eval_env *env, unsigned set, unsigned binding) +{ + for (unsigned i = 0; i < env->num_ssbos; ++i) { + if (env->ssbos[i].set == set && env->ssbos[i].binding == binding) + return (int)i; + } + HK_EVAL_CHECK(!"SSBO binding not found in hk_eval_env"); + return -1; +} + +static inline uint64_t +hk_eval_make_vaddr(unsigned ssbo_idx, uint64_t offset) +{ + HK_EVAL_CHECK(offset < (1ull << 40)); + return (((uint64_t)(ssbo_idx + 1)) << 40) | offset; +} + +static inline void +hk_eval_decode_vaddr(const struct hk_eval_env *env, uint64_t addr, + const struct hk_eval_ssbo **buf_out, uint64_t *off_out) +{ + uint64_t tag = addr >> 40; + HK_EVAL_CHECK(tag >= 1 && tag <= env->num_ssbos); + *buf_out = &env->ssbos[tag - 1]; + *off_out = addr & ((1ull << 40) - 1); +} + +static inline uint32_t +hk_eval_type_stride(const struct glsl_type *type) +{ + unsigned exp = glsl_get_explicit_stride(type); + if (exp) + return exp; + if (glsl_type_is_array(type)) { + const struct glsl_type *elem = glsl_get_array_element(type); + return glsl_get_components(elem) * (glsl_get_bit_size(elem) / 8); + } + return glsl_get_components(type) * (glsl_get_bit_size(type) / 8); +} + +static inline void +hk_eval_alu(struct hk_eval_env *env, const nir_alu_instr *alu) +{ + const unsigned comps = alu->def.num_components; + const unsigned bs = alu->def.bit_size; + uint64_t res[4] = {0}; + + switch (alu->op) { + case nir_op_vec2: + case nir_op_vec3: + case nir_op_vec4: + for (unsigned c = 0; c < comps; ++c) + res[c] = hk_eval_alu_src(env, &alu->src[c], 0); + break; + default: + for (unsigned c = 0; c < comps; ++c) { + uint64_t s0 = nir_op_infos[alu->op].num_inputs > 0 + ? hk_eval_alu_src(env, &alu->src[0], c) + : 0; + uint64_t s1 = nir_op_infos[alu->op].num_inputs > 1 + ? hk_eval_alu_src(env, &alu->src[1], c) + : 0; + uint64_t s2 = nir_op_infos[alu->op].num_inputs > 2 + ? hk_eval_alu_src(env, &alu->src[2], c) + : 0; + uint64_t r = 0; + switch (alu->op) { + case nir_op_mov: + r = s0; + break; + case nir_op_iadd: + r = (bs == 64) ? (s0 + s1) : (uint32_t)((uint32_t)s0 + (uint32_t)s1); + break; + case nir_op_isub: + r = (bs == 64) ? (s0 - s1) : (uint32_t)((uint32_t)s0 - (uint32_t)s1); + break; + case nir_op_imul: + r = (bs == 64) ? (s0 * s1) : (uint32_t)((uint32_t)s0 * (uint32_t)s1); + break; + case nir_op_ineg: + r = (bs == 64) ? (uint64_t)(-(int64_t)s0) + : (uint32_t)(-(int32_t)(uint32_t)s0); + break; + case nir_op_iabs: { + int32_t v = (int32_t)(uint32_t)s0; + r = (uint32_t)(v < 0 ? -v : v); + break; + } + case nir_op_idiv: { + int32_t a = (int32_t)(uint32_t)s0, b = (int32_t)(uint32_t)s1; + HK_EVAL_CHECK(b != 0); + r = (uint32_t)(a / b); + break; + } + case nir_op_udiv: { + uint32_t a = (uint32_t)s0, b = (uint32_t)s1; + HK_EVAL_CHECK(b != 0); + r = a / b; + break; + } + case nir_op_irem: { + int32_t a = (int32_t)(uint32_t)s0, b = (int32_t)(uint32_t)s1; + HK_EVAL_CHECK(b != 0); + r = (uint32_t)(a % b); + break; + } + case nir_op_imod: { + int32_t a = (int32_t)(uint32_t)s0, b = (int32_t)(uint32_t)s1; + HK_EVAL_CHECK(b != 0); + int32_t rem = a % b; + if (rem != 0 && ((rem < 0) != (b < 0))) + rem += b; + r = (uint32_t)rem; + break; + } + case nir_op_umod: { + uint32_t a = (uint32_t)s0, b = (uint32_t)s1; + HK_EVAL_CHECK(b != 0); + r = a % b; + break; + } + case nir_op_ishl: + r = (bs == 64) ? (s0 << (s1 & 63)) : (uint32_t)((uint32_t)s0 << (s1 & 31)); + break; + case nir_op_ishr: + r = (bs == 64) ? (uint64_t)((int64_t)s0 >> (s1 & 63)) + : (uint32_t)((int32_t)(uint32_t)s0 >> (s1 & 31)); + break; + case nir_op_ushr: + r = (bs == 64) ? (s0 >> (s1 & 63)) : ((uint32_t)s0 >> (s1 & 31)); + break; + case nir_op_iand: + r = (bs == 1) ? ((s0 & 1) & (s1 & 1)) : (s0 & s1); + break; + case nir_op_ior: + r = (bs == 1) ? ((s0 & 1) | (s1 & 1)) : (s0 | s1); + break; + case nir_op_ixor: + r = (bs == 1) ? ((s0 & 1) ^ (s1 & 1)) : (s0 ^ s1); + break; + case nir_op_inot: + r = (bs == 1) ? (!(s0 & 1)) : (bs == 64 ? ~s0 : (uint32_t)(~(uint32_t)s0)); + break; + case nir_op_ieq: + r = (alu->src[0].src.ssa->bit_size == 64) ? (s0 == s1) + : ((uint32_t)s0 == (uint32_t)s1); + break; + case nir_op_ine: + r = (alu->src[0].src.ssa->bit_size == 64) ? (s0 != s1) + : ((uint32_t)s0 != (uint32_t)s1); + break; + case nir_op_ilt: + r = (int32_t)(uint32_t)s0 < (int32_t)(uint32_t)s1; + break; + case nir_op_ige: + r = (int32_t)(uint32_t)s0 >= (int32_t)(uint32_t)s1; + break; + case nir_op_ult: + r = (uint32_t)s0 < (uint32_t)s1; + break; + case nir_op_uge: + r = (uint32_t)s0 >= (uint32_t)s1; + break; + case nir_op_imin: + r = (uint32_t)MIN2((int32_t)(uint32_t)s0, (int32_t)(uint32_t)s1); + break; + case nir_op_imax: + r = (uint32_t)MAX2((int32_t)(uint32_t)s0, (int32_t)(uint32_t)s1); + break; + case nir_op_umin: + r = MIN2((uint32_t)s0, (uint32_t)s1); + break; + case nir_op_umax: + r = MAX2((uint32_t)s0, (uint32_t)s1); + break; + case nir_op_bcsel: + r = (s0 & 1) ? s1 : s2; + break; + case nir_op_b2i32: + r = (s0 & 1) ? 1u : 0u; + break; + case nir_op_u2u64: + r = (uint64_t)(uint32_t)s0; + break; + case nir_op_i2i64: + r = (uint64_t)(int64_t)(int32_t)(uint32_t)s0; + break; + case nir_op_u2u32: + case nir_op_i2i32: + r = (uint32_t)s0; + break; + case nir_op_fadd: + r = hk_eval_f2u(hk_eval_u2f((uint32_t)s0) + hk_eval_u2f((uint32_t)s1)); + break; + case nir_op_fsub: + r = hk_eval_f2u(hk_eval_u2f((uint32_t)s0) - hk_eval_u2f((uint32_t)s1)); + break; + case nir_op_fmul: + r = hk_eval_f2u(hk_eval_u2f((uint32_t)s0) * hk_eval_u2f((uint32_t)s1)); + break; + case nir_op_ffma: + r = hk_eval_f2u(fmaf(hk_eval_u2f((uint32_t)s0), hk_eval_u2f((uint32_t)s1), + hk_eval_u2f((uint32_t)s2))); + break; + case nir_op_fneg: + r = (uint32_t)s0 ^ 0x80000000u; + break; + case nir_op_fabs: + r = (uint32_t)s0 & 0x7fffffffu; + break; + case nir_op_fmin: { + float a = hk_eval_u2f((uint32_t)s0), b = hk_eval_u2f((uint32_t)s1); + r = hk_eval_f2u(fminf(a, b)); + break; + } + case nir_op_fmax: { + float a = hk_eval_u2f((uint32_t)s0), b = hk_eval_u2f((uint32_t)s1); + r = hk_eval_f2u(fmaxf(a, b)); + break; + } + case nir_op_feq: + r = hk_eval_u2f((uint32_t)s0) == hk_eval_u2f((uint32_t)s1); + break; + case nir_op_fneu: + r = hk_eval_u2f((uint32_t)s0) != hk_eval_u2f((uint32_t)s1); + break; + case nir_op_flt: + r = hk_eval_u2f((uint32_t)s0) < hk_eval_u2f((uint32_t)s1); + break; + case nir_op_fge: + r = hk_eval_u2f((uint32_t)s0) >= hk_eval_u2f((uint32_t)s1); + break; + case nir_op_f2i32: + r = (uint32_t)(int32_t)hk_eval_u2f((uint32_t)s0); + break; + case nir_op_f2u32: + r = (uint32_t)hk_eval_u2f((uint32_t)s0); + break; + case nir_op_i2f32: + r = hk_eval_f2u((float)(int32_t)(uint32_t)s0); + break; + case nir_op_u2f32: + r = hk_eval_f2u((float)(uint32_t)s0); + break; + case nir_op_pack_64_2x32_split: + r = ((uint64_t)(uint32_t)s1 << 32) | (uint32_t)s0; + break; + case nir_op_unpack_64_2x32_split_x: + r = (uint32_t)s0; + break; + case nir_op_unpack_64_2x32_split_y: + r = (uint32_t)(s0 >> 32); + break; + default: + fprintf(stderr, "hk_nir_eval_test: unsupported alu op %s\n", + nir_op_infos[alu->op].name); + HK_EVAL_CHECK(!"unsupported alu op"); + } + res[c] = r; + } + break; + } + + for (unsigned c = 0; c < comps; ++c) + env->ssa[alu->def.index][c] = res[c]; +} + +enum hk_eval_flow { + HK_EVAL_FLOW_NORMAL = 0, + HK_EVAL_FLOW_BREAK, + HK_EVAL_FLOW_CONTINUE, + HK_EVAL_FLOW_RETURN, +}; + +static inline enum hk_eval_flow +hk_eval_cf_list(struct hk_eval_env *env, const struct exec_list *list, + nir_block **prev_block); + +static inline enum hk_eval_flow +hk_eval_block(struct hk_eval_env *env, nir_block *block, nir_block **prev_block) +{ + /* Evaluate all phis simultaneously using *prev_block. */ + unsigned phi_count = 0; + nir_foreach_phi(phi, block) + phi_count++; + + uint64_t (*phi_vals)[4] = NULL; + if (phi_count) { + phi_vals = calloc(phi_count, sizeof(*phi_vals)); + HK_EVAL_CHECK(phi_vals && *prev_block); + unsigned idx = 0; + nir_foreach_phi(phi, block) { + nir_phi_src *src = nir_phi_get_src_from_block(phi, *prev_block); + HK_EVAL_CHECK(src); + for (unsigned c = 0; c < phi->def.num_components; ++c) + phi_vals[idx][c] = hk_eval_read_ssa(env, src->src.ssa, c); + idx++; + } + idx = 0; + nir_foreach_phi(phi, block) { + for (unsigned c = 0; c < phi->def.num_components; ++c) + env->ssa[phi->def.index][c] = phi_vals[idx][c]; + idx++; + } + free(phi_vals); + } + + enum hk_eval_flow flow = HK_EVAL_FLOW_NORMAL; + nir_foreach_instr(instr, block) { + switch (instr->type) { + case nir_instr_type_phi: + break; + case nir_instr_type_load_const: { + nir_load_const_instr *lc = nir_instr_as_load_const(instr); + for (unsigned c = 0; c < lc->def.num_components; ++c) { + if (lc->def.bit_size == 1) + env->ssa[lc->def.index][c] = lc->value[c].b ? 1 : 0; + else if (lc->def.bit_size == 64) + env->ssa[lc->def.index][c] = lc->value[c].u64; + else + env->ssa[lc->def.index][c] = lc->value[c].u32; + } + break; + } + case nir_instr_type_undef: { + nir_undef_instr *u = nir_instr_as_undef(instr); + for (unsigned c = 0; c < u->def.num_components; ++c) + env->ssa[u->def.index][c] = 0; + break; + } + case nir_instr_type_alu: + hk_eval_alu(env, nir_instr_as_alu(instr)); + break; + case nir_instr_type_deref: { + nir_deref_instr *d = nir_instr_as_deref(instr); + uint64_t addr = 0; + switch (d->deref_type) { + case nir_deref_type_cast: { + uint64_t parent = hk_eval_read_ssa(env, d->parent.ssa, 0); + if (parent >> 40) { + addr = parent; + } else { + unsigned set = (unsigned)(parent >> 16); + unsigned binding = (unsigned)(parent & 0xffffu); + int idx = hk_eval_find_ssbo(env, set, binding); + addr = hk_eval_make_vaddr((unsigned)idx, 0); + } + break; + } + case nir_deref_type_struct: { + nir_deref_instr *parent = nir_deref_instr_parent(d); + uint64_t base = hk_eval_read_ssa(env, d->parent.ssa, 0); + int off = glsl_get_struct_field_offset(parent->type, d->strct.index); + addr = base + (uint64_t)(off > 0 ? off : 0); + break; + } + case nir_deref_type_array: { + nir_deref_instr *parent = nir_deref_instr_parent(d); + uint64_t base = hk_eval_read_ssa(env, d->parent.ssa, 0); + int64_t idx = (int64_t)(int32_t)(uint32_t)hk_eval_read_ssa(env, d->arr.index.ssa, 0); + uint32_t stride = hk_eval_type_stride(parent->type); + HK_EVAL_CHECK(idx >= 0); + addr = base + (uint64_t)idx * stride; + break; + } + default: + HK_EVAL_CHECK(!"unsupported deref type"); + } + env->ssa[d->def.index][0] = addr; + break; + } + case nir_instr_type_intrinsic: { + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); + switch (intr->intrinsic) { + case nir_intrinsic_load_global_invocation_id: + for (unsigned c = 0; c < 3; ++c) + env->ssa[intr->def.index][c] = env->gid[c]; + break; + case nir_intrinsic_load_workgroup_id: + for (unsigned c = 0; c < 3; ++c) + env->ssa[intr->def.index][c] = env->wg_id[c]; + break; + case nir_intrinsic_load_local_invocation_id: + for (unsigned c = 0; c < 3; ++c) + env->ssa[intr->def.index][c] = env->lid[c]; + break; + case nir_intrinsic_load_base_workgroup_id: + for (unsigned c = 0; c < 3; ++c) + env->ssa[intr->def.index][c] = env->base_wg[c]; + break; + case nir_intrinsic_load_push_constant: { + uint64_t off = nir_intrinsic_base(intr) + + (uint32_t)hk_eval_read_ssa(env, intr->src[0].ssa, 0); + const unsigned nbytes = intr->def.bit_size / 8; + for (unsigned c = 0; c < intr->def.num_components; ++c) { + uint64_t p = off + (uint64_t)c * nbytes; + HK_EVAL_CHECK(p + nbytes <= env->push_size); + uint32_t v = 0; + memcpy(&v, (const uint8_t *)env->push + p, nbytes); + env->ssa[intr->def.index][c] = v; + } + break; + } + case nir_intrinsic_vulkan_resource_index: { + uint64_t key = ((uint64_t)nir_intrinsic_desc_set(intr) << 16) | + nir_intrinsic_binding(intr); + for (unsigned c = 0; c < intr->def.num_components; ++c) + env->ssa[intr->def.index][c] = key; + break; + } + case nir_intrinsic_load_vulkan_descriptor: + for (unsigned c = 0; c < intr->def.num_components; ++c) + env->ssa[intr->def.index][c] = hk_eval_read_ssa(env, intr->src[0].ssa, c); + break; + case nir_intrinsic_deref_buffer_address: + env->ssa[intr->def.index][0] = hk_eval_read_ssa(env, intr->src[0].ssa, 0); + break; + case nir_intrinsic_load_deref: + case nir_intrinsic_load_global: { + uint64_t vaddr = hk_eval_read_ssa(env, intr->src[0].ssa, 0); + const struct hk_eval_ssbo *buf = NULL; + uint64_t off = 0; + hk_eval_decode_vaddr(env, vaddr, &buf, &off); + const unsigned nbytes = intr->def.bit_size / 8; + for (unsigned c = 0; c < intr->def.num_components; ++c) { + uint64_t p = off + (uint64_t)c * nbytes; + HK_EVAL_CHECK(p + nbytes <= buf->size); + uint32_t v = 0; + memcpy(&v, (const uint8_t *)buf->data + p, nbytes); + env->ssa[intr->def.index][c] = v; + } + break; + } + case nir_intrinsic_store_deref: + case nir_intrinsic_store_global: { + const bool is_deref = intr->intrinsic == nir_intrinsic_store_deref; + uint64_t vaddr = hk_eval_read_ssa(env, intr->src[is_deref ? 0 : 1].ssa, 0); + nir_def *val = intr->src[is_deref ? 1 : 0].ssa; + const struct hk_eval_ssbo *buf = NULL; + uint64_t off = 0; + hk_eval_decode_vaddr(env, vaddr, &buf, &off); + const unsigned nbytes = val->bit_size / 8; + const unsigned wmask = nir_intrinsic_write_mask(intr); + for (unsigned c = 0; c < val->num_components; ++c) { + if (!(wmask & (1u << c))) + continue; + uint64_t p = off + (uint64_t)c * nbytes; + HK_EVAL_CHECK(p + nbytes <= buf->size); + uint32_t v = (uint32_t)hk_eval_read_ssa(env, val, c); + memcpy((uint8_t *)buf->data + p, &v, nbytes); + } + break; + } + default: + fprintf(stderr, "hk_nir_eval_test: unsupported intrinsic %s\n", + nir_intrinsic_infos[intr->intrinsic].name); + HK_EVAL_CHECK(!"unsupported intrinsic"); + } + break; + } + case nir_instr_type_jump: { + nir_jump_instr *j = nir_instr_as_jump(instr); + if (j->type == nir_jump_break) + flow = HK_EVAL_FLOW_BREAK; + else if (j->type == nir_jump_continue) + flow = HK_EVAL_FLOW_CONTINUE; + else if (j->type == nir_jump_return) + flow = HK_EVAL_FLOW_RETURN; + break; + } + default: + HK_EVAL_CHECK(!"unsupported instr type"); + } + if (flow != HK_EVAL_FLOW_NORMAL) + break; + } + + *prev_block = block; + return flow; +} + +static inline enum hk_eval_flow +hk_eval_cf_list(struct hk_eval_env *env, const struct exec_list *list, + nir_block **prev_block) +{ + foreach_list_typed(nir_cf_node, cf, node, list) { + if (cf->type == nir_cf_node_block) { + enum hk_eval_flow f = + hk_eval_block(env, nir_cf_node_as_block(cf), prev_block); + if (f != HK_EVAL_FLOW_NORMAL) + return f; + } else if (cf->type == nir_cf_node_if) { + nir_if *nif = nir_cf_node_as_if(cf); + bool cond = (hk_eval_read_ssa(env, nif->condition.ssa, 0) & 1) != 0; + enum hk_eval_flow f = hk_eval_cf_list( + env, cond ? &nif->then_list : &nif->else_list, prev_block); + if (f != HK_EVAL_FLOW_NORMAL) + return f; + } else if (cf->type == nir_cf_node_loop) { + nir_loop *loop = nir_cf_node_as_loop(cf); + unsigned iters = 0; + for (;;) { + HK_EVAL_CHECK(++iters < 100000); + enum hk_eval_flow f = hk_eval_cf_list(env, &loop->body, prev_block); + if (f == HK_EVAL_FLOW_BREAK) + break; + if (f == HK_EVAL_FLOW_RETURN) + return f; + } + } else { + HK_EVAL_CHECK(!"unsupported cf node"); + } + } + return HK_EVAL_FLOW_NORMAL; +} + +static inline void +hk_eval_dispatch(nir_shader *nir, const uint32_t grid[3], + const struct hk_eval_ssbo *ssbos, unsigned num_ssbos, + const void *push, size_t push_size) +{ + nir_function_impl *impl = nir_shader_get_entrypoint(nir); + nir_index_ssa_defs(impl); + uint64_t (*ssa)[4] = calloc(impl->ssa_alloc + 1, sizeof(*ssa)); + HK_EVAL_CHECK(ssa); + + const uint32_t lx = nir->info.workgroup_size[0]; + const uint32_t ly = nir->info.workgroup_size[1]; + const uint32_t lz = nir->info.workgroup_size[2]; + + struct hk_eval_env env = { + .ssbos = ssbos, + .num_ssbos = num_ssbos, + .push = push, + .push_size = push_size, + .ssa = ssa, + .num_ssa = impl->ssa_alloc + 1, + }; + + for (uint32_t wz = 0; wz < grid[2]; ++wz) { + for (uint32_t wy = 0; wy < grid[1]; ++wy) { + for (uint32_t wx = 0; wx < grid[0]; ++wx) { + for (uint32_t tz = 0; tz < lz; ++tz) { + for (uint32_t ty = 0; ty < ly; ++ty) { + for (uint32_t tx = 0; tx < lx; ++tx) { + env.wg_id[0] = wx; + env.wg_id[1] = wy; + env.wg_id[2] = wz; + env.lid[0] = tx; + env.lid[1] = ty; + env.lid[2] = tz; + env.gid[0] = wx * lx + tx; + env.gid[1] = wy * ly + ty; + env.gid[2] = wz * lz + tz; + nir_block *prev = NULL; + hk_eval_cf_list(&env, &impl->body, &prev); + } + } + } + } + } + } + free(ssa); +} + +#endif diff --git a/src/asahi/vulkan/tests/test-hk-execution-allowance.c b/src/asahi/vulkan/tests/test-hk-execution-allowance.c index eeb474675469..836c8f5901f9 100644 --- a/src/asahi/vulkan/tests/test-hk-execution-allowance.c +++ b/src/asahi/vulkan/tests/test-hk-execution-allowance.c @@ -221,7 +221,7 @@ int main(void) for (enum agx_chip chip = AGX_CHIP_G13G; chip < AGX_CHIP_UNKNOWN; ++chip) assert(hk_shader_binary_version(chip) == (chip == AGX_CHIP_G17P || chip == AGX_CHIP_G17G || - chip == AGX_CHIP_G17S || chip == AGX_CHIP_G17C ? 48 : + chip == AGX_CHIP_G17S || chip == AGX_CHIP_G17C ? 49 : chip <= AGX_CHIP_G15P ? 38 : 37)); assert(hk_as_build_flags(AGX_CHIP_G17P, 0, true) == 0); assert(hk_as_build_flags(AGX_CHIP_G17P, DRM_ASAHI_FEATURE_RENDER_RAY_QUERY, true) == 0); diff --git a/src/asahi/vulkan/tests/test-hk-identity-copy4.c b/src/asahi/vulkan/tests/test-hk-identity-copy4.c new file mode 100644 index 000000000000..bb9163c7c39d --- /dev/null +++ b/src/asahi/vulkan/tests/test-hk-identity-copy4.c @@ -0,0 +1,791 @@ +/* + * Copyright 2026 Aurora Silicon + * SPDX-License-Identifier: MIT + */ + +#include +#include +#include +#include + +#include "asahi/compiler/agx_compile.h" +#include "compiler/glsl_types.h" +#include "compiler/nir/nir.h" +#include "compiler/nir/nir_builder.h" +#include "hk_identity_copy4.h" +#include "hk_nir_eval_test.h" + +static nir_deref_instr * +make_ssbo_elem_deref(nir_builder *b, unsigned set, unsigned binding, + const struct glsl_type *elem_type, bool read_only, + nir_def *index) +{ + const struct glsl_type *arr_type = glsl_array_type(elem_type, 0, 4); + struct glsl_struct_field field = { + .type = arr_type, + .name = "data", + .offset = 0, + }; + const struct glsl_type *block_type = + glsl_interface_type(&field, 1, GLSL_INTERFACE_PACKING_STD430, false, + "Buf"); + + nir_def *idx = nir_vulkan_resource_index( + b, 3, 32, nir_imm_int(b, 0), + .desc_set = set, .binding = binding, + .desc_type = nir_descriptor_type_storage_buffer, + .resource_type = read_only ? nir_resource_type_read_only_storage_buffer + : nir_resource_type_read_write_storage_buffer); + nir_def *desc = nir_load_vulkan_descriptor( + b, 3, 32, idx, .desc_type = nir_descriptor_type_storage_buffer); + nir_deref_instr *root = + nir_build_deref_cast(b, desc, nir_var_mem_ssbo, block_type, 0); + root->cast.align_mul = 4; + root->cast.align_offset = 0; + nir_deref_instr *arr = nir_build_deref_struct(b, root, 0); + nir_deref_instr *elem = nir_build_deref_array(b, arr, index); + elem->arr.in_bounds = true; + return elem; +} + +static nir_def * +load_push_u32(nir_builder *b, uint16_t off, uint16_t range) +{ + return nir_load_push_constant(b, 1, 32, nir_imm_int(b, off), + .base = 0, .range = range, .align_mul = 4); +} + +static nir_def * +build_short_or(nir_builder *b, nir_def *lhs, nir_def *rhs) +{ + nir_def *not_lhs = nir_inot(b, lhs); + nir_if *nif = nir_push_if(b, not_lhs); + nir_push_else(b, nif); + nir_pop_if(b, nif); + return nir_if_phi(b, rhs, lhs); +} + +static nir_def * +build_short_and(nir_builder *b, nir_def *lhs, nir_def *rhs) +{ + nir_if *nif = nir_push_if(b, lhs); + nir_push_else(b, nif); + nir_pop_if(b, nif); + return nir_if_phi(b, rhs, lhs); +} + +static nir_shader * +build_linear_shader(enum hk_identity_copy4_kind kind, + const struct glsl_type *elem_type, + enum gl_access_qualifier load_access, + bool extra_store, bool wrong_cond, + uint16_t count_off, uint16_t src_off, uint16_t dst_off, + uint16_t push_range) +{ + nir_builder b = nir_builder_init_simple_shader( + MESA_SHADER_COMPUTE, &agx_nir_options, "linear_test"); + b.shader->info.workgroup_size[0] = 64; + b.shader->info.workgroup_size[1] = 1; + b.shader->info.workgroup_size[2] = 1; + b.shader->info.num_ssbos = (kind == HK_IDENTITY_COPY4_LINEAR_FADD) ? 3 : 2; + b.shader->num_uniforms = push_range; + + nir_def *gid = nir_channel(&b, nir_load_global_invocation_id(&b, 32), 0); + nir_def *count = load_push_u32(&b, count_off, push_range); + nir_def *cond = wrong_cond ? nir_ult(&b, gid, count) : nir_ilt(&b, gid, count); + nir_if *nif = nir_push_if(&b, cond); + { + nir_def *s_idx = gid; + nir_def *d_idx = gid; + if (kind == HK_IDENTITY_COPY4_LINEAR_OFFSET) { + nir_def *so = load_push_u32(&b, src_off, push_range); + nir_def *doff = load_push_u32(&b, dst_off, push_range); + s_idx = nir_iadd(&b, gid, so); + d_idx = nir_iadd(&b, gid, doff); + } + nir_deref_instr *src0 = + make_ssbo_elem_deref(&b, 0, 0, elem_type, true, s_idx); + nir_def *v = nir_load_deref_with_access(&b, src0, load_access); + if (kind == HK_IDENTITY_COPY4_LINEAR_FADD) { + nir_deref_instr *src1 = + make_ssbo_elem_deref(&b, 0, 1, elem_type, true, s_idx); + nir_def *v1 = nir_load_deref_with_access(&b, src1, load_access); + v = nir_fadd(&b, v, v1); + } + unsigned dst_binding = (kind == HK_IDENTITY_COPY4_LINEAR_FADD) ? 2 : 1; + nir_deref_instr *dst = + make_ssbo_elem_deref(&b, 0, dst_binding, elem_type, false, d_idx); + nir_store_deref_with_access(&b, dst, v, 1, ACCESS_NON_READABLE); + if (extra_store) + nir_store_deref_with_access(&b, dst, v, 1, ACCESS_NON_READABLE); + } + nir_pop_if(&b, nif); + + nir_opt_copy_prop(b.shader); + nir_opt_dce(b.shader); + nir_validate_shader(b.shader, "linear_test"); + return b.shader; +} + +static nir_shader * +build_pad4d_shader(const uint16_t in_off[4], const uint16_t out_off[4], + const uint32_t pad_idx[4], uint16_t push_range, + bool run_defer_preprocess) +{ + nir_builder b = nir_builder_init_simple_shader( + MESA_SHADER_COMPUTE, &agx_nir_options, "pad4d_test"); + b.shader->info.workgroup_size[0] = 16; + b.shader->info.workgroup_size[1] = 16; + b.shader->info.workgroup_size[2] = 1; + b.shader->info.num_ssbos = 3; + b.shader->num_uniforms = push_range; + + nir_def *gid = nir_load_global_invocation_id(&b, 32); + nir_def *gx = nir_channel(&b, gid, 0); + nir_def *gy = nir_channel(&b, gid, 1); + + nir_def *in_s[4], *out_s[4]; + for (unsigned d = 0; d < 4; ++d) { + in_s[d] = load_push_u32(&b, in_off[d], push_range); + out_s[d] = load_push_u32(&b, out_off[d], push_range); + } + + nir_def *x_oob = nir_ige(&b, gx, nir_imul(&b, out_s[2], out_s[3])); + nir_def *y_oob = nir_ige(&b, gy, nir_imul(&b, out_s[0], out_s[1])); + nir_def *oob = build_short_or(&b, x_oob, y_oob); + nir_if *outer = nir_push_if(&b, oob); + nir_push_else(&b, outer); + { + nir_def *c[4]; + c[0] = nir_idiv(&b, gy, out_s[1]); + c[1] = nir_irem(&b, gy, out_s[1]); + c[2] = nir_idiv(&b, gx, out_s[3]); + c[3] = nir_irem(&b, gx, out_s[3]); + + nir_def *p[4]; + for (unsigned d = 0; d < 4; ++d) { + nir_deref_instr *pd = make_ssbo_elem_deref( + &b, 0, 1, glsl_int_type(), true, nir_imm_int(&b, pad_idx[d])); + p[d] = nir_load_deref_with_access( + &b, pd, ACCESS_NON_WRITEABLE | ACCESS_CAN_REORDER); + } + + nir_def *pad_cond = nir_ilt(&b, c[0], p[0]); + for (unsigned d = 1; d < 4; ++d) + pad_cond = build_short_or(&b, pad_cond, nir_ilt(&b, c[d], p[d])); + for (unsigned d = 0; d < 4; ++d) + pad_cond = build_short_or(&b, pad_cond, + nir_ige(&b, nir_isub(&b, c[d], p[d]), in_s[d])); + + nir_def *out_idx = nir_iadd( + &b, + nir_iadd(&b, + nir_iadd(&b, + nir_imul(&b, nir_imul(&b, nir_imul(&b, c[0], out_s[1]), out_s[2]), out_s[3]), + nir_imul(&b, nir_imul(&b, c[1], out_s[2]), out_s[3])), + nir_imul(&b, c[2], out_s[3])), + c[3]); + + nir_if *pif = nir_push_if(&b, pad_cond); + { + nir_deref_instr *dst = + make_ssbo_elem_deref(&b, 0, 2, glsl_float_type(), false, out_idx); + nir_store_deref_with_access(&b, dst, nir_imm_float(&b, 0.0f), 1, + ACCESS_NON_READABLE); + } + nir_push_else(&b, pif); + { + nir_def *ic[4]; + for (unsigned d = 0; d < 4; ++d) + ic[d] = nir_isub(&b, c[d], p[d]); + nir_def *in_idx = nir_iadd( + &b, + nir_iadd(&b, + nir_iadd(&b, + nir_imul(&b, nir_imul(&b, nir_imul(&b, ic[0], in_s[1]), in_s[2]), in_s[3]), + nir_imul(&b, nir_imul(&b, ic[1], in_s[2]), in_s[3])), + nir_imul(&b, ic[2], in_s[3])), + ic[3]); + nir_deref_instr *src = + make_ssbo_elem_deref(&b, 0, 0, glsl_float_type(), true, in_idx); + nir_def *val = nir_load_deref_with_access( + &b, src, ACCESS_NON_WRITEABLE | ACCESS_CAN_REORDER); + nir_deref_instr *dst = + make_ssbo_elem_deref(&b, 0, 2, glsl_float_type(), false, out_idx); + nir_store_deref_with_access(&b, dst, val, 1, ACCESS_NON_READABLE); + } + nir_pop_if(&b, pif); + } + nir_pop_if(&b, outer); + + if (run_defer_preprocess) + agx_preprocess_nir_native_defer_idiv(b.shader, AGX_CHIP_G17P); + else { + nir_opt_copy_prop(b.shader); + nir_opt_dce(b.shader); + } + nir_validate_shader(b.shader, "pad4d_test"); + return b.shader; +} + +struct im2col_layout { + uint16_t bw, bh, iw, ih, kw, pw, ph, sw, sh, ch; + uint16_t push_range; +}; + +static nir_shader * +build_im2col_shader(const struct im2col_layout *l, bool run_defer_preprocess) +{ + nir_builder b = nir_builder_init_simple_shader( + MESA_SHADER_COMPUTE, &agx_nir_options, "im2col_test"); + b.shader->info.workgroup_size[0] = 16; + b.shader->info.workgroup_size[1] = 16; + b.shader->info.workgroup_size[2] = 1; + b.shader->info.num_ssbos = 2; + b.shader->num_uniforms = l->push_range; + + nir_def *gid = nir_load_global_invocation_id(&b, 32); + nir_def *tap = nir_channel(&b, gid, 0); + nir_def *row = nir_channel(&b, gid, 1); + + nir_def *bw = load_push_u32(&b, l->bw, l->push_range); + nir_def *bh = load_push_u32(&b, l->bh, l->push_range); + nir_def *iw = load_push_u32(&b, l->iw, l->push_range); + nir_def *ih = load_push_u32(&b, l->ih, l->push_range); + nir_def *kw = load_push_u32(&b, l->kw, l->push_range); + nir_def *pw = load_push_u32(&b, l->pw, l->push_range); + nir_def *ph = load_push_u32(&b, l->ph, l->push_range); + nir_def *sw = load_push_u32(&b, l->sw, l->push_range); + nir_def *sh = load_push_u32(&b, l->sh, l->push_range); + nir_def *ch = load_push_u32(&b, l->ch, l->push_range); + + nir_def *oob = build_short_or(&b, nir_ige(&b, tap, pw), nir_ige(&b, row, ph)); + nir_if *outer = nir_push_if(&b, oob); + nir_push_else(&b, outer); + { + nir_def *is_unit = build_short_and(&b, nir_ieq_imm(&b, sh, 1), + nir_ieq_imm(&b, sw, 1)); + nir_def *pad_x = nir_imul(&b, bw, ch); + nir_def *one_pad = nir_iadd(&b, iw, pad_x); + nir_def *both_pads = nir_iadd(&b, one_pad, pad_x); + nir_if *iw_if = nir_push_if(&b, is_unit); + nir_push_else(&b, iw_if); + nir_pop_if(&b, iw_if); + nir_def *iw_pad = nir_if_phi(&b, both_pads, one_pad); + + nir_def *diff = nir_isub(&b, nir_idiv(&b, iw_pad, ch), nir_idiv(&b, kw, ch)); + nir_def *cols = nir_iadd_imm(&b, nir_idiv(&b, diff, sw), 1); + + nir_def *x = nir_iadd(&b, nir_imul(&b, nir_imul(&b, nir_irem(&b, row, cols), sw), ch), + nir_irem(&b, tap, kw)); + nir_def *y = nir_iadd(&b, nir_imul(&b, nir_idiv(&b, row, cols), sh), + nir_idiv(&b, tap, kw)); + + nir_def *zero_f = nir_imm_float(&b, 0.0f); + nir_def *unit_val = NULL, *nonunit_val = NULL; + nir_if *uif = nir_push_if(&b, is_unit); + { + nir_def *v = NULL; + nir_if *c0 = nir_push_if(&b, nir_ilt(&b, x, pad_x)); + nir_push_else(&b, c0); + { + nir_if *c1 = nir_push_if(&b, nir_ilt(&b, y, bh)); + nir_push_else(&b, c1); + { + nir_if *c2 = nir_push_if(&b, nir_ige(&b, x, one_pad)); + nir_push_else(&b, c2); + { + nir_if *c3 = nir_push_if(&b, nir_ige(&b, y, nir_iadd(&b, ih, bh))); + nir_push_else(&b, c3); + { + nir_def *s_idx = nir_iadd(&b, nir_imul(&b, nir_isub(&b, y, bh), iw), + nir_isub(&b, x, pad_x)); + nir_deref_instr *src = + make_ssbo_elem_deref(&b, 0, 0, glsl_float_type(), true, s_idx); + v = nir_load_deref_with_access( + &b, src, ACCESS_NON_WRITEABLE | ACCESS_CAN_REORDER); + } + nir_pop_if(&b, c3); + v = nir_if_phi(&b, zero_f, v); + } + nir_pop_if(&b, c2); + v = nir_if_phi(&b, zero_f, v); + } + nir_pop_if(&b, c1); + v = nir_if_phi(&b, zero_f, v); + } + nir_pop_if(&b, c0); + unit_val = nir_if_phi(&b, zero_f, v); + } + nir_push_else(&b, uif); + { + nir_def *oob_nu = build_short_or(&b, nir_ige(&b, x, iw), nir_ige(&b, y, ih)); + nir_def *v = NULL; + nir_if *nu = nir_push_if(&b, oob_nu); + nir_push_else(&b, nu); + { + nir_def *s_idx = nir_iadd(&b, nir_imul(&b, y, iw), x); + nir_deref_instr *src = + make_ssbo_elem_deref(&b, 0, 0, glsl_float_type(), true, s_idx); + v = nir_load_deref_with_access( + &b, src, ACCESS_NON_WRITEABLE | ACCESS_CAN_REORDER); + } + nir_pop_if(&b, nu); + nonunit_val = nir_if_phi(&b, zero_f, v); + } + nir_pop_if(&b, uif); + + nir_def *payload = nir_if_phi(&b, unit_val, nonunit_val); + nir_def *dst_idx = nir_iadd(&b, nir_imul(&b, row, pw), tap); + nir_deref_instr *dst = + make_ssbo_elem_deref(&b, 0, 1, glsl_float_type(), false, dst_idx); + nir_store_deref_with_access(&b, dst, payload, 1, ACCESS_NON_READABLE); + } + nir_pop_if(&b, outer); + + if (run_defer_preprocess) + agx_preprocess_nir_native_defer_idiv(b.shader, AGX_CHIP_G17P); + else { + nir_opt_copy_prop(b.shader); + nir_opt_dce(b.shader); + } + nir_validate_shader(b.shader, "im2col_test"); + return b.shader; +} + +static unsigned +count_vec4_stores(nir_shader *s) +{ + unsigned n = 0; + nir_foreach_function_impl(impl, s) { + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + if (instr->type != nir_instr_type_intrinsic) + continue; + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); + if (intr->intrinsic == nir_intrinsic_store_global && + intr->src[0].ssa->num_components == 4) + n++; + } + } + } + return n; +} + +static void +fill_pattern_u32(uint32_t *buf, unsigned n, uint32_t seed) +{ + /* Include special IEEE-754 bit patterns alongside pseudo-random floats. */ + static const uint32_t specials[] = { + 0x00000000u, /* +0.0 */ + 0x80000000u, /* -0.0 */ + 0x3f800000u, /* 1.0 */ + 0xbf800000u, /* -1.0 */ + 0x7f800000u, /* +Inf */ + 0xff800000u, /* -Inf */ + 0x7fc00001u, /* qNaN */ + 0x00000001u, /* min subnormal */ + }; + for (unsigned i = 0; i < n; ++i) { + if (i < ARRAY_SIZE(specials)) { + buf[i] = specials[(i + seed) % ARRAY_SIZE(specials)]; + } else { + float f = (float)((int)(i * 17 + seed * 31) % 257 - 128) * 0.125f; + memcpy(&buf[i], &f, sizeof(f)); + } + } +} + +static void +test_linear_bit_exact(void) +{ + /* Test both workgroup-aligned (512 vec4 = 2048 elems) and non-aligned tail (540 elems). */ + const uint32_t counts[] = { 16, 540, 2048, 2100 }; + + /* 1. Linear copy (bit-exact including -0.0, NaN, Inf, subnormals). */ + { + nir_shader *orig = build_linear_shader( + HK_IDENTITY_COPY4_LINEAR_COPY, glsl_float_type(), + ACCESS_NON_WRITEABLE, false, false, 0, 0, 0, 4); + struct hk_identity_copy4 info = {0}; + nir_shader *alt = hk_nir_copy_identity4(orig, &info); + HK_EVAL_CHECK(alt != NULL); + nir_validate_shader(alt, "linear_copy alt"); + HK_EVAL_CHECK(info.kind == HK_IDENTITY_COPY4_LINEAR_COPY); + HK_EVAL_CHECK(info.src_count == 1 && info.src_binding == 0 && info.dst_binding == 1); + HK_EVAL_CHECK(info.count_offset == 0); + HK_EVAL_CHECK(alt->info.workgroup_size[0] == 128 && alt->info.workgroup_size[1] == 1); + HK_EVAL_CHECK(count_vec4_stores(alt) == 8); + + for (unsigned ci = 0; ci < ARRAY_SIZE(counts); ++ci) { + const uint32_t count = counts[ci]; + uint32_t *src = calloc(count, sizeof(uint32_t)); + uint32_t *dst_orig = calloc(count, sizeof(uint32_t)); + uint32_t *dst_alt = calloc(count, sizeof(uint32_t)); + fill_pattern_u32(src, count, ci); + memset(dst_orig, 0xa5, count * sizeof(uint32_t)); + memset(dst_alt, 0xa5, count * sizeof(uint32_t)); + + uint32_t push[1] = { count }; + struct hk_eval_ssbo s_orig[2] = { + {0, 0, src, count * 4}, + {0, 1, dst_orig, count * 4}, + }; + struct hk_eval_ssbo s_alt[2] = { + {0, 0, src, count * 4}, + {0, 1, dst_alt, count * 4}, + }; + uint32_t g_orig[3] = { DIV_ROUND_UP(count, 64), 1, 1 }; + uint32_t g_alt[3] = { DIV_ROUND_UP(count / 4, 128 * 4), 1, 1 }; + hk_eval_dispatch(orig, g_orig, s_orig, 2, push, sizeof(push)); + hk_eval_dispatch(alt, g_alt, s_alt, 2, push, sizeof(push)); + HK_EVAL_CHECK(memcmp(dst_orig, dst_alt, count * sizeof(uint32_t)) == 0); + free(src); + free(dst_orig); + free(dst_alt); + } + ralloc_free(alt); + ralloc_free(orig); + } + + /* 2. Linear offset copy with permuted push offsets (push_range = 48). */ + { + nir_shader *orig = build_linear_shader( + HK_IDENTITY_COPY4_LINEAR_OFFSET, glsl_uint_type(), + ACCESS_NON_WRITEABLE | ACCESS_CAN_REORDER, false, false, 36, 20, 8, 48); + struct hk_identity_copy4 info = {0}; + nir_shader *alt = hk_nir_copy_identity4(orig, &info); + HK_EVAL_CHECK(alt != NULL); + nir_validate_shader(alt, "linear_offset alt"); + HK_EVAL_CHECK(info.kind == HK_IDENTITY_COPY4_LINEAR_OFFSET); + HK_EVAL_CHECK(info.count_offset == 36 && info.src_offset_offset == 20 && + info.dst_offset_offset == 8); + + const uint32_t count = 540, so = 16, doff = 24, total = 640; + uint32_t *src = calloc(total, 4); + uint32_t *dst_orig = calloc(total, 4); + uint32_t *dst_alt = calloc(total, 4); + fill_pattern_u32(src, total, 7); + memset(dst_orig, 0x5a, total * 4); + memset(dst_alt, 0x5a, total * 4); + + uint32_t push[12] = {0}; + push[36 / 4] = count; + push[20 / 4] = so; + push[8 / 4] = doff; + struct hk_eval_ssbo s_orig[2] = { {0, 0, src, total * 4}, {0, 1, dst_orig, total * 4} }; + struct hk_eval_ssbo s_alt[2] = { {0, 0, src, total * 4}, {0, 1, dst_alt, total * 4} }; + uint32_t g_orig[3] = { DIV_ROUND_UP(count, 64), 1, 1 }; + uint32_t g_alt[3] = { DIV_ROUND_UP(count / 4, 128 * 4), 1, 1 }; + hk_eval_dispatch(orig, g_orig, s_orig, 2, push, sizeof(push)); + hk_eval_dispatch(alt, g_alt, s_alt, 2, push, sizeof(push)); + HK_EVAL_CHECK(memcmp(dst_orig, dst_alt, total * 4) == 0); + free(src); + free(dst_orig); + free(dst_alt); + ralloc_free(alt); + ralloc_free(orig); + } + + /* 3. Linear FP32 fadd bit-exactness. */ + { + nir_shader *orig = build_linear_shader( + HK_IDENTITY_COPY4_LINEAR_FADD, glsl_float_type(), + ACCESS_NON_WRITEABLE, false, false, 12, 0, 0, 16); + struct hk_identity_copy4 info = {0}; + nir_shader *alt = hk_nir_copy_identity4(orig, &info); + HK_EVAL_CHECK(alt != NULL); + nir_validate_shader(alt, "linear_fadd alt"); + HK_EVAL_CHECK(info.kind == HK_IDENTITY_COPY4_LINEAR_FADD); + HK_EVAL_CHECK(info.count_offset == 12); + + const uint32_t count = 540; + uint32_t *a = calloc(count, 4), *b = calloc(count, 4); + uint32_t *dst_orig = calloc(count, 4), *dst_alt = calloc(count, 4); + fill_pattern_u32(a, count, 1); + fill_pattern_u32(b, count, 3); + uint32_t push[4] = {0, 0, 0, count}; + struct hk_eval_ssbo s_orig[3] = { {0, 0, a, count * 4}, {0, 1, b, count * 4}, {0, 2, dst_orig, count * 4} }; + struct hk_eval_ssbo s_alt[3] = { {0, 0, a, count * 4}, {0, 1, b, count * 4}, {0, 2, dst_alt, count * 4} }; + uint32_t g_orig[3] = { DIV_ROUND_UP(count, 64), 1, 1 }; + uint32_t g_alt[3] = { DIV_ROUND_UP(count / 4, 128 * 4), 1, 1 }; + hk_eval_dispatch(orig, g_orig, s_orig, 3, push, sizeof(push)); + hk_eval_dispatch(alt, g_alt, s_alt, 3, push, sizeof(push)); + HK_EVAL_CHECK(memcmp(dst_orig, dst_alt, count * 4) == 0); + free(a); + free(b); + free(dst_orig); + free(dst_alt); + ralloc_free(alt); + ralloc_free(orig); + } +} + +static void +test_pad4d_bit_exact(void) +{ + /* Permuted push layout (48 bytes) AND preprocessed with agx_preprocess_nir_native_defer_idiv. */ + const uint16_t in_off[4] = { 40, 28, 12, 4 }; + const uint16_t out_off[4] = { 32, 20, 8, 44 }; + const uint32_t pad_idx[4] = { 0, 2, 4, 6 }; + + nir_shader *orig = build_pad4d_shader(in_off, out_off, pad_idx, 48, true); + struct hk_identity_copy4 info = {0}; + nir_shader *alt = hk_nir_copy_identity4(orig, &info); + HK_EVAL_CHECK(alt != NULL); + nir_validate_shader(alt, "pad4d alt"); + HK_EVAL_CHECK(info.kind == HK_IDENTITY_COPY4_PAD4); + for (unsigned d = 0; d < 4; ++d) { + HK_EVAL_CHECK(info.in_shape_off[d] == in_off[d]); + HK_EVAL_CHECK(info.out_shape_off[d] == out_off[d]); + HK_EVAL_CHECK(info.pad_idx[d] == pad_idx[d]); + } + + struct { + int32_t in_s[4]; + int32_t out_s[4]; + int32_t pad[4]; + } cases[] = { + /* out_n == 1, p3 == 0 (fast vec4 path), border & interior */ + { {1, 5, 7, 8}, {1, 7, 9, 8}, {0, 1, 1, 0} }, + /* out_n == 1, p3 == 0, channel zero-pad (out_c > in_c) */ + { {1, 3, 5, 4}, {1, 5, 7, 8}, {0, 1, 1, 0} }, + /* out_n == 2, p3 == 0, non-zero batch pad */ + { {1, 3, 5, 8}, {2, 5, 7, 8}, {1, 1, 2, 0} }, + /* out_n == 2, p3 == 2 (unaligned channel pad slow path!), workgroup edge */ + { {2, 4, 5, 8}, {3, 6, 8, 12}, {1, 1, 1, 2} }, + /* out_n == 1, p3 == 4 (aligned non-zero channel pad) */ + { {1, 3, 4, 8}, {1, 4, 6, 16}, {0, 1, 1, 4} }, + }; + + for (unsigned ci = 0; ci < ARRAY_SIZE(cases); ++ci) { + uint32_t in_n = (uint32_t)(cases[ci].in_s[0] * cases[ci].in_s[1] * + cases[ci].in_s[2] * cases[ci].in_s[3]); + uint32_t out_n = (uint32_t)(cases[ci].out_s[0] * cases[ci].out_s[1] * + cases[ci].out_s[2] * cases[ci].out_s[3]); + uint32_t *in_buf = calloc(in_n, 4); + uint32_t *dst_orig = calloc(out_n, 4); + uint32_t *dst_alt = calloc(out_n, 4); + fill_pattern_u32(in_buf, in_n, 10 + ci); + memset(dst_orig, 0x33, out_n * 4); + memset(dst_alt, 0x33, out_n * 4); + + int32_t pad_buf[8] = {0}; + for (unsigned d = 0; d < 4; ++d) + pad_buf[pad_idx[d]] = cases[ci].pad[d]; + + int32_t push[12] = {0}; + for (unsigned d = 0; d < 4; ++d) { + push[in_off[d] / 4] = cases[ci].in_s[d]; + push[out_off[d] / 4] = cases[ci].out_s[d]; + } + + struct hk_eval_ssbo s_orig[3] = { + {0, 0, in_buf, in_n * 4}, + {0, 1, pad_buf, sizeof(pad_buf)}, + {0, 2, dst_orig, out_n * 4}, + }; + struct hk_eval_ssbo s_alt[3] = { + {0, 0, in_buf, in_n * 4}, + {0, 1, pad_buf, sizeof(pad_buf)}, + {0, 2, dst_alt, out_n * 4}, + }; + + uint32_t orig_x = (uint32_t)(cases[ci].out_s[2] * cases[ci].out_s[3]); + uint32_t orig_y = (uint32_t)(cases[ci].out_s[0] * cases[ci].out_s[1]); + uint32_t g_orig[3] = { DIV_ROUND_UP(orig_x, 16), DIV_ROUND_UP(orig_y, 16), 1 }; + uint32_t g_alt[3] = { + DIV_ROUND_UP(orig_x / 4, alt->info.workgroup_size[0]), + DIV_ROUND_UP(orig_y, alt->info.workgroup_size[1]), + 1, + }; + + hk_eval_dispatch(orig, g_orig, s_orig, 3, push, sizeof(push)); + hk_eval_dispatch(alt, g_alt, s_alt, 3, push, sizeof(push)); + HK_EVAL_CHECK(memcmp(dst_orig, dst_alt, out_n * 4) == 0); + + free(in_buf); + free(dst_orig); + free(dst_alt); + } + + ralloc_free(alt); + ralloc_free(orig); +} + +static void +test_im2col_bit_exact(void) +{ + /* Test BOTH standard 44B layout AND permuted 56B layout with gaps! */ + const struct im2col_layout layouts[] = { + { .bw = 0, .bh = 4, .iw = 8, .ih = 12, .kw = 16, .pw = 24, .ph = 28, .sw = 32, .sh = 36, .ch = 40, .push_range = 44 }, + { .bw = 52, .bh = 44, .iw = 36, .ih = 28, .kw = 24, .pw = 16, .ph = 12, .sw = 8, .sh = 4, .ch = 0, .push_range = 56 }, + }; + + for (unsigned li = 0; li < ARRAY_SIZE(layouts); ++li) { + const struct im2col_layout *l = &layouts[li]; + nir_shader *orig = build_im2col_shader(l, true); + struct hk_identity_copy4 info = {0}; + nir_shader *id_alt = hk_nir_copy_identity4(orig, &info); + HK_EVAL_CHECK(id_alt != NULL); + nir_validate_shader(id_alt, "im2col identity alt"); + HK_EVAL_CHECK(info.kind == HK_IDENTITY_COPY4_IM2COL_1X1); + HK_EVAL_CHECK(info.im2col_vec4_ok); + HK_EVAL_CHECK(info.border_width_offset == l->bw); + HK_EVAL_CHECK(info.border_height_offset == l->bh); + HK_EVAL_CHECK(info.input_width_offset == l->iw); + HK_EVAL_CHECK(info.input_height_offset == l->ih); + HK_EVAL_CHECK(info.kernel_width_offset == l->kw); + HK_EVAL_CHECK(info.patches_width_offset == l->pw); + HK_EVAL_CHECK(info.patches_height_offset == l->ph); + HK_EVAL_CHECK(info.stride_width_offset == l->sw); + HK_EVAL_CHECK(info.stride_height_offset == l->sh); + HK_EVAL_CHECK(info.channels_offset == l->ch); + + nir_shader *vec4_alt = hk_nir_im2col_vec4(orig); + HK_EVAL_CHECK(vec4_alt != NULL); + nir_validate_shader(vec4_alt, "im2col vec4 alt"); + + /* Case A: 1x1 identity copy -> compare orig vs id_alt AND vs vec4_alt. */ + { + const int32_t ch = 8, w = 13, h = 5; + const int32_t iw = w * ch, ih = h, kw = ch, pw = ch, ph = w * h; + uint32_t push[16] = {0}; + push[l->bw / 4] = 0; + push[l->bh / 4] = 0; + push[l->iw / 4] = iw; + push[l->ih / 4] = ih; + push[l->kw / 4] = kw; + push[l->pw / 4] = pw; + push[l->ph / 4] = ph; + push[l->sw / 4] = 1; + push[l->sh / 4] = 1; + push[l->ch / 4] = ch; + + const uint32_t elems = (uint32_t)(pw * ph); + uint32_t *src = calloc(elems, 4); + uint32_t *dst_orig = calloc(elems, 4); + uint32_t *dst_id = calloc(elems, 4); + uint32_t *dst_v4 = calloc(elems, 4); + fill_pattern_u32(src, elems, 20 + li); + + struct hk_eval_ssbo so[2] = { {0, 0, src, elems * 4}, {0, 1, dst_orig, elems * 4} }; + struct hk_eval_ssbo si[2] = { {0, 0, src, elems * 4}, {0, 1, dst_id, elems * 4} }; + struct hk_eval_ssbo sv[2] = { {0, 0, src, elems * 4}, {0, 1, dst_v4, elems * 4} }; + uint32_t go[3] = { DIV_ROUND_UP((uint32_t)pw, 16), DIV_ROUND_UP((uint32_t)ph, 16), 1 }; + uint32_t gi[3] = { DIV_ROUND_UP(elems / 4, 128 * 4), 1, 1 }; + uint32_t gv[3] = { + DIV_ROUND_UP((uint32_t)pw / 4, vec4_alt->info.workgroup_size[0]), + DIV_ROUND_UP((uint32_t)ph, vec4_alt->info.workgroup_size[1]), + 1, + }; + hk_eval_dispatch(orig, go, so, 2, push, l->push_range); + hk_eval_dispatch(id_alt, gi, si, 2, push, l->push_range); + hk_eval_dispatch(vec4_alt, gv, sv, 2, push, l->push_range); + HK_EVAL_CHECK(memcmp(dst_orig, dst_id, elems * 4) == 0); + HK_EVAL_CHECK(memcmp(dst_orig, dst_v4, elems * 4) == 0); + free(src); + free(dst_orig); + free(dst_id); + free(dst_v4); + } + + /* Case B: 3x3 unit-stride padded im2col (border & interior, workgroup edge). */ + /* Case C: 3x3 stride-2 non-unit im2col (border & interior, workgroup edge). */ + struct { + int32_t bw, bh, w, h, kdim, sw, sh, ch; + } icases[] = { + { 1, 1, 7, 5, 3, 1, 1, 8 }, + { 1, 1, 9, 7, 3, 2, 2, 8 }, + { 2, 1, 6, 5, 5, 1, 1, 4 }, + }; + for (unsigned ci = 0; ci < ARRAY_SIZE(icases); ++ci) { + const int32_t bw = icases[ci].bw, bh = icases[ci].bh; + const int32_t ch = icases[ci].ch; + const int32_t iw = icases[ci].w * ch, ih = icases[ci].h; + const int32_t kw = icases[ci].kdim * ch; + const int32_t pw = kw * icases[ci].kdim; + const int32_t sw = icases[ci].sw, sh = icases[ci].sh; + const bool unit = (sw == 1 && sh == 1); + const int32_t cols = ((iw + (unit ? 2 : 1) * bw * ch) / ch - kw / ch) / sw + 1; + const int32_t rows = ((ih + (unit ? 2 : 1) * bh) - icases[ci].kdim) / sh + 1; + const int32_t ph = cols * rows; + + uint32_t push[16] = {0}; + push[l->bw / 4] = bw; + push[l->bh / 4] = bh; + push[l->iw / 4] = iw; + push[l->ih / 4] = ih; + push[l->kw / 4] = kw; + push[l->pw / 4] = pw; + push[l->ph / 4] = ph; + push[l->sw / 4] = sw; + push[l->sh / 4] = sh; + push[l->ch / 4] = ch; + + const uint32_t src_elems = (uint32_t)(iw * ih); + const uint32_t dst_elems = (uint32_t)(pw * ph); + uint32_t *src = calloc(src_elems, 4); + uint32_t *dst_orig = calloc(dst_elems, 4); + uint32_t *dst_v4 = calloc(dst_elems, 4); + fill_pattern_u32(src, src_elems, 40 + li * 10 + ci); + memset(dst_orig, 0x77, dst_elems * 4); + memset(dst_v4, 0x77, dst_elems * 4); + + struct hk_eval_ssbo so[2] = { {0, 0, src, src_elems * 4}, {0, 1, dst_orig, dst_elems * 4} }; + struct hk_eval_ssbo sv[2] = { {0, 0, src, src_elems * 4}, {0, 1, dst_v4, dst_elems * 4} }; + uint32_t go[3] = { DIV_ROUND_UP((uint32_t)pw, 16), DIV_ROUND_UP((uint32_t)ph, 16), 1 }; + uint32_t gv[3] = { + DIV_ROUND_UP((uint32_t)pw / 4, vec4_alt->info.workgroup_size[0]), + DIV_ROUND_UP((uint32_t)ph, vec4_alt->info.workgroup_size[1]), + 1, + }; + hk_eval_dispatch(orig, go, so, 2, push, l->push_range); + hk_eval_dispatch(vec4_alt, gv, sv, 2, push, l->push_range); + HK_EVAL_CHECK(memcmp(dst_orig, dst_v4, dst_elems * 4) == 0); + free(src); + free(dst_orig); + free(dst_v4); + } + + ralloc_free(vec4_alt); + ralloc_free(id_alt); + ralloc_free(orig); + } +} + +int +main(void) +{ + glsl_type_singleton_init_or_ref(); + + test_linear_bit_exact(); + test_pad4d_bit_exact(); + test_im2col_bit_exact(); + + /* Negative: writable source load, extra store, or unsigned guard must reject. */ + { + struct hk_identity_copy4 info = {0}; + nir_shader *s1 = build_linear_shader( + HK_IDENTITY_COPY4_LINEAR_COPY, glsl_float_type(), + (enum gl_access_qualifier)0, false, false, 0, 0, 0, 12); + HK_EVAL_CHECK(hk_nir_copy_identity4(s1, &info) == NULL); + ralloc_free(s1); + + nir_shader *s2 = build_linear_shader( + HK_IDENTITY_COPY4_LINEAR_COPY, glsl_float_type(), + ACCESS_NON_WRITEABLE, true, false, 0, 0, 0, 12); + HK_EVAL_CHECK(hk_nir_copy_identity4(s2, &info) == NULL); + ralloc_free(s2); + + nir_shader *s3 = build_linear_shader( + HK_IDENTITY_COPY4_LINEAR_COPY, glsl_float_type(), + ACCESS_NON_WRITEABLE, false, true, 0, 0, 0, 12); + HK_EVAL_CHECK(hk_nir_copy_identity4(s3, &info) == NULL); + ralloc_free(s3); + } + + glsl_type_singleton_decref(); + printf("test-hk-identity-copy4: PASS\n"); + return 0; +}