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