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