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