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