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