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