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