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