0a91e1d009c0cdd79540681d6cd51e4fe5ae0423
[mesa.git] / src / intel / vulkan / genX_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 "anv_private.h"
25
26 #include "genxml/gen_macros.h"
27 #include "genxml/genX_pack.h"
28
29 #include "common/gen_l3_config.h"
30 #include "common/gen_sample_positions.h"
31 #include "nir/nir_xfb_info.h"
32 #include "vk_util.h"
33 #include "vk_format_info.h"
34
35 static uint32_t
36 vertex_element_comp_control(enum isl_format format, unsigned comp)
37 {
38 uint8_t bits;
39 switch (comp) {
40 case 0: bits = isl_format_layouts[format].channels.r.bits; break;
41 case 1: bits = isl_format_layouts[format].channels.g.bits; break;
42 case 2: bits = isl_format_layouts[format].channels.b.bits; break;
43 case 3: bits = isl_format_layouts[format].channels.a.bits; break;
44 default: unreachable("Invalid component");
45 }
46
47 /*
48 * Take in account hardware restrictions when dealing with 64-bit floats.
49 *
50 * From Broadwell spec, command reference structures, page 586:
51 * "When SourceElementFormat is set to one of the *64*_PASSTHRU formats,
52 * 64-bit components are stored * in the URB without any conversion. In
53 * this case, vertex elements must be written as 128 or 256 bits, with
54 * VFCOMP_STORE_0 being used to pad the output as required. E.g., if
55 * R64_PASSTHRU is used to copy a 64-bit Red component into the URB,
56 * Component 1 must be specified as VFCOMP_STORE_0 (with Components 2,3
57 * set to VFCOMP_NOSTORE) in order to output a 128-bit vertex element, or
58 * Components 1-3 must be specified as VFCOMP_STORE_0 in order to output
59 * a 256-bit vertex element. Likewise, use of R64G64B64_PASSTHRU requires
60 * Component 3 to be specified as VFCOMP_STORE_0 in order to output a
61 * 256-bit vertex element."
62 */
63 if (bits) {
64 return VFCOMP_STORE_SRC;
65 } else if (comp >= 2 &&
66 !isl_format_layouts[format].channels.b.bits &&
67 isl_format_layouts[format].channels.r.type == ISL_RAW) {
68 /* When emitting 64-bit attributes, we need to write either 128 or 256
69 * bit chunks, using VFCOMP_NOSTORE when not writing the chunk, and
70 * VFCOMP_STORE_0 to pad the written chunk */
71 return VFCOMP_NOSTORE;
72 } else if (comp < 3 ||
73 isl_format_layouts[format].channels.r.type == ISL_RAW) {
74 /* Note we need to pad with value 0, not 1, due hardware restrictions
75 * (see comment above) */
76 return VFCOMP_STORE_0;
77 } else if (isl_format_layouts[format].channels.r.type == ISL_UINT ||
78 isl_format_layouts[format].channels.r.type == ISL_SINT) {
79 assert(comp == 3);
80 return VFCOMP_STORE_1_INT;
81 } else {
82 assert(comp == 3);
83 return VFCOMP_STORE_1_FP;
84 }
85 }
86
87 static void
88 emit_vertex_input(struct anv_pipeline *pipeline,
89 const VkPipelineVertexInputStateCreateInfo *info)
90 {
91 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
92
93 /* Pull inputs_read out of the VS prog data */
94 const uint64_t inputs_read = vs_prog_data->inputs_read;
95 const uint64_t double_inputs_read =
96 vs_prog_data->double_inputs_read & inputs_read;
97 assert((inputs_read & ((1 << VERT_ATTRIB_GENERIC0) - 1)) == 0);
98 const uint32_t elements = inputs_read >> VERT_ATTRIB_GENERIC0;
99 const uint32_t elements_double = double_inputs_read >> VERT_ATTRIB_GENERIC0;
100 const bool needs_svgs_elem = vs_prog_data->uses_vertexid ||
101 vs_prog_data->uses_instanceid ||
102 vs_prog_data->uses_firstvertex ||
103 vs_prog_data->uses_baseinstance;
104
105 uint32_t elem_count = __builtin_popcount(elements) -
106 __builtin_popcount(elements_double) / 2;
107
108 const uint32_t total_elems =
109 MAX2(1, elem_count + needs_svgs_elem + vs_prog_data->uses_drawid);
110
111 uint32_t *p;
112
113 const uint32_t num_dwords = 1 + total_elems * 2;
114 p = anv_batch_emitn(&pipeline->batch, num_dwords,
115 GENX(3DSTATE_VERTEX_ELEMENTS));
116 if (!p)
117 return;
118
119 for (uint32_t i = 0; i < total_elems; i++) {
120 /* The SKL docs for VERTEX_ELEMENT_STATE say:
121 *
122 * "All elements must be valid from Element[0] to the last valid
123 * element. (I.e. if Element[2] is valid then Element[1] and
124 * Element[0] must also be valid)."
125 *
126 * The SKL docs for 3D_Vertex_Component_Control say:
127 *
128 * "Don't store this component. (Not valid for Component 0, but can
129 * be used for Component 1-3)."
130 *
131 * So we can't just leave a vertex element blank and hope for the best.
132 * We have to tell the VF hardware to put something in it; so we just
133 * store a bunch of zero.
134 *
135 * TODO: Compact vertex elements so we never end up with holes.
136 */
137 struct GENX(VERTEX_ELEMENT_STATE) element = {
138 .Valid = true,
139 .Component0Control = VFCOMP_STORE_0,
140 .Component1Control = VFCOMP_STORE_0,
141 .Component2Control = VFCOMP_STORE_0,
142 .Component3Control = VFCOMP_STORE_0,
143 };
144 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + i * 2], &element);
145 }
146
147 for (uint32_t i = 0; i < info->vertexAttributeDescriptionCount; i++) {
148 const VkVertexInputAttributeDescription *desc =
149 &info->pVertexAttributeDescriptions[i];
150 enum isl_format format = anv_get_isl_format(&pipeline->device->info,
151 desc->format,
152 VK_IMAGE_ASPECT_COLOR_BIT,
153 VK_IMAGE_TILING_LINEAR);
154
155 assert(desc->binding < MAX_VBS);
156
157 if ((elements & (1 << desc->location)) == 0)
158 continue; /* Binding unused */
159
160 uint32_t slot =
161 __builtin_popcount(elements & ((1 << desc->location) - 1)) -
162 DIV_ROUND_UP(__builtin_popcount(elements_double &
163 ((1 << desc->location) -1)), 2);
164
165 struct GENX(VERTEX_ELEMENT_STATE) element = {
166 .VertexBufferIndex = desc->binding,
167 .Valid = true,
168 .SourceElementFormat = format,
169 .EdgeFlagEnable = false,
170 .SourceElementOffset = desc->offset,
171 .Component0Control = vertex_element_comp_control(format, 0),
172 .Component1Control = vertex_element_comp_control(format, 1),
173 .Component2Control = vertex_element_comp_control(format, 2),
174 .Component3Control = vertex_element_comp_control(format, 3),
175 };
176 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + slot * 2], &element);
177
178 #if GEN_GEN >= 8
179 /* On Broadwell and later, we have a separate VF_INSTANCING packet
180 * that controls instancing. On Haswell and prior, that's part of
181 * VERTEX_BUFFER_STATE which we emit later.
182 */
183 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_INSTANCING), vfi) {
184 vfi.InstancingEnable = pipeline->vb[desc->binding].instanced;
185 vfi.VertexElementIndex = slot;
186 vfi.InstanceDataStepRate =
187 pipeline->vb[desc->binding].instance_divisor;
188 }
189 #endif
190 }
191
192 const uint32_t id_slot = elem_count;
193 if (needs_svgs_elem) {
194 /* From the Broadwell PRM for the 3D_Vertex_Component_Control enum:
195 * "Within a VERTEX_ELEMENT_STATE structure, if a Component
196 * Control field is set to something other than VFCOMP_STORE_SRC,
197 * no higher-numbered Component Control fields may be set to
198 * VFCOMP_STORE_SRC"
199 *
200 * This means, that if we have BaseInstance, we need BaseVertex as
201 * well. Just do all or nothing.
202 */
203 uint32_t base_ctrl = (vs_prog_data->uses_firstvertex ||
204 vs_prog_data->uses_baseinstance) ?
205 VFCOMP_STORE_SRC : VFCOMP_STORE_0;
206
207 struct GENX(VERTEX_ELEMENT_STATE) element = {
208 .VertexBufferIndex = ANV_SVGS_VB_INDEX,
209 .Valid = true,
210 .SourceElementFormat = ISL_FORMAT_R32G32_UINT,
211 .Component0Control = base_ctrl,
212 .Component1Control = base_ctrl,
213 #if GEN_GEN >= 8
214 .Component2Control = VFCOMP_STORE_0,
215 .Component3Control = VFCOMP_STORE_0,
216 #else
217 .Component2Control = VFCOMP_STORE_VID,
218 .Component3Control = VFCOMP_STORE_IID,
219 #endif
220 };
221 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + id_slot * 2], &element);
222 }
223
224 #if GEN_GEN >= 8
225 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_SGVS), sgvs) {
226 sgvs.VertexIDEnable = vs_prog_data->uses_vertexid;
227 sgvs.VertexIDComponentNumber = 2;
228 sgvs.VertexIDElementOffset = id_slot;
229 sgvs.InstanceIDEnable = vs_prog_data->uses_instanceid;
230 sgvs.InstanceIDComponentNumber = 3;
231 sgvs.InstanceIDElementOffset = id_slot;
232 }
233 #endif
234
235 const uint32_t drawid_slot = elem_count + needs_svgs_elem;
236 if (vs_prog_data->uses_drawid) {
237 struct GENX(VERTEX_ELEMENT_STATE) element = {
238 .VertexBufferIndex = ANV_DRAWID_VB_INDEX,
239 .Valid = true,
240 .SourceElementFormat = ISL_FORMAT_R32_UINT,
241 .Component0Control = VFCOMP_STORE_SRC,
242 .Component1Control = VFCOMP_STORE_0,
243 .Component2Control = VFCOMP_STORE_0,
244 .Component3Control = VFCOMP_STORE_0,
245 };
246 GENX(VERTEX_ELEMENT_STATE_pack)(NULL,
247 &p[1 + drawid_slot * 2],
248 &element);
249
250 #if GEN_GEN >= 8
251 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_INSTANCING), vfi) {
252 vfi.VertexElementIndex = drawid_slot;
253 }
254 #endif
255 }
256 }
257
258 void
259 genX(emit_urb_setup)(struct anv_device *device, struct anv_batch *batch,
260 const struct gen_l3_config *l3_config,
261 VkShaderStageFlags active_stages,
262 const unsigned entry_size[4])
263 {
264 const struct gen_device_info *devinfo = &device->info;
265 #if GEN_IS_HASWELL
266 const unsigned push_constant_kb = devinfo->gt == 3 ? 32 : 16;
267 #else
268 const unsigned push_constant_kb = GEN_GEN >= 8 ? 32 : 16;
269 #endif
270
271 const unsigned urb_size_kb = gen_get_l3_config_urb_size(devinfo, l3_config);
272
273 unsigned entries[4];
274 unsigned start[4];
275 gen_get_urb_config(devinfo,
276 1024 * push_constant_kb, 1024 * urb_size_kb,
277 active_stages &
278 VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
279 active_stages & VK_SHADER_STAGE_GEOMETRY_BIT,
280 entry_size, entries, start);
281
282 #if GEN_GEN == 7 && !GEN_IS_HASWELL
283 /* From the IVB PRM Vol. 2, Part 1, Section 3.2.1:
284 *
285 * "A PIPE_CONTROL with Post-Sync Operation set to 1h and a depth stall
286 * needs to be sent just prior to any 3DSTATE_VS, 3DSTATE_URB_VS,
287 * 3DSTATE_CONSTANT_VS, 3DSTATE_BINDING_TABLE_POINTER_VS,
288 * 3DSTATE_SAMPLER_STATE_POINTER_VS command. Only one PIPE_CONTROL
289 * needs to be sent before any combination of VS associated 3DSTATE."
290 */
291 anv_batch_emit(batch, GEN7_PIPE_CONTROL, pc) {
292 pc.DepthStallEnable = true;
293 pc.PostSyncOperation = WriteImmediateData;
294 pc.Address = (struct anv_address) { device->workaround_bo, 0 };
295 }
296 #endif
297
298 for (int i = 0; i <= MESA_SHADER_GEOMETRY; i++) {
299 anv_batch_emit(batch, GENX(3DSTATE_URB_VS), urb) {
300 urb._3DCommandSubOpcode += i;
301 urb.VSURBStartingAddress = start[i];
302 urb.VSURBEntryAllocationSize = entry_size[i] - 1;
303 urb.VSNumberofURBEntries = entries[i];
304 }
305 }
306 }
307
308 static void
309 emit_urb_setup(struct anv_pipeline *pipeline)
310 {
311 unsigned entry_size[4];
312 for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
313 const struct brw_vue_prog_data *prog_data =
314 !anv_pipeline_has_stage(pipeline, i) ? NULL :
315 (const struct brw_vue_prog_data *) pipeline->shaders[i]->prog_data;
316
317 entry_size[i] = prog_data ? prog_data->urb_entry_size : 1;
318 }
319
320 genX(emit_urb_setup)(pipeline->device, &pipeline->batch,
321 pipeline->urb.l3_config,
322 pipeline->active_stages, entry_size);
323 }
324
325 static void
326 emit_3dstate_sbe(struct anv_pipeline *pipeline)
327 {
328 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
329
330 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
331 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_SBE), sbe);
332 #if GEN_GEN >= 8
333 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_SBE_SWIZ), sbe);
334 #endif
335 return;
336 }
337
338 const struct brw_vue_map *fs_input_map =
339 &anv_pipeline_get_last_vue_prog_data(pipeline)->vue_map;
340
341 struct GENX(3DSTATE_SBE) sbe = {
342 GENX(3DSTATE_SBE_header),
343 .AttributeSwizzleEnable = true,
344 .PointSpriteTextureCoordinateOrigin = UPPERLEFT,
345 .NumberofSFOutputAttributes = wm_prog_data->num_varying_inputs,
346 .ConstantInterpolationEnable = wm_prog_data->flat_inputs,
347 };
348
349 #if GEN_GEN >= 9
350 for (unsigned i = 0; i < 32; i++)
351 sbe.AttributeActiveComponentFormat[i] = ACF_XYZW;
352 #endif
353
354 #if GEN_GEN >= 8
355 /* On Broadwell, they broke 3DSTATE_SBE into two packets */
356 struct GENX(3DSTATE_SBE_SWIZ) swiz = {
357 GENX(3DSTATE_SBE_SWIZ_header),
358 };
359 #else
360 # define swiz sbe
361 #endif
362
363 /* Skip the VUE header and position slots by default */
364 unsigned urb_entry_read_offset = 1;
365 int max_source_attr = 0;
366 for (int attr = 0; attr < VARYING_SLOT_MAX; attr++) {
367 int input_index = wm_prog_data->urb_setup[attr];
368
369 if (input_index < 0)
370 continue;
371
372 /* gl_Viewport and gl_Layer are stored in the VUE header */
373 if (attr == VARYING_SLOT_VIEWPORT || attr == VARYING_SLOT_LAYER) {
374 urb_entry_read_offset = 0;
375 continue;
376 }
377
378 if (attr == VARYING_SLOT_PNTC) {
379 sbe.PointSpriteTextureCoordinateEnable = 1 << input_index;
380 continue;
381 }
382
383 const int slot = fs_input_map->varying_to_slot[attr];
384
385 if (input_index >= 16)
386 continue;
387
388 if (slot == -1) {
389 /* This attribute does not exist in the VUE--that means that the
390 * vertex shader did not write to it. It could be that it's a
391 * regular varying read by the fragment shader but not written by
392 * the vertex shader or it's gl_PrimitiveID. In the first case the
393 * value is undefined, in the second it needs to be
394 * gl_PrimitiveID.
395 */
396 swiz.Attribute[input_index].ConstantSource = PRIM_ID;
397 swiz.Attribute[input_index].ComponentOverrideX = true;
398 swiz.Attribute[input_index].ComponentOverrideY = true;
399 swiz.Attribute[input_index].ComponentOverrideZ = true;
400 swiz.Attribute[input_index].ComponentOverrideW = true;
401 } else {
402 /* We have to subtract two slots to accout for the URB entry output
403 * read offset in the VS and GS stages.
404 */
405 const int source_attr = slot - 2 * urb_entry_read_offset;
406 assert(source_attr >= 0 && source_attr < 32);
407 max_source_attr = MAX2(max_source_attr, source_attr);
408 swiz.Attribute[input_index].SourceAttribute = source_attr;
409 }
410 }
411
412 sbe.VertexURBEntryReadOffset = urb_entry_read_offset;
413 sbe.VertexURBEntryReadLength = DIV_ROUND_UP(max_source_attr + 1, 2);
414 #if GEN_GEN >= 8
415 sbe.ForceVertexURBEntryReadOffset = true;
416 sbe.ForceVertexURBEntryReadLength = true;
417 #endif
418
419 uint32_t *dw = anv_batch_emit_dwords(&pipeline->batch,
420 GENX(3DSTATE_SBE_length));
421 if (!dw)
422 return;
423 GENX(3DSTATE_SBE_pack)(&pipeline->batch, dw, &sbe);
424
425 #if GEN_GEN >= 8
426 dw = anv_batch_emit_dwords(&pipeline->batch, GENX(3DSTATE_SBE_SWIZ_length));
427 if (!dw)
428 return;
429 GENX(3DSTATE_SBE_SWIZ_pack)(&pipeline->batch, dw, &swiz);
430 #endif
431 }
432
433 static const uint32_t vk_to_gen_cullmode[] = {
434 [VK_CULL_MODE_NONE] = CULLMODE_NONE,
435 [VK_CULL_MODE_FRONT_BIT] = CULLMODE_FRONT,
436 [VK_CULL_MODE_BACK_BIT] = CULLMODE_BACK,
437 [VK_CULL_MODE_FRONT_AND_BACK] = CULLMODE_BOTH
438 };
439
440 static const uint32_t vk_to_gen_fillmode[] = {
441 [VK_POLYGON_MODE_FILL] = FILL_MODE_SOLID,
442 [VK_POLYGON_MODE_LINE] = FILL_MODE_WIREFRAME,
443 [VK_POLYGON_MODE_POINT] = FILL_MODE_POINT,
444 };
445
446 static const uint32_t vk_to_gen_front_face[] = {
447 [VK_FRONT_FACE_COUNTER_CLOCKWISE] = 1,
448 [VK_FRONT_FACE_CLOCKWISE] = 0
449 };
450
451 static VkLineRasterizationModeEXT
452 vk_line_rasterization_mode(const VkPipelineRasterizationLineStateCreateInfoEXT *line_info,
453 const VkPipelineMultisampleStateCreateInfo *ms_info)
454 {
455 VkLineRasterizationModeEXT line_mode =
456 line_info ? line_info->lineRasterizationMode :
457 VK_LINE_RASTERIZATION_MODE_DEFAULT_EXT;
458
459 if (line_mode == VK_LINE_RASTERIZATION_MODE_DEFAULT_EXT) {
460 if (ms_info && ms_info->rasterizationSamples > 1) {
461 return VK_LINE_RASTERIZATION_MODE_RECTANGULAR_EXT;
462 } else {
463 return VK_LINE_RASTERIZATION_MODE_BRESENHAM_EXT;
464 }
465 }
466
467 return line_mode;
468 }
469
470 /** Returns the final polygon mode for rasterization
471 *
472 * This function takes into account polygon mode, primitive topology and the
473 * different shader stages which might generate their own type of primitives.
474 */
475 static VkPolygonMode
476 anv_raster_polygon_mode(struct anv_pipeline *pipeline,
477 const VkPipelineInputAssemblyStateCreateInfo *ia_info,
478 const VkPipelineRasterizationStateCreateInfo *rs_info)
479 {
480 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY)) {
481 switch (get_gs_prog_data(pipeline)->output_topology) {
482 case _3DPRIM_POINTLIST:
483 return VK_POLYGON_MODE_POINT;
484
485 case _3DPRIM_LINELIST:
486 case _3DPRIM_LINESTRIP:
487 case _3DPRIM_LINELOOP:
488 return VK_POLYGON_MODE_LINE;
489
490 case _3DPRIM_TRILIST:
491 case _3DPRIM_TRIFAN:
492 case _3DPRIM_TRISTRIP:
493 case _3DPRIM_RECTLIST:
494 case _3DPRIM_QUADLIST:
495 case _3DPRIM_QUADSTRIP:
496 case _3DPRIM_POLYGON:
497 return rs_info->polygonMode;
498 }
499 unreachable("Unsupported GS output topology");
500 } else if (anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL)) {
501 switch (get_tes_prog_data(pipeline)->output_topology) {
502 case BRW_TESS_OUTPUT_TOPOLOGY_POINT:
503 return VK_POLYGON_MODE_POINT;
504
505 case BRW_TESS_OUTPUT_TOPOLOGY_LINE:
506 return VK_POLYGON_MODE_LINE;
507
508 case BRW_TESS_OUTPUT_TOPOLOGY_TRI_CW:
509 case BRW_TESS_OUTPUT_TOPOLOGY_TRI_CCW:
510 return rs_info->polygonMode;
511 }
512 unreachable("Unsupported TCS output topology");
513 } else {
514 switch (ia_info->topology) {
515 case VK_PRIMITIVE_TOPOLOGY_POINT_LIST:
516 return VK_POLYGON_MODE_POINT;
517
518 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST:
519 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP:
520 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY:
521 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY:
522 return VK_POLYGON_MODE_LINE;
523
524 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST:
525 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP:
526 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN:
527 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY:
528 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY:
529 return rs_info->polygonMode;
530
531 default:
532 unreachable("Unsupported primitive topology");
533 }
534 }
535 }
536
537 #if GEN_GEN <= 7
538 static uint32_t
539 gen7_ms_rast_mode(struct anv_pipeline *pipeline,
540 const VkPipelineInputAssemblyStateCreateInfo *ia_info,
541 const VkPipelineRasterizationStateCreateInfo *rs_info,
542 const VkPipelineMultisampleStateCreateInfo *ms_info)
543 {
544 const VkPipelineRasterizationLineStateCreateInfoEXT *line_info =
545 vk_find_struct_const(rs_info->pNext,
546 PIPELINE_RASTERIZATION_LINE_STATE_CREATE_INFO_EXT);
547
548 VkPolygonMode raster_mode =
549 anv_raster_polygon_mode(pipeline, ia_info, rs_info);
550 if (raster_mode == VK_POLYGON_MODE_LINE) {
551 switch (vk_line_rasterization_mode(line_info, ms_info)) {
552 case VK_LINE_RASTERIZATION_MODE_RECTANGULAR_EXT:
553 return MSRASTMODE_ON_PATTERN;
554
555 case VK_LINE_RASTERIZATION_MODE_BRESENHAM_EXT:
556 case VK_LINE_RASTERIZATION_MODE_RECTANGULAR_SMOOTH_EXT:
557 return MSRASTMODE_OFF_PIXEL;
558
559 default:
560 unreachable("Unsupported line rasterization mode");
561 }
562 } else {
563 return (ms_info && ms_info->rasterizationSamples > 1) ?
564 MSRASTMODE_ON_PATTERN : MSRASTMODE_OFF_PIXEL;
565 }
566 }
567 #endif
568
569 static void
570 emit_rs_state(struct anv_pipeline *pipeline,
571 const VkPipelineInputAssemblyStateCreateInfo *ia_info,
572 const VkPipelineRasterizationStateCreateInfo *rs_info,
573 const VkPipelineMultisampleStateCreateInfo *ms_info,
574 const VkPipelineRasterizationLineStateCreateInfoEXT *line_info,
575 const struct anv_render_pass *pass,
576 const struct anv_subpass *subpass)
577 {
578 struct GENX(3DSTATE_SF) sf = {
579 GENX(3DSTATE_SF_header),
580 };
581
582 sf.ViewportTransformEnable = true;
583 sf.StatisticsEnable = true;
584 sf.TriangleStripListProvokingVertexSelect = 0;
585 sf.LineStripListProvokingVertexSelect = 0;
586 sf.TriangleFanProvokingVertexSelect = 1;
587 sf.VertexSubPixelPrecisionSelect = _8Bit;
588 sf.AALineDistanceMode = true;
589
590 #if GEN_IS_HASWELL
591 sf.LineStippleEnable = line_info && line_info->stippledLineEnable;
592 #endif
593
594 #if GEN_GEN >= 12
595 sf.DerefBlockSize = PerPolyDerefMode;
596 #endif
597
598 const struct brw_vue_prog_data *last_vue_prog_data =
599 anv_pipeline_get_last_vue_prog_data(pipeline);
600
601 if (last_vue_prog_data->vue_map.slots_valid & VARYING_BIT_PSIZ) {
602 sf.PointWidthSource = Vertex;
603 } else {
604 sf.PointWidthSource = State;
605 sf.PointWidth = 1.0;
606 }
607
608 #if GEN_GEN >= 8
609 struct GENX(3DSTATE_RASTER) raster = {
610 GENX(3DSTATE_RASTER_header),
611 };
612 #else
613 # define raster sf
614 #endif
615
616 VkPolygonMode raster_mode =
617 anv_raster_polygon_mode(pipeline, ia_info, rs_info);
618 VkLineRasterizationModeEXT line_mode =
619 vk_line_rasterization_mode(line_info, ms_info);
620
621 /* For details on 3DSTATE_RASTER multisample state, see the BSpec table
622 * "Multisample Modes State".
623 */
624 #if GEN_GEN >= 8
625 if (raster_mode == VK_POLYGON_MODE_LINE) {
626 /* Unfortunately, configuring our line rasterization hardware on gen8
627 * and later is rather painful. Instead of giving us bits to tell the
628 * hardware what line mode to use like we had on gen7, we now have an
629 * arcane combination of API Mode and MSAA enable bits which do things
630 * in a table which are expected to magically put the hardware into the
631 * right mode for your API. Sadly, Vulkan isn't any of the APIs the
632 * hardware people thought of so nothing works the way you want it to.
633 *
634 * Look at the table titled "Multisample Rasterization Modes" in Vol 7
635 * of the Skylake PRM for more details.
636 */
637 switch (line_mode) {
638 case VK_LINE_RASTERIZATION_MODE_RECTANGULAR_EXT:
639 raster.APIMode = DX100;
640 raster.DXMultisampleRasterizationEnable = true;
641 break;
642
643 case VK_LINE_RASTERIZATION_MODE_BRESENHAM_EXT:
644 case VK_LINE_RASTERIZATION_MODE_RECTANGULAR_SMOOTH_EXT:
645 raster.APIMode = DX9OGL;
646 raster.DXMultisampleRasterizationEnable = false;
647 break;
648
649 default:
650 unreachable("Unsupported line rasterization mode");
651 }
652 } else {
653 raster.APIMode = DX100;
654 raster.DXMultisampleRasterizationEnable = true;
655 }
656
657 /* NOTE: 3DSTATE_RASTER::ForcedSampleCount affects the BDW and SKL PMA fix
658 * computations. If we ever set this bit to a different value, they will
659 * need to be updated accordingly.
660 */
661 raster.ForcedSampleCount = FSC_NUMRASTSAMPLES_0;
662 raster.ForceMultisampling = false;
663 #else
664 raster.MultisampleRasterizationMode =
665 gen7_ms_rast_mode(pipeline, ia_info, rs_info, ms_info);
666 #endif
667
668 if (raster_mode == VK_POLYGON_MODE_LINE &&
669 line_mode == VK_LINE_RASTERIZATION_MODE_RECTANGULAR_SMOOTH_EXT)
670 raster.AntialiasingEnable = true;
671
672 raster.FrontWinding = vk_to_gen_front_face[rs_info->frontFace];
673 raster.CullMode = vk_to_gen_cullmode[rs_info->cullMode];
674 raster.FrontFaceFillMode = vk_to_gen_fillmode[rs_info->polygonMode];
675 raster.BackFaceFillMode = vk_to_gen_fillmode[rs_info->polygonMode];
676 raster.ScissorRectangleEnable = true;
677
678 #if GEN_GEN >= 9
679 /* GEN9+ splits ViewportZClipTestEnable into near and far enable bits */
680 raster.ViewportZFarClipTestEnable = pipeline->depth_clip_enable;
681 raster.ViewportZNearClipTestEnable = pipeline->depth_clip_enable;
682 #elif GEN_GEN >= 8
683 raster.ViewportZClipTestEnable = pipeline->depth_clip_enable;
684 #endif
685
686 raster.GlobalDepthOffsetEnableSolid = rs_info->depthBiasEnable;
687 raster.GlobalDepthOffsetEnableWireframe = rs_info->depthBiasEnable;
688 raster.GlobalDepthOffsetEnablePoint = rs_info->depthBiasEnable;
689
690 #if GEN_GEN == 7
691 /* Gen7 requires that we provide the depth format in 3DSTATE_SF so that it
692 * can get the depth offsets correct.
693 */
694 if (subpass->depth_stencil_attachment) {
695 VkFormat vk_format =
696 pass->attachments[subpass->depth_stencil_attachment->attachment].format;
697 assert(vk_format_is_depth_or_stencil(vk_format));
698 if (vk_format_aspects(vk_format) & VK_IMAGE_ASPECT_DEPTH_BIT) {
699 enum isl_format isl_format =
700 anv_get_isl_format(&pipeline->device->info, vk_format,
701 VK_IMAGE_ASPECT_DEPTH_BIT,
702 VK_IMAGE_TILING_OPTIMAL);
703 sf.DepthBufferSurfaceFormat =
704 isl_format_get_depth_format(isl_format, false);
705 }
706 }
707 #endif
708
709 #if GEN_GEN >= 8
710 GENX(3DSTATE_SF_pack)(NULL, pipeline->gen8.sf, &sf);
711 GENX(3DSTATE_RASTER_pack)(NULL, pipeline->gen8.raster, &raster);
712 #else
713 # undef raster
714 GENX(3DSTATE_SF_pack)(NULL, &pipeline->gen7.sf, &sf);
715 #endif
716 }
717
718 static void
719 emit_ms_state(struct anv_pipeline *pipeline,
720 const VkPipelineMultisampleStateCreateInfo *info)
721 {
722 uint32_t samples = 1;
723 uint32_t log2_samples = 0;
724
725 /* From the Vulkan 1.0 spec:
726 * If pSampleMask is NULL, it is treated as if the mask has all bits
727 * enabled, i.e. no coverage is removed from fragments.
728 *
729 * 3DSTATE_SAMPLE_MASK.SampleMask is 16 bits.
730 */
731 #if GEN_GEN >= 8
732 uint32_t sample_mask = 0xffff;
733 #else
734 uint32_t sample_mask = 0xff;
735 #endif
736
737 if (info) {
738 samples = info->rasterizationSamples;
739 log2_samples = __builtin_ffs(samples) - 1;
740 }
741
742 if (info && info->pSampleMask)
743 sample_mask &= info->pSampleMask[0];
744
745 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_MULTISAMPLE), ms) {
746 ms.NumberofMultisamples = log2_samples;
747
748 ms.PixelLocation = CENTER;
749 #if GEN_GEN >= 8
750 /* The PRM says that this bit is valid only for DX9:
751 *
752 * SW can choose to set this bit only for DX9 API. DX10/OGL API's
753 * should not have any effect by setting or not setting this bit.
754 */
755 ms.PixelPositionOffsetEnable = false;
756 #else
757
758 switch (samples) {
759 case 1:
760 GEN_SAMPLE_POS_1X(ms.Sample);
761 break;
762 case 2:
763 GEN_SAMPLE_POS_2X(ms.Sample);
764 break;
765 case 4:
766 GEN_SAMPLE_POS_4X(ms.Sample);
767 break;
768 case 8:
769 GEN_SAMPLE_POS_8X(ms.Sample);
770 break;
771 default:
772 break;
773 }
774 #endif
775 }
776
777 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_SAMPLE_MASK), sm) {
778 sm.SampleMask = sample_mask;
779 }
780 }
781
782 static const uint32_t vk_to_gen_logic_op[] = {
783 [VK_LOGIC_OP_COPY] = LOGICOP_COPY,
784 [VK_LOGIC_OP_CLEAR] = LOGICOP_CLEAR,
785 [VK_LOGIC_OP_AND] = LOGICOP_AND,
786 [VK_LOGIC_OP_AND_REVERSE] = LOGICOP_AND_REVERSE,
787 [VK_LOGIC_OP_AND_INVERTED] = LOGICOP_AND_INVERTED,
788 [VK_LOGIC_OP_NO_OP] = LOGICOP_NOOP,
789 [VK_LOGIC_OP_XOR] = LOGICOP_XOR,
790 [VK_LOGIC_OP_OR] = LOGICOP_OR,
791 [VK_LOGIC_OP_NOR] = LOGICOP_NOR,
792 [VK_LOGIC_OP_EQUIVALENT] = LOGICOP_EQUIV,
793 [VK_LOGIC_OP_INVERT] = LOGICOP_INVERT,
794 [VK_LOGIC_OP_OR_REVERSE] = LOGICOP_OR_REVERSE,
795 [VK_LOGIC_OP_COPY_INVERTED] = LOGICOP_COPY_INVERTED,
796 [VK_LOGIC_OP_OR_INVERTED] = LOGICOP_OR_INVERTED,
797 [VK_LOGIC_OP_NAND] = LOGICOP_NAND,
798 [VK_LOGIC_OP_SET] = LOGICOP_SET,
799 };
800
801 static const uint32_t vk_to_gen_blend[] = {
802 [VK_BLEND_FACTOR_ZERO] = BLENDFACTOR_ZERO,
803 [VK_BLEND_FACTOR_ONE] = BLENDFACTOR_ONE,
804 [VK_BLEND_FACTOR_SRC_COLOR] = BLENDFACTOR_SRC_COLOR,
805 [VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR] = BLENDFACTOR_INV_SRC_COLOR,
806 [VK_BLEND_FACTOR_DST_COLOR] = BLENDFACTOR_DST_COLOR,
807 [VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR] = BLENDFACTOR_INV_DST_COLOR,
808 [VK_BLEND_FACTOR_SRC_ALPHA] = BLENDFACTOR_SRC_ALPHA,
809 [VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA] = BLENDFACTOR_INV_SRC_ALPHA,
810 [VK_BLEND_FACTOR_DST_ALPHA] = BLENDFACTOR_DST_ALPHA,
811 [VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA] = BLENDFACTOR_INV_DST_ALPHA,
812 [VK_BLEND_FACTOR_CONSTANT_COLOR] = BLENDFACTOR_CONST_COLOR,
813 [VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR]= BLENDFACTOR_INV_CONST_COLOR,
814 [VK_BLEND_FACTOR_CONSTANT_ALPHA] = BLENDFACTOR_CONST_ALPHA,
815 [VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA]= BLENDFACTOR_INV_CONST_ALPHA,
816 [VK_BLEND_FACTOR_SRC_ALPHA_SATURATE] = BLENDFACTOR_SRC_ALPHA_SATURATE,
817 [VK_BLEND_FACTOR_SRC1_COLOR] = BLENDFACTOR_SRC1_COLOR,
818 [VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR] = BLENDFACTOR_INV_SRC1_COLOR,
819 [VK_BLEND_FACTOR_SRC1_ALPHA] = BLENDFACTOR_SRC1_ALPHA,
820 [VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA] = BLENDFACTOR_INV_SRC1_ALPHA,
821 };
822
823 static const uint32_t vk_to_gen_blend_op[] = {
824 [VK_BLEND_OP_ADD] = BLENDFUNCTION_ADD,
825 [VK_BLEND_OP_SUBTRACT] = BLENDFUNCTION_SUBTRACT,
826 [VK_BLEND_OP_REVERSE_SUBTRACT] = BLENDFUNCTION_REVERSE_SUBTRACT,
827 [VK_BLEND_OP_MIN] = BLENDFUNCTION_MIN,
828 [VK_BLEND_OP_MAX] = BLENDFUNCTION_MAX,
829 };
830
831 static const uint32_t vk_to_gen_compare_op[] = {
832 [VK_COMPARE_OP_NEVER] = PREFILTEROPNEVER,
833 [VK_COMPARE_OP_LESS] = PREFILTEROPLESS,
834 [VK_COMPARE_OP_EQUAL] = PREFILTEROPEQUAL,
835 [VK_COMPARE_OP_LESS_OR_EQUAL] = PREFILTEROPLEQUAL,
836 [VK_COMPARE_OP_GREATER] = PREFILTEROPGREATER,
837 [VK_COMPARE_OP_NOT_EQUAL] = PREFILTEROPNOTEQUAL,
838 [VK_COMPARE_OP_GREATER_OR_EQUAL] = PREFILTEROPGEQUAL,
839 [VK_COMPARE_OP_ALWAYS] = PREFILTEROPALWAYS,
840 };
841
842 static const uint32_t vk_to_gen_stencil_op[] = {
843 [VK_STENCIL_OP_KEEP] = STENCILOP_KEEP,
844 [VK_STENCIL_OP_ZERO] = STENCILOP_ZERO,
845 [VK_STENCIL_OP_REPLACE] = STENCILOP_REPLACE,
846 [VK_STENCIL_OP_INCREMENT_AND_CLAMP] = STENCILOP_INCRSAT,
847 [VK_STENCIL_OP_DECREMENT_AND_CLAMP] = STENCILOP_DECRSAT,
848 [VK_STENCIL_OP_INVERT] = STENCILOP_INVERT,
849 [VK_STENCIL_OP_INCREMENT_AND_WRAP] = STENCILOP_INCR,
850 [VK_STENCIL_OP_DECREMENT_AND_WRAP] = STENCILOP_DECR,
851 };
852
853 /* This function sanitizes the VkStencilOpState by looking at the compare ops
854 * and trying to determine whether or not a given stencil op can ever actually
855 * occur. Stencil ops which can never occur are set to VK_STENCIL_OP_KEEP.
856 * This function returns true if, after sanitation, any of the stencil ops are
857 * set to something other than VK_STENCIL_OP_KEEP.
858 */
859 static bool
860 sanitize_stencil_face(VkStencilOpState *face,
861 VkCompareOp depthCompareOp)
862 {
863 /* If compareOp is ALWAYS then the stencil test will never fail and failOp
864 * will never happen. Set failOp to KEEP in this case.
865 */
866 if (face->compareOp == VK_COMPARE_OP_ALWAYS)
867 face->failOp = VK_STENCIL_OP_KEEP;
868
869 /* If compareOp is NEVER or depthCompareOp is NEVER then one of the depth
870 * or stencil tests will fail and passOp will never happen.
871 */
872 if (face->compareOp == VK_COMPARE_OP_NEVER ||
873 depthCompareOp == VK_COMPARE_OP_NEVER)
874 face->passOp = VK_STENCIL_OP_KEEP;
875
876 /* If compareOp is NEVER or depthCompareOp is ALWAYS then either the
877 * stencil test will fail or the depth test will pass. In either case,
878 * depthFailOp will never happen.
879 */
880 if (face->compareOp == VK_COMPARE_OP_NEVER ||
881 depthCompareOp == VK_COMPARE_OP_ALWAYS)
882 face->depthFailOp = VK_STENCIL_OP_KEEP;
883
884 return face->failOp != VK_STENCIL_OP_KEEP ||
885 face->depthFailOp != VK_STENCIL_OP_KEEP ||
886 face->passOp != VK_STENCIL_OP_KEEP;
887 }
888
889 /* Intel hardware is fairly sensitive to whether or not depth/stencil writes
890 * are enabled. In the presence of discards, it's fairly easy to get into the
891 * non-promoted case which means a fairly big performance hit. From the Iron
892 * Lake PRM, Vol 2, pt. 1, section 8.4.3.2, "Early Depth Test Cases":
893 *
894 * "Non-promoted depth (N) is active whenever the depth test can be done
895 * early but it cannot determine whether or not to write source depth to
896 * the depth buffer, therefore the depth write must be performed post pixel
897 * shader. This includes cases where the pixel shader can kill pixels,
898 * including via sampler chroma key, as well as cases where the alpha test
899 * function is enabled, which kills pixels based on a programmable alpha
900 * test. In this case, even if the depth test fails, the pixel cannot be
901 * killed if a stencil write is indicated. Whether or not the stencil write
902 * happens depends on whether or not the pixel is killed later. In these
903 * cases if stencil test fails and stencil writes are off, the pixels can
904 * also be killed early. If stencil writes are enabled, the pixels must be
905 * treated as Computed depth (described above)."
906 *
907 * The same thing as mentioned in the stencil case can happen in the depth
908 * case as well if it thinks it writes depth but, thanks to the depth test
909 * being GL_EQUAL, the write doesn't actually matter. A little extra work
910 * up-front to try and disable depth and stencil writes can make a big
911 * difference.
912 *
913 * Unfortunately, the way depth and stencil testing is specified, there are
914 * many case where, regardless of depth/stencil writes being enabled, nothing
915 * actually gets written due to some other bit of state being set. This
916 * function attempts to "sanitize" the depth stencil state and disable writes
917 * and sometimes even testing whenever possible.
918 */
919 static void
920 sanitize_ds_state(VkPipelineDepthStencilStateCreateInfo *state,
921 bool *stencilWriteEnable,
922 VkImageAspectFlags ds_aspects)
923 {
924 *stencilWriteEnable = state->stencilTestEnable;
925
926 /* If the depth test is disabled, we won't be writing anything. Make sure we
927 * treat the test as always passing later on as well.
928 *
929 * Also, the Vulkan spec requires that if either depth or stencil is not
930 * present, the pipeline is to act as if the test silently passes. In that
931 * case we won't write either.
932 */
933 if (!state->depthTestEnable || !(ds_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
934 state->depthWriteEnable = false;
935 state->depthCompareOp = VK_COMPARE_OP_ALWAYS;
936 }
937
938 if (!(ds_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) {
939 *stencilWriteEnable = false;
940 state->front.compareOp = VK_COMPARE_OP_ALWAYS;
941 state->back.compareOp = VK_COMPARE_OP_ALWAYS;
942 }
943
944 /* If the stencil test is enabled and always fails, then we will never get
945 * to the depth test so we can just disable the depth test entirely.
946 */
947 if (state->stencilTestEnable &&
948 state->front.compareOp == VK_COMPARE_OP_NEVER &&
949 state->back.compareOp == VK_COMPARE_OP_NEVER) {
950 state->depthTestEnable = false;
951 state->depthWriteEnable = false;
952 }
953
954 /* If depthCompareOp is EQUAL then the value we would be writing to the
955 * depth buffer is the same as the value that's already there so there's no
956 * point in writing it.
957 */
958 if (state->depthCompareOp == VK_COMPARE_OP_EQUAL)
959 state->depthWriteEnable = false;
960
961 /* If the stencil ops are such that we don't actually ever modify the
962 * stencil buffer, we should disable writes.
963 */
964 if (!sanitize_stencil_face(&state->front, state->depthCompareOp) &&
965 !sanitize_stencil_face(&state->back, state->depthCompareOp))
966 *stencilWriteEnable = false;
967
968 /* If the depth test always passes and we never write out depth, that's the
969 * same as if the depth test is disabled entirely.
970 */
971 if (state->depthCompareOp == VK_COMPARE_OP_ALWAYS &&
972 !state->depthWriteEnable)
973 state->depthTestEnable = false;
974
975 /* If the stencil test always passes and we never write out stencil, that's
976 * the same as if the stencil test is disabled entirely.
977 */
978 if (state->front.compareOp == VK_COMPARE_OP_ALWAYS &&
979 state->back.compareOp == VK_COMPARE_OP_ALWAYS &&
980 !*stencilWriteEnable)
981 state->stencilTestEnable = false;
982 }
983
984 static void
985 emit_ds_state(struct anv_pipeline *pipeline,
986 const VkPipelineDepthStencilStateCreateInfo *pCreateInfo,
987 const struct anv_render_pass *pass,
988 const struct anv_subpass *subpass)
989 {
990 #if GEN_GEN == 7
991 # define depth_stencil_dw pipeline->gen7.depth_stencil_state
992 #elif GEN_GEN == 8
993 # define depth_stencil_dw pipeline->gen8.wm_depth_stencil
994 #else
995 # define depth_stencil_dw pipeline->gen9.wm_depth_stencil
996 #endif
997
998 if (pCreateInfo == NULL) {
999 /* We're going to OR this together with the dynamic state. We need
1000 * to make sure it's initialized to something useful.
1001 */
1002 pipeline->writes_stencil = false;
1003 pipeline->stencil_test_enable = false;
1004 pipeline->writes_depth = false;
1005 pipeline->depth_test_enable = false;
1006 pipeline->depth_bounds_test_enable = false;
1007 memset(depth_stencil_dw, 0, sizeof(depth_stencil_dw));
1008 return;
1009 }
1010
1011 VkImageAspectFlags ds_aspects = 0;
1012 if (subpass->depth_stencil_attachment) {
1013 VkFormat depth_stencil_format =
1014 pass->attachments[subpass->depth_stencil_attachment->attachment].format;
1015 ds_aspects = vk_format_aspects(depth_stencil_format);
1016 }
1017
1018 VkPipelineDepthStencilStateCreateInfo info = *pCreateInfo;
1019 sanitize_ds_state(&info, &pipeline->writes_stencil, ds_aspects);
1020 pipeline->stencil_test_enable = info.stencilTestEnable;
1021 pipeline->writes_depth = info.depthWriteEnable;
1022 pipeline->depth_test_enable = info.depthTestEnable;
1023 pipeline->depth_bounds_test_enable = info.depthBoundsTestEnable;
1024
1025 #if GEN_GEN <= 7
1026 struct GENX(DEPTH_STENCIL_STATE) depth_stencil = {
1027 #else
1028 struct GENX(3DSTATE_WM_DEPTH_STENCIL) depth_stencil = {
1029 #endif
1030 .DepthTestEnable = info.depthTestEnable,
1031 .DepthBufferWriteEnable = info.depthWriteEnable,
1032 .DepthTestFunction = vk_to_gen_compare_op[info.depthCompareOp],
1033 .DoubleSidedStencilEnable = true,
1034
1035 .StencilTestEnable = info.stencilTestEnable,
1036 .StencilFailOp = vk_to_gen_stencil_op[info.front.failOp],
1037 .StencilPassDepthPassOp = vk_to_gen_stencil_op[info.front.passOp],
1038 .StencilPassDepthFailOp = vk_to_gen_stencil_op[info.front.depthFailOp],
1039 .StencilTestFunction = vk_to_gen_compare_op[info.front.compareOp],
1040 .BackfaceStencilFailOp = vk_to_gen_stencil_op[info.back.failOp],
1041 .BackfaceStencilPassDepthPassOp = vk_to_gen_stencil_op[info.back.passOp],
1042 .BackfaceStencilPassDepthFailOp =vk_to_gen_stencil_op[info.back.depthFailOp],
1043 .BackfaceStencilTestFunction = vk_to_gen_compare_op[info.back.compareOp],
1044 };
1045
1046 #if GEN_GEN <= 7
1047 GENX(DEPTH_STENCIL_STATE_pack)(NULL, depth_stencil_dw, &depth_stencil);
1048 #else
1049 GENX(3DSTATE_WM_DEPTH_STENCIL_pack)(NULL, depth_stencil_dw, &depth_stencil);
1050 #endif
1051 }
1052
1053 static bool
1054 is_dual_src_blend_factor(VkBlendFactor factor)
1055 {
1056 return factor == VK_BLEND_FACTOR_SRC1_COLOR ||
1057 factor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR ||
1058 factor == VK_BLEND_FACTOR_SRC1_ALPHA ||
1059 factor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA;
1060 }
1061
1062 static void
1063 emit_cb_state(struct anv_pipeline *pipeline,
1064 const VkPipelineColorBlendStateCreateInfo *info,
1065 const VkPipelineMultisampleStateCreateInfo *ms_info)
1066 {
1067 struct anv_device *device = pipeline->device;
1068 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1069
1070 struct GENX(BLEND_STATE) blend_state = {
1071 #if GEN_GEN >= 8
1072 .AlphaToCoverageEnable = ms_info && ms_info->alphaToCoverageEnable,
1073 .AlphaToOneEnable = ms_info && ms_info->alphaToOneEnable,
1074 #endif
1075 };
1076
1077 uint32_t surface_count = 0;
1078 struct anv_pipeline_bind_map *map;
1079 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1080 map = &pipeline->shaders[MESA_SHADER_FRAGMENT]->bind_map;
1081 surface_count = map->surface_count;
1082 }
1083
1084 const uint32_t num_dwords = GENX(BLEND_STATE_length) +
1085 GENX(BLEND_STATE_ENTRY_length) * surface_count;
1086 pipeline->blend_state =
1087 anv_state_pool_alloc(&device->dynamic_state_pool, num_dwords * 4, 64);
1088
1089 bool has_writeable_rt = false;
1090 uint32_t *state_pos = pipeline->blend_state.map;
1091 state_pos += GENX(BLEND_STATE_length);
1092 #if GEN_GEN >= 8
1093 struct GENX(BLEND_STATE_ENTRY) bs0 = { 0 };
1094 #endif
1095 for (unsigned i = 0; i < surface_count; i++) {
1096 struct anv_pipeline_binding *binding = &map->surface_to_descriptor[i];
1097
1098 /* All color attachments are at the beginning of the binding table */
1099 if (binding->set != ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS)
1100 break;
1101
1102 /* We can have at most 8 attachments */
1103 assert(i < 8);
1104
1105 if (info == NULL || binding->index >= info->attachmentCount) {
1106 /* Default everything to disabled */
1107 struct GENX(BLEND_STATE_ENTRY) entry = {
1108 .WriteDisableAlpha = true,
1109 .WriteDisableRed = true,
1110 .WriteDisableGreen = true,
1111 .WriteDisableBlue = true,
1112 };
1113 GENX(BLEND_STATE_ENTRY_pack)(NULL, state_pos, &entry);
1114 state_pos += GENX(BLEND_STATE_ENTRY_length);
1115 continue;
1116 }
1117
1118 const VkPipelineColorBlendAttachmentState *a =
1119 &info->pAttachments[binding->index];
1120
1121 struct GENX(BLEND_STATE_ENTRY) entry = {
1122 #if GEN_GEN < 8
1123 .AlphaToCoverageEnable = ms_info && ms_info->alphaToCoverageEnable,
1124 .AlphaToOneEnable = ms_info && ms_info->alphaToOneEnable,
1125 #endif
1126 .LogicOpEnable = info->logicOpEnable,
1127 .LogicOpFunction = vk_to_gen_logic_op[info->logicOp],
1128 .ColorBufferBlendEnable = a->blendEnable,
1129 .ColorClampRange = COLORCLAMP_RTFORMAT,
1130 .PreBlendColorClampEnable = true,
1131 .PostBlendColorClampEnable = true,
1132 .SourceBlendFactor = vk_to_gen_blend[a->srcColorBlendFactor],
1133 .DestinationBlendFactor = vk_to_gen_blend[a->dstColorBlendFactor],
1134 .ColorBlendFunction = vk_to_gen_blend_op[a->colorBlendOp],
1135 .SourceAlphaBlendFactor = vk_to_gen_blend[a->srcAlphaBlendFactor],
1136 .DestinationAlphaBlendFactor = vk_to_gen_blend[a->dstAlphaBlendFactor],
1137 .AlphaBlendFunction = vk_to_gen_blend_op[a->alphaBlendOp],
1138 .WriteDisableAlpha = !(a->colorWriteMask & VK_COLOR_COMPONENT_A_BIT),
1139 .WriteDisableRed = !(a->colorWriteMask & VK_COLOR_COMPONENT_R_BIT),
1140 .WriteDisableGreen = !(a->colorWriteMask & VK_COLOR_COMPONENT_G_BIT),
1141 .WriteDisableBlue = !(a->colorWriteMask & VK_COLOR_COMPONENT_B_BIT),
1142 };
1143
1144 if (a->srcColorBlendFactor != a->srcAlphaBlendFactor ||
1145 a->dstColorBlendFactor != a->dstAlphaBlendFactor ||
1146 a->colorBlendOp != a->alphaBlendOp) {
1147 #if GEN_GEN >= 8
1148 blend_state.IndependentAlphaBlendEnable = true;
1149 #else
1150 entry.IndependentAlphaBlendEnable = true;
1151 #endif
1152 }
1153
1154 /* The Dual Source Blending documentation says:
1155 *
1156 * "If SRC1 is included in a src/dst blend factor and
1157 * a DualSource RT Write message is not used, results
1158 * are UNDEFINED. (This reflects the same restriction in DX APIs,
1159 * where undefined results are produced if “o1” is not written
1160 * by a PS – there are no default values defined)."
1161 *
1162 * There is no way to gracefully fix this undefined situation
1163 * so we just disable the blending to prevent possible issues.
1164 */
1165 if (!wm_prog_data->dual_src_blend &&
1166 (is_dual_src_blend_factor(a->srcColorBlendFactor) ||
1167 is_dual_src_blend_factor(a->dstColorBlendFactor) ||
1168 is_dual_src_blend_factor(a->srcAlphaBlendFactor) ||
1169 is_dual_src_blend_factor(a->dstAlphaBlendFactor))) {
1170 vk_debug_report(&device->physical->instance->debug_report_callbacks,
1171 VK_DEBUG_REPORT_WARNING_BIT_EXT,
1172 VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
1173 (uint64_t)(uintptr_t)device,
1174 0, 0, "anv",
1175 "Enabled dual-src blend factors without writing both targets "
1176 "in the shader. Disabling blending to avoid GPU hangs.");
1177 entry.ColorBufferBlendEnable = false;
1178 }
1179
1180 if (a->colorWriteMask != 0)
1181 has_writeable_rt = true;
1182
1183 /* Our hardware applies the blend factor prior to the blend function
1184 * regardless of what function is used. Technically, this means the
1185 * hardware can do MORE than GL or Vulkan specify. However, it also
1186 * means that, for MIN and MAX, we have to stomp the blend factor to
1187 * ONE to make it a no-op.
1188 */
1189 if (a->colorBlendOp == VK_BLEND_OP_MIN ||
1190 a->colorBlendOp == VK_BLEND_OP_MAX) {
1191 entry.SourceBlendFactor = BLENDFACTOR_ONE;
1192 entry.DestinationBlendFactor = BLENDFACTOR_ONE;
1193 }
1194 if (a->alphaBlendOp == VK_BLEND_OP_MIN ||
1195 a->alphaBlendOp == VK_BLEND_OP_MAX) {
1196 entry.SourceAlphaBlendFactor = BLENDFACTOR_ONE;
1197 entry.DestinationAlphaBlendFactor = BLENDFACTOR_ONE;
1198 }
1199 GENX(BLEND_STATE_ENTRY_pack)(NULL, state_pos, &entry);
1200 state_pos += GENX(BLEND_STATE_ENTRY_length);
1201 #if GEN_GEN >= 8
1202 if (i == 0)
1203 bs0 = entry;
1204 #endif
1205 }
1206
1207 #if GEN_GEN >= 8
1208 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS_BLEND), blend) {
1209 blend.AlphaToCoverageEnable = blend_state.AlphaToCoverageEnable;
1210 blend.HasWriteableRT = has_writeable_rt;
1211 blend.ColorBufferBlendEnable = bs0.ColorBufferBlendEnable;
1212 blend.SourceAlphaBlendFactor = bs0.SourceAlphaBlendFactor;
1213 blend.DestinationAlphaBlendFactor = bs0.DestinationAlphaBlendFactor;
1214 blend.SourceBlendFactor = bs0.SourceBlendFactor;
1215 blend.DestinationBlendFactor = bs0.DestinationBlendFactor;
1216 blend.AlphaTestEnable = false;
1217 blend.IndependentAlphaBlendEnable =
1218 blend_state.IndependentAlphaBlendEnable;
1219 }
1220 #else
1221 (void)has_writeable_rt;
1222 #endif
1223
1224 GENX(BLEND_STATE_pack)(NULL, pipeline->blend_state.map, &blend_state);
1225
1226 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_BLEND_STATE_POINTERS), bsp) {
1227 bsp.BlendStatePointer = pipeline->blend_state.offset;
1228 #if GEN_GEN >= 8
1229 bsp.BlendStatePointerValid = true;
1230 #endif
1231 }
1232 }
1233
1234 static void
1235 emit_3dstate_clip(struct anv_pipeline *pipeline,
1236 const VkPipelineInputAssemblyStateCreateInfo *ia_info,
1237 const VkPipelineViewportStateCreateInfo *vp_info,
1238 const VkPipelineRasterizationStateCreateInfo *rs_info)
1239 {
1240 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1241 (void) wm_prog_data;
1242 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_CLIP), clip) {
1243 clip.ClipEnable = true;
1244 clip.StatisticsEnable = true;
1245 clip.EarlyCullEnable = true;
1246 clip.APIMode = APIMODE_D3D;
1247 clip.GuardbandClipTestEnable = true;
1248
1249 /* Only enable the XY clip test when the final polygon rasterization
1250 * mode is VK_POLYGON_MODE_FILL. We want to leave it disabled for
1251 * points and lines so we get "pop-free" clipping.
1252 */
1253 VkPolygonMode raster_mode =
1254 anv_raster_polygon_mode(pipeline, ia_info, rs_info);
1255 clip.ViewportXYClipTestEnable = (raster_mode == VK_POLYGON_MODE_FILL);
1256
1257 #if GEN_GEN >= 8
1258 clip.VertexSubPixelPrecisionSelect = _8Bit;
1259 #endif
1260
1261 clip.ClipMode = CLIPMODE_NORMAL;
1262
1263 clip.TriangleStripListProvokingVertexSelect = 0;
1264 clip.LineStripListProvokingVertexSelect = 0;
1265 clip.TriangleFanProvokingVertexSelect = 1;
1266
1267 clip.MinimumPointWidth = 0.125;
1268 clip.MaximumPointWidth = 255.875;
1269
1270 const struct brw_vue_prog_data *last =
1271 anv_pipeline_get_last_vue_prog_data(pipeline);
1272
1273 /* From the Vulkan 1.0.45 spec:
1274 *
1275 * "If the last active vertex processing stage shader entry point's
1276 * interface does not include a variable decorated with
1277 * ViewportIndex, then the first viewport is used."
1278 */
1279 if (vp_info && (last->vue_map.slots_valid & VARYING_BIT_VIEWPORT)) {
1280 clip.MaximumVPIndex = vp_info->viewportCount - 1;
1281 } else {
1282 clip.MaximumVPIndex = 0;
1283 }
1284
1285 /* From the Vulkan 1.0.45 spec:
1286 *
1287 * "If the last active vertex processing stage shader entry point's
1288 * interface does not include a variable decorated with Layer, then
1289 * the first layer is used."
1290 */
1291 clip.ForceZeroRTAIndexEnable =
1292 !(last->vue_map.slots_valid & VARYING_BIT_LAYER);
1293
1294 #if GEN_GEN == 7
1295 clip.FrontWinding = vk_to_gen_front_face[rs_info->frontFace];
1296 clip.CullMode = vk_to_gen_cullmode[rs_info->cullMode];
1297 clip.ViewportZClipTestEnable = pipeline->depth_clip_enable;
1298 clip.UserClipDistanceClipTestEnableBitmask = last->clip_distance_mask;
1299 clip.UserClipDistanceCullTestEnableBitmask = last->cull_distance_mask;
1300 #else
1301 clip.NonPerspectiveBarycentricEnable = wm_prog_data ?
1302 (wm_prog_data->barycentric_interp_modes &
1303 BRW_BARYCENTRIC_NONPERSPECTIVE_BITS) != 0 : 0;
1304 #endif
1305 }
1306 }
1307
1308 static void
1309 emit_3dstate_streamout(struct anv_pipeline *pipeline,
1310 const VkPipelineRasterizationStateCreateInfo *rs_info)
1311 {
1312 #if GEN_GEN >= 8
1313 const struct brw_vue_prog_data *prog_data =
1314 anv_pipeline_get_last_vue_prog_data(pipeline);
1315 const struct brw_vue_map *vue_map = &prog_data->vue_map;
1316 #endif
1317
1318 nir_xfb_info *xfb_info;
1319 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY))
1320 xfb_info = pipeline->shaders[MESA_SHADER_GEOMETRY]->xfb_info;
1321 else if (anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL))
1322 xfb_info = pipeline->shaders[MESA_SHADER_TESS_EVAL]->xfb_info;
1323 else
1324 xfb_info = pipeline->shaders[MESA_SHADER_VERTEX]->xfb_info;
1325
1326 pipeline->xfb_used = xfb_info ? xfb_info->buffers_written : 0;
1327
1328 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_STREAMOUT), so) {
1329 so.RenderingDisable = rs_info->rasterizerDiscardEnable;
1330
1331 #if GEN_GEN >= 8
1332 if (xfb_info) {
1333 so.SOFunctionEnable = true;
1334 so.SOStatisticsEnable = true;
1335
1336 const VkPipelineRasterizationStateStreamCreateInfoEXT *stream_info =
1337 vk_find_struct_const(rs_info, PIPELINE_RASTERIZATION_STATE_STREAM_CREATE_INFO_EXT);
1338 so.RenderStreamSelect = stream_info ?
1339 stream_info->rasterizationStream : 0;
1340
1341 so.Buffer0SurfacePitch = xfb_info->buffers[0].stride;
1342 so.Buffer1SurfacePitch = xfb_info->buffers[1].stride;
1343 so.Buffer2SurfacePitch = xfb_info->buffers[2].stride;
1344 so.Buffer3SurfacePitch = xfb_info->buffers[3].stride;
1345
1346 int urb_entry_read_offset = 0;
1347 int urb_entry_read_length =
1348 (prog_data->vue_map.num_slots + 1) / 2 - urb_entry_read_offset;
1349
1350 /* We always read the whole vertex. This could be reduced at some
1351 * point by reading less and offsetting the register index in the
1352 * SO_DECLs.
1353 */
1354 so.Stream0VertexReadOffset = urb_entry_read_offset;
1355 so.Stream0VertexReadLength = urb_entry_read_length - 1;
1356 so.Stream1VertexReadOffset = urb_entry_read_offset;
1357 so.Stream1VertexReadLength = urb_entry_read_length - 1;
1358 so.Stream2VertexReadOffset = urb_entry_read_offset;
1359 so.Stream2VertexReadLength = urb_entry_read_length - 1;
1360 so.Stream3VertexReadOffset = urb_entry_read_offset;
1361 so.Stream3VertexReadLength = urb_entry_read_length - 1;
1362 }
1363 #endif /* GEN_GEN >= 8 */
1364 }
1365
1366 #if GEN_GEN >= 8
1367 if (xfb_info) {
1368 struct GENX(SO_DECL) so_decl[MAX_XFB_STREAMS][128];
1369 int next_offset[MAX_XFB_BUFFERS] = {0, 0, 0, 0};
1370 int decls[MAX_XFB_STREAMS] = {0, 0, 0, 0};
1371
1372 memset(so_decl, 0, sizeof(so_decl));
1373
1374 for (unsigned i = 0; i < xfb_info->output_count; i++) {
1375 const nir_xfb_output_info *output = &xfb_info->outputs[i];
1376 unsigned buffer = output->buffer;
1377 unsigned stream = xfb_info->buffer_to_stream[buffer];
1378
1379 /* Our hardware is unusual in that it requires us to program SO_DECLs
1380 * for fake "hole" components, rather than simply taking the offset
1381 * for each real varying. Each hole can have size 1, 2, 3, or 4; we
1382 * program as many size = 4 holes as we can, then a final hole to
1383 * accommodate the final 1, 2, or 3 remaining.
1384 */
1385 int hole_dwords = (output->offset - next_offset[buffer]) / 4;
1386 while (hole_dwords > 0) {
1387 so_decl[stream][decls[stream]++] = (struct GENX(SO_DECL)) {
1388 .HoleFlag = 1,
1389 .OutputBufferSlot = buffer,
1390 .ComponentMask = (1 << MIN2(hole_dwords, 4)) - 1,
1391 };
1392 hole_dwords -= 4;
1393 }
1394
1395 int varying = output->location;
1396 uint8_t component_mask = output->component_mask;
1397 /* VARYING_SLOT_PSIZ contains three scalar fields packed together:
1398 * - VARYING_SLOT_LAYER in VARYING_SLOT_PSIZ.y
1399 * - VARYING_SLOT_VIEWPORT in VARYING_SLOT_PSIZ.z
1400 * - VARYING_SLOT_PSIZ in VARYING_SLOT_PSIZ.w
1401 */
1402 if (varying == VARYING_SLOT_LAYER) {
1403 varying = VARYING_SLOT_PSIZ;
1404 component_mask = 1 << 1; // SO_DECL_COMPMASK_Y
1405 } else if (varying == VARYING_SLOT_VIEWPORT) {
1406 varying = VARYING_SLOT_PSIZ;
1407 component_mask = 1 << 2; // SO_DECL_COMPMASK_Z
1408 } else if (varying == VARYING_SLOT_PSIZ) {
1409 component_mask = 1 << 3; // SO_DECL_COMPMASK_W
1410 }
1411
1412 next_offset[buffer] = output->offset +
1413 __builtin_popcount(component_mask) * 4;
1414
1415 const int slot = vue_map->varying_to_slot[varying];
1416 if (slot < 0) {
1417 /* This can happen if the shader never writes to the varying.
1418 * Insert a hole instead of actual varying data.
1419 */
1420 so_decl[stream][decls[stream]++] = (struct GENX(SO_DECL)) {
1421 .HoleFlag = true,
1422 .OutputBufferSlot = buffer,
1423 .ComponentMask = component_mask,
1424 };
1425 } else {
1426 so_decl[stream][decls[stream]++] = (struct GENX(SO_DECL)) {
1427 .OutputBufferSlot = buffer,
1428 .RegisterIndex = slot,
1429 .ComponentMask = component_mask,
1430 };
1431 }
1432 }
1433
1434 int max_decls = 0;
1435 for (unsigned s = 0; s < MAX_XFB_STREAMS; s++)
1436 max_decls = MAX2(max_decls, decls[s]);
1437
1438 uint8_t sbs[MAX_XFB_STREAMS] = { };
1439 for (unsigned b = 0; b < MAX_XFB_BUFFERS; b++) {
1440 if (xfb_info->buffers_written & (1 << b))
1441 sbs[xfb_info->buffer_to_stream[b]] |= 1 << b;
1442 }
1443
1444 uint32_t *dw = anv_batch_emitn(&pipeline->batch, 3 + 2 * max_decls,
1445 GENX(3DSTATE_SO_DECL_LIST),
1446 .StreamtoBufferSelects0 = sbs[0],
1447 .StreamtoBufferSelects1 = sbs[1],
1448 .StreamtoBufferSelects2 = sbs[2],
1449 .StreamtoBufferSelects3 = sbs[3],
1450 .NumEntries0 = decls[0],
1451 .NumEntries1 = decls[1],
1452 .NumEntries2 = decls[2],
1453 .NumEntries3 = decls[3]);
1454
1455 for (int i = 0; i < max_decls; i++) {
1456 GENX(SO_DECL_ENTRY_pack)(NULL, dw + 3 + i * 2,
1457 &(struct GENX(SO_DECL_ENTRY)) {
1458 .Stream0Decl = so_decl[0][i],
1459 .Stream1Decl = so_decl[1][i],
1460 .Stream2Decl = so_decl[2][i],
1461 .Stream3Decl = so_decl[3][i],
1462 });
1463 }
1464 }
1465 #endif /* GEN_GEN >= 8 */
1466 }
1467
1468 static uint32_t
1469 get_sampler_count(const struct anv_shader_bin *bin)
1470 {
1471 uint32_t count_by_4 = DIV_ROUND_UP(bin->bind_map.sampler_count, 4);
1472
1473 /* We can potentially have way more than 32 samplers and that's ok.
1474 * However, the 3DSTATE_XS packets only have 3 bits to specify how
1475 * many to pre-fetch and all values above 4 are marked reserved.
1476 */
1477 return MIN2(count_by_4, 4);
1478 }
1479
1480 static uint32_t
1481 get_binding_table_entry_count(const struct anv_shader_bin *bin)
1482 {
1483 return DIV_ROUND_UP(bin->bind_map.surface_count, 32);
1484 }
1485
1486 static struct anv_address
1487 get_scratch_address(struct anv_pipeline *pipeline,
1488 gl_shader_stage stage,
1489 const struct anv_shader_bin *bin)
1490 {
1491 return (struct anv_address) {
1492 .bo = anv_scratch_pool_alloc(pipeline->device,
1493 &pipeline->device->scratch_pool,
1494 stage, bin->prog_data->total_scratch),
1495 .offset = 0,
1496 };
1497 }
1498
1499 static uint32_t
1500 get_scratch_space(const struct anv_shader_bin *bin)
1501 {
1502 return ffs(bin->prog_data->total_scratch / 2048);
1503 }
1504
1505 static void
1506 emit_3dstate_vs(struct anv_pipeline *pipeline)
1507 {
1508 const struct gen_device_info *devinfo = &pipeline->device->info;
1509 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
1510 const struct anv_shader_bin *vs_bin =
1511 pipeline->shaders[MESA_SHADER_VERTEX];
1512
1513 assert(anv_pipeline_has_stage(pipeline, MESA_SHADER_VERTEX));
1514
1515 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VS), vs) {
1516 vs.Enable = true;
1517 vs.StatisticsEnable = true;
1518 vs.KernelStartPointer = vs_bin->kernel.offset;
1519 #if GEN_GEN >= 8
1520 vs.SIMD8DispatchEnable =
1521 vs_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8;
1522 #endif
1523
1524 assert(!vs_prog_data->base.base.use_alt_mode);
1525 #if GEN_GEN < 11
1526 vs.SingleVertexDispatch = false;
1527 #endif
1528 vs.VectorMaskEnable = false;
1529 /* WA_1606682166:
1530 * Incorrect TDL's SSP address shift in SARB for 16:6 & 18:8 modes.
1531 * Disable the Sampler state prefetch functionality in the SARB by
1532 * programming 0xB000[30] to '1'.
1533 */
1534 vs.SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(vs_bin);
1535 vs.BindingTableEntryCount = get_binding_table_entry_count(vs_bin);
1536 vs.FloatingPointMode = IEEE754;
1537 vs.IllegalOpcodeExceptionEnable = false;
1538 vs.SoftwareExceptionEnable = false;
1539 vs.MaximumNumberofThreads = devinfo->max_vs_threads - 1;
1540
1541 if (GEN_GEN == 9 && devinfo->gt == 4 &&
1542 anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL)) {
1543 /* On Sky Lake GT4, we have experienced some hangs related to the VS
1544 * cache and tessellation. It is unknown exactly what is happening
1545 * but the Haswell docs for the "VS Reference Count Full Force Miss
1546 * Enable" field of the "Thread Mode" register refer to a HSW bug in
1547 * which the VUE handle reference count would overflow resulting in
1548 * internal reference counting bugs. My (Jason's) best guess is that
1549 * this bug cropped back up on SKL GT4 when we suddenly had more
1550 * threads in play than any previous gen9 hardware.
1551 *
1552 * What we do know for sure is that setting this bit when
1553 * tessellation shaders are in use fixes a GPU hang in Batman: Arkham
1554 * City when playing with DXVK (https://bugs.freedesktop.org/107280).
1555 * Disabling the vertex cache with tessellation shaders should only
1556 * have a minor performance impact as the tessellation shaders are
1557 * likely generating and processing far more geometry than the vertex
1558 * stage.
1559 */
1560 vs.VertexCacheDisable = true;
1561 }
1562
1563 vs.VertexURBEntryReadLength = vs_prog_data->base.urb_read_length;
1564 vs.VertexURBEntryReadOffset = 0;
1565 vs.DispatchGRFStartRegisterForURBData =
1566 vs_prog_data->base.base.dispatch_grf_start_reg;
1567
1568 #if GEN_GEN >= 8
1569 vs.UserClipDistanceClipTestEnableBitmask =
1570 vs_prog_data->base.clip_distance_mask;
1571 vs.UserClipDistanceCullTestEnableBitmask =
1572 vs_prog_data->base.cull_distance_mask;
1573 #endif
1574
1575 vs.PerThreadScratchSpace = get_scratch_space(vs_bin);
1576 vs.ScratchSpaceBasePointer =
1577 get_scratch_address(pipeline, MESA_SHADER_VERTEX, vs_bin);
1578 }
1579 }
1580
1581 static void
1582 emit_3dstate_hs_te_ds(struct anv_pipeline *pipeline,
1583 const VkPipelineTessellationStateCreateInfo *tess_info)
1584 {
1585 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL)) {
1586 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_HS), hs);
1587 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_TE), te);
1588 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_DS), ds);
1589 return;
1590 }
1591
1592 const struct gen_device_info *devinfo = &pipeline->device->info;
1593 const struct anv_shader_bin *tcs_bin =
1594 pipeline->shaders[MESA_SHADER_TESS_CTRL];
1595 const struct anv_shader_bin *tes_bin =
1596 pipeline->shaders[MESA_SHADER_TESS_EVAL];
1597
1598 const struct brw_tcs_prog_data *tcs_prog_data = get_tcs_prog_data(pipeline);
1599 const struct brw_tes_prog_data *tes_prog_data = get_tes_prog_data(pipeline);
1600
1601 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_HS), hs) {
1602 hs.Enable = true;
1603 hs.StatisticsEnable = true;
1604 hs.KernelStartPointer = tcs_bin->kernel.offset;
1605 /* WA_1606682166 */
1606 hs.SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(tcs_bin);
1607 hs.BindingTableEntryCount = get_binding_table_entry_count(tcs_bin);
1608
1609 #if GEN_GEN >= 12
1610 /* GEN:BUG:1604578095:
1611 *
1612 * Hang occurs when the number of max threads is less than 2 times
1613 * the number of instance count. The number of max threads must be
1614 * more than 2 times the number of instance count.
1615 */
1616 assert((devinfo->max_tcs_threads / 2) > tcs_prog_data->instances);
1617 #endif
1618
1619 hs.MaximumNumberofThreads = devinfo->max_tcs_threads - 1;
1620 hs.IncludeVertexHandles = true;
1621 hs.InstanceCount = tcs_prog_data->instances - 1;
1622
1623 hs.VertexURBEntryReadLength = 0;
1624 hs.VertexURBEntryReadOffset = 0;
1625 hs.DispatchGRFStartRegisterForURBData =
1626 tcs_prog_data->base.base.dispatch_grf_start_reg;
1627
1628 hs.PerThreadScratchSpace = get_scratch_space(tcs_bin);
1629 hs.ScratchSpaceBasePointer =
1630 get_scratch_address(pipeline, MESA_SHADER_TESS_CTRL, tcs_bin);
1631
1632 #if GEN_GEN >= 9
1633 hs.DispatchMode = tcs_prog_data->base.dispatch_mode;
1634 hs.IncludePrimitiveID = tcs_prog_data->include_primitive_id;
1635 #endif
1636 }
1637
1638 const VkPipelineTessellationDomainOriginStateCreateInfo *domain_origin_state =
1639 tess_info ? vk_find_struct_const(tess_info, PIPELINE_TESSELLATION_DOMAIN_ORIGIN_STATE_CREATE_INFO) : NULL;
1640
1641 VkTessellationDomainOrigin uv_origin =
1642 domain_origin_state ? domain_origin_state->domainOrigin :
1643 VK_TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT;
1644
1645 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_TE), te) {
1646 te.Partitioning = tes_prog_data->partitioning;
1647
1648 if (uv_origin == VK_TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT) {
1649 te.OutputTopology = tes_prog_data->output_topology;
1650 } else {
1651 /* When the origin is upper-left, we have to flip the winding order */
1652 if (tes_prog_data->output_topology == OUTPUT_TRI_CCW) {
1653 te.OutputTopology = OUTPUT_TRI_CW;
1654 } else if (tes_prog_data->output_topology == OUTPUT_TRI_CW) {
1655 te.OutputTopology = OUTPUT_TRI_CCW;
1656 } else {
1657 te.OutputTopology = tes_prog_data->output_topology;
1658 }
1659 }
1660
1661 te.TEDomain = tes_prog_data->domain;
1662 te.TEEnable = true;
1663 te.MaximumTessellationFactorOdd = 63.0;
1664 te.MaximumTessellationFactorNotOdd = 64.0;
1665 }
1666
1667 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_DS), ds) {
1668 ds.Enable = true;
1669 ds.StatisticsEnable = true;
1670 ds.KernelStartPointer = tes_bin->kernel.offset;
1671 /* WA_1606682166 */
1672 ds.SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(tes_bin);
1673 ds.BindingTableEntryCount = get_binding_table_entry_count(tes_bin);
1674 ds.MaximumNumberofThreads = devinfo->max_tes_threads - 1;
1675
1676 ds.ComputeWCoordinateEnable =
1677 tes_prog_data->domain == BRW_TESS_DOMAIN_TRI;
1678
1679 ds.PatchURBEntryReadLength = tes_prog_data->base.urb_read_length;
1680 ds.PatchURBEntryReadOffset = 0;
1681 ds.DispatchGRFStartRegisterForURBData =
1682 tes_prog_data->base.base.dispatch_grf_start_reg;
1683
1684 #if GEN_GEN >= 8
1685 #if GEN_GEN < 11
1686 ds.DispatchMode =
1687 tes_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8 ?
1688 DISPATCH_MODE_SIMD8_SINGLE_PATCH :
1689 DISPATCH_MODE_SIMD4X2;
1690 #else
1691 assert(tes_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8);
1692 ds.DispatchMode = DISPATCH_MODE_SIMD8_SINGLE_PATCH;
1693 #endif
1694
1695 ds.UserClipDistanceClipTestEnableBitmask =
1696 tes_prog_data->base.clip_distance_mask;
1697 ds.UserClipDistanceCullTestEnableBitmask =
1698 tes_prog_data->base.cull_distance_mask;
1699 #endif
1700
1701 ds.PerThreadScratchSpace = get_scratch_space(tes_bin);
1702 ds.ScratchSpaceBasePointer =
1703 get_scratch_address(pipeline, MESA_SHADER_TESS_EVAL, tes_bin);
1704 }
1705 }
1706
1707 static void
1708 emit_3dstate_gs(struct anv_pipeline *pipeline)
1709 {
1710 const struct gen_device_info *devinfo = &pipeline->device->info;
1711 const struct anv_shader_bin *gs_bin =
1712 pipeline->shaders[MESA_SHADER_GEOMETRY];
1713
1714 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY)) {
1715 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_GS), gs);
1716 return;
1717 }
1718
1719 const struct brw_gs_prog_data *gs_prog_data = get_gs_prog_data(pipeline);
1720
1721 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_GS), gs) {
1722 gs.Enable = true;
1723 gs.StatisticsEnable = true;
1724 gs.KernelStartPointer = gs_bin->kernel.offset;
1725 gs.DispatchMode = gs_prog_data->base.dispatch_mode;
1726
1727 gs.SingleProgramFlow = false;
1728 gs.VectorMaskEnable = false;
1729 /* WA_1606682166 */
1730 gs.SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(gs_bin);
1731 gs.BindingTableEntryCount = get_binding_table_entry_count(gs_bin);
1732 gs.IncludeVertexHandles = gs_prog_data->base.include_vue_handles;
1733 gs.IncludePrimitiveID = gs_prog_data->include_primitive_id;
1734
1735 if (GEN_GEN == 8) {
1736 /* Broadwell is weird. It needs us to divide by 2. */
1737 gs.MaximumNumberofThreads = devinfo->max_gs_threads / 2 - 1;
1738 } else {
1739 gs.MaximumNumberofThreads = devinfo->max_gs_threads - 1;
1740 }
1741
1742 gs.OutputVertexSize = gs_prog_data->output_vertex_size_hwords * 2 - 1;
1743 gs.OutputTopology = gs_prog_data->output_topology;
1744 gs.VertexURBEntryReadLength = gs_prog_data->base.urb_read_length;
1745 gs.ControlDataFormat = gs_prog_data->control_data_format;
1746 gs.ControlDataHeaderSize = gs_prog_data->control_data_header_size_hwords;
1747 gs.InstanceControl = MAX2(gs_prog_data->invocations, 1) - 1;
1748 gs.ReorderMode = TRAILING;
1749
1750 #if GEN_GEN >= 8
1751 gs.ExpectedVertexCount = gs_prog_data->vertices_in;
1752 gs.StaticOutput = gs_prog_data->static_vertex_count >= 0;
1753 gs.StaticOutputVertexCount = gs_prog_data->static_vertex_count >= 0 ?
1754 gs_prog_data->static_vertex_count : 0;
1755 #endif
1756
1757 gs.VertexURBEntryReadOffset = 0;
1758 gs.VertexURBEntryReadLength = gs_prog_data->base.urb_read_length;
1759 gs.DispatchGRFStartRegisterForURBData =
1760 gs_prog_data->base.base.dispatch_grf_start_reg;
1761
1762 #if GEN_GEN >= 8
1763 gs.UserClipDistanceClipTestEnableBitmask =
1764 gs_prog_data->base.clip_distance_mask;
1765 gs.UserClipDistanceCullTestEnableBitmask =
1766 gs_prog_data->base.cull_distance_mask;
1767 #endif
1768
1769 gs.PerThreadScratchSpace = get_scratch_space(gs_bin);
1770 gs.ScratchSpaceBasePointer =
1771 get_scratch_address(pipeline, MESA_SHADER_GEOMETRY, gs_bin);
1772 }
1773 }
1774
1775 static bool
1776 has_color_buffer_write_enabled(const struct anv_pipeline *pipeline,
1777 const VkPipelineColorBlendStateCreateInfo *blend)
1778 {
1779 const struct anv_shader_bin *shader_bin =
1780 pipeline->shaders[MESA_SHADER_FRAGMENT];
1781 if (!shader_bin)
1782 return false;
1783
1784 const struct anv_pipeline_bind_map *bind_map = &shader_bin->bind_map;
1785 for (int i = 0; i < bind_map->surface_count; i++) {
1786 struct anv_pipeline_binding *binding = &bind_map->surface_to_descriptor[i];
1787
1788 if (binding->set != ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS)
1789 continue;
1790
1791 if (binding->index == UINT32_MAX)
1792 continue;
1793
1794 if (blend && blend->pAttachments[binding->index].colorWriteMask != 0)
1795 return true;
1796 }
1797
1798 return false;
1799 }
1800
1801 static void
1802 emit_3dstate_wm(struct anv_pipeline *pipeline, struct anv_subpass *subpass,
1803 const VkPipelineInputAssemblyStateCreateInfo *ia,
1804 const VkPipelineRasterizationStateCreateInfo *raster,
1805 const VkPipelineColorBlendStateCreateInfo *blend,
1806 const VkPipelineMultisampleStateCreateInfo *multisample,
1807 const VkPipelineRasterizationLineStateCreateInfoEXT *line)
1808 {
1809 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1810
1811 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_WM), wm) {
1812 wm.StatisticsEnable = true;
1813 wm.LineEndCapAntialiasingRegionWidth = _05pixels;
1814 wm.LineAntialiasingRegionWidth = _10pixels;
1815 wm.PointRasterizationRule = RASTRULE_UPPER_RIGHT;
1816
1817 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1818 if (wm_prog_data->early_fragment_tests) {
1819 wm.EarlyDepthStencilControl = EDSC_PREPS;
1820 } else if (wm_prog_data->has_side_effects) {
1821 wm.EarlyDepthStencilControl = EDSC_PSEXEC;
1822 } else {
1823 wm.EarlyDepthStencilControl = EDSC_NORMAL;
1824 }
1825
1826 #if GEN_GEN >= 8
1827 /* Gen8 hardware tries to compute ThreadDispatchEnable for us but
1828 * doesn't take into account KillPixels when no depth or stencil
1829 * writes are enabled. In order for occlusion queries to work
1830 * correctly with no attachments, we need to force-enable PS thread
1831 * dispatch.
1832 *
1833 * The BDW docs are pretty clear that that this bit isn't validated
1834 * and probably shouldn't be used in production:
1835 *
1836 * "This must always be set to Normal. This field should not be
1837 * tested for functional validation."
1838 *
1839 * Unfortunately, however, the other mechanism we have for doing this
1840 * is 3DSTATE_PS_EXTRA::PixelShaderHasUAV which causes hangs on BDW.
1841 * Given two bad options, we choose the one which works.
1842 */
1843 if ((wm_prog_data->has_side_effects || wm_prog_data->uses_kill) &&
1844 !has_color_buffer_write_enabled(pipeline, blend))
1845 wm.ForceThreadDispatchEnable = ForceON;
1846 #endif
1847
1848 wm.BarycentricInterpolationMode =
1849 wm_prog_data->barycentric_interp_modes;
1850
1851 #if GEN_GEN < 8
1852 wm.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
1853 wm.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
1854 wm.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
1855 wm.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
1856
1857 /* If the subpass has a depth or stencil self-dependency, then we
1858 * need to force the hardware to do the depth/stencil write *after*
1859 * fragment shader execution. Otherwise, the writes may hit memory
1860 * before we get around to fetching from the input attachment and we
1861 * may get the depth or stencil value from the current draw rather
1862 * than the previous one.
1863 */
1864 wm.PixelShaderKillsPixel = subpass->has_ds_self_dep ||
1865 wm_prog_data->uses_kill;
1866
1867 if (wm.PixelShaderComputedDepthMode != PSCDEPTH_OFF ||
1868 wm_prog_data->has_side_effects ||
1869 wm.PixelShaderKillsPixel ||
1870 has_color_buffer_write_enabled(pipeline, blend))
1871 wm.ThreadDispatchEnable = true;
1872
1873 if (multisample && multisample->rasterizationSamples > 1) {
1874 if (wm_prog_data->persample_dispatch) {
1875 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1876 } else {
1877 wm.MultisampleDispatchMode = MSDISPMODE_PERPIXEL;
1878 }
1879 } else {
1880 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1881 }
1882 wm.MultisampleRasterizationMode =
1883 gen7_ms_rast_mode(pipeline, ia, raster, multisample);
1884 #endif
1885
1886 wm.LineStippleEnable = line && line->stippledLineEnable;
1887 }
1888 }
1889 }
1890
1891 static void
1892 emit_3dstate_ps(struct anv_pipeline *pipeline,
1893 const VkPipelineColorBlendStateCreateInfo *blend,
1894 const VkPipelineMultisampleStateCreateInfo *multisample)
1895 {
1896 UNUSED const struct gen_device_info *devinfo = &pipeline->device->info;
1897 const struct anv_shader_bin *fs_bin =
1898 pipeline->shaders[MESA_SHADER_FRAGMENT];
1899
1900 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1901 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS), ps) {
1902 #if GEN_GEN == 7
1903 /* Even if no fragments are ever dispatched, gen7 hardware hangs if
1904 * we don't at least set the maximum number of threads.
1905 */
1906 ps.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
1907 #endif
1908 }
1909 return;
1910 }
1911
1912 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1913
1914 #if GEN_GEN < 8
1915 /* The hardware wedges if you have this bit set but don't turn on any dual
1916 * source blend factors.
1917 */
1918 bool dual_src_blend = false;
1919 if (wm_prog_data->dual_src_blend && blend) {
1920 for (uint32_t i = 0; i < blend->attachmentCount; i++) {
1921 const VkPipelineColorBlendAttachmentState *bstate =
1922 &blend->pAttachments[i];
1923
1924 if (bstate->blendEnable &&
1925 (is_dual_src_blend_factor(bstate->srcColorBlendFactor) ||
1926 is_dual_src_blend_factor(bstate->dstColorBlendFactor) ||
1927 is_dual_src_blend_factor(bstate->srcAlphaBlendFactor) ||
1928 is_dual_src_blend_factor(bstate->dstAlphaBlendFactor))) {
1929 dual_src_blend = true;
1930 break;
1931 }
1932 }
1933 }
1934 #endif
1935
1936 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS), ps) {
1937 ps._8PixelDispatchEnable = wm_prog_data->dispatch_8;
1938 ps._16PixelDispatchEnable = wm_prog_data->dispatch_16;
1939 ps._32PixelDispatchEnable = wm_prog_data->dispatch_32;
1940
1941 /* From the Sky Lake PRM 3DSTATE_PS::32 Pixel Dispatch Enable:
1942 *
1943 * "When NUM_MULTISAMPLES = 16 or FORCE_SAMPLE_COUNT = 16, SIMD32
1944 * Dispatch must not be enabled for PER_PIXEL dispatch mode."
1945 *
1946 * Since 16x MSAA is first introduced on SKL, we don't need to apply
1947 * the workaround on any older hardware.
1948 */
1949 if (GEN_GEN >= 9 && !wm_prog_data->persample_dispatch &&
1950 multisample && multisample->rasterizationSamples == 16) {
1951 assert(ps._8PixelDispatchEnable || ps._16PixelDispatchEnable);
1952 ps._32PixelDispatchEnable = false;
1953 }
1954
1955 ps.KernelStartPointer0 = fs_bin->kernel.offset +
1956 brw_wm_prog_data_prog_offset(wm_prog_data, ps, 0);
1957 ps.KernelStartPointer1 = fs_bin->kernel.offset +
1958 brw_wm_prog_data_prog_offset(wm_prog_data, ps, 1);
1959 ps.KernelStartPointer2 = fs_bin->kernel.offset +
1960 brw_wm_prog_data_prog_offset(wm_prog_data, ps, 2);
1961
1962 ps.SingleProgramFlow = false;
1963 ps.VectorMaskEnable = GEN_GEN >= 8;
1964 /* WA_1606682166 */
1965 ps.SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(fs_bin);
1966 ps.BindingTableEntryCount = get_binding_table_entry_count(fs_bin);
1967 ps.PushConstantEnable = wm_prog_data->base.nr_params > 0 ||
1968 wm_prog_data->base.ubo_ranges[0].length;
1969 ps.PositionXYOffsetSelect = wm_prog_data->uses_pos_offset ?
1970 POSOFFSET_SAMPLE: POSOFFSET_NONE;
1971 #if GEN_GEN < 8
1972 ps.AttributeEnable = wm_prog_data->num_varying_inputs > 0;
1973 ps.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
1974 ps.DualSourceBlendEnable = dual_src_blend;
1975 #endif
1976
1977 #if GEN_IS_HASWELL
1978 /* Haswell requires the sample mask to be set in this packet as well
1979 * as in 3DSTATE_SAMPLE_MASK; the values should match.
1980 */
1981 ps.SampleMask = 0xff;
1982 #endif
1983
1984 #if GEN_GEN >= 9
1985 ps.MaximumNumberofThreadsPerPSD = 64 - 1;
1986 #elif GEN_GEN >= 8
1987 ps.MaximumNumberofThreadsPerPSD = 64 - 2;
1988 #else
1989 ps.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
1990 #endif
1991
1992 ps.DispatchGRFStartRegisterForConstantSetupData0 =
1993 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 0);
1994 ps.DispatchGRFStartRegisterForConstantSetupData1 =
1995 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 1);
1996 ps.DispatchGRFStartRegisterForConstantSetupData2 =
1997 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 2);
1998
1999 ps.PerThreadScratchSpace = get_scratch_space(fs_bin);
2000 ps.ScratchSpaceBasePointer =
2001 get_scratch_address(pipeline, MESA_SHADER_FRAGMENT, fs_bin);
2002 }
2003 }
2004
2005 #if GEN_GEN >= 8
2006 static void
2007 emit_3dstate_ps_extra(struct anv_pipeline *pipeline,
2008 struct anv_subpass *subpass)
2009 {
2010 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
2011
2012 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
2013 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS_EXTRA), ps);
2014 return;
2015 }
2016
2017 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS_EXTRA), ps) {
2018 ps.PixelShaderValid = true;
2019 ps.AttributeEnable = wm_prog_data->num_varying_inputs > 0;
2020 ps.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
2021 ps.PixelShaderIsPerSample = wm_prog_data->persample_dispatch;
2022 ps.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
2023 ps.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
2024 ps.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
2025
2026 /* If the subpass has a depth or stencil self-dependency, then we need
2027 * to force the hardware to do the depth/stencil write *after* fragment
2028 * shader execution. Otherwise, the writes may hit memory before we get
2029 * around to fetching from the input attachment and we may get the depth
2030 * or stencil value from the current draw rather than the previous one.
2031 */
2032 ps.PixelShaderKillsPixel = subpass->has_ds_self_dep ||
2033 wm_prog_data->uses_kill;
2034
2035 #if GEN_GEN >= 9
2036 ps.PixelShaderComputesStencil = wm_prog_data->computed_stencil;
2037 ps.PixelShaderPullsBary = wm_prog_data->pulls_bary;
2038
2039 ps.InputCoverageMaskState = ICMS_NONE;
2040 if (wm_prog_data->uses_sample_mask) {
2041 if (wm_prog_data->post_depth_coverage)
2042 ps.InputCoverageMaskState = ICMS_DEPTH_COVERAGE;
2043 else
2044 ps.InputCoverageMaskState = ICMS_INNER_CONSERVATIVE;
2045 }
2046 #else
2047 ps.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
2048 #endif
2049 }
2050 }
2051
2052 static void
2053 emit_3dstate_vf_topology(struct anv_pipeline *pipeline)
2054 {
2055 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_TOPOLOGY), vft) {
2056 vft.PrimitiveTopologyType = pipeline->topology;
2057 }
2058 }
2059 #endif
2060
2061 static void
2062 emit_3dstate_vf_statistics(struct anv_pipeline *pipeline)
2063 {
2064 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_STATISTICS), vfs) {
2065 vfs.StatisticsEnable = true;
2066 }
2067 }
2068
2069 static void
2070 compute_kill_pixel(struct anv_pipeline *pipeline,
2071 const VkPipelineMultisampleStateCreateInfo *ms_info,
2072 const struct anv_subpass *subpass)
2073 {
2074 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
2075 pipeline->kill_pixel = false;
2076 return;
2077 }
2078
2079 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
2080
2081 /* This computes the KillPixel portion of the computation for whether or
2082 * not we want to enable the PMA fix on gen8 or gen9. It's given by this
2083 * chunk of the giant formula:
2084 *
2085 * (3DSTATE_PS_EXTRA::PixelShaderKillsPixels ||
2086 * 3DSTATE_PS_EXTRA::oMask Present to RenderTarget ||
2087 * 3DSTATE_PS_BLEND::AlphaToCoverageEnable ||
2088 * 3DSTATE_PS_BLEND::AlphaTestEnable ||
2089 * 3DSTATE_WM_CHROMAKEY::ChromaKeyKillEnable)
2090 *
2091 * 3DSTATE_WM_CHROMAKEY::ChromaKeyKillEnable is always false and so is
2092 * 3DSTATE_PS_BLEND::AlphaTestEnable since Vulkan doesn't have a concept
2093 * of an alpha test.
2094 */
2095 pipeline->kill_pixel =
2096 subpass->has_ds_self_dep || wm_prog_data->uses_kill ||
2097 wm_prog_data->uses_omask ||
2098 (ms_info && ms_info->alphaToCoverageEnable);
2099 }
2100
2101 static VkResult
2102 genX(graphics_pipeline_create)(
2103 VkDevice _device,
2104 struct anv_pipeline_cache * cache,
2105 const VkGraphicsPipelineCreateInfo* pCreateInfo,
2106 const VkAllocationCallbacks* pAllocator,
2107 VkPipeline* pPipeline)
2108 {
2109 ANV_FROM_HANDLE(anv_device, device, _device);
2110 ANV_FROM_HANDLE(anv_render_pass, pass, pCreateInfo->renderPass);
2111 struct anv_subpass *subpass = &pass->subpasses[pCreateInfo->subpass];
2112 struct anv_pipeline *pipeline;
2113 VkResult result;
2114
2115 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
2116
2117 /* Use the default pipeline cache if none is specified */
2118 if (cache == NULL && device->physical->instance->pipeline_cache_enabled)
2119 cache = &device->default_pipeline_cache;
2120
2121 pipeline = vk_alloc2(&device->alloc, pAllocator, sizeof(*pipeline), 8,
2122 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2123 if (pipeline == NULL)
2124 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2125
2126 result = anv_pipeline_init(pipeline, device, cache,
2127 pCreateInfo, pAllocator);
2128 if (result != VK_SUCCESS) {
2129 vk_free2(&device->alloc, pAllocator, pipeline);
2130 return result;
2131 }
2132
2133 /* If rasterization is not enabled, various CreateInfo structs must be
2134 * ignored.
2135 */
2136 const bool raster_enabled =
2137 !pCreateInfo->pRasterizationState->rasterizerDiscardEnable;
2138
2139 const VkPipelineViewportStateCreateInfo *vp_info =
2140 raster_enabled ? pCreateInfo->pViewportState : NULL;
2141
2142 const VkPipelineMultisampleStateCreateInfo *ms_info =
2143 raster_enabled ? pCreateInfo->pMultisampleState : NULL;
2144
2145 const VkPipelineDepthStencilStateCreateInfo *ds_info =
2146 raster_enabled ? pCreateInfo->pDepthStencilState : NULL;
2147
2148 const VkPipelineColorBlendStateCreateInfo *cb_info =
2149 raster_enabled ? pCreateInfo->pColorBlendState : NULL;
2150
2151 const VkPipelineRasterizationLineStateCreateInfoEXT *line_info =
2152 vk_find_struct_const(pCreateInfo->pRasterizationState->pNext,
2153 PIPELINE_RASTERIZATION_LINE_STATE_CREATE_INFO_EXT);
2154
2155 assert(pCreateInfo->pVertexInputState);
2156 emit_vertex_input(pipeline, pCreateInfo->pVertexInputState);
2157 assert(pCreateInfo->pRasterizationState);
2158 emit_rs_state(pipeline, pCreateInfo->pInputAssemblyState,
2159 pCreateInfo->pRasterizationState,
2160 ms_info, line_info, pass, subpass);
2161 emit_ms_state(pipeline, ms_info);
2162 emit_ds_state(pipeline, ds_info, pass, subpass);
2163 emit_cb_state(pipeline, cb_info, ms_info);
2164 compute_kill_pixel(pipeline, ms_info, subpass);
2165
2166 emit_urb_setup(pipeline);
2167
2168 emit_3dstate_clip(pipeline,
2169 pCreateInfo->pInputAssemblyState,
2170 vp_info,
2171 pCreateInfo->pRasterizationState);
2172 emit_3dstate_streamout(pipeline, pCreateInfo->pRasterizationState);
2173
2174 #if 0
2175 /* From gen7_vs_state.c */
2176
2177 /**
2178 * From Graphics BSpec: 3D-Media-GPGPU Engine > 3D Pipeline Stages >
2179 * Geometry > Geometry Shader > State:
2180 *
2181 * "Note: Because of corruption in IVB:GT2, software needs to flush the
2182 * whole fixed function pipeline when the GS enable changes value in
2183 * the 3DSTATE_GS."
2184 *
2185 * The hardware architects have clarified that in this context "flush the
2186 * whole fixed function pipeline" means to emit a PIPE_CONTROL with the "CS
2187 * Stall" bit set.
2188 */
2189 if (!device->info.is_haswell && !device->info.is_baytrail)
2190 gen7_emit_vs_workaround_flush(brw);
2191 #endif
2192
2193 emit_3dstate_vs(pipeline);
2194 emit_3dstate_hs_te_ds(pipeline, pCreateInfo->pTessellationState);
2195 emit_3dstate_gs(pipeline);
2196 emit_3dstate_sbe(pipeline);
2197 emit_3dstate_wm(pipeline, subpass,
2198 pCreateInfo->pInputAssemblyState,
2199 pCreateInfo->pRasterizationState,
2200 cb_info, ms_info, line_info);
2201 emit_3dstate_ps(pipeline, cb_info, ms_info);
2202 #if GEN_GEN >= 8
2203 emit_3dstate_ps_extra(pipeline, subpass);
2204 emit_3dstate_vf_topology(pipeline);
2205 #endif
2206 emit_3dstate_vf_statistics(pipeline);
2207
2208 *pPipeline = anv_pipeline_to_handle(pipeline);
2209
2210 return pipeline->batch.status;
2211 }
2212
2213 static VkResult
2214 compute_pipeline_create(
2215 VkDevice _device,
2216 struct anv_pipeline_cache * cache,
2217 const VkComputePipelineCreateInfo* pCreateInfo,
2218 const VkAllocationCallbacks* pAllocator,
2219 VkPipeline* pPipeline)
2220 {
2221 ANV_FROM_HANDLE(anv_device, device, _device);
2222 const struct gen_device_info *devinfo = &device->info;
2223 struct anv_pipeline *pipeline;
2224 VkResult result;
2225
2226 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO);
2227
2228 /* Use the default pipeline cache if none is specified */
2229 if (cache == NULL && device->physical->instance->pipeline_cache_enabled)
2230 cache = &device->default_pipeline_cache;
2231
2232 pipeline = vk_alloc2(&device->alloc, pAllocator, sizeof(*pipeline), 8,
2233 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2234 if (pipeline == NULL)
2235 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2236
2237 pipeline->device = device;
2238
2239 pipeline->blend_state.map = NULL;
2240
2241 const VkAllocationCallbacks *alloc =
2242 pAllocator ? pAllocator : &device->alloc;
2243
2244 result = anv_reloc_list_init(&pipeline->batch_relocs, alloc);
2245 if (result != VK_SUCCESS) {
2246 vk_free2(&device->alloc, pAllocator, pipeline);
2247 return result;
2248 }
2249 pipeline->batch.alloc = alloc;
2250 pipeline->batch.next = pipeline->batch.start = pipeline->batch_data;
2251 pipeline->batch.end = pipeline->batch.start + sizeof(pipeline->batch_data);
2252 pipeline->batch.relocs = &pipeline->batch_relocs;
2253 pipeline->batch.status = VK_SUCCESS;
2254
2255 pipeline->mem_ctx = ralloc_context(NULL);
2256 pipeline->flags = pCreateInfo->flags;
2257
2258 /* When we free the pipeline, we detect stages based on the NULL status
2259 * of various prog_data pointers. Make them NULL by default.
2260 */
2261 memset(pipeline->shaders, 0, sizeof(pipeline->shaders));
2262 pipeline->num_executables = 0;
2263
2264 pipeline->needs_data_cache = false;
2265
2266 assert(pCreateInfo->stage.stage == VK_SHADER_STAGE_COMPUTE_BIT);
2267 pipeline->active_stages |= VK_SHADER_STAGE_COMPUTE_BIT;
2268 ANV_FROM_HANDLE(anv_shader_module, module, pCreateInfo->stage.module);
2269 result = anv_pipeline_compile_cs(pipeline, cache, pCreateInfo, module,
2270 pCreateInfo->stage.pName,
2271 pCreateInfo->stage.pSpecializationInfo);
2272 if (result != VK_SUCCESS) {
2273 ralloc_free(pipeline->mem_ctx);
2274 vk_free2(&device->alloc, pAllocator, pipeline);
2275 return result;
2276 }
2277
2278 const struct brw_cs_prog_data *cs_prog_data = get_cs_prog_data(pipeline);
2279
2280 anv_pipeline_setup_l3_config(pipeline, cs_prog_data->base.total_shared > 0);
2281
2282 uint32_t group_size = cs_prog_data->local_size[0] *
2283 cs_prog_data->local_size[1] * cs_prog_data->local_size[2];
2284 uint32_t remainder = group_size & (cs_prog_data->simd_size - 1);
2285
2286 if (remainder > 0)
2287 pipeline->cs_right_mask = ~0u >> (32 - remainder);
2288 else
2289 pipeline->cs_right_mask = ~0u >> (32 - cs_prog_data->simd_size);
2290
2291 const uint32_t vfe_curbe_allocation =
2292 ALIGN(cs_prog_data->push.per_thread.regs * cs_prog_data->threads +
2293 cs_prog_data->push.cross_thread.regs, 2);
2294
2295 const uint32_t subslices = MAX2(device->physical->subslice_total, 1);
2296
2297 const struct anv_shader_bin *cs_bin =
2298 pipeline->shaders[MESA_SHADER_COMPUTE];
2299
2300 anv_batch_emit(&pipeline->batch, GENX(MEDIA_VFE_STATE), vfe) {
2301 #if GEN_GEN > 7
2302 vfe.StackSize = 0;
2303 #else
2304 vfe.GPGPUMode = true;
2305 #endif
2306 vfe.MaximumNumberofThreads =
2307 devinfo->max_cs_threads * subslices - 1;
2308 vfe.NumberofURBEntries = GEN_GEN <= 7 ? 0 : 2;
2309 #if GEN_GEN < 11
2310 vfe.ResetGatewayTimer = true;
2311 #endif
2312 #if GEN_GEN <= 8
2313 vfe.BypassGatewayControl = true;
2314 #endif
2315 vfe.URBEntryAllocationSize = GEN_GEN <= 7 ? 0 : 2;
2316 vfe.CURBEAllocationSize = vfe_curbe_allocation;
2317
2318 if (cs_bin->prog_data->total_scratch) {
2319 if (GEN_GEN >= 8) {
2320 /* Broadwell's Per Thread Scratch Space is in the range [0, 11]
2321 * where 0 = 1k, 1 = 2k, 2 = 4k, ..., 11 = 2M.
2322 */
2323 vfe.PerThreadScratchSpace =
2324 ffs(cs_bin->prog_data->total_scratch) - 11;
2325 } else if (GEN_IS_HASWELL) {
2326 /* Haswell's Per Thread Scratch Space is in the range [0, 10]
2327 * where 0 = 2k, 1 = 4k, 2 = 8k, ..., 10 = 2M.
2328 */
2329 vfe.PerThreadScratchSpace =
2330 ffs(cs_bin->prog_data->total_scratch) - 12;
2331 } else {
2332 /* IVB and BYT use the range [0, 11] to mean [1kB, 12kB]
2333 * where 0 = 1kB, 1 = 2kB, 2 = 3kB, ..., 11 = 12kB.
2334 */
2335 vfe.PerThreadScratchSpace =
2336 cs_bin->prog_data->total_scratch / 1024 - 1;
2337 }
2338 vfe.ScratchSpaceBasePointer =
2339 get_scratch_address(pipeline, MESA_SHADER_COMPUTE, cs_bin);
2340 }
2341 }
2342
2343 struct GENX(INTERFACE_DESCRIPTOR_DATA) desc = {
2344 .KernelStartPointer = cs_bin->kernel.offset,
2345 /* WA_1606682166 */
2346 .SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(cs_bin),
2347 /* We add 1 because the CS indirect parameters buffer isn't accounted
2348 * for in bind_map.surface_count.
2349 */
2350 .BindingTableEntryCount = 1 + MIN2(cs_bin->bind_map.surface_count, 30),
2351 .BarrierEnable = cs_prog_data->uses_barrier,
2352 .SharedLocalMemorySize =
2353 encode_slm_size(GEN_GEN, cs_prog_data->base.total_shared),
2354
2355 #if !GEN_IS_HASWELL
2356 .ConstantURBEntryReadOffset = 0,
2357 #endif
2358 .ConstantURBEntryReadLength = cs_prog_data->push.per_thread.regs,
2359 #if GEN_GEN >= 8 || GEN_IS_HASWELL
2360 .CrossThreadConstantDataReadLength =
2361 cs_prog_data->push.cross_thread.regs,
2362 #endif
2363
2364 .NumberofThreadsinGPGPUThreadGroup = cs_prog_data->threads,
2365 };
2366 GENX(INTERFACE_DESCRIPTOR_DATA_pack)(NULL,
2367 pipeline->interface_descriptor_data,
2368 &desc);
2369
2370 *pPipeline = anv_pipeline_to_handle(pipeline);
2371
2372 return pipeline->batch.status;
2373 }
2374
2375 VkResult genX(CreateGraphicsPipelines)(
2376 VkDevice _device,
2377 VkPipelineCache pipelineCache,
2378 uint32_t count,
2379 const VkGraphicsPipelineCreateInfo* pCreateInfos,
2380 const VkAllocationCallbacks* pAllocator,
2381 VkPipeline* pPipelines)
2382 {
2383 ANV_FROM_HANDLE(anv_pipeline_cache, pipeline_cache, pipelineCache);
2384
2385 VkResult result = VK_SUCCESS;
2386
2387 unsigned i;
2388 for (i = 0; i < count; i++) {
2389 result = genX(graphics_pipeline_create)(_device,
2390 pipeline_cache,
2391 &pCreateInfos[i],
2392 pAllocator, &pPipelines[i]);
2393
2394 /* Bail out on the first error as it is not obvious what error should be
2395 * report upon 2 different failures. */
2396 if (result != VK_SUCCESS)
2397 break;
2398 }
2399
2400 for (; i < count; i++)
2401 pPipelines[i] = VK_NULL_HANDLE;
2402
2403 return result;
2404 }
2405
2406 VkResult genX(CreateComputePipelines)(
2407 VkDevice _device,
2408 VkPipelineCache pipelineCache,
2409 uint32_t count,
2410 const VkComputePipelineCreateInfo* pCreateInfos,
2411 const VkAllocationCallbacks* pAllocator,
2412 VkPipeline* pPipelines)
2413 {
2414 ANV_FROM_HANDLE(anv_pipeline_cache, pipeline_cache, pipelineCache);
2415
2416 VkResult result = VK_SUCCESS;
2417
2418 unsigned i;
2419 for (i = 0; i < count; i++) {
2420 result = compute_pipeline_create(_device, pipeline_cache,
2421 &pCreateInfos[i],
2422 pAllocator, &pPipelines[i]);
2423
2424 /* Bail out on the first error as it is not obvious what error should be
2425 * report upon 2 different failures. */
2426 if (result != VK_SUCCESS)
2427 break;
2428 }
2429
2430 for (; i < count; i++)
2431 pPipelines[i] = VK_NULL_HANDLE;
2432
2433 return result;
2434 }