ad0f08253e72125a62e2d543b3f0afcb0875c0cd
[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 "common/gen_l3_config.h"
32 #include "anv_private.h"
33 #include "compiler/brw_nir.h"
34 #include "anv_nir.h"
35 #include "spirv/nir_spirv.h"
36 #include "vk_util.h"
37
38 /* Needed for SWIZZLE macros */
39 #include "program/prog_instruction.h"
40
41 // Shader functions
42
43 VkResult anv_CreateShaderModule(
44 VkDevice _device,
45 const VkShaderModuleCreateInfo* pCreateInfo,
46 const VkAllocationCallbacks* pAllocator,
47 VkShaderModule* pShaderModule)
48 {
49 ANV_FROM_HANDLE(anv_device, device, _device);
50 struct anv_shader_module *module;
51
52 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
53 assert(pCreateInfo->flags == 0);
54
55 module = vk_alloc2(&device->alloc, pAllocator,
56 sizeof(*module) + pCreateInfo->codeSize, 8,
57 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
58 if (module == NULL)
59 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
60
61 module->size = pCreateInfo->codeSize;
62 memcpy(module->data, pCreateInfo->pCode, module->size);
63
64 _mesa_sha1_compute(module->data, module->size, module->sha1);
65
66 *pShaderModule = anv_shader_module_to_handle(module);
67
68 return VK_SUCCESS;
69 }
70
71 void anv_DestroyShaderModule(
72 VkDevice _device,
73 VkShaderModule _module,
74 const VkAllocationCallbacks* pAllocator)
75 {
76 ANV_FROM_HANDLE(anv_device, device, _device);
77 ANV_FROM_HANDLE(anv_shader_module, module, _module);
78
79 if (!module)
80 return;
81
82 vk_free2(&device->alloc, pAllocator, module);
83 }
84
85 #define SPIR_V_MAGIC_NUMBER 0x07230203
86
87 static const uint64_t stage_to_debug[] = {
88 [MESA_SHADER_VERTEX] = DEBUG_VS,
89 [MESA_SHADER_TESS_CTRL] = DEBUG_TCS,
90 [MESA_SHADER_TESS_EVAL] = DEBUG_TES,
91 [MESA_SHADER_GEOMETRY] = DEBUG_GS,
92 [MESA_SHADER_FRAGMENT] = DEBUG_WM,
93 [MESA_SHADER_COMPUTE] = DEBUG_CS,
94 };
95
96 /* Eventually, this will become part of anv_CreateShader. Unfortunately,
97 * we can't do that yet because we don't have the ability to copy nir.
98 */
99 static nir_shader *
100 anv_shader_compile_to_nir(struct anv_pipeline *pipeline,
101 void *mem_ctx,
102 const struct anv_shader_module *module,
103 const char *entrypoint_name,
104 gl_shader_stage stage,
105 const VkSpecializationInfo *spec_info)
106 {
107 const struct anv_device *device = pipeline->device;
108
109 const struct brw_compiler *compiler =
110 device->instance->physicalDevice.compiler;
111 const nir_shader_compiler_options *nir_options =
112 compiler->glsl_compiler_options[stage].NirOptions;
113
114 uint32_t *spirv = (uint32_t *) module->data;
115 assert(spirv[0] == SPIR_V_MAGIC_NUMBER);
116 assert(module->size % 4 == 0);
117
118 uint32_t num_spec_entries = 0;
119 struct nir_spirv_specialization *spec_entries = NULL;
120 if (spec_info && spec_info->mapEntryCount > 0) {
121 num_spec_entries = spec_info->mapEntryCount;
122 spec_entries = malloc(num_spec_entries * sizeof(*spec_entries));
123 for (uint32_t i = 0; i < num_spec_entries; i++) {
124 VkSpecializationMapEntry entry = spec_info->pMapEntries[i];
125 const void *data = spec_info->pData + entry.offset;
126 assert(data + entry.size <= spec_info->pData + spec_info->dataSize);
127
128 spec_entries[i].id = spec_info->pMapEntries[i].constantID;
129 if (spec_info->dataSize == 8)
130 spec_entries[i].data64 = *(const uint64_t *)data;
131 else
132 spec_entries[i].data32 = *(const uint32_t *)data;
133 }
134 }
135
136 struct spirv_to_nir_options spirv_options = {
137 .lower_workgroup_access_to_offsets = true,
138 .caps = {
139 .float64 = device->instance->physicalDevice.info.gen >= 8,
140 .int64 = device->instance->physicalDevice.info.gen >= 8,
141 .tessellation = true,
142 .device_group = true,
143 .draw_parameters = true,
144 .image_write_without_format = true,
145 .multiview = true,
146 .variable_pointers = true,
147 .storage_16bit = device->instance->physicalDevice.info.gen >= 8,
148 .int16 = device->instance->physicalDevice.info.gen >= 8,
149 .shader_viewport_index_layer = true,
150 .subgroup_arithmetic = true,
151 .subgroup_basic = true,
152 .subgroup_ballot = true,
153 .subgroup_quad = true,
154 .subgroup_shuffle = true,
155 .subgroup_vote = true,
156 .stencil_export = device->instance->physicalDevice.info.gen >= 9,
157 .storage_8bit = device->instance->physicalDevice.info.gen >= 8,
158 .post_depth_coverage = device->instance->physicalDevice.info.gen >= 9,
159 },
160 };
161
162 nir_function *entry_point =
163 spirv_to_nir(spirv, module->size / 4,
164 spec_entries, num_spec_entries,
165 stage, entrypoint_name, &spirv_options, nir_options);
166 nir_shader *nir = entry_point->shader;
167 assert(nir->info.stage == stage);
168 nir_validate_shader(nir, "after spirv_to_nir");
169 ralloc_steal(mem_ctx, nir);
170
171 free(spec_entries);
172
173 if (unlikely(INTEL_DEBUG & stage_to_debug[stage])) {
174 fprintf(stderr, "NIR (from SPIR-V) for %s shader:\n",
175 gl_shader_stage_name(stage));
176 nir_print_shader(nir, stderr);
177 }
178
179 /* We have to lower away local constant initializers right before we
180 * inline functions. That way they get properly initialized at the top
181 * of the function and not at the top of its caller.
182 */
183 NIR_PASS_V(nir, nir_lower_constant_initializers, nir_var_local);
184 NIR_PASS_V(nir, nir_lower_returns);
185 NIR_PASS_V(nir, nir_inline_functions);
186 NIR_PASS_V(nir, nir_copy_prop);
187
188 /* Pick off the single entrypoint that we want */
189 foreach_list_typed_safe(nir_function, func, node, &nir->functions) {
190 if (func != entry_point)
191 exec_node_remove(&func->node);
192 }
193 assert(exec_list_length(&nir->functions) == 1);
194
195 /* Now that we've deleted all but the main function, we can go ahead and
196 * lower the rest of the constant initializers. We do this here so that
197 * nir_remove_dead_variables and split_per_member_structs below see the
198 * corresponding stores.
199 */
200 NIR_PASS_V(nir, nir_lower_constant_initializers, ~0);
201
202 /* Split member structs. We do this before lower_io_to_temporaries so that
203 * it doesn't lower system values to temporaries by accident.
204 */
205 NIR_PASS_V(nir, nir_split_var_copies);
206 NIR_PASS_V(nir, nir_split_per_member_structs);
207
208 NIR_PASS_V(nir, nir_remove_dead_variables,
209 nir_var_shader_in | nir_var_shader_out | nir_var_system_value);
210
211 if (stage == MESA_SHADER_FRAGMENT)
212 NIR_PASS_V(nir, nir_lower_wpos_center, pipeline->sample_shading_enable);
213
214 NIR_PASS_V(nir, nir_propagate_invariant);
215 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
216 entry_point->impl, true, false);
217
218 /* Vulkan uses the separate-shader linking model */
219 nir->info.separate_shader = true;
220
221 nir = brw_preprocess_nir(compiler, nir);
222
223 if (stage == MESA_SHADER_FRAGMENT)
224 NIR_PASS_V(nir, anv_nir_lower_input_attachments);
225
226 return nir;
227 }
228
229 void anv_DestroyPipeline(
230 VkDevice _device,
231 VkPipeline _pipeline,
232 const VkAllocationCallbacks* pAllocator)
233 {
234 ANV_FROM_HANDLE(anv_device, device, _device);
235 ANV_FROM_HANDLE(anv_pipeline, pipeline, _pipeline);
236
237 if (!pipeline)
238 return;
239
240 anv_reloc_list_finish(&pipeline->batch_relocs,
241 pAllocator ? pAllocator : &device->alloc);
242 if (pipeline->blend_state.map)
243 anv_state_pool_free(&device->dynamic_state_pool, pipeline->blend_state);
244
245 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
246 if (pipeline->shaders[s])
247 anv_shader_bin_unref(device, pipeline->shaders[s]);
248 }
249
250 vk_free2(&device->alloc, pAllocator, pipeline);
251 }
252
253 static const uint32_t vk_to_gen_primitive_type[] = {
254 [VK_PRIMITIVE_TOPOLOGY_POINT_LIST] = _3DPRIM_POINTLIST,
255 [VK_PRIMITIVE_TOPOLOGY_LINE_LIST] = _3DPRIM_LINELIST,
256 [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP] = _3DPRIM_LINESTRIP,
257 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST] = _3DPRIM_TRILIST,
258 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP] = _3DPRIM_TRISTRIP,
259 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN] = _3DPRIM_TRIFAN,
260 [VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY] = _3DPRIM_LINELIST_ADJ,
261 [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY] = _3DPRIM_LINESTRIP_ADJ,
262 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY] = _3DPRIM_TRILIST_ADJ,
263 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY] = _3DPRIM_TRISTRIP_ADJ,
264 };
265
266 static void
267 populate_sampler_prog_key(const struct gen_device_info *devinfo,
268 struct brw_sampler_prog_key_data *key)
269 {
270 /* Almost all multisampled textures are compressed. The only time when we
271 * don't compress a multisampled texture is for 16x MSAA with a surface
272 * width greater than 8k which is a bit of an edge case. Since the sampler
273 * just ignores the MCS parameter to ld2ms when MCS is disabled, it's safe
274 * to tell the compiler to always assume compression.
275 */
276 key->compressed_multisample_layout_mask = ~0;
277
278 /* SkyLake added support for 16x MSAA. With this came a new message for
279 * reading from a 16x MSAA surface with compression. The new message was
280 * needed because now the MCS data is 64 bits instead of 32 or lower as is
281 * the case for 8x, 4x, and 2x. The key->msaa_16 bit-field controls which
282 * message we use. Fortunately, the 16x message works for 8x, 4x, and 2x
283 * so we can just use it unconditionally. This may not be quite as
284 * efficient but it saves us from recompiling.
285 */
286 if (devinfo->gen >= 9)
287 key->msaa_16 = ~0;
288
289 /* XXX: Handle texture swizzle on HSW- */
290 for (int i = 0; i < MAX_SAMPLERS; i++) {
291 /* Assume color sampler, no swizzling. (Works for BDW+) */
292 key->swizzles[i] = SWIZZLE_XYZW;
293 }
294 }
295
296 static void
297 populate_vs_prog_key(const struct gen_device_info *devinfo,
298 struct brw_vs_prog_key *key)
299 {
300 memset(key, 0, sizeof(*key));
301
302 populate_sampler_prog_key(devinfo, &key->tex);
303
304 /* XXX: Handle vertex input work-arounds */
305
306 /* XXX: Handle sampler_prog_key */
307 }
308
309 static void
310 populate_tcs_prog_key(const struct gen_device_info *devinfo,
311 unsigned input_vertices,
312 struct brw_tcs_prog_key *key)
313 {
314 memset(key, 0, sizeof(*key));
315
316 populate_sampler_prog_key(devinfo, &key->tex);
317
318 key->input_vertices = input_vertices;
319 }
320
321 static void
322 populate_tes_prog_key(const struct gen_device_info *devinfo,
323 struct brw_tes_prog_key *key)
324 {
325 memset(key, 0, sizeof(*key));
326
327 populate_sampler_prog_key(devinfo, &key->tex);
328 }
329
330 static void
331 populate_gs_prog_key(const struct gen_device_info *devinfo,
332 struct brw_gs_prog_key *key)
333 {
334 memset(key, 0, sizeof(*key));
335
336 populate_sampler_prog_key(devinfo, &key->tex);
337 }
338
339 static void
340 populate_wm_prog_key(const struct gen_device_info *devinfo,
341 const struct anv_subpass *subpass,
342 const VkPipelineMultisampleStateCreateInfo *ms_info,
343 struct brw_wm_prog_key *key)
344 {
345 memset(key, 0, sizeof(*key));
346
347 populate_sampler_prog_key(devinfo, &key->tex);
348
349 /* We set this to 0 here and set to the actual value before we call
350 * brw_compile_fs.
351 */
352 key->input_slots_valid = 0;
353
354 /* Vulkan doesn't specify a default */
355 key->high_quality_derivatives = false;
356
357 /* XXX Vulkan doesn't appear to specify */
358 key->clamp_fragment_color = false;
359
360 assert(subpass->color_count <= MAX_RTS);
361 for (uint32_t i = 0; i < subpass->color_count; i++) {
362 if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED)
363 key->color_outputs_valid |= (1 << i);
364 }
365
366 key->nr_color_regions = util_bitcount(key->color_outputs_valid);
367
368 key->replicate_alpha = key->nr_color_regions > 1 &&
369 ms_info && ms_info->alphaToCoverageEnable;
370
371 if (ms_info) {
372 /* We should probably pull this out of the shader, but it's fairly
373 * harmless to compute it and then let dead-code take care of it.
374 */
375 if (ms_info->rasterizationSamples > 1) {
376 key->persample_interp =
377 (ms_info->minSampleShading * ms_info->rasterizationSamples) > 1;
378 key->multisample_fbo = true;
379 }
380
381 key->frag_coord_adds_sample_pos = ms_info->sampleShadingEnable;
382 }
383 }
384
385 static void
386 populate_cs_prog_key(const struct gen_device_info *devinfo,
387 struct brw_cs_prog_key *key)
388 {
389 memset(key, 0, sizeof(*key));
390
391 populate_sampler_prog_key(devinfo, &key->tex);
392 }
393
394 struct anv_pipeline_stage {
395 gl_shader_stage stage;
396
397 const struct anv_shader_module *module;
398 const char *entrypoint;
399 const VkSpecializationInfo *spec_info;
400
401 union brw_any_prog_key key;
402
403 struct {
404 gl_shader_stage stage;
405 unsigned char sha1[20];
406 } cache_key;
407
408 nir_shader *nir;
409
410 struct anv_pipeline_binding surface_to_descriptor[256];
411 struct anv_pipeline_binding sampler_to_descriptor[256];
412 struct anv_pipeline_bind_map bind_map;
413
414 union brw_any_prog_data prog_data;
415 };
416
417 static void
418 anv_pipeline_hash_shader(struct mesa_sha1 *ctx,
419 struct anv_pipeline_stage *stage)
420 {
421 _mesa_sha1_update(ctx, stage->module->sha1, sizeof(stage->module->sha1));
422 _mesa_sha1_update(ctx, stage->entrypoint, strlen(stage->entrypoint));
423 _mesa_sha1_update(ctx, &stage->stage, sizeof(stage->stage));
424 if (stage->spec_info) {
425 _mesa_sha1_update(ctx, stage->spec_info->pMapEntries,
426 stage->spec_info->mapEntryCount *
427 sizeof(*stage->spec_info->pMapEntries));
428 _mesa_sha1_update(ctx, stage->spec_info->pData,
429 stage->spec_info->dataSize);
430 }
431 _mesa_sha1_update(ctx, &stage->key, brw_prog_key_size(stage->stage));
432 }
433
434 static void
435 anv_pipeline_hash_graphics(struct anv_pipeline *pipeline,
436 struct anv_pipeline_layout *layout,
437 struct anv_pipeline_stage *stages,
438 unsigned char *sha1_out)
439 {
440 struct mesa_sha1 ctx;
441 _mesa_sha1_init(&ctx);
442
443 _mesa_sha1_update(&ctx, &pipeline->subpass->view_mask,
444 sizeof(pipeline->subpass->view_mask));
445
446 if (layout)
447 _mesa_sha1_update(&ctx, layout->sha1, sizeof(layout->sha1));
448
449 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
450 if (stages[s].entrypoint)
451 anv_pipeline_hash_shader(&ctx, &stages[s]);
452 }
453
454 _mesa_sha1_final(&ctx, sha1_out);
455 }
456
457 static void
458 anv_pipeline_hash_compute(struct anv_pipeline *pipeline,
459 struct anv_pipeline_layout *layout,
460 struct anv_pipeline_stage *stage,
461 unsigned char *sha1_out)
462 {
463 struct mesa_sha1 ctx;
464 _mesa_sha1_init(&ctx);
465
466 if (layout)
467 _mesa_sha1_update(&ctx, layout->sha1, sizeof(layout->sha1));
468
469 anv_pipeline_hash_shader(&ctx, stage);
470
471 _mesa_sha1_final(&ctx, sha1_out);
472 }
473
474 static void
475 anv_pipeline_lower_nir(struct anv_pipeline *pipeline,
476 void *mem_ctx,
477 struct anv_pipeline_stage *stage,
478 struct anv_pipeline_layout *layout)
479 {
480 const struct brw_compiler *compiler =
481 pipeline->device->instance->physicalDevice.compiler;
482
483 struct brw_stage_prog_data *prog_data = &stage->prog_data.base;
484 nir_shader *nir = stage->nir;
485
486 NIR_PASS_V(nir, anv_nir_lower_ycbcr_textures, layout);
487
488 NIR_PASS_V(nir, anv_nir_lower_push_constants);
489
490 if (nir->info.stage != MESA_SHADER_COMPUTE)
491 NIR_PASS_V(nir, anv_nir_lower_multiview, pipeline->subpass->view_mask);
492
493 if (nir->info.stage == MESA_SHADER_COMPUTE)
494 prog_data->total_shared = nir->num_shared;
495
496 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
497
498 if (nir->num_uniforms > 0) {
499 assert(prog_data->nr_params == 0);
500
501 /* If the shader uses any push constants at all, we'll just give
502 * them the maximum possible number
503 */
504 assert(nir->num_uniforms <= MAX_PUSH_CONSTANTS_SIZE);
505 nir->num_uniforms = MAX_PUSH_CONSTANTS_SIZE;
506 prog_data->nr_params += MAX_PUSH_CONSTANTS_SIZE / sizeof(float);
507 prog_data->param = ralloc_array(mem_ctx, uint32_t, prog_data->nr_params);
508
509 /* We now set the param values to be offsets into a
510 * anv_push_constant_data structure. Since the compiler doesn't
511 * actually dereference any of the gl_constant_value pointers in the
512 * params array, it doesn't really matter what we put here.
513 */
514 struct anv_push_constants *null_data = NULL;
515 /* Fill out the push constants section of the param array */
516 for (unsigned i = 0; i < MAX_PUSH_CONSTANTS_SIZE / sizeof(float); i++) {
517 prog_data->param[i] = ANV_PARAM_PUSH(
518 (uintptr_t)&null_data->client_data[i * sizeof(float)]);
519 }
520 }
521
522 if (nir->info.num_ssbos > 0 || nir->info.num_images > 0)
523 pipeline->needs_data_cache = true;
524
525 NIR_PASS_V(nir, brw_nir_lower_image_load_store, compiler->devinfo);
526
527 /* Apply the actual pipeline layout to UBOs, SSBOs, and textures */
528 if (layout) {
529 anv_nir_apply_pipeline_layout(pipeline, layout, nir, prog_data,
530 &stage->bind_map);
531 }
532
533 if (nir->info.stage != MESA_SHADER_COMPUTE)
534 brw_nir_analyze_ubo_ranges(compiler, nir, NULL, prog_data->ubo_ranges);
535
536 assert(nir->num_uniforms == prog_data->nr_params * 4);
537
538 stage->nir = nir;
539 }
540
541 static void
542 anv_fill_binding_table(struct brw_stage_prog_data *prog_data, unsigned bias)
543 {
544 prog_data->binding_table.size_bytes = 0;
545 prog_data->binding_table.texture_start = bias;
546 prog_data->binding_table.gather_texture_start = bias;
547 prog_data->binding_table.ubo_start = bias;
548 prog_data->binding_table.ssbo_start = bias;
549 prog_data->binding_table.image_start = bias;
550 }
551
552 static void
553 anv_pipeline_link_vs(const struct brw_compiler *compiler,
554 struct anv_pipeline_stage *vs_stage,
555 struct anv_pipeline_stage *next_stage)
556 {
557 anv_fill_binding_table(&vs_stage->prog_data.vs.base.base, 0);
558
559 if (next_stage)
560 brw_nir_link_shaders(compiler, &vs_stage->nir, &next_stage->nir);
561 }
562
563 static const unsigned *
564 anv_pipeline_compile_vs(const struct brw_compiler *compiler,
565 void *mem_ctx,
566 struct anv_pipeline_stage *vs_stage)
567 {
568 brw_compute_vue_map(compiler->devinfo,
569 &vs_stage->prog_data.vs.base.vue_map,
570 vs_stage->nir->info.outputs_written,
571 vs_stage->nir->info.separate_shader);
572
573 return brw_compile_vs(compiler, NULL, mem_ctx, &vs_stage->key.vs,
574 &vs_stage->prog_data.vs, vs_stage->nir, -1, NULL);
575 }
576
577 static void
578 merge_tess_info(struct shader_info *tes_info,
579 const struct shader_info *tcs_info)
580 {
581 /* The Vulkan 1.0.38 spec, section 21.1 Tessellator says:
582 *
583 * "PointMode. Controls generation of points rather than triangles
584 * or lines. This functionality defaults to disabled, and is
585 * enabled if either shader stage includes the execution mode.
586 *
587 * and about Triangles, Quads, IsoLines, VertexOrderCw, VertexOrderCcw,
588 * PointMode, SpacingEqual, SpacingFractionalEven, SpacingFractionalOdd,
589 * and OutputVertices, it says:
590 *
591 * "One mode must be set in at least one of the tessellation
592 * shader stages."
593 *
594 * So, the fields can be set in either the TCS or TES, but they must
595 * agree if set in both. Our backend looks at TES, so bitwise-or in
596 * the values from the TCS.
597 */
598 assert(tcs_info->tess.tcs_vertices_out == 0 ||
599 tes_info->tess.tcs_vertices_out == 0 ||
600 tcs_info->tess.tcs_vertices_out == tes_info->tess.tcs_vertices_out);
601 tes_info->tess.tcs_vertices_out |= tcs_info->tess.tcs_vertices_out;
602
603 assert(tcs_info->tess.spacing == TESS_SPACING_UNSPECIFIED ||
604 tes_info->tess.spacing == TESS_SPACING_UNSPECIFIED ||
605 tcs_info->tess.spacing == tes_info->tess.spacing);
606 tes_info->tess.spacing |= tcs_info->tess.spacing;
607
608 assert(tcs_info->tess.primitive_mode == 0 ||
609 tes_info->tess.primitive_mode == 0 ||
610 tcs_info->tess.primitive_mode == tes_info->tess.primitive_mode);
611 tes_info->tess.primitive_mode |= tcs_info->tess.primitive_mode;
612 tes_info->tess.ccw |= tcs_info->tess.ccw;
613 tes_info->tess.point_mode |= tcs_info->tess.point_mode;
614 }
615
616 static void
617 anv_pipeline_link_tcs(const struct brw_compiler *compiler,
618 struct anv_pipeline_stage *tcs_stage,
619 struct anv_pipeline_stage *tes_stage)
620 {
621 assert(tes_stage && tes_stage->stage == MESA_SHADER_TESS_EVAL);
622
623 anv_fill_binding_table(&tcs_stage->prog_data.tcs.base.base, 0);
624
625 brw_nir_link_shaders(compiler, &tcs_stage->nir, &tes_stage->nir);
626
627 nir_lower_patch_vertices(tes_stage->nir,
628 tcs_stage->nir->info.tess.tcs_vertices_out,
629 NULL);
630
631 /* Copy TCS info into the TES info */
632 merge_tess_info(&tes_stage->nir->info, &tcs_stage->nir->info);
633
634 anv_fill_binding_table(&tcs_stage->prog_data.tcs.base.base, 0);
635 anv_fill_binding_table(&tes_stage->prog_data.tes.base.base, 0);
636
637 /* Whacking the key after cache lookup is a bit sketchy, but all of
638 * this comes from the SPIR-V, which is part of the hash used for the
639 * pipeline cache. So it should be safe.
640 */
641 tcs_stage->key.tcs.tes_primitive_mode =
642 tes_stage->nir->info.tess.primitive_mode;
643 tcs_stage->key.tcs.quads_workaround =
644 compiler->devinfo->gen < 9 &&
645 tes_stage->nir->info.tess.primitive_mode == 7 /* GL_QUADS */ &&
646 tes_stage->nir->info.tess.spacing == TESS_SPACING_EQUAL;
647 }
648
649 static const unsigned *
650 anv_pipeline_compile_tcs(const struct brw_compiler *compiler,
651 void *mem_ctx,
652 struct anv_pipeline_stage *tcs_stage,
653 struct anv_pipeline_stage *prev_stage)
654 {
655 tcs_stage->key.tcs.outputs_written =
656 tcs_stage->nir->info.outputs_written;
657 tcs_stage->key.tcs.patch_outputs_written =
658 tcs_stage->nir->info.patch_outputs_written;
659
660 return brw_compile_tcs(compiler, NULL, mem_ctx, &tcs_stage->key.tcs,
661 &tcs_stage->prog_data.tcs, tcs_stage->nir,
662 -1, NULL);
663 }
664
665 static void
666 anv_pipeline_link_tes(const struct brw_compiler *compiler,
667 struct anv_pipeline_stage *tes_stage,
668 struct anv_pipeline_stage *next_stage)
669 {
670 anv_fill_binding_table(&tes_stage->prog_data.tes.base.base, 0);
671
672 if (next_stage)
673 brw_nir_link_shaders(compiler, &tes_stage->nir, &next_stage->nir);
674 }
675
676 static const unsigned *
677 anv_pipeline_compile_tes(const struct brw_compiler *compiler,
678 void *mem_ctx,
679 struct anv_pipeline_stage *tes_stage,
680 struct anv_pipeline_stage *tcs_stage)
681 {
682 tes_stage->key.tes.inputs_read =
683 tcs_stage->nir->info.outputs_written;
684 tes_stage->key.tes.patch_inputs_read =
685 tcs_stage->nir->info.patch_outputs_written;
686
687 return brw_compile_tes(compiler, NULL, mem_ctx, &tes_stage->key.tes,
688 &tcs_stage->prog_data.tcs.base.vue_map,
689 &tes_stage->prog_data.tes, tes_stage->nir,
690 NULL, -1, NULL);
691 }
692
693 static void
694 anv_pipeline_link_gs(const struct brw_compiler *compiler,
695 struct anv_pipeline_stage *gs_stage,
696 struct anv_pipeline_stage *next_stage)
697 {
698 anv_fill_binding_table(&gs_stage->prog_data.gs.base.base, 0);
699
700 if (next_stage)
701 brw_nir_link_shaders(compiler, &gs_stage->nir, &next_stage->nir);
702 }
703
704 static const unsigned *
705 anv_pipeline_compile_gs(const struct brw_compiler *compiler,
706 void *mem_ctx,
707 struct anv_pipeline_stage *gs_stage,
708 struct anv_pipeline_stage *prev_stage)
709 {
710 brw_compute_vue_map(compiler->devinfo,
711 &gs_stage->prog_data.gs.base.vue_map,
712 gs_stage->nir->info.outputs_written,
713 gs_stage->nir->info.separate_shader);
714
715 return brw_compile_gs(compiler, NULL, mem_ctx, &gs_stage->key.gs,
716 &gs_stage->prog_data.gs, gs_stage->nir,
717 NULL, -1, NULL);
718 }
719
720 static void
721 anv_pipeline_link_fs(const struct brw_compiler *compiler,
722 struct anv_pipeline_stage *stage)
723 {
724 unsigned num_rts = 0;
725 const int max_rt = FRAG_RESULT_DATA7 - FRAG_RESULT_DATA0 + 1;
726 struct anv_pipeline_binding rt_bindings[max_rt];
727 nir_function_impl *impl = nir_shader_get_entrypoint(stage->nir);
728 int rt_to_bindings[max_rt];
729 memset(rt_to_bindings, -1, sizeof(rt_to_bindings));
730 bool rt_used[max_rt];
731 memset(rt_used, 0, sizeof(rt_used));
732
733 /* Flag used render targets */
734 nir_foreach_variable_safe(var, &stage->nir->outputs) {
735 if (var->data.location < FRAG_RESULT_DATA0)
736 continue;
737
738 const unsigned rt = var->data.location - FRAG_RESULT_DATA0;
739 /* Unused or out-of-bounds */
740 if (rt >= MAX_RTS || !(stage->key.wm.color_outputs_valid & (1 << rt)))
741 continue;
742
743 const unsigned array_len =
744 glsl_type_is_array(var->type) ? glsl_get_length(var->type) : 1;
745 assert(rt + array_len <= max_rt);
746
747 for (unsigned i = 0; i < array_len; i++)
748 rt_used[rt + i] = true;
749 }
750
751 /* Set new, compacted, location */
752 for (unsigned i = 0; i < max_rt; i++) {
753 if (!rt_used[i])
754 continue;
755
756 rt_to_bindings[i] = num_rts;
757 rt_bindings[rt_to_bindings[i]] = (struct anv_pipeline_binding) {
758 .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
759 .binding = 0,
760 .index = i,
761 };
762 num_rts++;
763 }
764
765 bool deleted_output = false;
766 nir_foreach_variable_safe(var, &stage->nir->outputs) {
767 if (var->data.location < FRAG_RESULT_DATA0)
768 continue;
769
770 const unsigned rt = var->data.location - FRAG_RESULT_DATA0;
771 if (rt >= MAX_RTS ||
772 !(stage->key.wm.color_outputs_valid & (1 << rt))) {
773 /* Unused or out-of-bounds, throw it away */
774 deleted_output = true;
775 var->data.mode = nir_var_local;
776 exec_node_remove(&var->node);
777 exec_list_push_tail(&impl->locals, &var->node);
778 continue;
779 }
780
781 /* Give it the new location */
782 assert(rt_to_bindings[rt] != -1);
783 var->data.location = rt_to_bindings[rt] + FRAG_RESULT_DATA0;
784 }
785
786 if (deleted_output)
787 nir_fixup_deref_modes(stage->nir);
788
789 if (num_rts == 0) {
790 /* If we have no render targets, we need a null render target */
791 rt_bindings[0] = (struct anv_pipeline_binding) {
792 .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
793 .binding = 0,
794 .index = UINT32_MAX,
795 };
796 num_rts = 1;
797 }
798
799 /* Now that we've determined the actual number of render targets, adjust
800 * the key accordingly.
801 */
802 stage->key.wm.nr_color_regions = num_rts;
803 stage->key.wm.color_outputs_valid = (1 << num_rts) - 1;
804
805 assert(num_rts <= max_rt);
806 assert(stage->bind_map.surface_count == 0);
807 typed_memcpy(stage->bind_map.surface_to_descriptor,
808 rt_bindings, num_rts);
809 stage->bind_map.surface_count += num_rts;
810
811 anv_fill_binding_table(&stage->prog_data.wm.base, 0);
812 }
813
814 static const unsigned *
815 anv_pipeline_compile_fs(const struct brw_compiler *compiler,
816 void *mem_ctx,
817 struct anv_pipeline_stage *fs_stage,
818 struct anv_pipeline_stage *prev_stage)
819 {
820 /* TODO: we could set this to 0 based on the information in nir_shader, but
821 * we need this before we call spirv_to_nir.
822 */
823 assert(prev_stage);
824 fs_stage->key.wm.input_slots_valid =
825 prev_stage->prog_data.vue.vue_map.slots_valid;
826
827 const unsigned *code =
828 brw_compile_fs(compiler, NULL, mem_ctx, &fs_stage->key.wm,
829 &fs_stage->prog_data.wm, fs_stage->nir,
830 NULL, -1, -1, -1, true, false, NULL, NULL);
831
832 if (fs_stage->key.wm.nr_color_regions == 0 &&
833 !fs_stage->prog_data.wm.has_side_effects &&
834 !fs_stage->prog_data.wm.uses_kill &&
835 fs_stage->prog_data.wm.computed_depth_mode == BRW_PSCDEPTH_OFF &&
836 !fs_stage->prog_data.wm.computed_stencil) {
837 /* This fragment shader has no outputs and no side effects. Go ahead
838 * and return the code pointer so we don't accidentally think the
839 * compile failed but zero out prog_data which will set program_size to
840 * zero and disable the stage.
841 */
842 memset(&fs_stage->prog_data, 0, sizeof(fs_stage->prog_data));
843 }
844
845 return code;
846 }
847
848 static VkResult
849 anv_pipeline_compile_graphics(struct anv_pipeline *pipeline,
850 struct anv_pipeline_cache *cache,
851 const VkGraphicsPipelineCreateInfo *info)
852 {
853 const struct brw_compiler *compiler =
854 pipeline->device->instance->physicalDevice.compiler;
855 struct anv_pipeline_stage stages[MESA_SHADER_STAGES] = {};
856
857 pipeline->active_stages = 0;
858
859 VkResult result;
860 for (uint32_t i = 0; i < info->stageCount; i++) {
861 const VkPipelineShaderStageCreateInfo *sinfo = &info->pStages[i];
862 gl_shader_stage stage = vk_to_mesa_shader_stage(sinfo->stage);
863
864 pipeline->active_stages |= sinfo->stage;
865
866 stages[stage].stage = stage;
867 stages[stage].module = anv_shader_module_from_handle(sinfo->module);
868 stages[stage].entrypoint = sinfo->pName;
869 stages[stage].spec_info = sinfo->pSpecializationInfo;
870
871 const struct gen_device_info *devinfo = &pipeline->device->info;
872 switch (stage) {
873 case MESA_SHADER_VERTEX:
874 populate_vs_prog_key(devinfo, &stages[stage].key.vs);
875 break;
876 case MESA_SHADER_TESS_CTRL:
877 populate_tcs_prog_key(devinfo,
878 info->pTessellationState->patchControlPoints,
879 &stages[stage].key.tcs);
880 break;
881 case MESA_SHADER_TESS_EVAL:
882 populate_tes_prog_key(devinfo, &stages[stage].key.tes);
883 break;
884 case MESA_SHADER_GEOMETRY:
885 populate_gs_prog_key(devinfo, &stages[stage].key.gs);
886 break;
887 case MESA_SHADER_FRAGMENT:
888 populate_wm_prog_key(devinfo, pipeline->subpass,
889 info->pMultisampleState,
890 &stages[stage].key.wm);
891 break;
892 default:
893 unreachable("Invalid graphics shader stage");
894 }
895 }
896
897 if (pipeline->active_stages & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)
898 pipeline->active_stages |= VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
899
900 assert(pipeline->active_stages & VK_SHADER_STAGE_VERTEX_BIT);
901
902 ANV_FROM_HANDLE(anv_pipeline_layout, layout, info->layout);
903
904 unsigned char sha1[20];
905 anv_pipeline_hash_graphics(pipeline, layout, stages, sha1);
906
907 unsigned found = 0;
908 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
909 if (!stages[s].entrypoint)
910 continue;
911
912 stages[s].cache_key.stage = s;
913 memcpy(stages[s].cache_key.sha1, sha1, sizeof(sha1));
914
915 struct anv_shader_bin *bin =
916 anv_device_search_for_kernel(pipeline->device, cache,
917 &stages[s].cache_key,
918 sizeof(stages[s].cache_key));
919 if (bin) {
920 found++;
921 pipeline->shaders[s] = bin;
922 }
923 }
924
925 if (found == __builtin_popcount(pipeline->active_stages)) {
926 /* We found all our shaders in the cache. We're done. */
927 goto done;
928 } else if (found > 0) {
929 /* We found some but not all of our shaders. This shouldn't happen
930 * most of the time but it can if we have a partially populated
931 * pipeline cache.
932 */
933 assert(found < __builtin_popcount(pipeline->active_stages));
934
935 vk_debug_report(&pipeline->device->instance->debug_report_callbacks,
936 VK_DEBUG_REPORT_WARNING_BIT_EXT |
937 VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
938 VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT,
939 (uint64_t)(uintptr_t)cache,
940 0, 0, "anv",
941 "Found a partial pipeline in the cache. This is "
942 "most likely caused by an incomplete pipeline cache "
943 "import or export");
944
945 /* We're going to have to recompile anyway, so just throw away our
946 * references to the shaders in the cache. We'll get them out of the
947 * cache again as part of the compilation process.
948 */
949 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
950 if (pipeline->shaders[s]) {
951 anv_shader_bin_unref(pipeline->device, pipeline->shaders[s]);
952 pipeline->shaders[s] = NULL;
953 }
954 }
955 }
956
957 void *pipeline_ctx = ralloc_context(NULL);
958
959 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
960 if (!stages[s].entrypoint)
961 continue;
962
963 assert(stages[s].stage == s);
964 assert(pipeline->shaders[s] == NULL);
965
966 stages[s].bind_map = (struct anv_pipeline_bind_map) {
967 .surface_to_descriptor = stages[s].surface_to_descriptor,
968 .sampler_to_descriptor = stages[s].sampler_to_descriptor
969 };
970
971 stages[s].nir = anv_shader_compile_to_nir(pipeline, pipeline_ctx,
972 stages[s].module,
973 stages[s].entrypoint,
974 stages[s].stage,
975 stages[s].spec_info);
976 if (stages[s].nir == NULL) {
977 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
978 goto fail;
979 }
980 }
981
982 /* Walk backwards to link */
983 struct anv_pipeline_stage *next_stage = NULL;
984 for (int s = MESA_SHADER_STAGES - 1; s >= 0; s--) {
985 if (!stages[s].entrypoint)
986 continue;
987
988 switch (s) {
989 case MESA_SHADER_VERTEX:
990 anv_pipeline_link_vs(compiler, &stages[s], next_stage);
991 break;
992 case MESA_SHADER_TESS_CTRL:
993 anv_pipeline_link_tcs(compiler, &stages[s], next_stage);
994 break;
995 case MESA_SHADER_TESS_EVAL:
996 anv_pipeline_link_tes(compiler, &stages[s], next_stage);
997 break;
998 case MESA_SHADER_GEOMETRY:
999 anv_pipeline_link_gs(compiler, &stages[s], next_stage);
1000 break;
1001 case MESA_SHADER_FRAGMENT:
1002 anv_pipeline_link_fs(compiler, &stages[s]);
1003 break;
1004 default:
1005 unreachable("Invalid graphics shader stage");
1006 }
1007
1008 next_stage = &stages[s];
1009 }
1010
1011 struct anv_pipeline_stage *prev_stage = NULL;
1012 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1013 if (!stages[s].entrypoint)
1014 continue;
1015
1016 void *stage_ctx = ralloc_context(NULL);
1017
1018 anv_pipeline_lower_nir(pipeline, stage_ctx, &stages[s], layout);
1019
1020 const unsigned *code;
1021 switch (s) {
1022 case MESA_SHADER_VERTEX:
1023 code = anv_pipeline_compile_vs(compiler, stage_ctx, &stages[s]);
1024 break;
1025 case MESA_SHADER_TESS_CTRL:
1026 code = anv_pipeline_compile_tcs(compiler, stage_ctx,
1027 &stages[s], prev_stage);
1028 break;
1029 case MESA_SHADER_TESS_EVAL:
1030 code = anv_pipeline_compile_tes(compiler, stage_ctx,
1031 &stages[s], prev_stage);
1032 break;
1033 case MESA_SHADER_GEOMETRY:
1034 code = anv_pipeline_compile_gs(compiler, stage_ctx,
1035 &stages[s], prev_stage);
1036 break;
1037 case MESA_SHADER_FRAGMENT:
1038 code = anv_pipeline_compile_fs(compiler, stage_ctx,
1039 &stages[s], prev_stage);
1040 break;
1041 default:
1042 unreachable("Invalid graphics shader stage");
1043 }
1044 if (code == NULL) {
1045 ralloc_free(stage_ctx);
1046 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1047 goto fail;
1048 }
1049
1050 struct anv_shader_bin *bin =
1051 anv_device_upload_kernel(pipeline->device, cache,
1052 &stages[s].cache_key,
1053 sizeof(stages[s].cache_key),
1054 code, stages[s].prog_data.base.program_size,
1055 stages[s].nir->constant_data,
1056 stages[s].nir->constant_data_size,
1057 &stages[s].prog_data.base,
1058 brw_prog_data_size(s),
1059 &stages[s].bind_map);
1060 if (!bin) {
1061 ralloc_free(stage_ctx);
1062 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1063 goto fail;
1064 }
1065
1066 pipeline->shaders[s] = bin;
1067 ralloc_free(stage_ctx);
1068
1069 prev_stage = &stages[s];
1070 }
1071
1072 ralloc_free(pipeline_ctx);
1073
1074 done:
1075
1076 if (pipeline->shaders[MESA_SHADER_FRAGMENT] &&
1077 pipeline->shaders[MESA_SHADER_FRAGMENT]->prog_data->program_size == 0) {
1078 /* This can happen if we decided to implicitly disable the fragment
1079 * shader. See anv_pipeline_compile_fs().
1080 */
1081 anv_shader_bin_unref(pipeline->device,
1082 pipeline->shaders[MESA_SHADER_FRAGMENT]);
1083 pipeline->shaders[MESA_SHADER_FRAGMENT] = NULL;
1084 pipeline->active_stages &= ~VK_SHADER_STAGE_FRAGMENT_BIT;
1085 }
1086
1087 return VK_SUCCESS;
1088
1089 fail:
1090 ralloc_free(pipeline_ctx);
1091
1092 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1093 if (pipeline->shaders[s])
1094 anv_shader_bin_unref(pipeline->device, pipeline->shaders[s]);
1095 }
1096
1097 return result;
1098 }
1099
1100 VkResult
1101 anv_pipeline_compile_cs(struct anv_pipeline *pipeline,
1102 struct anv_pipeline_cache *cache,
1103 const VkComputePipelineCreateInfo *info,
1104 const struct anv_shader_module *module,
1105 const char *entrypoint,
1106 const VkSpecializationInfo *spec_info)
1107 {
1108 const struct brw_compiler *compiler =
1109 pipeline->device->instance->physicalDevice.compiler;
1110
1111 struct anv_pipeline_stage stage = {
1112 .stage = MESA_SHADER_COMPUTE,
1113 .module = module,
1114 .entrypoint = entrypoint,
1115 .spec_info = spec_info,
1116 .cache_key = {
1117 .stage = MESA_SHADER_COMPUTE,
1118 }
1119 };
1120
1121 struct anv_shader_bin *bin = NULL;
1122
1123 populate_cs_prog_key(&pipeline->device->info, &stage.key.cs);
1124
1125 ANV_FROM_HANDLE(anv_pipeline_layout, layout, info->layout);
1126
1127 anv_pipeline_hash_compute(pipeline, layout, &stage, stage.cache_key.sha1);
1128 bin = anv_device_search_for_kernel(pipeline->device, cache, &stage.cache_key,
1129 sizeof(stage.cache_key));
1130
1131 if (bin == NULL) {
1132 stage.bind_map = (struct anv_pipeline_bind_map) {
1133 .surface_to_descriptor = stage.surface_to_descriptor,
1134 .sampler_to_descriptor = stage.sampler_to_descriptor
1135 };
1136
1137 void *mem_ctx = ralloc_context(NULL);
1138
1139 stage.nir = anv_shader_compile_to_nir(pipeline, mem_ctx,
1140 stage.module,
1141 stage.entrypoint,
1142 stage.stage,
1143 stage.spec_info);
1144 if (stage.nir == NULL) {
1145 ralloc_free(mem_ctx);
1146 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1147 }
1148
1149 anv_pipeline_lower_nir(pipeline, mem_ctx, &stage, layout);
1150
1151 NIR_PASS_V(stage.nir, anv_nir_add_base_work_group_id,
1152 &stage.prog_data.cs);
1153
1154 anv_fill_binding_table(&stage.prog_data.cs.base, 1);
1155
1156 const unsigned *shader_code =
1157 brw_compile_cs(compiler, NULL, mem_ctx, &stage.key.cs,
1158 &stage.prog_data.cs, stage.nir, -1, NULL);
1159 if (shader_code == NULL) {
1160 ralloc_free(mem_ctx);
1161 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1162 }
1163
1164 const unsigned code_size = stage.prog_data.base.program_size;
1165 bin = anv_device_upload_kernel(pipeline->device, cache,
1166 &stage.cache_key, sizeof(stage.cache_key),
1167 shader_code, code_size,
1168 stage.nir->constant_data,
1169 stage.nir->constant_data_size,
1170 &stage.prog_data.base,
1171 sizeof(stage.prog_data.cs),
1172 &stage.bind_map);
1173 if (!bin) {
1174 ralloc_free(mem_ctx);
1175 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1176 }
1177
1178 ralloc_free(mem_ctx);
1179 }
1180
1181 pipeline->active_stages = VK_SHADER_STAGE_COMPUTE_BIT;
1182 pipeline->shaders[MESA_SHADER_COMPUTE] = bin;
1183
1184 return VK_SUCCESS;
1185 }
1186
1187 /**
1188 * Copy pipeline state not marked as dynamic.
1189 * Dynamic state is pipeline state which hasn't been provided at pipeline
1190 * creation time, but is dynamically provided afterwards using various
1191 * vkCmdSet* functions.
1192 *
1193 * The set of state considered "non_dynamic" is determined by the pieces of
1194 * state that have their corresponding VkDynamicState enums omitted from
1195 * VkPipelineDynamicStateCreateInfo::pDynamicStates.
1196 *
1197 * @param[out] pipeline Destination non_dynamic state.
1198 * @param[in] pCreateInfo Source of non_dynamic state to be copied.
1199 */
1200 static void
1201 copy_non_dynamic_state(struct anv_pipeline *pipeline,
1202 const VkGraphicsPipelineCreateInfo *pCreateInfo)
1203 {
1204 anv_cmd_dirty_mask_t states = ANV_CMD_DIRTY_DYNAMIC_ALL;
1205 struct anv_subpass *subpass = pipeline->subpass;
1206
1207 pipeline->dynamic_state = default_dynamic_state;
1208
1209 if (pCreateInfo->pDynamicState) {
1210 /* Remove all of the states that are marked as dynamic */
1211 uint32_t count = pCreateInfo->pDynamicState->dynamicStateCount;
1212 for (uint32_t s = 0; s < count; s++)
1213 states &= ~(1 << pCreateInfo->pDynamicState->pDynamicStates[s]);
1214 }
1215
1216 struct anv_dynamic_state *dynamic = &pipeline->dynamic_state;
1217
1218 /* Section 9.2 of the Vulkan 1.0.15 spec says:
1219 *
1220 * pViewportState is [...] NULL if the pipeline
1221 * has rasterization disabled.
1222 */
1223 if (!pCreateInfo->pRasterizationState->rasterizerDiscardEnable) {
1224 assert(pCreateInfo->pViewportState);
1225
1226 dynamic->viewport.count = pCreateInfo->pViewportState->viewportCount;
1227 if (states & (1 << VK_DYNAMIC_STATE_VIEWPORT)) {
1228 typed_memcpy(dynamic->viewport.viewports,
1229 pCreateInfo->pViewportState->pViewports,
1230 pCreateInfo->pViewportState->viewportCount);
1231 }
1232
1233 dynamic->scissor.count = pCreateInfo->pViewportState->scissorCount;
1234 if (states & (1 << VK_DYNAMIC_STATE_SCISSOR)) {
1235 typed_memcpy(dynamic->scissor.scissors,
1236 pCreateInfo->pViewportState->pScissors,
1237 pCreateInfo->pViewportState->scissorCount);
1238 }
1239 }
1240
1241 if (states & (1 << VK_DYNAMIC_STATE_LINE_WIDTH)) {
1242 assert(pCreateInfo->pRasterizationState);
1243 dynamic->line_width = pCreateInfo->pRasterizationState->lineWidth;
1244 }
1245
1246 if (states & (1 << VK_DYNAMIC_STATE_DEPTH_BIAS)) {
1247 assert(pCreateInfo->pRasterizationState);
1248 dynamic->depth_bias.bias =
1249 pCreateInfo->pRasterizationState->depthBiasConstantFactor;
1250 dynamic->depth_bias.clamp =
1251 pCreateInfo->pRasterizationState->depthBiasClamp;
1252 dynamic->depth_bias.slope =
1253 pCreateInfo->pRasterizationState->depthBiasSlopeFactor;
1254 }
1255
1256 /* Section 9.2 of the Vulkan 1.0.15 spec says:
1257 *
1258 * pColorBlendState is [...] NULL if the pipeline has rasterization
1259 * disabled or if the subpass of the render pass the pipeline is
1260 * created against does not use any color attachments.
1261 */
1262 bool uses_color_att = false;
1263 for (unsigned i = 0; i < subpass->color_count; ++i) {
1264 if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED) {
1265 uses_color_att = true;
1266 break;
1267 }
1268 }
1269
1270 if (uses_color_att &&
1271 !pCreateInfo->pRasterizationState->rasterizerDiscardEnable) {
1272 assert(pCreateInfo->pColorBlendState);
1273
1274 if (states & (1 << VK_DYNAMIC_STATE_BLEND_CONSTANTS))
1275 typed_memcpy(dynamic->blend_constants,
1276 pCreateInfo->pColorBlendState->blendConstants, 4);
1277 }
1278
1279 /* If there is no depthstencil attachment, then don't read
1280 * pDepthStencilState. The Vulkan spec states that pDepthStencilState may
1281 * be NULL in this case. Even if pDepthStencilState is non-NULL, there is
1282 * no need to override the depthstencil defaults in
1283 * anv_pipeline::dynamic_state when there is no depthstencil attachment.
1284 *
1285 * Section 9.2 of the Vulkan 1.0.15 spec says:
1286 *
1287 * pDepthStencilState is [...] NULL if the pipeline has rasterization
1288 * disabled or if the subpass of the render pass the pipeline is created
1289 * against does not use a depth/stencil attachment.
1290 */
1291 if (!pCreateInfo->pRasterizationState->rasterizerDiscardEnable &&
1292 subpass->depth_stencil_attachment) {
1293 assert(pCreateInfo->pDepthStencilState);
1294
1295 if (states & (1 << VK_DYNAMIC_STATE_DEPTH_BOUNDS)) {
1296 dynamic->depth_bounds.min =
1297 pCreateInfo->pDepthStencilState->minDepthBounds;
1298 dynamic->depth_bounds.max =
1299 pCreateInfo->pDepthStencilState->maxDepthBounds;
1300 }
1301
1302 if (states & (1 << VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK)) {
1303 dynamic->stencil_compare_mask.front =
1304 pCreateInfo->pDepthStencilState->front.compareMask;
1305 dynamic->stencil_compare_mask.back =
1306 pCreateInfo->pDepthStencilState->back.compareMask;
1307 }
1308
1309 if (states & (1 << VK_DYNAMIC_STATE_STENCIL_WRITE_MASK)) {
1310 dynamic->stencil_write_mask.front =
1311 pCreateInfo->pDepthStencilState->front.writeMask;
1312 dynamic->stencil_write_mask.back =
1313 pCreateInfo->pDepthStencilState->back.writeMask;
1314 }
1315
1316 if (states & (1 << VK_DYNAMIC_STATE_STENCIL_REFERENCE)) {
1317 dynamic->stencil_reference.front =
1318 pCreateInfo->pDepthStencilState->front.reference;
1319 dynamic->stencil_reference.back =
1320 pCreateInfo->pDepthStencilState->back.reference;
1321 }
1322 }
1323
1324 pipeline->dynamic_state_mask = states;
1325 }
1326
1327 static void
1328 anv_pipeline_validate_create_info(const VkGraphicsPipelineCreateInfo *info)
1329 {
1330 #ifdef DEBUG
1331 struct anv_render_pass *renderpass = NULL;
1332 struct anv_subpass *subpass = NULL;
1333
1334 /* Assert that all required members of VkGraphicsPipelineCreateInfo are
1335 * present. See the Vulkan 1.0.28 spec, Section 9.2 Graphics Pipelines.
1336 */
1337 assert(info->sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
1338
1339 renderpass = anv_render_pass_from_handle(info->renderPass);
1340 assert(renderpass);
1341
1342 assert(info->subpass < renderpass->subpass_count);
1343 subpass = &renderpass->subpasses[info->subpass];
1344
1345 assert(info->stageCount >= 1);
1346 assert(info->pVertexInputState);
1347 assert(info->pInputAssemblyState);
1348 assert(info->pRasterizationState);
1349 if (!info->pRasterizationState->rasterizerDiscardEnable) {
1350 assert(info->pViewportState);
1351 assert(info->pMultisampleState);
1352
1353 if (subpass && subpass->depth_stencil_attachment)
1354 assert(info->pDepthStencilState);
1355
1356 if (subpass && subpass->color_count > 0) {
1357 bool all_color_unused = true;
1358 for (int i = 0; i < subpass->color_count; i++) {
1359 if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED)
1360 all_color_unused = false;
1361 }
1362 /* pColorBlendState is ignored if the pipeline has rasterization
1363 * disabled or if the subpass of the render pass the pipeline is
1364 * created against does not use any color attachments.
1365 */
1366 assert(info->pColorBlendState || all_color_unused);
1367 }
1368 }
1369
1370 for (uint32_t i = 0; i < info->stageCount; ++i) {
1371 switch (info->pStages[i].stage) {
1372 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
1373 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
1374 assert(info->pTessellationState);
1375 break;
1376 default:
1377 break;
1378 }
1379 }
1380 #endif
1381 }
1382
1383 /**
1384 * Calculate the desired L3 partitioning based on the current state of the
1385 * pipeline. For now this simply returns the conservative defaults calculated
1386 * by get_default_l3_weights(), but we could probably do better by gathering
1387 * more statistics from the pipeline state (e.g. guess of expected URB usage
1388 * and bound surfaces), or by using feed-back from performance counters.
1389 */
1390 void
1391 anv_pipeline_setup_l3_config(struct anv_pipeline *pipeline, bool needs_slm)
1392 {
1393 const struct gen_device_info *devinfo = &pipeline->device->info;
1394
1395 const struct gen_l3_weights w =
1396 gen_get_default_l3_weights(devinfo, pipeline->needs_data_cache, needs_slm);
1397
1398 pipeline->urb.l3_config = gen_get_l3_config(devinfo, w);
1399 pipeline->urb.total_size =
1400 gen_get_l3_config_urb_size(devinfo, pipeline->urb.l3_config);
1401 }
1402
1403 VkResult
1404 anv_pipeline_init(struct anv_pipeline *pipeline,
1405 struct anv_device *device,
1406 struct anv_pipeline_cache *cache,
1407 const VkGraphicsPipelineCreateInfo *pCreateInfo,
1408 const VkAllocationCallbacks *alloc)
1409 {
1410 VkResult result;
1411
1412 anv_pipeline_validate_create_info(pCreateInfo);
1413
1414 if (alloc == NULL)
1415 alloc = &device->alloc;
1416
1417 pipeline->device = device;
1418
1419 ANV_FROM_HANDLE(anv_render_pass, render_pass, pCreateInfo->renderPass);
1420 assert(pCreateInfo->subpass < render_pass->subpass_count);
1421 pipeline->subpass = &render_pass->subpasses[pCreateInfo->subpass];
1422
1423 result = anv_reloc_list_init(&pipeline->batch_relocs, alloc);
1424 if (result != VK_SUCCESS)
1425 return result;
1426
1427 pipeline->batch.alloc = alloc;
1428 pipeline->batch.next = pipeline->batch.start = pipeline->batch_data;
1429 pipeline->batch.end = pipeline->batch.start + sizeof(pipeline->batch_data);
1430 pipeline->batch.relocs = &pipeline->batch_relocs;
1431 pipeline->batch.status = VK_SUCCESS;
1432
1433 copy_non_dynamic_state(pipeline, pCreateInfo);
1434 pipeline->depth_clamp_enable = pCreateInfo->pRasterizationState &&
1435 pCreateInfo->pRasterizationState->depthClampEnable;
1436
1437 pipeline->sample_shading_enable = pCreateInfo->pMultisampleState &&
1438 pCreateInfo->pMultisampleState->sampleShadingEnable;
1439
1440 pipeline->needs_data_cache = false;
1441
1442 /* When we free the pipeline, we detect stages based on the NULL status
1443 * of various prog_data pointers. Make them NULL by default.
1444 */
1445 memset(pipeline->shaders, 0, sizeof(pipeline->shaders));
1446
1447 result = anv_pipeline_compile_graphics(pipeline, cache, pCreateInfo);
1448 if (result != VK_SUCCESS) {
1449 anv_reloc_list_finish(&pipeline->batch_relocs, alloc);
1450 return result;
1451 }
1452
1453 assert(pipeline->shaders[MESA_SHADER_VERTEX]);
1454
1455 anv_pipeline_setup_l3_config(pipeline, false);
1456
1457 const VkPipelineVertexInputStateCreateInfo *vi_info =
1458 pCreateInfo->pVertexInputState;
1459
1460 const uint64_t inputs_read = get_vs_prog_data(pipeline)->inputs_read;
1461
1462 pipeline->vb_used = 0;
1463 for (uint32_t i = 0; i < vi_info->vertexAttributeDescriptionCount; i++) {
1464 const VkVertexInputAttributeDescription *desc =
1465 &vi_info->pVertexAttributeDescriptions[i];
1466
1467 if (inputs_read & (1ull << (VERT_ATTRIB_GENERIC0 + desc->location)))
1468 pipeline->vb_used |= 1 << desc->binding;
1469 }
1470
1471 for (uint32_t i = 0; i < vi_info->vertexBindingDescriptionCount; i++) {
1472 const VkVertexInputBindingDescription *desc =
1473 &vi_info->pVertexBindingDescriptions[i];
1474
1475 pipeline->vb[desc->binding].stride = desc->stride;
1476
1477 /* Step rate is programmed per vertex element (attribute), not
1478 * binding. Set up a map of which bindings step per instance, for
1479 * reference by vertex element setup. */
1480 switch (desc->inputRate) {
1481 default:
1482 case VK_VERTEX_INPUT_RATE_VERTEX:
1483 pipeline->vb[desc->binding].instanced = false;
1484 break;
1485 case VK_VERTEX_INPUT_RATE_INSTANCE:
1486 pipeline->vb[desc->binding].instanced = true;
1487 break;
1488 }
1489
1490 pipeline->vb[desc->binding].instance_divisor = 1;
1491 }
1492
1493 const VkPipelineVertexInputDivisorStateCreateInfoEXT *vi_div_state =
1494 vk_find_struct_const(vi_info->pNext,
1495 PIPELINE_VERTEX_INPUT_DIVISOR_STATE_CREATE_INFO_EXT);
1496 if (vi_div_state) {
1497 for (uint32_t i = 0; i < vi_div_state->vertexBindingDivisorCount; i++) {
1498 const VkVertexInputBindingDivisorDescriptionEXT *desc =
1499 &vi_div_state->pVertexBindingDivisors[i];
1500
1501 pipeline->vb[desc->binding].instance_divisor = desc->divisor;
1502 }
1503 }
1504
1505 /* Our implementation of VK_KHR_multiview uses instancing to draw the
1506 * different views. If the client asks for instancing, we need to multiply
1507 * the instance divisor by the number of views ensure that we repeat the
1508 * client's per-instance data once for each view.
1509 */
1510 if (pipeline->subpass->view_mask) {
1511 const uint32_t view_count = anv_subpass_view_count(pipeline->subpass);
1512 for (uint32_t vb = 0; vb < MAX_VBS; vb++) {
1513 if (pipeline->vb[vb].instanced)
1514 pipeline->vb[vb].instance_divisor *= view_count;
1515 }
1516 }
1517
1518 const VkPipelineInputAssemblyStateCreateInfo *ia_info =
1519 pCreateInfo->pInputAssemblyState;
1520 const VkPipelineTessellationStateCreateInfo *tess_info =
1521 pCreateInfo->pTessellationState;
1522 pipeline->primitive_restart = ia_info->primitiveRestartEnable;
1523
1524 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL))
1525 pipeline->topology = _3DPRIM_PATCHLIST(tess_info->patchControlPoints);
1526 else
1527 pipeline->topology = vk_to_gen_primitive_type[ia_info->topology];
1528
1529 return VK_SUCCESS;
1530 }