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