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