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