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