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