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