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