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