bf243cdb6b4316cbfdfd432e8dae080609e83d2e
[mesa.git] / src / vulkan / anv_pipeline.c
1 /*
2 * Copyright © 2015 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #include <assert.h>
25 #include <stdbool.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29
30 #include "anv_private.h"
31 #include "brw_nir.h"
32 #include "anv_nir.h"
33 #include "glsl/nir/nir_spirv.h"
34
35 /* Needed for SWIZZLE macros */
36 #include "program/prog_instruction.h"
37
38 // Shader functions
39
40 VkResult anv_CreateShaderModule(
41 VkDevice _device,
42 const VkShaderModuleCreateInfo* pCreateInfo,
43 const VkAllocationCallbacks* pAllocator,
44 VkShaderModule* pShaderModule)
45 {
46 ANV_FROM_HANDLE(anv_device, device, _device);
47 struct anv_shader_module *module;
48
49 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
50 assert(pCreateInfo->flags == 0);
51
52 module = anv_alloc2(&device->alloc, pAllocator,
53 sizeof(*module) + pCreateInfo->codeSize, 8,
54 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
55 if (module == NULL)
56 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
57
58 module->nir = NULL;
59 module->size = pCreateInfo->codeSize;
60 memcpy(module->data, pCreateInfo->pCode, module->size);
61
62 *pShaderModule = anv_shader_module_to_handle(module);
63
64 return VK_SUCCESS;
65 }
66
67 void anv_DestroyShaderModule(
68 VkDevice _device,
69 VkShaderModule _module,
70 const VkAllocationCallbacks* pAllocator)
71 {
72 ANV_FROM_HANDLE(anv_device, device, _device);
73 ANV_FROM_HANDLE(anv_shader_module, module, _module);
74
75 anv_free2(&device->alloc, pAllocator, module);
76 }
77
78 #define SPIR_V_MAGIC_NUMBER 0x07230203
79
80 /* Eventually, this will become part of anv_CreateShader. Unfortunately,
81 * we can't do that yet because we don't have the ability to copy nir.
82 */
83 static nir_shader *
84 anv_shader_compile_to_nir(struct anv_device *device,
85 struct anv_shader_module *module,
86 const char *entrypoint_name,
87 gl_shader_stage stage)
88 {
89 if (strcmp(entrypoint_name, "main") != 0) {
90 anv_finishme("Multiple shaders per module not really supported");
91 }
92
93 const struct brw_compiler *compiler =
94 device->instance->physicalDevice.compiler;
95 const nir_shader_compiler_options *nir_options =
96 compiler->glsl_compiler_options[stage].NirOptions;
97
98 nir_shader *nir;
99 if (module->nir) {
100 /* Some things such as our meta clear/blit code will give us a NIR
101 * shader directly. In that case, we just ignore the SPIR-V entirely
102 * and just use the NIR shader */
103 nir = module->nir;
104 nir->options = nir_options;
105 } else {
106 uint32_t *spirv = (uint32_t *) module->data;
107 assert(spirv[0] == SPIR_V_MAGIC_NUMBER);
108 assert(module->size % 4 == 0);
109
110 nir = spirv_to_nir(spirv, module->size / 4, stage, nir_options);
111 }
112 nir_validate_shader(nir);
113
114 /* Vulkan uses the separate-shader linking model */
115 nir->info.separate_shader = true;
116
117 /* Make sure the provided shader has exactly one entrypoint and that the
118 * name matches the name that came in from the VkShader.
119 */
120 nir_function_impl *entrypoint = NULL;
121 nir_foreach_overload(nir, overload) {
122 if (strcmp(entrypoint_name, overload->function->name) == 0 &&
123 overload->impl) {
124 assert(entrypoint == NULL);
125 entrypoint = overload->impl;
126 }
127 }
128 assert(entrypoint != NULL);
129
130 nir = brw_preprocess_nir(nir, compiler->scalar_stage[stage]);
131
132 nir_shader_gather_info(nir, entrypoint);
133
134 return nir;
135 }
136
137 VkResult anv_CreatePipelineCache(
138 VkDevice device,
139 const VkPipelineCacheCreateInfo* pCreateInfo,
140 const VkAllocationCallbacks* pAllocator,
141 VkPipelineCache* pPipelineCache)
142 {
143 *pPipelineCache = (VkPipelineCache)1;
144
145 stub_return(VK_SUCCESS);
146 }
147
148 void anv_DestroyPipelineCache(
149 VkDevice _device,
150 VkPipelineCache _cache,
151 const VkAllocationCallbacks* pAllocator)
152 {
153 }
154
155 VkResult anv_GetPipelineCacheData(
156 VkDevice device,
157 VkPipelineCache pipelineCache,
158 size_t* pDataSize,
159 void* pData)
160 {
161 *pDataSize = 0;
162 stub_return(VK_SUCCESS);
163 }
164
165 VkResult anv_MergePipelineCaches(
166 VkDevice device,
167 VkPipelineCache destCache,
168 uint32_t srcCacheCount,
169 const VkPipelineCache* pSrcCaches)
170 {
171 stub_return(VK_SUCCESS);
172 }
173
174 void anv_DestroyPipeline(
175 VkDevice _device,
176 VkPipeline _pipeline,
177 const VkAllocationCallbacks* pAllocator)
178 {
179 ANV_FROM_HANDLE(anv_device, device, _device);
180 ANV_FROM_HANDLE(anv_pipeline, pipeline, _pipeline);
181
182 anv_reloc_list_finish(&pipeline->batch_relocs,
183 pAllocator ? pAllocator : &device->alloc);
184 anv_state_stream_finish(&pipeline->program_stream);
185 if (pipeline->blend_state.map)
186 anv_state_pool_free(&device->dynamic_state_pool, pipeline->blend_state);
187 anv_free2(&device->alloc, pAllocator, pipeline);
188 }
189
190 static const uint32_t vk_to_gen_primitive_type[] = {
191 [VK_PRIMITIVE_TOPOLOGY_POINT_LIST] = _3DPRIM_POINTLIST,
192 [VK_PRIMITIVE_TOPOLOGY_LINE_LIST] = _3DPRIM_LINELIST,
193 [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP] = _3DPRIM_LINESTRIP,
194 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST] = _3DPRIM_TRILIST,
195 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP] = _3DPRIM_TRISTRIP,
196 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN] = _3DPRIM_TRIFAN,
197 [VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY] = _3DPRIM_LINELIST_ADJ,
198 [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY] = _3DPRIM_LINESTRIP_ADJ,
199 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY] = _3DPRIM_TRILIST_ADJ,
200 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY] = _3DPRIM_TRISTRIP_ADJ,
201 /* [VK_PRIMITIVE_TOPOLOGY_PATCH_LIST] = _3DPRIM_PATCHLIST_1 */
202 };
203
204 static void
205 populate_sampler_prog_key(const struct brw_device_info *devinfo,
206 struct brw_sampler_prog_key_data *key)
207 {
208 /* XXX: Handle texture swizzle on HSW- */
209 for (int i = 0; i < MAX_SAMPLERS; i++) {
210 /* Assume color sampler, no swizzling. (Works for BDW+) */
211 key->swizzles[i] = SWIZZLE_XYZW;
212 }
213 }
214
215 static void
216 populate_vs_prog_key(const struct brw_device_info *devinfo,
217 struct brw_vs_prog_key *key)
218 {
219 memset(key, 0, sizeof(*key));
220
221 populate_sampler_prog_key(devinfo, &key->tex);
222
223 /* XXX: Handle vertex input work-arounds */
224
225 /* XXX: Handle sampler_prog_key */
226 }
227
228 static void
229 populate_gs_prog_key(const struct brw_device_info *devinfo,
230 struct brw_gs_prog_key *key)
231 {
232 memset(key, 0, sizeof(*key));
233
234 populate_sampler_prog_key(devinfo, &key->tex);
235 }
236
237 static void
238 populate_wm_prog_key(const struct brw_device_info *devinfo,
239 const VkGraphicsPipelineCreateInfo *info,
240 struct brw_wm_prog_key *key)
241 {
242 ANV_FROM_HANDLE(anv_render_pass, render_pass, info->renderPass);
243
244 memset(key, 0, sizeof(*key));
245
246 populate_sampler_prog_key(devinfo, &key->tex);
247
248 /* TODO: Fill out key->input_slots_valid */
249
250 /* Vulkan doesn't specify a default */
251 key->high_quality_derivatives = false;
252
253 /* XXX Vulkan doesn't appear to specify */
254 key->clamp_fragment_color = false;
255
256 /* Vulkan always specifies upper-left coordinates */
257 key->drawable_height = 0;
258 key->render_to_fbo = false;
259
260 key->nr_color_regions = render_pass->subpasses[info->subpass].color_count;
261
262 key->replicate_alpha = key->nr_color_regions > 1 &&
263 info->pMultisampleState &&
264 info->pMultisampleState->alphaToCoverageEnable;
265
266 if (info->pMultisampleState && info->pMultisampleState->rasterizationSamples > 1) {
267 /* We should probably pull this out of the shader, but it's fairly
268 * harmless to compute it and then let dead-code take care of it.
269 */
270 key->persample_shading = info->pMultisampleState->sampleShadingEnable;
271 if (key->persample_shading)
272 key->persample_2x = info->pMultisampleState->rasterizationSamples == 2;
273
274 key->compute_pos_offset = info->pMultisampleState->sampleShadingEnable;
275 key->compute_sample_id = info->pMultisampleState->sampleShadingEnable;
276 }
277 }
278
279 static void
280 populate_cs_prog_key(const struct brw_device_info *devinfo,
281 struct brw_cs_prog_key *key)
282 {
283 memset(key, 0, sizeof(*key));
284
285 populate_sampler_prog_key(devinfo, &key->tex);
286 }
287
288 static nir_shader *
289 anv_pipeline_compile(struct anv_pipeline *pipeline,
290 struct anv_shader_module *module,
291 const char *entrypoint,
292 gl_shader_stage stage,
293 struct brw_stage_prog_data *prog_data)
294 {
295 const struct brw_compiler *compiler =
296 pipeline->device->instance->physicalDevice.compiler;
297
298 nir_shader *nir = anv_shader_compile_to_nir(pipeline->device,
299 module, entrypoint, stage);
300 if (nir == NULL)
301 return NULL;
302
303 anv_nir_lower_push_constants(nir, compiler->scalar_stage[stage]);
304
305 /* Figure out the number of parameters */
306 prog_data->nr_params = 0;
307
308 if (nir->num_uniforms > 0) {
309 /* If the shader uses any push constants at all, we'll just give
310 * them the maximum possible number
311 */
312 prog_data->nr_params += MAX_PUSH_CONSTANTS_SIZE / sizeof(float);
313 }
314
315 if (pipeline->layout && pipeline->layout->stage[stage].has_dynamic_offsets)
316 prog_data->nr_params += MAX_DYNAMIC_BUFFERS * 2;
317
318 if (pipeline->layout && pipeline->layout->stage[stage].image_count > 0)
319 prog_data->nr_params += pipeline->layout->stage[stage].image_count *
320 BRW_IMAGE_PARAM_SIZE;
321
322 if (prog_data->nr_params > 0) {
323 /* XXX: I think we're leaking this */
324 prog_data->param = (const union gl_constant_value **)
325 malloc(prog_data->nr_params * sizeof(union gl_constant_value *));
326
327 /* We now set the param values to be offsets into a
328 * anv_push_constant_data structure. Since the compiler doesn't
329 * actually dereference any of the gl_constant_value pointers in the
330 * params array, it doesn't really matter what we put here.
331 */
332 struct anv_push_constants *null_data = NULL;
333 if (nir->num_uniforms > 0) {
334 /* Fill out the push constants section of the param array */
335 for (unsigned i = 0; i < MAX_PUSH_CONSTANTS_SIZE / sizeof(float); i++)
336 prog_data->param[i] = (const union gl_constant_value *)
337 &null_data->client_data[i * sizeof(float)];
338 }
339 }
340
341 /* Set up dynamic offsets */
342 anv_nir_apply_dynamic_offsets(pipeline, nir, prog_data);
343
344 /* Apply the actual pipeline layout to UBOs, SSBOs, and textures */
345 if (pipeline->layout)
346 anv_nir_apply_pipeline_layout(nir, prog_data, pipeline->layout);
347
348 /* All binding table offsets provided by apply_pipeline_layout() are
349 * relative to the start of the bindint table (plus MAX_RTS for VS).
350 */
351 unsigned bias = stage == MESA_SHADER_FRAGMENT ? MAX_RTS : 0;
352 prog_data->binding_table.size_bytes = 0;
353 prog_data->binding_table.texture_start = bias;
354 prog_data->binding_table.ubo_start = bias;
355 prog_data->binding_table.ssbo_start = bias;
356 prog_data->binding_table.image_start = bias;
357
358 /* Finish the optimization and compilation process */
359 nir = brw_lower_nir(nir, &pipeline->device->info, NULL,
360 compiler->scalar_stage[stage]);
361
362 /* nir_lower_io will only handle the push constants; we need to set this
363 * to the full number of possible uniforms.
364 */
365 nir->num_uniforms = prog_data->nr_params * 4;
366
367 return nir;
368 }
369
370 static uint32_t
371 anv_pipeline_upload_kernel(struct anv_pipeline *pipeline,
372 const void *data, size_t size)
373 {
374 struct anv_state state =
375 anv_state_stream_alloc(&pipeline->program_stream, size, 64);
376
377 assert(size < pipeline->program_stream.block_pool->block_size);
378
379 memcpy(state.map, data, size);
380
381 if (!pipeline->device->info.has_llc)
382 anv_state_clflush(state);
383
384 return state.offset;
385 }
386
387 static void
388 anv_pipeline_add_compiled_stage(struct anv_pipeline *pipeline,
389 gl_shader_stage stage,
390 struct brw_stage_prog_data *prog_data)
391 {
392 struct brw_device_info *devinfo = &pipeline->device->info;
393 uint32_t max_threads[] = {
394 [MESA_SHADER_VERTEX] = devinfo->max_vs_threads,
395 [MESA_SHADER_TESS_CTRL] = 0,
396 [MESA_SHADER_TESS_EVAL] = 0,
397 [MESA_SHADER_GEOMETRY] = devinfo->max_gs_threads,
398 [MESA_SHADER_FRAGMENT] = devinfo->max_wm_threads,
399 [MESA_SHADER_COMPUTE] = devinfo->max_cs_threads,
400 };
401
402 pipeline->prog_data[stage] = prog_data;
403 pipeline->active_stages |= mesa_to_vk_shader_stage(stage);
404 pipeline->scratch_start[stage] = pipeline->total_scratch;
405 pipeline->total_scratch =
406 align_u32(pipeline->total_scratch, 1024) +
407 prog_data->total_scratch * max_threads[stage];
408 }
409
410 static VkResult
411 anv_pipeline_compile_vs(struct anv_pipeline *pipeline,
412 const VkGraphicsPipelineCreateInfo *info,
413 struct anv_shader_module *module,
414 const char *entrypoint)
415 {
416 const struct brw_compiler *compiler =
417 pipeline->device->instance->physicalDevice.compiler;
418 struct brw_vs_prog_data *prog_data = &pipeline->vs_prog_data;
419 struct brw_vs_prog_key key;
420
421 populate_vs_prog_key(&pipeline->device->info, &key);
422
423 /* TODO: Look up shader in cache */
424
425 memset(prog_data, 0, sizeof(*prog_data));
426
427 nir_shader *nir = anv_pipeline_compile(pipeline, module, entrypoint,
428 MESA_SHADER_VERTEX,
429 &prog_data->base.base);
430 if (nir == NULL)
431 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
432
433 void *mem_ctx = ralloc_context(NULL);
434
435 if (module->nir == NULL)
436 ralloc_steal(mem_ctx, nir);
437
438 prog_data->inputs_read = nir->info.inputs_read;
439 pipeline->writes_point_size = nir->info.outputs_written & VARYING_SLOT_PSIZ;
440
441 brw_compute_vue_map(&pipeline->device->info,
442 &prog_data->base.vue_map,
443 nir->info.outputs_written,
444 nir->info.separate_shader);
445
446 unsigned code_size;
447 const unsigned *shader_code =
448 brw_compile_vs(compiler, NULL, mem_ctx, &key, prog_data, nir,
449 NULL, false, -1, &code_size, NULL);
450 if (shader_code == NULL) {
451 ralloc_free(mem_ctx);
452 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
453 }
454
455 const uint32_t offset =
456 anv_pipeline_upload_kernel(pipeline, shader_code, code_size);
457 if (prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8) {
458 pipeline->vs_simd8 = offset;
459 pipeline->vs_vec4 = NO_KERNEL;
460 } else {
461 pipeline->vs_simd8 = NO_KERNEL;
462 pipeline->vs_vec4 = offset;
463 }
464
465 ralloc_free(mem_ctx);
466
467 anv_pipeline_add_compiled_stage(pipeline, MESA_SHADER_VERTEX,
468 &prog_data->base.base);
469
470 return VK_SUCCESS;
471 }
472
473 static VkResult
474 anv_pipeline_compile_gs(struct anv_pipeline *pipeline,
475 const VkGraphicsPipelineCreateInfo *info,
476 struct anv_shader_module *module,
477 const char *entrypoint)
478 {
479 const struct brw_compiler *compiler =
480 pipeline->device->instance->physicalDevice.compiler;
481 struct brw_gs_prog_data *prog_data = &pipeline->gs_prog_data;
482 struct brw_gs_prog_key key;
483
484 populate_gs_prog_key(&pipeline->device->info, &key);
485
486 /* TODO: Look up shader in cache */
487
488 memset(prog_data, 0, sizeof(*prog_data));
489
490 nir_shader *nir = anv_pipeline_compile(pipeline, module, entrypoint,
491 MESA_SHADER_GEOMETRY,
492 &prog_data->base.base);
493 if (nir == NULL)
494 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
495
496 void *mem_ctx = ralloc_context(NULL);
497
498 if (module->nir == NULL)
499 ralloc_steal(mem_ctx, nir);
500
501 brw_compute_vue_map(&pipeline->device->info,
502 &prog_data->base.vue_map,
503 nir->info.outputs_written,
504 nir->info.separate_shader);
505
506 unsigned code_size;
507 const unsigned *shader_code =
508 brw_compile_gs(compiler, NULL, mem_ctx, &key, prog_data, nir,
509 NULL, -1, &code_size, NULL);
510 if (shader_code == NULL) {
511 ralloc_free(mem_ctx);
512 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
513 }
514
515 /* TODO: SIMD8 GS */
516 pipeline->gs_kernel =
517 anv_pipeline_upload_kernel(pipeline, shader_code, code_size);
518 pipeline->gs_vertex_count = nir->info.gs.vertices_in;
519
520 ralloc_free(mem_ctx);
521
522 anv_pipeline_add_compiled_stage(pipeline, MESA_SHADER_GEOMETRY,
523 &prog_data->base.base);
524
525 return VK_SUCCESS;
526 }
527
528 static VkResult
529 anv_pipeline_compile_fs(struct anv_pipeline *pipeline,
530 const VkGraphicsPipelineCreateInfo *info,
531 struct anv_shader_module *module,
532 const char *entrypoint)
533 {
534 const struct brw_compiler *compiler =
535 pipeline->device->instance->physicalDevice.compiler;
536 struct brw_wm_prog_data *prog_data = &pipeline->wm_prog_data;
537 struct brw_wm_prog_key key;
538
539 populate_wm_prog_key(&pipeline->device->info, info, &key);
540
541 if (pipeline->use_repclear)
542 key.nr_color_regions = 1;
543
544 /* TODO: Look up shader in cache */
545
546 memset(prog_data, 0, sizeof(*prog_data));
547
548 prog_data->binding_table.render_target_start = 0;
549
550 nir_shader *nir = anv_pipeline_compile(pipeline, module, entrypoint,
551 MESA_SHADER_FRAGMENT,
552 &prog_data->base);
553 if (nir == NULL)
554 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
555
556 void *mem_ctx = ralloc_context(NULL);
557
558 if (module->nir == NULL)
559 ralloc_steal(mem_ctx, nir);
560
561 unsigned code_size;
562 const unsigned *shader_code =
563 brw_compile_fs(compiler, NULL, mem_ctx, &key, prog_data, nir,
564 NULL, -1, -1, pipeline->use_repclear, &code_size, NULL);
565 if (shader_code == NULL) {
566 ralloc_free(mem_ctx);
567 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
568 }
569
570 uint32_t offset = anv_pipeline_upload_kernel(pipeline,
571 shader_code, code_size);
572 if (prog_data->no_8)
573 pipeline->ps_simd8 = NO_KERNEL;
574 else
575 pipeline->ps_simd8 = offset;
576
577 if (prog_data->no_8 || prog_data->prog_offset_16) {
578 pipeline->ps_simd16 = offset + prog_data->prog_offset_16;
579 } else {
580 pipeline->ps_simd16 = NO_KERNEL;
581 }
582
583 pipeline->ps_ksp2 = 0;
584 pipeline->ps_grf_start2 = 0;
585 if (pipeline->ps_simd8 != NO_KERNEL) {
586 pipeline->ps_ksp0 = pipeline->ps_simd8;
587 pipeline->ps_grf_start0 = prog_data->base.dispatch_grf_start_reg;
588 if (pipeline->ps_simd16 != NO_KERNEL) {
589 pipeline->ps_ksp2 = pipeline->ps_simd16;
590 pipeline->ps_grf_start2 = prog_data->dispatch_grf_start_reg_16;
591 }
592 } else if (pipeline->ps_simd16 != NO_KERNEL) {
593 pipeline->ps_ksp0 = pipeline->ps_simd16;
594 pipeline->ps_grf_start0 = prog_data->dispatch_grf_start_reg_16;
595 }
596
597 ralloc_free(mem_ctx);
598
599 anv_pipeline_add_compiled_stage(pipeline, MESA_SHADER_FRAGMENT,
600 &prog_data->base);
601
602 return VK_SUCCESS;
603 }
604
605 VkResult
606 anv_pipeline_compile_cs(struct anv_pipeline *pipeline,
607 const VkComputePipelineCreateInfo *info,
608 struct anv_shader_module *module,
609 const char *entrypoint)
610 {
611 const struct brw_compiler *compiler =
612 pipeline->device->instance->physicalDevice.compiler;
613 struct brw_cs_prog_data *prog_data = &pipeline->cs_prog_data;
614 struct brw_cs_prog_key key;
615
616 populate_cs_prog_key(&pipeline->device->info, &key);
617
618 /* TODO: Look up shader in cache */
619
620 memset(prog_data, 0, sizeof(*prog_data));
621
622 nir_shader *nir = anv_pipeline_compile(pipeline, module, entrypoint,
623 MESA_SHADER_COMPUTE,
624 &prog_data->base);
625 if (nir == NULL)
626 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
627
628 void *mem_ctx = ralloc_context(NULL);
629
630 if (module->nir == NULL)
631 ralloc_steal(mem_ctx, nir);
632
633 unsigned code_size;
634 const unsigned *shader_code =
635 brw_compile_cs(compiler, NULL, mem_ctx, &key, prog_data, nir,
636 -1, &code_size, NULL);
637 if (shader_code == NULL) {
638 ralloc_free(mem_ctx);
639 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
640 }
641
642 pipeline->cs_simd = anv_pipeline_upload_kernel(pipeline,
643 shader_code, code_size);
644 ralloc_free(mem_ctx);
645
646 anv_pipeline_add_compiled_stage(pipeline, MESA_SHADER_COMPUTE,
647 &prog_data->base);
648
649 return VK_SUCCESS;
650 }
651
652 static const int gen8_push_size = 32 * 1024;
653
654 static void
655 gen7_compute_urb_partition(struct anv_pipeline *pipeline)
656 {
657 const struct brw_device_info *devinfo = &pipeline->device->info;
658 bool vs_present = pipeline->active_stages & VK_SHADER_STAGE_VERTEX_BIT;
659 unsigned vs_size = vs_present ? pipeline->vs_prog_data.base.urb_entry_size : 1;
660 unsigned vs_entry_size_bytes = vs_size * 64;
661 bool gs_present = pipeline->active_stages & VK_SHADER_STAGE_GEOMETRY_BIT;
662 unsigned gs_size = gs_present ? pipeline->gs_prog_data.base.urb_entry_size : 1;
663 unsigned gs_entry_size_bytes = gs_size * 64;
664
665 /* From p35 of the Ivy Bridge PRM (section 1.7.1: 3DSTATE_URB_GS):
666 *
667 * VS Number of URB Entries must be divisible by 8 if the VS URB Entry
668 * Allocation Size is less than 9 512-bit URB entries.
669 *
670 * Similar text exists for GS.
671 */
672 unsigned vs_granularity = (vs_size < 9) ? 8 : 1;
673 unsigned gs_granularity = (gs_size < 9) ? 8 : 1;
674
675 /* URB allocations must be done in 8k chunks. */
676 unsigned chunk_size_bytes = 8192;
677
678 /* Determine the size of the URB in chunks. */
679 unsigned urb_chunks = devinfo->urb.size * 1024 / chunk_size_bytes;
680
681 /* Reserve space for push constants */
682 unsigned push_constant_bytes = gen8_push_size;
683 unsigned push_constant_chunks =
684 push_constant_bytes / chunk_size_bytes;
685
686 /* Initially, assign each stage the minimum amount of URB space it needs,
687 * and make a note of how much additional space it "wants" (the amount of
688 * additional space it could actually make use of).
689 */
690
691 /* VS has a lower limit on the number of URB entries */
692 unsigned vs_chunks =
693 ALIGN(devinfo->urb.min_vs_entries * vs_entry_size_bytes,
694 chunk_size_bytes) / chunk_size_bytes;
695 unsigned vs_wants =
696 ALIGN(devinfo->urb.max_vs_entries * vs_entry_size_bytes,
697 chunk_size_bytes) / chunk_size_bytes - vs_chunks;
698
699 unsigned gs_chunks = 0;
700 unsigned gs_wants = 0;
701 if (gs_present) {
702 /* There are two constraints on the minimum amount of URB space we can
703 * allocate:
704 *
705 * (1) We need room for at least 2 URB entries, since we always operate
706 * the GS in DUAL_OBJECT mode.
707 *
708 * (2) We can't allocate less than nr_gs_entries_granularity.
709 */
710 gs_chunks = ALIGN(MAX2(gs_granularity, 2) * gs_entry_size_bytes,
711 chunk_size_bytes) / chunk_size_bytes;
712 gs_wants =
713 ALIGN(devinfo->urb.max_gs_entries * gs_entry_size_bytes,
714 chunk_size_bytes) / chunk_size_bytes - gs_chunks;
715 }
716
717 /* There should always be enough URB space to satisfy the minimum
718 * requirements of each stage.
719 */
720 unsigned total_needs = push_constant_chunks + vs_chunks + gs_chunks;
721 assert(total_needs <= urb_chunks);
722
723 /* Mete out remaining space (if any) in proportion to "wants". */
724 unsigned total_wants = vs_wants + gs_wants;
725 unsigned remaining_space = urb_chunks - total_needs;
726 if (remaining_space > total_wants)
727 remaining_space = total_wants;
728 if (remaining_space > 0) {
729 unsigned vs_additional = (unsigned)
730 round(vs_wants * (((double) remaining_space) / total_wants));
731 vs_chunks += vs_additional;
732 remaining_space -= vs_additional;
733 gs_chunks += remaining_space;
734 }
735
736 /* Sanity check that we haven't over-allocated. */
737 assert(push_constant_chunks + vs_chunks + gs_chunks <= urb_chunks);
738
739 /* Finally, compute the number of entries that can fit in the space
740 * allocated to each stage.
741 */
742 unsigned nr_vs_entries = vs_chunks * chunk_size_bytes / vs_entry_size_bytes;
743 unsigned nr_gs_entries = gs_chunks * chunk_size_bytes / gs_entry_size_bytes;
744
745 /* Since we rounded up when computing *_wants, this may be slightly more
746 * than the maximum allowed amount, so correct for that.
747 */
748 nr_vs_entries = MIN2(nr_vs_entries, devinfo->urb.max_vs_entries);
749 nr_gs_entries = MIN2(nr_gs_entries, devinfo->urb.max_gs_entries);
750
751 /* Ensure that we program a multiple of the granularity. */
752 nr_vs_entries = ROUND_DOWN_TO(nr_vs_entries, vs_granularity);
753 nr_gs_entries = ROUND_DOWN_TO(nr_gs_entries, gs_granularity);
754
755 /* Finally, sanity check to make sure we have at least the minimum number
756 * of entries needed for each stage.
757 */
758 assert(nr_vs_entries >= devinfo->urb.min_vs_entries);
759 if (gs_present)
760 assert(nr_gs_entries >= 2);
761
762 /* Lay out the URB in the following order:
763 * - push constants
764 * - VS
765 * - GS
766 */
767 pipeline->urb.vs_start = push_constant_chunks;
768 pipeline->urb.vs_size = vs_size;
769 pipeline->urb.nr_vs_entries = nr_vs_entries;
770
771 pipeline->urb.gs_start = push_constant_chunks + vs_chunks;
772 pipeline->urb.gs_size = gs_size;
773 pipeline->urb.nr_gs_entries = nr_gs_entries;
774 }
775
776 static void
777 anv_pipeline_init_dynamic_state(struct anv_pipeline *pipeline,
778 const VkGraphicsPipelineCreateInfo *pCreateInfo)
779 {
780 anv_cmd_dirty_mask_t states = ANV_CMD_DIRTY_DYNAMIC_ALL;
781 ANV_FROM_HANDLE(anv_render_pass, pass, pCreateInfo->renderPass);
782 struct anv_subpass *subpass = &pass->subpasses[pCreateInfo->subpass];
783
784 pipeline->dynamic_state = default_dynamic_state;
785
786 if (pCreateInfo->pDynamicState) {
787 /* Remove all of the states that are marked as dynamic */
788 uint32_t count = pCreateInfo->pDynamicState->dynamicStateCount;
789 for (uint32_t s = 0; s < count; s++)
790 states &= ~(1 << pCreateInfo->pDynamicState->pDynamicStates[s]);
791 }
792
793 struct anv_dynamic_state *dynamic = &pipeline->dynamic_state;
794
795 dynamic->viewport.count = pCreateInfo->pViewportState->viewportCount;
796 if (states & (1 << VK_DYNAMIC_STATE_VIEWPORT)) {
797 typed_memcpy(dynamic->viewport.viewports,
798 pCreateInfo->pViewportState->pViewports,
799 pCreateInfo->pViewportState->viewportCount);
800 }
801
802 dynamic->scissor.count = pCreateInfo->pViewportState->scissorCount;
803 if (states & (1 << VK_DYNAMIC_STATE_SCISSOR)) {
804 typed_memcpy(dynamic->scissor.scissors,
805 pCreateInfo->pViewportState->pScissors,
806 pCreateInfo->pViewportState->scissorCount);
807 }
808
809 if (states & (1 << VK_DYNAMIC_STATE_LINE_WIDTH)) {
810 assert(pCreateInfo->pRasterizationState);
811 dynamic->line_width = pCreateInfo->pRasterizationState->lineWidth;
812 }
813
814 if (states & (1 << VK_DYNAMIC_STATE_DEPTH_BIAS)) {
815 assert(pCreateInfo->pRasterizationState);
816 dynamic->depth_bias.bias =
817 pCreateInfo->pRasterizationState->depthBiasConstantFactor;
818 dynamic->depth_bias.clamp =
819 pCreateInfo->pRasterizationState->depthBiasClamp;
820 dynamic->depth_bias.slope =
821 pCreateInfo->pRasterizationState->depthBiasSlopeFactor;
822 }
823
824 if (states & (1 << VK_DYNAMIC_STATE_BLEND_CONSTANTS)) {
825 assert(pCreateInfo->pColorBlendState);
826 typed_memcpy(dynamic->blend_constants,
827 pCreateInfo->pColorBlendState->blendConstants, 4);
828 }
829
830 /* If there is no depthstencil attachment, then don't read
831 * pDepthStencilState. The Vulkan spec states that pDepthStencilState may
832 * be NULL in this case. Even if pDepthStencilState is non-NULL, there is
833 * no need to override the depthstencil defaults in
834 * anv_pipeline::dynamic_state when there is no depthstencil attachment.
835 *
836 * From the Vulkan spec (20 Oct 2015, git-aa308cb):
837 *
838 * pDepthStencilState [...] may only be NULL if renderPass and subpass
839 * specify a subpass that has no depth/stencil attachment.
840 */
841 if (subpass->depth_stencil_attachment != VK_ATTACHMENT_UNUSED) {
842 if (states & (1 << VK_DYNAMIC_STATE_DEPTH_BOUNDS)) {
843 assert(pCreateInfo->pDepthStencilState);
844 dynamic->depth_bounds.min =
845 pCreateInfo->pDepthStencilState->minDepthBounds;
846 dynamic->depth_bounds.max =
847 pCreateInfo->pDepthStencilState->maxDepthBounds;
848 }
849
850 if (states & (1 << VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK)) {
851 assert(pCreateInfo->pDepthStencilState);
852 dynamic->stencil_compare_mask.front =
853 pCreateInfo->pDepthStencilState->front.compareMask;
854 dynamic->stencil_compare_mask.back =
855 pCreateInfo->pDepthStencilState->back.compareMask;
856 }
857
858 if (states & (1 << VK_DYNAMIC_STATE_STENCIL_WRITE_MASK)) {
859 assert(pCreateInfo->pDepthStencilState);
860 dynamic->stencil_write_mask.front =
861 pCreateInfo->pDepthStencilState->front.writeMask;
862 dynamic->stencil_write_mask.back =
863 pCreateInfo->pDepthStencilState->back.writeMask;
864 }
865
866 if (states & (1 << VK_DYNAMIC_STATE_STENCIL_REFERENCE)) {
867 assert(pCreateInfo->pDepthStencilState);
868 dynamic->stencil_reference.front =
869 pCreateInfo->pDepthStencilState->front.reference;
870 dynamic->stencil_reference.back =
871 pCreateInfo->pDepthStencilState->back.reference;
872 }
873 }
874
875 pipeline->dynamic_state_mask = states;
876 }
877
878 static void
879 anv_pipeline_validate_create_info(const VkGraphicsPipelineCreateInfo *info)
880 {
881 struct anv_render_pass *renderpass = NULL;
882 struct anv_subpass *subpass = NULL;
883
884 /* Assert that all required members of VkGraphicsPipelineCreateInfo are
885 * present, as explained by the Vulkan (20 Oct 2015, git-aa308cb), Section
886 * 4.2 Graphics Pipeline.
887 */
888 assert(info->sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
889
890 renderpass = anv_render_pass_from_handle(info->renderPass);
891 assert(renderpass);
892
893 if (renderpass != &anv_meta_dummy_renderpass) {
894 assert(info->subpass < renderpass->subpass_count);
895 subpass = &renderpass->subpasses[info->subpass];
896 }
897
898 assert(info->stageCount >= 1);
899 assert(info->pVertexInputState);
900 assert(info->pInputAssemblyState);
901 assert(info->pViewportState);
902 assert(info->pRasterizationState);
903 assert(info->pMultisampleState);
904
905 if (subpass && subpass->depth_stencil_attachment != VK_ATTACHMENT_UNUSED)
906 assert(info->pDepthStencilState);
907
908 if (subpass && subpass->color_count > 0)
909 assert(info->pColorBlendState);
910
911 for (uint32_t i = 0; i < info->stageCount; ++i) {
912 switch (info->pStages[i].stage) {
913 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
914 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
915 assert(info->pTessellationState);
916 break;
917 default:
918 break;
919 }
920 }
921 }
922
923 VkResult
924 anv_pipeline_init(struct anv_pipeline *pipeline, struct anv_device *device,
925 const VkGraphicsPipelineCreateInfo *pCreateInfo,
926 const struct anv_graphics_pipeline_create_info *extra,
927 const VkAllocationCallbacks *alloc)
928 {
929 anv_validate {
930 anv_pipeline_validate_create_info(pCreateInfo);
931 }
932
933 if (alloc == NULL)
934 alloc = &device->alloc;
935
936 pipeline->device = device;
937 pipeline->layout = anv_pipeline_layout_from_handle(pCreateInfo->layout);
938
939 anv_reloc_list_init(&pipeline->batch_relocs, alloc);
940 /* TODO: Handle allocation fail */
941
942 pipeline->batch.alloc = alloc;
943 pipeline->batch.next = pipeline->batch.start = pipeline->batch_data;
944 pipeline->batch.end = pipeline->batch.start + sizeof(pipeline->batch_data);
945 pipeline->batch.relocs = &pipeline->batch_relocs;
946
947 anv_state_stream_init(&pipeline->program_stream,
948 &device->instruction_block_pool);
949
950 anv_pipeline_init_dynamic_state(pipeline, pCreateInfo);
951
952 if (pCreateInfo->pTessellationState)
953 anv_finishme("VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO");
954 if (pCreateInfo->pMultisampleState &&
955 pCreateInfo->pMultisampleState->rasterizationSamples > 1)
956 anv_finishme("VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO");
957
958 pipeline->use_repclear = extra && extra->use_repclear;
959 pipeline->writes_point_size = false;
960
961 /* When we free the pipeline, we detect stages based on the NULL status
962 * of various prog_data pointers. Make them NULL by default.
963 */
964 memset(pipeline->prog_data, 0, sizeof(pipeline->prog_data));
965 memset(pipeline->scratch_start, 0, sizeof(pipeline->scratch_start));
966
967 pipeline->vs_simd8 = NO_KERNEL;
968 pipeline->vs_vec4 = NO_KERNEL;
969 pipeline->gs_kernel = NO_KERNEL;
970
971 pipeline->active_stages = 0;
972 pipeline->total_scratch = 0;
973
974 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
975 ANV_FROM_HANDLE(anv_shader_module, module,
976 pCreateInfo->pStages[i].module);
977 const char *entrypoint = pCreateInfo->pStages[i].pName;
978
979 switch (pCreateInfo->pStages[i].stage) {
980 case VK_SHADER_STAGE_VERTEX_BIT:
981 anv_pipeline_compile_vs(pipeline, pCreateInfo, module, entrypoint);
982 break;
983 case VK_SHADER_STAGE_GEOMETRY_BIT:
984 anv_pipeline_compile_gs(pipeline, pCreateInfo, module, entrypoint);
985 break;
986 case VK_SHADER_STAGE_FRAGMENT_BIT:
987 anv_pipeline_compile_fs(pipeline, pCreateInfo, module, entrypoint);
988 break;
989 default:
990 anv_finishme("Unsupported shader stage");
991 }
992 }
993
994 if (!(pipeline->active_stages & VK_SHADER_STAGE_VERTEX_BIT)) {
995 /* Vertex is only optional if disable_vs is set */
996 assert(extra->disable_vs);
997 memset(&pipeline->vs_prog_data, 0, sizeof(pipeline->vs_prog_data));
998 }
999
1000 gen7_compute_urb_partition(pipeline);
1001
1002 const VkPipelineVertexInputStateCreateInfo *vi_info =
1003 pCreateInfo->pVertexInputState;
1004 pipeline->vb_used = 0;
1005 for (uint32_t i = 0; i < vi_info->vertexBindingDescriptionCount; i++) {
1006 const VkVertexInputBindingDescription *desc =
1007 &vi_info->pVertexBindingDescriptions[i];
1008
1009 pipeline->vb_used |= 1 << desc->binding;
1010 pipeline->binding_stride[desc->binding] = desc->stride;
1011
1012 /* Step rate is programmed per vertex element (attribute), not
1013 * binding. Set up a map of which bindings step per instance, for
1014 * reference by vertex element setup. */
1015 switch (desc->inputRate) {
1016 default:
1017 case VK_VERTEX_INPUT_RATE_VERTEX:
1018 pipeline->instancing_enable[desc->binding] = false;
1019 break;
1020 case VK_VERTEX_INPUT_RATE_INSTANCE:
1021 pipeline->instancing_enable[desc->binding] = true;
1022 break;
1023 }
1024 }
1025
1026 const VkPipelineInputAssemblyStateCreateInfo *ia_info =
1027 pCreateInfo->pInputAssemblyState;
1028 pipeline->primitive_restart = ia_info->primitiveRestartEnable;
1029 pipeline->topology = vk_to_gen_primitive_type[ia_info->topology];
1030
1031 if (extra && extra->use_rectlist)
1032 pipeline->topology = _3DPRIM_RECTLIST;
1033
1034 return VK_SUCCESS;
1035 }
1036
1037 VkResult
1038 anv_graphics_pipeline_create(
1039 VkDevice _device,
1040 const VkGraphicsPipelineCreateInfo *pCreateInfo,
1041 const struct anv_graphics_pipeline_create_info *extra,
1042 const VkAllocationCallbacks *pAllocator,
1043 VkPipeline *pPipeline)
1044 {
1045 ANV_FROM_HANDLE(anv_device, device, _device);
1046
1047 switch (device->info.gen) {
1048 case 7:
1049 if (device->info.is_haswell)
1050 return gen75_graphics_pipeline_create(_device, pCreateInfo, extra, pAllocator, pPipeline);
1051 else
1052 return gen7_graphics_pipeline_create(_device, pCreateInfo, extra, pAllocator, pPipeline);
1053 case 8:
1054 return gen8_graphics_pipeline_create(_device, pCreateInfo, extra, pAllocator, pPipeline);
1055 case 9:
1056 return gen9_graphics_pipeline_create(_device, pCreateInfo, extra, pAllocator, pPipeline);
1057 default:
1058 unreachable("unsupported gen\n");
1059 }
1060 }
1061
1062 VkResult anv_CreateGraphicsPipelines(
1063 VkDevice _device,
1064 VkPipelineCache pipelineCache,
1065 uint32_t count,
1066 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1067 const VkAllocationCallbacks* pAllocator,
1068 VkPipeline* pPipelines)
1069 {
1070 VkResult result = VK_SUCCESS;
1071
1072 unsigned i = 0;
1073 for (; i < count; i++) {
1074 result = anv_graphics_pipeline_create(_device, &pCreateInfos[i],
1075 NULL, pAllocator, &pPipelines[i]);
1076 if (result != VK_SUCCESS) {
1077 for (unsigned j = 0; j < i; j++) {
1078 anv_DestroyPipeline(_device, pPipelines[j], pAllocator);
1079 }
1080
1081 return result;
1082 }
1083 }
1084
1085 return VK_SUCCESS;
1086 }
1087
1088 static VkResult anv_compute_pipeline_create(
1089 VkDevice _device,
1090 const VkComputePipelineCreateInfo* pCreateInfo,
1091 const VkAllocationCallbacks* pAllocator,
1092 VkPipeline* pPipeline)
1093 {
1094 ANV_FROM_HANDLE(anv_device, device, _device);
1095
1096 switch (device->info.gen) {
1097 case 7:
1098 if (device->info.is_haswell)
1099 return gen75_compute_pipeline_create(_device, pCreateInfo, pAllocator, pPipeline);
1100 else
1101 return gen7_compute_pipeline_create(_device, pCreateInfo, pAllocator, pPipeline);
1102 case 8:
1103 return gen8_compute_pipeline_create(_device, pCreateInfo, pAllocator, pPipeline);
1104 case 9:
1105 return gen9_compute_pipeline_create(_device, pCreateInfo, pAllocator, pPipeline);
1106 default:
1107 unreachable("unsupported gen\n");
1108 }
1109 }
1110
1111 VkResult anv_CreateComputePipelines(
1112 VkDevice _device,
1113 VkPipelineCache pipelineCache,
1114 uint32_t count,
1115 const VkComputePipelineCreateInfo* pCreateInfos,
1116 const VkAllocationCallbacks* pAllocator,
1117 VkPipeline* pPipelines)
1118 {
1119 VkResult result = VK_SUCCESS;
1120
1121 unsigned i = 0;
1122 for (; i < count; i++) {
1123 result = anv_compute_pipeline_create(_device, &pCreateInfos[i],
1124 pAllocator, &pPipelines[i]);
1125 if (result != VK_SUCCESS) {
1126 for (unsigned j = 0; j < i; j++) {
1127 anv_DestroyPipeline(_device, pPipelines[j], pAllocator);
1128 }
1129
1130 return result;
1131 }
1132 }
1133
1134 return VK_SUCCESS;
1135 }