Debian Codegraph @

src/asahi/vulkan/hk_shader.c

raw
1 /*
2 * Copyright 2024 Valve Corporation
3 * Copyright 2024 Alyssa Rosenzweig
4 * Copyright 2022-2023 Collabora Ltd. and Red Hat Inc.
5 * Copyright 2023 Advanced Micro Devices, Inc.
6 * Copyright 2018 Intel Corporation
7 * SPDX-License-Identifier: MIT
8 */
9 #include "hk_shader.h"
10
11 #include "poly/nir/poly_nir.h"
12 #include "agx_debug.h"
13 #include "agx_device.h"
14 #include "agx_helpers.h"
15 #include "agx_nir_lower_vbo.h"
16 #include "glsl_types.h"
17 #include "hk_instance.h"
18 #include "libagx.h"
19 #include "nir.h"
20 #include "nir_builder.h"
21
22 #include "agx_bo.h"
23 #include "hk_cmd_buffer.h"
24 #include "hk_descriptor_set_layout.h"
25 #include "hk_device.h"
26 #include "hk_physical_device.h"
27 #include "hk_sampler.h"
28 #include "hk_shader.h"
29
30 #include "nir_builder_opcodes.h"
31 #include "nir_builtin_builder.h"
32 #include "nir_intrinsics.h"
33 #include "nir_intrinsics_indices.h"
34 #include "nir_xfb_info.h"
35 #include "shader_enums.h"
36 #include "vk_graphics_state.h"
37 #include "vk_nir_convert_ycbcr.h"
38 #include "vk_physical_device_features.h"
39 #include "vk_pipeline.h"
40 #include "vk_pipeline_layout.h"
41 #include "vk_shader.h"
42 #include "vk_shader_module.h"
43 #include "vk_ycbcr_conversion.h"
44
45 #include "asahi/compiler/agx_compile.h"
46 #include "asahi/compiler/agx_nir.h"
47 #include "asahi/compiler/agx_nir_texture.h"
48 #include "asahi/lib/agx_abi.h"
49 #include "asahi/lib/agx_linker.h"
50 #include "asahi/lib/agx_tilebuffer.h"
51 #include "asahi/lib/agx_uvs.h"
52 #include "compiler/spirv/nir_spirv.h"
53
54 #include "util/blob.h"
55 #include "util/hash_table.h"
56 #include "util/macros.h"
57 #include "util/mesa-blake3.h"
58 #include "util/simple_mtx.h"
59 #include "util/u_debug.h"
60 #include "vulkan/vulkan_core.h"
61
62 struct hk_fs_key {
63 bool zs_self_dep;
64
65 /** True if sample shading is forced on via an API knob such as
66 * VkPipelineMultisampleStateCreateInfo::minSampleShading
67 */
68 bool force_sample_shading;
69
70 uint8_t pad[2];
71 };
72 static_assert(sizeof(struct hk_fs_key) == 4, "packed");
73
74 struct hk_vs_key {
75 struct agx_velem_key attribs[32];
76 bool skip_prolog;
77 bool static_strides;
78 bool kill_psiz;
79 bool pad[1];
80 };
81 static_assert(sizeof(struct hk_vs_key) == 260, "packed");
82
83 union hk_key {
84 struct hk_vs_key vs;
85 struct hk_fs_key fs;
86 };
87
88 static void
89 shared_var_info(const struct glsl_type *type, unsigned *size, unsigned *align)
90 {
91 assert(glsl_type_is_vector_or_scalar(type));
92
93 uint32_t comp_size =
94 glsl_type_is_boolean(type) ? 4 : glsl_get_bit_size(type) / 8;
95 unsigned length = glsl_get_vector_elements(type);
96 *size = comp_size * length, *align = comp_size;
97 }
98
99 uint64_t
100 hk_physical_device_compiler_flags(const struct hk_physical_device *pdev)
101 {
102 /* This could be optimized but it doesn't matter */
103 return pdev->dev.debug;
104 }
105
106 const nir_shader_compiler_options *
107 hk_get_nir_options(struct vk_physical_device *vk_pdev, mesa_shader_stage stage,
108 UNUSED const struct vk_pipeline_robustness_state *rs)
109 {
110 return &agx_nir_options;
111 }
112
113 static struct spirv_to_nir_options
114 hk_get_spirv_options(struct vk_physical_device *vk_pdev,
115 UNUSED mesa_shader_stage stage,
116 const struct vk_pipeline_robustness_state *rs)
117 {
118 return (struct spirv_to_nir_options){
119 .ssbo_addr_format = hk_buffer_addr_format(rs->storage_buffers),
120 .phys_ssbo_addr_format = nir_address_format_64bit_global,
121 .ubo_addr_format = hk_buffer_addr_format(rs->uniform_buffers),
122 .shared_addr_format = nir_address_format_32bit_offset,
123 .min_ssbo_alignment = HK_MIN_SSBO_ALIGNMENT,
124 .min_ubo_alignment = HK_MIN_UBO_ALIGNMENT,
125 };
126 }
127
128 void
129 hk_preprocess_nir_internal(struct vk_physical_device *vk_pdev, nir_shader *nir)
130 {
131 /* Must lower before io to temps */
132 if (nir->info.stage == MESA_SHADER_FRAGMENT) {
133 NIR_PASS(_, nir, nir_lower_terminate_to_demote);
134 NIR_PASS(_, nir, nir_lower_halt_to_return);
135 NIR_PASS(_, nir, nir_lower_returns);
136 }
137
138 /* Unroll loops before lowering indirects via
139 * nir_lower_io_vars_to_temporaries */
140 UNUSED bool progress = false;
141 NIR_PASS(_, nir, nir_lower_global_vars_to_local);
142
143 do {
144 progress = false;
145 NIR_PASS(progress, nir, nir_lower_vars_to_ssa);
146 NIR_PASS(progress, nir, nir_opt_copy_prop);
147 NIR_PASS(progress, nir, nir_opt_dce);
148 NIR_PASS(progress, nir, nir_opt_constant_folding);
149 NIR_PASS(progress, nir, nir_opt_loop);
150 NIR_PASS(progress, nir, nir_opt_loop_unroll);
151 } while (progress);
152
153 if (nir->info.stage == MESA_SHADER_FRAGMENT) {
154 struct nir_lower_sysvals_to_varyings_options sysvals_opts = {
155 .point_coord = true,
156 .primitive_id = nir->info.stage == MESA_SHADER_FRAGMENT,
157 };
158
159 nir_lower_sysvals_to_varyings(nir, &sysvals_opts);
160 }
161
162 NIR_PASS(_, nir, nir_lower_system_values);
163
164 /* Gather info before preprocess_nir but after some general lowering, so
165 * inputs_read and system_values_read are accurately set.
166 */
167 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
168
169 NIR_PASS(_, nir, nir_lower_io_vars_to_temporaries,
170 nir_shader_get_entrypoint(nir), nir_var_shader_out);
171
172 NIR_PASS(_, nir, nir_lower_global_vars_to_local);
173
174 NIR_PASS(_, nir, nir_split_var_copies);
175 NIR_PASS(_, nir, nir_split_struct_vars, nir_var_function_temp);
176
177 /* Optimize but allow copies because we haven't lowered them yet */
178 agx_preprocess_nir(nir);
179
180 NIR_PASS(_, nir, nir_lower_load_const_to_scalar);
181 NIR_PASS(_, nir, nir_lower_var_copies);
182 }
183
184 static void
185 hk_preprocess_nir(struct vk_physical_device *vk_pdev, nir_shader *nir,
186 UNUSED const struct vk_pipeline_robustness_state *rs)
187 {
188 hk_preprocess_nir_internal(vk_pdev, nir);
189 nir_lower_compute_system_values_options csv_options = {
190 .has_base_workgroup_id = true,
191 };
192 NIR_PASS(_, nir, nir_lower_compute_system_values, &csv_options);
193 }
194
195 static void
196 hk_populate_vs_key(struct hk_vs_key *key,
197 const struct vk_graphics_pipeline_state *state)
198 {
199 memset(key, 0, sizeof(*key));
200
201 if (state && state->ia &&
202 !BITSET_TEST(state->dynamic, MESA_VK_DYNAMIC_IA_PRIMITIVE_TOPOLOGY)) {
203
204 key->kill_psiz = state->ia->primitive_topology != MESA_PRIM_POINTS;
205 }
206
207 if (state && state->vi && !BITSET_TEST(state->dynamic, MESA_VK_DYNAMIC_VI) &&
208 !BITSET_TEST(state->dynamic, MESA_VK_DYNAMIC_VI_BINDINGS_VALID)) {
209
210 agx_fill_velem_keys(state->vi, ~0 /* compacted on use */, key->attribs);
211 key->skip_prolog = true;
212 key->static_strides =
213 !BITSET_TEST(state->dynamic, MESA_VK_DYNAMIC_VI_BINDING_STRIDES);
214
215 if (!key->static_strides) {
216 for (unsigned i = 0; i < ARRAY_SIZE(key->attribs); ++i) {
217 key->attribs[i].stride = 0;
218 }
219 }
220 }
221 }
222
223 static void
224 hk_populate_fs_key(struct hk_fs_key *key,
225 const struct vk_graphics_pipeline_state *state)
226 {
227 memset(key, 0, sizeof(*key));
228
229 if (state == NULL)
230 return;
231
232 if (state->pipeline_flags &
233 VK_PIPELINE_CREATE_2_DEPTH_STENCIL_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT)
234 key->zs_self_dep = true;
235
236 /* We force per-sample interpolation whenever sampleShadingEnable is set
237 * regardless of minSampleShading or rasterizationSamples.
238 *
239 * When sampleShadingEnable is set, few guarantees are made about the
240 * location of interpolation of the inputs. The only real guarantees are
241 * that the inputs are interpolated within the pixel and that you get at
242 * least `rasterizationSamples * minSampleShading` unique positions.
243 * Importantly, it does not require that when `rasterizationSamples *
244 * minSampleShading <= 1.0` that those positions are at the fragment
245 * center. Therefore, it's valid to just always do per-sample all the time.
246 *
247 * The one caveat here is that we have to be careful about gl_SampleMaskIn.
248 * When `hk_fs_key::force_sample_shading = true` we also turn any reads of
249 * gl_SampleMaskIn into `1 << gl_SampleID` because the hardware sample mask
250 * is actually per-fragment, not per-pass. We handle this by smashing
251 * minSampleShading to 1.0 whenever gl_SampleMaskIn is read.
252 */
253 const struct vk_multisample_state *ms = state->ms;
254 if (ms != NULL && ms->sample_shading_enable)
255 key->force_sample_shading = true;
256 }
257
258 enum hk_feature_key {
259 HK_FEAT_CUSTOM_BORDER = BITFIELD_BIT(0),
260 };
261
262 static enum hk_feature_key
263 hk_make_feature_key(const struct vk_features *feats)
264 {
265 return (!feats || feats->customBorderColors) ? HK_FEAT_CUSTOM_BORDER : 0;
266 }
267
268 static void
269 hk_hash_graphics_state(struct vk_physical_device *device,
270 const struct vk_graphics_pipeline_state *state,
271 const struct vk_features *features,
272 VkShaderStageFlags stages, blake3_hash blake3_out)
273 {
274 struct mesa_blake3 blake3_ctx;
275 _mesa_blake3_init(&blake3_ctx);
276 if (state && (stages & VK_SHADER_STAGE_VERTEX_BIT)) {
277 struct hk_vs_key key;
278 hk_populate_vs_key(&key, state);
279 _mesa_blake3_update(&blake3_ctx, &key, sizeof(key));
280 } else if (state && (stages & VK_SHADER_STAGE_FRAGMENT_BIT)) {
281 struct hk_fs_key key;
282 hk_populate_fs_key(&key, state);
283 _mesa_blake3_update(&blake3_ctx, &key, sizeof(key));
284 }
285
286 if (state &&
287 (stages & (VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT))) {
288 const bool is_multiview = state->mv->view_mask != 0;
289 _mesa_blake3_update(&blake3_ctx, &is_multiview, sizeof(is_multiview));
290 }
291
292 enum hk_feature_key feature_key = hk_make_feature_key(features);
293 _mesa_blake3_update(&blake3_ctx, &feature_key, sizeof(feature_key));
294
295 _mesa_blake3_final(&blake3_ctx, blake3_out);
296 }
297
298 static nir_def *
299 bounds_check(nir_builder *b, nir_def *data, nir_def *offs, nir_def *bound)
300 {
301 if (data->bit_size == 32 && data->num_components == 1) {
302 return nir_bounds_agx(b, data, offs, bound);
303 } else {
304 /* TODO: Optimize */
305 return nir_bcsel(b, nir_uge(b, bound, offs), data,
306 nir_imm_zero(b, data->num_components, data->bit_size));
307 }
308 }
309
310 static bool
311 is_op(nir_scalar s, nir_op op)
312 {
313 return nir_scalar_is_alu(s) && nir_scalar_alu_op(s) == op;
314 }
315
316 static nir_def *
317 check_in_bounds(nir_builder *b, nir_intrinsic_instr *intr)
318 {
319 nir_def *offset = intr->src[1].ssa;
320 nir_def *bound = intr->src[2].ssa;
321
322 unsigned bit_size = intr->def.bit_size;
323 assert(bit_size >= 8 && bit_size % 8 == 0);
324 unsigned byte_size = bit_size / 8;
325 unsigned load_size = byte_size * intr->num_components;
326
327 /* Try to bounds check in terms of elements */
328 nir_scalar offset_s = nir_scalar_resolved(offset, 0);
329 if (is_op(offset_s, nir_op_amul)) {
330 nir_scalar srcs[] = {nir_scalar_chase_alu_src(offset_s, 0),
331 nir_scalar_chase_alu_src(offset_s, 1)};
332 unsigned i = nir_scalar_is_const(srcs[0]) ? 1 : 0;
333 if (nir_scalar_is_const(srcs[1 - i]) &&
334 nir_scalar_as_uint(srcs[1 - i]) == load_size) {
335
336 nir_def *index = nir_mov_scalar(b, srcs[i]);
337 return nir_ult(b, index, nir_udiv_imm(b, bound, load_size));
338 }
339 }
340
341 /* TODO: handle also the iadd(amul) pattern, this is important */
342
343 /* Otherwise bounds check in bytes */
344 nir_def *sat_offset = nir_umin_imm(b, offset, UINT32_MAX - (load_size - 1));
345 return nir_ult(b, nir_iadd_imm(b, sat_offset, load_size - 1), bound);
346 }
347
348 static nir_def *
349 bound_offset(nir_builder *b, nir_def *valid, nir_scalar offset)
350 {
351 /* If we can, clamp the source of an amul instead of the result, to remain
352 * compatible with the hardware address mode.
353 */
354 if (is_op(offset, nir_op_amul)) {
355 nir_scalar srcs[] = {
356 nir_scalar_chase_alu_src(offset, 0),
357 nir_scalar_chase_alu_src(offset, 1),
358 };
359 unsigned i = nir_scalar_is_const(srcs[0]) ? 1 : 0;
360 nir_def *x = nir_mov_scalar(b, srcs[i]);
361 nir_def *y = nir_mov_scalar(b, srcs[1 - i]);
362
363 return nir_amul(b, nir_bcsel(b, valid, x, nir_imm_int(b, 0)), y);
364 }
365
366 /* Similar case for when there's an addition (chain) in the way */
367 if (is_op(offset, nir_op_iadd)) {
368 nir_scalar x = nir_scalar_chase_alu_src(offset, 0);
369 nir_scalar y = nir_scalar_chase_alu_src(offset, 1);
370
371 if (is_op(x, nir_op_amul) || is_op(y, nir_op_amul)) {
372 return nir_iadd(b, bound_offset(b, valid, x),
373 bound_offset(b, valid, y));
374 }
375 }
376
377 nir_def *def = nir_mov_scalar(b, offset);
378
379 /* If the offset fits within the zero page, clamping is pointless */
380 if (nir_scalar_is_const(offset) &&
381 (nir_scalar_as_uint(offset) + 16) < AGX_ZERO_PAGE_SIZE)
382 return def;
383
384 /* Otherwise, fallback on clamping the offset */
385 return nir_bcsel(b, valid, def, nir_imm_int(b, 0));
386 }
387
388 static void
389 lower_load_global_bounded(nir_builder *b, nir_intrinsic_instr *intr)
390 {
391 b->cursor = nir_before_instr(&intr->instr);
392 nir_def *base = intr->src[0].ssa;
393 nir_def *offset = intr->src[1].ssa;
394
395 /* Bounds check compatibly with the hardware address mode */
396 nir_def *valid = check_in_bounds(b, intr);
397 base = nir_bcsel(b, valid, base, nir_imm_int64(b, AGX_ZERO_PAGE_ADDRESS));
398 offset = bound_offset(b, valid, nir_scalar_resolved(offset, 0));
399
400 enum gl_access_qualifier access = nir_intrinsic_access(intr);
401
402 if (intr->intrinsic == nir_intrinsic_load_global_constant_bounded) {
403 access |= ACCESS_NON_WRITEABLE | ACCESS_CAN_REORDER;
404 }
405
406 nir_def *val = nir_load_global(
407 b, intr->def.num_components, intr->def.bit_size,
408 nir_iadd(b, base, nir_u2u64(b, offset)),
409 .align_mul = nir_intrinsic_align_mul(intr),
410 .align_offset = nir_intrinsic_align_offset(intr), .access = access);
411
412 nir_def_replace(&intr->def, val);
413 }
414
415 static bool
416 lower_load_global_constant_offset_instr(nir_builder *b,
417 nir_intrinsic_instr *intrin, void *data)
418 {
419 bool *has_soft_fault = data;
420
421 if (intrin->intrinsic == nir_intrinsic_load_global_bounded ||
422 (intrin->intrinsic == nir_intrinsic_load_global_constant_bounded &&
423 !(*has_soft_fault))) {
424
425 lower_load_global_bounded(b, intrin);
426 return true;
427 }
428
429 if (intrin->intrinsic != nir_intrinsic_load_global_constant_offset &&
430 intrin->intrinsic != nir_intrinsic_load_global_constant_bounded)
431 return false;
432
433 b->cursor = nir_before_instr(&intrin->instr);
434
435 nir_def *base_addr = intrin->src[0].ssa;
436 nir_def *offset = intrin->src[1].ssa;
437 nir_def *bound = NULL;
438
439 unsigned bit_size = intrin->def.bit_size;
440 assert(bit_size >= 8 && bit_size % 8 == 0);
441 unsigned byte_size = bit_size / 8;
442 unsigned load_size = byte_size * intrin->num_components;
443
444 if (intrin->intrinsic == nir_intrinsic_load_global_constant_bounded) {
445 bound = intrin->src[2].ssa;
446 }
447
448 unsigned align_mul = nir_intrinsic_align_mul(intrin);
449 unsigned align_offset = nir_intrinsic_align_offset(intrin);
450
451 nir_def *val = nir_load_global_constant(
452 b, intrin->def.num_components, intrin->def.bit_size,
453 nir_iadd(b, base_addr, nir_u2u64(b, offset)), .align_mul = align_mul,
454 .align_offset = align_offset, .access = nir_intrinsic_access(intrin));
455
456 if (intrin->intrinsic == nir_intrinsic_load_global_constant_bounded) {
457 nir_scalar offs = nir_scalar_resolved(offset, 0);
458 if (nir_scalar_is_const(offs)) {
459 /* Calculate last byte loaded */
460 unsigned offs_imm = nir_scalar_as_uint(offs) + load_size;
461
462 /* Simplify the bounds check. Uniform buffers are bounds checked at
463 * 64B granularity, so `bound` is a multiple of K = 64. Then
464 *
465 * offs_imm < bound <==> round_down(offs_imm, K) < bound. Proof:
466 *
467 * "=>" round_down(offs_imm, K) <= offs_imm < bound.
468 *
469 * "<=" Let a, b be integer s.t. offs_imm = K a + b with b < K.
470 * Note round_down(offs_imm, K) = Ka.
471 *
472 * Let c be integer s.t. bound = Kc.
473 * We have Ka < Kc => a < c.
474 * b < K => Ka + b < K(a + 1).
475 *
476 * a < c with integers => a + 1 <= c.
477 * offs_imm < K(a + 1) <= Kc = bound.
478 * Hence offs_imm < bound.
479 */
480 assert(align_mul == 64);
481 offs_imm &= ~(align_mul - 1);
482
483 /* Bounds checks are `offset > bound ? 0 : val` so if offset = 0,
484 * the bounds check is useless.
485 */
486 if (offs_imm) {
487 val = bounds_check(b, val, nir_imm_int(b, offs_imm), bound);
488 }
489 } else {
490 offset = nir_iadd_imm(b, offset, load_size);
491 val = bounds_check(b, val, offset, bound);
492 }
493 }
494
495 nir_def_replace(&intrin->def, val);
496 return true;
497 }
498
499 struct lower_ycbcr_state {
500 uint32_t set_layout_count;
501 struct vk_descriptor_set_layout *const *set_layouts;
502 };
503
504 static const struct vk_ycbcr_conversion_state *
505 lookup_ycbcr_conversion(const void *_state, uint32_t set, uint32_t binding,
506 uint32_t array_index)
507 {
508 const struct lower_ycbcr_state *state = _state;
509 assert(set < state->set_layout_count);
510 assert(state->set_layouts[set] != NULL);
511 const struct hk_descriptor_set_layout *set_layout =
512 vk_to_hk_descriptor_set_layout(state->set_layouts[set]);
513 assert(binding < set_layout->binding_count);
514
515 const struct hk_descriptor_set_binding_layout *bind_layout =
516 &set_layout->binding[binding];
517
518 if (bind_layout->immutable_samplers == NULL)
519 return NULL;
520
521 array_index = MIN2(array_index, bind_layout->array_size - 1);
522
523 const struct hk_sampler *sampler =
524 bind_layout->immutable_samplers[array_index];
525
526 return sampler && sampler->vk.ycbcr_conversion
527 ? &sampler->vk.ycbcr_conversion->state
528 : NULL;
529 }
530
531 static int
532 glsl_type_size(const struct glsl_type *type, bool bindless)
533 {
534 return glsl_count_attribute_slots(type, false);
535 }
536
537 /*
538 * This is the world's worst multiview implementation. We simply duplicate each
539 * draw on the CPU side, changing a uniform in between, and then plumb the view
540 * index into the layer ID here. Whatever, it works.
541 *
542 * The "proper" implementation on AGX would use vertex amplification, but a
543 * MacBook is not a VR headset.
544 */
545 static void
546 hk_lower_multiview(nir_shader *nir)
547 {
548 /* If there's an existing layer ID write, ignore it. This avoids validation
549 * splat with vk_meta.
550 */
551 nir_variable *existing = nir_find_variable_with_location(
552 nir, nir_var_shader_out, VARYING_SLOT_LAYER);
553
554 if (existing) {
555 existing->data.mode = nir_var_shader_temp;
556 existing->data.location = 0;
557 nir_fixup_deref_modes(nir);
558 }
559
560 /* Now write the view index as the layer */
561 nir_builder b =
562 nir_builder_at(nir_after_impl(nir_shader_get_entrypoint(nir)));
563
564 nir_variable *layer =
565 nir_variable_create(nir, nir_var_shader_out, glsl_uint_type(), NULL);
566
567 layer->data.location = VARYING_SLOT_LAYER;
568
569 nir_store_var(&b, layer, nir_load_view_index(&b), nir_component_mask(1));
570 b.shader->info.outputs_written |= VARYING_BIT_LAYER;
571 }
572
573 static nir_def *
574 query_custom_border(nir_builder *b, nir_tex_instr *tex)
575 {
576 return nir_build_texture_query(b, tex, nir_texop_custom_border_color_agx, 4,
577 tex->dest_type, false, false);
578 }
579
580 static nir_def *
581 has_custom_border(nir_builder *b, nir_tex_instr *tex)
582 {
583 return nir_build_texture_query(b, tex, nir_texop_has_custom_border_color_agx,
584 1, nir_type_bool1, false, false);
585 }
586
587 static bool
588 lower(nir_builder *b, nir_tex_instr *tex, UNUSED void *_data)
589 {
590 if (!nir_tex_instr_need_sampler(tex) || nir_tex_instr_is_query(tex))
591 return false;
592
593 /* XXX: this is a really weird edge case, is this even well-defined? */
594 if (tex->is_shadow)
595 return false;
596
597 b->cursor = nir_after_instr(&tex->instr);
598 nir_def *has_custom = has_custom_border(b, tex);
599
600 nir_instr *orig = nir_instr_clone(b->shader, &tex->instr);
601 nir_builder_instr_insert(b, orig);
602 nir_def *clamp_to_1 = &nir_instr_as_tex(orig)->def;
603
604 nir_push_if(b, has_custom);
605 nir_def *replaced = NULL;
606 {
607 /* Sample again, this time with clamp-to-0 instead of clamp-to-1 */
608 nir_instr *clone_instr = nir_instr_clone(b->shader, &tex->instr);
609 nir_builder_instr_insert(b, clone_instr);
610
611 nir_tex_instr *tex_0 = nir_instr_as_tex(clone_instr);
612 nir_def *clamp_to_0 = &tex_0->def;
613
614 tex_0->backend_flags |= AGX_TEXTURE_FLAG_CLAMP_TO_0;
615
616 /* Grab the border colour */
617 nir_def *border = query_custom_border(b, tex_0);
618
619 if (tex->op == nir_texop_tg4) {
620 border = nir_replicate(b, nir_channel(b, border, tex->component), 4);
621 }
622
623 /* Combine together with the border */
624 if (nir_alu_type_get_base_type(tex->dest_type) == nir_type_float &&
625 tex->op != nir_texop_tg4) {
626
627 /* For floats, lerp together:
628 *
629 * For border texels: (1 * border) + (0 * border ) = border
630 * For regular texels: (x * border) + (x * (1 - border)) = x.
631 *
632 * Linear filtering is linear (duh), so lerping is compatible.
633 */
634 replaced = nir_flrp(b, clamp_to_0, clamp_to_1, border);
635 b->shader->info.flrp_lowered = false;
636 } else {
637 /* For integers, just select componentwise since there is no linear
638 * filtering. Gathers also use this path since they are unfiltered in
639 * each component.
640 */
641 replaced = nir_bcsel(b, nir_ieq(b, clamp_to_0, clamp_to_1), clamp_to_0,
642 border);
643 }
644 }
645 nir_pop_if(b, NULL);
646
647 /* Put it together with a phi */
648 nir_def *phi = nir_if_phi(b, replaced, clamp_to_1);
649 nir_def_replace(&tex->def, phi);
650 return true;
651 }
652
653 static bool
654 agx_nir_lower_custom_border(nir_shader *nir)
655 {
656 return nir_shader_tex_pass(nir, lower, nir_metadata_none, NULL);
657 }
658
659 static nir_def *
660 query_min_lod(nir_builder *b, nir_tex_instr *tex, bool int_coords)
661 {
662 nir_alu_type T = int_coords ? nir_type_uint16 : nir_type_float16;
663 return nir_build_texture_query(b, tex, nir_texop_image_min_lod_agx, 1, T,
664 false, false);
665 }
666
667 static bool
668 lower_min_lod(nir_builder *b, nir_tex_instr *tex, UNUSED void *_data)
669 {
670 if (nir_tex_instr_is_query(tex))
671 return false;
672
673 /* Buffer textures don't have levels-of-detail */
674 if (tex->sampler_dim == GLSL_SAMPLER_DIM_BUF)
675 return false;
676
677 if (tex->backend_flags & AGX_TEXTURE_FLAG_NO_CLAMP)
678 return false;
679
680 bool int_coords = tex->op == nir_texop_txf || tex->op == nir_texop_txf_ms ||
681 tex->op == nir_texop_tg4;
682
683 b->cursor = nir_before_instr(&tex->instr);
684 nir_def *min_lod = query_min_lod(b, tex, int_coords);
685 nir_def *other_min_lod = nir_steal_tex_src(tex, nir_tex_src_min_lod);
686
687 if (tex->op == nir_texop_tg4) {
688 b->cursor = nir_after_instr(&tex->instr);
689
690 /* The Vulkan spec section "Texel Gathering" says:
691 *
692 * If levelbase < minLodIntegerimageView, then any values fetched are
693 * zero if the robustImageAccess2 feature is enabled.
694 *
695 * We currently always enable robustImageAccess2, so implement that
696 * semantic here.
697 *
698 * We could probably optimize this with a special descriptor for this case
699 * but tg4 is rare enough I'm not bothered.
700 */
701 nir_def *old = &tex->def;
702 nir_def *oob = nir_ine_imm(b, min_lod, 0);
703 nir_def *zero = nir_imm_zero(b, old->num_components, old->bit_size);
704 nir_def *new_ = nir_bcsel(b, oob, zero, old);
705 nir_def_rewrite_uses_after(old, new_);
706 } else if (tex->op == nir_texop_txl) {
707 assert(other_min_lod == NULL && "txl doesn't have an API min lod");
708
709 nir_def *lod = nir_steal_tex_src(tex, nir_tex_src_lod);
710 if (lod) {
711 min_lod = nir_fmax(b, nir_f2fN(b, lod, min_lod->bit_size), min_lod);
712 }
713
714 nir_tex_instr_add_src(tex, nir_tex_src_lod, min_lod);
715 } else {
716 if (other_min_lod) {
717 assert(!int_coords && "no API min lod");
718 min_lod = nir_fmax(b, min_lod, nir_f2f16(b, other_min_lod));
719 }
720
721 nir_tex_instr_add_src(tex, nir_tex_src_min_lod, min_lod);
722 }
723
724 return true;
725 }
726
727 static bool
728 agx_nir_lower_image_view_min_lod(nir_shader *nir)
729 {
730 return nir_shader_tex_pass(nir, lower_min_lod, nir_metadata_none, NULL);
731 }
732
733 /*
734 * In Vulkan, the VIEWPORT should read 0 in the fragment shader if it is not
735 * written by the vertex shader, but in our implementation, the varying would
736 * otherwise be undefined. This small pass predicates VIEWPORT reads based on
737 * whether the hardware vertex shader writes the VIEWPORT (nonzero UVS index).
738 */
739 static bool
740 lower_viewport_fs(nir_builder *b, nir_intrinsic_instr *intr, UNUSED void *data)
741 {
742 if (intr->intrinsic != nir_intrinsic_load_input)
743 return false;
744
745 nir_io_semantics sem = nir_intrinsic_io_semantics(intr);
746 if (sem.location != VARYING_SLOT_VIEWPORT)
747 return false;
748
749 b->cursor = nir_after_instr(&intr->instr);
750 nir_def *orig = &intr->def;
751
752 nir_def *uvs = nir_load_uvs_index_agx(b, .io_semantics = sem);
753 nir_def *def = nir_bcsel(b, nir_ine_imm(b, uvs, 0), orig, nir_imm_int(b, 0));
754
755 nir_def_rewrite_uses_after(orig, def);
756 return true;
757 }
758
759 static bool
760 lower_subpass_dim(nir_builder *b, nir_tex_instr *tex, UNUSED void *_data)
761 {
762 if (tex->sampler_dim == GLSL_SAMPLER_DIM_SUBPASS)
763 tex->sampler_dim = GLSL_SAMPLER_DIM_2D;
764 else if (tex->sampler_dim == GLSL_SAMPLER_DIM_SUBPASS_MS)
765 tex->sampler_dim = GLSL_SAMPLER_DIM_MS;
766 else
767 return false;
768
769 return true;
770 }
771
772 static bool
773 should_lower_robust(const nir_intrinsic_instr *intr, const void *_)
774 {
775 /* The hardware is robust, but our software image atomics are not. Unlike the
776 * GL driver, we don't use the common buffer image lowering, using the
777 * agx_nir_lower_texture lowering for robustImageAccess2 semantics.
778 */
779 return intr->intrinsic == nir_intrinsic_image_deref_atomic ||
780 intr->intrinsic == nir_intrinsic_image_deref_atomic_swap;
781 }
782
783 static void
784 hk_lower_nir(struct hk_device *dev, nir_shader *nir,
785 const struct vk_pipeline_robustness_state *rs, bool is_multiview,
786 uint32_t set_layout_count,
787 struct vk_descriptor_set_layout *const *set_layouts,
788 enum hk_feature_key features)
789 {
790 if (HK_PERF(dev, NOROBUST)) {
791 rs = &vk_robustness_disabled;
792 }
793
794 const nir_opt_access_options access_options = {
795 .is_vulkan = true,
796 };
797 NIR_PASS(_, nir, nir_opt_access, &access_options);
798
799 if (nir->info.stage == MESA_SHADER_FRAGMENT) {
800 NIR_PASS(_, nir, nir_lower_input_attachments,
801 &(nir_input_attachment_options){
802 .use_view_id_for_layer = is_multiview,
803 });
804
805 NIR_PASS(_, nir, nir_shader_tex_pass, lower_subpass_dim, nir_metadata_all,
806 NULL);
807 NIR_PASS(_, nir, nir_lower_wpos_center);
808 }
809
810 /* XXX: should be last geometry stage, how do I get to that? */
811 if (nir->info.stage == MESA_SHADER_VERTEX) {
812 if (is_multiview)
813 hk_lower_multiview(nir);
814 }
815
816 if (nir->info.stage == MESA_SHADER_TESS_EVAL) {
817 NIR_PASS(_, nir, nir_lower_patch_vertices,
818 nir->info.tess.tcs_vertices_out, NULL);
819 }
820
821 const struct lower_ycbcr_state ycbcr_state = {
822 .set_layout_count = set_layout_count,
823 .set_layouts = set_layouts,
824 };
825 NIR_PASS(_, nir, nir_vk_lower_ycbcr_tex, lookup_ycbcr_conversion,
826 &ycbcr_state);
827
828 /* Lower push constants before lower_descriptors */
829 NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_push_const,
830 nir_address_format_32bit_offset);
831
832 // NIR_PASS(_, nir, nir_opt_large_constants, NULL, 32);
833
834 /* Turn cache flushes into image coherency bits while we still have derefs */
835 NIR_PASS(_, nir, nir_lower_memory_model);
836
837 NIR_PASS(_, nir, nir_lower_robust_access, should_lower_robust, NULL);
838
839 /* We must do early lowering before hk_nir_lower_descriptors, since this will
840 * create lod_bias instructions.
841 */
842 NIR_PASS(_, nir, agx_nir_lower_texture_early, true /* support_lod_bias */);
843
844 struct hk_instance *instance = hk_physical_device_instance(
845 (struct hk_physical_device *)dev->vk.physical);
846
847 if (instance->image_view_min_lod) {
848 NIR_PASS(_, nir, agx_nir_lower_image_view_min_lod);
849 }
850
851 if ((features & HK_FEAT_CUSTOM_BORDER) && !HK_PERF(dev, NOBORDER)) {
852 NIR_PASS(_, nir, agx_nir_lower_custom_border);
853 }
854
855 NIR_PASS(_, nir, hk_nir_lower_descriptors, rs, set_layout_count,
856 set_layouts);
857 NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_global,
858 nir_address_format_64bit_global);
859 NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_ssbo,
860 hk_buffer_addr_format(rs->storage_buffers));
861 NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_ubo,
862 hk_buffer_addr_format(rs->uniform_buffers));
863
864 /* Before inserting bounds checks, we want to do a fair bit of optimization.
865 * lower_load_global_constant_offset_instr has special optimizations for
866 * constant offsets, so we want as many offsets to be constant as possible.
867 */
868 bool progress;
869 do {
870 progress = false;
871 NIR_PASS(progress, nir, nir_opt_constant_folding);
872 NIR_PASS(progress, nir, nir_opt_algebraic);
873 NIR_PASS(progress, nir, nir_opt_copy_prop);
874 NIR_PASS(progress, nir, nir_opt_dce);
875 } while (progress);
876
877 nir_move_options opts = nir_move_load_ssbo | nir_move_load_ubo;
878 NIR_PASS(progress, nir, nir_opt_sink, opts);
879 NIR_PASS(progress, nir, nir_opt_move, opts);
880
881 bool soft_fault = agx_has_soft_fault(&dev->dev);
882 NIR_PASS(_, nir, nir_shader_intrinsics_pass,
883 lower_load_global_constant_offset_instr, nir_metadata_none,
884 &soft_fault);
885
886 assert(nir->info.shared_size == 0);
887
888 NIR_PASS(_, nir, nir_lower_vars_to_explicit_types, nir_var_mem_shared,
889 shared_var_info);
890 NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_shared,
891 nir_address_format_32bit_offset);
892
893 if (nir->info.zero_initialize_shared_memory && nir->info.shared_size > 0) {
894 /* Align everything up to 16B so we can write whole vec4s. */
895 nir->info.shared_size = align(nir->info.shared_size, 16);
896 NIR_PASS(_, nir, nir_zero_initialize_shared_memory, nir->info.shared_size,
897 16);
898
899 /* We need to call lower_compute_system_values again because
900 * nir_zero_initialize_shared_memory generates load_invocation_id which
901 * has to be lowered to load_invocation_index.
902 */
903 NIR_PASS(_, nir, nir_lower_compute_system_values, NULL);
904 }
905
906 /* TODO: we can do indirect VS output */
907 nir_variable_mode lower_indirect_modes = 0;
908 if (nir->info.stage == MESA_SHADER_FRAGMENT)
909 lower_indirect_modes |= nir_var_shader_out;
910 else if (nir->info.stage == MESA_SHADER_VERTEX)
911 lower_indirect_modes |= nir_var_shader_in | nir_var_shader_out;
912
913 NIR_PASS(_, nir, nir_lower_indirect_derefs_to_if_else_trees,
914 lower_indirect_modes, UINT32_MAX);
915
916 NIR_PASS(_, nir, nir_lower_io, nir_var_shader_in | nir_var_shader_out,
917 glsl_type_size,
918 nir_lower_io_lower_64bit_to_32 |
919 nir_lower_io_use_interpolated_input_intrinsics);
920
921 if (nir->info.stage == MESA_SHADER_FRAGMENT) {
922 NIR_PASS(_, nir, nir_shader_intrinsics_pass, lower_viewport_fs,
923 nir_metadata_control_flow, NULL);
924 }
925
926 NIR_PASS(_, nir, agx_nir_lower_texture);
927 NIR_PASS(_, nir, agx_nir_lower_multisampled_image_store);
928
929 agx_preprocess_nir(nir);
930
931 nir_opt_peephole_select_options peephole_select_options = {
932 .limit = 0,
933 .discard_ok = true,
934 };
935 NIR_PASS(_, nir, nir_opt_peephole_select, &peephole_select_options);
936 NIR_PASS(_, nir, nir_opt_if,
937 nir_opt_if_optimize_phi_true_false | nir_opt_if_avoid_64bit_phis);
938 }
939
940 static void
941 hk_upload_shader(struct hk_device *dev, struct hk_shader *shader)
942 {
943 if (shader->b.info.has_preamble || shader->b.info.rodata.size_16) {
944 /* TODO: Do we wnat to compact? Revisit when we rework prolog/epilogs. */
945 size_t size = shader->b.info.binary_size;
946 assert(size > 0);
947
948 shader->bo = agx_bo_create(&dev->dev, size, 0,
949 AGX_BO_EXEC | AGX_BO_LOW_VA, "Preamble");
950 memcpy(agx_bo_map(shader->bo), shader->b.binary, size);
951 shader->preamble_addr =
952 shader->bo->va->addr + shader->b.info.preamble_offset;
953 }
954
955 if (!shader->linked.ht) {
956 /* If we only have a single variant, link now. */
957 shader->only_linked = hk_fast_link(dev, false, shader, NULL, NULL, 0);
958 }
959
960 if (shader->info.stage == MESA_SHADER_FRAGMENT) {
961 agx_pack_fragment_face_2(&shader->frag_face, 0, &shader->b.info);
962 }
963
964 agx_pack(&shader->counts, COUNTS, cfg) {
965 cfg.uniform_register_count = shader->b.info.push_count;
966 cfg.preshader_register_count = shader->b.info.nr_preamble_gprs;
967 cfg.sampler_state_register_count = agx_translate_sampler_state_count(
968 shader->b.info.sampler_state_count, false);
969 cfg.texture_state_register_count = shader->b.info.texture_state_count;
970 }
971 }
972
973 DERIVE_HASH_TABLE(hk_fast_link_key_vs);
974 DERIVE_HASH_TABLE(hk_fast_link_key_fs);
975
976 static VkResult
977 hk_init_link_ht(struct hk_shader *shader, mesa_shader_stage sw_stage)
978 {
979 simple_mtx_init(&shader->linked.lock, mtx_plain);
980
981 bool multiple_variants =
982 sw_stage == MESA_SHADER_VERTEX || sw_stage == MESA_SHADER_FRAGMENT;
983
984 if (!multiple_variants)
985 return VK_SUCCESS;
986
987 if (sw_stage == MESA_SHADER_VERTEX)
988 shader->linked.ht = hk_fast_link_key_vs_table_create(NULL);
989 else
990 shader->linked.ht = hk_fast_link_key_fs_table_create(NULL);
991
992 return (shader->linked.ht == NULL) ? VK_ERROR_OUT_OF_HOST_MEMORY
993 : VK_SUCCESS;
994 }
995
996 static bool
997 lower_uniforms(nir_builder *b, nir_intrinsic_instr *intr, void *data)
998 {
999 /* Root is first, descriptor sets follow immediately. */
1000 unsigned *root_ = data;
1001 unsigned root = *root_;
1002 unsigned sets = root + 4;
1003
1004 if (intr->intrinsic == nir_intrinsic_bindless_image_agx ||
1005 intr->intrinsic == nir_intrinsic_bindless_sampler_agx) {
1006 /* Change of units from sets to uniforms */
1007 nir_intrinsic_set_desc_set(intr,
1008 sets + (nir_intrinsic_desc_set(intr) * 4));
1009 return true;
1010 }
1011
1012 if (intr->intrinsic != nir_intrinsic_load_root_agx &&
1013 intr->intrinsic != nir_intrinsic_load_descriptor_set_agx)
1014 return false;
1015
1016 b->cursor = nir_before_instr(&intr->instr);
1017 nir_def *rep;
1018
1019 if (intr->intrinsic == nir_intrinsic_load_descriptor_set_agx) {
1020 unsigned s = nir_intrinsic_desc_set(intr);
1021 rep = nir_load_preamble(b, 1, 64, .base = sets + (4 * s));
1022 } else {
1023 rep = nir_load_preamble(b, 1, 64, .base = root);
1024 }
1025
1026 nir_def_replace(&intr->def, rep);
1027 return true;
1028 }
1029
1030 static bool
1031 kill_psiz_write(nir_builder *b, nir_intrinsic_instr *intr, void *data)
1032 {
1033 if (intr->intrinsic != nir_intrinsic_store_output ||
1034 nir_intrinsic_io_semantics(intr).location != VARYING_SLOT_PSIZ)
1035 return false;
1036
1037 if (nir_remove_sysval_output(intr, MESA_SHADER_FRAGMENT)) {
1038 b->shader->info.outputs_written &= ~VARYING_BIT_PSIZ;
1039 }
1040
1041 return true;
1042 }
1043
1044 static void
1045 hk_lower_hw_vs(nir_shader *nir, struct hk_shader *shader, bool kill_psiz)
1046 {
1047 /* Point size must be clamped, excessively large points don't render
1048 * properly on G13.
1049 *
1050 * Must be synced with pointSizeRange.
1051 */
1052 NIR_PASS(_, nir, nir_lower_point_size, 1.0f, 511.95f);
1053
1054 if (kill_psiz) {
1055 NIR_PASS(_, nir, nir_shader_intrinsics_pass, kill_psiz_write,
1056 nir_metadata_control_flow, NULL);
1057 }
1058
1059 NIR_PASS(_, nir, nir_lower_io_to_scalar, nir_var_shader_out, NULL, NULL);
1060 NIR_PASS(_, nir, agx_nir_lower_cull_distance_vs);
1061
1062 NIR_PASS(_, nir, agx_nir_lower_uvs, &shader->info.uvs);
1063 }
1064
1065 static VkResult
1066 hk_compile_nir(struct hk_device *dev, const VkAllocationCallbacks *pAllocator,
1067 nir_shader *nir, VkShaderCreateFlagsEXT shader_flags,
1068 const struct vk_pipeline_robustness_state *rs,
1069 const union hk_key *key, enum hk_feature_key features,
1070 struct hk_shader *shader, mesa_shader_stage sw_stage, bool hw,
1071 nir_xfb_info *xfb_info, unsigned set_count)
1072 {
1073 unsigned nr_vbos = 0;
1074 bool kill_psiz = false;
1075
1076 /* For now, only shader objects are supported */
1077 if (sw_stage == MESA_SHADER_VERTEX) {
1078 nr_vbos = DIV_ROUND_UP(
1079 BITSET_LAST_BIT(shader->info.vs.attrib_components_read), 4);
1080 kill_psiz = key->vs.kill_psiz;
1081 } else if (sw_stage == MESA_SHADER_FRAGMENT) {
1082 shader->info.fs.writes_memory = nir->info.writes_memory;
1083 shader->info.fs.interp.linear = nir->info.linear_varyings;
1084 shader->info.fs.interp.flat =
1085 ~(nir->info.linear_varyings | nir->info.perspective_varyings);
1086
1087 /* Discards must be lowering before lowering MSAA to handle discards */
1088 NIR_PASS(_, nir, agx_nir_lower_discard_zs_emit);
1089 NIR_PASS(_, nir, agx_nir_lower_fs_output_to_epilog,
1090 &shader->info.fs.epilog_key);
1091 NIR_PASS(_, nir, agx_nir_lower_sample_mask);
1092
1093 if (nir->info.fs.uses_sample_shading) {
1094 /* Ensure the sample mask is preserved in register */
1095 nir_builder b =
1096 nir_builder_at(nir_after_impl(nir_shader_get_entrypoint(nir)));
1097
1098 nir_def *mask =
1099 nir_load_exported_agx(&b, 1, 16, .base = AGX_ABI_FIN_SAMPLE_MASK);
1100
1101 nir_export_agx(&b, mask, .base = AGX_ABI_FOUT_SAMPLE_MASK);
1102
1103 NIR_PASS(_, nir, agx_nir_lower_to_per_sample);
1104 }
1105
1106 NIR_PASS(_, nir, agx_nir_lower_fs_active_samples_to_register);
1107 NIR_PASS(_, nir, agx_nir_lower_interpolation);
1108 } else if (sw_stage == MESA_SHADER_TESS_EVAL ||
1109 sw_stage == MESA_SHADER_TESS_CTRL) {
1110
1111 shader->info.tess.info.ccw = nir->info.tess.ccw;
1112 shader->info.tess.info.points = nir->info.tess.point_mode;
1113 shader->info.tess.info.spacing = nir->info.tess.spacing;
1114 shader->info.tess.info.mode = nir->info.tess._primitive_mode;
1115
1116 if (sw_stage == MESA_SHADER_TESS_CTRL) {
1117 shader->info.tess.tcs_output_patch_size =
1118 nir->info.tess.tcs_vertices_out;
1119 shader->info.tess.tcs_per_vertex_outputs =
1120 poly_tcs_per_vertex_outputs(nir);
1121 shader->info.tess.tcs_nr_patch_outputs =
1122 util_last_bit(nir->info.patch_outputs_written);
1123 shader->info.tess.tcs_output_stride = poly_tcs_output_stride(nir);
1124 } else {
1125 /* This destroys info so it needs to happen after the gather */
1126 NIR_PASS(_, nir, poly_nir_lower_tes, hw);
1127 }
1128 }
1129
1130 /* Normally, vertex shaders need to write a default point size. However, if
1131 * we have a geometry/tessellation shader, the hardware vertex (software
1132 * GS/TES) will handle this itself instead.
1133 */
1134 if (sw_stage == MESA_SHADER_VERTEX && hw && !kill_psiz) {
1135 NIR_PASS(_, nir, nir_lower_default_point_size);
1136 }
1137
1138 uint64_t outputs = nir->info.outputs_written;
1139 if (sw_stage == MESA_SHADER_VERTEX || sw_stage == MESA_SHADER_TESS_EVAL) {
1140 if (hw) {
1141 hk_lower_hw_vs(nir, shader, kill_psiz);
1142 } else {
1143 NIR_PASS(_, nir, poly_nir_lower_vs_before_gs);
1144 nir->info.stage = MESA_SHADER_COMPUTE;
1145 memset(&nir->info.cs, 0, sizeof(nir->info.cs));
1146 nir->xfb_info = NULL;
1147 }
1148 }
1149
1150 unsigned root = 0;
1151 if (sw_stage == MESA_SHADER_FRAGMENT)
1152 root = AGX_ABI_FUNI_ROOT;
1153 else if (sw_stage == MESA_SHADER_VERTEX)
1154 root = AGX_ABI_VUNI_COUNT_VK(nr_vbos);
1155
1156 shader->info.set_count = set_count;
1157
1158 /* XXX: rename */
1159 NIR_PASS(_, nir, hk_lower_uvs_index, sw_stage, nr_vbos);
1160 NIR_PASS(_, nir, nir_shader_intrinsics_pass, lower_uniforms,
1161 nir_metadata_control_flow, &root);
1162
1163 #if 0
1164 /* TODO */
1165 nir_variable_mode robust2_modes = 0;
1166 if (rs->uniform_buffers == VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT)
1167 robust2_modes |= nir_var_mem_ubo;
1168 if (rs->storage_buffers == VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2_EXT)
1169 robust2_modes |= nir_var_mem_ssbo;
1170 #endif
1171
1172 struct agx_shader_key backend_key = {
1173 .reserved_preamble = root + (4 * (1 + set_count)),
1174 .dev = agx_gather_device_key(&dev->dev),
1175 .no_stop = nir->info.stage == MESA_SHADER_FRAGMENT,
1176 .has_scratch = !nir->info.internal,
1177 .promote_constants = true,
1178 .promote_textures = true,
1179 };
1180
1181 /* For now, sample shading is always dynamic. Indicate that. */
1182 if (nir->info.stage == MESA_SHADER_FRAGMENT &&
1183 nir->info.fs.uses_sample_shading)
1184 backend_key.fs.inside_sample_loop = true;
1185
1186 simple_mtx_t *lock = NULL;
1187 if (agx_get_compiler_debug())
1188 lock = &hk_device_physical(dev)->debug_compile_lock;
1189
1190 if (lock)
1191 simple_mtx_lock(lock);
1192
1193 assert(nir->info.io_lowered);
1194 agx_compile_shader_nir(nir, &backend_key, &shader->b);
1195
1196 if (lock)
1197 simple_mtx_unlock(lock);
1198
1199 shader->code_ptr = shader->b.binary;
1200 shader->code_size = shader->b.info.binary_size;
1201
1202 shader->info.stage = sw_stage;
1203 shader->info.clip_distance_array_size = nir->info.clip_distance_array_size;
1204 shader->info.cull_distance_array_size = nir->info.cull_distance_array_size;
1205 shader->b.info.outputs = outputs;
1206
1207 if (xfb_info) {
1208 assert(xfb_info->output_count < ARRAY_SIZE(shader->info.xfb_outputs));
1209
1210 memcpy(&shader->info.xfb_info, xfb_info,
1211 nir_xfb_info_size(xfb_info->output_count));
1212
1213 typed_memcpy(shader->info.xfb_stride, nir->info.xfb_stride, 4);
1214 }
1215
1216 if (nir->constant_data_size > 0) {
1217 uint32_t data_size = align(nir->constant_data_size, HK_MIN_UBO_ALIGNMENT);
1218
1219 void *data = malloc(data_size);
1220 if (data == NULL) {
1221 ralloc_free(nir);
1222 return vk_error(dev, VK_ERROR_OUT_OF_HOST_MEMORY);
1223 }
1224
1225 memcpy(data, nir->constant_data, nir->constant_data_size);
1226
1227 assert(nir->constant_data_size <= data_size);
1228 memset(data + nir->constant_data_size, 0,
1229 data_size - nir->constant_data_size);
1230
1231 shader->data_ptr = data;
1232 shader->data_size = data_size;
1233 }
1234
1235 ralloc_free(nir);
1236
1237 VkResult result = hk_init_link_ht(shader, sw_stage);
1238 if (result != VK_SUCCESS)
1239 return vk_error(dev, result);
1240
1241 hk_upload_shader(dev, shader);
1242 return VK_SUCCESS;
1243 }
1244
1245 static const struct vk_shader_ops hk_shader_ops;
1246
1247 static void
1248 hk_destroy_linked_shader(struct hk_device *dev, struct hk_linked_shader *linked)
1249 {
1250 agx_bo_unreference(&dev->dev, linked->b.bo);
1251 ralloc_free(linked);
1252 }
1253
1254 static void
1255 hk_shader_destroy(struct hk_device *dev, struct hk_shader *s)
1256 {
1257 free((void *)s->code_ptr);
1258 free((void *)s->data_ptr);
1259 agx_bo_unreference(&dev->dev, s->bo);
1260
1261 simple_mtx_destroy(&s->linked.lock);
1262
1263 if (s->only_linked)
1264 hk_destroy_linked_shader(dev, s->only_linked);
1265
1266 if (s->linked.ht) {
1267 hash_table_foreach(s->linked.ht, entry) {
1268 hk_destroy_linked_shader(dev, entry->data);
1269 }
1270 _mesa_hash_table_destroy(s->linked.ht, NULL);
1271 }
1272 }
1273
1274 void
1275 hk_api_shader_destroy(struct vk_device *vk_dev, struct vk_shader *vk_shader,
1276 const VkAllocationCallbacks *pAllocator)
1277 {
1278 struct hk_device *dev = container_of(vk_dev, struct hk_device, vk);
1279 struct hk_api_shader *obj =
1280 container_of(vk_shader, struct hk_api_shader, vk);
1281
1282 hk_foreach_variant(obj, shader) {
1283 hk_shader_destroy(dev, shader);
1284 }
1285
1286 vk_shader_free(&dev->vk, pAllocator, &obj->vk);
1287 }
1288
1289 VkResult
1290 hk_compile_shader(struct hk_device *dev, struct vk_shader_compile_info *info,
1291 const struct vk_graphics_pipeline_state *state,
1292 const struct vk_features *vk_features,
1293 const VkAllocationCallbacks *pAllocator,
1294 struct hk_api_shader **shader_out)
1295 {
1296 VkResult result;
1297 enum hk_feature_key features = hk_make_feature_key(vk_features);
1298
1299 /* We consume the NIR, regardless of success or failure */
1300 nir_shader *nir = info->nir;
1301
1302 size_t size = sizeof(struct hk_api_shader) +
1303 sizeof(struct hk_shader) * hk_num_variants(info->stage);
1304 struct hk_api_shader *obj =
1305 vk_shader_zalloc(&dev->vk, &hk_shader_ops, info->stage, pAllocator, size);
1306
1307 if (obj == NULL) {
1308 ralloc_free(nir);
1309 return vk_error(dev, VK_ERROR_OUT_OF_HOST_MEMORY);
1310 }
1311
1312 if (!nir->info.io_lowered) {
1313 hk_lower_nir(dev, nir, info->robustness, false, info->set_layout_count,
1314 info->set_layouts, features);
1315 }
1316
1317 mesa_shader_stage sw_stage = nir->info.stage;
1318
1319 union hk_key key_tmp, *key = NULL;
1320 if (sw_stage == MESA_SHADER_FRAGMENT) {
1321 hk_populate_fs_key(&key_tmp.fs, state);
1322 key = &key_tmp;
1323
1324 nir->info.fs.uses_sample_shading |= key->fs.force_sample_shading;
1325
1326 /* Force late-Z for Z/S self-deps. TODO: There's probably a less silly way
1327 * to do this.
1328 */
1329 if (key->fs.zs_self_dep) {
1330 nir_builder b =
1331 nir_builder_at(nir_before_impl(nir_shader_get_entrypoint(nir)));
1332 nir_discard_if(&b, nir_imm_false(&b));
1333 nir->info.fs.uses_discard = true;
1334 }
1335
1336 NIR_PASS(_, nir, agx_nir_lower_sample_intrinsics, false);
1337 } else if (sw_stage == MESA_SHADER_VERTEX) {
1338 hk_populate_vs_key(&key_tmp.vs, state);
1339 key = &key_tmp;
1340 } else if (sw_stage == MESA_SHADER_TESS_CTRL) {
1341 NIR_PASS(_, nir, poly_nir_lower_tcs);
1342 }
1343
1344 /* Compile all variants up front */
1345 if (sw_stage == MESA_SHADER_GEOMETRY) {
1346 struct hk_shader *main_variant = hk_main_gs_variant(obj);
1347 struct hk_shader *count_variant = hk_count_gs_variant(obj);
1348
1349 nir_shader *count = NULL, *rast = NULL, *pre_gs = NULL;
1350
1351 NIR_PASS(_, nir, poly_nir_lower_gs, &count, &rast, &pre_gs,
1352 &count_variant->info.gs);
1353
1354 agx_preprocess_nir(count);
1355 agx_preprocess_nir(rast);
1356 agx_preprocess_nir(pre_gs);
1357
1358 struct hk_shader *shader = &obj->variants[HK_GS_VARIANT_RAST];
1359 hk_lower_hw_vs(rast, shader, false);
1360 shader->info.gs = count_variant->info.gs;
1361 main_variant->info.gs = count_variant->info.gs;
1362
1363 struct {
1364 nir_shader *in;
1365 struct hk_shader *out;
1366 } variants[] = {
1367 {nir, hk_main_gs_variant(obj)},
1368 {pre_gs, hk_pre_gs_variant(obj)},
1369 {count, count_variant},
1370 {rast, &obj->variants[HK_GS_VARIANT_RAST]},
1371 };
1372
1373 for (unsigned v = 0; v < ARRAY_SIZE(variants); ++v) {
1374 if (variants[v].in) {
1375 result =
1376 hk_compile_nir(dev, pAllocator, variants[v].in, info->flags,
1377 info->robustness, NULL, features, variants[v].out,
1378 sw_stage, true, NULL, info->set_layout_count);
1379
1380 if (result != VK_SUCCESS) {
1381 hk_api_shader_destroy(&dev->vk, &obj->vk, pAllocator);
1382 ralloc_free(nir);
1383 ralloc_free(pre_gs);
1384 ralloc_free(count);
1385 ralloc_free(rast);
1386 return result;
1387 }
1388 }
1389 }
1390 } else if (sw_stage == MESA_SHADER_VERTEX ||
1391 sw_stage == MESA_SHADER_TESS_EVAL) {
1392
1393 VkShaderStageFlags next_stage = info->next_stage_mask;
1394
1395 /* Transform feedback is layered on top of geometry shaders. If there is
1396 * not a geometry shader in the pipeline, we will compile a geometry
1397 * shader for the purpose. Update the next_stage mask accordingly.
1398 */
1399 if (nir->xfb_info != NULL) {
1400 next_stage |= VK_SHADER_STAGE_GEOMETRY_BIT;
1401 }
1402
1403 if (sw_stage == MESA_SHADER_VERTEX) {
1404 assert(
1405 !(nir->info.inputs_read & BITFIELD64_MASK(VERT_ATTRIB_GENERIC0)) &&
1406 "Fixed-function attributes not used in Vulkan");
1407
1408 NIR_PASS(_, nir, nir_recompute_io_bases, nir_var_shader_in);
1409 }
1410
1411 /* Fold constant offset srcs for IO. */
1412 NIR_PASS(_, nir, nir_opt_constant_folding);
1413
1414 for (enum hk_vs_variant v = 0; v < HK_VS_VARIANTS; ++v) {
1415 /* Only compile the software variant if we might use this shader with
1416 * geometry/tessellation. We need to compile the hardware variant
1417 * unconditionally to handle the VS -> null FS case, which does not
1418 * require setting the FRAGMENT bit.
1419 */
1420 if (v == HK_VS_VARIANT_SW &&
1421 !(next_stage & (VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT |
1422 VK_SHADER_STAGE_GEOMETRY_BIT)))
1423 continue;
1424
1425 struct hk_shader *shader = &obj->variants[v];
1426 bool hw = v == HK_VS_VARIANT_HW;
1427 bool last = (v + 1) == HK_VS_VARIANTS;
1428
1429 /* Each variant gets its own NIR. To save an extra clone, we use the
1430 * original NIR for the last stage.
1431 */
1432 nir_shader *clone = last ? nir : nir_shader_clone(NULL, nir);
1433
1434 NIR_PASS(_, clone, agx_nir_gather_vs_inputs,
1435 shader->info.vs.attrib_components_read);
1436
1437 if (sw_stage == MESA_SHADER_VERTEX) {
1438 shader->info.vs.use_prolog = !(key && key->vs.skip_prolog);
1439 shader->info.vs.attribs_read =
1440 nir->info.inputs_read >> VERT_ATTRIB_GENERIC0;
1441
1442 if (shader->info.vs.use_prolog) {
1443 NIR_PASS(_, clone, agx_nir_lower_vs_input_to_prolog);
1444 } else {
1445 struct agx_velem_key attribs[AGX_MAX_ATTRIBS];
1446 for (unsigned a = 0; a < AGX_MAX_ATTRIBS; ++a) {
1447 if (key->vs.attribs[a].format) {
1448 unsigned slot = util_bitcount64(
1449 shader->info.vs.attribs_read & BITFIELD_MASK(a));
1450
1451 attribs[slot] = key->vs.attribs[a];
1452 }
1453 }
1454
1455 struct agx_robustness agx_rs = {
1456 .soft_fault = agx_has_soft_fault(&dev->dev),
1457
1458 /* Correctly handling GPL + pipeline-robustness requires
1459 * runtime changes, and I don't care enough to optimize this.
1460 */
1461 .level = AGX_ROBUSTNESS_D3D,
1462 };
1463
1464 agx_nir_lower_vbo(clone, attribs, agx_rs,
1465 !key->vs.static_strides);
1466
1467 unsigned nr = DIV_ROUND_UP(
1468 BITSET_LAST_BIT(shader->info.vs.attrib_components_read), 4);
1469 agx_nir_lower_non_monolithic_uniforms(clone, nr);
1470 }
1471 }
1472
1473 /* hk_compile_nir takes ownership of the clone */
1474 result =
1475 hk_compile_nir(dev, pAllocator, clone, info->flags,
1476 info->robustness, key, features, shader, sw_stage,
1477 hw, nir->xfb_info, info->set_layout_count);
1478 if (result != VK_SUCCESS) {
1479 hk_api_shader_destroy(&dev->vk, &obj->vk, pAllocator);
1480 ralloc_free(nir);
1481 return result;
1482 }
1483 }
1484 } else {
1485 struct hk_shader *shader = hk_only_variant(obj);
1486
1487 /* hk_compile_nir takes ownership of nir */
1488 result = hk_compile_nir(dev, pAllocator, nir, info->flags,
1489 info->robustness, key, features, shader, sw_stage,
1490 true, NULL, info->set_layout_count);
1491 if (result != VK_SUCCESS) {
1492 hk_api_shader_destroy(&dev->vk, &obj->vk, pAllocator);
1493 return result;
1494 }
1495 }
1496
1497 *shader_out = obj;
1498 return VK_SUCCESS;
1499 }
1500
1501 static void
1502 nir_opts(nir_shader *nir, void *data)
1503 {
1504 bool progress;
1505
1506 do {
1507 progress = false;
1508
1509 NIR_PASS(progress, nir, nir_opt_loop);
1510 NIR_PASS(progress, nir, nir_opt_copy_prop);
1511 NIR_PASS(progress, nir, nir_opt_remove_phis);
1512 NIR_PASS(progress, nir, nir_opt_dce);
1513
1514 NIR_PASS(progress, nir, nir_opt_if, 0);
1515 NIR_PASS(progress, nir, nir_opt_dead_cf);
1516 NIR_PASS(progress, nir, nir_opt_cse);
1517
1518 NIR_PASS(progress, nir, nir_opt_peephole_select,
1519 &(nir_opt_peephole_select_options){
1520 .limit = 8,
1521 .expensive_alu_ok = true,
1522 .discard_ok = true,
1523 });
1524
1525 NIR_PASS(progress, nir, nir_opt_phi_precision);
1526 NIR_PASS(progress, nir, nir_opt_algebraic);
1527 NIR_PASS(progress, nir, nir_opt_constant_folding);
1528
1529 NIR_PASS(progress, nir, nir_opt_undef);
1530 NIR_PASS(progress, nir, nir_opt_loop_unroll);
1531 } while (progress);
1532 }
1533
1534 static VkResult
1535 hk_compile_shaders(struct vk_device *vk_dev, uint32_t shader_count,
1536 struct vk_shader_compile_info *infos,
1537 const struct vk_graphics_pipeline_state *state,
1538 const struct vk_features *features,
1539 const VkAllocationCallbacks *pAllocator,
1540 struct vk_shader **shaders_out)
1541 {
1542 struct hk_device *dev = container_of(vk_dev, struct hk_device, vk);
1543 nir_shader *shaders[shader_count];
1544
1545 /* Lower shaders, notably lowering I/O. This is a prerequisite for
1546 * intershader optimization.
1547 */
1548 for (uint32_t i = 0; i < shader_count; i++) {
1549 const struct vk_shader_compile_info *info = &infos[i];
1550 /* TODO: Multiview with ESO */
1551 const bool is_multiview = state && state->mv->view_mask != 0;
1552 enum hk_feature_key hk_features = hk_make_feature_key(features);
1553 nir_shader *nir = info->nir;
1554
1555 hk_lower_nir(dev, nir, info->robustness, is_multiview,
1556 info->set_layout_count, info->set_layouts, hk_features);
1557
1558 if (nir->xfb_info) {
1559 /* Fold constant offset srcs for IO. */
1560 NIR_PASS(_, nir, nir_opt_constant_folding);
1561
1562 nir_io_add_intrinsic_xfb_info(nir);
1563 }
1564
1565 shaders[i] = nir;
1566 }
1567
1568 nir_opt_varyings_bulk(shaders, shader_count, true, UINT32_MAX, UINT32_MAX,
1569 nir_opts, NULL);
1570
1571 for (uint32_t i = 0; i < shader_count; i++) {
1572 VkResult result =
1573 hk_compile_shader(dev, &infos[i], state, features, pAllocator,
1574 (struct hk_api_shader **)&shaders_out[i]);
1575 if (result != VK_SUCCESS) {
1576 /* Clean up all the shaders before this point */
1577 for (uint32_t j = 0; j < i; j++)
1578 hk_api_shader_destroy(&dev->vk, shaders_out[j], pAllocator);
1579
1580 /* Clean up all the NIR after this point */
1581 for (uint32_t j = i + 1; j < shader_count; j++)
1582 ralloc_free(infos[j].nir);
1583
1584 /* Memset the output array */
1585 memset(shaders_out, 0, shader_count * sizeof(*shaders_out));
1586
1587 return result;
1588 }
1589 }
1590
1591 return VK_SUCCESS;
1592 }
1593
1594 static VkResult
1595 hk_deserialize_shader(struct hk_device *dev, struct blob_reader *blob,
1596 struct hk_shader *shader)
1597 {
1598 struct hk_shader_info info;
1599 blob_copy_bytes(blob, &info, sizeof(info));
1600
1601 struct agx_shader_info b_info;
1602 blob_copy_bytes(blob, &b_info, sizeof(b_info));
1603
1604 const uint32_t code_size = blob_read_uint32(blob);
1605 const uint32_t data_size = blob_read_uint32(blob);
1606 if (blob->overrun)
1607 return vk_error(dev, VK_ERROR_INCOMPATIBLE_SHADER_BINARY_EXT);
1608
1609 VkResult result = hk_init_link_ht(shader, info.stage);
1610 if (result != VK_SUCCESS)
1611 return vk_error(dev, VK_ERROR_OUT_OF_HOST_MEMORY);
1612
1613 simple_mtx_init(&shader->linked.lock, mtx_plain);
1614
1615 shader->b.info = b_info;
1616 shader->info = info;
1617 shader->code_size = code_size;
1618 shader->data_size = data_size;
1619 shader->b.info.binary_size = code_size;
1620
1621 shader->code_ptr = malloc(code_size);
1622 if (shader->code_ptr == NULL)
1623 return vk_error(dev, VK_ERROR_OUT_OF_HOST_MEMORY);
1624
1625 shader->data_ptr = malloc(data_size);
1626 if (shader->data_ptr == NULL)
1627 return vk_error(dev, VK_ERROR_OUT_OF_HOST_MEMORY);
1628
1629 blob_copy_bytes(blob, (void *)shader->code_ptr, shader->code_size);
1630 blob_copy_bytes(blob, (void *)shader->data_ptr, shader->data_size);
1631 if (blob->overrun)
1632 return vk_error(dev, VK_ERROR_INCOMPATIBLE_SHADER_BINARY_EXT);
1633
1634 shader->b.binary = (void *)shader->code_ptr;
1635 hk_upload_shader(dev, shader);
1636 return VK_SUCCESS;
1637 }
1638
1639 static VkResult
1640 hk_deserialize_api_shader(struct vk_device *vk_dev, struct blob_reader *blob,
1641 uint32_t binary_version,
1642 const VkAllocationCallbacks *pAllocator,
1643 struct vk_shader **shader_out)
1644 {
1645 struct hk_device *dev = container_of(vk_dev, struct hk_device, vk);
1646
1647 mesa_shader_stage stage = blob_read_uint8(blob);
1648 if (blob->overrun)
1649 return vk_error(dev, VK_ERROR_INCOMPATIBLE_SHADER_BINARY_EXT);
1650
1651 size_t size = sizeof(struct hk_api_shader) +
1652 sizeof(struct hk_shader) * hk_num_variants(stage);
1653
1654 struct hk_api_shader *obj =
1655 vk_shader_zalloc(&dev->vk, &hk_shader_ops, stage, pAllocator, size);
1656
1657 if (obj == NULL)
1658 return vk_error(dev, VK_ERROR_OUT_OF_HOST_MEMORY);
1659
1660 hk_foreach_variant(obj, shader) {
1661 VkResult result = hk_deserialize_shader(dev, blob, shader);
1662
1663 if (result != VK_SUCCESS) {
1664 hk_api_shader_destroy(&dev->vk, &obj->vk, pAllocator);
1665 return result;
1666 }
1667 }
1668
1669 *shader_out = &obj->vk;
1670 return VK_SUCCESS;
1671 }
1672
1673 static void
1674 hk_shader_serialize(struct vk_device *vk_dev, const struct hk_shader *shader,
1675 struct blob *blob)
1676 {
1677 blob_write_bytes(blob, &shader->info, sizeof(shader->info));
1678 blob_write_bytes(blob, &shader->b.info, sizeof(shader->b.info));
1679
1680 blob_write_uint32(blob, shader->code_size);
1681 blob_write_uint32(blob, shader->data_size);
1682 blob_write_bytes(blob, shader->code_ptr, shader->code_size);
1683 blob_write_bytes(blob, shader->data_ptr, shader->data_size);
1684 }
1685
1686 static bool
1687 hk_api_shader_serialize(struct vk_device *vk_dev,
1688 const struct vk_shader *vk_shader, struct blob *blob)
1689 {
1690 struct hk_api_shader *obj =
1691 container_of(vk_shader, struct hk_api_shader, vk);
1692
1693 blob_write_uint8(blob, vk_shader->stage);
1694
1695 hk_foreach_variant(obj, shader) {
1696 hk_shader_serialize(vk_dev, shader, blob);
1697 }
1698
1699 return !blob->out_of_memory;
1700 }
1701
1702 static VkResult
1703 hk_shader_get_executable_properties(
1704 UNUSED struct vk_device *device, const struct vk_shader *vk_shader,
1705 uint32_t *executable_count, VkPipelineExecutablePropertiesKHR *properties)
1706 {
1707 struct hk_api_shader *obj =
1708 container_of(vk_shader, struct hk_api_shader, vk);
1709
1710 VK_OUTARRAY_MAKE_TYPED(VkPipelineExecutablePropertiesKHR, out, properties,
1711 executable_count);
1712
1713 vk_outarray_append_typed(VkPipelineExecutablePropertiesKHR, &out, props)
1714 {
1715 props->stages = mesa_to_vk_shader_stage(obj->vk.stage);
1716 props->subgroupSize = 32;
1717 VK_COPY_STR(props->name, _mesa_shader_stage_to_string(obj->vk.stage));
1718 VK_PRINT_STR(props->description, "%s shader",
1719 _mesa_shader_stage_to_string(obj->vk.stage));
1720 }
1721
1722 return vk_outarray_status(&out);
1723 }
1724
1725 static VkResult
1726 hk_shader_get_executable_statistics(
1727 UNUSED struct vk_device *device, const struct vk_shader *vk_shader,
1728 uint32_t executable_index, uint32_t *statistic_count,
1729 VkPipelineExecutableStatisticKHR *statistics)
1730 {
1731 struct hk_api_shader *obj =
1732 container_of(vk_shader, struct hk_api_shader, vk);
1733
1734 VK_OUTARRAY_MAKE_TYPED(VkPipelineExecutableStatisticKHR, out, statistics,
1735 statistic_count);
1736
1737 assert(executable_index == 0);
1738
1739 /* TODO: find a sane way to report multiple variants and have that play nice
1740 * with zink.
1741 */
1742 struct hk_shader *shader = hk_any_variant(obj);
1743 vk_add_agx2_stats(out, &shader->b.info.stats);
1744 return vk_outarray_status(&out);
1745 }
1746
1747 static bool
1748 write_ir_text(VkPipelineExecutableInternalRepresentationKHR *ir,
1749 const char *data)
1750 {
1751 ir->isText = VK_TRUE;
1752
1753 size_t data_len = strlen(data) + 1;
1754
1755 if (ir->pData == NULL) {
1756 ir->dataSize = data_len;
1757 return true;
1758 }
1759
1760 strncpy(ir->pData, data, ir->dataSize);
1761 if (ir->dataSize < data_len)
1762 return false;
1763
1764 ir->dataSize = data_len;
1765 return true;
1766 }
1767
1768 static VkResult
1769 hk_shader_get_executable_internal_representations(
1770 UNUSED struct vk_device *device, const struct vk_shader *vk_shader,
1771 uint32_t executable_index, uint32_t *internal_representation_count,
1772 VkPipelineExecutableInternalRepresentationKHR *internal_representations)
1773 {
1774 VK_OUTARRAY_MAKE_TYPED(VkPipelineExecutableInternalRepresentationKHR, out,
1775 internal_representations,
1776 internal_representation_count);
1777 bool incomplete_text = false;
1778
1779 assert(executable_index == 0);
1780
1781 /* TODO */
1782 #if 0
1783 vk_outarray_append_typed(VkPipelineExecutableInternalRepresentationKHR, &out, ir) {
1784 VK_COPY_STR(ir->name, "AGX assembly");
1785 VK_COPY_STR(ir->description, "AGX assembly");
1786 if (!write_ir_text(ir, TODO))
1787 incomplete_text = true;
1788 }
1789 #endif
1790
1791 return incomplete_text ? VK_INCOMPLETE : vk_outarray_status(&out);
1792 }
1793
1794 static const struct vk_shader_ops hk_shader_ops = {
1795 .destroy = hk_api_shader_destroy,
1796 .serialize = hk_api_shader_serialize,
1797 .get_executable_properties = hk_shader_get_executable_properties,
1798 .get_executable_statistics = hk_shader_get_executable_statistics,
1799 .get_executable_internal_representations =
1800 hk_shader_get_executable_internal_representations,
1801 };
1802
1803 const struct vk_device_shader_ops hk_device_shader_ops = {
1804 .get_nir_options = hk_get_nir_options,
1805 .get_spirv_options = hk_get_spirv_options,
1806 .preprocess_nir = hk_preprocess_nir,
1807 .hash_state = hk_hash_graphics_state,
1808 .compile = hk_compile_shaders,
1809 .deserialize = hk_deserialize_api_shader,
1810 .cmd_set_dynamic_graphics_state = vk_cmd_set_dynamic_graphics_state,
1811 .cmd_bind_shaders = hk_cmd_bind_shaders,
1812 };
1813
1814 struct hk_linked_shader *
1815 hk_fast_link(struct hk_device *dev, bool fragment, struct hk_shader *main,
1816 struct agx_shader_part *prolog, struct agx_shader_part *epilog,
1817 unsigned nr_samples_shaded)
1818 {
1819 struct hk_linked_shader *s = rzalloc(NULL, struct hk_linked_shader);
1820 agx_fast_link(&s->b, &dev->dev, fragment, &main->b, prolog, epilog,
1821 nr_samples_shaded);
1822
1823 if (fragment) {
1824 unsigned samplers = main->b.info.sampler_state_count;
1825 if (s->b.uses_txf)
1826 samplers = MAX2(samplers, 1);
1827
1828 agx_pack(&s->fs_counts, FRAGMENT_SHADER_WORD_0, cfg) {
1829 cfg.cf_binding_count = s->b.cf.nr_bindings;
1830 cfg.uniform_register_count = main->b.info.push_count;
1831 cfg.preshader_register_count = main->b.info.nr_preamble_gprs;
1832 cfg.texture_state_register_count = main->b.info.texture_state_count;
1833 cfg.sampler_state_register_count =
1834 agx_translate_sampler_state_count(samplers, false);
1835 }
1836 }
1837
1838 /* Now that we've linked, bake the USC words to bind this program */
1839 struct agx_usc_builder b = agx_usc_builder(s->usc.data, sizeof(s->usc.data));
1840
1841 if (main && main->b.info.rodata.size_16) {
1842 agx_usc_immediates(&b, &main->b.info.rodata, main->bo->va->addr);
1843 }
1844
1845 if (s->b.uses_txf)
1846 agx_usc_push_packed(&b, SAMPLER, dev->dev.txf_sampler);
1847
1848 agx_usc_shared_non_fragment(&b, &main->b.info, 0);
1849 agx_usc_push_packed(&b, SHADER, s->b.shader);
1850 agx_usc_push_packed(&b, REGISTERS, s->b.regs);
1851
1852 if (fragment)
1853 agx_usc_push_packed(&b, FRAGMENT_PROPERTIES, s->b.fragment_props);
1854
1855 if (main && main->b.info.has_preamble) {
1856 agx_usc_pack(&b, PRESHADER, cfg) {
1857 cfg.code = agx_usc_addr(&dev->dev, main->preamble_addr);
1858 }
1859 } else {
1860 agx_usc_pack(&b, NO_PRESHADER, cfg)
1861 ;
1862 }
1863
1864 s->usc.size = b.head - s->usc.data;
1865 return s;
1866 }