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