2 * Copyright 2014 Advanced Micro Devices, Inc.
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sub license, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
12 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
15 * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
16 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
17 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
18 * USE OR OTHER DEALINGS IN THE SOFTWARE.
20 * The above copyright notice and this permission notice (including the
21 * next paragraph) shall be included in all copies or substantial portions
25 /* based on pieces from si_pipe.c and radeon_llvm_emit.c */
26 #include "ac_llvm_build.h"
28 #include <llvm-c/Core.h>
29 #include <llvm/Config/llvm-config.h>
31 #include "c11/threads.h"
36 #include "ac_llvm_util.h"
37 #include "ac_shader_util.h"
38 #include "ac_exp_param.h"
39 #include "util/bitscan.h"
40 #include "util/macros.h"
41 #include "util/u_atomic.h"
42 #include "util/u_math.h"
45 #include "shader_enums.h"
47 #define AC_LLVM_INITIAL_CF_DEPTH 4
49 /* Data for if/else/endif and bgnloop/endloop control flow structures.
52 /* Loop exit or next part of if/else/endif. */
53 LLVMBasicBlockRef next_block;
54 LLVMBasicBlockRef loop_entry_block;
57 /* Initialize module-independent parts of the context.
59 * The caller is responsible for initializing ctx::module and ctx::builder.
62 ac_llvm_context_init(struct ac_llvm_context *ctx,
63 struct ac_llvm_compiler *compiler,
64 enum chip_class chip_class, enum radeon_family family,
65 enum ac_float_mode float_mode, unsigned wave_size,
66 unsigned ballot_mask_bits)
70 ctx->context = LLVMContextCreate();
72 ctx->chip_class = chip_class;
74 ctx->wave_size = wave_size;
75 ctx->ballot_mask_bits = ballot_mask_bits;
76 ctx->float_mode = float_mode;
77 ctx->module = ac_create_module(wave_size == 32 ? compiler->tm_wave32
80 ctx->builder = ac_create_builder(ctx->context, float_mode);
82 ctx->voidt = LLVMVoidTypeInContext(ctx->context);
83 ctx->i1 = LLVMInt1TypeInContext(ctx->context);
84 ctx->i8 = LLVMInt8TypeInContext(ctx->context);
85 ctx->i16 = LLVMIntTypeInContext(ctx->context, 16);
86 ctx->i32 = LLVMIntTypeInContext(ctx->context, 32);
87 ctx->i64 = LLVMIntTypeInContext(ctx->context, 64);
88 ctx->intptr = ctx->i32;
89 ctx->f16 = LLVMHalfTypeInContext(ctx->context);
90 ctx->f32 = LLVMFloatTypeInContext(ctx->context);
91 ctx->f64 = LLVMDoubleTypeInContext(ctx->context);
92 ctx->v2i16 = LLVMVectorType(ctx->i16, 2);
93 ctx->v2i32 = LLVMVectorType(ctx->i32, 2);
94 ctx->v3i32 = LLVMVectorType(ctx->i32, 3);
95 ctx->v4i32 = LLVMVectorType(ctx->i32, 4);
96 ctx->v2f32 = LLVMVectorType(ctx->f32, 2);
97 ctx->v3f32 = LLVMVectorType(ctx->f32, 3);
98 ctx->v4f32 = LLVMVectorType(ctx->f32, 4);
99 ctx->v8i32 = LLVMVectorType(ctx->i32, 8);
100 ctx->iN_wavemask = LLVMIntTypeInContext(ctx->context, ctx->wave_size);
101 ctx->iN_ballotmask = LLVMIntTypeInContext(ctx->context, ballot_mask_bits);
103 ctx->i8_0 = LLVMConstInt(ctx->i8, 0, false);
104 ctx->i8_1 = LLVMConstInt(ctx->i8, 1, false);
105 ctx->i16_0 = LLVMConstInt(ctx->i16, 0, false);
106 ctx->i16_1 = LLVMConstInt(ctx->i16, 1, false);
107 ctx->i32_0 = LLVMConstInt(ctx->i32, 0, false);
108 ctx->i32_1 = LLVMConstInt(ctx->i32, 1, false);
109 ctx->i64_0 = LLVMConstInt(ctx->i64, 0, false);
110 ctx->i64_1 = LLVMConstInt(ctx->i64, 1, false);
111 ctx->f16_0 = LLVMConstReal(ctx->f16, 0.0);
112 ctx->f16_1 = LLVMConstReal(ctx->f16, 1.0);
113 ctx->f32_0 = LLVMConstReal(ctx->f32, 0.0);
114 ctx->f32_1 = LLVMConstReal(ctx->f32, 1.0);
115 ctx->f64_0 = LLVMConstReal(ctx->f64, 0.0);
116 ctx->f64_1 = LLVMConstReal(ctx->f64, 1.0);
118 ctx->i1false = LLVMConstInt(ctx->i1, 0, false);
119 ctx->i1true = LLVMConstInt(ctx->i1, 1, false);
121 ctx->range_md_kind = LLVMGetMDKindIDInContext(ctx->context,
124 ctx->invariant_load_md_kind = LLVMGetMDKindIDInContext(ctx->context,
125 "invariant.load", 14);
127 ctx->fpmath_md_kind = LLVMGetMDKindIDInContext(ctx->context, "fpmath", 6);
129 args[0] = LLVMConstReal(ctx->f32, 2.5);
130 ctx->fpmath_md_2p5_ulp = LLVMMDNodeInContext(ctx->context, args, 1);
132 ctx->uniform_md_kind = LLVMGetMDKindIDInContext(ctx->context,
133 "amdgpu.uniform", 14);
135 ctx->empty_md = LLVMMDNodeInContext(ctx->context, NULL, 0);
136 ctx->flow = calloc(1, sizeof(*ctx->flow));
140 ac_llvm_context_dispose(struct ac_llvm_context *ctx)
142 free(ctx->flow->stack);
148 ac_get_llvm_num_components(LLVMValueRef value)
150 LLVMTypeRef type = LLVMTypeOf(value);
151 unsigned num_components = LLVMGetTypeKind(type) == LLVMVectorTypeKind
152 ? LLVMGetVectorSize(type)
154 return num_components;
158 ac_llvm_extract_elem(struct ac_llvm_context *ac,
162 if (LLVMGetTypeKind(LLVMTypeOf(value)) != LLVMVectorTypeKind) {
167 return LLVMBuildExtractElement(ac->builder, value,
168 LLVMConstInt(ac->i32, index, false), "");
172 ac_get_elem_bits(struct ac_llvm_context *ctx, LLVMTypeRef type)
174 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind)
175 type = LLVMGetElementType(type);
177 if (LLVMGetTypeKind(type) == LLVMIntegerTypeKind)
178 return LLVMGetIntTypeWidth(type);
180 if (type == ctx->f16)
182 if (type == ctx->f32)
184 if (type == ctx->f64)
187 unreachable("Unhandled type kind in get_elem_bits");
191 ac_get_type_size(LLVMTypeRef type)
193 LLVMTypeKind kind = LLVMGetTypeKind(type);
196 case LLVMIntegerTypeKind:
197 return LLVMGetIntTypeWidth(type) / 8;
198 case LLVMHalfTypeKind:
200 case LLVMFloatTypeKind:
202 case LLVMDoubleTypeKind:
204 case LLVMPointerTypeKind:
205 if (LLVMGetPointerAddressSpace(type) == AC_ADDR_SPACE_CONST_32BIT)
208 case LLVMVectorTypeKind:
209 return LLVMGetVectorSize(type) *
210 ac_get_type_size(LLVMGetElementType(type));
211 case LLVMArrayTypeKind:
212 return LLVMGetArrayLength(type) *
213 ac_get_type_size(LLVMGetElementType(type));
220 static LLVMTypeRef to_integer_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
224 else if (t == ctx->f16 || t == ctx->i16)
226 else if (t == ctx->f32 || t == ctx->i32)
228 else if (t == ctx->f64 || t == ctx->i64)
231 unreachable("Unhandled integer size");
235 ac_to_integer_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
237 if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
238 LLVMTypeRef elem_type = LLVMGetElementType(t);
239 return LLVMVectorType(to_integer_type_scalar(ctx, elem_type),
240 LLVMGetVectorSize(t));
242 if (LLVMGetTypeKind(t) == LLVMPointerTypeKind) {
243 switch (LLVMGetPointerAddressSpace(t)) {
244 case AC_ADDR_SPACE_GLOBAL:
246 case AC_ADDR_SPACE_CONST_32BIT:
247 case AC_ADDR_SPACE_LDS:
250 unreachable("unhandled address space");
253 return to_integer_type_scalar(ctx, t);
257 ac_to_integer(struct ac_llvm_context *ctx, LLVMValueRef v)
259 LLVMTypeRef type = LLVMTypeOf(v);
260 if (LLVMGetTypeKind(type) == LLVMPointerTypeKind) {
261 return LLVMBuildPtrToInt(ctx->builder, v, ac_to_integer_type(ctx, type), "");
263 return LLVMBuildBitCast(ctx->builder, v, ac_to_integer_type(ctx, type), "");
267 ac_to_integer_or_pointer(struct ac_llvm_context *ctx, LLVMValueRef v)
269 LLVMTypeRef type = LLVMTypeOf(v);
270 if (LLVMGetTypeKind(type) == LLVMPointerTypeKind)
272 return ac_to_integer(ctx, v);
275 static LLVMTypeRef to_float_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
279 else if (t == ctx->i16 || t == ctx->f16)
281 else if (t == ctx->i32 || t == ctx->f32)
283 else if (t == ctx->i64 || t == ctx->f64)
286 unreachable("Unhandled float size");
290 ac_to_float_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
292 if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
293 LLVMTypeRef elem_type = LLVMGetElementType(t);
294 return LLVMVectorType(to_float_type_scalar(ctx, elem_type),
295 LLVMGetVectorSize(t));
297 return to_float_type_scalar(ctx, t);
301 ac_to_float(struct ac_llvm_context *ctx, LLVMValueRef v)
303 LLVMTypeRef type = LLVMTypeOf(v);
304 return LLVMBuildBitCast(ctx->builder, v, ac_to_float_type(ctx, type), "");
309 ac_build_intrinsic(struct ac_llvm_context *ctx, const char *name,
310 LLVMTypeRef return_type, LLVMValueRef *params,
311 unsigned param_count, unsigned attrib_mask)
313 LLVMValueRef function, call;
314 bool set_callsite_attrs = !(attrib_mask & AC_FUNC_ATTR_LEGACY);
316 function = LLVMGetNamedFunction(ctx->module, name);
318 LLVMTypeRef param_types[32], function_type;
321 assert(param_count <= 32);
323 for (i = 0; i < param_count; ++i) {
325 param_types[i] = LLVMTypeOf(params[i]);
328 LLVMFunctionType(return_type, param_types, param_count, 0);
329 function = LLVMAddFunction(ctx->module, name, function_type);
331 LLVMSetFunctionCallConv(function, LLVMCCallConv);
332 LLVMSetLinkage(function, LLVMExternalLinkage);
334 if (!set_callsite_attrs)
335 ac_add_func_attributes(ctx->context, function, attrib_mask);
338 call = LLVMBuildCall(ctx->builder, function, params, param_count, "");
339 if (set_callsite_attrs)
340 ac_add_func_attributes(ctx->context, call, attrib_mask);
345 * Given the i32 or vNi32 \p type, generate the textual name (e.g. for use with
348 void ac_build_type_name_for_intr(LLVMTypeRef type, char *buf, unsigned bufsize)
350 LLVMTypeRef elem_type = type;
352 assert(bufsize >= 8);
354 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind) {
355 int ret = snprintf(buf, bufsize, "v%u",
356 LLVMGetVectorSize(type));
358 char *type_name = LLVMPrintTypeToString(type);
359 fprintf(stderr, "Error building type name for: %s\n",
361 LLVMDisposeMessage(type_name);
364 elem_type = LLVMGetElementType(type);
368 switch (LLVMGetTypeKind(elem_type)) {
370 case LLVMIntegerTypeKind:
371 snprintf(buf, bufsize, "i%d", LLVMGetIntTypeWidth(elem_type));
373 case LLVMHalfTypeKind:
374 snprintf(buf, bufsize, "f16");
376 case LLVMFloatTypeKind:
377 snprintf(buf, bufsize, "f32");
379 case LLVMDoubleTypeKind:
380 snprintf(buf, bufsize, "f64");
386 * Helper function that builds an LLVM IR PHI node and immediately adds
390 ac_build_phi(struct ac_llvm_context *ctx, LLVMTypeRef type,
391 unsigned count_incoming, LLVMValueRef *values,
392 LLVMBasicBlockRef *blocks)
394 LLVMValueRef phi = LLVMBuildPhi(ctx->builder, type, "");
395 LLVMAddIncoming(phi, values, blocks, count_incoming);
399 void ac_build_s_barrier(struct ac_llvm_context *ctx)
401 ac_build_intrinsic(ctx, "llvm.amdgcn.s.barrier", ctx->voidt, NULL,
402 0, AC_FUNC_ATTR_CONVERGENT);
405 /* Prevent optimizations (at least of memory accesses) across the current
406 * point in the program by emitting empty inline assembly that is marked as
407 * having side effects.
409 * Optionally, a value can be passed through the inline assembly to prevent
410 * LLVM from hoisting calls to ReadNone functions.
413 ac_build_optimization_barrier(struct ac_llvm_context *ctx,
416 static int counter = 0;
418 LLVMBuilderRef builder = ctx->builder;
421 snprintf(code, sizeof(code), "; %d", p_atomic_inc_return(&counter));
424 LLVMTypeRef ftype = LLVMFunctionType(ctx->voidt, NULL, 0, false);
425 LLVMValueRef inlineasm = LLVMConstInlineAsm(ftype, code, "", true, false);
426 LLVMBuildCall(builder, inlineasm, NULL, 0, "");
428 LLVMTypeRef ftype = LLVMFunctionType(ctx->i32, &ctx->i32, 1, false);
429 LLVMValueRef inlineasm = LLVMConstInlineAsm(ftype, code, "=v,0", true, false);
430 LLVMValueRef vgpr = *pvgpr;
431 LLVMTypeRef vgpr_type = LLVMTypeOf(vgpr);
432 unsigned vgpr_size = ac_get_type_size(vgpr_type);
435 assert(vgpr_size % 4 == 0);
437 vgpr = LLVMBuildBitCast(builder, vgpr, LLVMVectorType(ctx->i32, vgpr_size / 4), "");
438 vgpr0 = LLVMBuildExtractElement(builder, vgpr, ctx->i32_0, "");
439 vgpr0 = LLVMBuildCall(builder, inlineasm, &vgpr0, 1, "");
440 vgpr = LLVMBuildInsertElement(builder, vgpr, vgpr0, ctx->i32_0, "");
441 vgpr = LLVMBuildBitCast(builder, vgpr, vgpr_type, "");
448 ac_build_shader_clock(struct ac_llvm_context *ctx)
450 const char *intr = LLVM_VERSION_MAJOR >= 9 && ctx->chip_class >= GFX8 ?
451 "llvm.amdgcn.s.memrealtime" : "llvm.readcyclecounter";
452 LLVMValueRef tmp = ac_build_intrinsic(ctx, intr, ctx->i64, NULL, 0, 0);
453 return LLVMBuildBitCast(ctx->builder, tmp, ctx->v2i32, "");
457 ac_build_ballot(struct ac_llvm_context *ctx,
462 if (LLVM_VERSION_MAJOR >= 9) {
463 if (ctx->wave_size == 64)
464 name = "llvm.amdgcn.icmp.i64.i32";
466 name = "llvm.amdgcn.icmp.i32.i32";
468 name = "llvm.amdgcn.icmp.i32";
470 LLVMValueRef args[3] = {
473 LLVMConstInt(ctx->i32, LLVMIntNE, 0)
476 /* We currently have no other way to prevent LLVM from lifting the icmp
477 * calls to a dominating basic block.
479 ac_build_optimization_barrier(ctx, &args[0]);
481 args[0] = ac_to_integer(ctx, args[0]);
483 return ac_build_intrinsic(ctx, name, ctx->iN_wavemask, args, 3,
484 AC_FUNC_ATTR_NOUNWIND |
485 AC_FUNC_ATTR_READNONE |
486 AC_FUNC_ATTR_CONVERGENT);
489 LLVMValueRef ac_get_i1_sgpr_mask(struct ac_llvm_context *ctx,
492 const char *name = LLVM_VERSION_MAJOR >= 9 ? "llvm.amdgcn.icmp.i64.i1" : "llvm.amdgcn.icmp.i1";
493 LLVMValueRef args[3] = {
496 LLVMConstInt(ctx->i32, LLVMIntNE, 0),
499 return ac_build_intrinsic(ctx, name, ctx->i64, args, 3,
500 AC_FUNC_ATTR_NOUNWIND |
501 AC_FUNC_ATTR_READNONE |
502 AC_FUNC_ATTR_CONVERGENT);
506 ac_build_vote_all(struct ac_llvm_context *ctx, LLVMValueRef value)
508 LLVMValueRef active_set = ac_build_ballot(ctx, ctx->i32_1);
509 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
510 return LLVMBuildICmp(ctx->builder, LLVMIntEQ, vote_set, active_set, "");
514 ac_build_vote_any(struct ac_llvm_context *ctx, LLVMValueRef value)
516 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
517 return LLVMBuildICmp(ctx->builder, LLVMIntNE, vote_set,
518 LLVMConstInt(ctx->iN_wavemask, 0, 0), "");
522 ac_build_vote_eq(struct ac_llvm_context *ctx, LLVMValueRef value)
524 LLVMValueRef active_set = ac_build_ballot(ctx, ctx->i32_1);
525 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
527 LLVMValueRef all = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
528 vote_set, active_set, "");
529 LLVMValueRef none = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
531 LLVMConstInt(ctx->iN_wavemask, 0, 0), "");
532 return LLVMBuildOr(ctx->builder, all, none, "");
536 ac_build_varying_gather_values(struct ac_llvm_context *ctx, LLVMValueRef *values,
537 unsigned value_count, unsigned component)
539 LLVMValueRef vec = NULL;
541 if (value_count == 1) {
542 return values[component];
543 } else if (!value_count)
544 unreachable("value_count is 0");
546 for (unsigned i = component; i < value_count + component; i++) {
547 LLVMValueRef value = values[i];
550 vec = LLVMGetUndef( LLVMVectorType(LLVMTypeOf(value), value_count));
551 LLVMValueRef index = LLVMConstInt(ctx->i32, i - component, false);
552 vec = LLVMBuildInsertElement(ctx->builder, vec, value, index, "");
558 ac_build_gather_values_extended(struct ac_llvm_context *ctx,
559 LLVMValueRef *values,
560 unsigned value_count,
561 unsigned value_stride,
565 LLVMBuilderRef builder = ctx->builder;
566 LLVMValueRef vec = NULL;
569 if (value_count == 1 && !always_vector) {
571 return LLVMBuildLoad(builder, values[0], "");
573 } else if (!value_count)
574 unreachable("value_count is 0");
576 for (i = 0; i < value_count; i++) {
577 LLVMValueRef value = values[i * value_stride];
579 value = LLVMBuildLoad(builder, value, "");
582 vec = LLVMGetUndef( LLVMVectorType(LLVMTypeOf(value), value_count));
583 LLVMValueRef index = LLVMConstInt(ctx->i32, i, false);
584 vec = LLVMBuildInsertElement(builder, vec, value, index, "");
590 ac_build_gather_values(struct ac_llvm_context *ctx,
591 LLVMValueRef *values,
592 unsigned value_count)
594 return ac_build_gather_values_extended(ctx, values, value_count, 1, false, false);
597 /* Expand a scalar or vector to <dst_channels x type> by filling the remaining
598 * channels with undef. Extract at most src_channels components from the input.
601 ac_build_expand(struct ac_llvm_context *ctx,
603 unsigned src_channels,
604 unsigned dst_channels)
606 LLVMTypeRef elemtype;
607 LLVMValueRef chan[dst_channels];
609 if (LLVMGetTypeKind(LLVMTypeOf(value)) == LLVMVectorTypeKind) {
610 unsigned vec_size = LLVMGetVectorSize(LLVMTypeOf(value));
612 if (src_channels == dst_channels && vec_size == dst_channels)
615 src_channels = MIN2(src_channels, vec_size);
617 for (unsigned i = 0; i < src_channels; i++)
618 chan[i] = ac_llvm_extract_elem(ctx, value, i);
620 elemtype = LLVMGetElementType(LLVMTypeOf(value));
623 assert(src_channels == 1);
626 elemtype = LLVMTypeOf(value);
629 for (unsigned i = src_channels; i < dst_channels; i++)
630 chan[i] = LLVMGetUndef(elemtype);
632 return ac_build_gather_values(ctx, chan, dst_channels);
635 /* Extract components [start, start + channels) from a vector.
638 ac_extract_components(struct ac_llvm_context *ctx,
643 LLVMValueRef chan[channels];
645 for (unsigned i = 0; i < channels; i++)
646 chan[i] = ac_llvm_extract_elem(ctx, value, i + start);
648 return ac_build_gather_values(ctx, chan, channels);
651 /* Expand a scalar or vector to <4 x type> by filling the remaining channels
652 * with undef. Extract at most num_channels components from the input.
654 LLVMValueRef ac_build_expand_to_vec4(struct ac_llvm_context *ctx,
656 unsigned num_channels)
658 return ac_build_expand(ctx, value, num_channels, 4);
661 LLVMValueRef ac_build_round(struct ac_llvm_context *ctx, LLVMValueRef value)
663 unsigned type_size = ac_get_type_size(LLVMTypeOf(value));
667 name = "llvm.rint.f16";
668 else if (type_size == 4)
669 name = "llvm.rint.f32";
671 name = "llvm.rint.f64";
673 return ac_build_intrinsic(ctx, name, LLVMTypeOf(value), &value, 1,
674 AC_FUNC_ATTR_READNONE);
678 ac_build_fdiv(struct ac_llvm_context *ctx,
682 /* If we do (num / den), LLVM >= 7.0 does:
683 * return num * v_rcp_f32(den * (fabs(den) > 0x1.0p+96f ? 0x1.0p-32f : 1.0f));
685 * If we do (num * (1 / den)), LLVM does:
686 * return num * v_rcp_f32(den);
688 LLVMValueRef one = LLVMConstReal(LLVMTypeOf(num), 1.0);
689 LLVMValueRef rcp = LLVMBuildFDiv(ctx->builder, one, den, "");
690 LLVMValueRef ret = LLVMBuildFMul(ctx->builder, num, rcp, "");
692 /* Use v_rcp_f32 instead of precise division. */
693 if (!LLVMIsConstant(ret))
694 LLVMSetMetadata(ret, ctx->fpmath_md_kind, ctx->fpmath_md_2p5_ulp);
698 /* See fast_idiv_by_const.h. */
699 /* Set: increment = util_fast_udiv_info::increment ? multiplier : 0; */
700 LLVMValueRef ac_build_fast_udiv(struct ac_llvm_context *ctx,
702 LLVMValueRef multiplier,
703 LLVMValueRef pre_shift,
704 LLVMValueRef post_shift,
705 LLVMValueRef increment)
707 LLVMBuilderRef builder = ctx->builder;
709 num = LLVMBuildLShr(builder, num, pre_shift, "");
710 num = LLVMBuildMul(builder,
711 LLVMBuildZExt(builder, num, ctx->i64, ""),
712 LLVMBuildZExt(builder, multiplier, ctx->i64, ""), "");
713 num = LLVMBuildAdd(builder, num,
714 LLVMBuildZExt(builder, increment, ctx->i64, ""), "");
715 num = LLVMBuildLShr(builder, num, LLVMConstInt(ctx->i64, 32, 0), "");
716 num = LLVMBuildTrunc(builder, num, ctx->i32, "");
717 return LLVMBuildLShr(builder, num, post_shift, "");
720 /* See fast_idiv_by_const.h. */
721 /* If num != UINT_MAX, this more efficient version can be used. */
722 /* Set: increment = util_fast_udiv_info::increment; */
723 LLVMValueRef ac_build_fast_udiv_nuw(struct ac_llvm_context *ctx,
725 LLVMValueRef multiplier,
726 LLVMValueRef pre_shift,
727 LLVMValueRef post_shift,
728 LLVMValueRef increment)
730 LLVMBuilderRef builder = ctx->builder;
732 num = LLVMBuildLShr(builder, num, pre_shift, "");
733 num = LLVMBuildNUWAdd(builder, num, increment, "");
734 num = LLVMBuildMul(builder,
735 LLVMBuildZExt(builder, num, ctx->i64, ""),
736 LLVMBuildZExt(builder, multiplier, ctx->i64, ""), "");
737 num = LLVMBuildLShr(builder, num, LLVMConstInt(ctx->i64, 32, 0), "");
738 num = LLVMBuildTrunc(builder, num, ctx->i32, "");
739 return LLVMBuildLShr(builder, num, post_shift, "");
742 /* See fast_idiv_by_const.h. */
743 /* Both operands must fit in 31 bits and the divisor must not be 1. */
744 LLVMValueRef ac_build_fast_udiv_u31_d_not_one(struct ac_llvm_context *ctx,
746 LLVMValueRef multiplier,
747 LLVMValueRef post_shift)
749 LLVMBuilderRef builder = ctx->builder;
751 num = LLVMBuildMul(builder,
752 LLVMBuildZExt(builder, num, ctx->i64, ""),
753 LLVMBuildZExt(builder, multiplier, ctx->i64, ""), "");
754 num = LLVMBuildLShr(builder, num, LLVMConstInt(ctx->i64, 32, 0), "");
755 num = LLVMBuildTrunc(builder, num, ctx->i32, "");
756 return LLVMBuildLShr(builder, num, post_shift, "");
759 /* Coordinates for cube map selection. sc, tc, and ma are as in Table 8.27
760 * of the OpenGL 4.5 (Compatibility Profile) specification, except ma is
761 * already multiplied by two. id is the cube face number.
763 struct cube_selection_coords {
770 build_cube_intrinsic(struct ac_llvm_context *ctx,
772 struct cube_selection_coords *out)
774 LLVMTypeRef f32 = ctx->f32;
776 out->stc[1] = ac_build_intrinsic(ctx, "llvm.amdgcn.cubetc",
777 f32, in, 3, AC_FUNC_ATTR_READNONE);
778 out->stc[0] = ac_build_intrinsic(ctx, "llvm.amdgcn.cubesc",
779 f32, in, 3, AC_FUNC_ATTR_READNONE);
780 out->ma = ac_build_intrinsic(ctx, "llvm.amdgcn.cubema",
781 f32, in, 3, AC_FUNC_ATTR_READNONE);
782 out->id = ac_build_intrinsic(ctx, "llvm.amdgcn.cubeid",
783 f32, in, 3, AC_FUNC_ATTR_READNONE);
787 * Build a manual selection sequence for cube face sc/tc coordinates and
788 * major axis vector (multiplied by 2 for consistency) for the given
789 * vec3 \p coords, for the face implied by \p selcoords.
791 * For the major axis, we always adjust the sign to be in the direction of
792 * selcoords.ma; i.e., a positive out_ma means that coords is pointed towards
793 * the selcoords major axis.
795 static void build_cube_select(struct ac_llvm_context *ctx,
796 const struct cube_selection_coords *selcoords,
797 const LLVMValueRef *coords,
798 LLVMValueRef *out_st,
799 LLVMValueRef *out_ma)
801 LLVMBuilderRef builder = ctx->builder;
802 LLVMTypeRef f32 = LLVMTypeOf(coords[0]);
803 LLVMValueRef is_ma_positive;
805 LLVMValueRef is_ma_z, is_not_ma_z;
806 LLVMValueRef is_ma_y;
807 LLVMValueRef is_ma_x;
811 is_ma_positive = LLVMBuildFCmp(builder, LLVMRealUGE,
812 selcoords->ma, LLVMConstReal(f32, 0.0), "");
813 sgn_ma = LLVMBuildSelect(builder, is_ma_positive,
814 LLVMConstReal(f32, 1.0), LLVMConstReal(f32, -1.0), "");
816 is_ma_z = LLVMBuildFCmp(builder, LLVMRealUGE, selcoords->id, LLVMConstReal(f32, 4.0), "");
817 is_not_ma_z = LLVMBuildNot(builder, is_ma_z, "");
818 is_ma_y = LLVMBuildAnd(builder, is_not_ma_z,
819 LLVMBuildFCmp(builder, LLVMRealUGE, selcoords->id, LLVMConstReal(f32, 2.0), ""), "");
820 is_ma_x = LLVMBuildAnd(builder, is_not_ma_z, LLVMBuildNot(builder, is_ma_y, ""), "");
823 tmp = LLVMBuildSelect(builder, is_ma_x, coords[2], coords[0], "");
824 sgn = LLVMBuildSelect(builder, is_ma_y, LLVMConstReal(f32, 1.0),
825 LLVMBuildSelect(builder, is_ma_z, sgn_ma,
826 LLVMBuildFNeg(builder, sgn_ma, ""), ""), "");
827 out_st[0] = LLVMBuildFMul(builder, tmp, sgn, "");
830 tmp = LLVMBuildSelect(builder, is_ma_y, coords[2], coords[1], "");
831 sgn = LLVMBuildSelect(builder, is_ma_y, sgn_ma,
832 LLVMConstReal(f32, -1.0), "");
833 out_st[1] = LLVMBuildFMul(builder, tmp, sgn, "");
836 tmp = LLVMBuildSelect(builder, is_ma_z, coords[2],
837 LLVMBuildSelect(builder, is_ma_y, coords[1], coords[0], ""), "");
838 tmp = ac_build_intrinsic(ctx, "llvm.fabs.f32",
839 ctx->f32, &tmp, 1, AC_FUNC_ATTR_READNONE);
840 *out_ma = LLVMBuildFMul(builder, tmp, LLVMConstReal(f32, 2.0), "");
844 ac_prepare_cube_coords(struct ac_llvm_context *ctx,
845 bool is_deriv, bool is_array, bool is_lod,
846 LLVMValueRef *coords_arg,
847 LLVMValueRef *derivs_arg)
850 LLVMBuilderRef builder = ctx->builder;
851 struct cube_selection_coords selcoords;
852 LLVMValueRef coords[3];
855 if (is_array && !is_lod) {
856 LLVMValueRef tmp = ac_build_round(ctx, coords_arg[3]);
858 /* Section 8.9 (Texture Functions) of the GLSL 4.50 spec says:
860 * "For Array forms, the array layer used will be
862 * max(0, min(d−1, floor(layer+0.5)))
864 * where d is the depth of the texture array and layer
865 * comes from the component indicated in the tables below.
866 * Workaroudn for an issue where the layer is taken from a
867 * helper invocation which happens to fall on a different
868 * layer due to extrapolation."
870 * GFX8 and earlier attempt to implement this in hardware by
871 * clamping the value of coords[2] = (8 * layer) + face.
872 * Unfortunately, this means that the we end up with the wrong
873 * face when clamping occurs.
875 * Clamp the layer earlier to work around the issue.
877 if (ctx->chip_class <= GFX8) {
879 ge0 = LLVMBuildFCmp(builder, LLVMRealOGE, tmp, ctx->f32_0, "");
880 tmp = LLVMBuildSelect(builder, ge0, tmp, ctx->f32_0, "");
886 build_cube_intrinsic(ctx, coords_arg, &selcoords);
888 invma = ac_build_intrinsic(ctx, "llvm.fabs.f32",
889 ctx->f32, &selcoords.ma, 1, AC_FUNC_ATTR_READNONE);
890 invma = ac_build_fdiv(ctx, LLVMConstReal(ctx->f32, 1.0), invma);
892 for (int i = 0; i < 2; ++i)
893 coords[i] = LLVMBuildFMul(builder, selcoords.stc[i], invma, "");
895 coords[2] = selcoords.id;
897 if (is_deriv && derivs_arg) {
898 LLVMValueRef derivs[4];
901 /* Convert cube derivatives to 2D derivatives. */
902 for (axis = 0; axis < 2; axis++) {
903 LLVMValueRef deriv_st[2];
904 LLVMValueRef deriv_ma;
906 /* Transform the derivative alongside the texture
907 * coordinate. Mathematically, the correct formula is
908 * as follows. Assume we're projecting onto the +Z face
909 * and denote by dx/dh the derivative of the (original)
910 * X texture coordinate with respect to horizontal
911 * window coordinates. The projection onto the +Z face
916 * Then df/dh = df/dx * dx/dh + df/dz * dz/dh
917 * = 1/z * dx/dh - x/z * 1/z * dz/dh.
919 * This motivatives the implementation below.
921 * Whether this actually gives the expected results for
922 * apps that might feed in derivatives obtained via
923 * finite differences is anyone's guess. The OpenGL spec
924 * seems awfully quiet about how textureGrad for cube
925 * maps should be handled.
927 build_cube_select(ctx, &selcoords, &derivs_arg[axis * 3],
928 deriv_st, &deriv_ma);
930 deriv_ma = LLVMBuildFMul(builder, deriv_ma, invma, "");
932 for (int i = 0; i < 2; ++i)
933 derivs[axis * 2 + i] =
934 LLVMBuildFSub(builder,
935 LLVMBuildFMul(builder, deriv_st[i], invma, ""),
936 LLVMBuildFMul(builder, deriv_ma, coords[i], ""), "");
939 memcpy(derivs_arg, derivs, sizeof(derivs));
942 /* Shift the texture coordinate. This must be applied after the
943 * derivative calculation.
945 for (int i = 0; i < 2; ++i)
946 coords[i] = LLVMBuildFAdd(builder, coords[i], LLVMConstReal(ctx->f32, 1.5), "");
949 /* for cube arrays coord.z = coord.w(array_index) * 8 + face */
950 /* coords_arg.w component - array_index for cube arrays */
951 coords[2] = ac_build_fmad(ctx, coords_arg[3], LLVMConstReal(ctx->f32, 8.0), coords[2]);
954 memcpy(coords_arg, coords, sizeof(coords));
959 ac_build_fs_interp(struct ac_llvm_context *ctx,
960 LLVMValueRef llvm_chan,
961 LLVMValueRef attr_number,
966 LLVMValueRef args[5];
971 args[2] = attr_number;
974 p1 = ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p1",
975 ctx->f32, args, 4, AC_FUNC_ATTR_READNONE);
980 args[3] = attr_number;
983 return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p2",
984 ctx->f32, args, 5, AC_FUNC_ATTR_READNONE);
988 ac_build_fs_interp_f16(struct ac_llvm_context *ctx,
989 LLVMValueRef llvm_chan,
990 LLVMValueRef attr_number,
995 LLVMValueRef args[6];
1000 args[2] = attr_number;
1001 args[3] = ctx->i1false;
1004 p1 = ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p1.f16",
1005 ctx->f32, args, 5, AC_FUNC_ATTR_READNONE);
1009 args[2] = llvm_chan;
1010 args[3] = attr_number;
1011 args[4] = ctx->i1false;
1014 return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p2.f16",
1015 ctx->f16, args, 6, AC_FUNC_ATTR_READNONE);
1019 ac_build_fs_interp_mov(struct ac_llvm_context *ctx,
1020 LLVMValueRef parameter,
1021 LLVMValueRef llvm_chan,
1022 LLVMValueRef attr_number,
1023 LLVMValueRef params)
1025 LLVMValueRef args[4];
1027 args[0] = parameter;
1028 args[1] = llvm_chan;
1029 args[2] = attr_number;
1032 return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.mov",
1033 ctx->f32, args, 4, AC_FUNC_ATTR_READNONE);
1037 ac_build_gep_ptr(struct ac_llvm_context *ctx,
1038 LLVMValueRef base_ptr,
1041 return LLVMBuildGEP(ctx->builder, base_ptr, &index, 1, "");
1045 ac_build_gep0(struct ac_llvm_context *ctx,
1046 LLVMValueRef base_ptr,
1049 LLVMValueRef indices[2] = {
1053 return LLVMBuildGEP(ctx->builder, base_ptr, indices, 2, "");
1056 LLVMValueRef ac_build_pointer_add(struct ac_llvm_context *ctx, LLVMValueRef ptr,
1059 return LLVMBuildPointerCast(ctx->builder,
1060 LLVMBuildGEP(ctx->builder, ptr, &index, 1, ""),
1061 LLVMTypeOf(ptr), "");
1065 ac_build_indexed_store(struct ac_llvm_context *ctx,
1066 LLVMValueRef base_ptr, LLVMValueRef index,
1069 LLVMBuildStore(ctx->builder, value,
1070 ac_build_gep0(ctx, base_ptr, index));
1074 * Build an LLVM bytecode indexed load using LLVMBuildGEP + LLVMBuildLoad.
1075 * It's equivalent to doing a load from &base_ptr[index].
1077 * \param base_ptr Where the array starts.
1078 * \param index The element index into the array.
1079 * \param uniform Whether the base_ptr and index can be assumed to be
1080 * dynamically uniform (i.e. load to an SGPR)
1081 * \param invariant Whether the load is invariant (no other opcodes affect it)
1082 * \param no_unsigned_wraparound
1083 * For all possible re-associations and re-distributions of an expression
1084 * "base_ptr + index * elemsize" into "addr + offset" (excluding GEPs
1085 * without inbounds in base_ptr), this parameter is true if "addr + offset"
1086 * does not result in an unsigned integer wraparound. This is used for
1087 * optimal code generation of 32-bit pointer arithmetic.
1089 * For example, a 32-bit immediate offset that causes a 32-bit unsigned
1090 * integer wraparound can't be an imm offset in s_load_dword, because
1091 * the instruction performs "addr + offset" in 64 bits.
1093 * Expected usage for bindless textures by chaining GEPs:
1094 * // possible unsigned wraparound, don't use InBounds:
1095 * ptr1 = LLVMBuildGEP(base_ptr, index);
1096 * image = load(ptr1); // becomes "s_load ptr1, 0"
1098 * ptr2 = LLVMBuildInBoundsGEP(ptr1, 32 / elemsize);
1099 * sampler = load(ptr2); // becomes "s_load ptr1, 32" thanks to InBounds
1102 ac_build_load_custom(struct ac_llvm_context *ctx, LLVMValueRef base_ptr,
1103 LLVMValueRef index, bool uniform, bool invariant,
1104 bool no_unsigned_wraparound)
1106 LLVMValueRef pointer, result;
1108 if (no_unsigned_wraparound &&
1109 LLVMGetPointerAddressSpace(LLVMTypeOf(base_ptr)) == AC_ADDR_SPACE_CONST_32BIT)
1110 pointer = LLVMBuildInBoundsGEP(ctx->builder, base_ptr, &index, 1, "");
1112 pointer = LLVMBuildGEP(ctx->builder, base_ptr, &index, 1, "");
1115 LLVMSetMetadata(pointer, ctx->uniform_md_kind, ctx->empty_md);
1116 result = LLVMBuildLoad(ctx->builder, pointer, "");
1118 LLVMSetMetadata(result, ctx->invariant_load_md_kind, ctx->empty_md);
1122 LLVMValueRef ac_build_load(struct ac_llvm_context *ctx, LLVMValueRef base_ptr,
1125 return ac_build_load_custom(ctx, base_ptr, index, false, false, false);
1128 LLVMValueRef ac_build_load_invariant(struct ac_llvm_context *ctx,
1129 LLVMValueRef base_ptr, LLVMValueRef index)
1131 return ac_build_load_custom(ctx, base_ptr, index, false, true, false);
1134 /* This assumes that there is no unsigned integer wraparound during the address
1135 * computation, excluding all GEPs within base_ptr. */
1136 LLVMValueRef ac_build_load_to_sgpr(struct ac_llvm_context *ctx,
1137 LLVMValueRef base_ptr, LLVMValueRef index)
1139 return ac_build_load_custom(ctx, base_ptr, index, true, true, true);
1142 /* See ac_build_load_custom() documentation. */
1143 LLVMValueRef ac_build_load_to_sgpr_uint_wraparound(struct ac_llvm_context *ctx,
1144 LLVMValueRef base_ptr, LLVMValueRef index)
1146 return ac_build_load_custom(ctx, base_ptr, index, true, true, false);
1149 static unsigned get_load_cache_policy(struct ac_llvm_context *ctx,
1150 unsigned cache_policy)
1152 return cache_policy |
1153 (ctx->chip_class >= GFX10 && cache_policy & ac_glc ? ac_dlc : 0);
1157 ac_build_buffer_store_common(struct ac_llvm_context *ctx,
1160 LLVMValueRef vindex,
1161 LLVMValueRef voffset,
1162 LLVMValueRef soffset,
1163 unsigned num_channels,
1164 LLVMTypeRef return_channel_type,
1165 unsigned cache_policy,
1169 LLVMValueRef args[6];
1172 args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
1174 args[idx++] = vindex ? vindex : ctx->i32_0;
1175 args[idx++] = voffset ? voffset : ctx->i32_0;
1176 args[idx++] = soffset ? soffset : ctx->i32_0;
1177 args[idx++] = LLVMConstInt(ctx->i32, cache_policy, 0);
1178 unsigned func = !ac_has_vec3_support(ctx->chip_class, use_format) && num_channels == 3 ? 4 : num_channels;
1179 const char *indexing_kind = structurized ? "struct" : "raw";
1180 char name[256], type_name[8];
1182 LLVMTypeRef type = func > 1 ? LLVMVectorType(return_channel_type, func) : return_channel_type;
1183 ac_build_type_name_for_intr(type, type_name, sizeof(type_name));
1186 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.store.format.%s",
1187 indexing_kind, type_name);
1189 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.store.%s",
1190 indexing_kind, type_name);
1193 ac_build_intrinsic(ctx, name, ctx->voidt, args, idx,
1194 AC_FUNC_ATTR_INACCESSIBLE_MEM_ONLY);
1198 ac_build_buffer_store_format(struct ac_llvm_context *ctx,
1201 LLVMValueRef vindex,
1202 LLVMValueRef voffset,
1203 unsigned num_channels,
1204 unsigned cache_policy)
1206 ac_build_buffer_store_common(ctx, rsrc, data, vindex,
1207 voffset, NULL, num_channels,
1208 ctx->f32, cache_policy,
1212 /* TBUFFER_STORE_FORMAT_{X,XY,XYZ,XYZW} <- the suffix is selected by num_channels=1..4.
1213 * The type of vdata must be one of i32 (num_channels=1), v2i32 (num_channels=2),
1214 * or v4i32 (num_channels=3,4).
1217 ac_build_buffer_store_dword(struct ac_llvm_context *ctx,
1220 unsigned num_channels,
1221 LLVMValueRef voffset,
1222 LLVMValueRef soffset,
1223 unsigned inst_offset,
1224 unsigned cache_policy,
1225 bool swizzle_enable_hint)
1227 /* Split 3 channel stores, because only LLVM 9+ support 3-channel
1229 if (num_channels == 3 && !ac_has_vec3_support(ctx->chip_class, false)) {
1230 LLVMValueRef v[3], v01;
1232 for (int i = 0; i < 3; i++) {
1233 v[i] = LLVMBuildExtractElement(ctx->builder, vdata,
1234 LLVMConstInt(ctx->i32, i, 0), "");
1236 v01 = ac_build_gather_values(ctx, v, 2);
1238 ac_build_buffer_store_dword(ctx, rsrc, v01, 2, voffset,
1239 soffset, inst_offset, cache_policy,
1240 swizzle_enable_hint);
1241 ac_build_buffer_store_dword(ctx, rsrc, v[2], 1, voffset,
1242 soffset, inst_offset + 8,
1244 swizzle_enable_hint);
1248 /* SWIZZLE_ENABLE requires that soffset isn't folded into voffset
1249 * (voffset is swizzled, but soffset isn't swizzled).
1250 * llvm.amdgcn.buffer.store doesn't have a separate soffset parameter.
1252 if (!swizzle_enable_hint) {
1253 LLVMValueRef offset = soffset;
1256 offset = LLVMBuildAdd(ctx->builder, offset,
1257 LLVMConstInt(ctx->i32, inst_offset, 0), "");
1259 ac_build_buffer_store_common(ctx, rsrc, ac_to_float(ctx, vdata),
1260 ctx->i32_0, voffset, offset,
1261 num_channels, ctx->f32,
1262 cache_policy, false, false);
1266 static const unsigned dfmts[] = {
1267 V_008F0C_BUF_DATA_FORMAT_32,
1268 V_008F0C_BUF_DATA_FORMAT_32_32,
1269 V_008F0C_BUF_DATA_FORMAT_32_32_32,
1270 V_008F0C_BUF_DATA_FORMAT_32_32_32_32
1272 unsigned dfmt = dfmts[num_channels - 1];
1273 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1274 LLVMValueRef immoffset = LLVMConstInt(ctx->i32, inst_offset, 0);
1276 ac_build_raw_tbuffer_store(ctx, rsrc, vdata, voffset, soffset,
1277 immoffset, num_channels, dfmt, nfmt, cache_policy);
1281 ac_build_buffer_load_common(struct ac_llvm_context *ctx,
1283 LLVMValueRef vindex,
1284 LLVMValueRef voffset,
1285 LLVMValueRef soffset,
1286 unsigned num_channels,
1287 LLVMTypeRef channel_type,
1288 unsigned cache_policy,
1293 LLVMValueRef args[5];
1295 args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
1297 args[idx++] = vindex ? vindex : ctx->i32_0;
1298 args[idx++] = voffset ? voffset : ctx->i32_0;
1299 args[idx++] = soffset ? soffset : ctx->i32_0;
1300 args[idx++] = LLVMConstInt(ctx->i32, get_load_cache_policy(ctx, cache_policy), 0);
1301 unsigned func = !ac_has_vec3_support(ctx->chip_class, use_format) && num_channels == 3 ? 4 : num_channels;
1302 const char *indexing_kind = structurized ? "struct" : "raw";
1303 char name[256], type_name[8];
1305 LLVMTypeRef type = func > 1 ? LLVMVectorType(channel_type, func) : channel_type;
1306 ac_build_type_name_for_intr(type, type_name, sizeof(type_name));
1309 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.load.format.%s",
1310 indexing_kind, type_name);
1312 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.load.%s",
1313 indexing_kind, type_name);
1316 return ac_build_intrinsic(ctx, name, type, args, idx,
1317 ac_get_load_intr_attribs(can_speculate));
1321 ac_build_buffer_load(struct ac_llvm_context *ctx,
1324 LLVMValueRef vindex,
1325 LLVMValueRef voffset,
1326 LLVMValueRef soffset,
1327 unsigned inst_offset,
1328 unsigned cache_policy,
1332 LLVMValueRef offset = LLVMConstInt(ctx->i32, inst_offset, 0);
1334 offset = LLVMBuildAdd(ctx->builder, offset, voffset, "");
1336 offset = LLVMBuildAdd(ctx->builder, offset, soffset, "");
1338 if (allow_smem && !(cache_policy & ac_slc) &&
1339 (!(cache_policy & ac_glc) || ctx->chip_class >= GFX8)) {
1340 assert(vindex == NULL);
1342 LLVMValueRef result[8];
1344 for (int i = 0; i < num_channels; i++) {
1346 offset = LLVMBuildAdd(ctx->builder, offset,
1347 LLVMConstInt(ctx->i32, 4, 0), "");
1349 LLVMValueRef args[3] = {
1352 LLVMConstInt(ctx->i32, get_load_cache_policy(ctx, cache_policy), 0),
1354 result[i] = ac_build_intrinsic(ctx,
1355 "llvm.amdgcn.s.buffer.load.f32",
1357 AC_FUNC_ATTR_READNONE);
1359 if (num_channels == 1)
1362 if (num_channels == 3 && !ac_has_vec3_support(ctx->chip_class, false))
1363 result[num_channels++] = LLVMGetUndef(ctx->f32);
1364 return ac_build_gather_values(ctx, result, num_channels);
1367 return ac_build_buffer_load_common(ctx, rsrc, vindex,
1369 num_channels, ctx->f32,
1371 can_speculate, false, false);
1374 LLVMValueRef ac_build_buffer_load_format(struct ac_llvm_context *ctx,
1376 LLVMValueRef vindex,
1377 LLVMValueRef voffset,
1378 unsigned num_channels,
1379 unsigned cache_policy,
1382 return ac_build_buffer_load_common(ctx, rsrc, vindex, voffset,
1383 ctx->i32_0, num_channels, ctx->f32,
1384 cache_policy, can_speculate,
1389 ac_build_tbuffer_load(struct ac_llvm_context *ctx,
1391 LLVMValueRef vindex,
1392 LLVMValueRef voffset,
1393 LLVMValueRef soffset,
1394 LLVMValueRef immoffset,
1395 unsigned num_channels,
1398 unsigned cache_policy,
1402 voffset = LLVMBuildAdd(ctx->builder, voffset, immoffset, "");
1404 LLVMValueRef args[6];
1406 args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
1408 args[idx++] = vindex ? vindex : ctx->i32_0;
1409 args[idx++] = voffset ? voffset : ctx->i32_0;
1410 args[idx++] = soffset ? soffset : ctx->i32_0;
1411 args[idx++] = LLVMConstInt(ctx->i32, ac_get_tbuffer_format(ctx->chip_class, dfmt, nfmt), 0);
1412 args[idx++] = LLVMConstInt(ctx->i32, get_load_cache_policy(ctx, cache_policy), 0);
1413 unsigned func = !ac_has_vec3_support(ctx->chip_class, true) && num_channels == 3 ? 4 : num_channels;
1414 const char *indexing_kind = structurized ? "struct" : "raw";
1415 char name[256], type_name[8];
1417 LLVMTypeRef type = func > 1 ? LLVMVectorType(ctx->i32, func) : ctx->i32;
1418 ac_build_type_name_for_intr(type, type_name, sizeof(type_name));
1420 snprintf(name, sizeof(name), "llvm.amdgcn.%s.tbuffer.load.%s",
1421 indexing_kind, type_name);
1423 return ac_build_intrinsic(ctx, name, type, args, idx,
1424 ac_get_load_intr_attribs(can_speculate));
1428 ac_build_struct_tbuffer_load(struct ac_llvm_context *ctx,
1430 LLVMValueRef vindex,
1431 LLVMValueRef voffset,
1432 LLVMValueRef soffset,
1433 LLVMValueRef immoffset,
1434 unsigned num_channels,
1437 unsigned cache_policy,
1440 return ac_build_tbuffer_load(ctx, rsrc, vindex, voffset, soffset,
1441 immoffset, num_channels, dfmt, nfmt,
1442 cache_policy, can_speculate, true);
1446 ac_build_raw_tbuffer_load(struct ac_llvm_context *ctx,
1448 LLVMValueRef voffset,
1449 LLVMValueRef soffset,
1450 LLVMValueRef immoffset,
1451 unsigned num_channels,
1454 unsigned cache_policy,
1457 return ac_build_tbuffer_load(ctx, rsrc, NULL, voffset, soffset,
1458 immoffset, num_channels, dfmt, nfmt,
1459 cache_policy, can_speculate, false);
1463 ac_build_tbuffer_load_short(struct ac_llvm_context *ctx,
1465 LLVMValueRef voffset,
1466 LLVMValueRef soffset,
1467 LLVMValueRef immoffset,
1468 unsigned cache_policy)
1472 if (LLVM_VERSION_MAJOR >= 9) {
1473 voffset = LLVMBuildAdd(ctx->builder, voffset, immoffset, "");
1475 /* LLVM 9+ supports i8/i16 with struct/raw intrinsics. */
1476 res = ac_build_buffer_load_common(ctx, rsrc, NULL,
1478 1, ctx->i16, cache_policy,
1479 false, false, false);
1481 unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_16;
1482 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1484 res = ac_build_raw_tbuffer_load(ctx, rsrc, voffset, soffset,
1485 immoffset, 1, dfmt, nfmt, cache_policy,
1488 res = LLVMBuildTrunc(ctx->builder, res, ctx->i16, "");
1495 ac_build_tbuffer_load_byte(struct ac_llvm_context *ctx,
1497 LLVMValueRef voffset,
1498 LLVMValueRef soffset,
1499 LLVMValueRef immoffset,
1500 unsigned cache_policy)
1504 if (LLVM_VERSION_MAJOR >= 9) {
1505 voffset = LLVMBuildAdd(ctx->builder, voffset, immoffset, "");
1507 /* LLVM 9+ supports i8/i16 with struct/raw intrinsics. */
1508 res = ac_build_buffer_load_common(ctx, rsrc, NULL,
1510 1, ctx->i8, cache_policy,
1511 false, false, false);
1513 unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_8;
1514 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1516 res = ac_build_raw_tbuffer_load(ctx, rsrc, voffset, soffset,
1517 immoffset, 1, dfmt, nfmt, cache_policy,
1520 res = LLVMBuildTrunc(ctx->builder, res, ctx->i8, "");
1527 * Convert an 11- or 10-bit unsigned floating point number to an f32.
1529 * The input exponent is expected to be biased analogous to IEEE-754, i.e. by
1530 * 2^(exp_bits-1) - 1 (as defined in OpenGL and other graphics APIs).
1533 ac_ufN_to_float(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned exp_bits, unsigned mant_bits)
1535 assert(LLVMTypeOf(src) == ctx->i32);
1538 LLVMValueRef mantissa;
1539 mantissa = LLVMBuildAnd(ctx->builder, src, LLVMConstInt(ctx->i32, (1 << mant_bits) - 1, false), "");
1541 /* Converting normal numbers is just a shift + correcting the exponent bias */
1542 unsigned normal_shift = 23 - mant_bits;
1543 unsigned bias_shift = 127 - ((1 << (exp_bits - 1)) - 1);
1544 LLVMValueRef shifted, normal;
1546 shifted = LLVMBuildShl(ctx->builder, src, LLVMConstInt(ctx->i32, normal_shift, false), "");
1547 normal = LLVMBuildAdd(ctx->builder, shifted, LLVMConstInt(ctx->i32, bias_shift << 23, false), "");
1549 /* Converting nan/inf numbers is the same, but with a different exponent update */
1550 LLVMValueRef naninf;
1551 naninf = LLVMBuildOr(ctx->builder, normal, LLVMConstInt(ctx->i32, 0xff << 23, false), "");
1553 /* Converting denormals is the complex case: determine the leading zeros of the
1554 * mantissa to obtain the correct shift for the mantissa and exponent correction.
1556 LLVMValueRef denormal;
1557 LLVMValueRef params[2] = {
1559 ctx->i1true, /* result can be undef when arg is 0 */
1561 LLVMValueRef ctlz = ac_build_intrinsic(ctx, "llvm.ctlz.i32", ctx->i32,
1562 params, 2, AC_FUNC_ATTR_READNONE);
1564 /* Shift such that the leading 1 ends up as the LSB of the exponent field. */
1565 tmp = LLVMBuildSub(ctx->builder, ctlz, LLVMConstInt(ctx->i32, 8, false), "");
1566 denormal = LLVMBuildShl(ctx->builder, mantissa, tmp, "");
1568 unsigned denormal_exp = bias_shift + (32 - mant_bits) - 1;
1569 tmp = LLVMBuildSub(ctx->builder, LLVMConstInt(ctx->i32, denormal_exp, false), ctlz, "");
1570 tmp = LLVMBuildShl(ctx->builder, tmp, LLVMConstInt(ctx->i32, 23, false), "");
1571 denormal = LLVMBuildAdd(ctx->builder, denormal, tmp, "");
1573 /* Select the final result. */
1574 LLVMValueRef result;
1576 tmp = LLVMBuildICmp(ctx->builder, LLVMIntUGE, src,
1577 LLVMConstInt(ctx->i32, ((1 << exp_bits) - 1) << mant_bits, false), "");
1578 result = LLVMBuildSelect(ctx->builder, tmp, naninf, normal, "");
1580 tmp = LLVMBuildICmp(ctx->builder, LLVMIntUGE, src,
1581 LLVMConstInt(ctx->i32, 1 << mant_bits, false), "");
1582 result = LLVMBuildSelect(ctx->builder, tmp, result, denormal, "");
1584 tmp = LLVMBuildICmp(ctx->builder, LLVMIntNE, src, ctx->i32_0, "");
1585 result = LLVMBuildSelect(ctx->builder, tmp, result, ctx->i32_0, "");
1587 return ac_to_float(ctx, result);
1591 * Generate a fully general open coded buffer format fetch with all required
1592 * fixups suitable for vertex fetch, using non-format buffer loads.
1594 * Some combinations of argument values have special interpretations:
1595 * - size = 8 bytes, format = fixed indicates PIPE_FORMAT_R11G11B10_FLOAT
1596 * - size = 8 bytes, format != {float,fixed} indicates a 2_10_10_10 data format
1598 * \param log_size log(size of channel in bytes)
1599 * \param num_channels number of channels (1 to 4)
1600 * \param format AC_FETCH_FORMAT_xxx value
1601 * \param reverse whether XYZ channels are reversed
1602 * \param known_aligned whether the source is known to be aligned to hardware's
1603 * effective element size for loading the given format
1604 * (note: this means dword alignment for 8_8_8_8, 16_16, etc.)
1605 * \param rsrc buffer resource descriptor
1606 * \return the resulting vector of floats or integers bitcast to <4 x i32>
1609 ac_build_opencoded_load_format(struct ac_llvm_context *ctx,
1611 unsigned num_channels,
1616 LLVMValueRef vindex,
1617 LLVMValueRef voffset,
1618 LLVMValueRef soffset,
1619 unsigned cache_policy,
1623 unsigned load_log_size = log_size;
1624 unsigned load_num_channels = num_channels;
1625 if (log_size == 3) {
1627 if (format == AC_FETCH_FORMAT_FLOAT) {
1628 load_num_channels = 2 * num_channels;
1630 load_num_channels = 1; /* 10_11_11 or 2_10_10_10 */
1634 int log_recombine = 0;
1635 if (ctx->chip_class == GFX6 && !known_aligned) {
1636 /* Avoid alignment restrictions by loading one byte at a time. */
1637 load_num_channels <<= load_log_size;
1638 log_recombine = load_log_size;
1640 } else if (load_num_channels == 2 || load_num_channels == 4) {
1641 log_recombine = -util_logbase2(load_num_channels);
1642 load_num_channels = 1;
1643 load_log_size += -log_recombine;
1646 assert(load_log_size >= 2 || LLVM_VERSION_MAJOR >= 9);
1648 LLVMValueRef loads[32]; /* up to 32 bytes */
1649 for (unsigned i = 0; i < load_num_channels; ++i) {
1650 tmp = LLVMBuildAdd(ctx->builder, soffset,
1651 LLVMConstInt(ctx->i32, i << load_log_size, false), "");
1652 LLVMTypeRef channel_type = load_log_size == 0 ? ctx->i8 :
1653 load_log_size == 1 ? ctx->i16 : ctx->i32;
1654 unsigned num_channels = 1 << (MAX2(load_log_size, 2) - 2);
1655 loads[i] = ac_build_buffer_load_common(
1656 ctx, rsrc, vindex, voffset, tmp,
1657 num_channels, channel_type, cache_policy,
1658 can_speculate, false, true);
1659 if (load_log_size >= 2)
1660 loads[i] = ac_to_integer(ctx, loads[i]);
1663 if (log_recombine > 0) {
1664 /* Recombine bytes if necessary (GFX6 only) */
1665 LLVMTypeRef dst_type = log_recombine == 2 ? ctx->i32 : ctx->i16;
1667 for (unsigned src = 0, dst = 0; src < load_num_channels; ++dst) {
1668 LLVMValueRef accum = NULL;
1669 for (unsigned i = 0; i < (1 << log_recombine); ++i, ++src) {
1670 tmp = LLVMBuildZExt(ctx->builder, loads[src], dst_type, "");
1674 tmp = LLVMBuildShl(ctx->builder, tmp,
1675 LLVMConstInt(dst_type, 8 * i, false), "");
1676 accum = LLVMBuildOr(ctx->builder, accum, tmp, "");
1681 } else if (log_recombine < 0) {
1682 /* Split vectors of dwords */
1683 if (load_log_size > 2) {
1684 assert(load_num_channels == 1);
1685 LLVMValueRef loaded = loads[0];
1686 unsigned log_split = load_log_size - 2;
1687 log_recombine += log_split;
1688 load_num_channels = 1 << log_split;
1690 for (unsigned i = 0; i < load_num_channels; ++i) {
1691 tmp = LLVMConstInt(ctx->i32, i, false);
1692 loads[i] = LLVMBuildExtractElement(ctx->builder, loaded, tmp, "");
1696 /* Further split dwords and shorts if required */
1697 if (log_recombine < 0) {
1698 for (unsigned src = load_num_channels,
1699 dst = load_num_channels << -log_recombine;
1701 unsigned dst_bits = 1 << (3 + load_log_size + log_recombine);
1702 LLVMTypeRef dst_type = LLVMIntTypeInContext(ctx->context, dst_bits);
1703 LLVMValueRef loaded = loads[src - 1];
1704 LLVMTypeRef loaded_type = LLVMTypeOf(loaded);
1705 for (unsigned i = 1 << -log_recombine; i > 0; --i, --dst) {
1706 tmp = LLVMConstInt(loaded_type, dst_bits * (i - 1), false);
1707 tmp = LLVMBuildLShr(ctx->builder, loaded, tmp, "");
1708 loads[dst - 1] = LLVMBuildTrunc(ctx->builder, tmp, dst_type, "");
1714 if (log_size == 3) {
1715 if (format == AC_FETCH_FORMAT_FLOAT) {
1716 for (unsigned i = 0; i < num_channels; ++i) {
1717 tmp = ac_build_gather_values(ctx, &loads[2 * i], 2);
1718 loads[i] = LLVMBuildBitCast(ctx->builder, tmp, ctx->f64, "");
1720 } else if (format == AC_FETCH_FORMAT_FIXED) {
1721 /* 10_11_11_FLOAT */
1722 LLVMValueRef data = loads[0];
1723 LLVMValueRef i32_2047 = LLVMConstInt(ctx->i32, 2047, false);
1724 LLVMValueRef r = LLVMBuildAnd(ctx->builder, data, i32_2047, "");
1725 tmp = LLVMBuildLShr(ctx->builder, data, LLVMConstInt(ctx->i32, 11, false), "");
1726 LLVMValueRef g = LLVMBuildAnd(ctx->builder, tmp, i32_2047, "");
1727 LLVMValueRef b = LLVMBuildLShr(ctx->builder, data, LLVMConstInt(ctx->i32, 22, false), "");
1729 loads[0] = ac_to_integer(ctx, ac_ufN_to_float(ctx, r, 5, 6));
1730 loads[1] = ac_to_integer(ctx, ac_ufN_to_float(ctx, g, 5, 6));
1731 loads[2] = ac_to_integer(ctx, ac_ufN_to_float(ctx, b, 5, 5));
1735 format = AC_FETCH_FORMAT_FLOAT;
1737 /* 2_10_10_10 data formats */
1738 LLVMValueRef data = loads[0];
1739 LLVMTypeRef i10 = LLVMIntTypeInContext(ctx->context, 10);
1740 LLVMTypeRef i2 = LLVMIntTypeInContext(ctx->context, 2);
1741 loads[0] = LLVMBuildTrunc(ctx->builder, data, i10, "");
1742 tmp = LLVMBuildLShr(ctx->builder, data, LLVMConstInt(ctx->i32, 10, false), "");
1743 loads[1] = LLVMBuildTrunc(ctx->builder, tmp, i10, "");
1744 tmp = LLVMBuildLShr(ctx->builder, data, LLVMConstInt(ctx->i32, 20, false), "");
1745 loads[2] = LLVMBuildTrunc(ctx->builder, tmp, i10, "");
1746 tmp = LLVMBuildLShr(ctx->builder, data, LLVMConstInt(ctx->i32, 30, false), "");
1747 loads[3] = LLVMBuildTrunc(ctx->builder, tmp, i2, "");
1753 if (format == AC_FETCH_FORMAT_FLOAT) {
1754 if (log_size != 2) {
1755 for (unsigned chan = 0; chan < num_channels; ++chan) {
1756 tmp = ac_to_float(ctx, loads[chan]);
1758 tmp = LLVMBuildFPTrunc(ctx->builder, tmp, ctx->f32, "");
1759 else if (log_size == 1)
1760 tmp = LLVMBuildFPExt(ctx->builder, tmp, ctx->f32, "");
1761 loads[chan] = ac_to_integer(ctx, tmp);
1764 } else if (format == AC_FETCH_FORMAT_UINT) {
1765 if (log_size != 2) {
1766 for (unsigned chan = 0; chan < num_channels; ++chan)
1767 loads[chan] = LLVMBuildZExt(ctx->builder, loads[chan], ctx->i32, "");
1769 } else if (format == AC_FETCH_FORMAT_SINT) {
1770 if (log_size != 2) {
1771 for (unsigned chan = 0; chan < num_channels; ++chan)
1772 loads[chan] = LLVMBuildSExt(ctx->builder, loads[chan], ctx->i32, "");
1775 bool unsign = format == AC_FETCH_FORMAT_UNORM ||
1776 format == AC_FETCH_FORMAT_USCALED ||
1777 format == AC_FETCH_FORMAT_UINT;
1779 for (unsigned chan = 0; chan < num_channels; ++chan) {
1781 tmp = LLVMBuildUIToFP(ctx->builder, loads[chan], ctx->f32, "");
1783 tmp = LLVMBuildSIToFP(ctx->builder, loads[chan], ctx->f32, "");
1786 LLVMValueRef scale = NULL;
1787 if (format == AC_FETCH_FORMAT_FIXED) {
1788 assert(log_size == 2);
1789 scale = LLVMConstReal(ctx->f32, 1.0 / 0x10000);
1790 } else if (format == AC_FETCH_FORMAT_UNORM) {
1791 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(loads[chan]));
1792 scale = LLVMConstReal(ctx->f32, 1.0 / (((uint64_t)1 << bits) - 1));
1793 } else if (format == AC_FETCH_FORMAT_SNORM) {
1794 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(loads[chan]));
1795 scale = LLVMConstReal(ctx->f32, 1.0 / (((uint64_t)1 << (bits - 1)) - 1));
1798 tmp = LLVMBuildFMul(ctx->builder, tmp, scale, "");
1800 if (format == AC_FETCH_FORMAT_SNORM) {
1801 /* Clamp to [-1, 1] */
1802 LLVMValueRef neg_one = LLVMConstReal(ctx->f32, -1.0);
1803 LLVMValueRef clamp =
1804 LLVMBuildFCmp(ctx->builder, LLVMRealULT, tmp, neg_one, "");
1805 tmp = LLVMBuildSelect(ctx->builder, clamp, neg_one, tmp, "");
1808 loads[chan] = ac_to_integer(ctx, tmp);
1812 while (num_channels < 4) {
1813 if (format == AC_FETCH_FORMAT_UINT || format == AC_FETCH_FORMAT_SINT) {
1814 loads[num_channels] = num_channels == 3 ? ctx->i32_1 : ctx->i32_0;
1816 loads[num_channels] = ac_to_integer(ctx, num_channels == 3 ? ctx->f32_1 : ctx->f32_0);
1823 loads[0] = loads[2];
1827 return ac_build_gather_values(ctx, loads, 4);
1831 ac_build_tbuffer_store(struct ac_llvm_context *ctx,
1834 LLVMValueRef vindex,
1835 LLVMValueRef voffset,
1836 LLVMValueRef soffset,
1837 LLVMValueRef immoffset,
1838 unsigned num_channels,
1841 unsigned cache_policy,
1844 voffset = LLVMBuildAdd(ctx->builder, voffset ? voffset : ctx->i32_0,
1847 LLVMValueRef args[7];
1849 args[idx++] = vdata;
1850 args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
1852 args[idx++] = vindex ? vindex : ctx->i32_0;
1853 args[idx++] = voffset ? voffset : ctx->i32_0;
1854 args[idx++] = soffset ? soffset : ctx->i32_0;
1855 args[idx++] = LLVMConstInt(ctx->i32, ac_get_tbuffer_format(ctx->chip_class, dfmt, nfmt), 0);
1856 args[idx++] = LLVMConstInt(ctx->i32, cache_policy, 0);
1857 unsigned func = !ac_has_vec3_support(ctx->chip_class, true) && num_channels == 3 ? 4 : num_channels;
1858 const char *indexing_kind = structurized ? "struct" : "raw";
1859 char name[256], type_name[8];
1861 LLVMTypeRef type = func > 1 ? LLVMVectorType(ctx->i32, func) : ctx->i32;
1862 ac_build_type_name_for_intr(type, type_name, sizeof(type_name));
1864 snprintf(name, sizeof(name), "llvm.amdgcn.%s.tbuffer.store.%s",
1865 indexing_kind, type_name);
1867 ac_build_intrinsic(ctx, name, ctx->voidt, args, idx,
1868 AC_FUNC_ATTR_INACCESSIBLE_MEM_ONLY);
1872 ac_build_struct_tbuffer_store(struct ac_llvm_context *ctx,
1875 LLVMValueRef vindex,
1876 LLVMValueRef voffset,
1877 LLVMValueRef soffset,
1878 LLVMValueRef immoffset,
1879 unsigned num_channels,
1882 unsigned cache_policy)
1884 ac_build_tbuffer_store(ctx, rsrc, vdata, vindex, voffset, soffset,
1885 immoffset, num_channels, dfmt, nfmt, cache_policy,
1890 ac_build_raw_tbuffer_store(struct ac_llvm_context *ctx,
1893 LLVMValueRef voffset,
1894 LLVMValueRef soffset,
1895 LLVMValueRef immoffset,
1896 unsigned num_channels,
1899 unsigned cache_policy)
1901 ac_build_tbuffer_store(ctx, rsrc, vdata, NULL, voffset, soffset,
1902 immoffset, num_channels, dfmt, nfmt, cache_policy,
1907 ac_build_tbuffer_store_short(struct ac_llvm_context *ctx,
1910 LLVMValueRef voffset,
1911 LLVMValueRef soffset,
1912 unsigned cache_policy)
1914 vdata = LLVMBuildBitCast(ctx->builder, vdata, ctx->i16, "");
1916 if (LLVM_VERSION_MAJOR >= 9) {
1917 /* LLVM 9+ supports i8/i16 with struct/raw intrinsics. */
1918 ac_build_buffer_store_common(ctx, rsrc, vdata, NULL,
1919 voffset, soffset, 1,
1920 ctx->i16, cache_policy,
1923 unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_16;
1924 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1926 vdata = LLVMBuildZExt(ctx->builder, vdata, ctx->i32, "");
1928 ac_build_raw_tbuffer_store(ctx, rsrc, vdata, voffset, soffset,
1929 ctx->i32_0, 1, dfmt, nfmt, cache_policy);
1934 ac_build_tbuffer_store_byte(struct ac_llvm_context *ctx,
1937 LLVMValueRef voffset,
1938 LLVMValueRef soffset,
1939 unsigned cache_policy)
1941 vdata = LLVMBuildBitCast(ctx->builder, vdata, ctx->i8, "");
1943 if (LLVM_VERSION_MAJOR >= 9) {
1944 /* LLVM 9+ supports i8/i16 with struct/raw intrinsics. */
1945 ac_build_buffer_store_common(ctx, rsrc, vdata, NULL,
1946 voffset, soffset, 1,
1947 ctx->i8, cache_policy,
1950 unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_8;
1951 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1953 vdata = LLVMBuildZExt(ctx->builder, vdata, ctx->i32, "");
1955 ac_build_raw_tbuffer_store(ctx, rsrc, vdata, voffset, soffset,
1956 ctx->i32_0, 1, dfmt, nfmt, cache_policy);
1960 * Set range metadata on an instruction. This can only be used on load and
1961 * call instructions. If you know an instruction can only produce the values
1962 * 0, 1, 2, you would do set_range_metadata(value, 0, 3);
1963 * \p lo is the minimum value inclusive.
1964 * \p hi is the maximum value exclusive.
1966 static void set_range_metadata(struct ac_llvm_context *ctx,
1967 LLVMValueRef value, unsigned lo, unsigned hi)
1969 LLVMValueRef range_md, md_args[2];
1970 LLVMTypeRef type = LLVMTypeOf(value);
1971 LLVMContextRef context = LLVMGetTypeContext(type);
1973 md_args[0] = LLVMConstInt(type, lo, false);
1974 md_args[1] = LLVMConstInt(type, hi, false);
1975 range_md = LLVMMDNodeInContext(context, md_args, 2);
1976 LLVMSetMetadata(value, ctx->range_md_kind, range_md);
1980 ac_get_thread_id(struct ac_llvm_context *ctx)
1984 LLVMValueRef tid_args[2];
1985 tid_args[0] = LLVMConstInt(ctx->i32, 0xffffffff, false);
1986 tid_args[1] = ctx->i32_0;
1987 tid_args[1] = ac_build_intrinsic(ctx,
1988 "llvm.amdgcn.mbcnt.lo", ctx->i32,
1989 tid_args, 2, AC_FUNC_ATTR_READNONE);
1991 if (ctx->wave_size == 32) {
1994 tid = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi",
1996 2, AC_FUNC_ATTR_READNONE);
1998 set_range_metadata(ctx, tid, 0, ctx->wave_size);
2003 * AMD GCN implements derivatives using the local data store (LDS)
2004 * All writes to the LDS happen in all executing threads at
2005 * the same time. TID is the Thread ID for the current
2006 * thread and is a value between 0 and 63, representing
2007 * the thread's position in the wavefront.
2009 * For the pixel shader threads are grouped into quads of four pixels.
2010 * The TIDs of the pixels of a quad are:
2018 * So, masking the TID with 0xfffffffc yields the TID of the top left pixel
2019 * of the quad, masking with 0xfffffffd yields the TID of the top pixel of
2020 * the current pixel's column, and masking with 0xfffffffe yields the TID
2021 * of the left pixel of the current pixel's row.
2023 * Adding 1 yields the TID of the pixel to the right of the left pixel, and
2024 * adding 2 yields the TID of the pixel below the top pixel.
2027 ac_build_ddxy(struct ac_llvm_context *ctx,
2032 unsigned tl_lanes[4], trbl_lanes[4];
2033 char name[32], type[8];
2034 LLVMValueRef tl, trbl;
2035 LLVMTypeRef result_type;
2036 LLVMValueRef result;
2038 result_type = ac_to_float_type(ctx, LLVMTypeOf(val));
2040 if (result_type == ctx->f16)
2041 val = LLVMBuildZExt(ctx->builder, val, ctx->i32, "");
2043 for (unsigned i = 0; i < 4; ++i) {
2044 tl_lanes[i] = i & mask;
2045 trbl_lanes[i] = (i & mask) + idx;
2048 tl = ac_build_quad_swizzle(ctx, val,
2049 tl_lanes[0], tl_lanes[1],
2050 tl_lanes[2], tl_lanes[3]);
2051 trbl = ac_build_quad_swizzle(ctx, val,
2052 trbl_lanes[0], trbl_lanes[1],
2053 trbl_lanes[2], trbl_lanes[3]);
2055 if (result_type == ctx->f16) {
2056 tl = LLVMBuildTrunc(ctx->builder, tl, ctx->i16, "");
2057 trbl = LLVMBuildTrunc(ctx->builder, trbl, ctx->i16, "");
2060 tl = LLVMBuildBitCast(ctx->builder, tl, result_type, "");
2061 trbl = LLVMBuildBitCast(ctx->builder, trbl, result_type, "");
2062 result = LLVMBuildFSub(ctx->builder, trbl, tl, "");
2064 ac_build_type_name_for_intr(result_type, type, sizeof(type));
2065 snprintf(name, sizeof(name), "llvm.amdgcn.wqm.%s", type);
2067 return ac_build_intrinsic(ctx, name, result_type, &result, 1, 0);
2071 ac_build_sendmsg(struct ac_llvm_context *ctx,
2073 LLVMValueRef wave_id)
2075 LLVMValueRef args[2];
2076 args[0] = LLVMConstInt(ctx->i32, msg, false);
2078 ac_build_intrinsic(ctx, "llvm.amdgcn.s.sendmsg", ctx->voidt, args, 2, 0);
2082 ac_build_imsb(struct ac_llvm_context *ctx,
2084 LLVMTypeRef dst_type)
2086 LLVMValueRef msb = ac_build_intrinsic(ctx, "llvm.amdgcn.sffbh.i32",
2088 AC_FUNC_ATTR_READNONE);
2090 /* The HW returns the last bit index from MSB, but NIR/TGSI wants
2091 * the index from LSB. Invert it by doing "31 - msb". */
2092 msb = LLVMBuildSub(ctx->builder, LLVMConstInt(ctx->i32, 31, false),
2095 LLVMValueRef all_ones = LLVMConstInt(ctx->i32, -1, true);
2096 LLVMValueRef cond = LLVMBuildOr(ctx->builder,
2097 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
2098 arg, ctx->i32_0, ""),
2099 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
2100 arg, all_ones, ""), "");
2102 return LLVMBuildSelect(ctx->builder, cond, all_ones, msb, "");
2106 ac_build_umsb(struct ac_llvm_context *ctx,
2108 LLVMTypeRef dst_type)
2110 const char *intrin_name;
2112 LLVMValueRef highest_bit;
2116 bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(arg));
2119 intrin_name = "llvm.ctlz.i64";
2121 highest_bit = LLVMConstInt(ctx->i64, 63, false);
2125 intrin_name = "llvm.ctlz.i32";
2127 highest_bit = LLVMConstInt(ctx->i32, 31, false);
2131 intrin_name = "llvm.ctlz.i16";
2133 highest_bit = LLVMConstInt(ctx->i16, 15, false);
2137 intrin_name = "llvm.ctlz.i8";
2139 highest_bit = LLVMConstInt(ctx->i8, 7, false);
2143 unreachable(!"invalid bitsize");
2147 LLVMValueRef params[2] = {
2152 LLVMValueRef msb = ac_build_intrinsic(ctx, intrin_name, type,
2154 AC_FUNC_ATTR_READNONE);
2156 /* The HW returns the last bit index from MSB, but TGSI/NIR wants
2157 * the index from LSB. Invert it by doing "31 - msb". */
2158 msb = LLVMBuildSub(ctx->builder, highest_bit, msb, "");
2160 if (bitsize == 64) {
2161 msb = LLVMBuildTrunc(ctx->builder, msb, ctx->i32, "");
2162 } else if (bitsize < 32) {
2163 msb = LLVMBuildSExt(ctx->builder, msb, ctx->i32, "");
2166 /* check for zero */
2167 return LLVMBuildSelect(ctx->builder,
2168 LLVMBuildICmp(ctx->builder, LLVMIntEQ, arg, zero, ""),
2169 LLVMConstInt(ctx->i32, -1, true), msb, "");
2172 LLVMValueRef ac_build_fmin(struct ac_llvm_context *ctx, LLVMValueRef a,
2176 snprintf(name, sizeof(name), "llvm.minnum.f%d", ac_get_elem_bits(ctx, LLVMTypeOf(a)));
2177 LLVMValueRef args[2] = {a, b};
2178 return ac_build_intrinsic(ctx, name, LLVMTypeOf(a), args, 2,
2179 AC_FUNC_ATTR_READNONE);
2182 LLVMValueRef ac_build_fmax(struct ac_llvm_context *ctx, LLVMValueRef a,
2186 snprintf(name, sizeof(name), "llvm.maxnum.f%d", ac_get_elem_bits(ctx, LLVMTypeOf(a)));
2187 LLVMValueRef args[2] = {a, b};
2188 return ac_build_intrinsic(ctx, name, LLVMTypeOf(a), args, 2,
2189 AC_FUNC_ATTR_READNONE);
2192 LLVMValueRef ac_build_imin(struct ac_llvm_context *ctx, LLVMValueRef a,
2195 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSLE, a, b, "");
2196 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
2199 LLVMValueRef ac_build_imax(struct ac_llvm_context *ctx, LLVMValueRef a,
2202 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, a, b, "");
2203 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
2206 LLVMValueRef ac_build_umin(struct ac_llvm_context *ctx, LLVMValueRef a,
2209 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntULE, a, b, "");
2210 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
2213 LLVMValueRef ac_build_umax(struct ac_llvm_context *ctx, LLVMValueRef a,
2216 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntUGE, a, b, "");
2217 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
2220 LLVMValueRef ac_build_clamp(struct ac_llvm_context *ctx, LLVMValueRef value)
2222 LLVMTypeRef t = LLVMTypeOf(value);
2223 return ac_build_fmin(ctx, ac_build_fmax(ctx, value, LLVMConstReal(t, 0.0)),
2224 LLVMConstReal(t, 1.0));
2227 void ac_build_export(struct ac_llvm_context *ctx, struct ac_export_args *a)
2229 LLVMValueRef args[9];
2231 args[0] = LLVMConstInt(ctx->i32, a->target, 0);
2232 args[1] = LLVMConstInt(ctx->i32, a->enabled_channels, 0);
2235 LLVMTypeRef i16 = LLVMInt16TypeInContext(ctx->context);
2236 LLVMTypeRef v2i16 = LLVMVectorType(i16, 2);
2238 args[2] = LLVMBuildBitCast(ctx->builder, a->out[0],
2240 args[3] = LLVMBuildBitCast(ctx->builder, a->out[1],
2242 args[4] = LLVMConstInt(ctx->i1, a->done, 0);
2243 args[5] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
2245 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.compr.v2i16",
2246 ctx->voidt, args, 6, 0);
2248 args[2] = a->out[0];
2249 args[3] = a->out[1];
2250 args[4] = a->out[2];
2251 args[5] = a->out[3];
2252 args[6] = LLVMConstInt(ctx->i1, a->done, 0);
2253 args[7] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
2255 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.f32",
2256 ctx->voidt, args, 8, 0);
2260 void ac_build_export_null(struct ac_llvm_context *ctx)
2262 struct ac_export_args args;
2264 args.enabled_channels = 0x0; /* enabled channels */
2265 args.valid_mask = 1; /* whether the EXEC mask is valid */
2266 args.done = 1; /* DONE bit */
2267 args.target = V_008DFC_SQ_EXP_NULL;
2268 args.compr = 0; /* COMPR flag (0 = 32-bit export) */
2269 args.out[0] = LLVMGetUndef(ctx->f32); /* R */
2270 args.out[1] = LLVMGetUndef(ctx->f32); /* G */
2271 args.out[2] = LLVMGetUndef(ctx->f32); /* B */
2272 args.out[3] = LLVMGetUndef(ctx->f32); /* A */
2274 ac_build_export(ctx, &args);
2277 static unsigned ac_num_coords(enum ac_image_dim dim)
2283 case ac_image_1darray:
2287 case ac_image_2darray:
2288 case ac_image_2dmsaa:
2290 case ac_image_2darraymsaa:
2293 unreachable("ac_num_coords: bad dim");
2297 static unsigned ac_num_derivs(enum ac_image_dim dim)
2301 case ac_image_1darray:
2304 case ac_image_2darray:
2309 case ac_image_2dmsaa:
2310 case ac_image_2darraymsaa:
2312 unreachable("derivatives not supported");
2316 static const char *get_atomic_name(enum ac_atomic_op op)
2319 case ac_atomic_swap: return "swap";
2320 case ac_atomic_add: return "add";
2321 case ac_atomic_sub: return "sub";
2322 case ac_atomic_smin: return "smin";
2323 case ac_atomic_umin: return "umin";
2324 case ac_atomic_smax: return "smax";
2325 case ac_atomic_umax: return "umax";
2326 case ac_atomic_and: return "and";
2327 case ac_atomic_or: return "or";
2328 case ac_atomic_xor: return "xor";
2329 case ac_atomic_inc_wrap: return "inc";
2330 case ac_atomic_dec_wrap: return "dec";
2332 unreachable("bad atomic op");
2335 LLVMValueRef ac_build_image_opcode(struct ac_llvm_context *ctx,
2336 struct ac_image_args *a)
2338 const char *overload[3] = { "", "", "" };
2339 unsigned num_overloads = 0;
2340 LLVMValueRef args[18];
2341 unsigned num_args = 0;
2342 enum ac_image_dim dim = a->dim;
2344 assert(!a->lod || a->lod == ctx->i32_0 || a->lod == ctx->f32_0 ||
2346 assert((a->opcode != ac_image_get_resinfo && a->opcode != ac_image_load_mip &&
2347 a->opcode != ac_image_store_mip) ||
2349 assert(a->opcode == ac_image_sample || a->opcode == ac_image_gather4 ||
2350 (!a->compare && !a->offset));
2351 assert((a->opcode == ac_image_sample || a->opcode == ac_image_gather4 ||
2352 a->opcode == ac_image_get_lod) ||
2354 assert((a->bias ? 1 : 0) +
2356 (a->level_zero ? 1 : 0) +
2357 (a->derivs[0] ? 1 : 0) <= 1);
2359 if (a->opcode == ac_image_get_lod) {
2361 case ac_image_1darray:
2364 case ac_image_2darray:
2373 bool sample = a->opcode == ac_image_sample ||
2374 a->opcode == ac_image_gather4 ||
2375 a->opcode == ac_image_get_lod;
2376 bool atomic = a->opcode == ac_image_atomic ||
2377 a->opcode == ac_image_atomic_cmpswap;
2378 bool load = a->opcode == ac_image_sample ||
2379 a->opcode == ac_image_gather4 ||
2380 a->opcode == ac_image_load ||
2381 a->opcode == ac_image_load_mip;
2382 LLVMTypeRef coord_type = sample ? ctx->f32 : ctx->i32;
2384 if (atomic || a->opcode == ac_image_store || a->opcode == ac_image_store_mip) {
2385 args[num_args++] = a->data[0];
2386 if (a->opcode == ac_image_atomic_cmpswap)
2387 args[num_args++] = a->data[1];
2391 args[num_args++] = LLVMConstInt(ctx->i32, a->dmask, false);
2394 args[num_args++] = ac_to_integer(ctx, a->offset);
2396 args[num_args++] = ac_to_float(ctx, a->bias);
2397 overload[num_overloads++] = ".f32";
2400 args[num_args++] = ac_to_float(ctx, a->compare);
2402 unsigned count = ac_num_derivs(dim);
2403 for (unsigned i = 0; i < count; ++i)
2404 args[num_args++] = ac_to_float(ctx, a->derivs[i]);
2405 overload[num_overloads++] = ".f32";
2407 unsigned num_coords =
2408 a->opcode != ac_image_get_resinfo ? ac_num_coords(dim) : 0;
2409 for (unsigned i = 0; i < num_coords; ++i)
2410 args[num_args++] = LLVMBuildBitCast(ctx->builder, a->coords[i], coord_type, "");
2412 args[num_args++] = LLVMBuildBitCast(ctx->builder, a->lod, coord_type, "");
2413 overload[num_overloads++] = sample ? ".f32" : ".i32";
2415 args[num_args++] = a->resource;
2417 args[num_args++] = a->sampler;
2418 args[num_args++] = LLVMConstInt(ctx->i1, a->unorm, false);
2421 args[num_args++] = ctx->i32_0; /* texfailctrl */
2422 args[num_args++] = LLVMConstInt(ctx->i32,
2423 load ? get_load_cache_policy(ctx, a->cache_policy) :
2424 a->cache_policy, false);
2427 const char *atomic_subop = "";
2428 switch (a->opcode) {
2429 case ac_image_sample: name = "sample"; break;
2430 case ac_image_gather4: name = "gather4"; break;
2431 case ac_image_load: name = "load"; break;
2432 case ac_image_load_mip: name = "load.mip"; break;
2433 case ac_image_store: name = "store"; break;
2434 case ac_image_store_mip: name = "store.mip"; break;
2435 case ac_image_atomic:
2437 atomic_subop = get_atomic_name(a->atomic);
2439 case ac_image_atomic_cmpswap:
2441 atomic_subop = "cmpswap";
2443 case ac_image_get_lod: name = "getlod"; break;
2444 case ac_image_get_resinfo: name = "getresinfo"; break;
2445 default: unreachable("invalid image opcode");
2448 const char *dimname;
2450 case ac_image_1d: dimname = "1d"; break;
2451 case ac_image_2d: dimname = "2d"; break;
2452 case ac_image_3d: dimname = "3d"; break;
2453 case ac_image_cube: dimname = "cube"; break;
2454 case ac_image_1darray: dimname = "1darray"; break;
2455 case ac_image_2darray: dimname = "2darray"; break;
2456 case ac_image_2dmsaa: dimname = "2dmsaa"; break;
2457 case ac_image_2darraymsaa: dimname = "2darraymsaa"; break;
2458 default: unreachable("invalid dim");
2462 a->lod && (a->opcode == ac_image_sample || a->opcode == ac_image_gather4);
2464 snprintf(intr_name, sizeof(intr_name),
2465 "llvm.amdgcn.image.%s%s" /* base name */
2466 "%s%s%s" /* sample/gather modifiers */
2467 ".%s.%s%s%s%s", /* dimension and type overloads */
2469 a->compare ? ".c" : "",
2472 a->derivs[0] ? ".d" :
2473 a->level_zero ? ".lz" : "",
2474 a->offset ? ".o" : "",
2476 atomic ? "i32" : "v4f32",
2477 overload[0], overload[1], overload[2]);
2482 else if (a->opcode == ac_image_store || a->opcode == ac_image_store_mip)
2487 LLVMValueRef result =
2488 ac_build_intrinsic(ctx, intr_name, retty, args, num_args,
2490 if (!sample && retty == ctx->v4f32) {
2491 result = LLVMBuildBitCast(ctx->builder, result,
2497 LLVMValueRef ac_build_image_get_sample_count(struct ac_llvm_context *ctx,
2500 LLVMValueRef samples;
2502 /* Read the samples from the descriptor directly.
2503 * Hardware doesn't have any instruction for this.
2505 samples = LLVMBuildExtractElement(ctx->builder, rsrc,
2506 LLVMConstInt(ctx->i32, 3, 0), "");
2507 samples = LLVMBuildLShr(ctx->builder, samples,
2508 LLVMConstInt(ctx->i32, 16, 0), "");
2509 samples = LLVMBuildAnd(ctx->builder, samples,
2510 LLVMConstInt(ctx->i32, 0xf, 0), "");
2511 samples = LLVMBuildShl(ctx->builder, ctx->i32_1,
2516 LLVMValueRef ac_build_cvt_pkrtz_f16(struct ac_llvm_context *ctx,
2517 LLVMValueRef args[2])
2520 LLVMVectorType(LLVMHalfTypeInContext(ctx->context), 2);
2522 return ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pkrtz", v2f16,
2523 args, 2, AC_FUNC_ATTR_READNONE);
2526 LLVMValueRef ac_build_cvt_pknorm_i16(struct ac_llvm_context *ctx,
2527 LLVMValueRef args[2])
2530 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.i16",
2531 ctx->v2i16, args, 2,
2532 AC_FUNC_ATTR_READNONE);
2533 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2536 LLVMValueRef ac_build_cvt_pknorm_u16(struct ac_llvm_context *ctx,
2537 LLVMValueRef args[2])
2540 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.u16",
2541 ctx->v2i16, args, 2,
2542 AC_FUNC_ATTR_READNONE);
2543 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2546 /* The 8-bit and 10-bit clamping is for HW workarounds. */
2547 LLVMValueRef ac_build_cvt_pk_i16(struct ac_llvm_context *ctx,
2548 LLVMValueRef args[2], unsigned bits, bool hi)
2550 assert(bits == 8 || bits == 10 || bits == 16);
2552 LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
2553 bits == 8 ? 127 : bits == 10 ? 511 : 32767, 0);
2554 LLVMValueRef min_rgb = LLVMConstInt(ctx->i32,
2555 bits == 8 ? -128 : bits == 10 ? -512 : -32768, 0);
2556 LLVMValueRef max_alpha =
2557 bits != 10 ? max_rgb : ctx->i32_1;
2558 LLVMValueRef min_alpha =
2559 bits != 10 ? min_rgb : LLVMConstInt(ctx->i32, -2, 0);
2563 for (int i = 0; i < 2; i++) {
2564 bool alpha = hi && i == 1;
2565 args[i] = ac_build_imin(ctx, args[i],
2566 alpha ? max_alpha : max_rgb);
2567 args[i] = ac_build_imax(ctx, args[i],
2568 alpha ? min_alpha : min_rgb);
2573 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.i16",
2574 ctx->v2i16, args, 2,
2575 AC_FUNC_ATTR_READNONE);
2576 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2579 /* The 8-bit and 10-bit clamping is for HW workarounds. */
2580 LLVMValueRef ac_build_cvt_pk_u16(struct ac_llvm_context *ctx,
2581 LLVMValueRef args[2], unsigned bits, bool hi)
2583 assert(bits == 8 || bits == 10 || bits == 16);
2585 LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
2586 bits == 8 ? 255 : bits == 10 ? 1023 : 65535, 0);
2587 LLVMValueRef max_alpha =
2588 bits != 10 ? max_rgb : LLVMConstInt(ctx->i32, 3, 0);
2592 for (int i = 0; i < 2; i++) {
2593 bool alpha = hi && i == 1;
2594 args[i] = ac_build_umin(ctx, args[i],
2595 alpha ? max_alpha : max_rgb);
2600 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.u16",
2601 ctx->v2i16, args, 2,
2602 AC_FUNC_ATTR_READNONE);
2603 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2606 LLVMValueRef ac_build_wqm_vote(struct ac_llvm_context *ctx, LLVMValueRef i1)
2608 return ac_build_intrinsic(ctx, "llvm.amdgcn.wqm.vote", ctx->i1,
2609 &i1, 1, AC_FUNC_ATTR_READNONE);
2612 void ac_build_kill_if_false(struct ac_llvm_context *ctx, LLVMValueRef i1)
2614 ac_build_intrinsic(ctx, "llvm.amdgcn.kill", ctx->voidt,
2618 LLVMValueRef ac_build_bfe(struct ac_llvm_context *ctx, LLVMValueRef input,
2619 LLVMValueRef offset, LLVMValueRef width,
2622 LLVMValueRef args[] = {
2628 return ac_build_intrinsic(ctx, is_signed ? "llvm.amdgcn.sbfe.i32" :
2629 "llvm.amdgcn.ubfe.i32",
2630 ctx->i32, args, 3, AC_FUNC_ATTR_READNONE);
2634 LLVMValueRef ac_build_imad(struct ac_llvm_context *ctx, LLVMValueRef s0,
2635 LLVMValueRef s1, LLVMValueRef s2)
2637 return LLVMBuildAdd(ctx->builder,
2638 LLVMBuildMul(ctx->builder, s0, s1, ""), s2, "");
2641 LLVMValueRef ac_build_fmad(struct ac_llvm_context *ctx, LLVMValueRef s0,
2642 LLVMValueRef s1, LLVMValueRef s2)
2644 /* FMA is better on GFX10, because it has FMA units instead of MUL-ADD units. */
2645 if (ctx->chip_class >= GFX10) {
2646 return ac_build_intrinsic(ctx, "llvm.fma.f32", ctx->f32,
2647 (LLVMValueRef []) {s0, s1, s2}, 3,
2648 AC_FUNC_ATTR_READNONE);
2651 return LLVMBuildFAdd(ctx->builder,
2652 LLVMBuildFMul(ctx->builder, s0, s1, ""), s2, "");
2655 void ac_build_waitcnt(struct ac_llvm_context *ctx, unsigned wait_flags)
2660 unsigned lgkmcnt = 63;
2661 unsigned vmcnt = ctx->chip_class >= GFX9 ? 63 : 15;
2662 unsigned vscnt = 63;
2664 if (wait_flags & AC_WAIT_LGKM)
2666 if (wait_flags & AC_WAIT_VLOAD)
2669 if (wait_flags & AC_WAIT_VSTORE) {
2670 if (ctx->chip_class >= GFX10)
2676 /* There is no intrinsic for vscnt(0), so use a fence. */
2677 if ((wait_flags & AC_WAIT_LGKM &&
2678 wait_flags & AC_WAIT_VLOAD &&
2679 wait_flags & AC_WAIT_VSTORE) ||
2681 LLVMBuildFence(ctx->builder, LLVMAtomicOrderingRelease, false, "");
2685 unsigned simm16 = (lgkmcnt << 8) |
2686 (7 << 4) | /* expcnt */
2688 ((vmcnt >> 4) << 14);
2690 LLVMValueRef args[1] = {
2691 LLVMConstInt(ctx->i32, simm16, false),
2693 ac_build_intrinsic(ctx, "llvm.amdgcn.s.waitcnt",
2694 ctx->voidt, args, 1, 0);
2697 LLVMValueRef ac_build_fmed3(struct ac_llvm_context *ctx, LLVMValueRef src0,
2698 LLVMValueRef src1, LLVMValueRef src2,
2701 LLVMValueRef result;
2703 if (bitsize == 64 || (bitsize == 16 && ctx->chip_class <= GFX8)) {
2704 /* Lower 64-bit fmed because LLVM doesn't expose an intrinsic,
2705 * or lower 16-bit fmed because it's only supported on GFX9+.
2707 LLVMValueRef min1, min2, max1;
2709 min1 = ac_build_fmin(ctx, src0, src1);
2710 max1 = ac_build_fmax(ctx, src0, src1);
2711 min2 = ac_build_fmin(ctx, max1, src2);
2713 result = ac_build_fmax(ctx, min2, min1);
2718 if (bitsize == 16) {
2719 intr = "llvm.amdgcn.fmed3.f16";
2722 assert(bitsize == 32);
2723 intr = "llvm.amdgcn.fmed3.f32";
2727 LLVMValueRef params[] = {
2733 result = ac_build_intrinsic(ctx, intr, type, params, 3,
2734 AC_FUNC_ATTR_READNONE);
2737 if (ctx->chip_class < GFX9 && bitsize == 32) {
2738 /* Only pre-GFX9 chips do not flush denorms. */
2739 result = ac_build_canonicalize(ctx, result, bitsize);
2745 LLVMValueRef ac_build_fract(struct ac_llvm_context *ctx, LLVMValueRef src0,
2751 if (bitsize == 16) {
2752 intr = "llvm.amdgcn.fract.f16";
2754 } else if (bitsize == 32) {
2755 intr = "llvm.amdgcn.fract.f32";
2758 intr = "llvm.amdgcn.fract.f64";
2762 LLVMValueRef params[] = {
2765 return ac_build_intrinsic(ctx, intr, type, params, 1,
2766 AC_FUNC_ATTR_READNONE);
2769 LLVMValueRef ac_build_isign(struct ac_llvm_context *ctx, LLVMValueRef src0,
2772 LLVMTypeRef type = LLVMIntTypeInContext(ctx->context, bitsize);
2773 LLVMValueRef zero = LLVMConstInt(type, 0, false);
2774 LLVMValueRef one = LLVMConstInt(type, 1, false);
2776 LLVMValueRef cmp, val;
2777 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, src0, zero, "");
2778 val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
2779 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGE, val, zero, "");
2780 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstInt(type, -1, true), "");
2784 LLVMValueRef ac_build_fsign(struct ac_llvm_context *ctx, LLVMValueRef src0,
2787 LLVMValueRef cmp, val, zero, one;
2790 if (bitsize == 16) {
2794 } else if (bitsize == 32) {
2804 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGT, src0, zero, "");
2805 val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
2806 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGE, val, zero, "");
2807 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstReal(type, -1.0), "");
2811 LLVMValueRef ac_build_bit_count(struct ac_llvm_context *ctx, LLVMValueRef src0)
2813 LLVMValueRef result;
2816 bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
2820 result = ac_build_intrinsic(ctx, "llvm.ctpop.i64", ctx->i64,
2821 (LLVMValueRef []) { src0 }, 1,
2822 AC_FUNC_ATTR_READNONE);
2824 result = LLVMBuildTrunc(ctx->builder, result, ctx->i32, "");
2827 result = ac_build_intrinsic(ctx, "llvm.ctpop.i32", ctx->i32,
2828 (LLVMValueRef []) { src0 }, 1,
2829 AC_FUNC_ATTR_READNONE);
2832 result = ac_build_intrinsic(ctx, "llvm.ctpop.i16", ctx->i16,
2833 (LLVMValueRef []) { src0 }, 1,
2834 AC_FUNC_ATTR_READNONE);
2836 result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
2839 result = ac_build_intrinsic(ctx, "llvm.ctpop.i8", ctx->i8,
2840 (LLVMValueRef []) { src0 }, 1,
2841 AC_FUNC_ATTR_READNONE);
2843 result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
2846 unreachable(!"invalid bitsize");
2853 LLVMValueRef ac_build_bitfield_reverse(struct ac_llvm_context *ctx,
2856 LLVMValueRef result;
2859 bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
2863 result = ac_build_intrinsic(ctx, "llvm.bitreverse.i64", ctx->i64,
2864 (LLVMValueRef []) { src0 }, 1,
2865 AC_FUNC_ATTR_READNONE);
2867 result = LLVMBuildTrunc(ctx->builder, result, ctx->i32, "");
2870 result = ac_build_intrinsic(ctx, "llvm.bitreverse.i32", ctx->i32,
2871 (LLVMValueRef []) { src0 }, 1,
2872 AC_FUNC_ATTR_READNONE);
2875 result = ac_build_intrinsic(ctx, "llvm.bitreverse.i16", ctx->i16,
2876 (LLVMValueRef []) { src0 }, 1,
2877 AC_FUNC_ATTR_READNONE);
2879 result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
2882 result = ac_build_intrinsic(ctx, "llvm.bitreverse.i8", ctx->i8,
2883 (LLVMValueRef []) { src0 }, 1,
2884 AC_FUNC_ATTR_READNONE);
2886 result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
2889 unreachable(!"invalid bitsize");
2896 #define AC_EXP_TARGET 0
2897 #define AC_EXP_ENABLED_CHANNELS 1
2898 #define AC_EXP_OUT0 2
2906 struct ac_vs_exp_chan
2910 enum ac_ir_type type;
2913 struct ac_vs_exp_inst {
2916 struct ac_vs_exp_chan chan[4];
2919 struct ac_vs_exports {
2921 struct ac_vs_exp_inst exp[VARYING_SLOT_MAX];
2924 /* Return true if the PARAM export has been eliminated. */
2925 static bool ac_eliminate_const_output(uint8_t *vs_output_param_offset,
2926 uint32_t num_outputs,
2927 struct ac_vs_exp_inst *exp)
2929 unsigned i, default_val; /* SPI_PS_INPUT_CNTL_i.DEFAULT_VAL */
2930 bool is_zero[4] = {}, is_one[4] = {};
2932 for (i = 0; i < 4; i++) {
2933 /* It's a constant expression. Undef outputs are eliminated too. */
2934 if (exp->chan[i].type == AC_IR_UNDEF) {
2937 } else if (exp->chan[i].type == AC_IR_CONST) {
2938 if (exp->chan[i].const_float == 0)
2940 else if (exp->chan[i].const_float == 1)
2943 return false; /* other constant */
2948 /* Only certain combinations of 0 and 1 can be eliminated. */
2949 if (is_zero[0] && is_zero[1] && is_zero[2])
2950 default_val = is_zero[3] ? 0 : 1;
2951 else if (is_one[0] && is_one[1] && is_one[2])
2952 default_val = is_zero[3] ? 2 : 3;
2956 /* The PARAM export can be represented as DEFAULT_VAL. Kill it. */
2957 LLVMInstructionEraseFromParent(exp->inst);
2959 /* Change OFFSET to DEFAULT_VAL. */
2960 for (i = 0; i < num_outputs; i++) {
2961 if (vs_output_param_offset[i] == exp->offset) {
2962 vs_output_param_offset[i] =
2963 AC_EXP_PARAM_DEFAULT_VAL_0000 + default_val;
2970 static bool ac_eliminate_duplicated_output(struct ac_llvm_context *ctx,
2971 uint8_t *vs_output_param_offset,
2972 uint32_t num_outputs,
2973 struct ac_vs_exports *processed,
2974 struct ac_vs_exp_inst *exp)
2976 unsigned p, copy_back_channels = 0;
2978 /* See if the output is already in the list of processed outputs.
2979 * The LLVMValueRef comparison relies on SSA.
2981 for (p = 0; p < processed->num; p++) {
2982 bool different = false;
2984 for (unsigned j = 0; j < 4; j++) {
2985 struct ac_vs_exp_chan *c1 = &processed->exp[p].chan[j];
2986 struct ac_vs_exp_chan *c2 = &exp->chan[j];
2988 /* Treat undef as a match. */
2989 if (c2->type == AC_IR_UNDEF)
2992 /* If c1 is undef but c2 isn't, we can copy c2 to c1
2993 * and consider the instruction duplicated.
2995 if (c1->type == AC_IR_UNDEF) {
2996 copy_back_channels |= 1 << j;
3000 /* Test whether the channels are not equal. */
3001 if (c1->type != c2->type ||
3002 (c1->type == AC_IR_CONST &&
3003 c1->const_float != c2->const_float) ||
3004 (c1->type == AC_IR_VALUE &&
3005 c1->value != c2->value)) {
3013 copy_back_channels = 0;
3015 if (p == processed->num)
3018 /* If a match was found, but the matching export has undef where the new
3019 * one has a normal value, copy the normal value to the undef channel.
3021 struct ac_vs_exp_inst *match = &processed->exp[p];
3023 /* Get current enabled channels mask. */
3024 LLVMValueRef arg = LLVMGetOperand(match->inst, AC_EXP_ENABLED_CHANNELS);
3025 unsigned enabled_channels = LLVMConstIntGetZExtValue(arg);
3027 while (copy_back_channels) {
3028 unsigned chan = u_bit_scan(©_back_channels);
3030 assert(match->chan[chan].type == AC_IR_UNDEF);
3031 LLVMSetOperand(match->inst, AC_EXP_OUT0 + chan,
3032 exp->chan[chan].value);
3033 match->chan[chan] = exp->chan[chan];
3035 /* Update number of enabled channels because the original mask
3036 * is not always 0xf.
3038 enabled_channels |= (1 << chan);
3039 LLVMSetOperand(match->inst, AC_EXP_ENABLED_CHANNELS,
3040 LLVMConstInt(ctx->i32, enabled_channels, 0));
3043 /* The PARAM export is duplicated. Kill it. */
3044 LLVMInstructionEraseFromParent(exp->inst);
3046 /* Change OFFSET to the matching export. */
3047 for (unsigned i = 0; i < num_outputs; i++) {
3048 if (vs_output_param_offset[i] == exp->offset) {
3049 vs_output_param_offset[i] = match->offset;
3056 void ac_optimize_vs_outputs(struct ac_llvm_context *ctx,
3057 LLVMValueRef main_fn,
3058 uint8_t *vs_output_param_offset,
3059 uint32_t num_outputs,
3060 uint8_t *num_param_exports)
3062 LLVMBasicBlockRef bb;
3063 bool removed_any = false;
3064 struct ac_vs_exports exports;
3068 /* Process all LLVM instructions. */
3069 bb = LLVMGetFirstBasicBlock(main_fn);
3071 LLVMValueRef inst = LLVMGetFirstInstruction(bb);
3074 LLVMValueRef cur = inst;
3075 inst = LLVMGetNextInstruction(inst);
3076 struct ac_vs_exp_inst exp;
3078 if (LLVMGetInstructionOpcode(cur) != LLVMCall)
3081 LLVMValueRef callee = ac_llvm_get_called_value(cur);
3083 if (!ac_llvm_is_function(callee))
3086 const char *name = LLVMGetValueName(callee);
3087 unsigned num_args = LLVMCountParams(callee);
3089 /* Check if this is an export instruction. */
3090 if ((num_args != 9 && num_args != 8) ||
3091 (strcmp(name, "llvm.SI.export") &&
3092 strcmp(name, "llvm.amdgcn.exp.f32")))
3095 LLVMValueRef arg = LLVMGetOperand(cur, AC_EXP_TARGET);
3096 unsigned target = LLVMConstIntGetZExtValue(arg);
3098 if (target < V_008DFC_SQ_EXP_PARAM)
3101 target -= V_008DFC_SQ_EXP_PARAM;
3103 /* Parse the instruction. */
3104 memset(&exp, 0, sizeof(exp));
3105 exp.offset = target;
3108 for (unsigned i = 0; i < 4; i++) {
3109 LLVMValueRef v = LLVMGetOperand(cur, AC_EXP_OUT0 + i);
3111 exp.chan[i].value = v;
3113 if (LLVMIsUndef(v)) {
3114 exp.chan[i].type = AC_IR_UNDEF;
3115 } else if (LLVMIsAConstantFP(v)) {
3116 LLVMBool loses_info;
3117 exp.chan[i].type = AC_IR_CONST;
3118 exp.chan[i].const_float =
3119 LLVMConstRealGetDouble(v, &loses_info);
3121 exp.chan[i].type = AC_IR_VALUE;
3125 /* Eliminate constant and duplicated PARAM exports. */
3126 if (ac_eliminate_const_output(vs_output_param_offset,
3127 num_outputs, &exp) ||
3128 ac_eliminate_duplicated_output(ctx,
3129 vs_output_param_offset,
3130 num_outputs, &exports,
3134 exports.exp[exports.num++] = exp;
3137 bb = LLVMGetNextBasicBlock(bb);
3140 /* Remove holes in export memory due to removed PARAM exports.
3141 * This is done by renumbering all PARAM exports.
3144 uint8_t old_offset[VARYING_SLOT_MAX];
3147 /* Make a copy of the offsets. We need the old version while
3148 * we are modifying some of them. */
3149 memcpy(old_offset, vs_output_param_offset,
3150 sizeof(old_offset));
3152 for (i = 0; i < exports.num; i++) {
3153 unsigned offset = exports.exp[i].offset;
3155 /* Update vs_output_param_offset. Multiple outputs can
3156 * have the same offset.
3158 for (out = 0; out < num_outputs; out++) {
3159 if (old_offset[out] == offset)
3160 vs_output_param_offset[out] = i;
3163 /* Change the PARAM offset in the instruction. */
3164 LLVMSetOperand(exports.exp[i].inst, AC_EXP_TARGET,
3165 LLVMConstInt(ctx->i32,
3166 V_008DFC_SQ_EXP_PARAM + i, 0));
3168 *num_param_exports = exports.num;
3172 void ac_init_exec_full_mask(struct ac_llvm_context *ctx)
3174 LLVMValueRef full_mask = LLVMConstInt(ctx->i64, ~0ull, 0);
3175 ac_build_intrinsic(ctx,
3176 "llvm.amdgcn.init.exec", ctx->voidt,
3177 &full_mask, 1, AC_FUNC_ATTR_CONVERGENT);
3180 void ac_declare_lds_as_pointer(struct ac_llvm_context *ctx)
3182 unsigned lds_size = ctx->chip_class >= GFX7 ? 65536 : 32768;
3183 ctx->lds = LLVMBuildIntToPtr(ctx->builder, ctx->i32_0,
3184 LLVMPointerType(LLVMArrayType(ctx->i32, lds_size / 4), AC_ADDR_SPACE_LDS),
3188 LLVMValueRef ac_lds_load(struct ac_llvm_context *ctx,
3189 LLVMValueRef dw_addr)
3191 return LLVMBuildLoad(ctx->builder, ac_build_gep0(ctx, ctx->lds, dw_addr), "");
3194 void ac_lds_store(struct ac_llvm_context *ctx,
3195 LLVMValueRef dw_addr,
3198 value = ac_to_integer(ctx, value);
3199 ac_build_indexed_store(ctx, ctx->lds,
3203 LLVMValueRef ac_find_lsb(struct ac_llvm_context *ctx,
3204 LLVMTypeRef dst_type,
3207 unsigned src0_bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
3208 const char *intrin_name;
3212 switch (src0_bitsize) {
3214 intrin_name = "llvm.cttz.i64";
3219 intrin_name = "llvm.cttz.i32";
3224 intrin_name = "llvm.cttz.i16";
3229 intrin_name = "llvm.cttz.i8";
3234 unreachable(!"invalid bitsize");
3237 LLVMValueRef params[2] = {
3240 /* The value of 1 means that ffs(x=0) = undef, so LLVM won't
3241 * add special code to check for x=0. The reason is that
3242 * the LLVM behavior for x=0 is different from what we
3243 * need here. However, LLVM also assumes that ffs(x) is
3244 * in [0, 31], but GLSL expects that ffs(0) = -1, so
3245 * a conditional assignment to handle 0 is still required.
3247 * The hardware already implements the correct behavior.
3252 LLVMValueRef lsb = ac_build_intrinsic(ctx, intrin_name, type,
3254 AC_FUNC_ATTR_READNONE);
3256 if (src0_bitsize == 64) {
3257 lsb = LLVMBuildTrunc(ctx->builder, lsb, ctx->i32, "");
3258 } else if (src0_bitsize < 32) {
3259 lsb = LLVMBuildSExt(ctx->builder, lsb, ctx->i32, "");
3262 /* TODO: We need an intrinsic to skip this conditional. */
3263 /* Check for zero: */
3264 return LLVMBuildSelect(ctx->builder, LLVMBuildICmp(ctx->builder,
3267 LLVMConstInt(ctx->i32, -1, 0), lsb, "");
3270 LLVMTypeRef ac_array_in_const_addr_space(LLVMTypeRef elem_type)
3272 return LLVMPointerType(elem_type, AC_ADDR_SPACE_CONST);
3275 LLVMTypeRef ac_array_in_const32_addr_space(LLVMTypeRef elem_type)
3277 return LLVMPointerType(elem_type, AC_ADDR_SPACE_CONST_32BIT);
3280 static struct ac_llvm_flow *
3281 get_current_flow(struct ac_llvm_context *ctx)
3283 if (ctx->flow->depth > 0)
3284 return &ctx->flow->stack[ctx->flow->depth - 1];
3288 static struct ac_llvm_flow *
3289 get_innermost_loop(struct ac_llvm_context *ctx)
3291 for (unsigned i = ctx->flow->depth; i > 0; --i) {
3292 if (ctx->flow->stack[i - 1].loop_entry_block)
3293 return &ctx->flow->stack[i - 1];
3298 static struct ac_llvm_flow *
3299 push_flow(struct ac_llvm_context *ctx)
3301 struct ac_llvm_flow *flow;
3303 if (ctx->flow->depth >= ctx->flow->depth_max) {
3304 unsigned new_max = MAX2(ctx->flow->depth << 1,
3305 AC_LLVM_INITIAL_CF_DEPTH);
3307 ctx->flow->stack = realloc(ctx->flow->stack, new_max * sizeof(*ctx->flow->stack));
3308 ctx->flow->depth_max = new_max;
3311 flow = &ctx->flow->stack[ctx->flow->depth];
3314 flow->next_block = NULL;
3315 flow->loop_entry_block = NULL;
3319 static void set_basicblock_name(LLVMBasicBlockRef bb, const char *base,
3323 snprintf(buf, sizeof(buf), "%s%d", base, label_id);
3324 LLVMSetValueName(LLVMBasicBlockAsValue(bb), buf);
3327 /* Append a basic block at the level of the parent flow.
3329 static LLVMBasicBlockRef append_basic_block(struct ac_llvm_context *ctx,
3332 assert(ctx->flow->depth >= 1);
3334 if (ctx->flow->depth >= 2) {
3335 struct ac_llvm_flow *flow = &ctx->flow->stack[ctx->flow->depth - 2];
3337 return LLVMInsertBasicBlockInContext(ctx->context,
3338 flow->next_block, name);
3341 LLVMValueRef main_fn =
3342 LLVMGetBasicBlockParent(LLVMGetInsertBlock(ctx->builder));
3343 return LLVMAppendBasicBlockInContext(ctx->context, main_fn, name);
3346 /* Emit a branch to the given default target for the current block if
3347 * applicable -- that is, if the current block does not already contain a
3348 * branch from a break or continue.
3350 static void emit_default_branch(LLVMBuilderRef builder,
3351 LLVMBasicBlockRef target)
3353 if (!LLVMGetBasicBlockTerminator(LLVMGetInsertBlock(builder)))
3354 LLVMBuildBr(builder, target);
3357 void ac_build_bgnloop(struct ac_llvm_context *ctx, int label_id)
3359 struct ac_llvm_flow *flow = push_flow(ctx);
3360 flow->loop_entry_block = append_basic_block(ctx, "LOOP");
3361 flow->next_block = append_basic_block(ctx, "ENDLOOP");
3362 set_basicblock_name(flow->loop_entry_block, "loop", label_id);
3363 LLVMBuildBr(ctx->builder, flow->loop_entry_block);
3364 LLVMPositionBuilderAtEnd(ctx->builder, flow->loop_entry_block);
3367 void ac_build_break(struct ac_llvm_context *ctx)
3369 struct ac_llvm_flow *flow = get_innermost_loop(ctx);
3370 LLVMBuildBr(ctx->builder, flow->next_block);
3373 void ac_build_continue(struct ac_llvm_context *ctx)
3375 struct ac_llvm_flow *flow = get_innermost_loop(ctx);
3376 LLVMBuildBr(ctx->builder, flow->loop_entry_block);
3379 void ac_build_else(struct ac_llvm_context *ctx, int label_id)
3381 struct ac_llvm_flow *current_branch = get_current_flow(ctx);
3382 LLVMBasicBlockRef endif_block;
3384 assert(!current_branch->loop_entry_block);
3386 endif_block = append_basic_block(ctx, "ENDIF");
3387 emit_default_branch(ctx->builder, endif_block);
3389 LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
3390 set_basicblock_name(current_branch->next_block, "else", label_id);
3392 current_branch->next_block = endif_block;
3395 void ac_build_endif(struct ac_llvm_context *ctx, int label_id)
3397 struct ac_llvm_flow *current_branch = get_current_flow(ctx);
3399 assert(!current_branch->loop_entry_block);
3401 emit_default_branch(ctx->builder, current_branch->next_block);
3402 LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
3403 set_basicblock_name(current_branch->next_block, "endif", label_id);
3408 void ac_build_endloop(struct ac_llvm_context *ctx, int label_id)
3410 struct ac_llvm_flow *current_loop = get_current_flow(ctx);
3412 assert(current_loop->loop_entry_block);
3414 emit_default_branch(ctx->builder, current_loop->loop_entry_block);
3416 LLVMPositionBuilderAtEnd(ctx->builder, current_loop->next_block);
3417 set_basicblock_name(current_loop->next_block, "endloop", label_id);
3421 void ac_build_ifcc(struct ac_llvm_context *ctx, LLVMValueRef cond, int label_id)
3423 struct ac_llvm_flow *flow = push_flow(ctx);
3424 LLVMBasicBlockRef if_block;
3426 if_block = append_basic_block(ctx, "IF");
3427 flow->next_block = append_basic_block(ctx, "ELSE");
3428 set_basicblock_name(if_block, "if", label_id);
3429 LLVMBuildCondBr(ctx->builder, cond, if_block, flow->next_block);
3430 LLVMPositionBuilderAtEnd(ctx->builder, if_block);
3433 void ac_build_if(struct ac_llvm_context *ctx, LLVMValueRef value,
3436 LLVMValueRef cond = LLVMBuildFCmp(ctx->builder, LLVMRealUNE,
3437 value, ctx->f32_0, "");
3438 ac_build_ifcc(ctx, cond, label_id);
3441 void ac_build_uif(struct ac_llvm_context *ctx, LLVMValueRef value,
3444 LLVMValueRef cond = LLVMBuildICmp(ctx->builder, LLVMIntNE,
3445 ac_to_integer(ctx, value),
3447 ac_build_ifcc(ctx, cond, label_id);
3450 LLVMValueRef ac_build_alloca_undef(struct ac_llvm_context *ac, LLVMTypeRef type,
3453 LLVMBuilderRef builder = ac->builder;
3454 LLVMBasicBlockRef current_block = LLVMGetInsertBlock(builder);
3455 LLVMValueRef function = LLVMGetBasicBlockParent(current_block);
3456 LLVMBasicBlockRef first_block = LLVMGetEntryBasicBlock(function);
3457 LLVMValueRef first_instr = LLVMGetFirstInstruction(first_block);
3458 LLVMBuilderRef first_builder = LLVMCreateBuilderInContext(ac->context);
3462 LLVMPositionBuilderBefore(first_builder, first_instr);
3464 LLVMPositionBuilderAtEnd(first_builder, first_block);
3467 res = LLVMBuildAlloca(first_builder, type, name);
3468 LLVMDisposeBuilder(first_builder);
3472 LLVMValueRef ac_build_alloca(struct ac_llvm_context *ac,
3473 LLVMTypeRef type, const char *name)
3475 LLVMValueRef ptr = ac_build_alloca_undef(ac, type, name);
3476 LLVMBuildStore(ac->builder, LLVMConstNull(type), ptr);
3480 LLVMValueRef ac_cast_ptr(struct ac_llvm_context *ctx, LLVMValueRef ptr,
3483 int addr_space = LLVMGetPointerAddressSpace(LLVMTypeOf(ptr));
3484 return LLVMBuildBitCast(ctx->builder, ptr,
3485 LLVMPointerType(type, addr_space), "");
3488 LLVMValueRef ac_trim_vector(struct ac_llvm_context *ctx, LLVMValueRef value,
3491 unsigned num_components = ac_get_llvm_num_components(value);
3492 if (count == num_components)
3495 LLVMValueRef masks[MAX2(count, 2)];
3496 masks[0] = ctx->i32_0;
3497 masks[1] = ctx->i32_1;
3498 for (unsigned i = 2; i < count; i++)
3499 masks[i] = LLVMConstInt(ctx->i32, i, false);
3502 return LLVMBuildExtractElement(ctx->builder, value, masks[0],
3505 LLVMValueRef swizzle = LLVMConstVector(masks, count);
3506 return LLVMBuildShuffleVector(ctx->builder, value, value, swizzle, "");
3509 LLVMValueRef ac_unpack_param(struct ac_llvm_context *ctx, LLVMValueRef param,
3510 unsigned rshift, unsigned bitwidth)
3512 LLVMValueRef value = param;
3514 value = LLVMBuildLShr(ctx->builder, value,
3515 LLVMConstInt(ctx->i32, rshift, false), "");
3517 if (rshift + bitwidth < 32) {
3518 unsigned mask = (1 << bitwidth) - 1;
3519 value = LLVMBuildAnd(ctx->builder, value,
3520 LLVMConstInt(ctx->i32, mask, false), "");
3525 /* Adjust the sample index according to FMASK.
3527 * For uncompressed MSAA surfaces, FMASK should return 0x76543210,
3528 * which is the identity mapping. Each nibble says which physical sample
3529 * should be fetched to get that sample.
3531 * For example, 0x11111100 means there are only 2 samples stored and
3532 * the second sample covers 3/4 of the pixel. When reading samples 0
3533 * and 1, return physical sample 0 (determined by the first two 0s
3534 * in FMASK), otherwise return physical sample 1.
3536 * The sample index should be adjusted as follows:
3537 * addr[sample_index] = (fmask >> (addr[sample_index] * 4)) & 0xF;
3539 void ac_apply_fmask_to_sample(struct ac_llvm_context *ac, LLVMValueRef fmask,
3540 LLVMValueRef *addr, bool is_array_tex)
3542 struct ac_image_args fmask_load = {};
3543 fmask_load.opcode = ac_image_load;
3544 fmask_load.resource = fmask;
3545 fmask_load.dmask = 0xf;
3546 fmask_load.dim = is_array_tex ? ac_image_2darray : ac_image_2d;
3547 fmask_load.attributes = AC_FUNC_ATTR_READNONE;
3549 fmask_load.coords[0] = addr[0];
3550 fmask_load.coords[1] = addr[1];
3552 fmask_load.coords[2] = addr[2];
3554 LLVMValueRef fmask_value = ac_build_image_opcode(ac, &fmask_load);
3555 fmask_value = LLVMBuildExtractElement(ac->builder, fmask_value,
3558 /* Apply the formula. */
3559 unsigned sample_chan = is_array_tex ? 3 : 2;
3560 LLVMValueRef final_sample;
3561 final_sample = LLVMBuildMul(ac->builder, addr[sample_chan],
3562 LLVMConstInt(ac->i32, 4, 0), "");
3563 final_sample = LLVMBuildLShr(ac->builder, fmask_value, final_sample, "");
3564 /* Mask the sample index by 0x7, because 0x8 means an unknown value
3565 * with EQAA, so those will map to 0. */
3566 final_sample = LLVMBuildAnd(ac->builder, final_sample,
3567 LLVMConstInt(ac->i32, 0x7, 0), "");
3569 /* Don't rewrite the sample index if WORD1.DATA_FORMAT of the FMASK
3570 * resource descriptor is 0 (invalid).
3573 tmp = LLVMBuildBitCast(ac->builder, fmask, ac->v8i32, "");
3574 tmp = LLVMBuildExtractElement(ac->builder, tmp, ac->i32_1, "");
3575 tmp = LLVMBuildICmp(ac->builder, LLVMIntNE, tmp, ac->i32_0, "");
3577 /* Replace the MSAA sample index. */
3578 addr[sample_chan] = LLVMBuildSelect(ac->builder, tmp, final_sample,
3579 addr[sample_chan], "");
3583 _ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef lane)
3585 ac_build_optimization_barrier(ctx, &src);
3586 return ac_build_intrinsic(ctx,
3587 lane == NULL ? "llvm.amdgcn.readfirstlane" : "llvm.amdgcn.readlane",
3588 LLVMTypeOf(src), (LLVMValueRef []) {
3590 lane == NULL ? 1 : 2,
3591 AC_FUNC_ATTR_READNONE |
3592 AC_FUNC_ATTR_CONVERGENT);
3596 * Builds the "llvm.amdgcn.readlane" or "llvm.amdgcn.readfirstlane" intrinsic.
3599 * @param lane - id of the lane or NULL for the first active lane
3600 * @return value of the lane
3603 ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef lane)
3605 LLVMTypeRef src_type = LLVMTypeOf(src);
3606 src = ac_to_integer(ctx, src);
3607 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
3611 ret = _ac_build_readlane(ctx, src, lane);
3613 assert(bits % 32 == 0);
3614 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
3615 LLVMValueRef src_vector =
3616 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
3617 ret = LLVMGetUndef(vec_type);
3618 for (unsigned i = 0; i < bits / 32; i++) {
3619 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3620 LLVMConstInt(ctx->i32, i, 0), "");
3621 LLVMValueRef ret_comp = _ac_build_readlane(ctx, src, lane);
3622 ret = LLVMBuildInsertElement(ctx->builder, ret, ret_comp,
3623 LLVMConstInt(ctx->i32, i, 0), "");
3626 if (LLVMGetTypeKind(src_type) == LLVMPointerTypeKind)
3627 return LLVMBuildIntToPtr(ctx->builder, ret, src_type, "");
3628 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3632 ac_build_writelane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef value, LLVMValueRef lane)
3634 return ac_build_intrinsic(ctx, "llvm.amdgcn.writelane", ctx->i32,
3635 (LLVMValueRef []) {value, lane, src}, 3,
3636 AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
3640 ac_build_mbcnt(struct ac_llvm_context *ctx, LLVMValueRef mask)
3642 if (ctx->wave_size == 32) {
3643 return ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.lo", ctx->i32,
3644 (LLVMValueRef []) { mask, ctx->i32_0 },
3645 2, AC_FUNC_ATTR_READNONE);
3647 LLVMValueRef mask_vec = LLVMBuildBitCast(ctx->builder, mask,
3648 LLVMVectorType(ctx->i32, 2),
3650 LLVMValueRef mask_lo = LLVMBuildExtractElement(ctx->builder, mask_vec,
3652 LLVMValueRef mask_hi = LLVMBuildExtractElement(ctx->builder, mask_vec,
3655 ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.lo", ctx->i32,
3656 (LLVMValueRef []) { mask_lo, ctx->i32_0 },
3657 2, AC_FUNC_ATTR_READNONE);
3658 val = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi", ctx->i32,
3659 (LLVMValueRef []) { mask_hi, val },
3660 2, AC_FUNC_ATTR_READNONE);
3665 _dpp_quad_perm = 0x000,
3666 _dpp_row_sl = 0x100,
3667 _dpp_row_sr = 0x110,
3668 _dpp_row_rr = 0x120,
3673 dpp_row_mirror = 0x140,
3674 dpp_row_half_mirror = 0x141,
3675 dpp_row_bcast15 = 0x142,
3676 dpp_row_bcast31 = 0x143
3679 static inline enum dpp_ctrl
3680 dpp_quad_perm(unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
3682 assert(lane0 < 4 && lane1 < 4 && lane2 < 4 && lane3 < 4);
3683 return _dpp_quad_perm | lane0 | (lane1 << 2) | (lane2 << 4) | (lane3 << 6);
3686 static inline enum dpp_ctrl
3687 dpp_row_sl(unsigned amount)
3689 assert(amount > 0 && amount < 16);
3690 return _dpp_row_sl | amount;
3693 static inline enum dpp_ctrl
3694 dpp_row_sr(unsigned amount)
3696 assert(amount > 0 && amount < 16);
3697 return _dpp_row_sr | amount;
3701 _ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
3702 enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
3705 return ac_build_intrinsic(ctx, "llvm.amdgcn.update.dpp.i32",
3709 LLVMConstInt(ctx->i32, dpp_ctrl, 0),
3710 LLVMConstInt(ctx->i32, row_mask, 0),
3711 LLVMConstInt(ctx->i32, bank_mask, 0),
3712 LLVMConstInt(ctx->i1, bound_ctrl, 0) },
3713 6, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
3717 ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
3718 enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
3721 LLVMTypeRef src_type = LLVMTypeOf(src);
3722 src = ac_to_integer(ctx, src);
3723 old = ac_to_integer(ctx, old);
3724 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
3727 ret = _ac_build_dpp(ctx, old, src, dpp_ctrl, row_mask,
3728 bank_mask, bound_ctrl);
3730 assert(bits % 32 == 0);
3731 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
3732 LLVMValueRef src_vector =
3733 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
3734 LLVMValueRef old_vector =
3735 LLVMBuildBitCast(ctx->builder, old, vec_type, "");
3736 ret = LLVMGetUndef(vec_type);
3737 for (unsigned i = 0; i < bits / 32; i++) {
3738 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3739 LLVMConstInt(ctx->i32, i,
3741 old = LLVMBuildExtractElement(ctx->builder, old_vector,
3742 LLVMConstInt(ctx->i32, i,
3744 LLVMValueRef ret_comp = _ac_build_dpp(ctx, old, src,
3749 ret = LLVMBuildInsertElement(ctx->builder, ret,
3751 LLVMConstInt(ctx->i32, i,
3755 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3759 _ac_build_permlane16(struct ac_llvm_context *ctx, LLVMValueRef src, uint64_t sel,
3760 bool exchange_rows, bool bound_ctrl)
3762 LLVMValueRef args[6] = {
3765 LLVMConstInt(ctx->i32, sel, false),
3766 LLVMConstInt(ctx->i32, sel >> 32, false),
3767 ctx->i1true, /* fi */
3768 bound_ctrl ? ctx->i1true : ctx->i1false,
3770 return ac_build_intrinsic(ctx, exchange_rows ? "llvm.amdgcn.permlanex16"
3771 : "llvm.amdgcn.permlane16",
3773 AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
3777 ac_build_permlane16(struct ac_llvm_context *ctx, LLVMValueRef src, uint64_t sel,
3778 bool exchange_rows, bool bound_ctrl)
3780 LLVMTypeRef src_type = LLVMTypeOf(src);
3781 src = ac_to_integer(ctx, src);
3782 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
3785 ret = _ac_build_permlane16(ctx, src, sel, exchange_rows,
3788 assert(bits % 32 == 0);
3789 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
3790 LLVMValueRef src_vector =
3791 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
3792 ret = LLVMGetUndef(vec_type);
3793 for (unsigned i = 0; i < bits / 32; i++) {
3794 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3795 LLVMConstInt(ctx->i32, i,
3797 LLVMValueRef ret_comp =
3798 _ac_build_permlane16(ctx, src, sel,
3801 ret = LLVMBuildInsertElement(ctx->builder, ret,
3803 LLVMConstInt(ctx->i32, i,
3807 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3810 static inline unsigned
3811 ds_pattern_bitmode(unsigned and_mask, unsigned or_mask, unsigned xor_mask)
3813 assert(and_mask < 32 && or_mask < 32 && xor_mask < 32);
3814 return and_mask | (or_mask << 5) | (xor_mask << 10);
3818 _ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
3820 return ac_build_intrinsic(ctx, "llvm.amdgcn.ds.swizzle",
3821 LLVMTypeOf(src), (LLVMValueRef []) {
3822 src, LLVMConstInt(ctx->i32, mask, 0) },
3823 2, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
3827 ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
3829 LLVMTypeRef src_type = LLVMTypeOf(src);
3830 src = ac_to_integer(ctx, src);
3831 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
3834 ret = _ac_build_ds_swizzle(ctx, src, mask);
3836 assert(bits % 32 == 0);
3837 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
3838 LLVMValueRef src_vector =
3839 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
3840 ret = LLVMGetUndef(vec_type);
3841 for (unsigned i = 0; i < bits / 32; i++) {
3842 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3843 LLVMConstInt(ctx->i32, i,
3845 LLVMValueRef ret_comp = _ac_build_ds_swizzle(ctx, src,
3847 ret = LLVMBuildInsertElement(ctx->builder, ret,
3849 LLVMConstInt(ctx->i32, i,
3853 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3857 ac_build_wwm(struct ac_llvm_context *ctx, LLVMValueRef src)
3859 char name[32], type[8];
3860 ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
3861 snprintf(name, sizeof(name), "llvm.amdgcn.wwm.%s", type);
3862 return ac_build_intrinsic(ctx, name, LLVMTypeOf(src),
3863 (LLVMValueRef []) { src }, 1,
3864 AC_FUNC_ATTR_READNONE);
3868 ac_build_set_inactive(struct ac_llvm_context *ctx, LLVMValueRef src,
3869 LLVMValueRef inactive)
3871 char name[33], type[8];
3872 LLVMTypeRef src_type = LLVMTypeOf(src);
3873 src = ac_to_integer(ctx, src);
3874 inactive = ac_to_integer(ctx, inactive);
3875 ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
3876 snprintf(name, sizeof(name), "llvm.amdgcn.set.inactive.%s", type);
3878 ac_build_intrinsic(ctx, name,
3879 LLVMTypeOf(src), (LLVMValueRef []) {
3881 AC_FUNC_ATTR_READNONE |
3882 AC_FUNC_ATTR_CONVERGENT);
3883 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3887 get_reduction_identity(struct ac_llvm_context *ctx, nir_op op, unsigned type_size)
3889 if (type_size == 4) {
3891 case nir_op_iadd: return ctx->i32_0;
3892 case nir_op_fadd: return ctx->f32_0;
3893 case nir_op_imul: return ctx->i32_1;
3894 case nir_op_fmul: return ctx->f32_1;
3895 case nir_op_imin: return LLVMConstInt(ctx->i32, INT32_MAX, 0);
3896 case nir_op_umin: return LLVMConstInt(ctx->i32, UINT32_MAX, 0);
3897 case nir_op_fmin: return LLVMConstReal(ctx->f32, INFINITY);
3898 case nir_op_imax: return LLVMConstInt(ctx->i32, INT32_MIN, 0);
3899 case nir_op_umax: return ctx->i32_0;
3900 case nir_op_fmax: return LLVMConstReal(ctx->f32, -INFINITY);
3901 case nir_op_iand: return LLVMConstInt(ctx->i32, -1, 0);
3902 case nir_op_ior: return ctx->i32_0;
3903 case nir_op_ixor: return ctx->i32_0;
3905 unreachable("bad reduction intrinsic");
3907 } else { /* type_size == 64bit */
3909 case nir_op_iadd: return ctx->i64_0;
3910 case nir_op_fadd: return ctx->f64_0;
3911 case nir_op_imul: return ctx->i64_1;
3912 case nir_op_fmul: return ctx->f64_1;
3913 case nir_op_imin: return LLVMConstInt(ctx->i64, INT64_MAX, 0);
3914 case nir_op_umin: return LLVMConstInt(ctx->i64, UINT64_MAX, 0);
3915 case nir_op_fmin: return LLVMConstReal(ctx->f64, INFINITY);
3916 case nir_op_imax: return LLVMConstInt(ctx->i64, INT64_MIN, 0);
3917 case nir_op_umax: return ctx->i64_0;
3918 case nir_op_fmax: return LLVMConstReal(ctx->f64, -INFINITY);
3919 case nir_op_iand: return LLVMConstInt(ctx->i64, -1, 0);
3920 case nir_op_ior: return ctx->i64_0;
3921 case nir_op_ixor: return ctx->i64_0;
3923 unreachable("bad reduction intrinsic");
3929 ac_build_alu_op(struct ac_llvm_context *ctx, LLVMValueRef lhs, LLVMValueRef rhs, nir_op op)
3931 bool _64bit = ac_get_type_size(LLVMTypeOf(lhs)) == 8;
3933 case nir_op_iadd: return LLVMBuildAdd(ctx->builder, lhs, rhs, "");
3934 case nir_op_fadd: return LLVMBuildFAdd(ctx->builder, lhs, rhs, "");
3935 case nir_op_imul: return LLVMBuildMul(ctx->builder, lhs, rhs, "");
3936 case nir_op_fmul: return LLVMBuildFMul(ctx->builder, lhs, rhs, "");
3937 case nir_op_imin: return LLVMBuildSelect(ctx->builder,
3938 LLVMBuildICmp(ctx->builder, LLVMIntSLT, lhs, rhs, ""),
3940 case nir_op_umin: return LLVMBuildSelect(ctx->builder,
3941 LLVMBuildICmp(ctx->builder, LLVMIntULT, lhs, rhs, ""),
3943 case nir_op_fmin: return ac_build_intrinsic(ctx,
3944 _64bit ? "llvm.minnum.f64" : "llvm.minnum.f32",
3945 _64bit ? ctx->f64 : ctx->f32,
3946 (LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
3947 case nir_op_imax: return LLVMBuildSelect(ctx->builder,
3948 LLVMBuildICmp(ctx->builder, LLVMIntSGT, lhs, rhs, ""),
3950 case nir_op_umax: return LLVMBuildSelect(ctx->builder,
3951 LLVMBuildICmp(ctx->builder, LLVMIntUGT, lhs, rhs, ""),
3953 case nir_op_fmax: return ac_build_intrinsic(ctx,
3954 _64bit ? "llvm.maxnum.f64" : "llvm.maxnum.f32",
3955 _64bit ? ctx->f64 : ctx->f32,
3956 (LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
3957 case nir_op_iand: return LLVMBuildAnd(ctx->builder, lhs, rhs, "");
3958 case nir_op_ior: return LLVMBuildOr(ctx->builder, lhs, rhs, "");
3959 case nir_op_ixor: return LLVMBuildXor(ctx->builder, lhs, rhs, "");
3961 unreachable("bad reduction intrinsic");
3966 * \param maxprefix specifies that the result only needs to be correct for a
3967 * prefix of this many threads
3969 * TODO: add inclusive and excluse scan functions for GFX6.
3972 ac_build_scan(struct ac_llvm_context *ctx, nir_op op, LLVMValueRef src, LLVMValueRef identity,
3973 unsigned maxprefix, bool inclusive)
3975 LLVMValueRef result, tmp;
3979 } else if (ctx->chip_class >= GFX10) {
3980 /* wavefront shift_right by 1 on GFX10 (emulate dpp_wf_sr1) */
3981 LLVMValueRef active, tmp1, tmp2;
3982 LLVMValueRef tid = ac_get_thread_id(ctx);
3984 tmp1 = ac_build_dpp(ctx, identity, src, dpp_row_sr(1), 0xf, 0xf, false);
3986 tmp2 = ac_build_permlane16(ctx, src, (uint64_t)~0, true, false);
3988 if (maxprefix > 32) {
3989 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ, tid,
3990 LLVMConstInt(ctx->i32, 32, false), "");
3992 tmp2 = LLVMBuildSelect(ctx->builder, active,
3993 ac_build_readlane(ctx, src,
3994 LLVMConstInt(ctx->i32, 31, false)),
3997 active = LLVMBuildOr(ctx->builder, active,
3998 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
3999 LLVMBuildAnd(ctx->builder, tid,
4000 LLVMConstInt(ctx->i32, 0x1f, false), ""),
4001 LLVMConstInt(ctx->i32, 0x10, false), ""), "");
4002 src = LLVMBuildSelect(ctx->builder, active, tmp2, tmp1, "");
4003 } else if (maxprefix > 16) {
4004 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ, tid,
4005 LLVMConstInt(ctx->i32, 16, false), "");
4007 src = LLVMBuildSelect(ctx->builder, active, tmp2, tmp1, "");
4011 } else if (ctx->chip_class >= GFX8) {
4012 src = ac_build_dpp(ctx, identity, src, dpp_wf_sr1, 0xf, 0xf, false);
4016 src = ac_build_dpp(ctx, identity, src, dpp_wf_sr1, 0xf, 0xf, false);
4021 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(1), 0xf, 0xf, false);
4022 result = ac_build_alu_op(ctx, result, tmp, op);
4025 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(2), 0xf, 0xf, false);
4026 result = ac_build_alu_op(ctx, result, tmp, op);
4029 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(3), 0xf, 0xf, false);
4030 result = ac_build_alu_op(ctx, result, tmp, op);
4033 tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(4), 0xf, 0xe, false);
4034 result = ac_build_alu_op(ctx, result, tmp, op);
4037 tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(8), 0xf, 0xc, false);
4038 result = ac_build_alu_op(ctx, result, tmp, op);
4039 if (maxprefix <= 16)
4042 if (ctx->chip_class >= GFX10) {
4043 LLVMValueRef tid = ac_get_thread_id(ctx);
4044 LLVMValueRef active;
4046 tmp = ac_build_permlane16(ctx, result, ~(uint64_t)0, true, false);
4048 active = LLVMBuildICmp(ctx->builder, LLVMIntNE,
4049 LLVMBuildAnd(ctx->builder, tid,
4050 LLVMConstInt(ctx->i32, 16, false), ""),
4053 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4055 result = ac_build_alu_op(ctx, result, tmp, op);
4057 if (maxprefix <= 32)
4060 tmp = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 31, false));
4062 active = LLVMBuildICmp(ctx->builder, LLVMIntUGE, tid,
4063 LLVMConstInt(ctx->i32, 32, false), "");
4065 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4067 result = ac_build_alu_op(ctx, result, tmp, op);
4071 tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
4072 result = ac_build_alu_op(ctx, result, tmp, op);
4073 if (maxprefix <= 32)
4075 tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
4076 result = ac_build_alu_op(ctx, result, tmp, op);
4081 ac_build_inclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
4083 LLVMValueRef result;
4085 if (LLVMTypeOf(src) == ctx->i1 && op == nir_op_iadd) {
4086 LLVMBuilderRef builder = ctx->builder;
4087 src = LLVMBuildZExt(builder, src, ctx->i32, "");
4088 result = ac_build_ballot(ctx, src);
4089 result = ac_build_mbcnt(ctx, result);
4090 result = LLVMBuildAdd(builder, result, src, "");
4094 ac_build_optimization_barrier(ctx, &src);
4096 LLVMValueRef identity =
4097 get_reduction_identity(ctx, op, ac_get_type_size(LLVMTypeOf(src)));
4098 result = LLVMBuildBitCast(ctx->builder, ac_build_set_inactive(ctx, src, identity),
4099 LLVMTypeOf(identity), "");
4100 result = ac_build_scan(ctx, op, result, identity, ctx->wave_size, true);
4102 return ac_build_wwm(ctx, result);
4106 ac_build_exclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
4108 LLVMValueRef result;
4110 if (LLVMTypeOf(src) == ctx->i1 && op == nir_op_iadd) {
4111 LLVMBuilderRef builder = ctx->builder;
4112 src = LLVMBuildZExt(builder, src, ctx->i32, "");
4113 result = ac_build_ballot(ctx, src);
4114 result = ac_build_mbcnt(ctx, result);
4118 ac_build_optimization_barrier(ctx, &src);
4120 LLVMValueRef identity =
4121 get_reduction_identity(ctx, op, ac_get_type_size(LLVMTypeOf(src)));
4122 result = LLVMBuildBitCast(ctx->builder, ac_build_set_inactive(ctx, src, identity),
4123 LLVMTypeOf(identity), "");
4124 result = ac_build_scan(ctx, op, result, identity, ctx->wave_size, false);
4126 return ac_build_wwm(ctx, result);
4130 ac_build_reduce(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op, unsigned cluster_size)
4132 if (cluster_size == 1) return src;
4133 ac_build_optimization_barrier(ctx, &src);
4134 LLVMValueRef result, swap;
4135 LLVMValueRef identity = get_reduction_identity(ctx, op,
4136 ac_get_type_size(LLVMTypeOf(src)));
4137 result = LLVMBuildBitCast(ctx->builder,
4138 ac_build_set_inactive(ctx, src, identity),
4139 LLVMTypeOf(identity), "");
4140 swap = ac_build_quad_swizzle(ctx, result, 1, 0, 3, 2);
4141 result = ac_build_alu_op(ctx, result, swap, op);
4142 if (cluster_size == 2) return ac_build_wwm(ctx, result);
4144 swap = ac_build_quad_swizzle(ctx, result, 2, 3, 0, 1);
4145 result = ac_build_alu_op(ctx, result, swap, op);
4146 if (cluster_size == 4) return ac_build_wwm(ctx, result);
4148 if (ctx->chip_class >= GFX8)
4149 swap = ac_build_dpp(ctx, identity, result, dpp_row_half_mirror, 0xf, 0xf, false);
4151 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x04));
4152 result = ac_build_alu_op(ctx, result, swap, op);
4153 if (cluster_size == 8) return ac_build_wwm(ctx, result);
4155 if (ctx->chip_class >= GFX8)
4156 swap = ac_build_dpp(ctx, identity, result, dpp_row_mirror, 0xf, 0xf, false);
4158 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x08));
4159 result = ac_build_alu_op(ctx, result, swap, op);
4160 if (cluster_size == 16) return ac_build_wwm(ctx, result);
4162 if (ctx->chip_class >= GFX10)
4163 swap = ac_build_permlane16(ctx, result, 0, true, false);
4164 else if (ctx->chip_class >= GFX8 && cluster_size != 32)
4165 swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
4167 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x10));
4168 result = ac_build_alu_op(ctx, result, swap, op);
4169 if (cluster_size == 32) return ac_build_wwm(ctx, result);
4171 if (ctx->chip_class >= GFX8) {
4172 if (ctx->chip_class >= GFX10)
4173 swap = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 31, false));
4175 swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
4176 result = ac_build_alu_op(ctx, result, swap, op);
4177 result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 63, 0));
4178 return ac_build_wwm(ctx, result);
4180 swap = ac_build_readlane(ctx, result, ctx->i32_0);
4181 result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 32, 0));
4182 result = ac_build_alu_op(ctx, result, swap, op);
4183 return ac_build_wwm(ctx, result);
4188 * "Top half" of a scan that reduces per-wave values across an entire
4191 * The source value must be present in the highest lane of the wave, and the
4192 * highest lane must be live.
4195 ac_build_wg_wavescan_top(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4197 if (ws->maxwaves <= 1)
4200 const LLVMValueRef last_lane = LLVMConstInt(ctx->i32, ctx->wave_size - 1, false);
4201 LLVMBuilderRef builder = ctx->builder;
4202 LLVMValueRef tid = ac_get_thread_id(ctx);
4205 tmp = LLVMBuildICmp(builder, LLVMIntEQ, tid, last_lane, "");
4206 ac_build_ifcc(ctx, tmp, 1000);
4207 LLVMBuildStore(builder, ws->src, LLVMBuildGEP(builder, ws->scratch, &ws->waveidx, 1, ""));
4208 ac_build_endif(ctx, 1000);
4212 * "Bottom half" of a scan that reduces per-wave values across an entire
4215 * The caller must place a barrier between the top and bottom halves.
4218 ac_build_wg_wavescan_bottom(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4220 const LLVMTypeRef type = LLVMTypeOf(ws->src);
4221 const LLVMValueRef identity =
4222 get_reduction_identity(ctx, ws->op, ac_get_type_size(type));
4224 if (ws->maxwaves <= 1) {
4225 ws->result_reduce = ws->src;
4226 ws->result_inclusive = ws->src;
4227 ws->result_exclusive = identity;
4230 assert(ws->maxwaves <= 32);
4232 LLVMBuilderRef builder = ctx->builder;
4233 LLVMValueRef tid = ac_get_thread_id(ctx);
4234 LLVMBasicBlockRef bbs[2];
4235 LLVMValueRef phivalues_scan[2];
4236 LLVMValueRef tmp, tmp2;
4238 bbs[0] = LLVMGetInsertBlock(builder);
4239 phivalues_scan[0] = LLVMGetUndef(type);
4241 if (ws->enable_reduce)
4242 tmp = LLVMBuildICmp(builder, LLVMIntULT, tid, ws->numwaves, "");
4243 else if (ws->enable_inclusive)
4244 tmp = LLVMBuildICmp(builder, LLVMIntULE, tid, ws->waveidx, "");
4246 tmp = LLVMBuildICmp(builder, LLVMIntULT, tid, ws->waveidx, "");
4247 ac_build_ifcc(ctx, tmp, 1001);
4249 tmp = LLVMBuildLoad(builder, LLVMBuildGEP(builder, ws->scratch, &tid, 1, ""), "");
4251 ac_build_optimization_barrier(ctx, &tmp);
4253 bbs[1] = LLVMGetInsertBlock(builder);
4254 phivalues_scan[1] = ac_build_scan(ctx, ws->op, tmp, identity, ws->maxwaves, true);
4256 ac_build_endif(ctx, 1001);
4258 const LLVMValueRef scan = ac_build_phi(ctx, type, 2, phivalues_scan, bbs);
4260 if (ws->enable_reduce) {
4261 tmp = LLVMBuildSub(builder, ws->numwaves, ctx->i32_1, "");
4262 ws->result_reduce = ac_build_readlane(ctx, scan, tmp);
4264 if (ws->enable_inclusive)
4265 ws->result_inclusive = ac_build_readlane(ctx, scan, ws->waveidx);
4266 if (ws->enable_exclusive) {
4267 tmp = LLVMBuildSub(builder, ws->waveidx, ctx->i32_1, "");
4268 tmp = ac_build_readlane(ctx, scan, tmp);
4269 tmp2 = LLVMBuildICmp(builder, LLVMIntEQ, ws->waveidx, ctx->i32_0, "");
4270 ws->result_exclusive = LLVMBuildSelect(builder, tmp2, identity, tmp, "");
4275 * Inclusive scan of a per-wave value across an entire workgroup.
4277 * This implies an s_barrier instruction.
4279 * Unlike ac_build_inclusive_scan, the caller \em must ensure that all threads
4280 * of the workgroup are live. (This requirement cannot easily be relaxed in a
4281 * useful manner because of the barrier in the algorithm.)
4284 ac_build_wg_wavescan(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4286 ac_build_wg_wavescan_top(ctx, ws);
4287 ac_build_s_barrier(ctx);
4288 ac_build_wg_wavescan_bottom(ctx, ws);
4292 * "Top half" of a scan that reduces per-thread values across an entire
4295 * All lanes must be active when this code runs.
4298 ac_build_wg_scan_top(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4300 if (ws->enable_exclusive) {
4301 ws->extra = ac_build_exclusive_scan(ctx, ws->src, ws->op);
4302 if (LLVMTypeOf(ws->src) == ctx->i1 && ws->op == nir_op_iadd)
4303 ws->src = LLVMBuildZExt(ctx->builder, ws->src, ctx->i32, "");
4304 ws->src = ac_build_alu_op(ctx, ws->extra, ws->src, ws->op);
4306 ws->src = ac_build_inclusive_scan(ctx, ws->src, ws->op);
4309 bool enable_inclusive = ws->enable_inclusive;
4310 bool enable_exclusive = ws->enable_exclusive;
4311 ws->enable_inclusive = false;
4312 ws->enable_exclusive = ws->enable_exclusive || enable_inclusive;
4313 ac_build_wg_wavescan_top(ctx, ws);
4314 ws->enable_inclusive = enable_inclusive;
4315 ws->enable_exclusive = enable_exclusive;
4319 * "Bottom half" of a scan that reduces per-thread values across an entire
4322 * The caller must place a barrier between the top and bottom halves.
4325 ac_build_wg_scan_bottom(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4327 bool enable_inclusive = ws->enable_inclusive;
4328 bool enable_exclusive = ws->enable_exclusive;
4329 ws->enable_inclusive = false;
4330 ws->enable_exclusive = ws->enable_exclusive || enable_inclusive;
4331 ac_build_wg_wavescan_bottom(ctx, ws);
4332 ws->enable_inclusive = enable_inclusive;
4333 ws->enable_exclusive = enable_exclusive;
4335 /* ws->result_reduce is already the correct value */
4336 if (ws->enable_inclusive)
4337 ws->result_inclusive = ac_build_alu_op(ctx, ws->result_inclusive, ws->src, ws->op);
4338 if (ws->enable_exclusive)
4339 ws->result_exclusive = ac_build_alu_op(ctx, ws->result_exclusive, ws->extra, ws->op);
4343 * A scan that reduces per-thread values across an entire workgroup.
4345 * The caller must ensure that all lanes are active when this code runs
4346 * (WWM is insufficient!), because there is an implied barrier.
4349 ac_build_wg_scan(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4351 ac_build_wg_scan_top(ctx, ws);
4352 ac_build_s_barrier(ctx);
4353 ac_build_wg_scan_bottom(ctx, ws);
4357 ac_build_quad_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src,
4358 unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
4360 unsigned mask = dpp_quad_perm(lane0, lane1, lane2, lane3);
4361 if (ctx->chip_class >= GFX8) {
4362 return ac_build_dpp(ctx, src, src, mask, 0xf, 0xf, false);
4364 return ac_build_ds_swizzle(ctx, src, (1 << 15) | mask);
4369 ac_build_shuffle(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef index)
4371 index = LLVMBuildMul(ctx->builder, index, LLVMConstInt(ctx->i32, 4, 0), "");
4372 return ac_build_intrinsic(ctx,
4373 "llvm.amdgcn.ds.bpermute", ctx->i32,
4374 (LLVMValueRef []) {index, src}, 2,
4375 AC_FUNC_ATTR_READNONE |
4376 AC_FUNC_ATTR_CONVERGENT);
4380 ac_build_frexp_exp(struct ac_llvm_context *ctx, LLVMValueRef src0,
4386 if (bitsize == 16) {
4387 intr = "llvm.amdgcn.frexp.exp.i16.f16";
4389 } else if (bitsize == 32) {
4390 intr = "llvm.amdgcn.frexp.exp.i32.f32";
4393 intr = "llvm.amdgcn.frexp.exp.i32.f64";
4397 LLVMValueRef params[] = {
4400 return ac_build_intrinsic(ctx, intr, type, params, 1,
4401 AC_FUNC_ATTR_READNONE);
4404 ac_build_frexp_mant(struct ac_llvm_context *ctx, LLVMValueRef src0,
4410 if (bitsize == 16) {
4411 intr = "llvm.amdgcn.frexp.mant.f16";
4413 } else if (bitsize == 32) {
4414 intr = "llvm.amdgcn.frexp.mant.f32";
4417 intr = "llvm.amdgcn.frexp.mant.f64";
4421 LLVMValueRef params[] = {
4424 return ac_build_intrinsic(ctx, intr, type, params, 1,
4425 AC_FUNC_ATTR_READNONE);
4429 ac_build_canonicalize(struct ac_llvm_context *ctx, LLVMValueRef src0,
4435 if (bitsize == 16) {
4436 intr = "llvm.canonicalize.f16";
4438 } else if (bitsize == 32) {
4439 intr = "llvm.canonicalize.f32";
4441 } else if (bitsize == 64) {
4442 intr = "llvm.canonicalize.f64";
4446 LLVMValueRef params[] = {
4449 return ac_build_intrinsic(ctx, intr, type, params, 1,
4450 AC_FUNC_ATTR_READNONE);
4454 * this takes an I,J coordinate pair,
4455 * and works out the X and Y derivatives.
4456 * it returns DDX(I), DDX(J), DDY(I), DDY(J).
4459 ac_build_ddxy_interp(struct ac_llvm_context *ctx, LLVMValueRef interp_ij)
4461 LLVMValueRef result[4], a;
4464 for (i = 0; i < 2; i++) {
4465 a = LLVMBuildExtractElement(ctx->builder, interp_ij,
4466 LLVMConstInt(ctx->i32, i, false), "");
4467 result[i] = ac_build_ddxy(ctx, AC_TID_MASK_TOP_LEFT, 1, a);
4468 result[2+i] = ac_build_ddxy(ctx, AC_TID_MASK_TOP_LEFT, 2, a);
4470 return ac_build_gather_values(ctx, result, 4);
4474 ac_build_load_helper_invocation(struct ac_llvm_context *ctx)
4476 LLVMValueRef result = ac_build_intrinsic(ctx, "llvm.amdgcn.ps.live",
4478 AC_FUNC_ATTR_READNONE);
4479 result = LLVMBuildNot(ctx->builder, result, "");
4480 return LLVMBuildSExt(ctx->builder, result, ctx->i32, "");
4483 LLVMValueRef ac_build_call(struct ac_llvm_context *ctx, LLVMValueRef func,
4484 LLVMValueRef *args, unsigned num_args)
4486 LLVMValueRef ret = LLVMBuildCall(ctx->builder, func, args, num_args, "");
4487 LLVMSetInstructionCallConv(ret, LLVMGetFunctionCallConv(func));
4492 ac_export_mrt_z(struct ac_llvm_context *ctx, LLVMValueRef depth,
4493 LLVMValueRef stencil, LLVMValueRef samplemask,
4494 struct ac_export_args *args)
4497 unsigned format = ac_get_spi_shader_z_format(depth != NULL,
4499 samplemask != NULL);
4501 assert(depth || stencil || samplemask);
4503 memset(args, 0, sizeof(*args));
4505 args->valid_mask = 1; /* whether the EXEC mask is valid */
4506 args->done = 1; /* DONE bit */
4508 /* Specify the target we are exporting */
4509 args->target = V_008DFC_SQ_EXP_MRTZ;
4511 args->compr = 0; /* COMP flag */
4512 args->out[0] = LLVMGetUndef(ctx->f32); /* R, depth */
4513 args->out[1] = LLVMGetUndef(ctx->f32); /* G, stencil test val[0:7], stencil op val[8:15] */
4514 args->out[2] = LLVMGetUndef(ctx->f32); /* B, sample mask */
4515 args->out[3] = LLVMGetUndef(ctx->f32); /* A, alpha to mask */
4517 if (format == V_028710_SPI_SHADER_UINT16_ABGR) {
4519 args->compr = 1; /* COMPR flag */
4522 /* Stencil should be in X[23:16]. */
4523 stencil = ac_to_integer(ctx, stencil);
4524 stencil = LLVMBuildShl(ctx->builder, stencil,
4525 LLVMConstInt(ctx->i32, 16, 0), "");
4526 args->out[0] = ac_to_float(ctx, stencil);
4530 /* SampleMask should be in Y[15:0]. */
4531 args->out[1] = samplemask;
4536 args->out[0] = depth;
4540 args->out[1] = stencil;
4544 args->out[2] = samplemask;
4549 /* GFX6 (except OLAND and HAINAN) has a bug that it only looks
4550 * at the X writemask component. */
4551 if (ctx->chip_class == GFX6 &&
4552 ctx->family != CHIP_OLAND &&
4553 ctx->family != CHIP_HAINAN)
4556 /* Specify which components to enable */
4557 args->enabled_channels = mask;