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