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