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