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