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