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