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