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