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