• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2016 Red Hat.
3  * Copyright © 2016 Bas Nieuwenhuizen
4  *
5  * based in part on anv driver which is:
6  * Copyright © 2015 Intel Corporation
7  *
8  * SPDX-License-Identifier: MIT
9  */
10 
11 #include "radv_shader.h"
12 #include "meta/radv_meta.h"
13 #include "nir/nir.h"
14 #include "nir/nir_builder.h"
15 #include "nir/nir_xfb_info.h"
16 #include "nir/radv_nir.h"
17 #include "spirv/nir_spirv.h"
18 #include "util/memstream.h"
19 #include "util/mesa-sha1.h"
20 #include "util/streaming-load-memcpy.h"
21 #include "util/u_atomic.h"
22 #include "radv_cs.h"
23 #include "radv_debug.h"
24 #include "radv_entrypoints.h"
25 #include "radv_nir_to_llvm.h"
26 #include "radv_printf.h"
27 #include "radv_sdma.h"
28 #include "radv_shader_args.h"
29 
30 #include "util/u_debug.h"
31 #include "ac_binary.h"
32 #include "ac_nir.h"
33 #if defined(USE_LIBELF)
34 #include "ac_rtld.h"
35 #endif
36 #include "aco_interface.h"
37 #include "sid.h"
38 #include "vk_debug_report.h"
39 #include "vk_format.h"
40 #include "vk_nir.h"
41 #include "vk_semaphore.h"
42 #include "vk_sync.h"
43 
44 #include "aco_shader_info.h"
45 #include "radv_aco_shader_info.h"
46 #if AMD_LLVM_AVAILABLE
47 #include "ac_llvm_util.h"
48 #endif
49 
50 static void
get_nir_options_for_stage(struct radv_physical_device * pdev,gl_shader_stage stage)51 get_nir_options_for_stage(struct radv_physical_device *pdev, gl_shader_stage stage)
52 {
53    const struct radv_instance *instance = radv_physical_device_instance(pdev);
54    nir_shader_compiler_options *options = &pdev->nir_options[stage];
55    bool split_fma =
56       (stage <= MESA_SHADER_GEOMETRY || stage == MESA_SHADER_MESH) && instance->debug_flags & RADV_DEBUG_SPLIT_FMA;
57 
58    ac_nir_set_options(&pdev->info, pdev->use_llvm, options);
59 
60    options->lower_ffma16 = split_fma || pdev->info.gfx_level < GFX9;
61    options->lower_ffma32 = split_fma || pdev->info.gfx_level < GFX10_3;
62    options->lower_ffma64 = split_fma;
63    options->max_unroll_iterations = 32;
64    options->max_unroll_iterations_aggressive = 128;
65    options->lower_doubles_options = nir_lower_drcp | nir_lower_dsqrt | nir_lower_drsq | nir_lower_ddiv;
66    options->io_options |= nir_io_mediump_is_32bit;
67    options->varying_expression_max_cost = ac_nir_varying_expression_max_cost;
68 }
69 
70 void
radv_get_nir_options(struct radv_physical_device * pdev)71 radv_get_nir_options(struct radv_physical_device *pdev)
72 {
73    for (gl_shader_stage stage = MESA_SHADER_VERTEX; stage < MESA_VULKAN_SHADER_STAGES; stage++)
74       get_nir_options_for_stage(pdev, stage);
75 }
76 
77 static uint8_t
vectorize_vec2_16bit(const nir_instr * instr,const void * _)78 vectorize_vec2_16bit(const nir_instr *instr, const void *_)
79 {
80    if (instr->type != nir_instr_type_alu)
81       return 0;
82 
83    const nir_alu_instr *alu = nir_instr_as_alu(instr);
84    const unsigned bit_size = alu->def.bit_size;
85    if (bit_size == 16)
86       return 2;
87    else
88       return 1;
89 }
90 
91 static bool
is_meta_shader(nir_shader * nir)92 is_meta_shader(nir_shader *nir)
93 {
94    return nir && nir->info.internal;
95 }
96 
97 static uint64_t
radv_dump_flag_for_stage(const gl_shader_stage stage)98 radv_dump_flag_for_stage(const gl_shader_stage stage)
99 {
100    switch (stage) {
101    case MESA_SHADER_VERTEX:
102       return RADV_DEBUG_DUMP_VS;
103    case MESA_SHADER_TESS_CTRL:
104       return RADV_DEBUG_DUMP_TCS;
105    case MESA_SHADER_TESS_EVAL:
106       return RADV_DEBUG_DUMP_TES;
107    case MESA_SHADER_GEOMETRY:
108       return RADV_DEBUG_DUMP_GS;
109    case MESA_SHADER_FRAGMENT:
110       return RADV_DEBUG_DUMP_PS;
111    case MESA_SHADER_TASK:
112       return RADV_DEBUG_DUMP_TASK;
113    case MESA_SHADER_MESH:
114       return RADV_DEBUG_DUMP_MESH;
115    default:
116       return RADV_DEBUG_DUMP_CS;
117    }
118 }
119 
120 bool
radv_can_dump_shader(struct radv_device * device,nir_shader * nir)121 radv_can_dump_shader(struct radv_device *device, nir_shader *nir)
122 {
123    const struct radv_physical_device *pdev = radv_device_physical(device);
124    const struct radv_instance *instance = radv_physical_device_instance(pdev);
125 
126    if (is_meta_shader(nir))
127       return instance->debug_flags & RADV_DEBUG_DUMP_META_SHADERS;
128 
129    if (!nir)
130       return false;
131 
132    return instance->debug_flags & radv_dump_flag_for_stage(nir->info.stage);
133 }
134 
135 bool
radv_can_dump_shader_stats(struct radv_device * device,nir_shader * nir)136 radv_can_dump_shader_stats(struct radv_device *device, nir_shader *nir)
137 {
138    const struct radv_physical_device *pdev = radv_device_physical(device);
139    const struct radv_instance *instance = radv_physical_device_instance(pdev);
140 
141    /* Only dump non-meta shader stats. */
142    return instance->debug_flags & RADV_DEBUG_DUMP_SHADER_STATS && !is_meta_shader(nir);
143 }
144 
145 void
radv_optimize_nir(struct nir_shader * shader,bool optimize_conservatively)146 radv_optimize_nir(struct nir_shader *shader, bool optimize_conservatively)
147 {
148    bool progress;
149 
150    struct set *skip = _mesa_pointer_set_create(NULL);
151    do {
152       progress = false;
153 
154       NIR_LOOP_PASS(progress, skip, shader, nir_split_array_vars, nir_var_function_temp);
155       NIR_LOOP_PASS(progress, skip, shader, nir_shrink_vec_array_vars, nir_var_function_temp);
156 
157       if (!shader->info.var_copies_lowered) {
158          /* Only run this pass if nir_lower_var_copies was not called
159           * yet. That would lower away any copy_deref instructions and we
160           * don't want to introduce any more.
161           */
162          NIR_LOOP_PASS(progress, skip, shader, nir_opt_find_array_copies);
163       }
164 
165       NIR_LOOP_PASS(progress, skip, shader, nir_opt_copy_prop_vars);
166       NIR_LOOP_PASS(progress, skip, shader, nir_opt_dead_write_vars);
167       NIR_LOOP_PASS(_, skip, shader, nir_lower_vars_to_ssa);
168 
169       NIR_LOOP_PASS(_, skip, shader, nir_lower_alu_width, vectorize_vec2_16bit, NULL);
170       NIR_LOOP_PASS(_, skip, shader, nir_lower_phis_to_scalar, true);
171 
172       NIR_LOOP_PASS(progress, skip, shader, nir_copy_prop);
173       NIR_LOOP_PASS(progress, skip, shader, nir_opt_remove_phis);
174       NIR_LOOP_PASS(progress, skip, shader, nir_opt_dce);
175       NIR_LOOP_PASS(progress, skip, shader, nir_opt_dead_cf);
176       bool opt_loop_progress = false;
177       NIR_LOOP_PASS_NOT_IDEMPOTENT(opt_loop_progress, skip, shader, nir_opt_loop);
178       if (opt_loop_progress) {
179          progress = true;
180          NIR_LOOP_PASS(progress, skip, shader, nir_copy_prop);
181          NIR_LOOP_PASS(progress, skip, shader, nir_opt_remove_phis);
182          NIR_LOOP_PASS(progress, skip, shader, nir_opt_dce);
183       }
184       NIR_LOOP_PASS_NOT_IDEMPOTENT(progress, skip, shader, nir_opt_if, nir_opt_if_optimize_phi_true_false);
185       NIR_LOOP_PASS(progress, skip, shader, nir_opt_cse);
186       NIR_LOOP_PASS(progress, skip, shader, nir_opt_peephole_select, 8, true, true);
187       NIR_LOOP_PASS(progress, skip, shader, nir_opt_constant_folding);
188       NIR_LOOP_PASS(progress, skip, shader, nir_opt_intrinsics);
189       NIR_LOOP_PASS_NOT_IDEMPOTENT(progress, skip, shader, nir_opt_algebraic);
190 
191       NIR_LOOP_PASS(progress, skip, shader, nir_opt_undef);
192 
193       if (shader->options->max_unroll_iterations) {
194          NIR_LOOP_PASS_NOT_IDEMPOTENT(progress, skip, shader, nir_opt_loop_unroll);
195       }
196    } while (progress && !optimize_conservatively);
197    _mesa_set_destroy(skip, NULL);
198 
199    NIR_PASS(progress, shader, nir_opt_shrink_vectors, true);
200    NIR_PASS(progress, shader, nir_remove_dead_variables,
201             nir_var_function_temp | nir_var_shader_in | nir_var_shader_out | nir_var_mem_shared, NULL);
202 
203    if (shader->info.stage == MESA_SHADER_FRAGMENT && shader->info.fs.uses_discard) {
204       NIR_PASS(progress, shader, nir_opt_conditional_discard);
205       NIR_PASS(progress, shader, nir_opt_move_discards_to_top);
206    }
207 
208    NIR_PASS(progress, shader, nir_opt_move, nir_move_load_ubo);
209 }
210 
211 void
radv_optimize_nir_algebraic(nir_shader * nir,bool opt_offsets,bool opt_mqsad)212 radv_optimize_nir_algebraic(nir_shader *nir, bool opt_offsets, bool opt_mqsad)
213 {
214    bool more_algebraic = true;
215    while (more_algebraic) {
216       more_algebraic = false;
217       NIR_PASS(_, nir, nir_copy_prop);
218       NIR_PASS(_, nir, nir_opt_dce);
219       NIR_PASS(_, nir, nir_opt_constant_folding);
220       NIR_PASS(_, nir, nir_opt_cse);
221       NIR_PASS(_, nir, nir_opt_peephole_select, 3, true, true);
222       NIR_PASS(more_algebraic, nir, nir_opt_algebraic);
223       NIR_PASS(_, nir, nir_opt_generate_bfi);
224       NIR_PASS(_, nir, nir_opt_remove_phis);
225       NIR_PASS(_, nir, nir_opt_dead_cf);
226    }
227 
228    if (opt_offsets) {
229       static const nir_opt_offsets_options offset_options = {
230          .uniform_max = 0,
231          .buffer_max = ~0,
232          .shared_max = ~0,
233          .shared_atomic_max = ~0,
234       };
235       NIR_PASS(_, nir, nir_opt_offsets, &offset_options);
236    }
237    if (opt_mqsad)
238       NIR_PASS(_, nir, nir_opt_mqsad);
239 
240    /* Do late algebraic optimization to turn add(a,
241     * neg(b)) back into subs, then the mandatory cleanup
242     * after algebraic.  Note that it may produce fnegs,
243     * and if so then we need to keep running to squash
244     * fneg(fneg(a)).
245     */
246    bool more_late_algebraic = true;
247    struct set *skip = _mesa_pointer_set_create(NULL);
248    while (more_late_algebraic) {
249       more_late_algebraic = false;
250       NIR_LOOP_PASS_NOT_IDEMPOTENT(more_late_algebraic, skip, nir, nir_opt_algebraic_late);
251       NIR_LOOP_PASS(_, skip, nir, nir_opt_constant_folding);
252       NIR_LOOP_PASS(_, skip, nir, nir_copy_prop);
253       NIR_LOOP_PASS(_, skip, nir, nir_opt_dce);
254       NIR_LOOP_PASS(_, skip, nir, nir_opt_cse);
255    }
256    _mesa_set_destroy(skip, NULL);
257 }
258 
259 static void
shared_var_info(const struct glsl_type * type,unsigned * size,unsigned * align)260 shared_var_info(const struct glsl_type *type, unsigned *size, unsigned *align)
261 {
262    assert(glsl_type_is_vector_or_scalar(type));
263 
264    uint32_t comp_size = glsl_type_is_boolean(type) ? 4 : glsl_get_bit_size(type) / 8;
265    unsigned length = glsl_get_vector_elements(type);
266    *size = comp_size * length, *align = comp_size;
267 }
268 
269 struct radv_shader_debug_data {
270    struct radv_device *device;
271    const struct vk_object_base *object;
272 };
273 
274 static void
radv_spirv_nir_debug(void * private_data,enum nir_spirv_debug_level level,size_t spirv_offset,const char * message)275 radv_spirv_nir_debug(void *private_data, enum nir_spirv_debug_level level, size_t spirv_offset, const char *message)
276 {
277    struct radv_shader_debug_data *debug_data = private_data;
278    const struct radv_physical_device *pdev = radv_device_physical(debug_data->device);
279    struct radv_instance *instance = radv_physical_device_instance(pdev);
280 
281    static const VkDebugReportFlagsEXT vk_flags[] = {
282       [NIR_SPIRV_DEBUG_LEVEL_INFO] = VK_DEBUG_REPORT_INFORMATION_BIT_EXT,
283       [NIR_SPIRV_DEBUG_LEVEL_WARNING] = VK_DEBUG_REPORT_WARNING_BIT_EXT,
284       [NIR_SPIRV_DEBUG_LEVEL_ERROR] = VK_DEBUG_REPORT_ERROR_BIT_EXT,
285    };
286    char buffer[256];
287 
288    snprintf(buffer, sizeof(buffer), "SPIR-V offset %lu: %s", (unsigned long)spirv_offset, message);
289 
290    vk_debug_report(&instance->vk, vk_flags[level], debug_data->object, 0, 0, "radv", buffer);
291 }
292 
293 static void
radv_compiler_debug(void * private_data,enum aco_compiler_debug_level level,const char * message)294 radv_compiler_debug(void *private_data, enum aco_compiler_debug_level level, const char *message)
295 {
296    struct radv_shader_debug_data *debug_data = private_data;
297    const struct radv_physical_device *pdev = radv_device_physical(debug_data->device);
298    struct radv_instance *instance = radv_physical_device_instance(pdev);
299 
300    static const VkDebugReportFlagsEXT vk_flags[] = {
301       [ACO_COMPILER_DEBUG_LEVEL_ERROR] = VK_DEBUG_REPORT_ERROR_BIT_EXT,
302    };
303 
304    /* VK_DEBUG_REPORT_DEBUG_BIT_EXT specifies diagnostic information
305     * from the implementation and layers.
306     */
307    vk_debug_report(&instance->vk, vk_flags[level] | VK_DEBUG_REPORT_DEBUG_BIT_EXT, NULL, 0, 0, "radv", message);
308 }
309 
310 nir_shader *
radv_shader_spirv_to_nir(struct radv_device * device,const struct radv_shader_stage * stage,const struct radv_spirv_to_nir_options * options,bool is_internal)311 radv_shader_spirv_to_nir(struct radv_device *device, const struct radv_shader_stage *stage,
312                          const struct radv_spirv_to_nir_options *options, bool is_internal)
313 {
314    const struct radv_physical_device *pdev = radv_device_physical(device);
315    const struct radv_instance *instance = radv_physical_device_instance(pdev);
316    unsigned subgroup_size = 64, ballot_bit_size = 64;
317    const unsigned required_subgroup_size = stage->key.subgroup_required_size * 32;
318    if (required_subgroup_size) {
319       /* Only compute/mesh/task shaders currently support requiring a
320        * specific subgroup size.
321        */
322       assert(stage->stage >= MESA_SHADER_COMPUTE);
323       subgroup_size = required_subgroup_size;
324       ballot_bit_size = required_subgroup_size;
325    }
326 
327    nir_shader *nir;
328 
329    if (stage->internal_nir) {
330       /* Some things such as our meta clear/blit code will give us a NIR
331        * shader directly.  In that case, we just ignore the SPIR-V entirely
332        * and just use the NIR shader.  We don't want to alter meta and RT
333        * shaders IR directly, so clone it first. */
334       nir = nir_shader_clone(NULL, stage->internal_nir);
335       nir_validate_shader(nir, "in internal shader");
336 
337       assert(exec_list_length(&nir->functions) == 1);
338    } else {
339       uint32_t *spirv = (uint32_t *)stage->spirv.data;
340       assert(stage->spirv.size % 4 == 0);
341 
342       if (instance->debug_flags & RADV_DEBUG_DUMP_SPIRV) {
343          const uint64_t dump_flags =
344             is_internal ? RADV_DEBUG_DUMP_META_SHADERS : radv_dump_flag_for_stage(stage->stage);
345          if (instance->debug_flags & dump_flags)
346             spirv_print_asm(stderr, (const uint32_t *)stage->spirv.data, stage->spirv.size / 4);
347       }
348 
349       uint32_t num_spec_entries = 0;
350       struct nir_spirv_specialization *spec_entries = vk_spec_info_to_nir_spirv(stage->spec_info, &num_spec_entries);
351       struct radv_shader_debug_data spirv_debug_data = {
352          .device = device,
353          .object = stage->spirv.object,
354       };
355       const struct spirv_capabilities spirv_caps =
356          vk_physical_device_get_spirv_capabilities(device->vk.physical);
357       const struct spirv_to_nir_options spirv_options = {
358          .amd_gcn_shader = true,
359          .amd_shader_ballot = true,
360          .amd_shader_explicit_vertex_parameter = true,
361          .amd_trinary_minmax = true,
362          .capabilities = &spirv_caps,
363          .ubo_addr_format = nir_address_format_vec2_index_32bit_offset,
364          .ssbo_addr_format = nir_address_format_vec2_index_32bit_offset,
365          .phys_ssbo_addr_format = nir_address_format_64bit_global,
366          .push_const_addr_format = nir_address_format_logical,
367          .shared_addr_format = nir_address_format_32bit_offset,
368          .constant_addr_format = nir_address_format_64bit_global,
369          .debug =
370             {
371                .func = radv_spirv_nir_debug,
372                .private_data = &spirv_debug_data,
373             },
374          .force_tex_non_uniform = pdev->cache_key.tex_non_uniform,
375          .force_ssbo_non_uniform = pdev->cache_key.ssbo_non_uniform,
376          .lower_terminate_to_discard = pdev->cache_key.lower_terminate_to_discard,
377          .emit_debug_break = !!device->trap_handler_shader,
378       };
379       nir = spirv_to_nir(spirv, stage->spirv.size / 4, spec_entries, num_spec_entries, stage->stage, stage->entrypoint,
380                          &spirv_options, &pdev->nir_options[stage->stage]);
381       nir->info.internal |= is_internal;
382       assert(nir->info.stage == stage->stage);
383       nir_validate_shader(nir, "after spirv_to_nir");
384 
385       free(spec_entries);
386 
387       radv_device_associate_nir(device, nir);
388 
389       const struct nir_lower_sysvals_to_varyings_options sysvals_to_varyings = {
390          .point_coord = true,
391       };
392       NIR_PASS_V(nir, nir_lower_sysvals_to_varyings, &sysvals_to_varyings);
393 
394       /* We have to lower away local constant initializers right before we
395        * inline functions.  That way they get properly initialized at the top
396        * of the function and not at the top of its caller.
397        */
398       NIR_PASS(_, nir, nir_lower_variable_initializers, nir_var_function_temp);
399       NIR_PASS(_, nir, nir_lower_returns);
400       bool progress = false;
401       NIR_PASS(progress, nir, nir_inline_functions);
402       if (progress) {
403          NIR_PASS(_, nir, nir_opt_copy_prop_vars);
404          NIR_PASS(_, nir, nir_copy_prop);
405       }
406       NIR_PASS(_, nir, nir_opt_deref);
407 
408       /* Pick off the single entrypoint that we want */
409       nir_remove_non_entrypoints(nir);
410 
411       /* Make sure we lower constant initializers on output variables so that
412        * nir_remove_dead_variables below sees the corresponding stores
413        */
414       NIR_PASS(_, nir, nir_lower_variable_initializers, nir_var_shader_out);
415 
416       /* Now that we've deleted all but the main function, we can go ahead and
417        * lower the rest of the constant initializers.
418        */
419       NIR_PASS(_, nir, nir_lower_variable_initializers, ~0);
420 
421       NIR_PASS(_, nir, radv_nir_lower_cooperative_matrix, subgroup_size);
422 
423       /* Split member structs.  We do this before lower_io_to_temporaries so that
424        * it doesn't lower system values to temporaries by accident.
425        */
426       NIR_PASS(_, nir, nir_split_var_copies);
427       NIR_PASS(_, nir, nir_split_per_member_structs);
428 
429       if (nir->info.stage == MESA_SHADER_FRAGMENT)
430          NIR_PASS(_, nir, nir_lower_io_to_vector, nir_var_shader_out);
431       if (nir->info.stage == MESA_SHADER_FRAGMENT)
432          NIR_PASS(_, nir, nir_lower_input_attachments,
433                   &(nir_input_attachment_options){
434                      .use_fragcoord_sysval = true,
435                      .use_layer_id_sysval = true,
436                   });
437 
438       nir_remove_dead_variables_options dead_vars_opts = {
439          .can_remove_var = nir_vk_is_not_xfb_output,
440       };
441       NIR_PASS(_, nir, nir_remove_dead_variables,
442                nir_var_shader_in | nir_var_shader_out | nir_var_system_value | nir_var_mem_shared, &dead_vars_opts);
443 
444       /* Variables can make nir_propagate_invariant more conservative
445        * than it needs to be.
446        */
447       NIR_PASS(_, nir, nir_lower_global_vars_to_local);
448 
449       NIR_PASS(_, nir, nir_lower_vars_to_ssa);
450 
451       NIR_PASS(_, nir, nir_propagate_invariant, pdev->cache_key.invariant_geom);
452 
453       NIR_PASS(_, nir, nir_lower_clip_cull_distance_arrays);
454 
455       if (nir->info.stage == MESA_SHADER_VERTEX || nir->info.stage == MESA_SHADER_TESS_EVAL ||
456           nir->info.stage == MESA_SHADER_GEOMETRY)
457          NIR_PASS_V(nir, nir_shader_gather_xfb_info);
458 
459       nir_lower_doubles_options lower_doubles = nir->options->lower_doubles_options;
460 
461       if (pdev->info.gfx_level == GFX6) {
462          /* GFX6 doesn't support v_floor_f64 and the precision
463           * of v_fract_f64 which is used to implement 64-bit
464           * floor is less than what Vulkan requires.
465           */
466          lower_doubles |= nir_lower_dfloor;
467       }
468 
469       NIR_PASS(_, nir, nir_lower_doubles, NULL, lower_doubles);
470 
471       NIR_PASS(_, nir, ac_nir_lower_sin_cos);
472    }
473 
474    if (options && options->lower_view_index_to_device_index)
475       NIR_PASS(_, nir, nir_lower_view_index_to_device_index);
476 
477    NIR_PASS(_, nir, nir_lower_system_values);
478    nir_lower_compute_system_values_options csv_options = {
479       /* Mesh shaders run as NGG which can implement local_invocation_index from
480        * the wave ID in merged_wave_info, but they don't have local_invocation_ids on GFX10.3.
481        */
482       .lower_cs_local_id_to_index = nir->info.stage == MESA_SHADER_MESH && !pdev->mesh_fast_launch_2,
483       .lower_local_invocation_index = nir->info.stage == MESA_SHADER_COMPUTE &&
484                                       ((nir->info.workgroup_size[0] == 1) + (nir->info.workgroup_size[1] == 1) +
485                                        (nir->info.workgroup_size[2] == 1)) == 2,
486    };
487    NIR_PASS(_, nir, nir_lower_compute_system_values, &csv_options);
488 
489    /* Vulkan uses the separate-shader linking model */
490    nir->info.separate_shader = true;
491 
492    nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
493 
494    if (nir->info.ray_queries > 0) {
495       /* Lower shared variables early to prevent the over allocation of shared memory in
496        * radv_nir_lower_ray_queries.  */
497       if (nir->info.stage == MESA_SHADER_COMPUTE) {
498          if (!nir->info.shared_memory_explicit_layout)
499             NIR_PASS(_, nir, nir_lower_vars_to_explicit_types, nir_var_mem_shared, shared_var_info);
500 
501          NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_shared, nir_address_format_32bit_offset);
502       }
503 
504       NIR_PASS(_, nir, nir_opt_ray_queries);
505       NIR_PASS(_, nir, nir_opt_ray_query_ranges);
506       NIR_PASS(_, nir, radv_nir_lower_ray_queries, device);
507    }
508 
509    nir_lower_tex_options tex_options = {
510       .lower_txp = ~0,
511       .lower_txf_offset = true,
512       .lower_tg4_offsets = true,
513       .lower_txs_cube_array = true,
514       .lower_to_fragment_fetch_amd = pdev->use_fmask,
515       .lower_lod_zero_width = true,
516       .lower_invalid_implicit_lod = true,
517       .lower_1d = pdev->info.gfx_level == GFX9,
518    };
519 
520    NIR_PASS(_, nir, nir_lower_tex, &tex_options);
521 
522    static const nir_lower_image_options image_options = {
523       .lower_cube_size = true,
524    };
525 
526    NIR_PASS(_, nir, nir_lower_image, &image_options);
527 
528    NIR_PASS(_, nir, nir_lower_vars_to_ssa);
529 
530    if (nir->info.stage == MESA_SHADER_VERTEX || nir->info.stage == MESA_SHADER_GEOMETRY ||
531        nir->info.stage == MESA_SHADER_FRAGMENT) {
532       NIR_PASS_V(nir, nir_lower_io_to_temporaries, nir_shader_get_entrypoint(nir), true, true);
533    } else if (nir->info.stage == MESA_SHADER_TESS_EVAL) {
534       NIR_PASS_V(nir, nir_lower_io_to_temporaries, nir_shader_get_entrypoint(nir), true, false);
535    }
536 
537    NIR_PASS(_, nir, nir_split_var_copies);
538 
539    NIR_PASS(_, nir, nir_lower_global_vars_to_local);
540    NIR_PASS(_, nir, nir_remove_dead_variables, nir_var_function_temp, NULL);
541 
542    bool gfx7minus = pdev->info.gfx_level <= GFX7;
543    bool has_inverse_ballot = true;
544    bool use_llvm = radv_use_llvm_for_stage(pdev, nir->info.stage);
545 #if AMD_LLVM_AVAILABLE
546    has_inverse_ballot = !use_llvm || LLVM_VERSION_MAJOR >= 17;
547 #endif
548 
549    NIR_PASS(_, nir, nir_lower_subgroups,
550             &(struct nir_lower_subgroups_options){
551                .subgroup_size = subgroup_size,
552                .ballot_bit_size = ballot_bit_size,
553                .ballot_components = 1,
554                .lower_to_scalar = 1,
555                .lower_subgroup_masks = 1,
556                .lower_relative_shuffle = 1,
557                .lower_rotate_to_shuffle = use_llvm,
558                .lower_shuffle_to_32bit = 1,
559                .lower_vote_eq = 1,
560                .lower_vote_bool_eq = 1,
561                .lower_quad_broadcast_dynamic = 1,
562                .lower_quad_broadcast_dynamic_to_const = gfx7minus,
563                .lower_shuffle_to_swizzle_amd = 1,
564                .lower_ballot_bit_count_to_mbcnt_amd = 1,
565                .lower_inverse_ballot = !has_inverse_ballot,
566                .lower_boolean_reduce = !use_llvm,
567                .lower_boolean_shuffle = true,
568             });
569 
570    NIR_PASS(_, nir, nir_lower_load_const_to_scalar);
571    NIR_PASS(_, nir, nir_opt_shrink_stores, !instance->drirc.disable_shrink_image_store);
572 
573    if (!stage->key.optimisations_disabled)
574       radv_optimize_nir(nir, false);
575 
576    /* We call nir_lower_var_copies() after the first radv_optimize_nir()
577     * to remove any copies introduced by nir_opt_find_array_copies().
578     */
579    NIR_PASS(_, nir, nir_lower_var_copies);
580 
581    unsigned lower_flrp = (nir->options->lower_flrp16 ? 16 : 0) | (nir->options->lower_flrp32 ? 32 : 0) |
582                          (nir->options->lower_flrp64 ? 64 : 0);
583    if (lower_flrp != 0) {
584       bool progress = false;
585       NIR_PASS(progress, nir, nir_lower_flrp, lower_flrp, false /* always precise */);
586       if (progress)
587          NIR_PASS(_, nir, nir_opt_constant_folding);
588    }
589 
590    const nir_opt_access_options opt_access_options = {
591       .is_vulkan = true,
592    };
593    NIR_PASS(_, nir, nir_opt_access, &opt_access_options);
594 
595    NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_push_const, nir_address_format_32bit_offset);
596 
597    NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_ubo | nir_var_mem_ssbo,
598             nir_address_format_vec2_index_32bit_offset);
599 
600    NIR_PASS(_, nir, radv_nir_lower_intrinsics_early, options && options->lower_view_index_to_zero);
601 
602    /* Lower deref operations for compute shared memory. */
603    if (nir->info.stage == MESA_SHADER_COMPUTE || nir->info.stage == MESA_SHADER_TASK ||
604        nir->info.stage == MESA_SHADER_MESH) {
605       nir_variable_mode var_modes = nir_var_mem_shared;
606 
607       if (nir->info.stage == MESA_SHADER_TASK || nir->info.stage == MESA_SHADER_MESH)
608          var_modes |= nir_var_mem_task_payload;
609 
610       if (!nir->info.shared_memory_explicit_layout)
611          NIR_PASS(_, nir, nir_lower_vars_to_explicit_types, var_modes, shared_var_info);
612       else if (var_modes & ~nir_var_mem_shared)
613          NIR_PASS(_, nir, nir_lower_vars_to_explicit_types, var_modes & ~nir_var_mem_shared, shared_var_info);
614       NIR_PASS(_, nir, nir_lower_explicit_io, var_modes, nir_address_format_32bit_offset);
615 
616       if (nir->info.zero_initialize_shared_memory && nir->info.shared_size > 0) {
617          const unsigned chunk_size = 16; /* max single store size */
618          const unsigned shared_size = ALIGN(nir->info.shared_size, chunk_size);
619          NIR_PASS(_, nir, nir_zero_initialize_shared_memory, shared_size, chunk_size);
620       }
621    }
622 
623    NIR_PASS(_, nir, nir_lower_explicit_io, nir_var_mem_global | nir_var_mem_constant, nir_address_format_64bit_global);
624 
625    /* Lower large variables that are always constant with load_constant
626     * intrinsics, which get turned into PC-relative loads from a data
627     * section next to the shader.
628     */
629    NIR_PASS(_, nir, nir_opt_large_constants, glsl_get_natural_size_align_bytes, 16);
630 
631    /* Lower primitive shading rate to match HW requirements. */
632    if ((nir->info.stage == MESA_SHADER_VERTEX || nir->info.stage == MESA_SHADER_GEOMETRY ||
633         nir->info.stage == MESA_SHADER_MESH) &&
634        nir->info.outputs_written & BITFIELD64_BIT(VARYING_SLOT_PRIMITIVE_SHADING_RATE)) {
635       /* Lower primitive shading rate to match HW requirements. */
636       NIR_PASS(_, nir, radv_nir_lower_primitive_shading_rate, pdev->info.gfx_level);
637    }
638 
639    /* Indirect lowering must be called after the radv_optimize_nir() loop
640     * has been called at least once. Otherwise indirect lowering can
641     * bloat the instruction count of the loop and cause it to be
642     * considered too large for unrolling.
643     */
644    if (ac_nir_lower_indirect_derefs(nir, pdev->info.gfx_level) && !stage->key.optimisations_disabled &&
645        nir->info.stage != MESA_SHADER_COMPUTE) {
646       /* Optimize the lowered code before the linking optimizations. */
647       radv_optimize_nir(nir, false);
648    }
649 
650    return nir;
651 }
652 
653 bool
radv_consider_culling(const struct radv_physical_device * pdev,struct nir_shader * nir,uint64_t ps_inputs_read,unsigned num_vertices_per_primitive,const struct radv_shader_info * info)654 radv_consider_culling(const struct radv_physical_device *pdev, struct nir_shader *nir, uint64_t ps_inputs_read,
655                       unsigned num_vertices_per_primitive, const struct radv_shader_info *info)
656 {
657    /* Culling doesn't make sense for meta shaders. */
658    if (is_meta_shader(nir))
659       return false;
660 
661    /* We don't support culling with multiple viewports yet. */
662    if (nir->info.outputs_written & (VARYING_BIT_VIEWPORT | VARYING_BIT_VIEWPORT_MASK))
663       return false;
664 
665    /* We don't support culling with vertex shader prologs. */
666    if (info->vs.has_prolog)
667       return false;
668 
669    if (!pdev->use_ngg_culling)
670       return false;
671 
672    /* Shader based culling efficiency can depend on PS throughput.
673     * Estimate an upper limit for PS input param count based on GPU info.
674     */
675    unsigned max_ps_params = 8;
676 
677    if (pdev->info.gfx_level >= GFX10_3 && pdev->info.has_dedicated_vram)
678       max_ps_params = 12; /* GFX10.3 and newer discrete GPUs. */
679    else if (pdev->info.gfx_level == GFX10 && pdev->info.has_dedicated_vram)
680       max_ps_params = 12;
681 
682    /* TODO: consider other heuristics here, such as PS execution time */
683    if (util_bitcount64(ps_inputs_read) > max_ps_params)
684       return false;
685 
686    /* Only triangle culling is supported. */
687    if (num_vertices_per_primitive != 3)
688       return false;
689 
690    /* When the shader writes memory, it is difficult to guarantee correctness.
691     * Future work:
692     * - if only write-only SSBOs are used
693     * - if we can prove that non-position outputs don't rely on memory stores
694     * then may be okay to keep the memory stores in the 1st shader part, and delete them from the 2nd.
695     */
696    if (nir->info.writes_memory)
697       return false;
698 
699    /* When the shader relies on the subgroup invocation ID, we'd break it, because the ID changes after the culling.
700     * Future work: try to save this to LDS and reload, but it can still be broken in subtle ways.
701     */
702    if (BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_SUBGROUP_INVOCATION))
703       return false;
704 
705    /* When re-using values that depend on subgroup operations, we'd break convergence guarantees.
706     * Since we only re-use uniform values, the only subgroup operations we really care about are
707     * ballot, reductions and vote intrinsics.
708     */
709    if (nir->info.maximally_reconverges && nir->info.uses_wide_subgroup_intrinsics)
710       return false;
711 
712    return true;
713 }
714 
715 void
radv_lower_ngg(struct radv_device * device,struct radv_shader_stage * ngg_stage,const struct radv_graphics_state_key * gfx_state)716 radv_lower_ngg(struct radv_device *device, struct radv_shader_stage *ngg_stage,
717                const struct radv_graphics_state_key *gfx_state)
718 {
719    const struct radv_physical_device *pdev = radv_device_physical(device);
720    const struct radv_shader_info *info = &ngg_stage->info;
721    nir_shader *nir = ngg_stage->nir;
722 
723    assert(nir->info.stage == MESA_SHADER_VERTEX || nir->info.stage == MESA_SHADER_TESS_EVAL ||
724           nir->info.stage == MESA_SHADER_GEOMETRY || nir->info.stage == MESA_SHADER_MESH);
725 
726    unsigned num_vertices_per_prim = 3;
727 
728    /* Get the number of vertices per input primitive */
729    if (nir->info.stage == MESA_SHADER_TESS_EVAL) {
730       if (nir->info.tess.point_mode)
731          num_vertices_per_prim = 1;
732       else if (nir->info.tess._primitive_mode == TESS_PRIMITIVE_ISOLINES)
733          num_vertices_per_prim = 2;
734 
735       /* Manually mark the primitive ID used, so the shader can repack it. */
736       if (info->outinfo.export_prim_id)
737          BITSET_SET(nir->info.system_values_read, SYSTEM_VALUE_PRIMITIVE_ID);
738 
739    } else if (nir->info.stage == MESA_SHADER_VERTEX) {
740       num_vertices_per_prim = radv_get_num_vertices_per_prim(gfx_state);
741 
742       /* Manually mark the instance ID used, so the shader can repack it. */
743       if (gfx_state->vi.instance_rate_inputs)
744          BITSET_SET(nir->info.system_values_read, SYSTEM_VALUE_INSTANCE_ID);
745 
746    } else if (nir->info.stage == MESA_SHADER_GEOMETRY) {
747       num_vertices_per_prim = nir->info.gs.vertices_in;
748    } else if (nir->info.stage == MESA_SHADER_MESH) {
749       if (nir->info.mesh.primitive_type == MESA_PRIM_POINTS)
750          num_vertices_per_prim = 1;
751       else if (nir->info.mesh.primitive_type == MESA_PRIM_LINES)
752          num_vertices_per_prim = 2;
753       else
754          assert(nir->info.mesh.primitive_type == MESA_PRIM_TRIANGLES);
755    } else {
756       unreachable("NGG needs to be VS, TES or GS.");
757    }
758 
759    if (nir->info.stage != MESA_SHADER_MESH)
760       nir->info.shared_size = info->ngg_info.lds_size;
761 
762    ac_nir_lower_ngg_options options = {0};
763    options.family = pdev->info.family;
764    options.gfx_level = pdev->info.gfx_level;
765    options.max_workgroup_size = info->workgroup_size;
766    options.wave_size = info->wave_size;
767    options.clip_cull_dist_mask = info->outinfo.clip_dist_mask | info->outinfo.cull_dist_mask;
768    options.vs_output_param_offset = info->outinfo.vs_output_param_offset;
769    options.has_param_exports = info->outinfo.param_exports || info->outinfo.prim_param_exports;
770    options.can_cull = nir->info.stage != MESA_SHADER_GEOMETRY && info->has_ngg_culling;
771    options.disable_streamout = !pdev->use_ngg_streamout;
772    options.has_gen_prim_query = info->has_prim_query;
773    options.has_xfb_prim_query = info->has_xfb_query;
774    options.has_gs_invocations_query = pdev->info.gfx_level < GFX11;
775    options.has_gs_primitives_query = pdev->info.gfx_level < GFX11;
776    options.force_vrs = info->force_vrs_per_vertex;
777 
778    if (nir->info.stage == MESA_SHADER_VERTEX || nir->info.stage == MESA_SHADER_TESS_EVAL) {
779       assert(info->is_ngg);
780 
781       if (info->has_ngg_culling)
782          radv_optimize_nir_algebraic(nir, false, false);
783 
784       options.num_vertices_per_primitive = num_vertices_per_prim;
785       options.early_prim_export = info->has_ngg_early_prim_export;
786       options.passthrough = info->is_ngg_passthrough;
787       options.export_primitive_id = info->outinfo.export_prim_id;
788       options.export_primitive_id_per_prim = info->outinfo.export_prim_id_per_primitive;
789       options.instance_rate_inputs = gfx_state->vi.instance_rate_inputs << VERT_ATTRIB_GENERIC0;
790 
791       NIR_PASS_V(nir, ac_nir_lower_ngg_nogs, &options);
792 
793       /* Increase ESGS ring size so the LLVM binary contains the correct LDS size. */
794       ngg_stage->info.ngg_info.esgs_ring_size = nir->info.shared_size;
795    } else if (nir->info.stage == MESA_SHADER_GEOMETRY) {
796       assert(info->is_ngg);
797 
798       options.gs_out_vtx_bytes = info->gs.gsvs_vertex_size;
799 
800       NIR_PASS_V(nir, ac_nir_lower_ngg_gs, &options);
801    } else if (nir->info.stage == MESA_SHADER_MESH) {
802       /* ACO aligns the workgroup size to the wave size. */
803       unsigned hw_workgroup_size = ALIGN(info->workgroup_size, info->wave_size);
804 
805       bool scratch_ring = false;
806       NIR_PASS_V(nir, ac_nir_lower_ngg_mesh, options.gfx_level, options.clip_cull_dist_mask,
807                  options.vs_output_param_offset, options.has_param_exports, &scratch_ring, info->wave_size,
808                  hw_workgroup_size, gfx_state->has_multiview_view_index, info->ms.has_query, pdev->mesh_fast_launch_2);
809       ngg_stage->info.ms.needs_ms_scratch_ring = scratch_ring;
810    } else {
811       unreachable("invalid SW stage passed to radv_lower_ngg");
812    }
813 }
814 
815 static unsigned
get_size_class(unsigned size,bool round_up)816 get_size_class(unsigned size, bool round_up)
817 {
818    size = round_up ? util_logbase2_ceil(size) : util_logbase2(size);
819    unsigned size_class = MAX2(size, RADV_SHADER_ALLOC_MIN_SIZE_CLASS) - RADV_SHADER_ALLOC_MIN_SIZE_CLASS;
820    return MIN2(size_class, RADV_SHADER_ALLOC_NUM_FREE_LISTS - 1);
821 }
822 
823 static void
remove_hole(struct radv_shader_free_list * free_list,union radv_shader_arena_block * hole)824 remove_hole(struct radv_shader_free_list *free_list, union radv_shader_arena_block *hole)
825 {
826    unsigned size_class = get_size_class(hole->size, false);
827    list_del(&hole->freelist);
828    if (list_is_empty(&free_list->free_lists[size_class]))
829       free_list->size_mask &= ~(1u << size_class);
830 }
831 
832 static void
add_hole(struct radv_shader_free_list * free_list,union radv_shader_arena_block * hole)833 add_hole(struct radv_shader_free_list *free_list, union radv_shader_arena_block *hole)
834 {
835    unsigned size_class = get_size_class(hole->size, false);
836    list_addtail(&hole->freelist, &free_list->free_lists[size_class]);
837    free_list->size_mask |= 1u << size_class;
838 }
839 
840 static union radv_shader_arena_block *
alloc_block_obj(struct radv_device * device)841 alloc_block_obj(struct radv_device *device)
842 {
843    if (!list_is_empty(&device->shader_block_obj_pool)) {
844       union radv_shader_arena_block *block =
845          list_first_entry(&device->shader_block_obj_pool, union radv_shader_arena_block, pool);
846       list_del(&block->pool);
847       return block;
848    }
849 
850    return malloc(sizeof(union radv_shader_arena_block));
851 }
852 
853 static void
free_block_obj(struct radv_device * device,union radv_shader_arena_block * block)854 free_block_obj(struct radv_device *device, union radv_shader_arena_block *block)
855 {
856    list_del(&block->pool);
857    list_add(&block->pool, &device->shader_block_obj_pool);
858 }
859 
860 VkResult
radv_shader_wait_for_upload(struct radv_device * device,uint64_t seq)861 radv_shader_wait_for_upload(struct radv_device *device, uint64_t seq)
862 {
863    if (!seq)
864       return VK_SUCCESS;
865 
866    const VkSemaphoreWaitInfo wait_info = {
867       .sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO,
868       .pSemaphores = &device->shader_upload_sem,
869       .semaphoreCount = 1,
870       .pValues = &seq,
871    };
872    return device->vk.dispatch_table.WaitSemaphores(radv_device_to_handle(device), &wait_info, UINT64_MAX);
873 }
874 
875 static struct radv_shader_arena *
radv_create_shader_arena(struct radv_device * device,struct radv_shader_free_list * free_list,unsigned min_size,unsigned arena_size,bool replayable,uint64_t replay_va)876 radv_create_shader_arena(struct radv_device *device, struct radv_shader_free_list *free_list, unsigned min_size,
877                          unsigned arena_size, bool replayable, uint64_t replay_va)
878 {
879    const struct radv_physical_device *pdev = radv_device_physical(device);
880    union radv_shader_arena_block *alloc = NULL;
881    struct radv_shader_arena *arena = calloc(1, sizeof(struct radv_shader_arena));
882    if (!arena)
883       goto fail;
884 
885    if (!arena_size)
886       arena_size = MAX2(
887          RADV_SHADER_ALLOC_MIN_ARENA_SIZE << MIN2(RADV_SHADER_ALLOC_MAX_ARENA_SIZE_SHIFT, device->shader_arena_shift),
888          min_size);
889    arena->size = arena_size;
890 
891    enum radeon_bo_flag flags = RADEON_FLAG_NO_INTERPROCESS_SHARING | RADEON_FLAG_32BIT;
892    if (device->shader_use_invisible_vram)
893       flags |= RADEON_FLAG_NO_CPU_ACCESS;
894    else
895       flags |= (pdev->info.cpdma_prefetch_writes_memory ? 0 : RADEON_FLAG_READ_ONLY);
896 
897    if (replayable)
898       flags |= RADEON_FLAG_REPLAYABLE;
899 
900    VkResult result;
901    result = radv_bo_create(device, NULL, arena_size, RADV_SHADER_ALLOC_ALIGNMENT, RADEON_DOMAIN_VRAM, flags,
902                            RADV_BO_PRIORITY_SHADER, replay_va, true, &arena->bo);
903    if (result != VK_SUCCESS)
904       goto fail;
905 
906    list_inithead(&arena->entries);
907    alloc = alloc_block_obj(device);
908    if (!alloc)
909       goto fail;
910 
911    list_inithead(&alloc->freelist);
912    alloc->arena = arena;
913    alloc->offset = 0;
914    alloc->size = arena_size;
915    list_addtail(&alloc->list, &arena->entries);
916    if (free_list)
917       add_hole(free_list, alloc);
918 
919    if (!(flags & RADEON_FLAG_NO_CPU_ACCESS)) {
920       arena->ptr = (char *)radv_buffer_map(device->ws, arena->bo);
921       if (!arena->ptr)
922          goto fail;
923    }
924 
925    if (replay_va)
926       arena->type = RADV_SHADER_ARENA_REPLAYED;
927    else if (replayable)
928       arena->type = RADV_SHADER_ARENA_REPLAYABLE;
929    else
930       arena->type = RADV_SHADER_ARENA_DEFAULT;
931 
932    return arena;
933 
934 fail:
935    if (alloc)
936       free_block_obj(device, alloc);
937    if (arena && arena->bo)
938       radv_bo_destroy(device, NULL, arena->bo);
939    free(arena);
940    return NULL;
941 }
942 
943 /* Inserts a block at an arbitrary place into a hole, splitting the hole as needed */
944 static union radv_shader_arena_block *
insert_block(struct radv_device * device,union radv_shader_arena_block * hole,uint32_t offset_in_hole,uint32_t size,struct radv_shader_free_list * free_list)945 insert_block(struct radv_device *device, union radv_shader_arena_block *hole, uint32_t offset_in_hole, uint32_t size,
946              struct radv_shader_free_list *free_list)
947 {
948    uint32_t hole_begin = hole->offset;
949    uint32_t hole_end = hole->offset + hole->size;
950 
951    /* The block might not lie exactly at the beginning or end
952     * of the hole. Resize the hole to fit the block exactly,
953     * and insert new holes before (left_hole) or after (right_hole) as needed.
954     * left_hole or right_hole are skipped if the allocation lies exactly at the
955     * beginning or end of the hole to avoid 0-sized holes. */
956    union radv_shader_arena_block *left_hole = NULL;
957    union radv_shader_arena_block *right_hole = NULL;
958 
959    if (offset_in_hole) {
960       left_hole = alloc_block_obj(device);
961       if (!left_hole)
962          return NULL;
963       list_inithead(&left_hole->freelist);
964       left_hole->arena = hole->arena;
965       left_hole->offset = hole->offset;
966       left_hole->size = offset_in_hole;
967 
968       if (free_list)
969          add_hole(free_list, left_hole);
970    }
971 
972    if (hole->size > offset_in_hole + size) {
973       right_hole = alloc_block_obj(device);
974       if (!right_hole) {
975          free(left_hole);
976          return NULL;
977       }
978       list_inithead(&right_hole->freelist);
979       right_hole->arena = hole->arena;
980       right_hole->offset = hole_begin + offset_in_hole + size;
981       right_hole->size = hole_end - right_hole->offset;
982 
983       if (free_list)
984          add_hole(free_list, right_hole);
985    }
986 
987    if (left_hole) {
988       hole->offset += left_hole->size;
989       hole->size -= left_hole->size;
990 
991       list_addtail(&left_hole->list, &hole->list);
992    }
993    if (right_hole) {
994       hole->size -= right_hole->size;
995 
996       list_add(&right_hole->list, &hole->list);
997    }
998 
999    if (free_list)
1000       remove_hole(free_list, hole);
1001    return hole;
1002 }
1003 
1004 /* Segregated fit allocator, implementing a good-fit allocation policy.
1005  *
1006  * This is an variation of sequential fit allocation with several lists of free blocks ("holes")
1007  * instead of one. Each list of holes only contains holes of a certain range of sizes, so holes that
1008  * are too small can easily be ignored while allocating. Because this also ignores holes that are
1009  * larger than necessary (approximating best-fit allocation), this could be described as a
1010  * "good-fit" allocator.
1011  *
1012  * Typically, shaders are allocated and only free'd when the device is destroyed. For this pattern,
1013  * this should allocate blocks for shaders fast and with no fragmentation, while still allowing
1014  * free'd memory to be re-used.
1015  */
1016 union radv_shader_arena_block *
radv_alloc_shader_memory(struct radv_device * device,uint32_t size,bool replayable,void * ptr)1017 radv_alloc_shader_memory(struct radv_device *device, uint32_t size, bool replayable, void *ptr)
1018 {
1019    const struct radv_physical_device *pdev = radv_device_physical(device);
1020 
1021    size = ac_align_shader_binary_for_prefetch(&pdev->info, size);
1022    size = align(size, RADV_SHADER_ALLOC_ALIGNMENT);
1023 
1024    mtx_lock(&device->shader_arena_mutex);
1025 
1026    struct radv_shader_free_list *free_list = replayable ? &device->capture_replay_free_list : &device->shader_free_list;
1027 
1028    /* Try to use an existing hole. Unless the shader is very large, this should only have to look
1029     * at the first one available.
1030     */
1031    unsigned free_list_mask = BITFIELD_MASK(RADV_SHADER_ALLOC_NUM_FREE_LISTS);
1032    unsigned size_class = ffs(free_list->size_mask & (free_list_mask << get_size_class(size, true)));
1033    if (size_class) {
1034       size_class--;
1035 
1036       list_for_each_entry (union radv_shader_arena_block, hole, &free_list->free_lists[size_class], freelist) {
1037          if (hole->size < size)
1038             continue;
1039 
1040          assert(hole->offset % RADV_SHADER_ALLOC_ALIGNMENT == 0);
1041 
1042          if (size == hole->size) {
1043             remove_hole(free_list, hole);
1044             hole->freelist.next = ptr;
1045             mtx_unlock(&device->shader_arena_mutex);
1046             return hole;
1047          } else {
1048             union radv_shader_arena_block *alloc = alloc_block_obj(device);
1049             if (!alloc) {
1050                mtx_unlock(&device->shader_arena_mutex);
1051                return NULL;
1052             }
1053             list_addtail(&alloc->list, &hole->list);
1054             alloc->freelist.prev = NULL;
1055             alloc->freelist.next = ptr;
1056             alloc->arena = hole->arena;
1057             alloc->offset = hole->offset;
1058             alloc->size = size;
1059 
1060             remove_hole(free_list, hole);
1061             hole->offset += size;
1062             hole->size -= size;
1063             add_hole(free_list, hole);
1064 
1065             mtx_unlock(&device->shader_arena_mutex);
1066             return alloc;
1067          }
1068       }
1069    }
1070 
1071    struct radv_shader_arena *arena = radv_create_shader_arena(device, free_list, size, 0, replayable, 0);
1072    union radv_shader_arena_block *alloc = NULL;
1073    if (!arena)
1074       goto fail;
1075 
1076    alloc =
1077       insert_block(device, list_entry(arena->entries.next, union radv_shader_arena_block, list), 0, size, free_list);
1078    alloc->freelist.prev = NULL;
1079    alloc->freelist.next = ptr;
1080 
1081    ++device->shader_arena_shift;
1082    list_addtail(&arena->list, &device->shader_arenas);
1083 
1084    mtx_unlock(&device->shader_arena_mutex);
1085    return alloc;
1086 
1087 fail:
1088    mtx_unlock(&device->shader_arena_mutex);
1089    free(alloc);
1090    if (arena) {
1091       free(arena->list.next);
1092       radv_bo_destroy(device, NULL, arena->bo);
1093    }
1094    free(arena);
1095    return NULL;
1096 }
1097 
1098 static union radv_shader_arena_block *
get_hole(struct radv_shader_arena * arena,struct list_head * head)1099 get_hole(struct radv_shader_arena *arena, struct list_head *head)
1100 {
1101    if (head == &arena->entries)
1102       return NULL;
1103 
1104    union radv_shader_arena_block *hole = list_entry(head, union radv_shader_arena_block, list);
1105    return hole->freelist.prev ? hole : NULL;
1106 }
1107 
1108 void
radv_free_shader_memory(struct radv_device * device,union radv_shader_arena_block * alloc)1109 radv_free_shader_memory(struct radv_device *device, union radv_shader_arena_block *alloc)
1110 {
1111    mtx_lock(&device->shader_arena_mutex);
1112 
1113    union radv_shader_arena_block *hole_prev = get_hole(alloc->arena, alloc->list.prev);
1114    union radv_shader_arena_block *hole_next = get_hole(alloc->arena, alloc->list.next);
1115 
1116    union radv_shader_arena_block *hole = alloc;
1117 
1118    struct radv_shader_free_list *free_list;
1119 
1120    switch (alloc->arena->type) {
1121    case RADV_SHADER_ARENA_DEFAULT:
1122       free_list = &device->shader_free_list;
1123       break;
1124    case RADV_SHADER_ARENA_REPLAYABLE:
1125       free_list = &device->capture_replay_free_list;
1126       break;
1127    case RADV_SHADER_ARENA_REPLAYED:
1128       free_list = NULL;
1129       break;
1130    default:
1131       unreachable("invalid shader arena type");
1132    }
1133 
1134    /* merge with previous hole */
1135    if (hole_prev) {
1136       if (free_list)
1137          remove_hole(free_list, hole_prev);
1138 
1139       hole_prev->size += hole->size;
1140       free_block_obj(device, hole);
1141 
1142       hole = hole_prev;
1143    }
1144 
1145    /* merge with next hole */
1146    if (hole_next) {
1147       if (free_list)
1148          remove_hole(free_list, hole_next);
1149 
1150       hole_next->offset -= hole->size;
1151       hole_next->size += hole->size;
1152       free_block_obj(device, hole);
1153 
1154       hole = hole_next;
1155    }
1156 
1157    if (list_is_singular(&hole->list)) {
1158       struct radv_shader_arena *arena = hole->arena;
1159       free_block_obj(device, hole);
1160 
1161       radv_bo_destroy(device, NULL, arena->bo);
1162       list_del(&arena->list);
1163 
1164       if (device->capture_replay_arena_vas) {
1165          struct hash_entry *arena_entry = NULL;
1166          hash_table_foreach (device->capture_replay_arena_vas->table, entry) {
1167             if (entry->data == arena) {
1168                arena_entry = entry;
1169                break;
1170             }
1171          }
1172          _mesa_hash_table_remove(device->capture_replay_arena_vas->table, arena_entry);
1173       }
1174 
1175       free(arena);
1176    } else if (free_list) {
1177       add_hole(free_list, hole);
1178    }
1179 
1180    mtx_unlock(&device->shader_arena_mutex);
1181 }
1182 
1183 union radv_shader_arena_block *
radv_replay_shader_arena_block(struct radv_device * device,const struct radv_serialized_shader_arena_block * src,void * ptr)1184 radv_replay_shader_arena_block(struct radv_device *device, const struct radv_serialized_shader_arena_block *src,
1185                                void *ptr)
1186 {
1187    mtx_lock(&device->shader_arena_mutex);
1188 
1189    union radv_shader_arena_block *ret_block = NULL;
1190 
1191    uint64_t va = src->arena_va;
1192    void *data = _mesa_hash_table_u64_search(device->capture_replay_arena_vas, va);
1193 
1194    if (!data) {
1195       struct radv_shader_arena *arena = radv_create_shader_arena(device, NULL, 0, src->arena_size, true, src->arena_va);
1196       if (!arena)
1197          goto out;
1198 
1199       _mesa_hash_table_u64_insert(device->capture_replay_arena_vas, src->arena_va, arena);
1200       list_addtail(&arena->list, &device->shader_arenas);
1201       data = arena;
1202    }
1203 
1204    uint32_t block_begin = src->offset;
1205    uint32_t block_end = src->offset + src->size;
1206 
1207    struct radv_shader_arena *arena = data;
1208    list_for_each_entry (union radv_shader_arena_block, hole, &arena->entries, list) {
1209       /* Only consider holes, not allocated shaders */
1210       if (!hole->freelist.prev)
1211          continue;
1212 
1213       uint32_t hole_begin = hole->offset;
1214       uint32_t hole_end = hole->offset + hole->size;
1215 
1216       if (hole_end < block_end)
1217          continue;
1218 
1219       /* If another allocated block overlaps the current replay block, allocation is impossible */
1220       if (hole_begin > block_begin)
1221          goto out;
1222 
1223       union radv_shader_arena_block *block = insert_block(device, hole, block_begin - hole_begin, src->size, NULL);
1224       if (!block)
1225          goto out;
1226 
1227       block->freelist.prev = NULL;
1228       block->freelist.next = ptr;
1229 
1230       ret_block = hole;
1231       break;
1232    }
1233 
1234 out:
1235    mtx_unlock(&device->shader_arena_mutex);
1236    return ret_block;
1237 }
1238 
1239 void
radv_init_shader_arenas(struct radv_device * device)1240 radv_init_shader_arenas(struct radv_device *device)
1241 {
1242    mtx_init(&device->shader_arena_mutex, mtx_plain);
1243 
1244    device->shader_free_list.size_mask = 0;
1245    device->capture_replay_free_list.size_mask = 0;
1246 
1247    list_inithead(&device->shader_arenas);
1248    list_inithead(&device->shader_block_obj_pool);
1249    for (unsigned i = 0; i < RADV_SHADER_ALLOC_NUM_FREE_LISTS; i++) {
1250       list_inithead(&device->shader_free_list.free_lists[i]);
1251       list_inithead(&device->capture_replay_free_list.free_lists[i]);
1252    }
1253 }
1254 
1255 void
radv_destroy_shader_arenas(struct radv_device * device)1256 radv_destroy_shader_arenas(struct radv_device *device)
1257 {
1258    list_for_each_entry_safe (union radv_shader_arena_block, block, &device->shader_block_obj_pool, pool)
1259       free(block);
1260 
1261    list_for_each_entry_safe (struct radv_shader_arena, arena, &device->shader_arenas, list) {
1262       radv_bo_destroy(device, NULL, arena->bo);
1263       free(arena);
1264    }
1265    mtx_destroy(&device->shader_arena_mutex);
1266 }
1267 
1268 VkResult
radv_init_shader_upload_queue(struct radv_device * device)1269 radv_init_shader_upload_queue(struct radv_device *device)
1270 {
1271    if (!device->shader_use_invisible_vram)
1272       return VK_SUCCESS;
1273 
1274    VkDevice vk_device = radv_device_to_handle(device);
1275    struct radeon_winsys *ws = device->ws;
1276 
1277    const struct vk_device_dispatch_table *disp = &device->vk.dispatch_table;
1278    VkResult result = VK_SUCCESS;
1279 
1280    result = ws->ctx_create(ws, RADEON_CTX_PRIORITY_MEDIUM, &device->shader_upload_hw_ctx);
1281    if (result != VK_SUCCESS)
1282       return result;
1283    mtx_init(&device->shader_upload_hw_ctx_mutex, mtx_plain);
1284 
1285    mtx_init(&device->shader_dma_submission_list_mutex, mtx_plain);
1286    cnd_init(&device->shader_dma_submission_list_cond);
1287    list_inithead(&device->shader_dma_submissions);
1288 
1289    for (unsigned i = 0; i < RADV_SHADER_UPLOAD_CS_COUNT; i++) {
1290       struct radv_shader_dma_submission *submission = calloc(1, sizeof(struct radv_shader_dma_submission));
1291       submission->cs = ws->cs_create(ws, AMD_IP_SDMA, false);
1292       if (!submission->cs) {
1293          free(submission);
1294          return VK_ERROR_OUT_OF_DEVICE_MEMORY;
1295       }
1296       list_addtail(&submission->list, &device->shader_dma_submissions);
1297    }
1298 
1299    const VkSemaphoreTypeCreateInfo sem_type = {
1300       .sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO,
1301       .semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE,
1302       .initialValue = 0,
1303    };
1304    const VkSemaphoreCreateInfo sem_create = {
1305       .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
1306       .pNext = &sem_type,
1307    };
1308    result = disp->CreateSemaphore(vk_device, &sem_create, NULL, &device->shader_upload_sem);
1309    if (result != VK_SUCCESS)
1310       return result;
1311 
1312    return VK_SUCCESS;
1313 }
1314 
1315 void
radv_destroy_shader_upload_queue(struct radv_device * device)1316 radv_destroy_shader_upload_queue(struct radv_device *device)
1317 {
1318    if (!device->shader_use_invisible_vram)
1319       return;
1320 
1321    struct vk_device_dispatch_table *disp = &device->vk.dispatch_table;
1322    struct radeon_winsys *ws = device->ws;
1323 
1324    /* Upload queue should be idle assuming that pipelines are not leaked */
1325    if (device->shader_upload_sem)
1326       disp->DestroySemaphore(radv_device_to_handle(device), device->shader_upload_sem, NULL);
1327 
1328    list_for_each_entry_safe (struct radv_shader_dma_submission, submission, &device->shader_dma_submissions, list) {
1329       if (submission->cs)
1330          ws->cs_destroy(submission->cs);
1331       if (submission->bo)
1332          radv_bo_destroy(device, NULL, submission->bo);
1333       list_del(&submission->list);
1334       free(submission);
1335    }
1336 
1337    cnd_destroy(&device->shader_dma_submission_list_cond);
1338    mtx_destroy(&device->shader_dma_submission_list_mutex);
1339 
1340    if (device->shader_upload_hw_ctx) {
1341       mtx_destroy(&device->shader_upload_hw_ctx_mutex);
1342       ws->ctx_destroy(device->shader_upload_hw_ctx);
1343    }
1344 }
1345 
1346 static bool
radv_should_use_wgp_mode(const struct radv_device * device,gl_shader_stage stage,const struct radv_shader_info * info)1347 radv_should_use_wgp_mode(const struct radv_device *device, gl_shader_stage stage, const struct radv_shader_info *info)
1348 {
1349    const struct radv_physical_device *pdev = radv_device_physical(device);
1350    enum amd_gfx_level chip = pdev->info.gfx_level;
1351    switch (stage) {
1352    case MESA_SHADER_COMPUTE:
1353    case MESA_SHADER_TESS_CTRL:
1354       return chip >= GFX10;
1355    case MESA_SHADER_GEOMETRY:
1356       return chip == GFX10 || (chip >= GFX10_3 && !info->is_ngg);
1357    case MESA_SHADER_VERTEX:
1358    case MESA_SHADER_TESS_EVAL:
1359       return chip == GFX10 && info->is_ngg;
1360    default:
1361       return false;
1362    }
1363 }
1364 
1365 #if defined(USE_LIBELF)
1366 static bool
radv_open_rtld_binary(struct radv_device * device,const struct radv_shader_binary * binary,struct ac_rtld_binary * rtld_binary)1367 radv_open_rtld_binary(struct radv_device *device, const struct radv_shader_binary *binary,
1368                       struct ac_rtld_binary *rtld_binary)
1369 {
1370    const struct radv_physical_device *pdev = radv_device_physical(device);
1371    const char *elf_data = (const char *)((struct radv_shader_binary_rtld *)binary)->data;
1372    size_t elf_size = ((struct radv_shader_binary_rtld *)binary)->elf_size;
1373    struct ac_rtld_symbol lds_symbols[3];
1374    unsigned num_lds_symbols = 0;
1375 
1376    if (pdev->info.gfx_level >= GFX9 && (binary->info.stage == MESA_SHADER_GEOMETRY || binary->info.is_ngg)) {
1377       struct ac_rtld_symbol *sym = &lds_symbols[num_lds_symbols++];
1378       sym->name = "esgs_ring";
1379       sym->size = binary->info.ngg_info.esgs_ring_size;
1380       sym->align = 64 * 1024;
1381    }
1382 
1383    if (binary->info.is_ngg && binary->info.stage == MESA_SHADER_GEOMETRY) {
1384       struct ac_rtld_symbol *sym = &lds_symbols[num_lds_symbols++];
1385       sym->name = "ngg_emit";
1386       sym->size = binary->info.ngg_info.ngg_emit_size * 4;
1387       sym->align = 4;
1388 
1389       sym = &lds_symbols[num_lds_symbols++];
1390       sym->name = "ngg_scratch";
1391       sym->size = 8;
1392       sym->align = 4;
1393    }
1394 
1395    struct ac_rtld_open_info open_info = {
1396       .info = &pdev->info,
1397       .shader_type = binary->info.stage,
1398       .wave_size = binary->info.wave_size,
1399       .num_parts = 1,
1400       .elf_ptrs = &elf_data,
1401       .elf_sizes = &elf_size,
1402       .num_shared_lds_symbols = num_lds_symbols,
1403       .shared_lds_symbols = lds_symbols,
1404    };
1405 
1406    return ac_rtld_open(rtld_binary, open_info);
1407 }
1408 #endif
1409 
1410 static void
radv_precompute_registers_hw_vs(struct radv_device * device,struct radv_shader_binary * binary)1411 radv_precompute_registers_hw_vs(struct radv_device *device, struct radv_shader_binary *binary)
1412 {
1413    const struct radv_physical_device *pdev = radv_device_physical(device);
1414    struct radv_shader_info *info = &binary->info;
1415 
1416    /* VS is required to export at least one param. */
1417    const uint32_t nparams = MAX2(info->outinfo.param_exports, 1);
1418    info->regs.spi_vs_out_config = S_0286C4_VS_EXPORT_COUNT(nparams - 1);
1419    if (pdev->info.gfx_level >= GFX10) {
1420       info->regs.spi_vs_out_config |= S_0286C4_NO_PC_EXPORT(info->outinfo.param_exports == 0);
1421    }
1422 
1423    info->regs.spi_shader_pos_format =
1424       S_02870C_POS0_EXPORT_FORMAT(V_02870C_SPI_SHADER_4COMP) |
1425       S_02870C_POS1_EXPORT_FORMAT(info->outinfo.pos_exports > 1 ? V_02870C_SPI_SHADER_4COMP
1426                                                                 : V_02870C_SPI_SHADER_NONE) |
1427       S_02870C_POS2_EXPORT_FORMAT(info->outinfo.pos_exports > 2 ? V_02870C_SPI_SHADER_4COMP
1428                                                                 : V_02870C_SPI_SHADER_NONE) |
1429       S_02870C_POS3_EXPORT_FORMAT(info->outinfo.pos_exports > 3 ? V_02870C_SPI_SHADER_4COMP : V_02870C_SPI_SHADER_NONE);
1430 
1431    const bool misc_vec_ena = info->outinfo.writes_pointsize || info->outinfo.writes_layer ||
1432                              info->outinfo.writes_viewport_index || info->outinfo.writes_primitive_shading_rate;
1433    const unsigned clip_dist_mask = info->outinfo.clip_dist_mask;
1434    const unsigned cull_dist_mask = info->outinfo.cull_dist_mask;
1435    const unsigned total_mask = clip_dist_mask | cull_dist_mask;
1436 
1437    info->regs.pa_cl_vs_out_cntl =
1438       S_02881C_USE_VTX_POINT_SIZE(info->outinfo.writes_pointsize) |
1439       S_02881C_USE_VTX_RENDER_TARGET_INDX(info->outinfo.writes_layer) |
1440       S_02881C_USE_VTX_VIEWPORT_INDX(info->outinfo.writes_viewport_index) |
1441       S_02881C_USE_VTX_VRS_RATE(info->outinfo.writes_primitive_shading_rate) |
1442       S_02881C_VS_OUT_MISC_VEC_ENA(misc_vec_ena) |
1443       S_02881C_VS_OUT_MISC_SIDE_BUS_ENA(misc_vec_ena ||
1444                                         (pdev->info.gfx_level >= GFX10_3 && info->outinfo.pos_exports > 1)) |
1445       S_02881C_VS_OUT_CCDIST0_VEC_ENA((total_mask & 0x0f) != 0) |
1446       S_02881C_VS_OUT_CCDIST1_VEC_ENA((total_mask & 0xf0) != 0) | total_mask << 8 | clip_dist_mask;
1447 
1448    if (pdev->info.gfx_level <= GFX8)
1449       info->regs.vs.vgt_reuse_off = info->outinfo.writes_viewport_index;
1450 
1451    unsigned late_alloc_wave64, cu_mask;
1452    ac_compute_late_alloc(&pdev->info, false, false, binary->config.scratch_bytes_per_wave > 0, &late_alloc_wave64,
1453                          &cu_mask);
1454 
1455    if (pdev->info.gfx_level >= GFX7) {
1456       info->regs.vs.spi_shader_pgm_rsrc3_vs =
1457          ac_apply_cu_en(S_00B118_CU_EN(cu_mask) | S_00B118_WAVE_LIMIT(0x3F), C_00B118_CU_EN, 0, &pdev->info);
1458       info->regs.vs.spi_shader_late_alloc_vs = S_00B11C_LIMIT(late_alloc_wave64);
1459 
1460       if (pdev->info.gfx_level >= GFX10) {
1461          const uint32_t oversub_pc_lines = late_alloc_wave64 ? pdev->info.pc_lines / 4 : 0;
1462 
1463          info->regs.ge_pc_alloc =
1464             S_030980_OVERSUB_EN(oversub_pc_lines > 0) | S_030980_NUM_PC_LINES(oversub_pc_lines - 1);
1465 
1466          /* Required programming for tessellation (legacy pipeline only). */
1467          if (binary->info.stage == MESA_SHADER_TESS_EVAL) {
1468             info->regs.vgt_gs_onchip_cntl = S_028A44_ES_VERTS_PER_SUBGRP(250) | S_028A44_GS_PRIMS_PER_SUBGRP(126) |
1469                                             S_028A44_GS_INST_PRIMS_IN_SUBGRP(126);
1470          }
1471       }
1472    }
1473 }
1474 
1475 static void
radv_precompute_registers_hw_gs(struct radv_device * device,struct radv_shader_binary * binary)1476 radv_precompute_registers_hw_gs(struct radv_device *device, struct radv_shader_binary *binary)
1477 {
1478    const struct radv_physical_device *pdev = radv_device_physical(device);
1479    struct radv_shader_info *info = &binary->info;
1480 
1481    info->regs.gs.vgt_esgs_ring_itemsize = info->gs_ring_info.esgs_itemsize;
1482 
1483    info->regs.gs.vgt_gs_max_prims_per_subgroup =
1484       S_028A94_MAX_PRIMS_PER_SUBGROUP(info->gs_ring_info.gs_inst_prims_in_subgroup);
1485 
1486    info->regs.vgt_gs_onchip_cntl = S_028A44_ES_VERTS_PER_SUBGRP(info->gs_ring_info.es_verts_per_subgroup) |
1487                                    S_028A44_GS_PRIMS_PER_SUBGRP(info->gs_ring_info.gs_prims_per_subgroup) |
1488                                    S_028A44_GS_INST_PRIMS_IN_SUBGRP(info->gs_ring_info.gs_inst_prims_in_subgroup);
1489 
1490    const uint32_t gs_max_out_vertices = info->gs.vertices_out;
1491    const uint8_t max_stream = info->gs.max_stream;
1492    const uint8_t *num_components = info->gs.num_stream_output_components;
1493 
1494    uint32_t offset = num_components[0] * gs_max_out_vertices;
1495    info->regs.gs.vgt_gsvs_ring_offset[0] = offset;
1496 
1497    if (max_stream >= 1)
1498       offset += num_components[1] * gs_max_out_vertices;
1499    info->regs.gs.vgt_gsvs_ring_offset[1] = offset;
1500 
1501    if (max_stream >= 2)
1502       offset += num_components[2] * gs_max_out_vertices;
1503    info->regs.gs.vgt_gsvs_ring_offset[2] = offset;
1504 
1505    if (max_stream >= 3)
1506       offset += num_components[3] * gs_max_out_vertices;
1507    info->regs.gs.vgt_gsvs_ring_itemsize = offset;
1508 
1509    for (uint32_t i = 0; i < 4; i++)
1510       info->regs.gs.vgt_gs_vert_itemsize[i] = (max_stream >= i) ? num_components[i] : 0;
1511 
1512    const uint32_t gs_num_invocations = info->gs.invocations;
1513    info->regs.gs.vgt_gs_instance_cnt =
1514       S_028B90_CNT(MIN2(gs_num_invocations, 127)) | S_028B90_ENABLE(gs_num_invocations > 0);
1515 
1516    info->regs.spi_shader_pgm_rsrc3_gs =
1517       ac_apply_cu_en(S_00B21C_CU_EN(0xffff) | S_00B21C_WAVE_LIMIT(0x3F), C_00B21C_CU_EN, 0, &pdev->info);
1518 
1519    if (pdev->info.gfx_level >= GFX10) {
1520       info->regs.spi_shader_pgm_rsrc4_gs =
1521          ac_apply_cu_en(S_00B204_CU_EN_GFX10(0xffff) | S_00B204_SPI_SHADER_LATE_ALLOC_GS_GFX10(0), C_00B204_CU_EN_GFX10,
1522                         16, &pdev->info);
1523    }
1524 
1525    info->regs.vgt_gs_max_vert_out = info->gs.vertices_out;
1526 }
1527 
1528 void
radv_precompute_registers_hw_ngg(struct radv_device * device,const struct ac_shader_config * config,struct radv_shader_info * info)1529 radv_precompute_registers_hw_ngg(struct radv_device *device, const struct ac_shader_config *config,
1530                                  struct radv_shader_info *info)
1531 {
1532    const struct radv_physical_device *pdev = radv_device_physical(device);
1533 
1534    const bool no_pc_export = info->outinfo.param_exports == 0 && info->outinfo.prim_param_exports == 0;
1535    const unsigned num_prim_params = info->outinfo.prim_param_exports;
1536 
1537    if (pdev->info.gfx_level >= GFX12) {
1538       unsigned num_params = info->outinfo.param_exports;
1539 
1540       /* Since there is no alloc/dealloc mechanism for the 12-bit ordered IDs, they can wrap
1541        * around if there are more than 2^12 workgroups, causing 2 workgroups to get the same
1542        * ordered ID, which would break the streamout algorithm.
1543        * The recommended solution is to use the alloc/dealloc mechanism of the attribute ring,
1544        * which is enough to limit the range of ordered IDs that can be in flight.
1545        */
1546       if (info->so.num_outputs) {
1547          num_params = MAX2(num_params, 8);
1548       } else {
1549          num_params = MAX2(num_params, 1);
1550       }
1551 
1552       info->regs.spi_vs_out_config = S_00B0C4_VS_EXPORT_COUNT(num_params - 1) |
1553                                      S_00B0C4_PRIM_EXPORT_COUNT(num_prim_params) | S_00B0C4_NO_PC_EXPORT(no_pc_export);
1554 
1555       info->regs.spi_shader_pgm_rsrc4_gs =
1556          S_00B220_SPI_SHADER_LATE_ALLOC_GS(127) | S_00B220_GLG_FORCE_DISABLE(1) | S_00B220_WAVE_LIMIT(0x3ff);
1557    } else {
1558       const unsigned num_params = MAX2(info->outinfo.param_exports, 1);
1559 
1560       info->regs.spi_vs_out_config = S_0286C4_VS_EXPORT_COUNT(num_params - 1) |
1561                                      S_0286C4_PRIM_EXPORT_COUNT(num_prim_params) | S_0286C4_NO_PC_EXPORT(no_pc_export);
1562 
1563       unsigned late_alloc_wave64, cu_mask;
1564       ac_compute_late_alloc(&pdev->info, true, info->has_ngg_culling, config->scratch_bytes_per_wave > 0,
1565                             &late_alloc_wave64, &cu_mask);
1566 
1567       info->regs.spi_shader_pgm_rsrc3_gs =
1568          ac_apply_cu_en(S_00B21C_CU_EN(cu_mask) | S_00B21C_WAVE_LIMIT(0x3F), C_00B21C_CU_EN, 0, &pdev->info);
1569 
1570       if (pdev->info.gfx_level >= GFX11) {
1571          info->regs.spi_shader_pgm_rsrc4_gs =
1572             ac_apply_cu_en(S_00B204_CU_EN_GFX11(0x1) | S_00B204_SPI_SHADER_LATE_ALLOC_GS_GFX10(late_alloc_wave64),
1573                            C_00B204_CU_EN_GFX11, 16, &pdev->info);
1574       } else {
1575          info->regs.spi_shader_pgm_rsrc4_gs =
1576             ac_apply_cu_en(S_00B204_CU_EN_GFX10(0xffff) | S_00B204_SPI_SHADER_LATE_ALLOC_GS_GFX10(late_alloc_wave64),
1577                            C_00B204_CU_EN_GFX10, 16, &pdev->info);
1578       }
1579 
1580       uint32_t oversub_pc_lines = late_alloc_wave64 ? pdev->info.pc_lines / 4 : 0;
1581       if (info->has_ngg_culling) {
1582          unsigned oversub_factor = 2;
1583 
1584          if (info->outinfo.param_exports > 4)
1585             oversub_factor = 4;
1586          else if (info->outinfo.param_exports > 2)
1587             oversub_factor = 3;
1588 
1589          oversub_pc_lines *= oversub_factor;
1590       }
1591 
1592       info->regs.ge_pc_alloc = S_030980_OVERSUB_EN(oversub_pc_lines > 0) | S_030980_NUM_PC_LINES(oversub_pc_lines - 1);
1593    }
1594 
1595    unsigned idx_format = V_028708_SPI_SHADER_1COMP;
1596    if (info->outinfo.writes_layer_per_primitive || info->outinfo.writes_viewport_index_per_primitive ||
1597        info->outinfo.writes_primitive_shading_rate_per_primitive)
1598       idx_format = V_028708_SPI_SHADER_2COMP;
1599 
1600    info->regs.ngg.spi_shader_idx_format = S_028708_IDX0_EXPORT_FORMAT(idx_format);
1601 
1602    info->regs.spi_shader_pos_format =
1603       S_02870C_POS0_EXPORT_FORMAT(V_02870C_SPI_SHADER_4COMP) |
1604       S_02870C_POS1_EXPORT_FORMAT(info->outinfo.pos_exports > 1 ? V_02870C_SPI_SHADER_4COMP
1605                                                                 : V_02870C_SPI_SHADER_NONE) |
1606       S_02870C_POS2_EXPORT_FORMAT(info->outinfo.pos_exports > 2 ? V_02870C_SPI_SHADER_4COMP
1607                                                                 : V_02870C_SPI_SHADER_NONE) |
1608       S_02870C_POS3_EXPORT_FORMAT(info->outinfo.pos_exports > 3 ? V_02870C_SPI_SHADER_4COMP : V_02870C_SPI_SHADER_NONE);
1609 
1610    const bool misc_vec_ena = info->outinfo.writes_pointsize || info->outinfo.writes_layer ||
1611                              info->outinfo.writes_viewport_index || info->outinfo.writes_primitive_shading_rate;
1612    const unsigned clip_dist_mask = info->outinfo.clip_dist_mask;
1613    const unsigned cull_dist_mask = info->outinfo.cull_dist_mask;
1614    const unsigned total_mask = clip_dist_mask | cull_dist_mask;
1615 
1616    info->regs.pa_cl_vs_out_cntl =
1617       S_02881C_USE_VTX_POINT_SIZE(info->outinfo.writes_pointsize) |
1618       S_02881C_USE_VTX_RENDER_TARGET_INDX(info->outinfo.writes_layer) |
1619       S_02881C_USE_VTX_VIEWPORT_INDX(info->outinfo.writes_viewport_index) |
1620       S_02881C_USE_VTX_VRS_RATE(info->outinfo.writes_primitive_shading_rate) |
1621       S_02881C_VS_OUT_MISC_VEC_ENA(misc_vec_ena) |
1622       S_02881C_VS_OUT_MISC_SIDE_BUS_ENA(misc_vec_ena ||
1623                                         (pdev->info.gfx_level >= GFX10_3 && info->outinfo.pos_exports > 1)) |
1624       S_02881C_VS_OUT_CCDIST0_VEC_ENA((total_mask & 0x0f) != 0) |
1625       S_02881C_VS_OUT_CCDIST1_VEC_ENA((total_mask & 0xf0) != 0) | total_mask << 8 | clip_dist_mask;
1626 
1627    info->regs.ngg.vgt_primitiveid_en =
1628       S_028A84_NGG_DISABLE_PROVOK_REUSE(info->stage == MESA_SHADER_VERTEX && info->outinfo.export_prim_id);
1629 
1630    const uint32_t gs_num_invocations = info->stage == MESA_SHADER_GEOMETRY ? info->gs.invocations : 1;
1631 
1632    info->regs.ngg.ge_max_output_per_subgroup = S_0287FC_MAX_VERTS_PER_SUBGROUP(info->ngg_info.max_out_verts);
1633 
1634    info->regs.ngg.ge_ngg_subgrp_cntl =
1635       S_028B4C_PRIM_AMP_FACTOR(info->ngg_info.prim_amp_factor) | S_028B4C_THDS_PER_SUBGRP(0); /* for fast launch */
1636 
1637    info->regs.vgt_gs_instance_cnt =
1638       S_028B90_CNT(gs_num_invocations) | S_028B90_ENABLE(gs_num_invocations > 1) |
1639       S_028B90_EN_MAX_VERT_OUT_PER_GS_INSTANCE(info->ngg_info.max_vert_out_per_gs_instance);
1640 
1641    if (pdev->info.gfx_level >= GFX11) {
1642       /* This should be <= 252 for performance on Gfx11. 256 works too but is slower. */
1643       const uint32_t max_prim_grp_size = pdev->info.gfx_level >= GFX12 ? 256 : 252;
1644 
1645       info->regs.ngg.ge_cntl = S_03096C_PRIMS_PER_SUBGRP(info->ngg_info.max_gsprims) |
1646                                S_03096C_VERTS_PER_SUBGRP(info->ngg_info.hw_max_esverts) |
1647                                S_03096C_PRIM_GRP_SIZE_GFX11(max_prim_grp_size) |
1648                                S_03096C_DIS_PG_SIZE_ADJUST_FOR_STRIP(pdev->info.gfx_level >= GFX12);
1649    } else {
1650       info->regs.ngg.ge_cntl = S_03096C_PRIM_GRP_SIZE_GFX10(info->ngg_info.max_gsprims) |
1651                                S_03096C_VERT_GRP_SIZE(info->ngg_info.hw_max_esverts);
1652 
1653       info->regs.vgt_gs_onchip_cntl = S_028A44_ES_VERTS_PER_SUBGRP(info->ngg_info.hw_max_esverts) |
1654                                       S_028A44_GS_PRIMS_PER_SUBGRP(info->ngg_info.max_gsprims) |
1655                                       S_028A44_GS_INST_PRIMS_IN_SUBGRP(info->ngg_info.max_gsprims * gs_num_invocations);
1656    }
1657 
1658 
1659    info->regs.vgt_gs_max_vert_out = info->gs.vertices_out;
1660 }
1661 
1662 static void
radv_precompute_registers_hw_ms(struct radv_device * device,struct radv_shader_binary * binary)1663 radv_precompute_registers_hw_ms(struct radv_device *device, struct radv_shader_binary *binary)
1664 {
1665    const struct radv_physical_device *pdev = radv_device_physical(device);
1666    struct radv_shader_info *info = &binary->info;
1667 
1668    radv_precompute_registers_hw_ngg(device, &binary->config, &binary->info);
1669 
1670    info->regs.vgt_gs_max_vert_out = pdev->mesh_fast_launch_2 ? info->ngg_info.max_out_verts : info->workgroup_size;
1671 
1672    info->regs.ms.spi_shader_gs_meshlet_dim = S_00B2B0_MESHLET_NUM_THREAD_X(info->cs.block_size[0] - 1) |
1673                                              S_00B2B0_MESHLET_NUM_THREAD_Y(info->cs.block_size[1] - 1) |
1674                                              S_00B2B0_MESHLET_NUM_THREAD_Z(info->cs.block_size[2] - 1) |
1675                                              S_00B2B0_MESHLET_THREADGROUP_SIZE(info->workgroup_size - 1);
1676 
1677    info->regs.ms.spi_shader_gs_meshlet_exp_alloc =
1678       S_00B2B4_MAX_EXP_VERTS(info->ngg_info.max_out_verts) | S_00B2B4_MAX_EXP_PRIMS(info->ngg_info.prim_amp_factor);
1679 }
1680 
1681 static void
radv_precompute_registers_hw_fs(struct radv_device * device,struct radv_shader_binary * binary)1682 radv_precompute_registers_hw_fs(struct radv_device *device, struct radv_shader_binary *binary)
1683 {
1684    const struct radv_physical_device *pdev = radv_device_physical(device);
1685    struct radv_shader_info *info = &binary->info;
1686 
1687    unsigned conservative_z_export = V_02880C_EXPORT_ANY_Z;
1688    if (info->ps.depth_layout == FRAG_DEPTH_LAYOUT_GREATER)
1689       conservative_z_export = V_02880C_EXPORT_GREATER_THAN_Z;
1690    else if (info->ps.depth_layout == FRAG_DEPTH_LAYOUT_LESS)
1691       conservative_z_export = V_02880C_EXPORT_LESS_THAN_Z;
1692 
1693    const unsigned z_order =
1694       info->ps.early_fragment_test || !info->ps.writes_memory ? V_02880C_EARLY_Z_THEN_LATE_Z : V_02880C_LATE_Z;
1695 
1696    /* It shouldn't be needed to export gl_SampleMask when MSAA is disabled, but this appears to break Project Cars
1697     * (DXVK). See https://bugs.freedesktop.org/show_bug.cgi?id=109401
1698     */
1699    const bool mask_export_enable = info->ps.writes_sample_mask;
1700    const bool disable_rbplus = pdev->info.has_rbplus && !pdev->info.rbplus_allowed;
1701 
1702    info->regs.ps.db_shader_control =
1703       S_02880C_Z_EXPORT_ENABLE(info->ps.writes_z) | S_02880C_STENCIL_TEST_VAL_EXPORT_ENABLE(info->ps.writes_stencil) |
1704       S_02880C_KILL_ENABLE(info->ps.can_discard) | S_02880C_MASK_EXPORT_ENABLE(mask_export_enable) |
1705       S_02880C_CONSERVATIVE_Z_EXPORT(conservative_z_export) | S_02880C_Z_ORDER(z_order) |
1706       S_02880C_DEPTH_BEFORE_SHADER(info->ps.early_fragment_test) |
1707       S_02880C_PRE_SHADER_DEPTH_COVERAGE_ENABLE(info->ps.post_depth_coverage) |
1708       S_02880C_EXEC_ON_HIER_FAIL(info->ps.writes_memory) | S_02880C_EXEC_ON_NOOP(info->ps.writes_memory) |
1709       S_02880C_DUAL_QUAD_DISABLE(disable_rbplus) | S_02880C_PRIMITIVE_ORDERED_PIXEL_SHADER(info->ps.pops);
1710 
1711    if (pdev->info.gfx_level >= GFX12) {
1712       info->regs.ps.spi_ps_in_control = S_028640_PS_W32_EN(info->wave_size == 32);
1713       info->regs.ps.spi_gs_out_config_ps = S_00B0C4_NUM_INTERP(info->ps.num_inputs);
1714 
1715       info->regs.ps.pa_sc_hisz_control = S_028BBC_ROUND(2); /* required minimum value */
1716       if (info->ps.depth_layout == FRAG_DEPTH_LAYOUT_GREATER)
1717          info->regs.ps.pa_sc_hisz_control |= S_028BBC_CONSERVATIVE_Z_EXPORT(V_028BBC_EXPORT_GREATER_THAN_Z);
1718       else if (info->ps.depth_layout == FRAG_DEPTH_LAYOUT_LESS)
1719          info->regs.ps.pa_sc_hisz_control |= S_028BBC_CONSERVATIVE_Z_EXPORT(V_028BBC_EXPORT_LESS_THAN_Z);
1720    } else {
1721       /* GFX11 workaround when there are no PS inputs but LDS is used. */
1722       const bool param_gen = pdev->info.gfx_level == GFX11 && !info->ps.num_inputs && binary->config.lds_size;
1723 
1724       info->regs.ps.spi_ps_in_control = S_0286D8_PS_W32_EN(info->wave_size == 32) | S_0286D8_PARAM_GEN(param_gen);
1725 
1726       /* Can't precompute NUM_INTERP on GFX10.3 because per-primititve attributes
1727        * are tracked separately in NUM_PRIM_INTERP.
1728        */
1729       if (pdev->info.gfx_level != GFX10_3) {
1730          info->regs.ps.spi_ps_in_control |= S_0286D8_NUM_INTERP(info->ps.num_inputs);
1731       }
1732 
1733       if (pdev->info.gfx_level >= GFX9 && pdev->info.gfx_level < GFX11)
1734          info->regs.ps.pa_sc_shader_control = S_028C40_LOAD_COLLISION_WAVEID(info->ps.pops);
1735    }
1736 
1737    info->regs.ps.spi_shader_z_format = ac_get_spi_shader_z_format(
1738       info->ps.writes_z, info->ps.writes_stencil, info->ps.writes_sample_mask, info->ps.writes_mrt0_alpha);
1739 }
1740 
1741 static void
radv_precompute_registers_hw_cs(struct radv_device * device,struct radv_shader_binary * binary)1742 radv_precompute_registers_hw_cs(struct radv_device *device, struct radv_shader_binary *binary)
1743 {
1744    const struct radv_physical_device *pdev = radv_device_physical(device);
1745    struct radv_shader_info *info = &binary->info;
1746 
1747    info->regs.cs.compute_resource_limits = radv_get_compute_resource_limits(pdev, info);
1748    if (pdev->info.gfx_level >= GFX12) {
1749       info->regs.cs.compute_num_thread_x = S_00B81C_NUM_THREAD_FULL_GFX12(info->cs.block_size[0]);
1750       info->regs.cs.compute_num_thread_y = S_00B820_NUM_THREAD_FULL_GFX12(info->cs.block_size[1]);
1751    } else {
1752       info->regs.cs.compute_num_thread_x = S_00B81C_NUM_THREAD_FULL_GFX6(info->cs.block_size[0]);
1753       info->regs.cs.compute_num_thread_y = S_00B820_NUM_THREAD_FULL_GFX6(info->cs.block_size[1]);
1754    }
1755    info->regs.cs.compute_num_thread_z = S_00B824_NUM_THREAD_FULL(info->cs.block_size[2]);
1756 }
1757 
1758 static void
radv_precompute_registers_pgm(const struct radv_device * device,struct radv_shader_info * info)1759 radv_precompute_registers_pgm(const struct radv_device *device, struct radv_shader_info *info)
1760 {
1761    const struct radv_physical_device *pdev = radv_device_physical(device);
1762    const enum amd_gfx_level gfx_level = pdev->info.gfx_level;
1763    enum ac_hw_stage hw_stage = radv_select_hw_stage(info, gfx_level);
1764 
1765    /* Special case for merged shaders compiled separately with ESO on GFX9+. */
1766    if (info->merged_shader_compiled_separately) {
1767       if (info->stage == MESA_SHADER_VERTEX && info->next_stage == MESA_SHADER_TESS_CTRL) {
1768          hw_stage = AC_HW_HULL_SHADER;
1769       } else if ((info->stage == MESA_SHADER_VERTEX || info->stage == MESA_SHADER_TESS_EVAL) &&
1770                  info->next_stage == MESA_SHADER_GEOMETRY) {
1771          hw_stage = info->is_ngg ? AC_HW_NEXT_GEN_GEOMETRY_SHADER : AC_HW_LEGACY_GEOMETRY_SHADER;
1772       }
1773    }
1774 
1775    switch (hw_stage) {
1776    case AC_HW_NEXT_GEN_GEOMETRY_SHADER:
1777       assert(gfx_level >= GFX10);
1778       if (gfx_level >= GFX12) {
1779          info->regs.pgm_lo = R_00B224_SPI_SHADER_PGM_LO_ES;
1780       } else {
1781          info->regs.pgm_lo = R_00B320_SPI_SHADER_PGM_LO_ES;
1782       }
1783 
1784       info->regs.pgm_rsrc1 = R_00B228_SPI_SHADER_PGM_RSRC1_GS;
1785       info->regs.pgm_rsrc2 = R_00B22C_SPI_SHADER_PGM_RSRC2_GS;
1786       break;
1787    case AC_HW_LEGACY_GEOMETRY_SHADER:
1788       assert(gfx_level < GFX11);
1789       if (gfx_level >= GFX10) {
1790          info->regs.pgm_lo = R_00B320_SPI_SHADER_PGM_LO_ES;
1791       } else if (gfx_level >= GFX9) {
1792          info->regs.pgm_lo = R_00B210_SPI_SHADER_PGM_LO_ES;
1793       } else {
1794          info->regs.pgm_lo = R_00B220_SPI_SHADER_PGM_LO_GS;
1795       }
1796 
1797       info->regs.pgm_rsrc1 = R_00B228_SPI_SHADER_PGM_RSRC1_GS;
1798       info->regs.pgm_rsrc2 = R_00B22C_SPI_SHADER_PGM_RSRC2_GS;
1799       break;
1800    case AC_HW_EXPORT_SHADER:
1801       assert(gfx_level < GFX9);
1802       info->regs.pgm_lo = R_00B320_SPI_SHADER_PGM_LO_ES;
1803       info->regs.pgm_rsrc1 = R_00B328_SPI_SHADER_PGM_RSRC1_ES;
1804       info->regs.pgm_rsrc2 = R_00B32C_SPI_SHADER_PGM_RSRC2_ES;
1805       break;
1806    case AC_HW_LOCAL_SHADER:
1807       assert(gfx_level < GFX9);
1808       info->regs.pgm_lo = R_00B520_SPI_SHADER_PGM_LO_LS;
1809       info->regs.pgm_rsrc1 = R_00B528_SPI_SHADER_PGM_RSRC1_LS;
1810       info->regs.pgm_rsrc2 = R_00B52C_SPI_SHADER_PGM_RSRC2_LS;
1811       break;
1812    case AC_HW_HULL_SHADER:
1813       if (gfx_level >= GFX12) {
1814          info->regs.pgm_lo = R_00B424_SPI_SHADER_PGM_LO_LS;
1815       } else if (gfx_level >= GFX10) {
1816          info->regs.pgm_lo = R_00B520_SPI_SHADER_PGM_LO_LS;
1817       } else if (gfx_level >= GFX9) {
1818          info->regs.pgm_lo = R_00B410_SPI_SHADER_PGM_LO_LS;
1819       } else {
1820          info->regs.pgm_lo = R_00B420_SPI_SHADER_PGM_LO_HS;
1821       }
1822 
1823       info->regs.pgm_rsrc1 = R_00B428_SPI_SHADER_PGM_RSRC1_HS;
1824       info->regs.pgm_rsrc2 = R_00B42C_SPI_SHADER_PGM_RSRC2_HS;
1825       break;
1826    case AC_HW_VERTEX_SHADER:
1827       assert(gfx_level < GFX11);
1828       info->regs.pgm_lo = R_00B120_SPI_SHADER_PGM_LO_VS;
1829       info->regs.pgm_rsrc1 = R_00B128_SPI_SHADER_PGM_RSRC1_VS;
1830       info->regs.pgm_rsrc2 = R_00B12C_SPI_SHADER_PGM_RSRC2_VS;
1831       break;
1832    case AC_HW_PIXEL_SHADER:
1833       info->regs.pgm_lo = R_00B020_SPI_SHADER_PGM_LO_PS;
1834       info->regs.pgm_rsrc1 = R_00B028_SPI_SHADER_PGM_RSRC1_PS;
1835       info->regs.pgm_rsrc2 = R_00B02C_SPI_SHADER_PGM_RSRC2_PS;
1836       break;
1837    case AC_HW_COMPUTE_SHADER:
1838       info->regs.pgm_lo = R_00B830_COMPUTE_PGM_LO;
1839       info->regs.pgm_rsrc1 = R_00B848_COMPUTE_PGM_RSRC1;
1840       info->regs.pgm_rsrc2 = R_00B84C_COMPUTE_PGM_RSRC2;
1841       info->regs.pgm_rsrc3 = R_00B8A0_COMPUTE_PGM_RSRC3;
1842       break;
1843    default:
1844       unreachable("invalid hw stage");
1845       break;
1846    }
1847 }
1848 
1849 static void
radv_precompute_registers(struct radv_device * device,struct radv_shader_binary * binary)1850 radv_precompute_registers(struct radv_device *device, struct radv_shader_binary *binary)
1851 {
1852    struct radv_shader_info *info = &binary->info;
1853 
1854    radv_precompute_registers_pgm(device, info);
1855 
1856    switch (info->stage) {
1857    case MESA_SHADER_VERTEX:
1858       if (!info->vs.as_ls && !info->vs.as_es) {
1859          if (info->is_ngg) {
1860             radv_precompute_registers_hw_ngg(device, &binary->config, &binary->info);
1861          } else {
1862             radv_precompute_registers_hw_vs(device, binary);
1863          }
1864       }
1865       break;
1866    case MESA_SHADER_TESS_EVAL:
1867       if (!info->tes.as_es) {
1868          if (info->is_ngg) {
1869             radv_precompute_registers_hw_ngg(device, &binary->config, &binary->info);
1870          } else {
1871             radv_precompute_registers_hw_vs(device, binary);
1872          }
1873       }
1874       break;
1875    case MESA_SHADER_GEOMETRY:
1876       if (info->is_ngg) {
1877          radv_precompute_registers_hw_ngg(device, &binary->config, &binary->info);
1878       } else {
1879          radv_precompute_registers_hw_gs(device, binary);
1880       }
1881       break;
1882    case MESA_SHADER_MESH:
1883       radv_precompute_registers_hw_ms(device, binary);
1884       break;
1885    case MESA_SHADER_FRAGMENT:
1886       radv_precompute_registers_hw_fs(device, binary);
1887       break;
1888    case MESA_SHADER_COMPUTE:
1889    case MESA_SHADER_TASK:
1890       radv_precompute_registers_hw_cs(device, binary);
1891       break;
1892    default:
1893       break;
1894    }
1895 }
1896 
1897 static bool
radv_mem_ordered(const struct radv_physical_device * pdev)1898 radv_mem_ordered(const struct radv_physical_device *pdev)
1899 {
1900    return pdev->info.gfx_level >= GFX10 && pdev->info.gfx_level < GFX12;
1901 }
1902 
1903 static bool
radv_postprocess_binary_config(struct radv_device * device,struct radv_shader_binary * binary,const struct radv_shader_args * args)1904 radv_postprocess_binary_config(struct radv_device *device, struct radv_shader_binary *binary,
1905                                const struct radv_shader_args *args)
1906 {
1907    const struct radv_physical_device *pdev = radv_device_physical(device);
1908    const struct radv_instance *instance = radv_physical_device_instance(pdev);
1909    struct ac_shader_config *config = &binary->config;
1910 
1911    if (binary->type == RADV_BINARY_TYPE_RTLD) {
1912 #if !defined(USE_LIBELF)
1913       return false;
1914 #else
1915       struct ac_rtld_binary rtld_binary = {0};
1916 
1917       if (!radv_open_rtld_binary(device, binary, &rtld_binary)) {
1918          return false;
1919       }
1920 
1921       if (!ac_rtld_read_config(&pdev->info, &rtld_binary, config)) {
1922          ac_rtld_close(&rtld_binary);
1923          return false;
1924       }
1925 
1926       if (rtld_binary.lds_size > 0) {
1927          unsigned encode_granularity = pdev->info.lds_encode_granularity;
1928          config->lds_size = DIV_ROUND_UP(rtld_binary.lds_size, encode_granularity);
1929       }
1930       if (!config->lds_size && binary->info.stage == MESA_SHADER_TESS_CTRL) {
1931          /* This is used for reporting LDS statistics */
1932          config->lds_size = binary->info.tcs.num_lds_blocks;
1933       }
1934 
1935       assert(!binary->info.has_ngg_culling || config->lds_size);
1936       ac_rtld_close(&rtld_binary);
1937 #endif
1938    }
1939 
1940    const struct radv_shader_info *info = &binary->info;
1941    gl_shader_stage stage = binary->info.stage;
1942    bool scratch_enabled = config->scratch_bytes_per_wave > 0;
1943    bool trap_enabled = !!device->trap_handler_shader;
1944    unsigned vgpr_comp_cnt = 0;
1945    unsigned num_input_vgprs = args->ac.num_vgprs_used;
1946 
1947    if (stage == MESA_SHADER_FRAGMENT) {
1948       num_input_vgprs = ac_get_fs_input_vgpr_cnt(config, NULL);
1949    }
1950 
1951    unsigned num_vgprs = MAX2(config->num_vgprs, num_input_vgprs);
1952    /* +2 for the ring offsets, +3 for scratch wave offset and VCC */
1953    unsigned num_sgprs = MAX2(config->num_sgprs, args->ac.num_sgprs_used + 2 + 3);
1954    unsigned num_shared_vgprs = config->num_shared_vgprs;
1955    /* shared VGPRs are introduced in Navi and are allocated in blocks of 8 (RDNA ref 3.6.5) */
1956    assert((pdev->info.gfx_level >= GFX10 && num_shared_vgprs % 8 == 0) ||
1957           (pdev->info.gfx_level < GFX10 && num_shared_vgprs == 0));
1958    unsigned num_shared_vgpr_blocks = num_shared_vgprs / 8;
1959    unsigned excp_en = 0, excp_en_msb = 0;
1960    bool dx10_clamp = pdev->info.gfx_level < GFX12;
1961 
1962    config->num_vgprs = num_vgprs;
1963    config->num_sgprs = num_sgprs;
1964    config->num_shared_vgprs = num_shared_vgprs;
1965 
1966    config->rsrc2 = S_00B12C_USER_SGPR(args->num_user_sgprs) | S_00B12C_SCRATCH_EN(scratch_enabled) |
1967                    S_00B12C_TRAP_PRESENT(trap_enabled);
1968 
1969    if (trap_enabled) {
1970       /* Configure the shader exceptions like memory violation, etc. */
1971       if (instance->trap_excp_flags & RADV_TRAP_EXCP_MEM_VIOL) {
1972          excp_en |= 1 << 8;     /* for the graphics stages */
1973          excp_en_msb |= 1 << 1; /* for the compute stage */
1974       }
1975 
1976       if (instance->trap_excp_flags & RADV_TRAP_EXCP_FLOAT_DIV_BY_ZERO)
1977          excp_en |= 1 << 2;
1978       if (instance->trap_excp_flags & RADV_TRAP_EXCP_FLOAT_OVERFLOW)
1979          excp_en |= 1 << 3;
1980       if (instance->trap_excp_flags & RADV_TRAP_EXCP_FLOAT_UNDERFLOW)
1981          excp_en |= 1 << 4;
1982 
1983       if (instance->trap_excp_flags &
1984           (RADV_TRAP_EXCP_FLOAT_DIV_BY_ZERO | RADV_TRAP_EXCP_FLOAT_OVERFLOW | RADV_TRAP_EXCP_FLOAT_UNDERFLOW)) {
1985          /* It seems needed to disable DX10_CLAMP, otherwise the float exceptions aren't thrown. */
1986          dx10_clamp = false;
1987       }
1988    }
1989 
1990    if (!pdev->use_ngg_streamout) {
1991       config->rsrc2 |= S_00B12C_SO_BASE0_EN(!!info->so.strides[0]) | S_00B12C_SO_BASE1_EN(!!info->so.strides[1]) |
1992                        S_00B12C_SO_BASE2_EN(!!info->so.strides[2]) | S_00B12C_SO_BASE3_EN(!!info->so.strides[3]) |
1993                        S_00B12C_SO_EN(!!info->so.num_outputs);
1994    }
1995 
1996    config->rsrc1 = S_00B848_VGPRS((num_vgprs - 1) / (info->wave_size == 32 ? 8 : 4)) | S_00B848_DX10_CLAMP(dx10_clamp) |
1997                    S_00B848_FLOAT_MODE(config->float_mode);
1998 
1999    if (pdev->info.gfx_level >= GFX10) {
2000       config->rsrc2 |= S_00B22C_USER_SGPR_MSB_GFX10(args->num_user_sgprs >> 5);
2001    } else {
2002       config->rsrc1 |= S_00B228_SGPRS((num_sgprs - 1) / 8);
2003       config->rsrc2 |= S_00B22C_USER_SGPR_MSB_GFX9(args->num_user_sgprs >> 5);
2004    }
2005 
2006    gl_shader_stage es_stage = MESA_SHADER_NONE;
2007    if (pdev->info.gfx_level >= GFX9) {
2008       es_stage = stage == MESA_SHADER_GEOMETRY ? info->gs.es_type : stage;
2009    }
2010 
2011    if (info->merged_shader_compiled_separately) {
2012       /* Update the stage for merged shaders compiled separately with ESO on GFX9+. */
2013       if (stage == MESA_SHADER_VERTEX && info->vs.as_ls) {
2014          stage = MESA_SHADER_TESS_CTRL;
2015       } else if (stage == MESA_SHADER_VERTEX && info->vs.as_es) {
2016          es_stage = MESA_SHADER_VERTEX;
2017          stage = MESA_SHADER_GEOMETRY;
2018       } else if (stage == MESA_SHADER_TESS_EVAL && info->tes.as_es) {
2019          es_stage = MESA_SHADER_TESS_EVAL;
2020          stage = MESA_SHADER_GEOMETRY;
2021       }
2022    }
2023 
2024    bool wgp_mode = radv_should_use_wgp_mode(device, stage, info);
2025 
2026    switch (stage) {
2027    case MESA_SHADER_TESS_EVAL:
2028       if (info->is_ngg) {
2029          config->rsrc1 |= S_00B228_MEM_ORDERED(radv_mem_ordered(pdev));
2030          config->rsrc2 |= S_00B22C_OC_LDS_EN(1) | S_00B22C_EXCP_EN(excp_en);
2031       } else if (info->tes.as_es) {
2032          assert(pdev->info.gfx_level <= GFX8);
2033          vgpr_comp_cnt = info->uses_prim_id ? 3 : 2;
2034 
2035          config->rsrc2 |= S_00B12C_OC_LDS_EN(1) | S_00B12C_EXCP_EN(excp_en);
2036       } else {
2037          bool enable_prim_id = info->outinfo.export_prim_id || info->uses_prim_id;
2038          vgpr_comp_cnt = enable_prim_id ? 3 : 2;
2039 
2040          config->rsrc1 |= S_00B128_MEM_ORDERED(radv_mem_ordered(pdev));
2041          config->rsrc2 |= S_00B12C_OC_LDS_EN(1) | S_00B12C_EXCP_EN(excp_en);
2042       }
2043       config->rsrc2 |= S_00B22C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
2044       break;
2045    case MESA_SHADER_TESS_CTRL:
2046       if (pdev->info.gfx_level >= GFX9) {
2047          /* We need at least 2 components for LS.
2048           * VGPR0-3: (VertexID, RelAutoindex, InstanceID / StepRate0, InstanceID).
2049           * StepRate0 is set to 1. so that VGPR3 doesn't have to be loaded.
2050           */
2051          if (pdev->info.gfx_level >= GFX10) {
2052             if (info->vs.needs_instance_id) {
2053                vgpr_comp_cnt = pdev->info.gfx_level >= GFX12 ? 1 : 3;
2054             } else if (pdev->info.gfx_level <= GFX10_3) {
2055                vgpr_comp_cnt = 1;
2056             }
2057             config->rsrc2 |= S_00B42C_EXCP_EN_GFX6(excp_en);
2058          } else {
2059             vgpr_comp_cnt = info->vs.needs_instance_id ? 2 : 1;
2060             config->rsrc2 |= S_00B42C_EXCP_EN_GFX9(excp_en);
2061          }
2062       } else {
2063          config->rsrc2 |= S_00B12C_OC_LDS_EN(1) | S_00B12C_EXCP_EN(excp_en);
2064       }
2065       config->rsrc1 |= S_00B428_MEM_ORDERED(radv_mem_ordered(pdev)) | S_00B428_WGP_MODE(wgp_mode);
2066       config->rsrc2 |= S_00B42C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
2067       break;
2068    case MESA_SHADER_VERTEX:
2069       if (info->is_ngg) {
2070          config->rsrc1 |= S_00B228_MEM_ORDERED(radv_mem_ordered(pdev));
2071       } else if (info->vs.as_ls) {
2072          assert(pdev->info.gfx_level <= GFX8);
2073          /* We need at least 2 components for LS.
2074           * VGPR0-3: (VertexID, RelAutoindex, InstanceID / StepRate0, InstanceID).
2075           * StepRate0 is set to 1. so that VGPR3 doesn't have to be loaded.
2076           *
2077           * On GFX12, InstanceID is in VGPR1.
2078           */
2079          vgpr_comp_cnt = info->vs.needs_instance_id ? 2 : 1;
2080       } else if (info->vs.as_es) {
2081          assert(pdev->info.gfx_level <= GFX8);
2082          /* VGPR0-3: (VertexID, InstanceID / StepRate0, ...) */
2083          vgpr_comp_cnt = info->vs.needs_instance_id ? 1 : 0;
2084       } else {
2085          /* VGPR0-3: (VertexID, InstanceID / StepRate0, PrimID, InstanceID)
2086           * If PrimID is disabled. InstanceID / StepRate1 is loaded instead.
2087           * StepRate0 is set to 1. so that VGPR3 doesn't have to be loaded.
2088           */
2089          if (info->vs.needs_instance_id && pdev->info.gfx_level >= GFX10) {
2090             vgpr_comp_cnt = 3;
2091          } else if (info->outinfo.export_prim_id) {
2092             vgpr_comp_cnt = 2;
2093          } else if (info->vs.needs_instance_id) {
2094             vgpr_comp_cnt = 1;
2095          } else {
2096             vgpr_comp_cnt = 0;
2097          }
2098 
2099          config->rsrc1 |= S_00B128_MEM_ORDERED(radv_mem_ordered(pdev));
2100       }
2101       config->rsrc2 |= S_00B12C_SHARED_VGPR_CNT(num_shared_vgpr_blocks) | S_00B12C_EXCP_EN(excp_en);
2102       break;
2103    case MESA_SHADER_MESH:
2104       config->rsrc1 |= S_00B228_MEM_ORDERED(radv_mem_ordered(pdev));
2105       config->rsrc2 |= S_00B12C_SHARED_VGPR_CNT(num_shared_vgpr_blocks) | S_00B12C_EXCP_EN(excp_en);
2106       break;
2107    case MESA_SHADER_FRAGMENT:
2108       config->rsrc1 |=
2109          S_00B028_MEM_ORDERED(radv_mem_ordered(pdev)) | S_00B028_LOAD_PROVOKING_VTX(info->ps.load_provoking_vtx);
2110       config->rsrc2 |= S_00B02C_SHARED_VGPR_CNT(num_shared_vgpr_blocks) | S_00B02C_EXCP_EN(excp_en) |
2111                        S_00B02C_LOAD_COLLISION_WAVEID(info->ps.pops && pdev->info.gfx_level < GFX11);
2112       break;
2113    case MESA_SHADER_GEOMETRY:
2114       config->rsrc1 |= S_00B228_MEM_ORDERED(radv_mem_ordered(pdev));
2115       config->rsrc2 |= S_00B22C_SHARED_VGPR_CNT(num_shared_vgpr_blocks) | S_00B22C_EXCP_EN(excp_en);
2116       break;
2117    case MESA_SHADER_RAYGEN:
2118    case MESA_SHADER_CLOSEST_HIT:
2119    case MESA_SHADER_MISS:
2120    case MESA_SHADER_CALLABLE:
2121    case MESA_SHADER_INTERSECTION:
2122    case MESA_SHADER_ANY_HIT:
2123    case MESA_SHADER_COMPUTE:
2124    case MESA_SHADER_TASK:
2125       config->rsrc1 |= S_00B848_MEM_ORDERED(radv_mem_ordered(pdev)) | S_00B848_WGP_MODE(wgp_mode);
2126       config->rsrc2 |= S_00B84C_TGID_X_EN(info->cs.uses_block_id[0]) | S_00B84C_TGID_Y_EN(info->cs.uses_block_id[1]) |
2127                        S_00B84C_TGID_Z_EN(info->cs.uses_block_id[2]) |
2128                        S_00B84C_TIDIG_COMP_CNT(info->cs.uses_thread_id[2]   ? 2
2129                                                : info->cs.uses_thread_id[1] ? 1
2130                                                                             : 0) |
2131                        S_00B84C_TG_SIZE_EN(info->cs.uses_local_invocation_idx) | S_00B84C_LDS_SIZE(config->lds_size) |
2132                        S_00B84C_EXCP_EN(excp_en) | S_00B84C_EXCP_EN_MSB(excp_en_msb);
2133       config->rsrc3 |= S_00B8A0_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
2134 
2135       break;
2136    default:
2137       unreachable("unsupported shader type");
2138       break;
2139    }
2140 
2141    if (pdev->info.gfx_level >= GFX10 && info->is_ngg &&
2142        (stage == MESA_SHADER_VERTEX || stage == MESA_SHADER_TESS_EVAL || stage == MESA_SHADER_GEOMETRY ||
2143         stage == MESA_SHADER_MESH)) {
2144       unsigned gs_vgpr_comp_cnt, es_vgpr_comp_cnt;
2145 
2146       /* VGPR5-8: (VertexID, UserVGPR0, UserVGPR1, UserVGPR2 / InstanceID)
2147        *
2148        * On GFX12, InstanceID is in VGPR1.
2149        */
2150       if (es_stage == MESA_SHADER_VERTEX) {
2151          if (info->vs.needs_instance_id) {
2152             es_vgpr_comp_cnt = pdev->info.gfx_level >= GFX12 ? 1 : 3;
2153          } else {
2154             es_vgpr_comp_cnt = 0;
2155          }
2156       } else if (es_stage == MESA_SHADER_TESS_EVAL) {
2157          bool enable_prim_id = info->outinfo.export_prim_id || info->uses_prim_id;
2158          es_vgpr_comp_cnt = enable_prim_id ? 3 : 2;
2159       } else if (es_stage == MESA_SHADER_MESH) {
2160          es_vgpr_comp_cnt = 0;
2161       } else {
2162          unreachable("Unexpected ES shader stage");
2163       }
2164 
2165       if (pdev->info.gfx_level >= GFX12) {
2166          if (info->gs.vertices_in >= 4) {
2167             gs_vgpr_comp_cnt = 2; /* VGPR2 contains offsets 3-5 */
2168          } else if (info->uses_prim_id ||
2169                     (es_stage == MESA_SHADER_VERTEX &&
2170                      (info->outinfo.export_prim_id || info->outinfo.export_prim_id_per_primitive))) {
2171             gs_vgpr_comp_cnt = 1; /* VGPR1 contains PrimitiveID. */
2172          } else {
2173             gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0-2, GS invocation ID. */
2174          }
2175       } else {
2176          /* GS vertex offsets in NGG:
2177           * - in passthrough mode, they are all packed into VGPR0
2178           * - in the default mode: VGPR0: offsets 0, 1; VGPR1: offsets 2, 3
2179           *
2180           * The vertex offset 2 is always needed when NGG isn't in passthrough mode
2181           * and uses triangle input primitives, including with NGG culling.
2182           */
2183          bool need_gs_vtx_offset2 = !info->is_ngg_passthrough || info->gs.vertices_in >= 3;
2184 
2185          /* TES only needs vertex offset 2 for triangles or quads. */
2186          if (stage == MESA_SHADER_TESS_EVAL)
2187             need_gs_vtx_offset2 &= info->tes._primitive_mode == TESS_PRIMITIVE_TRIANGLES ||
2188                                    info->tes._primitive_mode == TESS_PRIMITIVE_QUADS;
2189 
2190          if (info->uses_invocation_id) {
2191             gs_vgpr_comp_cnt = 3; /* VGPR3 contains InvocationID. */
2192          } else if (info->uses_prim_id ||
2193                     (es_stage == MESA_SHADER_VERTEX &&
2194                      (info->outinfo.export_prim_id || info->outinfo.export_prim_id_per_primitive))) {
2195             gs_vgpr_comp_cnt = 2; /* VGPR2 contains PrimitiveID. */
2196          } else if (need_gs_vtx_offset2) {
2197             gs_vgpr_comp_cnt = 1; /* VGPR1 contains offsets 2, 3 */
2198          } else {
2199             gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0, 1 (or passthrough prim) */
2200          }
2201       }
2202 
2203       /* Disable the WGP mode on gfx10.3 because it can hang. (it
2204        * happened on VanGogh) Let's disable it on all chips that
2205        * disable exactly 1 CU per SA for GS.
2206        */
2207       config->rsrc1 |= S_00B228_GS_VGPR_COMP_CNT(gs_vgpr_comp_cnt) | S_00B228_WGP_MODE(wgp_mode);
2208       config->rsrc2 |= S_00B22C_ES_VGPR_COMP_CNT(es_vgpr_comp_cnt) | S_00B22C_LDS_SIZE(config->lds_size) |
2209                        S_00B22C_OC_LDS_EN(es_stage == MESA_SHADER_TESS_EVAL);
2210    } else if (pdev->info.gfx_level >= GFX9 && stage == MESA_SHADER_GEOMETRY) {
2211       unsigned gs_vgpr_comp_cnt, es_vgpr_comp_cnt;
2212 
2213       if (es_stage == MESA_SHADER_VERTEX) {
2214          /* VGPR0-3: (VertexID, InstanceID / StepRate0, ...) */
2215          if (info->vs.needs_instance_id) {
2216             es_vgpr_comp_cnt = pdev->info.gfx_level >= GFX10 ? 3 : 1;
2217          } else {
2218             es_vgpr_comp_cnt = 0;
2219          }
2220       } else if (es_stage == MESA_SHADER_TESS_EVAL) {
2221          es_vgpr_comp_cnt = info->uses_prim_id ? 3 : 2;
2222       } else {
2223          unreachable("invalid shader ES type");
2224       }
2225 
2226       /* If offsets 4, 5 are used, GS_VGPR_COMP_CNT is ignored and
2227        * VGPR[0:4] are always loaded.
2228        */
2229       if (info->uses_invocation_id) {
2230          gs_vgpr_comp_cnt = 3; /* VGPR3 contains InvocationID. */
2231       } else if (info->uses_prim_id) {
2232          gs_vgpr_comp_cnt = 2; /* VGPR2 contains PrimitiveID. */
2233       } else if (info->gs.vertices_in >= 3) {
2234          gs_vgpr_comp_cnt = 1; /* VGPR1 contains offsets 2, 3 */
2235       } else {
2236          gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0, 1 */
2237       }
2238 
2239       config->rsrc1 |= S_00B228_GS_VGPR_COMP_CNT(gs_vgpr_comp_cnt) | S_00B228_WGP_MODE(wgp_mode);
2240       config->rsrc2 |=
2241          S_00B22C_ES_VGPR_COMP_CNT(es_vgpr_comp_cnt) | S_00B22C_OC_LDS_EN(es_stage == MESA_SHADER_TESS_EVAL);
2242    } else if (pdev->info.gfx_level >= GFX9 && stage == MESA_SHADER_TESS_CTRL) {
2243       config->rsrc1 |= S_00B428_LS_VGPR_COMP_CNT(vgpr_comp_cnt);
2244    } else {
2245       config->rsrc1 |= S_00B128_VGPR_COMP_CNT(vgpr_comp_cnt);
2246    }
2247 
2248    /* Precompute register values for faster emission. */
2249    radv_precompute_registers(device, binary);
2250 
2251    return true;
2252 }
2253 
2254 void
radv_shader_combine_cfg_vs_tcs(const struct radv_shader * vs,const struct radv_shader * tcs,uint32_t * rsrc1_out,uint32_t * rsrc2_out)2255 radv_shader_combine_cfg_vs_tcs(const struct radv_shader *vs, const struct radv_shader *tcs, uint32_t *rsrc1_out,
2256                                uint32_t *rsrc2_out)
2257 {
2258    if (rsrc1_out) {
2259       uint32_t rsrc1 = vs->config.rsrc1;
2260 
2261       if (G_00B848_VGPRS(tcs->config.rsrc1) > G_00B848_VGPRS(rsrc1))
2262          rsrc1 = (rsrc1 & C_00B848_VGPRS) | (tcs->config.rsrc1 & ~C_00B848_VGPRS);
2263       if (G_00B228_SGPRS(tcs->config.rsrc1) > G_00B228_SGPRS(rsrc1))
2264          rsrc1 = (rsrc1 & C_00B228_SGPRS) | (tcs->config.rsrc1 & ~C_00B228_SGPRS);
2265       if (G_00B428_LS_VGPR_COMP_CNT(tcs->config.rsrc1) > G_00B428_LS_VGPR_COMP_CNT(rsrc1))
2266          rsrc1 = (rsrc1 & C_00B428_LS_VGPR_COMP_CNT) | (tcs->config.rsrc1 & ~C_00B428_LS_VGPR_COMP_CNT);
2267 
2268       *rsrc1_out = rsrc1;
2269    }
2270 
2271    if (rsrc2_out) {
2272       uint32_t rsrc2 = vs->config.rsrc2;
2273 
2274       rsrc2 |= tcs->config.rsrc2 & ~C_00B12C_SCRATCH_EN;
2275 
2276       *rsrc2_out = rsrc2;
2277    }
2278 }
2279 
2280 void
radv_shader_combine_cfg_vs_gs(const struct radv_shader * vs,const struct radv_shader * gs,uint32_t * rsrc1_out,uint32_t * rsrc2_out)2281 radv_shader_combine_cfg_vs_gs(const struct radv_shader *vs, const struct radv_shader *gs, uint32_t *rsrc1_out,
2282                               uint32_t *rsrc2_out)
2283 {
2284    assert(G_00B12C_USER_SGPR(vs->config.rsrc2) == G_00B12C_USER_SGPR(gs->config.rsrc2));
2285 
2286    if (rsrc1_out) {
2287       uint32_t rsrc1 = vs->config.rsrc1;
2288 
2289       if (G_00B848_VGPRS(gs->config.rsrc1) > G_00B848_VGPRS(rsrc1))
2290          rsrc1 = (rsrc1 & C_00B848_VGPRS) | (gs->config.rsrc1 & ~C_00B848_VGPRS);
2291       if (G_00B228_SGPRS(gs->config.rsrc1) > G_00B228_SGPRS(rsrc1))
2292          rsrc1 = (rsrc1 & C_00B228_SGPRS) | (gs->config.rsrc1 & ~C_00B228_SGPRS);
2293       if (G_00B228_GS_VGPR_COMP_CNT(gs->config.rsrc1) > G_00B228_GS_VGPR_COMP_CNT(rsrc1))
2294          rsrc1 = (rsrc1 & C_00B228_GS_VGPR_COMP_CNT) | (gs->config.rsrc1 & ~C_00B228_GS_VGPR_COMP_CNT);
2295 
2296       *rsrc1_out = rsrc1;
2297    }
2298 
2299    if (rsrc2_out) {
2300       uint32_t rsrc2 = vs->config.rsrc2;
2301 
2302       if (G_00B22C_ES_VGPR_COMP_CNT(gs->config.rsrc2) > G_00B22C_ES_VGPR_COMP_CNT(rsrc2))
2303          rsrc2 = (rsrc2 & C_00B22C_ES_VGPR_COMP_CNT) | (gs->config.rsrc2 & ~C_00B22C_ES_VGPR_COMP_CNT);
2304 
2305       rsrc2 |= gs->config.rsrc2 & ~(C_00B12C_SCRATCH_EN & C_00B12C_SO_EN & C_00B12C_SO_BASE0_EN & C_00B12C_SO_BASE1_EN &
2306                                     C_00B12C_SO_BASE2_EN & C_00B12C_SO_BASE3_EN);
2307 
2308       *rsrc2_out = rsrc2;
2309    }
2310 }
2311 
2312 void
radv_shader_combine_cfg_tes_gs(const struct radv_shader * tes,const struct radv_shader * gs,uint32_t * rsrc1_out,uint32_t * rsrc2_out)2313 radv_shader_combine_cfg_tes_gs(const struct radv_shader *tes, const struct radv_shader *gs, uint32_t *rsrc1_out,
2314                                uint32_t *rsrc2_out)
2315 {
2316    radv_shader_combine_cfg_vs_gs(tes, gs, rsrc1_out, rsrc2_out);
2317 
2318    if (rsrc2_out) {
2319       *rsrc2_out |= S_00B22C_OC_LDS_EN(1);
2320    }
2321 }
2322 
2323 /* This struct has pointers into radv_shader_binary_legacy::data for easy access to the different sections. */
2324 struct radv_shader_binary_layout {
2325    void *stats;
2326    void *code;
2327    void *ir;
2328    void *disasm;
2329    void *debug_info;
2330 };
2331 
2332 static struct radv_shader_binary_layout
radv_shader_binary_get_layout(struct radv_shader_binary_legacy * binary)2333 radv_shader_binary_get_layout(struct radv_shader_binary_legacy *binary)
2334 {
2335    struct radv_shader_binary_layout layout = {0};
2336 
2337    uint32_t offset = 0;
2338 
2339    layout.stats = binary->data + offset;
2340    offset += binary->stats_size;
2341 
2342    layout.code = binary->data + offset;
2343    offset += binary->code_size;
2344 
2345    layout.ir = binary->data + offset;
2346    offset += binary->ir_size;
2347 
2348    layout.disasm = binary->data + offset;
2349    offset += binary->disasm_size;
2350 
2351    layout.debug_info = binary->data + offset;
2352    offset += binary->debug_info_size;
2353 
2354    return layout;
2355 }
2356 
2357 static bool
radv_shader_binary_upload(struct radv_device * device,const struct radv_shader_binary * binary,struct radv_shader * shader,void * dest_ptr)2358 radv_shader_binary_upload(struct radv_device *device, const struct radv_shader_binary *binary,
2359                           struct radv_shader *shader, void *dest_ptr)
2360 {
2361    shader->code = calloc(shader->code_size, 1);
2362    if (!shader->code) {
2363       radv_shader_unref(device, shader);
2364       return false;
2365    }
2366 
2367    if (binary->type == RADV_BINARY_TYPE_RTLD) {
2368 #if !defined(USE_LIBELF)
2369       return false;
2370 #else
2371       struct ac_rtld_binary rtld_binary = {0};
2372 
2373       if (!radv_open_rtld_binary(device, binary, &rtld_binary)) {
2374          free(shader);
2375          return false;
2376       }
2377 
2378       struct ac_rtld_upload_info info = {
2379          .binary = &rtld_binary,
2380          .rx_va = radv_shader_get_va(shader),
2381          .rx_ptr = dest_ptr,
2382       };
2383 
2384       if (!ac_rtld_upload(&info)) {
2385          radv_shader_unref(device, shader);
2386          ac_rtld_close(&rtld_binary);
2387          return false;
2388       }
2389 
2390       ac_rtld_close(&rtld_binary);
2391 
2392       if (shader->code) {
2393          /* Instead of running RTLD twice, just copy the relocated binary back from VRAM.
2394           * Use streaming memcpy to reduce penalty of copying from uncachable memory.
2395           */
2396          util_streaming_load_memcpy(shader->code, dest_ptr, shader->code_size);
2397       }
2398 #endif
2399    } else {
2400       struct radv_shader_binary_legacy *bin = (struct radv_shader_binary_legacy *)binary;
2401       struct radv_shader_binary_layout layout = radv_shader_binary_get_layout(bin);
2402 
2403       memcpy(dest_ptr, layout.code, bin->code_size);
2404 
2405       if (shader->code) {
2406          memcpy(shader->code, layout.code, bin->code_size);
2407       }
2408    }
2409 
2410    return true;
2411 }
2412 
2413 static VkResult
radv_shader_dma_resize_upload_buf(struct radv_device * device,struct radv_shader_dma_submission * submission,uint64_t size)2414 radv_shader_dma_resize_upload_buf(struct radv_device *device, struct radv_shader_dma_submission *submission,
2415                                   uint64_t size)
2416 {
2417    if (submission->bo)
2418       radv_bo_destroy(device, NULL, submission->bo);
2419 
2420    VkResult result = radv_bo_create(
2421       device, NULL, size, RADV_SHADER_ALLOC_ALIGNMENT, RADEON_DOMAIN_GTT,
2422       RADEON_FLAG_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING | RADEON_FLAG_32BIT | RADEON_FLAG_GTT_WC,
2423       RADV_BO_PRIORITY_UPLOAD_BUFFER, 0, true, &submission->bo);
2424    if (result != VK_SUCCESS)
2425       return result;
2426 
2427    submission->ptr = radv_buffer_map(device->ws, submission->bo);
2428    submission->bo_size = size;
2429 
2430    return VK_SUCCESS;
2431 }
2432 
2433 struct radv_shader_dma_submission *
radv_shader_dma_pop_submission(struct radv_device * device)2434 radv_shader_dma_pop_submission(struct radv_device *device)
2435 {
2436    struct radv_shader_dma_submission *submission;
2437 
2438    mtx_lock(&device->shader_dma_submission_list_mutex);
2439 
2440    while (list_is_empty(&device->shader_dma_submissions))
2441       cnd_wait(&device->shader_dma_submission_list_cond, &device->shader_dma_submission_list_mutex);
2442 
2443    submission = list_first_entry(&device->shader_dma_submissions, struct radv_shader_dma_submission, list);
2444    list_del(&submission->list);
2445 
2446    mtx_unlock(&device->shader_dma_submission_list_mutex);
2447 
2448    return submission;
2449 }
2450 
2451 void
radv_shader_dma_push_submission(struct radv_device * device,struct radv_shader_dma_submission * submission,uint64_t seq)2452 radv_shader_dma_push_submission(struct radv_device *device, struct radv_shader_dma_submission *submission, uint64_t seq)
2453 {
2454    submission->seq = seq;
2455 
2456    mtx_lock(&device->shader_dma_submission_list_mutex);
2457 
2458    list_addtail(&submission->list, &device->shader_dma_submissions);
2459    cnd_signal(&device->shader_dma_submission_list_cond);
2460 
2461    mtx_unlock(&device->shader_dma_submission_list_mutex);
2462 }
2463 
2464 struct radv_shader_dma_submission *
radv_shader_dma_get_submission(struct radv_device * device,struct radeon_winsys_bo * bo,uint64_t va,uint64_t size)2465 radv_shader_dma_get_submission(struct radv_device *device, struct radeon_winsys_bo *bo, uint64_t va, uint64_t size)
2466 {
2467    struct radv_shader_dma_submission *submission = radv_shader_dma_pop_submission(device);
2468    struct radeon_cmdbuf *cs = submission->cs;
2469    struct radeon_winsys *ws = device->ws;
2470    VkResult result;
2471 
2472    /* Wait for potentially in-flight submission to settle */
2473    result = radv_shader_wait_for_upload(device, submission->seq);
2474    if (result != VK_SUCCESS)
2475       goto fail;
2476 
2477    ws->cs_reset(cs);
2478 
2479    if (submission->bo_size < size) {
2480       result = radv_shader_dma_resize_upload_buf(device, submission, size);
2481       if (result != VK_SUCCESS)
2482          goto fail;
2483    }
2484 
2485    radv_sdma_copy_buffer(device, cs, radv_buffer_get_va(submission->bo), va, size);
2486    radv_cs_add_buffer(ws, cs, submission->bo);
2487    radv_cs_add_buffer(ws, cs, bo);
2488 
2489    result = ws->cs_finalize(cs);
2490    if (result != VK_SUCCESS)
2491       goto fail;
2492 
2493    return submission;
2494 
2495 fail:
2496    radv_shader_dma_push_submission(device, submission, 0);
2497 
2498    return NULL;
2499 }
2500 
2501 /*
2502  * If upload_seq_out is NULL, this function blocks until the DMA is complete. Otherwise, the
2503  * semaphore value to wait on device->shader_upload_sem is stored in *upload_seq_out.
2504  */
2505 bool
radv_shader_dma_submit(struct radv_device * device,struct radv_shader_dma_submission * submission,uint64_t * upload_seq_out)2506 radv_shader_dma_submit(struct radv_device *device, struct radv_shader_dma_submission *submission,
2507                        uint64_t *upload_seq_out)
2508 {
2509    struct radeon_cmdbuf *cs = submission->cs;
2510    struct radeon_winsys *ws = device->ws;
2511    VkResult result;
2512 
2513    mtx_lock(&device->shader_upload_hw_ctx_mutex);
2514 
2515    uint64_t upload_seq = device->shader_upload_seq + 1;
2516 
2517    struct vk_semaphore *semaphore = vk_semaphore_from_handle(device->shader_upload_sem);
2518    struct vk_sync *sync = vk_semaphore_get_active_sync(semaphore);
2519    const struct vk_sync_signal signal_info = {
2520       .sync = sync,
2521       .signal_value = upload_seq,
2522       .stage_mask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT,
2523    };
2524 
2525    struct radv_winsys_submit_info submit = {
2526       .ip_type = AMD_IP_SDMA,
2527       .queue_index = 0,
2528       .cs_array = &cs,
2529       .cs_count = 1,
2530    };
2531 
2532    result = ws->cs_submit(device->shader_upload_hw_ctx, &submit, 0, NULL, 1, &signal_info);
2533    if (result != VK_SUCCESS) {
2534       mtx_unlock(&device->shader_upload_hw_ctx_mutex);
2535       radv_shader_dma_push_submission(device, submission, 0);
2536       return false;
2537    }
2538    device->shader_upload_seq = upload_seq;
2539    mtx_unlock(&device->shader_upload_hw_ctx_mutex);
2540 
2541    radv_shader_dma_push_submission(device, submission, upload_seq);
2542 
2543    if (upload_seq_out) {
2544       *upload_seq_out = upload_seq;
2545    } else {
2546       result = radv_shader_wait_for_upload(device, upload_seq);
2547       if (result != VK_SUCCESS)
2548          return false;
2549    }
2550 
2551    return true;
2552 }
2553 
2554 static bool
radv_shader_upload(struct radv_device * device,struct radv_shader * shader,const struct radv_shader_binary * binary)2555 radv_shader_upload(struct radv_device *device, struct radv_shader *shader, const struct radv_shader_binary *binary)
2556 {
2557    if (device->shader_use_invisible_vram) {
2558       struct radv_shader_dma_submission *submission =
2559          radv_shader_dma_get_submission(device, shader->bo, shader->va, shader->code_size);
2560       if (!submission)
2561          return false;
2562 
2563       if (!radv_shader_binary_upload(device, binary, shader, submission->ptr)) {
2564          radv_shader_dma_push_submission(device, submission, 0);
2565          return false;
2566       }
2567 
2568       if (!radv_shader_dma_submit(device, submission, &shader->upload_seq))
2569          return false;
2570    } else {
2571       void *dest_ptr = shader->alloc->arena->ptr + shader->alloc->offset;
2572 
2573       if (!radv_shader_binary_upload(device, binary, shader, dest_ptr))
2574          return false;
2575    }
2576    return true;
2577 }
2578 
2579 unsigned
radv_get_max_waves(const struct radv_device * device,const struct ac_shader_config * conf,const struct radv_shader_info * info)2580 radv_get_max_waves(const struct radv_device *device, const struct ac_shader_config *conf,
2581                    const struct radv_shader_info *info)
2582 {
2583    const struct radv_physical_device *pdev = radv_device_physical(device);
2584    const struct radeon_info *gpu_info = &pdev->info;
2585    const enum amd_gfx_level gfx_level = gpu_info->gfx_level;
2586    const uint8_t wave_size = info->wave_size;
2587    gl_shader_stage stage = info->stage;
2588    unsigned max_simd_waves = gpu_info->max_waves_per_simd;
2589    unsigned lds_per_wave = 0;
2590 
2591    if (stage == MESA_SHADER_FRAGMENT) {
2592       lds_per_wave = conf->lds_size * gpu_info->lds_encode_granularity + info->ps.num_inputs * 48;
2593       lds_per_wave = align(lds_per_wave, gpu_info->lds_alloc_granularity);
2594    } else if (stage == MESA_SHADER_COMPUTE || stage == MESA_SHADER_TASK) {
2595       unsigned max_workgroup_size = info->workgroup_size;
2596       lds_per_wave = align(conf->lds_size * gpu_info->lds_encode_granularity, gpu_info->lds_alloc_granularity);
2597       lds_per_wave /= DIV_ROUND_UP(max_workgroup_size, wave_size);
2598    }
2599 
2600    if (conf->num_sgprs && gfx_level < GFX10) {
2601       unsigned sgprs = align(conf->num_sgprs, gfx_level >= GFX8 ? 16 : 8);
2602       max_simd_waves = MIN2(max_simd_waves, gpu_info->num_physical_sgprs_per_simd / sgprs);
2603    }
2604 
2605    if (conf->num_vgprs) {
2606       unsigned physical_vgprs = gpu_info->num_physical_wave64_vgprs_per_simd * (64 / wave_size);
2607       unsigned vgprs = align(conf->num_vgprs, wave_size == 32 ? 8 : 4);
2608       if (gfx_level >= GFX10_3) {
2609          unsigned real_vgpr_gran = gpu_info->num_physical_wave64_vgprs_per_simd / 64;
2610          vgprs = util_align_npot(vgprs, real_vgpr_gran * (wave_size == 32 ? 2 : 1));
2611       }
2612       max_simd_waves = MIN2(max_simd_waves, physical_vgprs / vgprs);
2613    }
2614 
2615    unsigned simd_per_workgroup = gpu_info->num_simd_per_compute_unit;
2616    if (gfx_level >= GFX10)
2617       simd_per_workgroup *= 2; /* like lds_size_per_workgroup, assume WGP on GFX10+ */
2618 
2619    unsigned max_lds_per_simd = gpu_info->lds_size_per_workgroup / simd_per_workgroup;
2620    if (lds_per_wave)
2621       max_simd_waves = MIN2(max_simd_waves, DIV_ROUND_UP(max_lds_per_simd, lds_per_wave));
2622 
2623    return gfx_level >= GFX10 ? max_simd_waves * (wave_size / 32) : max_simd_waves;
2624 }
2625 
2626 unsigned
radv_get_max_scratch_waves(const struct radv_device * device,struct radv_shader * shader)2627 radv_get_max_scratch_waves(const struct radv_device *device, struct radv_shader *shader)
2628 {
2629    const struct radv_physical_device *pdev = radv_device_physical(device);
2630    const unsigned num_cu = pdev->info.num_cu;
2631 
2632    return MIN2(device->scratch_waves, 4 * num_cu * shader->max_waves);
2633 }
2634 
2635 VkResult
radv_shader_create_uncached(struct radv_device * device,const struct radv_shader_binary * binary,bool replayable,struct radv_serialized_shader_arena_block * replay_block,struct radv_shader ** out_shader)2636 radv_shader_create_uncached(struct radv_device *device, const struct radv_shader_binary *binary, bool replayable,
2637                             struct radv_serialized_shader_arena_block *replay_block, struct radv_shader **out_shader)
2638 {
2639    VkResult result = VK_SUCCESS;
2640    struct radv_shader *shader = calloc(1, sizeof(struct radv_shader));
2641    if (!shader) {
2642       result = VK_ERROR_OUT_OF_HOST_MEMORY;
2643       goto out;
2644    }
2645    simple_mtx_init(&shader->replay_mtx, mtx_plain);
2646 
2647    _mesa_blake3_compute(binary, binary->total_size, shader->hash);
2648 
2649    vk_pipeline_cache_object_init(&device->vk, &shader->base, &radv_shader_ops, shader->hash, sizeof(shader->hash));
2650 
2651    shader->info = binary->info;
2652    shader->config = binary->config;
2653    shader->max_waves = radv_get_max_waves(device, &shader->config, &shader->info);
2654 
2655    if (binary->type == RADV_BINARY_TYPE_RTLD) {
2656 #if !defined(USE_LIBELF)
2657       goto out;
2658 #else
2659       struct radv_shader_binary_rtld *bin = (struct radv_shader_binary_rtld *)binary;
2660       struct ac_rtld_binary rtld_binary = {0};
2661 
2662       if (!radv_open_rtld_binary(device, binary, &rtld_binary)) {
2663          result = VK_ERROR_OUT_OF_HOST_MEMORY;
2664          goto out;
2665       }
2666 
2667       shader->code_size = rtld_binary.rx_size;
2668       shader->exec_size = rtld_binary.exec_size;
2669 
2670       const char *disasm_data;
2671       size_t disasm_size;
2672       if (!ac_rtld_get_section_by_name(&rtld_binary, ".AMDGPU.disasm", &disasm_data, &disasm_size)) {
2673          result = VK_ERROR_UNKNOWN;
2674          goto out;
2675       }
2676 
2677       shader->ir_string = bin->llvm_ir_size ? strdup((const char *)(bin->data + bin->elf_size)) : NULL;
2678       shader->disasm_string = malloc(disasm_size + 1);
2679       memcpy(shader->disasm_string, disasm_data, disasm_size);
2680       shader->disasm_string[disasm_size] = 0;
2681 
2682       ac_rtld_close(&rtld_binary);
2683 #endif
2684    } else {
2685       struct radv_shader_binary_legacy *bin = (struct radv_shader_binary_legacy *)binary;
2686       struct radv_shader_binary_layout layout = radv_shader_binary_get_layout(bin);
2687 
2688       shader->code_size = bin->code_size;
2689       shader->exec_size = bin->exec_size;
2690 
2691       if (bin->stats_size) {
2692          shader->statistics = calloc(bin->stats_size, 1);
2693          memcpy(shader->statistics, layout.stats, bin->stats_size);
2694       }
2695 
2696       shader->ir_string = bin->ir_size ? strdup(layout.ir) : NULL;
2697       shader->disasm_string = bin->disasm_size ? strdup(layout.disasm) : NULL;
2698 
2699       if (bin->debug_info_size) {
2700          shader->debug_info = malloc(bin->debug_info_size);
2701          memcpy(shader->debug_info, layout.debug_info, bin->debug_info_size);
2702          shader->debug_info_count = bin->debug_info_size / sizeof(struct ac_shader_debug_info);
2703       }
2704    }
2705 
2706    if (replay_block) {
2707       shader->alloc = radv_replay_shader_arena_block(device, replay_block, shader);
2708       if (!shader->alloc) {
2709          result = VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS;
2710          goto out;
2711       }
2712 
2713       shader->has_replay_alloc = true;
2714    } else {
2715       shader->alloc = radv_alloc_shader_memory(device, shader->code_size, replayable, shader);
2716       if (!shader->alloc) {
2717          result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
2718          goto out;
2719       }
2720    }
2721 
2722    shader->bo = shader->alloc->arena->bo;
2723    shader->va = radv_buffer_get_va(shader->bo) + shader->alloc->offset;
2724 
2725    if (!radv_shader_upload(device, shader, binary)) {
2726       result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
2727       goto out;
2728    }
2729 
2730    *out_shader = shader;
2731 
2732 out:
2733    if (result != VK_SUCCESS) {
2734       free(shader);
2735       *out_shader = NULL;
2736    }
2737 
2738    return result;
2739 }
2740 
2741 bool
radv_shader_reupload(struct radv_device * device,struct radv_shader * shader)2742 radv_shader_reupload(struct radv_device *device, struct radv_shader *shader)
2743 {
2744    if (device->shader_use_invisible_vram) {
2745       struct radv_shader_dma_submission *submission =
2746          radv_shader_dma_get_submission(device, shader->bo, shader->va, shader->code_size);
2747       if (!submission)
2748          return false;
2749 
2750       memcpy(submission->ptr, shader->code, shader->code_size);
2751 
2752       if (!radv_shader_dma_submit(device, submission, &shader->upload_seq))
2753          return false;
2754    } else {
2755       void *dest_ptr = shader->alloc->arena->ptr + shader->alloc->offset;
2756       memcpy(dest_ptr, shader->code, shader->code_size);
2757    }
2758    return true;
2759 }
2760 
2761 static bool
radv_shader_part_binary_upload(struct radv_device * device,const struct radv_shader_part_binary * bin,struct radv_shader_part * shader_part)2762 radv_shader_part_binary_upload(struct radv_device *device, const struct radv_shader_part_binary *bin,
2763                                struct radv_shader_part *shader_part)
2764 {
2765    struct radv_shader_dma_submission *submission = NULL;
2766    void *dest_ptr;
2767 
2768    if (device->shader_use_invisible_vram) {
2769       uint64_t va = radv_buffer_get_va(shader_part->alloc->arena->bo) + shader_part->alloc->offset;
2770       submission = radv_shader_dma_get_submission(device, shader_part->alloc->arena->bo, va, bin->code_size);
2771       if (!submission)
2772          return false;
2773 
2774       dest_ptr = submission->ptr;
2775    } else {
2776       dest_ptr = shader_part->alloc->arena->ptr + shader_part->alloc->offset;
2777    }
2778 
2779    memcpy(dest_ptr, bin->data, bin->code_size);
2780 
2781    if (device->shader_use_invisible_vram) {
2782       if (!radv_shader_dma_submit(device, submission, &shader_part->upload_seq))
2783          return false;
2784    }
2785 
2786    return true;
2787 }
2788 
2789 struct radv_shader_part *
radv_shader_part_create(struct radv_device * device,struct radv_shader_part_binary * binary,unsigned wave_size)2790 radv_shader_part_create(struct radv_device *device, struct radv_shader_part_binary *binary, unsigned wave_size)
2791 {
2792    struct radv_shader_part *shader_part;
2793 
2794    shader_part = calloc(1, sizeof(struct radv_shader_part));
2795    if (!shader_part)
2796       return NULL;
2797 
2798    shader_part->ref_count = 1;
2799    shader_part->code_size = binary->code_size;
2800    shader_part->rsrc1 =
2801       S_00B848_VGPRS((binary->num_vgprs - 1) / (wave_size == 32 ? 8 : 4)) | S_00B228_SGPRS((binary->num_sgprs - 1) / 8);
2802    shader_part->disasm_string = binary->disasm_size ? strdup((const char *)(binary->data + binary->code_size)) : NULL;
2803 
2804    shader_part->spi_shader_col_format = binary->info.spi_shader_col_format;
2805    shader_part->cb_shader_mask = binary->info.cb_shader_mask;
2806    shader_part->spi_shader_z_format = binary->info.spi_shader_z_format;
2807 
2808    /* Allocate memory and upload. */
2809    shader_part->alloc = radv_alloc_shader_memory(device, shader_part->code_size, false, NULL);
2810    if (!shader_part->alloc)
2811       goto fail;
2812 
2813    shader_part->bo = shader_part->alloc->arena->bo;
2814    shader_part->va = radv_buffer_get_va(shader_part->bo) + shader_part->alloc->offset;
2815 
2816    if (!radv_shader_part_binary_upload(device, binary, shader_part))
2817       goto fail;
2818 
2819    return shader_part;
2820 
2821 fail:
2822    radv_shader_part_destroy(device, shader_part);
2823    return NULL;
2824 }
2825 
2826 bool
radv_shader_part_cache_init(struct radv_shader_part_cache * cache,struct radv_shader_part_cache_ops * ops)2827 radv_shader_part_cache_init(struct radv_shader_part_cache *cache, struct radv_shader_part_cache_ops *ops)
2828 {
2829    cache->ops = ops;
2830    if (!_mesa_set_init(&cache->entries, NULL, cache->ops->hash, cache->ops->equals))
2831       return false;
2832    simple_mtx_init(&cache->lock, mtx_plain);
2833    return true;
2834 }
2835 
2836 void
radv_shader_part_cache_finish(struct radv_device * device,struct radv_shader_part_cache * cache)2837 radv_shader_part_cache_finish(struct radv_device *device, struct radv_shader_part_cache *cache)
2838 {
2839    set_foreach (&cache->entries, entry)
2840       radv_shader_part_unref(device, radv_shader_part_from_cache_entry(entry->key));
2841    simple_mtx_destroy(&cache->lock);
2842    ralloc_free(cache->entries.table);
2843 }
2844 
2845 /*
2846  * A cache with atomics-free fast path for prolog / epilog lookups.
2847  *
2848  * VS prologs and PS/TCS epilogs are used to support dynamic states. In
2849  * particular dynamic blend state is heavily used by Zink. These are called
2850  * every frame as a part of command buffer building, so these functions are
2851  * on the hot path.
2852  *
2853  * Originally this was implemented with a rwlock, but this lead to high
2854  * overhead. To avoid locking altogether in the hot path, the cache is done
2855  * at two levels: one at device level, and another at each CS. Access to the
2856  * CS cache is externally synchronized and do not require a lock.
2857  */
2858 struct radv_shader_part *
radv_shader_part_cache_get(struct radv_device * device,struct radv_shader_part_cache * cache,struct set * local_entries,const void * key)2859 radv_shader_part_cache_get(struct radv_device *device, struct radv_shader_part_cache *cache, struct set *local_entries,
2860                            const void *key)
2861 {
2862    struct set_entry *local, *global;
2863    bool local_found, global_found;
2864    uint32_t hash = cache->ops->hash(key);
2865 
2866    local = _mesa_set_search_or_add_pre_hashed(local_entries, hash, key, &local_found);
2867    if (local_found)
2868       return radv_shader_part_from_cache_entry(local->key);
2869 
2870    simple_mtx_lock(&cache->lock);
2871    global = _mesa_set_search_or_add_pre_hashed(&cache->entries, hash, key, &global_found);
2872    if (global_found) {
2873       simple_mtx_unlock(&cache->lock);
2874       local->key = global->key;
2875       return radv_shader_part_from_cache_entry(global->key);
2876    }
2877 
2878    struct radv_shader_part *shader_part = cache->ops->create(device, key);
2879    if (!shader_part) {
2880       _mesa_set_remove(&cache->entries, global);
2881       simple_mtx_unlock(&cache->lock);
2882       _mesa_set_remove(local_entries, local);
2883       return NULL;
2884    }
2885 
2886    /* Make the set entry a pointer to the key, so that the hash and equals
2887     * functions from radv_shader_part_cache_ops can be directly used.
2888     */
2889    global->key = &shader_part->key;
2890    simple_mtx_unlock(&cache->lock);
2891    local->key = &shader_part->key;
2892    return shader_part;
2893 }
2894 
2895 static char *
radv_gather_nir_debug_info(struct nir_shader * const * shaders,int shader_count)2896 radv_gather_nir_debug_info(struct nir_shader *const *shaders, int shader_count)
2897 {
2898    char **strings = malloc(shader_count * sizeof(char *));
2899    uint32_t total_size = 1;
2900    uint32_t first_line = 1;
2901 
2902    for (uint32_t i = 0; i < shader_count; i++) {
2903       char *string = nir_shader_gather_debug_info(shaders[i], "", first_line);
2904       strings[i] = string;
2905 
2906       uint32_t length = strlen(string);
2907       total_size += length;
2908 
2909       for (uint32_t c = 0; c < length; c++) {
2910          if (string[c] == '\n')
2911             first_line++;
2912       }
2913    }
2914 
2915    char *ret = calloc(total_size, sizeof(char));
2916    if (ret) {
2917       for (uint32_t i = 0; i < shader_count; i++)
2918          strcat(ret, strings[i]);
2919    }
2920 
2921    for (uint32_t i = 0; i < shader_count; i++)
2922       ralloc_free(strings[i]);
2923    free(strings);
2924 
2925    return ret;
2926 }
2927 
2928 char *
radv_dump_nir_shaders(const struct radv_instance * instance,struct nir_shader * const * shaders,int shader_count)2929 radv_dump_nir_shaders(const struct radv_instance *instance, struct nir_shader *const *shaders, int shader_count)
2930 {
2931    if (instance->debug_flags & RADV_DEBUG_NIR_DEBUG_INFO)
2932       return radv_gather_nir_debug_info(shaders, shader_count);
2933 
2934    char *data = NULL;
2935    char *ret = NULL;
2936    size_t size = 0;
2937    struct u_memstream mem;
2938    if (u_memstream_open(&mem, &data, &size)) {
2939       FILE *const memf = u_memstream_get(&mem);
2940       for (int i = 0; i < shader_count; ++i)
2941          nir_print_shader(shaders[i], memf);
2942       u_memstream_close(&mem);
2943    }
2944 
2945    ret = malloc(size + 1);
2946    if (ret) {
2947       memcpy(ret, data, size);
2948       ret[size] = 0;
2949    }
2950    free(data);
2951    return ret;
2952 }
2953 
2954 static void
radv_aco_build_shader_binary(void ** bin,const struct ac_shader_config * config,const char * llvm_ir_str,unsigned llvm_ir_size,const char * disasm_str,unsigned disasm_size,uint32_t * statistics,uint32_t stats_size,uint32_t exec_size,const uint32_t * code,uint32_t code_dw,const struct aco_symbol * symbols,unsigned num_symbols,const struct ac_shader_debug_info * debug_info,unsigned debug_info_count)2955 radv_aco_build_shader_binary(void **bin, const struct ac_shader_config *config, const char *llvm_ir_str,
2956                              unsigned llvm_ir_size, const char *disasm_str, unsigned disasm_size, uint32_t *statistics,
2957                              uint32_t stats_size, uint32_t exec_size, const uint32_t *code, uint32_t code_dw,
2958                              const struct aco_symbol *symbols, unsigned num_symbols,
2959                              const struct ac_shader_debug_info *debug_info, unsigned debug_info_count)
2960 {
2961    struct radv_shader_binary **binary = (struct radv_shader_binary **)bin;
2962 
2963    uint32_t debug_info_size = debug_info_count * sizeof(struct ac_shader_debug_info);
2964 
2965    size_t size = llvm_ir_size;
2966 
2967    size += debug_info_size;
2968    size += disasm_size;
2969    size += stats_size;
2970 
2971    size += code_dw * sizeof(uint32_t) + sizeof(struct radv_shader_binary_legacy);
2972 
2973    /* We need to calloc to prevent uninitialized data because this will be used
2974     * directly for the disk cache. Uninitialized data can appear because of
2975     * padding in the struct or because legacy_binary->data can be at an offset
2976     * from the start less than sizeof(radv_shader_binary_legacy). */
2977    struct radv_shader_binary_legacy *legacy_binary = (struct radv_shader_binary_legacy *)calloc(size, 1);
2978    legacy_binary->base.type = RADV_BINARY_TYPE_LEGACY;
2979    legacy_binary->base.total_size = size;
2980    legacy_binary->base.config = *config;
2981    legacy_binary->stats_size = stats_size;
2982    legacy_binary->exec_size = exec_size;
2983    legacy_binary->code_size = code_dw * sizeof(uint32_t);
2984    legacy_binary->ir_size = llvm_ir_size;
2985    legacy_binary->disasm_size = disasm_size;
2986    legacy_binary->debug_info_size = debug_info_size;
2987 
2988    struct radv_shader_binary_layout layout = radv_shader_binary_get_layout(legacy_binary);
2989 
2990    if (stats_size)
2991       memcpy(layout.stats, statistics, stats_size);
2992 
2993    memcpy(layout.code, code, code_dw * sizeof(uint32_t));
2994 
2995    if (llvm_ir_size)
2996       memcpy(layout.ir, llvm_ir_str, llvm_ir_size);
2997 
2998    if (disasm_size)
2999       memcpy(layout.disasm, disasm_str, disasm_size);
3000 
3001    if (debug_info_size)
3002       memcpy(layout.debug_info, debug_info, debug_info_size);
3003 
3004    *binary = (struct radv_shader_binary *)legacy_binary;
3005 }
3006 
3007 static void
radv_fill_nir_compiler_options(struct radv_nir_compiler_options * options,struct radv_device * device,const struct radv_graphics_state_key * gfx_state,bool should_use_wgp,bool can_dump_shader,bool keep_shader_info,bool keep_statistic_info)3008 radv_fill_nir_compiler_options(struct radv_nir_compiler_options *options, struct radv_device *device,
3009                                const struct radv_graphics_state_key *gfx_state, bool should_use_wgp,
3010                                bool can_dump_shader, bool keep_shader_info, bool keep_statistic_info)
3011 {
3012    const struct radv_physical_device *pdev = radv_device_physical(device);
3013    const struct radv_instance *instance = radv_physical_device_instance(pdev);
3014 
3015    /* robust_buffer_access_llvm here used by LLVM only, pipeline robustness is not exposed there. */
3016    options->robust_buffer_access_llvm =
3017       (device->vk.enabled_features.robustBufferAccess2 || device->vk.enabled_features.robustBufferAccess);
3018    options->wgp_mode = should_use_wgp;
3019    options->info = &pdev->info;
3020    options->dump_shader = can_dump_shader;
3021    options->dump_ir = options->dump_shader && (instance->debug_flags & RADV_DEBUG_DUMP_BACKEND_IR);
3022    options->dump_preoptir = options->dump_shader && (instance->debug_flags & RADV_DEBUG_DUMP_PREOPT_IR);
3023    options->record_asm = keep_shader_info || options->dump_shader;
3024    options->record_ir = keep_shader_info;
3025    options->record_stats = keep_statistic_info;
3026    options->check_ir = instance->debug_flags & RADV_DEBUG_CHECKIR;
3027    options->enable_mrt_output_nan_fixup = gfx_state ? gfx_state->ps.epilog.enable_mrt_output_nan_fixup : false;
3028 }
3029 
3030 void
radv_set_stage_key_robustness(const struct vk_pipeline_robustness_state * rs,gl_shader_stage stage,struct radv_shader_stage_key * key)3031 radv_set_stage_key_robustness(const struct vk_pipeline_robustness_state *rs, gl_shader_stage stage,
3032                               struct radv_shader_stage_key *key)
3033 {
3034    if (rs->storage_buffers == VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2)
3035       key->storage_robustness2 = 1;
3036    if (rs->uniform_buffers == VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2)
3037       key->uniform_robustness2 = 1;
3038    if (stage == MESA_SHADER_VERTEX &&
3039        (rs->vertex_inputs == VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS ||
3040         rs->vertex_inputs == VK_PIPELINE_ROBUSTNESS_BUFFER_BEHAVIOR_ROBUST_BUFFER_ACCESS_2))
3041       key->vertex_robustness1 = 1u;
3042 }
3043 
3044 static struct radv_shader_binary *
shader_compile(struct radv_device * device,struct nir_shader * const * shaders,int shader_count,gl_shader_stage stage,const struct radv_shader_info * info,const struct radv_shader_args * args,const struct radv_shader_stage_key * stage_key,struct radv_nir_compiler_options * options)3045 shader_compile(struct radv_device *device, struct nir_shader *const *shaders, int shader_count, gl_shader_stage stage,
3046                const struct radv_shader_info *info, const struct radv_shader_args *args,
3047                const struct radv_shader_stage_key *stage_key, struct radv_nir_compiler_options *options)
3048 {
3049    struct radv_shader_debug_data debug_data = {
3050       .device = device,
3051       .object = NULL,
3052    };
3053    options->debug.func = radv_compiler_debug;
3054    options->debug.private_data = &debug_data;
3055 
3056    struct radv_shader_binary *binary = NULL;
3057 
3058 #if AMD_LLVM_AVAILABLE
3059    const struct radv_physical_device *pdev = radv_device_physical(device);
3060 
3061    if (radv_use_llvm_for_stage(pdev, stage) || options->dump_shader || options->record_ir)
3062       ac_init_llvm_once();
3063 
3064    if (radv_use_llvm_for_stage(pdev, stage)) {
3065       llvm_compile_shader(options, info, shader_count, shaders, &binary, args);
3066 #else
3067    if (false) {
3068 #endif
3069    } else {
3070       struct aco_shader_info ac_info;
3071       struct aco_compiler_options ac_opts;
3072       radv_aco_convert_opts(&ac_opts, options, args, stage_key);
3073       radv_aco_convert_shader_info(&ac_info, info, args, &device->cache_key, options->info->gfx_level);
3074       aco_compile_shader(&ac_opts, &ac_info, shader_count, shaders, &args->ac, &radv_aco_build_shader_binary,
3075                          (void **)&binary);
3076    }
3077 
3078    binary->info = *info;
3079 
3080    if (!radv_postprocess_binary_config(device, binary, args)) {
3081       free(binary);
3082       return NULL;
3083    }
3084 
3085    return binary;
3086 }
3087 
3088 struct radv_shader_binary *
3089 radv_shader_nir_to_asm(struct radv_device *device, struct radv_shader_stage *pl_stage,
3090                        struct nir_shader *const *shaders, int shader_count,
3091                        const struct radv_graphics_state_key *gfx_state, bool keep_shader_info, bool keep_statistic_info)
3092 {
3093    gl_shader_stage stage = shaders[shader_count - 1]->info.stage;
3094    struct radv_shader_info *info = &pl_stage->info;
3095 
3096    bool dump_shader = false;
3097    for (unsigned i = 0; i < shader_count; ++i)
3098       dump_shader |= radv_can_dump_shader(device, shaders[i]);
3099 
3100    struct radv_nir_compiler_options options = {0};
3101    radv_fill_nir_compiler_options(&options, device, gfx_state, radv_should_use_wgp_mode(device, stage, info),
3102                                   dump_shader, keep_shader_info, keep_statistic_info);
3103 
3104    struct radv_shader_binary *binary =
3105       shader_compile(device, shaders, shader_count, stage, info, &pl_stage->args, &pl_stage->key, &options);
3106 
3107    return binary;
3108 }
3109 
3110 void
3111 radv_shader_dump_debug_info(struct radv_device *device, bool dump_shader, struct radv_shader_binary *binary,
3112                             struct radv_shader *shader, struct nir_shader *const *shaders, int shader_count,
3113                             struct radv_shader_info *info)
3114 {
3115    if (dump_shader) {
3116       const struct radv_physical_device *pdev = radv_device_physical(device);
3117       const struct radv_instance *instance = radv_physical_device_instance(pdev);
3118 
3119       if (instance->debug_flags & RADV_DEBUG_DUMP_ASM) {
3120          fprintf(stderr, "%s", radv_get_shader_name(info, shaders[0]->info.stage));
3121          for (int i = 1; i < shader_count; ++i)
3122             fprintf(stderr, " + %s", radv_get_shader_name(info, shaders[i]->info.stage));
3123 
3124          fprintf(stderr, "\ndisasm:\n%s\n", shader->disasm_string);
3125       }
3126    }
3127 }
3128 
3129 struct radv_shader *
3130 radv_create_trap_handler_shader(struct radv_device *device)
3131 {
3132    const struct radv_physical_device *pdev = radv_device_physical(device);
3133    const struct radv_instance *instance = radv_physical_device_instance(pdev);
3134    gl_shader_stage stage = MESA_SHADER_COMPUTE;
3135    struct radv_shader_stage_key stage_key = {0};
3136    struct radv_shader_info info = {0};
3137    struct radv_nir_compiler_options options = {0};
3138    const bool dump_shader = !!(instance->debug_flags & RADV_DEBUG_DUMP_TRAP_HANDLER);
3139 
3140    radv_fill_nir_compiler_options(&options, device, NULL, radv_should_use_wgp_mode(device, stage, &info), dump_shader,
3141                                   false, false);
3142 
3143    nir_builder b = radv_meta_init_shader(device, stage, "meta_trap_handler");
3144 
3145    info.wave_size = 64;
3146    info.workgroup_size = 64;
3147    info.stage = MESA_SHADER_COMPUTE;
3148    info.type = RADV_SHADER_TYPE_TRAP_HANDLER;
3149 
3150    struct radv_shader_args args;
3151    radv_declare_shader_args(device, NULL, &info, stage, MESA_SHADER_NONE, &args);
3152 
3153 #if AMD_LLVM_AVAILABLE
3154    if (options.dump_shader || options.record_ir)
3155       ac_init_llvm_once();
3156 #endif
3157 
3158    struct radv_shader_binary *binary = NULL;
3159    struct aco_compiler_options ac_opts;
3160    struct aco_shader_info ac_info;
3161 
3162    radv_aco_convert_shader_info(&ac_info, &info, &args, &device->cache_key, options.info->gfx_level);
3163    radv_aco_convert_opts(&ac_opts, &options, &args, &stage_key);
3164 
3165    aco_compile_trap_handler(&ac_opts, &ac_info, &args.ac, &radv_aco_build_shader_binary, (void **)&binary);
3166    binary->info = info;
3167 
3168    radv_postprocess_binary_config(device, binary, &args);
3169 
3170    struct radv_shader *shader;
3171    radv_shader_create_uncached(device, binary, false, NULL, &shader);
3172 
3173    if (options.dump_shader) {
3174       fprintf(stderr, "Trap handler");
3175       fprintf(stderr, "\ndisasm:\n%s\n", shader->disasm_string);
3176    }
3177 
3178    free(shader->disasm_string);
3179    ralloc_free(b.shader);
3180    free(binary);
3181 
3182    return shader;
3183 }
3184 
3185 static void
3186 radv_aco_build_shader_part(void **bin, uint32_t num_sgprs, uint32_t num_vgprs, const uint32_t *code, uint32_t code_size,
3187                            const char *disasm_str, uint32_t disasm_size)
3188 {
3189    struct radv_shader_part_binary **binary = (struct radv_shader_part_binary **)bin;
3190    size_t size = code_size * sizeof(uint32_t) + sizeof(struct radv_shader_part_binary);
3191 
3192    size += disasm_size;
3193    struct radv_shader_part_binary *part_binary = (struct radv_shader_part_binary *)calloc(size, 1);
3194 
3195    part_binary->num_sgprs = num_sgprs;
3196    part_binary->num_vgprs = num_vgprs;
3197    part_binary->total_size = size;
3198    part_binary->code_size = code_size * sizeof(uint32_t);
3199    memcpy(part_binary->data, code, part_binary->code_size);
3200    if (disasm_size) {
3201       memcpy((char *)part_binary->data + part_binary->code_size, disasm_str, disasm_size);
3202       part_binary->disasm_size = disasm_size;
3203    }
3204 
3205    *binary = part_binary;
3206 }
3207 
3208 struct radv_shader *
3209 radv_create_rt_prolog(struct radv_device *device)
3210 {
3211    const struct radv_physical_device *pdev = radv_device_physical(device);
3212    const struct radv_instance *instance = radv_physical_device_instance(pdev);
3213    struct radv_shader *prolog;
3214    struct radv_shader_args in_args = {0};
3215    struct radv_shader_args out_args = {0};
3216    struct radv_nir_compiler_options options = {0};
3217    radv_fill_nir_compiler_options(&options, device, NULL, false, instance->debug_flags & RADV_DEBUG_DUMP_PROLOGS,
3218                                   radv_device_fault_detection_enabled(device), false);
3219    struct radv_shader_info info = {0};
3220    info.stage = MESA_SHADER_COMPUTE;
3221    info.loads_push_constants = true;
3222    info.desc_set_used_mask = -1; /* just to force indirection */
3223    info.wave_size = pdev->rt_wave_size;
3224    info.workgroup_size = info.wave_size;
3225    info.user_data_0 = R_00B900_COMPUTE_USER_DATA_0;
3226    info.type = RADV_SHADER_TYPE_RT_PROLOG;
3227    info.cs.block_size[0] = 8;
3228    info.cs.block_size[1] = pdev->rt_wave_size == 64 ? 8 : 4;
3229    info.cs.block_size[2] = 1;
3230    info.cs.uses_thread_id[0] = true;
3231    info.cs.uses_thread_id[1] = true;
3232    for (unsigned i = 0; i < 3; i++)
3233       info.cs.uses_block_id[i] = true;
3234 
3235    radv_declare_shader_args(device, NULL, &info, MESA_SHADER_COMPUTE, MESA_SHADER_NONE, &in_args);
3236    radv_declare_rt_shader_args(options.info->gfx_level, &out_args);
3237    info.user_sgprs_locs = in_args.user_sgprs_locs;
3238 
3239 #if AMD_LLVM_AVAILABLE
3240    if (options.dump_shader || options.record_ir)
3241       ac_init_llvm_once();
3242 #endif
3243 
3244    struct radv_shader_binary *binary = NULL;
3245    struct radv_shader_stage_key stage_key = {0};
3246    struct aco_shader_info ac_info;
3247    struct aco_compiler_options ac_opts;
3248    radv_aco_convert_shader_info(&ac_info, &info, &in_args, &device->cache_key, options.info->gfx_level);
3249    radv_aco_convert_opts(&ac_opts, &options, &in_args, &stage_key);
3250    aco_compile_rt_prolog(&ac_opts, &ac_info, &in_args.ac, &out_args.ac, &radv_aco_build_shader_binary,
3251                          (void **)&binary);
3252    binary->info = info;
3253 
3254    radv_postprocess_binary_config(device, binary, &in_args);
3255    radv_shader_create_uncached(device, binary, false, NULL, &prolog);
3256    if (!prolog)
3257       goto done;
3258 
3259    if (options.dump_shader) {
3260       fprintf(stderr, "Raytracing prolog");
3261       fprintf(stderr, "\ndisasm:\n%s\n", prolog->disasm_string);
3262    }
3263 
3264 done:
3265    free(binary);
3266    return prolog;
3267 }
3268 
3269 struct radv_shader_part *
3270 radv_create_vs_prolog(struct radv_device *device, const struct radv_vs_prolog_key *key)
3271 {
3272    const struct radv_physical_device *pdev = radv_device_physical(device);
3273    const struct radv_instance *instance = radv_physical_device_instance(pdev);
3274    struct radv_shader_part *prolog;
3275    struct radv_shader_args args = {0};
3276    struct radv_nir_compiler_options options = {0};
3277    radv_fill_nir_compiler_options(&options, device, NULL, false, instance->debug_flags & RADV_DEBUG_DUMP_PROLOGS,
3278                                   radv_device_fault_detection_enabled(device), false);
3279 
3280    struct radv_shader_info info = {0};
3281    info.stage = MESA_SHADER_VERTEX;
3282    info.wave_size = key->wave32 ? 32 : 64;
3283    info.vs.needs_instance_id = true;
3284    info.vs.needs_base_instance = true;
3285    info.vs.needs_draw_id = true;
3286    info.vs.use_per_attribute_vb_descs = true;
3287    info.vs.vb_desc_usage_mask = BITFIELD_MASK(key->num_attributes);
3288    info.vs.has_prolog = true;
3289    info.vs.as_ls = key->as_ls;
3290    info.is_ngg = key->is_ngg;
3291 
3292    struct radv_graphics_state_key gfx_state = {0};
3293 
3294    radv_declare_shader_args(device, &gfx_state, &info, key->next_stage,
3295                             key->next_stage != MESA_SHADER_VERTEX ? MESA_SHADER_VERTEX : MESA_SHADER_NONE, &args);
3296 
3297    info.user_sgprs_locs = args.user_sgprs_locs;
3298    info.inline_push_constant_mask = args.ac.inline_push_const_mask;
3299 
3300 #if AMD_LLVM_AVAILABLE
3301    if (options.dump_shader || options.record_ir)
3302       ac_init_llvm_once();
3303 #endif
3304 
3305    struct radv_shader_part_binary *binary = NULL;
3306    struct radv_shader_stage_key stage_key = {0};
3307    struct aco_shader_info ac_info;
3308    struct aco_vs_prolog_info ac_prolog_info;
3309    struct aco_compiler_options ac_opts;
3310    radv_aco_convert_shader_info(&ac_info, &info, &args, &device->cache_key, options.info->gfx_level);
3311    radv_aco_convert_opts(&ac_opts, &options, &args, &stage_key);
3312    radv_aco_convert_vs_prolog_key(&ac_prolog_info, key, &args);
3313    aco_compile_vs_prolog(&ac_opts, &ac_info, &ac_prolog_info, &args.ac, &radv_aco_build_shader_part, (void **)&binary);
3314 
3315    prolog = radv_shader_part_create(device, binary, info.wave_size);
3316    if (!prolog)
3317       goto fail;
3318 
3319    prolog->key.vs = *key;
3320    prolog->nontrivial_divisors = key->nontrivial_divisors;
3321 
3322    if (options.dump_shader) {
3323       fprintf(stderr, "Vertex prolog");
3324       fprintf(stderr, "\ndisasm:\n%s\n", prolog->disasm_string);
3325    }
3326 
3327    free(binary);
3328 
3329    return prolog;
3330 
3331 fail:
3332    free(binary);
3333    return NULL;
3334 }
3335 
3336 struct radv_shader_part *
3337 radv_create_ps_epilog(struct radv_device *device, const struct radv_ps_epilog_key *key,
3338                       struct radv_shader_part_binary **binary_out)
3339 {
3340    const struct radv_physical_device *pdev = radv_device_physical(device);
3341    const struct radv_instance *instance = radv_physical_device_instance(pdev);
3342    struct radv_shader_part *epilog;
3343    struct radv_shader_args args = {0};
3344    struct radv_nir_compiler_options options = {0};
3345    radv_fill_nir_compiler_options(&options, device, NULL, false, instance->debug_flags & RADV_DEBUG_DUMP_EPILOGS,
3346                                   radv_device_fault_detection_enabled(device), false);
3347 
3348    struct radv_shader_info info = {0};
3349    info.stage = MESA_SHADER_FRAGMENT;
3350    info.wave_size = pdev->ps_wave_size;
3351    info.workgroup_size = 64;
3352 
3353    radv_declare_ps_epilog_args(device, key, &args);
3354 
3355 #if AMD_LLVM_AVAILABLE
3356    if (options.dump_shader || options.record_ir)
3357       ac_init_llvm_once();
3358 #endif
3359 
3360    struct radv_shader_part_binary *binary = NULL;
3361    struct radv_shader_stage_key stage_key = {0};
3362    struct aco_shader_info ac_info;
3363    struct aco_ps_epilog_info ac_epilog_info = {0};
3364    struct aco_compiler_options ac_opts;
3365    radv_aco_convert_shader_info(&ac_info, &info, &args, &device->cache_key, options.info->gfx_level);
3366    radv_aco_convert_opts(&ac_opts, &options, &args, &stage_key);
3367    radv_aco_convert_ps_epilog_key(&ac_epilog_info, key, &args);
3368    aco_compile_ps_epilog(&ac_opts, &ac_info, &ac_epilog_info, &args.ac, &radv_aco_build_shader_part, (void **)&binary);
3369 
3370    binary->info.spi_shader_col_format = key->spi_shader_col_format;
3371    binary->info.cb_shader_mask = ac_get_cb_shader_mask(key->spi_shader_col_format);
3372    binary->info.spi_shader_z_format = key->spi_shader_z_format;
3373 
3374    epilog = radv_shader_part_create(device, binary, info.wave_size);
3375    if (!epilog)
3376       goto fail;
3377 
3378    epilog->key.ps = *key;
3379 
3380    if (options.dump_shader) {
3381       fprintf(stderr, "Fragment epilog");
3382       fprintf(stderr, "\ndisasm:\n%s\n", epilog->disasm_string);
3383    }
3384 
3385    if (binary_out) {
3386       *binary_out = binary;
3387    } else {
3388       free(binary);
3389    }
3390 
3391    return epilog;
3392 
3393 fail:
3394    free(binary);
3395    return NULL;
3396 }
3397 
3398 void
3399 radv_shader_part_destroy(struct radv_device *device, struct radv_shader_part *shader_part)
3400 {
3401    assert(shader_part->ref_count == 0);
3402 
3403    if (device->shader_use_invisible_vram) {
3404       /* Wait for any pending upload to complete, or we'll be writing into freed shader memory. */
3405       radv_shader_wait_for_upload(device, shader_part->upload_seq);
3406    }
3407 
3408    if (shader_part->alloc)
3409       radv_free_shader_memory(device, shader_part->alloc);
3410    free(shader_part->disasm_string);
3411    free(shader_part);
3412 }
3413 
3414 uint64_t
3415 radv_shader_get_va(const struct radv_shader *shader)
3416 {
3417    return shader->va;
3418 }
3419 
3420 struct radv_shader *
3421 radv_find_shader(struct radv_device *device, uint64_t pc)
3422 {
3423    mtx_lock(&device->shader_arena_mutex);
3424    list_for_each_entry (struct radv_shader_arena, arena, &device->shader_arenas, list) {
3425 #ifdef __GNUC__
3426 #pragma GCC diagnostic push
3427 #pragma GCC diagnostic ignored "-Wshadow"
3428 #endif
3429       list_for_each_entry (union radv_shader_arena_block, block, &arena->entries, list) {
3430 #ifdef __GNUC__
3431 #pragma GCC diagnostic pop
3432 #endif
3433          uint64_t start = radv_buffer_get_va(block->arena->bo) + block->offset;
3434          start &= ((1ull << 48) - 1);
3435          if (!block->freelist.prev && pc >= start && pc < start + block->size) {
3436             mtx_unlock(&device->shader_arena_mutex);
3437             return (struct radv_shader *)block->freelist.next;
3438          }
3439       }
3440    }
3441 
3442    mtx_unlock(&device->shader_arena_mutex);
3443    return NULL;
3444 }
3445 
3446 const char *
3447 radv_get_shader_name(const struct radv_shader_info *info, gl_shader_stage stage)
3448 {
3449    switch (stage) {
3450    case MESA_SHADER_VERTEX:
3451       if (info->vs.as_ls)
3452          return "Vertex Shader as LS";
3453       else if (info->vs.as_es)
3454          return "Vertex Shader as ES";
3455       else if (info->is_ngg)
3456          return "Vertex Shader as ESGS";
3457       else
3458          return "Vertex Shader as VS";
3459    case MESA_SHADER_TESS_CTRL:
3460       return "Tessellation Control Shader";
3461    case MESA_SHADER_TESS_EVAL:
3462       if (info->tes.as_es)
3463          return "Tessellation Evaluation Shader as ES";
3464       else if (info->is_ngg)
3465          return "Tessellation Evaluation Shader as ESGS";
3466       else
3467          return "Tessellation Evaluation Shader as VS";
3468    case MESA_SHADER_GEOMETRY:
3469       return "Geometry Shader";
3470    case MESA_SHADER_FRAGMENT:
3471       return "Pixel Shader";
3472    case MESA_SHADER_COMPUTE:
3473       return info->type == RADV_SHADER_TYPE_TRAP_HANDLER ? "Trap Handler Shader" : "Compute Shader";
3474    case MESA_SHADER_MESH:
3475       return "Mesh Shader as NGG";
3476    case MESA_SHADER_TASK:
3477       return "Task Shader as CS";
3478    case MESA_SHADER_RAYGEN:
3479       return "Ray Generation Shader as CS Function";
3480    case MESA_SHADER_CLOSEST_HIT:
3481       return "Closest Hit Shader as CS Function";
3482    case MESA_SHADER_INTERSECTION:
3483       return "Intersection Shader as CS Function";
3484    case MESA_SHADER_ANY_HIT:
3485       return "Any Hit Shader as CS Function";
3486    case MESA_SHADER_MISS:
3487       return "Miss Shader as CS Function";
3488    case MESA_SHADER_CALLABLE:
3489       return "Callable Shader as CS Function";
3490    default:
3491       return "Unknown shader";
3492    };
3493 }
3494 
3495 unsigned
3496 radv_compute_spi_ps_input(const struct radv_physical_device *pdev, const struct radv_graphics_state_key *gfx_state,
3497                           const struct radv_shader_info *info)
3498 {
3499    unsigned spi_ps_input;
3500 
3501    spi_ps_input = S_0286CC_PERSP_CENTER_ENA(info->ps.reads_persp_center) |
3502                   S_0286CC_PERSP_CENTROID_ENA(info->ps.reads_persp_centroid) |
3503                   S_0286CC_PERSP_SAMPLE_ENA(info->ps.reads_persp_sample) |
3504                   S_0286CC_LINEAR_CENTER_ENA(info->ps.reads_linear_center) |
3505                   S_0286CC_LINEAR_CENTROID_ENA(info->ps.reads_linear_centroid) |
3506                   S_0286CC_LINEAR_SAMPLE_ENA(info->ps.reads_linear_sample) |
3507                   S_0286CC_PERSP_PULL_MODEL_ENA(info->ps.reads_barycentric_model) |
3508                   S_0286CC_FRONT_FACE_ENA(info->ps.reads_front_face) |
3509                   S_0286CC_POS_FIXED_PT_ENA(info->ps.reads_pixel_coord);
3510 
3511    if (info->ps.reads_frag_coord_mask || info->ps.reads_sample_pos_mask) {
3512       uint8_t mask = info->ps.reads_frag_coord_mask | info->ps.reads_sample_pos_mask;
3513 
3514       for (unsigned i = 0; i < 4; i++) {
3515          if (mask & (1 << i))
3516             spi_ps_input |= S_0286CC_POS_X_FLOAT_ENA(1) << i;
3517       }
3518 
3519       if (gfx_state->adjust_frag_coord_z && info->ps.reads_frag_coord_mask & (1 << 2)) {
3520          spi_ps_input |= S_0286CC_ANCILLARY_ENA(1);
3521       }
3522    }
3523 
3524    if (info->ps.reads_sample_id || info->ps.reads_frag_shading_rate || info->ps.reads_sample_mask_in ||
3525        info->ps.reads_layer) {
3526       spi_ps_input |= S_0286CC_ANCILLARY_ENA(1);
3527    }
3528 
3529    if (info->ps.reads_sample_mask_in || info->ps.reads_fully_covered) {
3530       spi_ps_input |= S_0286CC_SAMPLE_COVERAGE_ENA(1) |
3531                       S_02865C_COVERAGE_TO_SHADER_SELECT(pdev->info.gfx_level >= GFX12 && info->ps.reads_fully_covered);
3532    }
3533 
3534    if (G_0286CC_POS_W_FLOAT_ENA(spi_ps_input)) {
3535       /* If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be enabled too */
3536       spi_ps_input |= S_0286CC_PERSP_CENTER_ENA(1);
3537    }
3538 
3539    if (!(spi_ps_input & 0x7F)) {
3540       /* At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled */
3541       spi_ps_input |= S_0286CC_PERSP_CENTER_ENA(1);
3542    }
3543 
3544    return spi_ps_input;
3545 }
3546 
3547 const struct radv_userdata_info *
3548 radv_get_user_sgpr_info(const struct radv_shader *shader, int idx)
3549 {
3550    return &shader->info.user_sgprs_locs.shader_data[idx];
3551 }
3552 
3553 uint32_t
3554 radv_get_user_sgpr_loc(const struct radv_shader *shader, int idx)
3555 {
3556    const struct radv_userdata_info *loc = radv_get_user_sgpr_info(shader, idx);
3557 
3558    if (loc->sgpr_idx == -1)
3559       return 0;
3560 
3561    return shader->info.user_data_0 + loc->sgpr_idx * 4;
3562 }
3563 
3564 uint32_t
3565 radv_get_user_sgpr(const struct radv_shader *shader, int idx)
3566 {
3567    const uint32_t offset = radv_get_user_sgpr_loc(shader, idx);
3568 
3569    return offset ? ((offset - SI_SH_REG_OFFSET) >> 2) : 0;
3570 }
3571 
3572 void
3573 radv_get_tess_wg_info(const struct radv_physical_device *pdev, const struct shader_info *tcs_info,
3574                       unsigned tcs_num_input_vertices, unsigned tcs_num_lds_inputs, unsigned tcs_num_vram_outputs,
3575                       unsigned tcs_num_vram_patch_outputs, bool all_invocations_define_tess_levels,
3576                       unsigned *num_patches_per_wg, unsigned *hw_lds_size)
3577 {
3578    const uint32_t lds_input_vertex_size = get_tcs_input_vertex_stride(tcs_num_lds_inputs);
3579 
3580    ac_nir_compute_tess_wg_info(&pdev->info, tcs_info, pdev->ge_wave_size, false, all_invocations_define_tess_levels,
3581                                tcs_num_input_vertices, lds_input_vertex_size, tcs_num_vram_outputs,
3582                                tcs_num_vram_patch_outputs, num_patches_per_wg, hw_lds_size);
3583 }
3584 
3585 VkResult
3586 radv_dump_shader_stats(struct radv_device *device, struct radv_pipeline *pipeline, struct radv_shader *shader,
3587                        gl_shader_stage stage, FILE *output)
3588 {
3589    VkPipelineExecutablePropertiesKHR *props = NULL;
3590    uint32_t prop_count = 0;
3591    VkResult result;
3592 
3593    VkPipelineInfoKHR pipeline_info = {0};
3594    pipeline_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INFO_KHR;
3595    pipeline_info.pipeline = radv_pipeline_to_handle(pipeline);
3596 
3597    result = radv_GetPipelineExecutablePropertiesKHR(radv_device_to_handle(device), &pipeline_info, &prop_count, NULL);
3598    if (result != VK_SUCCESS)
3599       return result;
3600 
3601    props = calloc(prop_count, sizeof(*props));
3602    if (!props)
3603       return VK_ERROR_OUT_OF_HOST_MEMORY;
3604 
3605    result = radv_GetPipelineExecutablePropertiesKHR(radv_device_to_handle(device), &pipeline_info, &prop_count, props);
3606    if (result != VK_SUCCESS)
3607       goto fail;
3608 
3609    for (unsigned exec_idx = 0; exec_idx < prop_count; exec_idx++) {
3610       if (!(props[exec_idx].stages & mesa_to_vk_shader_stage(stage)))
3611          continue;
3612 
3613       VkPipelineExecutableStatisticKHR *stats = NULL;
3614       uint32_t stat_count = 0;
3615 
3616       VkPipelineExecutableInfoKHR exec_info = {0};
3617       exec_info.pipeline = radv_pipeline_to_handle(pipeline);
3618       exec_info.executableIndex = exec_idx;
3619 
3620       result = radv_GetPipelineExecutableStatisticsKHR(radv_device_to_handle(device), &exec_info, &stat_count, NULL);
3621       if (result != VK_SUCCESS)
3622          goto fail;
3623 
3624       stats = calloc(stat_count, sizeof(*stats));
3625       if (!stats) {
3626          result = VK_ERROR_OUT_OF_HOST_MEMORY;
3627          goto fail;
3628       }
3629 
3630       result = radv_GetPipelineExecutableStatisticsKHR(radv_device_to_handle(device), &exec_info, &stat_count, stats);
3631       if (result != VK_SUCCESS) {
3632          free(stats);
3633          goto fail;
3634       }
3635 
3636       fprintf(output, "\n%s:\n", radv_get_shader_name(&shader->info, stage));
3637       fprintf(output, "*** SHADER STATS ***\n");
3638 
3639       for (unsigned i = 0; i < stat_count; i++) {
3640          fprintf(output, "%s: ", stats[i].name);
3641          switch (stats[i].format) {
3642          case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_BOOL32_KHR:
3643             fprintf(output, "%s", stats[i].value.b32 == VK_TRUE ? "true" : "false");
3644             break;
3645          case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_INT64_KHR:
3646             fprintf(output, "%" PRIi64, stats[i].value.i64);
3647             break;
3648          case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR:
3649             fprintf(output, "%" PRIu64, stats[i].value.u64);
3650             break;
3651          case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_FLOAT64_KHR:
3652             fprintf(output, "%f", stats[i].value.f64);
3653             break;
3654          default:
3655             unreachable("Invalid pipeline statistic format");
3656          }
3657          fprintf(output, "\n");
3658       }
3659 
3660       fprintf(output, "********************\n\n\n");
3661 
3662       free(stats);
3663    }
3664 
3665 fail:
3666    free(props);
3667    return result;
3668 }
3669