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