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