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