anv: Explicitly cast between different enums
[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 "vk_format_info.h"
32
33 static uint32_t
34 vertex_element_comp_control(enum isl_format format, unsigned comp)
35 {
36 uint8_t bits;
37 switch (comp) {
38 case 0: bits = isl_format_layouts[format].channels.r.bits; break;
39 case 1: bits = isl_format_layouts[format].channels.g.bits; break;
40 case 2: bits = isl_format_layouts[format].channels.b.bits; break;
41 case 3: bits = isl_format_layouts[format].channels.a.bits; break;
42 default: unreachable("Invalid component");
43 }
44
45 /*
46 * Take in account hardware restrictions when dealing with 64-bit floats.
47 *
48 * From Broadwell spec, command reference structures, page 586:
49 * "When SourceElementFormat is set to one of the *64*_PASSTHRU formats,
50 * 64-bit components are stored * in the URB without any conversion. In
51 * this case, vertex elements must be written as 128 or 256 bits, with
52 * VFCOMP_STORE_0 being used to pad the output as required. E.g., if
53 * R64_PASSTHRU is used to copy a 64-bit Red component into the URB,
54 * Component 1 must be specified as VFCOMP_STORE_0 (with Components 2,3
55 * set to VFCOMP_NOSTORE) in order to output a 128-bit vertex element, or
56 * Components 1-3 must be specified as VFCOMP_STORE_0 in order to output
57 * a 256-bit vertex element. Likewise, use of R64G64B64_PASSTHRU requires
58 * Component 3 to be specified as VFCOMP_STORE_0 in order to output a
59 * 256-bit vertex element."
60 */
61 if (bits) {
62 return VFCOMP_STORE_SRC;
63 } else if (comp >= 2 &&
64 !isl_format_layouts[format].channels.b.bits &&
65 isl_format_layouts[format].channels.r.type == ISL_RAW) {
66 /* When emitting 64-bit attributes, we need to write either 128 or 256
67 * bit chunks, using VFCOMP_NOSTORE when not writing the chunk, and
68 * VFCOMP_STORE_0 to pad the written chunk */
69 return VFCOMP_NOSTORE;
70 } else if (comp < 3 ||
71 isl_format_layouts[format].channels.r.type == ISL_RAW) {
72 /* Note we need to pad with value 0, not 1, due hardware restrictions
73 * (see comment above) */
74 return VFCOMP_STORE_0;
75 } else if (isl_format_layouts[format].channels.r.type == ISL_UINT ||
76 isl_format_layouts[format].channels.r.type == ISL_SINT) {
77 assert(comp == 3);
78 return VFCOMP_STORE_1_INT;
79 } else {
80 assert(comp == 3);
81 return VFCOMP_STORE_1_FP;
82 }
83 }
84
85 static void
86 emit_vertex_input(struct anv_pipeline *pipeline,
87 const VkPipelineVertexInputStateCreateInfo *info)
88 {
89 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
90
91 /* Pull inputs_read out of the VS prog data */
92 const uint64_t inputs_read = vs_prog_data->inputs_read;
93 const uint64_t double_inputs_read = vs_prog_data->double_inputs_read;
94 assert((inputs_read & ((1 << VERT_ATTRIB_GENERIC0) - 1)) == 0);
95 const uint32_t elements = inputs_read >> VERT_ATTRIB_GENERIC0;
96 const uint32_t elements_double = double_inputs_read >> VERT_ATTRIB_GENERIC0;
97 const bool needs_svgs_elem = vs_prog_data->uses_vertexid ||
98 vs_prog_data->uses_instanceid ||
99 vs_prog_data->uses_basevertex ||
100 vs_prog_data->uses_baseinstance;
101
102 uint32_t elem_count = __builtin_popcount(elements) -
103 __builtin_popcount(elements_double) / 2;
104
105 const uint32_t total_elems =
106 elem_count + needs_svgs_elem + vs_prog_data->uses_drawid;
107 if (total_elems == 0)
108 return;
109
110 uint32_t *p;
111
112 const uint32_t num_dwords = 1 + total_elems * 2;
113 p = anv_batch_emitn(&pipeline->batch, num_dwords,
114 GENX(3DSTATE_VERTEX_ELEMENTS));
115 if (!p)
116 return;
117 memset(p + 1, 0, (num_dwords - 1) * 4);
118
119 for (uint32_t i = 0; i < info->vertexAttributeDescriptionCount; i++) {
120 const VkVertexInputAttributeDescription *desc =
121 &info->pVertexAttributeDescriptions[i];
122 enum isl_format format = anv_get_isl_format(&pipeline->device->info,
123 desc->format,
124 VK_IMAGE_ASPECT_COLOR_BIT,
125 VK_IMAGE_TILING_LINEAR);
126
127 assert(desc->binding < MAX_VBS);
128
129 if ((elements & (1 << desc->location)) == 0)
130 continue; /* Binding unused */
131
132 uint32_t slot =
133 __builtin_popcount(elements & ((1 << desc->location) - 1)) -
134 DIV_ROUND_UP(__builtin_popcount(elements_double &
135 ((1 << desc->location) -1)), 2);
136
137 struct GENX(VERTEX_ELEMENT_STATE) element = {
138 .VertexBufferIndex = desc->binding,
139 .Valid = true,
140 .SourceElementFormat = (enum GENX(SURFACE_FORMAT)) format,
141 .EdgeFlagEnable = false,
142 .SourceElementOffset = desc->offset,
143 .Component0Control = vertex_element_comp_control(format, 0),
144 .Component1Control = vertex_element_comp_control(format, 1),
145 .Component2Control = vertex_element_comp_control(format, 2),
146 .Component3Control = vertex_element_comp_control(format, 3),
147 };
148 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + slot * 2], &element);
149
150 #if GEN_GEN >= 8
151 /* On Broadwell and later, we have a separate VF_INSTANCING packet
152 * that controls instancing. On Haswell and prior, that's part of
153 * VERTEX_BUFFER_STATE which we emit later.
154 */
155 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_INSTANCING), vfi) {
156 vfi.InstancingEnable = pipeline->instancing_enable[desc->binding];
157 vfi.VertexElementIndex = slot;
158 /* Our implementation of VK_KHX_multiview uses instancing to draw
159 * the different views. If the client asks for instancing, we
160 * need to use the Instance Data Step Rate to ensure that we
161 * repeat the client's per-instance data once for each view.
162 */
163 vfi.InstanceDataStepRate = anv_subpass_view_count(pipeline->subpass);
164 }
165 #endif
166 }
167
168 const uint32_t id_slot = elem_count;
169 if (needs_svgs_elem) {
170 /* From the Broadwell PRM for the 3D_Vertex_Component_Control enum:
171 * "Within a VERTEX_ELEMENT_STATE structure, if a Component
172 * Control field is set to something other than VFCOMP_STORE_SRC,
173 * no higher-numbered Component Control fields may be set to
174 * VFCOMP_STORE_SRC"
175 *
176 * This means, that if we have BaseInstance, we need BaseVertex as
177 * well. Just do all or nothing.
178 */
179 uint32_t base_ctrl = (vs_prog_data->uses_basevertex ||
180 vs_prog_data->uses_baseinstance) ?
181 VFCOMP_STORE_SRC : VFCOMP_STORE_0;
182
183 struct GENX(VERTEX_ELEMENT_STATE) element = {
184 .VertexBufferIndex = ANV_SVGS_VB_INDEX,
185 .Valid = true,
186 .SourceElementFormat = (enum GENX(SURFACE_FORMAT)) ISL_FORMAT_R32G32_UINT,
187 .Component0Control = base_ctrl,
188 .Component1Control = base_ctrl,
189 #if GEN_GEN >= 8
190 .Component2Control = VFCOMP_STORE_0,
191 .Component3Control = VFCOMP_STORE_0,
192 #else
193 .Component2Control = VFCOMP_STORE_VID,
194 .Component3Control = VFCOMP_STORE_IID,
195 #endif
196 };
197 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + id_slot * 2], &element);
198 }
199
200 #if GEN_GEN >= 8
201 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_SGVS), sgvs) {
202 sgvs.VertexIDEnable = vs_prog_data->uses_vertexid;
203 sgvs.VertexIDComponentNumber = 2;
204 sgvs.VertexIDElementOffset = id_slot;
205 sgvs.InstanceIDEnable = vs_prog_data->uses_instanceid;
206 sgvs.InstanceIDComponentNumber = 3;
207 sgvs.InstanceIDElementOffset = id_slot;
208 }
209 #endif
210
211 const uint32_t drawid_slot = elem_count + needs_svgs_elem;
212 if (vs_prog_data->uses_drawid) {
213 struct GENX(VERTEX_ELEMENT_STATE) element = {
214 .VertexBufferIndex = ANV_DRAWID_VB_INDEX,
215 .Valid = true,
216 .SourceElementFormat = (enum GENX(SURFACE_FORMAT)) ISL_FORMAT_R32_UINT,
217 .Component0Control = VFCOMP_STORE_SRC,
218 .Component1Control = VFCOMP_STORE_0,
219 .Component2Control = VFCOMP_STORE_0,
220 .Component3Control = VFCOMP_STORE_0,
221 };
222 GENX(VERTEX_ELEMENT_STATE_pack)(NULL,
223 &p[1 + drawid_slot * 2],
224 &element);
225
226 #if GEN_GEN >= 8
227 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_INSTANCING), vfi) {
228 vfi.VertexElementIndex = drawid_slot;
229 }
230 #endif
231 }
232 }
233
234 void
235 genX(emit_urb_setup)(struct anv_device *device, struct anv_batch *batch,
236 const struct gen_l3_config *l3_config,
237 VkShaderStageFlags active_stages,
238 const unsigned entry_size[4])
239 {
240 const struct gen_device_info *devinfo = &device->info;
241 #if GEN_IS_HASWELL
242 const unsigned push_constant_kb = devinfo->gt == 3 ? 32 : 16;
243 #else
244 const unsigned push_constant_kb = GEN_GEN >= 8 ? 32 : 16;
245 #endif
246
247 const unsigned urb_size_kb = gen_get_l3_config_urb_size(devinfo, l3_config);
248
249 unsigned entries[4];
250 unsigned start[4];
251 gen_get_urb_config(devinfo,
252 1024 * push_constant_kb, 1024 * urb_size_kb,
253 active_stages &
254 VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
255 active_stages & VK_SHADER_STAGE_GEOMETRY_BIT,
256 entry_size, entries, start);
257
258 #if GEN_GEN == 7 && !GEN_IS_HASWELL
259 /* From the IVB PRM Vol. 2, Part 1, Section 3.2.1:
260 *
261 * "A PIPE_CONTROL with Post-Sync Operation set to 1h and a depth stall
262 * needs to be sent just prior to any 3DSTATE_VS, 3DSTATE_URB_VS,
263 * 3DSTATE_CONSTANT_VS, 3DSTATE_BINDING_TABLE_POINTER_VS,
264 * 3DSTATE_SAMPLER_STATE_POINTER_VS command. Only one PIPE_CONTROL
265 * needs to be sent before any combination of VS associated 3DSTATE."
266 */
267 anv_batch_emit(batch, GEN7_PIPE_CONTROL, pc) {
268 pc.DepthStallEnable = true;
269 pc.PostSyncOperation = WriteImmediateData;
270 pc.Address = (struct anv_address) { &device->workaround_bo, 0 };
271 }
272 #endif
273
274 for (int i = 0; i <= MESA_SHADER_GEOMETRY; i++) {
275 anv_batch_emit(batch, GENX(3DSTATE_URB_VS), urb) {
276 urb._3DCommandSubOpcode += i;
277 urb.VSURBStartingAddress = start[i];
278 urb.VSURBEntryAllocationSize = entry_size[i] - 1;
279 urb.VSNumberofURBEntries = entries[i];
280 }
281 }
282 }
283
284 static void
285 emit_urb_setup(struct anv_pipeline *pipeline)
286 {
287 unsigned entry_size[4];
288 for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
289 const struct brw_vue_prog_data *prog_data =
290 !anv_pipeline_has_stage(pipeline, i) ? NULL :
291 (const struct brw_vue_prog_data *) pipeline->shaders[i]->prog_data;
292
293 entry_size[i] = prog_data ? prog_data->urb_entry_size : 1;
294 }
295
296 genX(emit_urb_setup)(pipeline->device, &pipeline->batch,
297 pipeline->urb.l3_config,
298 pipeline->active_stages, entry_size);
299 }
300
301 static void
302 emit_3dstate_sbe(struct anv_pipeline *pipeline)
303 {
304 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
305
306 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
307 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_SBE), sbe);
308 #if GEN_GEN >= 8
309 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_SBE_SWIZ), sbe);
310 #endif
311 return;
312 }
313
314 const struct brw_vue_map *fs_input_map =
315 &anv_pipeline_get_last_vue_prog_data(pipeline)->vue_map;
316
317 struct GENX(3DSTATE_SBE) sbe = {
318 GENX(3DSTATE_SBE_header),
319 .AttributeSwizzleEnable = true,
320 .PointSpriteTextureCoordinateOrigin = UPPERLEFT,
321 .NumberofSFOutputAttributes = wm_prog_data->num_varying_inputs,
322 .ConstantInterpolationEnable = wm_prog_data->flat_inputs,
323 };
324
325 #if GEN_GEN >= 9
326 for (unsigned i = 0; i < 32; i++)
327 sbe.AttributeActiveComponentFormat[i] = ACF_XYZW;
328 #endif
329
330 #if GEN_GEN >= 8
331 /* On Broadwell, they broke 3DSTATE_SBE into two packets */
332 struct GENX(3DSTATE_SBE_SWIZ) swiz = {
333 GENX(3DSTATE_SBE_SWIZ_header),
334 };
335 #else
336 # define swiz sbe
337 #endif
338
339 /* Skip the VUE header and position slots by default */
340 unsigned urb_entry_read_offset = 1;
341 int max_source_attr = 0;
342 for (int attr = 0; attr < VARYING_SLOT_MAX; attr++) {
343 int input_index = wm_prog_data->urb_setup[attr];
344
345 if (input_index < 0)
346 continue;
347
348 /* gl_Layer is stored in the VUE header */
349 if (attr == VARYING_SLOT_LAYER) {
350 urb_entry_read_offset = 0;
351 continue;
352 }
353
354 if (attr == VARYING_SLOT_PNTC) {
355 sbe.PointSpriteTextureCoordinateEnable = 1 << input_index;
356 continue;
357 }
358
359 const int slot = fs_input_map->varying_to_slot[attr];
360
361 if (input_index >= 16)
362 continue;
363
364 if (slot == -1) {
365 /* This attribute does not exist in the VUE--that means that the
366 * vertex shader did not write to it. It could be that it's a
367 * regular varying read by the fragment shader but not written by
368 * the vertex shader or it's gl_PrimitiveID. In the first case the
369 * value is undefined, in the second it needs to be
370 * gl_PrimitiveID.
371 */
372 swiz.Attribute[input_index].ConstantSource = PRIM_ID;
373 swiz.Attribute[input_index].ComponentOverrideX = true;
374 swiz.Attribute[input_index].ComponentOverrideY = true;
375 swiz.Attribute[input_index].ComponentOverrideZ = true;
376 swiz.Attribute[input_index].ComponentOverrideW = true;
377 } else {
378 /* We have to subtract two slots to accout for the URB entry output
379 * read offset in the VS and GS stages.
380 */
381 assert(slot >= 2);
382 const int source_attr = slot - 2 * urb_entry_read_offset;
383 max_source_attr = MAX2(max_source_attr, source_attr);
384 swiz.Attribute[input_index].SourceAttribute = source_attr;
385 }
386 }
387
388 sbe.VertexURBEntryReadOffset = urb_entry_read_offset;
389 sbe.VertexURBEntryReadLength = DIV_ROUND_UP(max_source_attr + 1, 2);
390 #if GEN_GEN >= 8
391 sbe.ForceVertexURBEntryReadOffset = true;
392 sbe.ForceVertexURBEntryReadLength = true;
393 #endif
394
395 uint32_t *dw = anv_batch_emit_dwords(&pipeline->batch,
396 GENX(3DSTATE_SBE_length));
397 if (!dw)
398 return;
399 GENX(3DSTATE_SBE_pack)(&pipeline->batch, dw, &sbe);
400
401 #if GEN_GEN >= 8
402 dw = anv_batch_emit_dwords(&pipeline->batch, GENX(3DSTATE_SBE_SWIZ_length));
403 if (!dw)
404 return;
405 GENX(3DSTATE_SBE_SWIZ_pack)(&pipeline->batch, dw, &swiz);
406 #endif
407 }
408
409 static const uint32_t vk_to_gen_cullmode[] = {
410 [VK_CULL_MODE_NONE] = CULLMODE_NONE,
411 [VK_CULL_MODE_FRONT_BIT] = CULLMODE_FRONT,
412 [VK_CULL_MODE_BACK_BIT] = CULLMODE_BACK,
413 [VK_CULL_MODE_FRONT_AND_BACK] = CULLMODE_BOTH
414 };
415
416 static const uint32_t vk_to_gen_fillmode[] = {
417 [VK_POLYGON_MODE_FILL] = FILL_MODE_SOLID,
418 [VK_POLYGON_MODE_LINE] = FILL_MODE_WIREFRAME,
419 [VK_POLYGON_MODE_POINT] = FILL_MODE_POINT,
420 };
421
422 static const uint32_t vk_to_gen_front_face[] = {
423 [VK_FRONT_FACE_COUNTER_CLOCKWISE] = 1,
424 [VK_FRONT_FACE_CLOCKWISE] = 0
425 };
426
427 static void
428 emit_rs_state(struct anv_pipeline *pipeline,
429 const VkPipelineRasterizationStateCreateInfo *rs_info,
430 const VkPipelineMultisampleStateCreateInfo *ms_info,
431 const struct anv_render_pass *pass,
432 const struct anv_subpass *subpass)
433 {
434 struct GENX(3DSTATE_SF) sf = {
435 GENX(3DSTATE_SF_header),
436 };
437
438 sf.ViewportTransformEnable = true;
439 sf.StatisticsEnable = true;
440 sf.TriangleStripListProvokingVertexSelect = 0;
441 sf.LineStripListProvokingVertexSelect = 0;
442 sf.TriangleFanProvokingVertexSelect = 1;
443
444 const struct brw_vue_prog_data *last_vue_prog_data =
445 anv_pipeline_get_last_vue_prog_data(pipeline);
446
447 if (last_vue_prog_data->vue_map.slots_valid & VARYING_BIT_PSIZ) {
448 sf.PointWidthSource = Vertex;
449 } else {
450 sf.PointWidthSource = State;
451 sf.PointWidth = 1.0;
452 }
453
454 #if GEN_GEN >= 8
455 struct GENX(3DSTATE_RASTER) raster = {
456 GENX(3DSTATE_RASTER_header),
457 };
458 #else
459 # define raster sf
460 #endif
461
462 /* For details on 3DSTATE_RASTER multisample state, see the BSpec table
463 * "Multisample Modes State".
464 */
465 #if GEN_GEN >= 8
466 raster.DXMultisampleRasterizationEnable = true;
467 /* NOTE: 3DSTATE_RASTER::ForcedSampleCount affects the BDW and SKL PMA fix
468 * computations. If we ever set this bit to a different value, they will
469 * need to be updated accordingly.
470 */
471 raster.ForcedSampleCount = FSC_NUMRASTSAMPLES_0;
472 raster.ForceMultisampling = false;
473 #else
474 raster.MultisampleRasterizationMode =
475 (ms_info && ms_info->rasterizationSamples > 1) ?
476 MSRASTMODE_ON_PATTERN : MSRASTMODE_OFF_PIXEL;
477 #endif
478
479 raster.FrontWinding = vk_to_gen_front_face[rs_info->frontFace];
480 raster.CullMode = vk_to_gen_cullmode[rs_info->cullMode];
481 raster.FrontFaceFillMode = vk_to_gen_fillmode[rs_info->polygonMode];
482 raster.BackFaceFillMode = vk_to_gen_fillmode[rs_info->polygonMode];
483 raster.ScissorRectangleEnable = true;
484
485 #if GEN_GEN >= 9
486 /* GEN9+ splits ViewportZClipTestEnable into near and far enable bits */
487 raster.ViewportZFarClipTestEnable = !pipeline->depth_clamp_enable;
488 raster.ViewportZNearClipTestEnable = !pipeline->depth_clamp_enable;
489 #elif GEN_GEN >= 8
490 raster.ViewportZClipTestEnable = !pipeline->depth_clamp_enable;
491 #endif
492
493 raster.GlobalDepthOffsetEnableSolid = rs_info->depthBiasEnable;
494 raster.GlobalDepthOffsetEnableWireframe = rs_info->depthBiasEnable;
495 raster.GlobalDepthOffsetEnablePoint = rs_info->depthBiasEnable;
496
497 #if GEN_GEN == 7
498 /* Gen7 requires that we provide the depth format in 3DSTATE_SF so that it
499 * can get the depth offsets correct.
500 */
501 if (subpass->depth_stencil_attachment.attachment < pass->attachment_count) {
502 VkFormat vk_format =
503 pass->attachments[subpass->depth_stencil_attachment.attachment].format;
504 assert(vk_format_is_depth_or_stencil(vk_format));
505 if (vk_format_aspects(vk_format) & VK_IMAGE_ASPECT_DEPTH_BIT) {
506 enum isl_format isl_format =
507 anv_get_isl_format(&pipeline->device->info, vk_format,
508 VK_IMAGE_ASPECT_DEPTH_BIT,
509 VK_IMAGE_TILING_OPTIMAL);
510 sf.DepthBufferSurfaceFormat =
511 isl_format_get_depth_format(isl_format, false);
512 }
513 }
514 #endif
515
516 #if GEN_GEN >= 8
517 GENX(3DSTATE_SF_pack)(NULL, pipeline->gen8.sf, &sf);
518 GENX(3DSTATE_RASTER_pack)(NULL, pipeline->gen8.raster, &raster);
519 #else
520 # undef raster
521 GENX(3DSTATE_SF_pack)(NULL, &pipeline->gen7.sf, &sf);
522 #endif
523 }
524
525 static void
526 emit_ms_state(struct anv_pipeline *pipeline,
527 const VkPipelineMultisampleStateCreateInfo *info)
528 {
529 uint32_t samples = 1;
530 uint32_t log2_samples = 0;
531
532 /* From the Vulkan 1.0 spec:
533 * If pSampleMask is NULL, it is treated as if the mask has all bits
534 * enabled, i.e. no coverage is removed from fragments.
535 *
536 * 3DSTATE_SAMPLE_MASK.SampleMask is 16 bits.
537 */
538 #if GEN_GEN >= 8
539 uint32_t sample_mask = 0xffff;
540 #else
541 uint32_t sample_mask = 0xff;
542 #endif
543
544 if (info) {
545 samples = info->rasterizationSamples;
546 log2_samples = __builtin_ffs(samples) - 1;
547 }
548
549 if (info && info->pSampleMask)
550 sample_mask &= info->pSampleMask[0];
551
552 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_MULTISAMPLE), ms) {
553 ms.NumberofMultisamples = log2_samples;
554
555 ms.PixelLocation = CENTER;
556 #if GEN_GEN >= 8
557 /* The PRM says that this bit is valid only for DX9:
558 *
559 * SW can choose to set this bit only for DX9 API. DX10/OGL API's
560 * should not have any effect by setting or not setting this bit.
561 */
562 ms.PixelPositionOffsetEnable = false;
563 #else
564
565 switch (samples) {
566 case 1:
567 GEN_SAMPLE_POS_1X(ms.Sample);
568 break;
569 case 2:
570 GEN_SAMPLE_POS_2X(ms.Sample);
571 break;
572 case 4:
573 GEN_SAMPLE_POS_4X(ms.Sample);
574 break;
575 case 8:
576 GEN_SAMPLE_POS_8X(ms.Sample);
577 break;
578 default:
579 break;
580 }
581 #endif
582 }
583
584 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_SAMPLE_MASK), sm) {
585 sm.SampleMask = sample_mask;
586 }
587 }
588
589 static const uint32_t vk_to_gen_logic_op[] = {
590 [VK_LOGIC_OP_COPY] = LOGICOP_COPY,
591 [VK_LOGIC_OP_CLEAR] = LOGICOP_CLEAR,
592 [VK_LOGIC_OP_AND] = LOGICOP_AND,
593 [VK_LOGIC_OP_AND_REVERSE] = LOGICOP_AND_REVERSE,
594 [VK_LOGIC_OP_AND_INVERTED] = LOGICOP_AND_INVERTED,
595 [VK_LOGIC_OP_NO_OP] = LOGICOP_NOOP,
596 [VK_LOGIC_OP_XOR] = LOGICOP_XOR,
597 [VK_LOGIC_OP_OR] = LOGICOP_OR,
598 [VK_LOGIC_OP_NOR] = LOGICOP_NOR,
599 [VK_LOGIC_OP_EQUIVALENT] = LOGICOP_EQUIV,
600 [VK_LOGIC_OP_INVERT] = LOGICOP_INVERT,
601 [VK_LOGIC_OP_OR_REVERSE] = LOGICOP_OR_REVERSE,
602 [VK_LOGIC_OP_COPY_INVERTED] = LOGICOP_COPY_INVERTED,
603 [VK_LOGIC_OP_OR_INVERTED] = LOGICOP_OR_INVERTED,
604 [VK_LOGIC_OP_NAND] = LOGICOP_NAND,
605 [VK_LOGIC_OP_SET] = LOGICOP_SET,
606 };
607
608 static const uint32_t vk_to_gen_blend[] = {
609 [VK_BLEND_FACTOR_ZERO] = BLENDFACTOR_ZERO,
610 [VK_BLEND_FACTOR_ONE] = BLENDFACTOR_ONE,
611 [VK_BLEND_FACTOR_SRC_COLOR] = BLENDFACTOR_SRC_COLOR,
612 [VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR] = BLENDFACTOR_INV_SRC_COLOR,
613 [VK_BLEND_FACTOR_DST_COLOR] = BLENDFACTOR_DST_COLOR,
614 [VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR] = BLENDFACTOR_INV_DST_COLOR,
615 [VK_BLEND_FACTOR_SRC_ALPHA] = BLENDFACTOR_SRC_ALPHA,
616 [VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA] = BLENDFACTOR_INV_SRC_ALPHA,
617 [VK_BLEND_FACTOR_DST_ALPHA] = BLENDFACTOR_DST_ALPHA,
618 [VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA] = BLENDFACTOR_INV_DST_ALPHA,
619 [VK_BLEND_FACTOR_CONSTANT_COLOR] = BLENDFACTOR_CONST_COLOR,
620 [VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR]= BLENDFACTOR_INV_CONST_COLOR,
621 [VK_BLEND_FACTOR_CONSTANT_ALPHA] = BLENDFACTOR_CONST_ALPHA,
622 [VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA]= BLENDFACTOR_INV_CONST_ALPHA,
623 [VK_BLEND_FACTOR_SRC_ALPHA_SATURATE] = BLENDFACTOR_SRC_ALPHA_SATURATE,
624 [VK_BLEND_FACTOR_SRC1_COLOR] = BLENDFACTOR_SRC1_COLOR,
625 [VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR] = BLENDFACTOR_INV_SRC1_COLOR,
626 [VK_BLEND_FACTOR_SRC1_ALPHA] = BLENDFACTOR_SRC1_ALPHA,
627 [VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA] = BLENDFACTOR_INV_SRC1_ALPHA,
628 };
629
630 static const uint32_t vk_to_gen_blend_op[] = {
631 [VK_BLEND_OP_ADD] = BLENDFUNCTION_ADD,
632 [VK_BLEND_OP_SUBTRACT] = BLENDFUNCTION_SUBTRACT,
633 [VK_BLEND_OP_REVERSE_SUBTRACT] = BLENDFUNCTION_REVERSE_SUBTRACT,
634 [VK_BLEND_OP_MIN] = BLENDFUNCTION_MIN,
635 [VK_BLEND_OP_MAX] = BLENDFUNCTION_MAX,
636 };
637
638 static const uint32_t vk_to_gen_compare_op[] = {
639 [VK_COMPARE_OP_NEVER] = PREFILTEROPNEVER,
640 [VK_COMPARE_OP_LESS] = PREFILTEROPLESS,
641 [VK_COMPARE_OP_EQUAL] = PREFILTEROPEQUAL,
642 [VK_COMPARE_OP_LESS_OR_EQUAL] = PREFILTEROPLEQUAL,
643 [VK_COMPARE_OP_GREATER] = PREFILTEROPGREATER,
644 [VK_COMPARE_OP_NOT_EQUAL] = PREFILTEROPNOTEQUAL,
645 [VK_COMPARE_OP_GREATER_OR_EQUAL] = PREFILTEROPGEQUAL,
646 [VK_COMPARE_OP_ALWAYS] = PREFILTEROPALWAYS,
647 };
648
649 static const uint32_t vk_to_gen_stencil_op[] = {
650 [VK_STENCIL_OP_KEEP] = STENCILOP_KEEP,
651 [VK_STENCIL_OP_ZERO] = STENCILOP_ZERO,
652 [VK_STENCIL_OP_REPLACE] = STENCILOP_REPLACE,
653 [VK_STENCIL_OP_INCREMENT_AND_CLAMP] = STENCILOP_INCRSAT,
654 [VK_STENCIL_OP_DECREMENT_AND_CLAMP] = STENCILOP_DECRSAT,
655 [VK_STENCIL_OP_INVERT] = STENCILOP_INVERT,
656 [VK_STENCIL_OP_INCREMENT_AND_WRAP] = STENCILOP_INCR,
657 [VK_STENCIL_OP_DECREMENT_AND_WRAP] = STENCILOP_DECR,
658 };
659
660 /* This function sanitizes the VkStencilOpState by looking at the compare ops
661 * and trying to determine whether or not a given stencil op can ever actually
662 * occur. Stencil ops which can never occur are set to VK_STENCIL_OP_KEEP.
663 * This function returns true if, after sanitation, any of the stencil ops are
664 * set to something other than VK_STENCIL_OP_KEEP.
665 */
666 static bool
667 sanitize_stencil_face(VkStencilOpState *face,
668 VkCompareOp depthCompareOp)
669 {
670 /* If compareOp is ALWAYS then the stencil test will never fail and failOp
671 * will never happen. Set failOp to KEEP in this case.
672 */
673 if (face->compareOp == VK_COMPARE_OP_ALWAYS)
674 face->failOp = VK_STENCIL_OP_KEEP;
675
676 /* If compareOp is NEVER or depthCompareOp is NEVER then one of the depth
677 * or stencil tests will fail and passOp will never happen.
678 */
679 if (face->compareOp == VK_COMPARE_OP_NEVER ||
680 depthCompareOp == VK_COMPARE_OP_NEVER)
681 face->passOp = VK_STENCIL_OP_KEEP;
682
683 /* If compareOp is NEVER or depthCompareOp is ALWAYS then either the
684 * stencil test will fail or the depth test will pass. In either case,
685 * depthFailOp will never happen.
686 */
687 if (face->compareOp == VK_COMPARE_OP_NEVER ||
688 depthCompareOp == VK_COMPARE_OP_ALWAYS)
689 face->depthFailOp = VK_STENCIL_OP_KEEP;
690
691 return face->failOp != VK_STENCIL_OP_KEEP ||
692 face->depthFailOp != VK_STENCIL_OP_KEEP ||
693 face->passOp != VK_STENCIL_OP_KEEP;
694 }
695
696 /* Intel hardware is fairly sensitive to whether or not depth/stencil writes
697 * are enabled. In the presence of discards, it's fairly easy to get into the
698 * non-promoted case which means a fairly big performance hit. From the Iron
699 * Lake PRM, Vol 2, pt. 1, section 8.4.3.2, "Early Depth Test Cases":
700 *
701 * "Non-promoted depth (N) is active whenever the depth test can be done
702 * early but it cannot determine whether or not to write source depth to
703 * the depth buffer, therefore the depth write must be performed post pixel
704 * shader. This includes cases where the pixel shader can kill pixels,
705 * including via sampler chroma key, as well as cases where the alpha test
706 * function is enabled, which kills pixels based on a programmable alpha
707 * test. In this case, even if the depth test fails, the pixel cannot be
708 * killed if a stencil write is indicated. Whether or not the stencil write
709 * happens depends on whether or not the pixel is killed later. In these
710 * cases if stencil test fails and stencil writes are off, the pixels can
711 * also be killed early. If stencil writes are enabled, the pixels must be
712 * treated as Computed depth (described above)."
713 *
714 * The same thing as mentioned in the stencil case can happen in the depth
715 * case as well if it thinks it writes depth but, thanks to the depth test
716 * being GL_EQUAL, the write doesn't actually matter. A little extra work
717 * up-front to try and disable depth and stencil writes can make a big
718 * difference.
719 *
720 * Unfortunately, the way depth and stencil testing is specified, there are
721 * many case where, regardless of depth/stencil writes being enabled, nothing
722 * actually gets written due to some other bit of state being set. This
723 * function attempts to "sanitize" the depth stencil state and disable writes
724 * and sometimes even testing whenever possible.
725 */
726 static void
727 sanitize_ds_state(VkPipelineDepthStencilStateCreateInfo *state,
728 bool *stencilWriteEnable,
729 VkImageAspectFlags ds_aspects)
730 {
731 *stencilWriteEnable = state->stencilTestEnable;
732
733 /* If the depth test is disabled, we won't be writing anything. */
734 if (!state->depthTestEnable)
735 state->depthWriteEnable = false;
736
737 /* The Vulkan spec requires that if either depth or stencil is not present,
738 * the pipeline is to act as if the test silently passes.
739 */
740 if (!(ds_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
741 state->depthWriteEnable = false;
742 state->depthCompareOp = VK_COMPARE_OP_ALWAYS;
743 }
744
745 if (!(ds_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) {
746 *stencilWriteEnable = false;
747 state->front.compareOp = VK_COMPARE_OP_ALWAYS;
748 state->back.compareOp = VK_COMPARE_OP_ALWAYS;
749 }
750
751 /* If the stencil test is enabled and always fails, then we will never get
752 * to the depth test so we can just disable the depth test entirely.
753 */
754 if (state->stencilTestEnable &&
755 state->front.compareOp == VK_COMPARE_OP_NEVER &&
756 state->back.compareOp == VK_COMPARE_OP_NEVER) {
757 state->depthTestEnable = false;
758 state->depthWriteEnable = false;
759 }
760
761 /* If depthCompareOp is EQUAL then the value we would be writing to the
762 * depth buffer is the same as the value that's already there so there's no
763 * point in writing it.
764 */
765 if (state->depthCompareOp == VK_COMPARE_OP_EQUAL)
766 state->depthWriteEnable = false;
767
768 /* If the stencil ops are such that we don't actually ever modify the
769 * stencil buffer, we should disable writes.
770 */
771 if (!sanitize_stencil_face(&state->front, state->depthCompareOp) &&
772 !sanitize_stencil_face(&state->back, state->depthCompareOp))
773 *stencilWriteEnable = false;
774
775 /* If the depth test always passes and we never write out depth, that's the
776 * same as if the depth test is disabled entirely.
777 */
778 if (state->depthCompareOp == VK_COMPARE_OP_ALWAYS &&
779 !state->depthWriteEnable)
780 state->depthTestEnable = false;
781
782 /* If the stencil test always passes and we never write out stencil, that's
783 * the same as if the stencil test is disabled entirely.
784 */
785 if (state->front.compareOp == VK_COMPARE_OP_ALWAYS &&
786 state->back.compareOp == VK_COMPARE_OP_ALWAYS &&
787 !*stencilWriteEnable)
788 state->stencilTestEnable = false;
789 }
790
791 static void
792 emit_ds_state(struct anv_pipeline *pipeline,
793 const VkPipelineDepthStencilStateCreateInfo *pCreateInfo,
794 const struct anv_render_pass *pass,
795 const struct anv_subpass *subpass)
796 {
797 #if GEN_GEN == 7
798 # define depth_stencil_dw pipeline->gen7.depth_stencil_state
799 #elif GEN_GEN == 8
800 # define depth_stencil_dw pipeline->gen8.wm_depth_stencil
801 #else
802 # define depth_stencil_dw pipeline->gen9.wm_depth_stencil
803 #endif
804
805 if (pCreateInfo == NULL) {
806 /* We're going to OR this together with the dynamic state. We need
807 * to make sure it's initialized to something useful.
808 */
809 pipeline->writes_stencil = false;
810 pipeline->stencil_test_enable = false;
811 pipeline->writes_depth = false;
812 pipeline->depth_test_enable = false;
813 memset(depth_stencil_dw, 0, sizeof(depth_stencil_dw));
814 return;
815 }
816
817 VkImageAspectFlags ds_aspects = 0;
818 if (subpass->depth_stencil_attachment.attachment != VK_ATTACHMENT_UNUSED) {
819 VkFormat depth_stencil_format =
820 pass->attachments[subpass->depth_stencil_attachment.attachment].format;
821 ds_aspects = vk_format_aspects(depth_stencil_format);
822 }
823
824 VkPipelineDepthStencilStateCreateInfo info = *pCreateInfo;
825 sanitize_ds_state(&info, &pipeline->writes_stencil, ds_aspects);
826 pipeline->stencil_test_enable = info.stencilTestEnable;
827 pipeline->writes_depth = info.depthWriteEnable;
828 pipeline->depth_test_enable = info.depthTestEnable;
829
830 /* VkBool32 depthBoundsTestEnable; // optional (depth_bounds_test) */
831
832 #if GEN_GEN <= 7
833 struct GENX(DEPTH_STENCIL_STATE) depth_stencil = {
834 #else
835 struct GENX(3DSTATE_WM_DEPTH_STENCIL) depth_stencil = {
836 #endif
837 .DepthTestEnable = info.depthTestEnable,
838 .DepthBufferWriteEnable = info.depthWriteEnable,
839 .DepthTestFunction = vk_to_gen_compare_op[info.depthCompareOp],
840 .DoubleSidedStencilEnable = true,
841
842 .StencilTestEnable = info.stencilTestEnable,
843 .StencilFailOp = vk_to_gen_stencil_op[info.front.failOp],
844 .StencilPassDepthPassOp = vk_to_gen_stencil_op[info.front.passOp],
845 .StencilPassDepthFailOp = vk_to_gen_stencil_op[info.front.depthFailOp],
846 .StencilTestFunction = vk_to_gen_compare_op[info.front.compareOp],
847 .BackfaceStencilFailOp = vk_to_gen_stencil_op[info.back.failOp],
848 .BackfaceStencilPassDepthPassOp = vk_to_gen_stencil_op[info.back.passOp],
849 .BackfaceStencilPassDepthFailOp =vk_to_gen_stencil_op[info.back.depthFailOp],
850 .BackfaceStencilTestFunction = vk_to_gen_compare_op[info.back.compareOp],
851 };
852
853 #if GEN_GEN <= 7
854 GENX(DEPTH_STENCIL_STATE_pack)(NULL, depth_stencil_dw, &depth_stencil);
855 #else
856 GENX(3DSTATE_WM_DEPTH_STENCIL_pack)(NULL, depth_stencil_dw, &depth_stencil);
857 #endif
858 }
859
860 static void
861 emit_cb_state(struct anv_pipeline *pipeline,
862 const VkPipelineColorBlendStateCreateInfo *info,
863 const VkPipelineMultisampleStateCreateInfo *ms_info)
864 {
865 struct anv_device *device = pipeline->device;
866
867
868 struct GENX(BLEND_STATE) blend_state = {
869 #if GEN_GEN >= 8
870 .AlphaToCoverageEnable = ms_info && ms_info->alphaToCoverageEnable,
871 .AlphaToOneEnable = ms_info && ms_info->alphaToOneEnable,
872 #endif
873 };
874
875 uint32_t surface_count = 0;
876 struct anv_pipeline_bind_map *map;
877 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
878 map = &pipeline->shaders[MESA_SHADER_FRAGMENT]->bind_map;
879 surface_count = map->surface_count;
880 }
881
882 const uint32_t num_dwords = GENX(BLEND_STATE_length) +
883 GENX(BLEND_STATE_ENTRY_length) * surface_count;
884 pipeline->blend_state =
885 anv_state_pool_alloc(&device->dynamic_state_pool, num_dwords * 4, 64);
886
887 bool has_writeable_rt = false;
888 uint32_t *state_pos = pipeline->blend_state.map;
889 state_pos += GENX(BLEND_STATE_length);
890 #if GEN_GEN >= 8
891 struct GENX(BLEND_STATE_ENTRY) bs0 = { 0 };
892 #endif
893 for (unsigned i = 0; i < surface_count; i++) {
894 struct anv_pipeline_binding *binding = &map->surface_to_descriptor[i];
895
896 /* All color attachments are at the beginning of the binding table */
897 if (binding->set != ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS)
898 break;
899
900 /* We can have at most 8 attachments */
901 assert(i < 8);
902
903 if (info == NULL || binding->index >= info->attachmentCount) {
904 /* Default everything to disabled */
905 struct GENX(BLEND_STATE_ENTRY) entry = {
906 .WriteDisableAlpha = true,
907 .WriteDisableRed = true,
908 .WriteDisableGreen = true,
909 .WriteDisableBlue = true,
910 };
911 GENX(BLEND_STATE_ENTRY_pack)(NULL, state_pos, &entry);
912 state_pos += GENX(BLEND_STATE_ENTRY_length);
913 continue;
914 }
915
916 assert(binding->binding == 0);
917 const VkPipelineColorBlendAttachmentState *a =
918 &info->pAttachments[binding->index];
919
920 struct GENX(BLEND_STATE_ENTRY) entry = {
921 #if GEN_GEN < 8
922 .AlphaToCoverageEnable = ms_info && ms_info->alphaToCoverageEnable,
923 .AlphaToOneEnable = ms_info && ms_info->alphaToOneEnable,
924 #endif
925 .LogicOpEnable = info->logicOpEnable,
926 .LogicOpFunction = vk_to_gen_logic_op[info->logicOp],
927 .ColorBufferBlendEnable = a->blendEnable,
928 .ColorClampRange = COLORCLAMP_RTFORMAT,
929 .PreBlendColorClampEnable = true,
930 .PostBlendColorClampEnable = true,
931 .SourceBlendFactor = vk_to_gen_blend[a->srcColorBlendFactor],
932 .DestinationBlendFactor = vk_to_gen_blend[a->dstColorBlendFactor],
933 .ColorBlendFunction = vk_to_gen_blend_op[a->colorBlendOp],
934 .SourceAlphaBlendFactor = vk_to_gen_blend[a->srcAlphaBlendFactor],
935 .DestinationAlphaBlendFactor = vk_to_gen_blend[a->dstAlphaBlendFactor],
936 .AlphaBlendFunction = vk_to_gen_blend_op[a->alphaBlendOp],
937 .WriteDisableAlpha = !(a->colorWriteMask & VK_COLOR_COMPONENT_A_BIT),
938 .WriteDisableRed = !(a->colorWriteMask & VK_COLOR_COMPONENT_R_BIT),
939 .WriteDisableGreen = !(a->colorWriteMask & VK_COLOR_COMPONENT_G_BIT),
940 .WriteDisableBlue = !(a->colorWriteMask & VK_COLOR_COMPONENT_B_BIT),
941 };
942
943 if (a->srcColorBlendFactor != a->srcAlphaBlendFactor ||
944 a->dstColorBlendFactor != a->dstAlphaBlendFactor ||
945 a->colorBlendOp != a->alphaBlendOp) {
946 #if GEN_GEN >= 8
947 blend_state.IndependentAlphaBlendEnable = true;
948 #else
949 entry.IndependentAlphaBlendEnable = true;
950 #endif
951 }
952
953 if (a->colorWriteMask != 0)
954 has_writeable_rt = true;
955
956 /* Our hardware applies the blend factor prior to the blend function
957 * regardless of what function is used. Technically, this means the
958 * hardware can do MORE than GL or Vulkan specify. However, it also
959 * means that, for MIN and MAX, we have to stomp the blend factor to
960 * ONE to make it a no-op.
961 */
962 if (a->colorBlendOp == VK_BLEND_OP_MIN ||
963 a->colorBlendOp == VK_BLEND_OP_MAX) {
964 entry.SourceBlendFactor = BLENDFACTOR_ONE;
965 entry.DestinationBlendFactor = BLENDFACTOR_ONE;
966 }
967 if (a->alphaBlendOp == VK_BLEND_OP_MIN ||
968 a->alphaBlendOp == VK_BLEND_OP_MAX) {
969 entry.SourceAlphaBlendFactor = BLENDFACTOR_ONE;
970 entry.DestinationAlphaBlendFactor = BLENDFACTOR_ONE;
971 }
972 GENX(BLEND_STATE_ENTRY_pack)(NULL, state_pos, &entry);
973 state_pos += GENX(BLEND_STATE_ENTRY_length);
974 #if GEN_GEN >= 8
975 if (i == 0)
976 bs0 = entry;
977 #endif
978 }
979
980 #if GEN_GEN >= 8
981 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS_BLEND), blend) {
982 blend.AlphaToCoverageEnable = blend_state.AlphaToCoverageEnable;
983 blend.HasWriteableRT = has_writeable_rt;
984 blend.ColorBufferBlendEnable = bs0.ColorBufferBlendEnable;
985 blend.SourceAlphaBlendFactor = bs0.SourceAlphaBlendFactor;
986 blend.DestinationAlphaBlendFactor = bs0.DestinationAlphaBlendFactor;
987 blend.SourceBlendFactor = bs0.SourceBlendFactor;
988 blend.DestinationBlendFactor = bs0.DestinationBlendFactor;
989 blend.AlphaTestEnable = false;
990 blend.IndependentAlphaBlendEnable =
991 blend_state.IndependentAlphaBlendEnable;
992 }
993 #else
994 (void)has_writeable_rt;
995 #endif
996
997 GENX(BLEND_STATE_pack)(NULL, pipeline->blend_state.map, &blend_state);
998 anv_state_flush(device, pipeline->blend_state);
999
1000 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_BLEND_STATE_POINTERS), bsp) {
1001 bsp.BlendStatePointer = pipeline->blend_state.offset;
1002 #if GEN_GEN >= 8
1003 bsp.BlendStatePointerValid = true;
1004 #endif
1005 }
1006 }
1007
1008 static void
1009 emit_3dstate_clip(struct anv_pipeline *pipeline,
1010 const VkPipelineViewportStateCreateInfo *vp_info,
1011 const VkPipelineRasterizationStateCreateInfo *rs_info)
1012 {
1013 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1014 (void) wm_prog_data;
1015 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_CLIP), clip) {
1016 clip.ClipEnable = true;
1017 clip.StatisticsEnable = true;
1018 clip.EarlyCullEnable = true;
1019 clip.APIMode = APIMODE_D3D,
1020 clip.ViewportXYClipTestEnable = true;
1021
1022 clip.ClipMode = CLIPMODE_NORMAL;
1023
1024 clip.TriangleStripListProvokingVertexSelect = 0;
1025 clip.LineStripListProvokingVertexSelect = 0;
1026 clip.TriangleFanProvokingVertexSelect = 1;
1027
1028 clip.MinimumPointWidth = 0.125;
1029 clip.MaximumPointWidth = 255.875;
1030
1031 const struct brw_vue_prog_data *last =
1032 anv_pipeline_get_last_vue_prog_data(pipeline);
1033
1034 /* From the Vulkan 1.0.45 spec:
1035 *
1036 * "If the last active vertex processing stage shader entry point's
1037 * interface does not include a variable decorated with
1038 * ViewportIndex, then the first viewport is used."
1039 */
1040 if (vp_info && (last->vue_map.slots_valid & VARYING_BIT_VIEWPORT)) {
1041 clip.MaximumVPIndex = vp_info->viewportCount - 1;
1042 } else {
1043 clip.MaximumVPIndex = 0;
1044 }
1045
1046 /* From the Vulkan 1.0.45 spec:
1047 *
1048 * "If the last active vertex processing stage shader entry point's
1049 * interface does not include a variable decorated with Layer, then
1050 * the first layer is used."
1051 */
1052 clip.ForceZeroRTAIndexEnable =
1053 !(last->vue_map.slots_valid & VARYING_BIT_LAYER);
1054
1055 #if GEN_GEN == 7
1056 clip.FrontWinding = vk_to_gen_front_face[rs_info->frontFace];
1057 clip.CullMode = vk_to_gen_cullmode[rs_info->cullMode];
1058 clip.ViewportZClipTestEnable = !pipeline->depth_clamp_enable;
1059 if (last) {
1060 clip.UserClipDistanceClipTestEnableBitmask = last->clip_distance_mask;
1061 clip.UserClipDistanceCullTestEnableBitmask = last->cull_distance_mask;
1062 }
1063 #else
1064 clip.NonPerspectiveBarycentricEnable = wm_prog_data ?
1065 (wm_prog_data->barycentric_interp_modes &
1066 BRW_BARYCENTRIC_NONPERSPECTIVE_BITS) != 0 : 0;
1067 #endif
1068 }
1069 }
1070
1071 static void
1072 emit_3dstate_streamout(struct anv_pipeline *pipeline,
1073 const VkPipelineRasterizationStateCreateInfo *rs_info)
1074 {
1075 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_STREAMOUT), so) {
1076 so.RenderingDisable = rs_info->rasterizerDiscardEnable;
1077 }
1078 }
1079
1080 static uint32_t
1081 get_sampler_count(const struct anv_shader_bin *bin)
1082 {
1083 return DIV_ROUND_UP(bin->bind_map.sampler_count, 4);
1084 }
1085
1086 static uint32_t
1087 get_binding_table_entry_count(const struct anv_shader_bin *bin)
1088 {
1089 return DIV_ROUND_UP(bin->bind_map.surface_count, 32);
1090 }
1091
1092 static struct anv_address
1093 get_scratch_address(struct anv_pipeline *pipeline,
1094 gl_shader_stage stage,
1095 const struct anv_shader_bin *bin)
1096 {
1097 return (struct anv_address) {
1098 .bo = anv_scratch_pool_alloc(pipeline->device,
1099 &pipeline->device->scratch_pool,
1100 stage, bin->prog_data->total_scratch),
1101 .offset = 0,
1102 };
1103 }
1104
1105 static uint32_t
1106 get_scratch_space(const struct anv_shader_bin *bin)
1107 {
1108 return ffs(bin->prog_data->total_scratch / 2048);
1109 }
1110
1111 static uint32_t
1112 get_urb_output_offset()
1113 {
1114 /* Skip the VUE header and position slots */
1115 return 1;
1116 }
1117
1118 static uint32_t
1119 get_urb_output_length(const struct anv_shader_bin *bin)
1120 {
1121 const struct brw_vue_prog_data *prog_data =
1122 (const struct brw_vue_prog_data *)bin->prog_data;
1123
1124 return (prog_data->vue_map.num_slots + 1) / 2 - get_urb_output_offset();
1125 }
1126
1127 static void
1128 emit_3dstate_vs(struct anv_pipeline *pipeline)
1129 {
1130 const struct gen_device_info *devinfo = &pipeline->device->info;
1131 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
1132 const struct anv_shader_bin *vs_bin =
1133 pipeline->shaders[MESA_SHADER_VERTEX];
1134
1135 assert(anv_pipeline_has_stage(pipeline, MESA_SHADER_VERTEX));
1136
1137 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VS), vs) {
1138 vs.Enable = true;
1139 vs.StatisticsEnable = true;
1140 vs.KernelStartPointer = vs_bin->kernel.offset;
1141 #if GEN_GEN >= 8
1142 vs.SIMD8DispatchEnable =
1143 vs_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8;
1144 #endif
1145
1146 assert(!vs_prog_data->base.base.use_alt_mode);
1147 vs.SingleVertexDispatch = false;
1148 vs.VectorMaskEnable = false;
1149 vs.SamplerCount = get_sampler_count(vs_bin);
1150 vs.BindingTableEntryCount = get_binding_table_entry_count(vs_bin);
1151 vs.FloatingPointMode = IEEE754;
1152 vs.IllegalOpcodeExceptionEnable = false;
1153 vs.SoftwareExceptionEnable = false;
1154 vs.MaximumNumberofThreads = devinfo->max_vs_threads - 1;
1155 vs.VertexCacheDisable = false;
1156
1157 vs.VertexURBEntryReadLength = vs_prog_data->base.urb_read_length;
1158 vs.VertexURBEntryReadOffset = 0;
1159 vs.DispatchGRFStartRegisterForURBData =
1160 vs_prog_data->base.base.dispatch_grf_start_reg;
1161
1162 #if GEN_GEN >= 8
1163 vs.VertexURBEntryOutputReadOffset = get_urb_output_offset();
1164 vs.VertexURBEntryOutputLength = get_urb_output_length(vs_bin);
1165
1166 vs.UserClipDistanceClipTestEnableBitmask =
1167 vs_prog_data->base.clip_distance_mask;
1168 vs.UserClipDistanceCullTestEnableBitmask =
1169 vs_prog_data->base.cull_distance_mask;
1170 #endif
1171
1172 vs.PerThreadScratchSpace = get_scratch_space(vs_bin);
1173 vs.ScratchSpaceBasePointer =
1174 get_scratch_address(pipeline, MESA_SHADER_VERTEX, vs_bin);
1175 }
1176 }
1177
1178 static void
1179 emit_3dstate_hs_te_ds(struct anv_pipeline *pipeline)
1180 {
1181 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL)) {
1182 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_HS), hs);
1183 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_TE), te);
1184 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_DS), ds);
1185 return;
1186 }
1187
1188 const struct gen_device_info *devinfo = &pipeline->device->info;
1189 const struct anv_shader_bin *tcs_bin =
1190 pipeline->shaders[MESA_SHADER_TESS_CTRL];
1191 const struct anv_shader_bin *tes_bin =
1192 pipeline->shaders[MESA_SHADER_TESS_EVAL];
1193
1194 const struct brw_tcs_prog_data *tcs_prog_data = get_tcs_prog_data(pipeline);
1195 const struct brw_tes_prog_data *tes_prog_data = get_tes_prog_data(pipeline);
1196
1197 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_HS), hs) {
1198 hs.Enable = true;
1199 hs.StatisticsEnable = true;
1200 hs.KernelStartPointer = tcs_bin->kernel.offset;
1201
1202 hs.SamplerCount = get_sampler_count(tcs_bin);
1203 hs.BindingTableEntryCount = get_binding_table_entry_count(tcs_bin);
1204 hs.MaximumNumberofThreads = devinfo->max_tcs_threads - 1;
1205 hs.IncludeVertexHandles = true;
1206 hs.InstanceCount = tcs_prog_data->instances - 1;
1207
1208 hs.VertexURBEntryReadLength = 0;
1209 hs.VertexURBEntryReadOffset = 0;
1210 hs.DispatchGRFStartRegisterForURBData =
1211 tcs_prog_data->base.base.dispatch_grf_start_reg;
1212
1213 hs.PerThreadScratchSpace = get_scratch_space(tcs_bin);
1214 hs.ScratchSpaceBasePointer =
1215 get_scratch_address(pipeline, MESA_SHADER_TESS_CTRL, tcs_bin);
1216 }
1217
1218 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_TE), te) {
1219 te.Partitioning = tes_prog_data->partitioning;
1220 te.OutputTopology = tes_prog_data->output_topology;
1221 te.TEDomain = tes_prog_data->domain;
1222 te.TEEnable = true;
1223 te.MaximumTessellationFactorOdd = 63.0;
1224 te.MaximumTessellationFactorNotOdd = 64.0;
1225 }
1226
1227 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_DS), ds) {
1228 ds.Enable = true;
1229 ds.StatisticsEnable = true;
1230 ds.KernelStartPointer = tes_bin->kernel.offset;
1231
1232 ds.SamplerCount = get_sampler_count(tes_bin);
1233 ds.BindingTableEntryCount = get_binding_table_entry_count(tes_bin);
1234 ds.MaximumNumberofThreads = devinfo->max_tes_threads - 1;
1235
1236 ds.ComputeWCoordinateEnable =
1237 tes_prog_data->domain == BRW_TESS_DOMAIN_TRI;
1238
1239 ds.PatchURBEntryReadLength = tes_prog_data->base.urb_read_length;
1240 ds.PatchURBEntryReadOffset = 0;
1241 ds.DispatchGRFStartRegisterForURBData =
1242 tes_prog_data->base.base.dispatch_grf_start_reg;
1243
1244 #if GEN_GEN >= 8
1245 ds.VertexURBEntryOutputReadOffset = 1;
1246 ds.VertexURBEntryOutputLength =
1247 (tes_prog_data->base.vue_map.num_slots + 1) / 2 - 1;
1248
1249 ds.DispatchMode =
1250 tes_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8 ?
1251 DISPATCH_MODE_SIMD8_SINGLE_PATCH :
1252 DISPATCH_MODE_SIMD4X2;
1253
1254 ds.UserClipDistanceClipTestEnableBitmask =
1255 tes_prog_data->base.clip_distance_mask;
1256 ds.UserClipDistanceCullTestEnableBitmask =
1257 tes_prog_data->base.cull_distance_mask;
1258 #endif
1259
1260 ds.PerThreadScratchSpace = get_scratch_space(tes_bin);
1261 ds.ScratchSpaceBasePointer =
1262 get_scratch_address(pipeline, MESA_SHADER_TESS_EVAL, tes_bin);
1263 }
1264 }
1265
1266 static void
1267 emit_3dstate_gs(struct anv_pipeline *pipeline)
1268 {
1269 const struct gen_device_info *devinfo = &pipeline->device->info;
1270 const struct anv_shader_bin *gs_bin =
1271 pipeline->shaders[MESA_SHADER_GEOMETRY];
1272
1273 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY)) {
1274 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_GS), gs);
1275 return;
1276 }
1277
1278 const struct brw_gs_prog_data *gs_prog_data = get_gs_prog_data(pipeline);
1279
1280 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_GS), gs) {
1281 gs.Enable = true;
1282 gs.StatisticsEnable = true;
1283 gs.KernelStartPointer = gs_bin->kernel.offset;
1284 gs.DispatchMode = gs_prog_data->base.dispatch_mode;
1285
1286 gs.SingleProgramFlow = false;
1287 gs.VectorMaskEnable = false;
1288 gs.SamplerCount = get_sampler_count(gs_bin);
1289 gs.BindingTableEntryCount = get_binding_table_entry_count(gs_bin);
1290 gs.IncludeVertexHandles = gs_prog_data->base.include_vue_handles;
1291 gs.IncludePrimitiveID = gs_prog_data->include_primitive_id;
1292
1293 if (GEN_GEN == 8) {
1294 /* Broadwell is weird. It needs us to divide by 2. */
1295 gs.MaximumNumberofThreads = devinfo->max_gs_threads / 2 - 1;
1296 } else {
1297 gs.MaximumNumberofThreads = devinfo->max_gs_threads - 1;
1298 }
1299
1300 gs.OutputVertexSize = gs_prog_data->output_vertex_size_hwords * 2 - 1;
1301 gs.OutputTopology = gs_prog_data->output_topology;
1302 gs.VertexURBEntryReadLength = gs_prog_data->base.urb_read_length;
1303 gs.ControlDataFormat = gs_prog_data->control_data_format;
1304 gs.ControlDataHeaderSize = gs_prog_data->control_data_header_size_hwords;
1305 gs.InstanceControl = MAX2(gs_prog_data->invocations, 1) - 1;
1306 gs.ReorderMode = TRAILING;
1307
1308 #if GEN_GEN >= 8
1309 gs.ExpectedVertexCount = gs_prog_data->vertices_in;
1310 gs.StaticOutput = gs_prog_data->static_vertex_count >= 0;
1311 gs.StaticOutputVertexCount = gs_prog_data->static_vertex_count >= 0 ?
1312 gs_prog_data->static_vertex_count : 0;
1313 #endif
1314
1315 gs.VertexURBEntryReadOffset = 0;
1316 gs.VertexURBEntryReadLength = gs_prog_data->base.urb_read_length;
1317 gs.DispatchGRFStartRegisterForURBData =
1318 gs_prog_data->base.base.dispatch_grf_start_reg;
1319
1320 #if GEN_GEN >= 8
1321 gs.VertexURBEntryOutputReadOffset = get_urb_output_offset();
1322 gs.VertexURBEntryOutputLength = get_urb_output_length(gs_bin);
1323
1324 gs.UserClipDistanceClipTestEnableBitmask =
1325 gs_prog_data->base.clip_distance_mask;
1326 gs.UserClipDistanceCullTestEnableBitmask =
1327 gs_prog_data->base.cull_distance_mask;
1328 #endif
1329
1330 gs.PerThreadScratchSpace = get_scratch_space(gs_bin);
1331 gs.ScratchSpaceBasePointer =
1332 get_scratch_address(pipeline, MESA_SHADER_GEOMETRY, gs_bin);
1333 }
1334 }
1335
1336 static bool
1337 has_color_buffer_write_enabled(const struct anv_pipeline *pipeline)
1338 {
1339 const struct anv_shader_bin *shader_bin =
1340 pipeline->shaders[MESA_SHADER_FRAGMENT];
1341 if (!shader_bin)
1342 return false;
1343
1344 const struct anv_pipeline_bind_map *bind_map = &shader_bin->bind_map;
1345 for (int i = 0; i < bind_map->surface_count; i++) {
1346 if (bind_map->surface_to_descriptor[i].set !=
1347 ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS)
1348 continue;
1349 if (bind_map->surface_to_descriptor[i].index != UINT8_MAX)
1350 return true;
1351 }
1352
1353 return false;
1354 }
1355
1356 static void
1357 emit_3dstate_wm(struct anv_pipeline *pipeline, struct anv_subpass *subpass,
1358 const VkPipelineMultisampleStateCreateInfo *multisample)
1359 {
1360 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1361
1362 MAYBE_UNUSED uint32_t samples =
1363 multisample ? multisample->rasterizationSamples : 1;
1364
1365 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_WM), wm) {
1366 wm.StatisticsEnable = true;
1367 wm.LineEndCapAntialiasingRegionWidth = _05pixels;
1368 wm.LineAntialiasingRegionWidth = _10pixels;
1369 wm.PointRasterizationRule = RASTRULE_UPPER_RIGHT;
1370
1371 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1372 if (wm_prog_data->early_fragment_tests) {
1373 wm.EarlyDepthStencilControl = EDSC_PREPS;
1374 } else if (wm_prog_data->has_side_effects) {
1375 wm.EarlyDepthStencilControl = EDSC_PSEXEC;
1376 } else {
1377 wm.EarlyDepthStencilControl = EDSC_NORMAL;
1378 }
1379
1380 wm.BarycentricInterpolationMode =
1381 wm_prog_data->barycentric_interp_modes;
1382
1383 #if GEN_GEN < 8
1384 wm.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
1385 wm.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
1386 wm.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
1387 wm.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
1388
1389 /* If the subpass has a depth or stencil self-dependency, then we
1390 * need to force the hardware to do the depth/stencil write *after*
1391 * fragment shader execution. Otherwise, the writes may hit memory
1392 * before we get around to fetching from the input attachment and we
1393 * may get the depth or stencil value from the current draw rather
1394 * than the previous one.
1395 */
1396 wm.PixelShaderKillsPixel = subpass->has_ds_self_dep ||
1397 wm_prog_data->uses_kill;
1398
1399 if (wm.PixelShaderComputedDepthMode != PSCDEPTH_OFF ||
1400 wm_prog_data->has_side_effects ||
1401 wm.PixelShaderKillsPixel ||
1402 has_color_buffer_write_enabled(pipeline))
1403 wm.ThreadDispatchEnable = true;
1404
1405 if (samples > 1) {
1406 wm.MultisampleRasterizationMode = MSRASTMODE_ON_PATTERN;
1407 if (wm_prog_data->persample_dispatch) {
1408 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1409 } else {
1410 wm.MultisampleDispatchMode = MSDISPMODE_PERPIXEL;
1411 }
1412 } else {
1413 wm.MultisampleRasterizationMode = MSRASTMODE_OFF_PIXEL;
1414 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1415 }
1416 #endif
1417 }
1418 }
1419 }
1420
1421 static bool
1422 is_dual_src_blend_factor(VkBlendFactor factor)
1423 {
1424 return factor == VK_BLEND_FACTOR_SRC1_COLOR ||
1425 factor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR ||
1426 factor == VK_BLEND_FACTOR_SRC1_ALPHA ||
1427 factor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA;
1428 }
1429
1430 static void
1431 emit_3dstate_ps(struct anv_pipeline *pipeline,
1432 const VkPipelineColorBlendStateCreateInfo *blend)
1433 {
1434 MAYBE_UNUSED const struct gen_device_info *devinfo = &pipeline->device->info;
1435 const struct anv_shader_bin *fs_bin =
1436 pipeline->shaders[MESA_SHADER_FRAGMENT];
1437
1438 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1439 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS), ps) {
1440 #if GEN_GEN == 7
1441 /* Even if no fragments are ever dispatched, gen7 hardware hangs if
1442 * we don't at least set the maximum number of threads.
1443 */
1444 ps.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
1445 #endif
1446 }
1447 return;
1448 }
1449
1450 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1451
1452 #if GEN_GEN < 8
1453 /* The hardware wedges if you have this bit set but don't turn on any dual
1454 * source blend factors.
1455 */
1456 bool dual_src_blend = false;
1457 if (wm_prog_data->dual_src_blend && blend) {
1458 for (uint32_t i = 0; i < blend->attachmentCount; i++) {
1459 const VkPipelineColorBlendAttachmentState *bstate =
1460 &blend->pAttachments[i];
1461
1462 if (bstate->blendEnable &&
1463 (is_dual_src_blend_factor(bstate->srcColorBlendFactor) ||
1464 is_dual_src_blend_factor(bstate->dstColorBlendFactor) ||
1465 is_dual_src_blend_factor(bstate->srcAlphaBlendFactor) ||
1466 is_dual_src_blend_factor(bstate->dstAlphaBlendFactor))) {
1467 dual_src_blend = true;
1468 break;
1469 }
1470 }
1471 }
1472 #endif
1473
1474 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS), ps) {
1475 ps.KernelStartPointer0 = fs_bin->kernel.offset;
1476 ps.KernelStartPointer1 = 0;
1477 ps.KernelStartPointer2 = fs_bin->kernel.offset +
1478 wm_prog_data->prog_offset_2;
1479 ps._8PixelDispatchEnable = wm_prog_data->dispatch_8;
1480 ps._16PixelDispatchEnable = wm_prog_data->dispatch_16;
1481 ps._32PixelDispatchEnable = false;
1482
1483 ps.SingleProgramFlow = false;
1484 ps.VectorMaskEnable = true;
1485 ps.SamplerCount = get_sampler_count(fs_bin);
1486 ps.BindingTableEntryCount = get_binding_table_entry_count(fs_bin);
1487 ps.PushConstantEnable = wm_prog_data->base.nr_params > 0;
1488 ps.PositionXYOffsetSelect = wm_prog_data->uses_pos_offset ?
1489 POSOFFSET_SAMPLE: POSOFFSET_NONE;
1490 #if GEN_GEN < 8
1491 ps.AttributeEnable = wm_prog_data->num_varying_inputs > 0;
1492 ps.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
1493 ps.DualSourceBlendEnable = dual_src_blend;
1494 #endif
1495
1496 #if GEN_IS_HASWELL
1497 /* Haswell requires the sample mask to be set in this packet as well
1498 * as in 3DSTATE_SAMPLE_MASK; the values should match.
1499 */
1500 ps.SampleMask = 0xff;
1501 #endif
1502
1503 #if GEN_GEN >= 9
1504 ps.MaximumNumberofThreadsPerPSD = 64 - 1;
1505 #elif GEN_GEN >= 8
1506 ps.MaximumNumberofThreadsPerPSD = 64 - 2;
1507 #else
1508 ps.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
1509 #endif
1510
1511 ps.DispatchGRFStartRegisterForConstantSetupData0 =
1512 wm_prog_data->base.dispatch_grf_start_reg;
1513 ps.DispatchGRFStartRegisterForConstantSetupData1 = 0;
1514 ps.DispatchGRFStartRegisterForConstantSetupData2 =
1515 wm_prog_data->dispatch_grf_start_reg_2;
1516
1517 ps.PerThreadScratchSpace = get_scratch_space(fs_bin);
1518 ps.ScratchSpaceBasePointer =
1519 get_scratch_address(pipeline, MESA_SHADER_FRAGMENT, fs_bin);
1520 }
1521 }
1522
1523 #if GEN_GEN >= 8
1524 static void
1525 emit_3dstate_ps_extra(struct anv_pipeline *pipeline,
1526 struct anv_subpass *subpass)
1527 {
1528 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1529
1530 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1531 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS_EXTRA), ps);
1532 return;
1533 }
1534
1535 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS_EXTRA), ps) {
1536 ps.PixelShaderValid = true;
1537 ps.AttributeEnable = wm_prog_data->num_varying_inputs > 0;
1538 ps.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
1539 ps.PixelShaderIsPerSample = wm_prog_data->persample_dispatch;
1540 ps.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
1541 ps.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
1542 ps.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
1543
1544 /* If the subpass has a depth or stencil self-dependency, then we need
1545 * to force the hardware to do the depth/stencil write *after* fragment
1546 * shader execution. Otherwise, the writes may hit memory before we get
1547 * around to fetching from the input attachment and we may get the depth
1548 * or stencil value from the current draw rather than the previous one.
1549 */
1550 ps.PixelShaderKillsPixel = subpass->has_ds_self_dep ||
1551 wm_prog_data->uses_kill;
1552
1553 /* The stricter cross-primitive coherency guarantees that the hardware
1554 * gives us with the "Accesses UAV" bit set for at least one shader stage
1555 * and the "UAV coherency required" bit set on the 3DPRIMITIVE command are
1556 * redundant within the current image, atomic counter and SSBO GL APIs,
1557 * which all have very loose ordering and coherency requirements and
1558 * generally rely on the application to insert explicit barriers when a
1559 * shader invocation is expected to see the memory writes performed by the
1560 * invocations of some previous primitive. Regardless of the value of
1561 * "UAV coherency required", the "Accesses UAV" bits will implicitly cause
1562 * an in most cases useless DC flush when the lowermost stage with the bit
1563 * set finishes execution.
1564 *
1565 * It would be nice to disable it, but in some cases we can't because on
1566 * Gen8+ it also has an influence on rasterization via the PS UAV-only
1567 * signal (which could be set independently from the coherency mechanism
1568 * in the 3DSTATE_WM command on Gen7), and because in some cases it will
1569 * determine whether the hardware skips execution of the fragment shader
1570 * or not via the ThreadDispatchEnable signal. However if we know that
1571 * GEN8_PS_BLEND_HAS_WRITEABLE_RT is going to be set and
1572 * GEN8_PSX_PIXEL_SHADER_NO_RT_WRITE is not set it shouldn't make any
1573 * difference so we may just disable it here.
1574 *
1575 * Gen8 hardware tries to compute ThreadDispatchEnable for us but doesn't
1576 * take into account KillPixels when no depth or stencil writes are
1577 * enabled. In order for occlusion queries to work correctly with no
1578 * attachments, we need to force-enable here.
1579 */
1580 if ((wm_prog_data->has_side_effects || wm_prog_data->uses_kill) &&
1581 !has_color_buffer_write_enabled(pipeline))
1582 ps.PixelShaderHasUAV = true;
1583
1584 #if GEN_GEN >= 9
1585 ps.PixelShaderPullsBary = wm_prog_data->pulls_bary;
1586 ps.InputCoverageMaskState = wm_prog_data->uses_sample_mask ?
1587 ICMS_INNER_CONSERVATIVE : ICMS_NONE;
1588 #else
1589 ps.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
1590 #endif
1591 }
1592 }
1593
1594 static void
1595 emit_3dstate_vf_topology(struct anv_pipeline *pipeline)
1596 {
1597 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_TOPOLOGY), vft) {
1598 vft.PrimitiveTopologyType = pipeline->topology;
1599 }
1600 }
1601 #endif
1602
1603 static void
1604 emit_3dstate_vf_statistics(struct anv_pipeline *pipeline)
1605 {
1606 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_STATISTICS), vfs) {
1607 vfs.StatisticsEnable = true;
1608 }
1609 }
1610
1611 static void
1612 compute_kill_pixel(struct anv_pipeline *pipeline,
1613 const VkPipelineMultisampleStateCreateInfo *ms_info,
1614 const struct anv_subpass *subpass)
1615 {
1616 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1617 pipeline->kill_pixel = false;
1618 return;
1619 }
1620
1621 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1622
1623 /* This computes the KillPixel portion of the computation for whether or
1624 * not we want to enable the PMA fix on gen8 or gen9. It's given by this
1625 * chunk of the giant formula:
1626 *
1627 * (3DSTATE_PS_EXTRA::PixelShaderKillsPixels ||
1628 * 3DSTATE_PS_EXTRA::oMask Present to RenderTarget ||
1629 * 3DSTATE_PS_BLEND::AlphaToCoverageEnable ||
1630 * 3DSTATE_PS_BLEND::AlphaTestEnable ||
1631 * 3DSTATE_WM_CHROMAKEY::ChromaKeyKillEnable)
1632 *
1633 * 3DSTATE_WM_CHROMAKEY::ChromaKeyKillEnable is always false and so is
1634 * 3DSTATE_PS_BLEND::AlphaTestEnable since Vulkan doesn't have a concept
1635 * of an alpha test.
1636 */
1637 pipeline->kill_pixel =
1638 subpass->has_ds_self_dep || wm_prog_data->uses_kill ||
1639 wm_prog_data->uses_omask ||
1640 (ms_info && ms_info->alphaToCoverageEnable);
1641 }
1642
1643 static VkResult
1644 genX(graphics_pipeline_create)(
1645 VkDevice _device,
1646 struct anv_pipeline_cache * cache,
1647 const VkGraphicsPipelineCreateInfo* pCreateInfo,
1648 const VkAllocationCallbacks* pAllocator,
1649 VkPipeline* pPipeline)
1650 {
1651 ANV_FROM_HANDLE(anv_device, device, _device);
1652 ANV_FROM_HANDLE(anv_render_pass, pass, pCreateInfo->renderPass);
1653 struct anv_subpass *subpass = &pass->subpasses[pCreateInfo->subpass];
1654 struct anv_pipeline *pipeline;
1655 VkResult result;
1656
1657 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
1658
1659 pipeline = vk_alloc2(&device->alloc, pAllocator, sizeof(*pipeline), 8,
1660 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1661 if (pipeline == NULL)
1662 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1663
1664 result = anv_pipeline_init(pipeline, device, cache,
1665 pCreateInfo, pAllocator);
1666 if (result != VK_SUCCESS) {
1667 vk_free2(&device->alloc, pAllocator, pipeline);
1668 return result;
1669 }
1670
1671 assert(pCreateInfo->pVertexInputState);
1672 emit_vertex_input(pipeline, pCreateInfo->pVertexInputState);
1673 assert(pCreateInfo->pRasterizationState);
1674 emit_rs_state(pipeline, pCreateInfo->pRasterizationState,
1675 pCreateInfo->pMultisampleState, pass, subpass);
1676 emit_ms_state(pipeline, pCreateInfo->pMultisampleState);
1677 emit_ds_state(pipeline, pCreateInfo->pDepthStencilState, pass, subpass);
1678 emit_cb_state(pipeline, pCreateInfo->pColorBlendState,
1679 pCreateInfo->pMultisampleState);
1680 compute_kill_pixel(pipeline, pCreateInfo->pMultisampleState, subpass);
1681
1682 emit_urb_setup(pipeline);
1683
1684 emit_3dstate_clip(pipeline, pCreateInfo->pViewportState,
1685 pCreateInfo->pRasterizationState);
1686 emit_3dstate_streamout(pipeline, pCreateInfo->pRasterizationState);
1687
1688 #if 0
1689 /* From gen7_vs_state.c */
1690
1691 /**
1692 * From Graphics BSpec: 3D-Media-GPGPU Engine > 3D Pipeline Stages >
1693 * Geometry > Geometry Shader > State:
1694 *
1695 * "Note: Because of corruption in IVB:GT2, software needs to flush the
1696 * whole fixed function pipeline when the GS enable changes value in
1697 * the 3DSTATE_GS."
1698 *
1699 * The hardware architects have clarified that in this context "flush the
1700 * whole fixed function pipeline" means to emit a PIPE_CONTROL with the "CS
1701 * Stall" bit set.
1702 */
1703 if (!brw->is_haswell && !brw->is_baytrail)
1704 gen7_emit_vs_workaround_flush(brw);
1705 #endif
1706
1707 emit_3dstate_vs(pipeline);
1708 emit_3dstate_hs_te_ds(pipeline);
1709 emit_3dstate_gs(pipeline);
1710 emit_3dstate_sbe(pipeline);
1711 emit_3dstate_wm(pipeline, subpass, pCreateInfo->pMultisampleState);
1712 emit_3dstate_ps(pipeline, pCreateInfo->pColorBlendState);
1713 #if GEN_GEN >= 8
1714 emit_3dstate_ps_extra(pipeline, subpass);
1715 emit_3dstate_vf_topology(pipeline);
1716 #endif
1717 emit_3dstate_vf_statistics(pipeline);
1718
1719 *pPipeline = anv_pipeline_to_handle(pipeline);
1720
1721 return pipeline->batch.status;
1722 }
1723
1724 static VkResult
1725 compute_pipeline_create(
1726 VkDevice _device,
1727 struct anv_pipeline_cache * cache,
1728 const VkComputePipelineCreateInfo* pCreateInfo,
1729 const VkAllocationCallbacks* pAllocator,
1730 VkPipeline* pPipeline)
1731 {
1732 ANV_FROM_HANDLE(anv_device, device, _device);
1733 const struct anv_physical_device *physical_device =
1734 &device->instance->physicalDevice;
1735 const struct gen_device_info *devinfo = &physical_device->info;
1736 struct anv_pipeline *pipeline;
1737 VkResult result;
1738
1739 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO);
1740
1741 pipeline = vk_alloc2(&device->alloc, pAllocator, sizeof(*pipeline), 8,
1742 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1743 if (pipeline == NULL)
1744 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1745
1746 pipeline->device = device;
1747 pipeline->layout = anv_pipeline_layout_from_handle(pCreateInfo->layout);
1748
1749 pipeline->blend_state.map = NULL;
1750
1751 result = anv_reloc_list_init(&pipeline->batch_relocs,
1752 pAllocator ? pAllocator : &device->alloc);
1753 if (result != VK_SUCCESS) {
1754 vk_free2(&device->alloc, pAllocator, pipeline);
1755 return result;
1756 }
1757 pipeline->batch.next = pipeline->batch.start = pipeline->batch_data;
1758 pipeline->batch.end = pipeline->batch.start + sizeof(pipeline->batch_data);
1759 pipeline->batch.relocs = &pipeline->batch_relocs;
1760 pipeline->batch.status = VK_SUCCESS;
1761
1762 /* When we free the pipeline, we detect stages based on the NULL status
1763 * of various prog_data pointers. Make them NULL by default.
1764 */
1765 memset(pipeline->shaders, 0, sizeof(pipeline->shaders));
1766
1767 pipeline->active_stages = 0;
1768
1769 pipeline->needs_data_cache = false;
1770
1771 assert(pCreateInfo->stage.stage == VK_SHADER_STAGE_COMPUTE_BIT);
1772 ANV_FROM_HANDLE(anv_shader_module, module, pCreateInfo->stage.module);
1773 result = anv_pipeline_compile_cs(pipeline, cache, pCreateInfo, module,
1774 pCreateInfo->stage.pName,
1775 pCreateInfo->stage.pSpecializationInfo);
1776 if (result != VK_SUCCESS) {
1777 vk_free2(&device->alloc, pAllocator, pipeline);
1778 return result;
1779 }
1780
1781 const struct brw_cs_prog_data *cs_prog_data = get_cs_prog_data(pipeline);
1782
1783 anv_pipeline_setup_l3_config(pipeline, cs_prog_data->base.total_shared > 0);
1784
1785 uint32_t group_size = cs_prog_data->local_size[0] *
1786 cs_prog_data->local_size[1] * cs_prog_data->local_size[2];
1787 uint32_t remainder = group_size & (cs_prog_data->simd_size - 1);
1788
1789 if (remainder > 0)
1790 pipeline->cs_right_mask = ~0u >> (32 - remainder);
1791 else
1792 pipeline->cs_right_mask = ~0u >> (32 - cs_prog_data->simd_size);
1793
1794 const uint32_t vfe_curbe_allocation =
1795 ALIGN(cs_prog_data->push.per_thread.regs * cs_prog_data->threads +
1796 cs_prog_data->push.cross_thread.regs, 2);
1797
1798 const uint32_t subslices = MAX2(physical_device->subslice_total, 1);
1799
1800 const struct anv_shader_bin *cs_bin =
1801 pipeline->shaders[MESA_SHADER_COMPUTE];
1802
1803 anv_batch_emit(&pipeline->batch, GENX(MEDIA_VFE_STATE), vfe) {
1804 #if GEN_GEN > 7
1805 vfe.StackSize = 0;
1806 #else
1807 vfe.GPGPUMode = true;
1808 #endif
1809 vfe.MaximumNumberofThreads =
1810 devinfo->max_cs_threads * subslices - 1;
1811 vfe.NumberofURBEntries = GEN_GEN <= 7 ? 0 : 2;
1812 vfe.ResetGatewayTimer = true;
1813 #if GEN_GEN <= 8
1814 vfe.BypassGatewayControl = true;
1815 #endif
1816 vfe.URBEntryAllocationSize = GEN_GEN <= 7 ? 0 : 2;
1817 vfe.CURBEAllocationSize = vfe_curbe_allocation;
1818
1819 vfe.PerThreadScratchSpace = get_scratch_space(cs_bin);
1820 vfe.ScratchSpaceBasePointer =
1821 get_scratch_address(pipeline, MESA_SHADER_COMPUTE, cs_bin);
1822 }
1823
1824 struct GENX(INTERFACE_DESCRIPTOR_DATA) desc = {
1825 .KernelStartPointer = cs_bin->kernel.offset,
1826
1827 .SamplerCount = get_sampler_count(cs_bin),
1828 .BindingTableEntryCount = get_binding_table_entry_count(cs_bin),
1829 .BarrierEnable = cs_prog_data->uses_barrier,
1830 .SharedLocalMemorySize =
1831 encode_slm_size(GEN_GEN, cs_prog_data->base.total_shared),
1832
1833 #if !GEN_IS_HASWELL
1834 .ConstantURBEntryReadOffset = 0,
1835 #endif
1836 .ConstantURBEntryReadLength = cs_prog_data->push.per_thread.regs,
1837 #if GEN_GEN >= 8 || GEN_IS_HASWELL
1838 .CrossThreadConstantDataReadLength =
1839 cs_prog_data->push.cross_thread.regs,
1840 #endif
1841
1842 .NumberofThreadsinGPGPUThreadGroup = cs_prog_data->threads,
1843 };
1844 GENX(INTERFACE_DESCRIPTOR_DATA_pack)(NULL,
1845 pipeline->interface_descriptor_data,
1846 &desc);
1847
1848 *pPipeline = anv_pipeline_to_handle(pipeline);
1849
1850 return pipeline->batch.status;
1851 }
1852
1853 VkResult genX(CreateGraphicsPipelines)(
1854 VkDevice _device,
1855 VkPipelineCache pipelineCache,
1856 uint32_t count,
1857 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1858 const VkAllocationCallbacks* pAllocator,
1859 VkPipeline* pPipelines)
1860 {
1861 ANV_FROM_HANDLE(anv_pipeline_cache, pipeline_cache, pipelineCache);
1862
1863 VkResult result = VK_SUCCESS;
1864
1865 unsigned i;
1866 for (i = 0; i < count; i++) {
1867 result = genX(graphics_pipeline_create)(_device,
1868 pipeline_cache,
1869 &pCreateInfos[i],
1870 pAllocator, &pPipelines[i]);
1871
1872 /* Bail out on the first error as it is not obvious what error should be
1873 * report upon 2 different failures. */
1874 if (result != VK_SUCCESS)
1875 break;
1876 }
1877
1878 for (; i < count; i++)
1879 pPipelines[i] = VK_NULL_HANDLE;
1880
1881 return result;
1882 }
1883
1884 VkResult genX(CreateComputePipelines)(
1885 VkDevice _device,
1886 VkPipelineCache pipelineCache,
1887 uint32_t count,
1888 const VkComputePipelineCreateInfo* pCreateInfos,
1889 const VkAllocationCallbacks* pAllocator,
1890 VkPipeline* pPipelines)
1891 {
1892 ANV_FROM_HANDLE(anv_pipeline_cache, pipeline_cache, pipelineCache);
1893
1894 VkResult result = VK_SUCCESS;
1895
1896 unsigned i;
1897 for (i = 0; i < count; i++) {
1898 result = compute_pipeline_create(_device, pipeline_cache,
1899 &pCreateInfos[i],
1900 pAllocator, &pPipelines[i]);
1901
1902 /* Bail out on the first error as it is not obvious what error should be
1903 * report upon 2 different failures. */
1904 if (result != VK_SUCCESS)
1905 break;
1906 }
1907
1908 for (; i < count; i++)
1909 pPipelines[i] = VK_NULL_HANDLE;
1910
1911 return result;
1912 }