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