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