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