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