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