ac,radeonsi: use ac_build_fmad
[mesa.git] / src / amd / common / ac_llvm_build.c
1 /*
2 * Copyright 2014 Advanced Micro Devices, Inc.
3 *
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:
11 *
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.
19 *
20 * The above copyright notice and this permission notice (including the
21 * next paragraph) shall be included in all copies or substantial portions
22 * of the Software.
23 *
24 */
25 /* based on pieces from si_pipe.c and radeon_llvm_emit.c */
26 #include "ac_llvm_build.h"
27
28 #include <llvm-c/Core.h>
29
30 #include "c11/threads.h"
31
32 #include <assert.h>
33 #include <stdio.h>
34
35 #include "ac_llvm_util.h"
36 #include "ac_exp_param.h"
37 #include "util/bitscan.h"
38 #include "util/macros.h"
39 #include "util/u_atomic.h"
40 #include "util/u_math.h"
41 #include "sid.h"
42
43 #include "shader_enums.h"
44
45 #define AC_LLVM_INITIAL_CF_DEPTH 4
46
47 /* Data for if/else/endif and bgnloop/endloop control flow structures.
48 */
49 struct ac_llvm_flow {
50 /* Loop exit or next part of if/else/endif. */
51 LLVMBasicBlockRef next_block;
52 LLVMBasicBlockRef loop_entry_block;
53 };
54
55 /* Initialize module-independent parts of the context.
56 *
57 * The caller is responsible for initializing ctx::module and ctx::builder.
58 */
59 void
60 ac_llvm_context_init(struct ac_llvm_context *ctx,
61 enum chip_class chip_class, enum radeon_family family)
62 {
63 LLVMValueRef args[1];
64
65 ctx->context = LLVMContextCreate();
66
67 ctx->chip_class = chip_class;
68 ctx->family = family;
69 ctx->module = NULL;
70 ctx->builder = NULL;
71
72 ctx->voidt = LLVMVoidTypeInContext(ctx->context);
73 ctx->i1 = LLVMInt1TypeInContext(ctx->context);
74 ctx->i8 = LLVMInt8TypeInContext(ctx->context);
75 ctx->i16 = LLVMIntTypeInContext(ctx->context, 16);
76 ctx->i32 = LLVMIntTypeInContext(ctx->context, 32);
77 ctx->i64 = LLVMIntTypeInContext(ctx->context, 64);
78 ctx->intptr = HAVE_32BIT_POINTERS ? ctx->i32 : ctx->i64;
79 ctx->f16 = LLVMHalfTypeInContext(ctx->context);
80 ctx->f32 = LLVMFloatTypeInContext(ctx->context);
81 ctx->f64 = LLVMDoubleTypeInContext(ctx->context);
82 ctx->v2i16 = LLVMVectorType(ctx->i16, 2);
83 ctx->v2i32 = LLVMVectorType(ctx->i32, 2);
84 ctx->v3i32 = LLVMVectorType(ctx->i32, 3);
85 ctx->v4i32 = LLVMVectorType(ctx->i32, 4);
86 ctx->v2f32 = LLVMVectorType(ctx->f32, 2);
87 ctx->v4f32 = LLVMVectorType(ctx->f32, 4);
88 ctx->v8i32 = LLVMVectorType(ctx->i32, 8);
89
90 ctx->i32_0 = LLVMConstInt(ctx->i32, 0, false);
91 ctx->i32_1 = LLVMConstInt(ctx->i32, 1, false);
92 ctx->i64_0 = LLVMConstInt(ctx->i64, 0, false);
93 ctx->i64_1 = LLVMConstInt(ctx->i64, 1, false);
94 ctx->f32_0 = LLVMConstReal(ctx->f32, 0.0);
95 ctx->f32_1 = LLVMConstReal(ctx->f32, 1.0);
96 ctx->f64_0 = LLVMConstReal(ctx->f64, 0.0);
97 ctx->f64_1 = LLVMConstReal(ctx->f64, 1.0);
98
99 ctx->i1false = LLVMConstInt(ctx->i1, 0, false);
100 ctx->i1true = LLVMConstInt(ctx->i1, 1, false);
101
102 ctx->range_md_kind = LLVMGetMDKindIDInContext(ctx->context,
103 "range", 5);
104
105 ctx->invariant_load_md_kind = LLVMGetMDKindIDInContext(ctx->context,
106 "invariant.load", 14);
107
108 ctx->fpmath_md_kind = LLVMGetMDKindIDInContext(ctx->context, "fpmath", 6);
109
110 args[0] = LLVMConstReal(ctx->f32, 2.5);
111 ctx->fpmath_md_2p5_ulp = LLVMMDNodeInContext(ctx->context, args, 1);
112
113 ctx->uniform_md_kind = LLVMGetMDKindIDInContext(ctx->context,
114 "amdgpu.uniform", 14);
115
116 ctx->empty_md = LLVMMDNodeInContext(ctx->context, NULL, 0);
117 }
118
119 void
120 ac_llvm_context_dispose(struct ac_llvm_context *ctx)
121 {
122 free(ctx->flow);
123 ctx->flow = NULL;
124 ctx->flow_depth_max = 0;
125 }
126
127 int
128 ac_get_llvm_num_components(LLVMValueRef value)
129 {
130 LLVMTypeRef type = LLVMTypeOf(value);
131 unsigned num_components = LLVMGetTypeKind(type) == LLVMVectorTypeKind
132 ? LLVMGetVectorSize(type)
133 : 1;
134 return num_components;
135 }
136
137 LLVMValueRef
138 ac_llvm_extract_elem(struct ac_llvm_context *ac,
139 LLVMValueRef value,
140 int index)
141 {
142 if (LLVMGetTypeKind(LLVMTypeOf(value)) != LLVMVectorTypeKind) {
143 assert(index == 0);
144 return value;
145 }
146
147 return LLVMBuildExtractElement(ac->builder, value,
148 LLVMConstInt(ac->i32, index, false), "");
149 }
150
151 int
152 ac_get_elem_bits(struct ac_llvm_context *ctx, LLVMTypeRef type)
153 {
154 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind)
155 type = LLVMGetElementType(type);
156
157 if (LLVMGetTypeKind(type) == LLVMIntegerTypeKind)
158 return LLVMGetIntTypeWidth(type);
159
160 if (type == ctx->f16)
161 return 16;
162 if (type == ctx->f32)
163 return 32;
164 if (type == ctx->f64)
165 return 64;
166
167 unreachable("Unhandled type kind in get_elem_bits");
168 }
169
170 unsigned
171 ac_get_type_size(LLVMTypeRef type)
172 {
173 LLVMTypeKind kind = LLVMGetTypeKind(type);
174
175 switch (kind) {
176 case LLVMIntegerTypeKind:
177 return LLVMGetIntTypeWidth(type) / 8;
178 case LLVMHalfTypeKind:
179 return 2;
180 case LLVMFloatTypeKind:
181 return 4;
182 case LLVMDoubleTypeKind:
183 return 8;
184 case LLVMPointerTypeKind:
185 if (LLVMGetPointerAddressSpace(type) == AC_CONST_32BIT_ADDR_SPACE)
186 return 4;
187 return 8;
188 case LLVMVectorTypeKind:
189 return LLVMGetVectorSize(type) *
190 ac_get_type_size(LLVMGetElementType(type));
191 case LLVMArrayTypeKind:
192 return LLVMGetArrayLength(type) *
193 ac_get_type_size(LLVMGetElementType(type));
194 default:
195 assert(0);
196 return 0;
197 }
198 }
199
200 static LLVMTypeRef to_integer_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
201 {
202 if (t == ctx->f16 || t == ctx->i16)
203 return ctx->i16;
204 else if (t == ctx->f32 || t == ctx->i32)
205 return ctx->i32;
206 else if (t == ctx->f64 || t == ctx->i64)
207 return ctx->i64;
208 else
209 unreachable("Unhandled integer size");
210 }
211
212 LLVMTypeRef
213 ac_to_integer_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
214 {
215 if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
216 LLVMTypeRef elem_type = LLVMGetElementType(t);
217 return LLVMVectorType(to_integer_type_scalar(ctx, elem_type),
218 LLVMGetVectorSize(t));
219 }
220 return to_integer_type_scalar(ctx, t);
221 }
222
223 LLVMValueRef
224 ac_to_integer(struct ac_llvm_context *ctx, LLVMValueRef v)
225 {
226 LLVMTypeRef type = LLVMTypeOf(v);
227 return LLVMBuildBitCast(ctx->builder, v, ac_to_integer_type(ctx, type), "");
228 }
229
230 static LLVMTypeRef to_float_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
231 {
232 if (t == ctx->i16 || t == ctx->f16)
233 return ctx->f16;
234 else if (t == ctx->i32 || t == ctx->f32)
235 return ctx->f32;
236 else if (t == ctx->i64 || t == ctx->f64)
237 return ctx->f64;
238 else
239 unreachable("Unhandled float size");
240 }
241
242 LLVMTypeRef
243 ac_to_float_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
244 {
245 if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
246 LLVMTypeRef elem_type = LLVMGetElementType(t);
247 return LLVMVectorType(to_float_type_scalar(ctx, elem_type),
248 LLVMGetVectorSize(t));
249 }
250 return to_float_type_scalar(ctx, t);
251 }
252
253 LLVMValueRef
254 ac_to_float(struct ac_llvm_context *ctx, LLVMValueRef v)
255 {
256 LLVMTypeRef type = LLVMTypeOf(v);
257 return LLVMBuildBitCast(ctx->builder, v, ac_to_float_type(ctx, type), "");
258 }
259
260
261 LLVMValueRef
262 ac_build_intrinsic(struct ac_llvm_context *ctx, const char *name,
263 LLVMTypeRef return_type, LLVMValueRef *params,
264 unsigned param_count, unsigned attrib_mask)
265 {
266 LLVMValueRef function, call;
267 bool set_callsite_attrs = !(attrib_mask & AC_FUNC_ATTR_LEGACY);
268
269 function = LLVMGetNamedFunction(ctx->module, name);
270 if (!function) {
271 LLVMTypeRef param_types[32], function_type;
272 unsigned i;
273
274 assert(param_count <= 32);
275
276 for (i = 0; i < param_count; ++i) {
277 assert(params[i]);
278 param_types[i] = LLVMTypeOf(params[i]);
279 }
280 function_type =
281 LLVMFunctionType(return_type, param_types, param_count, 0);
282 function = LLVMAddFunction(ctx->module, name, function_type);
283
284 LLVMSetFunctionCallConv(function, LLVMCCallConv);
285 LLVMSetLinkage(function, LLVMExternalLinkage);
286
287 if (!set_callsite_attrs)
288 ac_add_func_attributes(ctx->context, function, attrib_mask);
289 }
290
291 call = LLVMBuildCall(ctx->builder, function, params, param_count, "");
292 if (set_callsite_attrs)
293 ac_add_func_attributes(ctx->context, call, attrib_mask);
294 return call;
295 }
296
297 /**
298 * Given the i32 or vNi32 \p type, generate the textual name (e.g. for use with
299 * intrinsic names).
300 */
301 void ac_build_type_name_for_intr(LLVMTypeRef type, char *buf, unsigned bufsize)
302 {
303 LLVMTypeRef elem_type = type;
304
305 assert(bufsize >= 8);
306
307 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind) {
308 int ret = snprintf(buf, bufsize, "v%u",
309 LLVMGetVectorSize(type));
310 if (ret < 0) {
311 char *type_name = LLVMPrintTypeToString(type);
312 fprintf(stderr, "Error building type name for: %s\n",
313 type_name);
314 return;
315 }
316 elem_type = LLVMGetElementType(type);
317 buf += ret;
318 bufsize -= ret;
319 }
320 switch (LLVMGetTypeKind(elem_type)) {
321 default: break;
322 case LLVMIntegerTypeKind:
323 snprintf(buf, bufsize, "i%d", LLVMGetIntTypeWidth(elem_type));
324 break;
325 case LLVMHalfTypeKind:
326 snprintf(buf, bufsize, "f16");
327 break;
328 case LLVMFloatTypeKind:
329 snprintf(buf, bufsize, "f32");
330 break;
331 case LLVMDoubleTypeKind:
332 snprintf(buf, bufsize, "f64");
333 break;
334 }
335 }
336
337 /**
338 * Helper function that builds an LLVM IR PHI node and immediately adds
339 * incoming edges.
340 */
341 LLVMValueRef
342 ac_build_phi(struct ac_llvm_context *ctx, LLVMTypeRef type,
343 unsigned count_incoming, LLVMValueRef *values,
344 LLVMBasicBlockRef *blocks)
345 {
346 LLVMValueRef phi = LLVMBuildPhi(ctx->builder, type, "");
347 LLVMAddIncoming(phi, values, blocks, count_incoming);
348 return phi;
349 }
350
351 void ac_build_s_barrier(struct ac_llvm_context *ctx)
352 {
353 ac_build_intrinsic(ctx, "llvm.amdgcn.s.barrier", ctx->voidt, NULL,
354 0, AC_FUNC_ATTR_CONVERGENT);
355 }
356
357 /* Prevent optimizations (at least of memory accesses) across the current
358 * point in the program by emitting empty inline assembly that is marked as
359 * having side effects.
360 *
361 * Optionally, a value can be passed through the inline assembly to prevent
362 * LLVM from hoisting calls to ReadNone functions.
363 */
364 void
365 ac_build_optimization_barrier(struct ac_llvm_context *ctx,
366 LLVMValueRef *pvgpr)
367 {
368 static int counter = 0;
369
370 LLVMBuilderRef builder = ctx->builder;
371 char code[16];
372
373 snprintf(code, sizeof(code), "; %d", p_atomic_inc_return(&counter));
374
375 if (!pvgpr) {
376 LLVMTypeRef ftype = LLVMFunctionType(ctx->voidt, NULL, 0, false);
377 LLVMValueRef inlineasm = LLVMConstInlineAsm(ftype, code, "", true, false);
378 LLVMBuildCall(builder, inlineasm, NULL, 0, "");
379 } else {
380 LLVMTypeRef ftype = LLVMFunctionType(ctx->i32, &ctx->i32, 1, false);
381 LLVMValueRef inlineasm = LLVMConstInlineAsm(ftype, code, "=v,0", true, false);
382 LLVMValueRef vgpr = *pvgpr;
383 LLVMTypeRef vgpr_type = LLVMTypeOf(vgpr);
384 unsigned vgpr_size = ac_get_type_size(vgpr_type);
385 LLVMValueRef vgpr0;
386
387 assert(vgpr_size % 4 == 0);
388
389 vgpr = LLVMBuildBitCast(builder, vgpr, LLVMVectorType(ctx->i32, vgpr_size / 4), "");
390 vgpr0 = LLVMBuildExtractElement(builder, vgpr, ctx->i32_0, "");
391 vgpr0 = LLVMBuildCall(builder, inlineasm, &vgpr0, 1, "");
392 vgpr = LLVMBuildInsertElement(builder, vgpr, vgpr0, ctx->i32_0, "");
393 vgpr = LLVMBuildBitCast(builder, vgpr, vgpr_type, "");
394
395 *pvgpr = vgpr;
396 }
397 }
398
399 LLVMValueRef
400 ac_build_shader_clock(struct ac_llvm_context *ctx)
401 {
402 LLVMValueRef tmp = ac_build_intrinsic(ctx, "llvm.readcyclecounter",
403 ctx->i64, NULL, 0, 0);
404 return LLVMBuildBitCast(ctx->builder, tmp, ctx->v2i32, "");
405 }
406
407 LLVMValueRef
408 ac_build_ballot(struct ac_llvm_context *ctx,
409 LLVMValueRef value)
410 {
411 LLVMValueRef args[3] = {
412 value,
413 ctx->i32_0,
414 LLVMConstInt(ctx->i32, LLVMIntNE, 0)
415 };
416
417 /* We currently have no other way to prevent LLVM from lifting the icmp
418 * calls to a dominating basic block.
419 */
420 ac_build_optimization_barrier(ctx, &args[0]);
421
422 args[0] = ac_to_integer(ctx, args[0]);
423
424 return ac_build_intrinsic(ctx,
425 "llvm.amdgcn.icmp.i32",
426 ctx->i64, args, 3,
427 AC_FUNC_ATTR_NOUNWIND |
428 AC_FUNC_ATTR_READNONE |
429 AC_FUNC_ATTR_CONVERGENT);
430 }
431
432 LLVMValueRef
433 ac_build_vote_all(struct ac_llvm_context *ctx, LLVMValueRef value)
434 {
435 LLVMValueRef active_set = ac_build_ballot(ctx, ctx->i32_1);
436 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
437 return LLVMBuildICmp(ctx->builder, LLVMIntEQ, vote_set, active_set, "");
438 }
439
440 LLVMValueRef
441 ac_build_vote_any(struct ac_llvm_context *ctx, LLVMValueRef value)
442 {
443 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
444 return LLVMBuildICmp(ctx->builder, LLVMIntNE, vote_set,
445 LLVMConstInt(ctx->i64, 0, 0), "");
446 }
447
448 LLVMValueRef
449 ac_build_vote_eq(struct ac_llvm_context *ctx, LLVMValueRef value)
450 {
451 LLVMValueRef active_set = ac_build_ballot(ctx, ctx->i32_1);
452 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
453
454 LLVMValueRef all = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
455 vote_set, active_set, "");
456 LLVMValueRef none = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
457 vote_set,
458 LLVMConstInt(ctx->i64, 0, 0), "");
459 return LLVMBuildOr(ctx->builder, all, none, "");
460 }
461
462 LLVMValueRef
463 ac_build_varying_gather_values(struct ac_llvm_context *ctx, LLVMValueRef *values,
464 unsigned value_count, unsigned component)
465 {
466 LLVMValueRef vec = NULL;
467
468 if (value_count == 1) {
469 return values[component];
470 } else if (!value_count)
471 unreachable("value_count is 0");
472
473 for (unsigned i = component; i < value_count + component; i++) {
474 LLVMValueRef value = values[i];
475
476 if (i == component)
477 vec = LLVMGetUndef( LLVMVectorType(LLVMTypeOf(value), value_count));
478 LLVMValueRef index = LLVMConstInt(ctx->i32, i - component, false);
479 vec = LLVMBuildInsertElement(ctx->builder, vec, value, index, "");
480 }
481 return vec;
482 }
483
484 LLVMValueRef
485 ac_build_gather_values_extended(struct ac_llvm_context *ctx,
486 LLVMValueRef *values,
487 unsigned value_count,
488 unsigned value_stride,
489 bool load,
490 bool always_vector)
491 {
492 LLVMBuilderRef builder = ctx->builder;
493 LLVMValueRef vec = NULL;
494 unsigned i;
495
496 if (value_count == 1 && !always_vector) {
497 if (load)
498 return LLVMBuildLoad(builder, values[0], "");
499 return values[0];
500 } else if (!value_count)
501 unreachable("value_count is 0");
502
503 for (i = 0; i < value_count; i++) {
504 LLVMValueRef value = values[i * value_stride];
505 if (load)
506 value = LLVMBuildLoad(builder, value, "");
507
508 if (!i)
509 vec = LLVMGetUndef( LLVMVectorType(LLVMTypeOf(value), value_count));
510 LLVMValueRef index = LLVMConstInt(ctx->i32, i, false);
511 vec = LLVMBuildInsertElement(builder, vec, value, index, "");
512 }
513 return vec;
514 }
515
516 LLVMValueRef
517 ac_build_gather_values(struct ac_llvm_context *ctx,
518 LLVMValueRef *values,
519 unsigned value_count)
520 {
521 return ac_build_gather_values_extended(ctx, values, value_count, 1, false, false);
522 }
523
524 /* Expand a scalar or vector to <4 x type> by filling the remaining channels
525 * with undef. Extract at most num_channels components from the input.
526 */
527 LLVMValueRef ac_build_expand_to_vec4(struct ac_llvm_context *ctx,
528 LLVMValueRef value,
529 unsigned num_channels)
530 {
531 LLVMTypeRef elemtype;
532 LLVMValueRef chan[4];
533
534 if (LLVMGetTypeKind(LLVMTypeOf(value)) == LLVMVectorTypeKind) {
535 unsigned vec_size = LLVMGetVectorSize(LLVMTypeOf(value));
536 num_channels = MIN2(num_channels, vec_size);
537
538 if (num_channels >= 4)
539 return value;
540
541 for (unsigned i = 0; i < num_channels; i++)
542 chan[i] = ac_llvm_extract_elem(ctx, value, i);
543
544 elemtype = LLVMGetElementType(LLVMTypeOf(value));
545 } else {
546 if (num_channels) {
547 assert(num_channels == 1);
548 chan[0] = value;
549 }
550 elemtype = LLVMTypeOf(value);
551 }
552
553 while (num_channels < 4)
554 chan[num_channels++] = LLVMGetUndef(elemtype);
555
556 return ac_build_gather_values(ctx, chan, 4);
557 }
558
559 LLVMValueRef
560 ac_build_fdiv(struct ac_llvm_context *ctx,
561 LLVMValueRef num,
562 LLVMValueRef den)
563 {
564 LLVMValueRef ret = LLVMBuildFDiv(ctx->builder, num, den, "");
565
566 /* Use v_rcp_f32 instead of precise division. */
567 if (!LLVMIsConstant(ret))
568 LLVMSetMetadata(ret, ctx->fpmath_md_kind, ctx->fpmath_md_2p5_ulp);
569 return ret;
570 }
571
572 /* Coordinates for cube map selection. sc, tc, and ma are as in Table 8.27
573 * of the OpenGL 4.5 (Compatibility Profile) specification, except ma is
574 * already multiplied by two. id is the cube face number.
575 */
576 struct cube_selection_coords {
577 LLVMValueRef stc[2];
578 LLVMValueRef ma;
579 LLVMValueRef id;
580 };
581
582 static void
583 build_cube_intrinsic(struct ac_llvm_context *ctx,
584 LLVMValueRef in[3],
585 struct cube_selection_coords *out)
586 {
587 LLVMTypeRef f32 = ctx->f32;
588
589 out->stc[1] = ac_build_intrinsic(ctx, "llvm.amdgcn.cubetc",
590 f32, in, 3, AC_FUNC_ATTR_READNONE);
591 out->stc[0] = ac_build_intrinsic(ctx, "llvm.amdgcn.cubesc",
592 f32, in, 3, AC_FUNC_ATTR_READNONE);
593 out->ma = ac_build_intrinsic(ctx, "llvm.amdgcn.cubema",
594 f32, in, 3, AC_FUNC_ATTR_READNONE);
595 out->id = ac_build_intrinsic(ctx, "llvm.amdgcn.cubeid",
596 f32, in, 3, AC_FUNC_ATTR_READNONE);
597 }
598
599 /**
600 * Build a manual selection sequence for cube face sc/tc coordinates and
601 * major axis vector (multiplied by 2 for consistency) for the given
602 * vec3 \p coords, for the face implied by \p selcoords.
603 *
604 * For the major axis, we always adjust the sign to be in the direction of
605 * selcoords.ma; i.e., a positive out_ma means that coords is pointed towards
606 * the selcoords major axis.
607 */
608 static void build_cube_select(struct ac_llvm_context *ctx,
609 const struct cube_selection_coords *selcoords,
610 const LLVMValueRef *coords,
611 LLVMValueRef *out_st,
612 LLVMValueRef *out_ma)
613 {
614 LLVMBuilderRef builder = ctx->builder;
615 LLVMTypeRef f32 = LLVMTypeOf(coords[0]);
616 LLVMValueRef is_ma_positive;
617 LLVMValueRef sgn_ma;
618 LLVMValueRef is_ma_z, is_not_ma_z;
619 LLVMValueRef is_ma_y;
620 LLVMValueRef is_ma_x;
621 LLVMValueRef sgn;
622 LLVMValueRef tmp;
623
624 is_ma_positive = LLVMBuildFCmp(builder, LLVMRealUGE,
625 selcoords->ma, LLVMConstReal(f32, 0.0), "");
626 sgn_ma = LLVMBuildSelect(builder, is_ma_positive,
627 LLVMConstReal(f32, 1.0), LLVMConstReal(f32, -1.0), "");
628
629 is_ma_z = LLVMBuildFCmp(builder, LLVMRealUGE, selcoords->id, LLVMConstReal(f32, 4.0), "");
630 is_not_ma_z = LLVMBuildNot(builder, is_ma_z, "");
631 is_ma_y = LLVMBuildAnd(builder, is_not_ma_z,
632 LLVMBuildFCmp(builder, LLVMRealUGE, selcoords->id, LLVMConstReal(f32, 2.0), ""), "");
633 is_ma_x = LLVMBuildAnd(builder, is_not_ma_z, LLVMBuildNot(builder, is_ma_y, ""), "");
634
635 /* Select sc */
636 tmp = LLVMBuildSelect(builder, is_ma_x, coords[2], coords[0], "");
637 sgn = LLVMBuildSelect(builder, is_ma_y, LLVMConstReal(f32, 1.0),
638 LLVMBuildSelect(builder, is_ma_z, sgn_ma,
639 LLVMBuildFNeg(builder, sgn_ma, ""), ""), "");
640 out_st[0] = LLVMBuildFMul(builder, tmp, sgn, "");
641
642 /* Select tc */
643 tmp = LLVMBuildSelect(builder, is_ma_y, coords[2], coords[1], "");
644 sgn = LLVMBuildSelect(builder, is_ma_y, sgn_ma,
645 LLVMConstReal(f32, -1.0), "");
646 out_st[1] = LLVMBuildFMul(builder, tmp, sgn, "");
647
648 /* Select ma */
649 tmp = LLVMBuildSelect(builder, is_ma_z, coords[2],
650 LLVMBuildSelect(builder, is_ma_y, coords[1], coords[0], ""), "");
651 tmp = ac_build_intrinsic(ctx, "llvm.fabs.f32",
652 ctx->f32, &tmp, 1, AC_FUNC_ATTR_READNONE);
653 *out_ma = LLVMBuildFMul(builder, tmp, LLVMConstReal(f32, 2.0), "");
654 }
655
656 void
657 ac_prepare_cube_coords(struct ac_llvm_context *ctx,
658 bool is_deriv, bool is_array, bool is_lod,
659 LLVMValueRef *coords_arg,
660 LLVMValueRef *derivs_arg)
661 {
662
663 LLVMBuilderRef builder = ctx->builder;
664 struct cube_selection_coords selcoords;
665 LLVMValueRef coords[3];
666 LLVMValueRef invma;
667
668 if (is_array && !is_lod) {
669 LLVMValueRef tmp = coords_arg[3];
670 tmp = ac_build_intrinsic(ctx, "llvm.rint.f32", ctx->f32, &tmp, 1, 0);
671
672 /* Section 8.9 (Texture Functions) of the GLSL 4.50 spec says:
673 *
674 * "For Array forms, the array layer used will be
675 *
676 * max(0, min(d−1, floor(layer+0.5)))
677 *
678 * where d is the depth of the texture array and layer
679 * comes from the component indicated in the tables below.
680 * Workaroudn for an issue where the layer is taken from a
681 * helper invocation which happens to fall on a different
682 * layer due to extrapolation."
683 *
684 * VI and earlier attempt to implement this in hardware by
685 * clamping the value of coords[2] = (8 * layer) + face.
686 * Unfortunately, this means that the we end up with the wrong
687 * face when clamping occurs.
688 *
689 * Clamp the layer earlier to work around the issue.
690 */
691 if (ctx->chip_class <= VI) {
692 LLVMValueRef ge0;
693 ge0 = LLVMBuildFCmp(builder, LLVMRealOGE, tmp, ctx->f32_0, "");
694 tmp = LLVMBuildSelect(builder, ge0, tmp, ctx->f32_0, "");
695 }
696
697 coords_arg[3] = tmp;
698 }
699
700 build_cube_intrinsic(ctx, coords_arg, &selcoords);
701
702 invma = ac_build_intrinsic(ctx, "llvm.fabs.f32",
703 ctx->f32, &selcoords.ma, 1, AC_FUNC_ATTR_READNONE);
704 invma = ac_build_fdiv(ctx, LLVMConstReal(ctx->f32, 1.0), invma);
705
706 for (int i = 0; i < 2; ++i)
707 coords[i] = LLVMBuildFMul(builder, selcoords.stc[i], invma, "");
708
709 coords[2] = selcoords.id;
710
711 if (is_deriv && derivs_arg) {
712 LLVMValueRef derivs[4];
713 int axis;
714
715 /* Convert cube derivatives to 2D derivatives. */
716 for (axis = 0; axis < 2; axis++) {
717 LLVMValueRef deriv_st[2];
718 LLVMValueRef deriv_ma;
719
720 /* Transform the derivative alongside the texture
721 * coordinate. Mathematically, the correct formula is
722 * as follows. Assume we're projecting onto the +Z face
723 * and denote by dx/dh the derivative of the (original)
724 * X texture coordinate with respect to horizontal
725 * window coordinates. The projection onto the +Z face
726 * plane is:
727 *
728 * f(x,z) = x/z
729 *
730 * Then df/dh = df/dx * dx/dh + df/dz * dz/dh
731 * = 1/z * dx/dh - x/z * 1/z * dz/dh.
732 *
733 * This motivatives the implementation below.
734 *
735 * Whether this actually gives the expected results for
736 * apps that might feed in derivatives obtained via
737 * finite differences is anyone's guess. The OpenGL spec
738 * seems awfully quiet about how textureGrad for cube
739 * maps should be handled.
740 */
741 build_cube_select(ctx, &selcoords, &derivs_arg[axis * 3],
742 deriv_st, &deriv_ma);
743
744 deriv_ma = LLVMBuildFMul(builder, deriv_ma, invma, "");
745
746 for (int i = 0; i < 2; ++i)
747 derivs[axis * 2 + i] =
748 LLVMBuildFSub(builder,
749 LLVMBuildFMul(builder, deriv_st[i], invma, ""),
750 LLVMBuildFMul(builder, deriv_ma, coords[i], ""), "");
751 }
752
753 memcpy(derivs_arg, derivs, sizeof(derivs));
754 }
755
756 /* Shift the texture coordinate. This must be applied after the
757 * derivative calculation.
758 */
759 for (int i = 0; i < 2; ++i)
760 coords[i] = LLVMBuildFAdd(builder, coords[i], LLVMConstReal(ctx->f32, 1.5), "");
761
762 if (is_array) {
763 /* for cube arrays coord.z = coord.w(array_index) * 8 + face */
764 /* coords_arg.w component - array_index for cube arrays */
765 coords[2] = ac_build_fmad(ctx, coords_arg[3], LLVMConstReal(ctx->f32, 8.0), coords[2]);
766 }
767
768 memcpy(coords_arg, coords, sizeof(coords));
769 }
770
771
772 LLVMValueRef
773 ac_build_fs_interp(struct ac_llvm_context *ctx,
774 LLVMValueRef llvm_chan,
775 LLVMValueRef attr_number,
776 LLVMValueRef params,
777 LLVMValueRef i,
778 LLVMValueRef j)
779 {
780 LLVMValueRef args[5];
781 LLVMValueRef p1;
782
783 args[0] = i;
784 args[1] = llvm_chan;
785 args[2] = attr_number;
786 args[3] = params;
787
788 p1 = ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p1",
789 ctx->f32, args, 4, AC_FUNC_ATTR_READNONE);
790
791 args[0] = p1;
792 args[1] = j;
793 args[2] = llvm_chan;
794 args[3] = attr_number;
795 args[4] = params;
796
797 return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p2",
798 ctx->f32, args, 5, AC_FUNC_ATTR_READNONE);
799 }
800
801 LLVMValueRef
802 ac_build_fs_interp_mov(struct ac_llvm_context *ctx,
803 LLVMValueRef parameter,
804 LLVMValueRef llvm_chan,
805 LLVMValueRef attr_number,
806 LLVMValueRef params)
807 {
808 LLVMValueRef args[4];
809
810 args[0] = parameter;
811 args[1] = llvm_chan;
812 args[2] = attr_number;
813 args[3] = params;
814
815 return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.mov",
816 ctx->f32, args, 4, AC_FUNC_ATTR_READNONE);
817 }
818
819 LLVMValueRef
820 ac_build_gep0(struct ac_llvm_context *ctx,
821 LLVMValueRef base_ptr,
822 LLVMValueRef index)
823 {
824 LLVMValueRef indices[2] = {
825 LLVMConstInt(ctx->i32, 0, 0),
826 index,
827 };
828 return LLVMBuildGEP(ctx->builder, base_ptr,
829 indices, 2, "");
830 }
831
832 void
833 ac_build_indexed_store(struct ac_llvm_context *ctx,
834 LLVMValueRef base_ptr, LLVMValueRef index,
835 LLVMValueRef value)
836 {
837 LLVMBuildStore(ctx->builder, value,
838 ac_build_gep0(ctx, base_ptr, index));
839 }
840
841 /**
842 * Build an LLVM bytecode indexed load using LLVMBuildGEP + LLVMBuildLoad.
843 * It's equivalent to doing a load from &base_ptr[index].
844 *
845 * \param base_ptr Where the array starts.
846 * \param index The element index into the array.
847 * \param uniform Whether the base_ptr and index can be assumed to be
848 * dynamically uniform (i.e. load to an SGPR)
849 * \param invariant Whether the load is invariant (no other opcodes affect it)
850 */
851 static LLVMValueRef
852 ac_build_load_custom(struct ac_llvm_context *ctx, LLVMValueRef base_ptr,
853 LLVMValueRef index, bool uniform, bool invariant)
854 {
855 LLVMValueRef pointer, result;
856
857 pointer = ac_build_gep0(ctx, base_ptr, index);
858 if (uniform)
859 LLVMSetMetadata(pointer, ctx->uniform_md_kind, ctx->empty_md);
860 result = LLVMBuildLoad(ctx->builder, pointer, "");
861 if (invariant)
862 LLVMSetMetadata(result, ctx->invariant_load_md_kind, ctx->empty_md);
863 return result;
864 }
865
866 LLVMValueRef ac_build_load(struct ac_llvm_context *ctx, LLVMValueRef base_ptr,
867 LLVMValueRef index)
868 {
869 return ac_build_load_custom(ctx, base_ptr, index, false, false);
870 }
871
872 LLVMValueRef ac_build_load_invariant(struct ac_llvm_context *ctx,
873 LLVMValueRef base_ptr, LLVMValueRef index)
874 {
875 return ac_build_load_custom(ctx, base_ptr, index, false, true);
876 }
877
878 LLVMValueRef ac_build_load_to_sgpr(struct ac_llvm_context *ctx,
879 LLVMValueRef base_ptr, LLVMValueRef index)
880 {
881 return ac_build_load_custom(ctx, base_ptr, index, true, true);
882 }
883
884 /* TBUFFER_STORE_FORMAT_{X,XY,XYZ,XYZW} <- the suffix is selected by num_channels=1..4.
885 * The type of vdata must be one of i32 (num_channels=1), v2i32 (num_channels=2),
886 * or v4i32 (num_channels=3,4).
887 */
888 void
889 ac_build_buffer_store_dword(struct ac_llvm_context *ctx,
890 LLVMValueRef rsrc,
891 LLVMValueRef vdata,
892 unsigned num_channels,
893 LLVMValueRef voffset,
894 LLVMValueRef soffset,
895 unsigned inst_offset,
896 bool glc,
897 bool slc,
898 bool writeonly_memory,
899 bool swizzle_enable_hint)
900 {
901 /* Split 3 channel stores, becase LLVM doesn't support 3-channel
902 * intrinsics. */
903 if (num_channels == 3) {
904 LLVMValueRef v[3], v01;
905
906 for (int i = 0; i < 3; i++) {
907 v[i] = LLVMBuildExtractElement(ctx->builder, vdata,
908 LLVMConstInt(ctx->i32, i, 0), "");
909 }
910 v01 = ac_build_gather_values(ctx, v, 2);
911
912 ac_build_buffer_store_dword(ctx, rsrc, v01, 2, voffset,
913 soffset, inst_offset, glc, slc,
914 writeonly_memory, swizzle_enable_hint);
915 ac_build_buffer_store_dword(ctx, rsrc, v[2], 1, voffset,
916 soffset, inst_offset + 8,
917 glc, slc,
918 writeonly_memory, swizzle_enable_hint);
919 return;
920 }
921
922 /* SWIZZLE_ENABLE requires that soffset isn't folded into voffset
923 * (voffset is swizzled, but soffset isn't swizzled).
924 * llvm.amdgcn.buffer.store doesn't have a separate soffset parameter.
925 */
926 if (!swizzle_enable_hint) {
927 LLVMValueRef offset = soffset;
928
929 static const char *types[] = {"f32", "v2f32", "v4f32"};
930
931 if (inst_offset)
932 offset = LLVMBuildAdd(ctx->builder, offset,
933 LLVMConstInt(ctx->i32, inst_offset, 0), "");
934 if (voffset)
935 offset = LLVMBuildAdd(ctx->builder, offset, voffset, "");
936
937 LLVMValueRef args[] = {
938 ac_to_float(ctx, vdata),
939 LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, ""),
940 LLVMConstInt(ctx->i32, 0, 0),
941 offset,
942 LLVMConstInt(ctx->i1, glc, 0),
943 LLVMConstInt(ctx->i1, slc, 0),
944 };
945
946 char name[256];
947 snprintf(name, sizeof(name), "llvm.amdgcn.buffer.store.%s",
948 types[CLAMP(num_channels, 1, 3) - 1]);
949
950 ac_build_intrinsic(ctx, name, ctx->voidt,
951 args, ARRAY_SIZE(args),
952 writeonly_memory ?
953 AC_FUNC_ATTR_INACCESSIBLE_MEM_ONLY :
954 AC_FUNC_ATTR_WRITEONLY);
955 return;
956 }
957
958 static const unsigned dfmt[] = {
959 V_008F0C_BUF_DATA_FORMAT_32,
960 V_008F0C_BUF_DATA_FORMAT_32_32,
961 V_008F0C_BUF_DATA_FORMAT_32_32_32,
962 V_008F0C_BUF_DATA_FORMAT_32_32_32_32
963 };
964 static const char *types[] = {"i32", "v2i32", "v4i32"};
965 LLVMValueRef args[] = {
966 vdata,
967 LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, ""),
968 LLVMConstInt(ctx->i32, 0, 0),
969 voffset ? voffset : LLVMConstInt(ctx->i32, 0, 0),
970 soffset,
971 LLVMConstInt(ctx->i32, inst_offset, 0),
972 LLVMConstInt(ctx->i32, dfmt[num_channels - 1], 0),
973 LLVMConstInt(ctx->i32, V_008F0C_BUF_NUM_FORMAT_UINT, 0),
974 LLVMConstInt(ctx->i1, glc, 0),
975 LLVMConstInt(ctx->i1, slc, 0),
976 };
977 char name[256];
978 snprintf(name, sizeof(name), "llvm.amdgcn.tbuffer.store.%s",
979 types[CLAMP(num_channels, 1, 3) - 1]);
980
981 ac_build_intrinsic(ctx, name, ctx->voidt,
982 args, ARRAY_SIZE(args),
983 writeonly_memory ?
984 AC_FUNC_ATTR_INACCESSIBLE_MEM_ONLY :
985 AC_FUNC_ATTR_WRITEONLY);
986 }
987
988 static LLVMValueRef
989 ac_build_buffer_load_common(struct ac_llvm_context *ctx,
990 LLVMValueRef rsrc,
991 LLVMValueRef vindex,
992 LLVMValueRef voffset,
993 unsigned num_channels,
994 bool glc,
995 bool slc,
996 bool can_speculate,
997 bool use_format)
998 {
999 LLVMValueRef args[] = {
1000 LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, ""),
1001 vindex ? vindex : LLVMConstInt(ctx->i32, 0, 0),
1002 voffset,
1003 LLVMConstInt(ctx->i1, glc, 0),
1004 LLVMConstInt(ctx->i1, slc, 0)
1005 };
1006 unsigned func = CLAMP(num_channels, 1, 3) - 1;
1007
1008 LLVMTypeRef types[] = {ctx->f32, ctx->v2f32, ctx->v4f32};
1009 const char *type_names[] = {"f32", "v2f32", "v4f32"};
1010 char name[256];
1011
1012 if (use_format) {
1013 snprintf(name, sizeof(name), "llvm.amdgcn.buffer.load.format.%s",
1014 type_names[func]);
1015 } else {
1016 snprintf(name, sizeof(name), "llvm.amdgcn.buffer.load.%s",
1017 type_names[func]);
1018 }
1019
1020 return ac_build_intrinsic(ctx, name, types[func], args,
1021 ARRAY_SIZE(args),
1022 ac_get_load_intr_attribs(can_speculate));
1023 }
1024
1025 LLVMValueRef
1026 ac_build_buffer_load(struct ac_llvm_context *ctx,
1027 LLVMValueRef rsrc,
1028 int num_channels,
1029 LLVMValueRef vindex,
1030 LLVMValueRef voffset,
1031 LLVMValueRef soffset,
1032 unsigned inst_offset,
1033 unsigned glc,
1034 unsigned slc,
1035 bool can_speculate,
1036 bool allow_smem)
1037 {
1038 LLVMValueRef offset = LLVMConstInt(ctx->i32, inst_offset, 0);
1039 if (voffset)
1040 offset = LLVMBuildAdd(ctx->builder, offset, voffset, "");
1041 if (soffset)
1042 offset = LLVMBuildAdd(ctx->builder, offset, soffset, "");
1043
1044 /* TODO: VI and later generations can use SMEM with GLC=1.*/
1045 if (allow_smem && !glc && !slc) {
1046 assert(vindex == NULL);
1047
1048 LLVMValueRef result[8];
1049
1050 for (int i = 0; i < num_channels; i++) {
1051 if (i) {
1052 offset = LLVMBuildAdd(ctx->builder, offset,
1053 LLVMConstInt(ctx->i32, 4, 0), "");
1054 }
1055 LLVMValueRef args[2] = {rsrc, offset};
1056 result[i] = ac_build_intrinsic(ctx, "llvm.SI.load.const.v4i32",
1057 ctx->f32, args, 2,
1058 AC_FUNC_ATTR_READNONE |
1059 AC_FUNC_ATTR_LEGACY);
1060 }
1061 if (num_channels == 1)
1062 return result[0];
1063
1064 if (num_channels == 3)
1065 result[num_channels++] = LLVMGetUndef(ctx->f32);
1066 return ac_build_gather_values(ctx, result, num_channels);
1067 }
1068
1069 return ac_build_buffer_load_common(ctx, rsrc, vindex, offset,
1070 num_channels, glc, slc,
1071 can_speculate, false);
1072 }
1073
1074 LLVMValueRef ac_build_buffer_load_format(struct ac_llvm_context *ctx,
1075 LLVMValueRef rsrc,
1076 LLVMValueRef vindex,
1077 LLVMValueRef voffset,
1078 unsigned num_channels,
1079 bool glc,
1080 bool can_speculate)
1081 {
1082 return ac_build_buffer_load_common(ctx, rsrc, vindex, voffset,
1083 num_channels, glc, false,
1084 can_speculate, true);
1085 }
1086
1087 LLVMValueRef ac_build_buffer_load_format_gfx9_safe(struct ac_llvm_context *ctx,
1088 LLVMValueRef rsrc,
1089 LLVMValueRef vindex,
1090 LLVMValueRef voffset,
1091 unsigned num_channels,
1092 bool glc,
1093 bool can_speculate)
1094 {
1095 LLVMValueRef elem_count = LLVMBuildExtractElement(ctx->builder, rsrc, LLVMConstInt(ctx->i32, 2, 0), "");
1096 LLVMValueRef stride = LLVMBuildExtractElement(ctx->builder, rsrc, LLVMConstInt(ctx->i32, 1, 0), "");
1097 stride = LLVMBuildLShr(ctx->builder, stride, LLVMConstInt(ctx->i32, 16, 0), "");
1098
1099 LLVMValueRef new_elem_count = LLVMBuildSelect(ctx->builder,
1100 LLVMBuildICmp(ctx->builder, LLVMIntUGT, elem_count, stride, ""),
1101 elem_count, stride, "");
1102
1103 LLVMValueRef new_rsrc = LLVMBuildInsertElement(ctx->builder, rsrc, new_elem_count,
1104 LLVMConstInt(ctx->i32, 2, 0), "");
1105
1106 return ac_build_buffer_load_common(ctx, new_rsrc, vindex, voffset,
1107 num_channels, glc, false,
1108 can_speculate, true);
1109 }
1110
1111 LLVMValueRef
1112 ac_build_tbuffer_load_short(struct ac_llvm_context *ctx,
1113 LLVMValueRef rsrc,
1114 LLVMValueRef vindex,
1115 LLVMValueRef voffset,
1116 LLVMValueRef soffset,
1117 LLVMValueRef immoffset)
1118 {
1119 const char *name = "llvm.amdgcn.tbuffer.load.i32";
1120 LLVMTypeRef type = ctx->i32;
1121 LLVMValueRef params[] = {
1122 rsrc,
1123 vindex,
1124 voffset,
1125 soffset,
1126 immoffset,
1127 LLVMConstInt(ctx->i32, V_008F0C_BUF_DATA_FORMAT_16, false),
1128 LLVMConstInt(ctx->i32, V_008F0C_BUF_NUM_FORMAT_UINT, false),
1129 ctx->i1false,
1130 ctx->i1false,
1131 };
1132 LLVMValueRef res = ac_build_intrinsic(ctx, name, type, params, 9, 0);
1133 return LLVMBuildTrunc(ctx->builder, res, ctx->i16, "");
1134 }
1135
1136 /**
1137 * Set range metadata on an instruction. This can only be used on load and
1138 * call instructions. If you know an instruction can only produce the values
1139 * 0, 1, 2, you would do set_range_metadata(value, 0, 3);
1140 * \p lo is the minimum value inclusive.
1141 * \p hi is the maximum value exclusive.
1142 */
1143 static void set_range_metadata(struct ac_llvm_context *ctx,
1144 LLVMValueRef value, unsigned lo, unsigned hi)
1145 {
1146 LLVMValueRef range_md, md_args[2];
1147 LLVMTypeRef type = LLVMTypeOf(value);
1148 LLVMContextRef context = LLVMGetTypeContext(type);
1149
1150 md_args[0] = LLVMConstInt(type, lo, false);
1151 md_args[1] = LLVMConstInt(type, hi, false);
1152 range_md = LLVMMDNodeInContext(context, md_args, 2);
1153 LLVMSetMetadata(value, ctx->range_md_kind, range_md);
1154 }
1155
1156 LLVMValueRef
1157 ac_get_thread_id(struct ac_llvm_context *ctx)
1158 {
1159 LLVMValueRef tid;
1160
1161 LLVMValueRef tid_args[2];
1162 tid_args[0] = LLVMConstInt(ctx->i32, 0xffffffff, false);
1163 tid_args[1] = LLVMConstInt(ctx->i32, 0, false);
1164 tid_args[1] = ac_build_intrinsic(ctx,
1165 "llvm.amdgcn.mbcnt.lo", ctx->i32,
1166 tid_args, 2, AC_FUNC_ATTR_READNONE);
1167
1168 tid = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi",
1169 ctx->i32, tid_args,
1170 2, AC_FUNC_ATTR_READNONE);
1171 set_range_metadata(ctx, tid, 0, 64);
1172 return tid;
1173 }
1174
1175 /*
1176 * SI implements derivatives using the local data store (LDS)
1177 * All writes to the LDS happen in all executing threads at
1178 * the same time. TID is the Thread ID for the current
1179 * thread and is a value between 0 and 63, representing
1180 * the thread's position in the wavefront.
1181 *
1182 * For the pixel shader threads are grouped into quads of four pixels.
1183 * The TIDs of the pixels of a quad are:
1184 *
1185 * +------+------+
1186 * |4n + 0|4n + 1|
1187 * +------+------+
1188 * |4n + 2|4n + 3|
1189 * +------+------+
1190 *
1191 * So, masking the TID with 0xfffffffc yields the TID of the top left pixel
1192 * of the quad, masking with 0xfffffffd yields the TID of the top pixel of
1193 * the current pixel's column, and masking with 0xfffffffe yields the TID
1194 * of the left pixel of the current pixel's row.
1195 *
1196 * Adding 1 yields the TID of the pixel to the right of the left pixel, and
1197 * adding 2 yields the TID of the pixel below the top pixel.
1198 */
1199 LLVMValueRef
1200 ac_build_ddxy(struct ac_llvm_context *ctx,
1201 uint32_t mask,
1202 int idx,
1203 LLVMValueRef val)
1204 {
1205 LLVMValueRef tl, trbl, args[2];
1206 LLVMValueRef result;
1207
1208 if (HAVE_LLVM >= 0x0700) {
1209 unsigned tl_lanes[4], trbl_lanes[4];
1210
1211 for (unsigned i = 0; i < 4; ++i) {
1212 tl_lanes[i] = i & mask;
1213 trbl_lanes[i] = (i & mask) + idx;
1214 }
1215
1216 tl = ac_build_quad_swizzle(ctx, val,
1217 tl_lanes[0], tl_lanes[1],
1218 tl_lanes[2], tl_lanes[3]);
1219 trbl = ac_build_quad_swizzle(ctx, val,
1220 trbl_lanes[0], trbl_lanes[1],
1221 trbl_lanes[2], trbl_lanes[3]);
1222 } else if (ctx->chip_class >= VI) {
1223 LLVMValueRef thread_id, tl_tid, trbl_tid;
1224 thread_id = ac_get_thread_id(ctx);
1225
1226 tl_tid = LLVMBuildAnd(ctx->builder, thread_id,
1227 LLVMConstInt(ctx->i32, mask, false), "");
1228
1229 trbl_tid = LLVMBuildAdd(ctx->builder, tl_tid,
1230 LLVMConstInt(ctx->i32, idx, false), "");
1231
1232 args[0] = LLVMBuildMul(ctx->builder, tl_tid,
1233 LLVMConstInt(ctx->i32, 4, false), "");
1234 args[1] = val;
1235 tl = ac_build_intrinsic(ctx,
1236 "llvm.amdgcn.ds.bpermute", ctx->i32,
1237 args, 2,
1238 AC_FUNC_ATTR_READNONE |
1239 AC_FUNC_ATTR_CONVERGENT);
1240
1241 args[0] = LLVMBuildMul(ctx->builder, trbl_tid,
1242 LLVMConstInt(ctx->i32, 4, false), "");
1243 trbl = ac_build_intrinsic(ctx,
1244 "llvm.amdgcn.ds.bpermute", ctx->i32,
1245 args, 2,
1246 AC_FUNC_ATTR_READNONE |
1247 AC_FUNC_ATTR_CONVERGENT);
1248 } else {
1249 uint32_t masks[2] = {};
1250
1251 switch (mask) {
1252 case AC_TID_MASK_TOP_LEFT:
1253 masks[0] = 0x8000;
1254 if (idx == 1)
1255 masks[1] = 0x8055;
1256 else
1257 masks[1] = 0x80aa;
1258
1259 break;
1260 case AC_TID_MASK_TOP:
1261 masks[0] = 0x8044;
1262 masks[1] = 0x80ee;
1263 break;
1264 case AC_TID_MASK_LEFT:
1265 masks[0] = 0x80a0;
1266 masks[1] = 0x80f5;
1267 break;
1268 default:
1269 assert(0);
1270 }
1271
1272 args[0] = val;
1273 args[1] = LLVMConstInt(ctx->i32, masks[0], false);
1274
1275 tl = ac_build_intrinsic(ctx,
1276 "llvm.amdgcn.ds.swizzle", ctx->i32,
1277 args, 2,
1278 AC_FUNC_ATTR_READNONE |
1279 AC_FUNC_ATTR_CONVERGENT);
1280
1281 args[1] = LLVMConstInt(ctx->i32, masks[1], false);
1282 trbl = ac_build_intrinsic(ctx,
1283 "llvm.amdgcn.ds.swizzle", ctx->i32,
1284 args, 2,
1285 AC_FUNC_ATTR_READNONE |
1286 AC_FUNC_ATTR_CONVERGENT);
1287 }
1288
1289 tl = LLVMBuildBitCast(ctx->builder, tl, ctx->f32, "");
1290 trbl = LLVMBuildBitCast(ctx->builder, trbl, ctx->f32, "");
1291 result = LLVMBuildFSub(ctx->builder, trbl, tl, "");
1292
1293 if (HAVE_LLVM >= 0x0700) {
1294 result = ac_build_intrinsic(ctx,
1295 "llvm.amdgcn.wqm.f32", ctx->f32,
1296 &result, 1, 0);
1297 }
1298
1299 return result;
1300 }
1301
1302 void
1303 ac_build_sendmsg(struct ac_llvm_context *ctx,
1304 uint32_t msg,
1305 LLVMValueRef wave_id)
1306 {
1307 LLVMValueRef args[2];
1308 args[0] = LLVMConstInt(ctx->i32, msg, false);
1309 args[1] = wave_id;
1310 ac_build_intrinsic(ctx, "llvm.amdgcn.s.sendmsg", ctx->voidt, args, 2, 0);
1311 }
1312
1313 LLVMValueRef
1314 ac_build_imsb(struct ac_llvm_context *ctx,
1315 LLVMValueRef arg,
1316 LLVMTypeRef dst_type)
1317 {
1318 LLVMValueRef msb = ac_build_intrinsic(ctx, "llvm.amdgcn.sffbh.i32",
1319 dst_type, &arg, 1,
1320 AC_FUNC_ATTR_READNONE);
1321
1322 /* The HW returns the last bit index from MSB, but NIR/TGSI wants
1323 * the index from LSB. Invert it by doing "31 - msb". */
1324 msb = LLVMBuildSub(ctx->builder, LLVMConstInt(ctx->i32, 31, false),
1325 msb, "");
1326
1327 LLVMValueRef all_ones = LLVMConstInt(ctx->i32, -1, true);
1328 LLVMValueRef cond = LLVMBuildOr(ctx->builder,
1329 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
1330 arg, LLVMConstInt(ctx->i32, 0, 0), ""),
1331 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
1332 arg, all_ones, ""), "");
1333
1334 return LLVMBuildSelect(ctx->builder, cond, all_ones, msb, "");
1335 }
1336
1337 LLVMValueRef
1338 ac_build_umsb(struct ac_llvm_context *ctx,
1339 LLVMValueRef arg,
1340 LLVMTypeRef dst_type)
1341 {
1342 const char *intrin_name;
1343 LLVMTypeRef type;
1344 LLVMValueRef highest_bit;
1345 LLVMValueRef zero;
1346
1347 if (ac_get_elem_bits(ctx, LLVMTypeOf(arg)) == 64) {
1348 intrin_name = "llvm.ctlz.i64";
1349 type = ctx->i64;
1350 highest_bit = LLVMConstInt(ctx->i64, 63, false);
1351 zero = ctx->i64_0;
1352 } else {
1353 intrin_name = "llvm.ctlz.i32";
1354 type = ctx->i32;
1355 highest_bit = LLVMConstInt(ctx->i32, 31, false);
1356 zero = ctx->i32_0;
1357 }
1358
1359 LLVMValueRef params[2] = {
1360 arg,
1361 ctx->i1true,
1362 };
1363
1364 LLVMValueRef msb = ac_build_intrinsic(ctx, intrin_name, type,
1365 params, 2,
1366 AC_FUNC_ATTR_READNONE);
1367
1368 /* The HW returns the last bit index from MSB, but TGSI/NIR wants
1369 * the index from LSB. Invert it by doing "31 - msb". */
1370 msb = LLVMBuildSub(ctx->builder, highest_bit, msb, "");
1371 msb = LLVMBuildTruncOrBitCast(ctx->builder, msb, ctx->i32, "");
1372
1373 /* check for zero */
1374 return LLVMBuildSelect(ctx->builder,
1375 LLVMBuildICmp(ctx->builder, LLVMIntEQ, arg, zero, ""),
1376 LLVMConstInt(ctx->i32, -1, true), msb, "");
1377 }
1378
1379 LLVMValueRef ac_build_fmin(struct ac_llvm_context *ctx, LLVMValueRef a,
1380 LLVMValueRef b)
1381 {
1382 LLVMValueRef args[2] = {a, b};
1383 return ac_build_intrinsic(ctx, "llvm.minnum.f32", ctx->f32, args, 2,
1384 AC_FUNC_ATTR_READNONE);
1385 }
1386
1387 LLVMValueRef ac_build_fmax(struct ac_llvm_context *ctx, LLVMValueRef a,
1388 LLVMValueRef b)
1389 {
1390 LLVMValueRef args[2] = {a, b};
1391 return ac_build_intrinsic(ctx, "llvm.maxnum.f32", ctx->f32, args, 2,
1392 AC_FUNC_ATTR_READNONE);
1393 }
1394
1395 LLVMValueRef ac_build_imin(struct ac_llvm_context *ctx, LLVMValueRef a,
1396 LLVMValueRef b)
1397 {
1398 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSLE, a, b, "");
1399 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
1400 }
1401
1402 LLVMValueRef ac_build_imax(struct ac_llvm_context *ctx, LLVMValueRef a,
1403 LLVMValueRef b)
1404 {
1405 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, a, b, "");
1406 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
1407 }
1408
1409 LLVMValueRef ac_build_umin(struct ac_llvm_context *ctx, LLVMValueRef a,
1410 LLVMValueRef b)
1411 {
1412 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntULE, a, b, "");
1413 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
1414 }
1415
1416 LLVMValueRef ac_build_clamp(struct ac_llvm_context *ctx, LLVMValueRef value)
1417 {
1418 return ac_build_fmin(ctx, ac_build_fmax(ctx, value, ctx->f32_0),
1419 ctx->f32_1);
1420 }
1421
1422 void ac_build_export(struct ac_llvm_context *ctx, struct ac_export_args *a)
1423 {
1424 LLVMValueRef args[9];
1425
1426 args[0] = LLVMConstInt(ctx->i32, a->target, 0);
1427 args[1] = LLVMConstInt(ctx->i32, a->enabled_channels, 0);
1428
1429 if (a->compr) {
1430 LLVMTypeRef i16 = LLVMInt16TypeInContext(ctx->context);
1431 LLVMTypeRef v2i16 = LLVMVectorType(i16, 2);
1432
1433 args[2] = LLVMBuildBitCast(ctx->builder, a->out[0],
1434 v2i16, "");
1435 args[3] = LLVMBuildBitCast(ctx->builder, a->out[1],
1436 v2i16, "");
1437 args[4] = LLVMConstInt(ctx->i1, a->done, 0);
1438 args[5] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
1439
1440 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.compr.v2i16",
1441 ctx->voidt, args, 6, 0);
1442 } else {
1443 args[2] = a->out[0];
1444 args[3] = a->out[1];
1445 args[4] = a->out[2];
1446 args[5] = a->out[3];
1447 args[6] = LLVMConstInt(ctx->i1, a->done, 0);
1448 args[7] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
1449
1450 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.f32",
1451 ctx->voidt, args, 8, 0);
1452 }
1453 }
1454
1455 void ac_build_export_null(struct ac_llvm_context *ctx)
1456 {
1457 struct ac_export_args args;
1458
1459 args.enabled_channels = 0x0; /* enabled channels */
1460 args.valid_mask = 1; /* whether the EXEC mask is valid */
1461 args.done = 1; /* DONE bit */
1462 args.target = V_008DFC_SQ_EXP_NULL;
1463 args.compr = 0; /* COMPR flag (0 = 32-bit export) */
1464 args.out[0] = LLVMGetUndef(ctx->f32); /* R */
1465 args.out[1] = LLVMGetUndef(ctx->f32); /* G */
1466 args.out[2] = LLVMGetUndef(ctx->f32); /* B */
1467 args.out[3] = LLVMGetUndef(ctx->f32); /* A */
1468
1469 ac_build_export(ctx, &args);
1470 }
1471
1472 static unsigned ac_num_coords(enum ac_image_dim dim)
1473 {
1474 switch (dim) {
1475 case ac_image_1d:
1476 return 1;
1477 case ac_image_2d:
1478 case ac_image_1darray:
1479 return 2;
1480 case ac_image_3d:
1481 case ac_image_cube:
1482 case ac_image_2darray:
1483 case ac_image_2dmsaa:
1484 return 3;
1485 case ac_image_2darraymsaa:
1486 return 4;
1487 default:
1488 unreachable("ac_num_coords: bad dim");
1489 }
1490 }
1491
1492 static unsigned ac_num_derivs(enum ac_image_dim dim)
1493 {
1494 switch (dim) {
1495 case ac_image_1d:
1496 case ac_image_1darray:
1497 return 2;
1498 case ac_image_2d:
1499 case ac_image_2darray:
1500 case ac_image_cube:
1501 return 4;
1502 case ac_image_3d:
1503 return 6;
1504 case ac_image_2dmsaa:
1505 case ac_image_2darraymsaa:
1506 default:
1507 unreachable("derivatives not supported");
1508 }
1509 }
1510
1511 static const char *get_atomic_name(enum ac_atomic_op op)
1512 {
1513 switch (op) {
1514 case ac_atomic_swap: return "swap";
1515 case ac_atomic_add: return "add";
1516 case ac_atomic_sub: return "sub";
1517 case ac_atomic_smin: return "smin";
1518 case ac_atomic_umin: return "umin";
1519 case ac_atomic_smax: return "smax";
1520 case ac_atomic_umax: return "umax";
1521 case ac_atomic_and: return "and";
1522 case ac_atomic_or: return "or";
1523 case ac_atomic_xor: return "xor";
1524 }
1525 unreachable("bad atomic op");
1526 }
1527
1528 /* LLVM 6 and older */
1529 static LLVMValueRef ac_build_image_opcode_llvm6(struct ac_llvm_context *ctx,
1530 struct ac_image_args *a)
1531 {
1532 LLVMValueRef args[16];
1533 LLVMTypeRef retty = ctx->v4f32;
1534 const char *name = NULL;
1535 const char *atomic_subop = "";
1536 char intr_name[128], coords_type[64];
1537
1538 bool sample = a->opcode == ac_image_sample ||
1539 a->opcode == ac_image_gather4 ||
1540 a->opcode == ac_image_get_lod;
1541 bool atomic = a->opcode == ac_image_atomic ||
1542 a->opcode == ac_image_atomic_cmpswap;
1543 bool da = a->dim == ac_image_cube ||
1544 a->dim == ac_image_1darray ||
1545 a->dim == ac_image_2darray ||
1546 a->dim == ac_image_2darraymsaa;
1547 if (a->opcode == ac_image_get_lod)
1548 da = false;
1549
1550 unsigned num_coords =
1551 a->opcode != ac_image_get_resinfo ? ac_num_coords(a->dim) : 0;
1552 LLVMValueRef addr;
1553 unsigned num_addr = 0;
1554
1555 if (a->opcode == ac_image_get_lod) {
1556 switch (a->dim) {
1557 case ac_image_1darray:
1558 num_coords = 1;
1559 break;
1560 case ac_image_2darray:
1561 case ac_image_cube:
1562 num_coords = 2;
1563 break;
1564 default:
1565 break;
1566 }
1567 }
1568
1569 if (a->offset)
1570 args[num_addr++] = ac_to_integer(ctx, a->offset);
1571 if (a->bias)
1572 args[num_addr++] = ac_to_integer(ctx, a->bias);
1573 if (a->compare)
1574 args[num_addr++] = ac_to_integer(ctx, a->compare);
1575 if (a->derivs[0]) {
1576 unsigned num_derivs = ac_num_derivs(a->dim);
1577 for (unsigned i = 0; i < num_derivs; ++i)
1578 args[num_addr++] = ac_to_integer(ctx, a->derivs[i]);
1579 }
1580 for (unsigned i = 0; i < num_coords; ++i)
1581 args[num_addr++] = ac_to_integer(ctx, a->coords[i]);
1582 if (a->lod)
1583 args[num_addr++] = ac_to_integer(ctx, a->lod);
1584
1585 unsigned pad_goal = util_next_power_of_two(num_addr);
1586 while (num_addr < pad_goal)
1587 args[num_addr++] = LLVMGetUndef(ctx->i32);
1588
1589 addr = ac_build_gather_values(ctx, args, num_addr);
1590
1591 unsigned num_args = 0;
1592 if (atomic || a->opcode == ac_image_store || a->opcode == ac_image_store_mip) {
1593 args[num_args++] = a->data[0];
1594 if (a->opcode == ac_image_atomic_cmpswap)
1595 args[num_args++] = a->data[1];
1596 }
1597
1598 unsigned coords_arg = num_args;
1599 if (sample)
1600 args[num_args++] = ac_to_float(ctx, addr);
1601 else
1602 args[num_args++] = ac_to_integer(ctx, addr);
1603
1604 args[num_args++] = a->resource;
1605 if (sample)
1606 args[num_args++] = a->sampler;
1607 if (!atomic) {
1608 args[num_args++] = LLVMConstInt(ctx->i32, a->dmask, 0);
1609 if (sample)
1610 args[num_args++] = LLVMConstInt(ctx->i1, a->unorm, 0);
1611 args[num_args++] = a->cache_policy & ac_glc ? ctx->i1true : ctx->i1false;
1612 args[num_args++] = a->cache_policy & ac_slc ? ctx->i1true : ctx->i1false;
1613 args[num_args++] = ctx->i1false; /* lwe */
1614 args[num_args++] = LLVMConstInt(ctx->i1, da, 0);
1615 } else {
1616 args[num_args++] = ctx->i1false; /* r128 */
1617 args[num_args++] = LLVMConstInt(ctx->i1, da, 0);
1618 args[num_args++] = a->cache_policy & ac_slc ? ctx->i1true : ctx->i1false;
1619 }
1620
1621 switch (a->opcode) {
1622 case ac_image_sample:
1623 name = "llvm.amdgcn.image.sample";
1624 break;
1625 case ac_image_gather4:
1626 name = "llvm.amdgcn.image.gather4";
1627 break;
1628 case ac_image_load:
1629 name = "llvm.amdgcn.image.load";
1630 break;
1631 case ac_image_load_mip:
1632 name = "llvm.amdgcn.image.load.mip";
1633 break;
1634 case ac_image_store:
1635 name = "llvm.amdgcn.image.store";
1636 retty = ctx->voidt;
1637 break;
1638 case ac_image_store_mip:
1639 name = "llvm.amdgcn.image.store.mip";
1640 retty = ctx->voidt;
1641 break;
1642 case ac_image_atomic:
1643 case ac_image_atomic_cmpswap:
1644 name = "llvm.amdgcn.image.atomic.";
1645 retty = ctx->i32;
1646 if (a->opcode == ac_image_atomic_cmpswap) {
1647 atomic_subop = "cmpswap";
1648 } else {
1649 atomic_subop = get_atomic_name(a->atomic);
1650 }
1651 break;
1652 case ac_image_get_lod:
1653 name = "llvm.amdgcn.image.getlod";
1654 break;
1655 case ac_image_get_resinfo:
1656 name = "llvm.amdgcn.image.getresinfo";
1657 break;
1658 default:
1659 unreachable("invalid image opcode");
1660 }
1661
1662 ac_build_type_name_for_intr(LLVMTypeOf(args[coords_arg]), coords_type,
1663 sizeof(coords_type));
1664
1665 if (atomic) {
1666 snprintf(intr_name, sizeof(intr_name), "llvm.amdgcn.image.atomic.%s.%s",
1667 atomic_subop, coords_type);
1668 } else {
1669 bool lod_suffix =
1670 a->lod && (a->opcode == ac_image_sample || a->opcode == ac_image_gather4);
1671
1672 snprintf(intr_name, sizeof(intr_name), "%s%s%s%s.v4f32.%s.v8i32",
1673 name,
1674 a->compare ? ".c" : "",
1675 a->bias ? ".b" :
1676 lod_suffix ? ".l" :
1677 a->derivs[0] ? ".d" :
1678 a->level_zero ? ".lz" : "",
1679 a->offset ? ".o" : "",
1680 coords_type);
1681 }
1682
1683 LLVMValueRef result =
1684 ac_build_intrinsic(ctx, intr_name, retty, args, num_args,
1685 a->attributes);
1686 if (!sample && retty == ctx->v4f32) {
1687 result = LLVMBuildBitCast(ctx->builder, result,
1688 ctx->v4i32, "");
1689 }
1690 return result;
1691 }
1692
1693 LLVMValueRef ac_build_image_opcode(struct ac_llvm_context *ctx,
1694 struct ac_image_args *a)
1695 {
1696 const char *overload[3] = { "", "", "" };
1697 unsigned num_overloads = 0;
1698 LLVMValueRef args[18];
1699 unsigned num_args = 0;
1700 enum ac_image_dim dim = a->dim;
1701
1702 assert(!a->lod || a->lod == ctx->i32_0 || a->lod == ctx->f32_0 ||
1703 !a->level_zero);
1704 assert((a->opcode != ac_image_get_resinfo && a->opcode != ac_image_load_mip &&
1705 a->opcode != ac_image_store_mip) ||
1706 a->lod);
1707 assert(a->opcode == ac_image_sample || a->opcode == ac_image_gather4 ||
1708 (!a->compare && !a->offset));
1709 assert((a->opcode == ac_image_sample || a->opcode == ac_image_gather4 ||
1710 a->opcode == ac_image_get_lod) ||
1711 !a->bias);
1712 assert((a->bias ? 1 : 0) +
1713 (a->lod ? 1 : 0) +
1714 (a->level_zero ? 1 : 0) +
1715 (a->derivs[0] ? 1 : 0) <= 1);
1716
1717 if (HAVE_LLVM < 0x0700)
1718 return ac_build_image_opcode_llvm6(ctx, a);
1719
1720 if (a->opcode == ac_image_get_lod) {
1721 switch (dim) {
1722 case ac_image_1darray:
1723 dim = ac_image_1d;
1724 break;
1725 case ac_image_2darray:
1726 case ac_image_cube:
1727 dim = ac_image_2d;
1728 break;
1729 default:
1730 break;
1731 }
1732 }
1733
1734 bool sample = a->opcode == ac_image_sample ||
1735 a->opcode == ac_image_gather4 ||
1736 a->opcode == ac_image_get_lod;
1737 bool atomic = a->opcode == ac_image_atomic ||
1738 a->opcode == ac_image_atomic_cmpswap;
1739 LLVMTypeRef coord_type = sample ? ctx->f32 : ctx->i32;
1740
1741 if (atomic || a->opcode == ac_image_store || a->opcode == ac_image_store_mip) {
1742 args[num_args++] = a->data[0];
1743 if (a->opcode == ac_image_atomic_cmpswap)
1744 args[num_args++] = a->data[1];
1745 }
1746
1747 if (!atomic)
1748 args[num_args++] = LLVMConstInt(ctx->i32, a->dmask, false);
1749
1750 if (a->offset)
1751 args[num_args++] = ac_to_integer(ctx, a->offset);
1752 if (a->bias) {
1753 args[num_args++] = ac_to_float(ctx, a->bias);
1754 overload[num_overloads++] = ".f32";
1755 }
1756 if (a->compare)
1757 args[num_args++] = ac_to_float(ctx, a->compare);
1758 if (a->derivs[0]) {
1759 unsigned count = ac_num_derivs(dim);
1760 for (unsigned i = 0; i < count; ++i)
1761 args[num_args++] = ac_to_float(ctx, a->derivs[i]);
1762 overload[num_overloads++] = ".f32";
1763 }
1764 unsigned num_coords =
1765 a->opcode != ac_image_get_resinfo ? ac_num_coords(dim) : 0;
1766 for (unsigned i = 0; i < num_coords; ++i)
1767 args[num_args++] = LLVMBuildBitCast(ctx->builder, a->coords[i], coord_type, "");
1768 if (a->lod)
1769 args[num_args++] = LLVMBuildBitCast(ctx->builder, a->lod, coord_type, "");
1770 overload[num_overloads++] = sample ? ".f32" : ".i32";
1771
1772 args[num_args++] = a->resource;
1773 if (sample) {
1774 args[num_args++] = a->sampler;
1775 args[num_args++] = LLVMConstInt(ctx->i1, a->unorm, false);
1776 }
1777
1778 args[num_args++] = ctx->i32_0; /* texfailctrl */
1779 args[num_args++] = LLVMConstInt(ctx->i32, a->cache_policy, false);
1780
1781 const char *name;
1782 const char *atomic_subop = "";
1783 switch (a->opcode) {
1784 case ac_image_sample: name = "sample"; break;
1785 case ac_image_gather4: name = "gather4"; break;
1786 case ac_image_load: name = "load"; break;
1787 case ac_image_load_mip: name = "load.mip"; break;
1788 case ac_image_store: name = "store"; break;
1789 case ac_image_store_mip: name = "store.mip"; break;
1790 case ac_image_atomic:
1791 name = "atomic.";
1792 atomic_subop = get_atomic_name(a->atomic);
1793 break;
1794 case ac_image_atomic_cmpswap:
1795 name = "atomic.";
1796 atomic_subop = "cmpswap";
1797 break;
1798 case ac_image_get_lod: name = "getlod"; break;
1799 case ac_image_get_resinfo: name = "getresinfo"; break;
1800 default: unreachable("invalid image opcode");
1801 }
1802
1803 const char *dimname;
1804 switch (dim) {
1805 case ac_image_1d: dimname = "1d"; break;
1806 case ac_image_2d: dimname = "2d"; break;
1807 case ac_image_3d: dimname = "3d"; break;
1808 case ac_image_cube: dimname = "cube"; break;
1809 case ac_image_1darray: dimname = "1darray"; break;
1810 case ac_image_2darray: dimname = "2darray"; break;
1811 case ac_image_2dmsaa: dimname = "2dmsaa"; break;
1812 case ac_image_2darraymsaa: dimname = "2darraymsaa"; break;
1813 default: unreachable("invalid dim");
1814 }
1815
1816 bool lod_suffix =
1817 a->lod && (a->opcode == ac_image_sample || a->opcode == ac_image_gather4);
1818 char intr_name[96];
1819 snprintf(intr_name, sizeof(intr_name),
1820 "llvm.amdgcn.image.%s%s" /* base name */
1821 "%s%s%s" /* sample/gather modifiers */
1822 ".%s.%s%s%s%s", /* dimension and type overloads */
1823 name, atomic_subop,
1824 a->compare ? ".c" : "",
1825 a->bias ? ".b" :
1826 lod_suffix ? ".l" :
1827 a->derivs[0] ? ".d" :
1828 a->level_zero ? ".lz" : "",
1829 a->offset ? ".o" : "",
1830 dimname,
1831 atomic ? "i32" : "v4f32",
1832 overload[0], overload[1], overload[2]);
1833
1834 LLVMTypeRef retty;
1835 if (atomic)
1836 retty = ctx->i32;
1837 else if (a->opcode == ac_image_store || a->opcode == ac_image_store_mip)
1838 retty = ctx->voidt;
1839 else
1840 retty = ctx->v4f32;
1841
1842 LLVMValueRef result =
1843 ac_build_intrinsic(ctx, intr_name, retty, args, num_args,
1844 a->attributes);
1845 if (!sample && retty == ctx->v4f32) {
1846 result = LLVMBuildBitCast(ctx->builder, result,
1847 ctx->v4i32, "");
1848 }
1849 return result;
1850 }
1851
1852 LLVMValueRef ac_build_cvt_pkrtz_f16(struct ac_llvm_context *ctx,
1853 LLVMValueRef args[2])
1854 {
1855 LLVMTypeRef v2f16 =
1856 LLVMVectorType(LLVMHalfTypeInContext(ctx->context), 2);
1857
1858 return ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pkrtz", v2f16,
1859 args, 2, AC_FUNC_ATTR_READNONE);
1860 }
1861
1862 LLVMValueRef ac_build_cvt_pknorm_i16(struct ac_llvm_context *ctx,
1863 LLVMValueRef args[2])
1864 {
1865 LLVMValueRef res =
1866 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.i16",
1867 ctx->v2i16, args, 2,
1868 AC_FUNC_ATTR_READNONE);
1869 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
1870 }
1871
1872 LLVMValueRef ac_build_cvt_pknorm_u16(struct ac_llvm_context *ctx,
1873 LLVMValueRef args[2])
1874 {
1875 LLVMValueRef res =
1876 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.u16",
1877 ctx->v2i16, args, 2,
1878 AC_FUNC_ATTR_READNONE);
1879 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
1880 }
1881
1882 /* The 8-bit and 10-bit clamping is for HW workarounds. */
1883 LLVMValueRef ac_build_cvt_pk_i16(struct ac_llvm_context *ctx,
1884 LLVMValueRef args[2], unsigned bits, bool hi)
1885 {
1886 assert(bits == 8 || bits == 10 || bits == 16);
1887
1888 LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
1889 bits == 8 ? 127 : bits == 10 ? 511 : 32767, 0);
1890 LLVMValueRef min_rgb = LLVMConstInt(ctx->i32,
1891 bits == 8 ? -128 : bits == 10 ? -512 : -32768, 0);
1892 LLVMValueRef max_alpha =
1893 bits != 10 ? max_rgb : ctx->i32_1;
1894 LLVMValueRef min_alpha =
1895 bits != 10 ? min_rgb : LLVMConstInt(ctx->i32, -2, 0);
1896
1897 /* Clamp. */
1898 if (bits != 16) {
1899 for (int i = 0; i < 2; i++) {
1900 bool alpha = hi && i == 1;
1901 args[i] = ac_build_imin(ctx, args[i],
1902 alpha ? max_alpha : max_rgb);
1903 args[i] = ac_build_imax(ctx, args[i],
1904 alpha ? min_alpha : min_rgb);
1905 }
1906 }
1907
1908 LLVMValueRef res =
1909 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.i16",
1910 ctx->v2i16, args, 2,
1911 AC_FUNC_ATTR_READNONE);
1912 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
1913 }
1914
1915 /* The 8-bit and 10-bit clamping is for HW workarounds. */
1916 LLVMValueRef ac_build_cvt_pk_u16(struct ac_llvm_context *ctx,
1917 LLVMValueRef args[2], unsigned bits, bool hi)
1918 {
1919 assert(bits == 8 || bits == 10 || bits == 16);
1920
1921 LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
1922 bits == 8 ? 255 : bits == 10 ? 1023 : 65535, 0);
1923 LLVMValueRef max_alpha =
1924 bits != 10 ? max_rgb : LLVMConstInt(ctx->i32, 3, 0);
1925
1926 /* Clamp. */
1927 if (bits != 16) {
1928 for (int i = 0; i < 2; i++) {
1929 bool alpha = hi && i == 1;
1930 args[i] = ac_build_umin(ctx, args[i],
1931 alpha ? max_alpha : max_rgb);
1932 }
1933 }
1934
1935 LLVMValueRef res =
1936 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.u16",
1937 ctx->v2i16, args, 2,
1938 AC_FUNC_ATTR_READNONE);
1939 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
1940 }
1941
1942 LLVMValueRef ac_build_wqm_vote(struct ac_llvm_context *ctx, LLVMValueRef i1)
1943 {
1944 return ac_build_intrinsic(ctx, "llvm.amdgcn.wqm.vote", ctx->i1,
1945 &i1, 1, AC_FUNC_ATTR_READNONE);
1946 }
1947
1948 void ac_build_kill_if_false(struct ac_llvm_context *ctx, LLVMValueRef i1)
1949 {
1950 ac_build_intrinsic(ctx, "llvm.amdgcn.kill", ctx->voidt,
1951 &i1, 1, 0);
1952 }
1953
1954 LLVMValueRef ac_build_bfe(struct ac_llvm_context *ctx, LLVMValueRef input,
1955 LLVMValueRef offset, LLVMValueRef width,
1956 bool is_signed)
1957 {
1958 LLVMValueRef args[] = {
1959 input,
1960 offset,
1961 width,
1962 };
1963
1964 return ac_build_intrinsic(ctx,
1965 is_signed ? "llvm.amdgcn.sbfe.i32" :
1966 "llvm.amdgcn.ubfe.i32",
1967 ctx->i32, args, 3,
1968 AC_FUNC_ATTR_READNONE);
1969 }
1970
1971 LLVMValueRef ac_build_imad(struct ac_llvm_context *ctx, LLVMValueRef s0,
1972 LLVMValueRef s1, LLVMValueRef s2)
1973 {
1974 return LLVMBuildAdd(ctx->builder,
1975 LLVMBuildMul(ctx->builder, s0, s1, ""), s2, "");
1976 }
1977
1978 LLVMValueRef ac_build_fmad(struct ac_llvm_context *ctx, LLVMValueRef s0,
1979 LLVMValueRef s1, LLVMValueRef s2)
1980 {
1981 return LLVMBuildFAdd(ctx->builder,
1982 LLVMBuildFMul(ctx->builder, s0, s1, ""), s2, "");
1983 }
1984
1985 void ac_build_waitcnt(struct ac_llvm_context *ctx, unsigned simm16)
1986 {
1987 LLVMValueRef args[1] = {
1988 LLVMConstInt(ctx->i32, simm16, false),
1989 };
1990 ac_build_intrinsic(ctx, "llvm.amdgcn.s.waitcnt",
1991 ctx->voidt, args, 1, 0);
1992 }
1993
1994 LLVMValueRef ac_build_fract(struct ac_llvm_context *ctx, LLVMValueRef src0,
1995 unsigned bitsize)
1996 {
1997 LLVMTypeRef type;
1998 char *intr;
1999
2000 if (bitsize == 32) {
2001 intr = "llvm.floor.f32";
2002 type = ctx->f32;
2003 } else {
2004 intr = "llvm.floor.f64";
2005 type = ctx->f64;
2006 }
2007
2008 LLVMValueRef params[] = {
2009 src0,
2010 };
2011 LLVMValueRef floor = ac_build_intrinsic(ctx, intr, type, params, 1,
2012 AC_FUNC_ATTR_READNONE);
2013 return LLVMBuildFSub(ctx->builder, src0, floor, "");
2014 }
2015
2016 LLVMValueRef ac_build_isign(struct ac_llvm_context *ctx, LLVMValueRef src0,
2017 unsigned bitsize)
2018 {
2019 LLVMValueRef cmp, val, zero, one;
2020 LLVMTypeRef type;
2021
2022 if (bitsize == 32) {
2023 type = ctx->i32;
2024 zero = ctx->i32_0;
2025 one = ctx->i32_1;
2026 } else {
2027 type = ctx->i64;
2028 zero = ctx->i64_0;
2029 one = ctx->i64_1;
2030 }
2031
2032 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, src0, zero, "");
2033 val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
2034 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGE, val, zero, "");
2035 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstInt(type, -1, true), "");
2036 return val;
2037 }
2038
2039 LLVMValueRef ac_build_fsign(struct ac_llvm_context *ctx, LLVMValueRef src0,
2040 unsigned bitsize)
2041 {
2042 LLVMValueRef cmp, val, zero, one;
2043 LLVMTypeRef type;
2044
2045 if (bitsize == 32) {
2046 type = ctx->f32;
2047 zero = ctx->f32_0;
2048 one = ctx->f32_1;
2049 } else {
2050 type = ctx->f64;
2051 zero = ctx->f64_0;
2052 one = ctx->f64_1;
2053 }
2054
2055 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGT, src0, zero, "");
2056 val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
2057 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGE, val, zero, "");
2058 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstReal(type, -1.0), "");
2059 return val;
2060 }
2061
2062 #define AC_EXP_TARGET 0
2063 #define AC_EXP_ENABLED_CHANNELS 1
2064 #define AC_EXP_OUT0 2
2065
2066 enum ac_ir_type {
2067 AC_IR_UNDEF,
2068 AC_IR_CONST,
2069 AC_IR_VALUE,
2070 };
2071
2072 struct ac_vs_exp_chan
2073 {
2074 LLVMValueRef value;
2075 float const_float;
2076 enum ac_ir_type type;
2077 };
2078
2079 struct ac_vs_exp_inst {
2080 unsigned offset;
2081 LLVMValueRef inst;
2082 struct ac_vs_exp_chan chan[4];
2083 };
2084
2085 struct ac_vs_exports {
2086 unsigned num;
2087 struct ac_vs_exp_inst exp[VARYING_SLOT_MAX];
2088 };
2089
2090 /* Return true if the PARAM export has been eliminated. */
2091 static bool ac_eliminate_const_output(uint8_t *vs_output_param_offset,
2092 uint32_t num_outputs,
2093 struct ac_vs_exp_inst *exp)
2094 {
2095 unsigned i, default_val; /* SPI_PS_INPUT_CNTL_i.DEFAULT_VAL */
2096 bool is_zero[4] = {}, is_one[4] = {};
2097
2098 for (i = 0; i < 4; i++) {
2099 /* It's a constant expression. Undef outputs are eliminated too. */
2100 if (exp->chan[i].type == AC_IR_UNDEF) {
2101 is_zero[i] = true;
2102 is_one[i] = true;
2103 } else if (exp->chan[i].type == AC_IR_CONST) {
2104 if (exp->chan[i].const_float == 0)
2105 is_zero[i] = true;
2106 else if (exp->chan[i].const_float == 1)
2107 is_one[i] = true;
2108 else
2109 return false; /* other constant */
2110 } else
2111 return false;
2112 }
2113
2114 /* Only certain combinations of 0 and 1 can be eliminated. */
2115 if (is_zero[0] && is_zero[1] && is_zero[2])
2116 default_val = is_zero[3] ? 0 : 1;
2117 else if (is_one[0] && is_one[1] && is_one[2])
2118 default_val = is_zero[3] ? 2 : 3;
2119 else
2120 return false;
2121
2122 /* The PARAM export can be represented as DEFAULT_VAL. Kill it. */
2123 LLVMInstructionEraseFromParent(exp->inst);
2124
2125 /* Change OFFSET to DEFAULT_VAL. */
2126 for (i = 0; i < num_outputs; i++) {
2127 if (vs_output_param_offset[i] == exp->offset) {
2128 vs_output_param_offset[i] =
2129 AC_EXP_PARAM_DEFAULT_VAL_0000 + default_val;
2130 break;
2131 }
2132 }
2133 return true;
2134 }
2135
2136 static bool ac_eliminate_duplicated_output(struct ac_llvm_context *ctx,
2137 uint8_t *vs_output_param_offset,
2138 uint32_t num_outputs,
2139 struct ac_vs_exports *processed,
2140 struct ac_vs_exp_inst *exp)
2141 {
2142 unsigned p, copy_back_channels = 0;
2143
2144 /* See if the output is already in the list of processed outputs.
2145 * The LLVMValueRef comparison relies on SSA.
2146 */
2147 for (p = 0; p < processed->num; p++) {
2148 bool different = false;
2149
2150 for (unsigned j = 0; j < 4; j++) {
2151 struct ac_vs_exp_chan *c1 = &processed->exp[p].chan[j];
2152 struct ac_vs_exp_chan *c2 = &exp->chan[j];
2153
2154 /* Treat undef as a match. */
2155 if (c2->type == AC_IR_UNDEF)
2156 continue;
2157
2158 /* If c1 is undef but c2 isn't, we can copy c2 to c1
2159 * and consider the instruction duplicated.
2160 */
2161 if (c1->type == AC_IR_UNDEF) {
2162 copy_back_channels |= 1 << j;
2163 continue;
2164 }
2165
2166 /* Test whether the channels are not equal. */
2167 if (c1->type != c2->type ||
2168 (c1->type == AC_IR_CONST &&
2169 c1->const_float != c2->const_float) ||
2170 (c1->type == AC_IR_VALUE &&
2171 c1->value != c2->value)) {
2172 different = true;
2173 break;
2174 }
2175 }
2176 if (!different)
2177 break;
2178
2179 copy_back_channels = 0;
2180 }
2181 if (p == processed->num)
2182 return false;
2183
2184 /* If a match was found, but the matching export has undef where the new
2185 * one has a normal value, copy the normal value to the undef channel.
2186 */
2187 struct ac_vs_exp_inst *match = &processed->exp[p];
2188
2189 /* Get current enabled channels mask. */
2190 LLVMValueRef arg = LLVMGetOperand(match->inst, AC_EXP_ENABLED_CHANNELS);
2191 unsigned enabled_channels = LLVMConstIntGetZExtValue(arg);
2192
2193 while (copy_back_channels) {
2194 unsigned chan = u_bit_scan(&copy_back_channels);
2195
2196 assert(match->chan[chan].type == AC_IR_UNDEF);
2197 LLVMSetOperand(match->inst, AC_EXP_OUT0 + chan,
2198 exp->chan[chan].value);
2199 match->chan[chan] = exp->chan[chan];
2200
2201 /* Update number of enabled channels because the original mask
2202 * is not always 0xf.
2203 */
2204 enabled_channels |= (1 << chan);
2205 LLVMSetOperand(match->inst, AC_EXP_ENABLED_CHANNELS,
2206 LLVMConstInt(ctx->i32, enabled_channels, 0));
2207 }
2208
2209 /* The PARAM export is duplicated. Kill it. */
2210 LLVMInstructionEraseFromParent(exp->inst);
2211
2212 /* Change OFFSET to the matching export. */
2213 for (unsigned i = 0; i < num_outputs; i++) {
2214 if (vs_output_param_offset[i] == exp->offset) {
2215 vs_output_param_offset[i] = match->offset;
2216 break;
2217 }
2218 }
2219 return true;
2220 }
2221
2222 void ac_optimize_vs_outputs(struct ac_llvm_context *ctx,
2223 LLVMValueRef main_fn,
2224 uint8_t *vs_output_param_offset,
2225 uint32_t num_outputs,
2226 uint8_t *num_param_exports)
2227 {
2228 LLVMBasicBlockRef bb;
2229 bool removed_any = false;
2230 struct ac_vs_exports exports;
2231
2232 exports.num = 0;
2233
2234 /* Process all LLVM instructions. */
2235 bb = LLVMGetFirstBasicBlock(main_fn);
2236 while (bb) {
2237 LLVMValueRef inst = LLVMGetFirstInstruction(bb);
2238
2239 while (inst) {
2240 LLVMValueRef cur = inst;
2241 inst = LLVMGetNextInstruction(inst);
2242 struct ac_vs_exp_inst exp;
2243
2244 if (LLVMGetInstructionOpcode(cur) != LLVMCall)
2245 continue;
2246
2247 LLVMValueRef callee = ac_llvm_get_called_value(cur);
2248
2249 if (!ac_llvm_is_function(callee))
2250 continue;
2251
2252 const char *name = LLVMGetValueName(callee);
2253 unsigned num_args = LLVMCountParams(callee);
2254
2255 /* Check if this is an export instruction. */
2256 if ((num_args != 9 && num_args != 8) ||
2257 (strcmp(name, "llvm.SI.export") &&
2258 strcmp(name, "llvm.amdgcn.exp.f32")))
2259 continue;
2260
2261 LLVMValueRef arg = LLVMGetOperand(cur, AC_EXP_TARGET);
2262 unsigned target = LLVMConstIntGetZExtValue(arg);
2263
2264 if (target < V_008DFC_SQ_EXP_PARAM)
2265 continue;
2266
2267 target -= V_008DFC_SQ_EXP_PARAM;
2268
2269 /* Parse the instruction. */
2270 memset(&exp, 0, sizeof(exp));
2271 exp.offset = target;
2272 exp.inst = cur;
2273
2274 for (unsigned i = 0; i < 4; i++) {
2275 LLVMValueRef v = LLVMGetOperand(cur, AC_EXP_OUT0 + i);
2276
2277 exp.chan[i].value = v;
2278
2279 if (LLVMIsUndef(v)) {
2280 exp.chan[i].type = AC_IR_UNDEF;
2281 } else if (LLVMIsAConstantFP(v)) {
2282 LLVMBool loses_info;
2283 exp.chan[i].type = AC_IR_CONST;
2284 exp.chan[i].const_float =
2285 LLVMConstRealGetDouble(v, &loses_info);
2286 } else {
2287 exp.chan[i].type = AC_IR_VALUE;
2288 }
2289 }
2290
2291 /* Eliminate constant and duplicated PARAM exports. */
2292 if (ac_eliminate_const_output(vs_output_param_offset,
2293 num_outputs, &exp) ||
2294 ac_eliminate_duplicated_output(ctx,
2295 vs_output_param_offset,
2296 num_outputs, &exports,
2297 &exp)) {
2298 removed_any = true;
2299 } else {
2300 exports.exp[exports.num++] = exp;
2301 }
2302 }
2303 bb = LLVMGetNextBasicBlock(bb);
2304 }
2305
2306 /* Remove holes in export memory due to removed PARAM exports.
2307 * This is done by renumbering all PARAM exports.
2308 */
2309 if (removed_any) {
2310 uint8_t old_offset[VARYING_SLOT_MAX];
2311 unsigned out, i;
2312
2313 /* Make a copy of the offsets. We need the old version while
2314 * we are modifying some of them. */
2315 memcpy(old_offset, vs_output_param_offset,
2316 sizeof(old_offset));
2317
2318 for (i = 0; i < exports.num; i++) {
2319 unsigned offset = exports.exp[i].offset;
2320
2321 /* Update vs_output_param_offset. Multiple outputs can
2322 * have the same offset.
2323 */
2324 for (out = 0; out < num_outputs; out++) {
2325 if (old_offset[out] == offset)
2326 vs_output_param_offset[out] = i;
2327 }
2328
2329 /* Change the PARAM offset in the instruction. */
2330 LLVMSetOperand(exports.exp[i].inst, AC_EXP_TARGET,
2331 LLVMConstInt(ctx->i32,
2332 V_008DFC_SQ_EXP_PARAM + i, 0));
2333 }
2334 *num_param_exports = exports.num;
2335 }
2336 }
2337
2338 void ac_init_exec_full_mask(struct ac_llvm_context *ctx)
2339 {
2340 LLVMValueRef full_mask = LLVMConstInt(ctx->i64, ~0ull, 0);
2341 ac_build_intrinsic(ctx,
2342 "llvm.amdgcn.init.exec", ctx->voidt,
2343 &full_mask, 1, AC_FUNC_ATTR_CONVERGENT);
2344 }
2345
2346 void ac_declare_lds_as_pointer(struct ac_llvm_context *ctx)
2347 {
2348 unsigned lds_size = ctx->chip_class >= CIK ? 65536 : 32768;
2349 ctx->lds = LLVMBuildIntToPtr(ctx->builder, ctx->i32_0,
2350 LLVMPointerType(LLVMArrayType(ctx->i32, lds_size / 4), AC_LOCAL_ADDR_SPACE),
2351 "lds");
2352 }
2353
2354 LLVMValueRef ac_lds_load(struct ac_llvm_context *ctx,
2355 LLVMValueRef dw_addr)
2356 {
2357 return ac_build_load(ctx, ctx->lds, dw_addr);
2358 }
2359
2360 void ac_lds_store(struct ac_llvm_context *ctx,
2361 LLVMValueRef dw_addr,
2362 LLVMValueRef value)
2363 {
2364 value = ac_to_integer(ctx, value);
2365 ac_build_indexed_store(ctx, ctx->lds,
2366 dw_addr, value);
2367 }
2368
2369 LLVMValueRef ac_find_lsb(struct ac_llvm_context *ctx,
2370 LLVMTypeRef dst_type,
2371 LLVMValueRef src0)
2372 {
2373 unsigned src0_bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
2374 const char *intrin_name;
2375 LLVMTypeRef type;
2376 LLVMValueRef zero;
2377 if (src0_bitsize == 64) {
2378 intrin_name = "llvm.cttz.i64";
2379 type = ctx->i64;
2380 zero = ctx->i64_0;
2381 } else {
2382 intrin_name = "llvm.cttz.i32";
2383 type = ctx->i32;
2384 zero = ctx->i32_0;
2385 }
2386
2387 LLVMValueRef params[2] = {
2388 src0,
2389
2390 /* The value of 1 means that ffs(x=0) = undef, so LLVM won't
2391 * add special code to check for x=0. The reason is that
2392 * the LLVM behavior for x=0 is different from what we
2393 * need here. However, LLVM also assumes that ffs(x) is
2394 * in [0, 31], but GLSL expects that ffs(0) = -1, so
2395 * a conditional assignment to handle 0 is still required.
2396 *
2397 * The hardware already implements the correct behavior.
2398 */
2399 LLVMConstInt(ctx->i1, 1, false),
2400 };
2401
2402 LLVMValueRef lsb = ac_build_intrinsic(ctx, intrin_name, type,
2403 params, 2,
2404 AC_FUNC_ATTR_READNONE);
2405
2406 if (src0_bitsize == 64) {
2407 lsb = LLVMBuildTrunc(ctx->builder, lsb, ctx->i32, "");
2408 }
2409
2410 /* TODO: We need an intrinsic to skip this conditional. */
2411 /* Check for zero: */
2412 return LLVMBuildSelect(ctx->builder, LLVMBuildICmp(ctx->builder,
2413 LLVMIntEQ, src0,
2414 zero, ""),
2415 LLVMConstInt(ctx->i32, -1, 0), lsb, "");
2416 }
2417
2418 LLVMTypeRef ac_array_in_const_addr_space(LLVMTypeRef elem_type)
2419 {
2420 return LLVMPointerType(LLVMArrayType(elem_type, 0),
2421 AC_CONST_ADDR_SPACE);
2422 }
2423
2424 LLVMTypeRef ac_array_in_const32_addr_space(LLVMTypeRef elem_type)
2425 {
2426 if (!HAVE_32BIT_POINTERS)
2427 return ac_array_in_const_addr_space(elem_type);
2428
2429 return LLVMPointerType(LLVMArrayType(elem_type, 0),
2430 AC_CONST_32BIT_ADDR_SPACE);
2431 }
2432
2433 static struct ac_llvm_flow *
2434 get_current_flow(struct ac_llvm_context *ctx)
2435 {
2436 if (ctx->flow_depth > 0)
2437 return &ctx->flow[ctx->flow_depth - 1];
2438 return NULL;
2439 }
2440
2441 static struct ac_llvm_flow *
2442 get_innermost_loop(struct ac_llvm_context *ctx)
2443 {
2444 for (unsigned i = ctx->flow_depth; i > 0; --i) {
2445 if (ctx->flow[i - 1].loop_entry_block)
2446 return &ctx->flow[i - 1];
2447 }
2448 return NULL;
2449 }
2450
2451 static struct ac_llvm_flow *
2452 push_flow(struct ac_llvm_context *ctx)
2453 {
2454 struct ac_llvm_flow *flow;
2455
2456 if (ctx->flow_depth >= ctx->flow_depth_max) {
2457 unsigned new_max = MAX2(ctx->flow_depth << 1,
2458 AC_LLVM_INITIAL_CF_DEPTH);
2459
2460 ctx->flow = realloc(ctx->flow, new_max * sizeof(*ctx->flow));
2461 ctx->flow_depth_max = new_max;
2462 }
2463
2464 flow = &ctx->flow[ctx->flow_depth];
2465 ctx->flow_depth++;
2466
2467 flow->next_block = NULL;
2468 flow->loop_entry_block = NULL;
2469 return flow;
2470 }
2471
2472 static void set_basicblock_name(LLVMBasicBlockRef bb, const char *base,
2473 int label_id)
2474 {
2475 char buf[32];
2476 snprintf(buf, sizeof(buf), "%s%d", base, label_id);
2477 LLVMSetValueName(LLVMBasicBlockAsValue(bb), buf);
2478 }
2479
2480 /* Append a basic block at the level of the parent flow.
2481 */
2482 static LLVMBasicBlockRef append_basic_block(struct ac_llvm_context *ctx,
2483 const char *name)
2484 {
2485 assert(ctx->flow_depth >= 1);
2486
2487 if (ctx->flow_depth >= 2) {
2488 struct ac_llvm_flow *flow = &ctx->flow[ctx->flow_depth - 2];
2489
2490 return LLVMInsertBasicBlockInContext(ctx->context,
2491 flow->next_block, name);
2492 }
2493
2494 LLVMValueRef main_fn =
2495 LLVMGetBasicBlockParent(LLVMGetInsertBlock(ctx->builder));
2496 return LLVMAppendBasicBlockInContext(ctx->context, main_fn, name);
2497 }
2498
2499 /* Emit a branch to the given default target for the current block if
2500 * applicable -- that is, if the current block does not already contain a
2501 * branch from a break or continue.
2502 */
2503 static void emit_default_branch(LLVMBuilderRef builder,
2504 LLVMBasicBlockRef target)
2505 {
2506 if (!LLVMGetBasicBlockTerminator(LLVMGetInsertBlock(builder)))
2507 LLVMBuildBr(builder, target);
2508 }
2509
2510 void ac_build_bgnloop(struct ac_llvm_context *ctx, int label_id)
2511 {
2512 struct ac_llvm_flow *flow = push_flow(ctx);
2513 flow->loop_entry_block = append_basic_block(ctx, "LOOP");
2514 flow->next_block = append_basic_block(ctx, "ENDLOOP");
2515 set_basicblock_name(flow->loop_entry_block, "loop", label_id);
2516 LLVMBuildBr(ctx->builder, flow->loop_entry_block);
2517 LLVMPositionBuilderAtEnd(ctx->builder, flow->loop_entry_block);
2518 }
2519
2520 void ac_build_break(struct ac_llvm_context *ctx)
2521 {
2522 struct ac_llvm_flow *flow = get_innermost_loop(ctx);
2523 LLVMBuildBr(ctx->builder, flow->next_block);
2524 }
2525
2526 void ac_build_continue(struct ac_llvm_context *ctx)
2527 {
2528 struct ac_llvm_flow *flow = get_innermost_loop(ctx);
2529 LLVMBuildBr(ctx->builder, flow->loop_entry_block);
2530 }
2531
2532 void ac_build_else(struct ac_llvm_context *ctx, int label_id)
2533 {
2534 struct ac_llvm_flow *current_branch = get_current_flow(ctx);
2535 LLVMBasicBlockRef endif_block;
2536
2537 assert(!current_branch->loop_entry_block);
2538
2539 endif_block = append_basic_block(ctx, "ENDIF");
2540 emit_default_branch(ctx->builder, endif_block);
2541
2542 LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
2543 set_basicblock_name(current_branch->next_block, "else", label_id);
2544
2545 current_branch->next_block = endif_block;
2546 }
2547
2548 void ac_build_endif(struct ac_llvm_context *ctx, int label_id)
2549 {
2550 struct ac_llvm_flow *current_branch = get_current_flow(ctx);
2551
2552 assert(!current_branch->loop_entry_block);
2553
2554 emit_default_branch(ctx->builder, current_branch->next_block);
2555 LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
2556 set_basicblock_name(current_branch->next_block, "endif", label_id);
2557
2558 ctx->flow_depth--;
2559 }
2560
2561 void ac_build_endloop(struct ac_llvm_context *ctx, int label_id)
2562 {
2563 struct ac_llvm_flow *current_loop = get_current_flow(ctx);
2564
2565 assert(current_loop->loop_entry_block);
2566
2567 emit_default_branch(ctx->builder, current_loop->loop_entry_block);
2568
2569 LLVMPositionBuilderAtEnd(ctx->builder, current_loop->next_block);
2570 set_basicblock_name(current_loop->next_block, "endloop", label_id);
2571 ctx->flow_depth--;
2572 }
2573
2574 static void if_cond_emit(struct ac_llvm_context *ctx, LLVMValueRef cond,
2575 int label_id)
2576 {
2577 struct ac_llvm_flow *flow = push_flow(ctx);
2578 LLVMBasicBlockRef if_block;
2579
2580 if_block = append_basic_block(ctx, "IF");
2581 flow->next_block = append_basic_block(ctx, "ELSE");
2582 set_basicblock_name(if_block, "if", label_id);
2583 LLVMBuildCondBr(ctx->builder, cond, if_block, flow->next_block);
2584 LLVMPositionBuilderAtEnd(ctx->builder, if_block);
2585 }
2586
2587 void ac_build_if(struct ac_llvm_context *ctx, LLVMValueRef value,
2588 int label_id)
2589 {
2590 LLVMValueRef cond = LLVMBuildFCmp(ctx->builder, LLVMRealUNE,
2591 value, ctx->f32_0, "");
2592 if_cond_emit(ctx, cond, label_id);
2593 }
2594
2595 void ac_build_uif(struct ac_llvm_context *ctx, LLVMValueRef value,
2596 int label_id)
2597 {
2598 LLVMValueRef cond = LLVMBuildICmp(ctx->builder, LLVMIntNE,
2599 ac_to_integer(ctx, value),
2600 ctx->i32_0, "");
2601 if_cond_emit(ctx, cond, label_id);
2602 }
2603
2604 LLVMValueRef ac_build_alloca(struct ac_llvm_context *ac, LLVMTypeRef type,
2605 const char *name)
2606 {
2607 LLVMBuilderRef builder = ac->builder;
2608 LLVMBasicBlockRef current_block = LLVMGetInsertBlock(builder);
2609 LLVMValueRef function = LLVMGetBasicBlockParent(current_block);
2610 LLVMBasicBlockRef first_block = LLVMGetEntryBasicBlock(function);
2611 LLVMValueRef first_instr = LLVMGetFirstInstruction(first_block);
2612 LLVMBuilderRef first_builder = LLVMCreateBuilderInContext(ac->context);
2613 LLVMValueRef res;
2614
2615 if (first_instr) {
2616 LLVMPositionBuilderBefore(first_builder, first_instr);
2617 } else {
2618 LLVMPositionBuilderAtEnd(first_builder, first_block);
2619 }
2620
2621 res = LLVMBuildAlloca(first_builder, type, name);
2622 LLVMBuildStore(builder, LLVMConstNull(type), res);
2623
2624 LLVMDisposeBuilder(first_builder);
2625
2626 return res;
2627 }
2628
2629 LLVMValueRef ac_build_alloca_undef(struct ac_llvm_context *ac,
2630 LLVMTypeRef type, const char *name)
2631 {
2632 LLVMValueRef ptr = ac_build_alloca(ac, type, name);
2633 LLVMBuildStore(ac->builder, LLVMGetUndef(type), ptr);
2634 return ptr;
2635 }
2636
2637 LLVMValueRef ac_cast_ptr(struct ac_llvm_context *ctx, LLVMValueRef ptr,
2638 LLVMTypeRef type)
2639 {
2640 int addr_space = LLVMGetPointerAddressSpace(LLVMTypeOf(ptr));
2641 return LLVMBuildBitCast(ctx->builder, ptr,
2642 LLVMPointerType(type, addr_space), "");
2643 }
2644
2645 LLVMValueRef ac_trim_vector(struct ac_llvm_context *ctx, LLVMValueRef value,
2646 unsigned count)
2647 {
2648 unsigned num_components = ac_get_llvm_num_components(value);
2649 if (count == num_components)
2650 return value;
2651
2652 LLVMValueRef masks[] = {
2653 LLVMConstInt(ctx->i32, 0, false), LLVMConstInt(ctx->i32, 1, false),
2654 LLVMConstInt(ctx->i32, 2, false), LLVMConstInt(ctx->i32, 3, false)};
2655
2656 if (count == 1)
2657 return LLVMBuildExtractElement(ctx->builder, value, masks[0],
2658 "");
2659
2660 LLVMValueRef swizzle = LLVMConstVector(masks, count);
2661 return LLVMBuildShuffleVector(ctx->builder, value, value, swizzle, "");
2662 }
2663
2664 LLVMValueRef ac_unpack_param(struct ac_llvm_context *ctx, LLVMValueRef param,
2665 unsigned rshift, unsigned bitwidth)
2666 {
2667 LLVMValueRef value = param;
2668 if (rshift)
2669 value = LLVMBuildLShr(ctx->builder, value,
2670 LLVMConstInt(ctx->i32, rshift, false), "");
2671
2672 if (rshift + bitwidth < 32) {
2673 unsigned mask = (1 << bitwidth) - 1;
2674 value = LLVMBuildAnd(ctx->builder, value,
2675 LLVMConstInt(ctx->i32, mask, false), "");
2676 }
2677 return value;
2678 }
2679
2680 /* Adjust the sample index according to FMASK.
2681 *
2682 * For uncompressed MSAA surfaces, FMASK should return 0x76543210,
2683 * which is the identity mapping. Each nibble says which physical sample
2684 * should be fetched to get that sample.
2685 *
2686 * For example, 0x11111100 means there are only 2 samples stored and
2687 * the second sample covers 3/4 of the pixel. When reading samples 0
2688 * and 1, return physical sample 0 (determined by the first two 0s
2689 * in FMASK), otherwise return physical sample 1.
2690 *
2691 * The sample index should be adjusted as follows:
2692 * addr[sample_index] = (fmask >> (addr[sample_index] * 4)) & 0xF;
2693 */
2694 void ac_apply_fmask_to_sample(struct ac_llvm_context *ac, LLVMValueRef fmask,
2695 LLVMValueRef *addr, bool is_array_tex)
2696 {
2697 struct ac_image_args fmask_load = {};
2698 fmask_load.opcode = ac_image_load;
2699 fmask_load.resource = fmask;
2700 fmask_load.dmask = 0xf;
2701 fmask_load.dim = is_array_tex ? ac_image_2darray : ac_image_2d;
2702
2703 fmask_load.coords[0] = addr[0];
2704 fmask_load.coords[1] = addr[1];
2705 if (is_array_tex)
2706 fmask_load.coords[2] = addr[2];
2707
2708 LLVMValueRef fmask_value = ac_build_image_opcode(ac, &fmask_load);
2709 fmask_value = LLVMBuildExtractElement(ac->builder, fmask_value,
2710 ac->i32_0, "");
2711
2712 /* Apply the formula. */
2713 unsigned sample_chan = is_array_tex ? 3 : 2;
2714 LLVMValueRef final_sample;
2715 final_sample = LLVMBuildMul(ac->builder, addr[sample_chan],
2716 LLVMConstInt(ac->i32, 4, 0), "");
2717 final_sample = LLVMBuildLShr(ac->builder, fmask_value, final_sample, "");
2718 /* Mask the sample index by 0x7, because 0x8 means an unknown value
2719 * with EQAA, so those will map to 0. */
2720 final_sample = LLVMBuildAnd(ac->builder, final_sample,
2721 LLVMConstInt(ac->i32, 0x7, 0), "");
2722
2723 /* Don't rewrite the sample index if WORD1.DATA_FORMAT of the FMASK
2724 * resource descriptor is 0 (invalid).
2725 */
2726 LLVMValueRef tmp;
2727 tmp = LLVMBuildBitCast(ac->builder, fmask, ac->v8i32, "");
2728 tmp = LLVMBuildExtractElement(ac->builder, tmp, ac->i32_1, "");
2729 tmp = LLVMBuildICmp(ac->builder, LLVMIntNE, tmp, ac->i32_0, "");
2730
2731 /* Replace the MSAA sample index. */
2732 addr[sample_chan] = LLVMBuildSelect(ac->builder, tmp, final_sample,
2733 addr[sample_chan], "");
2734 }
2735
2736 static LLVMValueRef
2737 _ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef lane)
2738 {
2739 ac_build_optimization_barrier(ctx, &src);
2740 return ac_build_intrinsic(ctx,
2741 lane == NULL ? "llvm.amdgcn.readfirstlane" : "llvm.amdgcn.readlane",
2742 LLVMTypeOf(src), (LLVMValueRef []) {
2743 src, lane },
2744 lane == NULL ? 1 : 2,
2745 AC_FUNC_ATTR_READNONE |
2746 AC_FUNC_ATTR_CONVERGENT);
2747 }
2748
2749 /**
2750 * Builds the "llvm.amdgcn.readlane" or "llvm.amdgcn.readfirstlane" intrinsic.
2751 * @param ctx
2752 * @param src
2753 * @param lane - id of the lane or NULL for the first active lane
2754 * @return value of the lane
2755 */
2756 LLVMValueRef
2757 ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef lane)
2758 {
2759 LLVMTypeRef src_type = LLVMTypeOf(src);
2760 src = ac_to_integer(ctx, src);
2761 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
2762 LLVMValueRef ret;
2763
2764 if (bits == 32) {
2765 ret = _ac_build_readlane(ctx, src, lane);
2766 } else {
2767 assert(bits % 32 == 0);
2768 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
2769 LLVMValueRef src_vector =
2770 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
2771 ret = LLVMGetUndef(vec_type);
2772 for (unsigned i = 0; i < bits / 32; i++) {
2773 src = LLVMBuildExtractElement(ctx->builder, src_vector,
2774 LLVMConstInt(ctx->i32, i, 0), "");
2775 LLVMValueRef ret_comp = _ac_build_readlane(ctx, src, lane);
2776 ret = LLVMBuildInsertElement(ctx->builder, ret, ret_comp,
2777 LLVMConstInt(ctx->i32, i, 0), "");
2778 }
2779 }
2780 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
2781 }
2782
2783 LLVMValueRef
2784 ac_build_writelane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef value, LLVMValueRef lane)
2785 {
2786 /* TODO: Use the actual instruction when LLVM adds an intrinsic for it.
2787 */
2788 LLVMValueRef pred = LLVMBuildICmp(ctx->builder, LLVMIntEQ, lane,
2789 ac_get_thread_id(ctx), "");
2790 return LLVMBuildSelect(ctx->builder, pred, value, src, "");
2791 }
2792
2793 LLVMValueRef
2794 ac_build_mbcnt(struct ac_llvm_context *ctx, LLVMValueRef mask)
2795 {
2796 LLVMValueRef mask_vec = LLVMBuildBitCast(ctx->builder, mask,
2797 LLVMVectorType(ctx->i32, 2),
2798 "");
2799 LLVMValueRef mask_lo = LLVMBuildExtractElement(ctx->builder, mask_vec,
2800 ctx->i32_0, "");
2801 LLVMValueRef mask_hi = LLVMBuildExtractElement(ctx->builder, mask_vec,
2802 ctx->i32_1, "");
2803 LLVMValueRef val =
2804 ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.lo", ctx->i32,
2805 (LLVMValueRef []) { mask_lo, ctx->i32_0 },
2806 2, AC_FUNC_ATTR_READNONE);
2807 val = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi", ctx->i32,
2808 (LLVMValueRef []) { mask_hi, val },
2809 2, AC_FUNC_ATTR_READNONE);
2810 return val;
2811 }
2812
2813 enum dpp_ctrl {
2814 _dpp_quad_perm = 0x000,
2815 _dpp_row_sl = 0x100,
2816 _dpp_row_sr = 0x110,
2817 _dpp_row_rr = 0x120,
2818 dpp_wf_sl1 = 0x130,
2819 dpp_wf_rl1 = 0x134,
2820 dpp_wf_sr1 = 0x138,
2821 dpp_wf_rr1 = 0x13C,
2822 dpp_row_mirror = 0x140,
2823 dpp_row_half_mirror = 0x141,
2824 dpp_row_bcast15 = 0x142,
2825 dpp_row_bcast31 = 0x143
2826 };
2827
2828 static inline enum dpp_ctrl
2829 dpp_quad_perm(unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
2830 {
2831 assert(lane0 < 4 && lane1 < 4 && lane2 < 4 && lane3 < 4);
2832 return _dpp_quad_perm | lane0 | (lane1 << 2) | (lane2 << 4) | (lane3 << 6);
2833 }
2834
2835 static inline enum dpp_ctrl
2836 dpp_row_sl(unsigned amount)
2837 {
2838 assert(amount > 0 && amount < 16);
2839 return _dpp_row_sl | amount;
2840 }
2841
2842 static inline enum dpp_ctrl
2843 dpp_row_sr(unsigned amount)
2844 {
2845 assert(amount > 0 && amount < 16);
2846 return _dpp_row_sr | amount;
2847 }
2848
2849 static LLVMValueRef
2850 _ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
2851 enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
2852 bool bound_ctrl)
2853 {
2854 return ac_build_intrinsic(ctx, "llvm.amdgcn.update.dpp.i32",
2855 LLVMTypeOf(old),
2856 (LLVMValueRef[]) {
2857 old, src,
2858 LLVMConstInt(ctx->i32, dpp_ctrl, 0),
2859 LLVMConstInt(ctx->i32, row_mask, 0),
2860 LLVMConstInt(ctx->i32, bank_mask, 0),
2861 LLVMConstInt(ctx->i1, bound_ctrl, 0) },
2862 6, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
2863 }
2864
2865 static LLVMValueRef
2866 ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
2867 enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
2868 bool bound_ctrl)
2869 {
2870 LLVMTypeRef src_type = LLVMTypeOf(src);
2871 src = ac_to_integer(ctx, src);
2872 old = ac_to_integer(ctx, old);
2873 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
2874 LLVMValueRef ret;
2875 if (bits == 32) {
2876 ret = _ac_build_dpp(ctx, old, src, dpp_ctrl, row_mask,
2877 bank_mask, bound_ctrl);
2878 } else {
2879 assert(bits % 32 == 0);
2880 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
2881 LLVMValueRef src_vector =
2882 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
2883 LLVMValueRef old_vector =
2884 LLVMBuildBitCast(ctx->builder, old, vec_type, "");
2885 ret = LLVMGetUndef(vec_type);
2886 for (unsigned i = 0; i < bits / 32; i++) {
2887 src = LLVMBuildExtractElement(ctx->builder, src_vector,
2888 LLVMConstInt(ctx->i32, i,
2889 0), "");
2890 old = LLVMBuildExtractElement(ctx->builder, old_vector,
2891 LLVMConstInt(ctx->i32, i,
2892 0), "");
2893 LLVMValueRef ret_comp = _ac_build_dpp(ctx, old, src,
2894 dpp_ctrl,
2895 row_mask,
2896 bank_mask,
2897 bound_ctrl);
2898 ret = LLVMBuildInsertElement(ctx->builder, ret,
2899 ret_comp,
2900 LLVMConstInt(ctx->i32, i,
2901 0), "");
2902 }
2903 }
2904 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
2905 }
2906
2907 static inline unsigned
2908 ds_pattern_bitmode(unsigned and_mask, unsigned or_mask, unsigned xor_mask)
2909 {
2910 assert(and_mask < 32 && or_mask < 32 && xor_mask < 32);
2911 return and_mask | (or_mask << 5) | (xor_mask << 10);
2912 }
2913
2914 static LLVMValueRef
2915 _ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
2916 {
2917 return ac_build_intrinsic(ctx, "llvm.amdgcn.ds.swizzle",
2918 LLVMTypeOf(src), (LLVMValueRef []) {
2919 src, LLVMConstInt(ctx->i32, mask, 0) },
2920 2, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
2921 }
2922
2923 LLVMValueRef
2924 ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
2925 {
2926 LLVMTypeRef src_type = LLVMTypeOf(src);
2927 src = ac_to_integer(ctx, src);
2928 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
2929 LLVMValueRef ret;
2930 if (bits == 32) {
2931 ret = _ac_build_ds_swizzle(ctx, src, mask);
2932 } else {
2933 assert(bits % 32 == 0);
2934 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
2935 LLVMValueRef src_vector =
2936 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
2937 ret = LLVMGetUndef(vec_type);
2938 for (unsigned i = 0; i < bits / 32; i++) {
2939 src = LLVMBuildExtractElement(ctx->builder, src_vector,
2940 LLVMConstInt(ctx->i32, i,
2941 0), "");
2942 LLVMValueRef ret_comp = _ac_build_ds_swizzle(ctx, src,
2943 mask);
2944 ret = LLVMBuildInsertElement(ctx->builder, ret,
2945 ret_comp,
2946 LLVMConstInt(ctx->i32, i,
2947 0), "");
2948 }
2949 }
2950 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
2951 }
2952
2953 static LLVMValueRef
2954 ac_build_wwm(struct ac_llvm_context *ctx, LLVMValueRef src)
2955 {
2956 char name[32], type[8];
2957 ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
2958 snprintf(name, sizeof(name), "llvm.amdgcn.wwm.%s", type);
2959 return ac_build_intrinsic(ctx, name, LLVMTypeOf(src),
2960 (LLVMValueRef []) { src }, 1,
2961 AC_FUNC_ATTR_READNONE);
2962 }
2963
2964 static LLVMValueRef
2965 ac_build_set_inactive(struct ac_llvm_context *ctx, LLVMValueRef src,
2966 LLVMValueRef inactive)
2967 {
2968 char name[33], type[8];
2969 LLVMTypeRef src_type = LLVMTypeOf(src);
2970 src = ac_to_integer(ctx, src);
2971 inactive = ac_to_integer(ctx, inactive);
2972 ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
2973 snprintf(name, sizeof(name), "llvm.amdgcn.set.inactive.%s", type);
2974 LLVMValueRef ret =
2975 ac_build_intrinsic(ctx, name,
2976 LLVMTypeOf(src), (LLVMValueRef []) {
2977 src, inactive }, 2,
2978 AC_FUNC_ATTR_READNONE |
2979 AC_FUNC_ATTR_CONVERGENT);
2980 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
2981 }
2982
2983 static LLVMValueRef
2984 get_reduction_identity(struct ac_llvm_context *ctx, nir_op op, unsigned type_size)
2985 {
2986 if (type_size == 4) {
2987 switch (op) {
2988 case nir_op_iadd: return ctx->i32_0;
2989 case nir_op_fadd: return ctx->f32_0;
2990 case nir_op_imul: return ctx->i32_1;
2991 case nir_op_fmul: return ctx->f32_1;
2992 case nir_op_imin: return LLVMConstInt(ctx->i32, INT32_MAX, 0);
2993 case nir_op_umin: return LLVMConstInt(ctx->i32, UINT32_MAX, 0);
2994 case nir_op_fmin: return LLVMConstReal(ctx->f32, INFINITY);
2995 case nir_op_imax: return LLVMConstInt(ctx->i32, INT32_MIN, 0);
2996 case nir_op_umax: return ctx->i32_0;
2997 case nir_op_fmax: return LLVMConstReal(ctx->f32, -INFINITY);
2998 case nir_op_iand: return LLVMConstInt(ctx->i32, -1, 0);
2999 case nir_op_ior: return ctx->i32_0;
3000 case nir_op_ixor: return ctx->i32_0;
3001 default:
3002 unreachable("bad reduction intrinsic");
3003 }
3004 } else { /* type_size == 64bit */
3005 switch (op) {
3006 case nir_op_iadd: return ctx->i64_0;
3007 case nir_op_fadd: return ctx->f64_0;
3008 case nir_op_imul: return ctx->i64_1;
3009 case nir_op_fmul: return ctx->f64_1;
3010 case nir_op_imin: return LLVMConstInt(ctx->i64, INT64_MAX, 0);
3011 case nir_op_umin: return LLVMConstInt(ctx->i64, UINT64_MAX, 0);
3012 case nir_op_fmin: return LLVMConstReal(ctx->f64, INFINITY);
3013 case nir_op_imax: return LLVMConstInt(ctx->i64, INT64_MIN, 0);
3014 case nir_op_umax: return ctx->i64_0;
3015 case nir_op_fmax: return LLVMConstReal(ctx->f64, -INFINITY);
3016 case nir_op_iand: return LLVMConstInt(ctx->i64, -1, 0);
3017 case nir_op_ior: return ctx->i64_0;
3018 case nir_op_ixor: return ctx->i64_0;
3019 default:
3020 unreachable("bad reduction intrinsic");
3021 }
3022 }
3023 }
3024
3025 static LLVMValueRef
3026 ac_build_alu_op(struct ac_llvm_context *ctx, LLVMValueRef lhs, LLVMValueRef rhs, nir_op op)
3027 {
3028 bool _64bit = ac_get_type_size(LLVMTypeOf(lhs)) == 8;
3029 switch (op) {
3030 case nir_op_iadd: return LLVMBuildAdd(ctx->builder, lhs, rhs, "");
3031 case nir_op_fadd: return LLVMBuildFAdd(ctx->builder, lhs, rhs, "");
3032 case nir_op_imul: return LLVMBuildMul(ctx->builder, lhs, rhs, "");
3033 case nir_op_fmul: return LLVMBuildFMul(ctx->builder, lhs, rhs, "");
3034 case nir_op_imin: return LLVMBuildSelect(ctx->builder,
3035 LLVMBuildICmp(ctx->builder, LLVMIntSLT, lhs, rhs, ""),
3036 lhs, rhs, "");
3037 case nir_op_umin: return LLVMBuildSelect(ctx->builder,
3038 LLVMBuildICmp(ctx->builder, LLVMIntULT, lhs, rhs, ""),
3039 lhs, rhs, "");
3040 case nir_op_fmin: return ac_build_intrinsic(ctx,
3041 _64bit ? "llvm.minnum.f64" : "llvm.minnum.f32",
3042 _64bit ? ctx->f64 : ctx->f32,
3043 (LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
3044 case nir_op_imax: return LLVMBuildSelect(ctx->builder,
3045 LLVMBuildICmp(ctx->builder, LLVMIntSGT, lhs, rhs, ""),
3046 lhs, rhs, "");
3047 case nir_op_umax: return LLVMBuildSelect(ctx->builder,
3048 LLVMBuildICmp(ctx->builder, LLVMIntUGT, lhs, rhs, ""),
3049 lhs, rhs, "");
3050 case nir_op_fmax: return ac_build_intrinsic(ctx,
3051 _64bit ? "llvm.maxnum.f64" : "llvm.maxnum.f32",
3052 _64bit ? ctx->f64 : ctx->f32,
3053 (LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
3054 case nir_op_iand: return LLVMBuildAnd(ctx->builder, lhs, rhs, "");
3055 case nir_op_ior: return LLVMBuildOr(ctx->builder, lhs, rhs, "");
3056 case nir_op_ixor: return LLVMBuildXor(ctx->builder, lhs, rhs, "");
3057 default:
3058 unreachable("bad reduction intrinsic");
3059 }
3060 }
3061
3062 /* TODO: add inclusive and excluse scan functions for SI chip class. */
3063 static LLVMValueRef
3064 ac_build_scan(struct ac_llvm_context *ctx, nir_op op, LLVMValueRef src, LLVMValueRef identity)
3065 {
3066 LLVMValueRef result, tmp;
3067 result = src;
3068 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(1), 0xf, 0xf, false);
3069 result = ac_build_alu_op(ctx, result, tmp, op);
3070 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(2), 0xf, 0xf, false);
3071 result = ac_build_alu_op(ctx, result, tmp, op);
3072 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(3), 0xf, 0xf, false);
3073 result = ac_build_alu_op(ctx, result, tmp, op);
3074 tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(4), 0xf, 0xe, false);
3075 result = ac_build_alu_op(ctx, result, tmp, op);
3076 tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(8), 0xf, 0xc, false);
3077 result = ac_build_alu_op(ctx, result, tmp, op);
3078 tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
3079 result = ac_build_alu_op(ctx, result, tmp, op);
3080 tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
3081 result = ac_build_alu_op(ctx, result, tmp, op);
3082 return result;
3083 }
3084
3085 LLVMValueRef
3086 ac_build_inclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
3087 {
3088 ac_build_optimization_barrier(ctx, &src);
3089 LLVMValueRef result;
3090 LLVMValueRef identity = get_reduction_identity(ctx, op,
3091 ac_get_type_size(LLVMTypeOf(src)));
3092 result = LLVMBuildBitCast(ctx->builder,
3093 ac_build_set_inactive(ctx, src, identity),
3094 LLVMTypeOf(identity), "");
3095 result = ac_build_scan(ctx, op, result, identity);
3096
3097 return ac_build_wwm(ctx, result);
3098 }
3099
3100 LLVMValueRef
3101 ac_build_exclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
3102 {
3103 ac_build_optimization_barrier(ctx, &src);
3104 LLVMValueRef result;
3105 LLVMValueRef identity = get_reduction_identity(ctx, op,
3106 ac_get_type_size(LLVMTypeOf(src)));
3107 result = LLVMBuildBitCast(ctx->builder,
3108 ac_build_set_inactive(ctx, src, identity),
3109 LLVMTypeOf(identity), "");
3110 result = ac_build_dpp(ctx, identity, result, dpp_wf_sr1, 0xf, 0xf, false);
3111 result = ac_build_scan(ctx, op, result, identity);
3112
3113 return ac_build_wwm(ctx, result);
3114 }
3115
3116 LLVMValueRef
3117 ac_build_reduce(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op, unsigned cluster_size)
3118 {
3119 if (cluster_size == 1) return src;
3120 ac_build_optimization_barrier(ctx, &src);
3121 LLVMValueRef result, swap;
3122 LLVMValueRef identity = get_reduction_identity(ctx, op,
3123 ac_get_type_size(LLVMTypeOf(src)));
3124 result = LLVMBuildBitCast(ctx->builder,
3125 ac_build_set_inactive(ctx, src, identity),
3126 LLVMTypeOf(identity), "");
3127 swap = ac_build_quad_swizzle(ctx, result, 1, 0, 3, 2);
3128 result = ac_build_alu_op(ctx, result, swap, op);
3129 if (cluster_size == 2) return ac_build_wwm(ctx, result);
3130
3131 swap = ac_build_quad_swizzle(ctx, result, 2, 3, 0, 1);
3132 result = ac_build_alu_op(ctx, result, swap, op);
3133 if (cluster_size == 4) return ac_build_wwm(ctx, result);
3134
3135 if (ctx->chip_class >= VI)
3136 swap = ac_build_dpp(ctx, identity, result, dpp_row_half_mirror, 0xf, 0xf, false);
3137 else
3138 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x04));
3139 result = ac_build_alu_op(ctx, result, swap, op);
3140 if (cluster_size == 8) return ac_build_wwm(ctx, result);
3141
3142 if (ctx->chip_class >= VI)
3143 swap = ac_build_dpp(ctx, identity, result, dpp_row_mirror, 0xf, 0xf, false);
3144 else
3145 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x08));
3146 result = ac_build_alu_op(ctx, result, swap, op);
3147 if (cluster_size == 16) return ac_build_wwm(ctx, result);
3148
3149 if (ctx->chip_class >= VI && cluster_size != 32)
3150 swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
3151 else
3152 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x10));
3153 result = ac_build_alu_op(ctx, result, swap, op);
3154 if (cluster_size == 32) return ac_build_wwm(ctx, result);
3155
3156 if (ctx->chip_class >= VI) {
3157 swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
3158 result = ac_build_alu_op(ctx, result, swap, op);
3159 result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 63, 0));
3160 return ac_build_wwm(ctx, result);
3161 } else {
3162 swap = ac_build_readlane(ctx, result, ctx->i32_0);
3163 result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 32, 0));
3164 result = ac_build_alu_op(ctx, result, swap, op);
3165 return ac_build_wwm(ctx, result);
3166 }
3167 }
3168
3169 LLVMValueRef
3170 ac_build_quad_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src,
3171 unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
3172 {
3173 unsigned mask = dpp_quad_perm(lane0, lane1, lane2, lane3);
3174 if (ctx->chip_class >= VI) {
3175 return ac_build_dpp(ctx, src, src, mask, 0xf, 0xf, false);
3176 } else {
3177 return ac_build_ds_swizzle(ctx, src, (1 << 15) | mask);
3178 }
3179 }
3180
3181 LLVMValueRef
3182 ac_build_shuffle(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef index)
3183 {
3184 index = LLVMBuildMul(ctx->builder, index, LLVMConstInt(ctx->i32, 4, 0), "");
3185 return ac_build_intrinsic(ctx,
3186 "llvm.amdgcn.ds.bpermute", ctx->i32,
3187 (LLVMValueRef []) {index, src}, 2,
3188 AC_FUNC_ATTR_READNONE |
3189 AC_FUNC_ATTR_CONVERGENT);
3190 }