radv: enable shaderResourceMinLod
[mesa.git] / src / amd / vulkan / radv_shader.c
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 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice (including the next
16 * paragraph) shall be included in all copies or substantial portions of the
17 * Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
25 * IN THE SOFTWARE.
26 */
27
28 #include "util/mesa-sha1.h"
29 #include "util/u_atomic.h"
30 #include "radv_debug.h"
31 #include "radv_private.h"
32 #include "radv_shader.h"
33 #include "radv_shader_helper.h"
34 #include "radv_shader_args.h"
35 #include "nir/nir.h"
36 #include "nir/nir_builder.h"
37 #include "spirv/nir_spirv.h"
38
39 #include "sid.h"
40 #include "ac_binary.h"
41 #include "ac_llvm_util.h"
42 #include "ac_nir_to_llvm.h"
43 #include "ac_rtld.h"
44 #include "vk_format.h"
45 #include "util/debug.h"
46 #include "ac_exp_param.h"
47
48 #include "aco_interface.h"
49
50 #include "util/string_buffer.h"
51
52 static const struct nir_shader_compiler_options nir_options_llvm = {
53 .vertex_id_zero_based = true,
54 .lower_scmp = true,
55 .lower_flrp16 = true,
56 .lower_flrp32 = true,
57 .lower_flrp64 = true,
58 .lower_device_index_to_zero = true,
59 .lower_fsat = true,
60 .lower_fdiv = true,
61 .lower_fmod = true,
62 .lower_bitfield_insert_to_bitfield_select = true,
63 .lower_bitfield_extract = true,
64 .lower_sub = true,
65 .lower_pack_snorm_2x16 = true,
66 .lower_pack_snorm_4x8 = true,
67 .lower_pack_unorm_2x16 = true,
68 .lower_pack_unorm_4x8 = true,
69 .lower_unpack_snorm_2x16 = true,
70 .lower_unpack_snorm_4x8 = true,
71 .lower_unpack_unorm_2x16 = true,
72 .lower_unpack_unorm_4x8 = true,
73 .lower_extract_byte = true,
74 .lower_extract_word = true,
75 .lower_ffma = true,
76 .lower_fpow = true,
77 .lower_mul_2x32_64 = true,
78 .lower_rotate = true,
79 .max_unroll_iterations = 32,
80 .use_interpolated_input_intrinsics = true,
81 /* nir_lower_int64() isn't actually called for the LLVM backend, but
82 * this helps the loop unrolling heuristics. */
83 .lower_int64_options = nir_lower_imul64 |
84 nir_lower_imul_high64 |
85 nir_lower_imul_2x32_64 |
86 nir_lower_divmod64 |
87 nir_lower_minmax64 |
88 nir_lower_iabs64,
89 };
90
91 static const struct nir_shader_compiler_options nir_options_aco = {
92 .vertex_id_zero_based = true,
93 .lower_scmp = true,
94 .lower_flrp16 = true,
95 .lower_flrp32 = true,
96 .lower_flrp64 = true,
97 .lower_device_index_to_zero = true,
98 .lower_fdiv = true,
99 .lower_fmod = true,
100 .lower_bitfield_insert_to_bitfield_select = true,
101 .lower_bitfield_extract = true,
102 .lower_pack_snorm_2x16 = true,
103 .lower_pack_snorm_4x8 = true,
104 .lower_pack_unorm_2x16 = true,
105 .lower_pack_unorm_4x8 = true,
106 .lower_unpack_snorm_2x16 = true,
107 .lower_unpack_snorm_4x8 = true,
108 .lower_unpack_unorm_2x16 = true,
109 .lower_unpack_unorm_4x8 = true,
110 .lower_unpack_half_2x16 = true,
111 .lower_extract_byte = true,
112 .lower_extract_word = true,
113 .lower_ffma = true,
114 .lower_fpow = true,
115 .lower_mul_2x32_64 = true,
116 .lower_rotate = true,
117 .max_unroll_iterations = 32,
118 .use_interpolated_input_intrinsics = true,
119 .lower_int64_options = nir_lower_imul64 |
120 nir_lower_imul_high64 |
121 nir_lower_imul_2x32_64 |
122 nir_lower_divmod64 |
123 nir_lower_logic64 |
124 nir_lower_minmax64 |
125 nir_lower_iabs64,
126 };
127
128 bool
129 radv_can_dump_shader(struct radv_device *device,
130 struct radv_shader_module *module,
131 bool is_gs_copy_shader)
132 {
133 if (!(device->instance->debug_flags & RADV_DEBUG_DUMP_SHADERS))
134 return false;
135 if (module)
136 return !module->nir ||
137 (device->instance->debug_flags & RADV_DEBUG_DUMP_META_SHADERS);
138
139 return is_gs_copy_shader;
140 }
141
142 bool
143 radv_can_dump_shader_stats(struct radv_device *device,
144 struct radv_shader_module *module)
145 {
146 /* Only dump non-meta shader stats. */
147 return device->instance->debug_flags & RADV_DEBUG_DUMP_SHADER_STATS &&
148 module && !module->nir;
149 }
150
151 VkResult radv_CreateShaderModule(
152 VkDevice _device,
153 const VkShaderModuleCreateInfo* pCreateInfo,
154 const VkAllocationCallbacks* pAllocator,
155 VkShaderModule* pShaderModule)
156 {
157 RADV_FROM_HANDLE(radv_device, device, _device);
158 struct radv_shader_module *module;
159
160 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
161 assert(pCreateInfo->flags == 0);
162
163 module = vk_alloc2(&device->vk.alloc, pAllocator,
164 sizeof(*module) + pCreateInfo->codeSize, 8,
165 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
166 if (module == NULL)
167 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
168
169 vk_object_base_init(&device->vk, &module->base,
170 VK_OBJECT_TYPE_SHADER_MODULE);
171
172 module->nir = NULL;
173 module->size = pCreateInfo->codeSize;
174 memcpy(module->data, pCreateInfo->pCode, module->size);
175
176 _mesa_sha1_compute(module->data, module->size, module->sha1);
177
178 *pShaderModule = radv_shader_module_to_handle(module);
179
180 return VK_SUCCESS;
181 }
182
183 void radv_DestroyShaderModule(
184 VkDevice _device,
185 VkShaderModule _module,
186 const VkAllocationCallbacks* pAllocator)
187 {
188 RADV_FROM_HANDLE(radv_device, device, _device);
189 RADV_FROM_HANDLE(radv_shader_module, module, _module);
190
191 if (!module)
192 return;
193
194 vk_object_base_finish(&module->base);
195 vk_free2(&device->vk.alloc, pAllocator, module);
196 }
197
198 void
199 radv_optimize_nir(struct nir_shader *shader, bool optimize_conservatively,
200 bool allow_copies)
201 {
202 bool progress;
203 unsigned lower_flrp =
204 (shader->options->lower_flrp16 ? 16 : 0) |
205 (shader->options->lower_flrp32 ? 32 : 0) |
206 (shader->options->lower_flrp64 ? 64 : 0);
207
208 do {
209 progress = false;
210
211 NIR_PASS(progress, shader, nir_split_array_vars, nir_var_function_temp);
212 NIR_PASS(progress, shader, nir_shrink_vec_array_vars, nir_var_function_temp);
213
214 NIR_PASS_V(shader, nir_lower_vars_to_ssa);
215 NIR_PASS_V(shader, nir_lower_pack);
216
217 if (allow_copies) {
218 /* Only run this pass in the first call to
219 * radv_optimize_nir. Later calls assume that we've
220 * lowered away any copy_deref instructions and we
221 * don't want to introduce any more.
222 */
223 NIR_PASS(progress, shader, nir_opt_find_array_copies);
224 }
225
226 NIR_PASS(progress, shader, nir_opt_copy_prop_vars);
227 NIR_PASS(progress, shader, nir_opt_dead_write_vars);
228 NIR_PASS(progress, shader, nir_remove_dead_variables,
229 nir_var_function_temp | nir_var_shader_in | nir_var_shader_out);
230
231 NIR_PASS_V(shader, nir_lower_alu_to_scalar, NULL, NULL);
232 NIR_PASS_V(shader, nir_lower_phis_to_scalar);
233
234 NIR_PASS(progress, shader, nir_copy_prop);
235 NIR_PASS(progress, shader, nir_opt_remove_phis);
236 NIR_PASS(progress, shader, nir_opt_dce);
237 if (nir_opt_trivial_continues(shader)) {
238 progress = true;
239 NIR_PASS(progress, shader, nir_copy_prop);
240 NIR_PASS(progress, shader, nir_opt_remove_phis);
241 NIR_PASS(progress, shader, nir_opt_dce);
242 }
243 NIR_PASS(progress, shader, nir_opt_if, true);
244 NIR_PASS(progress, shader, nir_opt_dead_cf);
245 NIR_PASS(progress, shader, nir_opt_cse);
246 NIR_PASS(progress, shader, nir_opt_peephole_select, 8, true, true);
247 NIR_PASS(progress, shader, nir_opt_constant_folding);
248 NIR_PASS(progress, shader, nir_opt_algebraic);
249
250 if (lower_flrp != 0) {
251 bool lower_flrp_progress = false;
252 NIR_PASS(lower_flrp_progress,
253 shader,
254 nir_lower_flrp,
255 lower_flrp,
256 false /* always_precise */,
257 shader->options->lower_ffma);
258 if (lower_flrp_progress) {
259 NIR_PASS(progress, shader,
260 nir_opt_constant_folding);
261 progress = true;
262 }
263
264 /* Nothing should rematerialize any flrps, so we only
265 * need to do this lowering once.
266 */
267 lower_flrp = 0;
268 }
269
270 NIR_PASS(progress, shader, nir_opt_undef);
271 if (shader->options->max_unroll_iterations) {
272 NIR_PASS(progress, shader, nir_opt_loop_unroll, 0);
273 }
274 } while (progress && !optimize_conservatively);
275
276 NIR_PASS(progress, shader, nir_opt_conditional_discard);
277 NIR_PASS(progress, shader, nir_opt_shrink_load);
278 NIR_PASS(progress, shader, nir_opt_move, nir_move_load_ubo);
279 }
280
281 static void
282 shared_var_info(const struct glsl_type *type, unsigned *size, unsigned *align)
283 {
284 assert(glsl_type_is_vector_or_scalar(type));
285
286 uint32_t comp_size = glsl_type_is_boolean(type) ? 4 : glsl_get_bit_size(type) / 8;
287 unsigned length = glsl_get_vector_elements(type);
288 *size = comp_size * length,
289 *align = comp_size;
290 }
291
292 nir_shader *
293 radv_shader_compile_to_nir(struct radv_device *device,
294 struct radv_shader_module *module,
295 const char *entrypoint_name,
296 gl_shader_stage stage,
297 const VkSpecializationInfo *spec_info,
298 const VkPipelineCreateFlags flags,
299 const struct radv_pipeline_layout *layout,
300 unsigned subgroup_size, unsigned ballot_bit_size)
301 {
302 nir_shader *nir;
303 const nir_shader_compiler_options *nir_options =
304 device->physical_device->use_aco ? &nir_options_aco :
305 &nir_options_llvm;
306
307 if (module->nir) {
308 /* Some things such as our meta clear/blit code will give us a NIR
309 * shader directly. In that case, we just ignore the SPIR-V entirely
310 * and just use the NIR shader */
311 nir = module->nir;
312 nir->options = nir_options;
313 nir_validate_shader(nir, "in internal shader");
314
315 assert(exec_list_length(&nir->functions) == 1);
316 } else {
317 uint32_t *spirv = (uint32_t *) module->data;
318 assert(module->size % 4 == 0);
319
320 if (device->instance->debug_flags & RADV_DEBUG_DUMP_SPIRV)
321 radv_print_spirv(module->data, module->size, stderr);
322
323 uint32_t num_spec_entries = 0;
324 struct nir_spirv_specialization *spec_entries = NULL;
325 if (spec_info && spec_info->mapEntryCount > 0) {
326 num_spec_entries = spec_info->mapEntryCount;
327 spec_entries = calloc(num_spec_entries, sizeof(*spec_entries));
328 for (uint32_t i = 0; i < num_spec_entries; i++) {
329 VkSpecializationMapEntry entry = spec_info->pMapEntries[i];
330 const void *data = spec_info->pData + entry.offset;
331 assert(data + entry.size <= spec_info->pData + spec_info->dataSize);
332
333 spec_entries[i].id = spec_info->pMapEntries[i].constantID;
334 switch (entry.size) {
335 case 8:
336 spec_entries[i].value.u64 = *(const uint64_t *)data;
337 break;
338 case 4:
339 spec_entries[i].value.u32 = *(const uint32_t *)data;
340 break;
341 case 2:
342 spec_entries[i].value.u16 = *(const uint16_t *)data;
343 break;
344 case 1:
345 spec_entries[i].value.u8 = *(const uint8_t *)data;
346 break;
347 default:
348 assert(!"Invalid spec constant size");
349 break;
350 }
351 }
352 }
353 bool int8_int16_enable = !device->physical_device->use_aco ||
354 device->physical_device->rad_info.chip_class >= GFX8;
355 const struct spirv_to_nir_options spirv_options = {
356 .lower_ubo_ssbo_access_to_offsets = true,
357 .caps = {
358 .amd_fragment_mask = true,
359 .amd_gcn_shader = true,
360 .amd_image_read_write_lod = true,
361 .amd_shader_ballot = device->physical_device->use_shader_ballot,
362 .amd_shader_explicit_vertex_parameter = true,
363 .amd_trinary_minmax = true,
364 .demote_to_helper_invocation = device->physical_device->use_aco,
365 .derivative_group = true,
366 .descriptor_array_dynamic_indexing = true,
367 .descriptor_array_non_uniform_indexing = true,
368 .descriptor_indexing = true,
369 .device_group = true,
370 .draw_parameters = true,
371 .float_controls = true,
372 .float16 = device->physical_device->rad_info.has_double_rate_fp16 && !device->physical_device->use_aco,
373 .float64 = true,
374 .geometry_streams = true,
375 .image_ms_array = true,
376 .image_read_without_format = true,
377 .image_write_without_format = true,
378 .int8 = int8_int16_enable,
379 .int16 = int8_int16_enable,
380 .int64 = true,
381 .int64_atomics = true,
382 .min_lod = true,
383 .multiview = true,
384 .physical_storage_buffer_address = true,
385 .post_depth_coverage = true,
386 .runtime_descriptor_array = true,
387 .shader_clock = true,
388 .shader_viewport_index_layer = true,
389 .stencil_export = true,
390 .storage_8bit = int8_int16_enable,
391 .storage_16bit = int8_int16_enable,
392 .storage_image_ms = true,
393 .subgroup_arithmetic = true,
394 .subgroup_ballot = true,
395 .subgroup_basic = true,
396 .subgroup_quad = true,
397 .subgroup_shuffle = true,
398 .subgroup_vote = true,
399 .tessellation = true,
400 .transform_feedback = true,
401 .variable_pointers = true,
402 },
403 .ubo_addr_format = nir_address_format_32bit_index_offset,
404 .ssbo_addr_format = nir_address_format_32bit_index_offset,
405 .phys_ssbo_addr_format = nir_address_format_64bit_global,
406 .push_const_addr_format = nir_address_format_logical,
407 .shared_addr_format = nir_address_format_32bit_offset,
408 .frag_coord_is_sysval = true,
409 };
410 nir = spirv_to_nir(spirv, module->size / 4,
411 spec_entries, num_spec_entries,
412 stage, entrypoint_name,
413 &spirv_options, nir_options);
414 assert(nir->info.stage == stage);
415 nir_validate_shader(nir, "after spirv_to_nir");
416
417 free(spec_entries);
418
419 /* We have to lower away local constant initializers right before we
420 * inline functions. That way they get properly initialized at the top
421 * of the function and not at the top of its caller.
422 */
423 NIR_PASS_V(nir, nir_lower_variable_initializers, nir_var_function_temp);
424 NIR_PASS_V(nir, nir_lower_returns);
425 NIR_PASS_V(nir, nir_inline_functions);
426 NIR_PASS_V(nir, nir_opt_deref);
427
428 /* Pick off the single entrypoint that we want */
429 foreach_list_typed_safe(nir_function, func, node, &nir->functions) {
430 if (func->is_entrypoint)
431 func->name = ralloc_strdup(func, "main");
432 else
433 exec_node_remove(&func->node);
434 }
435 assert(exec_list_length(&nir->functions) == 1);
436
437 /* Make sure we lower constant initializers on output variables so that
438 * nir_remove_dead_variables below sees the corresponding stores
439 */
440 NIR_PASS_V(nir, nir_lower_variable_initializers, nir_var_shader_out);
441
442 /* Now that we've deleted all but the main function, we can go ahead and
443 * lower the rest of the constant initializers.
444 */
445 NIR_PASS_V(nir, nir_lower_variable_initializers, ~0);
446
447 /* Split member structs. We do this before lower_io_to_temporaries so that
448 * it doesn't lower system values to temporaries by accident.
449 */
450 NIR_PASS_V(nir, nir_split_var_copies);
451 NIR_PASS_V(nir, nir_split_per_member_structs);
452
453 if (nir->info.stage == MESA_SHADER_FRAGMENT &&
454 device->physical_device->use_aco)
455 NIR_PASS_V(nir, nir_lower_io_to_vector, nir_var_shader_out);
456 if (nir->info.stage == MESA_SHADER_FRAGMENT)
457 NIR_PASS_V(nir, nir_lower_input_attachments, true);
458
459 NIR_PASS_V(nir, nir_remove_dead_variables,
460 nir_var_shader_in | nir_var_shader_out | nir_var_system_value | nir_var_mem_shared);
461
462 NIR_PASS_V(nir, nir_propagate_invariant);
463
464 NIR_PASS_V(nir, nir_lower_system_values);
465 NIR_PASS_V(nir, nir_lower_clip_cull_distance_arrays);
466 NIR_PASS_V(nir, radv_nir_lower_ycbcr_textures, layout);
467 if (device->instance->debug_flags & RADV_DEBUG_DISCARD_TO_DEMOTE)
468 NIR_PASS_V(nir, nir_lower_discard_to_demote);
469 }
470
471 /* Vulkan uses the separate-shader linking model */
472 nir->info.separate_shader = true;
473
474 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
475
476 if (nir->info.stage == MESA_SHADER_GEOMETRY)
477 nir_lower_gs_intrinsics(nir, true);
478
479 static const nir_lower_tex_options tex_options = {
480 .lower_txp = ~0,
481 .lower_tg4_offsets = true,
482 };
483
484 nir_lower_tex(nir, &tex_options);
485
486 nir_lower_vars_to_ssa(nir);
487
488 if (nir->info.stage == MESA_SHADER_VERTEX ||
489 nir->info.stage == MESA_SHADER_GEOMETRY ||
490 nir->info.stage == MESA_SHADER_FRAGMENT) {
491 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
492 nir_shader_get_entrypoint(nir), true, true);
493 } else if (nir->info.stage == MESA_SHADER_TESS_EVAL) {
494 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
495 nir_shader_get_entrypoint(nir), true, false);
496 }
497
498 nir_split_var_copies(nir);
499
500 nir_lower_global_vars_to_local(nir);
501 nir_remove_dead_variables(nir, nir_var_function_temp);
502 bool gfx7minus = device->physical_device->rad_info.chip_class <= GFX7;
503 nir_lower_subgroups(nir, &(struct nir_lower_subgroups_options) {
504 .subgroup_size = subgroup_size,
505 .ballot_bit_size = ballot_bit_size,
506 .lower_to_scalar = 1,
507 .lower_subgroup_masks = 1,
508 .lower_shuffle = 1,
509 .lower_shuffle_to_32bit = 1,
510 .lower_vote_eq_to_ballot = 1,
511 .lower_quad_broadcast_dynamic = 1,
512 .lower_quad_broadcast_dynamic_to_const = gfx7minus,
513 });
514
515 nir_lower_load_const_to_scalar(nir);
516
517 if (!(flags & VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT))
518 radv_optimize_nir(nir, false, true);
519
520 /* We call nir_lower_var_copies() after the first radv_optimize_nir()
521 * to remove any copies introduced by nir_opt_find_array_copies().
522 */
523 nir_lower_var_copies(nir);
524
525 /* Lower deref operations for compute shared memory. */
526 if (nir->info.stage == MESA_SHADER_COMPUTE) {
527 NIR_PASS_V(nir, nir_lower_vars_to_explicit_types,
528 nir_var_mem_shared, shared_var_info);
529 NIR_PASS_V(nir, nir_lower_explicit_io,
530 nir_var_mem_shared, nir_address_format_32bit_offset);
531 }
532
533 /* Lower large variables that are always constant with load_constant
534 * intrinsics, which get turned into PC-relative loads from a data
535 * section next to the shader.
536 */
537 NIR_PASS_V(nir, nir_opt_large_constants,
538 glsl_get_natural_size_align_bytes, 16);
539
540 /* Indirect lowering must be called after the radv_optimize_nir() loop
541 * has been called at least once. Otherwise indirect lowering can
542 * bloat the instruction count of the loop and cause it to be
543 * considered too large for unrolling.
544 */
545 ac_lower_indirect_derefs(nir, device->physical_device->rad_info.chip_class);
546 radv_optimize_nir(nir, flags & VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT, false);
547
548 return nir;
549 }
550
551 static int
552 type_size_vec4(const struct glsl_type *type, bool bindless)
553 {
554 return glsl_count_attribute_slots(type, false);
555 }
556
557 static nir_variable *
558 find_layer_in_var(nir_shader *nir)
559 {
560 nir_foreach_variable(var, &nir->inputs) {
561 if (var->data.location == VARYING_SLOT_LAYER) {
562 return var;
563 }
564 }
565
566 nir_variable *var =
567 nir_variable_create(nir, nir_var_shader_in, glsl_int_type(), "layer id");
568 var->data.location = VARYING_SLOT_LAYER;
569 var->data.interpolation = INTERP_MODE_FLAT;
570 return var;
571 }
572
573 /* We use layered rendering to implement multiview, which means we need to map
574 * view_index to gl_Layer. The attachment lowering also uses needs to know the
575 * layer so that it can sample from the correct layer. The code generates a
576 * load from the layer_id sysval, but since we don't have a way to get at this
577 * information from the fragment shader, we also need to lower this to the
578 * gl_Layer varying. This pass lowers both to a varying load from the LAYER
579 * slot, before lowering io, so that nir_assign_var_locations() will give the
580 * LAYER varying the correct driver_location.
581 */
582
583 static bool
584 lower_view_index(nir_shader *nir)
585 {
586 bool progress = false;
587 nir_function_impl *entry = nir_shader_get_entrypoint(nir);
588 nir_builder b;
589 nir_builder_init(&b, entry);
590
591 nir_variable *layer = NULL;
592 nir_foreach_block(block, entry) {
593 nir_foreach_instr_safe(instr, block) {
594 if (instr->type != nir_instr_type_intrinsic)
595 continue;
596
597 nir_intrinsic_instr *load = nir_instr_as_intrinsic(instr);
598 if (load->intrinsic != nir_intrinsic_load_view_index &&
599 load->intrinsic != nir_intrinsic_load_layer_id)
600 continue;
601
602 if (!layer)
603 layer = find_layer_in_var(nir);
604
605 b.cursor = nir_before_instr(instr);
606 nir_ssa_def *def = nir_load_var(&b, layer);
607 nir_ssa_def_rewrite_uses(&load->dest.ssa,
608 nir_src_for_ssa(def));
609
610 nir_instr_remove(instr);
611 progress = true;
612 }
613 }
614
615 return progress;
616 }
617
618 void
619 radv_lower_fs_io(nir_shader *nir)
620 {
621 NIR_PASS_V(nir, lower_view_index);
622 nir_assign_io_var_locations(&nir->inputs, &nir->num_inputs,
623 MESA_SHADER_FRAGMENT);
624
625 NIR_PASS_V(nir, nir_lower_io, nir_var_shader_in, type_size_vec4, 0);
626
627 /* This pass needs actual constants */
628 nir_opt_constant_folding(nir);
629
630 NIR_PASS_V(nir, nir_io_add_const_offset_to_base, nir_var_shader_in);
631 }
632
633
634 void *
635 radv_alloc_shader_memory(struct radv_device *device,
636 struct radv_shader_variant *shader)
637 {
638 mtx_lock(&device->shader_slab_mutex);
639 list_for_each_entry(struct radv_shader_slab, slab, &device->shader_slabs, slabs) {
640 uint64_t offset = 0;
641 list_for_each_entry(struct radv_shader_variant, s, &slab->shaders, slab_list) {
642 if (s->bo_offset - offset >= shader->code_size) {
643 shader->bo = slab->bo;
644 shader->bo_offset = offset;
645 list_addtail(&shader->slab_list, &s->slab_list);
646 mtx_unlock(&device->shader_slab_mutex);
647 return slab->ptr + offset;
648 }
649 offset = align_u64(s->bo_offset + s->code_size, 256);
650 }
651 if (offset <= slab->size && slab->size - offset >= shader->code_size) {
652 shader->bo = slab->bo;
653 shader->bo_offset = offset;
654 list_addtail(&shader->slab_list, &slab->shaders);
655 mtx_unlock(&device->shader_slab_mutex);
656 return slab->ptr + offset;
657 }
658 }
659
660 mtx_unlock(&device->shader_slab_mutex);
661 struct radv_shader_slab *slab = calloc(1, sizeof(struct radv_shader_slab));
662
663 slab->size = MAX2(256 * 1024, shader->code_size);
664 slab->bo = device->ws->buffer_create(device->ws, slab->size, 256,
665 RADEON_DOMAIN_VRAM,
666 RADEON_FLAG_NO_INTERPROCESS_SHARING |
667 (device->physical_device->rad_info.cpdma_prefetch_writes_memory ?
668 0 : RADEON_FLAG_READ_ONLY),
669 RADV_BO_PRIORITY_SHADER);
670 slab->ptr = (char*)device->ws->buffer_map(slab->bo);
671 list_inithead(&slab->shaders);
672
673 mtx_lock(&device->shader_slab_mutex);
674 list_add(&slab->slabs, &device->shader_slabs);
675
676 shader->bo = slab->bo;
677 shader->bo_offset = 0;
678 list_add(&shader->slab_list, &slab->shaders);
679 mtx_unlock(&device->shader_slab_mutex);
680 return slab->ptr;
681 }
682
683 void
684 radv_destroy_shader_slabs(struct radv_device *device)
685 {
686 list_for_each_entry_safe(struct radv_shader_slab, slab, &device->shader_slabs, slabs) {
687 device->ws->buffer_destroy(slab->bo);
688 free(slab);
689 }
690 mtx_destroy(&device->shader_slab_mutex);
691 }
692
693 /* For the UMR disassembler. */
694 #define DEBUGGER_END_OF_CODE_MARKER 0xbf9f0000 /* invalid instruction */
695 #define DEBUGGER_NUM_MARKERS 5
696
697 static unsigned
698 radv_get_shader_binary_size(size_t code_size)
699 {
700 return code_size + DEBUGGER_NUM_MARKERS * 4;
701 }
702
703 static void radv_postprocess_config(const struct radv_physical_device *pdevice,
704 const struct ac_shader_config *config_in,
705 const struct radv_shader_info *info,
706 gl_shader_stage stage,
707 struct ac_shader_config *config_out)
708 {
709 bool scratch_enabled = config_in->scratch_bytes_per_wave > 0;
710 unsigned vgpr_comp_cnt = 0;
711 unsigned num_input_vgprs = info->num_input_vgprs;
712
713 if (stage == MESA_SHADER_FRAGMENT) {
714 num_input_vgprs = ac_get_fs_input_vgpr_cnt(config_in, NULL, NULL);
715 }
716
717 unsigned num_vgprs = MAX2(config_in->num_vgprs, num_input_vgprs);
718 /* +3 for scratch wave offset and VCC */
719 unsigned num_sgprs = MAX2(config_in->num_sgprs, info->num_input_sgprs + 3);
720 unsigned num_shared_vgprs = config_in->num_shared_vgprs;
721 /* shared VGPRs are introduced in Navi and are allocated in blocks of 8 (RDNA ref 3.6.5) */
722 assert((pdevice->rad_info.chip_class >= GFX10 && num_shared_vgprs % 8 == 0)
723 || (pdevice->rad_info.chip_class < GFX10 && num_shared_vgprs == 0));
724 unsigned num_shared_vgpr_blocks = num_shared_vgprs / 8;
725
726 *config_out = *config_in;
727 config_out->num_vgprs = num_vgprs;
728 config_out->num_sgprs = num_sgprs;
729 config_out->num_shared_vgprs = num_shared_vgprs;
730
731 config_out->rsrc2 = S_00B12C_USER_SGPR(info->num_user_sgprs) |
732 S_00B12C_SCRATCH_EN(scratch_enabled);
733
734 if (!pdevice->use_ngg_streamout) {
735 config_out->rsrc2 |= S_00B12C_SO_BASE0_EN(!!info->so.strides[0]) |
736 S_00B12C_SO_BASE1_EN(!!info->so.strides[1]) |
737 S_00B12C_SO_BASE2_EN(!!info->so.strides[2]) |
738 S_00B12C_SO_BASE3_EN(!!info->so.strides[3]) |
739 S_00B12C_SO_EN(!!info->so.num_outputs);
740 }
741
742 config_out->rsrc1 = S_00B848_VGPRS((num_vgprs - 1) /
743 (info->wave_size == 32 ? 8 : 4)) |
744 S_00B848_DX10_CLAMP(1) |
745 S_00B848_FLOAT_MODE(config_out->float_mode);
746
747 if (pdevice->rad_info.chip_class >= GFX10) {
748 config_out->rsrc2 |= S_00B22C_USER_SGPR_MSB_GFX10(info->num_user_sgprs >> 5);
749 } else {
750 config_out->rsrc1 |= S_00B228_SGPRS((num_sgprs - 1) / 8);
751 config_out->rsrc2 |= S_00B22C_USER_SGPR_MSB_GFX9(info->num_user_sgprs >> 5);
752 }
753
754 switch (stage) {
755 case MESA_SHADER_TESS_EVAL:
756 if (info->is_ngg) {
757 config_out->rsrc1 |= S_00B228_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
758 config_out->rsrc2 |= S_00B22C_OC_LDS_EN(1);
759 } else if (info->tes.as_es) {
760 assert(pdevice->rad_info.chip_class <= GFX8);
761 vgpr_comp_cnt = info->uses_prim_id ? 3 : 2;
762
763 config_out->rsrc2 |= S_00B12C_OC_LDS_EN(1);
764 } else {
765 bool enable_prim_id = info->tes.export_prim_id || info->uses_prim_id;
766 vgpr_comp_cnt = enable_prim_id ? 3 : 2;
767
768 config_out->rsrc1 |= S_00B128_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
769 config_out->rsrc2 |= S_00B12C_OC_LDS_EN(1);
770 }
771 config_out->rsrc2 |= S_00B22C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
772 break;
773 case MESA_SHADER_TESS_CTRL:
774 if (pdevice->rad_info.chip_class >= GFX9) {
775 /* We need at least 2 components for LS.
776 * VGPR0-3: (VertexID, RelAutoindex, InstanceID / StepRate0, InstanceID).
777 * StepRate0 is set to 1. so that VGPR3 doesn't have to be loaded.
778 */
779 if (pdevice->rad_info.chip_class >= GFX10) {
780 vgpr_comp_cnt = info->vs.needs_instance_id ? 3 : 1;
781 } else {
782 vgpr_comp_cnt = info->vs.needs_instance_id ? 2 : 1;
783 }
784 } else {
785 config_out->rsrc2 |= S_00B12C_OC_LDS_EN(1);
786 }
787 config_out->rsrc1 |= S_00B428_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10) |
788 S_00B848_WGP_MODE(pdevice->rad_info.chip_class >= GFX10);
789 config_out->rsrc2 |= S_00B42C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
790 break;
791 case MESA_SHADER_VERTEX:
792 if (info->is_ngg) {
793 config_out->rsrc1 |= S_00B228_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
794 } else if (info->vs.as_ls) {
795 assert(pdevice->rad_info.chip_class <= GFX8);
796 /* We need at least 2 components for LS.
797 * VGPR0-3: (VertexID, RelAutoindex, InstanceID / StepRate0, InstanceID).
798 * StepRate0 is set to 1. so that VGPR3 doesn't have to be loaded.
799 */
800 vgpr_comp_cnt = info->vs.needs_instance_id ? 2 : 1;
801 } else if (info->vs.as_es) {
802 assert(pdevice->rad_info.chip_class <= GFX8);
803 /* VGPR0-3: (VertexID, InstanceID / StepRate0, ...) */
804 vgpr_comp_cnt = info->vs.needs_instance_id ? 1 : 0;
805 } else {
806 /* VGPR0-3: (VertexID, InstanceID / StepRate0, PrimID, InstanceID)
807 * If PrimID is disabled. InstanceID / StepRate1 is loaded instead.
808 * StepRate0 is set to 1. so that VGPR3 doesn't have to be loaded.
809 */
810 if (info->vs.needs_instance_id && pdevice->rad_info.chip_class >= GFX10) {
811 vgpr_comp_cnt = 3;
812 } else if (info->vs.export_prim_id) {
813 vgpr_comp_cnt = 2;
814 } else if (info->vs.needs_instance_id) {
815 vgpr_comp_cnt = 1;
816 } else {
817 vgpr_comp_cnt = 0;
818 }
819
820 config_out->rsrc1 |= S_00B128_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
821 }
822 config_out->rsrc2 |= S_00B12C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
823 break;
824 case MESA_SHADER_FRAGMENT:
825 config_out->rsrc1 |= S_00B028_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10);
826 config_out->rsrc2 |= S_00B02C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
827 break;
828 case MESA_SHADER_GEOMETRY:
829 config_out->rsrc1 |= S_00B228_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10) |
830 S_00B848_WGP_MODE(pdevice->rad_info.chip_class >= GFX10);
831 config_out->rsrc2 |= S_00B22C_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
832 break;
833 case MESA_SHADER_COMPUTE:
834 config_out->rsrc1 |= S_00B848_MEM_ORDERED(pdevice->rad_info.chip_class >= GFX10) |
835 S_00B848_WGP_MODE(pdevice->rad_info.chip_class >= GFX10);
836 config_out->rsrc2 |=
837 S_00B84C_TGID_X_EN(info->cs.uses_block_id[0]) |
838 S_00B84C_TGID_Y_EN(info->cs.uses_block_id[1]) |
839 S_00B84C_TGID_Z_EN(info->cs.uses_block_id[2]) |
840 S_00B84C_TIDIG_COMP_CNT(info->cs.uses_thread_id[2] ? 2 :
841 info->cs.uses_thread_id[1] ? 1 : 0) |
842 S_00B84C_TG_SIZE_EN(info->cs.uses_local_invocation_idx) |
843 S_00B84C_LDS_SIZE(config_in->lds_size);
844 config_out->rsrc3 |= S_00B8A0_SHARED_VGPR_CNT(num_shared_vgpr_blocks);
845
846 break;
847 default:
848 unreachable("unsupported shader type");
849 break;
850 }
851
852 if (pdevice->rad_info.chip_class >= GFX10 && info->is_ngg &&
853 (stage == MESA_SHADER_VERTEX || stage == MESA_SHADER_TESS_EVAL || stage == MESA_SHADER_GEOMETRY)) {
854 unsigned gs_vgpr_comp_cnt, es_vgpr_comp_cnt;
855 gl_shader_stage es_stage = stage;
856 if (stage == MESA_SHADER_GEOMETRY)
857 es_stage = info->gs.es_type;
858
859 /* VGPR5-8: (VertexID, UserVGPR0, UserVGPR1, UserVGPR2 / InstanceID) */
860 if (es_stage == MESA_SHADER_VERTEX) {
861 es_vgpr_comp_cnt = info->vs.needs_instance_id ? 3 : 0;
862 } else if (es_stage == MESA_SHADER_TESS_EVAL) {
863 bool enable_prim_id = info->tes.export_prim_id || info->uses_prim_id;
864 es_vgpr_comp_cnt = enable_prim_id ? 3 : 2;
865 } else
866 unreachable("Unexpected ES shader stage");
867
868 bool tes_triangles = stage == MESA_SHADER_TESS_EVAL &&
869 info->tes.primitive_mode >= 4; /* GL_TRIANGLES */
870 if (info->uses_invocation_id || stage == MESA_SHADER_VERTEX) {
871 gs_vgpr_comp_cnt = 3; /* VGPR3 contains InvocationID. */
872 } else if (info->uses_prim_id) {
873 gs_vgpr_comp_cnt = 2; /* VGPR2 contains PrimitiveID. */
874 } else if (info->gs.vertices_in >= 3 || tes_triangles) {
875 gs_vgpr_comp_cnt = 1; /* VGPR1 contains offsets 2, 3 */
876 } else {
877 gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0, 1 */
878 }
879
880 config_out->rsrc1 |= S_00B228_GS_VGPR_COMP_CNT(gs_vgpr_comp_cnt) |
881 S_00B228_WGP_MODE(1);
882 config_out->rsrc2 |= S_00B22C_ES_VGPR_COMP_CNT(es_vgpr_comp_cnt) |
883 S_00B22C_LDS_SIZE(config_in->lds_size) |
884 S_00B22C_OC_LDS_EN(es_stage == MESA_SHADER_TESS_EVAL);
885 } else if (pdevice->rad_info.chip_class >= GFX9 &&
886 stage == MESA_SHADER_GEOMETRY) {
887 unsigned es_type = info->gs.es_type;
888 unsigned gs_vgpr_comp_cnt, es_vgpr_comp_cnt;
889
890 if (es_type == MESA_SHADER_VERTEX) {
891 /* VGPR0-3: (VertexID, InstanceID / StepRate0, ...) */
892 if (info->vs.needs_instance_id) {
893 es_vgpr_comp_cnt = pdevice->rad_info.chip_class >= GFX10 ? 3 : 1;
894 } else {
895 es_vgpr_comp_cnt = 0;
896 }
897 } else if (es_type == MESA_SHADER_TESS_EVAL) {
898 es_vgpr_comp_cnt = info->uses_prim_id ? 3 : 2;
899 } else {
900 unreachable("invalid shader ES type");
901 }
902
903 /* If offsets 4, 5 are used, GS_VGPR_COMP_CNT is ignored and
904 * VGPR[0:4] are always loaded.
905 */
906 if (info->uses_invocation_id) {
907 gs_vgpr_comp_cnt = 3; /* VGPR3 contains InvocationID. */
908 } else if (info->uses_prim_id) {
909 gs_vgpr_comp_cnt = 2; /* VGPR2 contains PrimitiveID. */
910 } else if (info->gs.vertices_in >= 3) {
911 gs_vgpr_comp_cnt = 1; /* VGPR1 contains offsets 2, 3 */
912 } else {
913 gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0, 1 */
914 }
915
916 config_out->rsrc1 |= S_00B228_GS_VGPR_COMP_CNT(gs_vgpr_comp_cnt);
917 config_out->rsrc2 |= S_00B22C_ES_VGPR_COMP_CNT(es_vgpr_comp_cnt) |
918 S_00B22C_OC_LDS_EN(es_type == MESA_SHADER_TESS_EVAL);
919 } else if (pdevice->rad_info.chip_class >= GFX9 &&
920 stage == MESA_SHADER_TESS_CTRL) {
921 config_out->rsrc1 |= S_00B428_LS_VGPR_COMP_CNT(vgpr_comp_cnt);
922 } else {
923 config_out->rsrc1 |= S_00B128_VGPR_COMP_CNT(vgpr_comp_cnt);
924 }
925 }
926
927 struct radv_shader_variant *
928 radv_shader_variant_create(struct radv_device *device,
929 const struct radv_shader_binary *binary,
930 bool keep_shader_info)
931 {
932 struct ac_shader_config config = {0};
933 struct ac_rtld_binary rtld_binary = {0};
934 struct radv_shader_variant *variant = calloc(1, sizeof(struct radv_shader_variant));
935 if (!variant)
936 return NULL;
937
938 variant->ref_count = 1;
939
940 if (binary->type == RADV_BINARY_TYPE_RTLD) {
941 struct ac_rtld_symbol lds_symbols[2];
942 unsigned num_lds_symbols = 0;
943 const char *elf_data = (const char *)((struct radv_shader_binary_rtld *)binary)->data;
944 size_t elf_size = ((struct radv_shader_binary_rtld *)binary)->elf_size;
945
946 if (device->physical_device->rad_info.chip_class >= GFX9 &&
947 (binary->stage == MESA_SHADER_GEOMETRY || binary->info.is_ngg) &&
948 !binary->is_gs_copy_shader) {
949 /* We add this symbol even on LLVM <= 8 to ensure that
950 * shader->config.lds_size is set correctly below.
951 */
952 struct ac_rtld_symbol *sym = &lds_symbols[num_lds_symbols++];
953 sym->name = "esgs_ring";
954 sym->size = binary->info.ngg_info.esgs_ring_size;
955 sym->align = 64 * 1024;
956 }
957
958 if (binary->info.is_ngg &&
959 binary->stage == MESA_SHADER_GEOMETRY) {
960 struct ac_rtld_symbol *sym = &lds_symbols[num_lds_symbols++];
961 sym->name = "ngg_emit";
962 sym->size = binary->info.ngg_info.ngg_emit_size * 4;
963 sym->align = 4;
964 }
965
966 struct ac_rtld_open_info open_info = {
967 .info = &device->physical_device->rad_info,
968 .shader_type = binary->stage,
969 .wave_size = binary->info.wave_size,
970 .num_parts = 1,
971 .elf_ptrs = &elf_data,
972 .elf_sizes = &elf_size,
973 .num_shared_lds_symbols = num_lds_symbols,
974 .shared_lds_symbols = lds_symbols,
975 };
976
977 if (!ac_rtld_open(&rtld_binary, open_info)) {
978 free(variant);
979 return NULL;
980 }
981
982 if (!ac_rtld_read_config(&rtld_binary, &config)) {
983 ac_rtld_close(&rtld_binary);
984 free(variant);
985 return NULL;
986 }
987
988 if (rtld_binary.lds_size > 0) {
989 unsigned alloc_granularity = device->physical_device->rad_info.chip_class >= GFX7 ? 512 : 256;
990 config.lds_size = align(rtld_binary.lds_size, alloc_granularity) / alloc_granularity;
991 }
992
993 variant->code_size = rtld_binary.rx_size;
994 variant->exec_size = rtld_binary.exec_size;
995 } else {
996 assert(binary->type == RADV_BINARY_TYPE_LEGACY);
997 config = ((struct radv_shader_binary_legacy *)binary)->config;
998 variant->code_size = radv_get_shader_binary_size(((struct radv_shader_binary_legacy *)binary)->code_size);
999 variant->exec_size = ((struct radv_shader_binary_legacy *)binary)->exec_size;
1000 }
1001
1002 variant->info = binary->info;
1003 radv_postprocess_config(device->physical_device, &config, &binary->info,
1004 binary->stage, &variant->config);
1005
1006 if (radv_device_use_secure_compile(device->instance)) {
1007 if (binary->type == RADV_BINARY_TYPE_RTLD)
1008 ac_rtld_close(&rtld_binary);
1009
1010 return variant;
1011 }
1012
1013 void *dest_ptr = radv_alloc_shader_memory(device, variant);
1014
1015 if (binary->type == RADV_BINARY_TYPE_RTLD) {
1016 struct radv_shader_binary_rtld* bin = (struct radv_shader_binary_rtld *)binary;
1017 struct ac_rtld_upload_info info = {
1018 .binary = &rtld_binary,
1019 .rx_va = radv_buffer_get_va(variant->bo) + variant->bo_offset,
1020 .rx_ptr = dest_ptr,
1021 };
1022
1023 if (!ac_rtld_upload(&info)) {
1024 radv_shader_variant_destroy(device, variant);
1025 ac_rtld_close(&rtld_binary);
1026 return NULL;
1027 }
1028
1029 if (keep_shader_info ||
1030 (device->instance->debug_flags & RADV_DEBUG_DUMP_SHADERS)) {
1031 const char *disasm_data;
1032 size_t disasm_size;
1033 if (!ac_rtld_get_section_by_name(&rtld_binary, ".AMDGPU.disasm", &disasm_data, &disasm_size)) {
1034 radv_shader_variant_destroy(device, variant);
1035 ac_rtld_close(&rtld_binary);
1036 return NULL;
1037 }
1038
1039 variant->ir_string = bin->llvm_ir_size ? strdup((const char*)(bin->data + bin->elf_size)) : NULL;
1040 variant->disasm_string = malloc(disasm_size + 1);
1041 memcpy(variant->disasm_string, disasm_data, disasm_size);
1042 variant->disasm_string[disasm_size] = 0;
1043 }
1044
1045 ac_rtld_close(&rtld_binary);
1046 } else {
1047 struct radv_shader_binary_legacy* bin = (struct radv_shader_binary_legacy *)binary;
1048 memcpy(dest_ptr, bin->data + bin->stats_size, bin->code_size);
1049
1050 /* Add end-of-code markers for the UMR disassembler. */
1051 uint32_t *ptr32 = (uint32_t *)dest_ptr + bin->code_size / 4;
1052 for (unsigned i = 0; i < DEBUGGER_NUM_MARKERS; i++)
1053 ptr32[i] = DEBUGGER_END_OF_CODE_MARKER;
1054
1055 variant->ir_string = bin->ir_size ? strdup((const char*)(bin->data + bin->stats_size + bin->code_size)) : NULL;
1056 variant->disasm_string = bin->disasm_size ? strdup((const char*)(bin->data + bin->stats_size + bin->code_size + bin->ir_size)) : NULL;
1057
1058 if (bin->stats_size) {
1059 variant->statistics = calloc(bin->stats_size, 1);
1060 memcpy(variant->statistics, bin->data, bin->stats_size);
1061 }
1062 }
1063 return variant;
1064 }
1065
1066 static char *
1067 radv_dump_nir_shaders(struct nir_shader * const *shaders,
1068 int shader_count)
1069 {
1070 char *data = NULL;
1071 char *ret = NULL;
1072 size_t size = 0;
1073 FILE *f = open_memstream(&data, &size);
1074 if (f) {
1075 for (int i = 0; i < shader_count; ++i)
1076 nir_print_shader(shaders[i], f);
1077 fclose(f);
1078 }
1079
1080 ret = malloc(size + 1);
1081 if (ret) {
1082 memcpy(ret, data, size);
1083 ret[size] = 0;
1084 }
1085 free(data);
1086 return ret;
1087 }
1088
1089 static struct radv_shader_variant *
1090 shader_variant_compile(struct radv_device *device,
1091 struct radv_shader_module *module,
1092 struct nir_shader * const *shaders,
1093 int shader_count,
1094 gl_shader_stage stage,
1095 struct radv_shader_info *info,
1096 struct radv_nir_compiler_options *options,
1097 bool gs_copy_shader,
1098 bool keep_shader_info,
1099 bool keep_statistic_info,
1100 struct radv_shader_binary **binary_out)
1101 {
1102 enum radeon_family chip_family = device->physical_device->rad_info.family;
1103 struct radv_shader_binary *binary = NULL;
1104
1105 options->family = chip_family;
1106 options->chip_class = device->physical_device->rad_info.chip_class;
1107 options->dump_shader = radv_can_dump_shader(device, module, gs_copy_shader);
1108 options->dump_preoptir = options->dump_shader &&
1109 device->instance->debug_flags & RADV_DEBUG_PREOPTIR;
1110 options->record_ir = keep_shader_info;
1111 options->record_stats = keep_statistic_info;
1112 options->check_ir = device->instance->debug_flags & RADV_DEBUG_CHECKIR;
1113 options->tess_offchip_block_dw_size = device->tess_offchip_block_dw_size;
1114 options->address32_hi = device->physical_device->rad_info.address32_hi;
1115 options->has_ls_vgpr_init_bug = device->physical_device->rad_info.has_ls_vgpr_init_bug;
1116 options->use_ngg_streamout = device->physical_device->use_ngg_streamout;
1117
1118 struct radv_shader_args args = {};
1119 args.options = options;
1120 args.shader_info = info;
1121 args.is_gs_copy_shader = gs_copy_shader;
1122 radv_declare_shader_args(&args,
1123 gs_copy_shader ? MESA_SHADER_VERTEX
1124 : shaders[shader_count - 1]->info.stage,
1125 shader_count >= 2,
1126 shader_count >= 2 ? shaders[shader_count - 2]->info.stage
1127 : MESA_SHADER_VERTEX);
1128
1129 if (!device->physical_device->use_aco ||
1130 options->dump_shader || options->record_ir)
1131 ac_init_llvm_once();
1132
1133 if (device->physical_device->use_aco) {
1134 aco_compile_shader(shader_count, shaders, &binary, &args);
1135 } else {
1136 llvm_compile_shader(device, shader_count, shaders, &binary, &args);
1137 }
1138
1139 binary->info = *info;
1140
1141 struct radv_shader_variant *variant = radv_shader_variant_create(device, binary,
1142 keep_shader_info);
1143 if (!variant) {
1144 free(binary);
1145 return NULL;
1146 }
1147
1148 if (options->dump_shader) {
1149 fprintf(stderr, "%s", radv_get_shader_name(info, shaders[0]->info.stage));
1150 for (int i = 1; i < shader_count; ++i)
1151 fprintf(stderr, " + %s", radv_get_shader_name(info, shaders[i]->info.stage));
1152
1153 fprintf(stderr, "\ndisasm:\n%s\n", variant->disasm_string);
1154 }
1155
1156
1157 if (keep_shader_info) {
1158 variant->nir_string = radv_dump_nir_shaders(shaders, shader_count);
1159 if (!gs_copy_shader && !module->nir) {
1160 variant->spirv = malloc(module->size);
1161 if (!variant->spirv) {
1162 free(variant);
1163 free(binary);
1164 return NULL;
1165 }
1166
1167 memcpy(variant->spirv, module->data, module->size);
1168 variant->spirv_size = module->size;
1169 }
1170 }
1171
1172 if (binary_out)
1173 *binary_out = binary;
1174 else
1175 free(binary);
1176
1177 return variant;
1178 }
1179
1180 struct radv_shader_variant *
1181 radv_shader_variant_compile(struct radv_device *device,
1182 struct radv_shader_module *module,
1183 struct nir_shader *const *shaders,
1184 int shader_count,
1185 struct radv_pipeline_layout *layout,
1186 const struct radv_shader_variant_key *key,
1187 struct radv_shader_info *info,
1188 bool keep_shader_info, bool keep_statistic_info,
1189 struct radv_shader_binary **binary_out)
1190 {
1191 struct radv_nir_compiler_options options = {0};
1192
1193 options.layout = layout;
1194 if (key)
1195 options.key = *key;
1196
1197 options.explicit_scratch_args = device->physical_device->use_aco;
1198 options.robust_buffer_access = device->robust_buffer_access;
1199
1200 return shader_variant_compile(device, module, shaders, shader_count, shaders[shader_count - 1]->info.stage, info,
1201 &options, false, keep_shader_info, keep_statistic_info, binary_out);
1202 }
1203
1204 struct radv_shader_variant *
1205 radv_create_gs_copy_shader(struct radv_device *device,
1206 struct nir_shader *shader,
1207 struct radv_shader_info *info,
1208 struct radv_shader_binary **binary_out,
1209 bool keep_shader_info, bool keep_statistic_info,
1210 bool multiview)
1211 {
1212 struct radv_nir_compiler_options options = {0};
1213
1214 options.explicit_scratch_args = device->physical_device->use_aco;
1215 options.key.has_multiview_view_index = multiview;
1216
1217 return shader_variant_compile(device, NULL, &shader, 1, MESA_SHADER_VERTEX,
1218 info, &options, true, keep_shader_info, keep_statistic_info, binary_out);
1219 }
1220
1221 void
1222 radv_shader_variant_destroy(struct radv_device *device,
1223 struct radv_shader_variant *variant)
1224 {
1225 if (!p_atomic_dec_zero(&variant->ref_count))
1226 return;
1227
1228 mtx_lock(&device->shader_slab_mutex);
1229 list_del(&variant->slab_list);
1230 mtx_unlock(&device->shader_slab_mutex);
1231
1232 free(variant->spirv);
1233 free(variant->nir_string);
1234 free(variant->disasm_string);
1235 free(variant->ir_string);
1236 free(variant->statistics);
1237 free(variant);
1238 }
1239
1240 const char *
1241 radv_get_shader_name(struct radv_shader_info *info,
1242 gl_shader_stage stage)
1243 {
1244 switch (stage) {
1245 case MESA_SHADER_VERTEX:
1246 if (info->vs.as_ls)
1247 return "Vertex Shader as LS";
1248 else if (info->vs.as_es)
1249 return "Vertex Shader as ES";
1250 else if (info->is_ngg)
1251 return "Vertex Shader as ESGS";
1252 else
1253 return "Vertex Shader as VS";
1254 case MESA_SHADER_TESS_CTRL:
1255 return "Tessellation Control Shader";
1256 case MESA_SHADER_TESS_EVAL:
1257 if (info->tes.as_es)
1258 return "Tessellation Evaluation Shader as ES";
1259 else if (info->is_ngg)
1260 return "Tessellation Evaluation Shader as ESGS";
1261 else
1262 return "Tessellation Evaluation Shader as VS";
1263 case MESA_SHADER_GEOMETRY:
1264 return "Geometry Shader";
1265 case MESA_SHADER_FRAGMENT:
1266 return "Pixel Shader";
1267 case MESA_SHADER_COMPUTE:
1268 return "Compute Shader";
1269 default:
1270 return "Unknown shader";
1271 };
1272 }
1273
1274 unsigned
1275 radv_get_max_workgroup_size(enum chip_class chip_class,
1276 gl_shader_stage stage,
1277 const unsigned *sizes)
1278 {
1279 switch (stage) {
1280 case MESA_SHADER_TESS_CTRL:
1281 return chip_class >= GFX7 ? 128 : 64;
1282 case MESA_SHADER_GEOMETRY:
1283 return chip_class >= GFX9 ? 128 : 64;
1284 case MESA_SHADER_COMPUTE:
1285 break;
1286 default:
1287 return 0;
1288 }
1289
1290 unsigned max_workgroup_size = sizes[0] * sizes[1] * sizes[2];
1291 return max_workgroup_size;
1292 }
1293
1294 unsigned
1295 radv_get_max_waves(struct radv_device *device,
1296 struct radv_shader_variant *variant,
1297 gl_shader_stage stage)
1298 {
1299 enum chip_class chip_class = device->physical_device->rad_info.chip_class;
1300 unsigned lds_increment = chip_class >= GFX7 ? 512 : 256;
1301 uint8_t wave_size = variant->info.wave_size;
1302 struct ac_shader_config *conf = &variant->config;
1303 unsigned max_simd_waves;
1304 unsigned lds_per_wave = 0;
1305
1306 max_simd_waves = device->physical_device->rad_info.max_wave64_per_simd;
1307
1308 if (stage == MESA_SHADER_FRAGMENT) {
1309 lds_per_wave = conf->lds_size * lds_increment +
1310 align(variant->info.ps.num_interp * 48,
1311 lds_increment);
1312 } else if (stage == MESA_SHADER_COMPUTE) {
1313 unsigned max_workgroup_size =
1314 radv_get_max_workgroup_size(chip_class, stage, variant->info.cs.block_size);
1315 lds_per_wave = (conf->lds_size * lds_increment) /
1316 DIV_ROUND_UP(max_workgroup_size, wave_size);
1317 }
1318
1319 if (conf->num_sgprs) {
1320 unsigned sgprs = align(conf->num_sgprs, chip_class >= GFX8 ? 16 : 8);
1321 max_simd_waves =
1322 MIN2(max_simd_waves,
1323 device->physical_device->rad_info.num_physical_sgprs_per_simd /
1324 sgprs);
1325 }
1326
1327 if (conf->num_vgprs) {
1328 unsigned vgprs = align(conf->num_vgprs, wave_size == 32 ? 8 : 4);
1329 max_simd_waves =
1330 MIN2(max_simd_waves,
1331 device->physical_device->rad_info.num_physical_wave64_vgprs_per_simd / vgprs);
1332 }
1333
1334 unsigned max_lds_per_simd = device->physical_device->rad_info.lds_size_per_workgroup / device->physical_device->rad_info.num_simd_per_compute_unit;
1335 if (lds_per_wave)
1336 max_simd_waves = MIN2(max_simd_waves, max_lds_per_simd / lds_per_wave);
1337
1338 return max_simd_waves;
1339 }
1340
1341 static void
1342 generate_shader_stats(struct radv_device *device,
1343 struct radv_shader_variant *variant,
1344 gl_shader_stage stage,
1345 struct _mesa_string_buffer *buf)
1346 {
1347 struct ac_shader_config *conf = &variant->config;
1348 unsigned max_simd_waves = radv_get_max_waves(device, variant, stage);
1349
1350 if (stage == MESA_SHADER_FRAGMENT) {
1351 _mesa_string_buffer_printf(buf, "*** SHADER CONFIG ***\n"
1352 "SPI_PS_INPUT_ADDR = 0x%04x\n"
1353 "SPI_PS_INPUT_ENA = 0x%04x\n",
1354 conf->spi_ps_input_addr, conf->spi_ps_input_ena);
1355 }
1356
1357 _mesa_string_buffer_printf(buf, "*** SHADER STATS ***\n"
1358 "SGPRS: %d\n"
1359 "VGPRS: %d\n"
1360 "Spilled SGPRs: %d\n"
1361 "Spilled VGPRs: %d\n"
1362 "PrivMem VGPRS: %d\n"
1363 "Code Size: %d bytes\n"
1364 "LDS: %d blocks\n"
1365 "Scratch: %d bytes per wave\n"
1366 "Max Waves: %d\n",
1367 conf->num_sgprs, conf->num_vgprs,
1368 conf->spilled_sgprs, conf->spilled_vgprs,
1369 variant->info.private_mem_vgprs, variant->exec_size,
1370 conf->lds_size, conf->scratch_bytes_per_wave,
1371 max_simd_waves);
1372
1373 if (variant->statistics) {
1374 _mesa_string_buffer_printf(buf, "*** COMPILER STATS ***\n");
1375 for (unsigned i = 0; i < variant->statistics->count; i++) {
1376 struct radv_compiler_statistic_info *info = &variant->statistics->infos[i];
1377 uint32_t value = variant->statistics->values[i];
1378 _mesa_string_buffer_printf(buf, "%s: %lu\n", info->name, value);
1379 }
1380 }
1381
1382 _mesa_string_buffer_printf(buf, "********************\n\n\n");
1383 }
1384
1385 void
1386 radv_shader_dump_stats(struct radv_device *device,
1387 struct radv_shader_variant *variant,
1388 gl_shader_stage stage,
1389 FILE *file)
1390 {
1391 struct _mesa_string_buffer *buf = _mesa_string_buffer_create(NULL, 256);
1392
1393 generate_shader_stats(device, variant, stage, buf);
1394
1395 fprintf(file, "\n%s:\n", radv_get_shader_name(&variant->info, stage));
1396 fprintf(file, "%s", buf->buf);
1397
1398 _mesa_string_buffer_destroy(buf);
1399 }
1400
1401 VkResult
1402 radv_GetShaderInfoAMD(VkDevice _device,
1403 VkPipeline _pipeline,
1404 VkShaderStageFlagBits shaderStage,
1405 VkShaderInfoTypeAMD infoType,
1406 size_t* pInfoSize,
1407 void* pInfo)
1408 {
1409 RADV_FROM_HANDLE(radv_device, device, _device);
1410 RADV_FROM_HANDLE(radv_pipeline, pipeline, _pipeline);
1411 gl_shader_stage stage = vk_to_mesa_shader_stage(shaderStage);
1412 struct radv_shader_variant *variant = pipeline->shaders[stage];
1413 struct _mesa_string_buffer *buf;
1414 VkResult result = VK_SUCCESS;
1415
1416 /* Spec doesn't indicate what to do if the stage is invalid, so just
1417 * return no info for this. */
1418 if (!variant)
1419 return vk_error(device->instance, VK_ERROR_FEATURE_NOT_PRESENT);
1420
1421 switch (infoType) {
1422 case VK_SHADER_INFO_TYPE_STATISTICS_AMD:
1423 if (!pInfo) {
1424 *pInfoSize = sizeof(VkShaderStatisticsInfoAMD);
1425 } else {
1426 unsigned lds_multiplier = device->physical_device->rad_info.chip_class >= GFX7 ? 512 : 256;
1427 struct ac_shader_config *conf = &variant->config;
1428
1429 VkShaderStatisticsInfoAMD statistics = {};
1430 statistics.shaderStageMask = shaderStage;
1431 statistics.numPhysicalVgprs = device->physical_device->rad_info.num_physical_wave64_vgprs_per_simd;
1432 statistics.numPhysicalSgprs = device->physical_device->rad_info.num_physical_sgprs_per_simd;
1433 statistics.numAvailableSgprs = statistics.numPhysicalSgprs;
1434
1435 if (stage == MESA_SHADER_COMPUTE) {
1436 unsigned *local_size = variant->info.cs.block_size;
1437 unsigned workgroup_size = local_size[0] * local_size[1] * local_size[2];
1438
1439 statistics.numAvailableVgprs = statistics.numPhysicalVgprs /
1440 ceil((double)workgroup_size / statistics.numPhysicalVgprs);
1441
1442 statistics.computeWorkGroupSize[0] = local_size[0];
1443 statistics.computeWorkGroupSize[1] = local_size[1];
1444 statistics.computeWorkGroupSize[2] = local_size[2];
1445 } else {
1446 statistics.numAvailableVgprs = statistics.numPhysicalVgprs;
1447 }
1448
1449 statistics.resourceUsage.numUsedVgprs = conf->num_vgprs;
1450 statistics.resourceUsage.numUsedSgprs = conf->num_sgprs;
1451 statistics.resourceUsage.ldsSizePerLocalWorkGroup = 32768;
1452 statistics.resourceUsage.ldsUsageSizeInBytes = conf->lds_size * lds_multiplier;
1453 statistics.resourceUsage.scratchMemUsageInBytes = conf->scratch_bytes_per_wave;
1454
1455 size_t size = *pInfoSize;
1456 *pInfoSize = sizeof(statistics);
1457
1458 memcpy(pInfo, &statistics, MIN2(size, *pInfoSize));
1459
1460 if (size < *pInfoSize)
1461 result = VK_INCOMPLETE;
1462 }
1463
1464 break;
1465 case VK_SHADER_INFO_TYPE_DISASSEMBLY_AMD:
1466 buf = _mesa_string_buffer_create(NULL, 1024);
1467
1468 _mesa_string_buffer_printf(buf, "%s:\n", radv_get_shader_name(&variant->info, stage));
1469 _mesa_string_buffer_printf(buf, "%s\n\n", variant->ir_string);
1470 _mesa_string_buffer_printf(buf, "%s\n\n", variant->disasm_string);
1471 generate_shader_stats(device, variant, stage, buf);
1472
1473 /* Need to include the null terminator. */
1474 size_t length = buf->length + 1;
1475
1476 if (!pInfo) {
1477 *pInfoSize = length;
1478 } else {
1479 size_t size = *pInfoSize;
1480 *pInfoSize = length;
1481
1482 memcpy(pInfo, buf->buf, MIN2(size, length));
1483
1484 if (size < length)
1485 result = VK_INCOMPLETE;
1486 }
1487
1488 _mesa_string_buffer_destroy(buf);
1489 break;
1490 default:
1491 /* VK_SHADER_INFO_TYPE_BINARY_AMD unimplemented for now. */
1492 result = VK_ERROR_FEATURE_NOT_PRESENT;
1493 break;
1494 }
1495
1496 return result;
1497 }