1 /*
2  * Copyright © 2015 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 
24 #include <assert.h>
25 #include <stdbool.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 
30 #include "util/mesa-sha1.h"
31 #include "util/os_time.h"
32 #include "common/gen_l3_config.h"
33 #include "common/gen_disasm.h"
34 #include "anv_private.h"
35 #include "compiler/brw_nir.h"
36 #include "anv_nir.h"
37 #include "nir/nir_xfb_info.h"
38 #include "spirv/nir_spirv.h"
39 #include "vk_util.h"
40 
41 /* Needed for SWIZZLE macros */
42 #include "program/prog_instruction.h"
43 
44 // Shader functions
45 
anv_CreateShaderModule(VkDevice _device,const VkShaderModuleCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkShaderModule * pShaderModule)46 VkResult anv_CreateShaderModule(
47     VkDevice                                    _device,
48     const VkShaderModuleCreateInfo*             pCreateInfo,
49     const VkAllocationCallbacks*                pAllocator,
50     VkShaderModule*                             pShaderModule)
51 {
52    ANV_FROM_HANDLE(anv_device, device, _device);
53    struct anv_shader_module *module;
54 
55    assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
56    assert(pCreateInfo->flags == 0);
57 
58    module = vk_alloc2(&device->vk.alloc, pAllocator,
59                        sizeof(*module) + pCreateInfo->codeSize, 8,
60                        VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
61    if (module == NULL)
62       return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
63 
64    vk_object_base_init(&device->vk, &module->base,
65                        VK_OBJECT_TYPE_SHADER_MODULE);
66    module->size = pCreateInfo->codeSize;
67    memcpy(module->data, pCreateInfo->pCode, module->size);
68 
69    _mesa_sha1_compute(module->data, module->size, module->sha1);
70 
71    *pShaderModule = anv_shader_module_to_handle(module);
72 
73    return VK_SUCCESS;
74 }
75 
anv_DestroyShaderModule(VkDevice _device,VkShaderModule _module,const VkAllocationCallbacks * pAllocator)76 void anv_DestroyShaderModule(
77     VkDevice                                    _device,
78     VkShaderModule                              _module,
79     const VkAllocationCallbacks*                pAllocator)
80 {
81    ANV_FROM_HANDLE(anv_device, device, _device);
82    ANV_FROM_HANDLE(anv_shader_module, module, _module);
83 
84    if (!module)
85       return;
86 
87    vk_object_base_finish(&module->base);
88    vk_free2(&device->vk.alloc, pAllocator, module);
89 }
90 
91 #define SPIR_V_MAGIC_NUMBER 0x07230203
92 
93 struct anv_spirv_debug_data {
94    struct anv_device *device;
95    const struct anv_shader_module *module;
96 };
97 
anv_spirv_nir_debug(void * private_data,enum nir_spirv_debug_level level,size_t spirv_offset,const char * message)98 static void anv_spirv_nir_debug(void *private_data,
99                                 enum nir_spirv_debug_level level,
100                                 size_t spirv_offset,
101                                 const char *message)
102 {
103    struct anv_spirv_debug_data *debug_data = private_data;
104    struct anv_instance *instance = debug_data->device->physical->instance;
105 
106    static const VkDebugReportFlagsEXT vk_flags[] = {
107       [NIR_SPIRV_DEBUG_LEVEL_INFO] = VK_DEBUG_REPORT_INFORMATION_BIT_EXT,
108       [NIR_SPIRV_DEBUG_LEVEL_WARNING] = VK_DEBUG_REPORT_WARNING_BIT_EXT,
109       [NIR_SPIRV_DEBUG_LEVEL_ERROR] = VK_DEBUG_REPORT_ERROR_BIT_EXT,
110    };
111    char buffer[256];
112 
113    snprintf(buffer, sizeof(buffer), "SPIR-V offset %lu: %s", (unsigned long) spirv_offset, message);
114 
115    vk_debug_report(&instance->debug_report_callbacks,
116                    vk_flags[level],
117                    VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
118                    (uint64_t) (uintptr_t) debug_data->module,
119                    0, 0, "anv", buffer);
120 }
121 
122 /* Eventually, this will become part of anv_CreateShader.  Unfortunately,
123  * we can't do that yet because we don't have the ability to copy nir.
124  */
125 static nir_shader *
anv_shader_compile_to_nir(struct anv_device * device,void * mem_ctx,const struct anv_shader_module * module,const char * entrypoint_name,gl_shader_stage stage,const VkSpecializationInfo * spec_info)126 anv_shader_compile_to_nir(struct anv_device *device,
127                           void *mem_ctx,
128                           const struct anv_shader_module *module,
129                           const char *entrypoint_name,
130                           gl_shader_stage stage,
131                           const VkSpecializationInfo *spec_info)
132 {
133    const struct anv_physical_device *pdevice = device->physical;
134    const struct brw_compiler *compiler = pdevice->compiler;
135    const nir_shader_compiler_options *nir_options =
136       compiler->glsl_compiler_options[stage].NirOptions;
137 
138    uint32_t *spirv = (uint32_t *) module->data;
139    assert(spirv[0] == SPIR_V_MAGIC_NUMBER);
140    assert(module->size % 4 == 0);
141 
142    uint32_t num_spec_entries = 0;
143    struct nir_spirv_specialization *spec_entries = NULL;
144    if (spec_info && spec_info->mapEntryCount > 0) {
145       num_spec_entries = spec_info->mapEntryCount;
146       spec_entries = calloc(num_spec_entries, sizeof(*spec_entries));
147       for (uint32_t i = 0; i < num_spec_entries; i++) {
148          VkSpecializationMapEntry entry = spec_info->pMapEntries[i];
149          const void *data = spec_info->pData + entry.offset;
150          assert(data + entry.size <= spec_info->pData + spec_info->dataSize);
151 
152          spec_entries[i].id = spec_info->pMapEntries[i].constantID;
153          switch (entry.size) {
154          case 8:
155             spec_entries[i].value.u64 = *(const uint64_t *)data;
156             break;
157          case 4:
158             spec_entries[i].value.u32 = *(const uint32_t *)data;
159             break;
160          case 2:
161             spec_entries[i].value.u16 = *(const uint16_t *)data;
162             break;
163          case 1:
164             spec_entries[i].value.u8 = *(const uint8_t *)data;
165             break;
166          default:
167             assert(!"Invalid spec constant size");
168             break;
169          }
170       }
171    }
172 
173    struct anv_spirv_debug_data spirv_debug_data = {
174       .device = device,
175       .module = module,
176    };
177    struct spirv_to_nir_options spirv_options = {
178       .frag_coord_is_sysval = true,
179       .caps = {
180          .demote_to_helper_invocation = true,
181          .derivative_group = true,
182          .descriptor_array_dynamic_indexing = true,
183          .descriptor_array_non_uniform_indexing = true,
184          .descriptor_indexing = true,
185          .device_group = true,
186          .draw_parameters = true,
187          .float16 = pdevice->info.gen >= 8,
188          .float64 = pdevice->info.gen >= 8,
189          .fragment_shader_sample_interlock = pdevice->info.gen >= 9,
190          .fragment_shader_pixel_interlock = pdevice->info.gen >= 9,
191          .geometry_streams = true,
192          .image_write_without_format = true,
193          .int8 = pdevice->info.gen >= 8,
194          .int16 = pdevice->info.gen >= 8,
195          .int64 = pdevice->info.gen >= 8,
196          .int64_atomics = pdevice->info.gen >= 9 && pdevice->use_softpin,
197          .integer_functions2 = pdevice->info.gen >= 8,
198          .min_lod = true,
199          .multiview = true,
200          .physical_storage_buffer_address = pdevice->has_a64_buffer_access,
201          .post_depth_coverage = pdevice->info.gen >= 9,
202          .runtime_descriptor_array = true,
203          .float_controls = pdevice->info.gen >= 8,
204          .shader_clock = true,
205          .shader_viewport_index_layer = true,
206          .stencil_export = pdevice->info.gen >= 9,
207          .storage_8bit = pdevice->info.gen >= 8,
208          .storage_16bit = pdevice->info.gen >= 8,
209          .subgroup_arithmetic = true,
210          .subgroup_basic = true,
211          .subgroup_ballot = true,
212          .subgroup_quad = true,
213          .subgroup_shuffle = true,
214          .subgroup_vote = true,
215          .tessellation = true,
216          .transform_feedback = pdevice->info.gen >= 8,
217          .variable_pointers = true,
218          .vk_memory_model = true,
219          .vk_memory_model_device_scope = true,
220       },
221       .ubo_addr_format = nir_address_format_32bit_index_offset,
222       .ssbo_addr_format =
223           anv_nir_ssbo_addr_format(pdevice, device->robust_buffer_access),
224       .phys_ssbo_addr_format = nir_address_format_64bit_global,
225       .push_const_addr_format = nir_address_format_logical,
226 
227       /* TODO: Consider changing this to an address format that has the NULL
228        * pointer equals to 0.  That might be a better format to play nice
229        * with certain code / code generators.
230        */
231       .shared_addr_format = nir_address_format_32bit_offset,
232       .debug = {
233          .func = anv_spirv_nir_debug,
234          .private_data = &spirv_debug_data,
235       },
236    };
237 
238 
239    nir_shader *nir =
240       spirv_to_nir(spirv, module->size / 4,
241                    spec_entries, num_spec_entries,
242                    stage, entrypoint_name, &spirv_options, nir_options);
243    assert(nir->info.stage == stage);
244    nir_validate_shader(nir, "after spirv_to_nir");
245    ralloc_steal(mem_ctx, nir);
246 
247    free(spec_entries);
248 
249    if (unlikely(INTEL_DEBUG & intel_debug_flag_for_shader_stage(stage))) {
250       fprintf(stderr, "NIR (from SPIR-V) for %s shader:\n",
251               gl_shader_stage_name(stage));
252       nir_print_shader(nir, stderr);
253    }
254 
255    /* We have to lower away local constant initializers right before we
256     * inline functions.  That way they get properly initialized at the top
257     * of the function and not at the top of its caller.
258     */
259    NIR_PASS_V(nir, nir_lower_variable_initializers, nir_var_function_temp);
260    NIR_PASS_V(nir, nir_lower_returns);
261    NIR_PASS_V(nir, nir_inline_functions);
262    NIR_PASS_V(nir, nir_copy_prop);
263    NIR_PASS_V(nir, nir_opt_deref);
264 
265    /* Pick off the single entrypoint that we want */
266    foreach_list_typed_safe(nir_function, func, node, &nir->functions) {
267       if (!func->is_entrypoint)
268          exec_node_remove(&func->node);
269    }
270    assert(exec_list_length(&nir->functions) == 1);
271 
272    /* Now that we've deleted all but the main function, we can go ahead and
273     * lower the rest of the constant initializers.  We do this here so that
274     * nir_remove_dead_variables and split_per_member_structs below see the
275     * corresponding stores.
276     */
277    NIR_PASS_V(nir, nir_lower_variable_initializers, ~0);
278 
279    /* Split member structs.  We do this before lower_io_to_temporaries so that
280     * it doesn't lower system values to temporaries by accident.
281     */
282    NIR_PASS_V(nir, nir_split_var_copies);
283    NIR_PASS_V(nir, nir_split_per_member_structs);
284 
285    NIR_PASS_V(nir, nir_remove_dead_variables,
286               nir_var_shader_in | nir_var_shader_out | nir_var_system_value,
287               NULL);
288 
289    NIR_PASS_V(nir, nir_propagate_invariant);
290    NIR_PASS_V(nir, nir_lower_io_to_temporaries,
291               nir_shader_get_entrypoint(nir), true, false);
292 
293    NIR_PASS_V(nir, nir_lower_frexp);
294 
295    /* Vulkan uses the separate-shader linking model */
296    nir->info.separate_shader = true;
297 
298    brw_preprocess_nir(compiler, nir, NULL);
299 
300    return nir;
301 }
302 
303 VkResult
anv_pipeline_init(struct anv_pipeline * pipeline,struct anv_device * device,enum anv_pipeline_type type,VkPipelineCreateFlags flags,const VkAllocationCallbacks * pAllocator)304 anv_pipeline_init(struct anv_pipeline *pipeline,
305                   struct anv_device *device,
306                   enum anv_pipeline_type type,
307                   VkPipelineCreateFlags flags,
308                   const VkAllocationCallbacks *pAllocator)
309 {
310    VkResult result;
311 
312    memset(pipeline, 0, sizeof(*pipeline));
313 
314    vk_object_base_init(&device->vk, &pipeline->base,
315                        VK_OBJECT_TYPE_PIPELINE);
316    pipeline->device = device;
317 
318    /* It's the job of the child class to provide actual backing storage for
319     * the batch by setting batch.start, batch.next, and batch.end.
320     */
321    pipeline->batch.alloc = pAllocator ? pAllocator : &device->vk.alloc;
322    pipeline->batch.relocs = &pipeline->batch_relocs;
323    pipeline->batch.status = VK_SUCCESS;
324 
325    result = anv_reloc_list_init(&pipeline->batch_relocs,
326                                 pipeline->batch.alloc);
327    if (result != VK_SUCCESS)
328       return result;
329 
330    pipeline->mem_ctx = ralloc_context(NULL);
331 
332    pipeline->type = type;
333    pipeline->flags = flags;
334 
335    util_dynarray_init(&pipeline->executables, pipeline->mem_ctx);
336 
337    return VK_SUCCESS;
338 }
339 
340 void
anv_pipeline_finish(struct anv_pipeline * pipeline,struct anv_device * device,const VkAllocationCallbacks * pAllocator)341 anv_pipeline_finish(struct anv_pipeline *pipeline,
342                     struct anv_device *device,
343                     const VkAllocationCallbacks *pAllocator)
344 {
345    anv_reloc_list_finish(&pipeline->batch_relocs,
346                          pAllocator ? pAllocator : &device->vk.alloc);
347    ralloc_free(pipeline->mem_ctx);
348    vk_object_base_finish(&pipeline->base);
349 }
350 
anv_DestroyPipeline(VkDevice _device,VkPipeline _pipeline,const VkAllocationCallbacks * pAllocator)351 void anv_DestroyPipeline(
352     VkDevice                                    _device,
353     VkPipeline                                  _pipeline,
354     const VkAllocationCallbacks*                pAllocator)
355 {
356    ANV_FROM_HANDLE(anv_device, device, _device);
357    ANV_FROM_HANDLE(anv_pipeline, pipeline, _pipeline);
358 
359    if (!pipeline)
360       return;
361 
362    switch (pipeline->type) {
363    case ANV_PIPELINE_GRAPHICS: {
364       struct anv_graphics_pipeline *gfx_pipeline =
365          anv_pipeline_to_graphics(pipeline);
366 
367       if (gfx_pipeline->blend_state.map)
368          anv_state_pool_free(&device->dynamic_state_pool, gfx_pipeline->blend_state);
369 
370       for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
371          if (gfx_pipeline->shaders[s])
372             anv_shader_bin_unref(device, gfx_pipeline->shaders[s]);
373       }
374       break;
375    }
376 
377    case ANV_PIPELINE_COMPUTE: {
378       struct anv_compute_pipeline *compute_pipeline =
379          anv_pipeline_to_compute(pipeline);
380 
381       if (compute_pipeline->cs)
382          anv_shader_bin_unref(device, compute_pipeline->cs);
383 
384       break;
385    }
386 
387    default:
388       unreachable("invalid pipeline type");
389    }
390 
391    anv_pipeline_finish(pipeline, device, pAllocator);
392    vk_free2(&device->vk.alloc, pAllocator, pipeline);
393 }
394 
395 static const uint32_t vk_to_gen_primitive_type[] = {
396    [VK_PRIMITIVE_TOPOLOGY_POINT_LIST]                    = _3DPRIM_POINTLIST,
397    [VK_PRIMITIVE_TOPOLOGY_LINE_LIST]                     = _3DPRIM_LINELIST,
398    [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP]                    = _3DPRIM_LINESTRIP,
399    [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST]                 = _3DPRIM_TRILIST,
400    [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP]                = _3DPRIM_TRISTRIP,
401    [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN]                  = _3DPRIM_TRIFAN,
402    [VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY]      = _3DPRIM_LINELIST_ADJ,
403    [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY]     = _3DPRIM_LINESTRIP_ADJ,
404    [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY]  = _3DPRIM_TRILIST_ADJ,
405    [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY] = _3DPRIM_TRISTRIP_ADJ,
406 };
407 
408 static void
populate_sampler_prog_key(const struct gen_device_info * devinfo,struct brw_sampler_prog_key_data * key)409 populate_sampler_prog_key(const struct gen_device_info *devinfo,
410                           struct brw_sampler_prog_key_data *key)
411 {
412    /* Almost all multisampled textures are compressed.  The only time when we
413     * don't compress a multisampled texture is for 16x MSAA with a surface
414     * width greater than 8k which is a bit of an edge case.  Since the sampler
415     * just ignores the MCS parameter to ld2ms when MCS is disabled, it's safe
416     * to tell the compiler to always assume compression.
417     */
418    key->compressed_multisample_layout_mask = ~0;
419 
420    /* SkyLake added support for 16x MSAA.  With this came a new message for
421     * reading from a 16x MSAA surface with compression.  The new message was
422     * needed because now the MCS data is 64 bits instead of 32 or lower as is
423     * the case for 8x, 4x, and 2x.  The key->msaa_16 bit-field controls which
424     * message we use.  Fortunately, the 16x message works for 8x, 4x, and 2x
425     * so we can just use it unconditionally.  This may not be quite as
426     * efficient but it saves us from recompiling.
427     */
428    if (devinfo->gen >= 9)
429       key->msaa_16 = ~0;
430 
431    /* XXX: Handle texture swizzle on HSW- */
432    for (int i = 0; i < MAX_SAMPLERS; i++) {
433       /* Assume color sampler, no swizzling. (Works for BDW+) */
434       key->swizzles[i] = SWIZZLE_XYZW;
435    }
436 }
437 
438 static void
populate_base_prog_key(const struct gen_device_info * devinfo,VkPipelineShaderStageCreateFlags flags,struct brw_base_prog_key * key)439 populate_base_prog_key(const struct gen_device_info *devinfo,
440                        VkPipelineShaderStageCreateFlags flags,
441                        struct brw_base_prog_key *key)
442 {
443    if (flags & VK_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT)
444       key->subgroup_size_type = BRW_SUBGROUP_SIZE_VARYING;
445    else
446       key->subgroup_size_type = BRW_SUBGROUP_SIZE_API_CONSTANT;
447 
448    populate_sampler_prog_key(devinfo, &key->tex);
449 }
450 
451 static void
populate_vs_prog_key(const struct gen_device_info * devinfo,VkPipelineShaderStageCreateFlags flags,struct brw_vs_prog_key * key)452 populate_vs_prog_key(const struct gen_device_info *devinfo,
453                      VkPipelineShaderStageCreateFlags flags,
454                      struct brw_vs_prog_key *key)
455 {
456    memset(key, 0, sizeof(*key));
457 
458    populate_base_prog_key(devinfo, flags, &key->base);
459 
460    /* XXX: Handle vertex input work-arounds */
461 
462    /* XXX: Handle sampler_prog_key */
463 }
464 
465 static void
populate_tcs_prog_key(const struct gen_device_info * devinfo,VkPipelineShaderStageCreateFlags flags,unsigned input_vertices,struct brw_tcs_prog_key * key)466 populate_tcs_prog_key(const struct gen_device_info *devinfo,
467                       VkPipelineShaderStageCreateFlags flags,
468                       unsigned input_vertices,
469                       struct brw_tcs_prog_key *key)
470 {
471    memset(key, 0, sizeof(*key));
472 
473    populate_base_prog_key(devinfo, flags, &key->base);
474 
475    key->input_vertices = input_vertices;
476 }
477 
478 static void
populate_tes_prog_key(const struct gen_device_info * devinfo,VkPipelineShaderStageCreateFlags flags,struct brw_tes_prog_key * key)479 populate_tes_prog_key(const struct gen_device_info *devinfo,
480                       VkPipelineShaderStageCreateFlags flags,
481                       struct brw_tes_prog_key *key)
482 {
483    memset(key, 0, sizeof(*key));
484 
485    populate_base_prog_key(devinfo, flags, &key->base);
486 }
487 
488 static void
populate_gs_prog_key(const struct gen_device_info * devinfo,VkPipelineShaderStageCreateFlags flags,struct brw_gs_prog_key * key)489 populate_gs_prog_key(const struct gen_device_info *devinfo,
490                      VkPipelineShaderStageCreateFlags flags,
491                      struct brw_gs_prog_key *key)
492 {
493    memset(key, 0, sizeof(*key));
494 
495    populate_base_prog_key(devinfo, flags, &key->base);
496 }
497 
498 static void
populate_wm_prog_key(const struct gen_device_info * devinfo,VkPipelineShaderStageCreateFlags flags,const struct anv_subpass * subpass,const VkPipelineMultisampleStateCreateInfo * ms_info,struct brw_wm_prog_key * key)499 populate_wm_prog_key(const struct gen_device_info *devinfo,
500                      VkPipelineShaderStageCreateFlags flags,
501                      const struct anv_subpass *subpass,
502                      const VkPipelineMultisampleStateCreateInfo *ms_info,
503                      struct brw_wm_prog_key *key)
504 {
505    memset(key, 0, sizeof(*key));
506 
507    populate_base_prog_key(devinfo, flags, &key->base);
508 
509    /* We set this to 0 here and set to the actual value before we call
510     * brw_compile_fs.
511     */
512    key->input_slots_valid = 0;
513 
514    /* Vulkan doesn't specify a default */
515    key->high_quality_derivatives = false;
516 
517    /* XXX Vulkan doesn't appear to specify */
518    key->clamp_fragment_color = false;
519 
520    key->ignore_sample_mask_out = false;
521 
522    assert(subpass->color_count <= MAX_RTS);
523    for (uint32_t i = 0; i < subpass->color_count; i++) {
524       if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED)
525          key->color_outputs_valid |= (1 << i);
526    }
527 
528    key->nr_color_regions = subpass->color_count;
529 
530    /* To reduce possible shader recompilations we would need to know if
531     * there is a SampleMask output variable to compute if we should emit
532     * code to workaround the issue that hardware disables alpha to coverage
533     * when there is SampleMask output.
534     */
535    key->alpha_to_coverage = ms_info && ms_info->alphaToCoverageEnable;
536 
537    /* Vulkan doesn't support fixed-function alpha test */
538    key->alpha_test_replicate_alpha = false;
539 
540    if (ms_info) {
541       /* We should probably pull this out of the shader, but it's fairly
542        * harmless to compute it and then let dead-code take care of it.
543        */
544       if (ms_info->rasterizationSamples > 1) {
545          key->persample_interp = ms_info->sampleShadingEnable &&
546             (ms_info->minSampleShading * ms_info->rasterizationSamples) > 1;
547          key->multisample_fbo = true;
548       }
549 
550       key->frag_coord_adds_sample_pos = key->persample_interp;
551    }
552 }
553 
554 static void
populate_cs_prog_key(const struct gen_device_info * devinfo,VkPipelineShaderStageCreateFlags flags,const VkPipelineShaderStageRequiredSubgroupSizeCreateInfoEXT * rss_info,struct brw_cs_prog_key * key)555 populate_cs_prog_key(const struct gen_device_info *devinfo,
556                      VkPipelineShaderStageCreateFlags flags,
557                      const VkPipelineShaderStageRequiredSubgroupSizeCreateInfoEXT *rss_info,
558                      struct brw_cs_prog_key *key)
559 {
560    memset(key, 0, sizeof(*key));
561 
562    populate_base_prog_key(devinfo, flags, &key->base);
563 
564    if (rss_info) {
565       assert(key->base.subgroup_size_type != BRW_SUBGROUP_SIZE_VARYING);
566 
567       /* These enum values are expressly chosen to be equal to the subgroup
568        * size that they require.
569        */
570       assert(rss_info->requiredSubgroupSize == 8 ||
571              rss_info->requiredSubgroupSize == 16 ||
572              rss_info->requiredSubgroupSize == 32);
573       key->base.subgroup_size_type = rss_info->requiredSubgroupSize;
574    } else if (flags & VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT_EXT) {
575       /* If the client expressly requests full subgroups and they don't
576        * specify a subgroup size, we need to pick one.  If they're requested
577        * varying subgroup sizes, we set it to UNIFORM and let the back-end
578        * compiler pick.  Otherwise, we specify the API value of 32.
579        * Performance will likely be terrible in this case but there's nothing
580        * we can do about that.  The client should have chosen a size.
581        */
582       if (flags & VK_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT)
583          key->base.subgroup_size_type = BRW_SUBGROUP_SIZE_UNIFORM;
584       else
585          key->base.subgroup_size_type = BRW_SUBGROUP_SIZE_REQUIRE_32;
586    }
587 }
588 
589 struct anv_pipeline_stage {
590    gl_shader_stage stage;
591 
592    const struct anv_shader_module *module;
593    const char *entrypoint;
594    const VkSpecializationInfo *spec_info;
595 
596    unsigned char shader_sha1[20];
597 
598    union brw_any_prog_key key;
599 
600    struct {
601       gl_shader_stage stage;
602       unsigned char sha1[20];
603    } cache_key;
604 
605    nir_shader *nir;
606 
607    struct anv_pipeline_binding surface_to_descriptor[256];
608    struct anv_pipeline_binding sampler_to_descriptor[256];
609    struct anv_pipeline_bind_map bind_map;
610 
611    union brw_any_prog_data prog_data;
612 
613    uint32_t num_stats;
614    struct brw_compile_stats stats[3];
615    char *disasm[3];
616 
617    VkPipelineCreationFeedbackEXT feedback;
618 
619    const unsigned *code;
620 };
621 
622 static void
anv_pipeline_hash_shader(const struct anv_shader_module * module,const char * entrypoint,gl_shader_stage stage,const VkSpecializationInfo * spec_info,unsigned char * sha1_out)623 anv_pipeline_hash_shader(const struct anv_shader_module *module,
624                          const char *entrypoint,
625                          gl_shader_stage stage,
626                          const VkSpecializationInfo *spec_info,
627                          unsigned char *sha1_out)
628 {
629    struct mesa_sha1 ctx;
630    _mesa_sha1_init(&ctx);
631 
632    _mesa_sha1_update(&ctx, module->sha1, sizeof(module->sha1));
633    _mesa_sha1_update(&ctx, entrypoint, strlen(entrypoint));
634    _mesa_sha1_update(&ctx, &stage, sizeof(stage));
635    if (spec_info) {
636       _mesa_sha1_update(&ctx, spec_info->pMapEntries,
637                         spec_info->mapEntryCount *
638                         sizeof(*spec_info->pMapEntries));
639       _mesa_sha1_update(&ctx, spec_info->pData,
640                         spec_info->dataSize);
641    }
642 
643    _mesa_sha1_final(&ctx, sha1_out);
644 }
645 
646 static void
anv_pipeline_hash_graphics(struct anv_graphics_pipeline * pipeline,struct anv_pipeline_layout * layout,struct anv_pipeline_stage * stages,unsigned char * sha1_out)647 anv_pipeline_hash_graphics(struct anv_graphics_pipeline *pipeline,
648                            struct anv_pipeline_layout *layout,
649                            struct anv_pipeline_stage *stages,
650                            unsigned char *sha1_out)
651 {
652    struct mesa_sha1 ctx;
653    _mesa_sha1_init(&ctx);
654 
655    _mesa_sha1_update(&ctx, &pipeline->subpass->view_mask,
656                      sizeof(pipeline->subpass->view_mask));
657 
658    if (layout)
659       _mesa_sha1_update(&ctx, layout->sha1, sizeof(layout->sha1));
660 
661    const bool rba = pipeline->base.device->robust_buffer_access;
662    _mesa_sha1_update(&ctx, &rba, sizeof(rba));
663 
664    for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
665       if (stages[s].entrypoint) {
666          _mesa_sha1_update(&ctx, stages[s].shader_sha1,
667                            sizeof(stages[s].shader_sha1));
668          _mesa_sha1_update(&ctx, &stages[s].key, brw_prog_key_size(s));
669       }
670    }
671 
672    _mesa_sha1_final(&ctx, sha1_out);
673 }
674 
675 static void
anv_pipeline_hash_compute(struct anv_compute_pipeline * pipeline,struct anv_pipeline_layout * layout,struct anv_pipeline_stage * stage,unsigned char * sha1_out)676 anv_pipeline_hash_compute(struct anv_compute_pipeline *pipeline,
677                           struct anv_pipeline_layout *layout,
678                           struct anv_pipeline_stage *stage,
679                           unsigned char *sha1_out)
680 {
681    struct mesa_sha1 ctx;
682    _mesa_sha1_init(&ctx);
683 
684    if (layout)
685       _mesa_sha1_update(&ctx, layout->sha1, sizeof(layout->sha1));
686 
687    const bool rba = pipeline->base.device->robust_buffer_access;
688    _mesa_sha1_update(&ctx, &rba, sizeof(rba));
689 
690    _mesa_sha1_update(&ctx, stage->shader_sha1,
691                      sizeof(stage->shader_sha1));
692    _mesa_sha1_update(&ctx, &stage->key.cs, sizeof(stage->key.cs));
693 
694    _mesa_sha1_final(&ctx, sha1_out);
695 }
696 
697 static nir_shader *
anv_pipeline_stage_get_nir(struct anv_pipeline * pipeline,struct anv_pipeline_cache * cache,void * mem_ctx,struct anv_pipeline_stage * stage)698 anv_pipeline_stage_get_nir(struct anv_pipeline *pipeline,
699                            struct anv_pipeline_cache *cache,
700                            void *mem_ctx,
701                            struct anv_pipeline_stage *stage)
702 {
703    const struct brw_compiler *compiler =
704       pipeline->device->physical->compiler;
705    const nir_shader_compiler_options *nir_options =
706       compiler->glsl_compiler_options[stage->stage].NirOptions;
707    nir_shader *nir;
708 
709    nir = anv_device_search_for_nir(pipeline->device, cache,
710                                    nir_options,
711                                    stage->shader_sha1,
712                                    mem_ctx);
713    if (nir) {
714       assert(nir->info.stage == stage->stage);
715       return nir;
716    }
717 
718    nir = anv_shader_compile_to_nir(pipeline->device,
719                                    mem_ctx,
720                                    stage->module,
721                                    stage->entrypoint,
722                                    stage->stage,
723                                    stage->spec_info);
724    if (nir) {
725       anv_device_upload_nir(pipeline->device, cache, nir, stage->shader_sha1);
726       return nir;
727    }
728 
729    return NULL;
730 }
731 
732 static void
anv_pipeline_lower_nir(struct anv_pipeline * pipeline,void * mem_ctx,struct anv_pipeline_stage * stage,struct anv_pipeline_layout * layout)733 anv_pipeline_lower_nir(struct anv_pipeline *pipeline,
734                        void *mem_ctx,
735                        struct anv_pipeline_stage *stage,
736                        struct anv_pipeline_layout *layout)
737 {
738    const struct anv_physical_device *pdevice = pipeline->device->physical;
739    const struct brw_compiler *compiler = pdevice->compiler;
740 
741    struct brw_stage_prog_data *prog_data = &stage->prog_data.base;
742    nir_shader *nir = stage->nir;
743 
744    if (nir->info.stage == MESA_SHADER_FRAGMENT) {
745       NIR_PASS_V(nir, nir_lower_wpos_center,
746                  anv_pipeline_to_graphics(pipeline)->sample_shading_enable);
747       NIR_PASS_V(nir, nir_lower_input_attachments, true);
748    }
749 
750    NIR_PASS_V(nir, anv_nir_lower_ycbcr_textures, layout);
751 
752    if (pipeline->type == ANV_PIPELINE_GRAPHICS) {
753       NIR_PASS_V(nir, anv_nir_lower_multiview,
754                  anv_pipeline_to_graphics(pipeline));
755    }
756 
757    nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
758 
759    NIR_PASS_V(nir, brw_nir_lower_image_load_store, compiler->devinfo, NULL);
760 
761    NIR_PASS_V(nir, nir_lower_explicit_io, nir_var_mem_global,
762               nir_address_format_64bit_global);
763 
764    /* Apply the actual pipeline layout to UBOs, SSBOs, and textures */
765    anv_nir_apply_pipeline_layout(pdevice,
766                                  pipeline->device->robust_buffer_access,
767                                  layout, nir, &stage->bind_map);
768 
769    NIR_PASS_V(nir, nir_lower_explicit_io, nir_var_mem_ubo,
770               nir_address_format_32bit_index_offset);
771    NIR_PASS_V(nir, nir_lower_explicit_io, nir_var_mem_ssbo,
772               anv_nir_ssbo_addr_format(pdevice,
773                  pipeline->device->robust_buffer_access));
774 
775    NIR_PASS_V(nir, nir_opt_constant_folding);
776 
777    /* We don't support non-uniform UBOs and non-uniform SSBO access is
778     * handled naturally by falling back to A64 messages.
779     */
780    NIR_PASS_V(nir, nir_lower_non_uniform_access,
781               nir_lower_non_uniform_texture_access |
782               nir_lower_non_uniform_image_access);
783 
784    anv_nir_compute_push_layout(pdevice, pipeline->device->robust_buffer_access,
785                                nir, prog_data, &stage->bind_map, mem_ctx);
786 
787    stage->nir = nir;
788 }
789 
790 static void
anv_pipeline_link_vs(const struct brw_compiler * compiler,struct anv_pipeline_stage * vs_stage,struct anv_pipeline_stage * next_stage)791 anv_pipeline_link_vs(const struct brw_compiler *compiler,
792                      struct anv_pipeline_stage *vs_stage,
793                      struct anv_pipeline_stage *next_stage)
794 {
795    if (next_stage)
796       brw_nir_link_shaders(compiler, vs_stage->nir, next_stage->nir);
797 }
798 
799 static void
anv_pipeline_compile_vs(const struct brw_compiler * compiler,void * mem_ctx,struct anv_graphics_pipeline * pipeline,struct anv_pipeline_stage * vs_stage)800 anv_pipeline_compile_vs(const struct brw_compiler *compiler,
801                         void *mem_ctx,
802                         struct anv_graphics_pipeline *pipeline,
803                         struct anv_pipeline_stage *vs_stage)
804 {
805    /* When using Primitive Replication for multiview, each view gets its own
806     * position slot.
807     */
808    uint32_t pos_slots = pipeline->use_primitive_replication ?
809       anv_subpass_view_count(pipeline->subpass) : 1;
810 
811    brw_compute_vue_map(compiler->devinfo,
812                        &vs_stage->prog_data.vs.base.vue_map,
813                        vs_stage->nir->info.outputs_written,
814                        vs_stage->nir->info.separate_shader,
815                        pos_slots);
816 
817    vs_stage->num_stats = 1;
818    vs_stage->code = brw_compile_vs(compiler, pipeline->base.device, mem_ctx,
819                                    &vs_stage->key.vs,
820                                    &vs_stage->prog_data.vs,
821                                    vs_stage->nir, -1,
822                                    vs_stage->stats, NULL);
823 }
824 
825 static void
merge_tess_info(struct shader_info * tes_info,const struct shader_info * tcs_info)826 merge_tess_info(struct shader_info *tes_info,
827                 const struct shader_info *tcs_info)
828 {
829    /* The Vulkan 1.0.38 spec, section 21.1 Tessellator says:
830     *
831     *    "PointMode. Controls generation of points rather than triangles
832     *     or lines. This functionality defaults to disabled, and is
833     *     enabled if either shader stage includes the execution mode.
834     *
835     * and about Triangles, Quads, IsoLines, VertexOrderCw, VertexOrderCcw,
836     * PointMode, SpacingEqual, SpacingFractionalEven, SpacingFractionalOdd,
837     * and OutputVertices, it says:
838     *
839     *    "One mode must be set in at least one of the tessellation
840     *     shader stages."
841     *
842     * So, the fields can be set in either the TCS or TES, but they must
843     * agree if set in both.  Our backend looks at TES, so bitwise-or in
844     * the values from the TCS.
845     */
846    assert(tcs_info->tess.tcs_vertices_out == 0 ||
847           tes_info->tess.tcs_vertices_out == 0 ||
848           tcs_info->tess.tcs_vertices_out == tes_info->tess.tcs_vertices_out);
849    tes_info->tess.tcs_vertices_out |= tcs_info->tess.tcs_vertices_out;
850 
851    assert(tcs_info->tess.spacing == TESS_SPACING_UNSPECIFIED ||
852           tes_info->tess.spacing == TESS_SPACING_UNSPECIFIED ||
853           tcs_info->tess.spacing == tes_info->tess.spacing);
854    tes_info->tess.spacing |= tcs_info->tess.spacing;
855 
856    assert(tcs_info->tess.primitive_mode == 0 ||
857           tes_info->tess.primitive_mode == 0 ||
858           tcs_info->tess.primitive_mode == tes_info->tess.primitive_mode);
859    tes_info->tess.primitive_mode |= tcs_info->tess.primitive_mode;
860    tes_info->tess.ccw |= tcs_info->tess.ccw;
861    tes_info->tess.point_mode |= tcs_info->tess.point_mode;
862 }
863 
864 static void
anv_pipeline_link_tcs(const struct brw_compiler * compiler,struct anv_pipeline_stage * tcs_stage,struct anv_pipeline_stage * tes_stage)865 anv_pipeline_link_tcs(const struct brw_compiler *compiler,
866                       struct anv_pipeline_stage *tcs_stage,
867                       struct anv_pipeline_stage *tes_stage)
868 {
869    assert(tes_stage && tes_stage->stage == MESA_SHADER_TESS_EVAL);
870 
871    brw_nir_link_shaders(compiler, tcs_stage->nir, tes_stage->nir);
872 
873    nir_lower_patch_vertices(tes_stage->nir,
874                             tcs_stage->nir->info.tess.tcs_vertices_out,
875                             NULL);
876 
877    /* Copy TCS info into the TES info */
878    merge_tess_info(&tes_stage->nir->info, &tcs_stage->nir->info);
879 
880    /* Whacking the key after cache lookup is a bit sketchy, but all of
881     * this comes from the SPIR-V, which is part of the hash used for the
882     * pipeline cache.  So it should be safe.
883     */
884    tcs_stage->key.tcs.tes_primitive_mode =
885       tes_stage->nir->info.tess.primitive_mode;
886    tcs_stage->key.tcs.quads_workaround =
887       compiler->devinfo->gen < 9 &&
888       tes_stage->nir->info.tess.primitive_mode == 7 /* GL_QUADS */ &&
889       tes_stage->nir->info.tess.spacing == TESS_SPACING_EQUAL;
890 }
891 
892 static void
anv_pipeline_compile_tcs(const struct brw_compiler * compiler,void * mem_ctx,struct anv_device * device,struct anv_pipeline_stage * tcs_stage,struct anv_pipeline_stage * prev_stage)893 anv_pipeline_compile_tcs(const struct brw_compiler *compiler,
894                          void *mem_ctx,
895                          struct anv_device *device,
896                          struct anv_pipeline_stage *tcs_stage,
897                          struct anv_pipeline_stage *prev_stage)
898 {
899    tcs_stage->key.tcs.outputs_written =
900       tcs_stage->nir->info.outputs_written;
901    tcs_stage->key.tcs.patch_outputs_written =
902       tcs_stage->nir->info.patch_outputs_written;
903 
904    tcs_stage->num_stats = 1;
905    tcs_stage->code = brw_compile_tcs(compiler, device, mem_ctx,
906                                      &tcs_stage->key.tcs,
907                                      &tcs_stage->prog_data.tcs,
908                                      tcs_stage->nir, -1,
909                                      tcs_stage->stats, NULL);
910 }
911 
912 static void
anv_pipeline_link_tes(const struct brw_compiler * compiler,struct anv_pipeline_stage * tes_stage,struct anv_pipeline_stage * next_stage)913 anv_pipeline_link_tes(const struct brw_compiler *compiler,
914                       struct anv_pipeline_stage *tes_stage,
915                       struct anv_pipeline_stage *next_stage)
916 {
917    if (next_stage)
918       brw_nir_link_shaders(compiler, tes_stage->nir, next_stage->nir);
919 }
920 
921 static void
anv_pipeline_compile_tes(const struct brw_compiler * compiler,void * mem_ctx,struct anv_device * device,struct anv_pipeline_stage * tes_stage,struct anv_pipeline_stage * tcs_stage)922 anv_pipeline_compile_tes(const struct brw_compiler *compiler,
923                          void *mem_ctx,
924                          struct anv_device *device,
925                          struct anv_pipeline_stage *tes_stage,
926                          struct anv_pipeline_stage *tcs_stage)
927 {
928    tes_stage->key.tes.inputs_read =
929       tcs_stage->nir->info.outputs_written;
930    tes_stage->key.tes.patch_inputs_read =
931       tcs_stage->nir->info.patch_outputs_written;
932 
933    tes_stage->num_stats = 1;
934    tes_stage->code = brw_compile_tes(compiler, device, mem_ctx,
935                                      &tes_stage->key.tes,
936                                      &tcs_stage->prog_data.tcs.base.vue_map,
937                                      &tes_stage->prog_data.tes,
938                                      tes_stage->nir, -1,
939                                      tes_stage->stats, NULL);
940 }
941 
942 static void
anv_pipeline_link_gs(const struct brw_compiler * compiler,struct anv_pipeline_stage * gs_stage,struct anv_pipeline_stage * next_stage)943 anv_pipeline_link_gs(const struct brw_compiler *compiler,
944                      struct anv_pipeline_stage *gs_stage,
945                      struct anv_pipeline_stage *next_stage)
946 {
947    if (next_stage)
948       brw_nir_link_shaders(compiler, gs_stage->nir, next_stage->nir);
949 }
950 
951 static void
anv_pipeline_compile_gs(const struct brw_compiler * compiler,void * mem_ctx,struct anv_device * device,struct anv_pipeline_stage * gs_stage,struct anv_pipeline_stage * prev_stage)952 anv_pipeline_compile_gs(const struct brw_compiler *compiler,
953                         void *mem_ctx,
954                         struct anv_device *device,
955                         struct anv_pipeline_stage *gs_stage,
956                         struct anv_pipeline_stage *prev_stage)
957 {
958    brw_compute_vue_map(compiler->devinfo,
959                        &gs_stage->prog_data.gs.base.vue_map,
960                        gs_stage->nir->info.outputs_written,
961                        gs_stage->nir->info.separate_shader, 1);
962 
963    gs_stage->num_stats = 1;
964    gs_stage->code = brw_compile_gs(compiler, device, mem_ctx,
965                                    &gs_stage->key.gs,
966                                    &gs_stage->prog_data.gs,
967                                    gs_stage->nir, NULL, -1,
968                                    gs_stage->stats, NULL);
969 }
970 
971 static void
anv_pipeline_link_fs(const struct brw_compiler * compiler,struct anv_pipeline_stage * stage)972 anv_pipeline_link_fs(const struct brw_compiler *compiler,
973                      struct anv_pipeline_stage *stage)
974 {
975    unsigned num_rt_bindings;
976    struct anv_pipeline_binding rt_bindings[MAX_RTS];
977    if (stage->key.wm.nr_color_regions > 0) {
978       assert(stage->key.wm.nr_color_regions <= MAX_RTS);
979       for (unsigned rt = 0; rt < stage->key.wm.nr_color_regions; rt++) {
980          if (stage->key.wm.color_outputs_valid & BITFIELD_BIT(rt)) {
981             rt_bindings[rt] = (struct anv_pipeline_binding) {
982                .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
983                .index = rt,
984             };
985          } else {
986             /* Setup a null render target */
987             rt_bindings[rt] = (struct anv_pipeline_binding) {
988                .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
989                .index = UINT32_MAX,
990             };
991          }
992       }
993       num_rt_bindings = stage->key.wm.nr_color_regions;
994    } else {
995       /* Setup a null render target */
996       rt_bindings[0] = (struct anv_pipeline_binding) {
997          .set = ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS,
998          .index = UINT32_MAX,
999       };
1000       num_rt_bindings = 1;
1001    }
1002 
1003    assert(num_rt_bindings <= MAX_RTS);
1004    assert(stage->bind_map.surface_count == 0);
1005    typed_memcpy(stage->bind_map.surface_to_descriptor,
1006                 rt_bindings, num_rt_bindings);
1007    stage->bind_map.surface_count += num_rt_bindings;
1008 
1009    /* Now that we've set up the color attachments, we can go through and
1010     * eliminate any shader outputs that map to VK_ATTACHMENT_UNUSED in the
1011     * hopes that dead code can clean them up in this and any earlier shader
1012     * stages.
1013     */
1014    nir_function_impl *impl = nir_shader_get_entrypoint(stage->nir);
1015    bool deleted_output = false;
1016    nir_foreach_shader_out_variable_safe(var, stage->nir) {
1017       /* TODO: We don't delete depth/stencil writes.  We probably could if the
1018        * subpass doesn't have a depth/stencil attachment.
1019        */
1020       if (var->data.location < FRAG_RESULT_DATA0)
1021          continue;
1022 
1023       const unsigned rt = var->data.location - FRAG_RESULT_DATA0;
1024 
1025       /* If this is the RT at location 0 and we have alpha to coverage
1026        * enabled we still need that write because it will affect the coverage
1027        * mask even if it's never written to a color target.
1028        */
1029       if (rt == 0 && stage->key.wm.alpha_to_coverage)
1030          continue;
1031 
1032       const unsigned array_len =
1033          glsl_type_is_array(var->type) ? glsl_get_length(var->type) : 1;
1034       assert(rt + array_len <= MAX_RTS);
1035 
1036       if (rt >= MAX_RTS || !(stage->key.wm.color_outputs_valid &
1037                              BITFIELD_RANGE(rt, array_len))) {
1038          deleted_output = true;
1039          var->data.mode = nir_var_function_temp;
1040          exec_node_remove(&var->node);
1041          exec_list_push_tail(&impl->locals, &var->node);
1042       }
1043    }
1044 
1045    if (deleted_output)
1046       nir_fixup_deref_modes(stage->nir);
1047 
1048    /* We stored the number of subpass color attachments in nr_color_regions
1049     * when calculating the key for caching.  Now that we've computed the bind
1050     * map, we can reduce this to the actual max before we go into the back-end
1051     * compiler.
1052     */
1053    stage->key.wm.nr_color_regions =
1054       util_last_bit(stage->key.wm.color_outputs_valid);
1055 }
1056 
1057 static void
anv_pipeline_compile_fs(const struct brw_compiler * compiler,void * mem_ctx,struct anv_device * device,struct anv_pipeline_stage * fs_stage,struct anv_pipeline_stage * prev_stage)1058 anv_pipeline_compile_fs(const struct brw_compiler *compiler,
1059                         void *mem_ctx,
1060                         struct anv_device *device,
1061                         struct anv_pipeline_stage *fs_stage,
1062                         struct anv_pipeline_stage *prev_stage)
1063 {
1064    /* TODO: we could set this to 0 based on the information in nir_shader, but
1065     * we need this before we call spirv_to_nir.
1066     */
1067    assert(prev_stage);
1068    fs_stage->key.wm.input_slots_valid =
1069       prev_stage->prog_data.vue.vue_map.slots_valid;
1070 
1071    fs_stage->code = brw_compile_fs(compiler, device, mem_ctx,
1072                                    &fs_stage->key.wm,
1073                                    &fs_stage->prog_data.wm,
1074                                    fs_stage->nir, -1, -1, -1,
1075                                    true, false, NULL,
1076                                    fs_stage->stats, NULL);
1077 
1078    fs_stage->num_stats = (uint32_t)fs_stage->prog_data.wm.dispatch_8 +
1079                          (uint32_t)fs_stage->prog_data.wm.dispatch_16 +
1080                          (uint32_t)fs_stage->prog_data.wm.dispatch_32;
1081 
1082    if (fs_stage->key.wm.color_outputs_valid == 0 &&
1083        !fs_stage->prog_data.wm.has_side_effects &&
1084        !fs_stage->prog_data.wm.uses_omask &&
1085        !fs_stage->key.wm.alpha_to_coverage &&
1086        !fs_stage->prog_data.wm.uses_kill &&
1087        fs_stage->prog_data.wm.computed_depth_mode == BRW_PSCDEPTH_OFF &&
1088        !fs_stage->prog_data.wm.computed_stencil) {
1089       /* This fragment shader has no outputs and no side effects.  Go ahead
1090        * and return the code pointer so we don't accidentally think the
1091        * compile failed but zero out prog_data which will set program_size to
1092        * zero and disable the stage.
1093        */
1094       memset(&fs_stage->prog_data, 0, sizeof(fs_stage->prog_data));
1095    }
1096 }
1097 
1098 static void
anv_pipeline_add_executable(struct anv_pipeline * pipeline,struct anv_pipeline_stage * stage,struct brw_compile_stats * stats,uint32_t code_offset)1099 anv_pipeline_add_executable(struct anv_pipeline *pipeline,
1100                             struct anv_pipeline_stage *stage,
1101                             struct brw_compile_stats *stats,
1102                             uint32_t code_offset)
1103 {
1104    char *nir = NULL;
1105    if (stage->nir &&
1106        (pipeline->flags &
1107         VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR)) {
1108       char *stream_data = NULL;
1109       size_t stream_size = 0;
1110       FILE *stream = open_memstream(&stream_data, &stream_size);
1111 
1112       nir_print_shader(stage->nir, stream);
1113 
1114       fclose(stream);
1115 
1116       /* Copy it to a ralloc'd thing */
1117       nir = ralloc_size(pipeline->mem_ctx, stream_size + 1);
1118       memcpy(nir, stream_data, stream_size);
1119       nir[stream_size] = 0;
1120 
1121       free(stream_data);
1122    }
1123 
1124    char *disasm = NULL;
1125    if (stage->code &&
1126        (pipeline->flags &
1127         VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR)) {
1128       char *stream_data = NULL;
1129       size_t stream_size = 0;
1130       FILE *stream = open_memstream(&stream_data, &stream_size);
1131 
1132       uint32_t push_size = 0;
1133       for (unsigned i = 0; i < 4; i++)
1134          push_size += stage->bind_map.push_ranges[i].length;
1135       if (push_size > 0) {
1136          fprintf(stream, "Push constant ranges:\n");
1137          for (unsigned i = 0; i < 4; i++) {
1138             if (stage->bind_map.push_ranges[i].length == 0)
1139                continue;
1140 
1141             fprintf(stream, "    RANGE%d (%dB): ", i,
1142                     stage->bind_map.push_ranges[i].length * 32);
1143 
1144             switch (stage->bind_map.push_ranges[i].set) {
1145             case ANV_DESCRIPTOR_SET_NULL:
1146                fprintf(stream, "NULL");
1147                break;
1148 
1149             case ANV_DESCRIPTOR_SET_PUSH_CONSTANTS:
1150                fprintf(stream, "Vulkan push constants and API params");
1151                break;
1152 
1153             case ANV_DESCRIPTOR_SET_DESCRIPTORS:
1154                fprintf(stream, "Descriptor buffer for set %d (start=%dB)",
1155                        stage->bind_map.push_ranges[i].index,
1156                        stage->bind_map.push_ranges[i].start * 32);
1157                break;
1158 
1159             case ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS:
1160                unreachable("gl_NumWorkgroups is never pushed");
1161 
1162             case ANV_DESCRIPTOR_SET_SHADER_CONSTANTS:
1163                fprintf(stream, "Inline shader constant data (start=%dB)",
1164                        stage->bind_map.push_ranges[i].start * 32);
1165                break;
1166 
1167             case ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS:
1168                unreachable("Color attachments can't be pushed");
1169 
1170             default:
1171                fprintf(stream, "UBO (set=%d binding=%d start=%dB)",
1172                        stage->bind_map.push_ranges[i].set,
1173                        stage->bind_map.push_ranges[i].index,
1174                        stage->bind_map.push_ranges[i].start * 32);
1175                break;
1176             }
1177             fprintf(stream, "\n");
1178          }
1179          fprintf(stream, "\n");
1180       }
1181 
1182       /* Creating this is far cheaper than it looks.  It's perfectly fine to
1183        * do it for every binary.
1184        */
1185       struct gen_disasm *d = gen_disasm_create(&pipeline->device->info);
1186       gen_disasm_disassemble(d, stage->code, code_offset, stream);
1187       gen_disasm_destroy(d);
1188 
1189       fclose(stream);
1190 
1191       /* Copy it to a ralloc'd thing */
1192       disasm = ralloc_size(pipeline->mem_ctx, stream_size + 1);
1193       memcpy(disasm, stream_data, stream_size);
1194       disasm[stream_size] = 0;
1195 
1196       free(stream_data);
1197    }
1198 
1199    const struct anv_pipeline_executable exe = {
1200       .stage = stage->stage,
1201       .stats = *stats,
1202       .nir = nir,
1203       .disasm = disasm,
1204    };
1205    util_dynarray_append(&pipeline->executables,
1206                         struct anv_pipeline_executable, exe);
1207 }
1208 
1209 static void
anv_pipeline_add_executables(struct anv_pipeline * pipeline,struct anv_pipeline_stage * stage,struct anv_shader_bin * bin)1210 anv_pipeline_add_executables(struct anv_pipeline *pipeline,
1211                              struct anv_pipeline_stage *stage,
1212                              struct anv_shader_bin *bin)
1213 {
1214    if (stage->stage == MESA_SHADER_FRAGMENT) {
1215       /* We pull the prog data and stats out of the anv_shader_bin because
1216        * the anv_pipeline_stage may not be fully populated if we successfully
1217        * looked up the shader in a cache.
1218        */
1219       const struct brw_wm_prog_data *wm_prog_data =
1220          (const struct brw_wm_prog_data *)bin->prog_data;
1221       struct brw_compile_stats *stats = bin->stats;
1222 
1223       if (wm_prog_data->dispatch_8) {
1224          anv_pipeline_add_executable(pipeline, stage, stats++, 0);
1225       }
1226 
1227       if (wm_prog_data->dispatch_16) {
1228          anv_pipeline_add_executable(pipeline, stage, stats++,
1229                                      wm_prog_data->prog_offset_16);
1230       }
1231 
1232       if (wm_prog_data->dispatch_32) {
1233          anv_pipeline_add_executable(pipeline, stage, stats++,
1234                                      wm_prog_data->prog_offset_32);
1235       }
1236    } else {
1237       anv_pipeline_add_executable(pipeline, stage, bin->stats, 0);
1238    }
1239 }
1240 
1241 static void
anv_pipeline_init_from_cached_graphics(struct anv_graphics_pipeline * pipeline)1242 anv_pipeline_init_from_cached_graphics(struct anv_graphics_pipeline *pipeline)
1243 {
1244    /* TODO: Cache this pipeline-wide information. */
1245 
1246    /* Primitive replication depends on information from all the shaders.
1247     * Recover this bit from the fact that we have more than one position slot
1248     * in the vertex shader when using it.
1249     */
1250    assert(pipeline->active_stages & VK_SHADER_STAGE_VERTEX_BIT);
1251    int pos_slots = 0;
1252    const struct brw_vue_prog_data *vue_prog_data =
1253       (const void *) pipeline->shaders[MESA_SHADER_VERTEX]->prog_data;
1254    const struct brw_vue_map *vue_map = &vue_prog_data->vue_map;
1255    for (int i = 0; i < vue_map->num_slots; i++) {
1256       if (vue_map->slot_to_varying[i] == VARYING_SLOT_POS)
1257          pos_slots++;
1258    }
1259    pipeline->use_primitive_replication = pos_slots > 1;
1260 }
1261 
1262 static VkResult
anv_pipeline_compile_graphics(struct anv_graphics_pipeline * pipeline,struct anv_pipeline_cache * cache,const VkGraphicsPipelineCreateInfo * info)1263 anv_pipeline_compile_graphics(struct anv_graphics_pipeline *pipeline,
1264                               struct anv_pipeline_cache *cache,
1265                               const VkGraphicsPipelineCreateInfo *info)
1266 {
1267    VkPipelineCreationFeedbackEXT pipeline_feedback = {
1268       .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT,
1269    };
1270    int64_t pipeline_start = os_time_get_nano();
1271 
1272    const struct brw_compiler *compiler = pipeline->base.device->physical->compiler;
1273    struct anv_pipeline_stage stages[MESA_SHADER_STAGES] = {};
1274 
1275    pipeline->active_stages = 0;
1276 
1277    VkResult result;
1278    for (uint32_t i = 0; i < info->stageCount; i++) {
1279       const VkPipelineShaderStageCreateInfo *sinfo = &info->pStages[i];
1280       gl_shader_stage stage = vk_to_mesa_shader_stage(sinfo->stage);
1281 
1282       pipeline->active_stages |= sinfo->stage;
1283 
1284       int64_t stage_start = os_time_get_nano();
1285 
1286       stages[stage].stage = stage;
1287       stages[stage].module = anv_shader_module_from_handle(sinfo->module);
1288       stages[stage].entrypoint = sinfo->pName;
1289       stages[stage].spec_info = sinfo->pSpecializationInfo;
1290       anv_pipeline_hash_shader(stages[stage].module,
1291                                stages[stage].entrypoint,
1292                                stage,
1293                                stages[stage].spec_info,
1294                                stages[stage].shader_sha1);
1295 
1296       const struct gen_device_info *devinfo = &pipeline->base.device->info;
1297       switch (stage) {
1298       case MESA_SHADER_VERTEX:
1299          populate_vs_prog_key(devinfo, sinfo->flags, &stages[stage].key.vs);
1300          break;
1301       case MESA_SHADER_TESS_CTRL:
1302          populate_tcs_prog_key(devinfo, sinfo->flags,
1303                                info->pTessellationState->patchControlPoints,
1304                                &stages[stage].key.tcs);
1305          break;
1306       case MESA_SHADER_TESS_EVAL:
1307          populate_tes_prog_key(devinfo, sinfo->flags, &stages[stage].key.tes);
1308          break;
1309       case MESA_SHADER_GEOMETRY:
1310          populate_gs_prog_key(devinfo, sinfo->flags, &stages[stage].key.gs);
1311          break;
1312       case MESA_SHADER_FRAGMENT: {
1313          const bool raster_enabled =
1314             !info->pRasterizationState->rasterizerDiscardEnable;
1315          populate_wm_prog_key(devinfo, sinfo->flags,
1316                               pipeline->subpass,
1317                               raster_enabled ? info->pMultisampleState : NULL,
1318                               &stages[stage].key.wm);
1319          break;
1320       }
1321       default:
1322          unreachable("Invalid graphics shader stage");
1323       }
1324 
1325       stages[stage].feedback.duration += os_time_get_nano() - stage_start;
1326       stages[stage].feedback.flags |= VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT;
1327    }
1328 
1329    if (pipeline->active_stages & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)
1330       pipeline->active_stages |= VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
1331 
1332    assert(pipeline->active_stages & VK_SHADER_STAGE_VERTEX_BIT);
1333 
1334    ANV_FROM_HANDLE(anv_pipeline_layout, layout, info->layout);
1335 
1336    unsigned char sha1[20];
1337    anv_pipeline_hash_graphics(pipeline, layout, stages, sha1);
1338 
1339    for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1340       if (!stages[s].entrypoint)
1341          continue;
1342 
1343       stages[s].cache_key.stage = s;
1344       memcpy(stages[s].cache_key.sha1, sha1, sizeof(sha1));
1345    }
1346 
1347    const bool skip_cache_lookup =
1348       (pipeline->base.flags & VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR);
1349 
1350    if (!skip_cache_lookup) {
1351       unsigned found = 0;
1352       unsigned cache_hits = 0;
1353       for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1354          if (!stages[s].entrypoint)
1355             continue;
1356 
1357          int64_t stage_start = os_time_get_nano();
1358 
1359          bool cache_hit;
1360          struct anv_shader_bin *bin =
1361             anv_device_search_for_kernel(pipeline->base.device, cache,
1362                                          &stages[s].cache_key,
1363                                          sizeof(stages[s].cache_key), &cache_hit);
1364          if (bin) {
1365             found++;
1366             pipeline->shaders[s] = bin;
1367          }
1368 
1369          if (cache_hit) {
1370             cache_hits++;
1371             stages[s].feedback.flags |=
1372                VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1373          }
1374          stages[s].feedback.duration += os_time_get_nano() - stage_start;
1375       }
1376 
1377       if (found == __builtin_popcount(pipeline->active_stages)) {
1378          if (cache_hits == found) {
1379             pipeline_feedback.flags |=
1380                VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1381          }
1382          /* We found all our shaders in the cache.  We're done. */
1383          for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1384             if (!stages[s].entrypoint)
1385                continue;
1386 
1387             anv_pipeline_add_executables(&pipeline->base, &stages[s],
1388                                          pipeline->shaders[s]);
1389          }
1390          anv_pipeline_init_from_cached_graphics(pipeline);
1391          goto done;
1392       } else if (found > 0) {
1393          /* We found some but not all of our shaders.  This shouldn't happen
1394           * most of the time but it can if we have a partially populated
1395           * pipeline cache.
1396           */
1397          assert(found < __builtin_popcount(pipeline->active_stages));
1398 
1399          vk_debug_report(&pipeline->base.device->physical->instance->debug_report_callbacks,
1400                          VK_DEBUG_REPORT_WARNING_BIT_EXT |
1401                          VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
1402                          VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT,
1403                          (uint64_t)(uintptr_t)cache,
1404                          0, 0, "anv",
1405                          "Found a partial pipeline in the cache.  This is "
1406                          "most likely caused by an incomplete pipeline cache "
1407                          "import or export");
1408 
1409          /* We're going to have to recompile anyway, so just throw away our
1410           * references to the shaders in the cache.  We'll get them out of the
1411           * cache again as part of the compilation process.
1412           */
1413          for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1414             stages[s].feedback.flags = 0;
1415             if (pipeline->shaders[s]) {
1416                anv_shader_bin_unref(pipeline->base.device, pipeline->shaders[s]);
1417                pipeline->shaders[s] = NULL;
1418             }
1419          }
1420       }
1421    }
1422 
1423    if (info->flags & VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT_EXT)
1424       return VK_PIPELINE_COMPILE_REQUIRED_EXT;
1425 
1426    void *pipeline_ctx = ralloc_context(NULL);
1427 
1428    for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1429       if (!stages[s].entrypoint)
1430          continue;
1431 
1432       int64_t stage_start = os_time_get_nano();
1433 
1434       assert(stages[s].stage == s);
1435       assert(pipeline->shaders[s] == NULL);
1436 
1437       stages[s].bind_map = (struct anv_pipeline_bind_map) {
1438          .surface_to_descriptor = stages[s].surface_to_descriptor,
1439          .sampler_to_descriptor = stages[s].sampler_to_descriptor
1440       };
1441 
1442       stages[s].nir = anv_pipeline_stage_get_nir(&pipeline->base, cache,
1443                                                  pipeline_ctx,
1444                                                  &stages[s]);
1445       if (stages[s].nir == NULL) {
1446          result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1447          goto fail;
1448       }
1449 
1450       stages[s].feedback.duration += os_time_get_nano() - stage_start;
1451    }
1452 
1453    /* Walk backwards to link */
1454    struct anv_pipeline_stage *next_stage = NULL;
1455    for (int s = MESA_SHADER_STAGES - 1; s >= 0; s--) {
1456       if (!stages[s].entrypoint)
1457          continue;
1458 
1459       switch (s) {
1460       case MESA_SHADER_VERTEX:
1461          anv_pipeline_link_vs(compiler, &stages[s], next_stage);
1462          break;
1463       case MESA_SHADER_TESS_CTRL:
1464          anv_pipeline_link_tcs(compiler, &stages[s], next_stage);
1465          break;
1466       case MESA_SHADER_TESS_EVAL:
1467          anv_pipeline_link_tes(compiler, &stages[s], next_stage);
1468          break;
1469       case MESA_SHADER_GEOMETRY:
1470          anv_pipeline_link_gs(compiler, &stages[s], next_stage);
1471          break;
1472       case MESA_SHADER_FRAGMENT:
1473          anv_pipeline_link_fs(compiler, &stages[s]);
1474          break;
1475       default:
1476          unreachable("Invalid graphics shader stage");
1477       }
1478 
1479       next_stage = &stages[s];
1480    }
1481 
1482    if (pipeline->base.device->info.gen >= 12 &&
1483        pipeline->subpass->view_mask != 0) {
1484       /* For some pipelines HW Primitive Replication can be used instead of
1485        * instancing to implement Multiview.  This depend on how viewIndex is
1486        * used in all the active shaders, so this check can't be done per
1487        * individual shaders.
1488        */
1489       nir_shader *shaders[MESA_SHADER_STAGES] = {};
1490       for (unsigned s = 0; s < MESA_SHADER_STAGES; s++)
1491          shaders[s] = stages[s].nir;
1492 
1493       pipeline->use_primitive_replication =
1494          anv_check_for_primitive_replication(shaders, pipeline);
1495    } else {
1496       pipeline->use_primitive_replication = false;
1497    }
1498 
1499    struct anv_pipeline_stage *prev_stage = NULL;
1500    for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1501       if (!stages[s].entrypoint)
1502          continue;
1503 
1504       int64_t stage_start = os_time_get_nano();
1505 
1506       void *stage_ctx = ralloc_context(NULL);
1507 
1508       anv_pipeline_lower_nir(&pipeline->base, stage_ctx, &stages[s], layout);
1509 
1510       if (prev_stage && compiler->glsl_compiler_options[s].NirOptions->unify_interfaces) {
1511          prev_stage->nir->info.outputs_written |= stages[s].nir->info.inputs_read &
1512                   ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
1513          stages[s].nir->info.inputs_read |= prev_stage->nir->info.outputs_written &
1514                   ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
1515          prev_stage->nir->info.patch_outputs_written |= stages[s].nir->info.patch_inputs_read;
1516          stages[s].nir->info.patch_inputs_read |= prev_stage->nir->info.patch_outputs_written;
1517       }
1518 
1519       ralloc_free(stage_ctx);
1520 
1521       stages[s].feedback.duration += os_time_get_nano() - stage_start;
1522 
1523       prev_stage = &stages[s];
1524    }
1525 
1526    prev_stage = NULL;
1527    for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1528       if (!stages[s].entrypoint)
1529          continue;
1530 
1531       int64_t stage_start = os_time_get_nano();
1532 
1533       void *stage_ctx = ralloc_context(NULL);
1534 
1535       nir_xfb_info *xfb_info = NULL;
1536       if (s == MESA_SHADER_VERTEX ||
1537           s == MESA_SHADER_TESS_EVAL ||
1538           s == MESA_SHADER_GEOMETRY)
1539          xfb_info = nir_gather_xfb_info(stages[s].nir, stage_ctx);
1540 
1541       switch (s) {
1542       case MESA_SHADER_VERTEX:
1543          anv_pipeline_compile_vs(compiler, stage_ctx, pipeline,
1544                                  &stages[s]);
1545          break;
1546       case MESA_SHADER_TESS_CTRL:
1547          anv_pipeline_compile_tcs(compiler, stage_ctx, pipeline->base.device,
1548                                   &stages[s], prev_stage);
1549          break;
1550       case MESA_SHADER_TESS_EVAL:
1551          anv_pipeline_compile_tes(compiler, stage_ctx, pipeline->base.device,
1552                                   &stages[s], prev_stage);
1553          break;
1554       case MESA_SHADER_GEOMETRY:
1555          anv_pipeline_compile_gs(compiler, stage_ctx, pipeline->base.device,
1556                                  &stages[s], prev_stage);
1557          break;
1558       case MESA_SHADER_FRAGMENT:
1559          anv_pipeline_compile_fs(compiler, stage_ctx, pipeline->base.device,
1560                                  &stages[s], prev_stage);
1561          break;
1562       default:
1563          unreachable("Invalid graphics shader stage");
1564       }
1565       if (stages[s].code == NULL) {
1566          ralloc_free(stage_ctx);
1567          result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1568          goto fail;
1569       }
1570 
1571       anv_nir_validate_push_layout(&stages[s].prog_data.base,
1572                                    &stages[s].bind_map);
1573 
1574       struct anv_shader_bin *bin =
1575          anv_device_upload_kernel(pipeline->base.device, cache, s,
1576                                   &stages[s].cache_key,
1577                                   sizeof(stages[s].cache_key),
1578                                   stages[s].code,
1579                                   stages[s].prog_data.base.program_size,
1580                                   stages[s].nir->constant_data,
1581                                   stages[s].nir->constant_data_size,
1582                                   &stages[s].prog_data.base,
1583                                   brw_prog_data_size(s),
1584                                   stages[s].stats, stages[s].num_stats,
1585                                   xfb_info, &stages[s].bind_map);
1586       if (!bin) {
1587          ralloc_free(stage_ctx);
1588          result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1589          goto fail;
1590       }
1591 
1592       anv_pipeline_add_executables(&pipeline->base, &stages[s], bin);
1593 
1594       pipeline->shaders[s] = bin;
1595       ralloc_free(stage_ctx);
1596 
1597       stages[s].feedback.duration += os_time_get_nano() - stage_start;
1598 
1599       prev_stage = &stages[s];
1600    }
1601 
1602    ralloc_free(pipeline_ctx);
1603 
1604 done:
1605 
1606    if (pipeline->shaders[MESA_SHADER_FRAGMENT] &&
1607        pipeline->shaders[MESA_SHADER_FRAGMENT]->prog_data->program_size == 0) {
1608       /* This can happen if we decided to implicitly disable the fragment
1609        * shader.  See anv_pipeline_compile_fs().
1610        */
1611       anv_shader_bin_unref(pipeline->base.device,
1612                            pipeline->shaders[MESA_SHADER_FRAGMENT]);
1613       pipeline->shaders[MESA_SHADER_FRAGMENT] = NULL;
1614       pipeline->active_stages &= ~VK_SHADER_STAGE_FRAGMENT_BIT;
1615    }
1616 
1617    pipeline_feedback.duration = os_time_get_nano() - pipeline_start;
1618 
1619    const VkPipelineCreationFeedbackCreateInfoEXT *create_feedback =
1620       vk_find_struct_const(info->pNext, PIPELINE_CREATION_FEEDBACK_CREATE_INFO_EXT);
1621    if (create_feedback) {
1622       *create_feedback->pPipelineCreationFeedback = pipeline_feedback;
1623 
1624       assert(info->stageCount == create_feedback->pipelineStageCreationFeedbackCount);
1625       for (uint32_t i = 0; i < info->stageCount; i++) {
1626          gl_shader_stage s = vk_to_mesa_shader_stage(info->pStages[i].stage);
1627          create_feedback->pPipelineStageCreationFeedbacks[i] = stages[s].feedback;
1628       }
1629    }
1630 
1631    return VK_SUCCESS;
1632 
1633 fail:
1634    ralloc_free(pipeline_ctx);
1635 
1636    for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1637       if (pipeline->shaders[s])
1638          anv_shader_bin_unref(pipeline->base.device, pipeline->shaders[s]);
1639    }
1640 
1641    return result;
1642 }
1643 
1644 static void
shared_type_info(const struct glsl_type * type,unsigned * size,unsigned * align)1645 shared_type_info(const struct glsl_type *type, unsigned *size, unsigned *align)
1646 {
1647    assert(glsl_type_is_vector_or_scalar(type));
1648 
1649    uint32_t comp_size = glsl_type_is_boolean(type)
1650       ? 4 : glsl_get_bit_size(type) / 8;
1651    unsigned length = glsl_get_vector_elements(type);
1652    *size = comp_size * length,
1653    *align = comp_size * (length == 3 ? 4 : length);
1654 }
1655 
1656 VkResult
anv_pipeline_compile_cs(struct anv_compute_pipeline * pipeline,struct anv_pipeline_cache * cache,const VkComputePipelineCreateInfo * info,const struct anv_shader_module * module,const char * entrypoint,const VkSpecializationInfo * spec_info)1657 anv_pipeline_compile_cs(struct anv_compute_pipeline *pipeline,
1658                         struct anv_pipeline_cache *cache,
1659                         const VkComputePipelineCreateInfo *info,
1660                         const struct anv_shader_module *module,
1661                         const char *entrypoint,
1662                         const VkSpecializationInfo *spec_info)
1663 {
1664    VkPipelineCreationFeedbackEXT pipeline_feedback = {
1665       .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT,
1666    };
1667    int64_t pipeline_start = os_time_get_nano();
1668 
1669    const struct brw_compiler *compiler = pipeline->base.device->physical->compiler;
1670 
1671    struct anv_pipeline_stage stage = {
1672       .stage = MESA_SHADER_COMPUTE,
1673       .module = module,
1674       .entrypoint = entrypoint,
1675       .spec_info = spec_info,
1676       .cache_key = {
1677          .stage = MESA_SHADER_COMPUTE,
1678       },
1679       .feedback = {
1680          .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT_EXT,
1681       },
1682    };
1683    anv_pipeline_hash_shader(stage.module,
1684                             stage.entrypoint,
1685                             MESA_SHADER_COMPUTE,
1686                             stage.spec_info,
1687                             stage.shader_sha1);
1688 
1689    struct anv_shader_bin *bin = NULL;
1690 
1691    const VkPipelineShaderStageRequiredSubgroupSizeCreateInfoEXT *rss_info =
1692       vk_find_struct_const(info->stage.pNext,
1693                            PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO_EXT);
1694 
1695    populate_cs_prog_key(&pipeline->base.device->info, info->stage.flags,
1696                         rss_info, &stage.key.cs);
1697 
1698    ANV_FROM_HANDLE(anv_pipeline_layout, layout, info->layout);
1699 
1700    const bool skip_cache_lookup =
1701       (pipeline->base.flags & VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR);
1702 
1703    anv_pipeline_hash_compute(pipeline, layout, &stage, stage.cache_key.sha1);
1704 
1705    bool cache_hit = false;
1706    if (!skip_cache_lookup) {
1707       bin = anv_device_search_for_kernel(pipeline->base.device, cache,
1708                                          &stage.cache_key,
1709                                          sizeof(stage.cache_key),
1710                                          &cache_hit);
1711    }
1712 
1713    if (bin == NULL &&
1714        (info->flags & VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT_EXT))
1715       return VK_PIPELINE_COMPILE_REQUIRED_EXT;
1716 
1717    void *mem_ctx = ralloc_context(NULL);
1718    if (bin == NULL) {
1719       int64_t stage_start = os_time_get_nano();
1720 
1721       stage.bind_map = (struct anv_pipeline_bind_map) {
1722          .surface_to_descriptor = stage.surface_to_descriptor,
1723          .sampler_to_descriptor = stage.sampler_to_descriptor
1724       };
1725 
1726       /* Set up a binding for the gl_NumWorkGroups */
1727       stage.bind_map.surface_count = 1;
1728       stage.bind_map.surface_to_descriptor[0] = (struct anv_pipeline_binding) {
1729          .set = ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS,
1730       };
1731 
1732       stage.nir = anv_pipeline_stage_get_nir(&pipeline->base, cache, mem_ctx, &stage);
1733       if (stage.nir == NULL) {
1734          ralloc_free(mem_ctx);
1735          return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1736       }
1737 
1738       NIR_PASS_V(stage.nir, anv_nir_add_base_work_group_id);
1739 
1740       anv_pipeline_lower_nir(&pipeline->base, mem_ctx, &stage, layout);
1741 
1742       NIR_PASS_V(stage.nir, nir_lower_vars_to_explicit_types,
1743                  nir_var_mem_shared, shared_type_info);
1744       NIR_PASS_V(stage.nir, nir_lower_explicit_io,
1745                  nir_var_mem_shared, nir_address_format_32bit_offset);
1746       NIR_PASS_V(stage.nir, brw_nir_lower_cs_intrinsics);
1747 
1748       stage.num_stats = 1;
1749       stage.code = brw_compile_cs(compiler, pipeline->base.device, mem_ctx,
1750                                   &stage.key.cs, &stage.prog_data.cs,
1751                                   stage.nir, -1, stage.stats, NULL);
1752       if (stage.code == NULL) {
1753          ralloc_free(mem_ctx);
1754          return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1755       }
1756 
1757       anv_nir_validate_push_layout(&stage.prog_data.base, &stage.bind_map);
1758 
1759       if (!stage.prog_data.cs.uses_num_work_groups) {
1760          assert(stage.bind_map.surface_to_descriptor[0].set ==
1761                 ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS);
1762          stage.bind_map.surface_to_descriptor[0].set = ANV_DESCRIPTOR_SET_NULL;
1763       }
1764 
1765       const unsigned code_size = stage.prog_data.base.program_size;
1766       bin = anv_device_upload_kernel(pipeline->base.device, cache,
1767                                      MESA_SHADER_COMPUTE,
1768                                      &stage.cache_key, sizeof(stage.cache_key),
1769                                      stage.code, code_size,
1770                                      stage.nir->constant_data,
1771                                      stage.nir->constant_data_size,
1772                                      &stage.prog_data.base,
1773                                      sizeof(stage.prog_data.cs),
1774                                      stage.stats, stage.num_stats,
1775                                      NULL, &stage.bind_map);
1776       if (!bin) {
1777          ralloc_free(mem_ctx);
1778          return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1779       }
1780 
1781       stage.feedback.duration = os_time_get_nano() - stage_start;
1782    }
1783 
1784    anv_pipeline_add_executables(&pipeline->base, &stage, bin);
1785 
1786    ralloc_free(mem_ctx);
1787 
1788    if (cache_hit) {
1789       stage.feedback.flags |=
1790          VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1791       pipeline_feedback.flags |=
1792          VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT_EXT;
1793    }
1794    pipeline_feedback.duration = os_time_get_nano() - pipeline_start;
1795 
1796    const VkPipelineCreationFeedbackCreateInfoEXT *create_feedback =
1797       vk_find_struct_const(info->pNext, PIPELINE_CREATION_FEEDBACK_CREATE_INFO_EXT);
1798    if (create_feedback) {
1799       *create_feedback->pPipelineCreationFeedback = pipeline_feedback;
1800 
1801       assert(create_feedback->pipelineStageCreationFeedbackCount == 1);
1802       create_feedback->pPipelineStageCreationFeedbacks[0] = stage.feedback;
1803    }
1804 
1805    pipeline->cs = bin;
1806 
1807    return VK_SUCCESS;
1808 }
1809 
1810 struct anv_cs_parameters
anv_cs_parameters(const struct anv_compute_pipeline * pipeline)1811 anv_cs_parameters(const struct anv_compute_pipeline *pipeline)
1812 {
1813    const struct brw_cs_prog_data *cs_prog_data = get_cs_prog_data(pipeline);
1814 
1815    struct anv_cs_parameters cs_params = {};
1816 
1817    cs_params.group_size = cs_prog_data->local_size[0] *
1818                           cs_prog_data->local_size[1] *
1819                           cs_prog_data->local_size[2];
1820    cs_params.simd_size =
1821       brw_cs_simd_size_for_group_size(&pipeline->base.device->info,
1822                                       cs_prog_data, cs_params.group_size);
1823    cs_params.threads = DIV_ROUND_UP(cs_params.group_size, cs_params.simd_size);
1824 
1825    return cs_params;
1826 }
1827 
1828 /**
1829  * Copy pipeline state not marked as dynamic.
1830  * Dynamic state is pipeline state which hasn't been provided at pipeline
1831  * creation time, but is dynamically provided afterwards using various
1832  * vkCmdSet* functions.
1833  *
1834  * The set of state considered "non_dynamic" is determined by the pieces of
1835  * state that have their corresponding VkDynamicState enums omitted from
1836  * VkPipelineDynamicStateCreateInfo::pDynamicStates.
1837  *
1838  * @param[out] pipeline    Destination non_dynamic state.
1839  * @param[in]  pCreateInfo Source of non_dynamic state to be copied.
1840  */
1841 static void
copy_non_dynamic_state(struct anv_graphics_pipeline * pipeline,const VkGraphicsPipelineCreateInfo * pCreateInfo)1842 copy_non_dynamic_state(struct anv_graphics_pipeline *pipeline,
1843                        const VkGraphicsPipelineCreateInfo *pCreateInfo)
1844 {
1845    anv_cmd_dirty_mask_t states = ANV_CMD_DIRTY_DYNAMIC_ALL;
1846    struct anv_subpass *subpass = pipeline->subpass;
1847 
1848    pipeline->dynamic_state = default_dynamic_state;
1849 
1850    if (pCreateInfo->pDynamicState) {
1851       /* Remove all of the states that are marked as dynamic */
1852       uint32_t count = pCreateInfo->pDynamicState->dynamicStateCount;
1853       for (uint32_t s = 0; s < count; s++) {
1854          states &= ~anv_cmd_dirty_bit_for_vk_dynamic_state(
1855             pCreateInfo->pDynamicState->pDynamicStates[s]);
1856       }
1857    }
1858 
1859    struct anv_dynamic_state *dynamic = &pipeline->dynamic_state;
1860 
1861    /* Section 9.2 of the Vulkan 1.0.15 spec says:
1862     *
1863     *    pViewportState is [...] NULL if the pipeline
1864     *    has rasterization disabled.
1865     */
1866    if (!pCreateInfo->pRasterizationState->rasterizerDiscardEnable) {
1867       assert(pCreateInfo->pViewportState);
1868 
1869       dynamic->viewport.count = pCreateInfo->pViewportState->viewportCount;
1870       if (states & ANV_CMD_DIRTY_DYNAMIC_VIEWPORT) {
1871          typed_memcpy(dynamic->viewport.viewports,
1872                      pCreateInfo->pViewportState->pViewports,
1873                      pCreateInfo->pViewportState->viewportCount);
1874       }
1875 
1876       dynamic->scissor.count = pCreateInfo->pViewportState->scissorCount;
1877       if (states & ANV_CMD_DIRTY_DYNAMIC_SCISSOR) {
1878          typed_memcpy(dynamic->scissor.scissors,
1879                      pCreateInfo->pViewportState->pScissors,
1880                      pCreateInfo->pViewportState->scissorCount);
1881       }
1882    }
1883 
1884    if (states & ANV_CMD_DIRTY_DYNAMIC_LINE_WIDTH) {
1885       assert(pCreateInfo->pRasterizationState);
1886       dynamic->line_width = pCreateInfo->pRasterizationState->lineWidth;
1887    }
1888 
1889    if (states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_BIAS) {
1890       assert(pCreateInfo->pRasterizationState);
1891       dynamic->depth_bias.bias =
1892          pCreateInfo->pRasterizationState->depthBiasConstantFactor;
1893       dynamic->depth_bias.clamp =
1894          pCreateInfo->pRasterizationState->depthBiasClamp;
1895       dynamic->depth_bias.slope =
1896          pCreateInfo->pRasterizationState->depthBiasSlopeFactor;
1897    }
1898 
1899    if (states & ANV_CMD_DIRTY_DYNAMIC_CULL_MODE) {
1900       assert(pCreateInfo->pRasterizationState);
1901       dynamic->cull_mode =
1902          pCreateInfo->pRasterizationState->cullMode;
1903    }
1904 
1905    if (states & ANV_CMD_DIRTY_DYNAMIC_FRONT_FACE) {
1906       assert(pCreateInfo->pRasterizationState);
1907       dynamic->front_face =
1908          pCreateInfo->pRasterizationState->frontFace;
1909    }
1910 
1911    if (states & ANV_CMD_DIRTY_DYNAMIC_PRIMITIVE_TOPOLOGY) {
1912       assert(pCreateInfo->pInputAssemblyState);
1913       bool has_tess = false;
1914       for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1915          const VkPipelineShaderStageCreateInfo *sinfo = &pCreateInfo->pStages[i];
1916          gl_shader_stage stage = vk_to_mesa_shader_stage(sinfo->stage);
1917          if (stage == MESA_SHADER_TESS_CTRL || stage == MESA_SHADER_TESS_EVAL)
1918             has_tess = true;
1919       }
1920        if (has_tess) {
1921           const VkPipelineTessellationStateCreateInfo *tess_info =
1922              pCreateInfo->pTessellationState;
1923           dynamic->primitive_topology = _3DPRIM_PATCHLIST(tess_info->patchControlPoints);
1924        } else {
1925          dynamic->primitive_topology = pCreateInfo->pInputAssemblyState->topology;
1926        }
1927    }
1928 
1929    /* Section 9.2 of the Vulkan 1.0.15 spec says:
1930     *
1931     *    pColorBlendState is [...] NULL if the pipeline has rasterization
1932     *    disabled or if the subpass of the render pass the pipeline is
1933     *    created against does not use any color attachments.
1934     */
1935    bool uses_color_att = false;
1936    for (unsigned i = 0; i < subpass->color_count; ++i) {
1937       if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED) {
1938          uses_color_att = true;
1939          break;
1940       }
1941    }
1942 
1943    if (uses_color_att &&
1944        !pCreateInfo->pRasterizationState->rasterizerDiscardEnable) {
1945       assert(pCreateInfo->pColorBlendState);
1946 
1947       if (states & ANV_CMD_DIRTY_DYNAMIC_BLEND_CONSTANTS)
1948          typed_memcpy(dynamic->blend_constants,
1949                      pCreateInfo->pColorBlendState->blendConstants, 4);
1950    }
1951 
1952    /* If there is no depthstencil attachment, then don't read
1953     * pDepthStencilState. The Vulkan spec states that pDepthStencilState may
1954     * be NULL in this case. Even if pDepthStencilState is non-NULL, there is
1955     * no need to override the depthstencil defaults in
1956     * anv_pipeline::dynamic_state when there is no depthstencil attachment.
1957     *
1958     * Section 9.2 of the Vulkan 1.0.15 spec says:
1959     *
1960     *    pDepthStencilState is [...] NULL if the pipeline has rasterization
1961     *    disabled or if the subpass of the render pass the pipeline is created
1962     *    against does not use a depth/stencil attachment.
1963     */
1964    if (!pCreateInfo->pRasterizationState->rasterizerDiscardEnable &&
1965        subpass->depth_stencil_attachment) {
1966       assert(pCreateInfo->pDepthStencilState);
1967 
1968       if (states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_BOUNDS) {
1969          dynamic->depth_bounds.min =
1970             pCreateInfo->pDepthStencilState->minDepthBounds;
1971          dynamic->depth_bounds.max =
1972             pCreateInfo->pDepthStencilState->maxDepthBounds;
1973       }
1974 
1975       if (states & ANV_CMD_DIRTY_DYNAMIC_STENCIL_COMPARE_MASK) {
1976          dynamic->stencil_compare_mask.front =
1977             pCreateInfo->pDepthStencilState->front.compareMask;
1978          dynamic->stencil_compare_mask.back =
1979             pCreateInfo->pDepthStencilState->back.compareMask;
1980       }
1981 
1982       if (states & ANV_CMD_DIRTY_DYNAMIC_STENCIL_WRITE_MASK) {
1983          dynamic->stencil_write_mask.front =
1984             pCreateInfo->pDepthStencilState->front.writeMask;
1985          dynamic->stencil_write_mask.back =
1986             pCreateInfo->pDepthStencilState->back.writeMask;
1987       }
1988 
1989       if (states & ANV_CMD_DIRTY_DYNAMIC_STENCIL_REFERENCE) {
1990          dynamic->stencil_reference.front =
1991             pCreateInfo->pDepthStencilState->front.reference;
1992          dynamic->stencil_reference.back =
1993             pCreateInfo->pDepthStencilState->back.reference;
1994       }
1995 
1996       if (states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_TEST_ENABLE) {
1997          dynamic->depth_test_enable =
1998             pCreateInfo->pDepthStencilState->depthTestEnable;
1999       }
2000 
2001       if (states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_WRITE_ENABLE) {
2002          dynamic->depth_write_enable =
2003             pCreateInfo->pDepthStencilState->depthWriteEnable;
2004       }
2005 
2006       if (states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_COMPARE_OP) {
2007          dynamic->depth_compare_op =
2008             pCreateInfo->pDepthStencilState->depthCompareOp;
2009       }
2010 
2011       if (states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_BOUNDS_TEST_ENABLE) {
2012          dynamic->depth_bounds_test_enable =
2013             pCreateInfo->pDepthStencilState->depthBoundsTestEnable;
2014       }
2015 
2016       if (states & ANV_CMD_DIRTY_DYNAMIC_STENCIL_TEST_ENABLE) {
2017          dynamic->stencil_test_enable =
2018             pCreateInfo->pDepthStencilState->stencilTestEnable;
2019       }
2020 
2021       if (states & ANV_CMD_DIRTY_DYNAMIC_STENCIL_OP) {
2022          const VkPipelineDepthStencilStateCreateInfo *info =
2023             pCreateInfo->pDepthStencilState;
2024          memcpy(&dynamic->stencil_op.front, &info->front,
2025                 sizeof(dynamic->stencil_op.front));
2026          memcpy(&dynamic->stencil_op.back, &info->back,
2027                 sizeof(dynamic->stencil_op.back));
2028       }
2029    }
2030 
2031    const VkPipelineRasterizationLineStateCreateInfoEXT *line_state =
2032       vk_find_struct_const(pCreateInfo->pRasterizationState->pNext,
2033                            PIPELINE_RASTERIZATION_LINE_STATE_CREATE_INFO_EXT);
2034    if (line_state) {
2035       if (states & ANV_CMD_DIRTY_DYNAMIC_LINE_STIPPLE) {
2036          dynamic->line_stipple.factor = line_state->lineStippleFactor;
2037          dynamic->line_stipple.pattern = line_state->lineStipplePattern;
2038       }
2039    }
2040 
2041    pipeline->dynamic_state_mask = states;
2042 }
2043 
2044 static void
anv_pipeline_validate_create_info(const VkGraphicsPipelineCreateInfo * info)2045 anv_pipeline_validate_create_info(const VkGraphicsPipelineCreateInfo *info)
2046 {
2047 #ifdef DEBUG
2048    struct anv_render_pass *renderpass = NULL;
2049    struct anv_subpass *subpass = NULL;
2050 
2051    /* Assert that all required members of VkGraphicsPipelineCreateInfo are
2052     * present.  See the Vulkan 1.0.28 spec, Section 9.2 Graphics Pipelines.
2053     */
2054    assert(info->sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
2055 
2056    renderpass = anv_render_pass_from_handle(info->renderPass);
2057    assert(renderpass);
2058 
2059    assert(info->subpass < renderpass->subpass_count);
2060    subpass = &renderpass->subpasses[info->subpass];
2061 
2062    assert(info->stageCount >= 1);
2063    assert(info->pVertexInputState);
2064    assert(info->pInputAssemblyState);
2065    assert(info->pRasterizationState);
2066    if (!info->pRasterizationState->rasterizerDiscardEnable) {
2067       assert(info->pViewportState);
2068       assert(info->pMultisampleState);
2069 
2070       if (subpass && subpass->depth_stencil_attachment)
2071          assert(info->pDepthStencilState);
2072 
2073       if (subpass && subpass->color_count > 0) {
2074          bool all_color_unused = true;
2075          for (int i = 0; i < subpass->color_count; i++) {
2076             if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED)
2077                all_color_unused = false;
2078          }
2079          /* pColorBlendState is ignored if the pipeline has rasterization
2080           * disabled or if the subpass of the render pass the pipeline is
2081           * created against does not use any color attachments.
2082           */
2083          assert(info->pColorBlendState || all_color_unused);
2084       }
2085    }
2086 
2087    for (uint32_t i = 0; i < info->stageCount; ++i) {
2088       switch (info->pStages[i].stage) {
2089       case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
2090       case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
2091          assert(info->pTessellationState);
2092          break;
2093       default:
2094          break;
2095       }
2096    }
2097 #endif
2098 }
2099 
2100 /**
2101  * Calculate the desired L3 partitioning based on the current state of the
2102  * pipeline.  For now this simply returns the conservative defaults calculated
2103  * by get_default_l3_weights(), but we could probably do better by gathering
2104  * more statistics from the pipeline state (e.g. guess of expected URB usage
2105  * and bound surfaces), or by using feed-back from performance counters.
2106  */
2107 void
anv_pipeline_setup_l3_config(struct anv_pipeline * pipeline,bool needs_slm)2108 anv_pipeline_setup_l3_config(struct anv_pipeline *pipeline, bool needs_slm)
2109 {
2110    const struct gen_device_info *devinfo = &pipeline->device->info;
2111 
2112    const struct gen_l3_weights w =
2113       gen_get_default_l3_weights(devinfo, true, needs_slm);
2114 
2115    pipeline->l3_config = gen_get_l3_config(devinfo, w);
2116 }
2117 
2118 VkResult
anv_graphics_pipeline_init(struct anv_graphics_pipeline * pipeline,struct anv_device * device,struct anv_pipeline_cache * cache,const VkGraphicsPipelineCreateInfo * pCreateInfo,const VkAllocationCallbacks * alloc)2119 anv_graphics_pipeline_init(struct anv_graphics_pipeline *pipeline,
2120                            struct anv_device *device,
2121                            struct anv_pipeline_cache *cache,
2122                            const VkGraphicsPipelineCreateInfo *pCreateInfo,
2123                            const VkAllocationCallbacks *alloc)
2124 {
2125    VkResult result;
2126 
2127    anv_pipeline_validate_create_info(pCreateInfo);
2128 
2129    result = anv_pipeline_init(&pipeline->base, device,
2130                               ANV_PIPELINE_GRAPHICS, pCreateInfo->flags,
2131                               alloc);
2132    if (result != VK_SUCCESS)
2133       return result;
2134 
2135    anv_batch_set_storage(&pipeline->base.batch, ANV_NULL_ADDRESS,
2136                          pipeline->batch_data, sizeof(pipeline->batch_data));
2137 
2138    ANV_FROM_HANDLE(anv_render_pass, render_pass, pCreateInfo->renderPass);
2139    assert(pCreateInfo->subpass < render_pass->subpass_count);
2140    pipeline->subpass = &render_pass->subpasses[pCreateInfo->subpass];
2141 
2142    assert(pCreateInfo->pRasterizationState);
2143 
2144    copy_non_dynamic_state(pipeline, pCreateInfo);
2145    pipeline->depth_clamp_enable = pCreateInfo->pRasterizationState->depthClampEnable;
2146 
2147    /* Previously we enabled depth clipping when !depthClampEnable.
2148     * DepthClipStateCreateInfo now makes depth clipping explicit so if the
2149     * clipping info is available, use its enable value to determine clipping,
2150     * otherwise fallback to the previous !depthClampEnable logic.
2151     */
2152    const VkPipelineRasterizationDepthClipStateCreateInfoEXT *clip_info =
2153       vk_find_struct_const(pCreateInfo->pRasterizationState->pNext,
2154                            PIPELINE_RASTERIZATION_DEPTH_CLIP_STATE_CREATE_INFO_EXT);
2155    pipeline->depth_clip_enable = clip_info ? clip_info->depthClipEnable : !pipeline->depth_clamp_enable;
2156 
2157    pipeline->sample_shading_enable =
2158       !pCreateInfo->pRasterizationState->rasterizerDiscardEnable &&
2159       pCreateInfo->pMultisampleState &&
2160       pCreateInfo->pMultisampleState->sampleShadingEnable;
2161 
2162    /* When we free the pipeline, we detect stages based on the NULL status
2163     * of various prog_data pointers.  Make them NULL by default.
2164     */
2165    memset(pipeline->shaders, 0, sizeof(pipeline->shaders));
2166 
2167    result = anv_pipeline_compile_graphics(pipeline, cache, pCreateInfo);
2168    if (result != VK_SUCCESS) {
2169       anv_pipeline_finish(&pipeline->base, device, alloc);
2170       return result;
2171    }
2172 
2173    assert(pipeline->shaders[MESA_SHADER_VERTEX]);
2174 
2175    anv_pipeline_setup_l3_config(&pipeline->base, false);
2176 
2177    const VkPipelineVertexInputStateCreateInfo *vi_info =
2178       pCreateInfo->pVertexInputState;
2179 
2180    const uint64_t inputs_read = get_vs_prog_data(pipeline)->inputs_read;
2181 
2182    pipeline->vb_used = 0;
2183    for (uint32_t i = 0; i < vi_info->vertexAttributeDescriptionCount; i++) {
2184       const VkVertexInputAttributeDescription *desc =
2185          &vi_info->pVertexAttributeDescriptions[i];
2186 
2187       if (inputs_read & (1ull << (VERT_ATTRIB_GENERIC0 + desc->location)))
2188          pipeline->vb_used |= 1 << desc->binding;
2189    }
2190 
2191    for (uint32_t i = 0; i < vi_info->vertexBindingDescriptionCount; i++) {
2192       const VkVertexInputBindingDescription *desc =
2193          &vi_info->pVertexBindingDescriptions[i];
2194 
2195       pipeline->vb[desc->binding].stride = desc->stride;
2196 
2197       /* Step rate is programmed per vertex element (attribute), not
2198        * binding. Set up a map of which bindings step per instance, for
2199        * reference by vertex element setup. */
2200       switch (desc->inputRate) {
2201       default:
2202       case VK_VERTEX_INPUT_RATE_VERTEX:
2203          pipeline->vb[desc->binding].instanced = false;
2204          break;
2205       case VK_VERTEX_INPUT_RATE_INSTANCE:
2206          pipeline->vb[desc->binding].instanced = true;
2207          break;
2208       }
2209 
2210       pipeline->vb[desc->binding].instance_divisor = 1;
2211    }
2212 
2213    const VkPipelineVertexInputDivisorStateCreateInfoEXT *vi_div_state =
2214       vk_find_struct_const(vi_info->pNext,
2215                            PIPELINE_VERTEX_INPUT_DIVISOR_STATE_CREATE_INFO_EXT);
2216    if (vi_div_state) {
2217       for (uint32_t i = 0; i < vi_div_state->vertexBindingDivisorCount; i++) {
2218          const VkVertexInputBindingDivisorDescriptionEXT *desc =
2219             &vi_div_state->pVertexBindingDivisors[i];
2220 
2221          pipeline->vb[desc->binding].instance_divisor = desc->divisor;
2222       }
2223    }
2224 
2225    /* Our implementation of VK_KHR_multiview uses instancing to draw the
2226     * different views.  If the client asks for instancing, we need to multiply
2227     * the instance divisor by the number of views ensure that we repeat the
2228     * client's per-instance data once for each view.
2229     */
2230    if (pipeline->subpass->view_mask && !pipeline->use_primitive_replication) {
2231       const uint32_t view_count = anv_subpass_view_count(pipeline->subpass);
2232       for (uint32_t vb = 0; vb < MAX_VBS; vb++) {
2233          if (pipeline->vb[vb].instanced)
2234             pipeline->vb[vb].instance_divisor *= view_count;
2235       }
2236    }
2237 
2238    const VkPipelineInputAssemblyStateCreateInfo *ia_info =
2239       pCreateInfo->pInputAssemblyState;
2240    const VkPipelineTessellationStateCreateInfo *tess_info =
2241       pCreateInfo->pTessellationState;
2242    pipeline->primitive_restart = ia_info->primitiveRestartEnable;
2243 
2244    if (anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL))
2245       pipeline->topology = _3DPRIM_PATCHLIST(tess_info->patchControlPoints);
2246    else
2247       pipeline->topology = vk_to_gen_primitive_type[ia_info->topology];
2248 
2249    return VK_SUCCESS;
2250 }
2251 
2252 #define WRITE_STR(field, ...) ({                               \
2253    memset(field, 0, sizeof(field));                            \
2254    UNUSED int i = snprintf(field, sizeof(field), __VA_ARGS__); \
2255    assert(i > 0 && i < sizeof(field));                         \
2256 })
2257 
anv_GetPipelineExecutablePropertiesKHR(VkDevice device,const VkPipelineInfoKHR * pPipelineInfo,uint32_t * pExecutableCount,VkPipelineExecutablePropertiesKHR * pProperties)2258 VkResult anv_GetPipelineExecutablePropertiesKHR(
2259     VkDevice                                    device,
2260     const VkPipelineInfoKHR*                    pPipelineInfo,
2261     uint32_t*                                   pExecutableCount,
2262     VkPipelineExecutablePropertiesKHR*          pProperties)
2263 {
2264    ANV_FROM_HANDLE(anv_pipeline, pipeline, pPipelineInfo->pipeline);
2265    VK_OUTARRAY_MAKE(out, pProperties, pExecutableCount);
2266 
2267    util_dynarray_foreach (&pipeline->executables, struct anv_pipeline_executable, exe) {
2268       vk_outarray_append(&out, props) {
2269          gl_shader_stage stage = exe->stage;
2270          props->stages = mesa_to_vk_shader_stage(stage);
2271 
2272          unsigned simd_width = exe->stats.dispatch_width;
2273          if (stage == MESA_SHADER_FRAGMENT) {
2274             WRITE_STR(props->name, "%s%d %s",
2275                       simd_width ? "SIMD" : "vec",
2276                       simd_width ? simd_width : 4,
2277                       _mesa_shader_stage_to_string(stage));
2278          } else {
2279             WRITE_STR(props->name, "%s", _mesa_shader_stage_to_string(stage));
2280          }
2281          WRITE_STR(props->description, "%s%d %s shader",
2282                    simd_width ? "SIMD" : "vec",
2283                    simd_width ? simd_width : 4,
2284                    _mesa_shader_stage_to_string(stage));
2285 
2286          /* The compiler gives us a dispatch width of 0 for vec4 but Vulkan
2287           * wants a subgroup size of 1.
2288           */
2289          props->subgroupSize = MAX2(simd_width, 1);
2290       }
2291    }
2292 
2293    return vk_outarray_status(&out);
2294 }
2295 
2296 static const struct anv_pipeline_executable *
anv_pipeline_get_executable(struct anv_pipeline * pipeline,uint32_t index)2297 anv_pipeline_get_executable(struct anv_pipeline *pipeline, uint32_t index)
2298 {
2299    assert(index < util_dynarray_num_elements(&pipeline->executables,
2300                                              struct anv_pipeline_executable));
2301    return util_dynarray_element(
2302       &pipeline->executables, struct anv_pipeline_executable, index);
2303 }
2304 
anv_GetPipelineExecutableStatisticsKHR(VkDevice device,const VkPipelineExecutableInfoKHR * pExecutableInfo,uint32_t * pStatisticCount,VkPipelineExecutableStatisticKHR * pStatistics)2305 VkResult anv_GetPipelineExecutableStatisticsKHR(
2306     VkDevice                                    device,
2307     const VkPipelineExecutableInfoKHR*          pExecutableInfo,
2308     uint32_t*                                   pStatisticCount,
2309     VkPipelineExecutableStatisticKHR*           pStatistics)
2310 {
2311    ANV_FROM_HANDLE(anv_pipeline, pipeline, pExecutableInfo->pipeline);
2312    VK_OUTARRAY_MAKE(out, pStatistics, pStatisticCount);
2313 
2314    const struct anv_pipeline_executable *exe =
2315       anv_pipeline_get_executable(pipeline, pExecutableInfo->executableIndex);
2316 
2317    const struct brw_stage_prog_data *prog_data;
2318    switch (pipeline->type) {
2319    case ANV_PIPELINE_GRAPHICS: {
2320       prog_data = anv_pipeline_to_graphics(pipeline)->shaders[exe->stage]->prog_data;
2321       break;
2322    }
2323    case ANV_PIPELINE_COMPUTE: {
2324       prog_data = anv_pipeline_to_compute(pipeline)->cs->prog_data;
2325       break;
2326    }
2327    default:
2328       unreachable("invalid pipeline type");
2329    }
2330 
2331    vk_outarray_append(&out, stat) {
2332       WRITE_STR(stat->name, "Instruction Count");
2333       WRITE_STR(stat->description,
2334                 "Number of GEN instructions in the final generated "
2335                 "shader executable.");
2336       stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2337       stat->value.u64 = exe->stats.instructions;
2338    }
2339 
2340    vk_outarray_append(&out, stat) {
2341       WRITE_STR(stat->name, "SEND Count");
2342       WRITE_STR(stat->description,
2343                 "Number of instructions in the final generated shader "
2344                 "executable which access external units such as the "
2345                 "constant cache or the sampler.");
2346       stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2347       stat->value.u64 = exe->stats.sends;
2348    }
2349 
2350    vk_outarray_append(&out, stat) {
2351       WRITE_STR(stat->name, "Loop Count");
2352       WRITE_STR(stat->description,
2353                 "Number of loops (not unrolled) in the final generated "
2354                 "shader executable.");
2355       stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2356       stat->value.u64 = exe->stats.loops;
2357    }
2358 
2359    vk_outarray_append(&out, stat) {
2360       WRITE_STR(stat->name, "Cycle Count");
2361       WRITE_STR(stat->description,
2362                 "Estimate of the number of EU cycles required to execute "
2363                 "the final generated executable.  This is an estimate only "
2364                 "and may vary greatly from actual run-time performance.");
2365       stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2366       stat->value.u64 = exe->stats.cycles;
2367    }
2368 
2369    vk_outarray_append(&out, stat) {
2370       WRITE_STR(stat->name, "Spill Count");
2371       WRITE_STR(stat->description,
2372                 "Number of scratch spill operations.  This gives a rough "
2373                 "estimate of the cost incurred due to spilling temporary "
2374                 "values to memory.  If this is non-zero, you may want to "
2375                 "adjust your shader to reduce register pressure.");
2376       stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2377       stat->value.u64 = exe->stats.spills;
2378    }
2379 
2380    vk_outarray_append(&out, stat) {
2381       WRITE_STR(stat->name, "Fill Count");
2382       WRITE_STR(stat->description,
2383                 "Number of scratch fill operations.  This gives a rough "
2384                 "estimate of the cost incurred due to spilling temporary "
2385                 "values to memory.  If this is non-zero, you may want to "
2386                 "adjust your shader to reduce register pressure.");
2387       stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2388       stat->value.u64 = exe->stats.fills;
2389    }
2390 
2391    vk_outarray_append(&out, stat) {
2392       WRITE_STR(stat->name, "Scratch Memory Size");
2393       WRITE_STR(stat->description,
2394                 "Number of bytes of scratch memory required by the "
2395                 "generated shader executable.  If this is non-zero, you "
2396                 "may want to adjust your shader to reduce register "
2397                 "pressure.");
2398       stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2399       stat->value.u64 = prog_data->total_scratch;
2400    }
2401 
2402    if (exe->stage == MESA_SHADER_COMPUTE) {
2403       vk_outarray_append(&out, stat) {
2404          WRITE_STR(stat->name, "Workgroup Memory Size");
2405          WRITE_STR(stat->description,
2406                    "Number of bytes of workgroup shared memory used by this "
2407                    "compute shader including any padding.");
2408          stat->format = VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR;
2409          stat->value.u64 = brw_cs_prog_data_const(prog_data)->slm_size;
2410       }
2411    }
2412 
2413    return vk_outarray_status(&out);
2414 }
2415 
2416 static bool
write_ir_text(VkPipelineExecutableInternalRepresentationKHR * ir,const char * data)2417 write_ir_text(VkPipelineExecutableInternalRepresentationKHR* ir,
2418               const char *data)
2419 {
2420    ir->isText = VK_TRUE;
2421 
2422    size_t data_len = strlen(data) + 1;
2423 
2424    if (ir->pData == NULL) {
2425       ir->dataSize = data_len;
2426       return true;
2427    }
2428 
2429    strncpy(ir->pData, data, ir->dataSize);
2430    if (ir->dataSize < data_len)
2431       return false;
2432 
2433    ir->dataSize = data_len;
2434    return true;
2435 }
2436 
anv_GetPipelineExecutableInternalRepresentationsKHR(VkDevice device,const VkPipelineExecutableInfoKHR * pExecutableInfo,uint32_t * pInternalRepresentationCount,VkPipelineExecutableInternalRepresentationKHR * pInternalRepresentations)2437 VkResult anv_GetPipelineExecutableInternalRepresentationsKHR(
2438     VkDevice                                    device,
2439     const VkPipelineExecutableInfoKHR*          pExecutableInfo,
2440     uint32_t*                                   pInternalRepresentationCount,
2441     VkPipelineExecutableInternalRepresentationKHR* pInternalRepresentations)
2442 {
2443    ANV_FROM_HANDLE(anv_pipeline, pipeline, pExecutableInfo->pipeline);
2444    VK_OUTARRAY_MAKE(out, pInternalRepresentations,
2445                     pInternalRepresentationCount);
2446    bool incomplete_text = false;
2447 
2448    const struct anv_pipeline_executable *exe =
2449       anv_pipeline_get_executable(pipeline, pExecutableInfo->executableIndex);
2450 
2451    if (exe->nir) {
2452       vk_outarray_append(&out, ir) {
2453          WRITE_STR(ir->name, "Final NIR");
2454          WRITE_STR(ir->description,
2455                    "Final NIR before going into the back-end compiler");
2456 
2457          if (!write_ir_text(ir, exe->nir))
2458             incomplete_text = true;
2459       }
2460    }
2461 
2462    if (exe->disasm) {
2463       vk_outarray_append(&out, ir) {
2464          WRITE_STR(ir->name, "GEN Assembly");
2465          WRITE_STR(ir->description,
2466                    "Final GEN assembly for the generated shader binary");
2467 
2468          if (!write_ir_text(ir, exe->disasm))
2469             incomplete_text = true;
2470       }
2471    }
2472 
2473    return incomplete_text ? VK_INCOMPLETE : vk_outarray_status(&out);
2474 }
2475