cafe5668f1f45440d7123cc67337889679a55376
[mesa.git] / src / intel / vulkan / anv_pipeline.c
1 /*
2 * Copyright © 2015 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #include <assert.h>
25 #include <stdbool.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29
30 #include "util/mesa-sha1.h"
31 #include "util/os_time.h"
32 #include "common/gen_l3_config.h"
33 #include "common/gen_disasm.h"
34 #include "anv_private.h"
35 #include "compiler/brw_nir.h"
36 #include "anv_nir.h"
37 #include "nir/nir_xfb_info.h"
38 #include "spirv/nir_spirv.h"
39 #include "vk_util.h"
40
41 /* Needed for SWIZZLE macros */
42 #include "program/prog_instruction.h"
43
44 // Shader functions
45
46 VkResult anv_CreateShaderModule(
47 VkDevice _device,
48 const VkShaderModuleCreateInfo* pCreateInfo,
49 const VkAllocationCallbacks* pAllocator,
50 VkShaderModule* pShaderModule)
51 {
52 ANV_FROM_HANDLE(anv_device, device, _device);
53 struct anv_shader_module *module;
54
55 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
56 assert(pCreateInfo->flags == 0);
57
58 module = vk_alloc2(&device->vk.alloc, pAllocator,
59 sizeof(*module) + pCreateInfo->codeSize, 8,
60 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
61 if (module == NULL)
62 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
63
64 vk_object_base_init(&device->vk, &module->base,
65 VK_OBJECT_TYPE_SHADER_MODULE);
66 module->size = pCreateInfo->codeSize;
67 memcpy(module->data, pCreateInfo->pCode, module->size);
68
69 _mesa_sha1_compute(module->data, module->size, module->sha1);
70
71 *pShaderModule = anv_shader_module_to_handle(module);
72
73 return VK_SUCCESS;
74 }
75
76 void anv_DestroyShaderModule(
77 VkDevice _device,
78 VkShaderModule _module,
79 const VkAllocationCallbacks* pAllocator)
80 {
81 ANV_FROM_HANDLE(anv_device, device, _device);
82 ANV_FROM_HANDLE(anv_shader_module, module, _module);
83
84 if (!module)
85 return;
86
87 vk_object_base_finish(&module->base);
88 vk_free2(&device->vk.alloc, pAllocator, module);
89 }
90
91 #define SPIR_V_MAGIC_NUMBER 0x07230203
92
93 struct anv_spirv_debug_data {
94 struct anv_device *device;
95 const struct anv_shader_module *module;
96 };
97
98 static void anv_spirv_nir_debug(void *private_data,
99 enum nir_spirv_debug_level level,
100 size_t spirv_offset,
101 const char *message)
102 {
103 struct anv_spirv_debug_data *debug_data = private_data;
104 struct anv_instance *instance = debug_data->device->physical->instance;
105
106 static const VkDebugReportFlagsEXT vk_flags[] = {
107 [NIR_SPIRV_DEBUG_LEVEL_INFO] = VK_DEBUG_REPORT_INFORMATION_BIT_EXT,
108 [NIR_SPIRV_DEBUG_LEVEL_WARNING] = VK_DEBUG_REPORT_WARNING_BIT_EXT,
109 [NIR_SPIRV_DEBUG_LEVEL_ERROR] = VK_DEBUG_REPORT_ERROR_BIT_EXT,
110 };
111 char buffer[256];
112
113 snprintf(buffer, sizeof(buffer), "SPIR-V offset %lu: %s", (unsigned long) spirv_offset, message);
114
115 vk_debug_report(&instance->debug_report_callbacks,
116 vk_flags[level],
117 VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
118 (uint64_t) (uintptr_t) debug_data->module,
119 0, 0, "anv", buffer);
120 }
121
122 /* Eventually, this will become part of anv_CreateShader. Unfortunately,
123 * we can't do that yet because we don't have the ability to copy nir.
124 */
125 static nir_shader *
126 anv_shader_compile_to_nir(struct anv_device *device,
127 void *mem_ctx,
128 const struct anv_shader_module *module,
129 const char *entrypoint_name,
130 gl_shader_stage stage,
131 const VkSpecializationInfo *spec_info)
132 {
133 const struct anv_physical_device *pdevice = device->physical;
134 const struct brw_compiler *compiler = pdevice->compiler;
135 const nir_shader_compiler_options *nir_options =
136 compiler->glsl_compiler_options[stage].NirOptions;
137
138 uint32_t *spirv = (uint32_t *) module->data;
139 assert(spirv[0] == SPIR_V_MAGIC_NUMBER);
140 assert(module->size % 4 == 0);
141
142 uint32_t num_spec_entries = 0;
143 struct nir_spirv_specialization *spec_entries = NULL;
144 if (spec_info && spec_info->mapEntryCount > 0) {
145 num_spec_entries = spec_info->mapEntryCount;
146 spec_entries = calloc(num_spec_entries, sizeof(*spec_entries));
147 for (uint32_t i = 0; i < num_spec_entries; i++) {
148 VkSpecializationMapEntry entry = spec_info->pMapEntries[i];
149 const void *data = spec_info->pData + entry.offset;
150 assert(data + entry.size <= spec_info->pData + spec_info->dataSize);
151
152 spec_entries[i].id = spec_info->pMapEntries[i].constantID;
153 switch (entry.size) {
154 case 8:
155 spec_entries[i].value.u64 = *(const uint64_t *)data;
156 break;
157 case 4:
158 spec_entries[i].value.u32 = *(const uint32_t *)data;
159 break;
160 case 2:
161 spec_entries[i].value.u16 = *(const uint16_t *)data;
162 break;
163 case 1:
164 spec_entries[i].value.u8 = *(const uint8_t *)data;
165 break;
166 default:
167 assert(!"Invalid spec constant size");
168 break;
169 }
170 }
171 }
172
173 struct anv_spirv_debug_data spirv_debug_data = {
174 .device = device,
175 .module = module,
176 };
177 struct spirv_to_nir_options spirv_options = {
178 .frag_coord_is_sysval = true,
179 .caps = {
180 .demote_to_helper_invocation = true,
181 .derivative_group = true,
182 .descriptor_array_dynamic_indexing = true,
183 .descriptor_array_non_uniform_indexing = true,
184 .descriptor_indexing = true,
185 .device_group = true,
186 .draw_parameters = true,
187 .float16 = pdevice->info.gen >= 8,
188 .float64 = pdevice->info.gen >= 8,
189 .fragment_shader_sample_interlock = pdevice->info.gen >= 9,
190 .fragment_shader_pixel_interlock = pdevice->info.gen >= 9,
191 .geometry_streams = true,
192 .image_write_without_format = true,
193 .int8 = pdevice->info.gen >= 8,
194 .int16 = pdevice->info.gen >= 8,
195 .int64 = pdevice->info.gen >= 8,
196 .int64_atomics = pdevice->info.gen >= 9 && pdevice->use_softpin,
197 .integer_functions2 = pdevice->info.gen >= 8,
198 .min_lod = true,
199 .multiview = true,
200 .physical_storage_buffer_address = pdevice->has_a64_buffer_access,
201 .post_depth_coverage = pdevice->info.gen >= 9,
202 .runtime_descriptor_array = true,
203 .float_controls = pdevice->info.gen >= 8,
204 .shader_clock = true,
205 .shader_viewport_index_layer = true,
206 .stencil_export = pdevice->info.gen >= 9,
207 .storage_8bit = pdevice->info.gen >= 8,
208 .storage_16bit = pdevice->info.gen >= 8,
209 .subgroup_arithmetic = true,
210 .subgroup_basic = true,
211 .subgroup_ballot = true,
212 .subgroup_quad = true,
213 .subgroup_shuffle = true,
214 .subgroup_vote = true,
215 .tessellation = true,
216 .transform_feedback = pdevice->info.gen >= 8,
217 .variable_pointers = true,
218 .vk_memory_model = true,
219 .vk_memory_model_device_scope = true,
220 },
221 .ubo_addr_format = nir_address_format_32bit_index_offset,
222 .ssbo_addr_format =
223 anv_nir_ssbo_addr_format(pdevice, device->robust_buffer_access),
224 .phys_ssbo_addr_format = nir_address_format_64bit_global,
225 .push_const_addr_format = nir_address_format_logical,
226
227 /* TODO: Consider changing this to an address format that has the NULL
228 * pointer equals to 0. That might be a better format to play nice
229 * with certain code / code generators.
230 */
231 .shared_addr_format = nir_address_format_32bit_offset,
232 .debug = {
233 .func = anv_spirv_nir_debug,
234 .private_data = &spirv_debug_data,
235 },
236 };
237
238
239 nir_shader *nir =
240 spirv_to_nir(spirv, module->size / 4,
241 spec_entries, num_spec_entries,
242 stage, entrypoint_name, &spirv_options, nir_options);
243 assert(nir->info.stage == stage);
244 nir_validate_shader(nir, "after spirv_to_nir");
245 ralloc_steal(mem_ctx, nir);
246
247 free(spec_entries);
248
249 if (unlikely(INTEL_DEBUG & intel_debug_flag_for_shader_stage(stage))) {
250 fprintf(stderr, "NIR (from SPIR-V) for %s shader:\n",
251 gl_shader_stage_name(stage));
252 nir_print_shader(nir, stderr);
253 }
254
255 /* We have to lower away local constant initializers right before we
256 * inline functions. That way they get properly initialized at the top
257 * of the function and not at the top of its caller.
258 */
259 NIR_PASS_V(nir, nir_lower_variable_initializers, nir_var_function_temp);
260 NIR_PASS_V(nir, nir_lower_returns);
261 NIR_PASS_V(nir, nir_inline_functions);
262 NIR_PASS_V(nir, nir_copy_prop);
263 NIR_PASS_V(nir, nir_opt_deref);
264
265 /* Pick off the single entrypoint that we want */
266 foreach_list_typed_safe(nir_function, func, node, &nir->functions) {
267 if (!func->is_entrypoint)
268 exec_node_remove(&func->node);
269 }
270 assert(exec_list_length(&nir->functions) == 1);
271
272 /* Now that we've deleted all but the main function, we can go ahead and
273 * lower the rest of the constant initializers. We do this here so that
274 * nir_remove_dead_variables and split_per_member_structs below see the
275 * corresponding stores.
276 */
277 NIR_PASS_V(nir, nir_lower_variable_initializers, ~0);
278
279 /* Split member structs. We do this before lower_io_to_temporaries so that
280 * it doesn't lower system values to temporaries by accident.
281 */
282 NIR_PASS_V(nir, nir_split_var_copies);
283 NIR_PASS_V(nir, nir_split_per_member_structs);
284
285 NIR_PASS_V(nir, nir_remove_dead_variables,
286 nir_var_shader_in | nir_var_shader_out | nir_var_system_value,
287 NULL);
288
289 NIR_PASS_V(nir, nir_propagate_invariant);
290 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
291 nir_shader_get_entrypoint(nir), true, false);
292
293 NIR_PASS_V(nir, nir_lower_frexp);
294
295 /* Vulkan uses the separate-shader linking model */
296 nir->info.separate_shader = true;
297
298 brw_preprocess_nir(compiler, nir, NULL);
299
300 return nir;
301 }
302
303 VkResult
304 anv_pipeline_init(struct anv_pipeline *pipeline,
305 struct anv_device *device,
306 enum anv_pipeline_type type,
307 VkPipelineCreateFlags flags,
308 const VkAllocationCallbacks *pAllocator)
309 {
310 VkResult result;
311
312 memset(pipeline, 0, sizeof(*pipeline));
313
314 vk_object_base_init(&device->vk, &pipeline->base,
315 VK_OBJECT_TYPE_PIPELINE);
316 pipeline->device = device;
317
318 /* It's the job of the child class to provide actual backing storage for
319 * the batch by setting batch.start, batch.next, and batch.end.
320 */
321 pipeline->batch.alloc = pAllocator ? pAllocator : &device->vk.alloc;
322 pipeline->batch.relocs = &pipeline->batch_relocs;
323 pipeline->batch.status = VK_SUCCESS;
324
325 result = anv_reloc_list_init(&pipeline->batch_relocs,
326 pipeline->batch.alloc);
327 if (result != VK_SUCCESS)
328 return result;
329
330 pipeline->mem_ctx = ralloc_context(NULL);
331
332 pipeline->type = type;
333 pipeline->flags = flags;
334
335 util_dynarray_init(&pipeline->executables, pipeline->mem_ctx);
336
337 return VK_SUCCESS;
338 }
339
340 void
341 anv_pipeline_finish(struct anv_pipeline *pipeline,
342 struct anv_device *device,
343 const VkAllocationCallbacks *pAllocator)
344 {
345 anv_reloc_list_finish(&pipeline->batch_relocs,
346 pAllocator ? pAllocator : &device->vk.alloc);
347 ralloc_free(pipeline->mem_ctx);
348 vk_object_base_finish(&pipeline->base);
349 }
350
351 void anv_DestroyPipeline(
352 VkDevice _device,
353 VkPipeline _pipeline,
354 const VkAllocationCallbacks* pAllocator)
355 {
356 ANV_FROM_HANDLE(anv_device, device, _device);
357 ANV_FROM_HANDLE(anv_pipeline, pipeline, _pipeline);
358
359 if (!pipeline)
360 return;
361
362 switch (pipeline->type) {
363 case ANV_PIPELINE_GRAPHICS: {
364 struct anv_graphics_pipeline *gfx_pipeline =
365 anv_pipeline_to_graphics(pipeline);
366
367 if (gfx_pipeline->blend_state.map)
368 anv_state_pool_free(&device->dynamic_state_pool, gfx_pipeline->blend_state);
369
370 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
371 if (gfx_pipeline->shaders[s])
372 anv_shader_bin_unref(device, gfx_pipeline->shaders[s]);
373 }
374 break;
375 }
376
377 case ANV_PIPELINE_COMPUTE: {
378 struct anv_compute_pipeline *compute_pipeline =
379 anv_pipeline_to_compute(pipeline);
380
381 if (compute_pipeline->cs)
382 anv_shader_bin_unref(device, compute_pipeline->cs);
383
384 break;
385 }
386
387 default:
388 unreachable("invalid pipeline type");
389 }
390
391 anv_pipeline_finish(pipeline, device, pAllocator);
392 vk_free2(&device->vk.alloc, pAllocator, pipeline);
393 }
394
395 static const uint32_t vk_to_gen_primitive_type[] = {
396 [VK_PRIMITIVE_TOPOLOGY_POINT_LIST] = _3DPRIM_POINTLIST,
397 [VK_PRIMITIVE_TOPOLOGY_LINE_LIST] = _3DPRIM_LINELIST,
398 [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP] = _3DPRIM_LINESTRIP,
399 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST] = _3DPRIM_TRILIST,
400 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP] = _3DPRIM_TRISTRIP,
401 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN] = _3DPRIM_TRIFAN,
402 [VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY] = _3DPRIM_LINELIST_ADJ,
403 [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY] = _3DPRIM_LINESTRIP_ADJ,
404 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY] = _3DPRIM_TRILIST_ADJ,
405 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY] = _3DPRIM_TRISTRIP_ADJ,
406 };
407
408 static void
409 populate_sampler_prog_key(const struct gen_device_info *devinfo,
410 struct brw_sampler_prog_key_data *key)
411 {
412 /* Almost all multisampled textures are compressed. The only time when we
413 * don't compress a multisampled texture is for 16x MSAA with a surface
414 * width greater than 8k which is a bit of an edge case. Since the sampler
415 * just ignores the MCS parameter to ld2ms when MCS is disabled, it's safe
416 * to tell the compiler to always assume compression.
417 */
418 key->compressed_multisample_layout_mask = ~0;
419
420 /* SkyLake added support for 16x MSAA. With this came a new message for
421 * reading from a 16x MSAA surface with compression. The new message was
422 * needed because now the MCS data is 64 bits instead of 32 or lower as is
423 * the case for 8x, 4x, and 2x. The key->msaa_16 bit-field controls which
424 * message we use. Fortunately, the 16x message works for 8x, 4x, and 2x
425 * so we can just use it unconditionally. This may not be quite as
426 * efficient but it saves us from recompiling.
427 */
428 if (devinfo->gen >= 9)
429 key->msaa_16 = ~0;
430
431 /* XXX: Handle texture swizzle on HSW- */
432 for (int i = 0; i < MAX_SAMPLERS; i++) {
433 /* Assume color sampler, no swizzling. (Works for BDW+) */
434 key->swizzles[i] = SWIZZLE_XYZW;
435 }
436 }
437
438 static void
439 populate_base_prog_key(const struct gen_device_info *devinfo,
440 VkPipelineShaderStageCreateFlags flags,
441 struct brw_base_prog_key *key)
442 {
443 if (flags & VK_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT)
444 key->subgroup_size_type = BRW_SUBGROUP_SIZE_VARYING;
445 else
446 key->subgroup_size_type = BRW_SUBGROUP_SIZE_API_CONSTANT;
447
448 populate_sampler_prog_key(devinfo, &key->tex);
449 }
450
451 static void
452 populate_vs_prog_key(const struct gen_device_info *devinfo,
453 VkPipelineShaderStageCreateFlags flags,
454 struct brw_vs_prog_key *key)
455 {
456 memset(key, 0, sizeof(*key));
457
458 populate_base_prog_key(devinfo, flags, &key->base);
459
460 /* XXX: Handle vertex input work-arounds */
461
462 /* XXX: Handle sampler_prog_key */
463 }
464
465 static void
466 populate_tcs_prog_key(const struct gen_device_info *devinfo,
467 VkPipelineShaderStageCreateFlags flags,
468 unsigned input_vertices,
469 struct brw_tcs_prog_key *key)
470 {
471 memset(key, 0, sizeof(*key));
472
473 populate_base_prog_key(devinfo, flags, &key->base);
474
475 key->input_vertices = input_vertices;
476 }
477
478 static void
479 populate_tes_prog_key(const struct gen_device_info *devinfo,
480 VkPipelineShaderStageCreateFlags flags,
481 struct brw_tes_prog_key *key)
482 {
483 memset(key, 0, sizeof(*key));
484
485 populate_base_prog_key(devinfo, flags, &key->base);
486 }
487
488 static void
489 populate_gs_prog_key(const struct gen_device_info *devinfo,
490 VkPipelineShaderStageCreateFlags flags,
491 struct brw_gs_prog_key *key)
492 {
493 memset(key, 0, sizeof(*key));
494
495 populate_base_prog_key(devinfo, flags, &key->base);
496 }
497
498 static void
499 populate_wm_prog_key(const struct gen_device_info *devinfo,
500 VkPipelineShaderStageCreateFlags flags,
501 const struct anv_subpass *subpass,
502 const VkPipelineMultisampleStateCreateInfo *ms_info,
503 struct brw_wm_prog_key *key)
504 {
505 memset(key, 0, sizeof(*key));
506
507 populate_base_prog_key(devinfo, flags, &key->base);
508
509 /* We set this to 0 here and set to the actual value before we call
510 * brw_compile_fs.
511 */
512 key->input_slots_valid = 0;
513
514 /* Vulkan doesn't specify a default */
515 key->high_quality_derivatives = false;
516
517 /* XXX Vulkan doesn't appear to specify */
518 key->clamp_fragment_color = false;
519
520 key->ignore_sample_mask_out = false;
521
522 assert(subpass->color_count <= MAX_RTS);
523 for (uint32_t i = 0; i < subpass->color_count; i++) {
524 if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED)
525 key->color_outputs_valid |= (1 << i);
526 }
527
528 key->nr_color_regions = subpass->color_count;
529
530 /* To reduce possible shader recompilations we would need to know if
531 * there is a SampleMask output variable to compute if we should emit
532 * code to workaround the issue that hardware disables alpha to coverage
533 * when there is SampleMask output.
534 */
535 key->alpha_to_coverage = ms_info && ms_info->alphaToCoverageEnable;
536
537 /* Vulkan doesn't support fixed-function alpha test */
538 key->alpha_test_replicate_alpha = false;
539
540 if (ms_info) {
541 /* We should probably pull this out of the shader, but it's fairly
542 * harmless to compute it and then let dead-code take care of it.
543 */
544 if (ms_info->rasterizationSamples > 1) {
545 key->persample_interp = ms_info->sampleShadingEnable &&
546 (ms_info->minSampleShading * ms_info->rasterizationSamples) > 1;
547 key->multisample_fbo = true;
548 }
549
550 key->frag_coord_adds_sample_pos = key->persample_interp;
551 }
552 }
553
554 static void
555 populate_cs_prog_key(const struct gen_device_info *devinfo,
556 VkPipelineShaderStageCreateFlags flags,
557 const VkPipelineShaderStageRequiredSubgroupSizeCreateInfoEXT *rss_info,
558 struct brw_cs_prog_key *key)
559 {
560 memset(key, 0, sizeof(*key));
561
562 populate_base_prog_key(devinfo, flags, &key->base);
563
564 if (rss_info) {
565 assert(key->base.subgroup_size_type != BRW_SUBGROUP_SIZE_VARYING);
566
567 /* These enum values are expressly chosen to be equal to the subgroup
568 * size that they require.
569 */
570 assert(rss_info->requiredSubgroupSize == 8 ||
571 rss_info->requiredSubgroupSize == 16 ||
572 rss_info->requiredSubgroupSize == 32);
573 key->base.subgroup_size_type = rss_info->requiredSubgroupSize;
574 } else if (flags & VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT_EXT) {
575 /* If the client expressly requests full subgroups and they don't
576 * specify a subgroup size, we need to pick one. If they're requested
577 * varying subgroup sizes, we set it to UNIFORM and let the back-end
578 * compiler pick. Otherwise, we specify the API value of 32.
579 * Performance will likely be terrible in this case but there's nothing
580 * we can do about that. The client should have chosen a size.
581 */
582 if (flags & VK_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT)
583 key->base.subgroup_size_type = BRW_SUBGROUP_SIZE_UNIFORM;
584 else
585 key->base.subgroup_size_type = BRW_SUBGROUP_SIZE_REQUIRE_32;
586 }
587 }
588
589 struct anv_pipeline_stage {
590 gl_shader_stage stage;
591
592 const struct anv_shader_module *module;
593 const char *entrypoint;
594 const VkSpecializationInfo *spec_info;
595
596 unsigned char shader_sha1[20];
597
598 union brw_any_prog_key key;
599
600 struct {
601 gl_shader_stage stage;
602 unsigned char sha1[20];
603 } cache_key;
604
605 nir_shader *nir;
606
607 struct anv_pipeline_binding surface_to_descriptor[256];
608 struct anv_pipeline_binding sampler_to_descriptor[256];
609 struct anv_pipeline_bind_map bind_map;
610
611 union brw_any_prog_data prog_data;
612
613 uint32_t num_stats;
614 struct brw_compile_stats stats[3];
615 char *disasm[3];
616
617 VkPipelineCreationFeedbackEXT feedback;
618
619 const unsigned *code;
620 };
621
622 static void
623 anv_pipeline_hash_shader(const struct anv_shader_module *module,
624 const char *entrypoint,
625 gl_shader_stage stage,
626 const VkSpecializationInfo *spec_info,
627 unsigned char *sha1_out)
628 {
629 struct mesa_sha1 ctx;
630 _mesa_sha1_init(&ctx);
631
632 _mesa_sha1_update(&ctx, module->sha1, sizeof(module->sha1));
633 _mesa_sha1_update(&ctx, entrypoint, strlen(entrypoint));
634 _mesa_sha1_update(&ctx, &stage, sizeof(stage));
635 if (spec_info) {
636 _mesa_sha1_update(&ctx, spec_info->pMapEntries,
637 spec_info->mapEntryCount *
638 sizeof(*spec_info->pMapEntries));
639 _mesa_sha1_update(&ctx, spec_info->pData,
640 spec_info->dataSize);
641 }
642
643 _mesa_sha1_final(&ctx, sha1_out);
644 }
645
646 static void
647 anv_pipeline_hash_graphics(struct anv_graphics_pipeline *pipeline,
648 struct anv_pipeline_layout *layout,
649 struct anv_pipeline_stage *stages,
650 unsigned char *sha1_out)
651 {
652 struct mesa_sha1 ctx;
653 _mesa_sha1_init(&ctx);
654
655 _mesa_sha1_update(&ctx, &pipeline->subpass->view_mask,
656 sizeof(pipeline->subpass->view_mask));
657
658 if (layout)
659 _mesa_sha1_update(&ctx, layout->sha1, sizeof(layout->sha1));
660
661 const bool rba = pipeline->base.device->robust_buffer_access;
662 _mesa_sha1_update(&ctx, &rba, sizeof(rba));
663
664 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
665 if (stages[s].entrypoint) {
666 _mesa_sha1_update(&ctx, stages[s].shader_sha1,
667 sizeof(stages[s].shader_sha1));
668 _mesa_sha1_update(&ctx, &stages[s].key, brw_prog_key_size(s));
669 }
670 }
671
672 _mesa_sha1_final(&ctx, sha1_out);
673 }
674
675 static void
676 anv_pipeline_hash_compute(struct anv_compute_pipeline *pipeline,
677 struct anv_pipeline_layout *layout,
678 struct anv_pipeline_stage *stage,
679 unsigned char *sha1_out)
680 {
681 struct mesa_sha1 ctx;
682 _mesa_sha1_init(&ctx);
683
684 if (layout)
685 _mesa_sha1_update(&ctx, layout->sha1, sizeof(layout->sha1));
686
687 const bool rba = pipeline->base.device->robust_buffer_access;
688 _mesa_sha1_update(&ctx, &rba, sizeof(rba));
689
690 _mesa_sha1_update(&ctx, stage->shader_sha1,
691 sizeof(stage->shader_sha1));
692 _mesa_sha1_update(&ctx, &stage->key.cs, sizeof(stage->key.cs));
693
694 _mesa_sha1_final(&ctx, sha1_out);
695 }
696
697 static nir_shader *
698 anv_pipeline_stage_get_nir(struct anv_pipeline *pipeline,
699 struct anv_pipeline_cache *cache,
700 void *mem_ctx,
701 struct anv_pipeline_stage *stage)
702 {
703 const struct brw_compiler *compiler =
704 pipeline->device->physical->compiler;
705 const nir_shader_compiler_options *nir_options =
706 compiler->glsl_compiler_options[stage->stage].NirOptions;
707 nir_shader *nir;
708
709 nir = anv_device_search_for_nir(pipeline->device, cache,
710 nir_options,
711 stage->shader_sha1,
712 mem_ctx);
713 if (nir) {
714 assert(nir->info.stage == stage->stage);
715 return nir;
716 }
717
718 nir = anv_shader_compile_to_nir(pipeline->device,
719 mem_ctx,
720 stage->module,
721 stage->entrypoint,
722 stage->stage,
723 stage->spec_info);
724 if (nir) {
725 anv_device_upload_nir(pipeline->device, cache, nir, stage->shader_sha1);
726 return nir;
727 }
728
729 return NULL;
730 }
731
732 static void
733 anv_pipeline_lower_nir(struct anv_pipeline *pipeline,
734 void *mem_ctx,
735 struct anv_pipeline_stage *stage,
736 struct anv_pipeline_layout *layout)
737 {
738 const struct anv_physical_device *pdevice = pipeline->device->physical;
739 const struct brw_compiler *compiler = pdevice->compiler;
740
741 struct brw_stage_prog_data *prog_data = &stage->prog_data.base;
742 nir_shader *nir = stage->nir;
743
744 if (nir->info.stage == MESA_SHADER_FRAGMENT) {
745 NIR_PASS_V(nir, nir_lower_wpos_center,
746 anv_pipeline_to_graphics(pipeline)->sample_shading_enable);
747 NIR_PASS_V(nir, nir_lower_input_attachments,
748 &(nir_input_attachment_options) {
749 .use_fragcoord_sysval = true,
750 .use_layer_id_sysval = true,
751 });
752 }
753
754 NIR_PASS_V(nir, anv_nir_lower_ycbcr_textures, layout);
755
756 if (pipeline->type == ANV_PIPELINE_GRAPHICS) {
757 NIR_PASS_V(nir, anv_nir_lower_multiview,
758 anv_pipeline_to_graphics(pipeline));
759 }
760
761 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
762
763 NIR_PASS_V(nir, brw_nir_lower_image_load_store, compiler->devinfo, NULL);
764
765 NIR_PASS_V(nir, nir_lower_explicit_io, nir_var_mem_global,
766 nir_address_format_64bit_global);
767
768 /* Apply the actual pipeline layout to UBOs, SSBOs, and textures */
769 anv_nir_apply_pipeline_layout(pdevice,
770 pipeline->device->robust_buffer_access,
771 layout, nir, &stage->bind_map);
772
773 NIR_PASS_V(nir, nir_lower_explicit_io, nir_var_mem_ubo,
774 nir_address_format_32bit_index_offset);
775 NIR_PASS_V(nir, nir_lower_explicit_io, nir_var_mem_ssbo,
776 anv_nir_ssbo_addr_format(pdevice,
777 pipeline->device->robust_buffer_access));
778
779 NIR_PASS_V(nir, nir_opt_constant_folding);
780
781 /* We don't support non-uniform UBOs and non-uniform SSBO access is
782 * handled naturally by falling back to A64 messages.
783 */
784 NIR_PASS_V(nir, nir_lower_non_uniform_access,
785 nir_lower_non_uniform_texture_access |
786 nir_lower_non_uniform_image_access);
787
788 anv_nir_compute_push_layout(pdevice, pipeline->device->robust_buffer_access,
789 nir, prog_data, &stage->bind_map, mem_ctx);
790
791 stage->nir = nir;
792 }
793
794 static void
795 anv_pipeline_link_vs(const struct brw_compiler *compiler,
796 struct anv_pipeline_stage *vs_stage,
797 struct anv_pipeline_stage *next_stage)
798 {
799 if (next_stage)
800 brw_nir_link_shaders(compiler, vs_stage->nir, next_stage->nir);
801 }
802
803 static void
804 anv_pipeline_compile_vs(const struct brw_compiler *compiler,
805 void *mem_ctx,
806 struct anv_graphics_pipeline *pipeline,
807 struct anv_pipeline_stage *vs_stage)
808 {
809 /* When using Primitive Replication for multiview, each view gets its own
810 * position slot.
811 */
812 uint32_t pos_slots = pipeline->use_primitive_replication ?
813 anv_subpass_view_count(pipeline->subpass) : 1;
814
815 brw_compute_vue_map(compiler->devinfo,
816 &vs_stage->prog_data.vs.base.vue_map,
817 vs_stage->nir->info.outputs_written,
818 vs_stage->nir->info.separate_shader,
819 pos_slots);
820
821 vs_stage->num_stats = 1;
822 vs_stage->code = brw_compile_vs(compiler, pipeline->base.device, mem_ctx,
823 &vs_stage->key.vs,
824 &vs_stage->prog_data.vs,
825 vs_stage->nir, -1,
826 vs_stage->stats, NULL);
827 }
828
829 static void
830 merge_tess_info(struct shader_info *tes_info,
831 const struct shader_info *tcs_info)
832 {
833 /* The Vulkan 1.0.38 spec, section 21.1 Tessellator says:
834 *
835 * "PointMode. Controls generation of points rather than triangles
836 * or lines. This functionality defaults to disabled, and is
837 * enabled if either shader stage includes the execution mode.
838 *
839 * and about Triangles, Quads, IsoLines, VertexOrderCw, VertexOrderCcw,
840 * PointMode, SpacingEqual, SpacingFractionalEven, SpacingFractionalOdd,
841 * and OutputVertices, it says:
842 *
843 * "One mode must be set in at least one of the tessellation
844 * shader stages."
845 *
846 * So, the fields can be set in either the TCS or TES, but they must
847 * agree if set in both. Our backend looks at TES, so bitwise-or in
848 * the values from the TCS.
849 */
850 assert(tcs_info->tess.tcs_vertices_out == 0 ||
851 tes_info->tess.tcs_vertices_out == 0 ||
852 tcs_info->tess.tcs_vertices_out == tes_info->tess.tcs_vertices_out);
853 tes_info->tess.tcs_vertices_out |= tcs_info->tess.tcs_vertices_out;
854
855 assert(tcs_info->tess.spacing == TESS_SPACING_UNSPECIFIED ||
856 tes_info->tess.spacing == TESS_SPACING_UNSPECIFIED ||
857 tcs_info->tess.spacing == tes_info->tess.spacing);
858 tes_info->tess.spacing |= tcs_info->tess.spacing;
859
860 assert(tcs_info->tess.primitive_mode == 0 ||
861 tes_info->tess.primitive_mode == 0 ||
862 tcs_info->tess.primitive_mode == tes_info->tess.primitive_mode);
863 tes_info->tess.primitive_mode |= tcs_info->tess.primitive_mode;
864 tes_info->tess.ccw |= tcs_info->tess.ccw;
865 tes_info->tess.point_mode |= tcs_info->tess.point_mode;
866 }
867
868 static void
869 anv_pipeline_link_tcs(const struct brw_compiler *compiler,
870 struct anv_pipeline_stage *tcs_stage,
871 struct anv_pipeline_stage *tes_stage)
872 {
873 assert(tes_stage && tes_stage->stage == MESA_SHADER_TESS_EVAL);
874
875 brw_nir_link_shaders(compiler, tcs_stage->nir, tes_stage->nir);
876
877 nir_lower_patch_vertices(tes_stage->nir,
878 tcs_stage->nir->info.tess.tcs_vertices_out,
879 NULL);
880
881 /* Copy TCS info into the TES info */
882 merge_tess_info(&tes_stage->nir->info, &tcs_stage->nir->info);
883
884 /* Whacking the key after cache lookup is a bit sketchy, but all of
885 * this comes from the SPIR-V, which is part of the hash used for the
886 * pipeline cache. So it should be safe.
887 */
888 tcs_stage->key.tcs.tes_primitive_mode =
889 tes_stage->nir->info.tess.primitive_mode;
890 tcs_stage->key.tcs.quads_workaround =
891 compiler->devinfo->gen < 9 &&
892 tes_stage->nir->info.tess.primitive_mode == 7 /* GL_QUADS */ &&
893 tes_stage->nir->info.tess.spacing == TESS_SPACING_EQUAL;
894 }
895
896 static void
897 anv_pipeline_compile_tcs(const struct brw_compiler *compiler,
898 void *mem_ctx,
899 struct anv_device *device,
900 struct anv_pipeline_stage *tcs_stage,
901 struct anv_pipeline_stage *prev_stage)
902 {
903 tcs_stage->key.tcs.outputs_written =
904 tcs_stage->nir->info.outputs_written;
905 tcs_stage->key.tcs.patch_outputs_written =
906 tcs_stage->nir->info.patch_outputs_written;
907
908 tcs_stage->num_stats = 1;
909 tcs_stage->code = brw_compile_tcs(compiler, device, mem_ctx,
910 &tcs_stage->key.tcs,
911 &tcs_stage->prog_data.tcs,
912 tcs_stage->nir, -1,
913 tcs_stage->stats, NULL);
914 }
915
916 static void
917 anv_pipeline_link_tes(const struct brw_compiler *compiler,
918 struct anv_pipeline_stage *tes_stage,
919 struct anv_pipeline_stage *next_stage)
920 {
921 if (next_stage)
922 brw_nir_link_shaders(compiler, tes_stage->nir, next_stage->nir);
923 }
924
925 static void
926 anv_pipeline_compile_tes(const struct brw_compiler *compiler,
927 void *mem_ctx,
928 struct anv_device *device,
929 struct anv_pipeline_stage *tes_stage,
930 struct anv_pipeline_stage *tcs_stage)
931 {
932 tes_stage->key.tes.inputs_read =
933 tcs_stage->nir->info.outputs_written;
934 tes_stage->key.tes.patch_inputs_read =
935 tcs_stage->nir->info.patch_outputs_written;
936
937 tes_stage->num_stats = 1;
938 tes_stage->code = brw_compile_tes(compiler, device, mem_ctx,
939 &tes_stage->key.tes,
940 &tcs_stage->prog_data.tcs.base.vue_map,
941 &tes_stage->prog_data.tes,
942 tes_stage->nir, -1,
943 tes_stage->stats, NULL);
944 }
945
946 static void
947 anv_pipeline_link_gs(const struct brw_compiler *compiler,
948 struct anv_pipeline_stage *gs_stage,
949 struct anv_pipeline_stage *next_stage)
950 {
951 if (next_stage)
952 brw_nir_link_shaders(compiler, gs_stage->nir, next_stage->nir);
953 }
954
955 static void
956 anv_pipeline_compile_gs(const struct brw_compiler *compiler,
957 void *mem_ctx,
958 struct anv_device *device,
959 struct anv_pipeline_stage *gs_stage,
960 struct anv_pipeline_stage *prev_stage)
961 {
962 brw_compute_vue_map(compiler->devinfo,
963 &gs_stage->prog_data.gs.base.vue_map,
964 gs_stage->nir->info.outputs_written,
965 gs_stage->nir->info.separate_shader, 1);
966
967 gs_stage->num_stats = 1;
968 gs_stage->code = brw_compile_gs(compiler, device, mem_ctx,
969 &gs_stage->key.gs,
970 &gs_stage->prog_data.gs,
971 gs_stage->nir, NULL, -1,
972 gs_stage->stats, NULL);
973 }
974
975 static void
976 anv_pipeline_link_fs(const struct brw_compiler *compiler,
977 struct anv_pipeline_stage *stage)
978 {
979 unsigned num_rt_bindings;
980 struct anv_pipeline_binding rt_bindings[MAX_RTS];
981 if (stage->key.wm.nr_color_regions > 0) {
982 assert(stage->key.wm.nr_color_regions <= MAX_RTS);
983 for (unsigned rt = 0; rt < stage->key.wm.nr_color_regions; rt++) {
984 if (stage->key.wm.color_outputs_valid & BITFIELD_BIT(rt)) {
985 rt_bindings[rt] = (struct anv_pipeline_binding) {
986 .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
987 .index = rt,
988 };
989 } else {
990 /* Setup a null render target */
991 rt_bindings[rt] = (struct anv_pipeline_binding) {
992 .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
993 .index = UINT32_MAX,
994 };
995 }
996 }
997 num_rt_bindings = stage->key.wm.nr_color_regions;
998 } else {
999 /* Setup a null render target */
1000 rt_bindings[0] = (struct anv_pipeline_binding) {
1001 .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
1002 .index = UINT32_MAX,
1003 };
1004 num_rt_bindings = 1;
1005 }
1006
1007 assert(num_rt_bindings <= MAX_RTS);
1008 assert(stage->bind_map.surface_count == 0);
1009 typed_memcpy(stage->bind_map.surface_to_descriptor,
1010 rt_bindings, num_rt_bindings);
1011 stage->bind_map.surface_count += num_rt_bindings;
1012
1013 /* Now that we've set up the color attachments, we can go through and
1014 * eliminate any shader outputs that map to VK_ATTACHMENT_UNUSED in the
1015 * hopes that dead code can clean them up in this and any earlier shader
1016 * stages.
1017 */
1018 nir_function_impl *impl = nir_shader_get_entrypoint(stage->nir);
1019 bool deleted_output = false;
1020 nir_foreach_shader_out_variable_safe(var, stage->nir) {
1021 /* TODO: We don't delete depth/stencil writes. We probably could if the
1022 * subpass doesn't have a depth/stencil attachment.
1023 */
1024 if (var->data.location < FRAG_RESULT_DATA0)
1025 continue;
1026
1027 const unsigned rt = var->data.location - FRAG_RESULT_DATA0;
1028
1029 /* If this is the RT at location 0 and we have alpha to coverage
1030 * enabled we still need that write because it will affect the coverage
1031 * mask even if it's never written to a color target.
1032 */
1033 if (rt == 0 && stage->key.wm.alpha_to_coverage)
1034 continue;
1035
1036 const unsigned array_len =
1037 glsl_type_is_array(var->type) ? glsl_get_length(var->type) : 1;
1038 assert(rt + array_len <= MAX_RTS);
1039
1040 if (rt >= MAX_RTS || !(stage->key.wm.color_outputs_valid &
1041 BITFIELD_RANGE(rt, array_len))) {
1042 deleted_output = true;
1043 var->data.mode = nir_var_function_temp;
1044 exec_node_remove(&var->node);
1045 exec_list_push_tail(&impl->locals, &var->node);
1046 }
1047 }
1048
1049 if (deleted_output)
1050 nir_fixup_deref_modes(stage->nir);
1051
1052 /* We stored the number of subpass color attachments in nr_color_regions
1053 * when calculating the key for caching. Now that we've computed the bind
1054 * map, we can reduce this to the actual max before we go into the back-end
1055 * compiler.
1056 */
1057 stage->key.wm.nr_color_regions =
1058 util_last_bit(stage->key.wm.color_outputs_valid);
1059 }
1060
1061 static void
1062 anv_pipeline_compile_fs(const struct brw_compiler *compiler,
1063 void *mem_ctx,
1064 struct anv_device *device,
1065 struct anv_pipeline_stage *fs_stage,
1066 struct anv_pipeline_stage *prev_stage)
1067 {
1068 /* TODO: we could set this to 0 based on the information in nir_shader, but
1069 * we need this before we call spirv_to_nir.
1070 */
1071 assert(prev_stage);
1072 fs_stage->key.wm.input_slots_valid =
1073 prev_stage->prog_data.vue.vue_map.slots_valid;
1074
1075 fs_stage->code = brw_compile_fs(compiler, device, mem_ctx,
1076 &fs_stage->key.wm,
1077 &fs_stage->prog_data.wm,
1078 fs_stage->nir, -1, -1, -1,
1079 true, false, NULL,
1080 fs_stage->stats, NULL);
1081
1082 fs_stage->num_stats = (uint32_t)fs_stage->prog_data.wm.dispatch_8 +
1083 (uint32_t)fs_stage->prog_data.wm.dispatch_16 +
1084 (uint32_t)fs_stage->prog_data.wm.dispatch_32;
1085
1086 if (fs_stage->key.wm.color_outputs_valid == 0 &&
1087 !fs_stage->prog_data.wm.has_side_effects &&
1088 !fs_stage->prog_data.wm.uses_omask &&
1089 !fs_stage->key.wm.alpha_to_coverage &&
1090 !fs_stage->prog_data.wm.uses_kill &&
1091 fs_stage->prog_data.wm.computed_depth_mode == BRW_PSCDEPTH_OFF &&
1092 !fs_stage->prog_data.wm.computed_stencil) {
1093 /* This fragment shader has no outputs and no side effects. Go ahead
1094 * and return the code pointer so we don't accidentally think the
1095 * compile failed but zero out prog_data which will set program_size to
1096 * zero and disable the stage.
1097 */
1098 memset(&fs_stage->prog_data, 0, sizeof(fs_stage->prog_data));
1099 }
1100 }
1101
1102 static void
1103 anv_pipeline_add_executable(struct anv_pipeline *pipeline,
1104 struct anv_pipeline_stage *stage,
1105 struct brw_compile_stats *stats,
1106 uint32_t code_offset)
1107 {
1108 char *nir = NULL;
1109 if (stage->nir &&
1110 (pipeline->flags &
1111 VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR)) {
1112 char *stream_data = NULL;
1113 size_t stream_size = 0;
1114 FILE *stream = open_memstream(&stream_data, &stream_size);
1115
1116 nir_print_shader(stage->nir, stream);
1117
1118 fclose(stream);
1119
1120 /* Copy it to a ralloc'd thing */
1121 nir = ralloc_size(pipeline->mem_ctx, stream_size + 1);
1122 memcpy(nir, stream_data, stream_size);
1123 nir[stream_size] = 0;
1124
1125 free(stream_data);
1126 }
1127
1128 char *disasm = NULL;
1129 if (stage->code &&
1130 (pipeline->flags &
1131 VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR)) {
1132 char *stream_data = NULL;
1133 size_t stream_size = 0;
1134 FILE *stream = open_memstream(&stream_data, &stream_size);
1135
1136 uint32_t push_size = 0;
1137 for (unsigned i = 0; i < 4; i++)
1138 push_size += stage->bind_map.push_ranges[i].length;
1139 if (push_size > 0) {
1140 fprintf(stream, "Push constant ranges:\n");
1141 for (unsigned i = 0; i < 4; i++) {
1142 if (stage->bind_map.push_ranges[i].length == 0)
1143 continue;
1144
1145 fprintf(stream, " RANGE%d (%dB): ", i,
1146 stage->bind_map.push_ranges[i].length * 32);
1147
1148 switch (stage->bind_map.push_ranges[i].set) {
1149 case ANV_DESCRIPTOR_SET_NULL:
1150 fprintf(stream, "NULL");
1151 break;
1152
1153 case ANV_DESCRIPTOR_SET_PUSH_CONSTANTS:
1154 fprintf(stream, "Vulkan push constants and API params");
1155 break;
1156
1157 case ANV_DESCRIPTOR_SET_DESCRIPTORS:
1158 fprintf(stream, "Descriptor buffer for set %d (start=%dB)",
1159 stage->bind_map.push_ranges[i].index,
1160 stage->bind_map.push_ranges[i].start * 32);
1161 break;
1162
1163 case ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS:
1164 unreachable("gl_NumWorkgroups is never pushed");
1165
1166 case ANV_DESCRIPTOR_SET_SHADER_CONSTANTS:
1167 fprintf(stream, "Inline shader constant data (start=%dB)",
1168 stage->bind_map.push_ranges[i].start * 32);
1169 break;
1170
1171 case ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS:
1172 unreachable("Color attachments can't be pushed");
1173
1174 default:
1175 fprintf(stream, "UBO (set=%d binding=%d start=%dB)",
1176 stage->bind_map.push_ranges[i].set,
1177 stage->bind_map.push_ranges[i].index,
1178 stage->bind_map.push_ranges[i].start * 32);
1179 break;
1180 }
1181 fprintf(stream, "\n");
1182 }
1183 fprintf(stream, "\n");
1184 }
1185
1186 /* Creating this is far cheaper than it looks. It's perfectly fine to
1187 * do it for every binary.
1188 */
1189 struct gen_disasm *d = gen_disasm_create(&pipeline->device->info);
1190 gen_disasm_disassemble(d, stage->code, code_offset, stream);
1191 gen_disasm_destroy(d);
1192
1193 fclose(stream);
1194
1195 /* Copy it to a ralloc'd thing */
1196 disasm = ralloc_size(pipeline->mem_ctx, stream_size + 1);
1197 memcpy(disasm, stream_data, stream_size);
1198 disasm[stream_size] = 0;
1199
1200 free(stream_data);
1201 }
1202
1203 const struct anv_pipeline_executable exe = {
1204 .stage = stage->stage,
1205 .stats = *stats,
1206 .nir = nir,
1207 .disasm = disasm,
1208 };
1209 util_dynarray_append(&pipeline->executables,
1210 struct anv_pipeline_executable, exe);
1211 }
1212
1213 static void
1214 anv_pipeline_add_executables(struct anv_pipeline *pipeline,
1215 struct anv_pipeline_stage *stage,
1216 struct anv_shader_bin *bin)
1217 {
1218 if (stage->stage == MESA_SHADER_FRAGMENT) {
1219 /* We pull the prog data and stats out of the anv_shader_bin because
1220 * the anv_pipeline_stage may not be fully populated if we successfully
1221 * looked up the shader in a cache.
1222 */
1223 const struct brw_wm_prog_data *wm_prog_data =
1224 (const struct brw_wm_prog_data *)bin->prog_data;
1225 struct brw_compile_stats *stats = bin->stats;
1226
1227 if (wm_prog_data->dispatch_8) {
1228 anv_pipeline_add_executable(pipeline, stage, stats++, 0);
1229 }
1230
1231 if (wm_prog_data->dispatch_16) {
1232 anv_pipeline_add_executable(pipeline, stage, stats++,
1233 wm_prog_data->prog_offset_16);
1234 }
1235
1236 if (wm_prog_data->dispatch_32) {
1237 anv_pipeline_add_executable(pipeline, stage, stats++,
1238 wm_prog_data->prog_offset_32);
1239 }
1240 } else {
1241 anv_pipeline_add_executable(pipeline, stage, bin->stats, 0);
1242 }
1243 }
1244
1245 static void
1246 anv_pipeline_init_from_cached_graphics(struct anv_graphics_pipeline *pipeline)
1247 {
1248 /* TODO: Cache this pipeline-wide information. */
1249
1250 /* Primitive replication depends on information from all the shaders.
1251 * Recover this bit from the fact that we have more than one position slot
1252 * in the vertex shader when using it.
1253 */
1254 assert(pipeline->active_stages & VK_SHADER_STAGE_VERTEX_BIT);
1255 int pos_slots = 0;
1256 const struct brw_vue_prog_data *vue_prog_data =
1257 (const void *) pipeline->shaders[MESA_SHADER_VERTEX]->prog_data;
1258 const struct brw_vue_map *vue_map = &vue_prog_data->vue_map;
1259 for (int i = 0; i < vue_map->num_slots; i++) {
1260 if (vue_map->slot_to_varying[i] == VARYING_SLOT_POS)
1261 pos_slots++;
1262 }
1263 pipeline->use_primitive_replication = pos_slots > 1;
1264 }
1265
1266 static VkResult
1267 anv_pipeline_compile_graphics(struct anv_graphics_pipeline *pipeline,
1268 struct anv_pipeline_cache *cache,
1269 const VkGraphicsPipelineCreateInfo *info)
1270 {
1271 VkPipelineCreationFeedbackEXT pipeline_feedback = {
1272 .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT,
1273 };
1274 int64_t pipeline_start = os_time_get_nano();
1275
1276 const struct brw_compiler *compiler = pipeline->base.device->physical->compiler;
1277 struct anv_pipeline_stage stages[MESA_SHADER_STAGES] = {};
1278
1279 pipeline->active_stages = 0;
1280
1281 VkResult result;
1282 for (uint32_t i = 0; i < info->stageCount; i++) {
1283 const VkPipelineShaderStageCreateInfo *sinfo = &info->pStages[i];
1284 gl_shader_stage stage = vk_to_mesa_shader_stage(sinfo->stage);
1285
1286 pipeline->active_stages |= sinfo->stage;
1287
1288 int64_t stage_start = os_time_get_nano();
1289
1290 stages[stage].stage = stage;
1291 stages[stage].module = anv_shader_module_from_handle(sinfo->module);
1292 stages[stage].entrypoint = sinfo->pName;
1293 stages[stage].spec_info = sinfo->pSpecializationInfo;
1294 anv_pipeline_hash_shader(stages[stage].module,
1295 stages[stage].entrypoint,
1296 stage,
1297 stages[stage].spec_info,
1298 stages[stage].shader_sha1);
1299
1300 const struct gen_device_info *devinfo = &pipeline->base.device->info;
1301 switch (stage) {
1302 case MESA_SHADER_VERTEX:
1303 populate_vs_prog_key(devinfo, sinfo->flags, &stages[stage].key.vs);
1304 break;
1305 case MESA_SHADER_TESS_CTRL:
1306 populate_tcs_prog_key(devinfo, sinfo->flags,
1307 info->pTessellationState->patchControlPoints,
1308 &stages[stage].key.tcs);
1309 break;
1310 case MESA_SHADER_TESS_EVAL:
1311 populate_tes_prog_key(devinfo, sinfo->flags, &stages[stage].key.tes);
1312 break;
1313 case MESA_SHADER_GEOMETRY:
1314 populate_gs_prog_key(devinfo, sinfo->flags, &stages[stage].key.gs);
1315 break;
1316 case MESA_SHADER_FRAGMENT: {
1317 const bool raster_enabled =
1318 !info->pRasterizationState->rasterizerDiscardEnable;
1319 populate_wm_prog_key(devinfo, sinfo->flags,
1320 pipeline->subpass,
1321 raster_enabled ? info->pMultisampleState : NULL,
1322 &stages[stage].key.wm);
1323 break;
1324 }
1325 default:
1326 unreachable("Invalid graphics shader stage");
1327 }
1328
1329 stages[stage].feedback.duration += os_time_get_nano() - stage_start;
1330 stages[stage].feedback.flags |= VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT;
1331 }
1332
1333 if (pipeline->active_stages & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)
1334 pipeline->active_stages |= VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
1335
1336 assert(pipeline->active_stages & VK_SHADER_STAGE_VERTEX_BIT);
1337
1338 ANV_FROM_HANDLE(anv_pipeline_layout, layout, info->layout);
1339
1340 unsigned char sha1[20];
1341 anv_pipeline_hash_graphics(pipeline, layout, stages, sha1);
1342
1343 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1344 if (!stages[s].entrypoint)
1345 continue;
1346
1347 stages[s].cache_key.stage = s;
1348 memcpy(stages[s].cache_key.sha1, sha1, sizeof(sha1));
1349 }
1350
1351 const bool skip_cache_lookup =
1352 (pipeline->base.flags & VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR);
1353
1354 if (!skip_cache_lookup) {
1355 unsigned found = 0;
1356 unsigned cache_hits = 0;
1357 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1358 if (!stages[s].entrypoint)
1359 continue;
1360
1361 int64_t stage_start = os_time_get_nano();
1362
1363 bool cache_hit;
1364 struct anv_shader_bin *bin =
1365 anv_device_search_for_kernel(pipeline->base.device, cache,
1366 &stages[s].cache_key,
1367 sizeof(stages[s].cache_key), &cache_hit);
1368 if (bin) {
1369 found++;
1370 pipeline->shaders[s] = bin;
1371 }
1372
1373 if (cache_hit) {
1374 cache_hits++;
1375 stages[s].feedback.flags |=
1376 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1377 }
1378 stages[s].feedback.duration += os_time_get_nano() - stage_start;
1379 }
1380
1381 if (found == __builtin_popcount(pipeline->active_stages)) {
1382 if (cache_hits == found) {
1383 pipeline_feedback.flags |=
1384 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1385 }
1386 /* We found all our shaders in the cache. We're done. */
1387 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1388 if (!stages[s].entrypoint)
1389 continue;
1390
1391 anv_pipeline_add_executables(&pipeline->base, &stages[s],
1392 pipeline->shaders[s]);
1393 }
1394 anv_pipeline_init_from_cached_graphics(pipeline);
1395 goto done;
1396 } else if (found > 0) {
1397 /* We found some but not all of our shaders. This shouldn't happen
1398 * most of the time but it can if we have a partially populated
1399 * pipeline cache.
1400 */
1401 assert(found < __builtin_popcount(pipeline->active_stages));
1402
1403 vk_debug_report(&pipeline->base.device->physical->instance->debug_report_callbacks,
1404 VK_DEBUG_REPORT_WARNING_BIT_EXT |
1405 VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
1406 VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT,
1407 (uint64_t)(uintptr_t)cache,
1408 0, 0, "anv",
1409 "Found a partial pipeline in the cache. This is "
1410 "most likely caused by an incomplete pipeline cache "
1411 "import or export");
1412
1413 /* We're going to have to recompile anyway, so just throw away our
1414 * references to the shaders in the cache. We'll get them out of the
1415 * cache again as part of the compilation process.
1416 */
1417 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1418 stages[s].feedback.flags = 0;
1419 if (pipeline->shaders[s]) {
1420 anv_shader_bin_unref(pipeline->base.device, pipeline->shaders[s]);
1421 pipeline->shaders[s] = NULL;
1422 }
1423 }
1424 }
1425 }
1426
1427 if (info->flags & VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT_EXT)
1428 return VK_PIPELINE_COMPILE_REQUIRED_EXT;
1429
1430 void *pipeline_ctx = ralloc_context(NULL);
1431
1432 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1433 if (!stages[s].entrypoint)
1434 continue;
1435
1436 int64_t stage_start = os_time_get_nano();
1437
1438 assert(stages[s].stage == s);
1439 assert(pipeline->shaders[s] == NULL);
1440
1441 stages[s].bind_map = (struct anv_pipeline_bind_map) {
1442 .surface_to_descriptor = stages[s].surface_to_descriptor,
1443 .sampler_to_descriptor = stages[s].sampler_to_descriptor
1444 };
1445
1446 stages[s].nir = anv_pipeline_stage_get_nir(&pipeline->base, cache,
1447 pipeline_ctx,
1448 &stages[s]);
1449 if (stages[s].nir == NULL) {
1450 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1451 goto fail;
1452 }
1453
1454 stages[s].feedback.duration += os_time_get_nano() - stage_start;
1455 }
1456
1457 /* Walk backwards to link */
1458 struct anv_pipeline_stage *next_stage = NULL;
1459 for (int s = MESA_SHADER_STAGES - 1; s >= 0; s--) {
1460 if (!stages[s].entrypoint)
1461 continue;
1462
1463 switch (s) {
1464 case MESA_SHADER_VERTEX:
1465 anv_pipeline_link_vs(compiler, &stages[s], next_stage);
1466 break;
1467 case MESA_SHADER_TESS_CTRL:
1468 anv_pipeline_link_tcs(compiler, &stages[s], next_stage);
1469 break;
1470 case MESA_SHADER_TESS_EVAL:
1471 anv_pipeline_link_tes(compiler, &stages[s], next_stage);
1472 break;
1473 case MESA_SHADER_GEOMETRY:
1474 anv_pipeline_link_gs(compiler, &stages[s], next_stage);
1475 break;
1476 case MESA_SHADER_FRAGMENT:
1477 anv_pipeline_link_fs(compiler, &stages[s]);
1478 break;
1479 default:
1480 unreachable("Invalid graphics shader stage");
1481 }
1482
1483 next_stage = &stages[s];
1484 }
1485
1486 if (pipeline->base.device->info.gen >= 12 &&
1487 pipeline->subpass->view_mask != 0) {
1488 /* For some pipelines HW Primitive Replication can be used instead of
1489 * instancing to implement Multiview. This depend on how viewIndex is
1490 * used in all the active shaders, so this check can't be done per
1491 * individual shaders.
1492 */
1493 nir_shader *shaders[MESA_SHADER_STAGES] = {};
1494 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++)
1495 shaders[s] = stages[s].nir;
1496
1497 pipeline->use_primitive_replication =
1498 anv_check_for_primitive_replication(shaders, pipeline);
1499 } else {
1500 pipeline->use_primitive_replication = false;
1501 }
1502
1503 struct anv_pipeline_stage *prev_stage = NULL;
1504 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1505 if (!stages[s].entrypoint)
1506 continue;
1507
1508 int64_t stage_start = os_time_get_nano();
1509
1510 void *stage_ctx = ralloc_context(NULL);
1511
1512 anv_pipeline_lower_nir(&pipeline->base, stage_ctx, &stages[s], layout);
1513
1514 if (prev_stage && compiler->glsl_compiler_options[s].NirOptions->unify_interfaces) {
1515 prev_stage->nir->info.outputs_written |= stages[s].nir->info.inputs_read &
1516 ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
1517 stages[s].nir->info.inputs_read |= prev_stage->nir->info.outputs_written &
1518 ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
1519 prev_stage->nir->info.patch_outputs_written |= stages[s].nir->info.patch_inputs_read;
1520 stages[s].nir->info.patch_inputs_read |= prev_stage->nir->info.patch_outputs_written;
1521 }
1522
1523 ralloc_free(stage_ctx);
1524
1525 stages[s].feedback.duration += os_time_get_nano() - stage_start;
1526
1527 prev_stage = &stages[s];
1528 }
1529
1530 prev_stage = NULL;
1531 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1532 if (!stages[s].entrypoint)
1533 continue;
1534
1535 int64_t stage_start = os_time_get_nano();
1536
1537 void *stage_ctx = ralloc_context(NULL);
1538
1539 nir_xfb_info *xfb_info = NULL;
1540 if (s == MESA_SHADER_VERTEX ||
1541 s == MESA_SHADER_TESS_EVAL ||
1542 s == MESA_SHADER_GEOMETRY)
1543 xfb_info = nir_gather_xfb_info(stages[s].nir, stage_ctx);
1544
1545 switch (s) {
1546 case MESA_SHADER_VERTEX:
1547 anv_pipeline_compile_vs(compiler, stage_ctx, pipeline,
1548 &stages[s]);
1549 break;
1550 case MESA_SHADER_TESS_CTRL:
1551 anv_pipeline_compile_tcs(compiler, stage_ctx, pipeline->base.device,
1552 &stages[s], prev_stage);
1553 break;
1554 case MESA_SHADER_TESS_EVAL:
1555 anv_pipeline_compile_tes(compiler, stage_ctx, pipeline->base.device,
1556 &stages[s], prev_stage);
1557 break;
1558 case MESA_SHADER_GEOMETRY:
1559 anv_pipeline_compile_gs(compiler, stage_ctx, pipeline->base.device,
1560 &stages[s], prev_stage);
1561 break;
1562 case MESA_SHADER_FRAGMENT:
1563 anv_pipeline_compile_fs(compiler, stage_ctx, pipeline->base.device,
1564 &stages[s], prev_stage);
1565 break;
1566 default:
1567 unreachable("Invalid graphics shader stage");
1568 }
1569 if (stages[s].code == NULL) {
1570 ralloc_free(stage_ctx);
1571 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1572 goto fail;
1573 }
1574
1575 anv_nir_validate_push_layout(&stages[s].prog_data.base,
1576 &stages[s].bind_map);
1577
1578 struct anv_shader_bin *bin =
1579 anv_device_upload_kernel(pipeline->base.device, cache, s,
1580 &stages[s].cache_key,
1581 sizeof(stages[s].cache_key),
1582 stages[s].code,
1583 stages[s].prog_data.base.program_size,
1584 stages[s].nir->constant_data,
1585 stages[s].nir->constant_data_size,
1586 &stages[s].prog_data.base,
1587 brw_prog_data_size(s),
1588 stages[s].stats, stages[s].num_stats,
1589 xfb_info, &stages[s].bind_map);
1590 if (!bin) {
1591 ralloc_free(stage_ctx);
1592 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1593 goto fail;
1594 }
1595
1596 anv_pipeline_add_executables(&pipeline->base, &stages[s], bin);
1597
1598 pipeline->shaders[s] = bin;
1599 ralloc_free(stage_ctx);
1600
1601 stages[s].feedback.duration += os_time_get_nano() - stage_start;
1602
1603 prev_stage = &stages[s];
1604 }
1605
1606 ralloc_free(pipeline_ctx);
1607
1608 done:
1609
1610 if (pipeline->shaders[MESA_SHADER_FRAGMENT] &&
1611 pipeline->shaders[MESA_SHADER_FRAGMENT]->prog_data->program_size == 0) {
1612 /* This can happen if we decided to implicitly disable the fragment
1613 * shader. See anv_pipeline_compile_fs().
1614 */
1615 anv_shader_bin_unref(pipeline->base.device,
1616 pipeline->shaders[MESA_SHADER_FRAGMENT]);
1617 pipeline->shaders[MESA_SHADER_FRAGMENT] = NULL;
1618 pipeline->active_stages &= ~VK_SHADER_STAGE_FRAGMENT_BIT;
1619 }
1620
1621 pipeline_feedback.duration = os_time_get_nano() - pipeline_start;
1622
1623 const VkPipelineCreationFeedbackCreateInfoEXT *create_feedback =
1624 vk_find_struct_const(info->pNext, PIPELINE_CREATION_FEEDBACK_CREATE_INFO_EXT);
1625 if (create_feedback) {
1626 *create_feedback->pPipelineCreationFeedback = pipeline_feedback;
1627
1628 assert(info->stageCount == create_feedback->pipelineStageCreationFeedbackCount);
1629 for (uint32_t i = 0; i < info->stageCount; i++) {
1630 gl_shader_stage s = vk_to_mesa_shader_stage(info->pStages[i].stage);
1631 create_feedback->pPipelineStageCreationFeedbacks[i] = stages[s].feedback;
1632 }
1633 }
1634
1635 return VK_SUCCESS;
1636
1637 fail:
1638 ralloc_free(pipeline_ctx);
1639
1640 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1641 if (pipeline->shaders[s])
1642 anv_shader_bin_unref(pipeline->base.device, pipeline->shaders[s]);
1643 }
1644
1645 return result;
1646 }
1647
1648 static void
1649 shared_type_info(const struct glsl_type *type, unsigned *size, unsigned *align)
1650 {
1651 assert(glsl_type_is_vector_or_scalar(type));
1652
1653 uint32_t comp_size = glsl_type_is_boolean(type)
1654 ? 4 : glsl_get_bit_size(type) / 8;
1655 unsigned length = glsl_get_vector_elements(type);
1656 *size = comp_size * length,
1657 *align = comp_size * (length == 3 ? 4 : length);
1658 }
1659
1660 VkResult
1661 anv_pipeline_compile_cs(struct anv_compute_pipeline *pipeline,
1662 struct anv_pipeline_cache *cache,
1663 const VkComputePipelineCreateInfo *info,
1664 const struct anv_shader_module *module,
1665 const char *entrypoint,
1666 const VkSpecializationInfo *spec_info)
1667 {
1668 VkPipelineCreationFeedbackEXT pipeline_feedback = {
1669 .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT,
1670 };
1671 int64_t pipeline_start = os_time_get_nano();
1672
1673 const struct brw_compiler *compiler = pipeline->base.device->physical->compiler;
1674
1675 struct anv_pipeline_stage stage = {
1676 .stage = MESA_SHADER_COMPUTE,
1677 .module = module,
1678 .entrypoint = entrypoint,
1679 .spec_info = spec_info,
1680 .cache_key = {
1681 .stage = MESA_SHADER_COMPUTE,
1682 },
1683 .feedback = {
1684 .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT,
1685 },
1686 };
1687 anv_pipeline_hash_shader(stage.module,
1688 stage.entrypoint,
1689 MESA_SHADER_COMPUTE,
1690 stage.spec_info,
1691 stage.shader_sha1);
1692
1693 struct anv_shader_bin *bin = NULL;
1694
1695 const VkPipelineShaderStageRequiredSubgroupSizeCreateInfoEXT *rss_info =
1696 vk_find_struct_const(info->stage.pNext,
1697 PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO_EXT);
1698
1699 populate_cs_prog_key(&pipeline->base.device->info, info->stage.flags,
1700 rss_info, &stage.key.cs);
1701
1702 ANV_FROM_HANDLE(anv_pipeline_layout, layout, info->layout);
1703
1704 const bool skip_cache_lookup =
1705 (pipeline->base.flags & VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR);
1706
1707 anv_pipeline_hash_compute(pipeline, layout, &stage, stage.cache_key.sha1);
1708
1709 bool cache_hit = false;
1710 if (!skip_cache_lookup) {
1711 bin = anv_device_search_for_kernel(pipeline->base.device, cache,
1712 &stage.cache_key,
1713 sizeof(stage.cache_key),
1714 &cache_hit);
1715 }
1716
1717 if (bin == NULL &&
1718 (info->flags & VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT_EXT))
1719 return VK_PIPELINE_COMPILE_REQUIRED_EXT;
1720
1721 void *mem_ctx = ralloc_context(NULL);
1722 if (bin == NULL) {
1723 int64_t stage_start = os_time_get_nano();
1724
1725 stage.bind_map = (struct anv_pipeline_bind_map) {
1726 .surface_to_descriptor = stage.surface_to_descriptor,
1727 .sampler_to_descriptor = stage.sampler_to_descriptor
1728 };
1729
1730 /* Set up a binding for the gl_NumWorkGroups */
1731 stage.bind_map.surface_count = 1;
1732 stage.bind_map.surface_to_descriptor[0] = (struct anv_pipeline_binding) {
1733 .set = ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS,
1734 };
1735
1736 stage.nir = anv_pipeline_stage_get_nir(&pipeline->base, cache, mem_ctx, &stage);
1737 if (stage.nir == NULL) {
1738 ralloc_free(mem_ctx);
1739 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1740 }
1741
1742 NIR_PASS_V(stage.nir, anv_nir_add_base_work_group_id);
1743
1744 anv_pipeline_lower_nir(&pipeline->base, mem_ctx, &stage, layout);
1745
1746 NIR_PASS_V(stage.nir, nir_lower_vars_to_explicit_types,
1747 nir_var_mem_shared, shared_type_info);
1748 NIR_PASS_V(stage.nir, nir_lower_explicit_io,
1749 nir_var_mem_shared, nir_address_format_32bit_offset);
1750 NIR_PASS_V(stage.nir, brw_nir_lower_cs_intrinsics);
1751
1752 stage.num_stats = 1;
1753 stage.code = brw_compile_cs(compiler, pipeline->base.device, mem_ctx,
1754 &stage.key.cs, &stage.prog_data.cs,
1755 stage.nir, -1, stage.stats, NULL);
1756 if (stage.code == NULL) {
1757 ralloc_free(mem_ctx);
1758 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1759 }
1760
1761 anv_nir_validate_push_layout(&stage.prog_data.base, &stage.bind_map);
1762
1763 if (!stage.prog_data.cs.uses_num_work_groups) {
1764 assert(stage.bind_map.surface_to_descriptor[0].set ==
1765 ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS);
1766 stage.bind_map.surface_to_descriptor[0].set = ANV_DESCRIPTOR_SET_NULL;
1767 }
1768
1769 const unsigned code_size = stage.prog_data.base.program_size;
1770 bin = anv_device_upload_kernel(pipeline->base.device, cache,
1771 MESA_SHADER_COMPUTE,
1772 &stage.cache_key, sizeof(stage.cache_key),
1773 stage.code, code_size,
1774 stage.nir->constant_data,
1775 stage.nir->constant_data_size,
1776 &stage.prog_data.base,
1777 sizeof(stage.prog_data.cs),
1778 stage.stats, stage.num_stats,
1779 NULL, &stage.bind_map);
1780 if (!bin) {
1781 ralloc_free(mem_ctx);
1782 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1783 }
1784
1785 stage.feedback.duration = os_time_get_nano() - stage_start;
1786 }
1787
1788 anv_pipeline_add_executables(&pipeline->base, &stage, bin);
1789
1790 ralloc_free(mem_ctx);
1791
1792 if (cache_hit) {
1793 stage.feedback.flags |=
1794 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1795 pipeline_feedback.flags |=
1796 VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1797 }
1798 pipeline_feedback.duration = os_time_get_nano() - pipeline_start;
1799
1800 const VkPipelineCreationFeedbackCreateInfoEXT *create_feedback =
1801 vk_find_struct_const(info->pNext, PIPELINE_CREATION_FEEDBACK_CREATE_INFO_EXT);
1802 if (create_feedback) {
1803 *create_feedback->pPipelineCreationFeedback = pipeline_feedback;
1804
1805 assert(create_feedback->pipelineStageCreationFeedbackCount == 1);
1806 create_feedback->pPipelineStageCreationFeedbacks[0] = stage.feedback;
1807 }
1808
1809 pipeline->cs = bin;
1810
1811 return VK_SUCCESS;
1812 }
1813
1814 struct anv_cs_parameters
1815 anv_cs_parameters(const struct anv_compute_pipeline *pipeline)
1816 {
1817 const struct brw_cs_prog_data *cs_prog_data = get_cs_prog_data(pipeline);
1818
1819 struct anv_cs_parameters cs_params = {};
1820
1821 cs_params.group_size = cs_prog_data->local_size[0] *
1822 cs_prog_data->local_size[1] *
1823 cs_prog_data->local_size[2];
1824 cs_params.simd_size =
1825 brw_cs_simd_size_for_group_size(&pipeline->base.device->info,
1826 cs_prog_data, cs_params.group_size);
1827 cs_params.threads = DIV_ROUND_UP(cs_params.group_size, cs_params.simd_size);
1828
1829 return cs_params;
1830 }
1831
1832 /**
1833 * Copy pipeline state not marked as dynamic.
1834 * Dynamic state is pipeline state which hasn't been provided at pipeline
1835 * creation time, but is dynamically provided afterwards using various
1836 * vkCmdSet* functions.
1837 *
1838 * The set of state considered "non_dynamic" is determined by the pieces of
1839 * state that have their corresponding VkDynamicState enums omitted from
1840 * VkPipelineDynamicStateCreateInfo::pDynamicStates.
1841 *
1842 * @param[out] pipeline Destination non_dynamic state.
1843 * @param[in] pCreateInfo Source of non_dynamic state to be copied.
1844 */
1845 static void
1846 copy_non_dynamic_state(struct anv_graphics_pipeline *pipeline,
1847 const VkGraphicsPipelineCreateInfo *pCreateInfo)
1848 {
1849 anv_cmd_dirty_mask_t states = ANV_CMD_DIRTY_DYNAMIC_ALL;
1850 struct anv_subpass *subpass = pipeline->subpass;
1851
1852 pipeline->dynamic_state = default_dynamic_state;
1853
1854 if (pCreateInfo->pDynamicState) {
1855 /* Remove all of the states that are marked as dynamic */
1856 uint32_t count = pCreateInfo->pDynamicState->dynamicStateCount;
1857 for (uint32_t s = 0; s < count; s++) {
1858 states &= ~anv_cmd_dirty_bit_for_vk_dynamic_state(
1859 pCreateInfo->pDynamicState->pDynamicStates[s]);
1860 }
1861 }
1862
1863 struct anv_dynamic_state *dynamic = &pipeline->dynamic_state;
1864
1865 /* Section 9.2 of the Vulkan 1.0.15 spec says:
1866 *
1867 * pViewportState is [...] NULL if the pipeline
1868 * has rasterization disabled.
1869 */
1870 if (!pCreateInfo->pRasterizationState->rasterizerDiscardEnable) {
1871 assert(pCreateInfo->pViewportState);
1872
1873 dynamic->viewport.count = pCreateInfo->pViewportState->viewportCount;
1874 if (states & ANV_CMD_DIRTY_DYNAMIC_VIEWPORT) {
1875 typed_memcpy(dynamic->viewport.viewports,
1876 pCreateInfo->pViewportState->pViewports,
1877 pCreateInfo->pViewportState->viewportCount);
1878 }
1879
1880 dynamic->scissor.count = pCreateInfo->pViewportState->scissorCount;
1881 if (states & ANV_CMD_DIRTY_DYNAMIC_SCISSOR) {
1882 typed_memcpy(dynamic->scissor.scissors,
1883 pCreateInfo->pViewportState->pScissors,
1884 pCreateInfo->pViewportState->scissorCount);
1885 }
1886 }
1887
1888 if (states & ANV_CMD_DIRTY_DYNAMIC_LINE_WIDTH) {
1889 assert(pCreateInfo->pRasterizationState);
1890 dynamic->line_width = pCreateInfo->pRasterizationState->lineWidth;
1891 }
1892
1893 if (states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_BIAS) {
1894 assert(pCreateInfo->pRasterizationState);
1895 dynamic->depth_bias.bias =
1896 pCreateInfo->pRasterizationState->depthBiasConstantFactor;
1897 dynamic->depth_bias.clamp =
1898 pCreateInfo->pRasterizationState->depthBiasClamp;
1899 dynamic->depth_bias.slope =
1900 pCreateInfo->pRasterizationState->depthBiasSlopeFactor;
1901 }
1902
1903 if (states & ANV_CMD_DIRTY_DYNAMIC_CULL_MODE) {
1904 assert(pCreateInfo->pRasterizationState);
1905 dynamic->cull_mode =
1906 pCreateInfo->pRasterizationState->cullMode;
1907 }
1908
1909 if (states & ANV_CMD_DIRTY_DYNAMIC_FRONT_FACE) {
1910 assert(pCreateInfo->pRasterizationState);
1911 dynamic->front_face =
1912 pCreateInfo->pRasterizationState->frontFace;
1913 }
1914
1915 if (states & ANV_CMD_DIRTY_DYNAMIC_PRIMITIVE_TOPOLOGY) {
1916 assert(pCreateInfo->pInputAssemblyState);
1917 bool has_tess = false;
1918 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1919 const VkPipelineShaderStageCreateInfo *sinfo = &pCreateInfo->pStages[i];
1920 gl_shader_stage stage = vk_to_mesa_shader_stage(sinfo->stage);
1921 if (stage == MESA_SHADER_TESS_CTRL || stage == MESA_SHADER_TESS_EVAL)
1922 has_tess = true;
1923 }
1924 if (has_tess) {
1925 const VkPipelineTessellationStateCreateInfo *tess_info =
1926 pCreateInfo->pTessellationState;
1927 dynamic->primitive_topology = _3DPRIM_PATCHLIST(tess_info->patchControlPoints);
1928 } else {
1929 dynamic->primitive_topology = pCreateInfo->pInputAssemblyState->topology;
1930 }
1931 }
1932
1933 /* Section 9.2 of the Vulkan 1.0.15 spec says:
1934 *
1935 * pColorBlendState is [...] NULL if the pipeline has rasterization
1936 * disabled or if the subpass of the render pass the pipeline is
1937 * created against does not use any color attachments.
1938 */
1939 bool uses_color_att = false;
1940 for (unsigned i = 0; i < subpass->color_count; ++i) {
1941 if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED) {
1942 uses_color_att = true;
1943 break;
1944 }
1945 }
1946
1947 if (uses_color_att &&
1948 !pCreateInfo->pRasterizationState->rasterizerDiscardEnable) {
1949 assert(pCreateInfo->pColorBlendState);
1950
1951 if (states & ANV_CMD_DIRTY_DYNAMIC_BLEND_CONSTANTS)
1952 typed_memcpy(dynamic->blend_constants,
1953 pCreateInfo->pColorBlendState->blendConstants, 4);
1954 }
1955
1956 /* If there is no depthstencil attachment, then don't read
1957 * pDepthStencilState. The Vulkan spec states that pDepthStencilState may
1958 * be NULL in this case. Even if pDepthStencilState is non-NULL, there is
1959 * no need to override the depthstencil defaults in
1960 * anv_pipeline::dynamic_state when there is no depthstencil attachment.
1961 *
1962 * Section 9.2 of the Vulkan 1.0.15 spec says:
1963 *
1964 * pDepthStencilState is [...] NULL if the pipeline has rasterization
1965 * disabled or if the subpass of the render pass the pipeline is created
1966 * against does not use a depth/stencil attachment.
1967 */
1968 if (!pCreateInfo->pRasterizationState->rasterizerDiscardEnable &&
1969 subpass->depth_stencil_attachment) {
1970 assert(pCreateInfo->pDepthStencilState);
1971
1972 if (states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_BOUNDS) {
1973 dynamic->depth_bounds.min =
1974 pCreateInfo->pDepthStencilState->minDepthBounds;
1975 dynamic->depth_bounds.max =
1976 pCreateInfo->pDepthStencilState->maxDepthBounds;
1977 }
1978
1979 if (states & ANV_CMD_DIRTY_DYNAMIC_STENCIL_COMPARE_MASK) {
1980 dynamic->stencil_compare_mask.front =
1981 pCreateInfo->pDepthStencilState->front.compareMask;
1982 dynamic->stencil_compare_mask.back =
1983 pCreateInfo->pDepthStencilState->back.compareMask;
1984 }
1985
1986 if (states & ANV_CMD_DIRTY_DYNAMIC_STENCIL_WRITE_MASK) {
1987 dynamic->stencil_write_mask.front =
1988 pCreateInfo->pDepthStencilState->front.writeMask;
1989 dynamic->stencil_write_mask.back =
1990 pCreateInfo->pDepthStencilState->back.writeMask;
1991 }
1992
1993 if (states & ANV_CMD_DIRTY_DYNAMIC_STENCIL_REFERENCE) {
1994 dynamic->stencil_reference.front =
1995 pCreateInfo->pDepthStencilState->front.reference;
1996 dynamic->stencil_reference.back =
1997 pCreateInfo->pDepthStencilState->back.reference;
1998 }
1999
2000 if (states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_TEST_ENABLE) {
2001 dynamic->depth_test_enable =
2002 pCreateInfo->pDepthStencilState->depthTestEnable;
2003 }
2004
2005 if (states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_WRITE_ENABLE) {
2006 dynamic->depth_write_enable =
2007 pCreateInfo->pDepthStencilState->depthWriteEnable;
2008 }
2009
2010 if (states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_COMPARE_OP) {
2011 dynamic->depth_compare_op =
2012 pCreateInfo->pDepthStencilState->depthCompareOp;
2013 }
2014
2015 if (states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_BOUNDS_TEST_ENABLE) {
2016 dynamic->depth_bounds_test_enable =
2017 pCreateInfo->pDepthStencilState->depthBoundsTestEnable;
2018 }
2019
2020 if (states & ANV_CMD_DIRTY_DYNAMIC_STENCIL_TEST_ENABLE) {
2021 dynamic->stencil_test_enable =
2022 pCreateInfo->pDepthStencilState->stencilTestEnable;
2023 }
2024
2025 if (states & ANV_CMD_DIRTY_DYNAMIC_STENCIL_OP) {
2026 const VkPipelineDepthStencilStateCreateInfo *info =
2027 pCreateInfo->pDepthStencilState;
2028 memcpy(&dynamic->stencil_op.front, &info->front,
2029 sizeof(dynamic->stencil_op.front));
2030 memcpy(&dynamic->stencil_op.back, &info->back,
2031 sizeof(dynamic->stencil_op.back));
2032 }
2033 }
2034
2035 const VkPipelineRasterizationLineStateCreateInfoEXT *line_state =
2036 vk_find_struct_const(pCreateInfo->pRasterizationState->pNext,
2037 PIPELINE_RASTERIZATION_LINE_STATE_CREATE_INFO_EXT);
2038 if (line_state) {
2039 if (states & ANV_CMD_DIRTY_DYNAMIC_LINE_STIPPLE) {
2040 dynamic->line_stipple.factor = line_state->lineStippleFactor;
2041 dynamic->line_stipple.pattern = line_state->lineStipplePattern;
2042 }
2043 }
2044
2045 pipeline->dynamic_state_mask = states;
2046 }
2047
2048 static void
2049 anv_pipeline_validate_create_info(const VkGraphicsPipelineCreateInfo *info)
2050 {
2051 #ifdef DEBUG
2052 struct anv_render_pass *renderpass = NULL;
2053 struct anv_subpass *subpass = NULL;
2054
2055 /* Assert that all required members of VkGraphicsPipelineCreateInfo are
2056 * present. See the Vulkan 1.0.28 spec, Section 9.2 Graphics Pipelines.
2057 */
2058 assert(info->sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
2059
2060 renderpass = anv_render_pass_from_handle(info->renderPass);
2061 assert(renderpass);
2062
2063 assert(info->subpass < renderpass->subpass_count);
2064 subpass = &renderpass->subpasses[info->subpass];
2065
2066 assert(info->stageCount >= 1);
2067 assert(info->pVertexInputState);
2068 assert(info->pInputAssemblyState);
2069 assert(info->pRasterizationState);
2070 if (!info->pRasterizationState->rasterizerDiscardEnable) {
2071 assert(info->pViewportState);
2072 assert(info->pMultisampleState);
2073
2074 if (subpass && subpass->depth_stencil_attachment)
2075 assert(info->pDepthStencilState);
2076
2077 if (subpass && subpass->color_count > 0) {
2078 bool all_color_unused = true;
2079 for (int i = 0; i < subpass->color_count; i++) {
2080 if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED)
2081 all_color_unused = false;
2082 }
2083 /* pColorBlendState is ignored if the pipeline has rasterization
2084 * disabled or if the subpass of the render pass the pipeline is
2085 * created against does not use any color attachments.
2086 */
2087 assert(info->pColorBlendState || all_color_unused);
2088 }
2089 }
2090
2091 for (uint32_t i = 0; i < info->stageCount; ++i) {
2092 switch (info->pStages[i].stage) {
2093 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
2094 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
2095 assert(info->pTessellationState);
2096 break;
2097 default:
2098 break;
2099 }
2100 }
2101 #endif
2102 }
2103
2104 /**
2105 * Calculate the desired L3 partitioning based on the current state of the
2106 * pipeline. For now this simply returns the conservative defaults calculated
2107 * by get_default_l3_weights(), but we could probably do better by gathering
2108 * more statistics from the pipeline state (e.g. guess of expected URB usage
2109 * and bound surfaces), or by using feed-back from performance counters.
2110 */
2111 void
2112 anv_pipeline_setup_l3_config(struct anv_pipeline *pipeline, bool needs_slm)
2113 {
2114 const struct gen_device_info *devinfo = &pipeline->device->info;
2115
2116 const struct gen_l3_weights w =
2117 gen_get_default_l3_weights(devinfo, true, needs_slm);
2118
2119 pipeline->l3_config = gen_get_l3_config(devinfo, w);
2120 }
2121
2122 VkResult
2123 anv_graphics_pipeline_init(struct anv_graphics_pipeline *pipeline,
2124 struct anv_device *device,
2125 struct anv_pipeline_cache *cache,
2126 const VkGraphicsPipelineCreateInfo *pCreateInfo,
2127 const VkAllocationCallbacks *alloc)
2128 {
2129 VkResult result;
2130
2131 anv_pipeline_validate_create_info(pCreateInfo);
2132
2133 result = anv_pipeline_init(&pipeline->base, device,
2134 ANV_PIPELINE_GRAPHICS, pCreateInfo->flags,
2135 alloc);
2136 if (result != VK_SUCCESS)
2137 return result;
2138
2139 anv_batch_set_storage(&pipeline->base.batch, ANV_NULL_ADDRESS,
2140 pipeline->batch_data, sizeof(pipeline->batch_data));
2141
2142 ANV_FROM_HANDLE(anv_render_pass, render_pass, pCreateInfo->renderPass);
2143 assert(pCreateInfo->subpass < render_pass->subpass_count);
2144 pipeline->subpass = &render_pass->subpasses[pCreateInfo->subpass];
2145
2146 assert(pCreateInfo->pRasterizationState);
2147
2148 copy_non_dynamic_state(pipeline, pCreateInfo);
2149 pipeline->depth_clamp_enable = pCreateInfo->pRasterizationState->depthClampEnable;
2150
2151 /* Previously we enabled depth clipping when !depthClampEnable.
2152 * DepthClipStateCreateInfo now makes depth clipping explicit so if the
2153 * clipping info is available, use its enable value to determine clipping,
2154 * otherwise fallback to the previous !depthClampEnable logic.
2155 */
2156 const VkPipelineRasterizationDepthClipStateCreateInfoEXT *clip_info =
2157 vk_find_struct_const(pCreateInfo->pRasterizationState->pNext,
2158 PIPELINE_RASTERIZATION_DEPTH_CLIP_STATE_CREATE_INFO_EXT);
2159 pipeline->depth_clip_enable = clip_info ? clip_info->depthClipEnable : !pipeline->depth_clamp_enable;
2160
2161 pipeline->sample_shading_enable =
2162 !pCreateInfo->pRasterizationState->rasterizerDiscardEnable &&
2163 pCreateInfo->pMultisampleState &&
2164 pCreateInfo->pMultisampleState->sampleShadingEnable;
2165
2166 /* When we free the pipeline, we detect stages based on the NULL status
2167 * of various prog_data pointers. Make them NULL by default.
2168 */
2169 memset(pipeline->shaders, 0, sizeof(pipeline->shaders));
2170
2171 result = anv_pipeline_compile_graphics(pipeline, cache, pCreateInfo);
2172 if (result != VK_SUCCESS) {
2173 anv_pipeline_finish(&pipeline->base, device, alloc);
2174 return result;
2175 }
2176
2177 assert(pipeline->shaders[MESA_SHADER_VERTEX]);
2178
2179 anv_pipeline_setup_l3_config(&pipeline->base, false);
2180
2181 const VkPipelineVertexInputStateCreateInfo *vi_info =
2182 pCreateInfo->pVertexInputState;
2183
2184 const uint64_t inputs_read = get_vs_prog_data(pipeline)->inputs_read;
2185
2186 pipeline->vb_used = 0;
2187 for (uint32_t i = 0; i < vi_info->vertexAttributeDescriptionCount; i++) {
2188 const VkVertexInputAttributeDescription *desc =
2189 &vi_info->pVertexAttributeDescriptions[i];
2190
2191 if (inputs_read & (1ull << (VERT_ATTRIB_GENERIC0 + desc->location)))
2192 pipeline->vb_used |= 1 << desc->binding;
2193 }
2194
2195 for (uint32_t i = 0; i < vi_info->vertexBindingDescriptionCount; i++) {
2196 const VkVertexInputBindingDescription *desc =
2197 &vi_info->pVertexBindingDescriptions[i];
2198
2199 pipeline->vb[desc->binding].stride = desc->stride;
2200
2201 /* Step rate is programmed per vertex element (attribute), not
2202 * binding. Set up a map of which bindings step per instance, for
2203 * reference by vertex element setup. */
2204 switch (desc->inputRate) {
2205 default:
2206 case VK_VERTEX_INPUT_RATE_VERTEX:
2207 pipeline->vb[desc->binding].instanced = false;
2208 break;
2209 case VK_VERTEX_INPUT_RATE_INSTANCE:
2210 pipeline->vb[desc->binding].instanced = true;
2211 break;
2212 }
2213
2214 pipeline->vb[desc->binding].instance_divisor = 1;
2215 }
2216
2217 const VkPipelineVertexInputDivisorStateCreateInfoEXT *vi_div_state =
2218 vk_find_struct_const(vi_info->pNext,
2219 PIPELINE_VERTEX_INPUT_DIVISOR_STATE_CREATE_INFO_EXT);
2220 if (vi_div_state) {
2221 for (uint32_t i = 0; i < vi_div_state->vertexBindingDivisorCount; i++) {
2222 const VkVertexInputBindingDivisorDescriptionEXT *desc =
2223 &vi_div_state->pVertexBindingDivisors[i];
2224
2225 pipeline->vb[desc->binding].instance_divisor = desc->divisor;
2226 }
2227 }
2228
2229 /* Our implementation of VK_KHR_multiview uses instancing to draw the
2230 * different views. If the client asks for instancing, we need to multiply
2231 * the instance divisor by the number of views ensure that we repeat the
2232 * client's per-instance data once for each view.
2233 */
2234 if (pipeline->subpass->view_mask && !pipeline->use_primitive_replication) {
2235 const uint32_t view_count = anv_subpass_view_count(pipeline->subpass);
2236 for (uint32_t vb = 0; vb < MAX_VBS; vb++) {
2237 if (pipeline->vb[vb].instanced)
2238 pipeline->vb[vb].instance_divisor *= view_count;
2239 }
2240 }
2241
2242 const VkPipelineInputAssemblyStateCreateInfo *ia_info =
2243 pCreateInfo->pInputAssemblyState;
2244 const VkPipelineTessellationStateCreateInfo *tess_info =
2245 pCreateInfo->pTessellationState;
2246 pipeline->primitive_restart = ia_info->primitiveRestartEnable;
2247
2248 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL))
2249 pipeline->topology = _3DPRIM_PATCHLIST(tess_info->patchControlPoints);
2250 else
2251 pipeline->topology = vk_to_gen_primitive_type[ia_info->topology];
2252
2253 return VK_SUCCESS;
2254 }
2255
2256 #define WRITE_STR(field, ...) ({ \
2257 memset(field, 0, sizeof(field)); \
2258 UNUSED int i = snprintf(field, sizeof(field), __VA_ARGS__); \
2259 assert(i > 0 && i < sizeof(field)); \
2260 })
2261
2262 VkResult anv_GetPipelineExecutablePropertiesKHR(
2263 VkDevice device,
2264 const VkPipelineInfoKHR* pPipelineInfo,
2265 uint32_t* pExecutableCount,
2266 VkPipelineExecutablePropertiesKHR* pProperties)
2267 {
2268 ANV_FROM_HANDLE(anv_pipeline, pipeline, pPipelineInfo->pipeline);
2269 VK_OUTARRAY_MAKE(out, pProperties, pExecutableCount);
2270
2271 util_dynarray_foreach (&pipeline->executables, struct anv_pipeline_executable, exe) {
2272 vk_outarray_append(&out, props) {
2273 gl_shader_stage stage = exe->stage;
2274 props->stages = mesa_to_vk_shader_stage(stage);
2275
2276 unsigned simd_width = exe->stats.dispatch_width;
2277 if (stage == MESA_SHADER_FRAGMENT) {
2278 WRITE_STR(props->name, "%s%d %s",
2279 simd_width ? "SIMD" : "vec",
2280 simd_width ? simd_width : 4,
2281 _mesa_shader_stage_to_string(stage));
2282 } else {
2283 WRITE_STR(props->name, "%s", _mesa_shader_stage_to_string(stage));
2284 }
2285 WRITE_STR(props->description, "%s%d %s shader",
2286 simd_width ? "SIMD" : "vec",
2287 simd_width ? simd_width : 4,
2288 _mesa_shader_stage_to_string(stage));
2289
2290 /* The compiler gives us a dispatch width of 0 for vec4 but Vulkan
2291 * wants a subgroup size of 1.
2292 */
2293 props->subgroupSize = MAX2(simd_width, 1);
2294 }
2295 }
2296
2297 return vk_outarray_status(&out);
2298 }
2299
2300 static const struct anv_pipeline_executable *
2301 anv_pipeline_get_executable(struct anv_pipeline *pipeline, uint32_t index)
2302 {
2303 assert(index < util_dynarray_num_elements(&pipeline->executables,
2304 struct anv_pipeline_executable));
2305 return util_dynarray_element(
2306 &pipeline->executables, struct anv_pipeline_executable, index);
2307 }
2308
2309 VkResult anv_GetPipelineExecutableStatisticsKHR(
2310 VkDevice device,
2311 const VkPipelineExecutableInfoKHR* pExecutableInfo,
2312 uint32_t* pStatisticCount,
2313 VkPipelineExecutableStatisticKHR* pStatistics)
2314 {
2315 ANV_FROM_HANDLE(anv_pipeline, pipeline, pExecutableInfo->pipeline);
2316 VK_OUTARRAY_MAKE(out, pStatistics, pStatisticCount);
2317
2318 const struct anv_pipeline_executable *exe =
2319 anv_pipeline_get_executable(pipeline, pExecutableInfo->executableIndex);
2320
2321 const struct brw_stage_prog_data *prog_data;
2322 switch (pipeline->type) {
2323 case ANV_PIPELINE_GRAPHICS: {
2324 prog_data = anv_pipeline_to_graphics(pipeline)->shaders[exe->stage]->prog_data;
2325 break;
2326 }
2327 case ANV_PIPELINE_COMPUTE: {
2328 prog_data = anv_pipeline_to_compute(pipeline)->cs->prog_data;
2329 break;
2330 }
2331 default:
2332 unreachable("invalid pipeline type");
2333 }
2334
2335 vk_outarray_append(&out, stat) {
2336 WRITE_STR(stat->name, "Instruction Count");
2337 WRITE_STR(stat->description,
2338 "Number of GEN instructions in the final generated "
2339 "shader executable.");
2340 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2341 stat->value.u64 = exe->stats.instructions;
2342 }
2343
2344 vk_outarray_append(&out, stat) {
2345 WRITE_STR(stat->name, "SEND Count");
2346 WRITE_STR(stat->description,
2347 "Number of instructions in the final generated shader "
2348 "executable which access external units such as the "
2349 "constant cache or the sampler.");
2350 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2351 stat->value.u64 = exe->stats.sends;
2352 }
2353
2354 vk_outarray_append(&out, stat) {
2355 WRITE_STR(stat->name, "Loop Count");
2356 WRITE_STR(stat->description,
2357 "Number of loops (not unrolled) in the final generated "
2358 "shader executable.");
2359 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2360 stat->value.u64 = exe->stats.loops;
2361 }
2362
2363 vk_outarray_append(&out, stat) {
2364 WRITE_STR(stat->name, "Cycle Count");
2365 WRITE_STR(stat->description,
2366 "Estimate of the number of EU cycles required to execute "
2367 "the final generated executable. This is an estimate only "
2368 "and may vary greatly from actual run-time performance.");
2369 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2370 stat->value.u64 = exe->stats.cycles;
2371 }
2372
2373 vk_outarray_append(&out, stat) {
2374 WRITE_STR(stat->name, "Spill Count");
2375 WRITE_STR(stat->description,
2376 "Number of scratch spill operations. This gives a rough "
2377 "estimate of the cost incurred due to spilling temporary "
2378 "values to memory. If this is non-zero, you may want to "
2379 "adjust your shader to reduce register pressure.");
2380 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2381 stat->value.u64 = exe->stats.spills;
2382 }
2383
2384 vk_outarray_append(&out, stat) {
2385 WRITE_STR(stat->name, "Fill Count");
2386 WRITE_STR(stat->description,
2387 "Number of scratch fill operations. This gives a rough "
2388 "estimate of the cost incurred due to spilling temporary "
2389 "values to memory. If this is non-zero, you may want to "
2390 "adjust your shader to reduce register pressure.");
2391 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2392 stat->value.u64 = exe->stats.fills;
2393 }
2394
2395 vk_outarray_append(&out, stat) {
2396 WRITE_STR(stat->name, "Scratch Memory Size");
2397 WRITE_STR(stat->description,
2398 "Number of bytes of scratch memory required by the "
2399 "generated shader executable. If this is non-zero, you "
2400 "may want to adjust your shader to reduce register "
2401 "pressure.");
2402 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2403 stat->value.u64 = prog_data->total_scratch;
2404 }
2405
2406 if (exe->stage == MESA_SHADER_COMPUTE) {
2407 vk_outarray_append(&out, stat) {
2408 WRITE_STR(stat->name, "Workgroup Memory Size");
2409 WRITE_STR(stat->description,
2410 "Number of bytes of workgroup shared memory used by this "
2411 "compute shader including any padding.");
2412 stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2413 stat->value.u64 = brw_cs_prog_data_const(prog_data)->slm_size;
2414 }
2415 }
2416
2417 return vk_outarray_status(&out);
2418 }
2419
2420 static bool
2421 write_ir_text(VkPipelineExecutableInternalRepresentationKHR* ir,
2422 const char *data)
2423 {
2424 ir->isText = VK_TRUE;
2425
2426 size_t data_len = strlen(data) + 1;
2427
2428 if (ir->pData == NULL) {
2429 ir->dataSize = data_len;
2430 return true;
2431 }
2432
2433 strncpy(ir->pData, data, ir->dataSize);
2434 if (ir->dataSize < data_len)
2435 return false;
2436
2437 ir->dataSize = data_len;
2438 return true;
2439 }
2440
2441 VkResult anv_GetPipelineExecutableInternalRepresentationsKHR(
2442 VkDevice device,
2443 const VkPipelineExecutableInfoKHR* pExecutableInfo,
2444 uint32_t* pInternalRepresentationCount,
2445 VkPipelineExecutableInternalRepresentationKHR* pInternalRepresentations)
2446 {
2447 ANV_FROM_HANDLE(anv_pipeline, pipeline, pExecutableInfo->pipeline);
2448 VK_OUTARRAY_MAKE(out, pInternalRepresentations,
2449 pInternalRepresentationCount);
2450 bool incomplete_text = false;
2451
2452 const struct anv_pipeline_executable *exe =
2453 anv_pipeline_get_executable(pipeline, pExecutableInfo->executableIndex);
2454
2455 if (exe->nir) {
2456 vk_outarray_append(&out, ir) {
2457 WRITE_STR(ir->name, "Final NIR");
2458 WRITE_STR(ir->description,
2459 "Final NIR before going into the back-end compiler");
2460
2461 if (!write_ir_text(ir, exe->nir))
2462 incomplete_text = true;
2463 }
2464 }
2465
2466 if (exe->disasm) {
2467 vk_outarray_append(&out, ir) {
2468 WRITE_STR(ir->name, "GEN Assembly");
2469 WRITE_STR(ir->description,
2470 "Final GEN assembly for the generated shader binary");
2471
2472 if (!write_ir_text(ir, exe->disasm))
2473 incomplete_text = true;
2474 }
2475 }
2476
2477 return incomplete_text ? VK_INCOMPLETE : vk_outarray_status(&out);
2478 }