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