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