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