ac/nir: convert type helpers to ac_llvm_context
[mesa.git] / src / amd / common / ac_nir_to_llvm.c
1 /*
2 * Copyright © 2016 Bas Nieuwenhuizen
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 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * 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 NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #include "ac_nir_to_llvm.h"
25 #include "ac_llvm_build.h"
26 #include "ac_llvm_util.h"
27 #include "ac_binary.h"
28 #include "sid.h"
29 #include "nir/nir.h"
30 #include "../vulkan/radv_descriptor_set.h"
31 #include "util/bitscan.h"
32 #include <llvm-c/Transforms/Scalar.h>
33 #include "ac_shader_info.h"
34 #include "ac_exp_param.h"
35
36 enum radeon_llvm_calling_convention {
37 RADEON_LLVM_AMDGPU_VS = 87,
38 RADEON_LLVM_AMDGPU_GS = 88,
39 RADEON_LLVM_AMDGPU_PS = 89,
40 RADEON_LLVM_AMDGPU_CS = 90,
41 };
42
43 #define CONST_ADDR_SPACE 2
44 #define LOCAL_ADDR_SPACE 3
45
46 #define RADEON_LLVM_MAX_INPUTS (VARYING_SLOT_VAR31 + 1)
47 #define RADEON_LLVM_MAX_OUTPUTS (VARYING_SLOT_VAR31 + 1)
48
49 enum desc_type {
50 DESC_IMAGE,
51 DESC_FMASK,
52 DESC_SAMPLER,
53 DESC_BUFFER,
54 };
55
56 struct nir_to_llvm_context {
57 struct ac_llvm_context ac;
58 const struct ac_nir_compiler_options *options;
59 struct ac_shader_variant_info *shader_info;
60 unsigned max_workgroup_size;
61 LLVMContextRef context;
62 LLVMModuleRef module;
63 LLVMBuilderRef builder;
64 LLVMValueRef main_function;
65
66 struct hash_table *defs;
67 struct hash_table *phis;
68
69 LLVMValueRef descriptor_sets[AC_UD_MAX_SETS];
70 LLVMValueRef ring_offsets;
71 LLVMValueRef push_constants;
72 LLVMValueRef num_work_groups;
73 LLVMValueRef workgroup_ids;
74 LLVMValueRef local_invocation_ids;
75 LLVMValueRef tg_size;
76
77 LLVMValueRef vertex_buffers;
78 LLVMValueRef base_vertex;
79 LLVMValueRef start_instance;
80 LLVMValueRef draw_index;
81 LLVMValueRef vertex_id;
82 LLVMValueRef rel_auto_id;
83 LLVMValueRef vs_prim_id;
84 LLVMValueRef instance_id;
85 LLVMValueRef ls_out_layout;
86 LLVMValueRef es2gs_offset;
87
88 LLVMValueRef tcs_offchip_layout;
89 LLVMValueRef tcs_out_offsets;
90 LLVMValueRef tcs_out_layout;
91 LLVMValueRef tcs_in_layout;
92 LLVMValueRef oc_lds;
93 LLVMValueRef tess_factor_offset;
94 LLVMValueRef tcs_patch_id;
95 LLVMValueRef tcs_rel_ids;
96 LLVMValueRef tes_rel_patch_id;
97 LLVMValueRef tes_patch_id;
98 LLVMValueRef tes_u;
99 LLVMValueRef tes_v;
100
101 LLVMValueRef gsvs_ring_stride;
102 LLVMValueRef gsvs_num_entries;
103 LLVMValueRef gs2vs_offset;
104 LLVMValueRef gs_wave_id;
105 LLVMValueRef gs_vtx_offset[6];
106 LLVMValueRef gs_prim_id, gs_invocation_id;
107
108 LLVMValueRef esgs_ring;
109 LLVMValueRef gsvs_ring;
110 LLVMValueRef hs_ring_tess_offchip;
111 LLVMValueRef hs_ring_tess_factor;
112
113 LLVMValueRef prim_mask;
114 LLVMValueRef sample_pos_offset;
115 LLVMValueRef persp_sample, persp_center, persp_centroid;
116 LLVMValueRef linear_sample, linear_center, linear_centroid;
117 LLVMValueRef front_face;
118 LLVMValueRef ancillary;
119 LLVMValueRef sample_coverage;
120 LLVMValueRef frag_pos[4];
121
122 LLVMBasicBlockRef continue_block;
123 LLVMBasicBlockRef break_block;
124
125 LLVMTypeRef i1;
126 LLVMTypeRef i8;
127 LLVMTypeRef i16;
128 LLVMTypeRef i32;
129 LLVMTypeRef i64;
130 LLVMTypeRef v2i32;
131 LLVMTypeRef v3i32;
132 LLVMTypeRef v4i32;
133 LLVMTypeRef v8i32;
134 LLVMTypeRef f64;
135 LLVMTypeRef f32;
136 LLVMTypeRef f16;
137 LLVMTypeRef v2f32;
138 LLVMTypeRef v4f32;
139 LLVMTypeRef v16i8;
140 LLVMTypeRef voidt;
141
142 LLVMValueRef i1true;
143 LLVMValueRef i1false;
144 LLVMValueRef i32zero;
145 LLVMValueRef i32one;
146 LLVMValueRef f32zero;
147 LLVMValueRef f32one;
148 LLVMValueRef v4f32empty;
149
150 unsigned uniform_md_kind;
151 LLVMValueRef empty_md;
152 gl_shader_stage stage;
153
154 LLVMValueRef lds;
155 LLVMValueRef inputs[RADEON_LLVM_MAX_INPUTS * 4];
156 LLVMValueRef outputs[RADEON_LLVM_MAX_OUTPUTS * 4];
157
158 LLVMValueRef shared_memory;
159 uint64_t input_mask;
160 uint64_t output_mask;
161 int num_locals;
162 LLVMValueRef *locals;
163 bool has_ddxy;
164 uint8_t num_output_clips;
165 uint8_t num_output_culls;
166
167 bool has_ds_bpermute;
168
169 bool is_gs_copy_shader;
170 LLVMValueRef gs_next_vertex;
171 unsigned gs_max_out_vertices;
172
173 unsigned tes_primitive_mode;
174 uint64_t tess_outputs_written;
175 uint64_t tess_patch_outputs_written;
176 };
177
178 static LLVMValueRef get_sampler_desc(struct nir_to_llvm_context *ctx,
179 const nir_deref_var *deref,
180 enum desc_type desc_type);
181 static unsigned radeon_llvm_reg_index_soa(unsigned index, unsigned chan)
182 {
183 return (index * 4) + chan;
184 }
185
186 static unsigned shader_io_get_unique_index(gl_varying_slot slot)
187 {
188 /* handle patch indices separate */
189 if (slot == VARYING_SLOT_TESS_LEVEL_OUTER)
190 return 0;
191 if (slot == VARYING_SLOT_TESS_LEVEL_INNER)
192 return 1;
193 if (slot >= VARYING_SLOT_PATCH0 && slot <= VARYING_SLOT_TESS_MAX)
194 return 2 + (slot - VARYING_SLOT_PATCH0);
195
196 if (slot == VARYING_SLOT_POS)
197 return 0;
198 if (slot == VARYING_SLOT_PSIZ)
199 return 1;
200 if (slot == VARYING_SLOT_CLIP_DIST0)
201 return 2;
202 /* 3 is reserved for clip dist as well */
203 if (slot >= VARYING_SLOT_VAR0 && slot <= VARYING_SLOT_VAR31)
204 return 4 + (slot - VARYING_SLOT_VAR0);
205 unreachable("illegal slot in get unique index\n");
206 }
207
208 static unsigned llvm_get_type_size(LLVMTypeRef type)
209 {
210 LLVMTypeKind kind = LLVMGetTypeKind(type);
211
212 switch (kind) {
213 case LLVMIntegerTypeKind:
214 return LLVMGetIntTypeWidth(type) / 8;
215 case LLVMFloatTypeKind:
216 return 4;
217 case LLVMPointerTypeKind:
218 return 8;
219 case LLVMVectorTypeKind:
220 return LLVMGetVectorSize(type) *
221 llvm_get_type_size(LLVMGetElementType(type));
222 default:
223 assert(0);
224 return 0;
225 }
226 }
227
228 static void set_llvm_calling_convention(LLVMValueRef func,
229 gl_shader_stage stage)
230 {
231 enum radeon_llvm_calling_convention calling_conv;
232
233 switch (stage) {
234 case MESA_SHADER_VERTEX:
235 case MESA_SHADER_TESS_CTRL:
236 case MESA_SHADER_TESS_EVAL:
237 calling_conv = RADEON_LLVM_AMDGPU_VS;
238 break;
239 case MESA_SHADER_GEOMETRY:
240 calling_conv = RADEON_LLVM_AMDGPU_GS;
241 break;
242 case MESA_SHADER_FRAGMENT:
243 calling_conv = RADEON_LLVM_AMDGPU_PS;
244 break;
245 case MESA_SHADER_COMPUTE:
246 calling_conv = RADEON_LLVM_AMDGPU_CS;
247 break;
248 default:
249 unreachable("Unhandle shader type");
250 }
251
252 LLVMSetFunctionCallConv(func, calling_conv);
253 }
254
255 #define MAX_ARGS 23
256 struct arg_info {
257 LLVMTypeRef types[MAX_ARGS];
258 LLVMValueRef *assign[MAX_ARGS];
259 unsigned array_params_mask;
260 uint8_t count;
261 uint8_t user_sgpr_count;
262 uint8_t sgpr_count;
263 uint8_t num_user_sgprs_used;
264 uint8_t num_sgprs_used;
265 uint8_t num_vgprs_used;
266 };
267
268 static inline void
269 add_argument(struct arg_info *info,
270 LLVMTypeRef type, LLVMValueRef *param_ptr)
271 {
272 assert(info->count < MAX_ARGS);
273 info->assign[info->count] = param_ptr;
274 info->types[info->count] = type;
275 info->count++;
276 }
277
278 static inline void
279 add_sgpr_argument(struct arg_info *info,
280 LLVMTypeRef type, LLVMValueRef *param_ptr)
281 {
282 add_argument(info, type, param_ptr);
283 info->num_sgprs_used += llvm_get_type_size(type) / 4;
284 info->sgpr_count++;
285 }
286
287 static inline void
288 add_user_sgpr_argument(struct arg_info *info,
289 LLVMTypeRef type,
290 LLVMValueRef *param_ptr)
291 {
292 add_sgpr_argument(info, type, param_ptr);
293 info->num_user_sgprs_used += llvm_get_type_size(type) / 4;
294 info->user_sgpr_count++;
295 }
296
297 static inline void
298 add_vgpr_argument(struct arg_info *info,
299 LLVMTypeRef type,
300 LLVMValueRef *param_ptr)
301 {
302 add_argument(info, type, param_ptr);
303 info->num_vgprs_used += llvm_get_type_size(type) / 4;
304 }
305
306 static inline void
307 add_user_sgpr_array_argument(struct arg_info *info,
308 LLVMTypeRef type,
309 LLVMValueRef *param_ptr)
310 {
311 info->array_params_mask |= (1 << info->count);
312 add_user_sgpr_argument(info, type, param_ptr);
313 }
314
315 static void assign_arguments(LLVMValueRef main_function,
316 struct arg_info *info)
317 {
318 unsigned i;
319 for (i = 0; i < info->count; i++) {
320 if (info->assign[i])
321 *info->assign[i] = LLVMGetParam(main_function, i);
322 }
323 }
324
325 static LLVMValueRef
326 create_llvm_function(LLVMContextRef ctx, LLVMModuleRef module,
327 LLVMBuilderRef builder, LLVMTypeRef *return_types,
328 unsigned num_return_elems,
329 struct arg_info *args,
330 unsigned max_workgroup_size,
331 bool unsafe_math)
332 {
333 LLVMTypeRef main_function_type, ret_type;
334 LLVMBasicBlockRef main_function_body;
335
336 if (num_return_elems)
337 ret_type = LLVMStructTypeInContext(ctx, return_types,
338 num_return_elems, true);
339 else
340 ret_type = LLVMVoidTypeInContext(ctx);
341
342 /* Setup the function */
343 main_function_type =
344 LLVMFunctionType(ret_type, args->types, args->count, 0);
345 LLVMValueRef main_function =
346 LLVMAddFunction(module, "main", main_function_type);
347 main_function_body =
348 LLVMAppendBasicBlockInContext(ctx, main_function, "main_body");
349 LLVMPositionBuilderAtEnd(builder, main_function_body);
350
351 LLVMSetFunctionCallConv(main_function, RADEON_LLVM_AMDGPU_CS);
352 for (unsigned i = 0; i < args->sgpr_count; ++i) {
353 if (args->array_params_mask & (1 << i)) {
354 LLVMValueRef P = LLVMGetParam(main_function, i);
355 ac_add_function_attr(ctx, main_function, i + 1, AC_FUNC_ATTR_BYVAL);
356 ac_add_attr_dereferenceable(P, UINT64_MAX);
357 }
358 else {
359 ac_add_function_attr(ctx, main_function, i + 1, AC_FUNC_ATTR_INREG);
360 }
361 }
362
363 if (max_workgroup_size) {
364 ac_llvm_add_target_dep_function_attr(main_function,
365 "amdgpu-max-work-group-size",
366 max_workgroup_size);
367 }
368 if (unsafe_math) {
369 /* These were copied from some LLVM test. */
370 LLVMAddTargetDependentFunctionAttr(main_function,
371 "less-precise-fpmad",
372 "true");
373 LLVMAddTargetDependentFunctionAttr(main_function,
374 "no-infs-fp-math",
375 "true");
376 LLVMAddTargetDependentFunctionAttr(main_function,
377 "no-nans-fp-math",
378 "true");
379 LLVMAddTargetDependentFunctionAttr(main_function,
380 "unsafe-fp-math",
381 "true");
382 }
383 return main_function;
384 }
385
386 static LLVMTypeRef const_array(LLVMTypeRef elem_type, int num_elements)
387 {
388 return LLVMPointerType(LLVMArrayType(elem_type, num_elements),
389 CONST_ADDR_SPACE);
390 }
391
392 static LLVMValueRef get_shared_memory_ptr(struct nir_to_llvm_context *ctx,
393 int idx,
394 LLVMTypeRef type)
395 {
396 LLVMValueRef offset;
397 LLVMValueRef ptr;
398 int addr_space;
399
400 offset = LLVMConstInt(ctx->i32, idx * 16, false);
401
402 ptr = ctx->shared_memory;
403 ptr = LLVMBuildGEP(ctx->builder, ptr, &offset, 1, "");
404 addr_space = LLVMGetPointerAddressSpace(LLVMTypeOf(ptr));
405 ptr = LLVMBuildBitCast(ctx->builder, ptr, LLVMPointerType(type, addr_space), "");
406 return ptr;
407 }
408
409 static LLVMTypeRef to_integer_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
410 {
411 if (t == ctx->f16 || t == ctx->i16)
412 return ctx->i16;
413 else if (t == ctx->f32 || t == ctx->i32)
414 return ctx->i32;
415 else if (t == ctx->f64 || t == ctx->i64)
416 return ctx->i64;
417 else
418 unreachable("Unhandled integer size");
419 }
420
421 static LLVMTypeRef to_integer_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
422 {
423 if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
424 LLVMTypeRef elem_type = LLVMGetElementType(t);
425 return LLVMVectorType(to_integer_type_scalar(ctx, elem_type),
426 LLVMGetVectorSize(t));
427 }
428 return to_integer_type_scalar(ctx, t);
429 }
430
431 static LLVMValueRef to_integer(struct ac_llvm_context *ctx, LLVMValueRef v)
432 {
433 LLVMTypeRef type = LLVMTypeOf(v);
434 return LLVMBuildBitCast(ctx->builder, v, to_integer_type(ctx, type), "");
435 }
436
437 static LLVMTypeRef to_float_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
438 {
439 if (t == ctx->i16 || t == ctx->f16)
440 return ctx->f16;
441 else if (t == ctx->i32 || t == ctx->f32)
442 return ctx->f32;
443 else if (t == ctx->i64 || t == ctx->f64)
444 return ctx->f64;
445 else
446 unreachable("Unhandled float size");
447 }
448
449 static LLVMTypeRef to_float_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
450 {
451 if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
452 LLVMTypeRef elem_type = LLVMGetElementType(t);
453 return LLVMVectorType(to_float_type_scalar(ctx, elem_type),
454 LLVMGetVectorSize(t));
455 }
456 return to_float_type_scalar(ctx, t);
457 }
458
459 static LLVMValueRef to_float(struct ac_llvm_context *ctx, LLVMValueRef v)
460 {
461 LLVMTypeRef type = LLVMTypeOf(v);
462 return LLVMBuildBitCast(ctx->builder, v, to_float_type(ctx, type), "");
463 }
464
465 static int get_elem_bits(struct ac_llvm_context *ctx, LLVMTypeRef type)
466 {
467 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind)
468 type = LLVMGetElementType(type);
469
470 if (LLVMGetTypeKind(type) == LLVMIntegerTypeKind)
471 return LLVMGetIntTypeWidth(type);
472
473 if (type == ctx->f16)
474 return 16;
475 if (type == ctx->f32)
476 return 32;
477 if (type == ctx->f64)
478 return 64;
479
480 unreachable("Unhandled type kind in get_elem_bits");
481 }
482
483 static LLVMValueRef unpack_param(struct nir_to_llvm_context *ctx,
484 LLVMValueRef param, unsigned rshift,
485 unsigned bitwidth)
486 {
487 LLVMValueRef value = param;
488 if (rshift)
489 value = LLVMBuildLShr(ctx->builder, value,
490 LLVMConstInt(ctx->i32, rshift, false), "");
491
492 if (rshift + bitwidth < 32) {
493 unsigned mask = (1 << bitwidth) - 1;
494 value = LLVMBuildAnd(ctx->builder, value,
495 LLVMConstInt(ctx->i32, mask, false), "");
496 }
497 return value;
498 }
499
500 static LLVMValueRef get_rel_patch_id(struct nir_to_llvm_context *ctx)
501 {
502 switch (ctx->stage) {
503 case MESA_SHADER_TESS_CTRL:
504 return unpack_param(ctx, ctx->tcs_rel_ids, 0, 8);
505 case MESA_SHADER_TESS_EVAL:
506 return ctx->tes_rel_patch_id;
507 break;
508 default:
509 unreachable("Illegal stage");
510 }
511 }
512
513 /* Tessellation shaders pass outputs to the next shader using LDS.
514 *
515 * LS outputs = TCS inputs
516 * TCS outputs = TES inputs
517 *
518 * The LDS layout is:
519 * - TCS inputs for patch 0
520 * - TCS inputs for patch 1
521 * - TCS inputs for patch 2 = get_tcs_in_current_patch_offset (if RelPatchID==2)
522 * - ...
523 * - TCS outputs for patch 0 = get_tcs_out_patch0_offset
524 * - Per-patch TCS outputs for patch 0 = get_tcs_out_patch0_patch_data_offset
525 * - TCS outputs for patch 1
526 * - Per-patch TCS outputs for patch 1
527 * - TCS outputs for patch 2 = get_tcs_out_current_patch_offset (if RelPatchID==2)
528 * - Per-patch TCS outputs for patch 2 = get_tcs_out_current_patch_data_offset (if RelPatchID==2)
529 * - ...
530 *
531 * All three shaders VS(LS), TCS, TES share the same LDS space.
532 */
533 static LLVMValueRef
534 get_tcs_in_patch_stride(struct nir_to_llvm_context *ctx)
535 {
536 if (ctx->stage == MESA_SHADER_VERTEX)
537 return unpack_param(ctx, ctx->ls_out_layout, 0, 13);
538 else if (ctx->stage == MESA_SHADER_TESS_CTRL)
539 return unpack_param(ctx, ctx->tcs_in_layout, 0, 13);
540 else {
541 assert(0);
542 return NULL;
543 }
544 }
545
546 static LLVMValueRef
547 get_tcs_out_patch_stride(struct nir_to_llvm_context *ctx)
548 {
549 return unpack_param(ctx, ctx->tcs_out_layout, 0, 13);
550 }
551
552 static LLVMValueRef
553 get_tcs_out_patch0_offset(struct nir_to_llvm_context *ctx)
554 {
555 return LLVMBuildMul(ctx->builder,
556 unpack_param(ctx, ctx->tcs_out_offsets, 0, 16),
557 LLVMConstInt(ctx->i32, 4, false), "");
558 }
559
560 static LLVMValueRef
561 get_tcs_out_patch0_patch_data_offset(struct nir_to_llvm_context *ctx)
562 {
563 return LLVMBuildMul(ctx->builder,
564 unpack_param(ctx, ctx->tcs_out_offsets, 16, 16),
565 LLVMConstInt(ctx->i32, 4, false), "");
566 }
567
568 static LLVMValueRef
569 get_tcs_in_current_patch_offset(struct nir_to_llvm_context *ctx)
570 {
571 LLVMValueRef patch_stride = get_tcs_in_patch_stride(ctx);
572 LLVMValueRef rel_patch_id = get_rel_patch_id(ctx);
573
574 return LLVMBuildMul(ctx->builder, patch_stride, rel_patch_id, "");
575 }
576
577 static LLVMValueRef
578 get_tcs_out_current_patch_offset(struct nir_to_llvm_context *ctx)
579 {
580 LLVMValueRef patch0_offset = get_tcs_out_patch0_offset(ctx);
581 LLVMValueRef patch_stride = get_tcs_out_patch_stride(ctx);
582 LLVMValueRef rel_patch_id = get_rel_patch_id(ctx);
583
584 return LLVMBuildAdd(ctx->builder, patch0_offset,
585 LLVMBuildMul(ctx->builder, patch_stride,
586 rel_patch_id, ""),
587 "");
588 }
589
590 static LLVMValueRef
591 get_tcs_out_current_patch_data_offset(struct nir_to_llvm_context *ctx)
592 {
593 LLVMValueRef patch0_patch_data_offset =
594 get_tcs_out_patch0_patch_data_offset(ctx);
595 LLVMValueRef patch_stride = get_tcs_out_patch_stride(ctx);
596 LLVMValueRef rel_patch_id = get_rel_patch_id(ctx);
597
598 return LLVMBuildAdd(ctx->builder, patch0_patch_data_offset,
599 LLVMBuildMul(ctx->builder, patch_stride,
600 rel_patch_id, ""),
601 "");
602 }
603
604 static void set_userdata_location(struct ac_userdata_info *ud_info, uint8_t *sgpr_idx, uint8_t num_sgprs)
605 {
606 ud_info->sgpr_idx = *sgpr_idx;
607 ud_info->num_sgprs = num_sgprs;
608 ud_info->indirect = false;
609 ud_info->indirect_offset = 0;
610 *sgpr_idx += num_sgprs;
611 }
612
613 static void set_userdata_location_shader(struct nir_to_llvm_context *ctx,
614 int idx, uint8_t *sgpr_idx, uint8_t num_sgprs)
615 {
616 set_userdata_location(&ctx->shader_info->user_sgprs_locs.shader_data[idx], sgpr_idx, num_sgprs);
617 }
618
619
620 static void set_userdata_location_indirect(struct ac_userdata_info *ud_info, uint8_t sgpr_idx, uint8_t num_sgprs,
621 uint32_t indirect_offset)
622 {
623 ud_info->sgpr_idx = sgpr_idx;
624 ud_info->num_sgprs = num_sgprs;
625 ud_info->indirect = true;
626 ud_info->indirect_offset = indirect_offset;
627 }
628
629 static void declare_tess_lds(struct nir_to_llvm_context *ctx)
630 {
631 unsigned lds_size = ctx->options->chip_class >= CIK ? 65536 : 32768;
632 ctx->lds = LLVMBuildIntToPtr(ctx->builder, ctx->i32zero,
633 LLVMPointerType(LLVMArrayType(ctx->i32, lds_size / 4), LOCAL_ADDR_SPACE),
634 "tess_lds");
635 }
636
637 struct user_sgpr_info {
638 bool need_ring_offsets;
639 uint8_t sgpr_count;
640 bool indirect_all_descriptor_sets;
641 };
642
643 static void allocate_user_sgprs(struct nir_to_llvm_context *ctx,
644 struct user_sgpr_info *user_sgpr_info)
645 {
646 memset(user_sgpr_info, 0, sizeof(struct user_sgpr_info));
647
648 /* until we sort out scratch/global buffers always assign ring offsets for gs/vs/es */
649 if (ctx->stage == MESA_SHADER_GEOMETRY ||
650 ctx->stage == MESA_SHADER_VERTEX ||
651 ctx->stage == MESA_SHADER_TESS_CTRL ||
652 ctx->stage == MESA_SHADER_TESS_EVAL ||
653 ctx->is_gs_copy_shader)
654 user_sgpr_info->need_ring_offsets = true;
655
656 if (ctx->stage == MESA_SHADER_FRAGMENT &&
657 ctx->shader_info->info.ps.needs_sample_positions)
658 user_sgpr_info->need_ring_offsets = true;
659
660 /* 2 user sgprs will nearly always be allocated for scratch/rings */
661 if (ctx->options->supports_spill || user_sgpr_info->need_ring_offsets) {
662 user_sgpr_info->sgpr_count += 2;
663 }
664
665 switch (ctx->stage) {
666 case MESA_SHADER_COMPUTE:
667 user_sgpr_info->sgpr_count += ctx->shader_info->info.cs.grid_components_used;
668 break;
669 case MESA_SHADER_FRAGMENT:
670 user_sgpr_info->sgpr_count += ctx->shader_info->info.ps.needs_sample_positions;
671 break;
672 case MESA_SHADER_VERTEX:
673 if (!ctx->is_gs_copy_shader) {
674 user_sgpr_info->sgpr_count += ctx->shader_info->info.vs.has_vertex_buffers ? 2 : 0;
675 if (ctx->shader_info->info.vs.needs_draw_id) {
676 user_sgpr_info->sgpr_count += 3;
677 } else {
678 user_sgpr_info->sgpr_count += 2;
679 }
680 }
681 if (ctx->options->key.vs.as_ls)
682 user_sgpr_info->sgpr_count++;
683 break;
684 case MESA_SHADER_TESS_CTRL:
685 user_sgpr_info->sgpr_count += 4;
686 break;
687 case MESA_SHADER_TESS_EVAL:
688 user_sgpr_info->sgpr_count += 1;
689 break;
690 case MESA_SHADER_GEOMETRY:
691 user_sgpr_info->sgpr_count += 2;
692 break;
693 default:
694 break;
695 }
696
697 if (ctx->shader_info->info.needs_push_constants)
698 user_sgpr_info->sgpr_count += 2;
699
700 uint32_t remaining_sgprs = 16 - user_sgpr_info->sgpr_count;
701 if (remaining_sgprs / 2 < util_bitcount(ctx->shader_info->info.desc_set_used_mask)) {
702 user_sgpr_info->sgpr_count += 2;
703 user_sgpr_info->indirect_all_descriptor_sets = true;
704 } else {
705 user_sgpr_info->sgpr_count += util_bitcount(ctx->shader_info->info.desc_set_used_mask) * 2;
706 }
707 }
708
709 static void create_function(struct nir_to_llvm_context *ctx)
710 {
711 unsigned num_sets = ctx->options->layout ? ctx->options->layout->num_sets : 0;
712 uint8_t user_sgpr_idx;
713 struct user_sgpr_info user_sgpr_info;
714 struct arg_info args = {};
715 LLVMValueRef desc_sets;
716
717 allocate_user_sgprs(ctx, &user_sgpr_info);
718 if (user_sgpr_info.need_ring_offsets && !ctx->options->supports_spill) {
719 add_user_sgpr_argument(&args, const_array(ctx->v16i8, 16), &ctx->ring_offsets); /* address of rings */
720 }
721
722 /* 1 for each descriptor set */
723 if (!user_sgpr_info.indirect_all_descriptor_sets) {
724 for (unsigned i = 0; i < num_sets; ++i) {
725 if (ctx->options->layout->set[i].layout->shader_stages & (1 << ctx->stage)) {
726 add_user_sgpr_array_argument(&args, const_array(ctx->i8, 1024 * 1024), &ctx->descriptor_sets[i]);
727 }
728 }
729 } else
730 add_user_sgpr_array_argument(&args, const_array(const_array(ctx->i8, 1024 * 1024), 32), &desc_sets);
731
732 if (ctx->shader_info->info.needs_push_constants) {
733 /* 1 for push constants and dynamic descriptors */
734 add_user_sgpr_array_argument(&args, const_array(ctx->i8, 1024 * 1024), &ctx->push_constants);
735 }
736
737 switch (ctx->stage) {
738 case MESA_SHADER_COMPUTE:
739 if (ctx->shader_info->info.cs.grid_components_used)
740 add_user_sgpr_argument(&args, LLVMVectorType(ctx->i32, ctx->shader_info->info.cs.grid_components_used), &ctx->num_work_groups); /* grid size */
741 add_sgpr_argument(&args, LLVMVectorType(ctx->i32, 3), &ctx->workgroup_ids);
742 add_sgpr_argument(&args, ctx->i32, &ctx->tg_size);
743 add_vgpr_argument(&args, LLVMVectorType(ctx->i32, 3), &ctx->local_invocation_ids);
744 break;
745 case MESA_SHADER_VERTEX:
746 if (!ctx->is_gs_copy_shader) {
747 if (ctx->shader_info->info.vs.has_vertex_buffers)
748 add_user_sgpr_argument(&args, const_array(ctx->v16i8, 16), &ctx->vertex_buffers); /* vertex buffers */
749 add_user_sgpr_argument(&args, ctx->i32, &ctx->base_vertex); // base vertex
750 add_user_sgpr_argument(&args, ctx->i32, &ctx->start_instance);// start instance
751 if (ctx->shader_info->info.vs.needs_draw_id)
752 add_user_sgpr_argument(&args, ctx->i32, &ctx->draw_index); // draw id
753 }
754 if (ctx->options->key.vs.as_es)
755 add_sgpr_argument(&args, ctx->i32, &ctx->es2gs_offset); // es2gs offset
756 else if (ctx->options->key.vs.as_ls)
757 add_user_sgpr_argument(&args, ctx->i32, &ctx->ls_out_layout); // ls out layout
758 add_vgpr_argument(&args, ctx->i32, &ctx->vertex_id); // vertex id
759 if (!ctx->is_gs_copy_shader) {
760 add_vgpr_argument(&args, ctx->i32, &ctx->rel_auto_id); // rel auto id
761 add_vgpr_argument(&args, ctx->i32, &ctx->vs_prim_id); // vs prim id
762 add_vgpr_argument(&args, ctx->i32, &ctx->instance_id); // instance id
763 }
764 break;
765 case MESA_SHADER_TESS_CTRL:
766 add_user_sgpr_argument(&args, ctx->i32, &ctx->tcs_offchip_layout); // tcs offchip layout
767 add_user_sgpr_argument(&args, ctx->i32, &ctx->tcs_out_offsets); // tcs out offsets
768 add_user_sgpr_argument(&args, ctx->i32, &ctx->tcs_out_layout); // tcs out layout
769 add_user_sgpr_argument(&args, ctx->i32, &ctx->tcs_in_layout); // tcs in layout
770 add_sgpr_argument(&args, ctx->i32, &ctx->oc_lds); // param oc lds
771 add_sgpr_argument(&args, ctx->i32, &ctx->tess_factor_offset); // tess factor offset
772 add_vgpr_argument(&args, ctx->i32, &ctx->tcs_patch_id); // patch id
773 add_vgpr_argument(&args, ctx->i32, &ctx->tcs_rel_ids); // rel ids;
774 break;
775 case MESA_SHADER_TESS_EVAL:
776 add_user_sgpr_argument(&args, ctx->i32, &ctx->tcs_offchip_layout); // tcs offchip layout
777 if (ctx->options->key.tes.as_es) {
778 add_sgpr_argument(&args, ctx->i32, &ctx->oc_lds); // OC LDS
779 add_sgpr_argument(&args, ctx->i32, NULL); //
780 add_sgpr_argument(&args, ctx->i32, &ctx->es2gs_offset); // es2gs offset
781 } else {
782 add_sgpr_argument(&args, ctx->i32, NULL); //
783 add_sgpr_argument(&args, ctx->i32, &ctx->oc_lds); // OC LDS
784 }
785 add_vgpr_argument(&args, ctx->f32, &ctx->tes_u); // tes_u
786 add_vgpr_argument(&args, ctx->f32, &ctx->tes_v); // tes_v
787 add_vgpr_argument(&args, ctx->i32, &ctx->tes_rel_patch_id); // tes rel patch id
788 add_vgpr_argument(&args, ctx->i32, &ctx->tes_patch_id); // tes patch id
789 break;
790 case MESA_SHADER_GEOMETRY:
791 add_user_sgpr_argument(&args, ctx->i32, &ctx->gsvs_ring_stride); // gsvs stride
792 add_user_sgpr_argument(&args, ctx->i32, &ctx->gsvs_num_entries); // gsvs num entires
793 add_sgpr_argument(&args, ctx->i32, &ctx->gs2vs_offset); // gs2vs offset
794 add_sgpr_argument(&args, ctx->i32, &ctx->gs_wave_id); // wave id
795 add_vgpr_argument(&args, ctx->i32, &ctx->gs_vtx_offset[0]); // vtx0
796 add_vgpr_argument(&args, ctx->i32, &ctx->gs_vtx_offset[1]); // vtx1
797 add_vgpr_argument(&args, ctx->i32, &ctx->gs_prim_id); // prim id
798 add_vgpr_argument(&args, ctx->i32, &ctx->gs_vtx_offset[2]);
799 add_vgpr_argument(&args, ctx->i32, &ctx->gs_vtx_offset[3]);
800 add_vgpr_argument(&args, ctx->i32, &ctx->gs_vtx_offset[4]);
801 add_vgpr_argument(&args, ctx->i32, &ctx->gs_vtx_offset[5]);
802 add_vgpr_argument(&args, ctx->i32, &ctx->gs_invocation_id);
803 break;
804 case MESA_SHADER_FRAGMENT:
805 if (ctx->shader_info->info.ps.needs_sample_positions)
806 add_user_sgpr_argument(&args, ctx->i32, &ctx->sample_pos_offset); /* sample position offset */
807 add_sgpr_argument(&args, ctx->i32, &ctx->prim_mask); /* prim mask */
808 add_vgpr_argument(&args, ctx->v2i32, &ctx->persp_sample); /* persp sample */
809 add_vgpr_argument(&args, ctx->v2i32, &ctx->persp_center); /* persp center */
810 add_vgpr_argument(&args, ctx->v2i32, &ctx->persp_centroid); /* persp centroid */
811 add_vgpr_argument(&args, ctx->v3i32, NULL); /* persp pull model */
812 add_vgpr_argument(&args, ctx->v2i32, &ctx->linear_sample); /* linear sample */
813 add_vgpr_argument(&args, ctx->v2i32, &ctx->linear_center); /* linear center */
814 add_vgpr_argument(&args, ctx->v2i32, &ctx->linear_centroid); /* linear centroid */
815 add_vgpr_argument(&args, ctx->f32, NULL); /* line stipple tex */
816 add_vgpr_argument(&args, ctx->f32, &ctx->frag_pos[0]); /* pos x float */
817 add_vgpr_argument(&args, ctx->f32, &ctx->frag_pos[1]); /* pos y float */
818 add_vgpr_argument(&args, ctx->f32, &ctx->frag_pos[2]); /* pos z float */
819 add_vgpr_argument(&args, ctx->f32, &ctx->frag_pos[3]); /* pos w float */
820 add_vgpr_argument(&args, ctx->i32, &ctx->front_face); /* front face */
821 add_vgpr_argument(&args, ctx->i32, &ctx->ancillary); /* ancillary */
822 add_vgpr_argument(&args, ctx->i32, &ctx->sample_coverage); /* sample coverage */
823 add_vgpr_argument(&args, ctx->i32, NULL); /* fixed pt */
824 break;
825 default:
826 unreachable("Shader stage not implemented");
827 }
828
829 ctx->main_function = create_llvm_function(
830 ctx->context, ctx->module, ctx->builder, NULL, 0, &args,
831 ctx->max_workgroup_size,
832 ctx->options->unsafe_math);
833 set_llvm_calling_convention(ctx->main_function, ctx->stage);
834
835
836 ctx->shader_info->num_input_vgprs = 0;
837 ctx->shader_info->num_input_sgprs = ctx->shader_info->num_user_sgprs =
838 ctx->options->supports_spill ? 2 : 0;
839
840 ctx->shader_info->num_user_sgprs += args.num_user_sgprs_used;
841 ctx->shader_info->num_input_sgprs += args.num_sgprs_used;
842
843 if (ctx->stage != MESA_SHADER_FRAGMENT)
844 ctx->shader_info->num_input_vgprs = args.num_vgprs_used;
845
846 assign_arguments(ctx->main_function, &args);
847
848 user_sgpr_idx = 0;
849
850 if (ctx->options->supports_spill || user_sgpr_info.need_ring_offsets) {
851 set_userdata_location_shader(ctx, AC_UD_SCRATCH_RING_OFFSETS, &user_sgpr_idx, 2);
852 if (ctx->options->supports_spill) {
853 ctx->ring_offsets = ac_build_intrinsic(&ctx->ac, "llvm.amdgcn.implicit.buffer.ptr",
854 LLVMPointerType(ctx->i8, CONST_ADDR_SPACE),
855 NULL, 0, AC_FUNC_ATTR_READNONE);
856 ctx->ring_offsets = LLVMBuildBitCast(ctx->builder, ctx->ring_offsets,
857 const_array(ctx->v16i8, 16), "");
858 }
859 }
860
861 if (!user_sgpr_info.indirect_all_descriptor_sets) {
862 for (unsigned i = 0; i < num_sets; ++i) {
863 if (ctx->options->layout->set[i].layout->shader_stages & (1 << ctx->stage)) {
864 set_userdata_location(&ctx->shader_info->user_sgprs_locs.descriptor_sets[i], &user_sgpr_idx, 2);
865 } else
866 ctx->descriptor_sets[i] = NULL;
867 }
868 } else {
869 uint32_t desc_sgpr_idx = user_sgpr_idx;
870 set_userdata_location_shader(ctx, AC_UD_INDIRECT_DESCRIPTOR_SETS, &user_sgpr_idx, 2);
871
872 for (unsigned i = 0; i < num_sets; ++i) {
873 if (ctx->options->layout->set[i].layout->shader_stages & (1 << ctx->stage)) {
874 set_userdata_location_indirect(&ctx->shader_info->user_sgprs_locs.descriptor_sets[i], desc_sgpr_idx, 2, i * 8);
875 ctx->descriptor_sets[i] = ac_build_indexed_load_const(&ctx->ac, desc_sets, LLVMConstInt(ctx->i32, i, false));
876
877 } else
878 ctx->descriptor_sets[i] = NULL;
879 }
880 ctx->shader_info->need_indirect_descriptor_sets = true;
881 }
882
883 if (ctx->shader_info->info.needs_push_constants) {
884 set_userdata_location_shader(ctx, AC_UD_PUSH_CONSTANTS, &user_sgpr_idx, 2);
885 }
886
887 switch (ctx->stage) {
888 case MESA_SHADER_COMPUTE:
889 if (ctx->shader_info->info.cs.grid_components_used) {
890 set_userdata_location_shader(ctx, AC_UD_CS_GRID_SIZE, &user_sgpr_idx, ctx->shader_info->info.cs.grid_components_used);
891 }
892 break;
893 case MESA_SHADER_VERTEX:
894 if (!ctx->is_gs_copy_shader) {
895 if (ctx->shader_info->info.vs.has_vertex_buffers) {
896 set_userdata_location_shader(ctx, AC_UD_VS_VERTEX_BUFFERS, &user_sgpr_idx, 2);
897 }
898 unsigned vs_num = 2;
899 if (ctx->shader_info->info.vs.needs_draw_id)
900 vs_num++;
901
902 set_userdata_location_shader(ctx, AC_UD_VS_BASE_VERTEX_START_INSTANCE, &user_sgpr_idx, vs_num);
903 }
904 if (ctx->options->key.vs.as_ls) {
905 set_userdata_location_shader(ctx, AC_UD_VS_LS_TCS_IN_LAYOUT, &user_sgpr_idx, 1);
906 }
907 if (ctx->options->key.vs.as_ls)
908 declare_tess_lds(ctx);
909 break;
910 case MESA_SHADER_TESS_CTRL:
911 set_userdata_location_shader(ctx, AC_UD_TCS_OFFCHIP_LAYOUT, &user_sgpr_idx, 4);
912 declare_tess_lds(ctx);
913 break;
914 case MESA_SHADER_TESS_EVAL:
915 set_userdata_location_shader(ctx, AC_UD_TES_OFFCHIP_LAYOUT, &user_sgpr_idx, 1);
916 break;
917 case MESA_SHADER_GEOMETRY:
918 set_userdata_location_shader(ctx, AC_UD_GS_VS_RING_STRIDE_ENTRIES, &user_sgpr_idx, 2);
919 break;
920 case MESA_SHADER_FRAGMENT:
921 if (ctx->shader_info->info.ps.needs_sample_positions) {
922 set_userdata_location_shader(ctx, AC_UD_PS_SAMPLE_POS_OFFSET, &user_sgpr_idx, 1);
923 }
924 break;
925 default:
926 unreachable("Shader stage not implemented");
927 }
928 }
929
930 static void setup_types(struct nir_to_llvm_context *ctx)
931 {
932 LLVMValueRef args[4];
933
934 ctx->voidt = LLVMVoidTypeInContext(ctx->context);
935 ctx->i1 = LLVMIntTypeInContext(ctx->context, 1);
936 ctx->i8 = LLVMIntTypeInContext(ctx->context, 8);
937 ctx->i16 = LLVMIntTypeInContext(ctx->context, 16);
938 ctx->i32 = LLVMIntTypeInContext(ctx->context, 32);
939 ctx->i64 = LLVMIntTypeInContext(ctx->context, 64);
940 ctx->v2i32 = LLVMVectorType(ctx->i32, 2);
941 ctx->v3i32 = LLVMVectorType(ctx->i32, 3);
942 ctx->v4i32 = LLVMVectorType(ctx->i32, 4);
943 ctx->v8i32 = LLVMVectorType(ctx->i32, 8);
944 ctx->f32 = LLVMFloatTypeInContext(ctx->context);
945 ctx->f16 = LLVMHalfTypeInContext(ctx->context);
946 ctx->f64 = LLVMDoubleTypeInContext(ctx->context);
947 ctx->v2f32 = LLVMVectorType(ctx->f32, 2);
948 ctx->v4f32 = LLVMVectorType(ctx->f32, 4);
949 ctx->v16i8 = LLVMVectorType(ctx->i8, 16);
950
951 ctx->i1false = LLVMConstInt(ctx->i1, 0, false);
952 ctx->i1true = LLVMConstInt(ctx->i1, 1, false);
953 ctx->i32zero = LLVMConstInt(ctx->i32, 0, false);
954 ctx->i32one = LLVMConstInt(ctx->i32, 1, false);
955 ctx->f32zero = LLVMConstReal(ctx->f32, 0.0);
956 ctx->f32one = LLVMConstReal(ctx->f32, 1.0);
957
958 args[0] = ctx->f32zero;
959 args[1] = ctx->f32zero;
960 args[2] = ctx->f32zero;
961 args[3] = ctx->f32one;
962 ctx->v4f32empty = LLVMConstVector(args, 4);
963
964 ctx->uniform_md_kind =
965 LLVMGetMDKindIDInContext(ctx->context, "amdgpu.uniform", 14);
966 ctx->empty_md = LLVMMDNodeInContext(ctx->context, NULL, 0);
967
968 args[0] = LLVMConstReal(ctx->f32, 2.5);
969 }
970
971 static int get_llvm_num_components(LLVMValueRef value)
972 {
973 LLVMTypeRef type = LLVMTypeOf(value);
974 unsigned num_components = LLVMGetTypeKind(type) == LLVMVectorTypeKind
975 ? LLVMGetVectorSize(type)
976 : 1;
977 return num_components;
978 }
979
980 static LLVMValueRef llvm_extract_elem(struct nir_to_llvm_context *ctx,
981 LLVMValueRef value,
982 int index)
983 {
984 int count = get_llvm_num_components(value);
985
986 assert(index < count);
987 if (count == 1)
988 return value;
989
990 return LLVMBuildExtractElement(ctx->builder, value,
991 LLVMConstInt(ctx->i32, index, false), "");
992 }
993
994 static LLVMValueRef trim_vector(struct nir_to_llvm_context *ctx,
995 LLVMValueRef value, unsigned count)
996 {
997 unsigned num_components = get_llvm_num_components(value);
998 if (count == num_components)
999 return value;
1000
1001 LLVMValueRef masks[] = {
1002 LLVMConstInt(ctx->i32, 0, false), LLVMConstInt(ctx->i32, 1, false),
1003 LLVMConstInt(ctx->i32, 2, false), LLVMConstInt(ctx->i32, 3, false)};
1004
1005 if (count == 1)
1006 return LLVMBuildExtractElement(ctx->builder, value, masks[0],
1007 "");
1008
1009 LLVMValueRef swizzle = LLVMConstVector(masks, count);
1010 return LLVMBuildShuffleVector(ctx->builder, value, value, swizzle, "");
1011 }
1012
1013 static void
1014 build_store_values_extended(struct nir_to_llvm_context *ctx,
1015 LLVMValueRef *values,
1016 unsigned value_count,
1017 unsigned value_stride,
1018 LLVMValueRef vec)
1019 {
1020 LLVMBuilderRef builder = ctx->builder;
1021 unsigned i;
1022
1023 if (value_count == 1) {
1024 LLVMBuildStore(builder, vec, values[0]);
1025 return;
1026 }
1027
1028 for (i = 0; i < value_count; i++) {
1029 LLVMValueRef ptr = values[i * value_stride];
1030 LLVMValueRef index = LLVMConstInt(ctx->i32, i, false);
1031 LLVMValueRef value = LLVMBuildExtractElement(builder, vec, index, "");
1032 LLVMBuildStore(builder, value, ptr);
1033 }
1034 }
1035
1036 static LLVMTypeRef get_def_type(struct nir_to_llvm_context *ctx,
1037 const nir_ssa_def *def)
1038 {
1039 LLVMTypeRef type = LLVMIntTypeInContext(ctx->context, def->bit_size);
1040 if (def->num_components > 1) {
1041 type = LLVMVectorType(type, def->num_components);
1042 }
1043 return type;
1044 }
1045
1046 static LLVMValueRef get_src(struct nir_to_llvm_context *ctx, nir_src src)
1047 {
1048 assert(src.is_ssa);
1049 struct hash_entry *entry = _mesa_hash_table_search(ctx->defs, src.ssa);
1050 return (LLVMValueRef)entry->data;
1051 }
1052
1053
1054 static LLVMBasicBlockRef get_block(struct nir_to_llvm_context *ctx,
1055 const struct nir_block *b)
1056 {
1057 struct hash_entry *entry = _mesa_hash_table_search(ctx->defs, b);
1058 return (LLVMBasicBlockRef)entry->data;
1059 }
1060
1061 static LLVMValueRef get_alu_src(struct nir_to_llvm_context *ctx,
1062 nir_alu_src src,
1063 unsigned num_components)
1064 {
1065 LLVMValueRef value = get_src(ctx, src.src);
1066 bool need_swizzle = false;
1067
1068 assert(value);
1069 LLVMTypeRef type = LLVMTypeOf(value);
1070 unsigned src_components = LLVMGetTypeKind(type) == LLVMVectorTypeKind
1071 ? LLVMGetVectorSize(type)
1072 : 1;
1073
1074 for (unsigned i = 0; i < num_components; ++i) {
1075 assert(src.swizzle[i] < src_components);
1076 if (src.swizzle[i] != i)
1077 need_swizzle = true;
1078 }
1079
1080 if (need_swizzle || num_components != src_components) {
1081 LLVMValueRef masks[] = {
1082 LLVMConstInt(ctx->i32, src.swizzle[0], false),
1083 LLVMConstInt(ctx->i32, src.swizzle[1], false),
1084 LLVMConstInt(ctx->i32, src.swizzle[2], false),
1085 LLVMConstInt(ctx->i32, src.swizzle[3], false)};
1086
1087 if (src_components > 1 && num_components == 1) {
1088 value = LLVMBuildExtractElement(ctx->builder, value,
1089 masks[0], "");
1090 } else if (src_components == 1 && num_components > 1) {
1091 LLVMValueRef values[] = {value, value, value, value};
1092 value = ac_build_gather_values(&ctx->ac, values, num_components);
1093 } else {
1094 LLVMValueRef swizzle = LLVMConstVector(masks, num_components);
1095 value = LLVMBuildShuffleVector(ctx->builder, value, value,
1096 swizzle, "");
1097 }
1098 }
1099 assert(!src.negate);
1100 assert(!src.abs);
1101 return value;
1102 }
1103
1104 static LLVMValueRef emit_int_cmp(struct nir_to_llvm_context *ctx,
1105 LLVMIntPredicate pred, LLVMValueRef src0,
1106 LLVMValueRef src1)
1107 {
1108 LLVMValueRef result = LLVMBuildICmp(ctx->builder, pred, src0, src1, "");
1109 return LLVMBuildSelect(ctx->builder, result,
1110 LLVMConstInt(ctx->i32, 0xFFFFFFFF, false),
1111 LLVMConstInt(ctx->i32, 0, false), "");
1112 }
1113
1114 static LLVMValueRef emit_float_cmp(struct nir_to_llvm_context *ctx,
1115 LLVMRealPredicate pred, LLVMValueRef src0,
1116 LLVMValueRef src1)
1117 {
1118 LLVMValueRef result;
1119 src0 = to_float(&ctx->ac, src0);
1120 src1 = to_float(&ctx->ac, src1);
1121 result = LLVMBuildFCmp(ctx->builder, pred, src0, src1, "");
1122 return LLVMBuildSelect(ctx->builder, result,
1123 LLVMConstInt(ctx->i32, 0xFFFFFFFF, false),
1124 LLVMConstInt(ctx->i32, 0, false), "");
1125 }
1126
1127 static LLVMValueRef emit_intrin_1f_param(struct nir_to_llvm_context *ctx,
1128 const char *intrin,
1129 LLVMTypeRef result_type,
1130 LLVMValueRef src0)
1131 {
1132 char name[64];
1133 LLVMValueRef params[] = {
1134 to_float(&ctx->ac, src0),
1135 };
1136
1137 sprintf(name, "%s.f%d", intrin, get_elem_bits(&ctx->ac, result_type));
1138 return ac_build_intrinsic(&ctx->ac, name, result_type, params, 1, AC_FUNC_ATTR_READNONE);
1139 }
1140
1141 static LLVMValueRef emit_intrin_2f_param(struct nir_to_llvm_context *ctx,
1142 const char *intrin,
1143 LLVMTypeRef result_type,
1144 LLVMValueRef src0, LLVMValueRef src1)
1145 {
1146 char name[64];
1147 LLVMValueRef params[] = {
1148 to_float(&ctx->ac, src0),
1149 to_float(&ctx->ac, src1),
1150 };
1151
1152 sprintf(name, "%s.f%d", intrin, get_elem_bits(&ctx->ac, result_type));
1153 return ac_build_intrinsic(&ctx->ac, name, result_type, params, 2, AC_FUNC_ATTR_READNONE);
1154 }
1155
1156 static LLVMValueRef emit_intrin_3f_param(struct nir_to_llvm_context *ctx,
1157 const char *intrin,
1158 LLVMTypeRef result_type,
1159 LLVMValueRef src0, LLVMValueRef src1, LLVMValueRef src2)
1160 {
1161 char name[64];
1162 LLVMValueRef params[] = {
1163 to_float(&ctx->ac, src0),
1164 to_float(&ctx->ac, src1),
1165 to_float(&ctx->ac, src2),
1166 };
1167
1168 sprintf(name, "%s.f%d", intrin, get_elem_bits(&ctx->ac, result_type));
1169 return ac_build_intrinsic(&ctx->ac, name, result_type, params, 3, AC_FUNC_ATTR_READNONE);
1170 }
1171
1172 static LLVMValueRef emit_bcsel(struct nir_to_llvm_context *ctx,
1173 LLVMValueRef src0, LLVMValueRef src1, LLVMValueRef src2)
1174 {
1175 LLVMValueRef v = LLVMBuildICmp(ctx->builder, LLVMIntNE, src0,
1176 ctx->i32zero, "");
1177 return LLVMBuildSelect(ctx->builder, v, src1, src2, "");
1178 }
1179
1180 static LLVMValueRef emit_find_lsb(struct nir_to_llvm_context *ctx,
1181 LLVMValueRef src0)
1182 {
1183 LLVMValueRef params[2] = {
1184 src0,
1185
1186 /* The value of 1 means that ffs(x=0) = undef, so LLVM won't
1187 * add special code to check for x=0. The reason is that
1188 * the LLVM behavior for x=0 is different from what we
1189 * need here.
1190 *
1191 * The hardware already implements the correct behavior.
1192 */
1193 LLVMConstInt(ctx->i1, 1, false),
1194 };
1195 return ac_build_intrinsic(&ctx->ac, "llvm.cttz.i32", ctx->i32, params, 2, AC_FUNC_ATTR_READNONE);
1196 }
1197
1198 static LLVMValueRef emit_ifind_msb(struct nir_to_llvm_context *ctx,
1199 LLVMValueRef src0)
1200 {
1201 return ac_build_imsb(&ctx->ac, src0, ctx->i32);
1202 }
1203
1204 static LLVMValueRef emit_ufind_msb(struct nir_to_llvm_context *ctx,
1205 LLVMValueRef src0)
1206 {
1207 return ac_build_umsb(&ctx->ac, src0, ctx->i32);
1208 }
1209
1210 static LLVMValueRef emit_minmax_int(struct nir_to_llvm_context *ctx,
1211 LLVMIntPredicate pred,
1212 LLVMValueRef src0, LLVMValueRef src1)
1213 {
1214 return LLVMBuildSelect(ctx->builder,
1215 LLVMBuildICmp(ctx->builder, pred, src0, src1, ""),
1216 src0,
1217 src1, "");
1218
1219 }
1220 static LLVMValueRef emit_iabs(struct nir_to_llvm_context *ctx,
1221 LLVMValueRef src0)
1222 {
1223 return emit_minmax_int(ctx, LLVMIntSGT, src0,
1224 LLVMBuildNeg(ctx->builder, src0, ""));
1225 }
1226
1227 static LLVMValueRef emit_fsign(struct nir_to_llvm_context *ctx,
1228 LLVMValueRef src0)
1229 {
1230 LLVMValueRef cmp, val;
1231
1232 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGT, src0, ctx->f32zero, "");
1233 val = LLVMBuildSelect(ctx->builder, cmp, ctx->f32one, src0, "");
1234 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGE, val, ctx->f32zero, "");
1235 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstReal(ctx->f32, -1.0), "");
1236 return val;
1237 }
1238
1239 static LLVMValueRef emit_isign(struct nir_to_llvm_context *ctx,
1240 LLVMValueRef src0)
1241 {
1242 LLVMValueRef cmp, val;
1243
1244 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, src0, ctx->i32zero, "");
1245 val = LLVMBuildSelect(ctx->builder, cmp, ctx->i32one, src0, "");
1246 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGE, val, ctx->i32zero, "");
1247 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstInt(ctx->i32, -1, true), "");
1248 return val;
1249 }
1250
1251 static LLVMValueRef emit_ffract(struct nir_to_llvm_context *ctx,
1252 LLVMValueRef src0)
1253 {
1254 const char *intr = "llvm.floor.f32";
1255 LLVMValueRef fsrc0 = to_float(&ctx->ac, src0);
1256 LLVMValueRef params[] = {
1257 fsrc0,
1258 };
1259 LLVMValueRef floor = ac_build_intrinsic(&ctx->ac, intr,
1260 ctx->f32, params, 1,
1261 AC_FUNC_ATTR_READNONE);
1262 return LLVMBuildFSub(ctx->builder, fsrc0, floor, "");
1263 }
1264
1265 static LLVMValueRef emit_uint_carry(struct nir_to_llvm_context *ctx,
1266 const char *intrin,
1267 LLVMValueRef src0, LLVMValueRef src1)
1268 {
1269 LLVMTypeRef ret_type;
1270 LLVMTypeRef types[] = { ctx->i32, ctx->i1 };
1271 LLVMValueRef res;
1272 LLVMValueRef params[] = { src0, src1 };
1273 ret_type = LLVMStructTypeInContext(ctx->context, types,
1274 2, true);
1275
1276 res = ac_build_intrinsic(&ctx->ac, intrin, ret_type,
1277 params, 2, AC_FUNC_ATTR_READNONE);
1278
1279 res = LLVMBuildExtractValue(ctx->builder, res, 1, "");
1280 res = LLVMBuildZExt(ctx->builder, res, ctx->i32, "");
1281 return res;
1282 }
1283
1284 static LLVMValueRef emit_b2f(struct nir_to_llvm_context *ctx,
1285 LLVMValueRef src0)
1286 {
1287 return LLVMBuildAnd(ctx->builder, src0, LLVMBuildBitCast(ctx->builder, LLVMConstReal(ctx->f32, 1.0), ctx->i32, ""), "");
1288 }
1289
1290 static LLVMValueRef emit_f2f16(struct nir_to_llvm_context *ctx,
1291 LLVMValueRef src0)
1292 {
1293 LLVMValueRef result;
1294 LLVMValueRef cond;
1295
1296 src0 = to_float(&ctx->ac, src0);
1297 result = LLVMBuildFPTrunc(ctx->builder, src0, ctx->f16, "");
1298
1299 /* TODO SI/CIK options here */
1300 if (ctx->options->chip_class >= VI) {
1301 LLVMValueRef args[2];
1302 /* Check if the result is a denormal - and flush to 0 if so. */
1303 args[0] = result;
1304 args[1] = LLVMConstInt(ctx->i32, N_SUBNORMAL | P_SUBNORMAL, false);
1305 cond = ac_build_intrinsic(&ctx->ac, "llvm.amdgcn.class.f16", ctx->i1, args, 2, AC_FUNC_ATTR_READNONE);
1306 }
1307
1308 /* need to convert back up to f32 */
1309 result = LLVMBuildFPExt(ctx->builder, result, ctx->f32, "");
1310
1311 if (ctx->options->chip_class >= VI)
1312 result = LLVMBuildSelect(ctx->builder, cond, ctx->f32zero, result, "");
1313
1314 return result;
1315 }
1316
1317 static LLVMValueRef emit_umul_high(struct nir_to_llvm_context *ctx,
1318 LLVMValueRef src0, LLVMValueRef src1)
1319 {
1320 LLVMValueRef dst64, result;
1321 src0 = LLVMBuildZExt(ctx->builder, src0, ctx->i64, "");
1322 src1 = LLVMBuildZExt(ctx->builder, src1, ctx->i64, "");
1323
1324 dst64 = LLVMBuildMul(ctx->builder, src0, src1, "");
1325 dst64 = LLVMBuildLShr(ctx->builder, dst64, LLVMConstInt(ctx->i64, 32, false), "");
1326 result = LLVMBuildTrunc(ctx->builder, dst64, ctx->i32, "");
1327 return result;
1328 }
1329
1330 static LLVMValueRef emit_imul_high(struct nir_to_llvm_context *ctx,
1331 LLVMValueRef src0, LLVMValueRef src1)
1332 {
1333 LLVMValueRef dst64, result;
1334 src0 = LLVMBuildSExt(ctx->builder, src0, ctx->i64, "");
1335 src1 = LLVMBuildSExt(ctx->builder, src1, ctx->i64, "");
1336
1337 dst64 = LLVMBuildMul(ctx->builder, src0, src1, "");
1338 dst64 = LLVMBuildAShr(ctx->builder, dst64, LLVMConstInt(ctx->i64, 32, false), "");
1339 result = LLVMBuildTrunc(ctx->builder, dst64, ctx->i32, "");
1340 return result;
1341 }
1342
1343 static LLVMValueRef emit_bitfield_extract(struct nir_to_llvm_context *ctx,
1344 bool is_signed,
1345 const LLVMValueRef srcs[3])
1346 {
1347 LLVMValueRef result;
1348 LLVMValueRef icond = LLVMBuildICmp(ctx->builder, LLVMIntEQ, srcs[2], LLVMConstInt(ctx->i32, 32, false), "");
1349
1350 result = ac_build_bfe(&ctx->ac, srcs[0], srcs[1], srcs[2], is_signed);
1351 result = LLVMBuildSelect(ctx->builder, icond, srcs[0], result, "");
1352 return result;
1353 }
1354
1355 static LLVMValueRef emit_bitfield_insert(struct nir_to_llvm_context *ctx,
1356 LLVMValueRef src0, LLVMValueRef src1,
1357 LLVMValueRef src2, LLVMValueRef src3)
1358 {
1359 LLVMValueRef bfi_args[3], result;
1360
1361 bfi_args[0] = LLVMBuildShl(ctx->builder,
1362 LLVMBuildSub(ctx->builder,
1363 LLVMBuildShl(ctx->builder,
1364 ctx->i32one,
1365 src3, ""),
1366 ctx->i32one, ""),
1367 src2, "");
1368 bfi_args[1] = LLVMBuildShl(ctx->builder, src1, src2, "");
1369 bfi_args[2] = src0;
1370
1371 LLVMValueRef icond = LLVMBuildICmp(ctx->builder, LLVMIntEQ, src3, LLVMConstInt(ctx->i32, 32, false), "");
1372
1373 /* Calculate:
1374 * (arg0 & arg1) | (~arg0 & arg2) = arg2 ^ (arg0 & (arg1 ^ arg2)
1375 * Use the right-hand side, which the LLVM backend can convert to V_BFI.
1376 */
1377 result = LLVMBuildXor(ctx->builder, bfi_args[2],
1378 LLVMBuildAnd(ctx->builder, bfi_args[0],
1379 LLVMBuildXor(ctx->builder, bfi_args[1], bfi_args[2], ""), ""), "");
1380
1381 result = LLVMBuildSelect(ctx->builder, icond, src1, result, "");
1382 return result;
1383 }
1384
1385 static LLVMValueRef emit_pack_half_2x16(struct nir_to_llvm_context *ctx,
1386 LLVMValueRef src0)
1387 {
1388 LLVMValueRef const16 = LLVMConstInt(ctx->i32, 16, false);
1389 int i;
1390 LLVMValueRef comp[2];
1391
1392 src0 = to_float(&ctx->ac, src0);
1393 comp[0] = LLVMBuildExtractElement(ctx->builder, src0, ctx->i32zero, "");
1394 comp[1] = LLVMBuildExtractElement(ctx->builder, src0, ctx->i32one, "");
1395 for (i = 0; i < 2; i++) {
1396 comp[i] = LLVMBuildFPTrunc(ctx->builder, comp[i], ctx->f16, "");
1397 comp[i] = LLVMBuildBitCast(ctx->builder, comp[i], ctx->i16, "");
1398 comp[i] = LLVMBuildZExt(ctx->builder, comp[i], ctx->i32, "");
1399 }
1400
1401 comp[1] = LLVMBuildShl(ctx->builder, comp[1], const16, "");
1402 comp[0] = LLVMBuildOr(ctx->builder, comp[0], comp[1], "");
1403
1404 return comp[0];
1405 }
1406
1407 static LLVMValueRef emit_unpack_half_2x16(struct nir_to_llvm_context *ctx,
1408 LLVMValueRef src0)
1409 {
1410 LLVMValueRef const16 = LLVMConstInt(ctx->i32, 16, false);
1411 LLVMValueRef temps[2], result, val;
1412 int i;
1413
1414 for (i = 0; i < 2; i++) {
1415 val = i == 1 ? LLVMBuildLShr(ctx->builder, src0, const16, "") : src0;
1416 val = LLVMBuildTrunc(ctx->builder, val, ctx->i16, "");
1417 val = LLVMBuildBitCast(ctx->builder, val, ctx->f16, "");
1418 temps[i] = LLVMBuildFPExt(ctx->builder, val, ctx->f32, "");
1419 }
1420
1421 result = LLVMBuildInsertElement(ctx->builder, LLVMGetUndef(ctx->v2f32), temps[0],
1422 ctx->i32zero, "");
1423 result = LLVMBuildInsertElement(ctx->builder, result, temps[1],
1424 ctx->i32one, "");
1425 return result;
1426 }
1427
1428 static LLVMValueRef emit_ddxy(struct nir_to_llvm_context *ctx,
1429 nir_op op,
1430 LLVMValueRef src0)
1431 {
1432 unsigned mask;
1433 int idx;
1434 LLVMValueRef result;
1435 ctx->has_ddxy = true;
1436
1437 if (!ctx->lds && !ctx->has_ds_bpermute)
1438 ctx->lds = LLVMAddGlobalInAddressSpace(ctx->module,
1439 LLVMArrayType(ctx->i32, 64),
1440 "ddxy_lds", LOCAL_ADDR_SPACE);
1441
1442 if (op == nir_op_fddx_fine || op == nir_op_fddx)
1443 mask = AC_TID_MASK_LEFT;
1444 else if (op == nir_op_fddy_fine || op == nir_op_fddy)
1445 mask = AC_TID_MASK_TOP;
1446 else
1447 mask = AC_TID_MASK_TOP_LEFT;
1448
1449 /* for DDX we want to next X pixel, DDY next Y pixel. */
1450 if (op == nir_op_fddx_fine ||
1451 op == nir_op_fddx_coarse ||
1452 op == nir_op_fddx)
1453 idx = 1;
1454 else
1455 idx = 2;
1456
1457 result = ac_build_ddxy(&ctx->ac, ctx->has_ds_bpermute,
1458 mask, idx, ctx->lds,
1459 src0);
1460 return result;
1461 }
1462
1463 /*
1464 * this takes an I,J coordinate pair,
1465 * and works out the X and Y derivatives.
1466 * it returns DDX(I), DDX(J), DDY(I), DDY(J).
1467 */
1468 static LLVMValueRef emit_ddxy_interp(
1469 struct nir_to_llvm_context *ctx,
1470 LLVMValueRef interp_ij)
1471 {
1472 LLVMValueRef result[4], a;
1473 unsigned i;
1474
1475 for (i = 0; i < 2; i++) {
1476 a = LLVMBuildExtractElement(ctx->builder, interp_ij,
1477 LLVMConstInt(ctx->i32, i, false), "");
1478 result[i] = emit_ddxy(ctx, nir_op_fddx, a);
1479 result[2+i] = emit_ddxy(ctx, nir_op_fddy, a);
1480 }
1481 return ac_build_gather_values(&ctx->ac, result, 4);
1482 }
1483
1484 static void visit_alu(struct nir_to_llvm_context *ctx, const nir_alu_instr *instr)
1485 {
1486 LLVMValueRef src[4], result = NULL;
1487 unsigned num_components = instr->dest.dest.ssa.num_components;
1488 unsigned src_components;
1489 LLVMTypeRef def_type = get_def_type(ctx, &instr->dest.dest.ssa);
1490
1491 assert(nir_op_infos[instr->op].num_inputs <= ARRAY_SIZE(src));
1492 switch (instr->op) {
1493 case nir_op_vec2:
1494 case nir_op_vec3:
1495 case nir_op_vec4:
1496 src_components = 1;
1497 break;
1498 case nir_op_pack_half_2x16:
1499 src_components = 2;
1500 break;
1501 case nir_op_unpack_half_2x16:
1502 src_components = 1;
1503 break;
1504 default:
1505 src_components = num_components;
1506 break;
1507 }
1508 for (unsigned i = 0; i < nir_op_infos[instr->op].num_inputs; i++)
1509 src[i] = get_alu_src(ctx, instr->src[i], src_components);
1510
1511 switch (instr->op) {
1512 case nir_op_fmov:
1513 case nir_op_imov:
1514 result = src[0];
1515 break;
1516 case nir_op_fneg:
1517 src[0] = to_float(&ctx->ac, src[0]);
1518 result = LLVMBuildFNeg(ctx->builder, src[0], "");
1519 break;
1520 case nir_op_ineg:
1521 result = LLVMBuildNeg(ctx->builder, src[0], "");
1522 break;
1523 case nir_op_inot:
1524 result = LLVMBuildNot(ctx->builder, src[0], "");
1525 break;
1526 case nir_op_iadd:
1527 result = LLVMBuildAdd(ctx->builder, src[0], src[1], "");
1528 break;
1529 case nir_op_fadd:
1530 src[0] = to_float(&ctx->ac, src[0]);
1531 src[1] = to_float(&ctx->ac, src[1]);
1532 result = LLVMBuildFAdd(ctx->builder, src[0], src[1], "");
1533 break;
1534 case nir_op_fsub:
1535 src[0] = to_float(&ctx->ac, src[0]);
1536 src[1] = to_float(&ctx->ac, src[1]);
1537 result = LLVMBuildFSub(ctx->builder, src[0], src[1], "");
1538 break;
1539 case nir_op_isub:
1540 result = LLVMBuildSub(ctx->builder, src[0], src[1], "");
1541 break;
1542 case nir_op_imul:
1543 result = LLVMBuildMul(ctx->builder, src[0], src[1], "");
1544 break;
1545 case nir_op_imod:
1546 result = LLVMBuildSRem(ctx->builder, src[0], src[1], "");
1547 break;
1548 case nir_op_umod:
1549 result = LLVMBuildURem(ctx->builder, src[0], src[1], "");
1550 break;
1551 case nir_op_fmod:
1552 src[0] = to_float(&ctx->ac, src[0]);
1553 src[1] = to_float(&ctx->ac, src[1]);
1554 result = ac_build_fdiv(&ctx->ac, src[0], src[1]);
1555 result = emit_intrin_1f_param(ctx, "llvm.floor",
1556 to_float_type(&ctx->ac, def_type), result);
1557 result = LLVMBuildFMul(ctx->builder, src[1] , result, "");
1558 result = LLVMBuildFSub(ctx->builder, src[0], result, "");
1559 break;
1560 case nir_op_frem:
1561 src[0] = to_float(&ctx->ac, src[0]);
1562 src[1] = to_float(&ctx->ac, src[1]);
1563 result = LLVMBuildFRem(ctx->builder, src[0], src[1], "");
1564 break;
1565 case nir_op_irem:
1566 result = LLVMBuildSRem(ctx->builder, src[0], src[1], "");
1567 break;
1568 case nir_op_idiv:
1569 result = LLVMBuildSDiv(ctx->builder, src[0], src[1], "");
1570 break;
1571 case nir_op_udiv:
1572 result = LLVMBuildUDiv(ctx->builder, src[0], src[1], "");
1573 break;
1574 case nir_op_fmul:
1575 src[0] = to_float(&ctx->ac, src[0]);
1576 src[1] = to_float(&ctx->ac, src[1]);
1577 result = LLVMBuildFMul(ctx->builder, src[0], src[1], "");
1578 break;
1579 case nir_op_fdiv:
1580 src[0] = to_float(&ctx->ac, src[0]);
1581 src[1] = to_float(&ctx->ac, src[1]);
1582 result = ac_build_fdiv(&ctx->ac, src[0], src[1]);
1583 break;
1584 case nir_op_frcp:
1585 src[0] = to_float(&ctx->ac, src[0]);
1586 result = ac_build_fdiv(&ctx->ac, ctx->f32one, src[0]);
1587 break;
1588 case nir_op_iand:
1589 result = LLVMBuildAnd(ctx->builder, src[0], src[1], "");
1590 break;
1591 case nir_op_ior:
1592 result = LLVMBuildOr(ctx->builder, src[0], src[1], "");
1593 break;
1594 case nir_op_ixor:
1595 result = LLVMBuildXor(ctx->builder, src[0], src[1], "");
1596 break;
1597 case nir_op_ishl:
1598 result = LLVMBuildShl(ctx->builder, src[0], src[1], "");
1599 break;
1600 case nir_op_ishr:
1601 result = LLVMBuildAShr(ctx->builder, src[0], src[1], "");
1602 break;
1603 case nir_op_ushr:
1604 result = LLVMBuildLShr(ctx->builder, src[0], src[1], "");
1605 break;
1606 case nir_op_ilt:
1607 result = emit_int_cmp(ctx, LLVMIntSLT, src[0], src[1]);
1608 break;
1609 case nir_op_ine:
1610 result = emit_int_cmp(ctx, LLVMIntNE, src[0], src[1]);
1611 break;
1612 case nir_op_ieq:
1613 result = emit_int_cmp(ctx, LLVMIntEQ, src[0], src[1]);
1614 break;
1615 case nir_op_ige:
1616 result = emit_int_cmp(ctx, LLVMIntSGE, src[0], src[1]);
1617 break;
1618 case nir_op_ult:
1619 result = emit_int_cmp(ctx, LLVMIntULT, src[0], src[1]);
1620 break;
1621 case nir_op_uge:
1622 result = emit_int_cmp(ctx, LLVMIntUGE, src[0], src[1]);
1623 break;
1624 case nir_op_feq:
1625 result = emit_float_cmp(ctx, LLVMRealUEQ, src[0], src[1]);
1626 break;
1627 case nir_op_fne:
1628 result = emit_float_cmp(ctx, LLVMRealUNE, src[0], src[1]);
1629 break;
1630 case nir_op_flt:
1631 result = emit_float_cmp(ctx, LLVMRealULT, src[0], src[1]);
1632 break;
1633 case nir_op_fge:
1634 result = emit_float_cmp(ctx, LLVMRealUGE, src[0], src[1]);
1635 break;
1636 case nir_op_fabs:
1637 result = emit_intrin_1f_param(ctx, "llvm.fabs",
1638 to_float_type(&ctx->ac, def_type), src[0]);
1639 break;
1640 case nir_op_iabs:
1641 result = emit_iabs(ctx, src[0]);
1642 break;
1643 case nir_op_imax:
1644 result = emit_minmax_int(ctx, LLVMIntSGT, src[0], src[1]);
1645 break;
1646 case nir_op_imin:
1647 result = emit_minmax_int(ctx, LLVMIntSLT, src[0], src[1]);
1648 break;
1649 case nir_op_umax:
1650 result = emit_minmax_int(ctx, LLVMIntUGT, src[0], src[1]);
1651 break;
1652 case nir_op_umin:
1653 result = emit_minmax_int(ctx, LLVMIntULT, src[0], src[1]);
1654 break;
1655 case nir_op_isign:
1656 result = emit_isign(ctx, src[0]);
1657 break;
1658 case nir_op_fsign:
1659 src[0] = to_float(&ctx->ac, src[0]);
1660 result = emit_fsign(ctx, src[0]);
1661 break;
1662 case nir_op_ffloor:
1663 result = emit_intrin_1f_param(ctx, "llvm.floor",
1664 to_float_type(&ctx->ac, def_type), src[0]);
1665 break;
1666 case nir_op_ftrunc:
1667 result = emit_intrin_1f_param(ctx, "llvm.trunc",
1668 to_float_type(&ctx->ac, def_type), src[0]);
1669 break;
1670 case nir_op_fceil:
1671 result = emit_intrin_1f_param(ctx, "llvm.ceil",
1672 to_float_type(&ctx->ac, def_type), src[0]);
1673 break;
1674 case nir_op_fround_even:
1675 result = emit_intrin_1f_param(ctx, "llvm.rint",
1676 to_float_type(&ctx->ac, def_type),src[0]);
1677 break;
1678 case nir_op_ffract:
1679 result = emit_ffract(ctx, src[0]);
1680 break;
1681 case nir_op_fsin:
1682 result = emit_intrin_1f_param(ctx, "llvm.sin",
1683 to_float_type(&ctx->ac, def_type), src[0]);
1684 break;
1685 case nir_op_fcos:
1686 result = emit_intrin_1f_param(ctx, "llvm.cos",
1687 to_float_type(&ctx->ac, def_type), src[0]);
1688 break;
1689 case nir_op_fsqrt:
1690 result = emit_intrin_1f_param(ctx, "llvm.sqrt",
1691 to_float_type(&ctx->ac, def_type), src[0]);
1692 break;
1693 case nir_op_fexp2:
1694 result = emit_intrin_1f_param(ctx, "llvm.exp2",
1695 to_float_type(&ctx->ac, def_type), src[0]);
1696 break;
1697 case nir_op_flog2:
1698 result = emit_intrin_1f_param(ctx, "llvm.log2",
1699 to_float_type(&ctx->ac, def_type), src[0]);
1700 break;
1701 case nir_op_frsq:
1702 result = emit_intrin_1f_param(ctx, "llvm.sqrt",
1703 to_float_type(&ctx->ac, def_type), src[0]);
1704 result = ac_build_fdiv(&ctx->ac, ctx->f32one, result);
1705 break;
1706 case nir_op_fpow:
1707 result = emit_intrin_2f_param(ctx, "llvm.pow",
1708 to_float_type(&ctx->ac, def_type), src[0], src[1]);
1709 break;
1710 case nir_op_fmax:
1711 result = emit_intrin_2f_param(ctx, "llvm.maxnum",
1712 to_float_type(&ctx->ac, def_type), src[0], src[1]);
1713 if (instr->dest.dest.ssa.bit_size == 32)
1714 result = emit_intrin_1f_param(ctx, "llvm.canonicalize",
1715 to_float_type(&ctx->ac, def_type),
1716 result);
1717 break;
1718 case nir_op_fmin:
1719 result = emit_intrin_2f_param(ctx, "llvm.minnum",
1720 to_float_type(&ctx->ac, def_type), src[0], src[1]);
1721 if (instr->dest.dest.ssa.bit_size == 32)
1722 result = emit_intrin_1f_param(ctx, "llvm.canonicalize",
1723 to_float_type(&ctx->ac, def_type),
1724 result);
1725 break;
1726 case nir_op_ffma:
1727 result = emit_intrin_3f_param(ctx, "llvm.fma",
1728 to_float_type(&ctx->ac, def_type), src[0], src[1], src[2]);
1729 break;
1730 case nir_op_ibitfield_extract:
1731 result = emit_bitfield_extract(ctx, true, src);
1732 break;
1733 case nir_op_ubitfield_extract:
1734 result = emit_bitfield_extract(ctx, false, src);
1735 break;
1736 case nir_op_bitfield_insert:
1737 result = emit_bitfield_insert(ctx, src[0], src[1], src[2], src[3]);
1738 break;
1739 case nir_op_bitfield_reverse:
1740 result = ac_build_intrinsic(&ctx->ac, "llvm.bitreverse.i32", ctx->i32, src, 1, AC_FUNC_ATTR_READNONE);
1741 break;
1742 case nir_op_bit_count:
1743 result = ac_build_intrinsic(&ctx->ac, "llvm.ctpop.i32", ctx->i32, src, 1, AC_FUNC_ATTR_READNONE);
1744 break;
1745 case nir_op_vec2:
1746 case nir_op_vec3:
1747 case nir_op_vec4:
1748 for (unsigned i = 0; i < nir_op_infos[instr->op].num_inputs; i++)
1749 src[i] = to_integer(&ctx->ac, src[i]);
1750 result = ac_build_gather_values(&ctx->ac, src, num_components);
1751 break;
1752 case nir_op_f2i32:
1753 case nir_op_f2i64:
1754 src[0] = to_float(&ctx->ac, src[0]);
1755 result = LLVMBuildFPToSI(ctx->builder, src[0], def_type, "");
1756 break;
1757 case nir_op_f2u32:
1758 case nir_op_f2u64:
1759 src[0] = to_float(&ctx->ac, src[0]);
1760 result = LLVMBuildFPToUI(ctx->builder, src[0], def_type, "");
1761 break;
1762 case nir_op_i2f32:
1763 case nir_op_i2f64:
1764 result = LLVMBuildSIToFP(ctx->builder, src[0], to_float_type(&ctx->ac, def_type), "");
1765 break;
1766 case nir_op_u2f32:
1767 case nir_op_u2f64:
1768 result = LLVMBuildUIToFP(ctx->builder, src[0], to_float_type(&ctx->ac, def_type), "");
1769 break;
1770 case nir_op_f2f64:
1771 result = LLVMBuildFPExt(ctx->builder, src[0], to_float_type(&ctx->ac, def_type), "");
1772 break;
1773 case nir_op_f2f32:
1774 result = LLVMBuildFPTrunc(ctx->builder, src[0], to_float_type(&ctx->ac, def_type), "");
1775 break;
1776 case nir_op_u2u32:
1777 case nir_op_u2u64:
1778 if (get_elem_bits(&ctx->ac, LLVMTypeOf(src[0])) < get_elem_bits(&ctx->ac, def_type))
1779 result = LLVMBuildZExt(ctx->builder, src[0], def_type, "");
1780 else
1781 result = LLVMBuildTrunc(ctx->builder, src[0], def_type, "");
1782 break;
1783 case nir_op_i2i32:
1784 case nir_op_i2i64:
1785 if (get_elem_bits(&ctx->ac, LLVMTypeOf(src[0])) < get_elem_bits(&ctx->ac, def_type))
1786 result = LLVMBuildSExt(ctx->builder, src[0], def_type, "");
1787 else
1788 result = LLVMBuildTrunc(ctx->builder, src[0], def_type, "");
1789 break;
1790 case nir_op_bcsel:
1791 result = emit_bcsel(ctx, src[0], src[1], src[2]);
1792 break;
1793 case nir_op_find_lsb:
1794 result = emit_find_lsb(ctx, src[0]);
1795 break;
1796 case nir_op_ufind_msb:
1797 result = emit_ufind_msb(ctx, src[0]);
1798 break;
1799 case nir_op_ifind_msb:
1800 result = emit_ifind_msb(ctx, src[0]);
1801 break;
1802 case nir_op_uadd_carry:
1803 result = emit_uint_carry(ctx, "llvm.uadd.with.overflow.i32", src[0], src[1]);
1804 break;
1805 case nir_op_usub_borrow:
1806 result = emit_uint_carry(ctx, "llvm.usub.with.overflow.i32", src[0], src[1]);
1807 break;
1808 case nir_op_b2f:
1809 result = emit_b2f(ctx, src[0]);
1810 break;
1811 case nir_op_fquantize2f16:
1812 result = emit_f2f16(ctx, src[0]);
1813 break;
1814 case nir_op_umul_high:
1815 result = emit_umul_high(ctx, src[0], src[1]);
1816 break;
1817 case nir_op_imul_high:
1818 result = emit_imul_high(ctx, src[0], src[1]);
1819 break;
1820 case nir_op_pack_half_2x16:
1821 result = emit_pack_half_2x16(ctx, src[0]);
1822 break;
1823 case nir_op_unpack_half_2x16:
1824 result = emit_unpack_half_2x16(ctx, src[0]);
1825 break;
1826 case nir_op_fddx:
1827 case nir_op_fddy:
1828 case nir_op_fddx_fine:
1829 case nir_op_fddy_fine:
1830 case nir_op_fddx_coarse:
1831 case nir_op_fddy_coarse:
1832 result = emit_ddxy(ctx, instr->op, src[0]);
1833 break;
1834 default:
1835 fprintf(stderr, "Unknown NIR alu instr: ");
1836 nir_print_instr(&instr->instr, stderr);
1837 fprintf(stderr, "\n");
1838 abort();
1839 }
1840
1841 if (result) {
1842 assert(instr->dest.dest.is_ssa);
1843 result = to_integer(&ctx->ac, result);
1844 _mesa_hash_table_insert(ctx->defs, &instr->dest.dest.ssa,
1845 result);
1846 }
1847 }
1848
1849 static void visit_load_const(struct nir_to_llvm_context *ctx,
1850 const nir_load_const_instr *instr)
1851 {
1852 LLVMValueRef values[4], value = NULL;
1853 LLVMTypeRef element_type =
1854 LLVMIntTypeInContext(ctx->context, instr->def.bit_size);
1855
1856 for (unsigned i = 0; i < instr->def.num_components; ++i) {
1857 switch (instr->def.bit_size) {
1858 case 32:
1859 values[i] = LLVMConstInt(element_type,
1860 instr->value.u32[i], false);
1861 break;
1862 case 64:
1863 values[i] = LLVMConstInt(element_type,
1864 instr->value.u64[i], false);
1865 break;
1866 default:
1867 fprintf(stderr,
1868 "unsupported nir load_const bit_size: %d\n",
1869 instr->def.bit_size);
1870 abort();
1871 }
1872 }
1873 if (instr->def.num_components > 1) {
1874 value = LLVMConstVector(values, instr->def.num_components);
1875 } else
1876 value = values[0];
1877
1878 _mesa_hash_table_insert(ctx->defs, &instr->def, value);
1879 }
1880
1881 static LLVMValueRef cast_ptr(struct nir_to_llvm_context *ctx, LLVMValueRef ptr,
1882 LLVMTypeRef type)
1883 {
1884 int addr_space = LLVMGetPointerAddressSpace(LLVMTypeOf(ptr));
1885 return LLVMBuildBitCast(ctx->builder, ptr,
1886 LLVMPointerType(type, addr_space), "");
1887 }
1888
1889 static LLVMValueRef
1890 get_buffer_size(struct nir_to_llvm_context *ctx, LLVMValueRef descriptor, bool in_elements)
1891 {
1892 LLVMValueRef size =
1893 LLVMBuildExtractElement(ctx->builder, descriptor,
1894 LLVMConstInt(ctx->i32, 2, false), "");
1895
1896 /* VI only */
1897 if (ctx->options->chip_class >= VI && in_elements) {
1898 /* On VI, the descriptor contains the size in bytes,
1899 * but TXQ must return the size in elements.
1900 * The stride is always non-zero for resources using TXQ.
1901 */
1902 LLVMValueRef stride =
1903 LLVMBuildExtractElement(ctx->builder, descriptor,
1904 LLVMConstInt(ctx->i32, 1, false), "");
1905 stride = LLVMBuildLShr(ctx->builder, stride,
1906 LLVMConstInt(ctx->i32, 16, false), "");
1907 stride = LLVMBuildAnd(ctx->builder, stride,
1908 LLVMConstInt(ctx->i32, 0x3fff, false), "");
1909
1910 size = LLVMBuildUDiv(ctx->builder, size, stride, "");
1911 }
1912 return size;
1913 }
1914
1915 /**
1916 * Given the i32 or vNi32 \p type, generate the textual name (e.g. for use with
1917 * intrinsic names).
1918 */
1919 static void build_int_type_name(
1920 LLVMTypeRef type,
1921 char *buf, unsigned bufsize)
1922 {
1923 assert(bufsize >= 6);
1924
1925 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind)
1926 snprintf(buf, bufsize, "v%ui32",
1927 LLVMGetVectorSize(type));
1928 else
1929 strcpy(buf, "i32");
1930 }
1931
1932 static LLVMValueRef radv_lower_gather4_integer(struct nir_to_llvm_context *ctx,
1933 struct ac_image_args *args,
1934 const nir_tex_instr *instr)
1935 {
1936 enum glsl_base_type stype = glsl_get_sampler_result_type(instr->texture->var->type);
1937 LLVMValueRef coord = args->addr;
1938 LLVMValueRef half_texel[2];
1939 LLVMValueRef compare_cube_wa;
1940 LLVMValueRef result;
1941 int c;
1942 unsigned coord_vgpr_index = (unsigned)args->offset + (unsigned)args->compare;
1943
1944 //TODO Rect
1945 {
1946 struct ac_image_args txq_args = { 0 };
1947
1948 txq_args.da = instr->is_array || instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE;
1949 txq_args.opcode = ac_image_get_resinfo;
1950 txq_args.dmask = 0xf;
1951 txq_args.addr = ctx->i32zero;
1952 txq_args.resource = args->resource;
1953 LLVMValueRef size = ac_build_image_opcode(&ctx->ac, &txq_args);
1954
1955 for (c = 0; c < 2; c++) {
1956 half_texel[c] = LLVMBuildExtractElement(ctx->builder, size,
1957 LLVMConstInt(ctx->i32, c, false), "");
1958 half_texel[c] = LLVMBuildUIToFP(ctx->builder, half_texel[c], ctx->f32, "");
1959 half_texel[c] = ac_build_fdiv(&ctx->ac, ctx->f32one, half_texel[c]);
1960 half_texel[c] = LLVMBuildFMul(ctx->builder, half_texel[c],
1961 LLVMConstReal(ctx->f32, -0.5), "");
1962 }
1963 }
1964
1965 LLVMValueRef orig_coords = args->addr;
1966
1967 for (c = 0; c < 2; c++) {
1968 LLVMValueRef tmp;
1969 LLVMValueRef index = LLVMConstInt(ctx->i32, coord_vgpr_index + c, 0);
1970 tmp = LLVMBuildExtractElement(ctx->builder, coord, index, "");
1971 tmp = LLVMBuildBitCast(ctx->builder, tmp, ctx->f32, "");
1972 tmp = LLVMBuildFAdd(ctx->builder, tmp, half_texel[c], "");
1973 tmp = LLVMBuildBitCast(ctx->builder, tmp, ctx->i32, "");
1974 coord = LLVMBuildInsertElement(ctx->builder, coord, tmp, index, "");
1975 }
1976
1977
1978 /*
1979 * Apparantly cube has issue with integer types that the workaround doesn't solve,
1980 * so this tests if the format is 8_8_8_8 and an integer type do an alternate
1981 * workaround by sampling using a scaled type and converting.
1982 * This is taken from amdgpu-pro shaders.
1983 */
1984 /* NOTE this produces some ugly code compared to amdgpu-pro,
1985 * LLVM ends up dumping SGPRs into VGPRs to deal with the compare/select,
1986 * and then reads them back. -pro generates two selects,
1987 * one s_cmp for the descriptor rewriting
1988 * one v_cmp for the coordinate and result changes.
1989 */
1990 if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) {
1991 LLVMValueRef tmp, tmp2;
1992
1993 /* workaround 8/8/8/8 uint/sint cube gather bug */
1994 /* first detect it then change to a scaled read and f2i */
1995 tmp = LLVMBuildExtractElement(ctx->builder, args->resource, ctx->i32one, "");
1996 tmp2 = tmp;
1997
1998 /* extract the DATA_FORMAT */
1999 tmp = ac_build_bfe(&ctx->ac, tmp, LLVMConstInt(ctx->i32, 20, false),
2000 LLVMConstInt(ctx->i32, 6, false), false);
2001
2002 /* is the DATA_FORMAT == 8_8_8_8 */
2003 compare_cube_wa = LLVMBuildICmp(ctx->builder, LLVMIntEQ, tmp, LLVMConstInt(ctx->i32, V_008F14_IMG_DATA_FORMAT_8_8_8_8, false), "");
2004
2005 if (stype == GLSL_TYPE_UINT)
2006 /* Create a NUM FORMAT - 0x2 or 0x4 - USCALED or UINT */
2007 tmp = LLVMBuildSelect(ctx->builder, compare_cube_wa, LLVMConstInt(ctx->i32, 0x8000000, false),
2008 LLVMConstInt(ctx->i32, 0x10000000, false), "");
2009 else
2010 /* Create a NUM FORMAT - 0x3 or 0x5 - SSCALED or SINT */
2011 tmp = LLVMBuildSelect(ctx->builder, compare_cube_wa, LLVMConstInt(ctx->i32, 0xc000000, false),
2012 LLVMConstInt(ctx->i32, 0x14000000, false), "");
2013
2014 /* replace the NUM FORMAT in the descriptor */
2015 tmp2 = LLVMBuildAnd(ctx->builder, tmp2, LLVMConstInt(ctx->i32, C_008F14_NUM_FORMAT_GFX6, false), "");
2016 tmp2 = LLVMBuildOr(ctx->builder, tmp2, tmp, "");
2017
2018 args->resource = LLVMBuildInsertElement(ctx->builder, args->resource, tmp2, ctx->i32one, "");
2019
2020 /* don't modify the coordinates for this case */
2021 coord = LLVMBuildSelect(ctx->builder, compare_cube_wa, orig_coords, coord, "");
2022 }
2023 args->addr = coord;
2024 result = ac_build_image_opcode(&ctx->ac, args);
2025
2026 if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) {
2027 LLVMValueRef tmp, tmp2;
2028
2029 /* if the cube workaround is in place, f2i the result. */
2030 for (c = 0; c < 4; c++) {
2031 tmp = LLVMBuildExtractElement(ctx->builder, result, LLVMConstInt(ctx->i32, c, false), "");
2032 if (stype == GLSL_TYPE_UINT)
2033 tmp2 = LLVMBuildFPToUI(ctx->builder, tmp, ctx->i32, "");
2034 else
2035 tmp2 = LLVMBuildFPToSI(ctx->builder, tmp, ctx->i32, "");
2036 tmp = LLVMBuildBitCast(ctx->builder, tmp, ctx->i32, "");
2037 tmp2 = LLVMBuildBitCast(ctx->builder, tmp2, ctx->i32, "");
2038 tmp = LLVMBuildSelect(ctx->builder, compare_cube_wa, tmp2, tmp, "");
2039 tmp = LLVMBuildBitCast(ctx->builder, tmp, ctx->f32, "");
2040 result = LLVMBuildInsertElement(ctx->builder, result, tmp, LLVMConstInt(ctx->i32, c, false), "");
2041 }
2042 }
2043 return result;
2044 }
2045
2046 static LLVMValueRef build_tex_intrinsic(struct nir_to_llvm_context *ctx,
2047 const nir_tex_instr *instr,
2048 bool lod_is_zero,
2049 struct ac_image_args *args)
2050 {
2051 if (instr->sampler_dim == GLSL_SAMPLER_DIM_BUF) {
2052 return ac_build_buffer_load_format(&ctx->ac,
2053 args->resource,
2054 args->addr,
2055 LLVMConstInt(ctx->i32, 0, false),
2056 true);
2057 }
2058
2059 args->opcode = ac_image_sample;
2060 args->compare = instr->is_shadow;
2061
2062 switch (instr->op) {
2063 case nir_texop_txf:
2064 case nir_texop_txf_ms:
2065 case nir_texop_samples_identical:
2066 args->opcode = instr->sampler_dim == GLSL_SAMPLER_DIM_MS ? ac_image_load : ac_image_load_mip;
2067 args->compare = false;
2068 args->offset = false;
2069 break;
2070 case nir_texop_txb:
2071 args->bias = true;
2072 break;
2073 case nir_texop_txl:
2074 if (lod_is_zero)
2075 args->level_zero = true;
2076 else
2077 args->lod = true;
2078 break;
2079 case nir_texop_txs:
2080 case nir_texop_query_levels:
2081 args->opcode = ac_image_get_resinfo;
2082 break;
2083 case nir_texop_tex:
2084 if (ctx->stage != MESA_SHADER_FRAGMENT)
2085 args->level_zero = true;
2086 break;
2087 case nir_texop_txd:
2088 args->deriv = true;
2089 break;
2090 case nir_texop_tg4:
2091 args->opcode = ac_image_gather4;
2092 args->level_zero = true;
2093 break;
2094 case nir_texop_lod:
2095 args->opcode = ac_image_get_lod;
2096 args->compare = false;
2097 args->offset = false;
2098 break;
2099 default:
2100 break;
2101 }
2102
2103 if (instr->op == nir_texop_tg4) {
2104 enum glsl_base_type stype = glsl_get_sampler_result_type(instr->texture->var->type);
2105 if (stype == GLSL_TYPE_UINT || stype == GLSL_TYPE_INT) {
2106 return radv_lower_gather4_integer(ctx, args, instr);
2107 }
2108 }
2109 return ac_build_image_opcode(&ctx->ac, args);
2110 }
2111
2112 static LLVMValueRef visit_vulkan_resource_index(struct nir_to_llvm_context *ctx,
2113 nir_intrinsic_instr *instr)
2114 {
2115 LLVMValueRef index = get_src(ctx, instr->src[0]);
2116 unsigned desc_set = nir_intrinsic_desc_set(instr);
2117 unsigned binding = nir_intrinsic_binding(instr);
2118 LLVMValueRef desc_ptr = ctx->descriptor_sets[desc_set];
2119 struct radv_pipeline_layout *pipeline_layout = ctx->options->layout;
2120 struct radv_descriptor_set_layout *layout = pipeline_layout->set[desc_set].layout;
2121 unsigned base_offset = layout->binding[binding].offset;
2122 LLVMValueRef offset, stride;
2123
2124 if (layout->binding[binding].type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC ||
2125 layout->binding[binding].type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) {
2126 unsigned idx = pipeline_layout->set[desc_set].dynamic_offset_start +
2127 layout->binding[binding].dynamic_offset_offset;
2128 desc_ptr = ctx->push_constants;
2129 base_offset = pipeline_layout->push_constant_size + 16 * idx;
2130 stride = LLVMConstInt(ctx->i32, 16, false);
2131 } else
2132 stride = LLVMConstInt(ctx->i32, layout->binding[binding].size, false);
2133
2134 offset = LLVMConstInt(ctx->i32, base_offset, false);
2135 index = LLVMBuildMul(ctx->builder, index, stride, "");
2136 offset = LLVMBuildAdd(ctx->builder, offset, index, "");
2137
2138 desc_ptr = ac_build_gep0(&ctx->ac, desc_ptr, offset);
2139 desc_ptr = cast_ptr(ctx, desc_ptr, ctx->v4i32);
2140 LLVMSetMetadata(desc_ptr, ctx->uniform_md_kind, ctx->empty_md);
2141
2142 return LLVMBuildLoad(ctx->builder, desc_ptr, "");
2143 }
2144
2145 static LLVMValueRef visit_load_push_constant(struct nir_to_llvm_context *ctx,
2146 nir_intrinsic_instr *instr)
2147 {
2148 LLVMValueRef ptr, addr;
2149
2150 addr = LLVMConstInt(ctx->i32, nir_intrinsic_base(instr), 0);
2151 addr = LLVMBuildAdd(ctx->builder, addr, get_src(ctx, instr->src[0]), "");
2152
2153 ptr = ac_build_gep0(&ctx->ac, ctx->push_constants, addr);
2154 ptr = cast_ptr(ctx, ptr, get_def_type(ctx, &instr->dest.ssa));
2155
2156 return LLVMBuildLoad(ctx->builder, ptr, "");
2157 }
2158
2159 static LLVMValueRef visit_get_buffer_size(struct nir_to_llvm_context *ctx,
2160 const nir_intrinsic_instr *instr)
2161 {
2162 LLVMValueRef desc = get_src(ctx, instr->src[0]);
2163
2164 return get_buffer_size(ctx, desc, false);
2165 }
2166 static void visit_store_ssbo(struct nir_to_llvm_context *ctx,
2167 nir_intrinsic_instr *instr)
2168 {
2169 const char *store_name;
2170 LLVMValueRef src_data = get_src(ctx, instr->src[0]);
2171 LLVMTypeRef data_type = ctx->f32;
2172 int elem_size_mult = get_elem_bits(&ctx->ac, LLVMTypeOf(src_data)) / 32;
2173 int components_32bit = elem_size_mult * instr->num_components;
2174 unsigned writemask = nir_intrinsic_write_mask(instr);
2175 LLVMValueRef base_data, base_offset;
2176 LLVMValueRef params[6];
2177
2178 if (ctx->stage == MESA_SHADER_FRAGMENT)
2179 ctx->shader_info->fs.writes_memory = true;
2180
2181 params[1] = get_src(ctx, instr->src[1]);
2182 params[2] = LLVMConstInt(ctx->i32, 0, false); /* vindex */
2183 params[4] = ctx->i1false; /* glc */
2184 params[5] = ctx->i1false; /* slc */
2185
2186 if (components_32bit > 1)
2187 data_type = LLVMVectorType(ctx->f32, components_32bit);
2188
2189 base_data = to_float(&ctx->ac, src_data);
2190 base_data = trim_vector(ctx, base_data, instr->num_components);
2191 base_data = LLVMBuildBitCast(ctx->builder, base_data,
2192 data_type, "");
2193 base_offset = get_src(ctx, instr->src[2]); /* voffset */
2194 while (writemask) {
2195 int start, count;
2196 LLVMValueRef data;
2197 LLVMValueRef offset;
2198 LLVMValueRef tmp;
2199 u_bit_scan_consecutive_range(&writemask, &start, &count);
2200
2201 /* Due to an LLVM limitation, split 3-element writes
2202 * into a 2-element and a 1-element write. */
2203 if (count == 3) {
2204 writemask |= 1 << (start + 2);
2205 count = 2;
2206 }
2207
2208 start *= elem_size_mult;
2209 count *= elem_size_mult;
2210
2211 if (count > 4) {
2212 writemask |= ((1u << (count - 4)) - 1u) << (start + 4);
2213 count = 4;
2214 }
2215
2216 if (count == 4) {
2217 store_name = "llvm.amdgcn.buffer.store.v4f32";
2218 data = base_data;
2219 } else if (count == 2) {
2220 tmp = LLVMBuildExtractElement(ctx->builder,
2221 base_data, LLVMConstInt(ctx->i32, start, false), "");
2222 data = LLVMBuildInsertElement(ctx->builder, LLVMGetUndef(ctx->v2f32), tmp,
2223 ctx->i32zero, "");
2224
2225 tmp = LLVMBuildExtractElement(ctx->builder,
2226 base_data, LLVMConstInt(ctx->i32, start + 1, false), "");
2227 data = LLVMBuildInsertElement(ctx->builder, data, tmp,
2228 ctx->i32one, "");
2229 store_name = "llvm.amdgcn.buffer.store.v2f32";
2230
2231 } else {
2232 assert(count == 1);
2233 if (get_llvm_num_components(base_data) > 1)
2234 data = LLVMBuildExtractElement(ctx->builder, base_data,
2235 LLVMConstInt(ctx->i32, start, false), "");
2236 else
2237 data = base_data;
2238 store_name = "llvm.amdgcn.buffer.store.f32";
2239 }
2240
2241 offset = base_offset;
2242 if (start != 0) {
2243 offset = LLVMBuildAdd(ctx->builder, offset, LLVMConstInt(ctx->i32, start * 4, false), "");
2244 }
2245 params[0] = data;
2246 params[3] = offset;
2247 ac_build_intrinsic(&ctx->ac, store_name,
2248 ctx->voidt, params, 6, 0);
2249 }
2250 }
2251
2252 static LLVMValueRef visit_atomic_ssbo(struct nir_to_llvm_context *ctx,
2253 const nir_intrinsic_instr *instr)
2254 {
2255 const char *name;
2256 LLVMValueRef params[6];
2257 int arg_count = 0;
2258 if (ctx->stage == MESA_SHADER_FRAGMENT)
2259 ctx->shader_info->fs.writes_memory = true;
2260
2261 if (instr->intrinsic == nir_intrinsic_ssbo_atomic_comp_swap) {
2262 params[arg_count++] = llvm_extract_elem(ctx, get_src(ctx, instr->src[3]), 0);
2263 }
2264 params[arg_count++] = llvm_extract_elem(ctx, get_src(ctx, instr->src[2]), 0);
2265 params[arg_count++] = get_src(ctx, instr->src[0]);
2266 params[arg_count++] = LLVMConstInt(ctx->i32, 0, false); /* vindex */
2267 params[arg_count++] = get_src(ctx, instr->src[1]); /* voffset */
2268 params[arg_count++] = ctx->i1false; /* slc */
2269
2270 switch (instr->intrinsic) {
2271 case nir_intrinsic_ssbo_atomic_add:
2272 name = "llvm.amdgcn.buffer.atomic.add";
2273 break;
2274 case nir_intrinsic_ssbo_atomic_imin:
2275 name = "llvm.amdgcn.buffer.atomic.smin";
2276 break;
2277 case nir_intrinsic_ssbo_atomic_umin:
2278 name = "llvm.amdgcn.buffer.atomic.umin";
2279 break;
2280 case nir_intrinsic_ssbo_atomic_imax:
2281 name = "llvm.amdgcn.buffer.atomic.smax";
2282 break;
2283 case nir_intrinsic_ssbo_atomic_umax:
2284 name = "llvm.amdgcn.buffer.atomic.umax";
2285 break;
2286 case nir_intrinsic_ssbo_atomic_and:
2287 name = "llvm.amdgcn.buffer.atomic.and";
2288 break;
2289 case nir_intrinsic_ssbo_atomic_or:
2290 name = "llvm.amdgcn.buffer.atomic.or";
2291 break;
2292 case nir_intrinsic_ssbo_atomic_xor:
2293 name = "llvm.amdgcn.buffer.atomic.xor";
2294 break;
2295 case nir_intrinsic_ssbo_atomic_exchange:
2296 name = "llvm.amdgcn.buffer.atomic.swap";
2297 break;
2298 case nir_intrinsic_ssbo_atomic_comp_swap:
2299 name = "llvm.amdgcn.buffer.atomic.cmpswap";
2300 break;
2301 default:
2302 abort();
2303 }
2304
2305 return ac_build_intrinsic(&ctx->ac, name, ctx->i32, params, arg_count, 0);
2306 }
2307
2308 static LLVMValueRef visit_load_buffer(struct nir_to_llvm_context *ctx,
2309 const nir_intrinsic_instr *instr)
2310 {
2311 LLVMValueRef results[2];
2312 int load_components;
2313 int num_components = instr->num_components;
2314 if (instr->dest.ssa.bit_size == 64)
2315 num_components *= 2;
2316
2317 for (int i = 0; i < num_components; i += load_components) {
2318 load_components = MIN2(num_components - i, 4);
2319 const char *load_name;
2320 LLVMTypeRef data_type = ctx->f32;
2321 LLVMValueRef offset = LLVMConstInt(ctx->i32, i * 4, false);
2322 offset = LLVMBuildAdd(ctx->builder, get_src(ctx, instr->src[1]), offset, "");
2323
2324 if (load_components == 3)
2325 data_type = LLVMVectorType(ctx->f32, 4);
2326 else if (load_components > 1)
2327 data_type = LLVMVectorType(ctx->f32, load_components);
2328
2329 if (load_components >= 3)
2330 load_name = "llvm.amdgcn.buffer.load.v4f32";
2331 else if (load_components == 2)
2332 load_name = "llvm.amdgcn.buffer.load.v2f32";
2333 else if (load_components == 1)
2334 load_name = "llvm.amdgcn.buffer.load.f32";
2335 else
2336 unreachable("unhandled number of components");
2337
2338 LLVMValueRef params[] = {
2339 get_src(ctx, instr->src[0]),
2340 LLVMConstInt(ctx->i32, 0, false),
2341 offset,
2342 ctx->i1false,
2343 ctx->i1false,
2344 };
2345
2346 results[i] = ac_build_intrinsic(&ctx->ac, load_name, data_type, params, 5, 0);
2347
2348 }
2349
2350 LLVMValueRef ret = results[0];
2351 if (num_components > 4 || num_components == 3) {
2352 LLVMValueRef masks[] = {
2353 LLVMConstInt(ctx->i32, 0, false), LLVMConstInt(ctx->i32, 1, false),
2354 LLVMConstInt(ctx->i32, 2, false), LLVMConstInt(ctx->i32, 3, false),
2355 LLVMConstInt(ctx->i32, 4, false), LLVMConstInt(ctx->i32, 5, false),
2356 LLVMConstInt(ctx->i32, 6, false), LLVMConstInt(ctx->i32, 7, false)
2357 };
2358
2359 LLVMValueRef swizzle = LLVMConstVector(masks, num_components);
2360 ret = LLVMBuildShuffleVector(ctx->builder, results[0],
2361 results[num_components > 4 ? 1 : 0], swizzle, "");
2362 }
2363
2364 return LLVMBuildBitCast(ctx->builder, ret,
2365 get_def_type(ctx, &instr->dest.ssa), "");
2366 }
2367
2368 static LLVMValueRef visit_load_ubo_buffer(struct nir_to_llvm_context *ctx,
2369 const nir_intrinsic_instr *instr)
2370 {
2371 LLVMValueRef results[8], ret;
2372 LLVMValueRef rsrc = get_src(ctx, instr->src[0]);
2373 LLVMValueRef offset = get_src(ctx, instr->src[1]);
2374 int num_components = instr->num_components;
2375
2376 rsrc = LLVMBuildBitCast(ctx->builder, rsrc, LLVMVectorType(ctx->i8, 16), "");
2377
2378 if (instr->dest.ssa.bit_size == 64)
2379 num_components *= 2;
2380
2381 for (unsigned i = 0; i < num_components; ++i) {
2382 LLVMValueRef params[] = {
2383 rsrc,
2384 LLVMBuildAdd(ctx->builder, LLVMConstInt(ctx->i32, 4 * i, 0),
2385 offset, "")
2386 };
2387 results[i] = ac_build_intrinsic(&ctx->ac, "llvm.SI.load.const", ctx->f32,
2388 params, 2,
2389 AC_FUNC_ATTR_READNONE |
2390 AC_FUNC_ATTR_LEGACY);
2391 }
2392
2393
2394 ret = ac_build_gather_values(&ctx->ac, results, instr->num_components);
2395 return LLVMBuildBitCast(ctx->builder, ret,
2396 get_def_type(ctx, &instr->dest.ssa), "");
2397 }
2398
2399 static void
2400 radv_get_deref_offset(struct nir_to_llvm_context *ctx, nir_deref_var *deref,
2401 bool vs_in, unsigned *vertex_index_out,
2402 LLVMValueRef *vertex_index_ref,
2403 unsigned *const_out, LLVMValueRef *indir_out)
2404 {
2405 unsigned const_offset = 0;
2406 nir_deref *tail = &deref->deref;
2407 LLVMValueRef offset = NULL;
2408
2409 if (vertex_index_out != NULL || vertex_index_ref != NULL) {
2410 tail = tail->child;
2411 nir_deref_array *deref_array = nir_deref_as_array(tail);
2412 if (vertex_index_out)
2413 *vertex_index_out = deref_array->base_offset;
2414
2415 if (vertex_index_ref) {
2416 LLVMValueRef vtx = LLVMConstInt(ctx->i32, deref_array->base_offset, false);
2417 if (deref_array->deref_array_type == nir_deref_array_type_indirect) {
2418 vtx = LLVMBuildAdd(ctx->builder, vtx, get_src(ctx, deref_array->indirect), "");
2419 }
2420 *vertex_index_ref = vtx;
2421 }
2422 }
2423
2424 if (deref->var->data.compact) {
2425 assert(tail->child->deref_type == nir_deref_type_array);
2426 assert(glsl_type_is_scalar(glsl_without_array(deref->var->type)));
2427 nir_deref_array *deref_array = nir_deref_as_array(tail->child);
2428 /* We always lower indirect dereferences for "compact" array vars. */
2429 assert(deref_array->deref_array_type == nir_deref_array_type_direct);
2430
2431 const_offset = deref_array->base_offset;
2432 goto out;
2433 }
2434
2435 while (tail->child != NULL) {
2436 const struct glsl_type *parent_type = tail->type;
2437 tail = tail->child;
2438
2439 if (tail->deref_type == nir_deref_type_array) {
2440 nir_deref_array *deref_array = nir_deref_as_array(tail);
2441 LLVMValueRef index, stride, local_offset;
2442 unsigned size = glsl_count_attribute_slots(tail->type, vs_in);
2443
2444 const_offset += size * deref_array->base_offset;
2445 if (deref_array->deref_array_type == nir_deref_array_type_direct)
2446 continue;
2447
2448 assert(deref_array->deref_array_type == nir_deref_array_type_indirect);
2449 index = get_src(ctx, deref_array->indirect);
2450 stride = LLVMConstInt(ctx->i32, size, 0);
2451 local_offset = LLVMBuildMul(ctx->builder, stride, index, "");
2452
2453 if (offset)
2454 offset = LLVMBuildAdd(ctx->builder, offset, local_offset, "");
2455 else
2456 offset = local_offset;
2457 } else if (tail->deref_type == nir_deref_type_struct) {
2458 nir_deref_struct *deref_struct = nir_deref_as_struct(tail);
2459
2460 for (unsigned i = 0; i < deref_struct->index; i++) {
2461 const struct glsl_type *ft = glsl_get_struct_field(parent_type, i);
2462 const_offset += glsl_count_attribute_slots(ft, vs_in);
2463 }
2464 } else
2465 unreachable("unsupported deref type");
2466
2467 }
2468 out:
2469 if (const_offset && offset)
2470 offset = LLVMBuildAdd(ctx->builder, offset,
2471 LLVMConstInt(ctx->i32, const_offset, 0),
2472 "");
2473
2474 *const_out = const_offset;
2475 *indir_out = offset;
2476 }
2477
2478 static LLVMValueRef
2479 lds_load(struct nir_to_llvm_context *ctx,
2480 LLVMValueRef dw_addr)
2481 {
2482 LLVMValueRef value;
2483 value = ac_build_indexed_load(&ctx->ac, ctx->lds, dw_addr, false);
2484 return value;
2485 }
2486
2487 static void
2488 lds_store(struct nir_to_llvm_context *ctx,
2489 LLVMValueRef dw_addr, LLVMValueRef value)
2490 {
2491 value = LLVMBuildBitCast(ctx->builder, value, ctx->i32, "");
2492 ac_build_indexed_store(&ctx->ac, ctx->lds,
2493 dw_addr, value);
2494 }
2495
2496 /* The offchip buffer layout for TCS->TES is
2497 *
2498 * - attribute 0 of patch 0 vertex 0
2499 * - attribute 0 of patch 0 vertex 1
2500 * - attribute 0 of patch 0 vertex 2
2501 * ...
2502 * - attribute 0 of patch 1 vertex 0
2503 * - attribute 0 of patch 1 vertex 1
2504 * ...
2505 * - attribute 1 of patch 0 vertex 0
2506 * - attribute 1 of patch 0 vertex 1
2507 * ...
2508 * - per patch attribute 0 of patch 0
2509 * - per patch attribute 0 of patch 1
2510 * ...
2511 *
2512 * Note that every attribute has 4 components.
2513 */
2514 static LLVMValueRef get_tcs_tes_buffer_address(struct nir_to_llvm_context *ctx,
2515 LLVMValueRef vertex_index,
2516 LLVMValueRef param_index)
2517 {
2518 LLVMValueRef base_addr, vertices_per_patch, num_patches, total_vertices;
2519 LLVMValueRef param_stride, constant16;
2520 LLVMValueRef rel_patch_id = get_rel_patch_id(ctx);
2521
2522 vertices_per_patch = unpack_param(ctx, ctx->tcs_offchip_layout, 9, 6);
2523 num_patches = unpack_param(ctx, ctx->tcs_offchip_layout, 0, 9);
2524 total_vertices = LLVMBuildMul(ctx->builder, vertices_per_patch,
2525 num_patches, "");
2526
2527 constant16 = LLVMConstInt(ctx->i32, 16, false);
2528 if (vertex_index) {
2529 base_addr = LLVMBuildMul(ctx->builder, rel_patch_id,
2530 vertices_per_patch, "");
2531
2532 base_addr = LLVMBuildAdd(ctx->builder, base_addr,
2533 vertex_index, "");
2534
2535 param_stride = total_vertices;
2536 } else {
2537 base_addr = rel_patch_id;
2538 param_stride = num_patches;
2539 }
2540
2541 base_addr = LLVMBuildAdd(ctx->builder, base_addr,
2542 LLVMBuildMul(ctx->builder, param_index,
2543 param_stride, ""), "");
2544
2545 base_addr = LLVMBuildMul(ctx->builder, base_addr, constant16, "");
2546
2547 if (!vertex_index) {
2548 LLVMValueRef patch_data_offset =
2549 unpack_param(ctx, ctx->tcs_offchip_layout, 16, 16);
2550
2551 base_addr = LLVMBuildAdd(ctx->builder, base_addr,
2552 patch_data_offset, "");
2553 }
2554 return base_addr;
2555 }
2556
2557 static LLVMValueRef get_tcs_tes_buffer_address_params(struct nir_to_llvm_context *ctx,
2558 unsigned param,
2559 unsigned const_index,
2560 bool is_compact,
2561 LLVMValueRef vertex_index,
2562 LLVMValueRef indir_index)
2563 {
2564 LLVMValueRef param_index;
2565
2566 if (indir_index)
2567 param_index = LLVMBuildAdd(ctx->builder, LLVMConstInt(ctx->i32, param, false),
2568 indir_index, "");
2569 else {
2570 if (const_index && !is_compact)
2571 param += const_index;
2572 param_index = LLVMConstInt(ctx->i32, param, false);
2573 }
2574 return get_tcs_tes_buffer_address(ctx, vertex_index, param_index);
2575 }
2576
2577 static void
2578 mark_tess_output(struct nir_to_llvm_context *ctx,
2579 bool is_patch, uint32_t param)
2580
2581 {
2582 if (is_patch) {
2583 ctx->tess_patch_outputs_written |= (1ull << param);
2584 } else
2585 ctx->tess_outputs_written |= (1ull << param);
2586 }
2587
2588 static LLVMValueRef
2589 get_dw_address(struct nir_to_llvm_context *ctx,
2590 LLVMValueRef dw_addr,
2591 unsigned param,
2592 unsigned const_index,
2593 bool compact_const_index,
2594 LLVMValueRef vertex_index,
2595 LLVMValueRef stride,
2596 LLVMValueRef indir_index)
2597
2598 {
2599
2600 if (vertex_index) {
2601 dw_addr = LLVMBuildAdd(ctx->builder, dw_addr,
2602 LLVMBuildMul(ctx->builder,
2603 vertex_index,
2604 stride, ""), "");
2605 }
2606
2607 if (indir_index)
2608 dw_addr = LLVMBuildAdd(ctx->builder, dw_addr,
2609 LLVMBuildMul(ctx->builder, indir_index,
2610 LLVMConstInt(ctx->i32, 4, false), ""), "");
2611 else if (const_index && !compact_const_index)
2612 dw_addr = LLVMBuildAdd(ctx->builder, dw_addr,
2613 LLVMConstInt(ctx->i32, const_index, false), "");
2614
2615 dw_addr = LLVMBuildAdd(ctx->builder, dw_addr,
2616 LLVMConstInt(ctx->i32, param * 4, false), "");
2617
2618 if (const_index && compact_const_index)
2619 dw_addr = LLVMBuildAdd(ctx->builder, dw_addr,
2620 LLVMConstInt(ctx->i32, const_index, false), "");
2621 return dw_addr;
2622 }
2623
2624 static LLVMValueRef
2625 load_tcs_input(struct nir_to_llvm_context *ctx,
2626 nir_intrinsic_instr *instr)
2627 {
2628 LLVMValueRef dw_addr, stride;
2629 unsigned const_index;
2630 LLVMValueRef vertex_index;
2631 LLVMValueRef indir_index;
2632 unsigned param;
2633 LLVMValueRef value[4], result;
2634 const bool per_vertex = nir_is_per_vertex_io(instr->variables[0]->var, ctx->stage);
2635 const bool is_compact = instr->variables[0]->var->data.compact;
2636 param = shader_io_get_unique_index(instr->variables[0]->var->data.location);
2637 radv_get_deref_offset(ctx, instr->variables[0],
2638 false, NULL, per_vertex ? &vertex_index : NULL,
2639 &const_index, &indir_index);
2640
2641 stride = unpack_param(ctx, ctx->tcs_in_layout, 13, 8);
2642 dw_addr = get_tcs_in_current_patch_offset(ctx);
2643 dw_addr = get_dw_address(ctx, dw_addr, param, const_index, is_compact, vertex_index, stride,
2644 indir_index);
2645
2646 for (unsigned i = 0; i < instr->num_components; i++) {
2647 value[i] = lds_load(ctx, dw_addr);
2648 dw_addr = LLVMBuildAdd(ctx->builder, dw_addr,
2649 ctx->i32one, "");
2650 }
2651 result = ac_build_gather_values(&ctx->ac, value, instr->num_components);
2652 result = LLVMBuildBitCast(ctx->builder, result, get_def_type(ctx, &instr->dest.ssa), "");
2653 return result;
2654 }
2655
2656 static LLVMValueRef
2657 load_tcs_output(struct nir_to_llvm_context *ctx,
2658 nir_intrinsic_instr *instr)
2659 {
2660 LLVMValueRef dw_addr, stride;
2661 LLVMValueRef value[4], result;
2662 LLVMValueRef vertex_index = NULL;
2663 LLVMValueRef indir_index = NULL;
2664 unsigned const_index = 0;
2665 unsigned param;
2666 const bool per_vertex = nir_is_per_vertex_io(instr->variables[0]->var, ctx->stage);
2667 const bool is_compact = instr->variables[0]->var->data.compact;
2668 param = shader_io_get_unique_index(instr->variables[0]->var->data.location);
2669 radv_get_deref_offset(ctx, instr->variables[0],
2670 false, NULL, per_vertex ? &vertex_index : NULL,
2671 &const_index, &indir_index);
2672
2673 if (!instr->variables[0]->var->data.patch) {
2674 stride = unpack_param(ctx, ctx->tcs_out_layout, 13, 8);
2675 dw_addr = get_tcs_out_current_patch_offset(ctx);
2676 } else {
2677 dw_addr = get_tcs_out_current_patch_data_offset(ctx);
2678 }
2679
2680 dw_addr = get_dw_address(ctx, dw_addr, param, const_index, is_compact, vertex_index, stride,
2681 indir_index);
2682
2683 for (unsigned i = 0; i < instr->num_components; i++) {
2684 value[i] = lds_load(ctx, dw_addr);
2685 dw_addr = LLVMBuildAdd(ctx->builder, dw_addr,
2686 ctx->i32one, "");
2687 }
2688 result = ac_build_gather_values(&ctx->ac, value, instr->num_components);
2689 result = LLVMBuildBitCast(ctx->builder, result, get_def_type(ctx, &instr->dest.ssa), "");
2690 return result;
2691 }
2692
2693 static void
2694 store_tcs_output(struct nir_to_llvm_context *ctx,
2695 nir_intrinsic_instr *instr,
2696 LLVMValueRef src,
2697 unsigned writemask)
2698 {
2699 LLVMValueRef stride, dw_addr;
2700 LLVMValueRef buf_addr = NULL;
2701 LLVMValueRef vertex_index = NULL;
2702 LLVMValueRef indir_index = NULL;
2703 unsigned const_index = 0;
2704 unsigned param;
2705 const bool per_vertex = nir_is_per_vertex_io(instr->variables[0]->var, ctx->stage);
2706 const bool is_compact = instr->variables[0]->var->data.compact;
2707
2708 radv_get_deref_offset(ctx, instr->variables[0],
2709 false, NULL, per_vertex ? &vertex_index : NULL,
2710 &const_index, &indir_index);
2711
2712 param = shader_io_get_unique_index(instr->variables[0]->var->data.location);
2713 if (instr->variables[0]->var->data.location == VARYING_SLOT_CLIP_DIST0 &&
2714 is_compact && const_index > 3) {
2715 const_index -= 3;
2716 param++;
2717 }
2718
2719 if (!instr->variables[0]->var->data.patch) {
2720 stride = unpack_param(ctx, ctx->tcs_out_layout, 13, 8);
2721 dw_addr = get_tcs_out_current_patch_offset(ctx);
2722 } else {
2723 dw_addr = get_tcs_out_current_patch_data_offset(ctx);
2724 }
2725
2726 mark_tess_output(ctx, instr->variables[0]->var->data.patch, param);
2727
2728 dw_addr = get_dw_address(ctx, dw_addr, param, const_index, is_compact, vertex_index, stride,
2729 indir_index);
2730 buf_addr = get_tcs_tes_buffer_address_params(ctx, param, const_index, is_compact,
2731 vertex_index, indir_index);
2732
2733 unsigned base = is_compact ? const_index : 0;
2734 for (unsigned chan = 0; chan < 8; chan++) {
2735 bool is_tess_factor = false;
2736 if (!(writemask & (1 << chan)))
2737 continue;
2738 LLVMValueRef value = llvm_extract_elem(ctx, src, chan);
2739
2740 lds_store(ctx, dw_addr, value);
2741
2742 if (instr->variables[0]->var->data.location == VARYING_SLOT_TESS_LEVEL_INNER ||
2743 instr->variables[0]->var->data.location == VARYING_SLOT_TESS_LEVEL_OUTER)
2744 is_tess_factor = true;
2745
2746 if (!is_tess_factor && writemask != 0xF)
2747 ac_build_buffer_store_dword(&ctx->ac, ctx->hs_ring_tess_offchip, value, 1,
2748 buf_addr, ctx->oc_lds,
2749 4 * (base + chan), 1, 0, true, false);
2750
2751 dw_addr = LLVMBuildAdd(ctx->builder, dw_addr,
2752 ctx->i32one, "");
2753 }
2754
2755 if (writemask == 0xF) {
2756 ac_build_buffer_store_dword(&ctx->ac, ctx->hs_ring_tess_offchip, src, 4,
2757 buf_addr, ctx->oc_lds,
2758 (base * 4), 1, 0, true, false);
2759 }
2760 }
2761
2762 static LLVMValueRef
2763 load_tes_input(struct nir_to_llvm_context *ctx,
2764 const nir_intrinsic_instr *instr)
2765 {
2766 LLVMValueRef buf_addr;
2767 LLVMValueRef result;
2768 LLVMValueRef vertex_index = NULL;
2769 LLVMValueRef indir_index = NULL;
2770 unsigned const_index = 0;
2771 unsigned param;
2772 const bool per_vertex = nir_is_per_vertex_io(instr->variables[0]->var, ctx->stage);
2773 const bool is_compact = instr->variables[0]->var->data.compact;
2774
2775 radv_get_deref_offset(ctx, instr->variables[0],
2776 false, NULL, per_vertex ? &vertex_index : NULL,
2777 &const_index, &indir_index);
2778 param = shader_io_get_unique_index(instr->variables[0]->var->data.location);
2779 if (instr->variables[0]->var->data.location == VARYING_SLOT_CLIP_DIST0 &&
2780 is_compact && const_index > 3) {
2781 const_index -= 3;
2782 param++;
2783 }
2784 buf_addr = get_tcs_tes_buffer_address_params(ctx, param, const_index,
2785 is_compact, vertex_index, indir_index);
2786
2787 result = ac_build_buffer_load(&ctx->ac, ctx->hs_ring_tess_offchip, instr->num_components, NULL,
2788 buf_addr, ctx->oc_lds, is_compact ? (4 * const_index) : 0, 1, 0, true, false);
2789 result = trim_vector(ctx, result, instr->num_components);
2790 result = LLVMBuildBitCast(ctx->builder, result, get_def_type(ctx, &instr->dest.ssa), "");
2791 return result;
2792 }
2793
2794 static LLVMValueRef
2795 load_gs_input(struct nir_to_llvm_context *ctx,
2796 nir_intrinsic_instr *instr)
2797 {
2798 LLVMValueRef indir_index, vtx_offset;
2799 unsigned const_index;
2800 LLVMValueRef args[9];
2801 unsigned param, vtx_offset_param;
2802 LLVMValueRef value[4], result;
2803 unsigned vertex_index;
2804 radv_get_deref_offset(ctx, instr->variables[0],
2805 false, &vertex_index, NULL,
2806 &const_index, &indir_index);
2807 vtx_offset_param = vertex_index;
2808 assert(vtx_offset_param < 6);
2809 vtx_offset = LLVMBuildMul(ctx->builder, ctx->gs_vtx_offset[vtx_offset_param],
2810 LLVMConstInt(ctx->i32, 4, false), "");
2811
2812 param = shader_io_get_unique_index(instr->variables[0]->var->data.location);
2813 for (unsigned i = 0; i < instr->num_components; i++) {
2814
2815 args[0] = ctx->esgs_ring;
2816 args[1] = vtx_offset;
2817 args[2] = LLVMConstInt(ctx->i32, (param * 4 + i + const_index) * 256, false);
2818 args[3] = ctx->i32zero;
2819 args[4] = ctx->i32one; /* OFFEN */
2820 args[5] = ctx->i32zero; /* IDXEN */
2821 args[6] = ctx->i32one; /* GLC */
2822 args[7] = ctx->i32zero; /* SLC */
2823 args[8] = ctx->i32zero; /* TFE */
2824
2825 value[i] = ac_build_intrinsic(&ctx->ac, "llvm.SI.buffer.load.dword.i32.i32",
2826 ctx->i32, args, 9,
2827 AC_FUNC_ATTR_READONLY |
2828 AC_FUNC_ATTR_LEGACY);
2829 }
2830 result = ac_build_gather_values(&ctx->ac, value, instr->num_components);
2831
2832 return result;
2833 }
2834
2835 static LLVMValueRef visit_load_var(struct nir_to_llvm_context *ctx,
2836 nir_intrinsic_instr *instr)
2837 {
2838 LLVMValueRef values[8];
2839 int idx = instr->variables[0]->var->data.driver_location;
2840 int ve = instr->dest.ssa.num_components;
2841 LLVMValueRef indir_index;
2842 LLVMValueRef ret;
2843 unsigned const_index;
2844 bool vs_in = ctx->stage == MESA_SHADER_VERTEX &&
2845 instr->variables[0]->var->data.mode == nir_var_shader_in;
2846 radv_get_deref_offset(ctx, instr->variables[0], vs_in, NULL, NULL,
2847 &const_index, &indir_index);
2848
2849 if (instr->dest.ssa.bit_size == 64)
2850 ve *= 2;
2851
2852 switch (instr->variables[0]->var->data.mode) {
2853 case nir_var_shader_in:
2854 if (ctx->stage == MESA_SHADER_TESS_CTRL)
2855 return load_tcs_input(ctx, instr);
2856 if (ctx->stage == MESA_SHADER_TESS_EVAL)
2857 return load_tes_input(ctx, instr);
2858 if (ctx->stage == MESA_SHADER_GEOMETRY) {
2859 return load_gs_input(ctx, instr);
2860 }
2861 for (unsigned chan = 0; chan < ve; chan++) {
2862 if (indir_index) {
2863 unsigned count = glsl_count_attribute_slots(
2864 instr->variables[0]->var->type,
2865 ctx->stage == MESA_SHADER_VERTEX);
2866 count -= chan / 4;
2867 LLVMValueRef tmp_vec = ac_build_gather_values_extended(
2868 &ctx->ac, ctx->inputs + idx + chan, count,
2869 4, false);
2870
2871 values[chan] = LLVMBuildExtractElement(ctx->builder,
2872 tmp_vec,
2873 indir_index, "");
2874 } else
2875 values[chan] = ctx->inputs[idx + chan + const_index * 4];
2876 }
2877 break;
2878 case nir_var_local:
2879 for (unsigned chan = 0; chan < ve; chan++) {
2880 if (indir_index) {
2881 unsigned count = glsl_count_attribute_slots(
2882 instr->variables[0]->var->type, false);
2883 count -= chan / 4;
2884 LLVMValueRef tmp_vec = ac_build_gather_values_extended(
2885 &ctx->ac, ctx->locals + idx + chan, count,
2886 4, true);
2887
2888 values[chan] = LLVMBuildExtractElement(ctx->builder,
2889 tmp_vec,
2890 indir_index, "");
2891 } else {
2892 values[chan] = LLVMBuildLoad(ctx->builder, ctx->locals[idx + chan + const_index * 4], "");
2893 }
2894 }
2895 break;
2896 case nir_var_shader_out:
2897 if (ctx->stage == MESA_SHADER_TESS_CTRL)
2898 return load_tcs_output(ctx, instr);
2899 for (unsigned chan = 0; chan < ve; chan++) {
2900 if (indir_index) {
2901 unsigned count = glsl_count_attribute_slots(
2902 instr->variables[0]->var->type, false);
2903 count -= chan / 4;
2904 LLVMValueRef tmp_vec = ac_build_gather_values_extended(
2905 &ctx->ac, ctx->outputs + idx + chan, count,
2906 4, true);
2907
2908 values[chan] = LLVMBuildExtractElement(ctx->builder,
2909 tmp_vec,
2910 indir_index, "");
2911 } else {
2912 values[chan] = LLVMBuildLoad(ctx->builder,
2913 ctx->outputs[idx + chan + const_index * 4],
2914 "");
2915 }
2916 }
2917 break;
2918 case nir_var_shared: {
2919 LLVMValueRef ptr = get_shared_memory_ptr(ctx, idx, ctx->i32);
2920 LLVMValueRef derived_ptr;
2921
2922 if (indir_index)
2923 indir_index = LLVMBuildMul(ctx->builder, indir_index, LLVMConstInt(ctx->i32, 4, false), "");
2924
2925 for (unsigned chan = 0; chan < ve; chan++) {
2926 LLVMValueRef index = LLVMConstInt(ctx->i32, chan, false);
2927 if (indir_index)
2928 index = LLVMBuildAdd(ctx->builder, index, indir_index, "");
2929 derived_ptr = LLVMBuildGEP(ctx->builder, ptr, &index, 1, "");
2930
2931 values[chan] = LLVMBuildLoad(ctx->builder, derived_ptr, "");
2932 }
2933 break;
2934 }
2935 default:
2936 unreachable("unhandle variable mode");
2937 }
2938 ret = ac_build_gather_values(&ctx->ac, values, ve);
2939 return LLVMBuildBitCast(ctx->builder, ret, get_def_type(ctx, &instr->dest.ssa), "");
2940 }
2941
2942 static void
2943 visit_store_var(struct nir_to_llvm_context *ctx,
2944 nir_intrinsic_instr *instr)
2945 {
2946 LLVMValueRef temp_ptr, value;
2947 int idx = instr->variables[0]->var->data.driver_location;
2948 LLVMValueRef src = to_float(&ctx->ac, get_src(ctx, instr->src[0]));
2949 int writemask = instr->const_index[0];
2950 LLVMValueRef indir_index;
2951 unsigned const_index;
2952 radv_get_deref_offset(ctx, instr->variables[0], false,
2953 NULL, NULL, &const_index, &indir_index);
2954
2955 if (get_elem_bits(&ctx->ac, LLVMTypeOf(src)) == 64) {
2956 int old_writemask = writemask;
2957
2958 src = LLVMBuildBitCast(ctx->builder, src,
2959 LLVMVectorType(ctx->f32, get_llvm_num_components(src) * 2),
2960 "");
2961
2962 writemask = 0;
2963 for (unsigned chan = 0; chan < 4; chan++) {
2964 if (old_writemask & (1 << chan))
2965 writemask |= 3u << (2 * chan);
2966 }
2967 }
2968
2969 switch (instr->variables[0]->var->data.mode) {
2970 case nir_var_shader_out:
2971
2972 if (ctx->stage == MESA_SHADER_TESS_CTRL) {
2973 store_tcs_output(ctx, instr, src, writemask);
2974 return;
2975 }
2976
2977 for (unsigned chan = 0; chan < 8; chan++) {
2978 int stride = 4;
2979 if (!(writemask & (1 << chan)))
2980 continue;
2981
2982 value = llvm_extract_elem(ctx, src, chan);
2983
2984 if (instr->variables[0]->var->data.compact)
2985 stride = 1;
2986 if (indir_index) {
2987 unsigned count = glsl_count_attribute_slots(
2988 instr->variables[0]->var->type, false);
2989 count -= chan / 4;
2990 LLVMValueRef tmp_vec = ac_build_gather_values_extended(
2991 &ctx->ac, ctx->outputs + idx + chan, count,
2992 stride, true);
2993
2994 if (get_llvm_num_components(tmp_vec) > 1) {
2995 tmp_vec = LLVMBuildInsertElement(ctx->builder, tmp_vec,
2996 value, indir_index, "");
2997 } else
2998 tmp_vec = value;
2999 build_store_values_extended(ctx, ctx->outputs + idx + chan,
3000 count, stride, tmp_vec);
3001
3002 } else {
3003 temp_ptr = ctx->outputs[idx + chan + const_index * stride];
3004
3005 LLVMBuildStore(ctx->builder, value, temp_ptr);
3006 }
3007 }
3008 break;
3009 case nir_var_local:
3010 for (unsigned chan = 0; chan < 8; chan++) {
3011 if (!(writemask & (1 << chan)))
3012 continue;
3013
3014 value = llvm_extract_elem(ctx, src, chan);
3015 if (indir_index) {
3016 unsigned count = glsl_count_attribute_slots(
3017 instr->variables[0]->var->type, false);
3018 count -= chan / 4;
3019 LLVMValueRef tmp_vec = ac_build_gather_values_extended(
3020 &ctx->ac, ctx->locals + idx + chan, count,
3021 4, true);
3022
3023 tmp_vec = LLVMBuildInsertElement(ctx->builder, tmp_vec,
3024 value, indir_index, "");
3025 build_store_values_extended(ctx, ctx->locals + idx + chan,
3026 count, 4, tmp_vec);
3027 } else {
3028 temp_ptr = ctx->locals[idx + chan + const_index * 4];
3029
3030 LLVMBuildStore(ctx->builder, value, temp_ptr);
3031 }
3032 }
3033 break;
3034 case nir_var_shared: {
3035 LLVMValueRef ptr = get_shared_memory_ptr(ctx, idx, ctx->i32);
3036
3037 if (indir_index)
3038 indir_index = LLVMBuildMul(ctx->builder, indir_index, LLVMConstInt(ctx->i32, 4, false), "");
3039
3040 for (unsigned chan = 0; chan < 8; chan++) {
3041 if (!(writemask & (1 << chan)))
3042 continue;
3043 LLVMValueRef index = LLVMConstInt(ctx->i32, chan, false);
3044 LLVMValueRef derived_ptr;
3045
3046 if (indir_index)
3047 index = LLVMBuildAdd(ctx->builder, index, indir_index, "");
3048
3049 value = llvm_extract_elem(ctx, src, chan);
3050 derived_ptr = LLVMBuildGEP(ctx->builder, ptr, &index, 1, "");
3051 LLVMBuildStore(ctx->builder,
3052 to_integer(&ctx->ac, value), derived_ptr);
3053 }
3054 break;
3055 }
3056 default:
3057 break;
3058 }
3059 }
3060
3061 static int image_type_to_components_count(enum glsl_sampler_dim dim, bool array)
3062 {
3063 switch (dim) {
3064 case GLSL_SAMPLER_DIM_BUF:
3065 return 1;
3066 case GLSL_SAMPLER_DIM_1D:
3067 return array ? 2 : 1;
3068 case GLSL_SAMPLER_DIM_2D:
3069 return array ? 3 : 2;
3070 case GLSL_SAMPLER_DIM_MS:
3071 return array ? 4 : 3;
3072 case GLSL_SAMPLER_DIM_3D:
3073 case GLSL_SAMPLER_DIM_CUBE:
3074 return 3;
3075 case GLSL_SAMPLER_DIM_RECT:
3076 case GLSL_SAMPLER_DIM_SUBPASS:
3077 return 2;
3078 case GLSL_SAMPLER_DIM_SUBPASS_MS:
3079 return 3;
3080 default:
3081 break;
3082 }
3083 return 0;
3084 }
3085
3086
3087
3088 /* Adjust the sample index according to FMASK.
3089 *
3090 * For uncompressed MSAA surfaces, FMASK should return 0x76543210,
3091 * which is the identity mapping. Each nibble says which physical sample
3092 * should be fetched to get that sample.
3093 *
3094 * For example, 0x11111100 means there are only 2 samples stored and
3095 * the second sample covers 3/4 of the pixel. When reading samples 0
3096 * and 1, return physical sample 0 (determined by the first two 0s
3097 * in FMASK), otherwise return physical sample 1.
3098 *
3099 * The sample index should be adjusted as follows:
3100 * sample_index = (fmask >> (sample_index * 4)) & 0xF;
3101 */
3102 static LLVMValueRef adjust_sample_index_using_fmask(struct nir_to_llvm_context *ctx,
3103 LLVMValueRef coord_x, LLVMValueRef coord_y,
3104 LLVMValueRef coord_z,
3105 LLVMValueRef sample_index,
3106 LLVMValueRef fmask_desc_ptr)
3107 {
3108 LLVMValueRef fmask_load_address[4];
3109 LLVMValueRef res;
3110
3111 fmask_load_address[0] = coord_x;
3112 fmask_load_address[1] = coord_y;
3113 if (coord_z) {
3114 fmask_load_address[2] = coord_z;
3115 fmask_load_address[3] = LLVMGetUndef(ctx->i32);
3116 }
3117
3118 struct ac_image_args args = {0};
3119
3120 args.opcode = ac_image_load;
3121 args.da = coord_z ? true : false;
3122 args.resource = fmask_desc_ptr;
3123 args.dmask = 0xf;
3124 args.addr = ac_build_gather_values(&ctx->ac, fmask_load_address, coord_z ? 4 : 2);
3125
3126 res = ac_build_image_opcode(&ctx->ac, &args);
3127
3128 res = to_integer(&ctx->ac, res);
3129 LLVMValueRef four = LLVMConstInt(ctx->i32, 4, false);
3130 LLVMValueRef F = LLVMConstInt(ctx->i32, 0xf, false);
3131
3132 LLVMValueRef fmask = LLVMBuildExtractElement(ctx->builder,
3133 res,
3134 ctx->i32zero, "");
3135
3136 LLVMValueRef sample_index4 =
3137 LLVMBuildMul(ctx->builder, sample_index, four, "");
3138 LLVMValueRef shifted_fmask =
3139 LLVMBuildLShr(ctx->builder, fmask, sample_index4, "");
3140 LLVMValueRef final_sample =
3141 LLVMBuildAnd(ctx->builder, shifted_fmask, F, "");
3142
3143 /* Don't rewrite the sample index if WORD1.DATA_FORMAT of the FMASK
3144 * resource descriptor is 0 (invalid),
3145 */
3146 LLVMValueRef fmask_desc =
3147 LLVMBuildBitCast(ctx->builder, fmask_desc_ptr,
3148 ctx->v8i32, "");
3149
3150 LLVMValueRef fmask_word1 =
3151 LLVMBuildExtractElement(ctx->builder, fmask_desc,
3152 ctx->i32one, "");
3153
3154 LLVMValueRef word1_is_nonzero =
3155 LLVMBuildICmp(ctx->builder, LLVMIntNE,
3156 fmask_word1, ctx->i32zero, "");
3157
3158 /* Replace the MSAA sample index. */
3159 sample_index =
3160 LLVMBuildSelect(ctx->builder, word1_is_nonzero,
3161 final_sample, sample_index, "");
3162 return sample_index;
3163 }
3164
3165 static LLVMValueRef get_image_coords(struct nir_to_llvm_context *ctx,
3166 const nir_intrinsic_instr *instr)
3167 {
3168 const struct glsl_type *type = instr->variables[0]->var->type;
3169 if(instr->variables[0]->deref.child)
3170 type = instr->variables[0]->deref.child->type;
3171
3172 LLVMValueRef src0 = get_src(ctx, instr->src[0]);
3173 LLVMValueRef coords[4];
3174 LLVMValueRef masks[] = {
3175 LLVMConstInt(ctx->i32, 0, false), LLVMConstInt(ctx->i32, 1, false),
3176 LLVMConstInt(ctx->i32, 2, false), LLVMConstInt(ctx->i32, 3, false),
3177 };
3178 LLVMValueRef res;
3179 LLVMValueRef sample_index = llvm_extract_elem(ctx, get_src(ctx, instr->src[1]), 0);
3180
3181 int count;
3182 enum glsl_sampler_dim dim = glsl_get_sampler_dim(type);
3183 bool add_frag_pos = (dim == GLSL_SAMPLER_DIM_SUBPASS ||
3184 dim == GLSL_SAMPLER_DIM_SUBPASS_MS);
3185 bool is_ms = (dim == GLSL_SAMPLER_DIM_MS ||
3186 dim == GLSL_SAMPLER_DIM_SUBPASS_MS);
3187
3188 count = image_type_to_components_count(dim,
3189 glsl_sampler_type_is_array(type));
3190
3191 if (is_ms) {
3192 LLVMValueRef fmask_load_address[3];
3193 int chan;
3194
3195 fmask_load_address[0] = LLVMBuildExtractElement(ctx->builder, src0, masks[0], "");
3196 fmask_load_address[1] = LLVMBuildExtractElement(ctx->builder, src0, masks[1], "");
3197 if (glsl_sampler_type_is_array(type))
3198 fmask_load_address[2] = LLVMBuildExtractElement(ctx->builder, src0, masks[2], "");
3199 else
3200 fmask_load_address[2] = NULL;
3201 if (add_frag_pos) {
3202 for (chan = 0; chan < 2; ++chan)
3203 fmask_load_address[chan] = LLVMBuildAdd(ctx->builder, fmask_load_address[chan], LLVMBuildFPToUI(ctx->builder, ctx->frag_pos[chan], ctx->i32, ""), "");
3204 }
3205 sample_index = adjust_sample_index_using_fmask(ctx,
3206 fmask_load_address[0],
3207 fmask_load_address[1],
3208 fmask_load_address[2],
3209 sample_index,
3210 get_sampler_desc(ctx, instr->variables[0], DESC_FMASK));
3211 }
3212 if (count == 1) {
3213 if (instr->src[0].ssa->num_components)
3214 res = LLVMBuildExtractElement(ctx->builder, src0, masks[0], "");
3215 else
3216 res = src0;
3217 } else {
3218 int chan;
3219 if (is_ms)
3220 count--;
3221 for (chan = 0; chan < count; ++chan) {
3222 coords[chan] = LLVMBuildExtractElement(ctx->builder, src0, masks[chan], "");
3223 }
3224
3225 if (add_frag_pos) {
3226 for (chan = 0; chan < count; ++chan)
3227 coords[chan] = LLVMBuildAdd(ctx->builder, coords[chan], LLVMBuildFPToUI(ctx->builder, ctx->frag_pos[chan], ctx->i32, ""), "");
3228 }
3229 if (is_ms) {
3230 coords[count] = sample_index;
3231 count++;
3232 }
3233
3234 if (count == 3) {
3235 coords[3] = LLVMGetUndef(ctx->i32);
3236 count = 4;
3237 }
3238 res = ac_build_gather_values(&ctx->ac, coords, count);
3239 }
3240 return res;
3241 }
3242
3243 static LLVMValueRef visit_image_load(struct nir_to_llvm_context *ctx,
3244 const nir_intrinsic_instr *instr)
3245 {
3246 LLVMValueRef params[7];
3247 LLVMValueRef res;
3248 char intrinsic_name[64];
3249 const nir_variable *var = instr->variables[0]->var;
3250 const struct glsl_type *type = var->type;
3251 if(instr->variables[0]->deref.child)
3252 type = instr->variables[0]->deref.child->type;
3253
3254 type = glsl_without_array(type);
3255 if (glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_BUF) {
3256 params[0] = get_sampler_desc(ctx, instr->variables[0], DESC_BUFFER);
3257 params[1] = LLVMBuildExtractElement(ctx->builder, get_src(ctx, instr->src[0]),
3258 LLVMConstInt(ctx->i32, 0, false), ""); /* vindex */
3259 params[2] = LLVMConstInt(ctx->i32, 0, false); /* voffset */
3260 params[3] = ctx->i1false; /* glc */
3261 params[4] = ctx->i1false; /* slc */
3262 res = ac_build_intrinsic(&ctx->ac, "llvm.amdgcn.buffer.load.format.v4f32", ctx->v4f32,
3263 params, 5, 0);
3264
3265 res = trim_vector(ctx, res, instr->dest.ssa.num_components);
3266 res = to_integer(&ctx->ac, res);
3267 } else {
3268 bool is_da = glsl_sampler_type_is_array(type) ||
3269 glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_CUBE;
3270 LLVMValueRef da = is_da ? ctx->i1true : ctx->i1false;
3271 LLVMValueRef glc = ctx->i1false;
3272 LLVMValueRef slc = ctx->i1false;
3273
3274 params[0] = get_image_coords(ctx, instr);
3275 params[1] = get_sampler_desc(ctx, instr->variables[0], DESC_IMAGE);
3276 params[2] = LLVMConstInt(ctx->i32, 15, false); /* dmask */
3277 if (HAVE_LLVM <= 0x0309) {
3278 params[3] = ctx->i1false; /* r128 */
3279 params[4] = da;
3280 params[5] = glc;
3281 params[6] = slc;
3282 } else {
3283 LLVMValueRef lwe = ctx->i1false;
3284 params[3] = glc;
3285 params[4] = slc;
3286 params[5] = lwe;
3287 params[6] = da;
3288 }
3289
3290 ac_get_image_intr_name("llvm.amdgcn.image.load",
3291 ctx->v4f32, /* vdata */
3292 LLVMTypeOf(params[0]), /* coords */
3293 LLVMTypeOf(params[1]), /* rsrc */
3294 intrinsic_name, sizeof(intrinsic_name));
3295
3296 res = ac_build_intrinsic(&ctx->ac, intrinsic_name, ctx->v4f32,
3297 params, 7, AC_FUNC_ATTR_READONLY);
3298 }
3299 return to_integer(&ctx->ac, res);
3300 }
3301
3302 static void visit_image_store(struct nir_to_llvm_context *ctx,
3303 nir_intrinsic_instr *instr)
3304 {
3305 LLVMValueRef params[8];
3306 char intrinsic_name[64];
3307 const nir_variable *var = instr->variables[0]->var;
3308 const struct glsl_type *type = glsl_without_array(var->type);
3309
3310 if (ctx->stage == MESA_SHADER_FRAGMENT)
3311 ctx->shader_info->fs.writes_memory = true;
3312
3313 if (glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_BUF) {
3314 params[0] = to_float(&ctx->ac, get_src(ctx, instr->src[2])); /* data */
3315 params[1] = get_sampler_desc(ctx, instr->variables[0], DESC_BUFFER);
3316 params[2] = LLVMBuildExtractElement(ctx->builder, get_src(ctx, instr->src[0]),
3317 LLVMConstInt(ctx->i32, 0, false), ""); /* vindex */
3318 params[3] = LLVMConstInt(ctx->i32, 0, false); /* voffset */
3319 params[4] = ctx->i1false; /* glc */
3320 params[5] = ctx->i1false; /* slc */
3321 ac_build_intrinsic(&ctx->ac, "llvm.amdgcn.buffer.store.format.v4f32", ctx->voidt,
3322 params, 6, 0);
3323 } else {
3324 bool is_da = glsl_sampler_type_is_array(type) ||
3325 glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_CUBE;
3326 LLVMValueRef da = is_da ? ctx->i1true : ctx->i1false;
3327 LLVMValueRef glc = ctx->i1false;
3328 LLVMValueRef slc = ctx->i1false;
3329
3330 params[0] = to_float(&ctx->ac, get_src(ctx, instr->src[2]));
3331 params[1] = get_image_coords(ctx, instr); /* coords */
3332 params[2] = get_sampler_desc(ctx, instr->variables[0], DESC_IMAGE);
3333 params[3] = LLVMConstInt(ctx->i32, 15, false); /* dmask */
3334 if (HAVE_LLVM <= 0x0309) {
3335 params[4] = ctx->i1false; /* r128 */
3336 params[5] = da;
3337 params[6] = glc;
3338 params[7] = slc;
3339 } else {
3340 LLVMValueRef lwe = ctx->i1false;
3341 params[4] = glc;
3342 params[5] = slc;
3343 params[6] = lwe;
3344 params[7] = da;
3345 }
3346
3347 ac_get_image_intr_name("llvm.amdgcn.image.store",
3348 LLVMTypeOf(params[0]), /* vdata */
3349 LLVMTypeOf(params[1]), /* coords */
3350 LLVMTypeOf(params[2]), /* rsrc */
3351 intrinsic_name, sizeof(intrinsic_name));
3352
3353 ac_build_intrinsic(&ctx->ac, intrinsic_name, ctx->voidt,
3354 params, 8, 0);
3355 }
3356
3357 }
3358
3359 static LLVMValueRef visit_image_atomic(struct nir_to_llvm_context *ctx,
3360 const nir_intrinsic_instr *instr)
3361 {
3362 LLVMValueRef params[6];
3363 int param_count = 0;
3364 const nir_variable *var = instr->variables[0]->var;
3365
3366 const char *base_name = "llvm.amdgcn.image.atomic";
3367 const char *atomic_name;
3368 LLVMValueRef coords;
3369 char intrinsic_name[32], coords_type[8];
3370 const struct glsl_type *type = glsl_without_array(var->type);
3371
3372 if (ctx->stage == MESA_SHADER_FRAGMENT)
3373 ctx->shader_info->fs.writes_memory = true;
3374
3375 params[param_count++] = get_src(ctx, instr->src[2]);
3376 if (instr->intrinsic == nir_intrinsic_image_atomic_comp_swap)
3377 params[param_count++] = get_src(ctx, instr->src[3]);
3378
3379 if (glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_BUF) {
3380 params[param_count++] = get_sampler_desc(ctx, instr->variables[0], DESC_BUFFER);
3381 coords = params[param_count++] = LLVMBuildExtractElement(ctx->builder, get_src(ctx, instr->src[0]),
3382 LLVMConstInt(ctx->i32, 0, false), ""); /* vindex */
3383 params[param_count++] = ctx->i32zero; /* voffset */
3384 params[param_count++] = ctx->i1false; /* glc */
3385 params[param_count++] = ctx->i1false; /* slc */
3386 } else {
3387 bool da = glsl_sampler_type_is_array(type) ||
3388 glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_CUBE;
3389
3390 coords = params[param_count++] = get_image_coords(ctx, instr);
3391 params[param_count++] = get_sampler_desc(ctx, instr->variables[0], DESC_IMAGE);
3392 params[param_count++] = ctx->i1false; /* r128 */
3393 params[param_count++] = da ? ctx->i1true : ctx->i1false; /* da */
3394 params[param_count++] = ctx->i1false; /* slc */
3395 }
3396
3397 switch (instr->intrinsic) {
3398 case nir_intrinsic_image_atomic_add:
3399 atomic_name = "add";
3400 break;
3401 case nir_intrinsic_image_atomic_min:
3402 atomic_name = "smin";
3403 break;
3404 case nir_intrinsic_image_atomic_max:
3405 atomic_name = "smax";
3406 break;
3407 case nir_intrinsic_image_atomic_and:
3408 atomic_name = "and";
3409 break;
3410 case nir_intrinsic_image_atomic_or:
3411 atomic_name = "or";
3412 break;
3413 case nir_intrinsic_image_atomic_xor:
3414 atomic_name = "xor";
3415 break;
3416 case nir_intrinsic_image_atomic_exchange:
3417 atomic_name = "swap";
3418 break;
3419 case nir_intrinsic_image_atomic_comp_swap:
3420 atomic_name = "cmpswap";
3421 break;
3422 default:
3423 abort();
3424 }
3425 build_int_type_name(LLVMTypeOf(coords),
3426 coords_type, sizeof(coords_type));
3427
3428 snprintf(intrinsic_name, sizeof(intrinsic_name),
3429 "%s.%s.%s", base_name, atomic_name, coords_type);
3430 return ac_build_intrinsic(&ctx->ac, intrinsic_name, ctx->i32, params, param_count, 0);
3431 }
3432
3433 static LLVMValueRef visit_image_size(struct nir_to_llvm_context *ctx,
3434 const nir_intrinsic_instr *instr)
3435 {
3436 LLVMValueRef res;
3437 const nir_variable *var = instr->variables[0]->var;
3438 const struct glsl_type *type = instr->variables[0]->var->type;
3439 bool da = glsl_sampler_type_is_array(var->type) ||
3440 glsl_get_sampler_dim(var->type) == GLSL_SAMPLER_DIM_CUBE;
3441 if(instr->variables[0]->deref.child)
3442 type = instr->variables[0]->deref.child->type;
3443
3444 if (glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_BUF)
3445 return get_buffer_size(ctx, get_sampler_desc(ctx, instr->variables[0], DESC_BUFFER), true);
3446
3447 struct ac_image_args args = { 0 };
3448
3449 args.da = da;
3450 args.dmask = 0xf;
3451 args.resource = get_sampler_desc(ctx, instr->variables[0], DESC_IMAGE);
3452 args.opcode = ac_image_get_resinfo;
3453 args.addr = ctx->i32zero;
3454
3455 res = ac_build_image_opcode(&ctx->ac, &args);
3456
3457 if (glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_CUBE &&
3458 glsl_sampler_type_is_array(type)) {
3459 LLVMValueRef two = LLVMConstInt(ctx->i32, 2, false);
3460 LLVMValueRef six = LLVMConstInt(ctx->i32, 6, false);
3461 LLVMValueRef z = LLVMBuildExtractElement(ctx->builder, res, two, "");
3462 z = LLVMBuildSDiv(ctx->builder, z, six, "");
3463 res = LLVMBuildInsertElement(ctx->builder, res, z, two, "");
3464 }
3465 return res;
3466 }
3467
3468 #define NOOP_WAITCNT 0xf7f
3469 #define LGKM_CNT 0x07f
3470 #define VM_CNT 0xf70
3471
3472 static void emit_waitcnt(struct nir_to_llvm_context *ctx,
3473 unsigned simm16)
3474 {
3475 LLVMValueRef args[1] = {
3476 LLVMConstInt(ctx->i32, simm16, false),
3477 };
3478 ac_build_intrinsic(&ctx->ac, "llvm.amdgcn.s.waitcnt",
3479 ctx->voidt, args, 1, 0);
3480 }
3481
3482 static void emit_barrier(struct nir_to_llvm_context *ctx)
3483 {
3484 /* SI only (thanks to a hw bug workaround):
3485 * The real barrier instruction isn’t needed, because an entire patch
3486 * always fits into a single wave.
3487 */
3488 if (ctx->options->chip_class == SI &&
3489 ctx->stage == MESA_SHADER_TESS_CTRL) {
3490 emit_waitcnt(ctx, LGKM_CNT & VM_CNT);
3491 return;
3492 }
3493 ac_build_intrinsic(&ctx->ac, "llvm.amdgcn.s.barrier",
3494 ctx->voidt, NULL, 0, AC_FUNC_ATTR_CONVERGENT);
3495 }
3496
3497 static void emit_discard_if(struct nir_to_llvm_context *ctx,
3498 const nir_intrinsic_instr *instr)
3499 {
3500 LLVMValueRef cond;
3501 ctx->shader_info->fs.can_discard = true;
3502
3503 cond = LLVMBuildICmp(ctx->builder, LLVMIntNE,
3504 get_src(ctx, instr->src[0]),
3505 ctx->i32zero, "");
3506
3507 cond = LLVMBuildSelect(ctx->builder, cond,
3508 LLVMConstReal(ctx->f32, -1.0f),
3509 ctx->f32zero, "");
3510 ac_build_kill(&ctx->ac, cond);
3511 }
3512
3513 static LLVMValueRef
3514 visit_load_local_invocation_index(struct nir_to_llvm_context *ctx)
3515 {
3516 LLVMValueRef result;
3517 LLVMValueRef thread_id = ac_get_thread_id(&ctx->ac);
3518 result = LLVMBuildAnd(ctx->builder, ctx->tg_size,
3519 LLVMConstInt(ctx->i32, 0xfc0, false), "");
3520
3521 return LLVMBuildAdd(ctx->builder, result, thread_id, "");
3522 }
3523
3524 static LLVMValueRef visit_var_atomic(struct nir_to_llvm_context *ctx,
3525 const nir_intrinsic_instr *instr)
3526 {
3527 LLVMValueRef ptr, result;
3528 int idx = instr->variables[0]->var->data.driver_location;
3529 LLVMValueRef src = get_src(ctx, instr->src[0]);
3530 ptr = get_shared_memory_ptr(ctx, idx, ctx->i32);
3531
3532 if (instr->intrinsic == nir_intrinsic_var_atomic_comp_swap) {
3533 LLVMValueRef src1 = get_src(ctx, instr->src[1]);
3534 result = LLVMBuildAtomicCmpXchg(ctx->builder,
3535 ptr, src, src1,
3536 LLVMAtomicOrderingSequentiallyConsistent,
3537 LLVMAtomicOrderingSequentiallyConsistent,
3538 false);
3539 } else {
3540 LLVMAtomicRMWBinOp op;
3541 switch (instr->intrinsic) {
3542 case nir_intrinsic_var_atomic_add:
3543 op = LLVMAtomicRMWBinOpAdd;
3544 break;
3545 case nir_intrinsic_var_atomic_umin:
3546 op = LLVMAtomicRMWBinOpUMin;
3547 break;
3548 case nir_intrinsic_var_atomic_umax:
3549 op = LLVMAtomicRMWBinOpUMax;
3550 break;
3551 case nir_intrinsic_var_atomic_imin:
3552 op = LLVMAtomicRMWBinOpMin;
3553 break;
3554 case nir_intrinsic_var_atomic_imax:
3555 op = LLVMAtomicRMWBinOpMax;
3556 break;
3557 case nir_intrinsic_var_atomic_and:
3558 op = LLVMAtomicRMWBinOpAnd;
3559 break;
3560 case nir_intrinsic_var_atomic_or:
3561 op = LLVMAtomicRMWBinOpOr;
3562 break;
3563 case nir_intrinsic_var_atomic_xor:
3564 op = LLVMAtomicRMWBinOpXor;
3565 break;
3566 case nir_intrinsic_var_atomic_exchange:
3567 op = LLVMAtomicRMWBinOpXchg;
3568 break;
3569 default:
3570 return NULL;
3571 }
3572
3573 result = LLVMBuildAtomicRMW(ctx->builder, op, ptr, to_integer(&ctx->ac, src),
3574 LLVMAtomicOrderingSequentiallyConsistent,
3575 false);
3576 }
3577 return result;
3578 }
3579
3580 #define INTERP_CENTER 0
3581 #define INTERP_CENTROID 1
3582 #define INTERP_SAMPLE 2
3583
3584 static LLVMValueRef lookup_interp_param(struct nir_to_llvm_context *ctx,
3585 enum glsl_interp_mode interp, unsigned location)
3586 {
3587 switch (interp) {
3588 case INTERP_MODE_FLAT:
3589 default:
3590 return NULL;
3591 case INTERP_MODE_SMOOTH:
3592 case INTERP_MODE_NONE:
3593 if (location == INTERP_CENTER)
3594 return ctx->persp_center;
3595 else if (location == INTERP_CENTROID)
3596 return ctx->persp_centroid;
3597 else if (location == INTERP_SAMPLE)
3598 return ctx->persp_sample;
3599 break;
3600 case INTERP_MODE_NOPERSPECTIVE:
3601 if (location == INTERP_CENTER)
3602 return ctx->linear_center;
3603 else if (location == INTERP_CENTROID)
3604 return ctx->linear_centroid;
3605 else if (location == INTERP_SAMPLE)
3606 return ctx->linear_sample;
3607 break;
3608 }
3609 return NULL;
3610 }
3611
3612 static LLVMValueRef load_sample_position(struct nir_to_llvm_context *ctx,
3613 LLVMValueRef sample_id)
3614 {
3615 LLVMValueRef result;
3616 LLVMValueRef ptr = ac_build_gep0(&ctx->ac, ctx->ring_offsets, LLVMConstInt(ctx->i32, RING_PS_SAMPLE_POSITIONS, false));
3617
3618 ptr = LLVMBuildBitCast(ctx->builder, ptr,
3619 const_array(ctx->v2f32, 64), "");
3620
3621 sample_id = LLVMBuildAdd(ctx->builder, sample_id, ctx->sample_pos_offset, "");
3622 result = ac_build_indexed_load(&ctx->ac, ptr, sample_id, false);
3623
3624 return result;
3625 }
3626
3627 static LLVMValueRef load_sample_pos(struct nir_to_llvm_context *ctx)
3628 {
3629 LLVMValueRef values[2];
3630
3631 values[0] = emit_ffract(ctx, ctx->frag_pos[0]);
3632 values[1] = emit_ffract(ctx, ctx->frag_pos[1]);
3633 return ac_build_gather_values(&ctx->ac, values, 2);
3634 }
3635
3636 static LLVMValueRef visit_interp(struct nir_to_llvm_context *ctx,
3637 const nir_intrinsic_instr *instr)
3638 {
3639 LLVMValueRef result[2];
3640 LLVMValueRef interp_param, attr_number;
3641 unsigned location;
3642 unsigned chan;
3643 LLVMValueRef src_c0, src_c1;
3644 LLVMValueRef src0;
3645 int input_index = instr->variables[0]->var->data.location - VARYING_SLOT_VAR0;
3646 switch (instr->intrinsic) {
3647 case nir_intrinsic_interp_var_at_centroid:
3648 location = INTERP_CENTROID;
3649 break;
3650 case nir_intrinsic_interp_var_at_sample:
3651 case nir_intrinsic_interp_var_at_offset:
3652 location = INTERP_CENTER;
3653 src0 = get_src(ctx, instr->src[0]);
3654 break;
3655 default:
3656 break;
3657 }
3658
3659 if (instr->intrinsic == nir_intrinsic_interp_var_at_offset) {
3660 src_c0 = to_float(&ctx->ac, LLVMBuildExtractElement(ctx->builder, src0, ctx->i32zero, ""));
3661 src_c1 = to_float(&ctx->ac, LLVMBuildExtractElement(ctx->builder, src0, ctx->i32one, ""));
3662 } else if (instr->intrinsic == nir_intrinsic_interp_var_at_sample) {
3663 LLVMValueRef sample_position;
3664 LLVMValueRef halfval = LLVMConstReal(ctx->f32, 0.5f);
3665
3666 /* fetch sample ID */
3667 sample_position = load_sample_position(ctx, src0);
3668
3669 src_c0 = LLVMBuildExtractElement(ctx->builder, sample_position, ctx->i32zero, "");
3670 src_c0 = LLVMBuildFSub(ctx->builder, src_c0, halfval, "");
3671 src_c1 = LLVMBuildExtractElement(ctx->builder, sample_position, ctx->i32one, "");
3672 src_c1 = LLVMBuildFSub(ctx->builder, src_c1, halfval, "");
3673 }
3674 interp_param = lookup_interp_param(ctx, instr->variables[0]->var->data.interpolation, location);
3675 attr_number = LLVMConstInt(ctx->i32, input_index, false);
3676
3677 if (location == INTERP_SAMPLE || location == INTERP_CENTER) {
3678 LLVMValueRef ij_out[2];
3679 LLVMValueRef ddxy_out = emit_ddxy_interp(ctx, interp_param);
3680
3681 /*
3682 * take the I then J parameters, and the DDX/Y for it, and
3683 * calculate the IJ inputs for the interpolator.
3684 * temp1 = ddx * offset/sample.x + I;
3685 * interp_param.I = ddy * offset/sample.y + temp1;
3686 * temp1 = ddx * offset/sample.x + J;
3687 * interp_param.J = ddy * offset/sample.y + temp1;
3688 */
3689 for (unsigned i = 0; i < 2; i++) {
3690 LLVMValueRef ix_ll = LLVMConstInt(ctx->i32, i, false);
3691 LLVMValueRef iy_ll = LLVMConstInt(ctx->i32, i + 2, false);
3692 LLVMValueRef ddx_el = LLVMBuildExtractElement(ctx->builder,
3693 ddxy_out, ix_ll, "");
3694 LLVMValueRef ddy_el = LLVMBuildExtractElement(ctx->builder,
3695 ddxy_out, iy_ll, "");
3696 LLVMValueRef interp_el = LLVMBuildExtractElement(ctx->builder,
3697 interp_param, ix_ll, "");
3698 LLVMValueRef temp1, temp2;
3699
3700 interp_el = LLVMBuildBitCast(ctx->builder, interp_el,
3701 ctx->f32, "");
3702
3703 temp1 = LLVMBuildFMul(ctx->builder, ddx_el, src_c0, "");
3704 temp1 = LLVMBuildFAdd(ctx->builder, temp1, interp_el, "");
3705
3706 temp2 = LLVMBuildFMul(ctx->builder, ddy_el, src_c1, "");
3707 temp2 = LLVMBuildFAdd(ctx->builder, temp2, temp1, "");
3708
3709 ij_out[i] = LLVMBuildBitCast(ctx->builder,
3710 temp2, ctx->i32, "");
3711 }
3712 interp_param = ac_build_gather_values(&ctx->ac, ij_out, 2);
3713
3714 }
3715
3716 for (chan = 0; chan < 2; chan++) {
3717 LLVMValueRef llvm_chan = LLVMConstInt(ctx->i32, chan, false);
3718
3719 if (interp_param) {
3720 interp_param = LLVMBuildBitCast(ctx->builder,
3721 interp_param, LLVMVectorType(ctx->f32, 2), "");
3722 LLVMValueRef i = LLVMBuildExtractElement(
3723 ctx->builder, interp_param, ctx->i32zero, "");
3724 LLVMValueRef j = LLVMBuildExtractElement(
3725 ctx->builder, interp_param, ctx->i32one, "");
3726
3727 result[chan] = ac_build_fs_interp(&ctx->ac,
3728 llvm_chan, attr_number,
3729 ctx->prim_mask, i, j);
3730 } else {
3731 result[chan] = ac_build_fs_interp_mov(&ctx->ac,
3732 LLVMConstInt(ctx->i32, 2, false),
3733 llvm_chan, attr_number,
3734 ctx->prim_mask);
3735 }
3736 }
3737 return ac_build_gather_values(&ctx->ac, result, 2);
3738 }
3739
3740 static void
3741 visit_emit_vertex(struct nir_to_llvm_context *ctx,
3742 const nir_intrinsic_instr *instr)
3743 {
3744 LLVMValueRef gs_next_vertex;
3745 LLVMValueRef can_emit, kill;
3746 int idx;
3747
3748 assert(instr->const_index[0] == 0);
3749 /* Write vertex attribute values to GSVS ring */
3750 gs_next_vertex = LLVMBuildLoad(ctx->builder,
3751 ctx->gs_next_vertex,
3752 "");
3753
3754 /* If this thread has already emitted the declared maximum number of
3755 * vertices, kill it: excessive vertex emissions are not supposed to
3756 * have any effect, and GS threads have no externally observable
3757 * effects other than emitting vertices.
3758 */
3759 can_emit = LLVMBuildICmp(ctx->builder, LLVMIntULT, gs_next_vertex,
3760 LLVMConstInt(ctx->i32, ctx->gs_max_out_vertices, false), "");
3761
3762 kill = LLVMBuildSelect(ctx->builder, can_emit,
3763 LLVMConstReal(ctx->f32, 1.0f),
3764 LLVMConstReal(ctx->f32, -1.0f), "");
3765 ac_build_kill(&ctx->ac, kill);
3766
3767 /* loop num outputs */
3768 idx = 0;
3769 for (unsigned i = 0; i < RADEON_LLVM_MAX_OUTPUTS; ++i) {
3770 LLVMValueRef *out_ptr = &ctx->outputs[i * 4];
3771 int length = 4;
3772 int slot = idx;
3773 int slot_inc = 1;
3774
3775 if (!(ctx->output_mask & (1ull << i)))
3776 continue;
3777
3778 if (i == VARYING_SLOT_CLIP_DIST0) {
3779 /* pack clip and cull into a single set of slots */
3780 length = ctx->num_output_clips + ctx->num_output_culls;
3781 if (length > 4)
3782 slot_inc = 2;
3783 }
3784 for (unsigned j = 0; j < length; j++) {
3785 LLVMValueRef out_val = LLVMBuildLoad(ctx->builder,
3786 out_ptr[j], "");
3787 LLVMValueRef voffset = LLVMConstInt(ctx->i32, (slot * 4 + j) * ctx->gs_max_out_vertices, false);
3788 voffset = LLVMBuildAdd(ctx->builder, voffset, gs_next_vertex, "");
3789 voffset = LLVMBuildMul(ctx->builder, voffset, LLVMConstInt(ctx->i32, 4, false), "");
3790
3791 out_val = LLVMBuildBitCast(ctx->builder, out_val, ctx->i32, "");
3792
3793 ac_build_buffer_store_dword(&ctx->ac, ctx->gsvs_ring,
3794 out_val, 1,
3795 voffset, ctx->gs2vs_offset, 0,
3796 1, 1, true, true);
3797 }
3798 idx += slot_inc;
3799 }
3800
3801 gs_next_vertex = LLVMBuildAdd(ctx->builder, gs_next_vertex,
3802 ctx->i32one, "");
3803 LLVMBuildStore(ctx->builder, gs_next_vertex, ctx->gs_next_vertex);
3804
3805 ac_build_sendmsg(&ctx->ac, AC_SENDMSG_GS_OP_EMIT | AC_SENDMSG_GS | (0 << 8), ctx->gs_wave_id);
3806 }
3807
3808 static void
3809 visit_end_primitive(struct nir_to_llvm_context *ctx,
3810 const nir_intrinsic_instr *instr)
3811 {
3812 ac_build_sendmsg(&ctx->ac, AC_SENDMSG_GS_OP_CUT | AC_SENDMSG_GS | (0 << 8), ctx->gs_wave_id);
3813 }
3814
3815 static LLVMValueRef
3816 visit_load_tess_coord(struct nir_to_llvm_context *ctx,
3817 const nir_intrinsic_instr *instr)
3818 {
3819 LLVMValueRef coord[4] = {
3820 ctx->tes_u,
3821 ctx->tes_v,
3822 ctx->f32zero,
3823 ctx->f32zero,
3824 };
3825
3826 if (ctx->tes_primitive_mode == GL_TRIANGLES)
3827 coord[2] = LLVMBuildFSub(ctx->builder, ctx->f32one,
3828 LLVMBuildFAdd(ctx->builder, coord[0], coord[1], ""), "");
3829
3830 LLVMValueRef result = ac_build_gather_values(&ctx->ac, coord, instr->num_components);
3831 return LLVMBuildBitCast(ctx->builder, result,
3832 get_def_type(ctx, &instr->dest.ssa), "");
3833 }
3834
3835 static void visit_intrinsic(struct nir_to_llvm_context *ctx,
3836 nir_intrinsic_instr *instr)
3837 {
3838 LLVMValueRef result = NULL;
3839
3840 switch (instr->intrinsic) {
3841 case nir_intrinsic_load_work_group_id: {
3842 result = ctx->workgroup_ids;
3843 break;
3844 }
3845 case nir_intrinsic_load_base_vertex: {
3846 result = ctx->base_vertex;
3847 break;
3848 }
3849 case nir_intrinsic_load_vertex_id_zero_base: {
3850 result = ctx->vertex_id;
3851 break;
3852 }
3853 case nir_intrinsic_load_local_invocation_id: {
3854 result = ctx->local_invocation_ids;
3855 break;
3856 }
3857 case nir_intrinsic_load_base_instance:
3858 result = ctx->start_instance;
3859 break;
3860 case nir_intrinsic_load_draw_id:
3861 result = ctx->draw_index;
3862 break;
3863 case nir_intrinsic_load_invocation_id:
3864 if (ctx->stage == MESA_SHADER_TESS_CTRL)
3865 result = unpack_param(ctx, ctx->tcs_rel_ids, 8, 5);
3866 else
3867 result = ctx->gs_invocation_id;
3868 break;
3869 case nir_intrinsic_load_primitive_id:
3870 if (ctx->stage == MESA_SHADER_GEOMETRY) {
3871 ctx->shader_info->gs.uses_prim_id = true;
3872 result = ctx->gs_prim_id;
3873 } else if (ctx->stage == MESA_SHADER_TESS_CTRL) {
3874 ctx->shader_info->tcs.uses_prim_id = true;
3875 result = ctx->tcs_patch_id;
3876 } else if (ctx->stage == MESA_SHADER_TESS_EVAL) {
3877 ctx->shader_info->tcs.uses_prim_id = true;
3878 result = ctx->tes_patch_id;
3879 } else
3880 fprintf(stderr, "Unknown primitive id intrinsic: %d", ctx->stage);
3881 break;
3882 case nir_intrinsic_load_sample_id:
3883 ctx->shader_info->fs.force_persample = true;
3884 result = unpack_param(ctx, ctx->ancillary, 8, 4);
3885 break;
3886 case nir_intrinsic_load_sample_pos:
3887 ctx->shader_info->fs.force_persample = true;
3888 result = load_sample_pos(ctx);
3889 break;
3890 case nir_intrinsic_load_sample_mask_in:
3891 result = ctx->sample_coverage;
3892 break;
3893 case nir_intrinsic_load_front_face:
3894 result = ctx->front_face;
3895 break;
3896 case nir_intrinsic_load_instance_id:
3897 result = ctx->instance_id;
3898 ctx->shader_info->vs.vgpr_comp_cnt = MAX2(3,
3899 ctx->shader_info->vs.vgpr_comp_cnt);
3900 break;
3901 case nir_intrinsic_load_num_work_groups:
3902 result = ctx->num_work_groups;
3903 break;
3904 case nir_intrinsic_load_local_invocation_index:
3905 result = visit_load_local_invocation_index(ctx);
3906 break;
3907 case nir_intrinsic_load_push_constant:
3908 result = visit_load_push_constant(ctx, instr);
3909 break;
3910 case nir_intrinsic_vulkan_resource_index:
3911 result = visit_vulkan_resource_index(ctx, instr);
3912 break;
3913 case nir_intrinsic_store_ssbo:
3914 visit_store_ssbo(ctx, instr);
3915 break;
3916 case nir_intrinsic_load_ssbo:
3917 result = visit_load_buffer(ctx, instr);
3918 break;
3919 case nir_intrinsic_ssbo_atomic_add:
3920 case nir_intrinsic_ssbo_atomic_imin:
3921 case nir_intrinsic_ssbo_atomic_umin:
3922 case nir_intrinsic_ssbo_atomic_imax:
3923 case nir_intrinsic_ssbo_atomic_umax:
3924 case nir_intrinsic_ssbo_atomic_and:
3925 case nir_intrinsic_ssbo_atomic_or:
3926 case nir_intrinsic_ssbo_atomic_xor:
3927 case nir_intrinsic_ssbo_atomic_exchange:
3928 case nir_intrinsic_ssbo_atomic_comp_swap:
3929 result = visit_atomic_ssbo(ctx, instr);
3930 break;
3931 case nir_intrinsic_load_ubo:
3932 result = visit_load_ubo_buffer(ctx, instr);
3933 break;
3934 case nir_intrinsic_get_buffer_size:
3935 result = visit_get_buffer_size(ctx, instr);
3936 break;
3937 case nir_intrinsic_load_var:
3938 result = visit_load_var(ctx, instr);
3939 break;
3940 case nir_intrinsic_store_var:
3941 visit_store_var(ctx, instr);
3942 break;
3943 case nir_intrinsic_image_load:
3944 result = visit_image_load(ctx, instr);
3945 break;
3946 case nir_intrinsic_image_store:
3947 visit_image_store(ctx, instr);
3948 break;
3949 case nir_intrinsic_image_atomic_add:
3950 case nir_intrinsic_image_atomic_min:
3951 case nir_intrinsic_image_atomic_max:
3952 case nir_intrinsic_image_atomic_and:
3953 case nir_intrinsic_image_atomic_or:
3954 case nir_intrinsic_image_atomic_xor:
3955 case nir_intrinsic_image_atomic_exchange:
3956 case nir_intrinsic_image_atomic_comp_swap:
3957 result = visit_image_atomic(ctx, instr);
3958 break;
3959 case nir_intrinsic_image_size:
3960 result = visit_image_size(ctx, instr);
3961 break;
3962 case nir_intrinsic_discard:
3963 ctx->shader_info->fs.can_discard = true;
3964 ac_build_intrinsic(&ctx->ac, "llvm.AMDGPU.kilp",
3965 ctx->voidt,
3966 NULL, 0, AC_FUNC_ATTR_LEGACY);
3967 break;
3968 case nir_intrinsic_discard_if:
3969 emit_discard_if(ctx, instr);
3970 break;
3971 case nir_intrinsic_memory_barrier:
3972 emit_waitcnt(ctx, VM_CNT);
3973 break;
3974 case nir_intrinsic_barrier:
3975 emit_barrier(ctx);
3976 break;
3977 case nir_intrinsic_var_atomic_add:
3978 case nir_intrinsic_var_atomic_imin:
3979 case nir_intrinsic_var_atomic_umin:
3980 case nir_intrinsic_var_atomic_imax:
3981 case nir_intrinsic_var_atomic_umax:
3982 case nir_intrinsic_var_atomic_and:
3983 case nir_intrinsic_var_atomic_or:
3984 case nir_intrinsic_var_atomic_xor:
3985 case nir_intrinsic_var_atomic_exchange:
3986 case nir_intrinsic_var_atomic_comp_swap:
3987 result = visit_var_atomic(ctx, instr);
3988 break;
3989 case nir_intrinsic_interp_var_at_centroid:
3990 case nir_intrinsic_interp_var_at_sample:
3991 case nir_intrinsic_interp_var_at_offset:
3992 result = visit_interp(ctx, instr);
3993 break;
3994 case nir_intrinsic_emit_vertex:
3995 visit_emit_vertex(ctx, instr);
3996 break;
3997 case nir_intrinsic_end_primitive:
3998 visit_end_primitive(ctx, instr);
3999 break;
4000 case nir_intrinsic_load_tess_coord:
4001 result = visit_load_tess_coord(ctx, instr);
4002 break;
4003 case nir_intrinsic_load_patch_vertices_in:
4004 result = LLVMConstInt(ctx->i32, ctx->options->key.tcs.input_vertices, false);
4005 break;
4006 default:
4007 fprintf(stderr, "Unknown intrinsic: ");
4008 nir_print_instr(&instr->instr, stderr);
4009 fprintf(stderr, "\n");
4010 break;
4011 }
4012 if (result) {
4013 _mesa_hash_table_insert(ctx->defs, &instr->dest.ssa, result);
4014 }
4015 }
4016
4017 static LLVMValueRef get_sampler_desc(struct nir_to_llvm_context *ctx,
4018 const nir_deref_var *deref,
4019 enum desc_type desc_type)
4020 {
4021 unsigned desc_set = deref->var->data.descriptor_set;
4022 LLVMValueRef list = ctx->descriptor_sets[desc_set];
4023 struct radv_descriptor_set_layout *layout = ctx->options->layout->set[desc_set].layout;
4024 struct radv_descriptor_set_binding_layout *binding = layout->binding + deref->var->data.binding;
4025 unsigned offset = binding->offset;
4026 unsigned stride = binding->size;
4027 unsigned type_size;
4028 LLVMBuilderRef builder = ctx->builder;
4029 LLVMTypeRef type;
4030 LLVMValueRef index = NULL;
4031 unsigned constant_index = 0;
4032
4033 assert(deref->var->data.binding < layout->binding_count);
4034
4035 switch (desc_type) {
4036 case DESC_IMAGE:
4037 type = ctx->v8i32;
4038 type_size = 32;
4039 break;
4040 case DESC_FMASK:
4041 type = ctx->v8i32;
4042 offset += 32;
4043 type_size = 32;
4044 break;
4045 case DESC_SAMPLER:
4046 type = ctx->v4i32;
4047 if (binding->type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
4048 offset += 64;
4049
4050 type_size = 16;
4051 break;
4052 case DESC_BUFFER:
4053 type = ctx->v4i32;
4054 type_size = 16;
4055 break;
4056 default:
4057 unreachable("invalid desc_type\n");
4058 }
4059
4060 if (deref->deref.child) {
4061 const nir_deref_array *child =
4062 (const nir_deref_array *)deref->deref.child;
4063
4064 assert(child->deref_array_type != nir_deref_array_type_wildcard);
4065 offset += child->base_offset * stride;
4066 if (child->deref_array_type == nir_deref_array_type_indirect) {
4067 index = get_src(ctx, child->indirect);
4068 }
4069
4070 constant_index = child->base_offset;
4071 }
4072 if (desc_type == DESC_SAMPLER && binding->immutable_samplers_offset &&
4073 (!index || binding->immutable_samplers_equal)) {
4074 if (binding->immutable_samplers_equal)
4075 constant_index = 0;
4076
4077 const uint32_t *samplers = radv_immutable_samplers(layout, binding);
4078
4079 LLVMValueRef constants[] = {
4080 LLVMConstInt(ctx->i32, samplers[constant_index * 4 + 0], 0),
4081 LLVMConstInt(ctx->i32, samplers[constant_index * 4 + 1], 0),
4082 LLVMConstInt(ctx->i32, samplers[constant_index * 4 + 2], 0),
4083 LLVMConstInt(ctx->i32, samplers[constant_index * 4 + 3], 0),
4084 };
4085 return ac_build_gather_values(&ctx->ac, constants, 4);
4086 }
4087
4088 assert(stride % type_size == 0);
4089
4090 if (!index)
4091 index = ctx->i32zero;
4092
4093 index = LLVMBuildMul(builder, index, LLVMConstInt(ctx->i32, stride / type_size, 0), "");
4094
4095 list = ac_build_gep0(&ctx->ac, list, LLVMConstInt(ctx->i32, offset, 0));
4096 list = LLVMBuildPointerCast(builder, list, const_array(type, 0), "");
4097
4098 return ac_build_indexed_load_const(&ctx->ac, list, index);
4099 }
4100
4101 static void set_tex_fetch_args(struct nir_to_llvm_context *ctx,
4102 struct ac_image_args *args,
4103 const nir_tex_instr *instr,
4104 nir_texop op,
4105 LLVMValueRef res_ptr, LLVMValueRef samp_ptr,
4106 LLVMValueRef *param, unsigned count,
4107 unsigned dmask)
4108 {
4109 unsigned is_rect = 0;
4110 bool da = instr->is_array || instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE;
4111
4112 if (op == nir_texop_lod)
4113 da = false;
4114 /* Pad to power of two vector */
4115 while (count < util_next_power_of_two(count))
4116 param[count++] = LLVMGetUndef(ctx->i32);
4117
4118 if (count > 1)
4119 args->addr = ac_build_gather_values(&ctx->ac, param, count);
4120 else
4121 args->addr = param[0];
4122
4123 args->resource = res_ptr;
4124 args->sampler = samp_ptr;
4125
4126 if (instr->sampler_dim == GLSL_SAMPLER_DIM_BUF && op == nir_texop_txf) {
4127 args->addr = param[0];
4128 return;
4129 }
4130
4131 args->dmask = dmask;
4132 args->unorm = is_rect;
4133 args->da = da;
4134 }
4135
4136 /* Disable anisotropic filtering if BASE_LEVEL == LAST_LEVEL.
4137 *
4138 * SI-CI:
4139 * If BASE_LEVEL == LAST_LEVEL, the shader must disable anisotropic
4140 * filtering manually. The driver sets img7 to a mask clearing
4141 * MAX_ANISO_RATIO if BASE_LEVEL == LAST_LEVEL. The shader must do:
4142 * s_and_b32 samp0, samp0, img7
4143 *
4144 * VI:
4145 * The ANISO_OVERRIDE sampler field enables this fix in TA.
4146 */
4147 static LLVMValueRef sici_fix_sampler_aniso(struct nir_to_llvm_context *ctx,
4148 LLVMValueRef res, LLVMValueRef samp)
4149 {
4150 LLVMBuilderRef builder = ctx->builder;
4151 LLVMValueRef img7, samp0;
4152
4153 if (ctx->options->chip_class >= VI)
4154 return samp;
4155
4156 img7 = LLVMBuildExtractElement(builder, res,
4157 LLVMConstInt(ctx->i32, 7, 0), "");
4158 samp0 = LLVMBuildExtractElement(builder, samp,
4159 LLVMConstInt(ctx->i32, 0, 0), "");
4160 samp0 = LLVMBuildAnd(builder, samp0, img7, "");
4161 return LLVMBuildInsertElement(builder, samp, samp0,
4162 LLVMConstInt(ctx->i32, 0, 0), "");
4163 }
4164
4165 static void tex_fetch_ptrs(struct nir_to_llvm_context *ctx,
4166 nir_tex_instr *instr,
4167 LLVMValueRef *res_ptr, LLVMValueRef *samp_ptr,
4168 LLVMValueRef *fmask_ptr)
4169 {
4170 if (instr->sampler_dim == GLSL_SAMPLER_DIM_BUF)
4171 *res_ptr = get_sampler_desc(ctx, instr->texture, DESC_BUFFER);
4172 else
4173 *res_ptr = get_sampler_desc(ctx, instr->texture, DESC_IMAGE);
4174 if (samp_ptr) {
4175 if (instr->sampler)
4176 *samp_ptr = get_sampler_desc(ctx, instr->sampler, DESC_SAMPLER);
4177 else
4178 *samp_ptr = get_sampler_desc(ctx, instr->texture, DESC_SAMPLER);
4179 if (instr->sampler_dim < GLSL_SAMPLER_DIM_RECT)
4180 *samp_ptr = sici_fix_sampler_aniso(ctx, *res_ptr, *samp_ptr);
4181 }
4182 if (fmask_ptr && !instr->sampler && (instr->op == nir_texop_txf_ms ||
4183 instr->op == nir_texop_samples_identical))
4184 *fmask_ptr = get_sampler_desc(ctx, instr->texture, DESC_FMASK);
4185 }
4186
4187 static LLVMValueRef apply_round_slice(struct nir_to_llvm_context *ctx,
4188 LLVMValueRef coord)
4189 {
4190 coord = to_float(&ctx->ac, coord);
4191 coord = ac_build_intrinsic(&ctx->ac, "llvm.rint.f32", ctx->f32, &coord, 1, 0);
4192 coord = to_integer(&ctx->ac, coord);
4193 return coord;
4194 }
4195
4196 static void visit_tex(struct nir_to_llvm_context *ctx, nir_tex_instr *instr)
4197 {
4198 LLVMValueRef result = NULL;
4199 struct ac_image_args args = { 0 };
4200 unsigned dmask = 0xf;
4201 LLVMValueRef address[16];
4202 LLVMValueRef coords[5];
4203 LLVMValueRef coord = NULL, lod = NULL, comparator = NULL;
4204 LLVMValueRef bias = NULL, offsets = NULL;
4205 LLVMValueRef res_ptr, samp_ptr, fmask_ptr = NULL, sample_index = NULL;
4206 LLVMValueRef ddx = NULL, ddy = NULL;
4207 LLVMValueRef derivs[6];
4208 unsigned chan, count = 0;
4209 unsigned const_src = 0, num_deriv_comp = 0;
4210 bool lod_is_zero = false;
4211 tex_fetch_ptrs(ctx, instr, &res_ptr, &samp_ptr, &fmask_ptr);
4212
4213 for (unsigned i = 0; i < instr->num_srcs; i++) {
4214 switch (instr->src[i].src_type) {
4215 case nir_tex_src_coord:
4216 coord = get_src(ctx, instr->src[i].src);
4217 break;
4218 case nir_tex_src_projector:
4219 break;
4220 case nir_tex_src_comparator:
4221 comparator = get_src(ctx, instr->src[i].src);
4222 break;
4223 case nir_tex_src_offset:
4224 offsets = get_src(ctx, instr->src[i].src);
4225 const_src = i;
4226 break;
4227 case nir_tex_src_bias:
4228 bias = get_src(ctx, instr->src[i].src);
4229 break;
4230 case nir_tex_src_lod: {
4231 nir_const_value *val = nir_src_as_const_value(instr->src[i].src);
4232
4233 if (val && val->i32[0] == 0)
4234 lod_is_zero = true;
4235 lod = get_src(ctx, instr->src[i].src);
4236 break;
4237 }
4238 case nir_tex_src_ms_index:
4239 sample_index = get_src(ctx, instr->src[i].src);
4240 break;
4241 case nir_tex_src_ms_mcs:
4242 break;
4243 case nir_tex_src_ddx:
4244 ddx = get_src(ctx, instr->src[i].src);
4245 num_deriv_comp = instr->src[i].src.ssa->num_components;
4246 break;
4247 case nir_tex_src_ddy:
4248 ddy = get_src(ctx, instr->src[i].src);
4249 break;
4250 case nir_tex_src_texture_offset:
4251 case nir_tex_src_sampler_offset:
4252 case nir_tex_src_plane:
4253 default:
4254 break;
4255 }
4256 }
4257
4258 if (instr->op == nir_texop_txs && instr->sampler_dim == GLSL_SAMPLER_DIM_BUF) {
4259 result = get_buffer_size(ctx, res_ptr, true);
4260 goto write_result;
4261 }
4262
4263 if (instr->op == nir_texop_texture_samples) {
4264 LLVMValueRef res, samples, is_msaa;
4265 res = LLVMBuildBitCast(ctx->builder, res_ptr, ctx->v8i32, "");
4266 samples = LLVMBuildExtractElement(ctx->builder, res,
4267 LLVMConstInt(ctx->i32, 3, false), "");
4268 is_msaa = LLVMBuildLShr(ctx->builder, samples,
4269 LLVMConstInt(ctx->i32, 28, false), "");
4270 is_msaa = LLVMBuildAnd(ctx->builder, is_msaa,
4271 LLVMConstInt(ctx->i32, 0xe, false), "");
4272 is_msaa = LLVMBuildICmp(ctx->builder, LLVMIntEQ, is_msaa,
4273 LLVMConstInt(ctx->i32, 0xe, false), "");
4274
4275 samples = LLVMBuildLShr(ctx->builder, samples,
4276 LLVMConstInt(ctx->i32, 16, false), "");
4277 samples = LLVMBuildAnd(ctx->builder, samples,
4278 LLVMConstInt(ctx->i32, 0xf, false), "");
4279 samples = LLVMBuildShl(ctx->builder, ctx->i32one,
4280 samples, "");
4281 samples = LLVMBuildSelect(ctx->builder, is_msaa, samples,
4282 ctx->i32one, "");
4283 result = samples;
4284 goto write_result;
4285 }
4286
4287 if (coord)
4288 for (chan = 0; chan < instr->coord_components; chan++)
4289 coords[chan] = llvm_extract_elem(ctx, coord, chan);
4290
4291 if (offsets && instr->op != nir_texop_txf) {
4292 LLVMValueRef offset[3], pack;
4293 for (chan = 0; chan < 3; ++chan)
4294 offset[chan] = ctx->i32zero;
4295
4296 args.offset = true;
4297 for (chan = 0; chan < get_llvm_num_components(offsets); chan++) {
4298 offset[chan] = llvm_extract_elem(ctx, offsets, chan);
4299 offset[chan] = LLVMBuildAnd(ctx->builder, offset[chan],
4300 LLVMConstInt(ctx->i32, 0x3f, false), "");
4301 if (chan)
4302 offset[chan] = LLVMBuildShl(ctx->builder, offset[chan],
4303 LLVMConstInt(ctx->i32, chan * 8, false), "");
4304 }
4305 pack = LLVMBuildOr(ctx->builder, offset[0], offset[1], "");
4306 pack = LLVMBuildOr(ctx->builder, pack, offset[2], "");
4307 address[count++] = pack;
4308
4309 }
4310 /* pack LOD bias value */
4311 if (instr->op == nir_texop_txb && bias) {
4312 address[count++] = bias;
4313 }
4314
4315 /* Pack depth comparison value */
4316 if (instr->is_shadow && comparator) {
4317 address[count++] = llvm_extract_elem(ctx, comparator, 0);
4318 }
4319
4320 /* pack derivatives */
4321 if (ddx || ddy) {
4322 switch (instr->sampler_dim) {
4323 case GLSL_SAMPLER_DIM_3D:
4324 case GLSL_SAMPLER_DIM_CUBE:
4325 num_deriv_comp = 3;
4326 break;
4327 case GLSL_SAMPLER_DIM_2D:
4328 default:
4329 num_deriv_comp = 2;
4330 break;
4331 case GLSL_SAMPLER_DIM_1D:
4332 num_deriv_comp = 1;
4333 break;
4334 }
4335
4336 for (unsigned i = 0; i < num_deriv_comp; i++) {
4337 derivs[i] = to_float(&ctx->ac, llvm_extract_elem(ctx, ddx, i));
4338 derivs[num_deriv_comp + i] = to_float(&ctx->ac, llvm_extract_elem(ctx, ddy, i));
4339 }
4340 }
4341
4342 if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE && coord) {
4343 if (instr->is_array && instr->op != nir_texop_lod)
4344 coords[3] = apply_round_slice(ctx, coords[3]);
4345 for (chan = 0; chan < instr->coord_components; chan++)
4346 coords[chan] = to_float(&ctx->ac, coords[chan]);
4347 if (instr->coord_components == 3)
4348 coords[3] = LLVMGetUndef(ctx->f32);
4349 ac_prepare_cube_coords(&ctx->ac,
4350 instr->op == nir_texop_txd, instr->is_array,
4351 coords, derivs);
4352 if (num_deriv_comp)
4353 num_deriv_comp--;
4354 }
4355
4356 if (ddx || ddy) {
4357 for (unsigned i = 0; i < num_deriv_comp * 2; i++)
4358 address[count++] = derivs[i];
4359 }
4360
4361 /* Pack texture coordinates */
4362 if (coord) {
4363 address[count++] = coords[0];
4364 if (instr->coord_components > 1) {
4365 if (instr->sampler_dim == GLSL_SAMPLER_DIM_1D && instr->is_array && instr->op != nir_texop_txf) {
4366 coords[1] = apply_round_slice(ctx, coords[1]);
4367 }
4368 address[count++] = coords[1];
4369 }
4370 if (instr->coord_components > 2) {
4371 /* This seems like a bit of a hack - but it passes Vulkan CTS with it */
4372 if (instr->sampler_dim != GLSL_SAMPLER_DIM_3D &&
4373 instr->sampler_dim != GLSL_SAMPLER_DIM_CUBE &&
4374 instr->op != nir_texop_txf) {
4375 coords[2] = apply_round_slice(ctx, coords[2]);
4376 }
4377 address[count++] = coords[2];
4378 }
4379 }
4380
4381 /* Pack LOD */
4382 if (lod && ((instr->op == nir_texop_txl && !lod_is_zero) ||
4383 instr->op == nir_texop_txf)) {
4384 address[count++] = lod;
4385 } else if (instr->op == nir_texop_txf_ms && sample_index) {
4386 address[count++] = sample_index;
4387 } else if(instr->op == nir_texop_txs) {
4388 count = 0;
4389 if (lod)
4390 address[count++] = lod;
4391 else
4392 address[count++] = ctx->i32zero;
4393 }
4394
4395 for (chan = 0; chan < count; chan++) {
4396 address[chan] = LLVMBuildBitCast(ctx->builder,
4397 address[chan], ctx->i32, "");
4398 }
4399
4400 if (instr->op == nir_texop_samples_identical) {
4401 LLVMValueRef txf_address[4];
4402 struct ac_image_args txf_args = { 0 };
4403 unsigned txf_count = count;
4404 memcpy(txf_address, address, sizeof(txf_address));
4405
4406 if (!instr->is_array)
4407 txf_address[2] = ctx->i32zero;
4408 txf_address[3] = ctx->i32zero;
4409
4410 set_tex_fetch_args(ctx, &txf_args, instr, nir_texop_txf,
4411 fmask_ptr, NULL,
4412 txf_address, txf_count, 0xf);
4413
4414 result = build_tex_intrinsic(ctx, instr, false, &txf_args);
4415
4416 result = LLVMBuildExtractElement(ctx->builder, result, ctx->i32zero, "");
4417 result = emit_int_cmp(ctx, LLVMIntEQ, result, ctx->i32zero);
4418 goto write_result;
4419 }
4420
4421 if (instr->sampler_dim == GLSL_SAMPLER_DIM_MS &&
4422 instr->op != nir_texop_txs) {
4423 unsigned sample_chan = instr->is_array ? 3 : 2;
4424 address[sample_chan] = adjust_sample_index_using_fmask(ctx,
4425 address[0],
4426 address[1],
4427 instr->is_array ? address[2] : NULL,
4428 address[sample_chan],
4429 fmask_ptr);
4430 }
4431
4432 if (offsets && instr->op == nir_texop_txf) {
4433 nir_const_value *const_offset =
4434 nir_src_as_const_value(instr->src[const_src].src);
4435 int num_offsets = instr->src[const_src].src.ssa->num_components;
4436 assert(const_offset);
4437 num_offsets = MIN2(num_offsets, instr->coord_components);
4438 if (num_offsets > 2)
4439 address[2] = LLVMBuildAdd(ctx->builder,
4440 address[2], LLVMConstInt(ctx->i32, const_offset->i32[2], false), "");
4441 if (num_offsets > 1)
4442 address[1] = LLVMBuildAdd(ctx->builder,
4443 address[1], LLVMConstInt(ctx->i32, const_offset->i32[1], false), "");
4444 address[0] = LLVMBuildAdd(ctx->builder,
4445 address[0], LLVMConstInt(ctx->i32, const_offset->i32[0], false), "");
4446
4447 }
4448
4449 /* TODO TG4 support */
4450 if (instr->op == nir_texop_tg4) {
4451 if (instr->is_shadow)
4452 dmask = 1;
4453 else
4454 dmask = 1 << instr->component;
4455 }
4456 set_tex_fetch_args(ctx, &args, instr, instr->op,
4457 res_ptr, samp_ptr, address, count, dmask);
4458
4459 result = build_tex_intrinsic(ctx, instr, lod_is_zero, &args);
4460
4461 if (instr->op == nir_texop_query_levels)
4462 result = LLVMBuildExtractElement(ctx->builder, result, LLVMConstInt(ctx->i32, 3, false), "");
4463 else if (instr->is_shadow && instr->op != nir_texop_txs && instr->op != nir_texop_lod && instr->op != nir_texop_tg4)
4464 result = LLVMBuildExtractElement(ctx->builder, result, ctx->i32zero, "");
4465 else if (instr->op == nir_texop_txs &&
4466 instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE &&
4467 instr->is_array) {
4468 LLVMValueRef two = LLVMConstInt(ctx->i32, 2, false);
4469 LLVMValueRef six = LLVMConstInt(ctx->i32, 6, false);
4470 LLVMValueRef z = LLVMBuildExtractElement(ctx->builder, result, two, "");
4471 z = LLVMBuildSDiv(ctx->builder, z, six, "");
4472 result = LLVMBuildInsertElement(ctx->builder, result, z, two, "");
4473 } else if (instr->dest.ssa.num_components != 4)
4474 result = trim_vector(ctx, result, instr->dest.ssa.num_components);
4475
4476 write_result:
4477 if (result) {
4478 assert(instr->dest.is_ssa);
4479 result = to_integer(&ctx->ac, result);
4480 _mesa_hash_table_insert(ctx->defs, &instr->dest.ssa, result);
4481 }
4482 }
4483
4484
4485 static void visit_phi(struct nir_to_llvm_context *ctx, nir_phi_instr *instr)
4486 {
4487 LLVMTypeRef type = get_def_type(ctx, &instr->dest.ssa);
4488 LLVMValueRef result = LLVMBuildPhi(ctx->builder, type, "");
4489
4490 _mesa_hash_table_insert(ctx->defs, &instr->dest.ssa, result);
4491 _mesa_hash_table_insert(ctx->phis, instr, result);
4492 }
4493
4494 static void visit_post_phi(struct nir_to_llvm_context *ctx,
4495 nir_phi_instr *instr,
4496 LLVMValueRef llvm_phi)
4497 {
4498 nir_foreach_phi_src(src, instr) {
4499 LLVMBasicBlockRef block = get_block(ctx, src->pred);
4500 LLVMValueRef llvm_src = get_src(ctx, src->src);
4501
4502 LLVMAddIncoming(llvm_phi, &llvm_src, &block, 1);
4503 }
4504 }
4505
4506 static void phi_post_pass(struct nir_to_llvm_context *ctx)
4507 {
4508 struct hash_entry *entry;
4509 hash_table_foreach(ctx->phis, entry) {
4510 visit_post_phi(ctx, (nir_phi_instr*)entry->key,
4511 (LLVMValueRef)entry->data);
4512 }
4513 }
4514
4515
4516 static void visit_ssa_undef(struct nir_to_llvm_context *ctx,
4517 const nir_ssa_undef_instr *instr)
4518 {
4519 unsigned num_components = instr->def.num_components;
4520 LLVMValueRef undef;
4521
4522 if (num_components == 1)
4523 undef = LLVMGetUndef(ctx->i32);
4524 else {
4525 undef = LLVMGetUndef(LLVMVectorType(ctx->i32, num_components));
4526 }
4527 _mesa_hash_table_insert(ctx->defs, &instr->def, undef);
4528 }
4529
4530 static void visit_jump(struct nir_to_llvm_context *ctx,
4531 const nir_jump_instr *instr)
4532 {
4533 switch (instr->type) {
4534 case nir_jump_break:
4535 LLVMBuildBr(ctx->builder, ctx->break_block);
4536 LLVMClearInsertionPosition(ctx->builder);
4537 break;
4538 case nir_jump_continue:
4539 LLVMBuildBr(ctx->builder, ctx->continue_block);
4540 LLVMClearInsertionPosition(ctx->builder);
4541 break;
4542 default:
4543 fprintf(stderr, "Unknown NIR jump instr: ");
4544 nir_print_instr(&instr->instr, stderr);
4545 fprintf(stderr, "\n");
4546 abort();
4547 }
4548 }
4549
4550 static void visit_cf_list(struct nir_to_llvm_context *ctx,
4551 struct exec_list *list);
4552
4553 static void visit_block(struct nir_to_llvm_context *ctx, nir_block *block)
4554 {
4555 LLVMBasicBlockRef llvm_block = LLVMGetInsertBlock(ctx->builder);
4556 nir_foreach_instr(instr, block)
4557 {
4558 switch (instr->type) {
4559 case nir_instr_type_alu:
4560 visit_alu(ctx, nir_instr_as_alu(instr));
4561 break;
4562 case nir_instr_type_load_const:
4563 visit_load_const(ctx, nir_instr_as_load_const(instr));
4564 break;
4565 case nir_instr_type_intrinsic:
4566 visit_intrinsic(ctx, nir_instr_as_intrinsic(instr));
4567 break;
4568 case nir_instr_type_tex:
4569 visit_tex(ctx, nir_instr_as_tex(instr));
4570 break;
4571 case nir_instr_type_phi:
4572 visit_phi(ctx, nir_instr_as_phi(instr));
4573 break;
4574 case nir_instr_type_ssa_undef:
4575 visit_ssa_undef(ctx, nir_instr_as_ssa_undef(instr));
4576 break;
4577 case nir_instr_type_jump:
4578 visit_jump(ctx, nir_instr_as_jump(instr));
4579 break;
4580 default:
4581 fprintf(stderr, "Unknown NIR instr type: ");
4582 nir_print_instr(instr, stderr);
4583 fprintf(stderr, "\n");
4584 abort();
4585 }
4586 }
4587
4588 _mesa_hash_table_insert(ctx->defs, block, llvm_block);
4589 }
4590
4591 static void visit_if(struct nir_to_llvm_context *ctx, nir_if *if_stmt)
4592 {
4593 LLVMValueRef value = get_src(ctx, if_stmt->condition);
4594
4595 LLVMBasicBlockRef merge_block =
4596 LLVMAppendBasicBlockInContext(ctx->context, ctx->main_function, "");
4597 LLVMBasicBlockRef if_block =
4598 LLVMAppendBasicBlockInContext(ctx->context, ctx->main_function, "");
4599 LLVMBasicBlockRef else_block = merge_block;
4600 if (!exec_list_is_empty(&if_stmt->else_list))
4601 else_block = LLVMAppendBasicBlockInContext(
4602 ctx->context, ctx->main_function, "");
4603
4604 LLVMValueRef cond = LLVMBuildICmp(ctx->builder, LLVMIntNE, value,
4605 LLVMConstInt(ctx->i32, 0, false), "");
4606 LLVMBuildCondBr(ctx->builder, cond, if_block, else_block);
4607
4608 LLVMPositionBuilderAtEnd(ctx->builder, if_block);
4609 visit_cf_list(ctx, &if_stmt->then_list);
4610 if (LLVMGetInsertBlock(ctx->builder))
4611 LLVMBuildBr(ctx->builder, merge_block);
4612
4613 if (!exec_list_is_empty(&if_stmt->else_list)) {
4614 LLVMPositionBuilderAtEnd(ctx->builder, else_block);
4615 visit_cf_list(ctx, &if_stmt->else_list);
4616 if (LLVMGetInsertBlock(ctx->builder))
4617 LLVMBuildBr(ctx->builder, merge_block);
4618 }
4619
4620 LLVMPositionBuilderAtEnd(ctx->builder, merge_block);
4621 }
4622
4623 static void visit_loop(struct nir_to_llvm_context *ctx, nir_loop *loop)
4624 {
4625 LLVMBasicBlockRef continue_parent = ctx->continue_block;
4626 LLVMBasicBlockRef break_parent = ctx->break_block;
4627
4628 ctx->continue_block =
4629 LLVMAppendBasicBlockInContext(ctx->context, ctx->main_function, "");
4630 ctx->break_block =
4631 LLVMAppendBasicBlockInContext(ctx->context, ctx->main_function, "");
4632
4633 LLVMBuildBr(ctx->builder, ctx->continue_block);
4634 LLVMPositionBuilderAtEnd(ctx->builder, ctx->continue_block);
4635 visit_cf_list(ctx, &loop->body);
4636
4637 if (LLVMGetInsertBlock(ctx->builder))
4638 LLVMBuildBr(ctx->builder, ctx->continue_block);
4639 LLVMPositionBuilderAtEnd(ctx->builder, ctx->break_block);
4640
4641 ctx->continue_block = continue_parent;
4642 ctx->break_block = break_parent;
4643 }
4644
4645 static void visit_cf_list(struct nir_to_llvm_context *ctx,
4646 struct exec_list *list)
4647 {
4648 foreach_list_typed(nir_cf_node, node, node, list)
4649 {
4650 switch (node->type) {
4651 case nir_cf_node_block:
4652 visit_block(ctx, nir_cf_node_as_block(node));
4653 break;
4654
4655 case nir_cf_node_if:
4656 visit_if(ctx, nir_cf_node_as_if(node));
4657 break;
4658
4659 case nir_cf_node_loop:
4660 visit_loop(ctx, nir_cf_node_as_loop(node));
4661 break;
4662
4663 default:
4664 assert(0);
4665 }
4666 }
4667 }
4668
4669 static void
4670 handle_vs_input_decl(struct nir_to_llvm_context *ctx,
4671 struct nir_variable *variable)
4672 {
4673 LLVMValueRef t_list_ptr = ctx->vertex_buffers;
4674 LLVMValueRef t_offset;
4675 LLVMValueRef t_list;
4676 LLVMValueRef input;
4677 LLVMValueRef buffer_index;
4678 int index = variable->data.location - VERT_ATTRIB_GENERIC0;
4679 int idx = variable->data.location;
4680 unsigned attrib_count = glsl_count_attribute_slots(variable->type, true);
4681
4682 variable->data.driver_location = idx * 4;
4683
4684 if (ctx->options->key.vs.instance_rate_inputs & (1u << index)) {
4685 buffer_index = LLVMBuildAdd(ctx->builder, ctx->instance_id,
4686 ctx->start_instance, "");
4687 ctx->shader_info->vs.vgpr_comp_cnt = MAX2(3,
4688 ctx->shader_info->vs.vgpr_comp_cnt);
4689 } else
4690 buffer_index = LLVMBuildAdd(ctx->builder, ctx->vertex_id,
4691 ctx->base_vertex, "");
4692
4693 for (unsigned i = 0; i < attrib_count; ++i, ++idx) {
4694 t_offset = LLVMConstInt(ctx->i32, index + i, false);
4695
4696 t_list = ac_build_indexed_load_const(&ctx->ac, t_list_ptr, t_offset);
4697
4698 input = ac_build_buffer_load_format(&ctx->ac, t_list,
4699 buffer_index,
4700 LLVMConstInt(ctx->i32, 0, false),
4701 true);
4702
4703 for (unsigned chan = 0; chan < 4; chan++) {
4704 LLVMValueRef llvm_chan = LLVMConstInt(ctx->i32, chan, false);
4705 ctx->inputs[radeon_llvm_reg_index_soa(idx, chan)] =
4706 to_integer(&ctx->ac, LLVMBuildExtractElement(ctx->builder,
4707 input, llvm_chan, ""));
4708 }
4709 }
4710 }
4711
4712 static void interp_fs_input(struct nir_to_llvm_context *ctx,
4713 unsigned attr,
4714 LLVMValueRef interp_param,
4715 LLVMValueRef prim_mask,
4716 LLVMValueRef result[4])
4717 {
4718 LLVMValueRef attr_number;
4719 unsigned chan;
4720 LLVMValueRef i, j;
4721 bool interp = interp_param != NULL;
4722
4723 attr_number = LLVMConstInt(ctx->i32, attr, false);
4724
4725 /* fs.constant returns the param from the middle vertex, so it's not
4726 * really useful for flat shading. It's meant to be used for custom
4727 * interpolation (but the intrinsic can't fetch from the other two
4728 * vertices).
4729 *
4730 * Luckily, it doesn't matter, because we rely on the FLAT_SHADE state
4731 * to do the right thing. The only reason we use fs.constant is that
4732 * fs.interp cannot be used on integers, because they can be equal
4733 * to NaN.
4734 */
4735 if (interp) {
4736 interp_param = LLVMBuildBitCast(ctx->builder, interp_param,
4737 LLVMVectorType(ctx->f32, 2), "");
4738
4739 i = LLVMBuildExtractElement(ctx->builder, interp_param,
4740 ctx->i32zero, "");
4741 j = LLVMBuildExtractElement(ctx->builder, interp_param,
4742 ctx->i32one, "");
4743 }
4744
4745 for (chan = 0; chan < 4; chan++) {
4746 LLVMValueRef llvm_chan = LLVMConstInt(ctx->i32, chan, false);
4747
4748 if (interp) {
4749 result[chan] = ac_build_fs_interp(&ctx->ac,
4750 llvm_chan,
4751 attr_number,
4752 prim_mask, i, j);
4753 } else {
4754 result[chan] = ac_build_fs_interp_mov(&ctx->ac,
4755 LLVMConstInt(ctx->i32, 2, false),
4756 llvm_chan,
4757 attr_number,
4758 prim_mask);
4759 }
4760 }
4761 }
4762
4763 static void
4764 handle_fs_input_decl(struct nir_to_llvm_context *ctx,
4765 struct nir_variable *variable)
4766 {
4767 int idx = variable->data.location;
4768 unsigned attrib_count = glsl_count_attribute_slots(variable->type, false);
4769 LLVMValueRef interp;
4770
4771 variable->data.driver_location = idx * 4;
4772 ctx->input_mask |= ((1ull << attrib_count) - 1) << variable->data.location;
4773
4774 if (glsl_get_base_type(glsl_without_array(variable->type)) == GLSL_TYPE_FLOAT) {
4775 unsigned interp_type;
4776 if (variable->data.sample) {
4777 interp_type = INTERP_SAMPLE;
4778 ctx->shader_info->fs.force_persample = true;
4779 } else if (variable->data.centroid)
4780 interp_type = INTERP_CENTROID;
4781 else
4782 interp_type = INTERP_CENTER;
4783
4784 interp = lookup_interp_param(ctx, variable->data.interpolation, interp_type);
4785 } else
4786 interp = NULL;
4787
4788 for (unsigned i = 0; i < attrib_count; ++i)
4789 ctx->inputs[radeon_llvm_reg_index_soa(idx + i, 0)] = interp;
4790
4791 }
4792
4793 static void
4794 handle_shader_input_decl(struct nir_to_llvm_context *ctx,
4795 struct nir_variable *variable)
4796 {
4797 switch (ctx->stage) {
4798 case MESA_SHADER_VERTEX:
4799 handle_vs_input_decl(ctx, variable);
4800 break;
4801 case MESA_SHADER_FRAGMENT:
4802 handle_fs_input_decl(ctx, variable);
4803 break;
4804 default:
4805 break;
4806 }
4807
4808 }
4809
4810 static void
4811 handle_fs_inputs_pre(struct nir_to_llvm_context *ctx,
4812 struct nir_shader *nir)
4813 {
4814 unsigned index = 0;
4815 for (unsigned i = 0; i < RADEON_LLVM_MAX_INPUTS; ++i) {
4816 LLVMValueRef interp_param;
4817 LLVMValueRef *inputs = ctx->inputs +radeon_llvm_reg_index_soa(i, 0);
4818
4819 if (!(ctx->input_mask & (1ull << i)))
4820 continue;
4821
4822 if (i >= VARYING_SLOT_VAR0 || i == VARYING_SLOT_PNTC ||
4823 i == VARYING_SLOT_PRIMITIVE_ID || i == VARYING_SLOT_LAYER) {
4824 interp_param = *inputs;
4825 interp_fs_input(ctx, index, interp_param, ctx->prim_mask,
4826 inputs);
4827
4828 if (!interp_param)
4829 ctx->shader_info->fs.flat_shaded_mask |= 1u << index;
4830 ++index;
4831 } else if (i == VARYING_SLOT_POS) {
4832 for(int i = 0; i < 3; ++i)
4833 inputs[i] = ctx->frag_pos[i];
4834
4835 inputs[3] = ac_build_fdiv(&ctx->ac, ctx->f32one, ctx->frag_pos[3]);
4836 }
4837 }
4838 ctx->shader_info->fs.num_interp = index;
4839 if (ctx->input_mask & (1 << VARYING_SLOT_PNTC))
4840 ctx->shader_info->fs.has_pcoord = true;
4841 if (ctx->input_mask & (1 << VARYING_SLOT_PRIMITIVE_ID))
4842 ctx->shader_info->fs.prim_id_input = true;
4843 if (ctx->input_mask & (1 << VARYING_SLOT_LAYER))
4844 ctx->shader_info->fs.layer_input = true;
4845 ctx->shader_info->fs.input_mask = ctx->input_mask >> VARYING_SLOT_VAR0;
4846 }
4847
4848 static LLVMValueRef
4849 ac_build_alloca(struct nir_to_llvm_context *ctx,
4850 LLVMTypeRef type,
4851 const char *name)
4852 {
4853 LLVMBuilderRef builder = ctx->builder;
4854 LLVMBasicBlockRef current_block = LLVMGetInsertBlock(builder);
4855 LLVMValueRef function = LLVMGetBasicBlockParent(current_block);
4856 LLVMBasicBlockRef first_block = LLVMGetEntryBasicBlock(function);
4857 LLVMValueRef first_instr = LLVMGetFirstInstruction(first_block);
4858 LLVMBuilderRef first_builder = LLVMCreateBuilderInContext(ctx->context);
4859 LLVMValueRef res;
4860
4861 if (first_instr) {
4862 LLVMPositionBuilderBefore(first_builder, first_instr);
4863 } else {
4864 LLVMPositionBuilderAtEnd(first_builder, first_block);
4865 }
4866
4867 res = LLVMBuildAlloca(first_builder, type, name);
4868 LLVMBuildStore(builder, LLVMConstNull(type), res);
4869
4870 LLVMDisposeBuilder(first_builder);
4871
4872 return res;
4873 }
4874
4875 static LLVMValueRef si_build_alloca_undef(struct nir_to_llvm_context *ctx,
4876 LLVMTypeRef type,
4877 const char *name)
4878 {
4879 LLVMValueRef ptr = ac_build_alloca(ctx, type, name);
4880 LLVMBuildStore(ctx->builder, LLVMGetUndef(type), ptr);
4881 return ptr;
4882 }
4883
4884 static void
4885 handle_shader_output_decl(struct nir_to_llvm_context *ctx,
4886 struct nir_variable *variable)
4887 {
4888 int idx = variable->data.location + variable->data.index;
4889 unsigned attrib_count = glsl_count_attribute_slots(variable->type, false);
4890 uint64_t mask_attribs;
4891 variable->data.driver_location = idx * 4;
4892
4893 /* tess ctrl has it's own load/store paths for outputs */
4894 if (ctx->stage == MESA_SHADER_TESS_CTRL)
4895 return;
4896
4897 mask_attribs = ((1ull << attrib_count) - 1) << idx;
4898 if (ctx->stage == MESA_SHADER_VERTEX ||
4899 ctx->stage == MESA_SHADER_TESS_EVAL ||
4900 ctx->stage == MESA_SHADER_GEOMETRY) {
4901 if (idx == VARYING_SLOT_CLIP_DIST0) {
4902 int length = ctx->num_output_clips + ctx->num_output_culls;
4903 if (ctx->stage == MESA_SHADER_VERTEX) {
4904 ctx->shader_info->vs.outinfo.clip_dist_mask = (1 << ctx->num_output_clips) - 1;
4905 ctx->shader_info->vs.outinfo.cull_dist_mask = (1 << ctx->num_output_culls) - 1;
4906 }
4907 if (ctx->stage == MESA_SHADER_TESS_EVAL) {
4908 ctx->shader_info->tes.outinfo.clip_dist_mask = (1 << ctx->num_output_clips) - 1;
4909 ctx->shader_info->tes.outinfo.cull_dist_mask = (1 << ctx->num_output_culls) - 1;
4910 }
4911
4912 if (length > 4)
4913 attrib_count = 2;
4914 else
4915 attrib_count = 1;
4916 mask_attribs = 1ull << idx;
4917 }
4918 }
4919
4920 for (unsigned i = 0; i < attrib_count; ++i) {
4921 for (unsigned chan = 0; chan < 4; chan++) {
4922 ctx->outputs[radeon_llvm_reg_index_soa(idx + i, chan)] =
4923 si_build_alloca_undef(ctx, ctx->f32, "");
4924 }
4925 }
4926 ctx->output_mask |= mask_attribs;
4927 }
4928
4929 static void
4930 setup_locals(struct nir_to_llvm_context *ctx,
4931 struct nir_function *func)
4932 {
4933 int i, j;
4934 ctx->num_locals = 0;
4935 nir_foreach_variable(variable, &func->impl->locals) {
4936 unsigned attrib_count = glsl_count_attribute_slots(variable->type, false);
4937 variable->data.driver_location = ctx->num_locals * 4;
4938 ctx->num_locals += attrib_count;
4939 }
4940 ctx->locals = malloc(4 * ctx->num_locals * sizeof(LLVMValueRef));
4941 if (!ctx->locals)
4942 return;
4943
4944 for (i = 0; i < ctx->num_locals; i++) {
4945 for (j = 0; j < 4; j++) {
4946 ctx->locals[i * 4 + j] =
4947 si_build_alloca_undef(ctx, ctx->f32, "temp");
4948 }
4949 }
4950 }
4951
4952 static LLVMValueRef
4953 emit_float_saturate(struct nir_to_llvm_context *ctx, LLVMValueRef v, float lo, float hi)
4954 {
4955 v = to_float(&ctx->ac, v);
4956 v = emit_intrin_2f_param(ctx, "llvm.maxnum.f32", ctx->f32, v, LLVMConstReal(ctx->f32, lo));
4957 return emit_intrin_2f_param(ctx, "llvm.minnum.f32", ctx->f32, v, LLVMConstReal(ctx->f32, hi));
4958 }
4959
4960
4961 static LLVMValueRef emit_pack_int16(struct nir_to_llvm_context *ctx,
4962 LLVMValueRef src0, LLVMValueRef src1)
4963 {
4964 LLVMValueRef const16 = LLVMConstInt(ctx->i32, 16, false);
4965 LLVMValueRef comp[2];
4966
4967 comp[0] = LLVMBuildAnd(ctx->builder, src0, LLVMConstInt(ctx-> i32, 65535, 0), "");
4968 comp[1] = LLVMBuildAnd(ctx->builder, src1, LLVMConstInt(ctx-> i32, 65535, 0), "");
4969 comp[1] = LLVMBuildShl(ctx->builder, comp[1], const16, "");
4970 return LLVMBuildOr(ctx->builder, comp[0], comp[1], "");
4971 }
4972
4973 /* Initialize arguments for the shader export intrinsic */
4974 static void
4975 si_llvm_init_export_args(struct nir_to_llvm_context *ctx,
4976 LLVMValueRef *values,
4977 unsigned target,
4978 struct ac_export_args *args)
4979 {
4980 /* Default is 0xf. Adjusted below depending on the format. */
4981 args->enabled_channels = 0xf;
4982
4983 /* Specify whether the EXEC mask represents the valid mask */
4984 args->valid_mask = 0;
4985
4986 /* Specify whether this is the last export */
4987 args->done = 0;
4988
4989 /* Specify the target we are exporting */
4990 args->target = target;
4991
4992 args->compr = false;
4993 args->out[0] = LLVMGetUndef(ctx->f32);
4994 args->out[1] = LLVMGetUndef(ctx->f32);
4995 args->out[2] = LLVMGetUndef(ctx->f32);
4996 args->out[3] = LLVMGetUndef(ctx->f32);
4997
4998 if (!values)
4999 return;
5000
5001 if (ctx->stage == MESA_SHADER_FRAGMENT && target >= V_008DFC_SQ_EXP_MRT) {
5002 LLVMValueRef val[4];
5003 unsigned index = target - V_008DFC_SQ_EXP_MRT;
5004 unsigned col_format = (ctx->options->key.fs.col_format >> (4 * index)) & 0xf;
5005 bool is_int8 = (ctx->options->key.fs.is_int8 >> index) & 1;
5006
5007 switch(col_format) {
5008 case V_028714_SPI_SHADER_ZERO:
5009 args->enabled_channels = 0; /* writemask */
5010 args->target = V_008DFC_SQ_EXP_NULL;
5011 break;
5012
5013 case V_028714_SPI_SHADER_32_R:
5014 args->enabled_channels = 1;
5015 args->out[0] = values[0];
5016 break;
5017
5018 case V_028714_SPI_SHADER_32_GR:
5019 args->enabled_channels = 0x3;
5020 args->out[0] = values[0];
5021 args->out[1] = values[1];
5022 break;
5023
5024 case V_028714_SPI_SHADER_32_AR:
5025 args->enabled_channels = 0x9;
5026 args->out[0] = values[0];
5027 args->out[3] = values[3];
5028 break;
5029
5030 case V_028714_SPI_SHADER_FP16_ABGR:
5031 args->compr = 1;
5032
5033 for (unsigned chan = 0; chan < 2; chan++) {
5034 LLVMValueRef pack_args[2] = {
5035 values[2 * chan],
5036 values[2 * chan + 1]
5037 };
5038 LLVMValueRef packed;
5039
5040 packed = ac_build_cvt_pkrtz_f16(&ctx->ac, pack_args);
5041 args->out[chan] = packed;
5042 }
5043 break;
5044
5045 case V_028714_SPI_SHADER_UNORM16_ABGR:
5046 for (unsigned chan = 0; chan < 4; chan++) {
5047 val[chan] = ac_build_clamp(&ctx->ac, values[chan]);
5048 val[chan] = LLVMBuildFMul(ctx->builder, val[chan],
5049 LLVMConstReal(ctx->f32, 65535), "");
5050 val[chan] = LLVMBuildFAdd(ctx->builder, val[chan],
5051 LLVMConstReal(ctx->f32, 0.5), "");
5052 val[chan] = LLVMBuildFPToUI(ctx->builder, val[chan],
5053 ctx->i32, "");
5054 }
5055
5056 args->compr = 1;
5057 args->out[0] = emit_pack_int16(ctx, val[0], val[1]);
5058 args->out[1] = emit_pack_int16(ctx, val[2], val[3]);
5059 break;
5060
5061 case V_028714_SPI_SHADER_SNORM16_ABGR:
5062 for (unsigned chan = 0; chan < 4; chan++) {
5063 val[chan] = emit_float_saturate(ctx, values[chan], -1, 1);
5064 val[chan] = LLVMBuildFMul(ctx->builder, val[chan],
5065 LLVMConstReal(ctx->f32, 32767), "");
5066
5067 /* If positive, add 0.5, else add -0.5. */
5068 val[chan] = LLVMBuildFAdd(ctx->builder, val[chan],
5069 LLVMBuildSelect(ctx->builder,
5070 LLVMBuildFCmp(ctx->builder, LLVMRealOGE,
5071 val[chan], ctx->f32zero, ""),
5072 LLVMConstReal(ctx->f32, 0.5),
5073 LLVMConstReal(ctx->f32, -0.5), ""), "");
5074 val[chan] = LLVMBuildFPToSI(ctx->builder, val[chan], ctx->i32, "");
5075 }
5076
5077 args->compr = 1;
5078 args->out[0] = emit_pack_int16(ctx, val[0], val[1]);
5079 args->out[1] = emit_pack_int16(ctx, val[2], val[3]);
5080 break;
5081
5082 case V_028714_SPI_SHADER_UINT16_ABGR: {
5083 LLVMValueRef max = LLVMConstInt(ctx->i32, is_int8 ? 255 : 65535, 0);
5084
5085 for (unsigned chan = 0; chan < 4; chan++) {
5086 val[chan] = to_integer(&ctx->ac, values[chan]);
5087 val[chan] = emit_minmax_int(ctx, LLVMIntULT, val[chan], max);
5088 }
5089
5090 args->compr = 1;
5091 args->out[0] = emit_pack_int16(ctx, val[0], val[1]);
5092 args->out[1] = emit_pack_int16(ctx, val[2], val[3]);
5093 break;
5094 }
5095
5096 case V_028714_SPI_SHADER_SINT16_ABGR: {
5097 LLVMValueRef max = LLVMConstInt(ctx->i32, is_int8 ? 127 : 32767, 0);
5098 LLVMValueRef min = LLVMConstInt(ctx->i32, is_int8 ? -128 : -32768, 0);
5099
5100 /* Clamp. */
5101 for (unsigned chan = 0; chan < 4; chan++) {
5102 val[chan] = to_integer(&ctx->ac, values[chan]);
5103 val[chan] = emit_minmax_int(ctx, LLVMIntSLT, val[chan], max);
5104 val[chan] = emit_minmax_int(ctx, LLVMIntSGT, val[chan], min);
5105 }
5106
5107 args->compr = 1;
5108 args->out[0] = emit_pack_int16(ctx, val[0], val[1]);
5109 args->out[1] = emit_pack_int16(ctx, val[2], val[3]);
5110 break;
5111 }
5112
5113 default:
5114 case V_028714_SPI_SHADER_32_ABGR:
5115 memcpy(&args->out[0], values, sizeof(values[0]) * 4);
5116 break;
5117 }
5118 } else
5119 memcpy(&args->out[0], values, sizeof(values[0]) * 4);
5120
5121 for (unsigned i = 0; i < 4; ++i)
5122 args->out[i] = to_float(&ctx->ac, args->out[i]);
5123 }
5124
5125 static void
5126 handle_vs_outputs_post(struct nir_to_llvm_context *ctx,
5127 bool export_prim_id,
5128 struct ac_vs_output_info *outinfo)
5129 {
5130 uint32_t param_count = 0;
5131 unsigned target;
5132 unsigned pos_idx, num_pos_exports = 0;
5133 struct ac_export_args args, pos_args[4] = {};
5134 LLVMValueRef psize_value = NULL, layer_value = NULL, viewport_index_value = NULL;
5135 int i;
5136
5137 memset(outinfo->vs_output_param_offset, AC_EXP_PARAM_UNDEFINED,
5138 sizeof(outinfo->vs_output_param_offset));
5139
5140 if (ctx->output_mask & (1ull << VARYING_SLOT_CLIP_DIST0)) {
5141 LLVMValueRef slots[8];
5142 unsigned j;
5143
5144 if (outinfo->cull_dist_mask)
5145 outinfo->cull_dist_mask <<= ctx->num_output_clips;
5146
5147 i = VARYING_SLOT_CLIP_DIST0;
5148 for (j = 0; j < ctx->num_output_clips + ctx->num_output_culls; j++)
5149 slots[j] = to_float(&ctx->ac, LLVMBuildLoad(ctx->builder,
5150 ctx->outputs[radeon_llvm_reg_index_soa(i, j)], ""));
5151
5152 for (i = ctx->num_output_clips + ctx->num_output_culls; i < 8; i++)
5153 slots[i] = LLVMGetUndef(ctx->f32);
5154
5155 if (ctx->num_output_clips + ctx->num_output_culls > 4) {
5156 target = V_008DFC_SQ_EXP_POS + 3;
5157 si_llvm_init_export_args(ctx, &slots[4], target, &args);
5158 memcpy(&pos_args[target - V_008DFC_SQ_EXP_POS],
5159 &args, sizeof(args));
5160 }
5161
5162 target = V_008DFC_SQ_EXP_POS + 2;
5163 si_llvm_init_export_args(ctx, &slots[0], target, &args);
5164 memcpy(&pos_args[target - V_008DFC_SQ_EXP_POS],
5165 &args, sizeof(args));
5166
5167 }
5168
5169 for (unsigned i = 0; i < RADEON_LLVM_MAX_OUTPUTS; ++i) {
5170 LLVMValueRef values[4];
5171 if (!(ctx->output_mask & (1ull << i)))
5172 continue;
5173
5174 for (unsigned j = 0; j < 4; j++)
5175 values[j] = to_float(&ctx->ac, LLVMBuildLoad(ctx->builder,
5176 ctx->outputs[radeon_llvm_reg_index_soa(i, j)], ""));
5177
5178 if (i == VARYING_SLOT_POS) {
5179 target = V_008DFC_SQ_EXP_POS;
5180 } else if (i == VARYING_SLOT_CLIP_DIST0) {
5181 continue;
5182 } else if (i == VARYING_SLOT_PSIZ) {
5183 outinfo->writes_pointsize = true;
5184 psize_value = values[0];
5185 continue;
5186 } else if (i == VARYING_SLOT_LAYER) {
5187 outinfo->writes_layer = true;
5188 layer_value = values[0];
5189 target = V_008DFC_SQ_EXP_PARAM + param_count;
5190 outinfo->vs_output_param_offset[VARYING_SLOT_LAYER] = param_count;
5191 param_count++;
5192 } else if (i == VARYING_SLOT_VIEWPORT) {
5193 outinfo->writes_viewport_index = true;
5194 viewport_index_value = values[0];
5195 continue;
5196 } else if (i == VARYING_SLOT_PRIMITIVE_ID) {
5197 target = V_008DFC_SQ_EXP_PARAM + param_count;
5198 outinfo->vs_output_param_offset[VARYING_SLOT_PRIMITIVE_ID] = param_count;
5199 param_count++;
5200 } else if (i >= VARYING_SLOT_VAR0) {
5201 outinfo->export_mask |= 1u << (i - VARYING_SLOT_VAR0);
5202 target = V_008DFC_SQ_EXP_PARAM + param_count;
5203 outinfo->vs_output_param_offset[i] = param_count;
5204 param_count++;
5205 }
5206
5207 si_llvm_init_export_args(ctx, values, target, &args);
5208
5209 if (target >= V_008DFC_SQ_EXP_POS &&
5210 target <= (V_008DFC_SQ_EXP_POS + 3)) {
5211 memcpy(&pos_args[target - V_008DFC_SQ_EXP_POS],
5212 &args, sizeof(args));
5213 } else {
5214 ac_build_export(&ctx->ac, &args);
5215 }
5216 }
5217
5218 /* We need to add the position output manually if it's missing. */
5219 if (!pos_args[0].out[0]) {
5220 pos_args[0].enabled_channels = 0xf;
5221 pos_args[0].valid_mask = 0;
5222 pos_args[0].done = 0;
5223 pos_args[0].target = V_008DFC_SQ_EXP_POS;
5224 pos_args[0].compr = 0;
5225 pos_args[0].out[0] = ctx->f32zero; /* X */
5226 pos_args[0].out[1] = ctx->f32zero; /* Y */
5227 pos_args[0].out[2] = ctx->f32zero; /* Z */
5228 pos_args[0].out[3] = ctx->f32one; /* W */
5229 }
5230
5231 uint32_t mask = ((outinfo->writes_pointsize == true ? 1 : 0) |
5232 (outinfo->writes_layer == true ? 4 : 0) |
5233 (outinfo->writes_viewport_index == true ? 8 : 0));
5234 if (mask) {
5235 pos_args[1].enabled_channels = mask;
5236 pos_args[1].valid_mask = 0;
5237 pos_args[1].done = 0;
5238 pos_args[1].target = V_008DFC_SQ_EXP_POS + 1;
5239 pos_args[1].compr = 0;
5240 pos_args[1].out[0] = ctx->f32zero; /* X */
5241 pos_args[1].out[1] = ctx->f32zero; /* Y */
5242 pos_args[1].out[2] = ctx->f32zero; /* Z */
5243 pos_args[1].out[3] = ctx->f32zero; /* W */
5244
5245 if (outinfo->writes_pointsize == true)
5246 pos_args[1].out[0] = psize_value;
5247 if (outinfo->writes_layer == true)
5248 pos_args[1].out[2] = layer_value;
5249 if (outinfo->writes_viewport_index == true)
5250 pos_args[1].out[3] = viewport_index_value;
5251 }
5252 for (i = 0; i < 4; i++) {
5253 if (pos_args[i].out[0])
5254 num_pos_exports++;
5255 }
5256
5257 pos_idx = 0;
5258 for (i = 0; i < 4; i++) {
5259 if (!pos_args[i].out[0])
5260 continue;
5261
5262 /* Specify the target we are exporting */
5263 pos_args[i].target = V_008DFC_SQ_EXP_POS + pos_idx++;
5264 if (pos_idx == num_pos_exports)
5265 pos_args[i].done = 1;
5266 ac_build_export(&ctx->ac, &pos_args[i]);
5267 }
5268
5269
5270 if (export_prim_id) {
5271 LLVMValueRef values[4];
5272 target = V_008DFC_SQ_EXP_PARAM + param_count;
5273 outinfo->vs_output_param_offset[VARYING_SLOT_PRIMITIVE_ID] = param_count;
5274 param_count++;
5275
5276 values[0] = ctx->vs_prim_id;
5277 ctx->shader_info->vs.vgpr_comp_cnt = MAX2(2,
5278 ctx->shader_info->vs.vgpr_comp_cnt);
5279 for (unsigned j = 1; j < 4; j++)
5280 values[j] = ctx->f32zero;
5281 si_llvm_init_export_args(ctx, values, target, &args);
5282 ac_build_export(&ctx->ac, &args);
5283 outinfo->export_prim_id = true;
5284 }
5285
5286 outinfo->pos_exports = num_pos_exports;
5287 outinfo->param_exports = param_count;
5288 }
5289
5290 static void
5291 handle_es_outputs_post(struct nir_to_llvm_context *ctx,
5292 struct ac_es_output_info *outinfo)
5293 {
5294 int j;
5295 uint64_t max_output_written = 0;
5296 for (unsigned i = 0; i < RADEON_LLVM_MAX_OUTPUTS; ++i) {
5297 LLVMValueRef *out_ptr = &ctx->outputs[i * 4];
5298 int param_index;
5299 int length = 4;
5300
5301 if (!(ctx->output_mask & (1ull << i)))
5302 continue;
5303
5304 if (i == VARYING_SLOT_CLIP_DIST0)
5305 length = ctx->num_output_clips + ctx->num_output_culls;
5306
5307 param_index = shader_io_get_unique_index(i);
5308
5309 max_output_written = MAX2(param_index + (length > 4), max_output_written);
5310
5311 for (j = 0; j < length; j++) {
5312 LLVMValueRef out_val = LLVMBuildLoad(ctx->builder, out_ptr[j], "");
5313 out_val = LLVMBuildBitCast(ctx->builder, out_val, ctx->i32, "");
5314
5315 ac_build_buffer_store_dword(&ctx->ac,
5316 ctx->esgs_ring,
5317 out_val, 1,
5318 NULL, ctx->es2gs_offset,
5319 (4 * param_index + j) * 4,
5320 1, 1, true, true);
5321 }
5322 }
5323 outinfo->esgs_itemsize = (max_output_written + 1) * 16;
5324 }
5325
5326 static void
5327 handle_ls_outputs_post(struct nir_to_llvm_context *ctx)
5328 {
5329 LLVMValueRef vertex_id = ctx->rel_auto_id;
5330 LLVMValueRef vertex_dw_stride = unpack_param(ctx, ctx->ls_out_layout, 13, 8);
5331 LLVMValueRef base_dw_addr = LLVMBuildMul(ctx->builder, vertex_id,
5332 vertex_dw_stride, "");
5333
5334 for (unsigned i = 0; i < RADEON_LLVM_MAX_OUTPUTS; ++i) {
5335 LLVMValueRef *out_ptr = &ctx->outputs[i * 4];
5336 int length = 4;
5337
5338 if (!(ctx->output_mask & (1ull << i)))
5339 continue;
5340
5341 if (i == VARYING_SLOT_CLIP_DIST0)
5342 length = ctx->num_output_clips + ctx->num_output_culls;
5343 int param = shader_io_get_unique_index(i);
5344 mark_tess_output(ctx, false, param);
5345 if (length > 4)
5346 mark_tess_output(ctx, false, param + 1);
5347 LLVMValueRef dw_addr = LLVMBuildAdd(ctx->builder, base_dw_addr,
5348 LLVMConstInt(ctx->i32, param * 4, false),
5349 "");
5350 for (unsigned j = 0; j < length; j++) {
5351 lds_store(ctx, dw_addr,
5352 LLVMBuildLoad(ctx->builder, out_ptr[j], ""));
5353 dw_addr = LLVMBuildAdd(ctx->builder, dw_addr, ctx->i32one, "");
5354 }
5355 }
5356 }
5357
5358 struct ac_build_if_state
5359 {
5360 struct nir_to_llvm_context *ctx;
5361 LLVMValueRef condition;
5362 LLVMBasicBlockRef entry_block;
5363 LLVMBasicBlockRef true_block;
5364 LLVMBasicBlockRef false_block;
5365 LLVMBasicBlockRef merge_block;
5366 };
5367
5368 static LLVMBasicBlockRef
5369 ac_build_insert_new_block(struct nir_to_llvm_context *ctx, const char *name)
5370 {
5371 LLVMBasicBlockRef current_block;
5372 LLVMBasicBlockRef next_block;
5373 LLVMBasicBlockRef new_block;
5374
5375 /* get current basic block */
5376 current_block = LLVMGetInsertBlock(ctx->builder);
5377
5378 /* chqeck if there's another block after this one */
5379 next_block = LLVMGetNextBasicBlock(current_block);
5380 if (next_block) {
5381 /* insert the new block before the next block */
5382 new_block = LLVMInsertBasicBlockInContext(ctx->context, next_block, name);
5383 }
5384 else {
5385 /* append new block after current block */
5386 LLVMValueRef function = LLVMGetBasicBlockParent(current_block);
5387 new_block = LLVMAppendBasicBlockInContext(ctx->context, function, name);
5388 }
5389 return new_block;
5390 }
5391
5392 static void
5393 ac_nir_build_if(struct ac_build_if_state *ifthen,
5394 struct nir_to_llvm_context *ctx,
5395 LLVMValueRef condition)
5396 {
5397 LLVMBasicBlockRef block = LLVMGetInsertBlock(ctx->builder);
5398
5399 memset(ifthen, 0, sizeof *ifthen);
5400 ifthen->ctx = ctx;
5401 ifthen->condition = condition;
5402 ifthen->entry_block = block;
5403
5404 /* create endif/merge basic block for the phi functions */
5405 ifthen->merge_block = ac_build_insert_new_block(ctx, "endif-block");
5406
5407 /* create/insert true_block before merge_block */
5408 ifthen->true_block =
5409 LLVMInsertBasicBlockInContext(ctx->context,
5410 ifthen->merge_block,
5411 "if-true-block");
5412
5413 /* successive code goes into the true block */
5414 LLVMPositionBuilderAtEnd(ctx->builder, ifthen->true_block);
5415 }
5416
5417 /**
5418 * End a conditional.
5419 */
5420 static void
5421 ac_nir_build_endif(struct ac_build_if_state *ifthen)
5422 {
5423 LLVMBuilderRef builder = ifthen->ctx->builder;
5424
5425 /* Insert branch to the merge block from current block */
5426 LLVMBuildBr(builder, ifthen->merge_block);
5427
5428 /*
5429 * Now patch in the various branch instructions.
5430 */
5431
5432 /* Insert the conditional branch instruction at the end of entry_block */
5433 LLVMPositionBuilderAtEnd(builder, ifthen->entry_block);
5434 if (ifthen->false_block) {
5435 /* we have an else clause */
5436 LLVMBuildCondBr(builder, ifthen->condition,
5437 ifthen->true_block, ifthen->false_block);
5438 }
5439 else {
5440 /* no else clause */
5441 LLVMBuildCondBr(builder, ifthen->condition,
5442 ifthen->true_block, ifthen->merge_block);
5443 }
5444
5445 /* Resume building code at end of the ifthen->merge_block */
5446 LLVMPositionBuilderAtEnd(builder, ifthen->merge_block);
5447 }
5448
5449 static void
5450 write_tess_factors(struct nir_to_llvm_context *ctx)
5451 {
5452 unsigned stride, outer_comps, inner_comps;
5453 struct ac_build_if_state if_ctx, inner_if_ctx;
5454 LLVMValueRef invocation_id = unpack_param(ctx, ctx->tcs_rel_ids, 8, 5);
5455 LLVMValueRef rel_patch_id = unpack_param(ctx, ctx->tcs_rel_ids, 0, 8);
5456 unsigned tess_inner_index, tess_outer_index;
5457 LLVMValueRef lds_base, lds_inner, lds_outer, byteoffset, buffer;
5458 LLVMValueRef out[6], vec0, vec1, tf_base, inner[4], outer[4];
5459 int i;
5460 emit_barrier(ctx);
5461
5462 switch (ctx->options->key.tcs.primitive_mode) {
5463 case GL_ISOLINES:
5464 stride = 2;
5465 outer_comps = 2;
5466 inner_comps = 0;
5467 break;
5468 case GL_TRIANGLES:
5469 stride = 4;
5470 outer_comps = 3;
5471 inner_comps = 1;
5472 break;
5473 case GL_QUADS:
5474 stride = 6;
5475 outer_comps = 4;
5476 inner_comps = 2;
5477 break;
5478 default:
5479 return;
5480 }
5481
5482 ac_nir_build_if(&if_ctx, ctx,
5483 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
5484 invocation_id, ctx->i32zero, ""));
5485
5486 tess_inner_index = shader_io_get_unique_index(VARYING_SLOT_TESS_LEVEL_INNER);
5487 tess_outer_index = shader_io_get_unique_index(VARYING_SLOT_TESS_LEVEL_OUTER);
5488
5489 mark_tess_output(ctx, true, tess_inner_index);
5490 mark_tess_output(ctx, true, tess_outer_index);
5491 lds_base = get_tcs_out_current_patch_data_offset(ctx);
5492 lds_inner = LLVMBuildAdd(ctx->builder, lds_base,
5493 LLVMConstInt(ctx->i32, tess_inner_index * 4, false), "");
5494 lds_outer = LLVMBuildAdd(ctx->builder, lds_base,
5495 LLVMConstInt(ctx->i32, tess_outer_index * 4, false), "");
5496
5497 for (i = 0; i < 4; i++) {
5498 inner[i] = LLVMGetUndef(ctx->i32);
5499 outer[i] = LLVMGetUndef(ctx->i32);
5500 }
5501
5502 // LINES reverseal
5503 if (ctx->options->key.tcs.primitive_mode == GL_ISOLINES) {
5504 outer[0] = out[1] = lds_load(ctx, lds_outer);
5505 lds_outer = LLVMBuildAdd(ctx->builder, lds_outer,
5506 LLVMConstInt(ctx->i32, 1, false), "");
5507 outer[1] = out[0] = lds_load(ctx, lds_outer);
5508 } else {
5509 for (i = 0; i < outer_comps; i++) {
5510 outer[i] = out[i] =
5511 lds_load(ctx, lds_outer);
5512 lds_outer = LLVMBuildAdd(ctx->builder, lds_outer,
5513 LLVMConstInt(ctx->i32, 1, false), "");
5514 }
5515 for (i = 0; i < inner_comps; i++) {
5516 inner[i] = out[outer_comps+i] =
5517 lds_load(ctx, lds_inner);
5518 lds_inner = LLVMBuildAdd(ctx->builder, lds_inner,
5519 LLVMConstInt(ctx->i32, 1, false), "");
5520 }
5521 }
5522
5523 /* Convert the outputs to vectors for stores. */
5524 vec0 = ac_build_gather_values(&ctx->ac, out, MIN2(stride, 4));
5525 vec1 = NULL;
5526
5527 if (stride > 4)
5528 vec1 = ac_build_gather_values(&ctx->ac, out + 4, stride - 4);
5529
5530
5531 buffer = ctx->hs_ring_tess_factor;
5532 tf_base = ctx->tess_factor_offset;
5533 byteoffset = LLVMBuildMul(ctx->builder, rel_patch_id,
5534 LLVMConstInt(ctx->i32, 4 * stride, false), "");
5535
5536 ac_nir_build_if(&inner_if_ctx, ctx,
5537 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
5538 rel_patch_id, ctx->i32zero, ""));
5539
5540 /* Store the dynamic HS control word. */
5541 ac_build_buffer_store_dword(&ctx->ac, buffer,
5542 LLVMConstInt(ctx->i32, 0x80000000, false),
5543 1, ctx->i32zero, tf_base,
5544 0, 1, 0, true, false);
5545 ac_nir_build_endif(&inner_if_ctx);
5546
5547 /* Store the tessellation factors. */
5548 ac_build_buffer_store_dword(&ctx->ac, buffer, vec0,
5549 MIN2(stride, 4), byteoffset, tf_base,
5550 4, 1, 0, true, false);
5551 if (vec1)
5552 ac_build_buffer_store_dword(&ctx->ac, buffer, vec1,
5553 stride - 4, byteoffset, tf_base,
5554 20, 1, 0, true, false);
5555
5556 //TODO store to offchip for TES to read - only if TES reads them
5557 if (1) {
5558 LLVMValueRef inner_vec, outer_vec, tf_outer_offset;
5559 LLVMValueRef tf_inner_offset;
5560 unsigned param_outer, param_inner;
5561
5562 param_outer = shader_io_get_unique_index(VARYING_SLOT_TESS_LEVEL_OUTER);
5563 tf_outer_offset = get_tcs_tes_buffer_address(ctx, NULL,
5564 LLVMConstInt(ctx->i32, param_outer, 0));
5565
5566 outer_vec = ac_build_gather_values(&ctx->ac, outer,
5567 util_next_power_of_two(outer_comps));
5568
5569 ac_build_buffer_store_dword(&ctx->ac, ctx->hs_ring_tess_offchip, outer_vec,
5570 outer_comps, tf_outer_offset,
5571 ctx->oc_lds, 0, 1, 0, true, false);
5572 if (inner_comps) {
5573 param_inner = shader_io_get_unique_index(VARYING_SLOT_TESS_LEVEL_INNER);
5574 tf_inner_offset = get_tcs_tes_buffer_address(ctx, NULL,
5575 LLVMConstInt(ctx->i32, param_inner, 0));
5576
5577 inner_vec = inner_comps == 1 ? inner[0] :
5578 ac_build_gather_values(&ctx->ac, inner, inner_comps);
5579 ac_build_buffer_store_dword(&ctx->ac, ctx->hs_ring_tess_offchip, inner_vec,
5580 inner_comps, tf_inner_offset,
5581 ctx->oc_lds, 0, 1, 0, true, false);
5582 }
5583 }
5584 ac_nir_build_endif(&if_ctx);
5585 }
5586
5587 static void
5588 handle_tcs_outputs_post(struct nir_to_llvm_context *ctx)
5589 {
5590 write_tess_factors(ctx);
5591 }
5592
5593 static bool
5594 si_export_mrt_color(struct nir_to_llvm_context *ctx,
5595 LLVMValueRef *color, unsigned param, bool is_last,
5596 struct ac_export_args *args)
5597 {
5598 /* Export */
5599 si_llvm_init_export_args(ctx, color, param,
5600 args);
5601
5602 if (is_last) {
5603 args->valid_mask = 1; /* whether the EXEC mask is valid */
5604 args->done = 1; /* DONE bit */
5605 } else if (!args->enabled_channels)
5606 return false; /* unnecessary NULL export */
5607
5608 return true;
5609 }
5610
5611 static void
5612 si_export_mrt_z(struct nir_to_llvm_context *ctx,
5613 LLVMValueRef depth, LLVMValueRef stencil,
5614 LLVMValueRef samplemask)
5615 {
5616 struct ac_export_args args;
5617
5618 args.enabled_channels = 0;
5619 args.valid_mask = 1;
5620 args.done = 1;
5621 args.target = V_008DFC_SQ_EXP_MRTZ;
5622 args.compr = false;
5623
5624 args.out[0] = LLVMGetUndef(ctx->f32); /* R, depth */
5625 args.out[1] = LLVMGetUndef(ctx->f32); /* G, stencil test val[0:7], stencil op val[8:15] */
5626 args.out[2] = LLVMGetUndef(ctx->f32); /* B, sample mask */
5627 args.out[3] = LLVMGetUndef(ctx->f32); /* A, alpha to mask */
5628
5629 if (depth) {
5630 args.out[0] = depth;
5631 args.enabled_channels |= 0x1;
5632 }
5633
5634 if (stencil) {
5635 args.out[1] = stencil;
5636 args.enabled_channels |= 0x2;
5637 }
5638
5639 if (samplemask) {
5640 args.out[2] = samplemask;
5641 args.enabled_channels |= 0x4;
5642 }
5643
5644 /* SI (except OLAND) has a bug that it only looks
5645 * at the X writemask component. */
5646 if (ctx->options->chip_class == SI &&
5647 ctx->options->family != CHIP_OLAND)
5648 args.enabled_channels |= 0x1;
5649
5650 ac_build_export(&ctx->ac, &args);
5651 }
5652
5653 static void
5654 handle_fs_outputs_post(struct nir_to_llvm_context *ctx)
5655 {
5656 unsigned index = 0;
5657 LLVMValueRef depth = NULL, stencil = NULL, samplemask = NULL;
5658 struct ac_export_args color_args[8];
5659
5660 for (unsigned i = 0; i < RADEON_LLVM_MAX_OUTPUTS; ++i) {
5661 LLVMValueRef values[4];
5662
5663 if (!(ctx->output_mask & (1ull << i)))
5664 continue;
5665
5666 if (i == FRAG_RESULT_DEPTH) {
5667 ctx->shader_info->fs.writes_z = true;
5668 depth = to_float(&ctx->ac, LLVMBuildLoad(ctx->builder,
5669 ctx->outputs[radeon_llvm_reg_index_soa(i, 0)], ""));
5670 } else if (i == FRAG_RESULT_STENCIL) {
5671 ctx->shader_info->fs.writes_stencil = true;
5672 stencil = to_float(&ctx->ac, LLVMBuildLoad(ctx->builder,
5673 ctx->outputs[radeon_llvm_reg_index_soa(i, 0)], ""));
5674 } else if (i == FRAG_RESULT_SAMPLE_MASK) {
5675 ctx->shader_info->fs.writes_sample_mask = true;
5676 samplemask = to_float(&ctx->ac, LLVMBuildLoad(ctx->builder,
5677 ctx->outputs[radeon_llvm_reg_index_soa(i, 0)], ""));
5678 } else {
5679 bool last = false;
5680 for (unsigned j = 0; j < 4; j++)
5681 values[j] = to_float(&ctx->ac, LLVMBuildLoad(ctx->builder,
5682 ctx->outputs[radeon_llvm_reg_index_soa(i, j)], ""));
5683
5684 if (!ctx->shader_info->fs.writes_z && !ctx->shader_info->fs.writes_stencil && !ctx->shader_info->fs.writes_sample_mask)
5685 last = ctx->output_mask <= ((1ull << (i + 1)) - 1);
5686
5687 bool ret = si_export_mrt_color(ctx, values, V_008DFC_SQ_EXP_MRT + (i - FRAG_RESULT_DATA0), last, &color_args[index]);
5688 if (ret)
5689 index++;
5690 }
5691 }
5692
5693 for (unsigned i = 0; i < index; i++)
5694 ac_build_export(&ctx->ac, &color_args[i]);
5695 if (depth || stencil || samplemask)
5696 si_export_mrt_z(ctx, depth, stencil, samplemask);
5697 else if (!index) {
5698 si_export_mrt_color(ctx, NULL, V_008DFC_SQ_EXP_NULL, true, &color_args[0]);
5699 ac_build_export(&ctx->ac, &color_args[0]);
5700 }
5701
5702 ctx->shader_info->fs.output_mask = index ? ((1ull << index) - 1) : 0;
5703 }
5704
5705 static void
5706 emit_gs_epilogue(struct nir_to_llvm_context *ctx)
5707 {
5708 ac_build_sendmsg(&ctx->ac, AC_SENDMSG_GS_OP_NOP | AC_SENDMSG_GS_DONE, ctx->gs_wave_id);
5709 }
5710
5711 static void
5712 handle_shader_outputs_post(struct nir_to_llvm_context *ctx)
5713 {
5714 switch (ctx->stage) {
5715 case MESA_SHADER_VERTEX:
5716 if (ctx->options->key.vs.as_ls)
5717 handle_ls_outputs_post(ctx);
5718 else if (ctx->options->key.vs.as_es)
5719 handle_es_outputs_post(ctx, &ctx->shader_info->vs.es_info);
5720 else
5721 handle_vs_outputs_post(ctx, ctx->options->key.vs.export_prim_id,
5722 &ctx->shader_info->vs.outinfo);
5723 break;
5724 case MESA_SHADER_FRAGMENT:
5725 handle_fs_outputs_post(ctx);
5726 break;
5727 case MESA_SHADER_GEOMETRY:
5728 emit_gs_epilogue(ctx);
5729 break;
5730 case MESA_SHADER_TESS_CTRL:
5731 handle_tcs_outputs_post(ctx);
5732 break;
5733 case MESA_SHADER_TESS_EVAL:
5734 if (ctx->options->key.tes.as_es)
5735 handle_es_outputs_post(ctx, &ctx->shader_info->tes.es_info);
5736 else
5737 handle_vs_outputs_post(ctx, ctx->options->key.tes.export_prim_id,
5738 &ctx->shader_info->tes.outinfo);
5739 break;
5740 default:
5741 break;
5742 }
5743 }
5744
5745 static void
5746 handle_shared_compute_var(struct nir_to_llvm_context *ctx,
5747 struct nir_variable *variable, uint32_t *offset, int idx)
5748 {
5749 unsigned size = glsl_count_attribute_slots(variable->type, false);
5750 variable->data.driver_location = *offset;
5751 *offset += size;
5752 }
5753
5754 static void ac_llvm_finalize_module(struct nir_to_llvm_context * ctx)
5755 {
5756 LLVMPassManagerRef passmgr;
5757 /* Create the pass manager */
5758 passmgr = LLVMCreateFunctionPassManagerForModule(
5759 ctx->module);
5760
5761 /* This pass should eliminate all the load and store instructions */
5762 LLVMAddPromoteMemoryToRegisterPass(passmgr);
5763
5764 /* Add some optimization passes */
5765 LLVMAddScalarReplAggregatesPass(passmgr);
5766 LLVMAddLICMPass(passmgr);
5767 LLVMAddAggressiveDCEPass(passmgr);
5768 LLVMAddCFGSimplificationPass(passmgr);
5769 LLVMAddInstructionCombiningPass(passmgr);
5770
5771 /* Run the pass */
5772 LLVMInitializeFunctionPassManager(passmgr);
5773 LLVMRunFunctionPassManager(passmgr, ctx->main_function);
5774 LLVMFinalizeFunctionPassManager(passmgr);
5775
5776 LLVMDisposeBuilder(ctx->builder);
5777 LLVMDisposePassManager(passmgr);
5778 }
5779
5780 static void
5781 ac_nir_eliminate_const_vs_outputs(struct nir_to_llvm_context *ctx)
5782 {
5783 struct ac_vs_output_info *outinfo;
5784
5785 switch (ctx->stage) {
5786 case MESA_SHADER_FRAGMENT:
5787 case MESA_SHADER_COMPUTE:
5788 case MESA_SHADER_TESS_CTRL:
5789 case MESA_SHADER_GEOMETRY:
5790 return;
5791 case MESA_SHADER_VERTEX:
5792 if (ctx->options->key.vs.as_ls ||
5793 ctx->options->key.vs.as_es)
5794 return;
5795 outinfo = &ctx->shader_info->vs.outinfo;
5796 break;
5797 case MESA_SHADER_TESS_EVAL:
5798 if (ctx->options->key.vs.as_es)
5799 return;
5800 outinfo = &ctx->shader_info->tes.outinfo;
5801 break;
5802 default:
5803 unreachable("Unhandled shader type");
5804 }
5805
5806 ac_optimize_vs_outputs(&ctx->ac,
5807 ctx->main_function,
5808 outinfo->vs_output_param_offset,
5809 VARYING_SLOT_MAX,
5810 &outinfo->param_exports);
5811 }
5812
5813 static void
5814 ac_setup_rings(struct nir_to_llvm_context *ctx)
5815 {
5816 if ((ctx->stage == MESA_SHADER_VERTEX && ctx->options->key.vs.as_es) ||
5817 (ctx->stage == MESA_SHADER_TESS_EVAL && ctx->options->key.tes.as_es)) {
5818 ctx->esgs_ring = ac_build_indexed_load_const(&ctx->ac, ctx->ring_offsets, LLVMConstInt(ctx->i32, RING_ESGS_VS, false));
5819 }
5820
5821 if (ctx->is_gs_copy_shader) {
5822 ctx->gsvs_ring = ac_build_indexed_load_const(&ctx->ac, ctx->ring_offsets, LLVMConstInt(ctx->i32, RING_GSVS_VS, false));
5823 }
5824 if (ctx->stage == MESA_SHADER_GEOMETRY) {
5825 LLVMValueRef tmp;
5826 ctx->esgs_ring = ac_build_indexed_load_const(&ctx->ac, ctx->ring_offsets, LLVMConstInt(ctx->i32, RING_ESGS_GS, false));
5827 ctx->gsvs_ring = ac_build_indexed_load_const(&ctx->ac, ctx->ring_offsets, LLVMConstInt(ctx->i32, RING_GSVS_GS, false));
5828
5829 ctx->gsvs_ring = LLVMBuildBitCast(ctx->builder, ctx->gsvs_ring, ctx->v4i32, "");
5830
5831 ctx->gsvs_ring = LLVMBuildInsertElement(ctx->builder, ctx->gsvs_ring, ctx->gsvs_num_entries, LLVMConstInt(ctx->i32, 2, false), "");
5832 tmp = LLVMBuildExtractElement(ctx->builder, ctx->gsvs_ring, ctx->i32one, "");
5833 tmp = LLVMBuildOr(ctx->builder, tmp, ctx->gsvs_ring_stride, "");
5834 ctx->gsvs_ring = LLVMBuildInsertElement(ctx->builder, ctx->gsvs_ring, tmp, ctx->i32one, "");
5835
5836 ctx->gsvs_ring = LLVMBuildBitCast(ctx->builder, ctx->gsvs_ring, ctx->v16i8, "");
5837 }
5838
5839 if (ctx->stage == MESA_SHADER_TESS_CTRL ||
5840 ctx->stage == MESA_SHADER_TESS_EVAL) {
5841 ctx->hs_ring_tess_offchip = ac_build_indexed_load_const(&ctx->ac, ctx->ring_offsets, LLVMConstInt(ctx->i32, RING_HS_TESS_OFFCHIP, false));
5842 ctx->hs_ring_tess_factor = ac_build_indexed_load_const(&ctx->ac, ctx->ring_offsets, LLVMConstInt(ctx->i32, RING_HS_TESS_FACTOR, false));
5843 }
5844 }
5845
5846 static unsigned
5847 ac_nir_get_max_workgroup_size(enum chip_class chip_class,
5848 const struct nir_shader *nir)
5849 {
5850 switch (nir->stage) {
5851 case MESA_SHADER_TESS_CTRL:
5852 return chip_class >= CIK ? 128 : 64;
5853 case MESA_SHADER_GEOMETRY:
5854 return 64;
5855 case MESA_SHADER_COMPUTE:
5856 break;
5857 default:
5858 return 0;
5859 }
5860
5861 unsigned max_workgroup_size = nir->info.cs.local_size[0] *
5862 nir->info.cs.local_size[1] *
5863 nir->info.cs.local_size[2];
5864 return max_workgroup_size;
5865 }
5866
5867 static
5868 LLVMModuleRef ac_translate_nir_to_llvm(LLVMTargetMachineRef tm,
5869 struct nir_shader *nir,
5870 struct ac_shader_variant_info *shader_info,
5871 const struct ac_nir_compiler_options *options)
5872 {
5873 struct nir_to_llvm_context ctx = {0};
5874 struct nir_function *func;
5875 unsigned i;
5876 ctx.options = options;
5877 ctx.shader_info = shader_info;
5878 ctx.context = LLVMContextCreate();
5879 ctx.module = LLVMModuleCreateWithNameInContext("shader", ctx.context);
5880
5881 ac_llvm_context_init(&ctx.ac, ctx.context);
5882 ctx.ac.module = ctx.module;
5883
5884 ctx.has_ds_bpermute = ctx.options->chip_class >= VI;
5885
5886 memset(shader_info, 0, sizeof(*shader_info));
5887
5888 ac_nir_shader_info_pass(nir, options, &shader_info->info);
5889
5890 LLVMSetTarget(ctx.module, options->supports_spill ? "amdgcn-mesa-mesa3d" : "amdgcn--");
5891
5892 LLVMTargetDataRef data_layout = LLVMCreateTargetDataLayout(tm);
5893 char *data_layout_str = LLVMCopyStringRepOfTargetData(data_layout);
5894 LLVMSetDataLayout(ctx.module, data_layout_str);
5895 LLVMDisposeTargetData(data_layout);
5896 LLVMDisposeMessage(data_layout_str);
5897
5898 setup_types(&ctx);
5899
5900 ctx.builder = LLVMCreateBuilderInContext(ctx.context);
5901 ctx.ac.builder = ctx.builder;
5902 ctx.stage = nir->stage;
5903 ctx.max_workgroup_size = ac_nir_get_max_workgroup_size(ctx.options->chip_class, nir);
5904
5905 for (i = 0; i < AC_UD_MAX_SETS; i++)
5906 shader_info->user_sgprs_locs.descriptor_sets[i].sgpr_idx = -1;
5907 for (i = 0; i < AC_UD_MAX_UD; i++)
5908 shader_info->user_sgprs_locs.shader_data[i].sgpr_idx = -1;
5909
5910 create_function(&ctx);
5911
5912 if (nir->stage == MESA_SHADER_COMPUTE) {
5913 int num_shared = 0;
5914 nir_foreach_variable(variable, &nir->shared)
5915 num_shared++;
5916 if (num_shared) {
5917 int idx = 0;
5918 uint32_t shared_size = 0;
5919 LLVMValueRef var;
5920 LLVMTypeRef i8p = LLVMPointerType(ctx.i8, LOCAL_ADDR_SPACE);
5921 nir_foreach_variable(variable, &nir->shared) {
5922 handle_shared_compute_var(&ctx, variable, &shared_size, idx);
5923 idx++;
5924 }
5925
5926 shared_size *= 16;
5927 var = LLVMAddGlobalInAddressSpace(ctx.module,
5928 LLVMArrayType(ctx.i8, shared_size),
5929 "compute_lds",
5930 LOCAL_ADDR_SPACE);
5931 LLVMSetAlignment(var, 4);
5932 ctx.shared_memory = LLVMBuildBitCast(ctx.builder, var, i8p, "");
5933 }
5934 } else if (nir->stage == MESA_SHADER_GEOMETRY) {
5935 ctx.gs_next_vertex = ac_build_alloca(&ctx, ctx.i32, "gs_next_vertex");
5936
5937 ctx.gs_max_out_vertices = nir->info.gs.vertices_out;
5938 } else if (nir->stage == MESA_SHADER_TESS_EVAL) {
5939 ctx.tes_primitive_mode = nir->info.tess.primitive_mode;
5940 }
5941
5942 ac_setup_rings(&ctx);
5943
5944 nir_foreach_variable(variable, &nir->inputs)
5945 handle_shader_input_decl(&ctx, variable);
5946
5947 if (nir->stage == MESA_SHADER_FRAGMENT)
5948 handle_fs_inputs_pre(&ctx, nir);
5949
5950 ctx.num_output_clips = nir->info.clip_distance_array_size;
5951 ctx.num_output_culls = nir->info.cull_distance_array_size;
5952
5953 nir_foreach_variable(variable, &nir->outputs)
5954 handle_shader_output_decl(&ctx, variable);
5955
5956 ctx.defs = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
5957 _mesa_key_pointer_equal);
5958 ctx.phis = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
5959 _mesa_key_pointer_equal);
5960
5961 func = (struct nir_function *)exec_list_get_head(&nir->functions);
5962
5963 setup_locals(&ctx, func);
5964
5965 visit_cf_list(&ctx, &func->impl->body);
5966 phi_post_pass(&ctx);
5967
5968 handle_shader_outputs_post(&ctx);
5969 LLVMBuildRetVoid(ctx.builder);
5970
5971 ac_llvm_finalize_module(&ctx);
5972
5973 ac_nir_eliminate_const_vs_outputs(&ctx);
5974 free(ctx.locals);
5975 ralloc_free(ctx.defs);
5976 ralloc_free(ctx.phis);
5977
5978 if (nir->stage == MESA_SHADER_GEOMETRY) {
5979 unsigned addclip = ctx.num_output_clips + ctx.num_output_culls > 4;
5980 shader_info->gs.gsvs_vertex_size = (util_bitcount64(ctx.output_mask) + addclip) * 16;
5981 shader_info->gs.max_gsvs_emit_size = shader_info->gs.gsvs_vertex_size *
5982 nir->info.gs.vertices_out;
5983 } else if (nir->stage == MESA_SHADER_TESS_CTRL) {
5984 shader_info->tcs.outputs_written = ctx.tess_outputs_written;
5985 shader_info->tcs.patch_outputs_written = ctx.tess_patch_outputs_written;
5986 } else if (nir->stage == MESA_SHADER_VERTEX && ctx.options->key.vs.as_ls) {
5987 shader_info->vs.outputs_written = ctx.tess_outputs_written;
5988 }
5989
5990 return ctx.module;
5991 }
5992
5993 static void ac_diagnostic_handler(LLVMDiagnosticInfoRef di, void *context)
5994 {
5995 unsigned *retval = (unsigned *)context;
5996 LLVMDiagnosticSeverity severity = LLVMGetDiagInfoSeverity(di);
5997 char *description = LLVMGetDiagInfoDescription(di);
5998
5999 if (severity == LLVMDSError) {
6000 *retval = 1;
6001 fprintf(stderr, "LLVM triggered Diagnostic Handler: %s\n",
6002 description);
6003 }
6004
6005 LLVMDisposeMessage(description);
6006 }
6007
6008 static unsigned ac_llvm_compile(LLVMModuleRef M,
6009 struct ac_shader_binary *binary,
6010 LLVMTargetMachineRef tm)
6011 {
6012 unsigned retval = 0;
6013 char *err;
6014 LLVMContextRef llvm_ctx;
6015 LLVMMemoryBufferRef out_buffer;
6016 unsigned buffer_size;
6017 const char *buffer_data;
6018 LLVMBool mem_err;
6019
6020 /* Setup Diagnostic Handler*/
6021 llvm_ctx = LLVMGetModuleContext(M);
6022
6023 LLVMContextSetDiagnosticHandler(llvm_ctx, ac_diagnostic_handler,
6024 &retval);
6025
6026 /* Compile IR*/
6027 mem_err = LLVMTargetMachineEmitToMemoryBuffer(tm, M, LLVMObjectFile,
6028 &err, &out_buffer);
6029
6030 /* Process Errors/Warnings */
6031 if (mem_err) {
6032 fprintf(stderr, "%s: %s", __FUNCTION__, err);
6033 free(err);
6034 retval = 1;
6035 goto out;
6036 }
6037
6038 /* Extract Shader Code*/
6039 buffer_size = LLVMGetBufferSize(out_buffer);
6040 buffer_data = LLVMGetBufferStart(out_buffer);
6041
6042 ac_elf_read(buffer_data, buffer_size, binary);
6043
6044 /* Clean up */
6045 LLVMDisposeMemoryBuffer(out_buffer);
6046
6047 out:
6048 return retval;
6049 }
6050
6051 static void ac_compile_llvm_module(LLVMTargetMachineRef tm,
6052 LLVMModuleRef llvm_module,
6053 struct ac_shader_binary *binary,
6054 struct ac_shader_config *config,
6055 struct ac_shader_variant_info *shader_info,
6056 gl_shader_stage stage,
6057 bool dump_shader, bool supports_spill)
6058 {
6059 if (dump_shader)
6060 ac_dump_module(llvm_module);
6061
6062 memset(binary, 0, sizeof(*binary));
6063 int v = ac_llvm_compile(llvm_module, binary, tm);
6064 if (v) {
6065 fprintf(stderr, "compile failed\n");
6066 }
6067
6068 if (dump_shader)
6069 fprintf(stderr, "disasm:\n%s\n", binary->disasm_string);
6070
6071 ac_shader_binary_read_config(binary, config, 0, supports_spill);
6072
6073 LLVMContextRef ctx = LLVMGetModuleContext(llvm_module);
6074 LLVMDisposeModule(llvm_module);
6075 LLVMContextDispose(ctx);
6076
6077 if (stage == MESA_SHADER_FRAGMENT) {
6078 shader_info->num_input_vgprs = 0;
6079 if (G_0286CC_PERSP_SAMPLE_ENA(config->spi_ps_input_addr))
6080 shader_info->num_input_vgprs += 2;
6081 if (G_0286CC_PERSP_CENTER_ENA(config->spi_ps_input_addr))
6082 shader_info->num_input_vgprs += 2;
6083 if (G_0286CC_PERSP_CENTROID_ENA(config->spi_ps_input_addr))
6084 shader_info->num_input_vgprs += 2;
6085 if (G_0286CC_PERSP_PULL_MODEL_ENA(config->spi_ps_input_addr))
6086 shader_info->num_input_vgprs += 3;
6087 if (G_0286CC_LINEAR_SAMPLE_ENA(config->spi_ps_input_addr))
6088 shader_info->num_input_vgprs += 2;
6089 if (G_0286CC_LINEAR_CENTER_ENA(config->spi_ps_input_addr))
6090 shader_info->num_input_vgprs += 2;
6091 if (G_0286CC_LINEAR_CENTROID_ENA(config->spi_ps_input_addr))
6092 shader_info->num_input_vgprs += 2;
6093 if (G_0286CC_LINE_STIPPLE_TEX_ENA(config->spi_ps_input_addr))
6094 shader_info->num_input_vgprs += 1;
6095 if (G_0286CC_POS_X_FLOAT_ENA(config->spi_ps_input_addr))
6096 shader_info->num_input_vgprs += 1;
6097 if (G_0286CC_POS_Y_FLOAT_ENA(config->spi_ps_input_addr))
6098 shader_info->num_input_vgprs += 1;
6099 if (G_0286CC_POS_Z_FLOAT_ENA(config->spi_ps_input_addr))
6100 shader_info->num_input_vgprs += 1;
6101 if (G_0286CC_POS_W_FLOAT_ENA(config->spi_ps_input_addr))
6102 shader_info->num_input_vgprs += 1;
6103 if (G_0286CC_FRONT_FACE_ENA(config->spi_ps_input_addr))
6104 shader_info->num_input_vgprs += 1;
6105 if (G_0286CC_ANCILLARY_ENA(config->spi_ps_input_addr))
6106 shader_info->num_input_vgprs += 1;
6107 if (G_0286CC_SAMPLE_COVERAGE_ENA(config->spi_ps_input_addr))
6108 shader_info->num_input_vgprs += 1;
6109 if (G_0286CC_POS_FIXED_PT_ENA(config->spi_ps_input_addr))
6110 shader_info->num_input_vgprs += 1;
6111 }
6112 config->num_vgprs = MAX2(config->num_vgprs, shader_info->num_input_vgprs);
6113
6114 /* +3 for scratch wave offset and VCC */
6115 config->num_sgprs = MAX2(config->num_sgprs,
6116 shader_info->num_input_sgprs + 3);
6117 }
6118
6119 void ac_compile_nir_shader(LLVMTargetMachineRef tm,
6120 struct ac_shader_binary *binary,
6121 struct ac_shader_config *config,
6122 struct ac_shader_variant_info *shader_info,
6123 struct nir_shader *nir,
6124 const struct ac_nir_compiler_options *options,
6125 bool dump_shader)
6126 {
6127
6128 LLVMModuleRef llvm_module = ac_translate_nir_to_llvm(tm, nir, shader_info,
6129 options);
6130
6131 ac_compile_llvm_module(tm, llvm_module, binary, config, shader_info, nir->stage, dump_shader, options->supports_spill);
6132 switch (nir->stage) {
6133 case MESA_SHADER_COMPUTE:
6134 for (int i = 0; i < 3; ++i)
6135 shader_info->cs.block_size[i] = nir->info.cs.local_size[i];
6136 break;
6137 case MESA_SHADER_FRAGMENT:
6138 shader_info->fs.early_fragment_test = nir->info.fs.early_fragment_tests;
6139 break;
6140 case MESA_SHADER_GEOMETRY:
6141 shader_info->gs.vertices_in = nir->info.gs.vertices_in;
6142 shader_info->gs.vertices_out = nir->info.gs.vertices_out;
6143 shader_info->gs.output_prim = nir->info.gs.output_primitive;
6144 shader_info->gs.invocations = nir->info.gs.invocations;
6145 break;
6146 case MESA_SHADER_TESS_EVAL:
6147 shader_info->tes.primitive_mode = nir->info.tess.primitive_mode;
6148 shader_info->tes.spacing = nir->info.tess.spacing;
6149 shader_info->tes.ccw = nir->info.tess.ccw;
6150 shader_info->tes.point_mode = nir->info.tess.point_mode;
6151 shader_info->tes.as_es = options->key.tes.as_es;
6152 break;
6153 case MESA_SHADER_TESS_CTRL:
6154 shader_info->tcs.tcs_vertices_out = nir->info.tess.tcs_vertices_out;
6155 break;
6156 case MESA_SHADER_VERTEX:
6157 shader_info->vs.as_es = options->key.vs.as_es;
6158 shader_info->vs.as_ls = options->key.vs.as_ls;
6159 /* in LS mode we need at least 1, invocation id needs 3, handled elsewhere */
6160 if (options->key.vs.as_ls)
6161 shader_info->vs.vgpr_comp_cnt = MAX2(1, shader_info->vs.vgpr_comp_cnt);
6162 break;
6163 default:
6164 break;
6165 }
6166 }
6167
6168 static void
6169 ac_gs_copy_shader_emit(struct nir_to_llvm_context *ctx)
6170 {
6171 LLVMValueRef args[9];
6172 args[0] = ctx->gsvs_ring;
6173 args[1] = LLVMBuildMul(ctx->builder, ctx->vertex_id, LLVMConstInt(ctx->i32, 4, false), "");
6174 args[3] = ctx->i32zero;
6175 args[4] = ctx->i32one; /* OFFEN */
6176 args[5] = ctx->i32zero; /* IDXEN */
6177 args[6] = ctx->i32one; /* GLC */
6178 args[7] = ctx->i32one; /* SLC */
6179 args[8] = ctx->i32zero; /* TFE */
6180
6181 int idx = 0;
6182
6183 for (unsigned i = 0; i < RADEON_LLVM_MAX_OUTPUTS; ++i) {
6184 int length = 4;
6185 int slot = idx;
6186 int slot_inc = 1;
6187 if (!(ctx->output_mask & (1ull << i)))
6188 continue;
6189
6190 if (i == VARYING_SLOT_CLIP_DIST0) {
6191 /* unpack clip and cull from a single set of slots */
6192 length = ctx->num_output_clips + ctx->num_output_culls;
6193 if (length > 4)
6194 slot_inc = 2;
6195 }
6196
6197 for (unsigned j = 0; j < length; j++) {
6198 LLVMValueRef value;
6199 args[2] = LLVMConstInt(ctx->i32,
6200 (slot * 4 + j) *
6201 ctx->gs_max_out_vertices * 16 * 4, false);
6202
6203 value = ac_build_intrinsic(&ctx->ac,
6204 "llvm.SI.buffer.load.dword.i32.i32",
6205 ctx->i32, args, 9,
6206 AC_FUNC_ATTR_READONLY |
6207 AC_FUNC_ATTR_LEGACY);
6208
6209 LLVMBuildStore(ctx->builder,
6210 to_float(&ctx->ac, value), ctx->outputs[radeon_llvm_reg_index_soa(i, j)]);
6211 }
6212 idx += slot_inc;
6213 }
6214 handle_vs_outputs_post(ctx, false, &ctx->shader_info->vs.outinfo);
6215 }
6216
6217 void ac_create_gs_copy_shader(LLVMTargetMachineRef tm,
6218 struct nir_shader *geom_shader,
6219 struct ac_shader_binary *binary,
6220 struct ac_shader_config *config,
6221 struct ac_shader_variant_info *shader_info,
6222 const struct ac_nir_compiler_options *options,
6223 bool dump_shader)
6224 {
6225 struct nir_to_llvm_context ctx = {0};
6226 ctx.context = LLVMContextCreate();
6227 ctx.module = LLVMModuleCreateWithNameInContext("shader", ctx.context);
6228 ctx.options = options;
6229 ctx.shader_info = shader_info;
6230
6231 ac_llvm_context_init(&ctx.ac, ctx.context);
6232 ctx.ac.module = ctx.module;
6233
6234 ctx.is_gs_copy_shader = true;
6235 LLVMSetTarget(ctx.module, "amdgcn--");
6236 setup_types(&ctx);
6237
6238 ctx.builder = LLVMCreateBuilderInContext(ctx.context);
6239 ctx.ac.builder = ctx.builder;
6240 ctx.stage = MESA_SHADER_VERTEX;
6241
6242 create_function(&ctx);
6243
6244 ctx.gs_max_out_vertices = geom_shader->info.gs.vertices_out;
6245 ac_setup_rings(&ctx);
6246
6247 ctx.num_output_clips = geom_shader->info.clip_distance_array_size;
6248 ctx.num_output_culls = geom_shader->info.cull_distance_array_size;
6249
6250 nir_foreach_variable(variable, &geom_shader->outputs)
6251 handle_shader_output_decl(&ctx, variable);
6252
6253 ac_gs_copy_shader_emit(&ctx);
6254
6255 LLVMBuildRetVoid(ctx.builder);
6256
6257 ac_llvm_finalize_module(&ctx);
6258
6259 ac_compile_llvm_module(tm, ctx.module, binary, config, shader_info,
6260 MESA_SHADER_VERTEX,
6261 dump_shader, options->supports_spill);
6262 }