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