radv_shader.c revision 01e04c3f
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 "gfx9d.h"
44#include "ac_binary.h"
45#include "ac_llvm_util.h"
46#include "ac_nir_to_llvm.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
53static const struct nir_shader_compiler_options nir_options = {
54	.vertex_id_zero_based = true,
55	.lower_scmp = 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_sub = true,
62	.lower_pack_snorm_2x16 = true,
63	.lower_pack_snorm_4x8 = true,
64	.lower_pack_unorm_2x16 = true,
65	.lower_pack_unorm_4x8 = true,
66	.lower_unpack_snorm_2x16 = true,
67	.lower_unpack_snorm_4x8 = true,
68	.lower_unpack_unorm_2x16 = true,
69	.lower_unpack_unorm_4x8 = true,
70	.lower_extract_byte = true,
71	.lower_extract_word = true,
72	.lower_ffma = true,
73	.lower_fpow = true,
74	.max_unroll_iterations = 32
75};
76
77VkResult radv_CreateShaderModule(
78	VkDevice                                    _device,
79	const VkShaderModuleCreateInfo*             pCreateInfo,
80	const VkAllocationCallbacks*                pAllocator,
81	VkShaderModule*                             pShaderModule)
82{
83	RADV_FROM_HANDLE(radv_device, device, _device);
84	struct radv_shader_module *module;
85
86	assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
87	assert(pCreateInfo->flags == 0);
88
89	module = vk_alloc2(&device->alloc, pAllocator,
90			     sizeof(*module) + pCreateInfo->codeSize, 8,
91			     VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
92	if (module == NULL)
93		return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
94
95	module->nir = NULL;
96	module->size = pCreateInfo->codeSize;
97	memcpy(module->data, pCreateInfo->pCode, module->size);
98
99	_mesa_sha1_compute(module->data, module->size, module->sha1);
100
101	*pShaderModule = radv_shader_module_to_handle(module);
102
103	return VK_SUCCESS;
104}
105
106void radv_DestroyShaderModule(
107	VkDevice                                    _device,
108	VkShaderModule                              _module,
109	const VkAllocationCallbacks*                pAllocator)
110{
111	RADV_FROM_HANDLE(radv_device, device, _device);
112	RADV_FROM_HANDLE(radv_shader_module, module, _module);
113
114	if (!module)
115		return;
116
117	vk_free2(&device->alloc, pAllocator, module);
118}
119
120void
121radv_optimize_nir(struct nir_shader *shader, bool optimize_conservatively,
122                  bool allow_copies)
123{
124        bool progress;
125
126        do {
127                progress = false;
128
129		NIR_PASS(progress, shader, nir_split_array_vars, nir_var_local);
130		NIR_PASS(progress, shader, nir_shrink_vec_array_vars, nir_var_local);
131
132                NIR_PASS_V(shader, nir_lower_vars_to_ssa);
133		NIR_PASS_V(shader, nir_lower_pack);
134
135		if (allow_copies) {
136			/* Only run this pass in the first call to
137			 * radv_optimize_nir.  Later calls assume that we've
138			 * lowered away any copy_deref instructions and we
139			 *  don't want to introduce any more.
140			*/
141			NIR_PASS(progress, shader, nir_opt_find_array_copies);
142		}
143
144		NIR_PASS(progress, shader, nir_opt_copy_prop_vars);
145		NIR_PASS(progress, shader, nir_opt_dead_write_vars);
146
147                NIR_PASS_V(shader, nir_lower_alu_to_scalar);
148                NIR_PASS_V(shader, nir_lower_phis_to_scalar);
149
150                NIR_PASS(progress, shader, nir_copy_prop);
151                NIR_PASS(progress, shader, nir_opt_remove_phis);
152                NIR_PASS(progress, shader, nir_opt_dce);
153                if (nir_opt_trivial_continues(shader)) {
154                        progress = true;
155                        NIR_PASS(progress, shader, nir_copy_prop);
156			NIR_PASS(progress, shader, nir_opt_remove_phis);
157                        NIR_PASS(progress, shader, nir_opt_dce);
158                }
159                NIR_PASS(progress, shader, nir_opt_if);
160                NIR_PASS(progress, shader, nir_opt_dead_cf);
161                NIR_PASS(progress, shader, nir_opt_cse);
162                NIR_PASS(progress, shader, nir_opt_peephole_select, 8);
163                NIR_PASS(progress, shader, nir_opt_algebraic);
164                NIR_PASS(progress, shader, nir_opt_constant_folding);
165                NIR_PASS(progress, shader, nir_opt_undef);
166                NIR_PASS(progress, shader, nir_opt_conditional_discard);
167                if (shader->options->max_unroll_iterations) {
168                        NIR_PASS(progress, shader, nir_opt_loop_unroll, 0);
169                }
170        } while (progress && !optimize_conservatively);
171
172        NIR_PASS(progress, shader, nir_opt_shrink_load);
173        NIR_PASS(progress, shader, nir_opt_move_load_ubo);
174}
175
176nir_shader *
177radv_shader_compile_to_nir(struct radv_device *device,
178			   struct radv_shader_module *module,
179			   const char *entrypoint_name,
180			   gl_shader_stage stage,
181			   const VkSpecializationInfo *spec_info,
182			   const VkPipelineCreateFlags flags)
183{
184	nir_shader *nir;
185	nir_function *entry_point;
186	if (module->nir) {
187		/* Some things such as our meta clear/blit code will give us a NIR
188		 * shader directly.  In that case, we just ignore the SPIR-V entirely
189		 * and just use the NIR shader */
190		nir = module->nir;
191		nir->options = &nir_options;
192		nir_validate_shader(nir, "in internal shader");
193
194		assert(exec_list_length(&nir->functions) == 1);
195		struct exec_node *node = exec_list_get_head(&nir->functions);
196		entry_point = exec_node_data(nir_function, node, node);
197	} else {
198		uint32_t *spirv = (uint32_t *) module->data;
199		assert(module->size % 4 == 0);
200
201		if (device->instance->debug_flags & RADV_DEBUG_DUMP_SPIRV)
202			radv_print_spirv(spirv, module->size, stderr);
203
204		uint32_t num_spec_entries = 0;
205		struct nir_spirv_specialization *spec_entries = NULL;
206		if (spec_info && spec_info->mapEntryCount > 0) {
207			num_spec_entries = spec_info->mapEntryCount;
208			spec_entries = malloc(num_spec_entries * sizeof(*spec_entries));
209			for (uint32_t i = 0; i < num_spec_entries; i++) {
210				VkSpecializationMapEntry entry = spec_info->pMapEntries[i];
211				const void *data = spec_info->pData + entry.offset;
212				assert(data + entry.size <= spec_info->pData + spec_info->dataSize);
213
214				spec_entries[i].id = spec_info->pMapEntries[i].constantID;
215				if (spec_info->dataSize == 8)
216					spec_entries[i].data64 = *(const uint64_t *)data;
217				else
218					spec_entries[i].data32 = *(const uint32_t *)data;
219			}
220		}
221		const struct spirv_to_nir_options spirv_options = {
222			.caps = {
223				.device_group = true,
224				.draw_parameters = true,
225				.float64 = true,
226				.image_read_without_format = true,
227				.image_write_without_format = true,
228				.tessellation = true,
229				.int64 = true,
230				.int16 = true,
231				.multiview = true,
232				.subgroup_arithmetic = true,
233				.subgroup_ballot = true,
234				.subgroup_basic = true,
235				.subgroup_quad = true,
236				.subgroup_shuffle = true,
237				.subgroup_vote = true,
238				.variable_pointers = true,
239				.gcn_shader = true,
240				.trinary_minmax = true,
241				.shader_viewport_index_layer = true,
242				.descriptor_array_dynamic_indexing = true,
243				.runtime_descriptor_array = true,
244				.stencil_export = true,
245				.storage_16bit = true,
246				.geometry_streams = true,
247				.transform_feedback = true,
248			},
249		};
250		entry_point = spirv_to_nir(spirv, module->size / 4,
251					   spec_entries, num_spec_entries,
252					   stage, entrypoint_name,
253					   &spirv_options, &nir_options);
254		nir = entry_point->shader;
255		assert(nir->info.stage == stage);
256		nir_validate_shader(nir, "after spirv_to_nir");
257
258		free(spec_entries);
259
260		/* We have to lower away local constant initializers right before we
261		 * inline functions.  That way they get properly initialized at the top
262		 * of the function and not at the top of its caller.
263		 */
264		NIR_PASS_V(nir, nir_lower_constant_initializers, nir_var_local);
265		NIR_PASS_V(nir, nir_lower_returns);
266		NIR_PASS_V(nir, nir_inline_functions);
267		NIR_PASS_V(nir, nir_copy_prop);
268
269		/* Pick off the single entrypoint that we want */
270		foreach_list_typed_safe(nir_function, func, node, &nir->functions) {
271			if (func != entry_point)
272				exec_node_remove(&func->node);
273		}
274		assert(exec_list_length(&nir->functions) == 1);
275		entry_point->name = ralloc_strdup(entry_point, "main");
276
277		/* Make sure we lower constant initializers on output variables so that
278		 * nir_remove_dead_variables below sees the corresponding stores
279		 */
280		NIR_PASS_V(nir, nir_lower_constant_initializers, nir_var_shader_out);
281
282		/* Now that we've deleted all but the main function, we can go ahead and
283		 * lower the rest of the constant initializers.
284		 */
285		NIR_PASS_V(nir, nir_lower_constant_initializers, ~0);
286
287		/* Split member structs.  We do this before lower_io_to_temporaries so that
288		 * it doesn't lower system values to temporaries by accident.
289		 */
290		NIR_PASS_V(nir, nir_split_var_copies);
291		NIR_PASS_V(nir, nir_split_per_member_structs);
292
293		NIR_PASS_V(nir, nir_remove_dead_variables,
294		           nir_var_shader_in | nir_var_shader_out | nir_var_system_value);
295
296		NIR_PASS_V(nir, nir_lower_system_values);
297		NIR_PASS_V(nir, nir_lower_clip_cull_distance_arrays);
298	}
299
300	/* Vulkan uses the separate-shader linking model */
301	nir->info.separate_shader = true;
302
303	nir_shader_gather_info(nir, entry_point->impl);
304
305	static const nir_lower_tex_options tex_options = {
306	  .lower_txp = ~0,
307	};
308
309	nir_lower_tex(nir, &tex_options);
310
311	nir_lower_vars_to_ssa(nir);
312
313	if (nir->info.stage == MESA_SHADER_VERTEX ||
314	    nir->info.stage == MESA_SHADER_GEOMETRY) {
315		NIR_PASS_V(nir, nir_lower_io_to_temporaries,
316			   nir_shader_get_entrypoint(nir), true, true);
317	} else if (nir->info.stage == MESA_SHADER_TESS_EVAL||
318		   nir->info.stage == MESA_SHADER_FRAGMENT) {
319		NIR_PASS_V(nir, nir_lower_io_to_temporaries,
320			   nir_shader_get_entrypoint(nir), true, false);
321	}
322
323	nir_split_var_copies(nir);
324
325	nir_lower_global_vars_to_local(nir);
326	nir_remove_dead_variables(nir, nir_var_local);
327	nir_lower_subgroups(nir, &(struct nir_lower_subgroups_options) {
328			.subgroup_size = 64,
329			.ballot_bit_size = 64,
330			.lower_to_scalar = 1,
331			.lower_subgroup_masks = 1,
332			.lower_shuffle = 1,
333			.lower_shuffle_to_32bit = 1,
334			.lower_vote_eq_to_ballot = 1,
335		});
336
337	nir_lower_load_const_to_scalar(nir);
338
339	if (!(flags & VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT))
340		radv_optimize_nir(nir, false, true);
341
342	/* We call nir_lower_var_copies() after the first radv_optimize_nir()
343	 * to remove any copies introduced by nir_opt_find_array_copies().
344	 */
345	nir_lower_var_copies(nir);
346
347	/* Indirect lowering must be called after the radv_optimize_nir() loop
348	 * has been called at least once. Otherwise indirect lowering can
349	 * bloat the instruction count of the loop and cause it to be
350	 * considered too large for unrolling.
351	 */
352	ac_lower_indirect_derefs(nir, device->physical_device->rad_info.chip_class);
353	radv_optimize_nir(nir, flags & VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT, false);
354
355	return nir;
356}
357
358void *
359radv_alloc_shader_memory(struct radv_device *device,
360			 struct radv_shader_variant *shader)
361{
362	mtx_lock(&device->shader_slab_mutex);
363	list_for_each_entry(struct radv_shader_slab, slab, &device->shader_slabs, slabs) {
364		uint64_t offset = 0;
365		list_for_each_entry(struct radv_shader_variant, s, &slab->shaders, slab_list) {
366			if (s->bo_offset - offset >= shader->code_size) {
367				shader->bo = slab->bo;
368				shader->bo_offset = offset;
369				list_addtail(&shader->slab_list, &s->slab_list);
370				mtx_unlock(&device->shader_slab_mutex);
371				return slab->ptr + offset;
372			}
373			offset = align_u64(s->bo_offset + s->code_size, 256);
374		}
375		if (slab->size - offset >= shader->code_size) {
376			shader->bo = slab->bo;
377			shader->bo_offset = offset;
378			list_addtail(&shader->slab_list, &slab->shaders);
379			mtx_unlock(&device->shader_slab_mutex);
380			return slab->ptr + offset;
381		}
382	}
383
384	mtx_unlock(&device->shader_slab_mutex);
385	struct radv_shader_slab *slab = calloc(1, sizeof(struct radv_shader_slab));
386
387	slab->size = 256 * 1024;
388	slab->bo = device->ws->buffer_create(device->ws, slab->size, 256,
389	                                     RADEON_DOMAIN_VRAM,
390					     RADEON_FLAG_NO_INTERPROCESS_SHARING |
391					     (device->physical_device->cpdma_prefetch_writes_memory ?
392					             0 : RADEON_FLAG_READ_ONLY));
393	slab->ptr = (char*)device->ws->buffer_map(slab->bo);
394	list_inithead(&slab->shaders);
395
396	mtx_lock(&device->shader_slab_mutex);
397	list_add(&slab->slabs, &device->shader_slabs);
398
399	shader->bo = slab->bo;
400	shader->bo_offset = 0;
401	list_add(&shader->slab_list, &slab->shaders);
402	mtx_unlock(&device->shader_slab_mutex);
403	return slab->ptr;
404}
405
406void
407radv_destroy_shader_slabs(struct radv_device *device)
408{
409	list_for_each_entry_safe(struct radv_shader_slab, slab, &device->shader_slabs, slabs) {
410		device->ws->buffer_destroy(slab->bo);
411		free(slab);
412	}
413	mtx_destroy(&device->shader_slab_mutex);
414}
415
416/* For the UMR disassembler. */
417#define DEBUGGER_END_OF_CODE_MARKER    0xbf9f0000 /* invalid instruction */
418#define DEBUGGER_NUM_MARKERS           5
419
420static unsigned
421radv_get_shader_binary_size(struct ac_shader_binary *binary)
422{
423	return binary->code_size + DEBUGGER_NUM_MARKERS * 4;
424}
425
426static void
427radv_fill_shader_variant(struct radv_device *device,
428			 struct radv_shader_variant *variant,
429			 struct ac_shader_binary *binary,
430			 gl_shader_stage stage)
431{
432	bool scratch_enabled = variant->config.scratch_bytes_per_wave > 0;
433	struct radv_shader_info *info = &variant->info.info;
434	unsigned vgpr_comp_cnt = 0;
435
436	variant->code_size = radv_get_shader_binary_size(binary);
437	variant->rsrc2 = S_00B12C_USER_SGPR(variant->info.num_user_sgprs) |
438			 S_00B12C_USER_SGPR_MSB(variant->info.num_user_sgprs >> 5) |
439			 S_00B12C_SCRATCH_EN(scratch_enabled) |
440			 S_00B12C_SO_BASE0_EN(!!info->so.strides[0]) |
441			 S_00B12C_SO_BASE1_EN(!!info->so.strides[1]) |
442			 S_00B12C_SO_BASE2_EN(!!info->so.strides[2]) |
443			 S_00B12C_SO_BASE3_EN(!!info->so.strides[3]) |
444			 S_00B12C_SO_EN(!!info->so.num_outputs);
445
446	variant->rsrc1 = S_00B848_VGPRS((variant->config.num_vgprs - 1) / 4) |
447		S_00B848_SGPRS((variant->config.num_sgprs - 1) / 8) |
448		S_00B848_DX10_CLAMP(1) |
449		S_00B848_FLOAT_MODE(variant->config.float_mode);
450
451	switch (stage) {
452	case MESA_SHADER_TESS_EVAL:
453		vgpr_comp_cnt = 3;
454		variant->rsrc2 |= S_00B12C_OC_LDS_EN(1);
455		break;
456	case MESA_SHADER_TESS_CTRL:
457		if (device->physical_device->rad_info.chip_class >= GFX9) {
458			vgpr_comp_cnt = variant->info.vs.vgpr_comp_cnt;
459		} else {
460			variant->rsrc2 |= S_00B12C_OC_LDS_EN(1);
461		}
462		break;
463	case MESA_SHADER_VERTEX:
464	case MESA_SHADER_GEOMETRY:
465		vgpr_comp_cnt = variant->info.vs.vgpr_comp_cnt;
466		break;
467	case MESA_SHADER_FRAGMENT:
468		break;
469	case MESA_SHADER_COMPUTE:
470		variant->rsrc2 |=
471			S_00B84C_TGID_X_EN(info->cs.uses_block_id[0]) |
472			S_00B84C_TGID_Y_EN(info->cs.uses_block_id[1]) |
473			S_00B84C_TGID_Z_EN(info->cs.uses_block_id[2]) |
474			S_00B84C_TIDIG_COMP_CNT(info->cs.uses_thread_id[2] ? 2 :
475						info->cs.uses_thread_id[1] ? 1 : 0) |
476			S_00B84C_TG_SIZE_EN(info->cs.uses_local_invocation_idx) |
477			S_00B84C_LDS_SIZE(variant->config.lds_size);
478		break;
479	default:
480		unreachable("unsupported shader type");
481		break;
482	}
483
484	if (device->physical_device->rad_info.chip_class >= GFX9 &&
485	    stage == MESA_SHADER_GEOMETRY) {
486		unsigned es_type = variant->info.gs.es_type;
487		unsigned gs_vgpr_comp_cnt, es_vgpr_comp_cnt;
488
489		if (es_type == MESA_SHADER_VERTEX) {
490			es_vgpr_comp_cnt = variant->info.vs.vgpr_comp_cnt;
491		} else if (es_type == MESA_SHADER_TESS_EVAL) {
492			es_vgpr_comp_cnt = 3;
493		} else {
494			unreachable("invalid shader ES type");
495		}
496
497		/* If offsets 4, 5 are used, GS_VGPR_COMP_CNT is ignored and
498		 * VGPR[0:4] are always loaded.
499		 */
500		if (info->uses_invocation_id) {
501			gs_vgpr_comp_cnt = 3; /* VGPR3 contains InvocationID. */
502		} else if (info->uses_prim_id) {
503			gs_vgpr_comp_cnt = 2; /* VGPR2 contains PrimitiveID. */
504		} else if (variant->info.gs.vertices_in >= 3) {
505			gs_vgpr_comp_cnt = 1; /* VGPR1 contains offsets 2, 3 */
506		} else {
507			gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0, 1 */
508		}
509
510		variant->rsrc1 |= S_00B228_GS_VGPR_COMP_CNT(gs_vgpr_comp_cnt);
511		variant->rsrc2 |= S_00B22C_ES_VGPR_COMP_CNT(es_vgpr_comp_cnt) |
512		                  S_00B22C_OC_LDS_EN(es_type == MESA_SHADER_TESS_EVAL);
513	} else if (device->physical_device->rad_info.chip_class >= GFX9 &&
514		   stage == MESA_SHADER_TESS_CTRL) {
515		variant->rsrc1 |= S_00B428_LS_VGPR_COMP_CNT(vgpr_comp_cnt);
516	} else {
517		variant->rsrc1 |= S_00B128_VGPR_COMP_CNT(vgpr_comp_cnt);
518	}
519
520	void *ptr = radv_alloc_shader_memory(device, variant);
521	memcpy(ptr, binary->code, binary->code_size);
522
523	/* Add end-of-code markers for the UMR disassembler. */
524       uint32_t *ptr32 = (uint32_t *)ptr + binary->code_size / 4;
525       for (unsigned i = 0; i < DEBUGGER_NUM_MARKERS; i++)
526		ptr32[i] = DEBUGGER_END_OF_CODE_MARKER;
527
528}
529
530static void radv_init_llvm_target()
531{
532	LLVMInitializeAMDGPUTargetInfo();
533	LLVMInitializeAMDGPUTarget();
534	LLVMInitializeAMDGPUTargetMC();
535	LLVMInitializeAMDGPUAsmPrinter();
536
537	/* For inline assembly. */
538	LLVMInitializeAMDGPUAsmParser();
539
540	/* Workaround for bug in llvm 4.0 that causes image intrinsics
541	 * to disappear.
542	 * https://reviews.llvm.org/D26348
543	 *
544	 * Workaround for bug in llvm that causes the GPU to hang in presence
545	 * of nested loops because there is an exec mask issue. The proper
546	 * solution is to fix LLVM but this might require a bunch of work.
547	 * https://bugs.llvm.org/show_bug.cgi?id=37744
548	 *
549	 * "mesa" is the prefix for error messages.
550	 */
551	const char *argv[3] = { "mesa", "-simplifycfg-sink-common=false",
552				"-amdgpu-skip-threshold=1" };
553	LLVMParseCommandLineOptions(3, argv, NULL);
554}
555
556static once_flag radv_init_llvm_target_once_flag = ONCE_FLAG_INIT;
557
558static void radv_init_llvm_once(void)
559{
560	call_once(&radv_init_llvm_target_once_flag, radv_init_llvm_target);
561}
562
563static struct radv_shader_variant *
564shader_variant_create(struct radv_device *device,
565		      struct radv_shader_module *module,
566		      struct nir_shader * const *shaders,
567		      int shader_count,
568		      gl_shader_stage stage,
569		      struct radv_nir_compiler_options *options,
570		      bool gs_copy_shader,
571		      void **code_out,
572		      unsigned *code_size_out)
573{
574	enum radeon_family chip_family = device->physical_device->rad_info.family;
575	enum ac_target_machine_options tm_options = 0;
576	struct radv_shader_variant *variant;
577	struct ac_shader_binary binary;
578	struct ac_llvm_compiler ac_llvm;
579	bool thread_compiler;
580	variant = calloc(1, sizeof(struct radv_shader_variant));
581	if (!variant)
582		return NULL;
583
584	options->family = chip_family;
585	options->chip_class = device->physical_device->rad_info.chip_class;
586	options->dump_shader = radv_can_dump_shader(device, module, gs_copy_shader);
587	options->dump_preoptir = options->dump_shader &&
588				 device->instance->debug_flags & RADV_DEBUG_PREOPTIR;
589	options->record_llvm_ir = device->keep_shader_info;
590	options->check_ir = device->instance->debug_flags & RADV_DEBUG_CHECKIR;
591	options->tess_offchip_block_dw_size = device->tess_offchip_block_dw_size;
592	options->address32_hi = device->physical_device->rad_info.address32_hi;
593
594	if (options->supports_spill)
595		tm_options |= AC_TM_SUPPORTS_SPILL;
596	if (device->instance->perftest_flags & RADV_PERFTEST_SISCHED)
597		tm_options |= AC_TM_SISCHED;
598	if (options->check_ir)
599		tm_options |= AC_TM_CHECK_IR;
600
601	thread_compiler = !(device->instance->debug_flags & RADV_DEBUG_NOTHREADLLVM);
602	radv_init_llvm_once();
603	radv_init_llvm_compiler(&ac_llvm, false,
604				thread_compiler,
605				chip_family, tm_options);
606	if (gs_copy_shader) {
607		assert(shader_count == 1);
608		radv_compile_gs_copy_shader(&ac_llvm, *shaders, &binary,
609					    &variant->config, &variant->info,
610					    options);
611	} else {
612		radv_compile_nir_shader(&ac_llvm, &binary, &variant->config,
613					&variant->info, shaders, shader_count,
614					options);
615	}
616
617	radv_destroy_llvm_compiler(&ac_llvm, thread_compiler);
618
619	radv_fill_shader_variant(device, variant, &binary, stage);
620
621	if (code_out) {
622		*code_out = binary.code;
623		*code_size_out = binary.code_size;
624	} else
625		free(binary.code);
626	free(binary.config);
627	free(binary.rodata);
628	free(binary.global_symbol_offsets);
629	free(binary.relocs);
630	variant->ref_count = 1;
631
632	if (device->keep_shader_info) {
633		variant->disasm_string = binary.disasm_string;
634		variant->llvm_ir_string = binary.llvm_ir_string;
635		if (!gs_copy_shader && !module->nir) {
636			variant->nir = *shaders;
637			variant->spirv = (uint32_t *)module->data;
638			variant->spirv_size = module->size;
639		}
640	} else {
641		free(binary.disasm_string);
642	}
643
644	return variant;
645}
646
647struct radv_shader_variant *
648radv_shader_variant_create(struct radv_device *device,
649			   struct radv_shader_module *module,
650			   struct nir_shader *const *shaders,
651			   int shader_count,
652			   struct radv_pipeline_layout *layout,
653			   const struct radv_shader_variant_key *key,
654			   void **code_out,
655			   unsigned *code_size_out)
656{
657	struct radv_nir_compiler_options options = {0};
658
659	options.layout = layout;
660	if (key)
661		options.key = *key;
662
663	options.unsafe_math = !!(device->instance->debug_flags & RADV_DEBUG_UNSAFE_MATH);
664	options.supports_spill = true;
665
666	return shader_variant_create(device, module, shaders, shader_count, shaders[shader_count - 1]->info.stage,
667				     &options, false, code_out, code_size_out);
668}
669
670struct radv_shader_variant *
671radv_create_gs_copy_shader(struct radv_device *device,
672			   struct nir_shader *shader,
673			   void **code_out,
674			   unsigned *code_size_out,
675			   bool multiview)
676{
677	struct radv_nir_compiler_options options = {0};
678
679	options.key.has_multiview_view_index = multiview;
680
681	return shader_variant_create(device, NULL, &shader, 1, MESA_SHADER_VERTEX,
682				     &options, true, code_out, code_size_out);
683}
684
685void
686radv_shader_variant_destroy(struct radv_device *device,
687			    struct radv_shader_variant *variant)
688{
689	if (!p_atomic_dec_zero(&variant->ref_count))
690		return;
691
692	mtx_lock(&device->shader_slab_mutex);
693	list_del(&variant->slab_list);
694	mtx_unlock(&device->shader_slab_mutex);
695
696	ralloc_free(variant->nir);
697	free(variant->disasm_string);
698	free(variant->llvm_ir_string);
699	free(variant);
700}
701
702const char *
703radv_get_shader_name(struct radv_shader_variant *var, gl_shader_stage stage)
704{
705	switch (stage) {
706	case MESA_SHADER_VERTEX: return var->info.vs.as_ls ? "Vertex Shader as LS" : var->info.vs.as_es ? "Vertex Shader as ES" : "Vertex Shader as VS";
707	case MESA_SHADER_GEOMETRY: return "Geometry Shader";
708	case MESA_SHADER_FRAGMENT: return "Pixel Shader";
709	case MESA_SHADER_COMPUTE: return "Compute Shader";
710	case MESA_SHADER_TESS_CTRL: return "Tessellation Control Shader";
711	case MESA_SHADER_TESS_EVAL: return var->info.tes.as_es ? "Tessellation Evaluation Shader as ES" : "Tessellation Evaluation Shader as VS";
712	default:
713		return "Unknown shader";
714	};
715}
716
717static void
718generate_shader_stats(struct radv_device *device,
719		      struct radv_shader_variant *variant,
720		      gl_shader_stage stage,
721		      struct _mesa_string_buffer *buf)
722{
723	unsigned lds_increment = device->physical_device->rad_info.chip_class >= CIK ? 512 : 256;
724	struct ac_shader_config *conf;
725	unsigned max_simd_waves;
726	unsigned lds_per_wave = 0;
727
728	max_simd_waves = ac_get_max_simd_waves(device->physical_device->rad_info.family);
729
730	conf = &variant->config;
731
732	if (stage == MESA_SHADER_FRAGMENT) {
733		lds_per_wave = conf->lds_size * lds_increment +
734			       align(variant->info.fs.num_interp * 48,
735				     lds_increment);
736	}
737
738	if (conf->num_sgprs)
739		max_simd_waves =
740			MIN2(max_simd_waves,
741			     radv_get_num_physical_sgprs(device->physical_device) / conf->num_sgprs);
742
743	if (conf->num_vgprs)
744		max_simd_waves =
745			MIN2(max_simd_waves,
746			     RADV_NUM_PHYSICAL_VGPRS / conf->num_vgprs);
747
748	/* LDS is 64KB per CU (4 SIMDs), divided into 16KB blocks per SIMD
749	 * that PS can use.
750	 */
751	if (lds_per_wave)
752		max_simd_waves = MIN2(max_simd_waves, 16384 / lds_per_wave);
753
754	if (stage == MESA_SHADER_FRAGMENT) {
755		_mesa_string_buffer_printf(buf, "*** SHADER CONFIG ***\n"
756					   "SPI_PS_INPUT_ADDR = 0x%04x\n"
757					   "SPI_PS_INPUT_ENA  = 0x%04x\n",
758					   conf->spi_ps_input_addr, conf->spi_ps_input_ena);
759	}
760
761	_mesa_string_buffer_printf(buf, "*** SHADER STATS ***\n"
762				   "SGPRS: %d\n"
763				   "VGPRS: %d\n"
764				   "Spilled SGPRs: %d\n"
765				   "Spilled VGPRs: %d\n"
766				   "PrivMem VGPRS: %d\n"
767				   "Code Size: %d bytes\n"
768				   "LDS: %d blocks\n"
769				   "Scratch: %d bytes per wave\n"
770				   "Max Waves: %d\n"
771				   "********************\n\n\n",
772				   conf->num_sgprs, conf->num_vgprs,
773				   conf->spilled_sgprs, conf->spilled_vgprs,
774				   variant->info.private_mem_vgprs, variant->code_size,
775				   conf->lds_size, conf->scratch_bytes_per_wave,
776				   max_simd_waves);
777}
778
779void
780radv_shader_dump_stats(struct radv_device *device,
781		       struct radv_shader_variant *variant,
782		       gl_shader_stage stage,
783		       FILE *file)
784{
785	struct _mesa_string_buffer *buf = _mesa_string_buffer_create(NULL, 256);
786
787	generate_shader_stats(device, variant, stage, buf);
788
789	fprintf(file, "\n%s:\n", radv_get_shader_name(variant, stage));
790	fprintf(file, "%s", buf->buf);
791
792	_mesa_string_buffer_destroy(buf);
793}
794
795VkResult
796radv_GetShaderInfoAMD(VkDevice _device,
797		      VkPipeline _pipeline,
798		      VkShaderStageFlagBits shaderStage,
799		      VkShaderInfoTypeAMD infoType,
800		      size_t* pInfoSize,
801		      void* pInfo)
802{
803	RADV_FROM_HANDLE(radv_device, device, _device);
804	RADV_FROM_HANDLE(radv_pipeline, pipeline, _pipeline);
805	gl_shader_stage stage = vk_to_mesa_shader_stage(shaderStage);
806	struct radv_shader_variant *variant = pipeline->shaders[stage];
807	struct _mesa_string_buffer *buf;
808	VkResult result = VK_SUCCESS;
809
810	/* Spec doesn't indicate what to do if the stage is invalid, so just
811	 * return no info for this. */
812	if (!variant)
813		return vk_error(device->instance, VK_ERROR_FEATURE_NOT_PRESENT);
814
815	switch (infoType) {
816	case VK_SHADER_INFO_TYPE_STATISTICS_AMD:
817		if (!pInfo) {
818			*pInfoSize = sizeof(VkShaderStatisticsInfoAMD);
819		} else {
820			unsigned lds_multiplier = device->physical_device->rad_info.chip_class >= CIK ? 512 : 256;
821			struct ac_shader_config *conf = &variant->config;
822
823			VkShaderStatisticsInfoAMD statistics = {};
824			statistics.shaderStageMask = shaderStage;
825			statistics.numPhysicalVgprs = RADV_NUM_PHYSICAL_VGPRS;
826			statistics.numPhysicalSgprs = radv_get_num_physical_sgprs(device->physical_device);
827			statistics.numAvailableSgprs = statistics.numPhysicalSgprs;
828
829			if (stage == MESA_SHADER_COMPUTE) {
830				unsigned *local_size = variant->nir->info.cs.local_size;
831				unsigned workgroup_size = local_size[0] * local_size[1] * local_size[2];
832
833				statistics.numAvailableVgprs = statistics.numPhysicalVgprs /
834							       ceil((double)workgroup_size / statistics.numPhysicalVgprs);
835
836				statistics.computeWorkGroupSize[0] = local_size[0];
837				statistics.computeWorkGroupSize[1] = local_size[1];
838				statistics.computeWorkGroupSize[2] = local_size[2];
839			} else {
840				statistics.numAvailableVgprs = statistics.numPhysicalVgprs;
841			}
842
843			statistics.resourceUsage.numUsedVgprs = conf->num_vgprs;
844			statistics.resourceUsage.numUsedSgprs = conf->num_sgprs;
845			statistics.resourceUsage.ldsSizePerLocalWorkGroup = 32768;
846			statistics.resourceUsage.ldsUsageSizeInBytes = conf->lds_size * lds_multiplier;
847			statistics.resourceUsage.scratchMemUsageInBytes = conf->scratch_bytes_per_wave;
848
849			size_t size = *pInfoSize;
850			*pInfoSize = sizeof(statistics);
851
852			memcpy(pInfo, &statistics, MIN2(size, *pInfoSize));
853
854			if (size < *pInfoSize)
855				result = VK_INCOMPLETE;
856		}
857
858		break;
859	case VK_SHADER_INFO_TYPE_DISASSEMBLY_AMD:
860		buf = _mesa_string_buffer_create(NULL, 1024);
861
862		_mesa_string_buffer_printf(buf, "%s:\n", radv_get_shader_name(variant, stage));
863		_mesa_string_buffer_printf(buf, "%s\n\n", variant->disasm_string);
864		generate_shader_stats(device, variant, stage, buf);
865
866		/* Need to include the null terminator. */
867		size_t length = buf->length + 1;
868
869		if (!pInfo) {
870			*pInfoSize = length;
871		} else {
872			size_t size = *pInfoSize;
873			*pInfoSize = length;
874
875			memcpy(pInfo, buf->buf, MIN2(size, length));
876
877			if (size < length)
878				result = VK_INCOMPLETE;
879		}
880
881		_mesa_string_buffer_destroy(buf);
882		break;
883	default:
884		/* VK_SHADER_INFO_TYPE_BINARY_AMD unimplemented for now. */
885		result = VK_ERROR_FEATURE_NOT_PRESENT;
886		break;
887	}
888
889	return result;
890}
891