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