radeonsi/nir: implement FBFETCH for KHR_blend_equation_advanced
[mesa.git] / src / gallium / drivers / radeonsi / si_shader.c
1 /*
2 * Copyright 2012 Advanced Micro Devices, Inc.
3 * All Rights Reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * on the rights to use, copy, modify, merge, publish, distribute, sub
9 * license, and/or sell copies of the Software, and to permit persons to whom
10 * the Software is furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice (including the next
13 * paragraph) shall be included in all copies or substantial portions of the
14 * Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
20 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22 * USE OR OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25 #include "util/u_memory.h"
26 #include "util/u_string.h"
27 #include "tgsi/tgsi_build.h"
28 #include "tgsi/tgsi_strings.h"
29 #include "tgsi/tgsi_util.h"
30 #include "tgsi/tgsi_dump.h"
31 #include "tgsi/tgsi_from_mesa.h"
32
33 #include "ac_binary.h"
34 #include "ac_exp_param.h"
35 #include "ac_shader_util.h"
36 #include "ac_rtld.h"
37 #include "ac_llvm_util.h"
38 #include "si_shader_internal.h"
39 #include "si_pipe.h"
40 #include "sid.h"
41
42 #include "compiler/nir/nir.h"
43
44 static const char scratch_rsrc_dword0_symbol[] =
45 "SCRATCH_RSRC_DWORD0";
46
47 static const char scratch_rsrc_dword1_symbol[] =
48 "SCRATCH_RSRC_DWORD1";
49
50 static void si_init_shader_ctx(struct si_shader_context *ctx,
51 struct si_screen *sscreen,
52 struct ac_llvm_compiler *compiler,
53 unsigned wave_size);
54
55 static void si_llvm_emit_barrier(const struct lp_build_tgsi_action *action,
56 struct lp_build_tgsi_context *bld_base,
57 struct lp_build_emit_data *emit_data);
58
59 static void si_dump_shader_key(const struct si_shader *shader, FILE *f);
60
61 static void si_build_vs_prolog_function(struct si_shader_context *ctx,
62 union si_shader_part_key *key);
63 static void si_build_tcs_epilog_function(struct si_shader_context *ctx,
64 union si_shader_part_key *key);
65 static void si_build_ps_prolog_function(struct si_shader_context *ctx,
66 union si_shader_part_key *key);
67 static void si_build_ps_epilog_function(struct si_shader_context *ctx,
68 union si_shader_part_key *key);
69 static void si_fix_resource_usage(struct si_screen *sscreen,
70 struct si_shader *shader);
71
72 /* Ideally pass the sample mask input to the PS epilog as v14, which
73 * is its usual location, so that the shader doesn't have to add v_mov.
74 */
75 #define PS_EPILOG_SAMPLEMASK_MIN_LOC 14
76
77 static bool llvm_type_is_64bit(struct si_shader_context *ctx,
78 LLVMTypeRef type)
79 {
80 if (type == ctx->ac.i64 || type == ctx->ac.f64)
81 return true;
82
83 return false;
84 }
85
86 /** Whether the shader runs as a combination of multiple API shaders */
87 static bool is_multi_part_shader(struct si_shader_context *ctx)
88 {
89 if (ctx->screen->info.chip_class <= GFX8)
90 return false;
91
92 return ctx->shader->key.as_ls ||
93 ctx->shader->key.as_es ||
94 ctx->type == PIPE_SHADER_TESS_CTRL ||
95 ctx->type == PIPE_SHADER_GEOMETRY;
96 }
97
98 /** Whether the shader runs on a merged HW stage (LSHS or ESGS) */
99 static bool is_merged_shader(struct si_shader_context *ctx)
100 {
101 return ctx->shader->key.as_ngg || is_multi_part_shader(ctx);
102 }
103
104 void si_init_function_info(struct si_function_info *fninfo)
105 {
106 fninfo->num_params = 0;
107 fninfo->num_sgpr_params = 0;
108 }
109
110 unsigned add_arg_assign(struct si_function_info *fninfo,
111 enum si_arg_regfile regfile, LLVMTypeRef type,
112 LLVMValueRef *assign)
113 {
114 assert(regfile != ARG_SGPR || fninfo->num_sgpr_params == fninfo->num_params);
115
116 unsigned idx = fninfo->num_params++;
117 assert(idx < ARRAY_SIZE(fninfo->types));
118
119 if (regfile == ARG_SGPR)
120 fninfo->num_sgpr_params = fninfo->num_params;
121
122 fninfo->types[idx] = type;
123 fninfo->assign[idx] = assign;
124 return idx;
125 }
126
127 static unsigned add_arg(struct si_function_info *fninfo,
128 enum si_arg_regfile regfile, LLVMTypeRef type)
129 {
130 return add_arg_assign(fninfo, regfile, type, NULL);
131 }
132
133 static void add_arg_assign_checked(struct si_function_info *fninfo,
134 enum si_arg_regfile regfile, LLVMTypeRef type,
135 LLVMValueRef *assign, unsigned idx)
136 {
137 MAYBE_UNUSED unsigned actual = add_arg_assign(fninfo, regfile, type, assign);
138 assert(actual == idx);
139 }
140
141 static void add_arg_checked(struct si_function_info *fninfo,
142 enum si_arg_regfile regfile, LLVMTypeRef type,
143 unsigned idx)
144 {
145 add_arg_assign_checked(fninfo, regfile, type, NULL, idx);
146 }
147
148 /**
149 * Returns a unique index for a per-patch semantic name and index. The index
150 * must be less than 32, so that a 32-bit bitmask of used inputs or outputs
151 * can be calculated.
152 */
153 unsigned si_shader_io_get_unique_index_patch(unsigned semantic_name, unsigned index)
154 {
155 switch (semantic_name) {
156 case TGSI_SEMANTIC_TESSOUTER:
157 return 0;
158 case TGSI_SEMANTIC_TESSINNER:
159 return 1;
160 case TGSI_SEMANTIC_PATCH:
161 assert(index < 30);
162 return 2 + index;
163
164 default:
165 assert(!"invalid semantic name");
166 return 0;
167 }
168 }
169
170 /**
171 * Returns a unique index for a semantic name and index. The index must be
172 * less than 64, so that a 64-bit bitmask of used inputs or outputs can be
173 * calculated.
174 */
175 unsigned si_shader_io_get_unique_index(unsigned semantic_name, unsigned index,
176 unsigned is_varying)
177 {
178 switch (semantic_name) {
179 case TGSI_SEMANTIC_POSITION:
180 return 0;
181 case TGSI_SEMANTIC_GENERIC:
182 /* Since some shader stages use the the highest used IO index
183 * to determine the size to allocate for inputs/outputs
184 * (in LDS, tess and GS rings). GENERIC should be placed right
185 * after POSITION to make that size as small as possible.
186 */
187 if (index < SI_MAX_IO_GENERIC)
188 return 1 + index;
189
190 assert(!"invalid generic index");
191 return 0;
192 case TGSI_SEMANTIC_FOG:
193 return SI_MAX_IO_GENERIC + 1;
194 case TGSI_SEMANTIC_COLOR:
195 assert(index < 2);
196 return SI_MAX_IO_GENERIC + 2 + index;
197 case TGSI_SEMANTIC_BCOLOR:
198 assert(index < 2);
199 /* If it's a varying, COLOR and BCOLOR alias. */
200 if (is_varying)
201 return SI_MAX_IO_GENERIC + 2 + index;
202 else
203 return SI_MAX_IO_GENERIC + 4 + index;
204 case TGSI_SEMANTIC_TEXCOORD:
205 assert(index < 8);
206 return SI_MAX_IO_GENERIC + 6 + index;
207
208 /* These are rarely used between LS and HS or ES and GS. */
209 case TGSI_SEMANTIC_CLIPDIST:
210 assert(index < 2);
211 return SI_MAX_IO_GENERIC + 6 + 8 + index;
212 case TGSI_SEMANTIC_CLIPVERTEX:
213 return SI_MAX_IO_GENERIC + 6 + 8 + 2;
214 case TGSI_SEMANTIC_PSIZE:
215 return SI_MAX_IO_GENERIC + 6 + 8 + 3;
216
217 /* These can't be written by LS, HS, and ES. */
218 case TGSI_SEMANTIC_LAYER:
219 return SI_MAX_IO_GENERIC + 6 + 8 + 4;
220 case TGSI_SEMANTIC_VIEWPORT_INDEX:
221 return SI_MAX_IO_GENERIC + 6 + 8 + 5;
222 case TGSI_SEMANTIC_PRIMID:
223 STATIC_ASSERT(SI_MAX_IO_GENERIC + 6 + 8 + 6 <= 63);
224 return SI_MAX_IO_GENERIC + 6 + 8 + 6;
225 default:
226 fprintf(stderr, "invalid semantic name = %u\n", semantic_name);
227 assert(!"invalid semantic name");
228 return 0;
229 }
230 }
231
232 /**
233 * Get the value of a shader input parameter and extract a bitfield.
234 */
235 static LLVMValueRef unpack_llvm_param(struct si_shader_context *ctx,
236 LLVMValueRef value, unsigned rshift,
237 unsigned bitwidth)
238 {
239 if (LLVMGetTypeKind(LLVMTypeOf(value)) == LLVMFloatTypeKind)
240 value = ac_to_integer(&ctx->ac, value);
241
242 if (rshift)
243 value = LLVMBuildLShr(ctx->ac.builder, value,
244 LLVMConstInt(ctx->i32, rshift, 0), "");
245
246 if (rshift + bitwidth < 32) {
247 unsigned mask = (1 << bitwidth) - 1;
248 value = LLVMBuildAnd(ctx->ac.builder, value,
249 LLVMConstInt(ctx->i32, mask, 0), "");
250 }
251
252 return value;
253 }
254
255 LLVMValueRef si_unpack_param(struct si_shader_context *ctx,
256 unsigned param, unsigned rshift,
257 unsigned bitwidth)
258 {
259 LLVMValueRef value = LLVMGetParam(ctx->main_fn, param);
260
261 return unpack_llvm_param(ctx, value, rshift, bitwidth);
262 }
263
264 static LLVMValueRef get_rel_patch_id(struct si_shader_context *ctx)
265 {
266 switch (ctx->type) {
267 case PIPE_SHADER_TESS_CTRL:
268 return unpack_llvm_param(ctx, ctx->abi.tcs_rel_ids, 0, 8);
269
270 case PIPE_SHADER_TESS_EVAL:
271 return LLVMGetParam(ctx->main_fn,
272 ctx->param_tes_rel_patch_id);
273
274 default:
275 assert(0);
276 return NULL;
277 }
278 }
279
280 /* Tessellation shaders pass outputs to the next shader using LDS.
281 *
282 * LS outputs = TCS inputs
283 * TCS outputs = TES inputs
284 *
285 * The LDS layout is:
286 * - TCS inputs for patch 0
287 * - TCS inputs for patch 1
288 * - TCS inputs for patch 2 = get_tcs_in_current_patch_offset (if RelPatchID==2)
289 * - ...
290 * - TCS outputs for patch 0 = get_tcs_out_patch0_offset
291 * - Per-patch TCS outputs for patch 0 = get_tcs_out_patch0_patch_data_offset
292 * - TCS outputs for patch 1
293 * - Per-patch TCS outputs for patch 1
294 * - TCS outputs for patch 2 = get_tcs_out_current_patch_offset (if RelPatchID==2)
295 * - Per-patch TCS outputs for patch 2 = get_tcs_out_current_patch_data_offset (if RelPatchID==2)
296 * - ...
297 *
298 * All three shaders VS(LS), TCS, TES share the same LDS space.
299 */
300
301 static LLVMValueRef
302 get_tcs_in_patch_stride(struct si_shader_context *ctx)
303 {
304 return si_unpack_param(ctx, ctx->param_vs_state_bits, 8, 13);
305 }
306
307 static unsigned get_tcs_out_vertex_dw_stride_constant(struct si_shader_context *ctx)
308 {
309 assert(ctx->type == PIPE_SHADER_TESS_CTRL);
310
311 if (ctx->shader->key.mono.u.ff_tcs_inputs_to_copy)
312 return util_last_bit64(ctx->shader->key.mono.u.ff_tcs_inputs_to_copy) * 4;
313
314 return util_last_bit64(ctx->shader->selector->outputs_written) * 4;
315 }
316
317 static LLVMValueRef get_tcs_out_vertex_dw_stride(struct si_shader_context *ctx)
318 {
319 unsigned stride = get_tcs_out_vertex_dw_stride_constant(ctx);
320
321 return LLVMConstInt(ctx->i32, stride, 0);
322 }
323
324 static LLVMValueRef get_tcs_out_patch_stride(struct si_shader_context *ctx)
325 {
326 if (ctx->shader->key.mono.u.ff_tcs_inputs_to_copy)
327 return si_unpack_param(ctx, ctx->param_tcs_out_lds_layout, 0, 13);
328
329 const struct tgsi_shader_info *info = &ctx->shader->selector->info;
330 unsigned tcs_out_vertices = info->properties[TGSI_PROPERTY_TCS_VERTICES_OUT];
331 unsigned vertex_dw_stride = get_tcs_out_vertex_dw_stride_constant(ctx);
332 unsigned num_patch_outputs = util_last_bit64(ctx->shader->selector->patch_outputs_written);
333 unsigned patch_dw_stride = tcs_out_vertices * vertex_dw_stride +
334 num_patch_outputs * 4;
335 return LLVMConstInt(ctx->i32, patch_dw_stride, 0);
336 }
337
338 static LLVMValueRef
339 get_tcs_out_patch0_offset(struct si_shader_context *ctx)
340 {
341 return LLVMBuildMul(ctx->ac.builder,
342 si_unpack_param(ctx,
343 ctx->param_tcs_out_lds_offsets,
344 0, 16),
345 LLVMConstInt(ctx->i32, 4, 0), "");
346 }
347
348 static LLVMValueRef
349 get_tcs_out_patch0_patch_data_offset(struct si_shader_context *ctx)
350 {
351 return LLVMBuildMul(ctx->ac.builder,
352 si_unpack_param(ctx,
353 ctx->param_tcs_out_lds_offsets,
354 16, 16),
355 LLVMConstInt(ctx->i32, 4, 0), "");
356 }
357
358 static LLVMValueRef
359 get_tcs_in_current_patch_offset(struct si_shader_context *ctx)
360 {
361 LLVMValueRef patch_stride = get_tcs_in_patch_stride(ctx);
362 LLVMValueRef rel_patch_id = get_rel_patch_id(ctx);
363
364 return LLVMBuildMul(ctx->ac.builder, patch_stride, rel_patch_id, "");
365 }
366
367 static LLVMValueRef
368 get_tcs_out_current_patch_offset(struct si_shader_context *ctx)
369 {
370 LLVMValueRef patch0_offset = get_tcs_out_patch0_offset(ctx);
371 LLVMValueRef patch_stride = get_tcs_out_patch_stride(ctx);
372 LLVMValueRef rel_patch_id = get_rel_patch_id(ctx);
373
374 return ac_build_imad(&ctx->ac, patch_stride, rel_patch_id, patch0_offset);
375 }
376
377 static LLVMValueRef
378 get_tcs_out_current_patch_data_offset(struct si_shader_context *ctx)
379 {
380 LLVMValueRef patch0_patch_data_offset =
381 get_tcs_out_patch0_patch_data_offset(ctx);
382 LLVMValueRef patch_stride = get_tcs_out_patch_stride(ctx);
383 LLVMValueRef rel_patch_id = get_rel_patch_id(ctx);
384
385 return ac_build_imad(&ctx->ac, patch_stride, rel_patch_id, patch0_patch_data_offset);
386 }
387
388 static LLVMValueRef get_num_tcs_out_vertices(struct si_shader_context *ctx)
389 {
390 unsigned tcs_out_vertices =
391 ctx->shader->selector ?
392 ctx->shader->selector->info.properties[TGSI_PROPERTY_TCS_VERTICES_OUT] : 0;
393
394 /* If !tcs_out_vertices, it's either the fixed-func TCS or the TCS epilog. */
395 if (ctx->type == PIPE_SHADER_TESS_CTRL && tcs_out_vertices)
396 return LLVMConstInt(ctx->i32, tcs_out_vertices, 0);
397
398 return si_unpack_param(ctx, ctx->param_tcs_offchip_layout, 6, 6);
399 }
400
401 static LLVMValueRef get_tcs_in_vertex_dw_stride(struct si_shader_context *ctx)
402 {
403 unsigned stride;
404
405 switch (ctx->type) {
406 case PIPE_SHADER_VERTEX:
407 stride = ctx->shader->selector->lshs_vertex_stride / 4;
408 return LLVMConstInt(ctx->i32, stride, 0);
409
410 case PIPE_SHADER_TESS_CTRL:
411 if (ctx->screen->info.chip_class >= GFX9 &&
412 ctx->shader->is_monolithic) {
413 stride = ctx->shader->key.part.tcs.ls->lshs_vertex_stride / 4;
414 return LLVMConstInt(ctx->i32, stride, 0);
415 }
416 return si_unpack_param(ctx, ctx->param_vs_state_bits, 24, 8);
417
418 default:
419 assert(0);
420 return NULL;
421 }
422 }
423
424 static LLVMValueRef unpack_sint16(struct si_shader_context *ctx,
425 LLVMValueRef i32, unsigned index)
426 {
427 assert(index <= 1);
428
429 if (index == 1)
430 return LLVMBuildAShr(ctx->ac.builder, i32,
431 LLVMConstInt(ctx->i32, 16, 0), "");
432
433 return LLVMBuildSExt(ctx->ac.builder,
434 LLVMBuildTrunc(ctx->ac.builder, i32,
435 ctx->ac.i16, ""),
436 ctx->i32, "");
437 }
438
439 void si_llvm_load_input_vs(
440 struct si_shader_context *ctx,
441 unsigned input_index,
442 LLVMValueRef out[4])
443 {
444 const struct tgsi_shader_info *info = &ctx->shader->selector->info;
445 unsigned vs_blit_property = info->properties[TGSI_PROPERTY_VS_BLIT_SGPRS];
446
447 if (vs_blit_property) {
448 LLVMValueRef vertex_id = ctx->abi.vertex_id;
449 LLVMValueRef sel_x1 = LLVMBuildICmp(ctx->ac.builder,
450 LLVMIntULE, vertex_id,
451 ctx->i32_1, "");
452 /* Use LLVMIntNE, because we have 3 vertices and only
453 * the middle one should use y2.
454 */
455 LLVMValueRef sel_y1 = LLVMBuildICmp(ctx->ac.builder,
456 LLVMIntNE, vertex_id,
457 ctx->i32_1, "");
458
459 if (input_index == 0) {
460 /* Position: */
461 LLVMValueRef x1y1 = LLVMGetParam(ctx->main_fn,
462 ctx->param_vs_blit_inputs);
463 LLVMValueRef x2y2 = LLVMGetParam(ctx->main_fn,
464 ctx->param_vs_blit_inputs + 1);
465
466 LLVMValueRef x1 = unpack_sint16(ctx, x1y1, 0);
467 LLVMValueRef y1 = unpack_sint16(ctx, x1y1, 1);
468 LLVMValueRef x2 = unpack_sint16(ctx, x2y2, 0);
469 LLVMValueRef y2 = unpack_sint16(ctx, x2y2, 1);
470
471 LLVMValueRef x = LLVMBuildSelect(ctx->ac.builder, sel_x1,
472 x1, x2, "");
473 LLVMValueRef y = LLVMBuildSelect(ctx->ac.builder, sel_y1,
474 y1, y2, "");
475
476 out[0] = LLVMBuildSIToFP(ctx->ac.builder, x, ctx->f32, "");
477 out[1] = LLVMBuildSIToFP(ctx->ac.builder, y, ctx->f32, "");
478 out[2] = LLVMGetParam(ctx->main_fn,
479 ctx->param_vs_blit_inputs + 2);
480 out[3] = ctx->ac.f32_1;
481 return;
482 }
483
484 /* Color or texture coordinates: */
485 assert(input_index == 1);
486
487 if (vs_blit_property == SI_VS_BLIT_SGPRS_POS_COLOR) {
488 for (int i = 0; i < 4; i++) {
489 out[i] = LLVMGetParam(ctx->main_fn,
490 ctx->param_vs_blit_inputs + 3 + i);
491 }
492 } else {
493 assert(vs_blit_property == SI_VS_BLIT_SGPRS_POS_TEXCOORD);
494 LLVMValueRef x1 = LLVMGetParam(ctx->main_fn,
495 ctx->param_vs_blit_inputs + 3);
496 LLVMValueRef y1 = LLVMGetParam(ctx->main_fn,
497 ctx->param_vs_blit_inputs + 4);
498 LLVMValueRef x2 = LLVMGetParam(ctx->main_fn,
499 ctx->param_vs_blit_inputs + 5);
500 LLVMValueRef y2 = LLVMGetParam(ctx->main_fn,
501 ctx->param_vs_blit_inputs + 6);
502
503 out[0] = LLVMBuildSelect(ctx->ac.builder, sel_x1,
504 x1, x2, "");
505 out[1] = LLVMBuildSelect(ctx->ac.builder, sel_y1,
506 y1, y2, "");
507 out[2] = LLVMGetParam(ctx->main_fn,
508 ctx->param_vs_blit_inputs + 7);
509 out[3] = LLVMGetParam(ctx->main_fn,
510 ctx->param_vs_blit_inputs + 8);
511 }
512 return;
513 }
514
515 union si_vs_fix_fetch fix_fetch;
516 LLVMValueRef t_list_ptr;
517 LLVMValueRef t_offset;
518 LLVMValueRef t_list;
519 LLVMValueRef vertex_index;
520 LLVMValueRef tmp;
521
522 /* Load the T list */
523 t_list_ptr = LLVMGetParam(ctx->main_fn, ctx->param_vertex_buffers);
524
525 t_offset = LLVMConstInt(ctx->i32, input_index, 0);
526
527 t_list = ac_build_load_to_sgpr(&ctx->ac, t_list_ptr, t_offset);
528
529 vertex_index = LLVMGetParam(ctx->main_fn,
530 ctx->param_vertex_index0 +
531 input_index);
532
533 /* Use the open-coded implementation for all loads of doubles and
534 * of dword-sized data that needs fixups. We need to insert conversion
535 * code anyway, and the amd/common code does it for us.
536 *
537 * Note: On LLVM <= 8, we can only open-code formats with
538 * channel size >= 4 bytes.
539 */
540 bool opencode = ctx->shader->key.mono.vs_fetch_opencode & (1 << input_index);
541 fix_fetch.bits = ctx->shader->key.mono.vs_fix_fetch[input_index].bits;
542 if (opencode ||
543 (fix_fetch.u.log_size == 3 && fix_fetch.u.format == AC_FETCH_FORMAT_FLOAT) ||
544 (fix_fetch.u.log_size == 2)) {
545 tmp = ac_build_opencoded_load_format(
546 &ctx->ac, fix_fetch.u.log_size, fix_fetch.u.num_channels_m1 + 1,
547 fix_fetch.u.format, fix_fetch.u.reverse, !opencode,
548 t_list, vertex_index, ctx->ac.i32_0, ctx->ac.i32_0, 0, true);
549 for (unsigned i = 0; i < 4; ++i)
550 out[i] = LLVMBuildExtractElement(ctx->ac.builder, tmp, LLVMConstInt(ctx->i32, i, false), "");
551 return;
552 }
553
554 /* Do multiple loads for special formats. */
555 unsigned required_channels = util_last_bit(info->input_usage_mask[input_index]);
556 LLVMValueRef fetches[4];
557 unsigned num_fetches;
558 unsigned fetch_stride;
559 unsigned channels_per_fetch;
560
561 if (fix_fetch.u.log_size <= 1 && fix_fetch.u.num_channels_m1 == 2) {
562 num_fetches = MIN2(required_channels, 3);
563 fetch_stride = 1 << fix_fetch.u.log_size;
564 channels_per_fetch = 1;
565 } else {
566 num_fetches = 1;
567 fetch_stride = 0;
568 channels_per_fetch = required_channels;
569 }
570
571 for (unsigned i = 0; i < num_fetches; ++i) {
572 LLVMValueRef voffset = LLVMConstInt(ctx->i32, fetch_stride * i, 0);
573 fetches[i] = ac_build_buffer_load_format(&ctx->ac, t_list, vertex_index, voffset,
574 channels_per_fetch, 0, true);
575 }
576
577 if (num_fetches == 1 && channels_per_fetch > 1) {
578 LLVMValueRef fetch = fetches[0];
579 for (unsigned i = 0; i < channels_per_fetch; ++i) {
580 tmp = LLVMConstInt(ctx->i32, i, false);
581 fetches[i] = LLVMBuildExtractElement(
582 ctx->ac.builder, fetch, tmp, "");
583 }
584 num_fetches = channels_per_fetch;
585 channels_per_fetch = 1;
586 }
587
588 for (unsigned i = num_fetches; i < 4; ++i)
589 fetches[i] = LLVMGetUndef(ctx->f32);
590
591 if (fix_fetch.u.log_size <= 1 && fix_fetch.u.num_channels_m1 == 2 &&
592 required_channels == 4) {
593 if (fix_fetch.u.format == AC_FETCH_FORMAT_UINT || fix_fetch.u.format == AC_FETCH_FORMAT_SINT)
594 fetches[3] = ctx->ac.i32_1;
595 else
596 fetches[3] = ctx->ac.f32_1;
597 } else if (fix_fetch.u.log_size == 3 &&
598 (fix_fetch.u.format == AC_FETCH_FORMAT_SNORM ||
599 fix_fetch.u.format == AC_FETCH_FORMAT_SSCALED ||
600 fix_fetch.u.format == AC_FETCH_FORMAT_SINT) &&
601 required_channels == 4) {
602 /* For 2_10_10_10, the hardware returns an unsigned value;
603 * convert it to a signed one.
604 */
605 LLVMValueRef tmp = fetches[3];
606 LLVMValueRef c30 = LLVMConstInt(ctx->i32, 30, 0);
607
608 /* First, recover the sign-extended signed integer value. */
609 if (fix_fetch.u.format == AC_FETCH_FORMAT_SSCALED)
610 tmp = LLVMBuildFPToUI(ctx->ac.builder, tmp, ctx->i32, "");
611 else
612 tmp = ac_to_integer(&ctx->ac, tmp);
613
614 /* For the integer-like cases, do a natural sign extension.
615 *
616 * For the SNORM case, the values are 0.0, 0.333, 0.666, 1.0
617 * and happen to contain 0, 1, 2, 3 as the two LSBs of the
618 * exponent.
619 */
620 tmp = LLVMBuildShl(ctx->ac.builder, tmp,
621 fix_fetch.u.format == AC_FETCH_FORMAT_SNORM ?
622 LLVMConstInt(ctx->i32, 7, 0) : c30, "");
623 tmp = LLVMBuildAShr(ctx->ac.builder, tmp, c30, "");
624
625 /* Convert back to the right type. */
626 if (fix_fetch.u.format == AC_FETCH_FORMAT_SNORM) {
627 LLVMValueRef clamp;
628 LLVMValueRef neg_one = LLVMConstReal(ctx->f32, -1.0);
629 tmp = LLVMBuildSIToFP(ctx->ac.builder, tmp, ctx->f32, "");
630 clamp = LLVMBuildFCmp(ctx->ac.builder, LLVMRealULT, tmp, neg_one, "");
631 tmp = LLVMBuildSelect(ctx->ac.builder, clamp, neg_one, tmp, "");
632 } else if (fix_fetch.u.format == AC_FETCH_FORMAT_SSCALED) {
633 tmp = LLVMBuildSIToFP(ctx->ac.builder, tmp, ctx->f32, "");
634 }
635
636 fetches[3] = tmp;
637 }
638
639 for (unsigned i = 0; i < 4; ++i)
640 out[i] = ac_to_float(&ctx->ac, fetches[i]);
641 }
642
643 static void declare_input_vs(
644 struct si_shader_context *ctx,
645 unsigned input_index,
646 const struct tgsi_full_declaration *decl,
647 LLVMValueRef out[4])
648 {
649 si_llvm_load_input_vs(ctx, input_index, out);
650 }
651
652 LLVMValueRef si_get_primitive_id(struct si_shader_context *ctx,
653 unsigned swizzle)
654 {
655 if (swizzle > 0)
656 return ctx->i32_0;
657
658 switch (ctx->type) {
659 case PIPE_SHADER_VERTEX:
660 return LLVMGetParam(ctx->main_fn,
661 ctx->param_vs_prim_id);
662 case PIPE_SHADER_TESS_CTRL:
663 return ctx->abi.tcs_patch_id;
664 case PIPE_SHADER_TESS_EVAL:
665 return ctx->abi.tes_patch_id;
666 case PIPE_SHADER_GEOMETRY:
667 return ctx->abi.gs_prim_id;
668 default:
669 assert(0);
670 return ctx->i32_0;
671 }
672 }
673
674 /**
675 * Return the value of tgsi_ind_register for indexing.
676 * This is the indirect index with the constant offset added to it.
677 */
678 LLVMValueRef si_get_indirect_index(struct si_shader_context *ctx,
679 const struct tgsi_ind_register *ind,
680 unsigned addr_mul,
681 int rel_index)
682 {
683 LLVMValueRef result;
684
685 if (ind->File == TGSI_FILE_ADDRESS) {
686 result = ctx->addrs[ind->Index][ind->Swizzle];
687 result = LLVMBuildLoad(ctx->ac.builder, result, "");
688 } else {
689 struct tgsi_full_src_register src = {};
690
691 src.Register.File = ind->File;
692 src.Register.Index = ind->Index;
693
694 /* Set the second index to 0 for constants. */
695 if (ind->File == TGSI_FILE_CONSTANT)
696 src.Register.Dimension = 1;
697
698 result = ctx->bld_base.emit_fetch_funcs[ind->File](&ctx->bld_base, &src,
699 TGSI_TYPE_SIGNED,
700 ind->Swizzle);
701 result = ac_to_integer(&ctx->ac, result);
702 }
703
704 return ac_build_imad(&ctx->ac, result, LLVMConstInt(ctx->i32, addr_mul, 0),
705 LLVMConstInt(ctx->i32, rel_index, 0));
706 }
707
708 /**
709 * Like si_get_indirect_index, but restricts the return value to a (possibly
710 * undefined) value inside [0..num).
711 */
712 LLVMValueRef si_get_bounded_indirect_index(struct si_shader_context *ctx,
713 const struct tgsi_ind_register *ind,
714 int rel_index, unsigned num)
715 {
716 LLVMValueRef result = si_get_indirect_index(ctx, ind, 1, rel_index);
717
718 return si_llvm_bound_index(ctx, result, num);
719 }
720
721 static LLVMValueRef get_dw_address_from_generic_indices(struct si_shader_context *ctx,
722 LLVMValueRef vertex_dw_stride,
723 LLVMValueRef base_addr,
724 LLVMValueRef vertex_index,
725 LLVMValueRef param_index,
726 unsigned input_index,
727 ubyte *name,
728 ubyte *index,
729 bool is_patch)
730 {
731 if (vertex_dw_stride) {
732 base_addr = ac_build_imad(&ctx->ac, vertex_index,
733 vertex_dw_stride, base_addr);
734 }
735
736 if (param_index) {
737 base_addr = ac_build_imad(&ctx->ac, param_index,
738 LLVMConstInt(ctx->i32, 4, 0), base_addr);
739 }
740
741 int param = is_patch ?
742 si_shader_io_get_unique_index_patch(name[input_index],
743 index[input_index]) :
744 si_shader_io_get_unique_index(name[input_index],
745 index[input_index], false);
746
747 /* Add the base address of the element. */
748 return LLVMBuildAdd(ctx->ac.builder, base_addr,
749 LLVMConstInt(ctx->i32, param * 4, 0), "");
750 }
751
752 /**
753 * Calculate a dword address given an input or output register and a stride.
754 */
755 static LLVMValueRef get_dw_address(struct si_shader_context *ctx,
756 const struct tgsi_full_dst_register *dst,
757 const struct tgsi_full_src_register *src,
758 LLVMValueRef vertex_dw_stride,
759 LLVMValueRef base_addr)
760 {
761 struct tgsi_shader_info *info = &ctx->shader->selector->info;
762 ubyte *name, *index, *array_first;
763 int input_index;
764 struct tgsi_full_dst_register reg;
765 LLVMValueRef vertex_index = NULL;
766 LLVMValueRef ind_index = NULL;
767
768 /* Set the register description. The address computation is the same
769 * for sources and destinations. */
770 if (src) {
771 reg.Register.File = src->Register.File;
772 reg.Register.Index = src->Register.Index;
773 reg.Register.Indirect = src->Register.Indirect;
774 reg.Register.Dimension = src->Register.Dimension;
775 reg.Indirect = src->Indirect;
776 reg.Dimension = src->Dimension;
777 reg.DimIndirect = src->DimIndirect;
778 } else
779 reg = *dst;
780
781 /* If the register is 2-dimensional (e.g. an array of vertices
782 * in a primitive), calculate the base address of the vertex. */
783 if (reg.Register.Dimension) {
784 if (reg.Dimension.Indirect)
785 vertex_index = si_get_indirect_index(ctx, &reg.DimIndirect,
786 1, reg.Dimension.Index);
787 else
788 vertex_index = LLVMConstInt(ctx->i32, reg.Dimension.Index, 0);
789 }
790
791 /* Get information about the register. */
792 if (reg.Register.File == TGSI_FILE_INPUT) {
793 name = info->input_semantic_name;
794 index = info->input_semantic_index;
795 array_first = info->input_array_first;
796 } else if (reg.Register.File == TGSI_FILE_OUTPUT) {
797 name = info->output_semantic_name;
798 index = info->output_semantic_index;
799 array_first = info->output_array_first;
800 } else {
801 assert(0);
802 return NULL;
803 }
804
805 if (reg.Register.Indirect) {
806 /* Add the relative address of the element. */
807 if (reg.Indirect.ArrayID)
808 input_index = array_first[reg.Indirect.ArrayID];
809 else
810 input_index = reg.Register.Index;
811
812 ind_index = si_get_indirect_index(ctx, &reg.Indirect,
813 1, reg.Register.Index - input_index);
814 } else {
815 input_index = reg.Register.Index;
816 }
817
818 return get_dw_address_from_generic_indices(ctx, vertex_dw_stride,
819 base_addr, vertex_index,
820 ind_index, input_index,
821 name, index,
822 !reg.Register.Dimension);
823 }
824
825 /* The offchip buffer layout for TCS->TES is
826 *
827 * - attribute 0 of patch 0 vertex 0
828 * - attribute 0 of patch 0 vertex 1
829 * - attribute 0 of patch 0 vertex 2
830 * ...
831 * - attribute 0 of patch 1 vertex 0
832 * - attribute 0 of patch 1 vertex 1
833 * ...
834 * - attribute 1 of patch 0 vertex 0
835 * - attribute 1 of patch 0 vertex 1
836 * ...
837 * - per patch attribute 0 of patch 0
838 * - per patch attribute 0 of patch 1
839 * ...
840 *
841 * Note that every attribute has 4 components.
842 */
843 static LLVMValueRef get_tcs_tes_buffer_address(struct si_shader_context *ctx,
844 LLVMValueRef rel_patch_id,
845 LLVMValueRef vertex_index,
846 LLVMValueRef param_index)
847 {
848 LLVMValueRef base_addr, vertices_per_patch, num_patches, total_vertices;
849 LLVMValueRef param_stride, constant16;
850
851 vertices_per_patch = get_num_tcs_out_vertices(ctx);
852 num_patches = si_unpack_param(ctx, ctx->param_tcs_offchip_layout, 0, 6);
853 total_vertices = LLVMBuildMul(ctx->ac.builder, vertices_per_patch,
854 num_patches, "");
855
856 constant16 = LLVMConstInt(ctx->i32, 16, 0);
857 if (vertex_index) {
858 base_addr = ac_build_imad(&ctx->ac, rel_patch_id,
859 vertices_per_patch, vertex_index);
860 param_stride = total_vertices;
861 } else {
862 base_addr = rel_patch_id;
863 param_stride = num_patches;
864 }
865
866 base_addr = ac_build_imad(&ctx->ac, param_index, param_stride, base_addr);
867 base_addr = LLVMBuildMul(ctx->ac.builder, base_addr, constant16, "");
868
869 if (!vertex_index) {
870 LLVMValueRef patch_data_offset =
871 si_unpack_param(ctx, ctx->param_tcs_offchip_layout, 12, 20);
872
873 base_addr = LLVMBuildAdd(ctx->ac.builder, base_addr,
874 patch_data_offset, "");
875 }
876 return base_addr;
877 }
878
879 /* This is a generic helper that can be shared by the NIR and TGSI backends */
880 static LLVMValueRef get_tcs_tes_buffer_address_from_generic_indices(
881 struct si_shader_context *ctx,
882 LLVMValueRef vertex_index,
883 LLVMValueRef param_index,
884 unsigned param_base,
885 ubyte *name,
886 ubyte *index,
887 bool is_patch)
888 {
889 unsigned param_index_base;
890
891 param_index_base = is_patch ?
892 si_shader_io_get_unique_index_patch(name[param_base], index[param_base]) :
893 si_shader_io_get_unique_index(name[param_base], index[param_base], false);
894
895 if (param_index) {
896 param_index = LLVMBuildAdd(ctx->ac.builder, param_index,
897 LLVMConstInt(ctx->i32, param_index_base, 0),
898 "");
899 } else {
900 param_index = LLVMConstInt(ctx->i32, param_index_base, 0);
901 }
902
903 return get_tcs_tes_buffer_address(ctx, get_rel_patch_id(ctx),
904 vertex_index, param_index);
905 }
906
907 static LLVMValueRef get_tcs_tes_buffer_address_from_reg(
908 struct si_shader_context *ctx,
909 const struct tgsi_full_dst_register *dst,
910 const struct tgsi_full_src_register *src)
911 {
912 struct tgsi_shader_info *info = &ctx->shader->selector->info;
913 ubyte *name, *index, *array_first;
914 struct tgsi_full_src_register reg;
915 LLVMValueRef vertex_index = NULL;
916 LLVMValueRef param_index = NULL;
917 unsigned param_base;
918
919 reg = src ? *src : tgsi_full_src_register_from_dst(dst);
920
921 if (reg.Register.Dimension) {
922
923 if (reg.Dimension.Indirect)
924 vertex_index = si_get_indirect_index(ctx, &reg.DimIndirect,
925 1, reg.Dimension.Index);
926 else
927 vertex_index = LLVMConstInt(ctx->i32, reg.Dimension.Index, 0);
928 }
929
930 /* Get information about the register. */
931 if (reg.Register.File == TGSI_FILE_INPUT) {
932 name = info->input_semantic_name;
933 index = info->input_semantic_index;
934 array_first = info->input_array_first;
935 } else if (reg.Register.File == TGSI_FILE_OUTPUT) {
936 name = info->output_semantic_name;
937 index = info->output_semantic_index;
938 array_first = info->output_array_first;
939 } else {
940 assert(0);
941 return NULL;
942 }
943
944 if (reg.Register.Indirect) {
945 if (reg.Indirect.ArrayID)
946 param_base = array_first[reg.Indirect.ArrayID];
947 else
948 param_base = reg.Register.Index;
949
950 param_index = si_get_indirect_index(ctx, &reg.Indirect,
951 1, reg.Register.Index - param_base);
952
953 } else {
954 param_base = reg.Register.Index;
955 }
956
957 return get_tcs_tes_buffer_address_from_generic_indices(ctx, vertex_index,
958 param_index, param_base,
959 name, index, !reg.Register.Dimension);
960 }
961
962 static LLVMValueRef buffer_load(struct lp_build_tgsi_context *bld_base,
963 LLVMTypeRef type, unsigned swizzle,
964 LLVMValueRef buffer, LLVMValueRef offset,
965 LLVMValueRef base, bool can_speculate)
966 {
967 struct si_shader_context *ctx = si_shader_context(bld_base);
968 LLVMValueRef value, value2;
969 LLVMTypeRef vec_type = LLVMVectorType(type, 4);
970
971 if (swizzle == ~0) {
972 value = ac_build_buffer_load(&ctx->ac, buffer, 4, NULL, base, offset,
973 0, ac_glc, can_speculate, false);
974
975 return LLVMBuildBitCast(ctx->ac.builder, value, vec_type, "");
976 }
977
978 if (!llvm_type_is_64bit(ctx, type)) {
979 value = ac_build_buffer_load(&ctx->ac, buffer, 4, NULL, base, offset,
980 0, ac_glc, can_speculate, false);
981
982 value = LLVMBuildBitCast(ctx->ac.builder, value, vec_type, "");
983 return LLVMBuildExtractElement(ctx->ac.builder, value,
984 LLVMConstInt(ctx->i32, swizzle, 0), "");
985 }
986
987 value = ac_build_buffer_load(&ctx->ac, buffer, 1, NULL, base, offset,
988 swizzle * 4, ac_glc, can_speculate, false);
989
990 value2 = ac_build_buffer_load(&ctx->ac, buffer, 1, NULL, base, offset,
991 swizzle * 4 + 4, ac_glc, can_speculate, false);
992
993 return si_llvm_emit_fetch_64bit(bld_base, type, value, value2);
994 }
995
996 /**
997 * Load from LSHS LDS storage.
998 *
999 * \param type output value type
1000 * \param swizzle offset (typically 0..3); it can be ~0, which loads a vec4
1001 * \param dw_addr address in dwords
1002 */
1003 static LLVMValueRef lshs_lds_load(struct lp_build_tgsi_context *bld_base,
1004 LLVMTypeRef type, unsigned swizzle,
1005 LLVMValueRef dw_addr)
1006 {
1007 struct si_shader_context *ctx = si_shader_context(bld_base);
1008 LLVMValueRef value;
1009
1010 if (swizzle == ~0) {
1011 LLVMValueRef values[TGSI_NUM_CHANNELS];
1012
1013 for (unsigned chan = 0; chan < TGSI_NUM_CHANNELS; chan++)
1014 values[chan] = lshs_lds_load(bld_base, type, chan, dw_addr);
1015
1016 return ac_build_gather_values(&ctx->ac, values,
1017 TGSI_NUM_CHANNELS);
1018 }
1019
1020 /* Split 64-bit loads. */
1021 if (llvm_type_is_64bit(ctx, type)) {
1022 LLVMValueRef lo, hi;
1023
1024 lo = lshs_lds_load(bld_base, ctx->i32, swizzle, dw_addr);
1025 hi = lshs_lds_load(bld_base, ctx->i32, swizzle + 1, dw_addr);
1026 return si_llvm_emit_fetch_64bit(bld_base, type, lo, hi);
1027 }
1028
1029 dw_addr = LLVMBuildAdd(ctx->ac.builder, dw_addr,
1030 LLVMConstInt(ctx->i32, swizzle, 0), "");
1031
1032 value = ac_lds_load(&ctx->ac, dw_addr);
1033
1034 return LLVMBuildBitCast(ctx->ac.builder, value, type, "");
1035 }
1036
1037 /**
1038 * Store to LSHS LDS storage.
1039 *
1040 * \param swizzle offset (typically 0..3)
1041 * \param dw_addr address in dwords
1042 * \param value value to store
1043 */
1044 static void lshs_lds_store(struct si_shader_context *ctx,
1045 unsigned dw_offset_imm, LLVMValueRef dw_addr,
1046 LLVMValueRef value)
1047 {
1048 dw_addr = LLVMBuildAdd(ctx->ac.builder, dw_addr,
1049 LLVMConstInt(ctx->i32, dw_offset_imm, 0), "");
1050
1051 ac_lds_store(&ctx->ac, dw_addr, value);
1052 }
1053
1054 enum si_tess_ring {
1055 TCS_FACTOR_RING,
1056 TESS_OFFCHIP_RING_TCS,
1057 TESS_OFFCHIP_RING_TES,
1058 };
1059
1060 static LLVMValueRef get_tess_ring_descriptor(struct si_shader_context *ctx,
1061 enum si_tess_ring ring)
1062 {
1063 LLVMBuilderRef builder = ctx->ac.builder;
1064 unsigned param = ring == TESS_OFFCHIP_RING_TES ? ctx->param_tes_offchip_addr :
1065 ctx->param_tcs_out_lds_layout;
1066 LLVMValueRef addr = LLVMGetParam(ctx->main_fn, param);
1067
1068 /* TCS only receives high 13 bits of the address. */
1069 if (ring == TESS_OFFCHIP_RING_TCS || ring == TCS_FACTOR_RING) {
1070 addr = LLVMBuildAnd(builder, addr,
1071 LLVMConstInt(ctx->i32, 0xfff80000, 0), "");
1072 }
1073
1074 if (ring == TCS_FACTOR_RING) {
1075 unsigned tf_offset = ctx->screen->tess_offchip_ring_size;
1076 addr = LLVMBuildAdd(builder, addr,
1077 LLVMConstInt(ctx->i32, tf_offset, 0), "");
1078 }
1079
1080 uint32_t rsrc3 = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
1081 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
1082 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
1083 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
1084
1085 if (ctx->screen->info.chip_class >= GFX10)
1086 rsrc3 |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
1087 S_008F0C_OOB_SELECT(3) |
1088 S_008F0C_RESOURCE_LEVEL(1);
1089 else
1090 rsrc3 |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
1091 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
1092
1093 LLVMValueRef desc[4];
1094 desc[0] = addr;
1095 desc[1] = LLVMConstInt(ctx->i32,
1096 S_008F04_BASE_ADDRESS_HI(ctx->screen->info.address32_hi), 0);
1097 desc[2] = LLVMConstInt(ctx->i32, 0xffffffff, 0);
1098 desc[3] = LLVMConstInt(ctx->i32, rsrc3, false);
1099
1100 return ac_build_gather_values(&ctx->ac, desc, 4);
1101 }
1102
1103 static LLVMValueRef fetch_input_tcs(
1104 struct lp_build_tgsi_context *bld_base,
1105 const struct tgsi_full_src_register *reg,
1106 enum tgsi_opcode_type type, unsigned swizzle_in)
1107 {
1108 struct si_shader_context *ctx = si_shader_context(bld_base);
1109 LLVMValueRef dw_addr, stride;
1110 unsigned swizzle = swizzle_in & 0xffff;
1111 stride = get_tcs_in_vertex_dw_stride(ctx);
1112 dw_addr = get_tcs_in_current_patch_offset(ctx);
1113 dw_addr = get_dw_address(ctx, NULL, reg, stride, dw_addr);
1114
1115 return lshs_lds_load(bld_base, tgsi2llvmtype(bld_base, type), swizzle, dw_addr);
1116 }
1117
1118 static LLVMValueRef si_nir_load_tcs_varyings(struct ac_shader_abi *abi,
1119 LLVMTypeRef type,
1120 LLVMValueRef vertex_index,
1121 LLVMValueRef param_index,
1122 unsigned const_index,
1123 unsigned location,
1124 unsigned driver_location,
1125 unsigned component,
1126 unsigned num_components,
1127 bool is_patch,
1128 bool is_compact,
1129 bool load_input)
1130 {
1131 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1132 struct tgsi_shader_info *info = &ctx->shader->selector->info;
1133 struct lp_build_tgsi_context *bld_base = &ctx->bld_base;
1134 LLVMValueRef dw_addr, stride;
1135
1136 driver_location = driver_location / 4;
1137
1138 if (load_input) {
1139 stride = get_tcs_in_vertex_dw_stride(ctx);
1140 dw_addr = get_tcs_in_current_patch_offset(ctx);
1141 } else {
1142 if (is_patch) {
1143 stride = NULL;
1144 dw_addr = get_tcs_out_current_patch_data_offset(ctx);
1145 } else {
1146 stride = get_tcs_out_vertex_dw_stride(ctx);
1147 dw_addr = get_tcs_out_current_patch_offset(ctx);
1148 }
1149 }
1150
1151 if (param_index) {
1152 /* Add the constant index to the indirect index */
1153 param_index = LLVMBuildAdd(ctx->ac.builder, param_index,
1154 LLVMConstInt(ctx->i32, const_index, 0), "");
1155 } else {
1156 param_index = LLVMConstInt(ctx->i32, const_index, 0);
1157 }
1158
1159 ubyte *names;
1160 ubyte *indices;
1161 if (load_input) {
1162 names = info->input_semantic_name;
1163 indices = info->input_semantic_index;
1164 } else {
1165 names = info->output_semantic_name;
1166 indices = info->output_semantic_index;
1167 }
1168
1169 dw_addr = get_dw_address_from_generic_indices(ctx, stride, dw_addr,
1170 vertex_index, param_index,
1171 driver_location,
1172 names, indices,
1173 is_patch);
1174
1175 LLVMValueRef value[4];
1176 for (unsigned i = 0; i < num_components; i++) {
1177 unsigned offset = i;
1178 if (llvm_type_is_64bit(ctx, type))
1179 offset *= 2;
1180
1181 offset += component;
1182 value[i + component] = lshs_lds_load(bld_base, type, offset, dw_addr);
1183 }
1184
1185 return ac_build_varying_gather_values(&ctx->ac, value, num_components, component);
1186 }
1187
1188 static LLVMValueRef fetch_output_tcs(
1189 struct lp_build_tgsi_context *bld_base,
1190 const struct tgsi_full_src_register *reg,
1191 enum tgsi_opcode_type type, unsigned swizzle_in)
1192 {
1193 struct si_shader_context *ctx = si_shader_context(bld_base);
1194 LLVMValueRef dw_addr, stride;
1195 unsigned swizzle = (swizzle_in & 0xffff);
1196
1197 if (reg->Register.Dimension) {
1198 stride = get_tcs_out_vertex_dw_stride(ctx);
1199 dw_addr = get_tcs_out_current_patch_offset(ctx);
1200 dw_addr = get_dw_address(ctx, NULL, reg, stride, dw_addr);
1201 } else {
1202 dw_addr = get_tcs_out_current_patch_data_offset(ctx);
1203 dw_addr = get_dw_address(ctx, NULL, reg, NULL, dw_addr);
1204 }
1205
1206 return lshs_lds_load(bld_base, tgsi2llvmtype(bld_base, type), swizzle, dw_addr);
1207 }
1208
1209 static LLVMValueRef fetch_input_tes(
1210 struct lp_build_tgsi_context *bld_base,
1211 const struct tgsi_full_src_register *reg,
1212 enum tgsi_opcode_type type, unsigned swizzle_in)
1213 {
1214 struct si_shader_context *ctx = si_shader_context(bld_base);
1215 LLVMValueRef base, addr;
1216 unsigned swizzle = (swizzle_in & 0xffff);
1217
1218 base = LLVMGetParam(ctx->main_fn, ctx->param_tcs_offchip_offset);
1219 addr = get_tcs_tes_buffer_address_from_reg(ctx, NULL, reg);
1220
1221 return buffer_load(bld_base, tgsi2llvmtype(bld_base, type), swizzle,
1222 ctx->tess_offchip_ring, base, addr, true);
1223 }
1224
1225 LLVMValueRef si_nir_load_input_tes(struct ac_shader_abi *abi,
1226 LLVMTypeRef type,
1227 LLVMValueRef vertex_index,
1228 LLVMValueRef param_index,
1229 unsigned const_index,
1230 unsigned location,
1231 unsigned driver_location,
1232 unsigned component,
1233 unsigned num_components,
1234 bool is_patch,
1235 bool is_compact,
1236 bool load_input)
1237 {
1238 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1239 struct tgsi_shader_info *info = &ctx->shader->selector->info;
1240 LLVMValueRef base, addr;
1241
1242 driver_location = driver_location / 4;
1243
1244 base = LLVMGetParam(ctx->main_fn, ctx->param_tcs_offchip_offset);
1245
1246 if (param_index) {
1247 /* Add the constant index to the indirect index */
1248 param_index = LLVMBuildAdd(ctx->ac.builder, param_index,
1249 LLVMConstInt(ctx->i32, const_index, 0), "");
1250 } else {
1251 param_index = LLVMConstInt(ctx->i32, const_index, 0);
1252 }
1253
1254 addr = get_tcs_tes_buffer_address_from_generic_indices(ctx, vertex_index,
1255 param_index, driver_location,
1256 info->input_semantic_name,
1257 info->input_semantic_index,
1258 is_patch);
1259
1260 /* TODO: This will generate rather ordinary llvm code, although it
1261 * should be easy for the optimiser to fix up. In future we might want
1262 * to refactor buffer_load(), but for now this maximises code sharing
1263 * between the NIR and TGSI backends.
1264 */
1265 LLVMValueRef value[4];
1266 for (unsigned i = 0; i < num_components; i++) {
1267 unsigned offset = i;
1268 if (llvm_type_is_64bit(ctx, type)) {
1269 offset *= 2;
1270 if (offset == 4) {
1271 addr = get_tcs_tes_buffer_address_from_generic_indices(ctx,
1272 vertex_index,
1273 param_index,
1274 driver_location + 1,
1275 info->input_semantic_name,
1276 info->input_semantic_index,
1277 is_patch);
1278 }
1279
1280 offset = offset % 4;
1281 }
1282
1283 offset += component;
1284 value[i + component] = buffer_load(&ctx->bld_base, type, offset,
1285 ctx->tess_offchip_ring, base, addr, true);
1286 }
1287
1288 return ac_build_varying_gather_values(&ctx->ac, value, num_components, component);
1289 }
1290
1291 static void store_output_tcs(struct lp_build_tgsi_context *bld_base,
1292 const struct tgsi_full_instruction *inst,
1293 const struct tgsi_opcode_info *info,
1294 unsigned index,
1295 LLVMValueRef dst[4])
1296 {
1297 struct si_shader_context *ctx = si_shader_context(bld_base);
1298 const struct tgsi_full_dst_register *reg = &inst->Dst[index];
1299 const struct tgsi_shader_info *sh_info = &ctx->shader->selector->info;
1300 unsigned chan_index;
1301 LLVMValueRef dw_addr, stride;
1302 LLVMValueRef buffer, base, buf_addr;
1303 LLVMValueRef values[4];
1304 bool skip_lds_store;
1305 bool is_tess_factor = false, is_tess_inner = false;
1306
1307 /* Only handle per-patch and per-vertex outputs here.
1308 * Vectors will be lowered to scalars and this function will be called again.
1309 */
1310 if (reg->Register.File != TGSI_FILE_OUTPUT ||
1311 (dst[0] && LLVMGetTypeKind(LLVMTypeOf(dst[0])) == LLVMVectorTypeKind)) {
1312 si_llvm_emit_store(bld_base, inst, info, index, dst);
1313 return;
1314 }
1315
1316 if (reg->Register.Dimension) {
1317 stride = get_tcs_out_vertex_dw_stride(ctx);
1318 dw_addr = get_tcs_out_current_patch_offset(ctx);
1319 dw_addr = get_dw_address(ctx, reg, NULL, stride, dw_addr);
1320 skip_lds_store = !sh_info->reads_pervertex_outputs;
1321 } else {
1322 dw_addr = get_tcs_out_current_patch_data_offset(ctx);
1323 dw_addr = get_dw_address(ctx, reg, NULL, NULL, dw_addr);
1324 skip_lds_store = !sh_info->reads_perpatch_outputs;
1325
1326 if (!reg->Register.Indirect) {
1327 int name = sh_info->output_semantic_name[reg->Register.Index];
1328
1329 /* Always write tess factors into LDS for the TCS epilog. */
1330 if (name == TGSI_SEMANTIC_TESSINNER ||
1331 name == TGSI_SEMANTIC_TESSOUTER) {
1332 /* The epilog doesn't read LDS if invocation 0 defines tess factors. */
1333 skip_lds_store = !sh_info->reads_tessfactor_outputs &&
1334 ctx->shader->selector->tcs_info.tessfactors_are_def_in_all_invocs;
1335 is_tess_factor = true;
1336 is_tess_inner = name == TGSI_SEMANTIC_TESSINNER;
1337 }
1338 }
1339 }
1340
1341 buffer = get_tess_ring_descriptor(ctx, TESS_OFFCHIP_RING_TCS);
1342
1343 base = LLVMGetParam(ctx->main_fn, ctx->param_tcs_offchip_offset);
1344 buf_addr = get_tcs_tes_buffer_address_from_reg(ctx, reg, NULL);
1345
1346 uint32_t writemask = reg->Register.WriteMask;
1347 while (writemask) {
1348 chan_index = u_bit_scan(&writemask);
1349 LLVMValueRef value = dst[chan_index];
1350
1351 if (inst->Instruction.Saturate)
1352 value = ac_build_clamp(&ctx->ac, value);
1353
1354 /* Skip LDS stores if there is no LDS read of this output. */
1355 if (!skip_lds_store)
1356 lshs_lds_store(ctx, chan_index, dw_addr, value);
1357
1358 value = ac_to_integer(&ctx->ac, value);
1359 values[chan_index] = value;
1360
1361 if (reg->Register.WriteMask != 0xF && !is_tess_factor) {
1362 ac_build_buffer_store_dword(&ctx->ac, buffer, value, 1,
1363 buf_addr, base,
1364 4 * chan_index, ac_glc, false);
1365 }
1366
1367 /* Write tess factors into VGPRs for the epilog. */
1368 if (is_tess_factor &&
1369 ctx->shader->selector->tcs_info.tessfactors_are_def_in_all_invocs) {
1370 if (!is_tess_inner) {
1371 LLVMBuildStore(ctx->ac.builder, value, /* outer */
1372 ctx->invoc0_tess_factors[chan_index]);
1373 } else if (chan_index < 2) {
1374 LLVMBuildStore(ctx->ac.builder, value, /* inner */
1375 ctx->invoc0_tess_factors[4 + chan_index]);
1376 }
1377 }
1378 }
1379
1380 if (reg->Register.WriteMask == 0xF && !is_tess_factor) {
1381 LLVMValueRef value = ac_build_gather_values(&ctx->ac,
1382 values, 4);
1383 ac_build_buffer_store_dword(&ctx->ac, buffer, value, 4, buf_addr,
1384 base, 0, ac_glc, false);
1385 }
1386 }
1387
1388 static void si_nir_store_output_tcs(struct ac_shader_abi *abi,
1389 const struct nir_variable *var,
1390 LLVMValueRef vertex_index,
1391 LLVMValueRef param_index,
1392 unsigned const_index,
1393 LLVMValueRef src,
1394 unsigned writemask)
1395 {
1396 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1397 struct tgsi_shader_info *info = &ctx->shader->selector->info;
1398 const unsigned component = var->data.location_frac;
1399 const bool is_patch = var->data.patch;
1400 unsigned driver_location = var->data.driver_location;
1401 LLVMValueRef dw_addr, stride;
1402 LLVMValueRef buffer, base, addr;
1403 LLVMValueRef values[8];
1404 bool skip_lds_store;
1405 bool is_tess_factor = false, is_tess_inner = false;
1406
1407 driver_location = driver_location / 4;
1408
1409 if (param_index) {
1410 /* Add the constant index to the indirect index */
1411 param_index = LLVMBuildAdd(ctx->ac.builder, param_index,
1412 LLVMConstInt(ctx->i32, const_index, 0), "");
1413 } else {
1414 if (const_index != 0)
1415 param_index = LLVMConstInt(ctx->i32, const_index, 0);
1416 }
1417
1418 if (!is_patch) {
1419 stride = get_tcs_out_vertex_dw_stride(ctx);
1420 dw_addr = get_tcs_out_current_patch_offset(ctx);
1421 dw_addr = get_dw_address_from_generic_indices(ctx, stride, dw_addr,
1422 vertex_index, param_index,
1423 driver_location,
1424 info->output_semantic_name,
1425 info->output_semantic_index,
1426 is_patch);
1427
1428 skip_lds_store = !info->reads_pervertex_outputs;
1429 } else {
1430 dw_addr = get_tcs_out_current_patch_data_offset(ctx);
1431 dw_addr = get_dw_address_from_generic_indices(ctx, NULL, dw_addr,
1432 vertex_index, param_index,
1433 driver_location,
1434 info->output_semantic_name,
1435 info->output_semantic_index,
1436 is_patch);
1437
1438 skip_lds_store = !info->reads_perpatch_outputs;
1439
1440 if (!param_index) {
1441 int name = info->output_semantic_name[driver_location];
1442
1443 /* Always write tess factors into LDS for the TCS epilog. */
1444 if (name == TGSI_SEMANTIC_TESSINNER ||
1445 name == TGSI_SEMANTIC_TESSOUTER) {
1446 /* The epilog doesn't read LDS if invocation 0 defines tess factors. */
1447 skip_lds_store = !info->reads_tessfactor_outputs &&
1448 ctx->shader->selector->tcs_info.tessfactors_are_def_in_all_invocs;
1449 is_tess_factor = true;
1450 is_tess_inner = name == TGSI_SEMANTIC_TESSINNER;
1451 }
1452 }
1453 }
1454
1455 buffer = get_tess_ring_descriptor(ctx, TESS_OFFCHIP_RING_TCS);
1456
1457 base = LLVMGetParam(ctx->main_fn, ctx->param_tcs_offchip_offset);
1458
1459 addr = get_tcs_tes_buffer_address_from_generic_indices(ctx, vertex_index,
1460 param_index, driver_location,
1461 info->output_semantic_name,
1462 info->output_semantic_index,
1463 is_patch);
1464
1465 for (unsigned chan = 0; chan < 8; chan++) {
1466 if (!(writemask & (1 << chan)))
1467 continue;
1468 LLVMValueRef value = ac_llvm_extract_elem(&ctx->ac, src, chan - component);
1469
1470 unsigned buffer_store_offset = chan % 4;
1471 if (chan == 4) {
1472 addr = get_tcs_tes_buffer_address_from_generic_indices(ctx,
1473 vertex_index,
1474 param_index,
1475 driver_location + 1,
1476 info->output_semantic_name,
1477 info->output_semantic_index,
1478 is_patch);
1479 }
1480
1481 /* Skip LDS stores if there is no LDS read of this output. */
1482 if (!skip_lds_store)
1483 lshs_lds_store(ctx, chan, dw_addr, value);
1484
1485 value = ac_to_integer(&ctx->ac, value);
1486 values[chan] = value;
1487
1488 if (writemask != 0xF && !is_tess_factor) {
1489 ac_build_buffer_store_dword(&ctx->ac, buffer, value, 1,
1490 addr, base,
1491 4 * buffer_store_offset,
1492 ac_glc, false);
1493 }
1494
1495 /* Write tess factors into VGPRs for the epilog. */
1496 if (is_tess_factor &&
1497 ctx->shader->selector->tcs_info.tessfactors_are_def_in_all_invocs) {
1498 if (!is_tess_inner) {
1499 LLVMBuildStore(ctx->ac.builder, value, /* outer */
1500 ctx->invoc0_tess_factors[chan]);
1501 } else if (chan < 2) {
1502 LLVMBuildStore(ctx->ac.builder, value, /* inner */
1503 ctx->invoc0_tess_factors[4 + chan]);
1504 }
1505 }
1506 }
1507
1508 if (writemask == 0xF && !is_tess_factor) {
1509 LLVMValueRef value = ac_build_gather_values(&ctx->ac,
1510 values, 4);
1511 ac_build_buffer_store_dword(&ctx->ac, buffer, value, 4, addr,
1512 base, 0, ac_glc, false);
1513 }
1514 }
1515
1516 LLVMValueRef si_llvm_load_input_gs(struct ac_shader_abi *abi,
1517 unsigned input_index,
1518 unsigned vtx_offset_param,
1519 LLVMTypeRef type,
1520 unsigned swizzle)
1521 {
1522 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1523 struct lp_build_tgsi_context *bld_base = &ctx->bld_base;
1524 struct si_shader *shader = ctx->shader;
1525 LLVMValueRef vtx_offset, soffset;
1526 struct tgsi_shader_info *info = &shader->selector->info;
1527 unsigned semantic_name = info->input_semantic_name[input_index];
1528 unsigned semantic_index = info->input_semantic_index[input_index];
1529 unsigned param;
1530 LLVMValueRef value;
1531
1532 param = si_shader_io_get_unique_index(semantic_name, semantic_index, false);
1533
1534 /* GFX9 has the ESGS ring in LDS. */
1535 if (ctx->screen->info.chip_class >= GFX9) {
1536 unsigned index = vtx_offset_param;
1537
1538 switch (index / 2) {
1539 case 0:
1540 vtx_offset = si_unpack_param(ctx, ctx->param_gs_vtx01_offset,
1541 index % 2 ? 16 : 0, 16);
1542 break;
1543 case 1:
1544 vtx_offset = si_unpack_param(ctx, ctx->param_gs_vtx23_offset,
1545 index % 2 ? 16 : 0, 16);
1546 break;
1547 case 2:
1548 vtx_offset = si_unpack_param(ctx, ctx->param_gs_vtx45_offset,
1549 index % 2 ? 16 : 0, 16);
1550 break;
1551 default:
1552 assert(0);
1553 return NULL;
1554 }
1555
1556 unsigned offset = param * 4 + swizzle;
1557 vtx_offset = LLVMBuildAdd(ctx->ac.builder, vtx_offset,
1558 LLVMConstInt(ctx->i32, offset, false), "");
1559
1560 LLVMValueRef ptr = ac_build_gep0(&ctx->ac, ctx->esgs_ring, vtx_offset);
1561 LLVMValueRef value = LLVMBuildLoad(ctx->ac.builder, ptr, "");
1562 if (llvm_type_is_64bit(ctx, type)) {
1563 ptr = LLVMBuildGEP(ctx->ac.builder, ptr,
1564 &ctx->ac.i32_1, 1, "");
1565 LLVMValueRef values[2] = {
1566 value,
1567 LLVMBuildLoad(ctx->ac.builder, ptr, "")
1568 };
1569 value = ac_build_gather_values(&ctx->ac, values, 2);
1570 }
1571 return LLVMBuildBitCast(ctx->ac.builder, value, type, "");
1572 }
1573
1574 /* GFX6: input load from the ESGS ring in memory. */
1575 if (swizzle == ~0) {
1576 LLVMValueRef values[TGSI_NUM_CHANNELS];
1577 unsigned chan;
1578 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
1579 values[chan] = si_llvm_load_input_gs(abi, input_index, vtx_offset_param,
1580 type, chan);
1581 }
1582 return ac_build_gather_values(&ctx->ac, values,
1583 TGSI_NUM_CHANNELS);
1584 }
1585
1586 /* Get the vertex offset parameter on GFX6. */
1587 LLVMValueRef gs_vtx_offset = ctx->gs_vtx_offset[vtx_offset_param];
1588
1589 vtx_offset = LLVMBuildMul(ctx->ac.builder, gs_vtx_offset,
1590 LLVMConstInt(ctx->i32, 4, 0), "");
1591
1592 soffset = LLVMConstInt(ctx->i32, (param * 4 + swizzle) * 256, 0);
1593
1594 value = ac_build_buffer_load(&ctx->ac, ctx->esgs_ring, 1, ctx->i32_0,
1595 vtx_offset, soffset, 0, ac_glc, true, false);
1596 if (llvm_type_is_64bit(ctx, type)) {
1597 LLVMValueRef value2;
1598 soffset = LLVMConstInt(ctx->i32, (param * 4 + swizzle + 1) * 256, 0);
1599
1600 value2 = ac_build_buffer_load(&ctx->ac, ctx->esgs_ring, 1,
1601 ctx->i32_0, vtx_offset, soffset,
1602 0, ac_glc, true, false);
1603 return si_llvm_emit_fetch_64bit(bld_base, type, value, value2);
1604 }
1605 return LLVMBuildBitCast(ctx->ac.builder, value, type, "");
1606 }
1607
1608 static LLVMValueRef si_nir_load_input_gs(struct ac_shader_abi *abi,
1609 unsigned location,
1610 unsigned driver_location,
1611 unsigned component,
1612 unsigned num_components,
1613 unsigned vertex_index,
1614 unsigned const_index,
1615 LLVMTypeRef type)
1616 {
1617 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1618
1619 LLVMValueRef value[4];
1620 for (unsigned i = 0; i < num_components; i++) {
1621 unsigned offset = i;
1622 if (llvm_type_is_64bit(ctx, type))
1623 offset *= 2;
1624
1625 offset += component;
1626 value[i + component] = si_llvm_load_input_gs(&ctx->abi, driver_location / 4,
1627 vertex_index, type, offset);
1628 }
1629
1630 return ac_build_varying_gather_values(&ctx->ac, value, num_components, component);
1631 }
1632
1633 static LLVMValueRef fetch_input_gs(
1634 struct lp_build_tgsi_context *bld_base,
1635 const struct tgsi_full_src_register *reg,
1636 enum tgsi_opcode_type type,
1637 unsigned swizzle_in)
1638 {
1639 struct si_shader_context *ctx = si_shader_context(bld_base);
1640 struct tgsi_shader_info *info = &ctx->shader->selector->info;
1641 unsigned swizzle = swizzle_in & 0xffff;
1642
1643 unsigned semantic_name = info->input_semantic_name[reg->Register.Index];
1644 if (swizzle != ~0 && semantic_name == TGSI_SEMANTIC_PRIMID)
1645 return si_get_primitive_id(ctx, swizzle);
1646
1647 if (!reg->Register.Dimension)
1648 return NULL;
1649
1650 return si_llvm_load_input_gs(&ctx->abi, reg->Register.Index,
1651 reg->Dimension.Index,
1652 tgsi2llvmtype(bld_base, type),
1653 swizzle);
1654 }
1655
1656 static int lookup_interp_param_index(unsigned interpolate, unsigned location)
1657 {
1658 switch (interpolate) {
1659 case TGSI_INTERPOLATE_CONSTANT:
1660 return 0;
1661
1662 case TGSI_INTERPOLATE_LINEAR:
1663 if (location == TGSI_INTERPOLATE_LOC_SAMPLE)
1664 return SI_PARAM_LINEAR_SAMPLE;
1665 else if (location == TGSI_INTERPOLATE_LOC_CENTROID)
1666 return SI_PARAM_LINEAR_CENTROID;
1667 else
1668 return SI_PARAM_LINEAR_CENTER;
1669 break;
1670 case TGSI_INTERPOLATE_COLOR:
1671 case TGSI_INTERPOLATE_PERSPECTIVE:
1672 if (location == TGSI_INTERPOLATE_LOC_SAMPLE)
1673 return SI_PARAM_PERSP_SAMPLE;
1674 else if (location == TGSI_INTERPOLATE_LOC_CENTROID)
1675 return SI_PARAM_PERSP_CENTROID;
1676 else
1677 return SI_PARAM_PERSP_CENTER;
1678 break;
1679 default:
1680 fprintf(stderr, "Warning: Unhandled interpolation mode.\n");
1681 return -1;
1682 }
1683 }
1684
1685 static LLVMValueRef si_build_fs_interp(struct si_shader_context *ctx,
1686 unsigned attr_index, unsigned chan,
1687 LLVMValueRef prim_mask,
1688 LLVMValueRef i, LLVMValueRef j)
1689 {
1690 if (i || j) {
1691 return ac_build_fs_interp(&ctx->ac,
1692 LLVMConstInt(ctx->i32, chan, 0),
1693 LLVMConstInt(ctx->i32, attr_index, 0),
1694 prim_mask, i, j);
1695 }
1696 return ac_build_fs_interp_mov(&ctx->ac,
1697 LLVMConstInt(ctx->i32, 2, 0), /* P0 */
1698 LLVMConstInt(ctx->i32, chan, 0),
1699 LLVMConstInt(ctx->i32, attr_index, 0),
1700 prim_mask);
1701 }
1702
1703 /**
1704 * Interpolate a fragment shader input.
1705 *
1706 * @param ctx context
1707 * @param input_index index of the input in hardware
1708 * @param semantic_name TGSI_SEMANTIC_*
1709 * @param semantic_index semantic index
1710 * @param num_interp_inputs number of all interpolated inputs (= BCOLOR offset)
1711 * @param colors_read_mask color components read (4 bits for each color, 8 bits in total)
1712 * @param interp_param interpolation weights (i,j)
1713 * @param prim_mask SI_PARAM_PRIM_MASK
1714 * @param face SI_PARAM_FRONT_FACE
1715 * @param result the return value (4 components)
1716 */
1717 static void interp_fs_input(struct si_shader_context *ctx,
1718 unsigned input_index,
1719 unsigned semantic_name,
1720 unsigned semantic_index,
1721 unsigned num_interp_inputs,
1722 unsigned colors_read_mask,
1723 LLVMValueRef interp_param,
1724 LLVMValueRef prim_mask,
1725 LLVMValueRef face,
1726 LLVMValueRef result[4])
1727 {
1728 LLVMValueRef i = NULL, j = NULL;
1729 unsigned chan;
1730
1731 /* fs.constant returns the param from the middle vertex, so it's not
1732 * really useful for flat shading. It's meant to be used for custom
1733 * interpolation (but the intrinsic can't fetch from the other two
1734 * vertices).
1735 *
1736 * Luckily, it doesn't matter, because we rely on the FLAT_SHADE state
1737 * to do the right thing. The only reason we use fs.constant is that
1738 * fs.interp cannot be used on integers, because they can be equal
1739 * to NaN.
1740 *
1741 * When interp is false we will use fs.constant or for newer llvm,
1742 * amdgcn.interp.mov.
1743 */
1744 bool interp = interp_param != NULL;
1745
1746 if (interp) {
1747 interp_param = LLVMBuildBitCast(ctx->ac.builder, interp_param,
1748 LLVMVectorType(ctx->f32, 2), "");
1749
1750 i = LLVMBuildExtractElement(ctx->ac.builder, interp_param,
1751 ctx->i32_0, "");
1752 j = LLVMBuildExtractElement(ctx->ac.builder, interp_param,
1753 ctx->i32_1, "");
1754 }
1755
1756 if (semantic_name == TGSI_SEMANTIC_COLOR &&
1757 ctx->shader->key.part.ps.prolog.color_two_side) {
1758 LLVMValueRef is_face_positive;
1759
1760 /* If BCOLOR0 is used, BCOLOR1 is at offset "num_inputs + 1",
1761 * otherwise it's at offset "num_inputs".
1762 */
1763 unsigned back_attr_offset = num_interp_inputs;
1764 if (semantic_index == 1 && colors_read_mask & 0xf)
1765 back_attr_offset += 1;
1766
1767 is_face_positive = LLVMBuildICmp(ctx->ac.builder, LLVMIntNE,
1768 face, ctx->i32_0, "");
1769
1770 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
1771 LLVMValueRef front, back;
1772
1773 front = si_build_fs_interp(ctx,
1774 input_index, chan,
1775 prim_mask, i, j);
1776 back = si_build_fs_interp(ctx,
1777 back_attr_offset, chan,
1778 prim_mask, i, j);
1779
1780 result[chan] = LLVMBuildSelect(ctx->ac.builder,
1781 is_face_positive,
1782 front,
1783 back,
1784 "");
1785 }
1786 } else if (semantic_name == TGSI_SEMANTIC_FOG) {
1787 result[0] = si_build_fs_interp(ctx, input_index,
1788 0, prim_mask, i, j);
1789 result[1] =
1790 result[2] = LLVMConstReal(ctx->f32, 0.0f);
1791 result[3] = LLVMConstReal(ctx->f32, 1.0f);
1792 } else {
1793 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
1794 result[chan] = si_build_fs_interp(ctx,
1795 input_index, chan,
1796 prim_mask, i, j);
1797 }
1798 }
1799 }
1800
1801 void si_llvm_load_input_fs(
1802 struct si_shader_context *ctx,
1803 unsigned input_index,
1804 LLVMValueRef out[4])
1805 {
1806 struct si_shader *shader = ctx->shader;
1807 struct tgsi_shader_info *info = &shader->selector->info;
1808 LLVMValueRef main_fn = ctx->main_fn;
1809 LLVMValueRef interp_param = NULL;
1810 int interp_param_idx;
1811 enum tgsi_semantic semantic_name = info->input_semantic_name[input_index];
1812 unsigned semantic_index = info->input_semantic_index[input_index];
1813 enum tgsi_interpolate_mode interp_mode = info->input_interpolate[input_index];
1814 enum tgsi_interpolate_loc interp_loc = info->input_interpolate_loc[input_index];
1815
1816 /* Get colors from input VGPRs (set by the prolog). */
1817 if (semantic_name == TGSI_SEMANTIC_COLOR) {
1818 unsigned colors_read = shader->selector->info.colors_read;
1819 unsigned mask = colors_read >> (semantic_index * 4);
1820 unsigned offset = SI_PARAM_POS_FIXED_PT + 1 +
1821 (semantic_index ? util_bitcount(colors_read & 0xf) : 0);
1822 LLVMValueRef undef = LLVMGetUndef(ctx->f32);
1823
1824 out[0] = mask & 0x1 ? LLVMGetParam(main_fn, offset++) : undef;
1825 out[1] = mask & 0x2 ? LLVMGetParam(main_fn, offset++) : undef;
1826 out[2] = mask & 0x4 ? LLVMGetParam(main_fn, offset++) : undef;
1827 out[3] = mask & 0x8 ? LLVMGetParam(main_fn, offset++) : undef;
1828 return;
1829 }
1830
1831 interp_param_idx = lookup_interp_param_index(interp_mode, interp_loc);
1832 if (interp_param_idx == -1)
1833 return;
1834 else if (interp_param_idx) {
1835 interp_param = LLVMGetParam(ctx->main_fn, interp_param_idx);
1836 }
1837
1838 interp_fs_input(ctx, input_index, semantic_name,
1839 semantic_index, 0, /* this param is unused */
1840 shader->selector->info.colors_read, interp_param,
1841 ctx->abi.prim_mask,
1842 LLVMGetParam(main_fn, SI_PARAM_FRONT_FACE),
1843 &out[0]);
1844 }
1845
1846 static void declare_input_fs(
1847 struct si_shader_context *ctx,
1848 unsigned input_index,
1849 const struct tgsi_full_declaration *decl,
1850 LLVMValueRef out[4])
1851 {
1852 si_llvm_load_input_fs(ctx, input_index, out);
1853 }
1854
1855 LLVMValueRef si_get_sample_id(struct si_shader_context *ctx)
1856 {
1857 return si_unpack_param(ctx, SI_PARAM_ANCILLARY, 8, 4);
1858 }
1859
1860 static LLVMValueRef get_base_vertex(struct ac_shader_abi *abi)
1861 {
1862 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1863
1864 /* For non-indexed draws, the base vertex set by the driver
1865 * (for direct draws) or the CP (for indirect draws) is the
1866 * first vertex ID, but GLSL expects 0 to be returned.
1867 */
1868 LLVMValueRef vs_state = LLVMGetParam(ctx->main_fn,
1869 ctx->param_vs_state_bits);
1870 LLVMValueRef indexed;
1871
1872 indexed = LLVMBuildLShr(ctx->ac.builder, vs_state, ctx->i32_1, "");
1873 indexed = LLVMBuildTrunc(ctx->ac.builder, indexed, ctx->i1, "");
1874
1875 return LLVMBuildSelect(ctx->ac.builder, indexed, ctx->abi.base_vertex,
1876 ctx->i32_0, "");
1877 }
1878
1879 static LLVMValueRef get_block_size(struct ac_shader_abi *abi)
1880 {
1881 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1882
1883 LLVMValueRef values[3];
1884 LLVMValueRef result;
1885 unsigned i;
1886 unsigned *properties = ctx->shader->selector->info.properties;
1887
1888 if (properties[TGSI_PROPERTY_CS_FIXED_BLOCK_WIDTH] != 0) {
1889 unsigned sizes[3] = {
1890 properties[TGSI_PROPERTY_CS_FIXED_BLOCK_WIDTH],
1891 properties[TGSI_PROPERTY_CS_FIXED_BLOCK_HEIGHT],
1892 properties[TGSI_PROPERTY_CS_FIXED_BLOCK_DEPTH]
1893 };
1894
1895 for (i = 0; i < 3; ++i)
1896 values[i] = LLVMConstInt(ctx->i32, sizes[i], 0);
1897
1898 result = ac_build_gather_values(&ctx->ac, values, 3);
1899 } else {
1900 result = LLVMGetParam(ctx->main_fn, ctx->param_block_size);
1901 }
1902
1903 return result;
1904 }
1905
1906 /**
1907 * Load a dword from a constant buffer.
1908 */
1909 static LLVMValueRef buffer_load_const(struct si_shader_context *ctx,
1910 LLVMValueRef resource,
1911 LLVMValueRef offset)
1912 {
1913 return ac_build_buffer_load(&ctx->ac, resource, 1, NULL, offset, NULL,
1914 0, 0, true, true);
1915 }
1916
1917 static LLVMValueRef load_sample_position(struct ac_shader_abi *abi, LLVMValueRef sample_id)
1918 {
1919 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1920 LLVMValueRef desc = LLVMGetParam(ctx->main_fn, ctx->param_rw_buffers);
1921 LLVMValueRef buf_index = LLVMConstInt(ctx->i32, SI_PS_CONST_SAMPLE_POSITIONS, 0);
1922 LLVMValueRef resource = ac_build_load_to_sgpr(&ctx->ac, desc, buf_index);
1923
1924 /* offset = sample_id * 8 (8 = 2 floats containing samplepos.xy) */
1925 LLVMValueRef offset0 = LLVMBuildMul(ctx->ac.builder, sample_id, LLVMConstInt(ctx->i32, 8, 0), "");
1926 LLVMValueRef offset1 = LLVMBuildAdd(ctx->ac.builder, offset0, LLVMConstInt(ctx->i32, 4, 0), "");
1927
1928 LLVMValueRef pos[4] = {
1929 buffer_load_const(ctx, resource, offset0),
1930 buffer_load_const(ctx, resource, offset1),
1931 LLVMConstReal(ctx->f32, 0),
1932 LLVMConstReal(ctx->f32, 0)
1933 };
1934
1935 return ac_build_gather_values(&ctx->ac, pos, 4);
1936 }
1937
1938 static LLVMValueRef load_sample_mask_in(struct ac_shader_abi *abi)
1939 {
1940 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1941 return ac_to_integer(&ctx->ac, abi->sample_coverage);
1942 }
1943
1944 static LLVMValueRef si_load_tess_coord(struct ac_shader_abi *abi)
1945 {
1946 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1947 LLVMValueRef coord[4] = {
1948 LLVMGetParam(ctx->main_fn, ctx->param_tes_u),
1949 LLVMGetParam(ctx->main_fn, ctx->param_tes_v),
1950 ctx->ac.f32_0,
1951 ctx->ac.f32_0
1952 };
1953
1954 /* For triangles, the vector should be (u, v, 1-u-v). */
1955 if (ctx->shader->selector->info.properties[TGSI_PROPERTY_TES_PRIM_MODE] ==
1956 PIPE_PRIM_TRIANGLES) {
1957 coord[2] = LLVMBuildFSub(ctx->ac.builder, ctx->ac.f32_1,
1958 LLVMBuildFAdd(ctx->ac.builder,
1959 coord[0], coord[1], ""), "");
1960 }
1961 return ac_build_gather_values(&ctx->ac, coord, 4);
1962 }
1963
1964 static LLVMValueRef load_tess_level(struct si_shader_context *ctx,
1965 unsigned semantic_name)
1966 {
1967 LLVMValueRef base, addr;
1968
1969 int param = si_shader_io_get_unique_index_patch(semantic_name, 0);
1970
1971 base = LLVMGetParam(ctx->main_fn, ctx->param_tcs_offchip_offset);
1972 addr = get_tcs_tes_buffer_address(ctx, get_rel_patch_id(ctx), NULL,
1973 LLVMConstInt(ctx->i32, param, 0));
1974
1975 return buffer_load(&ctx->bld_base, ctx->f32,
1976 ~0, ctx->tess_offchip_ring, base, addr, true);
1977
1978 }
1979
1980 static LLVMValueRef si_load_tess_level(struct ac_shader_abi *abi,
1981 unsigned varying_id)
1982 {
1983 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1984 unsigned semantic_name;
1985
1986 switch (varying_id) {
1987 case VARYING_SLOT_TESS_LEVEL_INNER:
1988 semantic_name = TGSI_SEMANTIC_TESSINNER;
1989 break;
1990 case VARYING_SLOT_TESS_LEVEL_OUTER:
1991 semantic_name = TGSI_SEMANTIC_TESSOUTER;
1992 break;
1993 default:
1994 unreachable("unknown tess level");
1995 }
1996
1997 return load_tess_level(ctx, semantic_name);
1998
1999 }
2000
2001 static LLVMValueRef si_load_patch_vertices_in(struct ac_shader_abi *abi)
2002 {
2003 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
2004 if (ctx->type == PIPE_SHADER_TESS_CTRL)
2005 return si_unpack_param(ctx, ctx->param_tcs_out_lds_layout, 13, 6);
2006 else if (ctx->type == PIPE_SHADER_TESS_EVAL)
2007 return get_num_tcs_out_vertices(ctx);
2008 else
2009 unreachable("invalid shader stage for TGSI_SEMANTIC_VERTICESIN");
2010 }
2011
2012 void si_load_system_value(struct si_shader_context *ctx,
2013 unsigned index,
2014 const struct tgsi_full_declaration *decl)
2015 {
2016 LLVMValueRef value = 0;
2017
2018 assert(index < RADEON_LLVM_MAX_SYSTEM_VALUES);
2019
2020 switch (decl->Semantic.Name) {
2021 case TGSI_SEMANTIC_INSTANCEID:
2022 value = ctx->abi.instance_id;
2023 break;
2024
2025 case TGSI_SEMANTIC_VERTEXID:
2026 value = LLVMBuildAdd(ctx->ac.builder,
2027 ctx->abi.vertex_id,
2028 ctx->abi.base_vertex, "");
2029 break;
2030
2031 case TGSI_SEMANTIC_VERTEXID_NOBASE:
2032 /* Unused. Clarify the meaning in indexed vs. non-indexed
2033 * draws if this is ever used again. */
2034 assert(false);
2035 break;
2036
2037 case TGSI_SEMANTIC_BASEVERTEX:
2038 value = get_base_vertex(&ctx->abi);
2039 break;
2040
2041 case TGSI_SEMANTIC_BASEINSTANCE:
2042 value = ctx->abi.start_instance;
2043 break;
2044
2045 case TGSI_SEMANTIC_DRAWID:
2046 value = ctx->abi.draw_id;
2047 break;
2048
2049 case TGSI_SEMANTIC_INVOCATIONID:
2050 if (ctx->type == PIPE_SHADER_TESS_CTRL) {
2051 value = unpack_llvm_param(ctx, ctx->abi.tcs_rel_ids, 8, 5);
2052 } else if (ctx->type == PIPE_SHADER_GEOMETRY) {
2053 if (ctx->screen->info.chip_class >= GFX10) {
2054 value = LLVMBuildAnd(ctx->ac.builder,
2055 ctx->abi.gs_invocation_id,
2056 LLVMConstInt(ctx->i32, 127, 0), "");
2057 } else {
2058 value = ctx->abi.gs_invocation_id;
2059 }
2060 } else {
2061 assert(!"INVOCATIONID not implemented");
2062 }
2063 break;
2064
2065 case TGSI_SEMANTIC_POSITION:
2066 {
2067 LLVMValueRef pos[4] = {
2068 LLVMGetParam(ctx->main_fn, SI_PARAM_POS_X_FLOAT),
2069 LLVMGetParam(ctx->main_fn, SI_PARAM_POS_Y_FLOAT),
2070 LLVMGetParam(ctx->main_fn, SI_PARAM_POS_Z_FLOAT),
2071 ac_build_fdiv(&ctx->ac, ctx->ac.f32_1,
2072 LLVMGetParam(ctx->main_fn, SI_PARAM_POS_W_FLOAT)),
2073 };
2074 value = ac_build_gather_values(&ctx->ac, pos, 4);
2075 break;
2076 }
2077
2078 case TGSI_SEMANTIC_FACE:
2079 value = ctx->abi.front_face;
2080 break;
2081
2082 case TGSI_SEMANTIC_SAMPLEID:
2083 value = si_get_sample_id(ctx);
2084 break;
2085
2086 case TGSI_SEMANTIC_SAMPLEPOS: {
2087 LLVMValueRef pos[4] = {
2088 LLVMGetParam(ctx->main_fn, SI_PARAM_POS_X_FLOAT),
2089 LLVMGetParam(ctx->main_fn, SI_PARAM_POS_Y_FLOAT),
2090 LLVMConstReal(ctx->f32, 0),
2091 LLVMConstReal(ctx->f32, 0)
2092 };
2093 pos[0] = ac_build_fract(&ctx->ac, pos[0], 32);
2094 pos[1] = ac_build_fract(&ctx->ac, pos[1], 32);
2095 value = ac_build_gather_values(&ctx->ac, pos, 4);
2096 break;
2097 }
2098
2099 case TGSI_SEMANTIC_SAMPLEMASK:
2100 /* This can only occur with the OpenGL Core profile, which
2101 * doesn't support smoothing.
2102 */
2103 value = LLVMGetParam(ctx->main_fn, SI_PARAM_SAMPLE_COVERAGE);
2104 break;
2105
2106 case TGSI_SEMANTIC_TESSCOORD:
2107 value = si_load_tess_coord(&ctx->abi);
2108 break;
2109
2110 case TGSI_SEMANTIC_VERTICESIN:
2111 value = si_load_patch_vertices_in(&ctx->abi);
2112 break;
2113
2114 case TGSI_SEMANTIC_TESSINNER:
2115 case TGSI_SEMANTIC_TESSOUTER:
2116 value = load_tess_level(ctx, decl->Semantic.Name);
2117 break;
2118
2119 case TGSI_SEMANTIC_DEFAULT_TESSOUTER_SI:
2120 case TGSI_SEMANTIC_DEFAULT_TESSINNER_SI:
2121 {
2122 LLVMValueRef buf, slot, val[4];
2123 int i, offset;
2124
2125 slot = LLVMConstInt(ctx->i32, SI_HS_CONST_DEFAULT_TESS_LEVELS, 0);
2126 buf = LLVMGetParam(ctx->main_fn, ctx->param_rw_buffers);
2127 buf = ac_build_load_to_sgpr(&ctx->ac, buf, slot);
2128 offset = decl->Semantic.Name == TGSI_SEMANTIC_DEFAULT_TESSINNER_SI ? 4 : 0;
2129
2130 for (i = 0; i < 4; i++)
2131 val[i] = buffer_load_const(ctx, buf,
2132 LLVMConstInt(ctx->i32, (offset + i) * 4, 0));
2133 value = ac_build_gather_values(&ctx->ac, val, 4);
2134 break;
2135 }
2136
2137 case TGSI_SEMANTIC_PRIMID:
2138 value = si_get_primitive_id(ctx, 0);
2139 break;
2140
2141 case TGSI_SEMANTIC_GRID_SIZE:
2142 value = ctx->abi.num_work_groups;
2143 break;
2144
2145 case TGSI_SEMANTIC_BLOCK_SIZE:
2146 value = get_block_size(&ctx->abi);
2147 break;
2148
2149 case TGSI_SEMANTIC_BLOCK_ID:
2150 {
2151 LLVMValueRef values[3];
2152
2153 for (int i = 0; i < 3; i++) {
2154 values[i] = ctx->i32_0;
2155 if (ctx->abi.workgroup_ids[i]) {
2156 values[i] = ctx->abi.workgroup_ids[i];
2157 }
2158 }
2159 value = ac_build_gather_values(&ctx->ac, values, 3);
2160 break;
2161 }
2162
2163 case TGSI_SEMANTIC_THREAD_ID:
2164 value = ctx->abi.local_invocation_ids;
2165 break;
2166
2167 case TGSI_SEMANTIC_HELPER_INVOCATION:
2168 value = ac_build_load_helper_invocation(&ctx->ac);
2169 break;
2170
2171 case TGSI_SEMANTIC_SUBGROUP_SIZE:
2172 value = LLVMConstInt(ctx->i32, ctx->ac.wave_size, 0);
2173 break;
2174
2175 case TGSI_SEMANTIC_SUBGROUP_INVOCATION:
2176 value = ac_get_thread_id(&ctx->ac);
2177 break;
2178
2179 case TGSI_SEMANTIC_SUBGROUP_EQ_MASK:
2180 {
2181 LLVMValueRef id = ac_get_thread_id(&ctx->ac);
2182 if (ctx->ac.wave_size == 64)
2183 id = LLVMBuildZExt(ctx->ac.builder, id, ctx->i64, "");
2184 value = LLVMBuildShl(ctx->ac.builder,
2185 LLVMConstInt(ctx->ac.iN_wavemask, 1, 0), id, "");
2186 if (ctx->ac.wave_size == 32)
2187 value = LLVMBuildZExt(ctx->ac.builder, value, ctx->i64, "");
2188 value = LLVMBuildBitCast(ctx->ac.builder, value, ctx->v2i32, "");
2189 break;
2190 }
2191
2192 case TGSI_SEMANTIC_SUBGROUP_GE_MASK:
2193 case TGSI_SEMANTIC_SUBGROUP_GT_MASK:
2194 case TGSI_SEMANTIC_SUBGROUP_LE_MASK:
2195 case TGSI_SEMANTIC_SUBGROUP_LT_MASK:
2196 {
2197 LLVMValueRef id = ac_get_thread_id(&ctx->ac);
2198 if (decl->Semantic.Name == TGSI_SEMANTIC_SUBGROUP_GT_MASK ||
2199 decl->Semantic.Name == TGSI_SEMANTIC_SUBGROUP_LE_MASK) {
2200 /* All bits set except LSB */
2201 value = LLVMConstInt(ctx->ac.iN_wavemask, -2, 0);
2202 } else {
2203 /* All bits set */
2204 value = LLVMConstInt(ctx->ac.iN_wavemask, -1, 0);
2205 }
2206 if (ctx->ac.wave_size == 64)
2207 id = LLVMBuildZExt(ctx->ac.builder, id, ctx->i64, "");
2208 value = LLVMBuildShl(ctx->ac.builder, value, id, "");
2209 if (decl->Semantic.Name == TGSI_SEMANTIC_SUBGROUP_LE_MASK ||
2210 decl->Semantic.Name == TGSI_SEMANTIC_SUBGROUP_LT_MASK)
2211 value = LLVMBuildNot(ctx->ac.builder, value, "");
2212 if (ctx->ac.wave_size == 32)
2213 value = LLVMBuildZExt(ctx->ac.builder, value, ctx->i64, "");
2214 value = LLVMBuildBitCast(ctx->ac.builder, value, ctx->v2i32, "");
2215 break;
2216 }
2217
2218 case TGSI_SEMANTIC_CS_USER_DATA:
2219 value = LLVMGetParam(ctx->main_fn, ctx->param_cs_user_data);
2220 break;
2221
2222 default:
2223 assert(!"unknown system value");
2224 return;
2225 }
2226
2227 ctx->system_values[index] = value;
2228 }
2229
2230 void si_declare_compute_memory(struct si_shader_context *ctx)
2231 {
2232 struct si_shader_selector *sel = ctx->shader->selector;
2233 unsigned lds_size = sel->info.properties[TGSI_PROPERTY_CS_LOCAL_SIZE];
2234
2235 LLVMTypeRef i8p = LLVMPointerType(ctx->i8, AC_ADDR_SPACE_LDS);
2236 LLVMValueRef var;
2237
2238 assert(!ctx->ac.lds);
2239
2240 var = LLVMAddGlobalInAddressSpace(ctx->ac.module,
2241 LLVMArrayType(ctx->i8, lds_size),
2242 "compute_lds",
2243 AC_ADDR_SPACE_LDS);
2244 LLVMSetAlignment(var, 64 * 1024);
2245
2246 ctx->ac.lds = LLVMBuildBitCast(ctx->ac.builder, var, i8p, "");
2247 }
2248
2249 void si_tgsi_declare_compute_memory(struct si_shader_context *ctx,
2250 const struct tgsi_full_declaration *decl)
2251 {
2252 assert(decl->Declaration.MemType == TGSI_MEMORY_TYPE_SHARED);
2253 assert(decl->Range.First == decl->Range.Last);
2254
2255 si_declare_compute_memory(ctx);
2256 }
2257
2258 static LLVMValueRef load_const_buffer_desc_fast_path(struct si_shader_context *ctx)
2259 {
2260 LLVMValueRef ptr =
2261 LLVMGetParam(ctx->main_fn, ctx->param_const_and_shader_buffers);
2262 struct si_shader_selector *sel = ctx->shader->selector;
2263
2264 /* Do the bounds checking with a descriptor, because
2265 * doing computation and manual bounds checking of 64-bit
2266 * addresses generates horrible VALU code with very high
2267 * VGPR usage and very low SIMD occupancy.
2268 */
2269 ptr = LLVMBuildPtrToInt(ctx->ac.builder, ptr, ctx->ac.intptr, "");
2270
2271 LLVMValueRef desc0, desc1;
2272 desc0 = ptr;
2273 desc1 = LLVMConstInt(ctx->i32,
2274 S_008F04_BASE_ADDRESS_HI(ctx->screen->info.address32_hi), 0);
2275
2276 uint32_t rsrc3 = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2277 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2278 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2279 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
2280
2281 if (ctx->screen->info.chip_class >= GFX10)
2282 rsrc3 |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2283 S_008F0C_OOB_SELECT(3) |
2284 S_008F0C_RESOURCE_LEVEL(1);
2285 else
2286 rsrc3 |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2287 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
2288
2289 LLVMValueRef desc_elems[] = {
2290 desc0,
2291 desc1,
2292 LLVMConstInt(ctx->i32, (sel->info.const_file_max[0] + 1) * 16, 0),
2293 LLVMConstInt(ctx->i32, rsrc3, false)
2294 };
2295
2296 return ac_build_gather_values(&ctx->ac, desc_elems, 4);
2297 }
2298
2299 static LLVMValueRef load_const_buffer_desc(struct si_shader_context *ctx, int i)
2300 {
2301 LLVMValueRef list_ptr = LLVMGetParam(ctx->main_fn,
2302 ctx->param_const_and_shader_buffers);
2303
2304 return ac_build_load_to_sgpr(&ctx->ac, list_ptr,
2305 LLVMConstInt(ctx->i32, si_get_constbuf_slot(i), 0));
2306 }
2307
2308 static LLVMValueRef load_ubo(struct ac_shader_abi *abi, LLVMValueRef index)
2309 {
2310 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
2311 struct si_shader_selector *sel = ctx->shader->selector;
2312
2313 LLVMValueRef ptr = LLVMGetParam(ctx->main_fn, ctx->param_const_and_shader_buffers);
2314
2315 if (sel->info.const_buffers_declared == 1 &&
2316 sel->info.shader_buffers_declared == 0) {
2317 return load_const_buffer_desc_fast_path(ctx);
2318 }
2319
2320 index = si_llvm_bound_index(ctx, index, ctx->num_const_buffers);
2321 index = LLVMBuildAdd(ctx->ac.builder, index,
2322 LLVMConstInt(ctx->i32, SI_NUM_SHADER_BUFFERS, 0), "");
2323
2324 return ac_build_load_to_sgpr(&ctx->ac, ptr, index);
2325 }
2326
2327 static LLVMValueRef
2328 load_ssbo(struct ac_shader_abi *abi, LLVMValueRef index, bool write)
2329 {
2330 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
2331 LLVMValueRef rsrc_ptr = LLVMGetParam(ctx->main_fn,
2332 ctx->param_const_and_shader_buffers);
2333
2334 index = si_llvm_bound_index(ctx, index, ctx->num_shader_buffers);
2335 index = LLVMBuildSub(ctx->ac.builder,
2336 LLVMConstInt(ctx->i32, SI_NUM_SHADER_BUFFERS - 1, 0),
2337 index, "");
2338
2339 return ac_build_load_to_sgpr(&ctx->ac, rsrc_ptr, index);
2340 }
2341
2342 static LLVMValueRef fetch_constant(
2343 struct lp_build_tgsi_context *bld_base,
2344 const struct tgsi_full_src_register *reg,
2345 enum tgsi_opcode_type type,
2346 unsigned swizzle_in)
2347 {
2348 struct si_shader_context *ctx = si_shader_context(bld_base);
2349 struct si_shader_selector *sel = ctx->shader->selector;
2350 const struct tgsi_ind_register *ireg = &reg->Indirect;
2351 unsigned buf, idx;
2352 unsigned swizzle = swizzle_in & 0xffff;
2353
2354 LLVMValueRef addr, bufp;
2355
2356 if (swizzle_in == LP_CHAN_ALL) {
2357 unsigned chan;
2358 LLVMValueRef values[4];
2359 for (chan = 0; chan < TGSI_NUM_CHANNELS; ++chan)
2360 values[chan] = fetch_constant(bld_base, reg, type, chan);
2361
2362 return ac_build_gather_values(&ctx->ac, values, 4);
2363 }
2364
2365 /* Split 64-bit loads. */
2366 if (tgsi_type_is_64bit(type)) {
2367 LLVMValueRef lo, hi;
2368
2369 lo = fetch_constant(bld_base, reg, TGSI_TYPE_UNSIGNED, swizzle);
2370 hi = fetch_constant(bld_base, reg, TGSI_TYPE_UNSIGNED, (swizzle_in >> 16));
2371 return si_llvm_emit_fetch_64bit(bld_base, tgsi2llvmtype(bld_base, type),
2372 lo, hi);
2373 }
2374
2375 idx = reg->Register.Index * 4 + swizzle;
2376 if (reg->Register.Indirect) {
2377 addr = si_get_indirect_index(ctx, ireg, 16, idx * 4);
2378 } else {
2379 addr = LLVMConstInt(ctx->i32, idx * 4, 0);
2380 }
2381
2382 /* Fast path when user data SGPRs point to constant buffer 0 directly. */
2383 if (sel->info.const_buffers_declared == 1 &&
2384 sel->info.shader_buffers_declared == 0) {
2385 LLVMValueRef desc = load_const_buffer_desc_fast_path(ctx);
2386 LLVMValueRef result = buffer_load_const(ctx, desc, addr);
2387 return bitcast(bld_base, type, result);
2388 }
2389
2390 assert(reg->Register.Dimension);
2391 buf = reg->Dimension.Index;
2392
2393 if (reg->Dimension.Indirect) {
2394 LLVMValueRef ptr = LLVMGetParam(ctx->main_fn, ctx->param_const_and_shader_buffers);
2395 LLVMValueRef index;
2396 index = si_get_bounded_indirect_index(ctx, &reg->DimIndirect,
2397 reg->Dimension.Index,
2398 ctx->num_const_buffers);
2399 index = LLVMBuildAdd(ctx->ac.builder, index,
2400 LLVMConstInt(ctx->i32, SI_NUM_SHADER_BUFFERS, 0), "");
2401 bufp = ac_build_load_to_sgpr(&ctx->ac, ptr, index);
2402 } else
2403 bufp = load_const_buffer_desc(ctx, buf);
2404
2405 return bitcast(bld_base, type, buffer_load_const(ctx, bufp, addr));
2406 }
2407
2408 /* Initialize arguments for the shader export intrinsic */
2409 static void si_llvm_init_export_args(struct si_shader_context *ctx,
2410 LLVMValueRef *values,
2411 unsigned target,
2412 struct ac_export_args *args)
2413 {
2414 LLVMValueRef f32undef = LLVMGetUndef(ctx->ac.f32);
2415 unsigned spi_shader_col_format = V_028714_SPI_SHADER_32_ABGR;
2416 unsigned chan;
2417 bool is_int8, is_int10;
2418
2419 /* Default is 0xf. Adjusted below depending on the format. */
2420 args->enabled_channels = 0xf; /* writemask */
2421
2422 /* Specify whether the EXEC mask represents the valid mask */
2423 args->valid_mask = 0;
2424
2425 /* Specify whether this is the last export */
2426 args->done = 0;
2427
2428 /* Specify the target we are exporting */
2429 args->target = target;
2430
2431 if (ctx->type == PIPE_SHADER_FRAGMENT) {
2432 const struct si_shader_key *key = &ctx->shader->key;
2433 unsigned col_formats = key->part.ps.epilog.spi_shader_col_format;
2434 int cbuf = target - V_008DFC_SQ_EXP_MRT;
2435
2436 assert(cbuf >= 0 && cbuf < 8);
2437 spi_shader_col_format = (col_formats >> (cbuf * 4)) & 0xf;
2438 is_int8 = (key->part.ps.epilog.color_is_int8 >> cbuf) & 0x1;
2439 is_int10 = (key->part.ps.epilog.color_is_int10 >> cbuf) & 0x1;
2440 }
2441
2442 args->compr = false;
2443 args->out[0] = f32undef;
2444 args->out[1] = f32undef;
2445 args->out[2] = f32undef;
2446 args->out[3] = f32undef;
2447
2448 LLVMValueRef (*packf)(struct ac_llvm_context *ctx, LLVMValueRef args[2]) = NULL;
2449 LLVMValueRef (*packi)(struct ac_llvm_context *ctx, LLVMValueRef args[2],
2450 unsigned bits, bool hi) = NULL;
2451
2452 switch (spi_shader_col_format) {
2453 case V_028714_SPI_SHADER_ZERO:
2454 args->enabled_channels = 0; /* writemask */
2455 args->target = V_008DFC_SQ_EXP_NULL;
2456 break;
2457
2458 case V_028714_SPI_SHADER_32_R:
2459 args->enabled_channels = 1; /* writemask */
2460 args->out[0] = values[0];
2461 break;
2462
2463 case V_028714_SPI_SHADER_32_GR:
2464 args->enabled_channels = 0x3; /* writemask */
2465 args->out[0] = values[0];
2466 args->out[1] = values[1];
2467 break;
2468
2469 case V_028714_SPI_SHADER_32_AR:
2470 if (ctx->screen->info.chip_class >= GFX10) {
2471 args->enabled_channels = 0x3; /* writemask */
2472 args->out[0] = values[0];
2473 args->out[1] = values[3];
2474 } else {
2475 args->enabled_channels = 0x9; /* writemask */
2476 args->out[0] = values[0];
2477 args->out[3] = values[3];
2478 }
2479 break;
2480
2481 case V_028714_SPI_SHADER_FP16_ABGR:
2482 packf = ac_build_cvt_pkrtz_f16;
2483 break;
2484
2485 case V_028714_SPI_SHADER_UNORM16_ABGR:
2486 packf = ac_build_cvt_pknorm_u16;
2487 break;
2488
2489 case V_028714_SPI_SHADER_SNORM16_ABGR:
2490 packf = ac_build_cvt_pknorm_i16;
2491 break;
2492
2493 case V_028714_SPI_SHADER_UINT16_ABGR:
2494 packi = ac_build_cvt_pk_u16;
2495 break;
2496
2497 case V_028714_SPI_SHADER_SINT16_ABGR:
2498 packi = ac_build_cvt_pk_i16;
2499 break;
2500
2501 case V_028714_SPI_SHADER_32_ABGR:
2502 memcpy(&args->out[0], values, sizeof(values[0]) * 4);
2503 break;
2504 }
2505
2506 /* Pack f16 or norm_i16/u16. */
2507 if (packf) {
2508 for (chan = 0; chan < 2; chan++) {
2509 LLVMValueRef pack_args[2] = {
2510 values[2 * chan],
2511 values[2 * chan + 1]
2512 };
2513 LLVMValueRef packed;
2514
2515 packed = packf(&ctx->ac, pack_args);
2516 args->out[chan] = ac_to_float(&ctx->ac, packed);
2517 }
2518 args->compr = 1; /* COMPR flag */
2519 }
2520 /* Pack i16/u16. */
2521 if (packi) {
2522 for (chan = 0; chan < 2; chan++) {
2523 LLVMValueRef pack_args[2] = {
2524 ac_to_integer(&ctx->ac, values[2 * chan]),
2525 ac_to_integer(&ctx->ac, values[2 * chan + 1])
2526 };
2527 LLVMValueRef packed;
2528
2529 packed = packi(&ctx->ac, pack_args,
2530 is_int8 ? 8 : is_int10 ? 10 : 16,
2531 chan == 1);
2532 args->out[chan] = ac_to_float(&ctx->ac, packed);
2533 }
2534 args->compr = 1; /* COMPR flag */
2535 }
2536 }
2537
2538 static void si_alpha_test(struct lp_build_tgsi_context *bld_base,
2539 LLVMValueRef alpha)
2540 {
2541 struct si_shader_context *ctx = si_shader_context(bld_base);
2542
2543 if (ctx->shader->key.part.ps.epilog.alpha_func != PIPE_FUNC_NEVER) {
2544 static LLVMRealPredicate cond_map[PIPE_FUNC_ALWAYS + 1] = {
2545 [PIPE_FUNC_LESS] = LLVMRealOLT,
2546 [PIPE_FUNC_EQUAL] = LLVMRealOEQ,
2547 [PIPE_FUNC_LEQUAL] = LLVMRealOLE,
2548 [PIPE_FUNC_GREATER] = LLVMRealOGT,
2549 [PIPE_FUNC_NOTEQUAL] = LLVMRealONE,
2550 [PIPE_FUNC_GEQUAL] = LLVMRealOGE,
2551 };
2552 LLVMRealPredicate cond = cond_map[ctx->shader->key.part.ps.epilog.alpha_func];
2553 assert(cond);
2554
2555 LLVMValueRef alpha_ref = LLVMGetParam(ctx->main_fn,
2556 SI_PARAM_ALPHA_REF);
2557 LLVMValueRef alpha_pass =
2558 LLVMBuildFCmp(ctx->ac.builder, cond, alpha, alpha_ref, "");
2559 ac_build_kill_if_false(&ctx->ac, alpha_pass);
2560 } else {
2561 ac_build_kill_if_false(&ctx->ac, ctx->i1false);
2562 }
2563 }
2564
2565 static LLVMValueRef si_scale_alpha_by_sample_mask(struct lp_build_tgsi_context *bld_base,
2566 LLVMValueRef alpha,
2567 unsigned samplemask_param)
2568 {
2569 struct si_shader_context *ctx = si_shader_context(bld_base);
2570 LLVMValueRef coverage;
2571
2572 /* alpha = alpha * popcount(coverage) / SI_NUM_SMOOTH_AA_SAMPLES */
2573 coverage = LLVMGetParam(ctx->main_fn,
2574 samplemask_param);
2575 coverage = ac_to_integer(&ctx->ac, coverage);
2576
2577 coverage = ac_build_intrinsic(&ctx->ac, "llvm.ctpop.i32",
2578 ctx->i32,
2579 &coverage, 1, AC_FUNC_ATTR_READNONE);
2580
2581 coverage = LLVMBuildUIToFP(ctx->ac.builder, coverage,
2582 ctx->f32, "");
2583
2584 coverage = LLVMBuildFMul(ctx->ac.builder, coverage,
2585 LLVMConstReal(ctx->f32,
2586 1.0 / SI_NUM_SMOOTH_AA_SAMPLES), "");
2587
2588 return LLVMBuildFMul(ctx->ac.builder, alpha, coverage, "");
2589 }
2590
2591 static void si_llvm_emit_clipvertex(struct si_shader_context *ctx,
2592 struct ac_export_args *pos, LLVMValueRef *out_elts)
2593 {
2594 unsigned reg_index;
2595 unsigned chan;
2596 unsigned const_chan;
2597 LLVMValueRef base_elt;
2598 LLVMValueRef ptr = LLVMGetParam(ctx->main_fn, ctx->param_rw_buffers);
2599 LLVMValueRef constbuf_index = LLVMConstInt(ctx->i32,
2600 SI_VS_CONST_CLIP_PLANES, 0);
2601 LLVMValueRef const_resource = ac_build_load_to_sgpr(&ctx->ac, ptr, constbuf_index);
2602
2603 for (reg_index = 0; reg_index < 2; reg_index ++) {
2604 struct ac_export_args *args = &pos[2 + reg_index];
2605
2606 args->out[0] =
2607 args->out[1] =
2608 args->out[2] =
2609 args->out[3] = LLVMConstReal(ctx->f32, 0.0f);
2610
2611 /* Compute dot products of position and user clip plane vectors */
2612 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
2613 for (const_chan = 0; const_chan < TGSI_NUM_CHANNELS; const_chan++) {
2614 LLVMValueRef addr =
2615 LLVMConstInt(ctx->i32, ((reg_index * 4 + chan) * 4 +
2616 const_chan) * 4, 0);
2617 base_elt = buffer_load_const(ctx, const_resource,
2618 addr);
2619 args->out[chan] = ac_build_fmad(&ctx->ac, base_elt,
2620 out_elts[const_chan], args->out[chan]);
2621 }
2622 }
2623
2624 args->enabled_channels = 0xf;
2625 args->valid_mask = 0;
2626 args->done = 0;
2627 args->target = V_008DFC_SQ_EXP_POS + 2 + reg_index;
2628 args->compr = 0;
2629 }
2630 }
2631
2632 static void si_dump_streamout(struct pipe_stream_output_info *so)
2633 {
2634 unsigned i;
2635
2636 if (so->num_outputs)
2637 fprintf(stderr, "STREAMOUT\n");
2638
2639 for (i = 0; i < so->num_outputs; i++) {
2640 unsigned mask = ((1 << so->output[i].num_components) - 1) <<
2641 so->output[i].start_component;
2642 fprintf(stderr, " %i: BUF%i[%i..%i] <- OUT[%i].%s%s%s%s\n",
2643 i, so->output[i].output_buffer,
2644 so->output[i].dst_offset, so->output[i].dst_offset + so->output[i].num_components - 1,
2645 so->output[i].register_index,
2646 mask & 1 ? "x" : "",
2647 mask & 2 ? "y" : "",
2648 mask & 4 ? "z" : "",
2649 mask & 8 ? "w" : "");
2650 }
2651 }
2652
2653 void si_emit_streamout_output(struct si_shader_context *ctx,
2654 LLVMValueRef const *so_buffers,
2655 LLVMValueRef const *so_write_offsets,
2656 struct pipe_stream_output *stream_out,
2657 struct si_shader_output_values *shader_out)
2658 {
2659 unsigned buf_idx = stream_out->output_buffer;
2660 unsigned start = stream_out->start_component;
2661 unsigned num_comps = stream_out->num_components;
2662 LLVMValueRef out[4];
2663
2664 assert(num_comps && num_comps <= 4);
2665 if (!num_comps || num_comps > 4)
2666 return;
2667
2668 /* Load the output as int. */
2669 for (int j = 0; j < num_comps; j++) {
2670 assert(stream_out->stream == shader_out->vertex_stream[start + j]);
2671
2672 out[j] = ac_to_integer(&ctx->ac, shader_out->values[start + j]);
2673 }
2674
2675 /* Pack the output. */
2676 LLVMValueRef vdata = NULL;
2677
2678 switch (num_comps) {
2679 case 1: /* as i32 */
2680 vdata = out[0];
2681 break;
2682 case 2: /* as v2i32 */
2683 case 3: /* as v3i32 */
2684 if (ac_has_vec3_support(ctx->screen->info.chip_class, false)) {
2685 vdata = ac_build_gather_values(&ctx->ac, out, num_comps);
2686 break;
2687 }
2688 /* as v4i32 (aligned to 4) */
2689 out[3] = LLVMGetUndef(ctx->i32);
2690 /* fall through */
2691 case 4: /* as v4i32 */
2692 vdata = ac_build_gather_values(&ctx->ac, out, util_next_power_of_two(num_comps));
2693 break;
2694 }
2695
2696 ac_build_buffer_store_dword(&ctx->ac, so_buffers[buf_idx],
2697 vdata, num_comps,
2698 so_write_offsets[buf_idx],
2699 ctx->i32_0,
2700 stream_out->dst_offset * 4, ac_glc | ac_slc, false);
2701 }
2702
2703 /**
2704 * Write streamout data to buffers for vertex stream @p stream (different
2705 * vertex streams can occur for GS copy shaders).
2706 */
2707 static void si_llvm_emit_streamout(struct si_shader_context *ctx,
2708 struct si_shader_output_values *outputs,
2709 unsigned noutput, unsigned stream)
2710 {
2711 struct si_shader_selector *sel = ctx->shader->selector;
2712 struct pipe_stream_output_info *so = &sel->so;
2713 LLVMBuilderRef builder = ctx->ac.builder;
2714 int i;
2715 struct lp_build_if_state if_ctx;
2716
2717 /* Get bits [22:16], i.e. (so_param >> 16) & 127; */
2718 LLVMValueRef so_vtx_count =
2719 si_unpack_param(ctx, ctx->param_streamout_config, 16, 7);
2720
2721 LLVMValueRef tid = ac_get_thread_id(&ctx->ac);
2722
2723 /* can_emit = tid < so_vtx_count; */
2724 LLVMValueRef can_emit =
2725 LLVMBuildICmp(builder, LLVMIntULT, tid, so_vtx_count, "");
2726
2727 /* Emit the streamout code conditionally. This actually avoids
2728 * out-of-bounds buffer access. The hw tells us via the SGPR
2729 * (so_vtx_count) which threads are allowed to emit streamout data. */
2730 lp_build_if(&if_ctx, &ctx->gallivm, can_emit);
2731 {
2732 /* The buffer offset is computed as follows:
2733 * ByteOffset = streamout_offset[buffer_id]*4 +
2734 * (streamout_write_index + thread_id)*stride[buffer_id] +
2735 * attrib_offset
2736 */
2737
2738 LLVMValueRef so_write_index =
2739 LLVMGetParam(ctx->main_fn,
2740 ctx->param_streamout_write_index);
2741
2742 /* Compute (streamout_write_index + thread_id). */
2743 so_write_index = LLVMBuildAdd(builder, so_write_index, tid, "");
2744
2745 /* Load the descriptor and compute the write offset for each
2746 * enabled buffer. */
2747 LLVMValueRef so_write_offset[4] = {};
2748 LLVMValueRef so_buffers[4];
2749 LLVMValueRef buf_ptr = LLVMGetParam(ctx->main_fn,
2750 ctx->param_rw_buffers);
2751
2752 for (i = 0; i < 4; i++) {
2753 if (!so->stride[i])
2754 continue;
2755
2756 LLVMValueRef offset = LLVMConstInt(ctx->i32,
2757 SI_VS_STREAMOUT_BUF0 + i, 0);
2758
2759 so_buffers[i] = ac_build_load_to_sgpr(&ctx->ac, buf_ptr, offset);
2760
2761 LLVMValueRef so_offset = LLVMGetParam(ctx->main_fn,
2762 ctx->param_streamout_offset[i]);
2763 so_offset = LLVMBuildMul(builder, so_offset, LLVMConstInt(ctx->i32, 4, 0), "");
2764
2765 so_write_offset[i] = ac_build_imad(&ctx->ac, so_write_index,
2766 LLVMConstInt(ctx->i32, so->stride[i]*4, 0),
2767 so_offset);
2768 }
2769
2770 /* Write streamout data. */
2771 for (i = 0; i < so->num_outputs; i++) {
2772 unsigned reg = so->output[i].register_index;
2773
2774 if (reg >= noutput)
2775 continue;
2776
2777 if (stream != so->output[i].stream)
2778 continue;
2779
2780 si_emit_streamout_output(ctx, so_buffers, so_write_offset,
2781 &so->output[i], &outputs[reg]);
2782 }
2783 }
2784 lp_build_endif(&if_ctx);
2785 }
2786
2787 static void si_export_param(struct si_shader_context *ctx, unsigned index,
2788 LLVMValueRef *values)
2789 {
2790 struct ac_export_args args;
2791
2792 si_llvm_init_export_args(ctx, values,
2793 V_008DFC_SQ_EXP_PARAM + index, &args);
2794 ac_build_export(&ctx->ac, &args);
2795 }
2796
2797 static void si_build_param_exports(struct si_shader_context *ctx,
2798 struct si_shader_output_values *outputs,
2799 unsigned noutput)
2800 {
2801 struct si_shader *shader = ctx->shader;
2802 unsigned param_count = 0;
2803
2804 for (unsigned i = 0; i < noutput; i++) {
2805 unsigned semantic_name = outputs[i].semantic_name;
2806 unsigned semantic_index = outputs[i].semantic_index;
2807
2808 if (outputs[i].vertex_stream[0] != 0 &&
2809 outputs[i].vertex_stream[1] != 0 &&
2810 outputs[i].vertex_stream[2] != 0 &&
2811 outputs[i].vertex_stream[3] != 0)
2812 continue;
2813
2814 switch (semantic_name) {
2815 case TGSI_SEMANTIC_LAYER:
2816 case TGSI_SEMANTIC_VIEWPORT_INDEX:
2817 case TGSI_SEMANTIC_CLIPDIST:
2818 case TGSI_SEMANTIC_COLOR:
2819 case TGSI_SEMANTIC_BCOLOR:
2820 case TGSI_SEMANTIC_PRIMID:
2821 case TGSI_SEMANTIC_FOG:
2822 case TGSI_SEMANTIC_TEXCOORD:
2823 case TGSI_SEMANTIC_GENERIC:
2824 break;
2825 default:
2826 continue;
2827 }
2828
2829 if ((semantic_name != TGSI_SEMANTIC_GENERIC ||
2830 semantic_index < SI_MAX_IO_GENERIC) &&
2831 shader->key.opt.kill_outputs &
2832 (1ull << si_shader_io_get_unique_index(semantic_name,
2833 semantic_index, true)))
2834 continue;
2835
2836 si_export_param(ctx, param_count, outputs[i].values);
2837
2838 assert(i < ARRAY_SIZE(shader->info.vs_output_param_offset));
2839 shader->info.vs_output_param_offset[i] = param_count++;
2840 }
2841
2842 shader->info.nr_param_exports = param_count;
2843 }
2844
2845 /**
2846 * Vertex color clamping.
2847 *
2848 * This uses a state constant loaded in a user data SGPR and
2849 * an IF statement is added that clamps all colors if the constant
2850 * is true.
2851 */
2852 static void si_vertex_color_clamping(struct si_shader_context *ctx,
2853 struct si_shader_output_values *outputs,
2854 unsigned noutput)
2855 {
2856 LLVMValueRef addr[SI_MAX_VS_OUTPUTS][4];
2857 bool has_colors = false;
2858
2859 /* Store original colors to alloca variables. */
2860 for (unsigned i = 0; i < noutput; i++) {
2861 if (outputs[i].semantic_name != TGSI_SEMANTIC_COLOR &&
2862 outputs[i].semantic_name != TGSI_SEMANTIC_BCOLOR)
2863 continue;
2864
2865 for (unsigned j = 0; j < 4; j++) {
2866 addr[i][j] = ac_build_alloca_undef(&ctx->ac, ctx->f32, "");
2867 LLVMBuildStore(ctx->ac.builder, outputs[i].values[j], addr[i][j]);
2868 }
2869 has_colors = true;
2870 }
2871
2872 if (!has_colors)
2873 return;
2874
2875 /* The state is in the first bit of the user SGPR. */
2876 LLVMValueRef cond = LLVMGetParam(ctx->main_fn, ctx->param_vs_state_bits);
2877 cond = LLVMBuildTrunc(ctx->ac.builder, cond, ctx->i1, "");
2878
2879 struct lp_build_if_state if_ctx;
2880 lp_build_if(&if_ctx, &ctx->gallivm, cond);
2881
2882 /* Store clamped colors to alloca variables within the conditional block. */
2883 for (unsigned i = 0; i < noutput; i++) {
2884 if (outputs[i].semantic_name != TGSI_SEMANTIC_COLOR &&
2885 outputs[i].semantic_name != TGSI_SEMANTIC_BCOLOR)
2886 continue;
2887
2888 for (unsigned j = 0; j < 4; j++) {
2889 LLVMBuildStore(ctx->ac.builder,
2890 ac_build_clamp(&ctx->ac, outputs[i].values[j]),
2891 addr[i][j]);
2892 }
2893 }
2894 lp_build_endif(&if_ctx);
2895
2896 /* Load clamped colors */
2897 for (unsigned i = 0; i < noutput; i++) {
2898 if (outputs[i].semantic_name != TGSI_SEMANTIC_COLOR &&
2899 outputs[i].semantic_name != TGSI_SEMANTIC_BCOLOR)
2900 continue;
2901
2902 for (unsigned j = 0; j < 4; j++) {
2903 outputs[i].values[j] =
2904 LLVMBuildLoad(ctx->ac.builder, addr[i][j], "");
2905 }
2906 }
2907 }
2908
2909 /* Generate export instructions for hardware VS shader stage or NGG GS stage
2910 * (position and parameter data only).
2911 */
2912 void si_llvm_export_vs(struct si_shader_context *ctx,
2913 struct si_shader_output_values *outputs,
2914 unsigned noutput)
2915 {
2916 struct si_shader *shader = ctx->shader;
2917 struct ac_export_args pos_args[4] = {};
2918 LLVMValueRef psize_value = NULL, edgeflag_value = NULL, layer_value = NULL, viewport_index_value = NULL;
2919 unsigned pos_idx;
2920 int i;
2921
2922 si_vertex_color_clamping(ctx, outputs, noutput);
2923
2924 /* Build position exports. */
2925 for (i = 0; i < noutput; i++) {
2926 switch (outputs[i].semantic_name) {
2927 case TGSI_SEMANTIC_POSITION:
2928 si_llvm_init_export_args(ctx, outputs[i].values,
2929 V_008DFC_SQ_EXP_POS, &pos_args[0]);
2930 break;
2931 case TGSI_SEMANTIC_PSIZE:
2932 psize_value = outputs[i].values[0];
2933 break;
2934 case TGSI_SEMANTIC_LAYER:
2935 layer_value = outputs[i].values[0];
2936 break;
2937 case TGSI_SEMANTIC_VIEWPORT_INDEX:
2938 viewport_index_value = outputs[i].values[0];
2939 break;
2940 case TGSI_SEMANTIC_EDGEFLAG:
2941 edgeflag_value = outputs[i].values[0];
2942 break;
2943 case TGSI_SEMANTIC_CLIPDIST:
2944 if (!shader->key.opt.clip_disable) {
2945 unsigned index = 2 + outputs[i].semantic_index;
2946 si_llvm_init_export_args(ctx, outputs[i].values,
2947 V_008DFC_SQ_EXP_POS + index,
2948 &pos_args[index]);
2949 }
2950 break;
2951 case TGSI_SEMANTIC_CLIPVERTEX:
2952 if (!shader->key.opt.clip_disable) {
2953 si_llvm_emit_clipvertex(ctx, pos_args,
2954 outputs[i].values);
2955 }
2956 break;
2957 }
2958 }
2959
2960 /* We need to add the position output manually if it's missing. */
2961 if (!pos_args[0].out[0]) {
2962 pos_args[0].enabled_channels = 0xf; /* writemask */
2963 pos_args[0].valid_mask = 0; /* EXEC mask */
2964 pos_args[0].done = 0; /* last export? */
2965 pos_args[0].target = V_008DFC_SQ_EXP_POS;
2966 pos_args[0].compr = 0; /* COMPR flag */
2967 pos_args[0].out[0] = ctx->ac.f32_0; /* X */
2968 pos_args[0].out[1] = ctx->ac.f32_0; /* Y */
2969 pos_args[0].out[2] = ctx->ac.f32_0; /* Z */
2970 pos_args[0].out[3] = ctx->ac.f32_1; /* W */
2971 }
2972
2973 /* Write the misc vector (point size, edgeflag, layer, viewport). */
2974 if (shader->selector->info.writes_psize ||
2975 shader->selector->pos_writes_edgeflag ||
2976 shader->selector->info.writes_viewport_index ||
2977 shader->selector->info.writes_layer) {
2978 pos_args[1].enabled_channels = shader->selector->info.writes_psize |
2979 (shader->selector->pos_writes_edgeflag << 1) |
2980 (shader->selector->info.writes_layer << 2);
2981
2982 pos_args[1].valid_mask = 0; /* EXEC mask */
2983 pos_args[1].done = 0; /* last export? */
2984 pos_args[1].target = V_008DFC_SQ_EXP_POS + 1;
2985 pos_args[1].compr = 0; /* COMPR flag */
2986 pos_args[1].out[0] = ctx->ac.f32_0; /* X */
2987 pos_args[1].out[1] = ctx->ac.f32_0; /* Y */
2988 pos_args[1].out[2] = ctx->ac.f32_0; /* Z */
2989 pos_args[1].out[3] = ctx->ac.f32_0; /* W */
2990
2991 if (shader->selector->info.writes_psize)
2992 pos_args[1].out[0] = psize_value;
2993
2994 if (shader->selector->pos_writes_edgeflag) {
2995 /* The output is a float, but the hw expects an integer
2996 * with the first bit containing the edge flag. */
2997 edgeflag_value = LLVMBuildFPToUI(ctx->ac.builder,
2998 edgeflag_value,
2999 ctx->i32, "");
3000 edgeflag_value = ac_build_umin(&ctx->ac,
3001 edgeflag_value,
3002 ctx->i32_1);
3003
3004 /* The LLVM intrinsic expects a float. */
3005 pos_args[1].out[1] = ac_to_float(&ctx->ac, edgeflag_value);
3006 }
3007
3008 if (ctx->screen->info.chip_class >= GFX9) {
3009 /* GFX9 has the layer in out.z[10:0] and the viewport
3010 * index in out.z[19:16].
3011 */
3012 if (shader->selector->info.writes_layer)
3013 pos_args[1].out[2] = layer_value;
3014
3015 if (shader->selector->info.writes_viewport_index) {
3016 LLVMValueRef v = viewport_index_value;
3017
3018 v = ac_to_integer(&ctx->ac, v);
3019 v = LLVMBuildShl(ctx->ac.builder, v,
3020 LLVMConstInt(ctx->i32, 16, 0), "");
3021 v = LLVMBuildOr(ctx->ac.builder, v,
3022 ac_to_integer(&ctx->ac, pos_args[1].out[2]), "");
3023 pos_args[1].out[2] = ac_to_float(&ctx->ac, v);
3024 pos_args[1].enabled_channels |= 1 << 2;
3025 }
3026 } else {
3027 if (shader->selector->info.writes_layer)
3028 pos_args[1].out[2] = layer_value;
3029
3030 if (shader->selector->info.writes_viewport_index) {
3031 pos_args[1].out[3] = viewport_index_value;
3032 pos_args[1].enabled_channels |= 1 << 3;
3033 }
3034 }
3035 }
3036
3037 for (i = 0; i < 4; i++)
3038 if (pos_args[i].out[0])
3039 shader->info.nr_pos_exports++;
3040
3041 /* Navi10-14 skip POS0 exports if EXEC=0 and DONE=0, causing a hang.
3042 * Setting valid_mask=1 prevents it and has no other effect.
3043 */
3044 if (ctx->screen->info.family == CHIP_NAVI10 ||
3045 ctx->screen->info.family == CHIP_NAVI12 ||
3046 ctx->screen->info.family == CHIP_NAVI14)
3047 pos_args[0].valid_mask = 1;
3048
3049 pos_idx = 0;
3050 for (i = 0; i < 4; i++) {
3051 if (!pos_args[i].out[0])
3052 continue;
3053
3054 /* Specify the target we are exporting */
3055 pos_args[i].target = V_008DFC_SQ_EXP_POS + pos_idx++;
3056
3057 if (pos_idx == shader->info.nr_pos_exports)
3058 /* Specify that this is the last export */
3059 pos_args[i].done = 1;
3060
3061 ac_build_export(&ctx->ac, &pos_args[i]);
3062 }
3063
3064 /* Build parameter exports. */
3065 si_build_param_exports(ctx, outputs, noutput);
3066 }
3067
3068 /**
3069 * Forward all outputs from the vertex shader to the TES. This is only used
3070 * for the fixed function TCS.
3071 */
3072 static void si_copy_tcs_inputs(struct lp_build_tgsi_context *bld_base)
3073 {
3074 struct si_shader_context *ctx = si_shader_context(bld_base);
3075 LLVMValueRef invocation_id, buffer, buffer_offset;
3076 LLVMValueRef lds_vertex_stride, lds_base;
3077 uint64_t inputs;
3078
3079 invocation_id = unpack_llvm_param(ctx, ctx->abi.tcs_rel_ids, 8, 5);
3080 buffer = get_tess_ring_descriptor(ctx, TESS_OFFCHIP_RING_TCS);
3081 buffer_offset = LLVMGetParam(ctx->main_fn, ctx->param_tcs_offchip_offset);
3082
3083 lds_vertex_stride = get_tcs_in_vertex_dw_stride(ctx);
3084 lds_base = get_tcs_in_current_patch_offset(ctx);
3085 lds_base = ac_build_imad(&ctx->ac, invocation_id, lds_vertex_stride,
3086 lds_base);
3087
3088 inputs = ctx->shader->key.mono.u.ff_tcs_inputs_to_copy;
3089 while (inputs) {
3090 unsigned i = u_bit_scan64(&inputs);
3091
3092 LLVMValueRef lds_ptr = LLVMBuildAdd(ctx->ac.builder, lds_base,
3093 LLVMConstInt(ctx->i32, 4 * i, 0),
3094 "");
3095
3096 LLVMValueRef buffer_addr = get_tcs_tes_buffer_address(ctx,
3097 get_rel_patch_id(ctx),
3098 invocation_id,
3099 LLVMConstInt(ctx->i32, i, 0));
3100
3101 LLVMValueRef value = lshs_lds_load(bld_base, ctx->ac.i32, ~0, lds_ptr);
3102
3103 ac_build_buffer_store_dword(&ctx->ac, buffer, value, 4, buffer_addr,
3104 buffer_offset, 0, ac_glc, false);
3105 }
3106 }
3107
3108 static void si_write_tess_factors(struct lp_build_tgsi_context *bld_base,
3109 LLVMValueRef rel_patch_id,
3110 LLVMValueRef invocation_id,
3111 LLVMValueRef tcs_out_current_patch_data_offset,
3112 LLVMValueRef invoc0_tf_outer[4],
3113 LLVMValueRef invoc0_tf_inner[2])
3114 {
3115 struct si_shader_context *ctx = si_shader_context(bld_base);
3116 struct si_shader *shader = ctx->shader;
3117 unsigned tess_inner_index, tess_outer_index;
3118 LLVMValueRef lds_base, lds_inner, lds_outer, byteoffset, buffer;
3119 LLVMValueRef out[6], vec0, vec1, tf_base, inner[4], outer[4];
3120 unsigned stride, outer_comps, inner_comps, i, offset;
3121 struct lp_build_if_state if_ctx, inner_if_ctx;
3122
3123 /* Add a barrier before loading tess factors from LDS. */
3124 if (!shader->key.part.tcs.epilog.invoc0_tess_factors_are_def)
3125 si_llvm_emit_barrier(NULL, bld_base, NULL);
3126
3127 /* Do this only for invocation 0, because the tess levels are per-patch,
3128 * not per-vertex.
3129 *
3130 * This can't jump, because invocation 0 executes this. It should
3131 * at least mask out the loads and stores for other invocations.
3132 */
3133 lp_build_if(&if_ctx, &ctx->gallivm,
3134 LLVMBuildICmp(ctx->ac.builder, LLVMIntEQ,
3135 invocation_id, ctx->i32_0, ""));
3136
3137 /* Determine the layout of one tess factor element in the buffer. */
3138 switch (shader->key.part.tcs.epilog.prim_mode) {
3139 case PIPE_PRIM_LINES:
3140 stride = 2; /* 2 dwords, 1 vec2 store */
3141 outer_comps = 2;
3142 inner_comps = 0;
3143 break;
3144 case PIPE_PRIM_TRIANGLES:
3145 stride = 4; /* 4 dwords, 1 vec4 store */
3146 outer_comps = 3;
3147 inner_comps = 1;
3148 break;
3149 case PIPE_PRIM_QUADS:
3150 stride = 6; /* 6 dwords, 2 stores (vec4 + vec2) */
3151 outer_comps = 4;
3152 inner_comps = 2;
3153 break;
3154 default:
3155 assert(0);
3156 return;
3157 }
3158
3159 for (i = 0; i < 4; i++) {
3160 inner[i] = LLVMGetUndef(ctx->i32);
3161 outer[i] = LLVMGetUndef(ctx->i32);
3162 }
3163
3164 if (shader->key.part.tcs.epilog.invoc0_tess_factors_are_def) {
3165 /* Tess factors are in VGPRs. */
3166 for (i = 0; i < outer_comps; i++)
3167 outer[i] = out[i] = invoc0_tf_outer[i];
3168 for (i = 0; i < inner_comps; i++)
3169 inner[i] = out[outer_comps+i] = invoc0_tf_inner[i];
3170 } else {
3171 /* Load tess_inner and tess_outer from LDS.
3172 * Any invocation can write them, so we can't get them from a temporary.
3173 */
3174 tess_inner_index = si_shader_io_get_unique_index_patch(TGSI_SEMANTIC_TESSINNER, 0);
3175 tess_outer_index = si_shader_io_get_unique_index_patch(TGSI_SEMANTIC_TESSOUTER, 0);
3176
3177 lds_base = tcs_out_current_patch_data_offset;
3178 lds_inner = LLVMBuildAdd(ctx->ac.builder, lds_base,
3179 LLVMConstInt(ctx->i32,
3180 tess_inner_index * 4, 0), "");
3181 lds_outer = LLVMBuildAdd(ctx->ac.builder, lds_base,
3182 LLVMConstInt(ctx->i32,
3183 tess_outer_index * 4, 0), "");
3184
3185 for (i = 0; i < outer_comps; i++) {
3186 outer[i] = out[i] =
3187 lshs_lds_load(bld_base, ctx->ac.i32, i, lds_outer);
3188 }
3189 for (i = 0; i < inner_comps; i++) {
3190 inner[i] = out[outer_comps+i] =
3191 lshs_lds_load(bld_base, ctx->ac.i32, i, lds_inner);
3192 }
3193 }
3194
3195 if (shader->key.part.tcs.epilog.prim_mode == PIPE_PRIM_LINES) {
3196 /* For isolines, the hardware expects tess factors in the
3197 * reverse order from what GLSL / TGSI specify.
3198 */
3199 LLVMValueRef tmp = out[0];
3200 out[0] = out[1];
3201 out[1] = tmp;
3202 }
3203
3204 /* Convert the outputs to vectors for stores. */
3205 vec0 = ac_build_gather_values(&ctx->ac, out, MIN2(stride, 4));
3206 vec1 = NULL;
3207
3208 if (stride > 4)
3209 vec1 = ac_build_gather_values(&ctx->ac, out+4, stride - 4);
3210
3211 /* Get the buffer. */
3212 buffer = get_tess_ring_descriptor(ctx, TCS_FACTOR_RING);
3213
3214 /* Get the offset. */
3215 tf_base = LLVMGetParam(ctx->main_fn,
3216 ctx->param_tcs_factor_offset);
3217 byteoffset = LLVMBuildMul(ctx->ac.builder, rel_patch_id,
3218 LLVMConstInt(ctx->i32, 4 * stride, 0), "");
3219
3220 lp_build_if(&inner_if_ctx, &ctx->gallivm,
3221 LLVMBuildICmp(ctx->ac.builder, LLVMIntEQ,
3222 rel_patch_id, ctx->i32_0, ""));
3223
3224 /* Store the dynamic HS control word. */
3225 offset = 0;
3226 if (ctx->screen->info.chip_class <= GFX8) {
3227 ac_build_buffer_store_dword(&ctx->ac, buffer,
3228 LLVMConstInt(ctx->i32, 0x80000000, 0),
3229 1, ctx->i32_0, tf_base,
3230 offset, ac_glc, false);
3231 offset += 4;
3232 }
3233
3234 lp_build_endif(&inner_if_ctx);
3235
3236 /* Store the tessellation factors. */
3237 ac_build_buffer_store_dword(&ctx->ac, buffer, vec0,
3238 MIN2(stride, 4), byteoffset, tf_base,
3239 offset, ac_glc, false);
3240 offset += 16;
3241 if (vec1)
3242 ac_build_buffer_store_dword(&ctx->ac, buffer, vec1,
3243 stride - 4, byteoffset, tf_base,
3244 offset, ac_glc, false);
3245
3246 /* Store the tess factors into the offchip buffer if TES reads them. */
3247 if (shader->key.part.tcs.epilog.tes_reads_tess_factors) {
3248 LLVMValueRef buf, base, inner_vec, outer_vec, tf_outer_offset;
3249 LLVMValueRef tf_inner_offset;
3250 unsigned param_outer, param_inner;
3251
3252 buf = get_tess_ring_descriptor(ctx, TESS_OFFCHIP_RING_TCS);
3253 base = LLVMGetParam(ctx->main_fn, ctx->param_tcs_offchip_offset);
3254
3255 param_outer = si_shader_io_get_unique_index_patch(
3256 TGSI_SEMANTIC_TESSOUTER, 0);
3257 tf_outer_offset = get_tcs_tes_buffer_address(ctx, rel_patch_id, NULL,
3258 LLVMConstInt(ctx->i32, param_outer, 0));
3259
3260 unsigned outer_vec_size =
3261 ac_has_vec3_support(ctx->screen->info.chip_class, false) ?
3262 outer_comps : util_next_power_of_two(outer_comps);
3263 outer_vec = ac_build_gather_values(&ctx->ac, outer, outer_vec_size);
3264
3265 ac_build_buffer_store_dword(&ctx->ac, buf, outer_vec,
3266 outer_comps, tf_outer_offset,
3267 base, 0, ac_glc, false);
3268 if (inner_comps) {
3269 param_inner = si_shader_io_get_unique_index_patch(
3270 TGSI_SEMANTIC_TESSINNER, 0);
3271 tf_inner_offset = get_tcs_tes_buffer_address(ctx, rel_patch_id, NULL,
3272 LLVMConstInt(ctx->i32, param_inner, 0));
3273
3274 inner_vec = inner_comps == 1 ? inner[0] :
3275 ac_build_gather_values(&ctx->ac, inner, inner_comps);
3276 ac_build_buffer_store_dword(&ctx->ac, buf, inner_vec,
3277 inner_comps, tf_inner_offset,
3278 base, 0, ac_glc, false);
3279 }
3280 }
3281
3282 lp_build_endif(&if_ctx);
3283 }
3284
3285 static LLVMValueRef
3286 si_insert_input_ret(struct si_shader_context *ctx, LLVMValueRef ret,
3287 unsigned param, unsigned return_index)
3288 {
3289 return LLVMBuildInsertValue(ctx->ac.builder, ret,
3290 LLVMGetParam(ctx->main_fn, param),
3291 return_index, "");
3292 }
3293
3294 static LLVMValueRef
3295 si_insert_input_ret_float(struct si_shader_context *ctx, LLVMValueRef ret,
3296 unsigned param, unsigned return_index)
3297 {
3298 LLVMBuilderRef builder = ctx->ac.builder;
3299 LLVMValueRef p = LLVMGetParam(ctx->main_fn, param);
3300
3301 return LLVMBuildInsertValue(builder, ret,
3302 ac_to_float(&ctx->ac, p),
3303 return_index, "");
3304 }
3305
3306 static LLVMValueRef
3307 si_insert_input_ptr(struct si_shader_context *ctx, LLVMValueRef ret,
3308 unsigned param, unsigned return_index)
3309 {
3310 LLVMBuilderRef builder = ctx->ac.builder;
3311 LLVMValueRef ptr = LLVMGetParam(ctx->main_fn, param);
3312 ptr = LLVMBuildPtrToInt(builder, ptr, ctx->i32, "");
3313 return LLVMBuildInsertValue(builder, ret, ptr, return_index, "");
3314 }
3315
3316 /* This only writes the tessellation factor levels. */
3317 static void si_llvm_emit_tcs_epilogue(struct ac_shader_abi *abi,
3318 unsigned max_outputs,
3319 LLVMValueRef *addrs)
3320 {
3321 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
3322 struct lp_build_tgsi_context *bld_base = &ctx->bld_base;
3323 LLVMBuilderRef builder = ctx->ac.builder;
3324 LLVMValueRef rel_patch_id, invocation_id, tf_lds_offset;
3325
3326 si_copy_tcs_inputs(bld_base);
3327
3328 rel_patch_id = get_rel_patch_id(ctx);
3329 invocation_id = unpack_llvm_param(ctx, ctx->abi.tcs_rel_ids, 8, 5);
3330 tf_lds_offset = get_tcs_out_current_patch_data_offset(ctx);
3331
3332 if (ctx->screen->info.chip_class >= GFX9) {
3333 LLVMBasicBlockRef blocks[2] = {
3334 LLVMGetInsertBlock(builder),
3335 ctx->merged_wrap_if_state.entry_block
3336 };
3337 LLVMValueRef values[2];
3338
3339 lp_build_endif(&ctx->merged_wrap_if_state);
3340
3341 values[0] = rel_patch_id;
3342 values[1] = LLVMGetUndef(ctx->i32);
3343 rel_patch_id = ac_build_phi(&ctx->ac, ctx->i32, 2, values, blocks);
3344
3345 values[0] = tf_lds_offset;
3346 values[1] = LLVMGetUndef(ctx->i32);
3347 tf_lds_offset = ac_build_phi(&ctx->ac, ctx->i32, 2, values, blocks);
3348
3349 values[0] = invocation_id;
3350 values[1] = ctx->i32_1; /* cause the epilog to skip threads */
3351 invocation_id = ac_build_phi(&ctx->ac, ctx->i32, 2, values, blocks);
3352 }
3353
3354 /* Return epilog parameters from this function. */
3355 LLVMValueRef ret = ctx->return_value;
3356 unsigned vgpr;
3357
3358 if (ctx->screen->info.chip_class >= GFX9) {
3359 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_offchip_layout,
3360 8 + GFX9_SGPR_TCS_OFFCHIP_LAYOUT);
3361 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_out_lds_layout,
3362 8 + GFX9_SGPR_TCS_OUT_LAYOUT);
3363 /* Tess offchip and tess factor offsets are at the beginning. */
3364 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_offchip_offset, 2);
3365 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_factor_offset, 4);
3366 vgpr = 8 + GFX9_SGPR_TCS_OUT_LAYOUT + 1;
3367 } else {
3368 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_offchip_layout,
3369 GFX6_SGPR_TCS_OFFCHIP_LAYOUT);
3370 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_out_lds_layout,
3371 GFX6_SGPR_TCS_OUT_LAYOUT);
3372 /* Tess offchip and tess factor offsets are after user SGPRs. */
3373 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_offchip_offset,
3374 GFX6_TCS_NUM_USER_SGPR);
3375 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_factor_offset,
3376 GFX6_TCS_NUM_USER_SGPR + 1);
3377 vgpr = GFX6_TCS_NUM_USER_SGPR + 2;
3378 }
3379
3380 /* VGPRs */
3381 rel_patch_id = ac_to_float(&ctx->ac, rel_patch_id);
3382 invocation_id = ac_to_float(&ctx->ac, invocation_id);
3383 tf_lds_offset = ac_to_float(&ctx->ac, tf_lds_offset);
3384
3385 /* Leave a hole corresponding to the two input VGPRs. This ensures that
3386 * the invocation_id output does not alias the tcs_rel_ids input,
3387 * which saves a V_MOV on gfx9.
3388 */
3389 vgpr += 2;
3390
3391 ret = LLVMBuildInsertValue(builder, ret, rel_patch_id, vgpr++, "");
3392 ret = LLVMBuildInsertValue(builder, ret, invocation_id, vgpr++, "");
3393
3394 if (ctx->shader->selector->tcs_info.tessfactors_are_def_in_all_invocs) {
3395 vgpr++; /* skip the tess factor LDS offset */
3396 for (unsigned i = 0; i < 6; i++) {
3397 LLVMValueRef value =
3398 LLVMBuildLoad(builder, ctx->invoc0_tess_factors[i], "");
3399 value = ac_to_float(&ctx->ac, value);
3400 ret = LLVMBuildInsertValue(builder, ret, value, vgpr++, "");
3401 }
3402 } else {
3403 ret = LLVMBuildInsertValue(builder, ret, tf_lds_offset, vgpr++, "");
3404 }
3405 ctx->return_value = ret;
3406 }
3407
3408 /* Pass TCS inputs from LS to TCS on GFX9. */
3409 static void si_set_ls_return_value_for_tcs(struct si_shader_context *ctx)
3410 {
3411 LLVMValueRef ret = ctx->return_value;
3412
3413 ret = si_insert_input_ptr(ctx, ret, 0, 0);
3414 ret = si_insert_input_ptr(ctx, ret, 1, 1);
3415 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_offchip_offset, 2);
3416 ret = si_insert_input_ret(ctx, ret, ctx->param_merged_wave_info, 3);
3417 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_factor_offset, 4);
3418 ret = si_insert_input_ret(ctx, ret, ctx->param_merged_scratch_offset, 5);
3419
3420 ret = si_insert_input_ptr(ctx, ret, ctx->param_rw_buffers,
3421 8 + SI_SGPR_RW_BUFFERS);
3422 ret = si_insert_input_ptr(ctx, ret,
3423 ctx->param_bindless_samplers_and_images,
3424 8 + SI_SGPR_BINDLESS_SAMPLERS_AND_IMAGES);
3425
3426 ret = si_insert_input_ret(ctx, ret, ctx->param_vs_state_bits,
3427 8 + SI_SGPR_VS_STATE_BITS);
3428
3429 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_offchip_layout,
3430 8 + GFX9_SGPR_TCS_OFFCHIP_LAYOUT);
3431 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_out_lds_offsets,
3432 8 + GFX9_SGPR_TCS_OUT_OFFSETS);
3433 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_out_lds_layout,
3434 8 + GFX9_SGPR_TCS_OUT_LAYOUT);
3435
3436 unsigned vgpr = 8 + GFX9_TCS_NUM_USER_SGPR;
3437 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
3438 ac_to_float(&ctx->ac, ctx->abi.tcs_patch_id),
3439 vgpr++, "");
3440 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
3441 ac_to_float(&ctx->ac, ctx->abi.tcs_rel_ids),
3442 vgpr++, "");
3443 ctx->return_value = ret;
3444 }
3445
3446 /* Pass GS inputs from ES to GS on GFX9. */
3447 static void si_set_es_return_value_for_gs(struct si_shader_context *ctx)
3448 {
3449 LLVMBuilderRef builder = ctx->ac.builder;
3450 LLVMValueRef ret = ctx->return_value;
3451
3452 ret = si_insert_input_ptr(ctx, ret, 0, 0);
3453 ret = si_insert_input_ptr(ctx, ret, 1, 1);
3454 if (ctx->shader->key.as_ngg)
3455 ret = LLVMBuildInsertValue(builder, ret, ctx->gs_tg_info, 2, "");
3456 else
3457 ret = si_insert_input_ret(ctx, ret, ctx->param_gs2vs_offset, 2);
3458 ret = si_insert_input_ret(ctx, ret, ctx->param_merged_wave_info, 3);
3459 ret = si_insert_input_ret(ctx, ret, ctx->param_merged_scratch_offset, 5);
3460
3461 ret = si_insert_input_ptr(ctx, ret, ctx->param_rw_buffers,
3462 8 + SI_SGPR_RW_BUFFERS);
3463 ret = si_insert_input_ptr(ctx, ret,
3464 ctx->param_bindless_samplers_and_images,
3465 8 + SI_SGPR_BINDLESS_SAMPLERS_AND_IMAGES);
3466 if (ctx->screen->info.chip_class >= GFX10) {
3467 ret = si_insert_input_ptr(ctx, ret, ctx->param_vs_state_bits,
3468 8 + SI_SGPR_VS_STATE_BITS);
3469 }
3470
3471 unsigned vgpr;
3472 if (ctx->type == PIPE_SHADER_VERTEX)
3473 vgpr = 8 + GFX9_VSGS_NUM_USER_SGPR;
3474 else
3475 vgpr = 8 + GFX9_TESGS_NUM_USER_SGPR;
3476
3477 for (unsigned i = 0; i < 5; i++) {
3478 unsigned param = ctx->param_gs_vtx01_offset + i;
3479 ret = si_insert_input_ret_float(ctx, ret, param, vgpr++);
3480 }
3481 ctx->return_value = ret;
3482 }
3483
3484 static void si_llvm_emit_ls_epilogue(struct ac_shader_abi *abi,
3485 unsigned max_outputs,
3486 LLVMValueRef *addrs)
3487 {
3488 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
3489 struct si_shader *shader = ctx->shader;
3490 struct tgsi_shader_info *info = &shader->selector->info;
3491 unsigned i, chan;
3492 LLVMValueRef vertex_id = LLVMGetParam(ctx->main_fn,
3493 ctx->param_rel_auto_id);
3494 LLVMValueRef vertex_dw_stride = get_tcs_in_vertex_dw_stride(ctx);
3495 LLVMValueRef base_dw_addr = LLVMBuildMul(ctx->ac.builder, vertex_id,
3496 vertex_dw_stride, "");
3497
3498 /* Write outputs to LDS. The next shader (TCS aka HS) will read
3499 * its inputs from it. */
3500 for (i = 0; i < info->num_outputs; i++) {
3501 unsigned name = info->output_semantic_name[i];
3502 unsigned index = info->output_semantic_index[i];
3503
3504 /* The ARB_shader_viewport_layer_array spec contains the
3505 * following issue:
3506 *
3507 * 2) What happens if gl_ViewportIndex or gl_Layer is
3508 * written in the vertex shader and a geometry shader is
3509 * present?
3510 *
3511 * RESOLVED: The value written by the last vertex processing
3512 * stage is used. If the last vertex processing stage
3513 * (vertex, tessellation evaluation or geometry) does not
3514 * statically assign to gl_ViewportIndex or gl_Layer, index
3515 * or layer zero is assumed.
3516 *
3517 * So writes to those outputs in VS-as-LS are simply ignored.
3518 */
3519 if (name == TGSI_SEMANTIC_LAYER ||
3520 name == TGSI_SEMANTIC_VIEWPORT_INDEX)
3521 continue;
3522
3523 int param = si_shader_io_get_unique_index(name, index, false);
3524 LLVMValueRef dw_addr = LLVMBuildAdd(ctx->ac.builder, base_dw_addr,
3525 LLVMConstInt(ctx->i32, param * 4, 0), "");
3526
3527 for (chan = 0; chan < 4; chan++) {
3528 if (!(info->output_usagemask[i] & (1 << chan)))
3529 continue;
3530
3531 lshs_lds_store(ctx, chan, dw_addr,
3532 LLVMBuildLoad(ctx->ac.builder, addrs[4 * i + chan], ""));
3533 }
3534 }
3535
3536 if (ctx->screen->info.chip_class >= GFX9)
3537 si_set_ls_return_value_for_tcs(ctx);
3538 }
3539
3540 static void si_llvm_emit_es_epilogue(struct ac_shader_abi *abi,
3541 unsigned max_outputs,
3542 LLVMValueRef *addrs)
3543 {
3544 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
3545 struct si_shader *es = ctx->shader;
3546 struct tgsi_shader_info *info = &es->selector->info;
3547 LLVMValueRef soffset = LLVMGetParam(ctx->main_fn,
3548 ctx->param_es2gs_offset);
3549 LLVMValueRef lds_base = NULL;
3550 unsigned chan;
3551 int i;
3552
3553 if (ctx->screen->info.chip_class >= GFX9 && info->num_outputs) {
3554 unsigned itemsize_dw = es->selector->esgs_itemsize / 4;
3555 LLVMValueRef vertex_idx = ac_get_thread_id(&ctx->ac);
3556 LLVMValueRef wave_idx = si_unpack_param(ctx, ctx->param_merged_wave_info, 24, 4);
3557 vertex_idx = LLVMBuildOr(ctx->ac.builder, vertex_idx,
3558 LLVMBuildMul(ctx->ac.builder, wave_idx,
3559 LLVMConstInt(ctx->i32, ctx->ac.wave_size, false), ""), "");
3560 lds_base = LLVMBuildMul(ctx->ac.builder, vertex_idx,
3561 LLVMConstInt(ctx->i32, itemsize_dw, 0), "");
3562 }
3563
3564 for (i = 0; i < info->num_outputs; i++) {
3565 int param;
3566
3567 if (info->output_semantic_name[i] == TGSI_SEMANTIC_VIEWPORT_INDEX ||
3568 info->output_semantic_name[i] == TGSI_SEMANTIC_LAYER)
3569 continue;
3570
3571 param = si_shader_io_get_unique_index(info->output_semantic_name[i],
3572 info->output_semantic_index[i], false);
3573
3574 for (chan = 0; chan < 4; chan++) {
3575 if (!(info->output_usagemask[i] & (1 << chan)))
3576 continue;
3577
3578 LLVMValueRef out_val = LLVMBuildLoad(ctx->ac.builder, addrs[4 * i + chan], "");
3579 out_val = ac_to_integer(&ctx->ac, out_val);
3580
3581 /* GFX9 has the ESGS ring in LDS. */
3582 if (ctx->screen->info.chip_class >= GFX9) {
3583 LLVMValueRef idx = LLVMConstInt(ctx->i32, param * 4 + chan, false);
3584 idx = LLVMBuildAdd(ctx->ac.builder, lds_base, idx, "");
3585 ac_build_indexed_store(&ctx->ac, ctx->esgs_ring, idx, out_val);
3586 continue;
3587 }
3588
3589 ac_build_buffer_store_dword(&ctx->ac,
3590 ctx->esgs_ring,
3591 out_val, 1, NULL, soffset,
3592 (4 * param + chan) * 4,
3593 ac_glc | ac_slc, true);
3594 }
3595 }
3596
3597 if (ctx->screen->info.chip_class >= GFX9)
3598 si_set_es_return_value_for_gs(ctx);
3599 }
3600
3601 static LLVMValueRef si_get_gs_wave_id(struct si_shader_context *ctx)
3602 {
3603 if (ctx->screen->info.chip_class >= GFX9)
3604 return si_unpack_param(ctx, ctx->param_merged_wave_info, 16, 8);
3605 else
3606 return LLVMGetParam(ctx->main_fn, ctx->param_gs_wave_id);
3607 }
3608
3609 static void emit_gs_epilogue(struct si_shader_context *ctx)
3610 {
3611 if (ctx->shader->key.as_ngg) {
3612 gfx10_ngg_gs_emit_epilogue(ctx);
3613 return;
3614 }
3615
3616 if (ctx->screen->info.chip_class >= GFX10)
3617 LLVMBuildFence(ctx->ac.builder, LLVMAtomicOrderingRelease, false, "");
3618
3619 ac_build_sendmsg(&ctx->ac, AC_SENDMSG_GS_OP_NOP | AC_SENDMSG_GS_DONE,
3620 si_get_gs_wave_id(ctx));
3621
3622 if (ctx->screen->info.chip_class >= GFX9)
3623 lp_build_endif(&ctx->merged_wrap_if_state);
3624 }
3625
3626 static void si_llvm_emit_gs_epilogue(struct ac_shader_abi *abi,
3627 unsigned max_outputs,
3628 LLVMValueRef *addrs)
3629 {
3630 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
3631 struct tgsi_shader_info UNUSED *info = &ctx->shader->selector->info;
3632
3633 assert(info->num_outputs <= max_outputs);
3634
3635 emit_gs_epilogue(ctx);
3636 }
3637
3638 static void si_tgsi_emit_gs_epilogue(struct lp_build_tgsi_context *bld_base)
3639 {
3640 struct si_shader_context *ctx = si_shader_context(bld_base);
3641 emit_gs_epilogue(ctx);
3642 }
3643
3644 static void si_llvm_emit_vs_epilogue(struct ac_shader_abi *abi,
3645 unsigned max_outputs,
3646 LLVMValueRef *addrs)
3647 {
3648 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
3649 struct tgsi_shader_info *info = &ctx->shader->selector->info;
3650 struct si_shader_output_values *outputs = NULL;
3651 int i,j;
3652
3653 assert(!ctx->shader->is_gs_copy_shader);
3654 assert(info->num_outputs <= max_outputs);
3655
3656 outputs = MALLOC((info->num_outputs + 1) * sizeof(outputs[0]));
3657
3658 for (i = 0; i < info->num_outputs; i++) {
3659 outputs[i].semantic_name = info->output_semantic_name[i];
3660 outputs[i].semantic_index = info->output_semantic_index[i];
3661
3662 for (j = 0; j < 4; j++) {
3663 outputs[i].values[j] =
3664 LLVMBuildLoad(ctx->ac.builder,
3665 addrs[4 * i + j],
3666 "");
3667 outputs[i].vertex_stream[j] =
3668 (info->output_streams[i] >> (2 * j)) & 3;
3669 }
3670 }
3671
3672 if (ctx->ac.chip_class <= GFX9 &&
3673 ctx->shader->selector->so.num_outputs)
3674 si_llvm_emit_streamout(ctx, outputs, i, 0);
3675
3676 /* Export PrimitiveID. */
3677 if (ctx->shader->key.mono.u.vs_export_prim_id) {
3678 outputs[i].semantic_name = TGSI_SEMANTIC_PRIMID;
3679 outputs[i].semantic_index = 0;
3680 outputs[i].values[0] = ac_to_float(&ctx->ac, si_get_primitive_id(ctx, 0));
3681 for (j = 1; j < 4; j++)
3682 outputs[i].values[j] = LLVMConstReal(ctx->f32, 0);
3683
3684 memset(outputs[i].vertex_stream, 0,
3685 sizeof(outputs[i].vertex_stream));
3686 i++;
3687 }
3688
3689 si_llvm_export_vs(ctx, outputs, i);
3690 FREE(outputs);
3691 }
3692
3693 static void si_llvm_emit_prim_discard_cs_epilogue(struct ac_shader_abi *abi,
3694 unsigned max_outputs,
3695 LLVMValueRef *addrs)
3696 {
3697 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
3698 struct tgsi_shader_info *info = &ctx->shader->selector->info;
3699 LLVMValueRef pos[4] = {};
3700
3701 assert(info->num_outputs <= max_outputs);
3702
3703 for (unsigned i = 0; i < info->num_outputs; i++) {
3704 if (info->output_semantic_name[i] != TGSI_SEMANTIC_POSITION)
3705 continue;
3706
3707 for (unsigned chan = 0; chan < 4; chan++)
3708 pos[chan] = LLVMBuildLoad(ctx->ac.builder, addrs[4 * i + chan], "");
3709 break;
3710 }
3711 assert(pos[0] != NULL);
3712
3713 /* Return the position output. */
3714 LLVMValueRef ret = ctx->return_value;
3715 for (unsigned chan = 0; chan < 4; chan++)
3716 ret = LLVMBuildInsertValue(ctx->ac.builder, ret, pos[chan], chan, "");
3717 ctx->return_value = ret;
3718 }
3719
3720 static void si_tgsi_emit_epilogue(struct lp_build_tgsi_context *bld_base)
3721 {
3722 struct si_shader_context *ctx = si_shader_context(bld_base);
3723
3724 ctx->abi.emit_outputs(&ctx->abi, RADEON_LLVM_MAX_OUTPUTS,
3725 &ctx->outputs[0][0]);
3726 }
3727
3728 struct si_ps_exports {
3729 unsigned num;
3730 struct ac_export_args args[10];
3731 };
3732
3733 static void si_export_mrt_z(struct lp_build_tgsi_context *bld_base,
3734 LLVMValueRef depth, LLVMValueRef stencil,
3735 LLVMValueRef samplemask, struct si_ps_exports *exp)
3736 {
3737 struct si_shader_context *ctx = si_shader_context(bld_base);
3738 struct ac_export_args args;
3739
3740 ac_export_mrt_z(&ctx->ac, depth, stencil, samplemask, &args);
3741
3742 memcpy(&exp->args[exp->num++], &args, sizeof(args));
3743 }
3744
3745 static void si_export_mrt_color(struct lp_build_tgsi_context *bld_base,
3746 LLVMValueRef *color, unsigned index,
3747 unsigned samplemask_param,
3748 bool is_last, struct si_ps_exports *exp)
3749 {
3750 struct si_shader_context *ctx = si_shader_context(bld_base);
3751 int i;
3752
3753 /* Clamp color */
3754 if (ctx->shader->key.part.ps.epilog.clamp_color)
3755 for (i = 0; i < 4; i++)
3756 color[i] = ac_build_clamp(&ctx->ac, color[i]);
3757
3758 /* Alpha to one */
3759 if (ctx->shader->key.part.ps.epilog.alpha_to_one)
3760 color[3] = ctx->ac.f32_1;
3761
3762 /* Alpha test */
3763 if (index == 0 &&
3764 ctx->shader->key.part.ps.epilog.alpha_func != PIPE_FUNC_ALWAYS)
3765 si_alpha_test(bld_base, color[3]);
3766
3767 /* Line & polygon smoothing */
3768 if (ctx->shader->key.part.ps.epilog.poly_line_smoothing)
3769 color[3] = si_scale_alpha_by_sample_mask(bld_base, color[3],
3770 samplemask_param);
3771
3772 /* If last_cbuf > 0, FS_COLOR0_WRITES_ALL_CBUFS is true. */
3773 if (ctx->shader->key.part.ps.epilog.last_cbuf > 0) {
3774 struct ac_export_args args[8];
3775 int c, last = -1;
3776
3777 /* Get the export arguments, also find out what the last one is. */
3778 for (c = 0; c <= ctx->shader->key.part.ps.epilog.last_cbuf; c++) {
3779 si_llvm_init_export_args(ctx, color,
3780 V_008DFC_SQ_EXP_MRT + c, &args[c]);
3781 if (args[c].enabled_channels)
3782 last = c;
3783 }
3784
3785 /* Emit all exports. */
3786 for (c = 0; c <= ctx->shader->key.part.ps.epilog.last_cbuf; c++) {
3787 if (is_last && last == c) {
3788 args[c].valid_mask = 1; /* whether the EXEC mask is valid */
3789 args[c].done = 1; /* DONE bit */
3790 } else if (!args[c].enabled_channels)
3791 continue; /* unnecessary NULL export */
3792
3793 memcpy(&exp->args[exp->num++], &args[c], sizeof(args[c]));
3794 }
3795 } else {
3796 struct ac_export_args args;
3797
3798 /* Export */
3799 si_llvm_init_export_args(ctx, color, V_008DFC_SQ_EXP_MRT + index,
3800 &args);
3801 if (is_last) {
3802 args.valid_mask = 1; /* whether the EXEC mask is valid */
3803 args.done = 1; /* DONE bit */
3804 } else if (!args.enabled_channels)
3805 return; /* unnecessary NULL export */
3806
3807 memcpy(&exp->args[exp->num++], &args, sizeof(args));
3808 }
3809 }
3810
3811 static void si_emit_ps_exports(struct si_shader_context *ctx,
3812 struct si_ps_exports *exp)
3813 {
3814 for (unsigned i = 0; i < exp->num; i++)
3815 ac_build_export(&ctx->ac, &exp->args[i]);
3816 }
3817
3818 /**
3819 * Return PS outputs in this order:
3820 *
3821 * v[0:3] = color0.xyzw
3822 * v[4:7] = color1.xyzw
3823 * ...
3824 * vN+0 = Depth
3825 * vN+1 = Stencil
3826 * vN+2 = SampleMask
3827 * vN+3 = SampleMaskIn (used for OpenGL smoothing)
3828 *
3829 * The alpha-ref SGPR is returned via its original location.
3830 */
3831 static void si_llvm_return_fs_outputs(struct ac_shader_abi *abi,
3832 unsigned max_outputs,
3833 LLVMValueRef *addrs)
3834 {
3835 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
3836 struct si_shader *shader = ctx->shader;
3837 struct tgsi_shader_info *info = &shader->selector->info;
3838 LLVMBuilderRef builder = ctx->ac.builder;
3839 unsigned i, j, first_vgpr, vgpr;
3840
3841 LLVMValueRef color[8][4] = {};
3842 LLVMValueRef depth = NULL, stencil = NULL, samplemask = NULL;
3843 LLVMValueRef ret;
3844
3845 if (ctx->postponed_kill)
3846 ac_build_kill_if_false(&ctx->ac, LLVMBuildLoad(builder, ctx->postponed_kill, ""));
3847
3848 /* Read the output values. */
3849 for (i = 0; i < info->num_outputs; i++) {
3850 unsigned semantic_name = info->output_semantic_name[i];
3851 unsigned semantic_index = info->output_semantic_index[i];
3852
3853 switch (semantic_name) {
3854 case TGSI_SEMANTIC_COLOR:
3855 assert(semantic_index < 8);
3856 for (j = 0; j < 4; j++) {
3857 LLVMValueRef ptr = addrs[4 * i + j];
3858 LLVMValueRef result = LLVMBuildLoad(builder, ptr, "");
3859 color[semantic_index][j] = result;
3860 }
3861 break;
3862 case TGSI_SEMANTIC_POSITION:
3863 depth = LLVMBuildLoad(builder,
3864 addrs[4 * i + 2], "");
3865 break;
3866 case TGSI_SEMANTIC_STENCIL:
3867 stencil = LLVMBuildLoad(builder,
3868 addrs[4 * i + 1], "");
3869 break;
3870 case TGSI_SEMANTIC_SAMPLEMASK:
3871 samplemask = LLVMBuildLoad(builder,
3872 addrs[4 * i + 0], "");
3873 break;
3874 default:
3875 fprintf(stderr, "Warning: GFX6 unhandled fs output type:%d\n",
3876 semantic_name);
3877 }
3878 }
3879
3880 /* Fill the return structure. */
3881 ret = ctx->return_value;
3882
3883 /* Set SGPRs. */
3884 ret = LLVMBuildInsertValue(builder, ret,
3885 ac_to_integer(&ctx->ac,
3886 LLVMGetParam(ctx->main_fn,
3887 SI_PARAM_ALPHA_REF)),
3888 SI_SGPR_ALPHA_REF, "");
3889
3890 /* Set VGPRs */
3891 first_vgpr = vgpr = SI_SGPR_ALPHA_REF + 1;
3892 for (i = 0; i < ARRAY_SIZE(color); i++) {
3893 if (!color[i][0])
3894 continue;
3895
3896 for (j = 0; j < 4; j++)
3897 ret = LLVMBuildInsertValue(builder, ret, color[i][j], vgpr++, "");
3898 }
3899 if (depth)
3900 ret = LLVMBuildInsertValue(builder, ret, depth, vgpr++, "");
3901 if (stencil)
3902 ret = LLVMBuildInsertValue(builder, ret, stencil, vgpr++, "");
3903 if (samplemask)
3904 ret = LLVMBuildInsertValue(builder, ret, samplemask, vgpr++, "");
3905
3906 /* Add the input sample mask for smoothing at the end. */
3907 if (vgpr < first_vgpr + PS_EPILOG_SAMPLEMASK_MIN_LOC)
3908 vgpr = first_vgpr + PS_EPILOG_SAMPLEMASK_MIN_LOC;
3909 ret = LLVMBuildInsertValue(builder, ret,
3910 LLVMGetParam(ctx->main_fn,
3911 SI_PARAM_SAMPLE_COVERAGE), vgpr++, "");
3912
3913 ctx->return_value = ret;
3914 }
3915
3916 static void membar_emit(
3917 const struct lp_build_tgsi_action *action,
3918 struct lp_build_tgsi_context *bld_base,
3919 struct lp_build_emit_data *emit_data)
3920 {
3921 struct si_shader_context *ctx = si_shader_context(bld_base);
3922 LLVMValueRef src0 = lp_build_emit_fetch(bld_base, emit_data->inst, 0, 0);
3923 unsigned flags = LLVMConstIntGetZExtValue(src0);
3924 unsigned wait_flags = 0;
3925
3926 if (flags & TGSI_MEMBAR_THREAD_GROUP)
3927 wait_flags |= AC_WAIT_LGKM | AC_WAIT_VLOAD | AC_WAIT_VSTORE;
3928
3929 if (flags & (TGSI_MEMBAR_ATOMIC_BUFFER |
3930 TGSI_MEMBAR_SHADER_BUFFER |
3931 TGSI_MEMBAR_SHADER_IMAGE))
3932 wait_flags |= AC_WAIT_VLOAD | AC_WAIT_VSTORE;
3933
3934 if (flags & TGSI_MEMBAR_SHARED)
3935 wait_flags |= AC_WAIT_LGKM;
3936
3937 ac_build_waitcnt(&ctx->ac, wait_flags);
3938 }
3939
3940 static void clock_emit(
3941 const struct lp_build_tgsi_action *action,
3942 struct lp_build_tgsi_context *bld_base,
3943 struct lp_build_emit_data *emit_data)
3944 {
3945 struct si_shader_context *ctx = si_shader_context(bld_base);
3946 LLVMValueRef tmp = ac_build_shader_clock(&ctx->ac);
3947
3948 emit_data->output[0] =
3949 LLVMBuildExtractElement(ctx->ac.builder, tmp, ctx->i32_0, "");
3950 emit_data->output[1] =
3951 LLVMBuildExtractElement(ctx->ac.builder, tmp, ctx->i32_1, "");
3952 }
3953
3954 static void si_llvm_emit_ddxy(
3955 const struct lp_build_tgsi_action *action,
3956 struct lp_build_tgsi_context *bld_base,
3957 struct lp_build_emit_data *emit_data)
3958 {
3959 struct si_shader_context *ctx = si_shader_context(bld_base);
3960 unsigned opcode = emit_data->info->opcode;
3961 LLVMValueRef val;
3962 int idx;
3963 unsigned mask;
3964
3965 if (opcode == TGSI_OPCODE_DDX_FINE)
3966 mask = AC_TID_MASK_LEFT;
3967 else if (opcode == TGSI_OPCODE_DDY_FINE)
3968 mask = AC_TID_MASK_TOP;
3969 else
3970 mask = AC_TID_MASK_TOP_LEFT;
3971
3972 /* for DDX we want to next X pixel, DDY next Y pixel. */
3973 idx = (opcode == TGSI_OPCODE_DDX || opcode == TGSI_OPCODE_DDX_FINE) ? 1 : 2;
3974
3975 val = ac_to_integer(&ctx->ac, emit_data->args[0]);
3976 val = ac_build_ddxy(&ctx->ac, mask, idx, val);
3977 emit_data->output[emit_data->chan] = val;
3978 }
3979
3980 static void build_interp_intrinsic(const struct lp_build_tgsi_action *action,
3981 struct lp_build_tgsi_context *bld_base,
3982 struct lp_build_emit_data *emit_data)
3983 {
3984 struct si_shader_context *ctx = si_shader_context(bld_base);
3985 struct si_shader *shader = ctx->shader;
3986 const struct tgsi_shader_info *info = &shader->selector->info;
3987 LLVMValueRef interp_param;
3988 const struct tgsi_full_instruction *inst = emit_data->inst;
3989 const struct tgsi_full_src_register *input = &inst->Src[0];
3990 int input_base, input_array_size;
3991 int chan;
3992 int i;
3993 LLVMValueRef prim_mask = ctx->abi.prim_mask;
3994 LLVMValueRef array_idx, offset_x = NULL, offset_y = NULL;
3995 int interp_param_idx;
3996 unsigned interp;
3997 unsigned location;
3998
3999 if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_OFFSET) {
4000 /* offset is in second src, first two channels */
4001 offset_x = lp_build_emit_fetch(bld_base, emit_data->inst, 1,
4002 TGSI_CHAN_X);
4003 offset_y = lp_build_emit_fetch(bld_base, emit_data->inst, 1,
4004 TGSI_CHAN_Y);
4005 } else if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_SAMPLE) {
4006 LLVMValueRef sample_position;
4007 LLVMValueRef sample_id;
4008 LLVMValueRef halfval = LLVMConstReal(ctx->f32, 0.5f);
4009
4010 /* fetch sample ID, then fetch its sample position,
4011 * and place into first two channels.
4012 */
4013 sample_id = lp_build_emit_fetch(bld_base,
4014 emit_data->inst, 1, TGSI_CHAN_X);
4015 sample_id = ac_to_integer(&ctx->ac, sample_id);
4016
4017 /* Section 8.13.2 (Interpolation Functions) of the OpenGL Shading
4018 * Language 4.50 spec says about interpolateAtSample:
4019 *
4020 * "Returns the value of the input interpolant variable at
4021 * the location of sample number sample. If multisample
4022 * buffers are not available, the input variable will be
4023 * evaluated at the center of the pixel. If sample sample
4024 * does not exist, the position used to interpolate the
4025 * input variable is undefined."
4026 *
4027 * This means that sample_id values outside of the valid are
4028 * in fact valid input, and the usual mechanism for loading the
4029 * sample position doesn't work.
4030 */
4031 if (ctx->shader->key.mono.u.ps.interpolate_at_sample_force_center) {
4032 LLVMValueRef center[4] = {
4033 LLVMConstReal(ctx->f32, 0.5),
4034 LLVMConstReal(ctx->f32, 0.5),
4035 ctx->ac.f32_0,
4036 ctx->ac.f32_0,
4037 };
4038
4039 sample_position = ac_build_gather_values(&ctx->ac, center, 4);
4040 } else {
4041 sample_position = load_sample_position(&ctx->abi, sample_id);
4042 }
4043
4044 offset_x = LLVMBuildExtractElement(ctx->ac.builder, sample_position,
4045 ctx->i32_0, "");
4046
4047 offset_x = LLVMBuildFSub(ctx->ac.builder, offset_x, halfval, "");
4048 offset_y = LLVMBuildExtractElement(ctx->ac.builder, sample_position,
4049 ctx->i32_1, "");
4050 offset_y = LLVMBuildFSub(ctx->ac.builder, offset_y, halfval, "");
4051 }
4052
4053 assert(input->Register.File == TGSI_FILE_INPUT);
4054
4055 if (input->Register.Indirect) {
4056 unsigned array_id = input->Indirect.ArrayID;
4057
4058 if (array_id) {
4059 input_base = info->input_array_first[array_id];
4060 input_array_size = info->input_array_last[array_id] - input_base + 1;
4061 } else {
4062 input_base = inst->Src[0].Register.Index;
4063 input_array_size = info->num_inputs - input_base;
4064 }
4065
4066 array_idx = si_get_indirect_index(ctx, &input->Indirect,
4067 1, input->Register.Index - input_base);
4068 } else {
4069 input_base = inst->Src[0].Register.Index;
4070 input_array_size = 1;
4071 array_idx = ctx->i32_0;
4072 }
4073
4074 interp = shader->selector->info.input_interpolate[input_base];
4075
4076 if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_OFFSET ||
4077 inst->Instruction.Opcode == TGSI_OPCODE_INTERP_SAMPLE)
4078 location = TGSI_INTERPOLATE_LOC_CENTER;
4079 else
4080 location = TGSI_INTERPOLATE_LOC_CENTROID;
4081
4082 interp_param_idx = lookup_interp_param_index(interp, location);
4083 if (interp_param_idx == -1)
4084 return;
4085 else if (interp_param_idx)
4086 interp_param = LLVMGetParam(ctx->main_fn, interp_param_idx);
4087 else
4088 interp_param = NULL;
4089
4090 if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_OFFSET ||
4091 inst->Instruction.Opcode == TGSI_OPCODE_INTERP_SAMPLE) {
4092 LLVMValueRef ij_out[2];
4093 LLVMValueRef ddxy_out = ac_build_ddxy_interp(&ctx->ac, interp_param);
4094
4095 /*
4096 * take the I then J parameters, and the DDX/Y for it, and
4097 * calculate the IJ inputs for the interpolator.
4098 * temp1 = ddx * offset/sample.x + I;
4099 * interp_param.I = ddy * offset/sample.y + temp1;
4100 * temp1 = ddx * offset/sample.x + J;
4101 * interp_param.J = ddy * offset/sample.y + temp1;
4102 */
4103 for (i = 0; i < 2; i++) {
4104 LLVMValueRef ix_ll = LLVMConstInt(ctx->i32, i, 0);
4105 LLVMValueRef iy_ll = LLVMConstInt(ctx->i32, i + 2, 0);
4106 LLVMValueRef ddx_el = LLVMBuildExtractElement(ctx->ac.builder,
4107 ddxy_out, ix_ll, "");
4108 LLVMValueRef ddy_el = LLVMBuildExtractElement(ctx->ac.builder,
4109 ddxy_out, iy_ll, "");
4110 LLVMValueRef interp_el = LLVMBuildExtractElement(ctx->ac.builder,
4111 interp_param, ix_ll, "");
4112 LLVMValueRef temp;
4113
4114 interp_el = ac_to_float(&ctx->ac, interp_el);
4115
4116 temp = ac_build_fmad(&ctx->ac, ddx_el, offset_x, interp_el);
4117 ij_out[i] = ac_build_fmad(&ctx->ac, ddy_el, offset_y, temp);
4118 }
4119 interp_param = ac_build_gather_values(&ctx->ac, ij_out, 2);
4120 }
4121
4122 if (interp_param)
4123 interp_param = ac_to_float(&ctx->ac, interp_param);
4124
4125 for (chan = 0; chan < 4; chan++) {
4126 LLVMValueRef gather = LLVMGetUndef(LLVMVectorType(ctx->f32, input_array_size));
4127 unsigned schan = tgsi_util_get_full_src_register_swizzle(&inst->Src[0], chan);
4128
4129 for (unsigned idx = 0; idx < input_array_size; ++idx) {
4130 LLVMValueRef v, i = NULL, j = NULL;
4131
4132 if (interp_param) {
4133 i = LLVMBuildExtractElement(
4134 ctx->ac.builder, interp_param, ctx->i32_0, "");
4135 j = LLVMBuildExtractElement(
4136 ctx->ac.builder, interp_param, ctx->i32_1, "");
4137 }
4138 v = si_build_fs_interp(ctx, input_base + idx, schan,
4139 prim_mask, i, j);
4140
4141 gather = LLVMBuildInsertElement(ctx->ac.builder,
4142 gather, v, LLVMConstInt(ctx->i32, idx, false), "");
4143 }
4144
4145 emit_data->output[chan] = LLVMBuildExtractElement(
4146 ctx->ac.builder, gather, array_idx, "");
4147 }
4148 }
4149
4150 static void vote_all_emit(
4151 const struct lp_build_tgsi_action *action,
4152 struct lp_build_tgsi_context *bld_base,
4153 struct lp_build_emit_data *emit_data)
4154 {
4155 struct si_shader_context *ctx = si_shader_context(bld_base);
4156
4157 LLVMValueRef tmp = ac_build_vote_all(&ctx->ac, emit_data->args[0]);
4158 emit_data->output[emit_data->chan] =
4159 LLVMBuildSExt(ctx->ac.builder, tmp, ctx->i32, "");
4160 }
4161
4162 static void vote_any_emit(
4163 const struct lp_build_tgsi_action *action,
4164 struct lp_build_tgsi_context *bld_base,
4165 struct lp_build_emit_data *emit_data)
4166 {
4167 struct si_shader_context *ctx = si_shader_context(bld_base);
4168
4169 LLVMValueRef tmp = ac_build_vote_any(&ctx->ac, emit_data->args[0]);
4170 emit_data->output[emit_data->chan] =
4171 LLVMBuildSExt(ctx->ac.builder, tmp, ctx->i32, "");
4172 }
4173
4174 static void vote_eq_emit(
4175 const struct lp_build_tgsi_action *action,
4176 struct lp_build_tgsi_context *bld_base,
4177 struct lp_build_emit_data *emit_data)
4178 {
4179 struct si_shader_context *ctx = si_shader_context(bld_base);
4180
4181 LLVMValueRef tmp = ac_build_vote_eq(&ctx->ac, emit_data->args[0]);
4182 emit_data->output[emit_data->chan] =
4183 LLVMBuildSExt(ctx->ac.builder, tmp, ctx->i32, "");
4184 }
4185
4186 static void ballot_emit(
4187 const struct lp_build_tgsi_action *action,
4188 struct lp_build_tgsi_context *bld_base,
4189 struct lp_build_emit_data *emit_data)
4190 {
4191 struct si_shader_context *ctx = si_shader_context(bld_base);
4192 LLVMBuilderRef builder = ctx->ac.builder;
4193 LLVMValueRef tmp;
4194
4195 tmp = lp_build_emit_fetch(bld_base, emit_data->inst, 0, TGSI_CHAN_X);
4196 tmp = ac_build_ballot(&ctx->ac, tmp);
4197
4198 emit_data->output[0] = LLVMBuildTrunc(builder, tmp, ctx->i32, "");
4199
4200 if (ctx->ac.wave_size == 32) {
4201 emit_data->output[1] = ctx->i32_0;
4202 } else {
4203 tmp = LLVMBuildLShr(builder, tmp, LLVMConstInt(ctx->i64, 32, 0), "");
4204 emit_data->output[1] = LLVMBuildTrunc(builder, tmp, ctx->i32, "");
4205 }
4206 }
4207
4208 static void read_lane_emit(
4209 const struct lp_build_tgsi_action *action,
4210 struct lp_build_tgsi_context *bld_base,
4211 struct lp_build_emit_data *emit_data)
4212 {
4213 struct si_shader_context *ctx = si_shader_context(bld_base);
4214
4215 if (emit_data->inst->Instruction.Opcode == TGSI_OPCODE_READ_INVOC) {
4216 emit_data->args[0] = lp_build_emit_fetch(bld_base, emit_data->inst,
4217 0, emit_data->src_chan);
4218
4219 /* Always read the source invocation (= lane) from the X channel. */
4220 emit_data->args[1] = lp_build_emit_fetch(bld_base, emit_data->inst,
4221 1, TGSI_CHAN_X);
4222 emit_data->arg_count = 2;
4223 }
4224
4225 /* We currently have no other way to prevent LLVM from lifting the icmp
4226 * calls to a dominating basic block.
4227 */
4228 ac_build_optimization_barrier(&ctx->ac, &emit_data->args[0]);
4229
4230 for (unsigned i = 0; i < emit_data->arg_count; ++i)
4231 emit_data->args[i] = ac_to_integer(&ctx->ac, emit_data->args[i]);
4232
4233 emit_data->output[emit_data->chan] =
4234 ac_build_intrinsic(&ctx->ac, action->intr_name,
4235 ctx->i32, emit_data->args, emit_data->arg_count,
4236 AC_FUNC_ATTR_READNONE |
4237 AC_FUNC_ATTR_CONVERGENT);
4238 }
4239
4240 static unsigned si_llvm_get_stream(struct lp_build_tgsi_context *bld_base,
4241 struct lp_build_emit_data *emit_data)
4242 {
4243 struct si_shader_context *ctx = si_shader_context(bld_base);
4244 struct tgsi_src_register src0 = emit_data->inst->Src[0].Register;
4245 LLVMValueRef imm;
4246 unsigned stream;
4247
4248 assert(src0.File == TGSI_FILE_IMMEDIATE);
4249
4250 imm = ctx->imms[src0.Index * TGSI_NUM_CHANNELS + src0.SwizzleX];
4251 stream = LLVMConstIntGetZExtValue(imm) & 0x3;
4252 return stream;
4253 }
4254
4255 /* Emit one vertex from the geometry shader */
4256 static void si_llvm_emit_vertex(struct ac_shader_abi *abi,
4257 unsigned stream,
4258 LLVMValueRef *addrs)
4259 {
4260 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
4261
4262 if (ctx->shader->key.as_ngg) {
4263 gfx10_ngg_gs_emit_vertex(ctx, stream, addrs);
4264 return;
4265 }
4266
4267 struct tgsi_shader_info *info = &ctx->shader->selector->info;
4268 struct si_shader *shader = ctx->shader;
4269 struct lp_build_if_state if_state;
4270 LLVMValueRef soffset = LLVMGetParam(ctx->main_fn,
4271 ctx->param_gs2vs_offset);
4272 LLVMValueRef gs_next_vertex;
4273 LLVMValueRef can_emit;
4274 unsigned chan, offset;
4275 int i;
4276
4277 /* Write vertex attribute values to GSVS ring */
4278 gs_next_vertex = LLVMBuildLoad(ctx->ac.builder,
4279 ctx->gs_next_vertex[stream],
4280 "");
4281
4282 /* If this thread has already emitted the declared maximum number of
4283 * vertices, skip the write: excessive vertex emissions are not
4284 * supposed to have any effect.
4285 *
4286 * If the shader has no writes to memory, kill it instead. This skips
4287 * further memory loads and may allow LLVM to skip to the end
4288 * altogether.
4289 */
4290 can_emit = LLVMBuildICmp(ctx->ac.builder, LLVMIntULT, gs_next_vertex,
4291 LLVMConstInt(ctx->i32,
4292 shader->selector->gs_max_out_vertices, 0), "");
4293
4294 bool use_kill = !info->writes_memory;
4295 if (use_kill) {
4296 ac_build_kill_if_false(&ctx->ac, can_emit);
4297 } else {
4298 lp_build_if(&if_state, &ctx->gallivm, can_emit);
4299 }
4300
4301 offset = 0;
4302 for (i = 0; i < info->num_outputs; i++) {
4303 for (chan = 0; chan < 4; chan++) {
4304 if (!(info->output_usagemask[i] & (1 << chan)) ||
4305 ((info->output_streams[i] >> (2 * chan)) & 3) != stream)
4306 continue;
4307
4308 LLVMValueRef out_val = LLVMBuildLoad(ctx->ac.builder, addrs[4 * i + chan], "");
4309 LLVMValueRef voffset =
4310 LLVMConstInt(ctx->i32, offset *
4311 shader->selector->gs_max_out_vertices, 0);
4312 offset++;
4313
4314 voffset = LLVMBuildAdd(ctx->ac.builder, voffset, gs_next_vertex, "");
4315 voffset = LLVMBuildMul(ctx->ac.builder, voffset,
4316 LLVMConstInt(ctx->i32, 4, 0), "");
4317
4318 out_val = ac_to_integer(&ctx->ac, out_val);
4319
4320 ac_build_buffer_store_dword(&ctx->ac,
4321 ctx->gsvs_ring[stream],
4322 out_val, 1,
4323 voffset, soffset, 0,
4324 ac_glc | ac_slc, true);
4325 }
4326 }
4327
4328 gs_next_vertex = LLVMBuildAdd(ctx->ac.builder, gs_next_vertex, ctx->i32_1, "");
4329 LLVMBuildStore(ctx->ac.builder, gs_next_vertex, ctx->gs_next_vertex[stream]);
4330
4331 /* Signal vertex emission if vertex data was written. */
4332 if (offset) {
4333 ac_build_sendmsg(&ctx->ac, AC_SENDMSG_GS_OP_EMIT | AC_SENDMSG_GS | (stream << 8),
4334 si_get_gs_wave_id(ctx));
4335 }
4336
4337 if (!use_kill)
4338 lp_build_endif(&if_state);
4339 }
4340
4341 /* Emit one vertex from the geometry shader */
4342 static void si_tgsi_emit_vertex(
4343 const struct lp_build_tgsi_action *action,
4344 struct lp_build_tgsi_context *bld_base,
4345 struct lp_build_emit_data *emit_data)
4346 {
4347 struct si_shader_context *ctx = si_shader_context(bld_base);
4348 unsigned stream = si_llvm_get_stream(bld_base, emit_data);
4349
4350 si_llvm_emit_vertex(&ctx->abi, stream, ctx->outputs[0]);
4351 }
4352
4353 /* Cut one primitive from the geometry shader */
4354 static void si_llvm_emit_primitive(struct ac_shader_abi *abi,
4355 unsigned stream)
4356 {
4357 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
4358
4359 if (ctx->shader->key.as_ngg) {
4360 LLVMBuildStore(ctx->ac.builder, ctx->ac.i32_0, ctx->gs_curprim_verts[stream]);
4361 return;
4362 }
4363
4364 /* Signal primitive cut */
4365 ac_build_sendmsg(&ctx->ac, AC_SENDMSG_GS_OP_CUT | AC_SENDMSG_GS | (stream << 8),
4366 si_get_gs_wave_id(ctx));
4367 }
4368
4369 /* Cut one primitive from the geometry shader */
4370 static void si_tgsi_emit_primitive(
4371 const struct lp_build_tgsi_action *action,
4372 struct lp_build_tgsi_context *bld_base,
4373 struct lp_build_emit_data *emit_data)
4374 {
4375 struct si_shader_context *ctx = si_shader_context(bld_base);
4376
4377 si_llvm_emit_primitive(&ctx->abi, si_llvm_get_stream(bld_base, emit_data));
4378 }
4379
4380 static void si_llvm_emit_barrier(const struct lp_build_tgsi_action *action,
4381 struct lp_build_tgsi_context *bld_base,
4382 struct lp_build_emit_data *emit_data)
4383 {
4384 struct si_shader_context *ctx = si_shader_context(bld_base);
4385
4386 /* GFX6 only (thanks to a hw bug workaround):
4387 * The real barrier instruction isn’t needed, because an entire patch
4388 * always fits into a single wave.
4389 */
4390 if (ctx->screen->info.chip_class == GFX6 &&
4391 ctx->type == PIPE_SHADER_TESS_CTRL) {
4392 ac_build_waitcnt(&ctx->ac, AC_WAIT_LGKM | AC_WAIT_VLOAD | AC_WAIT_VSTORE);
4393 return;
4394 }
4395
4396 ac_build_s_barrier(&ctx->ac);
4397 }
4398
4399 void si_create_function(struct si_shader_context *ctx,
4400 const char *name,
4401 LLVMTypeRef *returns, unsigned num_returns,
4402 struct si_function_info *fninfo,
4403 unsigned max_workgroup_size)
4404 {
4405 int i;
4406
4407 si_llvm_create_func(ctx, name, returns, num_returns,
4408 fninfo->types, fninfo->num_params);
4409 ctx->return_value = LLVMGetUndef(ctx->return_type);
4410
4411 for (i = 0; i < fninfo->num_sgpr_params; ++i) {
4412 LLVMValueRef P = LLVMGetParam(ctx->main_fn, i);
4413
4414 /* The combination of:
4415 * - noalias
4416 * - dereferenceable
4417 * - invariant.load
4418 * allows the optimization passes to move loads and reduces
4419 * SGPR spilling significantly.
4420 */
4421 ac_add_function_attr(ctx->ac.context, ctx->main_fn, i + 1,
4422 AC_FUNC_ATTR_INREG);
4423
4424 if (LLVMGetTypeKind(LLVMTypeOf(P)) == LLVMPointerTypeKind) {
4425 ac_add_function_attr(ctx->ac.context, ctx->main_fn, i + 1,
4426 AC_FUNC_ATTR_NOALIAS);
4427 ac_add_attr_dereferenceable(P, UINT64_MAX);
4428 }
4429 }
4430
4431 for (i = 0; i < fninfo->num_params; ++i) {
4432 if (fninfo->assign[i])
4433 *fninfo->assign[i] = LLVMGetParam(ctx->main_fn, i);
4434 }
4435
4436 if (ctx->screen->info.address32_hi) {
4437 ac_llvm_add_target_dep_function_attr(ctx->main_fn,
4438 "amdgpu-32bit-address-high-bits",
4439 ctx->screen->info.address32_hi);
4440 }
4441
4442 ac_llvm_set_workgroup_size(ctx->main_fn, max_workgroup_size);
4443
4444 LLVMAddTargetDependentFunctionAttr(ctx->main_fn,
4445 "no-signed-zeros-fp-math",
4446 "true");
4447
4448 if (ctx->screen->debug_flags & DBG(UNSAFE_MATH)) {
4449 /* These were copied from some LLVM test. */
4450 LLVMAddTargetDependentFunctionAttr(ctx->main_fn,
4451 "less-precise-fpmad",
4452 "true");
4453 LLVMAddTargetDependentFunctionAttr(ctx->main_fn,
4454 "no-infs-fp-math",
4455 "true");
4456 LLVMAddTargetDependentFunctionAttr(ctx->main_fn,
4457 "no-nans-fp-math",
4458 "true");
4459 LLVMAddTargetDependentFunctionAttr(ctx->main_fn,
4460 "unsafe-fp-math",
4461 "true");
4462 }
4463 }
4464
4465 static void declare_streamout_params(struct si_shader_context *ctx,
4466 struct pipe_stream_output_info *so,
4467 struct si_function_info *fninfo)
4468 {
4469 if (ctx->ac.chip_class >= GFX10)
4470 return;
4471
4472 /* Streamout SGPRs. */
4473 if (so->num_outputs) {
4474 if (ctx->type != PIPE_SHADER_TESS_EVAL)
4475 ctx->param_streamout_config = add_arg(fninfo, ARG_SGPR, ctx->ac.i32);
4476 else
4477 ctx->param_streamout_config = fninfo->num_params - 1;
4478
4479 ctx->param_streamout_write_index = add_arg(fninfo, ARG_SGPR, ctx->ac.i32);
4480 }
4481 /* A streamout buffer offset is loaded if the stride is non-zero. */
4482 for (int i = 0; i < 4; i++) {
4483 if (!so->stride[i])
4484 continue;
4485
4486 ctx->param_streamout_offset[i] = add_arg(fninfo, ARG_SGPR, ctx->ac.i32);
4487 }
4488 }
4489
4490 static unsigned si_get_max_workgroup_size(const struct si_shader *shader)
4491 {
4492 switch (shader->selector->type) {
4493 case PIPE_SHADER_VERTEX:
4494 case PIPE_SHADER_TESS_EVAL:
4495 return shader->key.as_ngg ? 128 : 0;
4496
4497 case PIPE_SHADER_TESS_CTRL:
4498 /* Return this so that LLVM doesn't remove s_barrier
4499 * instructions on chips where we use s_barrier. */
4500 return shader->selector->screen->info.chip_class >= GFX7 ? 128 : 0;
4501
4502 case PIPE_SHADER_GEOMETRY:
4503 return shader->selector->screen->info.chip_class >= GFX9 ? 128 : 0;
4504
4505 case PIPE_SHADER_COMPUTE:
4506 break; /* see below */
4507
4508 default:
4509 return 0;
4510 }
4511
4512 const unsigned *properties = shader->selector->info.properties;
4513 unsigned max_work_group_size =
4514 properties[TGSI_PROPERTY_CS_FIXED_BLOCK_WIDTH] *
4515 properties[TGSI_PROPERTY_CS_FIXED_BLOCK_HEIGHT] *
4516 properties[TGSI_PROPERTY_CS_FIXED_BLOCK_DEPTH];
4517
4518 if (!max_work_group_size) {
4519 /* This is a variable group size compute shader,
4520 * compile it for the maximum possible group size.
4521 */
4522 max_work_group_size = SI_MAX_VARIABLE_THREADS_PER_BLOCK;
4523 }
4524 return max_work_group_size;
4525 }
4526
4527 static void declare_const_and_shader_buffers(struct si_shader_context *ctx,
4528 struct si_function_info *fninfo,
4529 bool assign_params)
4530 {
4531 LLVMTypeRef const_shader_buf_type;
4532
4533 if (ctx->shader->selector->info.const_buffers_declared == 1 &&
4534 ctx->shader->selector->info.shader_buffers_declared == 0)
4535 const_shader_buf_type = ctx->f32;
4536 else
4537 const_shader_buf_type = ctx->v4i32;
4538
4539 unsigned const_and_shader_buffers =
4540 add_arg(fninfo, ARG_SGPR,
4541 ac_array_in_const32_addr_space(const_shader_buf_type));
4542
4543 if (assign_params)
4544 ctx->param_const_and_shader_buffers = const_and_shader_buffers;
4545 }
4546
4547 static void declare_samplers_and_images(struct si_shader_context *ctx,
4548 struct si_function_info *fninfo,
4549 bool assign_params)
4550 {
4551 unsigned samplers_and_images =
4552 add_arg(fninfo, ARG_SGPR,
4553 ac_array_in_const32_addr_space(ctx->v8i32));
4554
4555 if (assign_params)
4556 ctx->param_samplers_and_images = samplers_and_images;
4557 }
4558
4559 static void declare_per_stage_desc_pointers(struct si_shader_context *ctx,
4560 struct si_function_info *fninfo,
4561 bool assign_params)
4562 {
4563 declare_const_and_shader_buffers(ctx, fninfo, assign_params);
4564 declare_samplers_and_images(ctx, fninfo, assign_params);
4565 }
4566
4567 static void declare_global_desc_pointers(struct si_shader_context *ctx,
4568 struct si_function_info *fninfo)
4569 {
4570 ctx->param_rw_buffers = add_arg(fninfo, ARG_SGPR,
4571 ac_array_in_const32_addr_space(ctx->v4i32));
4572 ctx->param_bindless_samplers_and_images = add_arg(fninfo, ARG_SGPR,
4573 ac_array_in_const32_addr_space(ctx->v8i32));
4574 }
4575
4576 static void declare_vs_specific_input_sgprs(struct si_shader_context *ctx,
4577 struct si_function_info *fninfo)
4578 {
4579 ctx->param_vs_state_bits = add_arg(fninfo, ARG_SGPR, ctx->i32);
4580 add_arg_assign(fninfo, ARG_SGPR, ctx->i32, &ctx->abi.base_vertex);
4581 add_arg_assign(fninfo, ARG_SGPR, ctx->i32, &ctx->abi.start_instance);
4582 add_arg_assign(fninfo, ARG_SGPR, ctx->i32, &ctx->abi.draw_id);
4583 }
4584
4585 static void declare_vs_input_vgprs(struct si_shader_context *ctx,
4586 struct si_function_info *fninfo,
4587 unsigned *num_prolog_vgprs)
4588 {
4589 struct si_shader *shader = ctx->shader;
4590
4591 add_arg_assign(fninfo, ARG_VGPR, ctx->i32, &ctx->abi.vertex_id);
4592 if (shader->key.as_ls) {
4593 ctx->param_rel_auto_id = add_arg(fninfo, ARG_VGPR, ctx->i32);
4594 if (ctx->screen->info.chip_class >= GFX10) {
4595 add_arg(fninfo, ARG_VGPR, ctx->i32); /* user VGPR */
4596 add_arg_assign(fninfo, ARG_VGPR, ctx->i32, &ctx->abi.instance_id);
4597 } else {
4598 add_arg_assign(fninfo, ARG_VGPR, ctx->i32, &ctx->abi.instance_id);
4599 add_arg(fninfo, ARG_VGPR, ctx->i32); /* unused */
4600 }
4601 } else if (ctx->screen->info.chip_class == GFX10 &&
4602 !shader->is_gs_copy_shader) {
4603 add_arg(fninfo, ARG_VGPR, ctx->i32); /* user vgpr */
4604 add_arg(fninfo, ARG_VGPR, ctx->i32); /* user vgpr */
4605 add_arg_assign(fninfo, ARG_VGPR, ctx->i32, &ctx->abi.instance_id);
4606 } else {
4607 add_arg_assign(fninfo, ARG_VGPR, ctx->i32, &ctx->abi.instance_id);
4608 ctx->param_vs_prim_id = add_arg(fninfo, ARG_VGPR, ctx->i32);
4609 add_arg(fninfo, ARG_VGPR, ctx->i32); /* unused */
4610 }
4611
4612 if (!shader->is_gs_copy_shader) {
4613 /* Vertex load indices. */
4614 ctx->param_vertex_index0 = fninfo->num_params;
4615 for (unsigned i = 0; i < shader->selector->info.num_inputs; i++)
4616 add_arg(fninfo, ARG_VGPR, ctx->i32);
4617 *num_prolog_vgprs += shader->selector->info.num_inputs;
4618 }
4619 }
4620
4621 static void declare_vs_blit_inputs(struct si_shader_context *ctx,
4622 struct si_function_info *fninfo,
4623 unsigned vs_blit_property)
4624 {
4625 ctx->param_vs_blit_inputs = fninfo->num_params;
4626 add_arg(fninfo, ARG_SGPR, ctx->i32); /* i16 x1, y1 */
4627 add_arg(fninfo, ARG_SGPR, ctx->i32); /* i16 x2, y2 */
4628 add_arg(fninfo, ARG_SGPR, ctx->f32); /* depth */
4629
4630 if (vs_blit_property == SI_VS_BLIT_SGPRS_POS_COLOR) {
4631 add_arg(fninfo, ARG_SGPR, ctx->f32); /* color0 */
4632 add_arg(fninfo, ARG_SGPR, ctx->f32); /* color1 */
4633 add_arg(fninfo, ARG_SGPR, ctx->f32); /* color2 */
4634 add_arg(fninfo, ARG_SGPR, ctx->f32); /* color3 */
4635 } else if (vs_blit_property == SI_VS_BLIT_SGPRS_POS_TEXCOORD) {
4636 add_arg(fninfo, ARG_SGPR, ctx->f32); /* texcoord.x1 */
4637 add_arg(fninfo, ARG_SGPR, ctx->f32); /* texcoord.y1 */
4638 add_arg(fninfo, ARG_SGPR, ctx->f32); /* texcoord.x2 */
4639 add_arg(fninfo, ARG_SGPR, ctx->f32); /* texcoord.y2 */
4640 add_arg(fninfo, ARG_SGPR, ctx->f32); /* texcoord.z */
4641 add_arg(fninfo, ARG_SGPR, ctx->f32); /* texcoord.w */
4642 }
4643 }
4644
4645 static void declare_tes_input_vgprs(struct si_shader_context *ctx,
4646 struct si_function_info *fninfo)
4647 {
4648 ctx->param_tes_u = add_arg(fninfo, ARG_VGPR, ctx->f32);
4649 ctx->param_tes_v = add_arg(fninfo, ARG_VGPR, ctx->f32);
4650 ctx->param_tes_rel_patch_id = add_arg(fninfo, ARG_VGPR, ctx->i32);
4651 add_arg_assign(fninfo, ARG_VGPR, ctx->i32, &ctx->abi.tes_patch_id);
4652 }
4653
4654 enum {
4655 /* Convenient merged shader definitions. */
4656 SI_SHADER_MERGED_VERTEX_TESSCTRL = PIPE_SHADER_TYPES,
4657 SI_SHADER_MERGED_VERTEX_OR_TESSEVAL_GEOMETRY,
4658 };
4659
4660 static void create_function(struct si_shader_context *ctx)
4661 {
4662 struct si_shader *shader = ctx->shader;
4663 struct si_function_info fninfo;
4664 LLVMTypeRef returns[16+32*4];
4665 unsigned i, num_return_sgprs;
4666 unsigned num_returns = 0;
4667 unsigned num_prolog_vgprs = 0;
4668 unsigned type = ctx->type;
4669 unsigned vs_blit_property =
4670 shader->selector->info.properties[TGSI_PROPERTY_VS_BLIT_SGPRS];
4671
4672 si_init_function_info(&fninfo);
4673
4674 /* Set MERGED shaders. */
4675 if (ctx->screen->info.chip_class >= GFX9) {
4676 if (shader->key.as_ls || type == PIPE_SHADER_TESS_CTRL)
4677 type = SI_SHADER_MERGED_VERTEX_TESSCTRL; /* LS or HS */
4678 else if (shader->key.as_es || shader->key.as_ngg || type == PIPE_SHADER_GEOMETRY)
4679 type = SI_SHADER_MERGED_VERTEX_OR_TESSEVAL_GEOMETRY;
4680 }
4681
4682 LLVMTypeRef v3i32 = LLVMVectorType(ctx->i32, 3);
4683
4684 switch (type) {
4685 case PIPE_SHADER_VERTEX:
4686 declare_global_desc_pointers(ctx, &fninfo);
4687
4688 if (vs_blit_property) {
4689 declare_vs_blit_inputs(ctx, &fninfo, vs_blit_property);
4690
4691 /* VGPRs */
4692 declare_vs_input_vgprs(ctx, &fninfo, &num_prolog_vgprs);
4693 break;
4694 }
4695
4696 declare_per_stage_desc_pointers(ctx, &fninfo, true);
4697 declare_vs_specific_input_sgprs(ctx, &fninfo);
4698 ctx->param_vertex_buffers = add_arg(&fninfo, ARG_SGPR,
4699 ac_array_in_const32_addr_space(ctx->v4i32));
4700
4701 if (shader->key.as_es) {
4702 ctx->param_es2gs_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4703 } else if (shader->key.as_ls) {
4704 /* no extra parameters */
4705 } else {
4706 if (shader->is_gs_copy_shader) {
4707 fninfo.num_params = ctx->param_vs_state_bits + 1;
4708 fninfo.num_sgpr_params = fninfo.num_params;
4709 }
4710
4711 /* The locations of the other parameters are assigned dynamically. */
4712 declare_streamout_params(ctx, &shader->selector->so,
4713 &fninfo);
4714 }
4715
4716 /* VGPRs */
4717 declare_vs_input_vgprs(ctx, &fninfo, &num_prolog_vgprs);
4718
4719 /* Return values */
4720 if (shader->key.opt.vs_as_prim_discard_cs) {
4721 for (i = 0; i < 4; i++)
4722 returns[num_returns++] = ctx->f32; /* VGPRs */
4723 }
4724 break;
4725
4726 case PIPE_SHADER_TESS_CTRL: /* GFX6-GFX8 */
4727 declare_global_desc_pointers(ctx, &fninfo);
4728 declare_per_stage_desc_pointers(ctx, &fninfo, true);
4729 ctx->param_tcs_offchip_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4730 ctx->param_tcs_out_lds_offsets = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4731 ctx->param_tcs_out_lds_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4732 ctx->param_vs_state_bits = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4733 ctx->param_tcs_offchip_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4734 ctx->param_tcs_factor_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4735
4736 /* VGPRs */
4737 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.tcs_patch_id);
4738 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.tcs_rel_ids);
4739
4740 /* param_tcs_offchip_offset and param_tcs_factor_offset are
4741 * placed after the user SGPRs.
4742 */
4743 for (i = 0; i < GFX6_TCS_NUM_USER_SGPR + 2; i++)
4744 returns[num_returns++] = ctx->i32; /* SGPRs */
4745 for (i = 0; i < 11; i++)
4746 returns[num_returns++] = ctx->f32; /* VGPRs */
4747 break;
4748
4749 case SI_SHADER_MERGED_VERTEX_TESSCTRL:
4750 /* Merged stages have 8 system SGPRs at the beginning. */
4751 /* SPI_SHADER_USER_DATA_ADDR_LO/HI_HS */
4752 declare_per_stage_desc_pointers(ctx, &fninfo,
4753 ctx->type == PIPE_SHADER_TESS_CTRL);
4754 ctx->param_tcs_offchip_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4755 ctx->param_merged_wave_info = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4756 ctx->param_tcs_factor_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4757 ctx->param_merged_scratch_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4758 add_arg(&fninfo, ARG_SGPR, ctx->i32); /* unused */
4759 add_arg(&fninfo, ARG_SGPR, ctx->i32); /* unused */
4760
4761 declare_global_desc_pointers(ctx, &fninfo);
4762 declare_per_stage_desc_pointers(ctx, &fninfo,
4763 ctx->type == PIPE_SHADER_VERTEX);
4764 declare_vs_specific_input_sgprs(ctx, &fninfo);
4765
4766 ctx->param_tcs_offchip_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4767 ctx->param_tcs_out_lds_offsets = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4768 ctx->param_tcs_out_lds_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4769 ctx->param_vertex_buffers = add_arg(&fninfo, ARG_SGPR,
4770 ac_array_in_const32_addr_space(ctx->v4i32));
4771
4772 /* VGPRs (first TCS, then VS) */
4773 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.tcs_patch_id);
4774 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.tcs_rel_ids);
4775
4776 if (ctx->type == PIPE_SHADER_VERTEX) {
4777 declare_vs_input_vgprs(ctx, &fninfo,
4778 &num_prolog_vgprs);
4779
4780 /* LS return values are inputs to the TCS main shader part. */
4781 for (i = 0; i < 8 + GFX9_TCS_NUM_USER_SGPR; i++)
4782 returns[num_returns++] = ctx->i32; /* SGPRs */
4783 for (i = 0; i < 2; i++)
4784 returns[num_returns++] = ctx->f32; /* VGPRs */
4785 } else {
4786 /* TCS return values are inputs to the TCS epilog.
4787 *
4788 * param_tcs_offchip_offset, param_tcs_factor_offset,
4789 * param_tcs_offchip_layout, and param_rw_buffers
4790 * should be passed to the epilog.
4791 */
4792 for (i = 0; i <= 8 + GFX9_SGPR_TCS_OUT_LAYOUT; i++)
4793 returns[num_returns++] = ctx->i32; /* SGPRs */
4794 for (i = 0; i < 11; i++)
4795 returns[num_returns++] = ctx->f32; /* VGPRs */
4796 }
4797 break;
4798
4799 case SI_SHADER_MERGED_VERTEX_OR_TESSEVAL_GEOMETRY:
4800 /* Merged stages have 8 system SGPRs at the beginning. */
4801 /* SPI_SHADER_USER_DATA_ADDR_LO/HI_GS */
4802 declare_per_stage_desc_pointers(ctx, &fninfo,
4803 ctx->type == PIPE_SHADER_GEOMETRY);
4804
4805 if (ctx->shader->key.as_ngg)
4806 add_arg_assign(&fninfo, ARG_SGPR, ctx->i32, &ctx->gs_tg_info);
4807 else
4808 ctx->param_gs2vs_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4809
4810 ctx->param_merged_wave_info = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4811 ctx->param_tcs_offchip_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4812 ctx->param_merged_scratch_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4813 add_arg(&fninfo, ARG_SGPR, ctx->i32); /* unused (SPI_SHADER_PGM_LO/HI_GS << 8) */
4814 add_arg(&fninfo, ARG_SGPR, ctx->i32); /* unused (SPI_SHADER_PGM_LO/HI_GS >> 24) */
4815
4816 declare_global_desc_pointers(ctx, &fninfo);
4817 if (ctx->type != PIPE_SHADER_VERTEX || !vs_blit_property) {
4818 declare_per_stage_desc_pointers(ctx, &fninfo,
4819 (ctx->type == PIPE_SHADER_VERTEX ||
4820 ctx->type == PIPE_SHADER_TESS_EVAL));
4821 }
4822
4823 if (ctx->type == PIPE_SHADER_VERTEX) {
4824 if (vs_blit_property)
4825 declare_vs_blit_inputs(ctx, &fninfo, vs_blit_property);
4826 else
4827 declare_vs_specific_input_sgprs(ctx, &fninfo);
4828 } else {
4829 ctx->param_vs_state_bits = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4830 ctx->param_tcs_offchip_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4831 ctx->param_tes_offchip_addr = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4832 /* Declare as many input SGPRs as the VS has. */
4833 }
4834
4835 if (ctx->type == PIPE_SHADER_VERTEX) {
4836 ctx->param_vertex_buffers = add_arg(&fninfo, ARG_SGPR,
4837 ac_array_in_const32_addr_space(ctx->v4i32));
4838 }
4839
4840 /* VGPRs (first GS, then VS/TES) */
4841 ctx->param_gs_vtx01_offset = add_arg(&fninfo, ARG_VGPR, ctx->i32);
4842 ctx->param_gs_vtx23_offset = add_arg(&fninfo, ARG_VGPR, ctx->i32);
4843 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.gs_prim_id);
4844 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.gs_invocation_id);
4845 ctx->param_gs_vtx45_offset = add_arg(&fninfo, ARG_VGPR, ctx->i32);
4846
4847 if (ctx->type == PIPE_SHADER_VERTEX) {
4848 declare_vs_input_vgprs(ctx, &fninfo,
4849 &num_prolog_vgprs);
4850 } else if (ctx->type == PIPE_SHADER_TESS_EVAL) {
4851 declare_tes_input_vgprs(ctx, &fninfo);
4852 }
4853
4854 if (ctx->shader->key.as_es &&
4855 (ctx->type == PIPE_SHADER_VERTEX ||
4856 ctx->type == PIPE_SHADER_TESS_EVAL)) {
4857 unsigned num_user_sgprs;
4858
4859 if (ctx->type == PIPE_SHADER_VERTEX)
4860 num_user_sgprs = GFX9_VSGS_NUM_USER_SGPR;
4861 else
4862 num_user_sgprs = GFX9_TESGS_NUM_USER_SGPR;
4863
4864 /* ES return values are inputs to GS. */
4865 for (i = 0; i < 8 + num_user_sgprs; i++)
4866 returns[num_returns++] = ctx->i32; /* SGPRs */
4867 for (i = 0; i < 5; i++)
4868 returns[num_returns++] = ctx->f32; /* VGPRs */
4869 }
4870 break;
4871
4872 case PIPE_SHADER_TESS_EVAL:
4873 declare_global_desc_pointers(ctx, &fninfo);
4874 declare_per_stage_desc_pointers(ctx, &fninfo, true);
4875 ctx->param_vs_state_bits = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4876 ctx->param_tcs_offchip_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4877 ctx->param_tes_offchip_addr = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4878
4879 if (shader->key.as_es) {
4880 ctx->param_tcs_offchip_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4881 add_arg(&fninfo, ARG_SGPR, ctx->i32);
4882 ctx->param_es2gs_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4883 } else {
4884 add_arg(&fninfo, ARG_SGPR, ctx->i32);
4885 declare_streamout_params(ctx, &shader->selector->so,
4886 &fninfo);
4887 ctx->param_tcs_offchip_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4888 }
4889
4890 /* VGPRs */
4891 declare_tes_input_vgprs(ctx, &fninfo);
4892 break;
4893
4894 case PIPE_SHADER_GEOMETRY:
4895 declare_global_desc_pointers(ctx, &fninfo);
4896 declare_per_stage_desc_pointers(ctx, &fninfo, true);
4897 ctx->param_gs2vs_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4898 ctx->param_gs_wave_id = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4899
4900 /* VGPRs */
4901 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->gs_vtx_offset[0]);
4902 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->gs_vtx_offset[1]);
4903 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.gs_prim_id);
4904 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->gs_vtx_offset[2]);
4905 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->gs_vtx_offset[3]);
4906 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->gs_vtx_offset[4]);
4907 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->gs_vtx_offset[5]);
4908 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.gs_invocation_id);
4909 break;
4910
4911 case PIPE_SHADER_FRAGMENT:
4912 declare_global_desc_pointers(ctx, &fninfo);
4913 declare_per_stage_desc_pointers(ctx, &fninfo, true);
4914 add_arg_checked(&fninfo, ARG_SGPR, ctx->f32, SI_PARAM_ALPHA_REF);
4915 add_arg_assign_checked(&fninfo, ARG_SGPR, ctx->i32,
4916 &ctx->abi.prim_mask, SI_PARAM_PRIM_MASK);
4917
4918 add_arg_checked(&fninfo, ARG_VGPR, ctx->v2i32, SI_PARAM_PERSP_SAMPLE);
4919 add_arg_checked(&fninfo, ARG_VGPR, ctx->v2i32, SI_PARAM_PERSP_CENTER);
4920 add_arg_checked(&fninfo, ARG_VGPR, ctx->v2i32, SI_PARAM_PERSP_CENTROID);
4921 add_arg_checked(&fninfo, ARG_VGPR, v3i32, SI_PARAM_PERSP_PULL_MODEL);
4922 add_arg_checked(&fninfo, ARG_VGPR, ctx->v2i32, SI_PARAM_LINEAR_SAMPLE);
4923 add_arg_checked(&fninfo, ARG_VGPR, ctx->v2i32, SI_PARAM_LINEAR_CENTER);
4924 add_arg_checked(&fninfo, ARG_VGPR, ctx->v2i32, SI_PARAM_LINEAR_CENTROID);
4925 add_arg_checked(&fninfo, ARG_VGPR, ctx->f32, SI_PARAM_LINE_STIPPLE_TEX);
4926 add_arg_assign_checked(&fninfo, ARG_VGPR, ctx->f32,
4927 &ctx->abi.frag_pos[0], SI_PARAM_POS_X_FLOAT);
4928 add_arg_assign_checked(&fninfo, ARG_VGPR, ctx->f32,
4929 &ctx->abi.frag_pos[1], SI_PARAM_POS_Y_FLOAT);
4930 add_arg_assign_checked(&fninfo, ARG_VGPR, ctx->f32,
4931 &ctx->abi.frag_pos[2], SI_PARAM_POS_Z_FLOAT);
4932 add_arg_assign_checked(&fninfo, ARG_VGPR, ctx->f32,
4933 &ctx->abi.frag_pos[3], SI_PARAM_POS_W_FLOAT);
4934 add_arg_assign_checked(&fninfo, ARG_VGPR, ctx->i32,
4935 &ctx->abi.front_face, SI_PARAM_FRONT_FACE);
4936 shader->info.face_vgpr_index = 20;
4937 add_arg_assign_checked(&fninfo, ARG_VGPR, ctx->i32,
4938 &ctx->abi.ancillary, SI_PARAM_ANCILLARY);
4939 shader->info.ancillary_vgpr_index = 21;
4940 add_arg_assign_checked(&fninfo, ARG_VGPR, ctx->f32,
4941 &ctx->abi.sample_coverage, SI_PARAM_SAMPLE_COVERAGE);
4942 add_arg_checked(&fninfo, ARG_VGPR, ctx->i32, SI_PARAM_POS_FIXED_PT);
4943
4944 /* Color inputs from the prolog. */
4945 if (shader->selector->info.colors_read) {
4946 unsigned num_color_elements =
4947 util_bitcount(shader->selector->info.colors_read);
4948
4949 assert(fninfo.num_params + num_color_elements <= ARRAY_SIZE(fninfo.types));
4950 for (i = 0; i < num_color_elements; i++)
4951 add_arg(&fninfo, ARG_VGPR, ctx->f32);
4952
4953 num_prolog_vgprs += num_color_elements;
4954 }
4955
4956 /* Outputs for the epilog. */
4957 num_return_sgprs = SI_SGPR_ALPHA_REF + 1;
4958 num_returns =
4959 num_return_sgprs +
4960 util_bitcount(shader->selector->info.colors_written) * 4 +
4961 shader->selector->info.writes_z +
4962 shader->selector->info.writes_stencil +
4963 shader->selector->info.writes_samplemask +
4964 1 /* SampleMaskIn */;
4965
4966 num_returns = MAX2(num_returns,
4967 num_return_sgprs +
4968 PS_EPILOG_SAMPLEMASK_MIN_LOC + 1);
4969
4970 for (i = 0; i < num_return_sgprs; i++)
4971 returns[i] = ctx->i32;
4972 for (; i < num_returns; i++)
4973 returns[i] = ctx->f32;
4974 break;
4975
4976 case PIPE_SHADER_COMPUTE:
4977 declare_global_desc_pointers(ctx, &fninfo);
4978 declare_per_stage_desc_pointers(ctx, &fninfo, true);
4979 if (shader->selector->info.uses_grid_size)
4980 add_arg_assign(&fninfo, ARG_SGPR, v3i32, &ctx->abi.num_work_groups);
4981 if (shader->selector->info.uses_block_size &&
4982 shader->selector->info.properties[TGSI_PROPERTY_CS_FIXED_BLOCK_WIDTH] == 0)
4983 ctx->param_block_size = add_arg(&fninfo, ARG_SGPR, v3i32);
4984
4985 unsigned cs_user_data_dwords =
4986 shader->selector->info.properties[TGSI_PROPERTY_CS_USER_DATA_DWORDS];
4987 if (cs_user_data_dwords) {
4988 ctx->param_cs_user_data = add_arg(&fninfo, ARG_SGPR,
4989 LLVMVectorType(ctx->i32, cs_user_data_dwords));
4990 }
4991
4992 for (i = 0; i < 3; i++) {
4993 ctx->abi.workgroup_ids[i] = NULL;
4994 if (shader->selector->info.uses_block_id[i])
4995 add_arg_assign(&fninfo, ARG_SGPR, ctx->i32, &ctx->abi.workgroup_ids[i]);
4996 }
4997
4998 add_arg_assign(&fninfo, ARG_VGPR, v3i32, &ctx->abi.local_invocation_ids);
4999 break;
5000 default:
5001 assert(0 && "unimplemented shader");
5002 return;
5003 }
5004
5005 si_create_function(ctx, "main", returns, num_returns, &fninfo,
5006 si_get_max_workgroup_size(shader));
5007
5008 /* Reserve register locations for VGPR inputs the PS prolog may need. */
5009 if (ctx->type == PIPE_SHADER_FRAGMENT && !ctx->shader->is_monolithic) {
5010 ac_llvm_add_target_dep_function_attr(ctx->main_fn,
5011 "InitialPSInputAddr",
5012 S_0286D0_PERSP_SAMPLE_ENA(1) |
5013 S_0286D0_PERSP_CENTER_ENA(1) |
5014 S_0286D0_PERSP_CENTROID_ENA(1) |
5015 S_0286D0_LINEAR_SAMPLE_ENA(1) |
5016 S_0286D0_LINEAR_CENTER_ENA(1) |
5017 S_0286D0_LINEAR_CENTROID_ENA(1) |
5018 S_0286D0_FRONT_FACE_ENA(1) |
5019 S_0286D0_ANCILLARY_ENA(1) |
5020 S_0286D0_POS_FIXED_PT_ENA(1));
5021 }
5022
5023 shader->info.num_input_sgprs = 0;
5024 shader->info.num_input_vgprs = 0;
5025
5026 for (i = 0; i < fninfo.num_sgpr_params; ++i)
5027 shader->info.num_input_sgprs += ac_get_type_size(fninfo.types[i]) / 4;
5028
5029 for (; i < fninfo.num_params; ++i)
5030 shader->info.num_input_vgprs += ac_get_type_size(fninfo.types[i]) / 4;
5031
5032 assert(shader->info.num_input_vgprs >= num_prolog_vgprs);
5033 shader->info.num_input_vgprs -= num_prolog_vgprs;
5034
5035 if (shader->key.as_ls || ctx->type == PIPE_SHADER_TESS_CTRL) {
5036 if (USE_LDS_SYMBOLS && HAVE_LLVM >= 0x0900) {
5037 /* The LSHS size is not known until draw time, so we append it
5038 * at the end of whatever LDS use there may be in the rest of
5039 * the shader (currently none, unless LLVM decides to do its
5040 * own LDS-based lowering).
5041 */
5042 ctx->ac.lds = LLVMAddGlobalInAddressSpace(
5043 ctx->ac.module, LLVMArrayType(ctx->i32, 0),
5044 "__lds_end", AC_ADDR_SPACE_LDS);
5045 LLVMSetAlignment(ctx->ac.lds, 256);
5046 } else {
5047 ac_declare_lds_as_pointer(&ctx->ac);
5048 }
5049 }
5050 }
5051
5052 /* Ensure that the esgs ring is declared.
5053 *
5054 * We declare it with 64KB alignment as a hint that the
5055 * pointer value will always be 0.
5056 */
5057 static void declare_esgs_ring(struct si_shader_context *ctx)
5058 {
5059 if (ctx->esgs_ring)
5060 return;
5061
5062 assert(!LLVMGetNamedGlobal(ctx->ac.module, "esgs_ring"));
5063
5064 ctx->esgs_ring = LLVMAddGlobalInAddressSpace(
5065 ctx->ac.module, LLVMArrayType(ctx->i32, 0),
5066 "esgs_ring",
5067 AC_ADDR_SPACE_LDS);
5068 LLVMSetLinkage(ctx->esgs_ring, LLVMExternalLinkage);
5069 LLVMSetAlignment(ctx->esgs_ring, 64 * 1024);
5070 }
5071
5072 /**
5073 * Load ESGS and GSVS ring buffer resource descriptors and save the variables
5074 * for later use.
5075 */
5076 static void preload_ring_buffers(struct si_shader_context *ctx)
5077 {
5078 LLVMBuilderRef builder = ctx->ac.builder;
5079
5080 LLVMValueRef buf_ptr = LLVMGetParam(ctx->main_fn,
5081 ctx->param_rw_buffers);
5082
5083 if (ctx->shader->key.as_es || ctx->type == PIPE_SHADER_GEOMETRY) {
5084 if (ctx->screen->info.chip_class <= GFX8) {
5085 unsigned ring =
5086 ctx->type == PIPE_SHADER_GEOMETRY ? SI_GS_RING_ESGS
5087 : SI_ES_RING_ESGS;
5088 LLVMValueRef offset = LLVMConstInt(ctx->i32, ring, 0);
5089
5090 ctx->esgs_ring =
5091 ac_build_load_to_sgpr(&ctx->ac, buf_ptr, offset);
5092 } else {
5093 if (USE_LDS_SYMBOLS && HAVE_LLVM >= 0x0900) {
5094 /* Declare the ESGS ring as an explicit LDS symbol. */
5095 declare_esgs_ring(ctx);
5096 } else {
5097 ac_declare_lds_as_pointer(&ctx->ac);
5098 ctx->esgs_ring = ctx->ac.lds;
5099 }
5100 }
5101 }
5102
5103 if (ctx->shader->is_gs_copy_shader) {
5104 LLVMValueRef offset = LLVMConstInt(ctx->i32, SI_RING_GSVS, 0);
5105
5106 ctx->gsvs_ring[0] =
5107 ac_build_load_to_sgpr(&ctx->ac, buf_ptr, offset);
5108 } else if (ctx->type == PIPE_SHADER_GEOMETRY) {
5109 const struct si_shader_selector *sel = ctx->shader->selector;
5110 LLVMValueRef offset = LLVMConstInt(ctx->i32, SI_RING_GSVS, 0);
5111 LLVMValueRef base_ring;
5112
5113 base_ring = ac_build_load_to_sgpr(&ctx->ac, buf_ptr, offset);
5114
5115 /* The conceptual layout of the GSVS ring is
5116 * v0c0 .. vLv0 v0c1 .. vLc1 ..
5117 * but the real memory layout is swizzled across
5118 * threads:
5119 * t0v0c0 .. t15v0c0 t0v1c0 .. t15v1c0 ... t15vLcL
5120 * t16v0c0 ..
5121 * Override the buffer descriptor accordingly.
5122 */
5123 LLVMTypeRef v2i64 = LLVMVectorType(ctx->i64, 2);
5124 uint64_t stream_offset = 0;
5125
5126 for (unsigned stream = 0; stream < 4; ++stream) {
5127 unsigned num_components;
5128 unsigned stride;
5129 unsigned num_records;
5130 LLVMValueRef ring, tmp;
5131
5132 num_components = sel->info.num_stream_output_components[stream];
5133 if (!num_components)
5134 continue;
5135
5136 stride = 4 * num_components * sel->gs_max_out_vertices;
5137
5138 /* Limit on the stride field for <= GFX7. */
5139 assert(stride < (1 << 14));
5140
5141 num_records = ctx->ac.wave_size;
5142
5143 ring = LLVMBuildBitCast(builder, base_ring, v2i64, "");
5144 tmp = LLVMBuildExtractElement(builder, ring, ctx->i32_0, "");
5145 tmp = LLVMBuildAdd(builder, tmp,
5146 LLVMConstInt(ctx->i64,
5147 stream_offset, 0), "");
5148 stream_offset += stride * ctx->ac.wave_size;
5149
5150 ring = LLVMBuildInsertElement(builder, ring, tmp, ctx->i32_0, "");
5151 ring = LLVMBuildBitCast(builder, ring, ctx->v4i32, "");
5152 tmp = LLVMBuildExtractElement(builder, ring, ctx->i32_1, "");
5153 tmp = LLVMBuildOr(builder, tmp,
5154 LLVMConstInt(ctx->i32,
5155 S_008F04_STRIDE(stride) |
5156 S_008F04_SWIZZLE_ENABLE(1), 0), "");
5157 ring = LLVMBuildInsertElement(builder, ring, tmp, ctx->i32_1, "");
5158 ring = LLVMBuildInsertElement(builder, ring,
5159 LLVMConstInt(ctx->i32, num_records, 0),
5160 LLVMConstInt(ctx->i32, 2, 0), "");
5161
5162 uint32_t rsrc3 =
5163 S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
5164 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
5165 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
5166 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
5167 S_008F0C_INDEX_STRIDE(1) | /* index_stride = 16 (elements) */
5168 S_008F0C_ADD_TID_ENABLE(1);
5169
5170 if (ctx->ac.chip_class >= GFX10) {
5171 rsrc3 |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
5172 S_008F0C_OOB_SELECT(2) |
5173 S_008F0C_RESOURCE_LEVEL(1);
5174 } else {
5175 rsrc3 |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
5176 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
5177 S_008F0C_ELEMENT_SIZE(1); /* element_size = 4 (bytes) */
5178 }
5179
5180 ring = LLVMBuildInsertElement(builder, ring,
5181 LLVMConstInt(ctx->i32, rsrc3, false),
5182 LLVMConstInt(ctx->i32, 3, 0), "");
5183
5184 ctx->gsvs_ring[stream] = ring;
5185 }
5186 } else if (ctx->type == PIPE_SHADER_TESS_EVAL) {
5187 ctx->tess_offchip_ring = get_tess_ring_descriptor(ctx, TESS_OFFCHIP_RING_TES);
5188 }
5189 }
5190
5191 static void si_llvm_emit_polygon_stipple(struct si_shader_context *ctx,
5192 LLVMValueRef param_rw_buffers,
5193 unsigned param_pos_fixed_pt)
5194 {
5195 LLVMBuilderRef builder = ctx->ac.builder;
5196 LLVMValueRef slot, desc, offset, row, bit, address[2];
5197
5198 /* Use the fixed-point gl_FragCoord input.
5199 * Since the stipple pattern is 32x32 and it repeats, just get 5 bits
5200 * per coordinate to get the repeating effect.
5201 */
5202 address[0] = si_unpack_param(ctx, param_pos_fixed_pt, 0, 5);
5203 address[1] = si_unpack_param(ctx, param_pos_fixed_pt, 16, 5);
5204
5205 /* Load the buffer descriptor. */
5206 slot = LLVMConstInt(ctx->i32, SI_PS_CONST_POLY_STIPPLE, 0);
5207 desc = ac_build_load_to_sgpr(&ctx->ac, param_rw_buffers, slot);
5208
5209 /* The stipple pattern is 32x32, each row has 32 bits. */
5210 offset = LLVMBuildMul(builder, address[1],
5211 LLVMConstInt(ctx->i32, 4, 0), "");
5212 row = buffer_load_const(ctx, desc, offset);
5213 row = ac_to_integer(&ctx->ac, row);
5214 bit = LLVMBuildLShr(builder, row, address[0], "");
5215 bit = LLVMBuildTrunc(builder, bit, ctx->i1, "");
5216 ac_build_kill_if_false(&ctx->ac, bit);
5217 }
5218
5219 /* For the UMR disassembler. */
5220 #define DEBUGGER_END_OF_CODE_MARKER 0xbf9f0000 /* invalid instruction */
5221 #define DEBUGGER_NUM_MARKERS 5
5222
5223 static bool si_shader_binary_open(struct si_screen *screen,
5224 struct si_shader *shader,
5225 struct ac_rtld_binary *rtld)
5226 {
5227 const struct si_shader_selector *sel = shader->selector;
5228 const char *part_elfs[5];
5229 size_t part_sizes[5];
5230 unsigned num_parts = 0;
5231
5232 #define add_part(shader_or_part) \
5233 if (shader_or_part) { \
5234 part_elfs[num_parts] = (shader_or_part)->binary.elf_buffer; \
5235 part_sizes[num_parts] = (shader_or_part)->binary.elf_size; \
5236 num_parts++; \
5237 }
5238
5239 add_part(shader->prolog);
5240 add_part(shader->previous_stage);
5241 add_part(shader->prolog2);
5242 add_part(shader);
5243 add_part(shader->epilog);
5244
5245 #undef add_part
5246
5247 struct ac_rtld_symbol lds_symbols[2];
5248 unsigned num_lds_symbols = 0;
5249
5250 if (sel && screen->info.chip_class >= GFX9 && !shader->is_gs_copy_shader &&
5251 (sel->type == PIPE_SHADER_GEOMETRY || shader->key.as_ngg)) {
5252 /* We add this symbol even on LLVM <= 8 to ensure that
5253 * shader->config.lds_size is set correctly below.
5254 */
5255 struct ac_rtld_symbol *sym = &lds_symbols[num_lds_symbols++];
5256 sym->name = "esgs_ring";
5257 sym->size = shader->gs_info.esgs_ring_size;
5258 sym->align = 64 * 1024;
5259 }
5260
5261 if (shader->key.as_ngg && sel->type == PIPE_SHADER_GEOMETRY) {
5262 struct ac_rtld_symbol *sym = &lds_symbols[num_lds_symbols++];
5263 sym->name = "ngg_emit";
5264 sym->size = shader->ngg.ngg_emit_size * 4;
5265 sym->align = 4;
5266 }
5267
5268 bool ok = ac_rtld_open(rtld, (struct ac_rtld_open_info){
5269 .info = &screen->info,
5270 .options = {
5271 .halt_at_entry = screen->options.halt_shaders,
5272 },
5273 .shader_type = tgsi_processor_to_shader_stage(sel->type),
5274 .wave_size = si_get_shader_wave_size(shader),
5275 .num_parts = num_parts,
5276 .elf_ptrs = part_elfs,
5277 .elf_sizes = part_sizes,
5278 .num_shared_lds_symbols = num_lds_symbols,
5279 .shared_lds_symbols = lds_symbols });
5280
5281 if (rtld->lds_size > 0) {
5282 unsigned alloc_granularity = screen->info.chip_class >= GFX7 ? 512 : 256;
5283 shader->config.lds_size =
5284 align(rtld->lds_size, alloc_granularity) / alloc_granularity;
5285 }
5286
5287 return ok;
5288 }
5289
5290 static unsigned si_get_shader_binary_size(struct si_screen *screen, struct si_shader *shader)
5291 {
5292 struct ac_rtld_binary rtld;
5293 si_shader_binary_open(screen, shader, &rtld);
5294 return rtld.rx_size;
5295 }
5296
5297 static bool si_get_external_symbol(void *data, const char *name, uint64_t *value)
5298 {
5299 uint64_t *scratch_va = data;
5300
5301 if (!strcmp(scratch_rsrc_dword0_symbol, name)) {
5302 *value = (uint32_t)*scratch_va;
5303 return true;
5304 }
5305 if (!strcmp(scratch_rsrc_dword1_symbol, name)) {
5306 /* Enable scratch coalescing. */
5307 *value = S_008F04_BASE_ADDRESS_HI(*scratch_va >> 32) |
5308 S_008F04_SWIZZLE_ENABLE(1);
5309 if (HAVE_LLVM < 0x0800) {
5310 /* Old LLVM created an R_ABS32_HI relocation for
5311 * this symbol. */
5312 *value <<= 32;
5313 }
5314 return true;
5315 }
5316
5317 return false;
5318 }
5319
5320 bool si_shader_binary_upload(struct si_screen *sscreen, struct si_shader *shader,
5321 uint64_t scratch_va)
5322 {
5323 struct ac_rtld_binary binary;
5324 if (!si_shader_binary_open(sscreen, shader, &binary))
5325 return false;
5326
5327 si_resource_reference(&shader->bo, NULL);
5328 shader->bo = si_aligned_buffer_create(&sscreen->b,
5329 sscreen->cpdma_prefetch_writes_memory ?
5330 0 : SI_RESOURCE_FLAG_READ_ONLY,
5331 PIPE_USAGE_IMMUTABLE,
5332 align(binary.rx_size, SI_CPDMA_ALIGNMENT),
5333 256);
5334 if (!shader->bo)
5335 return false;
5336
5337 /* Upload. */
5338 struct ac_rtld_upload_info u = {};
5339 u.binary = &binary;
5340 u.get_external_symbol = si_get_external_symbol;
5341 u.cb_data = &scratch_va;
5342 u.rx_va = shader->bo->gpu_address;
5343 u.rx_ptr = sscreen->ws->buffer_map(shader->bo->buf, NULL,
5344 PIPE_TRANSFER_READ_WRITE |
5345 PIPE_TRANSFER_UNSYNCHRONIZED |
5346 RADEON_TRANSFER_TEMPORARY);
5347 if (!u.rx_ptr)
5348 return false;
5349
5350 bool ok = ac_rtld_upload(&u);
5351
5352 sscreen->ws->buffer_unmap(shader->bo->buf);
5353 ac_rtld_close(&binary);
5354
5355 return ok;
5356 }
5357
5358 static void si_shader_dump_disassembly(struct si_screen *screen,
5359 const struct si_shader_binary *binary,
5360 enum pipe_shader_type shader_type,
5361 unsigned wave_size,
5362 struct pipe_debug_callback *debug,
5363 const char *name, FILE *file)
5364 {
5365 struct ac_rtld_binary rtld_binary;
5366
5367 if (!ac_rtld_open(&rtld_binary, (struct ac_rtld_open_info){
5368 .info = &screen->info,
5369 .shader_type = tgsi_processor_to_shader_stage(shader_type),
5370 .wave_size = wave_size,
5371 .num_parts = 1,
5372 .elf_ptrs = &binary->elf_buffer,
5373 .elf_sizes = &binary->elf_size }))
5374 return;
5375
5376 const char *disasm;
5377 size_t nbytes;
5378
5379 if (!ac_rtld_get_section_by_name(&rtld_binary, ".AMDGPU.disasm", &disasm, &nbytes))
5380 goto out;
5381
5382 if (nbytes > INT_MAX)
5383 goto out;
5384
5385 if (debug && debug->debug_message) {
5386 /* Very long debug messages are cut off, so send the
5387 * disassembly one line at a time. This causes more
5388 * overhead, but on the plus side it simplifies
5389 * parsing of resulting logs.
5390 */
5391 pipe_debug_message(debug, SHADER_INFO,
5392 "Shader Disassembly Begin");
5393
5394 uint64_t line = 0;
5395 while (line < nbytes) {
5396 int count = nbytes - line;
5397 const char *nl = memchr(disasm + line, '\n', nbytes - line);
5398 if (nl)
5399 count = nl - (disasm + line);
5400
5401 if (count) {
5402 pipe_debug_message(debug, SHADER_INFO,
5403 "%.*s", count, disasm + line);
5404 }
5405
5406 line += count + 1;
5407 }
5408
5409 pipe_debug_message(debug, SHADER_INFO,
5410 "Shader Disassembly End");
5411 }
5412
5413 if (file) {
5414 fprintf(file, "Shader %s disassembly:\n", name);
5415 fprintf(file, "%*s", (int)nbytes, disasm);
5416 }
5417
5418 out:
5419 ac_rtld_close(&rtld_binary);
5420 }
5421
5422 static void si_calculate_max_simd_waves(struct si_shader *shader)
5423 {
5424 struct si_screen *sscreen = shader->selector->screen;
5425 struct ac_shader_config *conf = &shader->config;
5426 unsigned num_inputs = shader->selector->info.num_inputs;
5427 unsigned lds_increment = sscreen->info.chip_class >= GFX7 ? 512 : 256;
5428 unsigned lds_per_wave = 0;
5429 unsigned max_simd_waves;
5430
5431 max_simd_waves = ac_get_max_simd_waves(sscreen->info.family);
5432
5433 /* Compute LDS usage for PS. */
5434 switch (shader->selector->type) {
5435 case PIPE_SHADER_FRAGMENT:
5436 /* The minimum usage per wave is (num_inputs * 48). The maximum
5437 * usage is (num_inputs * 48 * 16).
5438 * We can get anything in between and it varies between waves.
5439 *
5440 * The 48 bytes per input for a single primitive is equal to
5441 * 4 bytes/component * 4 components/input * 3 points.
5442 *
5443 * Other stages don't know the size at compile time or don't
5444 * allocate LDS per wave, but instead they do it per thread group.
5445 */
5446 lds_per_wave = conf->lds_size * lds_increment +
5447 align(num_inputs * 48, lds_increment);
5448 break;
5449 case PIPE_SHADER_COMPUTE:
5450 if (shader->selector) {
5451 unsigned max_workgroup_size =
5452 si_get_max_workgroup_size(shader);
5453 lds_per_wave = (conf->lds_size * lds_increment) /
5454 DIV_ROUND_UP(max_workgroup_size,
5455 sscreen->compute_wave_size);
5456 }
5457 break;
5458 default:;
5459 }
5460
5461 /* Compute the per-SIMD wave counts. */
5462 if (conf->num_sgprs) {
5463 max_simd_waves =
5464 MIN2(max_simd_waves,
5465 ac_get_num_physical_sgprs(sscreen->info.chip_class) / conf->num_sgprs);
5466 }
5467
5468 if (conf->num_vgprs)
5469 max_simd_waves = MIN2(max_simd_waves, 256 / conf->num_vgprs);
5470
5471 /* LDS is 64KB per CU (4 SIMDs), which is 16KB per SIMD (usage above
5472 * 16KB makes some SIMDs unoccupied). */
5473 if (lds_per_wave)
5474 max_simd_waves = MIN2(max_simd_waves, 16384 / lds_per_wave);
5475
5476 shader->info.max_simd_waves = max_simd_waves;
5477 }
5478
5479 void si_shader_dump_stats_for_shader_db(struct si_screen *screen,
5480 struct si_shader *shader,
5481 struct pipe_debug_callback *debug)
5482 {
5483 const struct ac_shader_config *conf = &shader->config;
5484
5485 if (screen->options.debug_disassembly)
5486 si_shader_dump_disassembly(screen, &shader->binary,
5487 shader->selector->type,
5488 si_get_shader_wave_size(shader),
5489 debug, "main", NULL);
5490
5491 pipe_debug_message(debug, SHADER_INFO,
5492 "Shader Stats: SGPRS: %d VGPRS: %d Code Size: %d "
5493 "LDS: %d Scratch: %d Max Waves: %d Spilled SGPRs: %d "
5494 "Spilled VGPRs: %d PrivMem VGPRs: %d",
5495 conf->num_sgprs, conf->num_vgprs,
5496 si_get_shader_binary_size(screen, shader),
5497 conf->lds_size, conf->scratch_bytes_per_wave,
5498 shader->info.max_simd_waves, conf->spilled_sgprs,
5499 conf->spilled_vgprs, shader->info.private_mem_vgprs);
5500 }
5501
5502 static void si_shader_dump_stats(struct si_screen *sscreen,
5503 struct si_shader *shader,
5504 FILE *file,
5505 bool check_debug_option)
5506 {
5507 const struct ac_shader_config *conf = &shader->config;
5508
5509 if (!check_debug_option ||
5510 si_can_dump_shader(sscreen, shader->selector->type)) {
5511 if (shader->selector->type == PIPE_SHADER_FRAGMENT) {
5512 fprintf(file, "*** SHADER CONFIG ***\n"
5513 "SPI_PS_INPUT_ADDR = 0x%04x\n"
5514 "SPI_PS_INPUT_ENA = 0x%04x\n",
5515 conf->spi_ps_input_addr, conf->spi_ps_input_ena);
5516 }
5517
5518 fprintf(file, "*** SHADER STATS ***\n"
5519 "SGPRS: %d\n"
5520 "VGPRS: %d\n"
5521 "Spilled SGPRs: %d\n"
5522 "Spilled VGPRs: %d\n"
5523 "Private memory VGPRs: %d\n"
5524 "Code Size: %d bytes\n"
5525 "LDS: %d blocks\n"
5526 "Scratch: %d bytes per wave\n"
5527 "Max Waves: %d\n"
5528 "********************\n\n\n",
5529 conf->num_sgprs, conf->num_vgprs,
5530 conf->spilled_sgprs, conf->spilled_vgprs,
5531 shader->info.private_mem_vgprs,
5532 si_get_shader_binary_size(sscreen, shader),
5533 conf->lds_size, conf->scratch_bytes_per_wave,
5534 shader->info.max_simd_waves);
5535 }
5536 }
5537
5538 const char *si_get_shader_name(const struct si_shader *shader)
5539 {
5540 switch (shader->selector->type) {
5541 case PIPE_SHADER_VERTEX:
5542 if (shader->key.as_es)
5543 return "Vertex Shader as ES";
5544 else if (shader->key.as_ls)
5545 return "Vertex Shader as LS";
5546 else if (shader->key.opt.vs_as_prim_discard_cs)
5547 return "Vertex Shader as Primitive Discard CS";
5548 else if (shader->key.as_ngg)
5549 return "Vertex Shader as ESGS";
5550 else
5551 return "Vertex Shader as VS";
5552 case PIPE_SHADER_TESS_CTRL:
5553 return "Tessellation Control Shader";
5554 case PIPE_SHADER_TESS_EVAL:
5555 if (shader->key.as_es)
5556 return "Tessellation Evaluation Shader as ES";
5557 else if (shader->key.as_ngg)
5558 return "Tessellation Evaluation Shader as ESGS";
5559 else
5560 return "Tessellation Evaluation Shader as VS";
5561 case PIPE_SHADER_GEOMETRY:
5562 if (shader->is_gs_copy_shader)
5563 return "GS Copy Shader as VS";
5564 else
5565 return "Geometry Shader";
5566 case PIPE_SHADER_FRAGMENT:
5567 return "Pixel Shader";
5568 case PIPE_SHADER_COMPUTE:
5569 return "Compute Shader";
5570 default:
5571 return "Unknown Shader";
5572 }
5573 }
5574
5575 void si_shader_dump(struct si_screen *sscreen, struct si_shader *shader,
5576 struct pipe_debug_callback *debug,
5577 FILE *file, bool check_debug_option)
5578 {
5579 enum pipe_shader_type shader_type = shader->selector->type;
5580
5581 if (!check_debug_option ||
5582 si_can_dump_shader(sscreen, shader_type))
5583 si_dump_shader_key(shader, file);
5584
5585 if (!check_debug_option && shader->binary.llvm_ir_string) {
5586 if (shader->previous_stage &&
5587 shader->previous_stage->binary.llvm_ir_string) {
5588 fprintf(file, "\n%s - previous stage - LLVM IR:\n\n",
5589 si_get_shader_name(shader));
5590 fprintf(file, "%s\n", shader->previous_stage->binary.llvm_ir_string);
5591 }
5592
5593 fprintf(file, "\n%s - main shader part - LLVM IR:\n\n",
5594 si_get_shader_name(shader));
5595 fprintf(file, "%s\n", shader->binary.llvm_ir_string);
5596 }
5597
5598 if (!check_debug_option ||
5599 (si_can_dump_shader(sscreen, shader_type) &&
5600 !(sscreen->debug_flags & DBG(NO_ASM)))) {
5601 unsigned wave_size = si_get_shader_wave_size(shader);
5602
5603 fprintf(file, "\n%s:\n", si_get_shader_name(shader));
5604
5605 if (shader->prolog)
5606 si_shader_dump_disassembly(sscreen, &shader->prolog->binary,
5607 shader_type, wave_size, debug, "prolog", file);
5608 if (shader->previous_stage)
5609 si_shader_dump_disassembly(sscreen, &shader->previous_stage->binary,
5610 shader_type, wave_size, debug, "previous stage", file);
5611 if (shader->prolog2)
5612 si_shader_dump_disassembly(sscreen, &shader->prolog2->binary,
5613 shader_type, wave_size, debug, "prolog2", file);
5614
5615 si_shader_dump_disassembly(sscreen, &shader->binary, shader_type,
5616 wave_size, debug, "main", file);
5617
5618 if (shader->epilog)
5619 si_shader_dump_disassembly(sscreen, &shader->epilog->binary,
5620 shader_type, wave_size, debug, "epilog", file);
5621 fprintf(file, "\n");
5622 }
5623
5624 si_shader_dump_stats(sscreen, shader, file, check_debug_option);
5625 }
5626
5627 static int si_compile_llvm(struct si_screen *sscreen,
5628 struct si_shader_binary *binary,
5629 struct ac_shader_config *conf,
5630 struct ac_llvm_compiler *compiler,
5631 LLVMModuleRef mod,
5632 struct pipe_debug_callback *debug,
5633 enum pipe_shader_type shader_type,
5634 unsigned wave_size,
5635 const char *name,
5636 bool less_optimized)
5637 {
5638 unsigned count = p_atomic_inc_return(&sscreen->num_compilations);
5639
5640 if (si_can_dump_shader(sscreen, shader_type)) {
5641 fprintf(stderr, "radeonsi: Compiling shader %d\n", count);
5642
5643 if (!(sscreen->debug_flags & (DBG(NO_IR) | DBG(PREOPT_IR)))) {
5644 fprintf(stderr, "%s LLVM IR:\n\n", name);
5645 ac_dump_module(mod);
5646 fprintf(stderr, "\n");
5647 }
5648 }
5649
5650 if (sscreen->record_llvm_ir) {
5651 char *ir = LLVMPrintModuleToString(mod);
5652 binary->llvm_ir_string = strdup(ir);
5653 LLVMDisposeMessage(ir);
5654 }
5655
5656 if (!si_replace_shader(count, binary)) {
5657 unsigned r = si_llvm_compile(mod, binary, compiler, debug,
5658 less_optimized, wave_size);
5659 if (r)
5660 return r;
5661 }
5662
5663 struct ac_rtld_binary rtld;
5664 if (!ac_rtld_open(&rtld, (struct ac_rtld_open_info){
5665 .info = &sscreen->info,
5666 .shader_type = tgsi_processor_to_shader_stage(shader_type),
5667 .wave_size = wave_size,
5668 .num_parts = 1,
5669 .elf_ptrs = &binary->elf_buffer,
5670 .elf_sizes = &binary->elf_size }))
5671 return -1;
5672
5673 bool ok = ac_rtld_read_config(&rtld, conf);
5674 ac_rtld_close(&rtld);
5675 if (!ok)
5676 return -1;
5677
5678 /* Enable 64-bit and 16-bit denormals, because there is no performance
5679 * cost.
5680 *
5681 * If denormals are enabled, all floating-point output modifiers are
5682 * ignored.
5683 *
5684 * Don't enable denormals for 32-bit floats, because:
5685 * - Floating-point output modifiers would be ignored by the hw.
5686 * - Some opcodes don't support denormals, such as v_mad_f32. We would
5687 * have to stop using those.
5688 * - GFX6 & GFX7 would be very slow.
5689 */
5690 conf->float_mode |= V_00B028_FP_64_DENORMS;
5691
5692 return 0;
5693 }
5694
5695 static void si_llvm_build_ret(struct si_shader_context *ctx, LLVMValueRef ret)
5696 {
5697 if (LLVMGetTypeKind(LLVMTypeOf(ret)) == LLVMVoidTypeKind)
5698 LLVMBuildRetVoid(ctx->ac.builder);
5699 else
5700 LLVMBuildRet(ctx->ac.builder, ret);
5701 }
5702
5703 /* Generate code for the hardware VS shader stage to go with a geometry shader */
5704 struct si_shader *
5705 si_generate_gs_copy_shader(struct si_screen *sscreen,
5706 struct ac_llvm_compiler *compiler,
5707 struct si_shader_selector *gs_selector,
5708 struct pipe_debug_callback *debug)
5709 {
5710 struct si_shader_context ctx;
5711 struct si_shader *shader;
5712 LLVMBuilderRef builder;
5713 struct si_shader_output_values outputs[SI_MAX_VS_OUTPUTS];
5714 struct tgsi_shader_info *gsinfo = &gs_selector->info;
5715 int i;
5716
5717
5718 shader = CALLOC_STRUCT(si_shader);
5719 if (!shader)
5720 return NULL;
5721
5722 /* We can leave the fence as permanently signaled because the GS copy
5723 * shader only becomes visible globally after it has been compiled. */
5724 util_queue_fence_init(&shader->ready);
5725
5726 shader->selector = gs_selector;
5727 shader->is_gs_copy_shader = true;
5728
5729 si_init_shader_ctx(&ctx, sscreen, compiler,
5730 si_get_wave_size(sscreen, PIPE_SHADER_VERTEX, false, false));
5731 ctx.shader = shader;
5732 ctx.type = PIPE_SHADER_VERTEX;
5733
5734 builder = ctx.ac.builder;
5735
5736 create_function(&ctx);
5737 preload_ring_buffers(&ctx);
5738
5739 LLVMValueRef voffset =
5740 LLVMBuildMul(ctx.ac.builder, ctx.abi.vertex_id,
5741 LLVMConstInt(ctx.i32, 4, 0), "");
5742
5743 /* Fetch the vertex stream ID.*/
5744 LLVMValueRef stream_id;
5745
5746 if (ctx.ac.chip_class <= GFX9 && gs_selector->so.num_outputs)
5747 stream_id = si_unpack_param(&ctx, ctx.param_streamout_config, 24, 2);
5748 else
5749 stream_id = ctx.i32_0;
5750
5751 /* Fill in output information. */
5752 for (i = 0; i < gsinfo->num_outputs; ++i) {
5753 outputs[i].semantic_name = gsinfo->output_semantic_name[i];
5754 outputs[i].semantic_index = gsinfo->output_semantic_index[i];
5755
5756 for (int chan = 0; chan < 4; chan++) {
5757 outputs[i].vertex_stream[chan] =
5758 (gsinfo->output_streams[i] >> (2 * chan)) & 3;
5759 }
5760 }
5761
5762 LLVMBasicBlockRef end_bb;
5763 LLVMValueRef switch_inst;
5764
5765 end_bb = LLVMAppendBasicBlockInContext(ctx.ac.context, ctx.main_fn, "end");
5766 switch_inst = LLVMBuildSwitch(builder, stream_id, end_bb, 4);
5767
5768 for (int stream = 0; stream < 4; stream++) {
5769 LLVMBasicBlockRef bb;
5770 unsigned offset;
5771
5772 if (!gsinfo->num_stream_output_components[stream])
5773 continue;
5774
5775 if (stream > 0 && !gs_selector->so.num_outputs)
5776 continue;
5777
5778 bb = LLVMInsertBasicBlockInContext(ctx.ac.context, end_bb, "out");
5779 LLVMAddCase(switch_inst, LLVMConstInt(ctx.i32, stream, 0), bb);
5780 LLVMPositionBuilderAtEnd(builder, bb);
5781
5782 /* Fetch vertex data from GSVS ring */
5783 offset = 0;
5784 for (i = 0; i < gsinfo->num_outputs; ++i) {
5785 for (unsigned chan = 0; chan < 4; chan++) {
5786 if (!(gsinfo->output_usagemask[i] & (1 << chan)) ||
5787 outputs[i].vertex_stream[chan] != stream) {
5788 outputs[i].values[chan] = LLVMGetUndef(ctx.f32);
5789 continue;
5790 }
5791
5792 LLVMValueRef soffset = LLVMConstInt(ctx.i32,
5793 offset * gs_selector->gs_max_out_vertices * 16 * 4, 0);
5794 offset++;
5795
5796 outputs[i].values[chan] =
5797 ac_build_buffer_load(&ctx.ac,
5798 ctx.gsvs_ring[0], 1,
5799 ctx.i32_0, voffset,
5800 soffset, 0, ac_glc | ac_slc,
5801 true, false);
5802 }
5803 }
5804
5805 /* Streamout and exports. */
5806 if (ctx.ac.chip_class <= GFX9 && gs_selector->so.num_outputs) {
5807 si_llvm_emit_streamout(&ctx, outputs,
5808 gsinfo->num_outputs,
5809 stream);
5810 }
5811
5812 if (stream == 0)
5813 si_llvm_export_vs(&ctx, outputs, gsinfo->num_outputs);
5814
5815 LLVMBuildBr(builder, end_bb);
5816 }
5817
5818 LLVMPositionBuilderAtEnd(builder, end_bb);
5819
5820 LLVMBuildRetVoid(ctx.ac.builder);
5821
5822 ctx.type = PIPE_SHADER_GEOMETRY; /* override for shader dumping */
5823 si_llvm_optimize_module(&ctx);
5824
5825 bool ok = false;
5826 if (si_compile_llvm(sscreen, &ctx.shader->binary,
5827 &ctx.shader->config, ctx.compiler,
5828 ctx.ac.module,
5829 debug, PIPE_SHADER_GEOMETRY, ctx.ac.wave_size,
5830 "GS Copy Shader", false) == 0) {
5831 if (si_can_dump_shader(sscreen, PIPE_SHADER_GEOMETRY))
5832 fprintf(stderr, "GS Copy Shader:\n");
5833 si_shader_dump(sscreen, ctx.shader, debug, stderr, true);
5834
5835 if (!ctx.shader->config.scratch_bytes_per_wave)
5836 ok = si_shader_binary_upload(sscreen, ctx.shader, 0);
5837 else
5838 ok = true;
5839 }
5840
5841 si_llvm_dispose(&ctx);
5842
5843 if (!ok) {
5844 FREE(shader);
5845 shader = NULL;
5846 } else {
5847 si_fix_resource_usage(sscreen, shader);
5848 }
5849 return shader;
5850 }
5851
5852 static void si_dump_shader_key_vs(const struct si_shader_key *key,
5853 const struct si_vs_prolog_bits *prolog,
5854 const char *prefix, FILE *f)
5855 {
5856 fprintf(f, " %s.instance_divisor_is_one = %u\n",
5857 prefix, prolog->instance_divisor_is_one);
5858 fprintf(f, " %s.instance_divisor_is_fetched = %u\n",
5859 prefix, prolog->instance_divisor_is_fetched);
5860 fprintf(f, " %s.unpack_instance_id_from_vertex_id = %u\n",
5861 prefix, prolog->unpack_instance_id_from_vertex_id);
5862 fprintf(f, " %s.ls_vgpr_fix = %u\n",
5863 prefix, prolog->ls_vgpr_fix);
5864
5865 fprintf(f, " mono.vs.fetch_opencode = %x\n", key->mono.vs_fetch_opencode);
5866 fprintf(f, " mono.vs.fix_fetch = {");
5867 for (int i = 0; i < SI_MAX_ATTRIBS; i++) {
5868 union si_vs_fix_fetch fix = key->mono.vs_fix_fetch[i];
5869 if (i)
5870 fprintf(f, ", ");
5871 if (!fix.bits)
5872 fprintf(f, "0");
5873 else
5874 fprintf(f, "%u.%u.%u.%u", fix.u.reverse, fix.u.log_size,
5875 fix.u.num_channels_m1, fix.u.format);
5876 }
5877 fprintf(f, "}\n");
5878 }
5879
5880 static void si_dump_shader_key(const struct si_shader *shader, FILE *f)
5881 {
5882 const struct si_shader_key *key = &shader->key;
5883 enum pipe_shader_type shader_type = shader->selector->type;
5884
5885 fprintf(f, "SHADER KEY\n");
5886
5887 switch (shader_type) {
5888 case PIPE_SHADER_VERTEX:
5889 si_dump_shader_key_vs(key, &key->part.vs.prolog,
5890 "part.vs.prolog", f);
5891 fprintf(f, " as_es = %u\n", key->as_es);
5892 fprintf(f, " as_ls = %u\n", key->as_ls);
5893 fprintf(f, " mono.u.vs_export_prim_id = %u\n",
5894 key->mono.u.vs_export_prim_id);
5895 fprintf(f, " opt.vs_as_prim_discard_cs = %u\n",
5896 key->opt.vs_as_prim_discard_cs);
5897 fprintf(f, " opt.cs_prim_type = %s\n",
5898 tgsi_primitive_names[key->opt.cs_prim_type]);
5899 fprintf(f, " opt.cs_indexed = %u\n",
5900 key->opt.cs_indexed);
5901 fprintf(f, " opt.cs_instancing = %u\n",
5902 key->opt.cs_instancing);
5903 fprintf(f, " opt.cs_primitive_restart = %u\n",
5904 key->opt.cs_primitive_restart);
5905 fprintf(f, " opt.cs_provoking_vertex_first = %u\n",
5906 key->opt.cs_provoking_vertex_first);
5907 fprintf(f, " opt.cs_need_correct_orientation = %u\n",
5908 key->opt.cs_need_correct_orientation);
5909 fprintf(f, " opt.cs_cull_front = %u\n",
5910 key->opt.cs_cull_front);
5911 fprintf(f, " opt.cs_cull_back = %u\n",
5912 key->opt.cs_cull_back);
5913 fprintf(f, " opt.cs_cull_z = %u\n",
5914 key->opt.cs_cull_z);
5915 fprintf(f, " opt.cs_halfz_clip_space = %u\n",
5916 key->opt.cs_halfz_clip_space);
5917 break;
5918
5919 case PIPE_SHADER_TESS_CTRL:
5920 if (shader->selector->screen->info.chip_class >= GFX9) {
5921 si_dump_shader_key_vs(key, &key->part.tcs.ls_prolog,
5922 "part.tcs.ls_prolog", f);
5923 }
5924 fprintf(f, " part.tcs.epilog.prim_mode = %u\n", key->part.tcs.epilog.prim_mode);
5925 fprintf(f, " mono.u.ff_tcs_inputs_to_copy = 0x%"PRIx64"\n", key->mono.u.ff_tcs_inputs_to_copy);
5926 break;
5927
5928 case PIPE_SHADER_TESS_EVAL:
5929 fprintf(f, " as_es = %u\n", key->as_es);
5930 fprintf(f, " mono.u.vs_export_prim_id = %u\n",
5931 key->mono.u.vs_export_prim_id);
5932 break;
5933
5934 case PIPE_SHADER_GEOMETRY:
5935 if (shader->is_gs_copy_shader)
5936 break;
5937
5938 if (shader->selector->screen->info.chip_class >= GFX9 &&
5939 key->part.gs.es->type == PIPE_SHADER_VERTEX) {
5940 si_dump_shader_key_vs(key, &key->part.gs.vs_prolog,
5941 "part.gs.vs_prolog", f);
5942 }
5943 fprintf(f, " part.gs.prolog.tri_strip_adj_fix = %u\n", key->part.gs.prolog.tri_strip_adj_fix);
5944 break;
5945
5946 case PIPE_SHADER_COMPUTE:
5947 break;
5948
5949 case PIPE_SHADER_FRAGMENT:
5950 fprintf(f, " part.ps.prolog.color_two_side = %u\n", key->part.ps.prolog.color_two_side);
5951 fprintf(f, " part.ps.prolog.flatshade_colors = %u\n", key->part.ps.prolog.flatshade_colors);
5952 fprintf(f, " part.ps.prolog.poly_stipple = %u\n", key->part.ps.prolog.poly_stipple);
5953 fprintf(f, " part.ps.prolog.force_persp_sample_interp = %u\n", key->part.ps.prolog.force_persp_sample_interp);
5954 fprintf(f, " part.ps.prolog.force_linear_sample_interp = %u\n", key->part.ps.prolog.force_linear_sample_interp);
5955 fprintf(f, " part.ps.prolog.force_persp_center_interp = %u\n", key->part.ps.prolog.force_persp_center_interp);
5956 fprintf(f, " part.ps.prolog.force_linear_center_interp = %u\n", key->part.ps.prolog.force_linear_center_interp);
5957 fprintf(f, " part.ps.prolog.bc_optimize_for_persp = %u\n", key->part.ps.prolog.bc_optimize_for_persp);
5958 fprintf(f, " part.ps.prolog.bc_optimize_for_linear = %u\n", key->part.ps.prolog.bc_optimize_for_linear);
5959 fprintf(f, " part.ps.epilog.spi_shader_col_format = 0x%x\n", key->part.ps.epilog.spi_shader_col_format);
5960 fprintf(f, " part.ps.epilog.color_is_int8 = 0x%X\n", key->part.ps.epilog.color_is_int8);
5961 fprintf(f, " part.ps.epilog.color_is_int10 = 0x%X\n", key->part.ps.epilog.color_is_int10);
5962 fprintf(f, " part.ps.epilog.last_cbuf = %u\n", key->part.ps.epilog.last_cbuf);
5963 fprintf(f, " part.ps.epilog.alpha_func = %u\n", key->part.ps.epilog.alpha_func);
5964 fprintf(f, " part.ps.epilog.alpha_to_one = %u\n", key->part.ps.epilog.alpha_to_one);
5965 fprintf(f, " part.ps.epilog.poly_line_smoothing = %u\n", key->part.ps.epilog.poly_line_smoothing);
5966 fprintf(f, " part.ps.epilog.clamp_color = %u\n", key->part.ps.epilog.clamp_color);
5967 break;
5968
5969 default:
5970 assert(0);
5971 }
5972
5973 if ((shader_type == PIPE_SHADER_GEOMETRY ||
5974 shader_type == PIPE_SHADER_TESS_EVAL ||
5975 shader_type == PIPE_SHADER_VERTEX) &&
5976 !key->as_es && !key->as_ls) {
5977 fprintf(f, " opt.kill_outputs = 0x%"PRIx64"\n", key->opt.kill_outputs);
5978 fprintf(f, " opt.clip_disable = %u\n", key->opt.clip_disable);
5979 }
5980 }
5981
5982 static void si_init_shader_ctx(struct si_shader_context *ctx,
5983 struct si_screen *sscreen,
5984 struct ac_llvm_compiler *compiler,
5985 unsigned wave_size)
5986 {
5987 struct lp_build_tgsi_context *bld_base;
5988
5989 si_llvm_context_init(ctx, sscreen, compiler, wave_size);
5990
5991 bld_base = &ctx->bld_base;
5992 bld_base->emit_fetch_funcs[TGSI_FILE_CONSTANT] = fetch_constant;
5993
5994 bld_base->op_actions[TGSI_OPCODE_INTERP_CENTROID].emit = build_interp_intrinsic;
5995 bld_base->op_actions[TGSI_OPCODE_INTERP_SAMPLE].emit = build_interp_intrinsic;
5996 bld_base->op_actions[TGSI_OPCODE_INTERP_OFFSET].emit = build_interp_intrinsic;
5997
5998 bld_base->op_actions[TGSI_OPCODE_MEMBAR].emit = membar_emit;
5999
6000 bld_base->op_actions[TGSI_OPCODE_CLOCK].emit = clock_emit;
6001
6002 bld_base->op_actions[TGSI_OPCODE_DDX].emit = si_llvm_emit_ddxy;
6003 bld_base->op_actions[TGSI_OPCODE_DDY].emit = si_llvm_emit_ddxy;
6004 bld_base->op_actions[TGSI_OPCODE_DDX_FINE].emit = si_llvm_emit_ddxy;
6005 bld_base->op_actions[TGSI_OPCODE_DDY_FINE].emit = si_llvm_emit_ddxy;
6006
6007 bld_base->op_actions[TGSI_OPCODE_VOTE_ALL].emit = vote_all_emit;
6008 bld_base->op_actions[TGSI_OPCODE_VOTE_ANY].emit = vote_any_emit;
6009 bld_base->op_actions[TGSI_OPCODE_VOTE_EQ].emit = vote_eq_emit;
6010 bld_base->op_actions[TGSI_OPCODE_BALLOT].emit = ballot_emit;
6011 bld_base->op_actions[TGSI_OPCODE_READ_FIRST].intr_name = "llvm.amdgcn.readfirstlane";
6012 bld_base->op_actions[TGSI_OPCODE_READ_FIRST].emit = read_lane_emit;
6013 bld_base->op_actions[TGSI_OPCODE_READ_INVOC].intr_name = "llvm.amdgcn.readlane";
6014 bld_base->op_actions[TGSI_OPCODE_READ_INVOC].emit = read_lane_emit;
6015
6016 bld_base->op_actions[TGSI_OPCODE_EMIT].emit = si_tgsi_emit_vertex;
6017 bld_base->op_actions[TGSI_OPCODE_ENDPRIM].emit = si_tgsi_emit_primitive;
6018 bld_base->op_actions[TGSI_OPCODE_BARRIER].emit = si_llvm_emit_barrier;
6019 }
6020
6021 static void si_optimize_vs_outputs(struct si_shader_context *ctx)
6022 {
6023 struct si_shader *shader = ctx->shader;
6024 struct tgsi_shader_info *info = &shader->selector->info;
6025
6026 if ((ctx->type != PIPE_SHADER_VERTEX &&
6027 ctx->type != PIPE_SHADER_TESS_EVAL) ||
6028 shader->key.as_ls ||
6029 shader->key.as_es)
6030 return;
6031
6032 ac_optimize_vs_outputs(&ctx->ac,
6033 ctx->main_fn,
6034 shader->info.vs_output_param_offset,
6035 info->num_outputs,
6036 &shader->info.nr_param_exports);
6037 }
6038
6039 static void si_init_exec_from_input(struct si_shader_context *ctx,
6040 unsigned param, unsigned bitoffset)
6041 {
6042 LLVMValueRef args[] = {
6043 LLVMGetParam(ctx->main_fn, param),
6044 LLVMConstInt(ctx->i32, bitoffset, 0),
6045 };
6046 ac_build_intrinsic(&ctx->ac,
6047 "llvm.amdgcn.init.exec.from.input",
6048 ctx->voidt, args, 2, AC_FUNC_ATTR_CONVERGENT);
6049 }
6050
6051 static bool si_vs_needs_prolog(const struct si_shader_selector *sel,
6052 const struct si_vs_prolog_bits *key)
6053 {
6054 /* VGPR initialization fixup for Vega10 and Raven is always done in the
6055 * VS prolog. */
6056 return sel->vs_needs_prolog || key->ls_vgpr_fix;
6057 }
6058
6059 static bool si_compile_tgsi_main(struct si_shader_context *ctx)
6060 {
6061 struct si_shader *shader = ctx->shader;
6062 struct si_shader_selector *sel = shader->selector;
6063 struct lp_build_tgsi_context *bld_base = &ctx->bld_base;
6064
6065 // TODO clean all this up!
6066 switch (ctx->type) {
6067 case PIPE_SHADER_VERTEX:
6068 ctx->load_input = declare_input_vs;
6069 if (shader->key.as_ls)
6070 ctx->abi.emit_outputs = si_llvm_emit_ls_epilogue;
6071 else if (shader->key.as_es)
6072 ctx->abi.emit_outputs = si_llvm_emit_es_epilogue;
6073 else if (shader->key.opt.vs_as_prim_discard_cs)
6074 ctx->abi.emit_outputs = si_llvm_emit_prim_discard_cs_epilogue;
6075 else if (shader->key.as_ngg)
6076 ctx->abi.emit_outputs = gfx10_emit_ngg_epilogue;
6077 else
6078 ctx->abi.emit_outputs = si_llvm_emit_vs_epilogue;
6079 bld_base->emit_epilogue = si_tgsi_emit_epilogue;
6080 ctx->abi.load_base_vertex = get_base_vertex;
6081 break;
6082 case PIPE_SHADER_TESS_CTRL:
6083 bld_base->emit_fetch_funcs[TGSI_FILE_INPUT] = fetch_input_tcs;
6084 ctx->abi.load_tess_varyings = si_nir_load_tcs_varyings;
6085 bld_base->emit_fetch_funcs[TGSI_FILE_OUTPUT] = fetch_output_tcs;
6086 bld_base->emit_store = store_output_tcs;
6087 ctx->abi.store_tcs_outputs = si_nir_store_output_tcs;
6088 ctx->abi.emit_outputs = si_llvm_emit_tcs_epilogue;
6089 ctx->abi.load_patch_vertices_in = si_load_patch_vertices_in;
6090 bld_base->emit_epilogue = si_tgsi_emit_epilogue;
6091 break;
6092 case PIPE_SHADER_TESS_EVAL:
6093 bld_base->emit_fetch_funcs[TGSI_FILE_INPUT] = fetch_input_tes;
6094 ctx->abi.load_tess_varyings = si_nir_load_input_tes;
6095 ctx->abi.load_tess_coord = si_load_tess_coord;
6096 ctx->abi.load_tess_level = si_load_tess_level;
6097 ctx->abi.load_patch_vertices_in = si_load_patch_vertices_in;
6098 if (shader->key.as_es)
6099 ctx->abi.emit_outputs = si_llvm_emit_es_epilogue;
6100 else if (shader->key.as_ngg)
6101 ctx->abi.emit_outputs = gfx10_emit_ngg_epilogue;
6102 else
6103 ctx->abi.emit_outputs = si_llvm_emit_vs_epilogue;
6104 bld_base->emit_epilogue = si_tgsi_emit_epilogue;
6105 break;
6106 case PIPE_SHADER_GEOMETRY:
6107 bld_base->emit_fetch_funcs[TGSI_FILE_INPUT] = fetch_input_gs;
6108 ctx->abi.load_inputs = si_nir_load_input_gs;
6109 ctx->abi.emit_vertex = si_llvm_emit_vertex;
6110 ctx->abi.emit_primitive = si_llvm_emit_primitive;
6111 ctx->abi.emit_outputs = si_llvm_emit_gs_epilogue;
6112 bld_base->emit_epilogue = si_tgsi_emit_gs_epilogue;
6113 break;
6114 case PIPE_SHADER_FRAGMENT:
6115 ctx->load_input = declare_input_fs;
6116 ctx->abi.emit_outputs = si_llvm_return_fs_outputs;
6117 bld_base->emit_epilogue = si_tgsi_emit_epilogue;
6118 ctx->abi.lookup_interp_param = si_nir_lookup_interp_param;
6119 ctx->abi.load_sample_position = load_sample_position;
6120 ctx->abi.load_sample_mask_in = load_sample_mask_in;
6121 ctx->abi.emit_fbfetch = si_nir_emit_fbfetch;
6122 ctx->abi.emit_kill = si_llvm_emit_kill;
6123 break;
6124 case PIPE_SHADER_COMPUTE:
6125 ctx->abi.load_local_group_size = get_block_size;
6126 break;
6127 default:
6128 assert(!"Unsupported shader type");
6129 return false;
6130 }
6131
6132 ctx->abi.load_ubo = load_ubo;
6133 ctx->abi.load_ssbo = load_ssbo;
6134
6135 create_function(ctx);
6136 preload_ring_buffers(ctx);
6137
6138 if (ctx->type == PIPE_SHADER_TESS_CTRL &&
6139 sel->tcs_info.tessfactors_are_def_in_all_invocs) {
6140 for (unsigned i = 0; i < 6; i++) {
6141 ctx->invoc0_tess_factors[i] =
6142 ac_build_alloca_undef(&ctx->ac, ctx->i32, "");
6143 }
6144 }
6145
6146 if (ctx->type == PIPE_SHADER_GEOMETRY) {
6147 for (unsigned i = 0; i < 4; i++) {
6148 ctx->gs_next_vertex[i] =
6149 ac_build_alloca(&ctx->ac, ctx->i32, "");
6150 }
6151 if (shader->key.as_ngg) {
6152 for (unsigned i = 0; i < 4; ++i) {
6153 ctx->gs_curprim_verts[i] =
6154 lp_build_alloca(&ctx->gallivm, ctx->ac.i32, "");
6155 ctx->gs_generated_prims[i] =
6156 lp_build_alloca(&ctx->gallivm, ctx->ac.i32, "");
6157 }
6158
6159 unsigned scratch_size = 8;
6160 if (sel->so.num_outputs)
6161 scratch_size = 44;
6162
6163 LLVMTypeRef ai32 = LLVMArrayType(ctx->i32, scratch_size);
6164 ctx->gs_ngg_scratch = LLVMAddGlobalInAddressSpace(ctx->ac.module,
6165 ai32, "ngg_scratch", AC_ADDR_SPACE_LDS);
6166 LLVMSetInitializer(ctx->gs_ngg_scratch, LLVMGetUndef(ai32));
6167 LLVMSetAlignment(ctx->gs_ngg_scratch, 4);
6168
6169 ctx->gs_ngg_emit = LLVMAddGlobalInAddressSpace(ctx->ac.module,
6170 LLVMArrayType(ctx->i32, 0), "ngg_emit", AC_ADDR_SPACE_LDS);
6171 LLVMSetLinkage(ctx->gs_ngg_emit, LLVMExternalLinkage);
6172 LLVMSetAlignment(ctx->gs_ngg_emit, 4);
6173 }
6174 }
6175
6176 if (ctx->type != PIPE_SHADER_GEOMETRY &&
6177 (shader->key.as_ngg && !shader->key.as_es)) {
6178 /* Unconditionally declare scratch space base for streamout and
6179 * vertex compaction. Whether space is actually allocated is
6180 * determined during linking / PM4 creation.
6181 *
6182 * Add an extra dword per vertex to ensure an odd stride, which
6183 * avoids bank conflicts for SoA accesses.
6184 */
6185 declare_esgs_ring(ctx);
6186
6187 /* This is really only needed when streamout and / or vertex
6188 * compaction is enabled.
6189 */
6190 LLVMTypeRef asi32 = LLVMArrayType(ctx->i32, 8);
6191 ctx->gs_ngg_scratch = LLVMAddGlobalInAddressSpace(ctx->ac.module,
6192 asi32, "ngg_scratch", AC_ADDR_SPACE_LDS);
6193 LLVMSetInitializer(ctx->gs_ngg_scratch, LLVMGetUndef(asi32));
6194 LLVMSetAlignment(ctx->gs_ngg_scratch, 4);
6195 }
6196
6197 /* For GFX9 merged shaders:
6198 * - Set EXEC for the first shader. If the prolog is present, set
6199 * EXEC there instead.
6200 * - Add a barrier before the second shader.
6201 * - In the second shader, reset EXEC to ~0 and wrap the main part in
6202 * an if-statement. This is required for correctness in geometry
6203 * shaders, to ensure that empty GS waves do not send GS_EMIT and
6204 * GS_CUT messages.
6205 *
6206 * For monolithic merged shaders, the first shader is wrapped in an
6207 * if-block together with its prolog in si_build_wrapper_function.
6208 *
6209 * NGG vertex and tess eval shaders running as the last
6210 * vertex/geometry stage handle execution explicitly using
6211 * if-statements.
6212 */
6213 if (ctx->screen->info.chip_class >= GFX9) {
6214 if (!shader->is_monolithic &&
6215 sel->info.num_instructions > 1 && /* not empty shader */
6216 (shader->key.as_es || shader->key.as_ls) &&
6217 (ctx->type == PIPE_SHADER_TESS_EVAL ||
6218 (ctx->type == PIPE_SHADER_VERTEX &&
6219 !si_vs_needs_prolog(sel, &shader->key.part.vs.prolog)))) {
6220 si_init_exec_from_input(ctx,
6221 ctx->param_merged_wave_info, 0);
6222 } else if (ctx->type == PIPE_SHADER_TESS_CTRL ||
6223 ctx->type == PIPE_SHADER_GEOMETRY ||
6224 (shader->key.as_ngg && !shader->key.as_es)) {
6225 LLVMValueRef num_threads;
6226 bool nested_barrier;
6227
6228 if (!shader->is_monolithic ||
6229 (ctx->type == PIPE_SHADER_TESS_EVAL &&
6230 (shader->key.as_ngg && !shader->key.as_es)))
6231 ac_init_exec_full_mask(&ctx->ac);
6232
6233 if (ctx->type == PIPE_SHADER_TESS_CTRL ||
6234 ctx->type == PIPE_SHADER_GEOMETRY) {
6235 if (ctx->type == PIPE_SHADER_GEOMETRY && shader->key.as_ngg) {
6236 gfx10_ngg_gs_emit_prologue(ctx);
6237 nested_barrier = false;
6238 } else {
6239 nested_barrier = true;
6240 }
6241
6242 /* Number of patches / primitives */
6243 num_threads = si_unpack_param(ctx, ctx->param_merged_wave_info, 8, 8);
6244 } else {
6245 /* Number of vertices */
6246 num_threads = si_unpack_param(ctx, ctx->param_merged_wave_info, 0, 8);
6247 nested_barrier = false;
6248 }
6249
6250 LLVMValueRef ena =
6251 LLVMBuildICmp(ctx->ac.builder, LLVMIntULT,
6252 ac_get_thread_id(&ctx->ac), num_threads, "");
6253 lp_build_if(&ctx->merged_wrap_if_state, &ctx->gallivm, ena);
6254
6255 if (nested_barrier) {
6256 /* Execute a barrier before the second shader in
6257 * a merged shader.
6258 *
6259 * Execute the barrier inside the conditional block,
6260 * so that empty waves can jump directly to s_endpgm,
6261 * which will also signal the barrier.
6262 *
6263 * This is possible in gfx9, because an empty wave
6264 * for the second shader does not participate in
6265 * the epilogue. With NGG, empty waves may still
6266 * be required to export data (e.g. GS output vertices),
6267 * so we cannot let them exit early.
6268 *
6269 * If the shader is TCS and the TCS epilog is present
6270 * and contains a barrier, it will wait there and then
6271 * reach s_endpgm.
6272 */
6273 si_llvm_emit_barrier(NULL, bld_base, NULL);
6274 }
6275 }
6276 }
6277
6278 if (sel->force_correct_derivs_after_kill) {
6279 ctx->postponed_kill = ac_build_alloca_undef(&ctx->ac, ctx->i1, "");
6280 /* true = don't kill. */
6281 LLVMBuildStore(ctx->ac.builder, ctx->i1true,
6282 ctx->postponed_kill);
6283 }
6284
6285 if (sel->tokens) {
6286 if (!lp_build_tgsi_llvm(bld_base, sel->tokens)) {
6287 fprintf(stderr, "Failed to translate shader from TGSI to LLVM\n");
6288 return false;
6289 }
6290 } else {
6291 if (!si_nir_build_llvm(ctx, sel->nir)) {
6292 fprintf(stderr, "Failed to translate shader from NIR to LLVM\n");
6293 return false;
6294 }
6295 }
6296
6297 si_llvm_build_ret(ctx, ctx->return_value);
6298 return true;
6299 }
6300
6301 /**
6302 * Compute the VS prolog key, which contains all the information needed to
6303 * build the VS prolog function, and set shader->info bits where needed.
6304 *
6305 * \param info Shader info of the vertex shader.
6306 * \param num_input_sgprs Number of input SGPRs for the vertex shader.
6307 * \param prolog_key Key of the VS prolog
6308 * \param shader_out The vertex shader, or the next shader if merging LS+HS or ES+GS.
6309 * \param key Output shader part key.
6310 */
6311 static void si_get_vs_prolog_key(const struct tgsi_shader_info *info,
6312 unsigned num_input_sgprs,
6313 const struct si_vs_prolog_bits *prolog_key,
6314 struct si_shader *shader_out,
6315 union si_shader_part_key *key)
6316 {
6317 memset(key, 0, sizeof(*key));
6318 key->vs_prolog.states = *prolog_key;
6319 key->vs_prolog.num_input_sgprs = num_input_sgprs;
6320 key->vs_prolog.last_input = MAX2(1, info->num_inputs) - 1;
6321 key->vs_prolog.as_ls = shader_out->key.as_ls;
6322 key->vs_prolog.as_es = shader_out->key.as_es;
6323 key->vs_prolog.as_ngg = shader_out->key.as_ngg;
6324
6325 if (shader_out->selector->type == PIPE_SHADER_TESS_CTRL) {
6326 key->vs_prolog.as_ls = 1;
6327 key->vs_prolog.num_merged_next_stage_vgprs = 2;
6328 } else if (shader_out->selector->type == PIPE_SHADER_GEOMETRY) {
6329 key->vs_prolog.as_es = 1;
6330 key->vs_prolog.num_merged_next_stage_vgprs = 5;
6331 } else if (shader_out->key.as_ngg) {
6332 key->vs_prolog.num_merged_next_stage_vgprs = 5;
6333 }
6334
6335 /* Enable loading the InstanceID VGPR. */
6336 uint16_t input_mask = u_bit_consecutive(0, info->num_inputs);
6337
6338 if ((key->vs_prolog.states.instance_divisor_is_one |
6339 key->vs_prolog.states.instance_divisor_is_fetched) & input_mask)
6340 shader_out->info.uses_instanceid = true;
6341 }
6342
6343 /**
6344 * Compute the PS prolog key, which contains all the information needed to
6345 * build the PS prolog function, and set related bits in shader->config.
6346 */
6347 static void si_get_ps_prolog_key(struct si_shader *shader,
6348 union si_shader_part_key *key,
6349 bool separate_prolog)
6350 {
6351 struct tgsi_shader_info *info = &shader->selector->info;
6352
6353 memset(key, 0, sizeof(*key));
6354 key->ps_prolog.states = shader->key.part.ps.prolog;
6355 key->ps_prolog.colors_read = info->colors_read;
6356 key->ps_prolog.num_input_sgprs = shader->info.num_input_sgprs;
6357 key->ps_prolog.num_input_vgprs = shader->info.num_input_vgprs;
6358 key->ps_prolog.wqm = info->uses_derivatives &&
6359 (key->ps_prolog.colors_read ||
6360 key->ps_prolog.states.force_persp_sample_interp ||
6361 key->ps_prolog.states.force_linear_sample_interp ||
6362 key->ps_prolog.states.force_persp_center_interp ||
6363 key->ps_prolog.states.force_linear_center_interp ||
6364 key->ps_prolog.states.bc_optimize_for_persp ||
6365 key->ps_prolog.states.bc_optimize_for_linear);
6366 key->ps_prolog.ancillary_vgpr_index = shader->info.ancillary_vgpr_index;
6367
6368 if (info->colors_read) {
6369 unsigned *color = shader->selector->color_attr_index;
6370
6371 if (shader->key.part.ps.prolog.color_two_side) {
6372 /* BCOLORs are stored after the last input. */
6373 key->ps_prolog.num_interp_inputs = info->num_inputs;
6374 key->ps_prolog.face_vgpr_index = shader->info.face_vgpr_index;
6375 if (separate_prolog)
6376 shader->config.spi_ps_input_ena |= S_0286CC_FRONT_FACE_ENA(1);
6377 }
6378
6379 for (unsigned i = 0; i < 2; i++) {
6380 unsigned interp = info->input_interpolate[color[i]];
6381 unsigned location = info->input_interpolate_loc[color[i]];
6382
6383 if (!(info->colors_read & (0xf << i*4)))
6384 continue;
6385
6386 key->ps_prolog.color_attr_index[i] = color[i];
6387
6388 if (shader->key.part.ps.prolog.flatshade_colors &&
6389 interp == TGSI_INTERPOLATE_COLOR)
6390 interp = TGSI_INTERPOLATE_CONSTANT;
6391
6392 switch (interp) {
6393 case TGSI_INTERPOLATE_CONSTANT:
6394 key->ps_prolog.color_interp_vgpr_index[i] = -1;
6395 break;
6396 case TGSI_INTERPOLATE_PERSPECTIVE:
6397 case TGSI_INTERPOLATE_COLOR:
6398 /* Force the interpolation location for colors here. */
6399 if (shader->key.part.ps.prolog.force_persp_sample_interp)
6400 location = TGSI_INTERPOLATE_LOC_SAMPLE;
6401 if (shader->key.part.ps.prolog.force_persp_center_interp)
6402 location = TGSI_INTERPOLATE_LOC_CENTER;
6403
6404 switch (location) {
6405 case TGSI_INTERPOLATE_LOC_SAMPLE:
6406 key->ps_prolog.color_interp_vgpr_index[i] = 0;
6407 if (separate_prolog) {
6408 shader->config.spi_ps_input_ena |=
6409 S_0286CC_PERSP_SAMPLE_ENA(1);
6410 }
6411 break;
6412 case TGSI_INTERPOLATE_LOC_CENTER:
6413 key->ps_prolog.color_interp_vgpr_index[i] = 2;
6414 if (separate_prolog) {
6415 shader->config.spi_ps_input_ena |=
6416 S_0286CC_PERSP_CENTER_ENA(1);
6417 }
6418 break;
6419 case TGSI_INTERPOLATE_LOC_CENTROID:
6420 key->ps_prolog.color_interp_vgpr_index[i] = 4;
6421 if (separate_prolog) {
6422 shader->config.spi_ps_input_ena |=
6423 S_0286CC_PERSP_CENTROID_ENA(1);
6424 }
6425 break;
6426 default:
6427 assert(0);
6428 }
6429 break;
6430 case TGSI_INTERPOLATE_LINEAR:
6431 /* Force the interpolation location for colors here. */
6432 if (shader->key.part.ps.prolog.force_linear_sample_interp)
6433 location = TGSI_INTERPOLATE_LOC_SAMPLE;
6434 if (shader->key.part.ps.prolog.force_linear_center_interp)
6435 location = TGSI_INTERPOLATE_LOC_CENTER;
6436
6437 /* The VGPR assignment for non-monolithic shaders
6438 * works because InitialPSInputAddr is set on the
6439 * main shader and PERSP_PULL_MODEL is never used.
6440 */
6441 switch (location) {
6442 case TGSI_INTERPOLATE_LOC_SAMPLE:
6443 key->ps_prolog.color_interp_vgpr_index[i] =
6444 separate_prolog ? 6 : 9;
6445 if (separate_prolog) {
6446 shader->config.spi_ps_input_ena |=
6447 S_0286CC_LINEAR_SAMPLE_ENA(1);
6448 }
6449 break;
6450 case TGSI_INTERPOLATE_LOC_CENTER:
6451 key->ps_prolog.color_interp_vgpr_index[i] =
6452 separate_prolog ? 8 : 11;
6453 if (separate_prolog) {
6454 shader->config.spi_ps_input_ena |=
6455 S_0286CC_LINEAR_CENTER_ENA(1);
6456 }
6457 break;
6458 case TGSI_INTERPOLATE_LOC_CENTROID:
6459 key->ps_prolog.color_interp_vgpr_index[i] =
6460 separate_prolog ? 10 : 13;
6461 if (separate_prolog) {
6462 shader->config.spi_ps_input_ena |=
6463 S_0286CC_LINEAR_CENTROID_ENA(1);
6464 }
6465 break;
6466 default:
6467 assert(0);
6468 }
6469 break;
6470 default:
6471 assert(0);
6472 }
6473 }
6474 }
6475 }
6476
6477 /**
6478 * Check whether a PS prolog is required based on the key.
6479 */
6480 static bool si_need_ps_prolog(const union si_shader_part_key *key)
6481 {
6482 return key->ps_prolog.colors_read ||
6483 key->ps_prolog.states.force_persp_sample_interp ||
6484 key->ps_prolog.states.force_linear_sample_interp ||
6485 key->ps_prolog.states.force_persp_center_interp ||
6486 key->ps_prolog.states.force_linear_center_interp ||
6487 key->ps_prolog.states.bc_optimize_for_persp ||
6488 key->ps_prolog.states.bc_optimize_for_linear ||
6489 key->ps_prolog.states.poly_stipple ||
6490 key->ps_prolog.states.samplemask_log_ps_iter;
6491 }
6492
6493 /**
6494 * Compute the PS epilog key, which contains all the information needed to
6495 * build the PS epilog function.
6496 */
6497 static void si_get_ps_epilog_key(struct si_shader *shader,
6498 union si_shader_part_key *key)
6499 {
6500 struct tgsi_shader_info *info = &shader->selector->info;
6501 memset(key, 0, sizeof(*key));
6502 key->ps_epilog.colors_written = info->colors_written;
6503 key->ps_epilog.writes_z = info->writes_z;
6504 key->ps_epilog.writes_stencil = info->writes_stencil;
6505 key->ps_epilog.writes_samplemask = info->writes_samplemask;
6506 key->ps_epilog.states = shader->key.part.ps.epilog;
6507 }
6508
6509 /**
6510 * Build the GS prolog function. Rotate the input vertices for triangle strips
6511 * with adjacency.
6512 */
6513 static void si_build_gs_prolog_function(struct si_shader_context *ctx,
6514 union si_shader_part_key *key)
6515 {
6516 unsigned num_sgprs, num_vgprs;
6517 struct si_function_info fninfo;
6518 LLVMBuilderRef builder = ctx->ac.builder;
6519 LLVMTypeRef returns[48];
6520 LLVMValueRef func, ret;
6521
6522 si_init_function_info(&fninfo);
6523
6524 if (ctx->screen->info.chip_class >= GFX9) {
6525 if (key->gs_prolog.states.gfx9_prev_is_vs)
6526 num_sgprs = 8 + GFX9_VSGS_NUM_USER_SGPR;
6527 else
6528 num_sgprs = 8 + GFX9_TESGS_NUM_USER_SGPR;
6529 num_vgprs = 5; /* ES inputs are not needed by GS */
6530 } else {
6531 num_sgprs = GFX6_GS_NUM_USER_SGPR + 2;
6532 num_vgprs = 8;
6533 }
6534
6535 for (unsigned i = 0; i < num_sgprs; ++i) {
6536 add_arg(&fninfo, ARG_SGPR, ctx->i32);
6537 returns[i] = ctx->i32;
6538 }
6539
6540 for (unsigned i = 0; i < num_vgprs; ++i) {
6541 add_arg(&fninfo, ARG_VGPR, ctx->i32);
6542 returns[num_sgprs + i] = ctx->f32;
6543 }
6544
6545 /* Create the function. */
6546 si_create_function(ctx, "gs_prolog", returns, num_sgprs + num_vgprs,
6547 &fninfo, 0);
6548 func = ctx->main_fn;
6549
6550 /* Set the full EXEC mask for the prolog, because we are only fiddling
6551 * with registers here. The main shader part will set the correct EXEC
6552 * mask.
6553 */
6554 if (ctx->screen->info.chip_class >= GFX9 && !key->gs_prolog.is_monolithic)
6555 ac_init_exec_full_mask(&ctx->ac);
6556
6557 /* Copy inputs to outputs. This should be no-op, as the registers match,
6558 * but it will prevent the compiler from overwriting them unintentionally.
6559 */
6560 ret = ctx->return_value;
6561 for (unsigned i = 0; i < num_sgprs; i++) {
6562 LLVMValueRef p = LLVMGetParam(func, i);
6563 ret = LLVMBuildInsertValue(builder, ret, p, i, "");
6564 }
6565 for (unsigned i = 0; i < num_vgprs; i++) {
6566 LLVMValueRef p = LLVMGetParam(func, num_sgprs + i);
6567 p = ac_to_float(&ctx->ac, p);
6568 ret = LLVMBuildInsertValue(builder, ret, p, num_sgprs + i, "");
6569 }
6570
6571 if (key->gs_prolog.states.tri_strip_adj_fix) {
6572 /* Remap the input vertices for every other primitive. */
6573 const unsigned gfx6_vtx_params[6] = {
6574 num_sgprs,
6575 num_sgprs + 1,
6576 num_sgprs + 3,
6577 num_sgprs + 4,
6578 num_sgprs + 5,
6579 num_sgprs + 6
6580 };
6581 const unsigned gfx9_vtx_params[3] = {
6582 num_sgprs,
6583 num_sgprs + 1,
6584 num_sgprs + 4,
6585 };
6586 LLVMValueRef vtx_in[6], vtx_out[6];
6587 LLVMValueRef prim_id, rotate;
6588
6589 if (ctx->screen->info.chip_class >= GFX9) {
6590 for (unsigned i = 0; i < 3; i++) {
6591 vtx_in[i*2] = si_unpack_param(ctx, gfx9_vtx_params[i], 0, 16);
6592 vtx_in[i*2+1] = si_unpack_param(ctx, gfx9_vtx_params[i], 16, 16);
6593 }
6594 } else {
6595 for (unsigned i = 0; i < 6; i++)
6596 vtx_in[i] = LLVMGetParam(func, gfx6_vtx_params[i]);
6597 }
6598
6599 prim_id = LLVMGetParam(func, num_sgprs + 2);
6600 rotate = LLVMBuildTrunc(builder, prim_id, ctx->i1, "");
6601
6602 for (unsigned i = 0; i < 6; ++i) {
6603 LLVMValueRef base, rotated;
6604 base = vtx_in[i];
6605 rotated = vtx_in[(i + 4) % 6];
6606 vtx_out[i] = LLVMBuildSelect(builder, rotate, rotated, base, "");
6607 }
6608
6609 if (ctx->screen->info.chip_class >= GFX9) {
6610 for (unsigned i = 0; i < 3; i++) {
6611 LLVMValueRef hi, out;
6612
6613 hi = LLVMBuildShl(builder, vtx_out[i*2+1],
6614 LLVMConstInt(ctx->i32, 16, 0), "");
6615 out = LLVMBuildOr(builder, vtx_out[i*2], hi, "");
6616 out = ac_to_float(&ctx->ac, out);
6617 ret = LLVMBuildInsertValue(builder, ret, out,
6618 gfx9_vtx_params[i], "");
6619 }
6620 } else {
6621 for (unsigned i = 0; i < 6; i++) {
6622 LLVMValueRef out;
6623
6624 out = ac_to_float(&ctx->ac, vtx_out[i]);
6625 ret = LLVMBuildInsertValue(builder, ret, out,
6626 gfx6_vtx_params[i], "");
6627 }
6628 }
6629 }
6630
6631 LLVMBuildRet(builder, ret);
6632 }
6633
6634 /**
6635 * Given a list of shader part functions, build a wrapper function that
6636 * runs them in sequence to form a monolithic shader.
6637 */
6638 static void si_build_wrapper_function(struct si_shader_context *ctx,
6639 LLVMValueRef *parts,
6640 unsigned num_parts,
6641 unsigned main_part,
6642 unsigned next_shader_first_part)
6643 {
6644 LLVMBuilderRef builder = ctx->ac.builder;
6645 /* PS epilog has one arg per color component; gfx9 merged shader
6646 * prologs need to forward 32 user SGPRs.
6647 */
6648 struct si_function_info fninfo;
6649 LLVMValueRef initial[64], out[64];
6650 LLVMTypeRef function_type;
6651 unsigned num_first_params;
6652 unsigned num_out, initial_num_out;
6653 MAYBE_UNUSED unsigned num_out_sgpr; /* used in debug checks */
6654 MAYBE_UNUSED unsigned initial_num_out_sgpr; /* used in debug checks */
6655 unsigned num_sgprs, num_vgprs;
6656 unsigned gprs;
6657 struct lp_build_if_state if_state;
6658
6659 si_init_function_info(&fninfo);
6660
6661 for (unsigned i = 0; i < num_parts; ++i) {
6662 ac_add_function_attr(ctx->ac.context, parts[i], -1,
6663 AC_FUNC_ATTR_ALWAYSINLINE);
6664 LLVMSetLinkage(parts[i], LLVMPrivateLinkage);
6665 }
6666
6667 /* The parameters of the wrapper function correspond to those of the
6668 * first part in terms of SGPRs and VGPRs, but we use the types of the
6669 * main part to get the right types. This is relevant for the
6670 * dereferenceable attribute on descriptor table pointers.
6671 */
6672 num_sgprs = 0;
6673 num_vgprs = 0;
6674
6675 function_type = LLVMGetElementType(LLVMTypeOf(parts[0]));
6676 num_first_params = LLVMCountParamTypes(function_type);
6677
6678 for (unsigned i = 0; i < num_first_params; ++i) {
6679 LLVMValueRef param = LLVMGetParam(parts[0], i);
6680
6681 if (ac_is_sgpr_param(param)) {
6682 assert(num_vgprs == 0);
6683 num_sgprs += ac_get_type_size(LLVMTypeOf(param)) / 4;
6684 } else {
6685 num_vgprs += ac_get_type_size(LLVMTypeOf(param)) / 4;
6686 }
6687 }
6688
6689 gprs = 0;
6690 while (gprs < num_sgprs + num_vgprs) {
6691 LLVMValueRef param = LLVMGetParam(parts[main_part], fninfo.num_params);
6692 LLVMTypeRef type = LLVMTypeOf(param);
6693 unsigned size = ac_get_type_size(type) / 4;
6694
6695 add_arg(&fninfo, gprs < num_sgprs ? ARG_SGPR : ARG_VGPR, type);
6696
6697 assert(ac_is_sgpr_param(param) == (gprs < num_sgprs));
6698 assert(gprs + size <= num_sgprs + num_vgprs &&
6699 (gprs >= num_sgprs || gprs + size <= num_sgprs));
6700
6701 gprs += size;
6702 }
6703
6704 /* Prepare the return type. */
6705 unsigned num_returns = 0;
6706 LLVMTypeRef returns[32], last_func_type, return_type;
6707
6708 last_func_type = LLVMGetElementType(LLVMTypeOf(parts[num_parts - 1]));
6709 return_type = LLVMGetReturnType(last_func_type);
6710
6711 switch (LLVMGetTypeKind(return_type)) {
6712 case LLVMStructTypeKind:
6713 num_returns = LLVMCountStructElementTypes(return_type);
6714 assert(num_returns <= ARRAY_SIZE(returns));
6715 LLVMGetStructElementTypes(return_type, returns);
6716 break;
6717 case LLVMVoidTypeKind:
6718 break;
6719 default:
6720 unreachable("unexpected type");
6721 }
6722
6723 si_create_function(ctx, "wrapper", returns, num_returns, &fninfo,
6724 si_get_max_workgroup_size(ctx->shader));
6725
6726 if (is_merged_shader(ctx))
6727 ac_init_exec_full_mask(&ctx->ac);
6728
6729 /* Record the arguments of the function as if they were an output of
6730 * a previous part.
6731 */
6732 num_out = 0;
6733 num_out_sgpr = 0;
6734
6735 for (unsigned i = 0; i < fninfo.num_params; ++i) {
6736 LLVMValueRef param = LLVMGetParam(ctx->main_fn, i);
6737 LLVMTypeRef param_type = LLVMTypeOf(param);
6738 LLVMTypeRef out_type = i < fninfo.num_sgpr_params ? ctx->i32 : ctx->f32;
6739 unsigned size = ac_get_type_size(param_type) / 4;
6740
6741 if (size == 1) {
6742 if (LLVMGetTypeKind(param_type) == LLVMPointerTypeKind) {
6743 param = LLVMBuildPtrToInt(builder, param, ctx->i32, "");
6744 param_type = ctx->i32;
6745 }
6746
6747 if (param_type != out_type)
6748 param = LLVMBuildBitCast(builder, param, out_type, "");
6749 out[num_out++] = param;
6750 } else {
6751 LLVMTypeRef vector_type = LLVMVectorType(out_type, size);
6752
6753 if (LLVMGetTypeKind(param_type) == LLVMPointerTypeKind) {
6754 param = LLVMBuildPtrToInt(builder, param, ctx->i64, "");
6755 param_type = ctx->i64;
6756 }
6757
6758 if (param_type != vector_type)
6759 param = LLVMBuildBitCast(builder, param, vector_type, "");
6760
6761 for (unsigned j = 0; j < size; ++j)
6762 out[num_out++] = LLVMBuildExtractElement(
6763 builder, param, LLVMConstInt(ctx->i32, j, 0), "");
6764 }
6765
6766 if (i < fninfo.num_sgpr_params)
6767 num_out_sgpr = num_out;
6768 }
6769
6770 memcpy(initial, out, sizeof(out));
6771 initial_num_out = num_out;
6772 initial_num_out_sgpr = num_out_sgpr;
6773
6774 /* Now chain the parts. */
6775 LLVMValueRef ret = NULL;
6776 for (unsigned part = 0; part < num_parts; ++part) {
6777 LLVMValueRef in[48];
6778 LLVMTypeRef ret_type;
6779 unsigned out_idx = 0;
6780 unsigned num_params = LLVMCountParams(parts[part]);
6781
6782 /* Merged shaders are executed conditionally depending
6783 * on the number of enabled threads passed in the input SGPRs. */
6784 if (is_multi_part_shader(ctx) && part == 0) {
6785 LLVMValueRef ena, count = initial[3];
6786
6787 count = LLVMBuildAnd(builder, count,
6788 LLVMConstInt(ctx->i32, 0x7f, 0), "");
6789 ena = LLVMBuildICmp(builder, LLVMIntULT,
6790 ac_get_thread_id(&ctx->ac), count, "");
6791 lp_build_if(&if_state, &ctx->gallivm, ena);
6792 }
6793
6794 /* Derive arguments for the next part from outputs of the
6795 * previous one.
6796 */
6797 for (unsigned param_idx = 0; param_idx < num_params; ++param_idx) {
6798 LLVMValueRef param;
6799 LLVMTypeRef param_type;
6800 bool is_sgpr;
6801 unsigned param_size;
6802 LLVMValueRef arg = NULL;
6803
6804 param = LLVMGetParam(parts[part], param_idx);
6805 param_type = LLVMTypeOf(param);
6806 param_size = ac_get_type_size(param_type) / 4;
6807 is_sgpr = ac_is_sgpr_param(param);
6808
6809 if (is_sgpr) {
6810 ac_add_function_attr(ctx->ac.context, parts[part],
6811 param_idx + 1, AC_FUNC_ATTR_INREG);
6812 } else if (out_idx < num_out_sgpr) {
6813 /* Skip returned SGPRs the current part doesn't
6814 * declare on the input. */
6815 out_idx = num_out_sgpr;
6816 }
6817
6818 assert(out_idx + param_size <= (is_sgpr ? num_out_sgpr : num_out));
6819
6820 if (param_size == 1)
6821 arg = out[out_idx];
6822 else
6823 arg = ac_build_gather_values(&ctx->ac, &out[out_idx], param_size);
6824
6825 if (LLVMTypeOf(arg) != param_type) {
6826 if (LLVMGetTypeKind(param_type) == LLVMPointerTypeKind) {
6827 if (LLVMGetPointerAddressSpace(param_type) ==
6828 AC_ADDR_SPACE_CONST_32BIT) {
6829 arg = LLVMBuildBitCast(builder, arg, ctx->i32, "");
6830 arg = LLVMBuildIntToPtr(builder, arg, param_type, "");
6831 } else {
6832 arg = LLVMBuildBitCast(builder, arg, ctx->i64, "");
6833 arg = LLVMBuildIntToPtr(builder, arg, param_type, "");
6834 }
6835 } else {
6836 arg = LLVMBuildBitCast(builder, arg, param_type, "");
6837 }
6838 }
6839
6840 in[param_idx] = arg;
6841 out_idx += param_size;
6842 }
6843
6844 ret = ac_build_call(&ctx->ac, parts[part], in, num_params);
6845
6846 if (is_multi_part_shader(ctx) &&
6847 part + 1 == next_shader_first_part) {
6848 lp_build_endif(&if_state);
6849
6850 /* The second half of the merged shader should use
6851 * the inputs from the toplevel (wrapper) function,
6852 * not the return value from the last call.
6853 *
6854 * That's because the last call was executed condi-
6855 * tionally, so we can't consume it in the main
6856 * block.
6857 */
6858 memcpy(out, initial, sizeof(initial));
6859 num_out = initial_num_out;
6860 num_out_sgpr = initial_num_out_sgpr;
6861 continue;
6862 }
6863
6864 /* Extract the returned GPRs. */
6865 ret_type = LLVMTypeOf(ret);
6866 num_out = 0;
6867 num_out_sgpr = 0;
6868
6869 if (LLVMGetTypeKind(ret_type) != LLVMVoidTypeKind) {
6870 assert(LLVMGetTypeKind(ret_type) == LLVMStructTypeKind);
6871
6872 unsigned ret_size = LLVMCountStructElementTypes(ret_type);
6873
6874 for (unsigned i = 0; i < ret_size; ++i) {
6875 LLVMValueRef val =
6876 LLVMBuildExtractValue(builder, ret, i, "");
6877
6878 assert(num_out < ARRAY_SIZE(out));
6879 out[num_out++] = val;
6880
6881 if (LLVMTypeOf(val) == ctx->i32) {
6882 assert(num_out_sgpr + 1 == num_out);
6883 num_out_sgpr = num_out;
6884 }
6885 }
6886 }
6887 }
6888
6889 /* Return the value from the last part. */
6890 if (LLVMGetTypeKind(LLVMTypeOf(ret)) == LLVMVoidTypeKind)
6891 LLVMBuildRetVoid(builder);
6892 else
6893 LLVMBuildRet(builder, ret);
6894 }
6895
6896 static bool si_should_optimize_less(struct ac_llvm_compiler *compiler,
6897 struct si_shader_selector *sel)
6898 {
6899 if (!compiler->low_opt_passes)
6900 return false;
6901
6902 /* Assume a slow CPU. */
6903 assert(!sel->screen->info.has_dedicated_vram &&
6904 sel->screen->info.chip_class <= GFX8);
6905
6906 /* For a crazy dEQP test containing 2597 memory opcodes, mostly
6907 * buffer stores. */
6908 return sel->type == PIPE_SHADER_COMPUTE &&
6909 sel->info.num_memory_instructions > 1000;
6910 }
6911
6912 int si_compile_tgsi_shader(struct si_screen *sscreen,
6913 struct ac_llvm_compiler *compiler,
6914 struct si_shader *shader,
6915 struct pipe_debug_callback *debug)
6916 {
6917 struct si_shader_selector *sel = shader->selector;
6918 struct si_shader_context ctx;
6919 int r = -1;
6920
6921 /* Dump TGSI code before doing TGSI->LLVM conversion in case the
6922 * conversion fails. */
6923 if (si_can_dump_shader(sscreen, sel->type) &&
6924 !(sscreen->debug_flags & DBG(NO_TGSI))) {
6925 if (sel->tokens)
6926 tgsi_dump(sel->tokens, 0);
6927 else
6928 nir_print_shader(sel->nir, stderr);
6929 si_dump_streamout(&sel->so);
6930 }
6931
6932 si_init_shader_ctx(&ctx, sscreen, compiler, si_get_shader_wave_size(shader));
6933 si_llvm_context_set_tgsi(&ctx, shader);
6934
6935 memset(shader->info.vs_output_param_offset, AC_EXP_PARAM_UNDEFINED,
6936 sizeof(shader->info.vs_output_param_offset));
6937
6938 shader->info.uses_instanceid = sel->info.uses_instanceid;
6939
6940 if (!si_compile_tgsi_main(&ctx)) {
6941 si_llvm_dispose(&ctx);
6942 return -1;
6943 }
6944
6945 if (shader->is_monolithic && ctx.type == PIPE_SHADER_VERTEX) {
6946 LLVMValueRef parts[2];
6947 bool need_prolog = sel->vs_needs_prolog;
6948
6949 parts[1] = ctx.main_fn;
6950
6951 if (need_prolog) {
6952 union si_shader_part_key prolog_key;
6953 si_get_vs_prolog_key(&sel->info,
6954 shader->info.num_input_sgprs,
6955 &shader->key.part.vs.prolog,
6956 shader, &prolog_key);
6957 si_build_vs_prolog_function(&ctx, &prolog_key);
6958 parts[0] = ctx.main_fn;
6959 }
6960
6961 si_build_wrapper_function(&ctx, parts + !need_prolog,
6962 1 + need_prolog, need_prolog, 0);
6963
6964 if (ctx.shader->key.opt.vs_as_prim_discard_cs)
6965 si_build_prim_discard_compute_shader(&ctx);
6966 } else if (shader->is_monolithic && ctx.type == PIPE_SHADER_TESS_CTRL) {
6967 if (sscreen->info.chip_class >= GFX9) {
6968 struct si_shader_selector *ls = shader->key.part.tcs.ls;
6969 LLVMValueRef parts[4];
6970 bool vs_needs_prolog =
6971 si_vs_needs_prolog(ls, &shader->key.part.tcs.ls_prolog);
6972
6973 /* TCS main part */
6974 parts[2] = ctx.main_fn;
6975
6976 /* TCS epilog */
6977 union si_shader_part_key tcs_epilog_key;
6978 memset(&tcs_epilog_key, 0, sizeof(tcs_epilog_key));
6979 tcs_epilog_key.tcs_epilog.states = shader->key.part.tcs.epilog;
6980 si_build_tcs_epilog_function(&ctx, &tcs_epilog_key);
6981 parts[3] = ctx.main_fn;
6982
6983 /* VS as LS main part */
6984 struct si_shader shader_ls = {};
6985 shader_ls.selector = ls;
6986 shader_ls.key.as_ls = 1;
6987 shader_ls.key.mono = shader->key.mono;
6988 shader_ls.key.opt = shader->key.opt;
6989 shader_ls.is_monolithic = true;
6990 si_llvm_context_set_tgsi(&ctx, &shader_ls);
6991
6992 if (!si_compile_tgsi_main(&ctx)) {
6993 si_llvm_dispose(&ctx);
6994 return -1;
6995 }
6996 shader->info.uses_instanceid |= ls->info.uses_instanceid;
6997 parts[1] = ctx.main_fn;
6998
6999 /* LS prolog */
7000 if (vs_needs_prolog) {
7001 union si_shader_part_key vs_prolog_key;
7002 si_get_vs_prolog_key(&ls->info,
7003 shader_ls.info.num_input_sgprs,
7004 &shader->key.part.tcs.ls_prolog,
7005 shader, &vs_prolog_key);
7006 vs_prolog_key.vs_prolog.is_monolithic = true;
7007 si_build_vs_prolog_function(&ctx, &vs_prolog_key);
7008 parts[0] = ctx.main_fn;
7009 }
7010
7011 /* Reset the shader context. */
7012 ctx.shader = shader;
7013 ctx.type = PIPE_SHADER_TESS_CTRL;
7014
7015 si_build_wrapper_function(&ctx,
7016 parts + !vs_needs_prolog,
7017 4 - !vs_needs_prolog, vs_needs_prolog,
7018 vs_needs_prolog ? 2 : 1);
7019 } else {
7020 LLVMValueRef parts[2];
7021 union si_shader_part_key epilog_key;
7022
7023 parts[0] = ctx.main_fn;
7024
7025 memset(&epilog_key, 0, sizeof(epilog_key));
7026 epilog_key.tcs_epilog.states = shader->key.part.tcs.epilog;
7027 si_build_tcs_epilog_function(&ctx, &epilog_key);
7028 parts[1] = ctx.main_fn;
7029
7030 si_build_wrapper_function(&ctx, parts, 2, 0, 0);
7031 }
7032 } else if (shader->is_monolithic && ctx.type == PIPE_SHADER_GEOMETRY) {
7033 if (ctx.screen->info.chip_class >= GFX9) {
7034 struct si_shader_selector *es = shader->key.part.gs.es;
7035 LLVMValueRef es_prolog = NULL;
7036 LLVMValueRef es_main = NULL;
7037 LLVMValueRef gs_prolog = NULL;
7038 LLVMValueRef gs_main = ctx.main_fn;
7039
7040 /* GS prolog */
7041 union si_shader_part_key gs_prolog_key;
7042 memset(&gs_prolog_key, 0, sizeof(gs_prolog_key));
7043 gs_prolog_key.gs_prolog.states = shader->key.part.gs.prolog;
7044 gs_prolog_key.gs_prolog.is_monolithic = true;
7045 gs_prolog_key.gs_prolog.as_ngg = shader->key.as_ngg;
7046 si_build_gs_prolog_function(&ctx, &gs_prolog_key);
7047 gs_prolog = ctx.main_fn;
7048
7049 /* ES main part */
7050 struct si_shader shader_es = {};
7051 shader_es.selector = es;
7052 shader_es.key.as_es = 1;
7053 shader_es.key.as_ngg = shader->key.as_ngg;
7054 shader_es.key.mono = shader->key.mono;
7055 shader_es.key.opt = shader->key.opt;
7056 shader_es.is_monolithic = true;
7057 si_llvm_context_set_tgsi(&ctx, &shader_es);
7058
7059 if (!si_compile_tgsi_main(&ctx)) {
7060 si_llvm_dispose(&ctx);
7061 return -1;
7062 }
7063 shader->info.uses_instanceid |= es->info.uses_instanceid;
7064 es_main = ctx.main_fn;
7065
7066 /* ES prolog */
7067 if (es->vs_needs_prolog) {
7068 union si_shader_part_key vs_prolog_key;
7069 si_get_vs_prolog_key(&es->info,
7070 shader_es.info.num_input_sgprs,
7071 &shader->key.part.gs.vs_prolog,
7072 shader, &vs_prolog_key);
7073 vs_prolog_key.vs_prolog.is_monolithic = true;
7074 si_build_vs_prolog_function(&ctx, &vs_prolog_key);
7075 es_prolog = ctx.main_fn;
7076 }
7077
7078 /* Reset the shader context. */
7079 ctx.shader = shader;
7080 ctx.type = PIPE_SHADER_GEOMETRY;
7081
7082 /* Prepare the array of shader parts. */
7083 LLVMValueRef parts[4];
7084 unsigned num_parts = 0, main_part, next_first_part;
7085
7086 if (es_prolog)
7087 parts[num_parts++] = es_prolog;
7088
7089 parts[main_part = num_parts++] = es_main;
7090 parts[next_first_part = num_parts++] = gs_prolog;
7091 parts[num_parts++] = gs_main;
7092
7093 si_build_wrapper_function(&ctx, parts, num_parts,
7094 main_part, next_first_part);
7095 } else {
7096 LLVMValueRef parts[2];
7097 union si_shader_part_key prolog_key;
7098
7099 parts[1] = ctx.main_fn;
7100
7101 memset(&prolog_key, 0, sizeof(prolog_key));
7102 prolog_key.gs_prolog.states = shader->key.part.gs.prolog;
7103 si_build_gs_prolog_function(&ctx, &prolog_key);
7104 parts[0] = ctx.main_fn;
7105
7106 si_build_wrapper_function(&ctx, parts, 2, 1, 0);
7107 }
7108 } else if (shader->is_monolithic && ctx.type == PIPE_SHADER_FRAGMENT) {
7109 LLVMValueRef parts[3];
7110 union si_shader_part_key prolog_key;
7111 union si_shader_part_key epilog_key;
7112 bool need_prolog;
7113
7114 si_get_ps_prolog_key(shader, &prolog_key, false);
7115 need_prolog = si_need_ps_prolog(&prolog_key);
7116
7117 parts[need_prolog ? 1 : 0] = ctx.main_fn;
7118
7119 if (need_prolog) {
7120 si_build_ps_prolog_function(&ctx, &prolog_key);
7121 parts[0] = ctx.main_fn;
7122 }
7123
7124 si_get_ps_epilog_key(shader, &epilog_key);
7125 si_build_ps_epilog_function(&ctx, &epilog_key);
7126 parts[need_prolog ? 2 : 1] = ctx.main_fn;
7127
7128 si_build_wrapper_function(&ctx, parts, need_prolog ? 3 : 2,
7129 need_prolog ? 1 : 0, 0);
7130 }
7131
7132 si_llvm_optimize_module(&ctx);
7133
7134 /* Post-optimization transformations and analysis. */
7135 si_optimize_vs_outputs(&ctx);
7136
7137 if ((debug && debug->debug_message) ||
7138 si_can_dump_shader(sscreen, ctx.type)) {
7139 ctx.shader->info.private_mem_vgprs =
7140 ac_count_scratch_private_memory(ctx.main_fn);
7141 }
7142
7143 /* Make sure the input is a pointer and not integer followed by inttoptr. */
7144 assert(LLVMGetTypeKind(LLVMTypeOf(LLVMGetParam(ctx.main_fn, 0))) ==
7145 LLVMPointerTypeKind);
7146
7147 /* Compile to bytecode. */
7148 r = si_compile_llvm(sscreen, &shader->binary, &shader->config, compiler,
7149 ctx.ac.module, debug, ctx.type, ctx.ac.wave_size,
7150 si_get_shader_name(shader),
7151 si_should_optimize_less(compiler, shader->selector));
7152 si_llvm_dispose(&ctx);
7153 if (r) {
7154 fprintf(stderr, "LLVM failed to compile shader\n");
7155 return r;
7156 }
7157
7158 /* Validate SGPR and VGPR usage for compute to detect compiler bugs.
7159 * LLVM 3.9svn has this bug.
7160 */
7161 if (sel->type == PIPE_SHADER_COMPUTE) {
7162 unsigned wave_size = sscreen->compute_wave_size;
7163 unsigned max_vgprs = 256;
7164 unsigned max_sgprs = sscreen->info.chip_class >= GFX8 ? 800 : 512;
7165 unsigned max_sgprs_per_wave = 128;
7166 unsigned max_block_threads = si_get_max_workgroup_size(shader);
7167 unsigned min_waves_per_cu = DIV_ROUND_UP(max_block_threads, wave_size);
7168 unsigned min_waves_per_simd = DIV_ROUND_UP(min_waves_per_cu, 4);
7169
7170 max_vgprs = max_vgprs / min_waves_per_simd;
7171 max_sgprs = MIN2(max_sgprs / min_waves_per_simd, max_sgprs_per_wave);
7172
7173 if (shader->config.num_sgprs > max_sgprs ||
7174 shader->config.num_vgprs > max_vgprs) {
7175 fprintf(stderr, "LLVM failed to compile a shader correctly: "
7176 "SGPR:VGPR usage is %u:%u, but the hw limit is %u:%u\n",
7177 shader->config.num_sgprs, shader->config.num_vgprs,
7178 max_sgprs, max_vgprs);
7179
7180 /* Just terminate the process, because dependent
7181 * shaders can hang due to bad input data, but use
7182 * the env var to allow shader-db to work.
7183 */
7184 if (!debug_get_bool_option("SI_PASS_BAD_SHADERS", false))
7185 abort();
7186 }
7187 }
7188
7189 /* Add the scratch offset to input SGPRs. */
7190 if (shader->config.scratch_bytes_per_wave && !is_merged_shader(&ctx))
7191 shader->info.num_input_sgprs += 1; /* scratch byte offset */
7192
7193 /* Calculate the number of fragment input VGPRs. */
7194 if (ctx.type == PIPE_SHADER_FRAGMENT) {
7195 shader->info.num_input_vgprs = 0;
7196 shader->info.face_vgpr_index = -1;
7197 shader->info.ancillary_vgpr_index = -1;
7198
7199 if (G_0286CC_PERSP_SAMPLE_ENA(shader->config.spi_ps_input_addr))
7200 shader->info.num_input_vgprs += 2;
7201 if (G_0286CC_PERSP_CENTER_ENA(shader->config.spi_ps_input_addr))
7202 shader->info.num_input_vgprs += 2;
7203 if (G_0286CC_PERSP_CENTROID_ENA(shader->config.spi_ps_input_addr))
7204 shader->info.num_input_vgprs += 2;
7205 if (G_0286CC_PERSP_PULL_MODEL_ENA(shader->config.spi_ps_input_addr))
7206 shader->info.num_input_vgprs += 3;
7207 if (G_0286CC_LINEAR_SAMPLE_ENA(shader->config.spi_ps_input_addr))
7208 shader->info.num_input_vgprs += 2;
7209 if (G_0286CC_LINEAR_CENTER_ENA(shader->config.spi_ps_input_addr))
7210 shader->info.num_input_vgprs += 2;
7211 if (G_0286CC_LINEAR_CENTROID_ENA(shader->config.spi_ps_input_addr))
7212 shader->info.num_input_vgprs += 2;
7213 if (G_0286CC_LINE_STIPPLE_TEX_ENA(shader->config.spi_ps_input_addr))
7214 shader->info.num_input_vgprs += 1;
7215 if (G_0286CC_POS_X_FLOAT_ENA(shader->config.spi_ps_input_addr))
7216 shader->info.num_input_vgprs += 1;
7217 if (G_0286CC_POS_Y_FLOAT_ENA(shader->config.spi_ps_input_addr))
7218 shader->info.num_input_vgprs += 1;
7219 if (G_0286CC_POS_Z_FLOAT_ENA(shader->config.spi_ps_input_addr))
7220 shader->info.num_input_vgprs += 1;
7221 if (G_0286CC_POS_W_FLOAT_ENA(shader->config.spi_ps_input_addr))
7222 shader->info.num_input_vgprs += 1;
7223 if (G_0286CC_FRONT_FACE_ENA(shader->config.spi_ps_input_addr)) {
7224 shader->info.face_vgpr_index = shader->info.num_input_vgprs;
7225 shader->info.num_input_vgprs += 1;
7226 }
7227 if (G_0286CC_ANCILLARY_ENA(shader->config.spi_ps_input_addr)) {
7228 shader->info.ancillary_vgpr_index = shader->info.num_input_vgprs;
7229 shader->info.num_input_vgprs += 1;
7230 }
7231 if (G_0286CC_SAMPLE_COVERAGE_ENA(shader->config.spi_ps_input_addr))
7232 shader->info.num_input_vgprs += 1;
7233 if (G_0286CC_POS_FIXED_PT_ENA(shader->config.spi_ps_input_addr))
7234 shader->info.num_input_vgprs += 1;
7235 }
7236
7237 si_calculate_max_simd_waves(shader);
7238 si_shader_dump_stats_for_shader_db(sscreen, shader, debug);
7239 return 0;
7240 }
7241
7242 /**
7243 * Create, compile and return a shader part (prolog or epilog).
7244 *
7245 * \param sscreen screen
7246 * \param list list of shader parts of the same category
7247 * \param type shader type
7248 * \param key shader part key
7249 * \param prolog whether the part being requested is a prolog
7250 * \param tm LLVM target machine
7251 * \param debug debug callback
7252 * \param build the callback responsible for building the main function
7253 * \return non-NULL on success
7254 */
7255 static struct si_shader_part *
7256 si_get_shader_part(struct si_screen *sscreen,
7257 struct si_shader_part **list,
7258 enum pipe_shader_type type,
7259 bool prolog,
7260 union si_shader_part_key *key,
7261 struct ac_llvm_compiler *compiler,
7262 struct pipe_debug_callback *debug,
7263 void (*build)(struct si_shader_context *,
7264 union si_shader_part_key *),
7265 const char *name)
7266 {
7267 struct si_shader_part *result;
7268
7269 mtx_lock(&sscreen->shader_parts_mutex);
7270
7271 /* Find existing. */
7272 for (result = *list; result; result = result->next) {
7273 if (memcmp(&result->key, key, sizeof(*key)) == 0) {
7274 mtx_unlock(&sscreen->shader_parts_mutex);
7275 return result;
7276 }
7277 }
7278
7279 /* Compile a new one. */
7280 result = CALLOC_STRUCT(si_shader_part);
7281 result->key = *key;
7282
7283 struct si_shader shader = {};
7284
7285 switch (type) {
7286 case PIPE_SHADER_VERTEX:
7287 shader.key.as_ls = key->vs_prolog.as_ls;
7288 shader.key.as_es = key->vs_prolog.as_es;
7289 shader.key.as_ngg = key->vs_prolog.as_ngg;
7290 break;
7291 case PIPE_SHADER_TESS_CTRL:
7292 assert(!prolog);
7293 shader.key.part.tcs.epilog = key->tcs_epilog.states;
7294 break;
7295 case PIPE_SHADER_GEOMETRY:
7296 assert(prolog);
7297 shader.key.as_ngg = key->gs_prolog.as_ngg;
7298 break;
7299 case PIPE_SHADER_FRAGMENT:
7300 if (prolog)
7301 shader.key.part.ps.prolog = key->ps_prolog.states;
7302 else
7303 shader.key.part.ps.epilog = key->ps_epilog.states;
7304 break;
7305 default:
7306 unreachable("bad shader part");
7307 }
7308
7309 struct si_shader_context ctx;
7310 si_init_shader_ctx(&ctx, sscreen, compiler,
7311 si_get_wave_size(sscreen, type, shader.key.as_ngg,
7312 shader.key.as_es));
7313 ctx.shader = &shader;
7314 ctx.type = type;
7315
7316 build(&ctx, key);
7317
7318 /* Compile. */
7319 si_llvm_optimize_module(&ctx);
7320
7321 if (si_compile_llvm(sscreen, &result->binary, &result->config, compiler,
7322 ctx.ac.module, debug, ctx.type, ctx.ac.wave_size,
7323 name, false)) {
7324 FREE(result);
7325 result = NULL;
7326 goto out;
7327 }
7328
7329 result->next = *list;
7330 *list = result;
7331
7332 out:
7333 si_llvm_dispose(&ctx);
7334 mtx_unlock(&sscreen->shader_parts_mutex);
7335 return result;
7336 }
7337
7338 static LLVMValueRef si_prolog_get_rw_buffers(struct si_shader_context *ctx)
7339 {
7340 LLVMValueRef ptr[2], list;
7341 bool merged_shader = is_merged_shader(ctx);
7342
7343 ptr[0] = LLVMGetParam(ctx->main_fn, (merged_shader ? 8 : 0) + SI_SGPR_RW_BUFFERS);
7344 list = LLVMBuildIntToPtr(ctx->ac.builder, ptr[0],
7345 ac_array_in_const32_addr_space(ctx->v4i32), "");
7346 return list;
7347 }
7348
7349 /**
7350 * Build the vertex shader prolog function.
7351 *
7352 * The inputs are the same as VS (a lot of SGPRs and 4 VGPR system values).
7353 * All inputs are returned unmodified. The vertex load indices are
7354 * stored after them, which will be used by the API VS for fetching inputs.
7355 *
7356 * For example, the expected outputs for instance_divisors[] = {0, 1, 2} are:
7357 * input_v0,
7358 * input_v1,
7359 * input_v2,
7360 * input_v3,
7361 * (VertexID + BaseVertex),
7362 * (InstanceID + StartInstance),
7363 * (InstanceID / 2 + StartInstance)
7364 */
7365 static void si_build_vs_prolog_function(struct si_shader_context *ctx,
7366 union si_shader_part_key *key)
7367 {
7368 struct si_function_info fninfo;
7369 LLVMTypeRef *returns;
7370 LLVMValueRef ret, func;
7371 int num_returns, i;
7372 unsigned first_vs_vgpr = key->vs_prolog.num_merged_next_stage_vgprs;
7373 unsigned num_input_vgprs = key->vs_prolog.num_merged_next_stage_vgprs + 4;
7374 LLVMValueRef input_vgprs[9];
7375 unsigned num_all_input_regs = key->vs_prolog.num_input_sgprs +
7376 num_input_vgprs;
7377 unsigned user_sgpr_base = key->vs_prolog.num_merged_next_stage_vgprs ? 8 : 0;
7378
7379 si_init_function_info(&fninfo);
7380
7381 /* 4 preloaded VGPRs + vertex load indices as prolog outputs */
7382 returns = alloca((num_all_input_regs + key->vs_prolog.last_input + 1) *
7383 sizeof(LLVMTypeRef));
7384 num_returns = 0;
7385
7386 /* Declare input and output SGPRs. */
7387 for (i = 0; i < key->vs_prolog.num_input_sgprs; i++) {
7388 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7389 returns[num_returns++] = ctx->i32;
7390 }
7391
7392 /* Preloaded VGPRs (outputs must be floats) */
7393 for (i = 0; i < num_input_vgprs; i++) {
7394 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &input_vgprs[i]);
7395 returns[num_returns++] = ctx->f32;
7396 }
7397
7398 /* Vertex load indices. */
7399 for (i = 0; i <= key->vs_prolog.last_input; i++)
7400 returns[num_returns++] = ctx->f32;
7401
7402 /* Create the function. */
7403 si_create_function(ctx, "vs_prolog", returns, num_returns, &fninfo, 0);
7404 func = ctx->main_fn;
7405
7406 if (key->vs_prolog.num_merged_next_stage_vgprs) {
7407 if (!key->vs_prolog.is_monolithic)
7408 si_init_exec_from_input(ctx, 3, 0);
7409
7410 if (key->vs_prolog.as_ls &&
7411 ctx->screen->has_ls_vgpr_init_bug) {
7412 /* If there are no HS threads, SPI loads the LS VGPRs
7413 * starting at VGPR 0. Shift them back to where they
7414 * belong.
7415 */
7416 LLVMValueRef has_hs_threads =
7417 LLVMBuildICmp(ctx->ac.builder, LLVMIntNE,
7418 si_unpack_param(ctx, 3, 8, 8),
7419 ctx->i32_0, "");
7420
7421 for (i = 4; i > 0; --i) {
7422 input_vgprs[i + 1] =
7423 LLVMBuildSelect(ctx->ac.builder, has_hs_threads,
7424 input_vgprs[i + 1],
7425 input_vgprs[i - 1], "");
7426 }
7427 }
7428 }
7429
7430 unsigned vertex_id_vgpr = first_vs_vgpr;
7431 unsigned instance_id_vgpr =
7432 ctx->screen->info.chip_class >= GFX10 ?
7433 first_vs_vgpr + 3 :
7434 first_vs_vgpr + (key->vs_prolog.as_ls ? 2 : 1);
7435
7436 ctx->abi.vertex_id = input_vgprs[vertex_id_vgpr];
7437 ctx->abi.instance_id = input_vgprs[instance_id_vgpr];
7438
7439 /* InstanceID = VertexID >> 16;
7440 * VertexID = VertexID & 0xffff;
7441 */
7442 if (key->vs_prolog.states.unpack_instance_id_from_vertex_id) {
7443 ctx->abi.instance_id = LLVMBuildLShr(ctx->ac.builder, ctx->abi.vertex_id,
7444 LLVMConstInt(ctx->i32, 16, 0), "");
7445 ctx->abi.vertex_id = LLVMBuildAnd(ctx->ac.builder, ctx->abi.vertex_id,
7446 LLVMConstInt(ctx->i32, 0xffff, 0), "");
7447 }
7448
7449 /* Copy inputs to outputs. This should be no-op, as the registers match,
7450 * but it will prevent the compiler from overwriting them unintentionally.
7451 */
7452 ret = ctx->return_value;
7453 for (i = 0; i < key->vs_prolog.num_input_sgprs; i++) {
7454 LLVMValueRef p = LLVMGetParam(func, i);
7455 ret = LLVMBuildInsertValue(ctx->ac.builder, ret, p, i, "");
7456 }
7457 for (i = 0; i < num_input_vgprs; i++) {
7458 LLVMValueRef p = input_vgprs[i];
7459
7460 if (i == vertex_id_vgpr)
7461 p = ctx->abi.vertex_id;
7462 else if (i == instance_id_vgpr)
7463 p = ctx->abi.instance_id;
7464
7465 p = ac_to_float(&ctx->ac, p);
7466 ret = LLVMBuildInsertValue(ctx->ac.builder, ret, p,
7467 key->vs_prolog.num_input_sgprs + i, "");
7468 }
7469
7470 struct lp_build_if_state wrap_if_state;
7471 LLVMValueRef original_ret = ret;
7472 bool wrapped = false;
7473
7474 if (key->vs_prolog.is_monolithic && key->vs_prolog.as_ngg) {
7475 LLVMValueRef num_threads;
7476 LLVMValueRef ena;
7477
7478 num_threads = si_unpack_param(ctx, 3, 0, 8);
7479 ena = LLVMBuildICmp(ctx->ac.builder, LLVMIntULT,
7480 ac_get_thread_id(&ctx->ac), num_threads, "");
7481 lp_build_if(&wrap_if_state, &ctx->gallivm, ena);
7482 wrapped = true;
7483 }
7484
7485 /* Compute vertex load indices from instance divisors. */
7486 LLVMValueRef instance_divisor_constbuf = NULL;
7487
7488 if (key->vs_prolog.states.instance_divisor_is_fetched) {
7489 LLVMValueRef list = si_prolog_get_rw_buffers(ctx);
7490 LLVMValueRef buf_index =
7491 LLVMConstInt(ctx->i32, SI_VS_CONST_INSTANCE_DIVISORS, 0);
7492 instance_divisor_constbuf =
7493 ac_build_load_to_sgpr(&ctx->ac, list, buf_index);
7494 }
7495
7496 for (i = 0; i <= key->vs_prolog.last_input; i++) {
7497 bool divisor_is_one =
7498 key->vs_prolog.states.instance_divisor_is_one & (1u << i);
7499 bool divisor_is_fetched =
7500 key->vs_prolog.states.instance_divisor_is_fetched & (1u << i);
7501 LLVMValueRef index = NULL;
7502
7503 if (divisor_is_one) {
7504 index = ctx->abi.instance_id;
7505 } else if (divisor_is_fetched) {
7506 LLVMValueRef udiv_factors[4];
7507
7508 for (unsigned j = 0; j < 4; j++) {
7509 udiv_factors[j] =
7510 buffer_load_const(ctx, instance_divisor_constbuf,
7511 LLVMConstInt(ctx->i32, i*16 + j*4, 0));
7512 udiv_factors[j] = ac_to_integer(&ctx->ac, udiv_factors[j]);
7513 }
7514 /* The faster NUW version doesn't work when InstanceID == UINT_MAX.
7515 * Such InstanceID might not be achievable in a reasonable time though.
7516 */
7517 index = ac_build_fast_udiv_nuw(&ctx->ac, ctx->abi.instance_id,
7518 udiv_factors[0], udiv_factors[1],
7519 udiv_factors[2], udiv_factors[3]);
7520 }
7521
7522 if (divisor_is_one || divisor_is_fetched) {
7523 /* Add StartInstance. */
7524 index = LLVMBuildAdd(ctx->ac.builder, index,
7525 LLVMGetParam(ctx->main_fn, user_sgpr_base +
7526 SI_SGPR_START_INSTANCE), "");
7527 } else {
7528 /* VertexID + BaseVertex */
7529 index = LLVMBuildAdd(ctx->ac.builder,
7530 ctx->abi.vertex_id,
7531 LLVMGetParam(func, user_sgpr_base +
7532 SI_SGPR_BASE_VERTEX), "");
7533 }
7534
7535 index = ac_to_float(&ctx->ac, index);
7536 ret = LLVMBuildInsertValue(ctx->ac.builder, ret, index,
7537 fninfo.num_params + i, "");
7538 }
7539
7540 if (wrapped) {
7541 lp_build_endif(&wrap_if_state);
7542
7543 LLVMValueRef values[2] = {
7544 ret,
7545 original_ret
7546 };
7547 LLVMBasicBlockRef bbs[2] = {
7548 wrap_if_state.true_block,
7549 wrap_if_state.entry_block
7550 };
7551 ret = ac_build_phi(&ctx->ac, LLVMTypeOf(ret), 2, values, bbs);
7552 }
7553
7554 si_llvm_build_ret(ctx, ret);
7555 }
7556
7557 static bool si_get_vs_prolog(struct si_screen *sscreen,
7558 struct ac_llvm_compiler *compiler,
7559 struct si_shader *shader,
7560 struct pipe_debug_callback *debug,
7561 struct si_shader *main_part,
7562 const struct si_vs_prolog_bits *key)
7563 {
7564 struct si_shader_selector *vs = main_part->selector;
7565
7566 if (!si_vs_needs_prolog(vs, key))
7567 return true;
7568
7569 /* Get the prolog. */
7570 union si_shader_part_key prolog_key;
7571 si_get_vs_prolog_key(&vs->info, main_part->info.num_input_sgprs,
7572 key, shader, &prolog_key);
7573
7574 shader->prolog =
7575 si_get_shader_part(sscreen, &sscreen->vs_prologs,
7576 PIPE_SHADER_VERTEX, true, &prolog_key, compiler,
7577 debug, si_build_vs_prolog_function,
7578 "Vertex Shader Prolog");
7579 return shader->prolog != NULL;
7580 }
7581
7582 /**
7583 * Select and compile (or reuse) vertex shader parts (prolog & epilog).
7584 */
7585 static bool si_shader_select_vs_parts(struct si_screen *sscreen,
7586 struct ac_llvm_compiler *compiler,
7587 struct si_shader *shader,
7588 struct pipe_debug_callback *debug)
7589 {
7590 return si_get_vs_prolog(sscreen, compiler, shader, debug, shader,
7591 &shader->key.part.vs.prolog);
7592 }
7593
7594 /**
7595 * Compile the TCS epilog function. This writes tesselation factors to memory
7596 * based on the output primitive type of the tesselator (determined by TES).
7597 */
7598 static void si_build_tcs_epilog_function(struct si_shader_context *ctx,
7599 union si_shader_part_key *key)
7600 {
7601 struct lp_build_tgsi_context *bld_base = &ctx->bld_base;
7602 struct si_function_info fninfo;
7603 LLVMValueRef func;
7604
7605 si_init_function_info(&fninfo);
7606
7607 if (ctx->screen->info.chip_class >= GFX9) {
7608 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7609 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7610 ctx->param_tcs_offchip_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7611 add_arg(&fninfo, ARG_SGPR, ctx->i32); /* wave info */
7612 ctx->param_tcs_factor_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7613 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7614 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7615 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7616 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7617 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7618 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7619 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7620 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7621 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7622 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7623 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7624 ctx->param_tcs_offchip_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7625 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7626 ctx->param_tcs_out_lds_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7627 } else {
7628 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7629 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7630 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7631 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7632 ctx->param_tcs_offchip_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7633 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7634 ctx->param_tcs_out_lds_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7635 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7636 ctx->param_tcs_offchip_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7637 ctx->param_tcs_factor_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7638 }
7639
7640 add_arg(&fninfo, ARG_VGPR, ctx->i32); /* VGPR gap */
7641 add_arg(&fninfo, ARG_VGPR, ctx->i32); /* VGPR gap */
7642 unsigned tess_factors_idx =
7643 add_arg(&fninfo, ARG_VGPR, ctx->i32); /* patch index within the wave (REL_PATCH_ID) */
7644 add_arg(&fninfo, ARG_VGPR, ctx->i32); /* invocation ID within the patch */
7645 add_arg(&fninfo, ARG_VGPR, ctx->i32); /* LDS offset where tess factors should be loaded from */
7646
7647 for (unsigned i = 0; i < 6; i++)
7648 add_arg(&fninfo, ARG_VGPR, ctx->i32); /* tess factors */
7649
7650 /* Create the function. */
7651 si_create_function(ctx, "tcs_epilog", NULL, 0, &fninfo,
7652 ctx->screen->info.chip_class >= GFX7 ? 128 : 0);
7653 ac_declare_lds_as_pointer(&ctx->ac);
7654 func = ctx->main_fn;
7655
7656 LLVMValueRef invoc0_tess_factors[6];
7657 for (unsigned i = 0; i < 6; i++)
7658 invoc0_tess_factors[i] = LLVMGetParam(func, tess_factors_idx + 3 + i);
7659
7660 si_write_tess_factors(bld_base,
7661 LLVMGetParam(func, tess_factors_idx),
7662 LLVMGetParam(func, tess_factors_idx + 1),
7663 LLVMGetParam(func, tess_factors_idx + 2),
7664 invoc0_tess_factors, invoc0_tess_factors + 4);
7665
7666 LLVMBuildRetVoid(ctx->ac.builder);
7667 }
7668
7669 /**
7670 * Select and compile (or reuse) TCS parts (epilog).
7671 */
7672 static bool si_shader_select_tcs_parts(struct si_screen *sscreen,
7673 struct ac_llvm_compiler *compiler,
7674 struct si_shader *shader,
7675 struct pipe_debug_callback *debug)
7676 {
7677 if (sscreen->info.chip_class >= GFX9) {
7678 struct si_shader *ls_main_part =
7679 shader->key.part.tcs.ls->main_shader_part_ls;
7680
7681 if (!si_get_vs_prolog(sscreen, compiler, shader, debug, ls_main_part,
7682 &shader->key.part.tcs.ls_prolog))
7683 return false;
7684
7685 shader->previous_stage = ls_main_part;
7686 }
7687
7688 /* Get the epilog. */
7689 union si_shader_part_key epilog_key;
7690 memset(&epilog_key, 0, sizeof(epilog_key));
7691 epilog_key.tcs_epilog.states = shader->key.part.tcs.epilog;
7692
7693 shader->epilog = si_get_shader_part(sscreen, &sscreen->tcs_epilogs,
7694 PIPE_SHADER_TESS_CTRL, false,
7695 &epilog_key, compiler, debug,
7696 si_build_tcs_epilog_function,
7697 "Tessellation Control Shader Epilog");
7698 return shader->epilog != NULL;
7699 }
7700
7701 /**
7702 * Select and compile (or reuse) GS parts (prolog).
7703 */
7704 static bool si_shader_select_gs_parts(struct si_screen *sscreen,
7705 struct ac_llvm_compiler *compiler,
7706 struct si_shader *shader,
7707 struct pipe_debug_callback *debug)
7708 {
7709 if (sscreen->info.chip_class >= GFX9) {
7710 struct si_shader *es_main_part;
7711 enum pipe_shader_type es_type = shader->key.part.gs.es->type;
7712
7713 if (es_type == PIPE_SHADER_TESS_EVAL && shader->key.as_ngg)
7714 es_main_part = shader->key.part.gs.es->main_shader_part_ngg_es;
7715 else
7716 es_main_part = shader->key.part.gs.es->main_shader_part_es;
7717
7718 if (es_type == PIPE_SHADER_VERTEX &&
7719 !si_get_vs_prolog(sscreen, compiler, shader, debug, es_main_part,
7720 &shader->key.part.gs.vs_prolog))
7721 return false;
7722
7723 shader->previous_stage = es_main_part;
7724 }
7725
7726 if (!shader->key.part.gs.prolog.tri_strip_adj_fix)
7727 return true;
7728
7729 union si_shader_part_key prolog_key;
7730 memset(&prolog_key, 0, sizeof(prolog_key));
7731 prolog_key.gs_prolog.states = shader->key.part.gs.prolog;
7732 prolog_key.gs_prolog.as_ngg = shader->key.as_ngg;
7733
7734 shader->prolog2 = si_get_shader_part(sscreen, &sscreen->gs_prologs,
7735 PIPE_SHADER_GEOMETRY, true,
7736 &prolog_key, compiler, debug,
7737 si_build_gs_prolog_function,
7738 "Geometry Shader Prolog");
7739 return shader->prolog2 != NULL;
7740 }
7741
7742 /**
7743 * Build the pixel shader prolog function. This handles:
7744 * - two-side color selection and interpolation
7745 * - overriding interpolation parameters for the API PS
7746 * - polygon stippling
7747 *
7748 * All preloaded SGPRs and VGPRs are passed through unmodified unless they are
7749 * overriden by other states. (e.g. per-sample interpolation)
7750 * Interpolated colors are stored after the preloaded VGPRs.
7751 */
7752 static void si_build_ps_prolog_function(struct si_shader_context *ctx,
7753 union si_shader_part_key *key)
7754 {
7755 struct si_function_info fninfo;
7756 LLVMValueRef ret, func;
7757 int num_returns, i, num_color_channels;
7758
7759 assert(si_need_ps_prolog(key));
7760
7761 si_init_function_info(&fninfo);
7762
7763 /* Declare inputs. */
7764 for (i = 0; i < key->ps_prolog.num_input_sgprs; i++)
7765 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7766
7767 for (i = 0; i < key->ps_prolog.num_input_vgprs; i++)
7768 add_arg(&fninfo, ARG_VGPR, ctx->f32);
7769
7770 /* Declare outputs (same as inputs + add colors if needed) */
7771 num_returns = fninfo.num_params;
7772 num_color_channels = util_bitcount(key->ps_prolog.colors_read);
7773 for (i = 0; i < num_color_channels; i++)
7774 fninfo.types[num_returns++] = ctx->f32;
7775
7776 /* Create the function. */
7777 si_create_function(ctx, "ps_prolog", fninfo.types, num_returns,
7778 &fninfo, 0);
7779 func = ctx->main_fn;
7780
7781 /* Copy inputs to outputs. This should be no-op, as the registers match,
7782 * but it will prevent the compiler from overwriting them unintentionally.
7783 */
7784 ret = ctx->return_value;
7785 for (i = 0; i < fninfo.num_params; i++) {
7786 LLVMValueRef p = LLVMGetParam(func, i);
7787 ret = LLVMBuildInsertValue(ctx->ac.builder, ret, p, i, "");
7788 }
7789
7790 /* Polygon stippling. */
7791 if (key->ps_prolog.states.poly_stipple) {
7792 /* POS_FIXED_PT is always last. */
7793 unsigned pos = key->ps_prolog.num_input_sgprs +
7794 key->ps_prolog.num_input_vgprs - 1;
7795 LLVMValueRef list = si_prolog_get_rw_buffers(ctx);
7796
7797 si_llvm_emit_polygon_stipple(ctx, list, pos);
7798 }
7799
7800 if (key->ps_prolog.states.bc_optimize_for_persp ||
7801 key->ps_prolog.states.bc_optimize_for_linear) {
7802 unsigned i, base = key->ps_prolog.num_input_sgprs;
7803 LLVMValueRef center[2], centroid[2], tmp, bc_optimize;
7804
7805 /* The shader should do: if (PRIM_MASK[31]) CENTROID = CENTER;
7806 * The hw doesn't compute CENTROID if the whole wave only
7807 * contains fully-covered quads.
7808 *
7809 * PRIM_MASK is after user SGPRs.
7810 */
7811 bc_optimize = LLVMGetParam(func, SI_PS_NUM_USER_SGPR);
7812 bc_optimize = LLVMBuildLShr(ctx->ac.builder, bc_optimize,
7813 LLVMConstInt(ctx->i32, 31, 0), "");
7814 bc_optimize = LLVMBuildTrunc(ctx->ac.builder, bc_optimize,
7815 ctx->i1, "");
7816
7817 if (key->ps_prolog.states.bc_optimize_for_persp) {
7818 /* Read PERSP_CENTER. */
7819 for (i = 0; i < 2; i++)
7820 center[i] = LLVMGetParam(func, base + 2 + i);
7821 /* Read PERSP_CENTROID. */
7822 for (i = 0; i < 2; i++)
7823 centroid[i] = LLVMGetParam(func, base + 4 + i);
7824 /* Select PERSP_CENTROID. */
7825 for (i = 0; i < 2; i++) {
7826 tmp = LLVMBuildSelect(ctx->ac.builder, bc_optimize,
7827 center[i], centroid[i], "");
7828 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7829 tmp, base + 4 + i, "");
7830 }
7831 }
7832 if (key->ps_prolog.states.bc_optimize_for_linear) {
7833 /* Read LINEAR_CENTER. */
7834 for (i = 0; i < 2; i++)
7835 center[i] = LLVMGetParam(func, base + 8 + i);
7836 /* Read LINEAR_CENTROID. */
7837 for (i = 0; i < 2; i++)
7838 centroid[i] = LLVMGetParam(func, base + 10 + i);
7839 /* Select LINEAR_CENTROID. */
7840 for (i = 0; i < 2; i++) {
7841 tmp = LLVMBuildSelect(ctx->ac.builder, bc_optimize,
7842 center[i], centroid[i], "");
7843 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7844 tmp, base + 10 + i, "");
7845 }
7846 }
7847 }
7848
7849 /* Force per-sample interpolation. */
7850 if (key->ps_prolog.states.force_persp_sample_interp) {
7851 unsigned i, base = key->ps_prolog.num_input_sgprs;
7852 LLVMValueRef persp_sample[2];
7853
7854 /* Read PERSP_SAMPLE. */
7855 for (i = 0; i < 2; i++)
7856 persp_sample[i] = LLVMGetParam(func, base + i);
7857 /* Overwrite PERSP_CENTER. */
7858 for (i = 0; i < 2; i++)
7859 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7860 persp_sample[i], base + 2 + i, "");
7861 /* Overwrite PERSP_CENTROID. */
7862 for (i = 0; i < 2; i++)
7863 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7864 persp_sample[i], base + 4 + i, "");
7865 }
7866 if (key->ps_prolog.states.force_linear_sample_interp) {
7867 unsigned i, base = key->ps_prolog.num_input_sgprs;
7868 LLVMValueRef linear_sample[2];
7869
7870 /* Read LINEAR_SAMPLE. */
7871 for (i = 0; i < 2; i++)
7872 linear_sample[i] = LLVMGetParam(func, base + 6 + i);
7873 /* Overwrite LINEAR_CENTER. */
7874 for (i = 0; i < 2; i++)
7875 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7876 linear_sample[i], base + 8 + i, "");
7877 /* Overwrite LINEAR_CENTROID. */
7878 for (i = 0; i < 2; i++)
7879 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7880 linear_sample[i], base + 10 + i, "");
7881 }
7882
7883 /* Force center interpolation. */
7884 if (key->ps_prolog.states.force_persp_center_interp) {
7885 unsigned i, base = key->ps_prolog.num_input_sgprs;
7886 LLVMValueRef persp_center[2];
7887
7888 /* Read PERSP_CENTER. */
7889 for (i = 0; i < 2; i++)
7890 persp_center[i] = LLVMGetParam(func, base + 2 + i);
7891 /* Overwrite PERSP_SAMPLE. */
7892 for (i = 0; i < 2; i++)
7893 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7894 persp_center[i], base + i, "");
7895 /* Overwrite PERSP_CENTROID. */
7896 for (i = 0; i < 2; i++)
7897 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7898 persp_center[i], base + 4 + i, "");
7899 }
7900 if (key->ps_prolog.states.force_linear_center_interp) {
7901 unsigned i, base = key->ps_prolog.num_input_sgprs;
7902 LLVMValueRef linear_center[2];
7903
7904 /* Read LINEAR_CENTER. */
7905 for (i = 0; i < 2; i++)
7906 linear_center[i] = LLVMGetParam(func, base + 8 + i);
7907 /* Overwrite LINEAR_SAMPLE. */
7908 for (i = 0; i < 2; i++)
7909 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7910 linear_center[i], base + 6 + i, "");
7911 /* Overwrite LINEAR_CENTROID. */
7912 for (i = 0; i < 2; i++)
7913 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7914 linear_center[i], base + 10 + i, "");
7915 }
7916
7917 /* Interpolate colors. */
7918 unsigned color_out_idx = 0;
7919 for (i = 0; i < 2; i++) {
7920 unsigned writemask = (key->ps_prolog.colors_read >> (i * 4)) & 0xf;
7921 unsigned face_vgpr = key->ps_prolog.num_input_sgprs +
7922 key->ps_prolog.face_vgpr_index;
7923 LLVMValueRef interp[2], color[4];
7924 LLVMValueRef interp_ij = NULL, prim_mask = NULL, face = NULL;
7925
7926 if (!writemask)
7927 continue;
7928
7929 /* If the interpolation qualifier is not CONSTANT (-1). */
7930 if (key->ps_prolog.color_interp_vgpr_index[i] != -1) {
7931 unsigned interp_vgpr = key->ps_prolog.num_input_sgprs +
7932 key->ps_prolog.color_interp_vgpr_index[i];
7933
7934 /* Get the (i,j) updated by bc_optimize handling. */
7935 interp[0] = LLVMBuildExtractValue(ctx->ac.builder, ret,
7936 interp_vgpr, "");
7937 interp[1] = LLVMBuildExtractValue(ctx->ac.builder, ret,
7938 interp_vgpr + 1, "");
7939 interp_ij = ac_build_gather_values(&ctx->ac, interp, 2);
7940 }
7941
7942 /* Use the absolute location of the input. */
7943 prim_mask = LLVMGetParam(func, SI_PS_NUM_USER_SGPR);
7944
7945 if (key->ps_prolog.states.color_two_side) {
7946 face = LLVMGetParam(func, face_vgpr);
7947 face = ac_to_integer(&ctx->ac, face);
7948 }
7949
7950 interp_fs_input(ctx,
7951 key->ps_prolog.color_attr_index[i],
7952 TGSI_SEMANTIC_COLOR, i,
7953 key->ps_prolog.num_interp_inputs,
7954 key->ps_prolog.colors_read, interp_ij,
7955 prim_mask, face, color);
7956
7957 while (writemask) {
7958 unsigned chan = u_bit_scan(&writemask);
7959 ret = LLVMBuildInsertValue(ctx->ac.builder, ret, color[chan],
7960 fninfo.num_params + color_out_idx++, "");
7961 }
7962 }
7963
7964 /* Section 15.2.2 (Shader Inputs) of the OpenGL 4.5 (Core Profile) spec
7965 * says:
7966 *
7967 * "When per-sample shading is active due to the use of a fragment
7968 * input qualified by sample or due to the use of the gl_SampleID
7969 * or gl_SamplePosition variables, only the bit for the current
7970 * sample is set in gl_SampleMaskIn. When state specifies multiple
7971 * fragment shader invocations for a given fragment, the sample
7972 * mask for any single fragment shader invocation may specify a
7973 * subset of the covered samples for the fragment. In this case,
7974 * the bit corresponding to each covered sample will be set in
7975 * exactly one fragment shader invocation."
7976 *
7977 * The samplemask loaded by hardware is always the coverage of the
7978 * entire pixel/fragment, so mask bits out based on the sample ID.
7979 */
7980 if (key->ps_prolog.states.samplemask_log_ps_iter) {
7981 /* The bit pattern matches that used by fixed function fragment
7982 * processing. */
7983 static const uint16_t ps_iter_masks[] = {
7984 0xffff, /* not used */
7985 0x5555,
7986 0x1111,
7987 0x0101,
7988 0x0001,
7989 };
7990 assert(key->ps_prolog.states.samplemask_log_ps_iter < ARRAY_SIZE(ps_iter_masks));
7991
7992 uint32_t ps_iter_mask = ps_iter_masks[key->ps_prolog.states.samplemask_log_ps_iter];
7993 unsigned ancillary_vgpr = key->ps_prolog.num_input_sgprs +
7994 key->ps_prolog.ancillary_vgpr_index;
7995 LLVMValueRef sampleid = si_unpack_param(ctx, ancillary_vgpr, 8, 4);
7996 LLVMValueRef samplemask = LLVMGetParam(func, ancillary_vgpr + 1);
7997
7998 samplemask = ac_to_integer(&ctx->ac, samplemask);
7999 samplemask = LLVMBuildAnd(
8000 ctx->ac.builder,
8001 samplemask,
8002 LLVMBuildShl(ctx->ac.builder,
8003 LLVMConstInt(ctx->i32, ps_iter_mask, false),
8004 sampleid, ""),
8005 "");
8006 samplemask = ac_to_float(&ctx->ac, samplemask);
8007
8008 ret = LLVMBuildInsertValue(ctx->ac.builder, ret, samplemask,
8009 ancillary_vgpr + 1, "");
8010 }
8011
8012 /* Tell LLVM to insert WQM instruction sequence when needed. */
8013 if (key->ps_prolog.wqm) {
8014 LLVMAddTargetDependentFunctionAttr(func,
8015 "amdgpu-ps-wqm-outputs", "");
8016 }
8017
8018 si_llvm_build_ret(ctx, ret);
8019 }
8020
8021 /**
8022 * Build the pixel shader epilog function. This handles everything that must be
8023 * emulated for pixel shader exports. (alpha-test, format conversions, etc)
8024 */
8025 static void si_build_ps_epilog_function(struct si_shader_context *ctx,
8026 union si_shader_part_key *key)
8027 {
8028 struct lp_build_tgsi_context *bld_base = &ctx->bld_base;
8029 struct si_function_info fninfo;
8030 LLVMValueRef depth = NULL, stencil = NULL, samplemask = NULL;
8031 int i;
8032 struct si_ps_exports exp = {};
8033
8034 si_init_function_info(&fninfo);
8035
8036 /* Declare input SGPRs. */
8037 ctx->param_rw_buffers = add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
8038 ctx->param_bindless_samplers_and_images = add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
8039 ctx->param_const_and_shader_buffers = add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
8040 ctx->param_samplers_and_images = add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
8041 add_arg_checked(&fninfo, ARG_SGPR, ctx->f32, SI_PARAM_ALPHA_REF);
8042
8043 /* Declare input VGPRs. */
8044 unsigned required_num_params =
8045 fninfo.num_sgpr_params +
8046 util_bitcount(key->ps_epilog.colors_written) * 4 +
8047 key->ps_epilog.writes_z +
8048 key->ps_epilog.writes_stencil +
8049 key->ps_epilog.writes_samplemask;
8050
8051 required_num_params = MAX2(required_num_params,
8052 fninfo.num_sgpr_params + PS_EPILOG_SAMPLEMASK_MIN_LOC + 1);
8053
8054 while (fninfo.num_params < required_num_params)
8055 add_arg(&fninfo, ARG_VGPR, ctx->f32);
8056
8057 /* Create the function. */
8058 si_create_function(ctx, "ps_epilog", NULL, 0, &fninfo, 0);
8059 /* Disable elimination of unused inputs. */
8060 ac_llvm_add_target_dep_function_attr(ctx->main_fn,
8061 "InitialPSInputAddr", 0xffffff);
8062
8063 /* Process colors. */
8064 unsigned vgpr = fninfo.num_sgpr_params;
8065 unsigned colors_written = key->ps_epilog.colors_written;
8066 int last_color_export = -1;
8067
8068 /* Find the last color export. */
8069 if (!key->ps_epilog.writes_z &&
8070 !key->ps_epilog.writes_stencil &&
8071 !key->ps_epilog.writes_samplemask) {
8072 unsigned spi_format = key->ps_epilog.states.spi_shader_col_format;
8073
8074 /* If last_cbuf > 0, FS_COLOR0_WRITES_ALL_CBUFS is true. */
8075 if (colors_written == 0x1 && key->ps_epilog.states.last_cbuf > 0) {
8076 /* Just set this if any of the colorbuffers are enabled. */
8077 if (spi_format &
8078 ((1ull << (4 * (key->ps_epilog.states.last_cbuf + 1))) - 1))
8079 last_color_export = 0;
8080 } else {
8081 for (i = 0; i < 8; i++)
8082 if (colors_written & (1 << i) &&
8083 (spi_format >> (i * 4)) & 0xf)
8084 last_color_export = i;
8085 }
8086 }
8087
8088 while (colors_written) {
8089 LLVMValueRef color[4];
8090 int mrt = u_bit_scan(&colors_written);
8091
8092 for (i = 0; i < 4; i++)
8093 color[i] = LLVMGetParam(ctx->main_fn, vgpr++);
8094
8095 si_export_mrt_color(bld_base, color, mrt,
8096 fninfo.num_params - 1,
8097 mrt == last_color_export, &exp);
8098 }
8099
8100 /* Process depth, stencil, samplemask. */
8101 if (key->ps_epilog.writes_z)
8102 depth = LLVMGetParam(ctx->main_fn, vgpr++);
8103 if (key->ps_epilog.writes_stencil)
8104 stencil = LLVMGetParam(ctx->main_fn, vgpr++);
8105 if (key->ps_epilog.writes_samplemask)
8106 samplemask = LLVMGetParam(ctx->main_fn, vgpr++);
8107
8108 if (depth || stencil || samplemask)
8109 si_export_mrt_z(bld_base, depth, stencil, samplemask, &exp);
8110 else if (last_color_export == -1)
8111 ac_build_export_null(&ctx->ac);
8112
8113 if (exp.num)
8114 si_emit_ps_exports(ctx, &exp);
8115
8116 /* Compile. */
8117 LLVMBuildRetVoid(ctx->ac.builder);
8118 }
8119
8120 /**
8121 * Select and compile (or reuse) pixel shader parts (prolog & epilog).
8122 */
8123 static bool si_shader_select_ps_parts(struct si_screen *sscreen,
8124 struct ac_llvm_compiler *compiler,
8125 struct si_shader *shader,
8126 struct pipe_debug_callback *debug)
8127 {
8128 union si_shader_part_key prolog_key;
8129 union si_shader_part_key epilog_key;
8130
8131 /* Get the prolog. */
8132 si_get_ps_prolog_key(shader, &prolog_key, true);
8133
8134 /* The prolog is a no-op if these aren't set. */
8135 if (si_need_ps_prolog(&prolog_key)) {
8136 shader->prolog =
8137 si_get_shader_part(sscreen, &sscreen->ps_prologs,
8138 PIPE_SHADER_FRAGMENT, true,
8139 &prolog_key, compiler, debug,
8140 si_build_ps_prolog_function,
8141 "Fragment Shader Prolog");
8142 if (!shader->prolog)
8143 return false;
8144 }
8145
8146 /* Get the epilog. */
8147 si_get_ps_epilog_key(shader, &epilog_key);
8148
8149 shader->epilog =
8150 si_get_shader_part(sscreen, &sscreen->ps_epilogs,
8151 PIPE_SHADER_FRAGMENT, false,
8152 &epilog_key, compiler, debug,
8153 si_build_ps_epilog_function,
8154 "Fragment Shader Epilog");
8155 if (!shader->epilog)
8156 return false;
8157
8158 /* Enable POS_FIXED_PT if polygon stippling is enabled. */
8159 if (shader->key.part.ps.prolog.poly_stipple) {
8160 shader->config.spi_ps_input_ena |= S_0286CC_POS_FIXED_PT_ENA(1);
8161 assert(G_0286CC_POS_FIXED_PT_ENA(shader->config.spi_ps_input_addr));
8162 }
8163
8164 /* Set up the enable bits for per-sample shading if needed. */
8165 if (shader->key.part.ps.prolog.force_persp_sample_interp &&
8166 (G_0286CC_PERSP_CENTER_ENA(shader->config.spi_ps_input_ena) ||
8167 G_0286CC_PERSP_CENTROID_ENA(shader->config.spi_ps_input_ena))) {
8168 shader->config.spi_ps_input_ena &= C_0286CC_PERSP_CENTER_ENA;
8169 shader->config.spi_ps_input_ena &= C_0286CC_PERSP_CENTROID_ENA;
8170 shader->config.spi_ps_input_ena |= S_0286CC_PERSP_SAMPLE_ENA(1);
8171 }
8172 if (shader->key.part.ps.prolog.force_linear_sample_interp &&
8173 (G_0286CC_LINEAR_CENTER_ENA(shader->config.spi_ps_input_ena) ||
8174 G_0286CC_LINEAR_CENTROID_ENA(shader->config.spi_ps_input_ena))) {
8175 shader->config.spi_ps_input_ena &= C_0286CC_LINEAR_CENTER_ENA;
8176 shader->config.spi_ps_input_ena &= C_0286CC_LINEAR_CENTROID_ENA;
8177 shader->config.spi_ps_input_ena |= S_0286CC_LINEAR_SAMPLE_ENA(1);
8178 }
8179 if (shader->key.part.ps.prolog.force_persp_center_interp &&
8180 (G_0286CC_PERSP_SAMPLE_ENA(shader->config.spi_ps_input_ena) ||
8181 G_0286CC_PERSP_CENTROID_ENA(shader->config.spi_ps_input_ena))) {
8182 shader->config.spi_ps_input_ena &= C_0286CC_PERSP_SAMPLE_ENA;
8183 shader->config.spi_ps_input_ena &= C_0286CC_PERSP_CENTROID_ENA;
8184 shader->config.spi_ps_input_ena |= S_0286CC_PERSP_CENTER_ENA(1);
8185 }
8186 if (shader->key.part.ps.prolog.force_linear_center_interp &&
8187 (G_0286CC_LINEAR_SAMPLE_ENA(shader->config.spi_ps_input_ena) ||
8188 G_0286CC_LINEAR_CENTROID_ENA(shader->config.spi_ps_input_ena))) {
8189 shader->config.spi_ps_input_ena &= C_0286CC_LINEAR_SAMPLE_ENA;
8190 shader->config.spi_ps_input_ena &= C_0286CC_LINEAR_CENTROID_ENA;
8191 shader->config.spi_ps_input_ena |= S_0286CC_LINEAR_CENTER_ENA(1);
8192 }
8193
8194 /* POW_W_FLOAT requires that one of the perspective weights is enabled. */
8195 if (G_0286CC_POS_W_FLOAT_ENA(shader->config.spi_ps_input_ena) &&
8196 !(shader->config.spi_ps_input_ena & 0xf)) {
8197 shader->config.spi_ps_input_ena |= S_0286CC_PERSP_CENTER_ENA(1);
8198 assert(G_0286CC_PERSP_CENTER_ENA(shader->config.spi_ps_input_addr));
8199 }
8200
8201 /* At least one pair of interpolation weights must be enabled. */
8202 if (!(shader->config.spi_ps_input_ena & 0x7f)) {
8203 shader->config.spi_ps_input_ena |= S_0286CC_LINEAR_CENTER_ENA(1);
8204 assert(G_0286CC_LINEAR_CENTER_ENA(shader->config.spi_ps_input_addr));
8205 }
8206
8207 /* Samplemask fixup requires the sample ID. */
8208 if (shader->key.part.ps.prolog.samplemask_log_ps_iter) {
8209 shader->config.spi_ps_input_ena |= S_0286CC_ANCILLARY_ENA(1);
8210 assert(G_0286CC_ANCILLARY_ENA(shader->config.spi_ps_input_addr));
8211 }
8212
8213 /* The sample mask input is always enabled, because the API shader always
8214 * passes it through to the epilog. Disable it here if it's unused.
8215 */
8216 if (!shader->key.part.ps.epilog.poly_line_smoothing &&
8217 !shader->selector->info.reads_samplemask)
8218 shader->config.spi_ps_input_ena &= C_0286CC_SAMPLE_COVERAGE_ENA;
8219
8220 return true;
8221 }
8222
8223 void si_multiwave_lds_size_workaround(struct si_screen *sscreen,
8224 unsigned *lds_size)
8225 {
8226 /* If tessellation is all offchip and on-chip GS isn't used, this
8227 * workaround is not needed.
8228 */
8229 return;
8230
8231 /* SPI barrier management bug:
8232 * Make sure we have at least 4k of LDS in use to avoid the bug.
8233 * It applies to workgroup sizes of more than one wavefront.
8234 */
8235 if (sscreen->info.family == CHIP_BONAIRE ||
8236 sscreen->info.family == CHIP_KABINI)
8237 *lds_size = MAX2(*lds_size, 8);
8238 }
8239
8240 static void si_fix_resource_usage(struct si_screen *sscreen,
8241 struct si_shader *shader)
8242 {
8243 unsigned min_sgprs = shader->info.num_input_sgprs + 2; /* VCC */
8244
8245 shader->config.num_sgprs = MAX2(shader->config.num_sgprs, min_sgprs);
8246
8247 if (shader->selector->type == PIPE_SHADER_COMPUTE &&
8248 si_get_max_workgroup_size(shader) > sscreen->compute_wave_size) {
8249 si_multiwave_lds_size_workaround(sscreen,
8250 &shader->config.lds_size);
8251 }
8252 }
8253
8254 bool si_shader_create(struct si_screen *sscreen, struct ac_llvm_compiler *compiler,
8255 struct si_shader *shader,
8256 struct pipe_debug_callback *debug)
8257 {
8258 struct si_shader_selector *sel = shader->selector;
8259 struct si_shader *mainp = *si_get_main_shader_part(sel, &shader->key);
8260 int r;
8261
8262 /* LS, ES, VS are compiled on demand if the main part hasn't been
8263 * compiled for that stage.
8264 *
8265 * GS are compiled on demand if the main part hasn't been compiled
8266 * for the chosen NGG-ness.
8267 *
8268 * Vertex shaders are compiled on demand when a vertex fetch
8269 * workaround must be applied.
8270 */
8271 if (shader->is_monolithic) {
8272 /* Monolithic shader (compiled as a whole, has many variants,
8273 * may take a long time to compile).
8274 */
8275 r = si_compile_tgsi_shader(sscreen, compiler, shader, debug);
8276 if (r)
8277 return false;
8278 } else {
8279 /* The shader consists of several parts:
8280 *
8281 * - the middle part is the user shader, it has 1 variant only
8282 * and it was compiled during the creation of the shader
8283 * selector
8284 * - the prolog part is inserted at the beginning
8285 * - the epilog part is inserted at the end
8286 *
8287 * The prolog and epilog have many (but simple) variants.
8288 *
8289 * Starting with gfx9, geometry and tessellation control
8290 * shaders also contain the prolog and user shader parts of
8291 * the previous shader stage.
8292 */
8293
8294 if (!mainp)
8295 return false;
8296
8297 /* Copy the compiled TGSI shader data over. */
8298 shader->is_binary_shared = true;
8299 shader->binary = mainp->binary;
8300 shader->config = mainp->config;
8301 shader->info.num_input_sgprs = mainp->info.num_input_sgprs;
8302 shader->info.num_input_vgprs = mainp->info.num_input_vgprs;
8303 shader->info.face_vgpr_index = mainp->info.face_vgpr_index;
8304 shader->info.ancillary_vgpr_index = mainp->info.ancillary_vgpr_index;
8305 memcpy(shader->info.vs_output_param_offset,
8306 mainp->info.vs_output_param_offset,
8307 sizeof(mainp->info.vs_output_param_offset));
8308 shader->info.uses_instanceid = mainp->info.uses_instanceid;
8309 shader->info.nr_pos_exports = mainp->info.nr_pos_exports;
8310 shader->info.nr_param_exports = mainp->info.nr_param_exports;
8311
8312 /* Select prologs and/or epilogs. */
8313 switch (sel->type) {
8314 case PIPE_SHADER_VERTEX:
8315 if (!si_shader_select_vs_parts(sscreen, compiler, shader, debug))
8316 return false;
8317 break;
8318 case PIPE_SHADER_TESS_CTRL:
8319 if (!si_shader_select_tcs_parts(sscreen, compiler, shader, debug))
8320 return false;
8321 break;
8322 case PIPE_SHADER_TESS_EVAL:
8323 break;
8324 case PIPE_SHADER_GEOMETRY:
8325 if (!si_shader_select_gs_parts(sscreen, compiler, shader, debug))
8326 return false;
8327 break;
8328 case PIPE_SHADER_FRAGMENT:
8329 if (!si_shader_select_ps_parts(sscreen, compiler, shader, debug))
8330 return false;
8331
8332 /* Make sure we have at least as many VGPRs as there
8333 * are allocated inputs.
8334 */
8335 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
8336 shader->info.num_input_vgprs);
8337 break;
8338 default:;
8339 }
8340
8341 /* Update SGPR and VGPR counts. */
8342 if (shader->prolog) {
8343 shader->config.num_sgprs = MAX2(shader->config.num_sgprs,
8344 shader->prolog->config.num_sgprs);
8345 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
8346 shader->prolog->config.num_vgprs);
8347 }
8348 if (shader->previous_stage) {
8349 shader->config.num_sgprs = MAX2(shader->config.num_sgprs,
8350 shader->previous_stage->config.num_sgprs);
8351 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
8352 shader->previous_stage->config.num_vgprs);
8353 shader->config.spilled_sgprs =
8354 MAX2(shader->config.spilled_sgprs,
8355 shader->previous_stage->config.spilled_sgprs);
8356 shader->config.spilled_vgprs =
8357 MAX2(shader->config.spilled_vgprs,
8358 shader->previous_stage->config.spilled_vgprs);
8359 shader->info.private_mem_vgprs =
8360 MAX2(shader->info.private_mem_vgprs,
8361 shader->previous_stage->info.private_mem_vgprs);
8362 shader->config.scratch_bytes_per_wave =
8363 MAX2(shader->config.scratch_bytes_per_wave,
8364 shader->previous_stage->config.scratch_bytes_per_wave);
8365 shader->info.uses_instanceid |=
8366 shader->previous_stage->info.uses_instanceid;
8367 }
8368 if (shader->prolog2) {
8369 shader->config.num_sgprs = MAX2(shader->config.num_sgprs,
8370 shader->prolog2->config.num_sgprs);
8371 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
8372 shader->prolog2->config.num_vgprs);
8373 }
8374 if (shader->epilog) {
8375 shader->config.num_sgprs = MAX2(shader->config.num_sgprs,
8376 shader->epilog->config.num_sgprs);
8377 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
8378 shader->epilog->config.num_vgprs);
8379 }
8380 si_calculate_max_simd_waves(shader);
8381 }
8382
8383 if (shader->key.as_ngg) {
8384 assert(!shader->key.as_es && !shader->key.as_ls);
8385 gfx10_ngg_calculate_subgroup_info(shader);
8386 } else if (sscreen->info.chip_class >= GFX9 && sel->type == PIPE_SHADER_GEOMETRY) {
8387 gfx9_get_gs_info(shader->previous_stage_sel, sel, &shader->gs_info);
8388 }
8389
8390 si_fix_resource_usage(sscreen, shader);
8391 si_shader_dump(sscreen, shader, debug, stderr, true);
8392
8393 /* Upload. */
8394 if (!si_shader_binary_upload(sscreen, shader, 0)) {
8395 fprintf(stderr, "LLVM failed to upload shader\n");
8396 return false;
8397 }
8398
8399 return true;
8400 }
8401
8402 void si_shader_destroy(struct si_shader *shader)
8403 {
8404 if (shader->scratch_bo)
8405 si_resource_reference(&shader->scratch_bo, NULL);
8406
8407 si_resource_reference(&shader->bo, NULL);
8408
8409 if (!shader->is_binary_shared)
8410 si_shader_binary_clean(&shader->binary);
8411
8412 free(shader->shader_log);
8413 }