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