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