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