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