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