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