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