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