948e675d0915e780051326d8a2652d8b4f1474f9
[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 (prog_data->nr_params > 0) {
319 /* XXX: I think we're leaking this */
320 prog_data->param = (const gl_constant_value **)
321 malloc(prog_data->nr_params * sizeof(gl_constant_value *));
322
323 /* We now set the param values to be offsets into a
324 * anv_push_constant_data structure. Since the compiler doesn't
325 * actually dereference any of the gl_constant_value pointers in the
326 * params array, it doesn't really matter what we put here.
327 */
328 struct anv_push_constants *null_data = NULL;
329 if (nir->num_uniforms > 0) {
330 /* Fill out the push constants section of the param array */
331 for (unsigned i = 0; i < MAX_PUSH_CONSTANTS_SIZE / sizeof(float); i++)
332 prog_data->param[i] = (const gl_constant_value *)
333 &null_data->client_data[i * sizeof(float)];
334 }
335 }
336
337 /* Set up dynamic offsets */
338 anv_nir_apply_dynamic_offsets(pipeline, nir, prog_data);
339
340 /* Apply the actual pipeline layout to UBOs, SSBOs, and textures */
341 anv_nir_apply_pipeline_layout(nir, pipeline->layout);
342
343 /* All binding table offsets provided by apply_pipeline_layout() are
344 * relative to the start of the bindint table (plus MAX_RTS for VS).
345 */
346 unsigned bias = stage == MESA_SHADER_FRAGMENT ? MAX_RTS : 0;
347 prog_data->binding_table.size_bytes = 0;
348 prog_data->binding_table.texture_start = bias;
349 prog_data->binding_table.ubo_start = bias;
350 prog_data->binding_table.ssbo_start = bias;
351 prog_data->binding_table.image_start = bias;
352
353 /* Finish the optimization and compilation process */
354 nir = brw_lower_nir(nir, &pipeline->device->info, NULL,
355 compiler->scalar_stage[stage]);
356
357 /* nir_lower_io will only handle the push constants; we need to set this
358 * to the full number of possible uniforms.
359 */
360 nir->num_uniforms = prog_data->nr_params;
361
362 return nir;
363 }
364
365 static uint32_t
366 anv_pipeline_upload_kernel(struct anv_pipeline *pipeline,
367 const void *data, size_t size)
368 {
369 struct anv_state state =
370 anv_state_stream_alloc(&pipeline->program_stream, size, 64);
371
372 assert(size < pipeline->program_stream.block_pool->block_size);
373
374 memcpy(state.map, data, size);
375
376 if (!pipeline->device->info.has_llc)
377 anv_state_clflush(state);
378
379 return state.offset;
380 }
381
382 static void
383 anv_pipeline_add_compiled_stage(struct anv_pipeline *pipeline,
384 gl_shader_stage stage,
385 struct brw_stage_prog_data *prog_data)
386 {
387 struct brw_device_info *devinfo = &pipeline->device->info;
388 uint32_t max_threads[] = {
389 [MESA_SHADER_VERTEX] = devinfo->max_vs_threads,
390 [MESA_SHADER_TESS_CTRL] = 0,
391 [MESA_SHADER_TESS_EVAL] = 0,
392 [MESA_SHADER_GEOMETRY] = devinfo->max_gs_threads,
393 [MESA_SHADER_FRAGMENT] = devinfo->max_wm_threads,
394 [MESA_SHADER_COMPUTE] = devinfo->max_cs_threads,
395 };
396
397 pipeline->prog_data[stage] = prog_data;
398 pipeline->active_stages |= mesa_to_vk_shader_stage(stage);
399 pipeline->scratch_start[stage] = pipeline->total_scratch;
400 pipeline->total_scratch =
401 align_u32(pipeline->total_scratch, 1024) +
402 prog_data->total_scratch * max_threads[stage];
403 }
404
405 static VkResult
406 anv_pipeline_compile_vs(struct anv_pipeline *pipeline,
407 const VkGraphicsPipelineCreateInfo *info,
408 struct anv_shader_module *module,
409 const char *entrypoint)
410 {
411 const struct brw_compiler *compiler =
412 pipeline->device->instance->physicalDevice.compiler;
413 struct brw_vs_prog_data *prog_data = &pipeline->vs_prog_data;
414 struct brw_vs_prog_key key;
415
416 populate_vs_prog_key(&pipeline->device->info, &key);
417
418 /* TODO: Look up shader in cache */
419
420 memset(prog_data, 0, sizeof(*prog_data));
421
422 nir_shader *nir = anv_pipeline_compile(pipeline, module, entrypoint,
423 MESA_SHADER_VERTEX,
424 &prog_data->base.base);
425 if (nir == NULL)
426 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
427
428 void *mem_ctx = ralloc_context(NULL);
429
430 if (module->nir == NULL)
431 ralloc_steal(mem_ctx, nir);
432
433 prog_data->inputs_read = nir->info.inputs_read;
434 pipeline->writes_point_size = nir->info.outputs_written & VARYING_SLOT_PSIZ;
435
436 brw_compute_vue_map(&pipeline->device->info,
437 &prog_data->base.vue_map,
438 nir->info.outputs_written,
439 nir->info.separate_shader);
440
441 unsigned code_size;
442 const unsigned *shader_code =
443 brw_compile_vs(compiler, NULL, mem_ctx, &key, prog_data, nir,
444 NULL, false, -1, &code_size, NULL);
445 if (shader_code == NULL) {
446 ralloc_free(mem_ctx);
447 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
448 }
449
450 const uint32_t offset =
451 anv_pipeline_upload_kernel(pipeline, shader_code, code_size);
452 if (prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8) {
453 pipeline->vs_simd8 = offset;
454 pipeline->vs_vec4 = NO_KERNEL;
455 } else {
456 pipeline->vs_simd8 = NO_KERNEL;
457 pipeline->vs_vec4 = offset;
458 }
459
460 ralloc_free(mem_ctx);
461
462 anv_pipeline_add_compiled_stage(pipeline, MESA_SHADER_VERTEX,
463 &prog_data->base.base);
464
465 return VK_SUCCESS;
466 }
467
468 static VkResult
469 anv_pipeline_compile_gs(struct anv_pipeline *pipeline,
470 const VkGraphicsPipelineCreateInfo *info,
471 struct anv_shader_module *module,
472 const char *entrypoint)
473 {
474 const struct brw_compiler *compiler =
475 pipeline->device->instance->physicalDevice.compiler;
476 struct brw_gs_prog_data *prog_data = &pipeline->gs_prog_data;
477 struct brw_gs_prog_key key;
478
479 populate_gs_prog_key(&pipeline->device->info, &key);
480
481 /* TODO: Look up shader in cache */
482
483 memset(prog_data, 0, sizeof(*prog_data));
484
485 nir_shader *nir = anv_pipeline_compile(pipeline, module, entrypoint,
486 MESA_SHADER_GEOMETRY,
487 &prog_data->base.base);
488 if (nir == NULL)
489 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
490
491 void *mem_ctx = ralloc_context(NULL);
492
493 if (module->nir == NULL)
494 ralloc_steal(mem_ctx, nir);
495
496 brw_compute_vue_map(&pipeline->device->info,
497 &prog_data->base.vue_map,
498 nir->info.outputs_written,
499 nir->info.separate_shader);
500
501 unsigned code_size;
502 const unsigned *shader_code =
503 brw_compile_gs(compiler, NULL, mem_ctx, &key, prog_data, nir,
504 NULL, -1, &code_size, NULL);
505 if (shader_code == NULL) {
506 ralloc_free(mem_ctx);
507 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
508 }
509
510 /* TODO: SIMD8 GS */
511 pipeline->gs_vec4 =
512 anv_pipeline_upload_kernel(pipeline, shader_code, code_size);
513 pipeline->gs_vertex_count = nir->info.gs.vertices_in;
514
515 ralloc_free(mem_ctx);
516
517 anv_pipeline_add_compiled_stage(pipeline, MESA_SHADER_GEOMETRY,
518 &prog_data->base.base);
519
520 return VK_SUCCESS;
521 }
522
523 static VkResult
524 anv_pipeline_compile_fs(struct anv_pipeline *pipeline,
525 const VkGraphicsPipelineCreateInfo *info,
526 struct anv_shader_module *module,
527 const char *entrypoint)
528 {
529 const struct brw_compiler *compiler =
530 pipeline->device->instance->physicalDevice.compiler;
531 struct brw_wm_prog_data *prog_data = &pipeline->wm_prog_data;
532 struct brw_wm_prog_key key;
533
534 populate_wm_prog_key(&pipeline->device->info, info, &key);
535
536 if (pipeline->use_repclear)
537 key.nr_color_regions = 1;
538
539 /* TODO: Look up shader in cache */
540
541 memset(prog_data, 0, sizeof(*prog_data));
542
543 prog_data->binding_table.render_target_start = 0;
544
545 nir_shader *nir = anv_pipeline_compile(pipeline, module, entrypoint,
546 MESA_SHADER_FRAGMENT,
547 &prog_data->base);
548 if (nir == NULL)
549 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
550
551 void *mem_ctx = ralloc_context(NULL);
552
553 if (module->nir == NULL)
554 ralloc_steal(mem_ctx, nir);
555
556 unsigned code_size;
557 const unsigned *shader_code =
558 brw_compile_fs(compiler, NULL, mem_ctx, &key, prog_data, nir,
559 NULL, -1, -1, pipeline->use_repclear, &code_size, NULL);
560 if (shader_code == NULL) {
561 ralloc_free(mem_ctx);
562 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
563 }
564
565 uint32_t offset = anv_pipeline_upload_kernel(pipeline,
566 shader_code, code_size);
567 if (prog_data->no_8)
568 pipeline->ps_simd8 = NO_KERNEL;
569 else
570 pipeline->ps_simd8 = offset;
571
572 if (prog_data->no_8 || prog_data->prog_offset_16) {
573 pipeline->ps_simd16 = offset + prog_data->prog_offset_16;
574 } else {
575 pipeline->ps_simd16 = NO_KERNEL;
576 }
577
578 pipeline->ps_ksp2 = 0;
579 pipeline->ps_grf_start2 = 0;
580 if (pipeline->ps_simd8 != NO_KERNEL) {
581 pipeline->ps_ksp0 = pipeline->ps_simd8;
582 pipeline->ps_grf_start0 = prog_data->base.dispatch_grf_start_reg;
583 if (pipeline->ps_simd16 != NO_KERNEL) {
584 pipeline->ps_ksp2 = pipeline->ps_simd16;
585 pipeline->ps_grf_start2 = prog_data->dispatch_grf_start_reg_16;
586 }
587 } else if (pipeline->ps_simd16 != NO_KERNEL) {
588 pipeline->ps_ksp0 = pipeline->ps_simd16;
589 pipeline->ps_grf_start0 = prog_data->dispatch_grf_start_reg_16;
590 }
591
592 ralloc_free(mem_ctx);
593
594 anv_pipeline_add_compiled_stage(pipeline, MESA_SHADER_FRAGMENT,
595 &prog_data->base);
596
597 return VK_SUCCESS;
598 }
599
600 VkResult
601 anv_pipeline_compile_cs(struct anv_pipeline *pipeline,
602 const VkComputePipelineCreateInfo *info,
603 struct anv_shader_module *module,
604 const char *entrypoint)
605 {
606 const struct brw_compiler *compiler =
607 pipeline->device->instance->physicalDevice.compiler;
608 struct brw_cs_prog_data *prog_data = &pipeline->cs_prog_data;
609 struct brw_cs_prog_key key;
610
611 populate_cs_prog_key(&pipeline->device->info, &key);
612
613 /* TODO: Look up shader in cache */
614
615 memset(prog_data, 0, sizeof(*prog_data));
616
617 nir_shader *nir = anv_pipeline_compile(pipeline, module, entrypoint,
618 MESA_SHADER_COMPUTE,
619 &prog_data->base);
620 if (nir == NULL)
621 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
622
623 void *mem_ctx = ralloc_context(NULL);
624
625 if (module->nir == NULL)
626 ralloc_steal(mem_ctx, nir);
627
628 unsigned code_size;
629 const unsigned *shader_code =
630 brw_compile_cs(compiler, NULL, mem_ctx, &key, prog_data, nir,
631 -1, &code_size, NULL);
632 if (shader_code == NULL) {
633 ralloc_free(mem_ctx);
634 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
635 }
636
637 pipeline->cs_simd = anv_pipeline_upload_kernel(pipeline,
638 shader_code, code_size);
639 ralloc_free(mem_ctx);
640
641 anv_pipeline_add_compiled_stage(pipeline, MESA_SHADER_COMPUTE,
642 &prog_data->base);
643
644 return VK_SUCCESS;
645 }
646
647 static const int gen8_push_size = 32 * 1024;
648
649 static void
650 gen7_compute_urb_partition(struct anv_pipeline *pipeline)
651 {
652 const struct brw_device_info *devinfo = &pipeline->device->info;
653 bool vs_present = pipeline->active_stages & VK_SHADER_STAGE_VERTEX_BIT;
654 unsigned vs_size = vs_present ? pipeline->vs_prog_data.base.urb_entry_size : 1;
655 unsigned vs_entry_size_bytes = vs_size * 64;
656 bool gs_present = pipeline->active_stages & VK_SHADER_STAGE_GEOMETRY_BIT;
657 unsigned gs_size = gs_present ? pipeline->gs_prog_data.base.urb_entry_size : 1;
658 unsigned gs_entry_size_bytes = gs_size * 64;
659
660 /* From p35 of the Ivy Bridge PRM (section 1.7.1: 3DSTATE_URB_GS):
661 *
662 * VS Number of URB Entries must be divisible by 8 if the VS URB Entry
663 * Allocation Size is less than 9 512-bit URB entries.
664 *
665 * Similar text exists for GS.
666 */
667 unsigned vs_granularity = (vs_size < 9) ? 8 : 1;
668 unsigned gs_granularity = (gs_size < 9) ? 8 : 1;
669
670 /* URB allocations must be done in 8k chunks. */
671 unsigned chunk_size_bytes = 8192;
672
673 /* Determine the size of the URB in chunks. */
674 unsigned urb_chunks = devinfo->urb.size * 1024 / chunk_size_bytes;
675
676 /* Reserve space for push constants */
677 unsigned push_constant_bytes = gen8_push_size;
678 unsigned push_constant_chunks =
679 push_constant_bytes / chunk_size_bytes;
680
681 /* Initially, assign each stage the minimum amount of URB space it needs,
682 * and make a note of how much additional space it "wants" (the amount of
683 * additional space it could actually make use of).
684 */
685
686 /* VS has a lower limit on the number of URB entries */
687 unsigned vs_chunks =
688 ALIGN(devinfo->urb.min_vs_entries * vs_entry_size_bytes,
689 chunk_size_bytes) / chunk_size_bytes;
690 unsigned vs_wants =
691 ALIGN(devinfo->urb.max_vs_entries * vs_entry_size_bytes,
692 chunk_size_bytes) / chunk_size_bytes - vs_chunks;
693
694 unsigned gs_chunks = 0;
695 unsigned gs_wants = 0;
696 if (gs_present) {
697 /* There are two constraints on the minimum amount of URB space we can
698 * allocate:
699 *
700 * (1) We need room for at least 2 URB entries, since we always operate
701 * the GS in DUAL_OBJECT mode.
702 *
703 * (2) We can't allocate less than nr_gs_entries_granularity.
704 */
705 gs_chunks = ALIGN(MAX2(gs_granularity, 2) * gs_entry_size_bytes,
706 chunk_size_bytes) / chunk_size_bytes;
707 gs_wants =
708 ALIGN(devinfo->urb.max_gs_entries * gs_entry_size_bytes,
709 chunk_size_bytes) / chunk_size_bytes - gs_chunks;
710 }
711
712 /* There should always be enough URB space to satisfy the minimum
713 * requirements of each stage.
714 */
715 unsigned total_needs = push_constant_chunks + vs_chunks + gs_chunks;
716 assert(total_needs <= urb_chunks);
717
718 /* Mete out remaining space (if any) in proportion to "wants". */
719 unsigned total_wants = vs_wants + gs_wants;
720 unsigned remaining_space = urb_chunks - total_needs;
721 if (remaining_space > total_wants)
722 remaining_space = total_wants;
723 if (remaining_space > 0) {
724 unsigned vs_additional = (unsigned)
725 round(vs_wants * (((double) remaining_space) / total_wants));
726 vs_chunks += vs_additional;
727 remaining_space -= vs_additional;
728 gs_chunks += remaining_space;
729 }
730
731 /* Sanity check that we haven't over-allocated. */
732 assert(push_constant_chunks + vs_chunks + gs_chunks <= urb_chunks);
733
734 /* Finally, compute the number of entries that can fit in the space
735 * allocated to each stage.
736 */
737 unsigned nr_vs_entries = vs_chunks * chunk_size_bytes / vs_entry_size_bytes;
738 unsigned nr_gs_entries = gs_chunks * chunk_size_bytes / gs_entry_size_bytes;
739
740 /* Since we rounded up when computing *_wants, this may be slightly more
741 * than the maximum allowed amount, so correct for that.
742 */
743 nr_vs_entries = MIN2(nr_vs_entries, devinfo->urb.max_vs_entries);
744 nr_gs_entries = MIN2(nr_gs_entries, devinfo->urb.max_gs_entries);
745
746 /* Ensure that we program a multiple of the granularity. */
747 nr_vs_entries = ROUND_DOWN_TO(nr_vs_entries, vs_granularity);
748 nr_gs_entries = ROUND_DOWN_TO(nr_gs_entries, gs_granularity);
749
750 /* Finally, sanity check to make sure we have at least the minimum number
751 * of entries needed for each stage.
752 */
753 assert(nr_vs_entries >= devinfo->urb.min_vs_entries);
754 if (gs_present)
755 assert(nr_gs_entries >= 2);
756
757 /* Lay out the URB in the following order:
758 * - push constants
759 * - VS
760 * - GS
761 */
762 pipeline->urb.vs_start = push_constant_chunks;
763 pipeline->urb.vs_size = vs_size;
764 pipeline->urb.nr_vs_entries = nr_vs_entries;
765
766 pipeline->urb.gs_start = push_constant_chunks + vs_chunks;
767 pipeline->urb.gs_size = gs_size;
768 pipeline->urb.nr_gs_entries = nr_gs_entries;
769 }
770
771 static void
772 anv_pipeline_init_dynamic_state(struct anv_pipeline *pipeline,
773 const VkGraphicsPipelineCreateInfo *pCreateInfo)
774 {
775 anv_cmd_dirty_mask_t states = ANV_CMD_DIRTY_DYNAMIC_ALL;
776 ANV_FROM_HANDLE(anv_render_pass, pass, pCreateInfo->renderPass);
777 struct anv_subpass *subpass = &pass->subpasses[pCreateInfo->subpass];
778
779 pipeline->dynamic_state = default_dynamic_state;
780
781 if (pCreateInfo->pDynamicState) {
782 /* Remove all of the states that are marked as dynamic */
783 uint32_t count = pCreateInfo->pDynamicState->dynamicStateCount;
784 for (uint32_t s = 0; s < count; s++)
785 states &= ~(1 << pCreateInfo->pDynamicState->pDynamicStates[s]);
786 }
787
788 struct anv_dynamic_state *dynamic = &pipeline->dynamic_state;
789
790 dynamic->viewport.count = pCreateInfo->pViewportState->viewportCount;
791 if (states & (1 << VK_DYNAMIC_STATE_VIEWPORT)) {
792 typed_memcpy(dynamic->viewport.viewports,
793 pCreateInfo->pViewportState->pViewports,
794 pCreateInfo->pViewportState->viewportCount);
795 }
796
797 dynamic->scissor.count = pCreateInfo->pViewportState->scissorCount;
798 if (states & (1 << VK_DYNAMIC_STATE_SCISSOR)) {
799 typed_memcpy(dynamic->scissor.scissors,
800 pCreateInfo->pViewportState->pScissors,
801 pCreateInfo->pViewportState->scissorCount);
802 }
803
804 if (states & (1 << VK_DYNAMIC_STATE_LINE_WIDTH)) {
805 assert(pCreateInfo->pRasterizationState);
806 dynamic->line_width = pCreateInfo->pRasterizationState->lineWidth;
807 }
808
809 if (states & (1 << VK_DYNAMIC_STATE_DEPTH_BIAS)) {
810 assert(pCreateInfo->pRasterizationState);
811 dynamic->depth_bias.bias =
812 pCreateInfo->pRasterizationState->depthBiasConstantFactor;
813 dynamic->depth_bias.clamp =
814 pCreateInfo->pRasterizationState->depthBiasClamp;
815 dynamic->depth_bias.slope =
816 pCreateInfo->pRasterizationState->depthBiasSlopeFactor;
817 }
818
819 if (states & (1 << VK_DYNAMIC_STATE_BLEND_CONSTANTS)) {
820 assert(pCreateInfo->pColorBlendState);
821 typed_memcpy(dynamic->blend_constants,
822 pCreateInfo->pColorBlendState->blendConstants, 4);
823 }
824
825 /* If there is no depthstencil attachment, then don't read
826 * pDepthStencilState. The Vulkan spec states that pDepthStencilState may
827 * be NULL in this case. Even if pDepthStencilState is non-NULL, there is
828 * no need to override the depthstencil defaults in
829 * anv_pipeline::dynamic_state when there is no depthstencil attachment.
830 *
831 * From the Vulkan spec (20 Oct 2015, git-aa308cb):
832 *
833 * pDepthStencilState [...] may only be NULL if renderPass and subpass
834 * specify a subpass that has no depth/stencil attachment.
835 */
836 if (subpass->depth_stencil_attachment != VK_ATTACHMENT_UNUSED) {
837 if (states & (1 << VK_DYNAMIC_STATE_DEPTH_BOUNDS)) {
838 assert(pCreateInfo->pDepthStencilState);
839 dynamic->depth_bounds.min =
840 pCreateInfo->pDepthStencilState->minDepthBounds;
841 dynamic->depth_bounds.max =
842 pCreateInfo->pDepthStencilState->maxDepthBounds;
843 }
844
845 if (states & (1 << VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK)) {
846 assert(pCreateInfo->pDepthStencilState);
847 dynamic->stencil_compare_mask.front =
848 pCreateInfo->pDepthStencilState->front.compareMask;
849 dynamic->stencil_compare_mask.back =
850 pCreateInfo->pDepthStencilState->back.compareMask;
851 }
852
853 if (states & (1 << VK_DYNAMIC_STATE_STENCIL_WRITE_MASK)) {
854 assert(pCreateInfo->pDepthStencilState);
855 dynamic->stencil_write_mask.front =
856 pCreateInfo->pDepthStencilState->front.writeMask;
857 dynamic->stencil_write_mask.back =
858 pCreateInfo->pDepthStencilState->back.writeMask;
859 }
860
861 if (states & (1 << VK_DYNAMIC_STATE_STENCIL_REFERENCE)) {
862 assert(pCreateInfo->pDepthStencilState);
863 dynamic->stencil_reference.front =
864 pCreateInfo->pDepthStencilState->front.reference;
865 dynamic->stencil_reference.back =
866 pCreateInfo->pDepthStencilState->back.reference;
867 }
868 }
869
870 pipeline->dynamic_state_mask = states;
871 }
872
873 static void
874 anv_pipeline_validate_create_info(const VkGraphicsPipelineCreateInfo *info)
875 {
876 struct anv_render_pass *renderpass = NULL;
877 struct anv_subpass *subpass = NULL;
878
879 /* Assert that all required members of VkGraphicsPipelineCreateInfo are
880 * present, as explained by the Vulkan (20 Oct 2015, git-aa308cb), Section
881 * 4.2 Graphics Pipeline.
882 */
883 assert(info->sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
884
885 renderpass = anv_render_pass_from_handle(info->renderPass);
886 assert(renderpass);
887
888 if (renderpass != &anv_meta_dummy_renderpass) {
889 assert(info->subpass < renderpass->subpass_count);
890 subpass = &renderpass->subpasses[info->subpass];
891 }
892
893 assert(info->stageCount >= 1);
894 assert(info->pVertexInputState);
895 assert(info->pInputAssemblyState);
896 assert(info->pViewportState);
897 assert(info->pRasterizationState);
898 assert(info->pMultisampleState);
899
900 if (subpass && subpass->depth_stencil_attachment != VK_ATTACHMENT_UNUSED)
901 assert(info->pDepthStencilState);
902
903 if (subpass && subpass->color_count > 0)
904 assert(info->pColorBlendState);
905
906 for (uint32_t i = 0; i < info->stageCount; ++i) {
907 switch (info->pStages[i].stage) {
908 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
909 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
910 assert(info->pTessellationState);
911 break;
912 default:
913 break;
914 }
915 }
916 }
917
918 VkResult
919 anv_pipeline_init(struct anv_pipeline *pipeline, struct anv_device *device,
920 const VkGraphicsPipelineCreateInfo *pCreateInfo,
921 const struct anv_graphics_pipeline_create_info *extra,
922 const VkAllocationCallbacks *alloc)
923 {
924 anv_validate {
925 anv_pipeline_validate_create_info(pCreateInfo);
926 }
927
928 if (alloc == NULL)
929 alloc = &device->alloc;
930
931 pipeline->device = device;
932 pipeline->layout = anv_pipeline_layout_from_handle(pCreateInfo->layout);
933
934 anv_reloc_list_init(&pipeline->batch_relocs, alloc);
935 /* TODO: Handle allocation fail */
936
937 pipeline->batch.alloc = alloc;
938 pipeline->batch.next = pipeline->batch.start = pipeline->batch_data;
939 pipeline->batch.end = pipeline->batch.start + sizeof(pipeline->batch_data);
940 pipeline->batch.relocs = &pipeline->batch_relocs;
941
942 anv_state_stream_init(&pipeline->program_stream,
943 &device->instruction_block_pool);
944
945 anv_pipeline_init_dynamic_state(pipeline, pCreateInfo);
946
947 if (pCreateInfo->pTessellationState)
948 anv_finishme("VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO");
949 if (pCreateInfo->pMultisampleState &&
950 pCreateInfo->pMultisampleState->rasterizationSamples > 1)
951 anv_finishme("VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO");
952
953 pipeline->use_repclear = extra && extra->use_repclear;
954 pipeline->writes_point_size = false;
955
956 /* When we free the pipeline, we detect stages based on the NULL status
957 * of various prog_data pointers. Make them NULL by default.
958 */
959 memset(pipeline->prog_data, 0, sizeof(pipeline->prog_data));
960 memset(pipeline->scratch_start, 0, sizeof(pipeline->scratch_start));
961
962 pipeline->vs_simd8 = NO_KERNEL;
963 pipeline->vs_vec4 = NO_KERNEL;
964 pipeline->gs_vec4 = NO_KERNEL;
965
966 pipeline->active_stages = 0;
967 pipeline->total_scratch = 0;
968
969 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
970 ANV_FROM_HANDLE(anv_shader_module, module,
971 pCreateInfo->pStages[i].module);
972 const char *entrypoint = pCreateInfo->pStages[i].pName;
973
974 switch (pCreateInfo->pStages[i].stage) {
975 case VK_SHADER_STAGE_VERTEX_BIT:
976 anv_pipeline_compile_vs(pipeline, pCreateInfo, module, entrypoint);
977 break;
978 case VK_SHADER_STAGE_GEOMETRY_BIT:
979 anv_pipeline_compile_gs(pipeline, pCreateInfo, module, entrypoint);
980 break;
981 case VK_SHADER_STAGE_FRAGMENT_BIT:
982 anv_pipeline_compile_fs(pipeline, pCreateInfo, module, entrypoint);
983 break;
984 default:
985 anv_finishme("Unsupported shader stage");
986 }
987 }
988
989 if (!(pipeline->active_stages & VK_SHADER_STAGE_VERTEX_BIT)) {
990 /* Vertex is only optional if disable_vs is set */
991 assert(extra->disable_vs);
992 memset(&pipeline->vs_prog_data, 0, sizeof(pipeline->vs_prog_data));
993 }
994
995 gen7_compute_urb_partition(pipeline);
996
997 const VkPipelineVertexInputStateCreateInfo *vi_info =
998 pCreateInfo->pVertexInputState;
999 pipeline->vb_used = 0;
1000 for (uint32_t i = 0; i < vi_info->vertexBindingDescriptionCount; i++) {
1001 const VkVertexInputBindingDescription *desc =
1002 &vi_info->pVertexBindingDescriptions[i];
1003
1004 pipeline->vb_used |= 1 << desc->binding;
1005 pipeline->binding_stride[desc->binding] = desc->stride;
1006
1007 /* Step rate is programmed per vertex element (attribute), not
1008 * binding. Set up a map of which bindings step per instance, for
1009 * reference by vertex element setup. */
1010 switch (desc->inputRate) {
1011 default:
1012 case VK_VERTEX_INPUT_RATE_VERTEX:
1013 pipeline->instancing_enable[desc->binding] = false;
1014 break;
1015 case VK_VERTEX_INPUT_RATE_INSTANCE:
1016 pipeline->instancing_enable[desc->binding] = true;
1017 break;
1018 }
1019 }
1020
1021 const VkPipelineInputAssemblyStateCreateInfo *ia_info =
1022 pCreateInfo->pInputAssemblyState;
1023 pipeline->primitive_restart = ia_info->primitiveRestartEnable;
1024 pipeline->topology = vk_to_gen_primitive_type[ia_info->topology];
1025
1026 if (extra && extra->use_rectlist)
1027 pipeline->topology = _3DPRIM_RECTLIST;
1028
1029 return VK_SUCCESS;
1030 }
1031
1032 VkResult
1033 anv_graphics_pipeline_create(
1034 VkDevice _device,
1035 const VkGraphicsPipelineCreateInfo *pCreateInfo,
1036 const struct anv_graphics_pipeline_create_info *extra,
1037 const VkAllocationCallbacks *pAllocator,
1038 VkPipeline *pPipeline)
1039 {
1040 ANV_FROM_HANDLE(anv_device, device, _device);
1041
1042 switch (device->info.gen) {
1043 case 7:
1044 if (device->info.is_haswell)
1045 return gen75_graphics_pipeline_create(_device, pCreateInfo, extra, pAllocator, pPipeline);
1046 else
1047 return gen7_graphics_pipeline_create(_device, pCreateInfo, extra, pAllocator, pPipeline);
1048 case 8:
1049 return gen8_graphics_pipeline_create(_device, pCreateInfo, extra, pAllocator, pPipeline);
1050 case 9:
1051 return gen9_graphics_pipeline_create(_device, pCreateInfo, extra, pAllocator, pPipeline);
1052 default:
1053 unreachable("unsupported gen\n");
1054 }
1055 }
1056
1057 VkResult anv_CreateGraphicsPipelines(
1058 VkDevice _device,
1059 VkPipelineCache pipelineCache,
1060 uint32_t count,
1061 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1062 const VkAllocationCallbacks* pAllocator,
1063 VkPipeline* pPipelines)
1064 {
1065 VkResult result = VK_SUCCESS;
1066
1067 unsigned i = 0;
1068 for (; i < count; i++) {
1069 result = anv_graphics_pipeline_create(_device, &pCreateInfos[i],
1070 NULL, pAllocator, &pPipelines[i]);
1071 if (result != VK_SUCCESS) {
1072 for (unsigned j = 0; j < i; j++) {
1073 anv_DestroyPipeline(_device, pPipelines[j], pAllocator);
1074 }
1075
1076 return result;
1077 }
1078 }
1079
1080 return VK_SUCCESS;
1081 }
1082
1083 static VkResult anv_compute_pipeline_create(
1084 VkDevice _device,
1085 const VkComputePipelineCreateInfo* pCreateInfo,
1086 const VkAllocationCallbacks* pAllocator,
1087 VkPipeline* pPipeline)
1088 {
1089 ANV_FROM_HANDLE(anv_device, device, _device);
1090
1091 switch (device->info.gen) {
1092 case 7:
1093 if (device->info.is_haswell)
1094 return gen75_compute_pipeline_create(_device, pCreateInfo, pAllocator, pPipeline);
1095 else
1096 return gen7_compute_pipeline_create(_device, pCreateInfo, pAllocator, pPipeline);
1097 case 8:
1098 return gen8_compute_pipeline_create(_device, pCreateInfo, pAllocator, pPipeline);
1099 case 9:
1100 return gen9_compute_pipeline_create(_device, pCreateInfo, pAllocator, pPipeline);
1101 default:
1102 unreachable("unsupported gen\n");
1103 }
1104 }
1105
1106 VkResult anv_CreateComputePipelines(
1107 VkDevice _device,
1108 VkPipelineCache pipelineCache,
1109 uint32_t count,
1110 const VkComputePipelineCreateInfo* pCreateInfos,
1111 const VkAllocationCallbacks* pAllocator,
1112 VkPipeline* pPipelines)
1113 {
1114 VkResult result = VK_SUCCESS;
1115
1116 unsigned i = 0;
1117 for (; i < count; i++) {
1118 result = anv_compute_pipeline_create(_device, &pCreateInfos[i],
1119 pAllocator, &pPipelines[i]);
1120 if (result != VK_SUCCESS) {
1121 for (unsigned j = 0; j < i; j++) {
1122 anv_DestroyPipeline(_device, pPipelines[j], pAllocator);
1123 }
1124
1125 return result;
1126 }
1127 }
1128
1129 return VK_SUCCESS;
1130 }