ac/nir: adjust an assertion for D16 on GFX6-GFX7
[mesa.git] / src / amd / llvm / 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 #include <llvm/Config/llvm-config.h>
30
31 #include "c11/threads.h"
32
33 #include <assert.h>
34 #include <stdio.h>
35
36 #include "ac_llvm_util.h"
37 #include "ac_shader_util.h"
38 #include "ac_exp_param.h"
39 #include "util/bitscan.h"
40 #include "util/macros.h"
41 #include "util/u_atomic.h"
42 #include "util/u_math.h"
43 #include "sid.h"
44
45 #include "shader_enums.h"
46
47 #define AC_LLVM_INITIAL_CF_DEPTH 4
48
49 /* Data for if/else/endif and bgnloop/endloop control flow structures.
50 */
51 struct ac_llvm_flow {
52 /* Loop exit or next part of if/else/endif. */
53 LLVMBasicBlockRef next_block;
54 LLVMBasicBlockRef loop_entry_block;
55 };
56
57 /* Initialize module-independent parts of the context.
58 *
59 * The caller is responsible for initializing ctx::module and ctx::builder.
60 */
61 void
62 ac_llvm_context_init(struct ac_llvm_context *ctx,
63 struct ac_llvm_compiler *compiler,
64 enum chip_class chip_class, enum radeon_family family,
65 enum ac_float_mode float_mode, unsigned wave_size,
66 unsigned ballot_mask_bits)
67 {
68 ctx->context = LLVMContextCreate();
69
70 ctx->chip_class = chip_class;
71 ctx->family = family;
72 ctx->wave_size = wave_size;
73 ctx->ballot_mask_bits = ballot_mask_bits;
74 ctx->float_mode = float_mode;
75 ctx->module = ac_create_module(wave_size == 32 ? compiler->tm_wave32
76 : compiler->tm,
77 ctx->context);
78 ctx->builder = ac_create_builder(ctx->context, float_mode);
79
80 ctx->voidt = LLVMVoidTypeInContext(ctx->context);
81 ctx->i1 = LLVMInt1TypeInContext(ctx->context);
82 ctx->i8 = LLVMInt8TypeInContext(ctx->context);
83 ctx->i16 = LLVMIntTypeInContext(ctx->context, 16);
84 ctx->i32 = LLVMIntTypeInContext(ctx->context, 32);
85 ctx->i64 = LLVMIntTypeInContext(ctx->context, 64);
86 ctx->i128 = LLVMIntTypeInContext(ctx->context, 128);
87 ctx->intptr = ctx->i32;
88 ctx->f16 = LLVMHalfTypeInContext(ctx->context);
89 ctx->f32 = LLVMFloatTypeInContext(ctx->context);
90 ctx->f64 = LLVMDoubleTypeInContext(ctx->context);
91 ctx->v2i16 = LLVMVectorType(ctx->i16, 2);
92 ctx->v4i16 = LLVMVectorType(ctx->i16, 4);
93 ctx->v2f16 = LLVMVectorType(ctx->f16, 2);
94 ctx->v4f16 = LLVMVectorType(ctx->f16, 4);
95 ctx->v2i32 = LLVMVectorType(ctx->i32, 2);
96 ctx->v3i32 = LLVMVectorType(ctx->i32, 3);
97 ctx->v4i32 = LLVMVectorType(ctx->i32, 4);
98 ctx->v2f32 = LLVMVectorType(ctx->f32, 2);
99 ctx->v3f32 = LLVMVectorType(ctx->f32, 3);
100 ctx->v4f32 = LLVMVectorType(ctx->f32, 4);
101 ctx->v8i32 = LLVMVectorType(ctx->i32, 8);
102 ctx->iN_wavemask = LLVMIntTypeInContext(ctx->context, ctx->wave_size);
103 ctx->iN_ballotmask = LLVMIntTypeInContext(ctx->context, ballot_mask_bits);
104
105 ctx->i8_0 = LLVMConstInt(ctx->i8, 0, false);
106 ctx->i8_1 = LLVMConstInt(ctx->i8, 1, false);
107 ctx->i16_0 = LLVMConstInt(ctx->i16, 0, false);
108 ctx->i16_1 = LLVMConstInt(ctx->i16, 1, false);
109 ctx->i32_0 = LLVMConstInt(ctx->i32, 0, false);
110 ctx->i32_1 = LLVMConstInt(ctx->i32, 1, false);
111 ctx->i64_0 = LLVMConstInt(ctx->i64, 0, false);
112 ctx->i64_1 = LLVMConstInt(ctx->i64, 1, false);
113 ctx->i128_0 = LLVMConstInt(ctx->i128, 0, false);
114 ctx->i128_1 = LLVMConstInt(ctx->i128, 1, false);
115 ctx->f16_0 = LLVMConstReal(ctx->f16, 0.0);
116 ctx->f16_1 = LLVMConstReal(ctx->f16, 1.0);
117 ctx->f32_0 = LLVMConstReal(ctx->f32, 0.0);
118 ctx->f32_1 = LLVMConstReal(ctx->f32, 1.0);
119 ctx->f64_0 = LLVMConstReal(ctx->f64, 0.0);
120 ctx->f64_1 = LLVMConstReal(ctx->f64, 1.0);
121
122 ctx->i1false = LLVMConstInt(ctx->i1, 0, false);
123 ctx->i1true = LLVMConstInt(ctx->i1, 1, false);
124
125 ctx->range_md_kind = LLVMGetMDKindIDInContext(ctx->context,
126 "range", 5);
127
128 ctx->invariant_load_md_kind = LLVMGetMDKindIDInContext(ctx->context,
129 "invariant.load", 14);
130
131 ctx->uniform_md_kind = LLVMGetMDKindIDInContext(ctx->context,
132 "amdgpu.uniform", 14);
133
134 ctx->empty_md = LLVMMDNodeInContext(ctx->context, NULL, 0);
135 ctx->flow = calloc(1, sizeof(*ctx->flow));
136 }
137
138 void
139 ac_llvm_context_dispose(struct ac_llvm_context *ctx)
140 {
141 free(ctx->flow->stack);
142 free(ctx->flow);
143 ctx->flow = NULL;
144 }
145
146 int
147 ac_get_llvm_num_components(LLVMValueRef value)
148 {
149 LLVMTypeRef type = LLVMTypeOf(value);
150 unsigned num_components = LLVMGetTypeKind(type) == LLVMVectorTypeKind
151 ? LLVMGetVectorSize(type)
152 : 1;
153 return num_components;
154 }
155
156 LLVMValueRef
157 ac_llvm_extract_elem(struct ac_llvm_context *ac,
158 LLVMValueRef value,
159 int index)
160 {
161 if (LLVMGetTypeKind(LLVMTypeOf(value)) != LLVMVectorTypeKind) {
162 assert(index == 0);
163 return value;
164 }
165
166 return LLVMBuildExtractElement(ac->builder, value,
167 LLVMConstInt(ac->i32, index, false), "");
168 }
169
170 int
171 ac_get_elem_bits(struct ac_llvm_context *ctx, LLVMTypeRef type)
172 {
173 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind)
174 type = LLVMGetElementType(type);
175
176 if (LLVMGetTypeKind(type) == LLVMIntegerTypeKind)
177 return LLVMGetIntTypeWidth(type);
178
179 if (LLVMGetTypeKind(type) == LLVMPointerTypeKind) {
180 if (LLVMGetPointerAddressSpace(type) == AC_ADDR_SPACE_LDS)
181 return 32;
182 }
183
184 if (type == ctx->f16)
185 return 16;
186 if (type == ctx->f32)
187 return 32;
188 if (type == ctx->f64)
189 return 64;
190
191 unreachable("Unhandled type kind in get_elem_bits");
192 }
193
194 unsigned
195 ac_get_type_size(LLVMTypeRef type)
196 {
197 LLVMTypeKind kind = LLVMGetTypeKind(type);
198
199 switch (kind) {
200 case LLVMIntegerTypeKind:
201 return LLVMGetIntTypeWidth(type) / 8;
202 case LLVMHalfTypeKind:
203 return 2;
204 case LLVMFloatTypeKind:
205 return 4;
206 case LLVMDoubleTypeKind:
207 return 8;
208 case LLVMPointerTypeKind:
209 if (LLVMGetPointerAddressSpace(type) == AC_ADDR_SPACE_CONST_32BIT)
210 return 4;
211 return 8;
212 case LLVMVectorTypeKind:
213 return LLVMGetVectorSize(type) *
214 ac_get_type_size(LLVMGetElementType(type));
215 case LLVMArrayTypeKind:
216 return LLVMGetArrayLength(type) *
217 ac_get_type_size(LLVMGetElementType(type));
218 default:
219 assert(0);
220 return 0;
221 }
222 }
223
224 static LLVMTypeRef to_integer_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
225 {
226 if (t == ctx->i8)
227 return ctx->i8;
228 else if (t == ctx->f16 || t == ctx->i16)
229 return ctx->i16;
230 else if (t == ctx->f32 || t == ctx->i32)
231 return ctx->i32;
232 else if (t == ctx->f64 || t == ctx->i64)
233 return ctx->i64;
234 else
235 unreachable("Unhandled integer size");
236 }
237
238 LLVMTypeRef
239 ac_to_integer_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
240 {
241 if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
242 LLVMTypeRef elem_type = LLVMGetElementType(t);
243 return LLVMVectorType(to_integer_type_scalar(ctx, elem_type),
244 LLVMGetVectorSize(t));
245 }
246 if (LLVMGetTypeKind(t) == LLVMPointerTypeKind) {
247 switch (LLVMGetPointerAddressSpace(t)) {
248 case AC_ADDR_SPACE_GLOBAL:
249 return ctx->i64;
250 case AC_ADDR_SPACE_CONST_32BIT:
251 case AC_ADDR_SPACE_LDS:
252 return ctx->i32;
253 default:
254 unreachable("unhandled address space");
255 }
256 }
257 return to_integer_type_scalar(ctx, t);
258 }
259
260 LLVMValueRef
261 ac_to_integer(struct ac_llvm_context *ctx, LLVMValueRef v)
262 {
263 LLVMTypeRef type = LLVMTypeOf(v);
264 if (LLVMGetTypeKind(type) == LLVMPointerTypeKind) {
265 return LLVMBuildPtrToInt(ctx->builder, v, ac_to_integer_type(ctx, type), "");
266 }
267 return LLVMBuildBitCast(ctx->builder, v, ac_to_integer_type(ctx, type), "");
268 }
269
270 LLVMValueRef
271 ac_to_integer_or_pointer(struct ac_llvm_context *ctx, LLVMValueRef v)
272 {
273 LLVMTypeRef type = LLVMTypeOf(v);
274 if (LLVMGetTypeKind(type) == LLVMPointerTypeKind)
275 return v;
276 return ac_to_integer(ctx, v);
277 }
278
279 static LLVMTypeRef to_float_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
280 {
281 if (t == ctx->i8)
282 return ctx->i8;
283 else if (t == ctx->i16 || t == ctx->f16)
284 return ctx->f16;
285 else if (t == ctx->i32 || t == ctx->f32)
286 return ctx->f32;
287 else if (t == ctx->i64 || t == ctx->f64)
288 return ctx->f64;
289 else
290 unreachable("Unhandled float size");
291 }
292
293 LLVMTypeRef
294 ac_to_float_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
295 {
296 if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
297 LLVMTypeRef elem_type = LLVMGetElementType(t);
298 return LLVMVectorType(to_float_type_scalar(ctx, elem_type),
299 LLVMGetVectorSize(t));
300 }
301 return to_float_type_scalar(ctx, t);
302 }
303
304 LLVMValueRef
305 ac_to_float(struct ac_llvm_context *ctx, LLVMValueRef v)
306 {
307 LLVMTypeRef type = LLVMTypeOf(v);
308 return LLVMBuildBitCast(ctx->builder, v, ac_to_float_type(ctx, type), "");
309 }
310
311
312 LLVMValueRef
313 ac_build_intrinsic(struct ac_llvm_context *ctx, const char *name,
314 LLVMTypeRef return_type, LLVMValueRef *params,
315 unsigned param_count, unsigned attrib_mask)
316 {
317 LLVMValueRef function, call;
318 bool set_callsite_attrs = !(attrib_mask & AC_FUNC_ATTR_LEGACY);
319
320 function = LLVMGetNamedFunction(ctx->module, name);
321 if (!function) {
322 LLVMTypeRef param_types[32], function_type;
323 unsigned i;
324
325 assert(param_count <= 32);
326
327 for (i = 0; i < param_count; ++i) {
328 assert(params[i]);
329 param_types[i] = LLVMTypeOf(params[i]);
330 }
331 function_type =
332 LLVMFunctionType(return_type, param_types, param_count, 0);
333 function = LLVMAddFunction(ctx->module, name, function_type);
334
335 LLVMSetFunctionCallConv(function, LLVMCCallConv);
336 LLVMSetLinkage(function, LLVMExternalLinkage);
337
338 if (!set_callsite_attrs)
339 ac_add_func_attributes(ctx->context, function, attrib_mask);
340 }
341
342 call = LLVMBuildCall(ctx->builder, function, params, param_count, "");
343 if (set_callsite_attrs)
344 ac_add_func_attributes(ctx->context, call, attrib_mask);
345 return call;
346 }
347
348 /**
349 * Given the i32 or vNi32 \p type, generate the textual name (e.g. for use with
350 * intrinsic names).
351 */
352 void ac_build_type_name_for_intr(LLVMTypeRef type, char *buf, unsigned bufsize)
353 {
354 LLVMTypeRef elem_type = type;
355
356 assert(bufsize >= 8);
357
358 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind) {
359 int ret = snprintf(buf, bufsize, "v%u",
360 LLVMGetVectorSize(type));
361 if (ret < 0) {
362 char *type_name = LLVMPrintTypeToString(type);
363 fprintf(stderr, "Error building type name for: %s\n",
364 type_name);
365 LLVMDisposeMessage(type_name);
366 return;
367 }
368 elem_type = LLVMGetElementType(type);
369 buf += ret;
370 bufsize -= ret;
371 }
372 switch (LLVMGetTypeKind(elem_type)) {
373 default: break;
374 case LLVMIntegerTypeKind:
375 snprintf(buf, bufsize, "i%d", LLVMGetIntTypeWidth(elem_type));
376 break;
377 case LLVMHalfTypeKind:
378 snprintf(buf, bufsize, "f16");
379 break;
380 case LLVMFloatTypeKind:
381 snprintf(buf, bufsize, "f32");
382 break;
383 case LLVMDoubleTypeKind:
384 snprintf(buf, bufsize, "f64");
385 break;
386 }
387 }
388
389 /**
390 * Helper function that builds an LLVM IR PHI node and immediately adds
391 * incoming edges.
392 */
393 LLVMValueRef
394 ac_build_phi(struct ac_llvm_context *ctx, LLVMTypeRef type,
395 unsigned count_incoming, LLVMValueRef *values,
396 LLVMBasicBlockRef *blocks)
397 {
398 LLVMValueRef phi = LLVMBuildPhi(ctx->builder, type, "");
399 LLVMAddIncoming(phi, values, blocks, count_incoming);
400 return phi;
401 }
402
403 void ac_build_s_barrier(struct ac_llvm_context *ctx)
404 {
405 ac_build_intrinsic(ctx, "llvm.amdgcn.s.barrier", ctx->voidt, NULL,
406 0, AC_FUNC_ATTR_CONVERGENT);
407 }
408
409 /* Prevent optimizations (at least of memory accesses) across the current
410 * point in the program by emitting empty inline assembly that is marked as
411 * having side effects.
412 *
413 * Optionally, a value can be passed through the inline assembly to prevent
414 * LLVM from hoisting calls to ReadNone functions.
415 */
416 void
417 ac_build_optimization_barrier(struct ac_llvm_context *ctx,
418 LLVMValueRef *pvgpr)
419 {
420 static int counter = 0;
421
422 LLVMBuilderRef builder = ctx->builder;
423 char code[16];
424
425 snprintf(code, sizeof(code), "; %d", p_atomic_inc_return(&counter));
426
427 if (!pvgpr) {
428 LLVMTypeRef ftype = LLVMFunctionType(ctx->voidt, NULL, 0, false);
429 LLVMValueRef inlineasm = LLVMConstInlineAsm(ftype, code, "", true, false);
430 LLVMBuildCall(builder, inlineasm, NULL, 0, "");
431 } else {
432 LLVMTypeRef ftype = LLVMFunctionType(ctx->i32, &ctx->i32, 1, false);
433 LLVMValueRef inlineasm = LLVMConstInlineAsm(ftype, code, "=v,0", true, false);
434 LLVMTypeRef type = LLVMTypeOf(*pvgpr);
435 unsigned bitsize = ac_get_elem_bits(ctx, type);
436 LLVMValueRef vgpr = *pvgpr;
437 LLVMTypeRef vgpr_type;
438 unsigned vgpr_size;
439 LLVMValueRef vgpr0;
440
441 if (bitsize < 32)
442 vgpr = LLVMBuildZExt(ctx->builder, vgpr, ctx->i32, "");
443
444 vgpr_type = LLVMTypeOf(vgpr);
445 vgpr_size = ac_get_type_size(vgpr_type);
446
447 assert(vgpr_size % 4 == 0);
448
449 vgpr = LLVMBuildBitCast(builder, vgpr, LLVMVectorType(ctx->i32, vgpr_size / 4), "");
450 vgpr0 = LLVMBuildExtractElement(builder, vgpr, ctx->i32_0, "");
451 vgpr0 = LLVMBuildCall(builder, inlineasm, &vgpr0, 1, "");
452 vgpr = LLVMBuildInsertElement(builder, vgpr, vgpr0, ctx->i32_0, "");
453 vgpr = LLVMBuildBitCast(builder, vgpr, vgpr_type, "");
454
455 if (bitsize < 32)
456 vgpr = LLVMBuildTrunc(builder, vgpr, type, "");
457
458 *pvgpr = vgpr;
459 }
460 }
461
462 LLVMValueRef
463 ac_build_shader_clock(struct ac_llvm_context *ctx, nir_scope scope)
464 {
465 const char *name = scope == NIR_SCOPE_DEVICE ? "llvm.amdgcn.s.memrealtime" : "llvm.amdgcn.s.memtime";
466 LLVMValueRef tmp = ac_build_intrinsic(ctx, name, ctx->i64, NULL, 0, 0);
467 return LLVMBuildBitCast(ctx->builder, tmp, ctx->v2i32, "");
468 }
469
470 LLVMValueRef
471 ac_build_ballot(struct ac_llvm_context *ctx,
472 LLVMValueRef value)
473 {
474 const char *name;
475
476 if (LLVM_VERSION_MAJOR >= 9) {
477 if (ctx->wave_size == 64)
478 name = "llvm.amdgcn.icmp.i64.i32";
479 else
480 name = "llvm.amdgcn.icmp.i32.i32";
481 } else {
482 name = "llvm.amdgcn.icmp.i32";
483 }
484 LLVMValueRef args[3] = {
485 value,
486 ctx->i32_0,
487 LLVMConstInt(ctx->i32, LLVMIntNE, 0)
488 };
489
490 /* We currently have no other way to prevent LLVM from lifting the icmp
491 * calls to a dominating basic block.
492 */
493 ac_build_optimization_barrier(ctx, &args[0]);
494
495 args[0] = ac_to_integer(ctx, args[0]);
496
497 return ac_build_intrinsic(ctx, name, ctx->iN_wavemask, args, 3,
498 AC_FUNC_ATTR_NOUNWIND |
499 AC_FUNC_ATTR_READNONE |
500 AC_FUNC_ATTR_CONVERGENT);
501 }
502
503 LLVMValueRef ac_get_i1_sgpr_mask(struct ac_llvm_context *ctx,
504 LLVMValueRef value)
505 {
506 const char *name;
507
508 if (LLVM_VERSION_MAJOR >= 9) {
509 if (ctx->wave_size == 64)
510 name = "llvm.amdgcn.icmp.i64.i1";
511 else
512 name = "llvm.amdgcn.icmp.i32.i1";
513 } else {
514 name = "llvm.amdgcn.icmp.i1";
515 }
516 LLVMValueRef args[3] = {
517 value,
518 ctx->i1false,
519 LLVMConstInt(ctx->i32, LLVMIntNE, 0),
520 };
521
522 return ac_build_intrinsic(ctx, name, ctx->iN_wavemask, args, 3,
523 AC_FUNC_ATTR_NOUNWIND |
524 AC_FUNC_ATTR_READNONE |
525 AC_FUNC_ATTR_CONVERGENT);
526 }
527
528 LLVMValueRef
529 ac_build_vote_all(struct ac_llvm_context *ctx, LLVMValueRef value)
530 {
531 LLVMValueRef active_set = ac_build_ballot(ctx, ctx->i32_1);
532 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
533 return LLVMBuildICmp(ctx->builder, LLVMIntEQ, vote_set, active_set, "");
534 }
535
536 LLVMValueRef
537 ac_build_vote_any(struct ac_llvm_context *ctx, LLVMValueRef value)
538 {
539 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
540 return LLVMBuildICmp(ctx->builder, LLVMIntNE, vote_set,
541 LLVMConstInt(ctx->iN_wavemask, 0, 0), "");
542 }
543
544 LLVMValueRef
545 ac_build_vote_eq(struct ac_llvm_context *ctx, LLVMValueRef value)
546 {
547 LLVMValueRef active_set = ac_build_ballot(ctx, ctx->i32_1);
548 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
549
550 LLVMValueRef all = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
551 vote_set, active_set, "");
552 LLVMValueRef none = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
553 vote_set,
554 LLVMConstInt(ctx->iN_wavemask, 0, 0), "");
555 return LLVMBuildOr(ctx->builder, all, none, "");
556 }
557
558 LLVMValueRef
559 ac_build_varying_gather_values(struct ac_llvm_context *ctx, LLVMValueRef *values,
560 unsigned value_count, unsigned component)
561 {
562 LLVMValueRef vec = NULL;
563
564 if (value_count == 1) {
565 return values[component];
566 } else if (!value_count)
567 unreachable("value_count is 0");
568
569 for (unsigned i = component; i < value_count + component; i++) {
570 LLVMValueRef value = values[i];
571
572 if (i == component)
573 vec = LLVMGetUndef( LLVMVectorType(LLVMTypeOf(value), value_count));
574 LLVMValueRef index = LLVMConstInt(ctx->i32, i - component, false);
575 vec = LLVMBuildInsertElement(ctx->builder, vec, value, index, "");
576 }
577 return vec;
578 }
579
580 LLVMValueRef
581 ac_build_gather_values_extended(struct ac_llvm_context *ctx,
582 LLVMValueRef *values,
583 unsigned value_count,
584 unsigned value_stride,
585 bool load,
586 bool always_vector)
587 {
588 LLVMBuilderRef builder = ctx->builder;
589 LLVMValueRef vec = NULL;
590 unsigned i;
591
592 if (value_count == 1 && !always_vector) {
593 if (load)
594 return LLVMBuildLoad(builder, values[0], "");
595 return values[0];
596 } else if (!value_count)
597 unreachable("value_count is 0");
598
599 for (i = 0; i < value_count; i++) {
600 LLVMValueRef value = values[i * value_stride];
601 if (load)
602 value = LLVMBuildLoad(builder, value, "");
603
604 if (!i)
605 vec = LLVMGetUndef( LLVMVectorType(LLVMTypeOf(value), value_count));
606 LLVMValueRef index = LLVMConstInt(ctx->i32, i, false);
607 vec = LLVMBuildInsertElement(builder, vec, value, index, "");
608 }
609 return vec;
610 }
611
612 LLVMValueRef
613 ac_build_gather_values(struct ac_llvm_context *ctx,
614 LLVMValueRef *values,
615 unsigned value_count)
616 {
617 return ac_build_gather_values_extended(ctx, values, value_count, 1, false, false);
618 }
619
620 /* Expand a scalar or vector to <dst_channels x type> by filling the remaining
621 * channels with undef. Extract at most src_channels components from the input.
622 */
623 static LLVMValueRef
624 ac_build_expand(struct ac_llvm_context *ctx,
625 LLVMValueRef value,
626 unsigned src_channels,
627 unsigned dst_channels)
628 {
629 LLVMTypeRef elemtype;
630 LLVMValueRef chan[dst_channels];
631
632 if (LLVMGetTypeKind(LLVMTypeOf(value)) == LLVMVectorTypeKind) {
633 unsigned vec_size = LLVMGetVectorSize(LLVMTypeOf(value));
634
635 if (src_channels == dst_channels && vec_size == dst_channels)
636 return value;
637
638 src_channels = MIN2(src_channels, vec_size);
639
640 for (unsigned i = 0; i < src_channels; i++)
641 chan[i] = ac_llvm_extract_elem(ctx, value, i);
642
643 elemtype = LLVMGetElementType(LLVMTypeOf(value));
644 } else {
645 if (src_channels) {
646 assert(src_channels == 1);
647 chan[0] = value;
648 }
649 elemtype = LLVMTypeOf(value);
650 }
651
652 for (unsigned i = src_channels; i < dst_channels; i++)
653 chan[i] = LLVMGetUndef(elemtype);
654
655 return ac_build_gather_values(ctx, chan, dst_channels);
656 }
657
658 /* Extract components [start, start + channels) from a vector.
659 */
660 LLVMValueRef
661 ac_extract_components(struct ac_llvm_context *ctx,
662 LLVMValueRef value,
663 unsigned start,
664 unsigned channels)
665 {
666 LLVMValueRef chan[channels];
667
668 for (unsigned i = 0; i < channels; i++)
669 chan[i] = ac_llvm_extract_elem(ctx, value, i + start);
670
671 return ac_build_gather_values(ctx, chan, channels);
672 }
673
674 /* Expand a scalar or vector to <4 x type> by filling the remaining channels
675 * with undef. Extract at most num_channels components from the input.
676 */
677 LLVMValueRef ac_build_expand_to_vec4(struct ac_llvm_context *ctx,
678 LLVMValueRef value,
679 unsigned num_channels)
680 {
681 return ac_build_expand(ctx, value, num_channels, 4);
682 }
683
684 LLVMValueRef ac_build_round(struct ac_llvm_context *ctx, LLVMValueRef value)
685 {
686 unsigned type_size = ac_get_type_size(LLVMTypeOf(value));
687 const char *name;
688
689 if (type_size == 2)
690 name = "llvm.rint.f16";
691 else if (type_size == 4)
692 name = "llvm.rint.f32";
693 else
694 name = "llvm.rint.f64";
695
696 return ac_build_intrinsic(ctx, name, LLVMTypeOf(value), &value, 1,
697 AC_FUNC_ATTR_READNONE);
698 }
699
700 LLVMValueRef
701 ac_build_fdiv(struct ac_llvm_context *ctx,
702 LLVMValueRef num,
703 LLVMValueRef den)
704 {
705 unsigned type_size = ac_get_type_size(LLVMTypeOf(den));
706 const char *name;
707
708 if (type_size == 2)
709 name = "llvm.amdgcn.rcp.f16";
710 else if (type_size == 4)
711 name = "llvm.amdgcn.rcp.f32";
712 else
713 name = "llvm.amdgcn.rcp.f64";
714
715 LLVMValueRef rcp = ac_build_intrinsic(ctx, name, LLVMTypeOf(den),
716 &den, 1, AC_FUNC_ATTR_READNONE);
717
718 return LLVMBuildFMul(ctx->builder, num, rcp, "");
719 }
720
721 /* See fast_idiv_by_const.h. */
722 /* Set: increment = util_fast_udiv_info::increment ? multiplier : 0; */
723 LLVMValueRef ac_build_fast_udiv(struct ac_llvm_context *ctx,
724 LLVMValueRef num,
725 LLVMValueRef multiplier,
726 LLVMValueRef pre_shift,
727 LLVMValueRef post_shift,
728 LLVMValueRef increment)
729 {
730 LLVMBuilderRef builder = ctx->builder;
731
732 num = LLVMBuildLShr(builder, num, pre_shift, "");
733 num = LLVMBuildMul(builder,
734 LLVMBuildZExt(builder, num, ctx->i64, ""),
735 LLVMBuildZExt(builder, multiplier, ctx->i64, ""), "");
736 num = LLVMBuildAdd(builder, num,
737 LLVMBuildZExt(builder, increment, ctx->i64, ""), "");
738 num = LLVMBuildLShr(builder, num, LLVMConstInt(ctx->i64, 32, 0), "");
739 num = LLVMBuildTrunc(builder, num, ctx->i32, "");
740 return LLVMBuildLShr(builder, num, post_shift, "");
741 }
742
743 /* See fast_idiv_by_const.h. */
744 /* If num != UINT_MAX, this more efficient version can be used. */
745 /* Set: increment = util_fast_udiv_info::increment; */
746 LLVMValueRef ac_build_fast_udiv_nuw(struct ac_llvm_context *ctx,
747 LLVMValueRef num,
748 LLVMValueRef multiplier,
749 LLVMValueRef pre_shift,
750 LLVMValueRef post_shift,
751 LLVMValueRef increment)
752 {
753 LLVMBuilderRef builder = ctx->builder;
754
755 num = LLVMBuildLShr(builder, num, pre_shift, "");
756 num = LLVMBuildNUWAdd(builder, num, increment, "");
757 num = LLVMBuildMul(builder,
758 LLVMBuildZExt(builder, num, ctx->i64, ""),
759 LLVMBuildZExt(builder, multiplier, ctx->i64, ""), "");
760 num = LLVMBuildLShr(builder, num, LLVMConstInt(ctx->i64, 32, 0), "");
761 num = LLVMBuildTrunc(builder, num, ctx->i32, "");
762 return LLVMBuildLShr(builder, num, post_shift, "");
763 }
764
765 /* See fast_idiv_by_const.h. */
766 /* Both operands must fit in 31 bits and the divisor must not be 1. */
767 LLVMValueRef ac_build_fast_udiv_u31_d_not_one(struct ac_llvm_context *ctx,
768 LLVMValueRef num,
769 LLVMValueRef multiplier,
770 LLVMValueRef post_shift)
771 {
772 LLVMBuilderRef builder = ctx->builder;
773
774 num = LLVMBuildMul(builder,
775 LLVMBuildZExt(builder, num, ctx->i64, ""),
776 LLVMBuildZExt(builder, multiplier, ctx->i64, ""), "");
777 num = LLVMBuildLShr(builder, num, LLVMConstInt(ctx->i64, 32, 0), "");
778 num = LLVMBuildTrunc(builder, num, ctx->i32, "");
779 return LLVMBuildLShr(builder, num, post_shift, "");
780 }
781
782 /* Coordinates for cube map selection. sc, tc, and ma are as in Table 8.27
783 * of the OpenGL 4.5 (Compatibility Profile) specification, except ma is
784 * already multiplied by two. id is the cube face number.
785 */
786 struct cube_selection_coords {
787 LLVMValueRef stc[2];
788 LLVMValueRef ma;
789 LLVMValueRef id;
790 };
791
792 static void
793 build_cube_intrinsic(struct ac_llvm_context *ctx,
794 LLVMValueRef in[3],
795 struct cube_selection_coords *out)
796 {
797 LLVMTypeRef f32 = ctx->f32;
798
799 out->stc[1] = ac_build_intrinsic(ctx, "llvm.amdgcn.cubetc",
800 f32, in, 3, AC_FUNC_ATTR_READNONE);
801 out->stc[0] = ac_build_intrinsic(ctx, "llvm.amdgcn.cubesc",
802 f32, in, 3, AC_FUNC_ATTR_READNONE);
803 out->ma = ac_build_intrinsic(ctx, "llvm.amdgcn.cubema",
804 f32, in, 3, AC_FUNC_ATTR_READNONE);
805 out->id = ac_build_intrinsic(ctx, "llvm.amdgcn.cubeid",
806 f32, in, 3, AC_FUNC_ATTR_READNONE);
807 }
808
809 /**
810 * Build a manual selection sequence for cube face sc/tc coordinates and
811 * major axis vector (multiplied by 2 for consistency) for the given
812 * vec3 \p coords, for the face implied by \p selcoords.
813 *
814 * For the major axis, we always adjust the sign to be in the direction of
815 * selcoords.ma; i.e., a positive out_ma means that coords is pointed towards
816 * the selcoords major axis.
817 */
818 static void build_cube_select(struct ac_llvm_context *ctx,
819 const struct cube_selection_coords *selcoords,
820 const LLVMValueRef *coords,
821 LLVMValueRef *out_st,
822 LLVMValueRef *out_ma)
823 {
824 LLVMBuilderRef builder = ctx->builder;
825 LLVMTypeRef f32 = LLVMTypeOf(coords[0]);
826 LLVMValueRef is_ma_positive;
827 LLVMValueRef sgn_ma;
828 LLVMValueRef is_ma_z, is_not_ma_z;
829 LLVMValueRef is_ma_y;
830 LLVMValueRef is_ma_x;
831 LLVMValueRef sgn;
832 LLVMValueRef tmp;
833
834 is_ma_positive = LLVMBuildFCmp(builder, LLVMRealUGE,
835 selcoords->ma, LLVMConstReal(f32, 0.0), "");
836 sgn_ma = LLVMBuildSelect(builder, is_ma_positive,
837 LLVMConstReal(f32, 1.0), LLVMConstReal(f32, -1.0), "");
838
839 is_ma_z = LLVMBuildFCmp(builder, LLVMRealUGE, selcoords->id, LLVMConstReal(f32, 4.0), "");
840 is_not_ma_z = LLVMBuildNot(builder, is_ma_z, "");
841 is_ma_y = LLVMBuildAnd(builder, is_not_ma_z,
842 LLVMBuildFCmp(builder, LLVMRealUGE, selcoords->id, LLVMConstReal(f32, 2.0), ""), "");
843 is_ma_x = LLVMBuildAnd(builder, is_not_ma_z, LLVMBuildNot(builder, is_ma_y, ""), "");
844
845 /* Select sc */
846 tmp = LLVMBuildSelect(builder, is_ma_x, coords[2], coords[0], "");
847 sgn = LLVMBuildSelect(builder, is_ma_y, LLVMConstReal(f32, 1.0),
848 LLVMBuildSelect(builder, is_ma_z, sgn_ma,
849 LLVMBuildFNeg(builder, sgn_ma, ""), ""), "");
850 out_st[0] = LLVMBuildFMul(builder, tmp, sgn, "");
851
852 /* Select tc */
853 tmp = LLVMBuildSelect(builder, is_ma_y, coords[2], coords[1], "");
854 sgn = LLVMBuildSelect(builder, is_ma_y, sgn_ma,
855 LLVMConstReal(f32, -1.0), "");
856 out_st[1] = LLVMBuildFMul(builder, tmp, sgn, "");
857
858 /* Select ma */
859 tmp = LLVMBuildSelect(builder, is_ma_z, coords[2],
860 LLVMBuildSelect(builder, is_ma_y, coords[1], coords[0], ""), "");
861 tmp = ac_build_intrinsic(ctx, "llvm.fabs.f32",
862 ctx->f32, &tmp, 1, AC_FUNC_ATTR_READNONE);
863 *out_ma = LLVMBuildFMul(builder, tmp, LLVMConstReal(f32, 2.0), "");
864 }
865
866 void
867 ac_prepare_cube_coords(struct ac_llvm_context *ctx,
868 bool is_deriv, bool is_array, bool is_lod,
869 LLVMValueRef *coords_arg,
870 LLVMValueRef *derivs_arg)
871 {
872
873 LLVMBuilderRef builder = ctx->builder;
874 struct cube_selection_coords selcoords;
875 LLVMValueRef coords[3];
876 LLVMValueRef invma;
877
878 if (is_array && !is_lod) {
879 LLVMValueRef tmp = ac_build_round(ctx, coords_arg[3]);
880
881 /* Section 8.9 (Texture Functions) of the GLSL 4.50 spec says:
882 *
883 * "For Array forms, the array layer used will be
884 *
885 * max(0, min(d−1, floor(layer+0.5)))
886 *
887 * where d is the depth of the texture array and layer
888 * comes from the component indicated in the tables below.
889 * Workaroudn for an issue where the layer is taken from a
890 * helper invocation which happens to fall on a different
891 * layer due to extrapolation."
892 *
893 * GFX8 and earlier attempt to implement this in hardware by
894 * clamping the value of coords[2] = (8 * layer) + face.
895 * Unfortunately, this means that the we end up with the wrong
896 * face when clamping occurs.
897 *
898 * Clamp the layer earlier to work around the issue.
899 */
900 if (ctx->chip_class <= GFX8) {
901 LLVMValueRef ge0;
902 ge0 = LLVMBuildFCmp(builder, LLVMRealOGE, tmp, ctx->f32_0, "");
903 tmp = LLVMBuildSelect(builder, ge0, tmp, ctx->f32_0, "");
904 }
905
906 coords_arg[3] = tmp;
907 }
908
909 build_cube_intrinsic(ctx, coords_arg, &selcoords);
910
911 invma = ac_build_intrinsic(ctx, "llvm.fabs.f32",
912 ctx->f32, &selcoords.ma, 1, AC_FUNC_ATTR_READNONE);
913 invma = ac_build_fdiv(ctx, LLVMConstReal(ctx->f32, 1.0), invma);
914
915 for (int i = 0; i < 2; ++i)
916 coords[i] = LLVMBuildFMul(builder, selcoords.stc[i], invma, "");
917
918 coords[2] = selcoords.id;
919
920 if (is_deriv && derivs_arg) {
921 LLVMValueRef derivs[4];
922 int axis;
923
924 /* Convert cube derivatives to 2D derivatives. */
925 for (axis = 0; axis < 2; axis++) {
926 LLVMValueRef deriv_st[2];
927 LLVMValueRef deriv_ma;
928
929 /* Transform the derivative alongside the texture
930 * coordinate. Mathematically, the correct formula is
931 * as follows. Assume we're projecting onto the +Z face
932 * and denote by dx/dh the derivative of the (original)
933 * X texture coordinate with respect to horizontal
934 * window coordinates. The projection onto the +Z face
935 * plane is:
936 *
937 * f(x,z) = x/z
938 *
939 * Then df/dh = df/dx * dx/dh + df/dz * dz/dh
940 * = 1/z * dx/dh - x/z * 1/z * dz/dh.
941 *
942 * This motivatives the implementation below.
943 *
944 * Whether this actually gives the expected results for
945 * apps that might feed in derivatives obtained via
946 * finite differences is anyone's guess. The OpenGL spec
947 * seems awfully quiet about how textureGrad for cube
948 * maps should be handled.
949 */
950 build_cube_select(ctx, &selcoords, &derivs_arg[axis * 3],
951 deriv_st, &deriv_ma);
952
953 deriv_ma = LLVMBuildFMul(builder, deriv_ma, invma, "");
954
955 for (int i = 0; i < 2; ++i)
956 derivs[axis * 2 + i] =
957 LLVMBuildFSub(builder,
958 LLVMBuildFMul(builder, deriv_st[i], invma, ""),
959 LLVMBuildFMul(builder, deriv_ma, coords[i], ""), "");
960 }
961
962 memcpy(derivs_arg, derivs, sizeof(derivs));
963 }
964
965 /* Shift the texture coordinate. This must be applied after the
966 * derivative calculation.
967 */
968 for (int i = 0; i < 2; ++i)
969 coords[i] = LLVMBuildFAdd(builder, coords[i], LLVMConstReal(ctx->f32, 1.5), "");
970
971 if (is_array) {
972 /* for cube arrays coord.z = coord.w(array_index) * 8 + face */
973 /* coords_arg.w component - array_index for cube arrays */
974 coords[2] = ac_build_fmad(ctx, coords_arg[3], LLVMConstReal(ctx->f32, 8.0), coords[2]);
975 }
976
977 memcpy(coords_arg, coords, sizeof(coords));
978 }
979
980
981 LLVMValueRef
982 ac_build_fs_interp(struct ac_llvm_context *ctx,
983 LLVMValueRef llvm_chan,
984 LLVMValueRef attr_number,
985 LLVMValueRef params,
986 LLVMValueRef i,
987 LLVMValueRef j)
988 {
989 LLVMValueRef args[5];
990 LLVMValueRef p1;
991
992 args[0] = i;
993 args[1] = llvm_chan;
994 args[2] = attr_number;
995 args[3] = params;
996
997 p1 = ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p1",
998 ctx->f32, args, 4, AC_FUNC_ATTR_READNONE);
999
1000 args[0] = p1;
1001 args[1] = j;
1002 args[2] = llvm_chan;
1003 args[3] = attr_number;
1004 args[4] = params;
1005
1006 return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p2",
1007 ctx->f32, args, 5, AC_FUNC_ATTR_READNONE);
1008 }
1009
1010 LLVMValueRef
1011 ac_build_fs_interp_f16(struct ac_llvm_context *ctx,
1012 LLVMValueRef llvm_chan,
1013 LLVMValueRef attr_number,
1014 LLVMValueRef params,
1015 LLVMValueRef i,
1016 LLVMValueRef j)
1017 {
1018 LLVMValueRef args[6];
1019 LLVMValueRef p1;
1020
1021 args[0] = i;
1022 args[1] = llvm_chan;
1023 args[2] = attr_number;
1024 args[3] = ctx->i1false;
1025 args[4] = params;
1026
1027 p1 = ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p1.f16",
1028 ctx->f32, args, 5, AC_FUNC_ATTR_READNONE);
1029
1030 args[0] = p1;
1031 args[1] = j;
1032 args[2] = llvm_chan;
1033 args[3] = attr_number;
1034 args[4] = ctx->i1false;
1035 args[5] = params;
1036
1037 return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p2.f16",
1038 ctx->f16, args, 6, AC_FUNC_ATTR_READNONE);
1039 }
1040
1041 LLVMValueRef
1042 ac_build_fs_interp_mov(struct ac_llvm_context *ctx,
1043 LLVMValueRef parameter,
1044 LLVMValueRef llvm_chan,
1045 LLVMValueRef attr_number,
1046 LLVMValueRef params)
1047 {
1048 LLVMValueRef args[4];
1049
1050 args[0] = parameter;
1051 args[1] = llvm_chan;
1052 args[2] = attr_number;
1053 args[3] = params;
1054
1055 return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.mov",
1056 ctx->f32, args, 4, AC_FUNC_ATTR_READNONE);
1057 }
1058
1059 LLVMValueRef
1060 ac_build_gep_ptr(struct ac_llvm_context *ctx,
1061 LLVMValueRef base_ptr,
1062 LLVMValueRef index)
1063 {
1064 return LLVMBuildGEP(ctx->builder, base_ptr, &index, 1, "");
1065 }
1066
1067 LLVMValueRef
1068 ac_build_gep0(struct ac_llvm_context *ctx,
1069 LLVMValueRef base_ptr,
1070 LLVMValueRef index)
1071 {
1072 LLVMValueRef indices[2] = {
1073 ctx->i32_0,
1074 index,
1075 };
1076 return LLVMBuildGEP(ctx->builder, base_ptr, indices, 2, "");
1077 }
1078
1079 LLVMValueRef ac_build_pointer_add(struct ac_llvm_context *ctx, LLVMValueRef ptr,
1080 LLVMValueRef index)
1081 {
1082 return LLVMBuildPointerCast(ctx->builder,
1083 LLVMBuildGEP(ctx->builder, ptr, &index, 1, ""),
1084 LLVMTypeOf(ptr), "");
1085 }
1086
1087 void
1088 ac_build_indexed_store(struct ac_llvm_context *ctx,
1089 LLVMValueRef base_ptr, LLVMValueRef index,
1090 LLVMValueRef value)
1091 {
1092 LLVMBuildStore(ctx->builder, value,
1093 ac_build_gep0(ctx, base_ptr, index));
1094 }
1095
1096 /**
1097 * Build an LLVM bytecode indexed load using LLVMBuildGEP + LLVMBuildLoad.
1098 * It's equivalent to doing a load from &base_ptr[index].
1099 *
1100 * \param base_ptr Where the array starts.
1101 * \param index The element index into the array.
1102 * \param uniform Whether the base_ptr and index can be assumed to be
1103 * dynamically uniform (i.e. load to an SGPR)
1104 * \param invariant Whether the load is invariant (no other opcodes affect it)
1105 * \param no_unsigned_wraparound
1106 * For all possible re-associations and re-distributions of an expression
1107 * "base_ptr + index * elemsize" into "addr + offset" (excluding GEPs
1108 * without inbounds in base_ptr), this parameter is true if "addr + offset"
1109 * does not result in an unsigned integer wraparound. This is used for
1110 * optimal code generation of 32-bit pointer arithmetic.
1111 *
1112 * For example, a 32-bit immediate offset that causes a 32-bit unsigned
1113 * integer wraparound can't be an imm offset in s_load_dword, because
1114 * the instruction performs "addr + offset" in 64 bits.
1115 *
1116 * Expected usage for bindless textures by chaining GEPs:
1117 * // possible unsigned wraparound, don't use InBounds:
1118 * ptr1 = LLVMBuildGEP(base_ptr, index);
1119 * image = load(ptr1); // becomes "s_load ptr1, 0"
1120 *
1121 * ptr2 = LLVMBuildInBoundsGEP(ptr1, 32 / elemsize);
1122 * sampler = load(ptr2); // becomes "s_load ptr1, 32" thanks to InBounds
1123 */
1124 static LLVMValueRef
1125 ac_build_load_custom(struct ac_llvm_context *ctx, LLVMValueRef base_ptr,
1126 LLVMValueRef index, bool uniform, bool invariant,
1127 bool no_unsigned_wraparound)
1128 {
1129 LLVMValueRef pointer, result;
1130
1131 if (no_unsigned_wraparound &&
1132 LLVMGetPointerAddressSpace(LLVMTypeOf(base_ptr)) == AC_ADDR_SPACE_CONST_32BIT)
1133 pointer = LLVMBuildInBoundsGEP(ctx->builder, base_ptr, &index, 1, "");
1134 else
1135 pointer = LLVMBuildGEP(ctx->builder, base_ptr, &index, 1, "");
1136
1137 if (uniform)
1138 LLVMSetMetadata(pointer, ctx->uniform_md_kind, ctx->empty_md);
1139 result = LLVMBuildLoad(ctx->builder, pointer, "");
1140 if (invariant)
1141 LLVMSetMetadata(result, ctx->invariant_load_md_kind, ctx->empty_md);
1142 return result;
1143 }
1144
1145 LLVMValueRef ac_build_load(struct ac_llvm_context *ctx, LLVMValueRef base_ptr,
1146 LLVMValueRef index)
1147 {
1148 return ac_build_load_custom(ctx, base_ptr, index, false, false, false);
1149 }
1150
1151 LLVMValueRef ac_build_load_invariant(struct ac_llvm_context *ctx,
1152 LLVMValueRef base_ptr, LLVMValueRef index)
1153 {
1154 return ac_build_load_custom(ctx, base_ptr, index, false, true, false);
1155 }
1156
1157 /* This assumes that there is no unsigned integer wraparound during the address
1158 * computation, excluding all GEPs within base_ptr. */
1159 LLVMValueRef ac_build_load_to_sgpr(struct ac_llvm_context *ctx,
1160 LLVMValueRef base_ptr, LLVMValueRef index)
1161 {
1162 return ac_build_load_custom(ctx, base_ptr, index, true, true, true);
1163 }
1164
1165 /* See ac_build_load_custom() documentation. */
1166 LLVMValueRef ac_build_load_to_sgpr_uint_wraparound(struct ac_llvm_context *ctx,
1167 LLVMValueRef base_ptr, LLVMValueRef index)
1168 {
1169 return ac_build_load_custom(ctx, base_ptr, index, true, true, false);
1170 }
1171
1172 static unsigned get_load_cache_policy(struct ac_llvm_context *ctx,
1173 unsigned cache_policy)
1174 {
1175 return cache_policy |
1176 (ctx->chip_class >= GFX10 && cache_policy & ac_glc ? ac_dlc : 0);
1177 }
1178
1179 static void
1180 ac_build_buffer_store_common(struct ac_llvm_context *ctx,
1181 LLVMValueRef rsrc,
1182 LLVMValueRef data,
1183 LLVMValueRef vindex,
1184 LLVMValueRef voffset,
1185 LLVMValueRef soffset,
1186 unsigned cache_policy,
1187 bool use_format,
1188 bool structurized)
1189 {
1190 LLVMValueRef args[6];
1191 int idx = 0;
1192 args[idx++] = data;
1193 args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
1194 if (structurized)
1195 args[idx++] = vindex ? vindex : ctx->i32_0;
1196 args[idx++] = voffset ? voffset : ctx->i32_0;
1197 args[idx++] = soffset ? soffset : ctx->i32_0;
1198 args[idx++] = LLVMConstInt(ctx->i32, cache_policy, 0);
1199 const char *indexing_kind = structurized ? "struct" : "raw";
1200 char name[256], type_name[8];
1201
1202 ac_build_type_name_for_intr(LLVMTypeOf(data), type_name, sizeof(type_name));
1203
1204 if (use_format) {
1205 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.store.format.%s",
1206 indexing_kind, type_name);
1207 } else {
1208 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.store.%s",
1209 indexing_kind, type_name);
1210 }
1211
1212 ac_build_intrinsic(ctx, name, ctx->voidt, args, idx,
1213 AC_FUNC_ATTR_INACCESSIBLE_MEM_ONLY);
1214 }
1215
1216 void
1217 ac_build_buffer_store_format(struct ac_llvm_context *ctx,
1218 LLVMValueRef rsrc,
1219 LLVMValueRef data,
1220 LLVMValueRef vindex,
1221 LLVMValueRef voffset,
1222 unsigned cache_policy)
1223 {
1224 ac_build_buffer_store_common(ctx, rsrc, data, vindex, voffset, NULL,
1225 cache_policy, true, true);
1226 }
1227
1228 /* TBUFFER_STORE_FORMAT_{X,XY,XYZ,XYZW} <- the suffix is selected by num_channels=1..4.
1229 * The type of vdata must be one of i32 (num_channels=1), v2i32 (num_channels=2),
1230 * or v4i32 (num_channels=3,4).
1231 */
1232 void
1233 ac_build_buffer_store_dword(struct ac_llvm_context *ctx,
1234 LLVMValueRef rsrc,
1235 LLVMValueRef vdata,
1236 unsigned num_channels,
1237 LLVMValueRef voffset,
1238 LLVMValueRef soffset,
1239 unsigned inst_offset,
1240 unsigned cache_policy)
1241 {
1242 /* Split 3 channel stores, because only LLVM 9+ support 3-channel
1243 * intrinsics. */
1244 if (num_channels == 3 && !ac_has_vec3_support(ctx->chip_class, false)) {
1245 LLVMValueRef v[3], v01;
1246
1247 for (int i = 0; i < 3; i++) {
1248 v[i] = LLVMBuildExtractElement(ctx->builder, vdata,
1249 LLVMConstInt(ctx->i32, i, 0), "");
1250 }
1251 v01 = ac_build_gather_values(ctx, v, 2);
1252
1253 ac_build_buffer_store_dword(ctx, rsrc, v01, 2, voffset,
1254 soffset, inst_offset, cache_policy);
1255 ac_build_buffer_store_dword(ctx, rsrc, v[2], 1, voffset,
1256 soffset, inst_offset + 8,
1257 cache_policy);
1258 return;
1259 }
1260
1261 /* SWIZZLE_ENABLE requires that soffset isn't folded into voffset
1262 * (voffset is swizzled, but soffset isn't swizzled).
1263 * llvm.amdgcn.buffer.store doesn't have a separate soffset parameter.
1264 */
1265 if (!(cache_policy & ac_swizzled)) {
1266 LLVMValueRef offset = soffset;
1267
1268 if (inst_offset)
1269 offset = LLVMBuildAdd(ctx->builder, offset,
1270 LLVMConstInt(ctx->i32, inst_offset, 0), "");
1271
1272 ac_build_buffer_store_common(ctx, rsrc, ac_to_float(ctx, vdata),
1273 ctx->i32_0, voffset, offset,
1274 cache_policy, false, false);
1275 return;
1276 }
1277
1278 static const unsigned dfmts[] = {
1279 V_008F0C_BUF_DATA_FORMAT_32,
1280 V_008F0C_BUF_DATA_FORMAT_32_32,
1281 V_008F0C_BUF_DATA_FORMAT_32_32_32,
1282 V_008F0C_BUF_DATA_FORMAT_32_32_32_32
1283 };
1284 unsigned dfmt = dfmts[num_channels - 1];
1285 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1286 LLVMValueRef immoffset = LLVMConstInt(ctx->i32, inst_offset, 0);
1287
1288 ac_build_raw_tbuffer_store(ctx, rsrc, vdata, voffset, soffset,
1289 immoffset, num_channels, dfmt, nfmt, cache_policy);
1290 }
1291
1292 static LLVMValueRef
1293 ac_build_buffer_load_common(struct ac_llvm_context *ctx,
1294 LLVMValueRef rsrc,
1295 LLVMValueRef vindex,
1296 LLVMValueRef voffset,
1297 LLVMValueRef soffset,
1298 unsigned num_channels,
1299 LLVMTypeRef channel_type,
1300 unsigned cache_policy,
1301 bool can_speculate,
1302 bool use_format,
1303 bool structurized)
1304 {
1305 LLVMValueRef args[5];
1306 int idx = 0;
1307 args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
1308 if (structurized)
1309 args[idx++] = vindex ? vindex : ctx->i32_0;
1310 args[idx++] = voffset ? voffset : ctx->i32_0;
1311 args[idx++] = soffset ? soffset : ctx->i32_0;
1312 args[idx++] = LLVMConstInt(ctx->i32, get_load_cache_policy(ctx, cache_policy), 0);
1313 unsigned func = !ac_has_vec3_support(ctx->chip_class, use_format) && num_channels == 3 ? 4 : num_channels;
1314 const char *indexing_kind = structurized ? "struct" : "raw";
1315 char name[256], type_name[8];
1316
1317 /* D16 is only supported on gfx8+ */
1318 assert(!use_format ||
1319 (channel_type != ctx->f16 && channel_type != ctx->i16) ||
1320 ctx->chip_class >= GFX8);
1321
1322 LLVMTypeRef type = func > 1 ? LLVMVectorType(channel_type, func) : channel_type;
1323 ac_build_type_name_for_intr(type, type_name, sizeof(type_name));
1324
1325 if (use_format) {
1326 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.load.format.%s",
1327 indexing_kind, type_name);
1328 } else {
1329 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.load.%s",
1330 indexing_kind, type_name);
1331 }
1332
1333 return ac_build_intrinsic(ctx, name, type, args, idx,
1334 ac_get_load_intr_attribs(can_speculate));
1335 }
1336
1337 LLVMValueRef
1338 ac_build_buffer_load(struct ac_llvm_context *ctx,
1339 LLVMValueRef rsrc,
1340 int num_channels,
1341 LLVMValueRef vindex,
1342 LLVMValueRef voffset,
1343 LLVMValueRef soffset,
1344 unsigned inst_offset,
1345 unsigned cache_policy,
1346 bool can_speculate,
1347 bool allow_smem)
1348 {
1349 LLVMValueRef offset = LLVMConstInt(ctx->i32, inst_offset, 0);
1350 if (voffset)
1351 offset = LLVMBuildAdd(ctx->builder, offset, voffset, "");
1352 if (soffset)
1353 offset = LLVMBuildAdd(ctx->builder, offset, soffset, "");
1354
1355 if (allow_smem && !(cache_policy & ac_slc) &&
1356 (!(cache_policy & ac_glc) || ctx->chip_class >= GFX8)) {
1357 assert(vindex == NULL);
1358
1359 LLVMValueRef result[8];
1360
1361 for (int i = 0; i < num_channels; i++) {
1362 if (i) {
1363 offset = LLVMBuildAdd(ctx->builder, offset,
1364 LLVMConstInt(ctx->i32, 4, 0), "");
1365 }
1366 LLVMValueRef args[3] = {
1367 rsrc,
1368 offset,
1369 LLVMConstInt(ctx->i32, get_load_cache_policy(ctx, cache_policy), 0),
1370 };
1371 result[i] = ac_build_intrinsic(ctx,
1372 "llvm.amdgcn.s.buffer.load.f32",
1373 ctx->f32, args, 3,
1374 AC_FUNC_ATTR_READNONE);
1375 }
1376 if (num_channels == 1)
1377 return result[0];
1378
1379 if (num_channels == 3 && !ac_has_vec3_support(ctx->chip_class, false))
1380 result[num_channels++] = LLVMGetUndef(ctx->f32);
1381 return ac_build_gather_values(ctx, result, num_channels);
1382 }
1383
1384 return ac_build_buffer_load_common(ctx, rsrc, vindex,
1385 offset, ctx->i32_0,
1386 num_channels, ctx->f32,
1387 cache_policy,
1388 can_speculate, false, false);
1389 }
1390
1391 LLVMValueRef ac_build_buffer_load_format(struct ac_llvm_context *ctx,
1392 LLVMValueRef rsrc,
1393 LLVMValueRef vindex,
1394 LLVMValueRef voffset,
1395 unsigned num_channels,
1396 unsigned cache_policy,
1397 bool can_speculate,
1398 bool d16)
1399 {
1400 return ac_build_buffer_load_common(ctx, rsrc, vindex, voffset,
1401 ctx->i32_0, num_channels,
1402 d16 ? ctx->f16 : ctx->f32,
1403 cache_policy, can_speculate,
1404 true, true);
1405 }
1406
1407 static LLVMValueRef
1408 ac_build_tbuffer_load(struct ac_llvm_context *ctx,
1409 LLVMValueRef rsrc,
1410 LLVMValueRef vindex,
1411 LLVMValueRef voffset,
1412 LLVMValueRef soffset,
1413 LLVMValueRef immoffset,
1414 unsigned num_channels,
1415 unsigned dfmt,
1416 unsigned nfmt,
1417 unsigned cache_policy,
1418 bool can_speculate,
1419 bool structurized)
1420 {
1421 voffset = LLVMBuildAdd(ctx->builder, voffset, immoffset, "");
1422
1423 LLVMValueRef args[6];
1424 int idx = 0;
1425 args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
1426 if (structurized)
1427 args[idx++] = vindex ? vindex : ctx->i32_0;
1428 args[idx++] = voffset ? voffset : ctx->i32_0;
1429 args[idx++] = soffset ? soffset : ctx->i32_0;
1430 args[idx++] = LLVMConstInt(ctx->i32, ac_get_tbuffer_format(ctx->chip_class, dfmt, nfmt), 0);
1431 args[idx++] = LLVMConstInt(ctx->i32, get_load_cache_policy(ctx, cache_policy), 0);
1432 unsigned func = !ac_has_vec3_support(ctx->chip_class, true) && num_channels == 3 ? 4 : num_channels;
1433 const char *indexing_kind = structurized ? "struct" : "raw";
1434 char name[256], type_name[8];
1435
1436 LLVMTypeRef type = func > 1 ? LLVMVectorType(ctx->i32, func) : ctx->i32;
1437 ac_build_type_name_for_intr(type, type_name, sizeof(type_name));
1438
1439 snprintf(name, sizeof(name), "llvm.amdgcn.%s.tbuffer.load.%s",
1440 indexing_kind, type_name);
1441
1442 return ac_build_intrinsic(ctx, name, type, args, idx,
1443 ac_get_load_intr_attribs(can_speculate));
1444 }
1445
1446 LLVMValueRef
1447 ac_build_struct_tbuffer_load(struct ac_llvm_context *ctx,
1448 LLVMValueRef rsrc,
1449 LLVMValueRef vindex,
1450 LLVMValueRef voffset,
1451 LLVMValueRef soffset,
1452 LLVMValueRef immoffset,
1453 unsigned num_channels,
1454 unsigned dfmt,
1455 unsigned nfmt,
1456 unsigned cache_policy,
1457 bool can_speculate)
1458 {
1459 return ac_build_tbuffer_load(ctx, rsrc, vindex, voffset, soffset,
1460 immoffset, num_channels, dfmt, nfmt,
1461 cache_policy, can_speculate, true);
1462 }
1463
1464 LLVMValueRef
1465 ac_build_raw_tbuffer_load(struct ac_llvm_context *ctx,
1466 LLVMValueRef rsrc,
1467 LLVMValueRef voffset,
1468 LLVMValueRef soffset,
1469 LLVMValueRef immoffset,
1470 unsigned num_channels,
1471 unsigned dfmt,
1472 unsigned nfmt,
1473 unsigned cache_policy,
1474 bool can_speculate)
1475 {
1476 return ac_build_tbuffer_load(ctx, rsrc, NULL, voffset, soffset,
1477 immoffset, num_channels, dfmt, nfmt,
1478 cache_policy, can_speculate, false);
1479 }
1480
1481 LLVMValueRef
1482 ac_build_tbuffer_load_short(struct ac_llvm_context *ctx,
1483 LLVMValueRef rsrc,
1484 LLVMValueRef voffset,
1485 LLVMValueRef soffset,
1486 LLVMValueRef immoffset,
1487 unsigned cache_policy)
1488 {
1489 LLVMValueRef res;
1490
1491 if (LLVM_VERSION_MAJOR >= 9) {
1492 voffset = LLVMBuildAdd(ctx->builder, voffset, immoffset, "");
1493
1494 /* LLVM 9+ supports i8/i16 with struct/raw intrinsics. */
1495 res = ac_build_buffer_load_common(ctx, rsrc, NULL,
1496 voffset, soffset,
1497 1, ctx->i16, cache_policy,
1498 false, false, false);
1499 } else {
1500 unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_16;
1501 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1502
1503 res = ac_build_raw_tbuffer_load(ctx, rsrc, voffset, soffset,
1504 immoffset, 1, dfmt, nfmt, cache_policy,
1505 false);
1506
1507 res = LLVMBuildTrunc(ctx->builder, res, ctx->i16, "");
1508 }
1509
1510 return res;
1511 }
1512
1513 LLVMValueRef
1514 ac_build_tbuffer_load_byte(struct ac_llvm_context *ctx,
1515 LLVMValueRef rsrc,
1516 LLVMValueRef voffset,
1517 LLVMValueRef soffset,
1518 LLVMValueRef immoffset,
1519 unsigned cache_policy)
1520 {
1521 LLVMValueRef res;
1522
1523 if (LLVM_VERSION_MAJOR >= 9) {
1524 voffset = LLVMBuildAdd(ctx->builder, voffset, immoffset, "");
1525
1526 /* LLVM 9+ supports i8/i16 with struct/raw intrinsics. */
1527 res = ac_build_buffer_load_common(ctx, rsrc, NULL,
1528 voffset, soffset,
1529 1, ctx->i8, cache_policy,
1530 false, false, false);
1531 } else {
1532 unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_8;
1533 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1534
1535 res = ac_build_raw_tbuffer_load(ctx, rsrc, voffset, soffset,
1536 immoffset, 1, dfmt, nfmt, cache_policy,
1537 false);
1538
1539 res = LLVMBuildTrunc(ctx->builder, res, ctx->i8, "");
1540 }
1541
1542 return res;
1543 }
1544
1545 /**
1546 * Convert an 11- or 10-bit unsigned floating point number to an f32.
1547 *
1548 * The input exponent is expected to be biased analogous to IEEE-754, i.e. by
1549 * 2^(exp_bits-1) - 1 (as defined in OpenGL and other graphics APIs).
1550 */
1551 static LLVMValueRef
1552 ac_ufN_to_float(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned exp_bits, unsigned mant_bits)
1553 {
1554 assert(LLVMTypeOf(src) == ctx->i32);
1555
1556 LLVMValueRef tmp;
1557 LLVMValueRef mantissa;
1558 mantissa = LLVMBuildAnd(ctx->builder, src, LLVMConstInt(ctx->i32, (1 << mant_bits) - 1, false), "");
1559
1560 /* Converting normal numbers is just a shift + correcting the exponent bias */
1561 unsigned normal_shift = 23 - mant_bits;
1562 unsigned bias_shift = 127 - ((1 << (exp_bits - 1)) - 1);
1563 LLVMValueRef shifted, normal;
1564
1565 shifted = LLVMBuildShl(ctx->builder, src, LLVMConstInt(ctx->i32, normal_shift, false), "");
1566 normal = LLVMBuildAdd(ctx->builder, shifted, LLVMConstInt(ctx->i32, bias_shift << 23, false), "");
1567
1568 /* Converting nan/inf numbers is the same, but with a different exponent update */
1569 LLVMValueRef naninf;
1570 naninf = LLVMBuildOr(ctx->builder, normal, LLVMConstInt(ctx->i32, 0xff << 23, false), "");
1571
1572 /* Converting denormals is the complex case: determine the leading zeros of the
1573 * mantissa to obtain the correct shift for the mantissa and exponent correction.
1574 */
1575 LLVMValueRef denormal;
1576 LLVMValueRef params[2] = {
1577 mantissa,
1578 ctx->i1true, /* result can be undef when arg is 0 */
1579 };
1580 LLVMValueRef ctlz = ac_build_intrinsic(ctx, "llvm.ctlz.i32", ctx->i32,
1581 params, 2, AC_FUNC_ATTR_READNONE);
1582
1583 /* Shift such that the leading 1 ends up as the LSB of the exponent field. */
1584 tmp = LLVMBuildSub(ctx->builder, ctlz, LLVMConstInt(ctx->i32, 8, false), "");
1585 denormal = LLVMBuildShl(ctx->builder, mantissa, tmp, "");
1586
1587 unsigned denormal_exp = bias_shift + (32 - mant_bits) - 1;
1588 tmp = LLVMBuildSub(ctx->builder, LLVMConstInt(ctx->i32, denormal_exp, false), ctlz, "");
1589 tmp = LLVMBuildShl(ctx->builder, tmp, LLVMConstInt(ctx->i32, 23, false), "");
1590 denormal = LLVMBuildAdd(ctx->builder, denormal, tmp, "");
1591
1592 /* Select the final result. */
1593 LLVMValueRef result;
1594
1595 tmp = LLVMBuildICmp(ctx->builder, LLVMIntUGE, src,
1596 LLVMConstInt(ctx->i32, ((1 << exp_bits) - 1) << mant_bits, false), "");
1597 result = LLVMBuildSelect(ctx->builder, tmp, naninf, normal, "");
1598
1599 tmp = LLVMBuildICmp(ctx->builder, LLVMIntUGE, src,
1600 LLVMConstInt(ctx->i32, 1 << mant_bits, false), "");
1601 result = LLVMBuildSelect(ctx->builder, tmp, result, denormal, "");
1602
1603 tmp = LLVMBuildICmp(ctx->builder, LLVMIntNE, src, ctx->i32_0, "");
1604 result = LLVMBuildSelect(ctx->builder, tmp, result, ctx->i32_0, "");
1605
1606 return ac_to_float(ctx, result);
1607 }
1608
1609 /**
1610 * Generate a fully general open coded buffer format fetch with all required
1611 * fixups suitable for vertex fetch, using non-format buffer loads.
1612 *
1613 * Some combinations of argument values have special interpretations:
1614 * - size = 8 bytes, format = fixed indicates PIPE_FORMAT_R11G11B10_FLOAT
1615 * - size = 8 bytes, format != {float,fixed} indicates a 2_10_10_10 data format
1616 *
1617 * \param log_size log(size of channel in bytes)
1618 * \param num_channels number of channels (1 to 4)
1619 * \param format AC_FETCH_FORMAT_xxx value
1620 * \param reverse whether XYZ channels are reversed
1621 * \param known_aligned whether the source is known to be aligned to hardware's
1622 * effective element size for loading the given format
1623 * (note: this means dword alignment for 8_8_8_8, 16_16, etc.)
1624 * \param rsrc buffer resource descriptor
1625 * \return the resulting vector of floats or integers bitcast to <4 x i32>
1626 */
1627 LLVMValueRef
1628 ac_build_opencoded_load_format(struct ac_llvm_context *ctx,
1629 unsigned log_size,
1630 unsigned num_channels,
1631 unsigned format,
1632 bool reverse,
1633 bool known_aligned,
1634 LLVMValueRef rsrc,
1635 LLVMValueRef vindex,
1636 LLVMValueRef voffset,
1637 LLVMValueRef soffset,
1638 unsigned cache_policy,
1639 bool can_speculate)
1640 {
1641 LLVMValueRef tmp;
1642 unsigned load_log_size = log_size;
1643 unsigned load_num_channels = num_channels;
1644 if (log_size == 3) {
1645 load_log_size = 2;
1646 if (format == AC_FETCH_FORMAT_FLOAT) {
1647 load_num_channels = 2 * num_channels;
1648 } else {
1649 load_num_channels = 1; /* 10_11_11 or 2_10_10_10 */
1650 }
1651 }
1652
1653 int log_recombine = 0;
1654 if (ctx->chip_class == GFX6 && !known_aligned) {
1655 /* Avoid alignment restrictions by loading one byte at a time. */
1656 load_num_channels <<= load_log_size;
1657 log_recombine = load_log_size;
1658 load_log_size = 0;
1659 } else if (load_num_channels == 2 || load_num_channels == 4) {
1660 log_recombine = -util_logbase2(load_num_channels);
1661 load_num_channels = 1;
1662 load_log_size += -log_recombine;
1663 }
1664
1665 assert(load_log_size >= 2 || LLVM_VERSION_MAJOR >= 9);
1666
1667 LLVMValueRef loads[32]; /* up to 32 bytes */
1668 for (unsigned i = 0; i < load_num_channels; ++i) {
1669 tmp = LLVMBuildAdd(ctx->builder, soffset,
1670 LLVMConstInt(ctx->i32, i << load_log_size, false), "");
1671 LLVMTypeRef channel_type = load_log_size == 0 ? ctx->i8 :
1672 load_log_size == 1 ? ctx->i16 : ctx->i32;
1673 unsigned num_channels = 1 << (MAX2(load_log_size, 2) - 2);
1674 loads[i] = ac_build_buffer_load_common(
1675 ctx, rsrc, vindex, voffset, tmp,
1676 num_channels, channel_type, cache_policy,
1677 can_speculate, false, true);
1678 if (load_log_size >= 2)
1679 loads[i] = ac_to_integer(ctx, loads[i]);
1680 }
1681
1682 if (log_recombine > 0) {
1683 /* Recombine bytes if necessary (GFX6 only) */
1684 LLVMTypeRef dst_type = log_recombine == 2 ? ctx->i32 : ctx->i16;
1685
1686 for (unsigned src = 0, dst = 0; src < load_num_channels; ++dst) {
1687 LLVMValueRef accum = NULL;
1688 for (unsigned i = 0; i < (1 << log_recombine); ++i, ++src) {
1689 tmp = LLVMBuildZExt(ctx->builder, loads[src], dst_type, "");
1690 if (i == 0) {
1691 accum = tmp;
1692 } else {
1693 tmp = LLVMBuildShl(ctx->builder, tmp,
1694 LLVMConstInt(dst_type, 8 * i, false), "");
1695 accum = LLVMBuildOr(ctx->builder, accum, tmp, "");
1696 }
1697 }
1698 loads[dst] = accum;
1699 }
1700 } else if (log_recombine < 0) {
1701 /* Split vectors of dwords */
1702 if (load_log_size > 2) {
1703 assert(load_num_channels == 1);
1704 LLVMValueRef loaded = loads[0];
1705 unsigned log_split = load_log_size - 2;
1706 log_recombine += log_split;
1707 load_num_channels = 1 << log_split;
1708 load_log_size = 2;
1709 for (unsigned i = 0; i < load_num_channels; ++i) {
1710 tmp = LLVMConstInt(ctx->i32, i, false);
1711 loads[i] = LLVMBuildExtractElement(ctx->builder, loaded, tmp, "");
1712 }
1713 }
1714
1715 /* Further split dwords and shorts if required */
1716 if (log_recombine < 0) {
1717 for (unsigned src = load_num_channels,
1718 dst = load_num_channels << -log_recombine;
1719 src > 0; --src) {
1720 unsigned dst_bits = 1 << (3 + load_log_size + log_recombine);
1721 LLVMTypeRef dst_type = LLVMIntTypeInContext(ctx->context, dst_bits);
1722 LLVMValueRef loaded = loads[src - 1];
1723 LLVMTypeRef loaded_type = LLVMTypeOf(loaded);
1724 for (unsigned i = 1 << -log_recombine; i > 0; --i, --dst) {
1725 tmp = LLVMConstInt(loaded_type, dst_bits * (i - 1), false);
1726 tmp = LLVMBuildLShr(ctx->builder, loaded, tmp, "");
1727 loads[dst - 1] = LLVMBuildTrunc(ctx->builder, tmp, dst_type, "");
1728 }
1729 }
1730 }
1731 }
1732
1733 if (log_size == 3) {
1734 if (format == AC_FETCH_FORMAT_FLOAT) {
1735 for (unsigned i = 0; i < num_channels; ++i) {
1736 tmp = ac_build_gather_values(ctx, &loads[2 * i], 2);
1737 loads[i] = LLVMBuildBitCast(ctx->builder, tmp, ctx->f64, "");
1738 }
1739 } else if (format == AC_FETCH_FORMAT_FIXED) {
1740 /* 10_11_11_FLOAT */
1741 LLVMValueRef data = loads[0];
1742 LLVMValueRef i32_2047 = LLVMConstInt(ctx->i32, 2047, false);
1743 LLVMValueRef r = LLVMBuildAnd(ctx->builder, data, i32_2047, "");
1744 tmp = LLVMBuildLShr(ctx->builder, data, LLVMConstInt(ctx->i32, 11, false), "");
1745 LLVMValueRef g = LLVMBuildAnd(ctx->builder, tmp, i32_2047, "");
1746 LLVMValueRef b = LLVMBuildLShr(ctx->builder, data, LLVMConstInt(ctx->i32, 22, false), "");
1747
1748 loads[0] = ac_to_integer(ctx, ac_ufN_to_float(ctx, r, 5, 6));
1749 loads[1] = ac_to_integer(ctx, ac_ufN_to_float(ctx, g, 5, 6));
1750 loads[2] = ac_to_integer(ctx, ac_ufN_to_float(ctx, b, 5, 5));
1751
1752 num_channels = 3;
1753 log_size = 2;
1754 format = AC_FETCH_FORMAT_FLOAT;
1755 } else {
1756 /* 2_10_10_10 data formats */
1757 LLVMValueRef data = loads[0];
1758 LLVMTypeRef i10 = LLVMIntTypeInContext(ctx->context, 10);
1759 LLVMTypeRef i2 = LLVMIntTypeInContext(ctx->context, 2);
1760 loads[0] = LLVMBuildTrunc(ctx->builder, data, i10, "");
1761 tmp = LLVMBuildLShr(ctx->builder, data, LLVMConstInt(ctx->i32, 10, false), "");
1762 loads[1] = LLVMBuildTrunc(ctx->builder, tmp, i10, "");
1763 tmp = LLVMBuildLShr(ctx->builder, data, LLVMConstInt(ctx->i32, 20, false), "");
1764 loads[2] = LLVMBuildTrunc(ctx->builder, tmp, i10, "");
1765 tmp = LLVMBuildLShr(ctx->builder, data, LLVMConstInt(ctx->i32, 30, false), "");
1766 loads[3] = LLVMBuildTrunc(ctx->builder, tmp, i2, "");
1767
1768 num_channels = 4;
1769 }
1770 }
1771
1772 if (format == AC_FETCH_FORMAT_FLOAT) {
1773 if (log_size != 2) {
1774 for (unsigned chan = 0; chan < num_channels; ++chan) {
1775 tmp = ac_to_float(ctx, loads[chan]);
1776 if (log_size == 3)
1777 tmp = LLVMBuildFPTrunc(ctx->builder, tmp, ctx->f32, "");
1778 else if (log_size == 1)
1779 tmp = LLVMBuildFPExt(ctx->builder, tmp, ctx->f32, "");
1780 loads[chan] = ac_to_integer(ctx, tmp);
1781 }
1782 }
1783 } else if (format == AC_FETCH_FORMAT_UINT) {
1784 if (log_size != 2) {
1785 for (unsigned chan = 0; chan < num_channels; ++chan)
1786 loads[chan] = LLVMBuildZExt(ctx->builder, loads[chan], ctx->i32, "");
1787 }
1788 } else if (format == AC_FETCH_FORMAT_SINT) {
1789 if (log_size != 2) {
1790 for (unsigned chan = 0; chan < num_channels; ++chan)
1791 loads[chan] = LLVMBuildSExt(ctx->builder, loads[chan], ctx->i32, "");
1792 }
1793 } else {
1794 bool unsign = format == AC_FETCH_FORMAT_UNORM ||
1795 format == AC_FETCH_FORMAT_USCALED ||
1796 format == AC_FETCH_FORMAT_UINT;
1797
1798 for (unsigned chan = 0; chan < num_channels; ++chan) {
1799 if (unsign) {
1800 tmp = LLVMBuildUIToFP(ctx->builder, loads[chan], ctx->f32, "");
1801 } else {
1802 tmp = LLVMBuildSIToFP(ctx->builder, loads[chan], ctx->f32, "");
1803 }
1804
1805 LLVMValueRef scale = NULL;
1806 if (format == AC_FETCH_FORMAT_FIXED) {
1807 assert(log_size == 2);
1808 scale = LLVMConstReal(ctx->f32, 1.0 / 0x10000);
1809 } else if (format == AC_FETCH_FORMAT_UNORM) {
1810 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(loads[chan]));
1811 scale = LLVMConstReal(ctx->f32, 1.0 / (((uint64_t)1 << bits) - 1));
1812 } else if (format == AC_FETCH_FORMAT_SNORM) {
1813 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(loads[chan]));
1814 scale = LLVMConstReal(ctx->f32, 1.0 / (((uint64_t)1 << (bits - 1)) - 1));
1815 }
1816 if (scale)
1817 tmp = LLVMBuildFMul(ctx->builder, tmp, scale, "");
1818
1819 if (format == AC_FETCH_FORMAT_SNORM) {
1820 /* Clamp to [-1, 1] */
1821 LLVMValueRef neg_one = LLVMConstReal(ctx->f32, -1.0);
1822 LLVMValueRef clamp =
1823 LLVMBuildFCmp(ctx->builder, LLVMRealULT, tmp, neg_one, "");
1824 tmp = LLVMBuildSelect(ctx->builder, clamp, neg_one, tmp, "");
1825 }
1826
1827 loads[chan] = ac_to_integer(ctx, tmp);
1828 }
1829 }
1830
1831 while (num_channels < 4) {
1832 if (format == AC_FETCH_FORMAT_UINT || format == AC_FETCH_FORMAT_SINT) {
1833 loads[num_channels] = num_channels == 3 ? ctx->i32_1 : ctx->i32_0;
1834 } else {
1835 loads[num_channels] = ac_to_integer(ctx, num_channels == 3 ? ctx->f32_1 : ctx->f32_0);
1836 }
1837 num_channels++;
1838 }
1839
1840 if (reverse) {
1841 tmp = loads[0];
1842 loads[0] = loads[2];
1843 loads[2] = tmp;
1844 }
1845
1846 return ac_build_gather_values(ctx, loads, 4);
1847 }
1848
1849 static void
1850 ac_build_tbuffer_store(struct ac_llvm_context *ctx,
1851 LLVMValueRef rsrc,
1852 LLVMValueRef vdata,
1853 LLVMValueRef vindex,
1854 LLVMValueRef voffset,
1855 LLVMValueRef soffset,
1856 LLVMValueRef immoffset,
1857 unsigned num_channels,
1858 unsigned dfmt,
1859 unsigned nfmt,
1860 unsigned cache_policy,
1861 bool structurized)
1862 {
1863 voffset = LLVMBuildAdd(ctx->builder, voffset ? voffset : ctx->i32_0,
1864 immoffset, "");
1865
1866 LLVMValueRef args[7];
1867 int idx = 0;
1868 args[idx++] = vdata;
1869 args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
1870 if (structurized)
1871 args[idx++] = vindex ? vindex : ctx->i32_0;
1872 args[idx++] = voffset ? voffset : ctx->i32_0;
1873 args[idx++] = soffset ? soffset : ctx->i32_0;
1874 args[idx++] = LLVMConstInt(ctx->i32, ac_get_tbuffer_format(ctx->chip_class, dfmt, nfmt), 0);
1875 args[idx++] = LLVMConstInt(ctx->i32, cache_policy, 0);
1876 unsigned func = !ac_has_vec3_support(ctx->chip_class, true) && num_channels == 3 ? 4 : num_channels;
1877 const char *indexing_kind = structurized ? "struct" : "raw";
1878 char name[256], type_name[8];
1879
1880 LLVMTypeRef type = func > 1 ? LLVMVectorType(ctx->i32, func) : ctx->i32;
1881 ac_build_type_name_for_intr(type, type_name, sizeof(type_name));
1882
1883 snprintf(name, sizeof(name), "llvm.amdgcn.%s.tbuffer.store.%s",
1884 indexing_kind, type_name);
1885
1886 ac_build_intrinsic(ctx, name, ctx->voidt, args, idx,
1887 AC_FUNC_ATTR_INACCESSIBLE_MEM_ONLY);
1888 }
1889
1890 void
1891 ac_build_struct_tbuffer_store(struct ac_llvm_context *ctx,
1892 LLVMValueRef rsrc,
1893 LLVMValueRef vdata,
1894 LLVMValueRef vindex,
1895 LLVMValueRef voffset,
1896 LLVMValueRef soffset,
1897 LLVMValueRef immoffset,
1898 unsigned num_channels,
1899 unsigned dfmt,
1900 unsigned nfmt,
1901 unsigned cache_policy)
1902 {
1903 ac_build_tbuffer_store(ctx, rsrc, vdata, vindex, voffset, soffset,
1904 immoffset, num_channels, dfmt, nfmt, cache_policy,
1905 true);
1906 }
1907
1908 void
1909 ac_build_raw_tbuffer_store(struct ac_llvm_context *ctx,
1910 LLVMValueRef rsrc,
1911 LLVMValueRef vdata,
1912 LLVMValueRef voffset,
1913 LLVMValueRef soffset,
1914 LLVMValueRef immoffset,
1915 unsigned num_channels,
1916 unsigned dfmt,
1917 unsigned nfmt,
1918 unsigned cache_policy)
1919 {
1920 ac_build_tbuffer_store(ctx, rsrc, vdata, NULL, voffset, soffset,
1921 immoffset, num_channels, dfmt, nfmt, cache_policy,
1922 false);
1923 }
1924
1925 void
1926 ac_build_tbuffer_store_short(struct ac_llvm_context *ctx,
1927 LLVMValueRef rsrc,
1928 LLVMValueRef vdata,
1929 LLVMValueRef voffset,
1930 LLVMValueRef soffset,
1931 unsigned cache_policy)
1932 {
1933 vdata = LLVMBuildBitCast(ctx->builder, vdata, ctx->i16, "");
1934
1935 if (LLVM_VERSION_MAJOR >= 9) {
1936 /* LLVM 9+ supports i8/i16 with struct/raw intrinsics. */
1937 ac_build_buffer_store_common(ctx, rsrc, vdata, NULL,
1938 voffset, soffset, cache_policy,
1939 false, false);
1940 } else {
1941 unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_16;
1942 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1943
1944 vdata = LLVMBuildZExt(ctx->builder, vdata, ctx->i32, "");
1945
1946 ac_build_raw_tbuffer_store(ctx, rsrc, vdata, voffset, soffset,
1947 ctx->i32_0, 1, dfmt, nfmt, cache_policy);
1948 }
1949 }
1950
1951 void
1952 ac_build_tbuffer_store_byte(struct ac_llvm_context *ctx,
1953 LLVMValueRef rsrc,
1954 LLVMValueRef vdata,
1955 LLVMValueRef voffset,
1956 LLVMValueRef soffset,
1957 unsigned cache_policy)
1958 {
1959 vdata = LLVMBuildBitCast(ctx->builder, vdata, ctx->i8, "");
1960
1961 if (LLVM_VERSION_MAJOR >= 9) {
1962 /* LLVM 9+ supports i8/i16 with struct/raw intrinsics. */
1963 ac_build_buffer_store_common(ctx, rsrc, vdata, NULL,
1964 voffset, soffset, cache_policy,
1965 false, false);
1966 } else {
1967 unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_8;
1968 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1969
1970 vdata = LLVMBuildZExt(ctx->builder, vdata, ctx->i32, "");
1971
1972 ac_build_raw_tbuffer_store(ctx, rsrc, vdata, voffset, soffset,
1973 ctx->i32_0, 1, dfmt, nfmt, cache_policy);
1974 }
1975 }
1976 /**
1977 * Set range metadata on an instruction. This can only be used on load and
1978 * call instructions. If you know an instruction can only produce the values
1979 * 0, 1, 2, you would do set_range_metadata(value, 0, 3);
1980 * \p lo is the minimum value inclusive.
1981 * \p hi is the maximum value exclusive.
1982 */
1983 static void set_range_metadata(struct ac_llvm_context *ctx,
1984 LLVMValueRef value, unsigned lo, unsigned hi)
1985 {
1986 LLVMValueRef range_md, md_args[2];
1987 LLVMTypeRef type = LLVMTypeOf(value);
1988 LLVMContextRef context = LLVMGetTypeContext(type);
1989
1990 md_args[0] = LLVMConstInt(type, lo, false);
1991 md_args[1] = LLVMConstInt(type, hi, false);
1992 range_md = LLVMMDNodeInContext(context, md_args, 2);
1993 LLVMSetMetadata(value, ctx->range_md_kind, range_md);
1994 }
1995
1996 LLVMValueRef
1997 ac_get_thread_id(struct ac_llvm_context *ctx)
1998 {
1999 LLVMValueRef tid;
2000
2001 LLVMValueRef tid_args[2];
2002 tid_args[0] = LLVMConstInt(ctx->i32, 0xffffffff, false);
2003 tid_args[1] = ctx->i32_0;
2004 tid_args[1] = ac_build_intrinsic(ctx,
2005 "llvm.amdgcn.mbcnt.lo", ctx->i32,
2006 tid_args, 2, AC_FUNC_ATTR_READNONE);
2007
2008 if (ctx->wave_size == 32) {
2009 tid = tid_args[1];
2010 } else {
2011 tid = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi",
2012 ctx->i32, tid_args,
2013 2, AC_FUNC_ATTR_READNONE);
2014 }
2015 set_range_metadata(ctx, tid, 0, ctx->wave_size);
2016 return tid;
2017 }
2018
2019 /*
2020 * AMD GCN implements derivatives using the local data store (LDS)
2021 * All writes to the LDS happen in all executing threads at
2022 * the same time. TID is the Thread ID for the current
2023 * thread and is a value between 0 and 63, representing
2024 * the thread's position in the wavefront.
2025 *
2026 * For the pixel shader threads are grouped into quads of four pixels.
2027 * The TIDs of the pixels of a quad are:
2028 *
2029 * +------+------+
2030 * |4n + 0|4n + 1|
2031 * +------+------+
2032 * |4n + 2|4n + 3|
2033 * +------+------+
2034 *
2035 * So, masking the TID with 0xfffffffc yields the TID of the top left pixel
2036 * of the quad, masking with 0xfffffffd yields the TID of the top pixel of
2037 * the current pixel's column, and masking with 0xfffffffe yields the TID
2038 * of the left pixel of the current pixel's row.
2039 *
2040 * Adding 1 yields the TID of the pixel to the right of the left pixel, and
2041 * adding 2 yields the TID of the pixel below the top pixel.
2042 */
2043 LLVMValueRef
2044 ac_build_ddxy(struct ac_llvm_context *ctx,
2045 uint32_t mask,
2046 int idx,
2047 LLVMValueRef val)
2048 {
2049 unsigned tl_lanes[4], trbl_lanes[4];
2050 char name[32], type[8];
2051 LLVMValueRef tl, trbl;
2052 LLVMTypeRef result_type;
2053 LLVMValueRef result;
2054
2055 result_type = ac_to_float_type(ctx, LLVMTypeOf(val));
2056
2057 if (result_type == ctx->f16)
2058 val = LLVMBuildZExt(ctx->builder, val, ctx->i32, "");
2059 else if (result_type == ctx->v2f16)
2060 val = LLVMBuildBitCast(ctx->builder, val, ctx->i32, "");
2061
2062 for (unsigned i = 0; i < 4; ++i) {
2063 tl_lanes[i] = i & mask;
2064 trbl_lanes[i] = (i & mask) + idx;
2065 }
2066
2067 tl = ac_build_quad_swizzle(ctx, val,
2068 tl_lanes[0], tl_lanes[1],
2069 tl_lanes[2], tl_lanes[3]);
2070 trbl = ac_build_quad_swizzle(ctx, val,
2071 trbl_lanes[0], trbl_lanes[1],
2072 trbl_lanes[2], trbl_lanes[3]);
2073
2074 if (result_type == ctx->f16) {
2075 tl = LLVMBuildTrunc(ctx->builder, tl, ctx->i16, "");
2076 trbl = LLVMBuildTrunc(ctx->builder, trbl, ctx->i16, "");
2077 }
2078
2079 tl = LLVMBuildBitCast(ctx->builder, tl, result_type, "");
2080 trbl = LLVMBuildBitCast(ctx->builder, trbl, result_type, "");
2081 result = LLVMBuildFSub(ctx->builder, trbl, tl, "");
2082
2083 ac_build_type_name_for_intr(result_type, type, sizeof(type));
2084 snprintf(name, sizeof(name), "llvm.amdgcn.wqm.%s", type);
2085
2086 return ac_build_intrinsic(ctx, name, result_type, &result, 1, 0);
2087 }
2088
2089 void
2090 ac_build_sendmsg(struct ac_llvm_context *ctx,
2091 uint32_t msg,
2092 LLVMValueRef wave_id)
2093 {
2094 LLVMValueRef args[2];
2095 args[0] = LLVMConstInt(ctx->i32, msg, false);
2096 args[1] = wave_id;
2097 ac_build_intrinsic(ctx, "llvm.amdgcn.s.sendmsg", ctx->voidt, args, 2, 0);
2098 }
2099
2100 LLVMValueRef
2101 ac_build_imsb(struct ac_llvm_context *ctx,
2102 LLVMValueRef arg,
2103 LLVMTypeRef dst_type)
2104 {
2105 LLVMValueRef msb = ac_build_intrinsic(ctx, "llvm.amdgcn.sffbh.i32",
2106 dst_type, &arg, 1,
2107 AC_FUNC_ATTR_READNONE);
2108
2109 /* The HW returns the last bit index from MSB, but NIR/TGSI wants
2110 * the index from LSB. Invert it by doing "31 - msb". */
2111 msb = LLVMBuildSub(ctx->builder, LLVMConstInt(ctx->i32, 31, false),
2112 msb, "");
2113
2114 LLVMValueRef all_ones = LLVMConstInt(ctx->i32, -1, true);
2115 LLVMValueRef cond = LLVMBuildOr(ctx->builder,
2116 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
2117 arg, ctx->i32_0, ""),
2118 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
2119 arg, all_ones, ""), "");
2120
2121 return LLVMBuildSelect(ctx->builder, cond, all_ones, msb, "");
2122 }
2123
2124 LLVMValueRef
2125 ac_build_umsb(struct ac_llvm_context *ctx,
2126 LLVMValueRef arg,
2127 LLVMTypeRef dst_type)
2128 {
2129 const char *intrin_name;
2130 LLVMTypeRef type;
2131 LLVMValueRef highest_bit;
2132 LLVMValueRef zero;
2133 unsigned bitsize;
2134
2135 bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(arg));
2136 switch (bitsize) {
2137 case 64:
2138 intrin_name = "llvm.ctlz.i64";
2139 type = ctx->i64;
2140 highest_bit = LLVMConstInt(ctx->i64, 63, false);
2141 zero = ctx->i64_0;
2142 break;
2143 case 32:
2144 intrin_name = "llvm.ctlz.i32";
2145 type = ctx->i32;
2146 highest_bit = LLVMConstInt(ctx->i32, 31, false);
2147 zero = ctx->i32_0;
2148 break;
2149 case 16:
2150 intrin_name = "llvm.ctlz.i16";
2151 type = ctx->i16;
2152 highest_bit = LLVMConstInt(ctx->i16, 15, false);
2153 zero = ctx->i16_0;
2154 break;
2155 case 8:
2156 intrin_name = "llvm.ctlz.i8";
2157 type = ctx->i8;
2158 highest_bit = LLVMConstInt(ctx->i8, 7, false);
2159 zero = ctx->i8_0;
2160 break;
2161 default:
2162 unreachable(!"invalid bitsize");
2163 break;
2164 }
2165
2166 LLVMValueRef params[2] = {
2167 arg,
2168 ctx->i1true,
2169 };
2170
2171 LLVMValueRef msb = ac_build_intrinsic(ctx, intrin_name, type,
2172 params, 2,
2173 AC_FUNC_ATTR_READNONE);
2174
2175 /* The HW returns the last bit index from MSB, but TGSI/NIR wants
2176 * the index from LSB. Invert it by doing "31 - msb". */
2177 msb = LLVMBuildSub(ctx->builder, highest_bit, msb, "");
2178
2179 if (bitsize == 64) {
2180 msb = LLVMBuildTrunc(ctx->builder, msb, ctx->i32, "");
2181 } else if (bitsize < 32) {
2182 msb = LLVMBuildSExt(ctx->builder, msb, ctx->i32, "");
2183 }
2184
2185 /* check for zero */
2186 return LLVMBuildSelect(ctx->builder,
2187 LLVMBuildICmp(ctx->builder, LLVMIntEQ, arg, zero, ""),
2188 LLVMConstInt(ctx->i32, -1, true), msb, "");
2189 }
2190
2191 LLVMValueRef ac_build_fmin(struct ac_llvm_context *ctx, LLVMValueRef a,
2192 LLVMValueRef b)
2193 {
2194 char name[64], type[64];
2195
2196 ac_build_type_name_for_intr(LLVMTypeOf(a), type, sizeof(type));
2197 snprintf(name, sizeof(name), "llvm.minnum.%s", type);
2198 LLVMValueRef args[2] = {a, b};
2199 return ac_build_intrinsic(ctx, name, LLVMTypeOf(a), args, 2,
2200 AC_FUNC_ATTR_READNONE);
2201 }
2202
2203 LLVMValueRef ac_build_fmax(struct ac_llvm_context *ctx, LLVMValueRef a,
2204 LLVMValueRef b)
2205 {
2206 char name[64], type[64];
2207
2208 ac_build_type_name_for_intr(LLVMTypeOf(a), type, sizeof(type));
2209 snprintf(name, sizeof(name), "llvm.maxnum.%s", type);
2210 LLVMValueRef args[2] = {a, b};
2211 return ac_build_intrinsic(ctx, name, LLVMTypeOf(a), args, 2,
2212 AC_FUNC_ATTR_READNONE);
2213 }
2214
2215 LLVMValueRef ac_build_imin(struct ac_llvm_context *ctx, LLVMValueRef a,
2216 LLVMValueRef b)
2217 {
2218 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSLE, a, b, "");
2219 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
2220 }
2221
2222 LLVMValueRef ac_build_imax(struct ac_llvm_context *ctx, LLVMValueRef a,
2223 LLVMValueRef b)
2224 {
2225 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, a, b, "");
2226 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
2227 }
2228
2229 LLVMValueRef ac_build_umin(struct ac_llvm_context *ctx, LLVMValueRef a,
2230 LLVMValueRef b)
2231 {
2232 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntULE, a, b, "");
2233 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
2234 }
2235
2236 LLVMValueRef ac_build_umax(struct ac_llvm_context *ctx, LLVMValueRef a,
2237 LLVMValueRef b)
2238 {
2239 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntUGE, a, b, "");
2240 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
2241 }
2242
2243 LLVMValueRef ac_build_clamp(struct ac_llvm_context *ctx, LLVMValueRef value)
2244 {
2245 LLVMTypeRef t = LLVMTypeOf(value);
2246 return ac_build_fmin(ctx, ac_build_fmax(ctx, value, LLVMConstReal(t, 0.0)),
2247 LLVMConstReal(t, 1.0));
2248 }
2249
2250 void ac_build_export(struct ac_llvm_context *ctx, struct ac_export_args *a)
2251 {
2252 LLVMValueRef args[9];
2253
2254 args[0] = LLVMConstInt(ctx->i32, a->target, 0);
2255 args[1] = LLVMConstInt(ctx->i32, a->enabled_channels, 0);
2256
2257 if (a->compr) {
2258 args[2] = LLVMBuildBitCast(ctx->builder, a->out[0],
2259 ctx->v2i16, "");
2260 args[3] = LLVMBuildBitCast(ctx->builder, a->out[1],
2261 ctx->v2i16, "");
2262 args[4] = LLVMConstInt(ctx->i1, a->done, 0);
2263 args[5] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
2264
2265 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.compr.v2i16",
2266 ctx->voidt, args, 6, 0);
2267 } else {
2268 args[2] = a->out[0];
2269 args[3] = a->out[1];
2270 args[4] = a->out[2];
2271 args[5] = a->out[3];
2272 args[6] = LLVMConstInt(ctx->i1, a->done, 0);
2273 args[7] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
2274
2275 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.f32",
2276 ctx->voidt, args, 8, 0);
2277 }
2278 }
2279
2280 void ac_build_export_null(struct ac_llvm_context *ctx)
2281 {
2282 struct ac_export_args args;
2283
2284 args.enabled_channels = 0x0; /* enabled channels */
2285 args.valid_mask = 1; /* whether the EXEC mask is valid */
2286 args.done = 1; /* DONE bit */
2287 args.target = V_008DFC_SQ_EXP_NULL;
2288 args.compr = 0; /* COMPR flag (0 = 32-bit export) */
2289 args.out[0] = LLVMGetUndef(ctx->f32); /* R */
2290 args.out[1] = LLVMGetUndef(ctx->f32); /* G */
2291 args.out[2] = LLVMGetUndef(ctx->f32); /* B */
2292 args.out[3] = LLVMGetUndef(ctx->f32); /* A */
2293
2294 ac_build_export(ctx, &args);
2295 }
2296
2297 static unsigned ac_num_coords(enum ac_image_dim dim)
2298 {
2299 switch (dim) {
2300 case ac_image_1d:
2301 return 1;
2302 case ac_image_2d:
2303 case ac_image_1darray:
2304 return 2;
2305 case ac_image_3d:
2306 case ac_image_cube:
2307 case ac_image_2darray:
2308 case ac_image_2dmsaa:
2309 return 3;
2310 case ac_image_2darraymsaa:
2311 return 4;
2312 default:
2313 unreachable("ac_num_coords: bad dim");
2314 }
2315 }
2316
2317 static unsigned ac_num_derivs(enum ac_image_dim dim)
2318 {
2319 switch (dim) {
2320 case ac_image_1d:
2321 case ac_image_1darray:
2322 return 2;
2323 case ac_image_2d:
2324 case ac_image_2darray:
2325 case ac_image_cube:
2326 return 4;
2327 case ac_image_3d:
2328 return 6;
2329 case ac_image_2dmsaa:
2330 case ac_image_2darraymsaa:
2331 default:
2332 unreachable("derivatives not supported");
2333 }
2334 }
2335
2336 static const char *get_atomic_name(enum ac_atomic_op op)
2337 {
2338 switch (op) {
2339 case ac_atomic_swap: return "swap";
2340 case ac_atomic_add: return "add";
2341 case ac_atomic_sub: return "sub";
2342 case ac_atomic_smin: return "smin";
2343 case ac_atomic_umin: return "umin";
2344 case ac_atomic_smax: return "smax";
2345 case ac_atomic_umax: return "umax";
2346 case ac_atomic_and: return "and";
2347 case ac_atomic_or: return "or";
2348 case ac_atomic_xor: return "xor";
2349 case ac_atomic_inc_wrap: return "inc";
2350 case ac_atomic_dec_wrap: return "dec";
2351 }
2352 unreachable("bad atomic op");
2353 }
2354
2355 LLVMValueRef ac_build_image_opcode(struct ac_llvm_context *ctx,
2356 struct ac_image_args *a)
2357 {
2358 const char *overload[3] = { "", "", "" };
2359 unsigned num_overloads = 0;
2360 LLVMValueRef args[18];
2361 unsigned num_args = 0;
2362 enum ac_image_dim dim = a->dim;
2363
2364 assert(!a->lod || a->lod == ctx->i32_0 || a->lod == ctx->f32_0 ||
2365 !a->level_zero);
2366 assert((a->opcode != ac_image_get_resinfo && a->opcode != ac_image_load_mip &&
2367 a->opcode != ac_image_store_mip) ||
2368 a->lod);
2369 assert(a->opcode == ac_image_sample || a->opcode == ac_image_gather4 ||
2370 (!a->compare && !a->offset));
2371 assert((a->opcode == ac_image_sample || a->opcode == ac_image_gather4 ||
2372 a->opcode == ac_image_get_lod) ||
2373 !a->bias);
2374 assert((a->bias ? 1 : 0) +
2375 (a->lod ? 1 : 0) +
2376 (a->level_zero ? 1 : 0) +
2377 (a->derivs[0] ? 1 : 0) <= 1);
2378 assert((a->min_lod ? 1 : 0) +
2379 (a->lod ? 1 : 0) +
2380 (a->level_zero ? 1 : 0) <= 1);
2381 assert(!a->d16 || (ctx->chip_class >= GFX8 &&
2382 a->opcode != ac_image_atomic &&
2383 a->opcode != ac_image_atomic_cmpswap &&
2384 a->opcode != ac_image_get_lod &&
2385 a->opcode != ac_image_get_resinfo));
2386
2387 if (a->opcode == ac_image_get_lod) {
2388 switch (dim) {
2389 case ac_image_1darray:
2390 dim = ac_image_1d;
2391 break;
2392 case ac_image_2darray:
2393 case ac_image_cube:
2394 dim = ac_image_2d;
2395 break;
2396 default:
2397 break;
2398 }
2399 }
2400
2401 bool sample = a->opcode == ac_image_sample ||
2402 a->opcode == ac_image_gather4 ||
2403 a->opcode == ac_image_get_lod;
2404 bool atomic = a->opcode == ac_image_atomic ||
2405 a->opcode == ac_image_atomic_cmpswap;
2406 bool load = a->opcode == ac_image_sample ||
2407 a->opcode == ac_image_gather4 ||
2408 a->opcode == ac_image_load ||
2409 a->opcode == ac_image_load_mip;
2410 LLVMTypeRef coord_type = sample ? ctx->f32 : ctx->i32;
2411
2412 if (atomic || a->opcode == ac_image_store || a->opcode == ac_image_store_mip) {
2413 args[num_args++] = a->data[0];
2414 if (a->opcode == ac_image_atomic_cmpswap)
2415 args[num_args++] = a->data[1];
2416 }
2417
2418 if (!atomic)
2419 args[num_args++] = LLVMConstInt(ctx->i32, a->dmask, false);
2420
2421 if (a->offset)
2422 args[num_args++] = ac_to_integer(ctx, a->offset);
2423 if (a->bias) {
2424 args[num_args++] = ac_to_float(ctx, a->bias);
2425 overload[num_overloads++] = ".f32";
2426 }
2427 if (a->compare)
2428 args[num_args++] = ac_to_float(ctx, a->compare);
2429 if (a->derivs[0]) {
2430 unsigned count = ac_num_derivs(dim);
2431 for (unsigned i = 0; i < count; ++i)
2432 args[num_args++] = ac_to_float(ctx, a->derivs[i]);
2433 overload[num_overloads++] = ".f32";
2434 }
2435 unsigned num_coords =
2436 a->opcode != ac_image_get_resinfo ? ac_num_coords(dim) : 0;
2437 for (unsigned i = 0; i < num_coords; ++i)
2438 args[num_args++] = LLVMBuildBitCast(ctx->builder, a->coords[i], coord_type, "");
2439 if (a->lod)
2440 args[num_args++] = LLVMBuildBitCast(ctx->builder, a->lod, coord_type, "");
2441 if (a->min_lod)
2442 args[num_args++] = LLVMBuildBitCast(ctx->builder, a->min_lod, coord_type, "");
2443
2444 overload[num_overloads++] = sample ? ".f32" : ".i32";
2445
2446 args[num_args++] = a->resource;
2447 if (sample) {
2448 args[num_args++] = a->sampler;
2449 args[num_args++] = LLVMConstInt(ctx->i1, a->unorm, false);
2450 }
2451
2452 args[num_args++] = ctx->i32_0; /* texfailctrl */
2453 args[num_args++] = LLVMConstInt(ctx->i32,
2454 load ? get_load_cache_policy(ctx, a->cache_policy) :
2455 a->cache_policy, false);
2456
2457 const char *name;
2458 const char *atomic_subop = "";
2459 switch (a->opcode) {
2460 case ac_image_sample: name = "sample"; break;
2461 case ac_image_gather4: name = "gather4"; break;
2462 case ac_image_load: name = "load"; break;
2463 case ac_image_load_mip: name = "load.mip"; break;
2464 case ac_image_store: name = "store"; break;
2465 case ac_image_store_mip: name = "store.mip"; break;
2466 case ac_image_atomic:
2467 name = "atomic.";
2468 atomic_subop = get_atomic_name(a->atomic);
2469 break;
2470 case ac_image_atomic_cmpswap:
2471 name = "atomic.";
2472 atomic_subop = "cmpswap";
2473 break;
2474 case ac_image_get_lod: name = "getlod"; break;
2475 case ac_image_get_resinfo: name = "getresinfo"; break;
2476 default: unreachable("invalid image opcode");
2477 }
2478
2479 const char *dimname;
2480 switch (dim) {
2481 case ac_image_1d: dimname = "1d"; break;
2482 case ac_image_2d: dimname = "2d"; break;
2483 case ac_image_3d: dimname = "3d"; break;
2484 case ac_image_cube: dimname = "cube"; break;
2485 case ac_image_1darray: dimname = "1darray"; break;
2486 case ac_image_2darray: dimname = "2darray"; break;
2487 case ac_image_2dmsaa: dimname = "2dmsaa"; break;
2488 case ac_image_2darraymsaa: dimname = "2darraymsaa"; break;
2489 default: unreachable("invalid dim");
2490 }
2491
2492 bool lod_suffix =
2493 a->lod && (a->opcode == ac_image_sample || a->opcode == ac_image_gather4);
2494 char intr_name[96];
2495 snprintf(intr_name, sizeof(intr_name),
2496 "llvm.amdgcn.image.%s%s" /* base name */
2497 "%s%s%s%s" /* sample/gather modifiers */
2498 ".%s.%s%s%s%s", /* dimension and type overloads */
2499 name, atomic_subop,
2500 a->compare ? ".c" : "",
2501 a->bias ? ".b" :
2502 lod_suffix ? ".l" :
2503 a->derivs[0] ? ".d" :
2504 a->level_zero ? ".lz" : "",
2505 a->min_lod ? ".cl" : "",
2506 a->offset ? ".o" : "",
2507 dimname,
2508 atomic ? "i32" : (a->d16 ? "v4f16" : "v4f32"),
2509 overload[0], overload[1], overload[2]);
2510
2511 LLVMTypeRef retty;
2512 if (atomic)
2513 retty = ctx->i32;
2514 else if (a->opcode == ac_image_store || a->opcode == ac_image_store_mip)
2515 retty = ctx->voidt;
2516 else
2517 retty = a->d16 ? ctx->v4f16 : ctx->v4f32;
2518
2519 LLVMValueRef result =
2520 ac_build_intrinsic(ctx, intr_name, retty, args, num_args,
2521 a->attributes);
2522 if (!sample && !atomic && retty != ctx->voidt)
2523 result = ac_to_integer(ctx, result);
2524
2525 return result;
2526 }
2527
2528 LLVMValueRef ac_build_image_get_sample_count(struct ac_llvm_context *ctx,
2529 LLVMValueRef rsrc)
2530 {
2531 LLVMValueRef samples;
2532
2533 /* Read the samples from the descriptor directly.
2534 * Hardware doesn't have any instruction for this.
2535 */
2536 samples = LLVMBuildExtractElement(ctx->builder, rsrc,
2537 LLVMConstInt(ctx->i32, 3, 0), "");
2538 samples = LLVMBuildLShr(ctx->builder, samples,
2539 LLVMConstInt(ctx->i32, 16, 0), "");
2540 samples = LLVMBuildAnd(ctx->builder, samples,
2541 LLVMConstInt(ctx->i32, 0xf, 0), "");
2542 samples = LLVMBuildShl(ctx->builder, ctx->i32_1,
2543 samples, "");
2544 return samples;
2545 }
2546
2547 LLVMValueRef ac_build_cvt_pkrtz_f16(struct ac_llvm_context *ctx,
2548 LLVMValueRef args[2])
2549 {
2550 return ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pkrtz", ctx->v2f16,
2551 args, 2, AC_FUNC_ATTR_READNONE);
2552 }
2553
2554 LLVMValueRef ac_build_cvt_pknorm_i16(struct ac_llvm_context *ctx,
2555 LLVMValueRef args[2])
2556 {
2557 LLVMValueRef res =
2558 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.i16",
2559 ctx->v2i16, args, 2,
2560 AC_FUNC_ATTR_READNONE);
2561 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2562 }
2563
2564 LLVMValueRef ac_build_cvt_pknorm_u16(struct ac_llvm_context *ctx,
2565 LLVMValueRef args[2])
2566 {
2567 LLVMValueRef res =
2568 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.u16",
2569 ctx->v2i16, args, 2,
2570 AC_FUNC_ATTR_READNONE);
2571 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2572 }
2573
2574 /* The 8-bit and 10-bit clamping is for HW workarounds. */
2575 LLVMValueRef ac_build_cvt_pk_i16(struct ac_llvm_context *ctx,
2576 LLVMValueRef args[2], unsigned bits, bool hi)
2577 {
2578 assert(bits == 8 || bits == 10 || bits == 16);
2579
2580 LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
2581 bits == 8 ? 127 : bits == 10 ? 511 : 32767, 0);
2582 LLVMValueRef min_rgb = LLVMConstInt(ctx->i32,
2583 bits == 8 ? -128 : bits == 10 ? -512 : -32768, 0);
2584 LLVMValueRef max_alpha =
2585 bits != 10 ? max_rgb : ctx->i32_1;
2586 LLVMValueRef min_alpha =
2587 bits != 10 ? min_rgb : LLVMConstInt(ctx->i32, -2, 0);
2588
2589 /* Clamp. */
2590 if (bits != 16) {
2591 for (int i = 0; i < 2; i++) {
2592 bool alpha = hi && i == 1;
2593 args[i] = ac_build_imin(ctx, args[i],
2594 alpha ? max_alpha : max_rgb);
2595 args[i] = ac_build_imax(ctx, args[i],
2596 alpha ? min_alpha : min_rgb);
2597 }
2598 }
2599
2600 LLVMValueRef res =
2601 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.i16",
2602 ctx->v2i16, args, 2,
2603 AC_FUNC_ATTR_READNONE);
2604 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2605 }
2606
2607 /* The 8-bit and 10-bit clamping is for HW workarounds. */
2608 LLVMValueRef ac_build_cvt_pk_u16(struct ac_llvm_context *ctx,
2609 LLVMValueRef args[2], unsigned bits, bool hi)
2610 {
2611 assert(bits == 8 || bits == 10 || bits == 16);
2612
2613 LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
2614 bits == 8 ? 255 : bits == 10 ? 1023 : 65535, 0);
2615 LLVMValueRef max_alpha =
2616 bits != 10 ? max_rgb : LLVMConstInt(ctx->i32, 3, 0);
2617
2618 /* Clamp. */
2619 if (bits != 16) {
2620 for (int i = 0; i < 2; i++) {
2621 bool alpha = hi && i == 1;
2622 args[i] = ac_build_umin(ctx, args[i],
2623 alpha ? max_alpha : max_rgb);
2624 }
2625 }
2626
2627 LLVMValueRef res =
2628 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.u16",
2629 ctx->v2i16, args, 2,
2630 AC_FUNC_ATTR_READNONE);
2631 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2632 }
2633
2634 LLVMValueRef ac_build_wqm_vote(struct ac_llvm_context *ctx, LLVMValueRef i1)
2635 {
2636 return ac_build_intrinsic(ctx, "llvm.amdgcn.wqm.vote", ctx->i1,
2637 &i1, 1, AC_FUNC_ATTR_READNONE);
2638 }
2639
2640 void ac_build_kill_if_false(struct ac_llvm_context *ctx, LLVMValueRef i1)
2641 {
2642 ac_build_intrinsic(ctx, "llvm.amdgcn.kill", ctx->voidt,
2643 &i1, 1, 0);
2644 }
2645
2646 LLVMValueRef ac_build_bfe(struct ac_llvm_context *ctx, LLVMValueRef input,
2647 LLVMValueRef offset, LLVMValueRef width,
2648 bool is_signed)
2649 {
2650 LLVMValueRef args[] = {
2651 input,
2652 offset,
2653 width,
2654 };
2655
2656 return ac_build_intrinsic(ctx, is_signed ? "llvm.amdgcn.sbfe.i32" :
2657 "llvm.amdgcn.ubfe.i32",
2658 ctx->i32, args, 3, AC_FUNC_ATTR_READNONE);
2659
2660 }
2661
2662 LLVMValueRef ac_build_imad(struct ac_llvm_context *ctx, LLVMValueRef s0,
2663 LLVMValueRef s1, LLVMValueRef s2)
2664 {
2665 return LLVMBuildAdd(ctx->builder,
2666 LLVMBuildMul(ctx->builder, s0, s1, ""), s2, "");
2667 }
2668
2669 LLVMValueRef ac_build_fmad(struct ac_llvm_context *ctx, LLVMValueRef s0,
2670 LLVMValueRef s1, LLVMValueRef s2)
2671 {
2672 /* FMA is better on GFX10, because it has FMA units instead of MUL-ADD units. */
2673 if (ctx->chip_class >= GFX10) {
2674 return ac_build_intrinsic(ctx, "llvm.fma.f32", ctx->f32,
2675 (LLVMValueRef []) {s0, s1, s2}, 3,
2676 AC_FUNC_ATTR_READNONE);
2677 }
2678
2679 return LLVMBuildFAdd(ctx->builder,
2680 LLVMBuildFMul(ctx->builder, s0, s1, ""), s2, "");
2681 }
2682
2683 void ac_build_waitcnt(struct ac_llvm_context *ctx, unsigned wait_flags)
2684 {
2685 if (!wait_flags)
2686 return;
2687
2688 unsigned lgkmcnt = 63;
2689 unsigned vmcnt = ctx->chip_class >= GFX9 ? 63 : 15;
2690 unsigned vscnt = 63;
2691
2692 if (wait_flags & AC_WAIT_LGKM)
2693 lgkmcnt = 0;
2694 if (wait_flags & AC_WAIT_VLOAD)
2695 vmcnt = 0;
2696
2697 if (wait_flags & AC_WAIT_VSTORE) {
2698 if (ctx->chip_class >= GFX10)
2699 vscnt = 0;
2700 else
2701 vmcnt = 0;
2702 }
2703
2704 /* There is no intrinsic for vscnt(0), so use a fence. */
2705 if ((wait_flags & AC_WAIT_LGKM &&
2706 wait_flags & AC_WAIT_VLOAD &&
2707 wait_flags & AC_WAIT_VSTORE) ||
2708 vscnt == 0) {
2709 LLVMBuildFence(ctx->builder, LLVMAtomicOrderingRelease, false, "");
2710 return;
2711 }
2712
2713 unsigned simm16 = (lgkmcnt << 8) |
2714 (7 << 4) | /* expcnt */
2715 (vmcnt & 0xf) |
2716 ((vmcnt >> 4) << 14);
2717
2718 LLVMValueRef args[1] = {
2719 LLVMConstInt(ctx->i32, simm16, false),
2720 };
2721 ac_build_intrinsic(ctx, "llvm.amdgcn.s.waitcnt",
2722 ctx->voidt, args, 1, 0);
2723 }
2724
2725 LLVMValueRef ac_build_fmed3(struct ac_llvm_context *ctx, LLVMValueRef src0,
2726 LLVMValueRef src1, LLVMValueRef src2,
2727 unsigned bitsize)
2728 {
2729 LLVMValueRef result;
2730
2731 if (bitsize == 64 || (bitsize == 16 && ctx->chip_class <= GFX8)) {
2732 /* Lower 64-bit fmed because LLVM doesn't expose an intrinsic,
2733 * or lower 16-bit fmed because it's only supported on GFX9+.
2734 */
2735 LLVMValueRef min1, min2, max1;
2736
2737 min1 = ac_build_fmin(ctx, src0, src1);
2738 max1 = ac_build_fmax(ctx, src0, src1);
2739 min2 = ac_build_fmin(ctx, max1, src2);
2740
2741 result = ac_build_fmax(ctx, min2, min1);
2742 } else {
2743 LLVMTypeRef type;
2744 char *intr;
2745
2746 if (bitsize == 16) {
2747 intr = "llvm.amdgcn.fmed3.f16";
2748 type = ctx->f16;
2749 } else {
2750 assert(bitsize == 32);
2751 intr = "llvm.amdgcn.fmed3.f32";
2752 type = ctx->f32;
2753 }
2754
2755 LLVMValueRef params[] = {
2756 src0,
2757 src1,
2758 src2,
2759 };
2760
2761 result = ac_build_intrinsic(ctx, intr, type, params, 3,
2762 AC_FUNC_ATTR_READNONE);
2763 }
2764
2765 if (ctx->chip_class < GFX9 && bitsize == 32) {
2766 /* Only pre-GFX9 chips do not flush denorms. */
2767 result = ac_build_canonicalize(ctx, result, bitsize);
2768 }
2769
2770 return result;
2771 }
2772
2773 LLVMValueRef ac_build_fract(struct ac_llvm_context *ctx, LLVMValueRef src0,
2774 unsigned bitsize)
2775 {
2776 LLVMTypeRef type;
2777 char *intr;
2778
2779 if (bitsize == 16) {
2780 intr = "llvm.amdgcn.fract.f16";
2781 type = ctx->f16;
2782 } else if (bitsize == 32) {
2783 intr = "llvm.amdgcn.fract.f32";
2784 type = ctx->f32;
2785 } else {
2786 intr = "llvm.amdgcn.fract.f64";
2787 type = ctx->f64;
2788 }
2789
2790 LLVMValueRef params[] = {
2791 src0,
2792 };
2793 return ac_build_intrinsic(ctx, intr, type, params, 1,
2794 AC_FUNC_ATTR_READNONE);
2795 }
2796
2797 LLVMValueRef ac_build_isign(struct ac_llvm_context *ctx, LLVMValueRef src0,
2798 unsigned bitsize)
2799 {
2800 LLVMTypeRef type = LLVMIntTypeInContext(ctx->context, bitsize);
2801 LLVMValueRef zero = LLVMConstInt(type, 0, false);
2802 LLVMValueRef one = LLVMConstInt(type, 1, false);
2803
2804 LLVMValueRef cmp, val;
2805 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, src0, zero, "");
2806 val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
2807 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGE, val, zero, "");
2808 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstInt(type, -1, true), "");
2809 return val;
2810 }
2811
2812 LLVMValueRef ac_build_fsign(struct ac_llvm_context *ctx, LLVMValueRef src0,
2813 unsigned bitsize)
2814 {
2815 LLVMValueRef cmp, val, zero, one;
2816 LLVMTypeRef type;
2817
2818 if (bitsize == 16) {
2819 type = ctx->f16;
2820 zero = ctx->f16_0;
2821 one = ctx->f16_1;
2822 } else if (bitsize == 32) {
2823 type = ctx->f32;
2824 zero = ctx->f32_0;
2825 one = ctx->f32_1;
2826 } else {
2827 type = ctx->f64;
2828 zero = ctx->f64_0;
2829 one = ctx->f64_1;
2830 }
2831
2832 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGT, src0, zero, "");
2833 val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
2834 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGE, val, zero, "");
2835 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstReal(type, -1.0), "");
2836 return val;
2837 }
2838
2839 LLVMValueRef ac_build_bit_count(struct ac_llvm_context *ctx, LLVMValueRef src0)
2840 {
2841 LLVMValueRef result;
2842 unsigned bitsize;
2843
2844 bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
2845
2846 switch (bitsize) {
2847 case 128:
2848 result = ac_build_intrinsic(ctx, "llvm.ctpop.i128", ctx->i128,
2849 (LLVMValueRef []) { src0 }, 1,
2850 AC_FUNC_ATTR_READNONE);
2851 result = LLVMBuildTrunc(ctx->builder, result, ctx->i32, "");
2852 break;
2853 case 64:
2854 result = ac_build_intrinsic(ctx, "llvm.ctpop.i64", ctx->i64,
2855 (LLVMValueRef []) { src0 }, 1,
2856 AC_FUNC_ATTR_READNONE);
2857
2858 result = LLVMBuildTrunc(ctx->builder, result, ctx->i32, "");
2859 break;
2860 case 32:
2861 result = ac_build_intrinsic(ctx, "llvm.ctpop.i32", ctx->i32,
2862 (LLVMValueRef []) { src0 }, 1,
2863 AC_FUNC_ATTR_READNONE);
2864 break;
2865 case 16:
2866 result = ac_build_intrinsic(ctx, "llvm.ctpop.i16", ctx->i16,
2867 (LLVMValueRef []) { src0 }, 1,
2868 AC_FUNC_ATTR_READNONE);
2869
2870 result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
2871 break;
2872 case 8:
2873 result = ac_build_intrinsic(ctx, "llvm.ctpop.i8", ctx->i8,
2874 (LLVMValueRef []) { src0 }, 1,
2875 AC_FUNC_ATTR_READNONE);
2876
2877 result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
2878 break;
2879 default:
2880 unreachable(!"invalid bitsize");
2881 break;
2882 }
2883
2884 return result;
2885 }
2886
2887 LLVMValueRef ac_build_bitfield_reverse(struct ac_llvm_context *ctx,
2888 LLVMValueRef src0)
2889 {
2890 LLVMValueRef result;
2891 unsigned bitsize;
2892
2893 bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
2894
2895 switch (bitsize) {
2896 case 64:
2897 result = ac_build_intrinsic(ctx, "llvm.bitreverse.i64", ctx->i64,
2898 (LLVMValueRef []) { src0 }, 1,
2899 AC_FUNC_ATTR_READNONE);
2900
2901 result = LLVMBuildTrunc(ctx->builder, result, ctx->i32, "");
2902 break;
2903 case 32:
2904 result = ac_build_intrinsic(ctx, "llvm.bitreverse.i32", ctx->i32,
2905 (LLVMValueRef []) { src0 }, 1,
2906 AC_FUNC_ATTR_READNONE);
2907 break;
2908 case 16:
2909 result = ac_build_intrinsic(ctx, "llvm.bitreverse.i16", ctx->i16,
2910 (LLVMValueRef []) { src0 }, 1,
2911 AC_FUNC_ATTR_READNONE);
2912
2913 result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
2914 break;
2915 case 8:
2916 result = ac_build_intrinsic(ctx, "llvm.bitreverse.i8", ctx->i8,
2917 (LLVMValueRef []) { src0 }, 1,
2918 AC_FUNC_ATTR_READNONE);
2919
2920 result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
2921 break;
2922 default:
2923 unreachable(!"invalid bitsize");
2924 break;
2925 }
2926
2927 return result;
2928 }
2929
2930 #define AC_EXP_TARGET 0
2931 #define AC_EXP_ENABLED_CHANNELS 1
2932 #define AC_EXP_OUT0 2
2933
2934 enum ac_ir_type {
2935 AC_IR_UNDEF,
2936 AC_IR_CONST,
2937 AC_IR_VALUE,
2938 };
2939
2940 struct ac_vs_exp_chan
2941 {
2942 LLVMValueRef value;
2943 float const_float;
2944 enum ac_ir_type type;
2945 };
2946
2947 struct ac_vs_exp_inst {
2948 unsigned offset;
2949 LLVMValueRef inst;
2950 struct ac_vs_exp_chan chan[4];
2951 };
2952
2953 struct ac_vs_exports {
2954 unsigned num;
2955 struct ac_vs_exp_inst exp[VARYING_SLOT_MAX];
2956 };
2957
2958 /* Return true if the PARAM export has been eliminated. */
2959 static bool ac_eliminate_const_output(uint8_t *vs_output_param_offset,
2960 uint32_t num_outputs,
2961 struct ac_vs_exp_inst *exp)
2962 {
2963 unsigned i, default_val; /* SPI_PS_INPUT_CNTL_i.DEFAULT_VAL */
2964 bool is_zero[4] = {}, is_one[4] = {};
2965
2966 for (i = 0; i < 4; i++) {
2967 /* It's a constant expression. Undef outputs are eliminated too. */
2968 if (exp->chan[i].type == AC_IR_UNDEF) {
2969 is_zero[i] = true;
2970 is_one[i] = true;
2971 } else if (exp->chan[i].type == AC_IR_CONST) {
2972 if (exp->chan[i].const_float == 0)
2973 is_zero[i] = true;
2974 else if (exp->chan[i].const_float == 1)
2975 is_one[i] = true;
2976 else
2977 return false; /* other constant */
2978 } else
2979 return false;
2980 }
2981
2982 /* Only certain combinations of 0 and 1 can be eliminated. */
2983 if (is_zero[0] && is_zero[1] && is_zero[2])
2984 default_val = is_zero[3] ? 0 : 1;
2985 else if (is_one[0] && is_one[1] && is_one[2])
2986 default_val = is_zero[3] ? 2 : 3;
2987 else
2988 return false;
2989
2990 /* The PARAM export can be represented as DEFAULT_VAL. Kill it. */
2991 LLVMInstructionEraseFromParent(exp->inst);
2992
2993 /* Change OFFSET to DEFAULT_VAL. */
2994 for (i = 0; i < num_outputs; i++) {
2995 if (vs_output_param_offset[i] == exp->offset) {
2996 vs_output_param_offset[i] =
2997 AC_EXP_PARAM_DEFAULT_VAL_0000 + default_val;
2998 break;
2999 }
3000 }
3001 return true;
3002 }
3003
3004 static bool ac_eliminate_duplicated_output(struct ac_llvm_context *ctx,
3005 uint8_t *vs_output_param_offset,
3006 uint32_t num_outputs,
3007 struct ac_vs_exports *processed,
3008 struct ac_vs_exp_inst *exp)
3009 {
3010 unsigned p, copy_back_channels = 0;
3011
3012 /* See if the output is already in the list of processed outputs.
3013 * The LLVMValueRef comparison relies on SSA.
3014 */
3015 for (p = 0; p < processed->num; p++) {
3016 bool different = false;
3017
3018 for (unsigned j = 0; j < 4; j++) {
3019 struct ac_vs_exp_chan *c1 = &processed->exp[p].chan[j];
3020 struct ac_vs_exp_chan *c2 = &exp->chan[j];
3021
3022 /* Treat undef as a match. */
3023 if (c2->type == AC_IR_UNDEF)
3024 continue;
3025
3026 /* If c1 is undef but c2 isn't, we can copy c2 to c1
3027 * and consider the instruction duplicated.
3028 */
3029 if (c1->type == AC_IR_UNDEF) {
3030 copy_back_channels |= 1 << j;
3031 continue;
3032 }
3033
3034 /* Test whether the channels are not equal. */
3035 if (c1->type != c2->type ||
3036 (c1->type == AC_IR_CONST &&
3037 c1->const_float != c2->const_float) ||
3038 (c1->type == AC_IR_VALUE &&
3039 c1->value != c2->value)) {
3040 different = true;
3041 break;
3042 }
3043 }
3044 if (!different)
3045 break;
3046
3047 copy_back_channels = 0;
3048 }
3049 if (p == processed->num)
3050 return false;
3051
3052 /* If a match was found, but the matching export has undef where the new
3053 * one has a normal value, copy the normal value to the undef channel.
3054 */
3055 struct ac_vs_exp_inst *match = &processed->exp[p];
3056
3057 /* Get current enabled channels mask. */
3058 LLVMValueRef arg = LLVMGetOperand(match->inst, AC_EXP_ENABLED_CHANNELS);
3059 unsigned enabled_channels = LLVMConstIntGetZExtValue(arg);
3060
3061 while (copy_back_channels) {
3062 unsigned chan = u_bit_scan(&copy_back_channels);
3063
3064 assert(match->chan[chan].type == AC_IR_UNDEF);
3065 LLVMSetOperand(match->inst, AC_EXP_OUT0 + chan,
3066 exp->chan[chan].value);
3067 match->chan[chan] = exp->chan[chan];
3068
3069 /* Update number of enabled channels because the original mask
3070 * is not always 0xf.
3071 */
3072 enabled_channels |= (1 << chan);
3073 LLVMSetOperand(match->inst, AC_EXP_ENABLED_CHANNELS,
3074 LLVMConstInt(ctx->i32, enabled_channels, 0));
3075 }
3076
3077 /* The PARAM export is duplicated. Kill it. */
3078 LLVMInstructionEraseFromParent(exp->inst);
3079
3080 /* Change OFFSET to the matching export. */
3081 for (unsigned i = 0; i < num_outputs; i++) {
3082 if (vs_output_param_offset[i] == exp->offset) {
3083 vs_output_param_offset[i] = match->offset;
3084 break;
3085 }
3086 }
3087 return true;
3088 }
3089
3090 void ac_optimize_vs_outputs(struct ac_llvm_context *ctx,
3091 LLVMValueRef main_fn,
3092 uint8_t *vs_output_param_offset,
3093 uint32_t num_outputs,
3094 uint32_t skip_output_mask,
3095 uint8_t *num_param_exports)
3096 {
3097 LLVMBasicBlockRef bb;
3098 bool removed_any = false;
3099 struct ac_vs_exports exports;
3100
3101 exports.num = 0;
3102
3103 /* Process all LLVM instructions. */
3104 bb = LLVMGetFirstBasicBlock(main_fn);
3105 while (bb) {
3106 LLVMValueRef inst = LLVMGetFirstInstruction(bb);
3107
3108 while (inst) {
3109 LLVMValueRef cur = inst;
3110 inst = LLVMGetNextInstruction(inst);
3111 struct ac_vs_exp_inst exp;
3112
3113 if (LLVMGetInstructionOpcode(cur) != LLVMCall)
3114 continue;
3115
3116 LLVMValueRef callee = ac_llvm_get_called_value(cur);
3117
3118 if (!ac_llvm_is_function(callee))
3119 continue;
3120
3121 const char *name = LLVMGetValueName(callee);
3122 unsigned num_args = LLVMCountParams(callee);
3123
3124 /* Check if this is an export instruction. */
3125 if ((num_args != 9 && num_args != 8) ||
3126 (strcmp(name, "llvm.SI.export") &&
3127 strcmp(name, "llvm.amdgcn.exp.f32")))
3128 continue;
3129
3130 LLVMValueRef arg = LLVMGetOperand(cur, AC_EXP_TARGET);
3131 unsigned target = LLVMConstIntGetZExtValue(arg);
3132
3133 if (target < V_008DFC_SQ_EXP_PARAM)
3134 continue;
3135
3136 target -= V_008DFC_SQ_EXP_PARAM;
3137
3138 /* Parse the instruction. */
3139 memset(&exp, 0, sizeof(exp));
3140 exp.offset = target;
3141 exp.inst = cur;
3142
3143 for (unsigned i = 0; i < 4; i++) {
3144 LLVMValueRef v = LLVMGetOperand(cur, AC_EXP_OUT0 + i);
3145
3146 exp.chan[i].value = v;
3147
3148 if (LLVMIsUndef(v)) {
3149 exp.chan[i].type = AC_IR_UNDEF;
3150 } else if (LLVMIsAConstantFP(v)) {
3151 LLVMBool loses_info;
3152 exp.chan[i].type = AC_IR_CONST;
3153 exp.chan[i].const_float =
3154 LLVMConstRealGetDouble(v, &loses_info);
3155 } else {
3156 exp.chan[i].type = AC_IR_VALUE;
3157 }
3158 }
3159
3160 /* Eliminate constant and duplicated PARAM exports. */
3161 if (!((1u << target) & skip_output_mask) &&
3162 (ac_eliminate_const_output(vs_output_param_offset,
3163 num_outputs, &exp) ||
3164 ac_eliminate_duplicated_output(ctx,
3165 vs_output_param_offset,
3166 num_outputs, &exports,
3167 &exp))) {
3168 removed_any = true;
3169 } else {
3170 exports.exp[exports.num++] = exp;
3171 }
3172 }
3173 bb = LLVMGetNextBasicBlock(bb);
3174 }
3175
3176 /* Remove holes in export memory due to removed PARAM exports.
3177 * This is done by renumbering all PARAM exports.
3178 */
3179 if (removed_any) {
3180 uint8_t old_offset[VARYING_SLOT_MAX];
3181 unsigned out, i;
3182
3183 /* Make a copy of the offsets. We need the old version while
3184 * we are modifying some of them. */
3185 memcpy(old_offset, vs_output_param_offset,
3186 sizeof(old_offset));
3187
3188 for (i = 0; i < exports.num; i++) {
3189 unsigned offset = exports.exp[i].offset;
3190
3191 /* Update vs_output_param_offset. Multiple outputs can
3192 * have the same offset.
3193 */
3194 for (out = 0; out < num_outputs; out++) {
3195 if (old_offset[out] == offset)
3196 vs_output_param_offset[out] = i;
3197 }
3198
3199 /* Change the PARAM offset in the instruction. */
3200 LLVMSetOperand(exports.exp[i].inst, AC_EXP_TARGET,
3201 LLVMConstInt(ctx->i32,
3202 V_008DFC_SQ_EXP_PARAM + i, 0));
3203 }
3204 *num_param_exports = exports.num;
3205 }
3206 }
3207
3208 void ac_init_exec_full_mask(struct ac_llvm_context *ctx)
3209 {
3210 LLVMValueRef full_mask = LLVMConstInt(ctx->i64, ~0ull, 0);
3211 ac_build_intrinsic(ctx,
3212 "llvm.amdgcn.init.exec", ctx->voidt,
3213 &full_mask, 1, AC_FUNC_ATTR_CONVERGENT);
3214 }
3215
3216 void ac_declare_lds_as_pointer(struct ac_llvm_context *ctx)
3217 {
3218 unsigned lds_size = ctx->chip_class >= GFX7 ? 65536 : 32768;
3219 ctx->lds = LLVMBuildIntToPtr(ctx->builder, ctx->i32_0,
3220 LLVMPointerType(LLVMArrayType(ctx->i32, lds_size / 4), AC_ADDR_SPACE_LDS),
3221 "lds");
3222 }
3223
3224 LLVMValueRef ac_lds_load(struct ac_llvm_context *ctx,
3225 LLVMValueRef dw_addr)
3226 {
3227 return LLVMBuildLoad(ctx->builder, ac_build_gep0(ctx, ctx->lds, dw_addr), "");
3228 }
3229
3230 void ac_lds_store(struct ac_llvm_context *ctx,
3231 LLVMValueRef dw_addr,
3232 LLVMValueRef value)
3233 {
3234 value = ac_to_integer(ctx, value);
3235 ac_build_indexed_store(ctx, ctx->lds,
3236 dw_addr, value);
3237 }
3238
3239 LLVMValueRef ac_find_lsb(struct ac_llvm_context *ctx,
3240 LLVMTypeRef dst_type,
3241 LLVMValueRef src0)
3242 {
3243 unsigned src0_bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
3244 const char *intrin_name;
3245 LLVMTypeRef type;
3246 LLVMValueRef zero;
3247
3248 switch (src0_bitsize) {
3249 case 64:
3250 intrin_name = "llvm.cttz.i64";
3251 type = ctx->i64;
3252 zero = ctx->i64_0;
3253 break;
3254 case 32:
3255 intrin_name = "llvm.cttz.i32";
3256 type = ctx->i32;
3257 zero = ctx->i32_0;
3258 break;
3259 case 16:
3260 intrin_name = "llvm.cttz.i16";
3261 type = ctx->i16;
3262 zero = ctx->i16_0;
3263 break;
3264 case 8:
3265 intrin_name = "llvm.cttz.i8";
3266 type = ctx->i8;
3267 zero = ctx->i8_0;
3268 break;
3269 default:
3270 unreachable(!"invalid bitsize");
3271 }
3272
3273 LLVMValueRef params[2] = {
3274 src0,
3275
3276 /* The value of 1 means that ffs(x=0) = undef, so LLVM won't
3277 * add special code to check for x=0. The reason is that
3278 * the LLVM behavior for x=0 is different from what we
3279 * need here. However, LLVM also assumes that ffs(x) is
3280 * in [0, 31], but GLSL expects that ffs(0) = -1, so
3281 * a conditional assignment to handle 0 is still required.
3282 *
3283 * The hardware already implements the correct behavior.
3284 */
3285 ctx->i1true,
3286 };
3287
3288 LLVMValueRef lsb = ac_build_intrinsic(ctx, intrin_name, type,
3289 params, 2,
3290 AC_FUNC_ATTR_READNONE);
3291
3292 if (src0_bitsize == 64) {
3293 lsb = LLVMBuildTrunc(ctx->builder, lsb, ctx->i32, "");
3294 } else if (src0_bitsize < 32) {
3295 lsb = LLVMBuildSExt(ctx->builder, lsb, ctx->i32, "");
3296 }
3297
3298 /* TODO: We need an intrinsic to skip this conditional. */
3299 /* Check for zero: */
3300 return LLVMBuildSelect(ctx->builder, LLVMBuildICmp(ctx->builder,
3301 LLVMIntEQ, src0,
3302 zero, ""),
3303 LLVMConstInt(ctx->i32, -1, 0), lsb, "");
3304 }
3305
3306 LLVMTypeRef ac_array_in_const_addr_space(LLVMTypeRef elem_type)
3307 {
3308 return LLVMPointerType(elem_type, AC_ADDR_SPACE_CONST);
3309 }
3310
3311 LLVMTypeRef ac_array_in_const32_addr_space(LLVMTypeRef elem_type)
3312 {
3313 return LLVMPointerType(elem_type, AC_ADDR_SPACE_CONST_32BIT);
3314 }
3315
3316 static struct ac_llvm_flow *
3317 get_current_flow(struct ac_llvm_context *ctx)
3318 {
3319 if (ctx->flow->depth > 0)
3320 return &ctx->flow->stack[ctx->flow->depth - 1];
3321 return NULL;
3322 }
3323
3324 static struct ac_llvm_flow *
3325 get_innermost_loop(struct ac_llvm_context *ctx)
3326 {
3327 for (unsigned i = ctx->flow->depth; i > 0; --i) {
3328 if (ctx->flow->stack[i - 1].loop_entry_block)
3329 return &ctx->flow->stack[i - 1];
3330 }
3331 return NULL;
3332 }
3333
3334 static struct ac_llvm_flow *
3335 push_flow(struct ac_llvm_context *ctx)
3336 {
3337 struct ac_llvm_flow *flow;
3338
3339 if (ctx->flow->depth >= ctx->flow->depth_max) {
3340 unsigned new_max = MAX2(ctx->flow->depth << 1,
3341 AC_LLVM_INITIAL_CF_DEPTH);
3342
3343 ctx->flow->stack = realloc(ctx->flow->stack, new_max * sizeof(*ctx->flow->stack));
3344 ctx->flow->depth_max = new_max;
3345 }
3346
3347 flow = &ctx->flow->stack[ctx->flow->depth];
3348 ctx->flow->depth++;
3349
3350 flow->next_block = NULL;
3351 flow->loop_entry_block = NULL;
3352 return flow;
3353 }
3354
3355 static void set_basicblock_name(LLVMBasicBlockRef bb, const char *base,
3356 int label_id)
3357 {
3358 char buf[32];
3359 snprintf(buf, sizeof(buf), "%s%d", base, label_id);
3360 LLVMSetValueName(LLVMBasicBlockAsValue(bb), buf);
3361 }
3362
3363 /* Append a basic block at the level of the parent flow.
3364 */
3365 static LLVMBasicBlockRef append_basic_block(struct ac_llvm_context *ctx,
3366 const char *name)
3367 {
3368 assert(ctx->flow->depth >= 1);
3369
3370 if (ctx->flow->depth >= 2) {
3371 struct ac_llvm_flow *flow = &ctx->flow->stack[ctx->flow->depth - 2];
3372
3373 return LLVMInsertBasicBlockInContext(ctx->context,
3374 flow->next_block, name);
3375 }
3376
3377 LLVMValueRef main_fn =
3378 LLVMGetBasicBlockParent(LLVMGetInsertBlock(ctx->builder));
3379 return LLVMAppendBasicBlockInContext(ctx->context, main_fn, name);
3380 }
3381
3382 /* Emit a branch to the given default target for the current block if
3383 * applicable -- that is, if the current block does not already contain a
3384 * branch from a break or continue.
3385 */
3386 static void emit_default_branch(LLVMBuilderRef builder,
3387 LLVMBasicBlockRef target)
3388 {
3389 if (!LLVMGetBasicBlockTerminator(LLVMGetInsertBlock(builder)))
3390 LLVMBuildBr(builder, target);
3391 }
3392
3393 void ac_build_bgnloop(struct ac_llvm_context *ctx, int label_id)
3394 {
3395 struct ac_llvm_flow *flow = push_flow(ctx);
3396 flow->loop_entry_block = append_basic_block(ctx, "LOOP");
3397 flow->next_block = append_basic_block(ctx, "ENDLOOP");
3398 set_basicblock_name(flow->loop_entry_block, "loop", label_id);
3399 LLVMBuildBr(ctx->builder, flow->loop_entry_block);
3400 LLVMPositionBuilderAtEnd(ctx->builder, flow->loop_entry_block);
3401 }
3402
3403 void ac_build_break(struct ac_llvm_context *ctx)
3404 {
3405 struct ac_llvm_flow *flow = get_innermost_loop(ctx);
3406 LLVMBuildBr(ctx->builder, flow->next_block);
3407 }
3408
3409 void ac_build_continue(struct ac_llvm_context *ctx)
3410 {
3411 struct ac_llvm_flow *flow = get_innermost_loop(ctx);
3412 LLVMBuildBr(ctx->builder, flow->loop_entry_block);
3413 }
3414
3415 void ac_build_else(struct ac_llvm_context *ctx, int label_id)
3416 {
3417 struct ac_llvm_flow *current_branch = get_current_flow(ctx);
3418 LLVMBasicBlockRef endif_block;
3419
3420 assert(!current_branch->loop_entry_block);
3421
3422 endif_block = append_basic_block(ctx, "ENDIF");
3423 emit_default_branch(ctx->builder, endif_block);
3424
3425 LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
3426 set_basicblock_name(current_branch->next_block, "else", label_id);
3427
3428 current_branch->next_block = endif_block;
3429 }
3430
3431 void ac_build_endif(struct ac_llvm_context *ctx, int label_id)
3432 {
3433 struct ac_llvm_flow *current_branch = get_current_flow(ctx);
3434
3435 assert(!current_branch->loop_entry_block);
3436
3437 emit_default_branch(ctx->builder, current_branch->next_block);
3438 LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
3439 set_basicblock_name(current_branch->next_block, "endif", label_id);
3440
3441 ctx->flow->depth--;
3442 }
3443
3444 void ac_build_endloop(struct ac_llvm_context *ctx, int label_id)
3445 {
3446 struct ac_llvm_flow *current_loop = get_current_flow(ctx);
3447
3448 assert(current_loop->loop_entry_block);
3449
3450 emit_default_branch(ctx->builder, current_loop->loop_entry_block);
3451
3452 LLVMPositionBuilderAtEnd(ctx->builder, current_loop->next_block);
3453 set_basicblock_name(current_loop->next_block, "endloop", label_id);
3454 ctx->flow->depth--;
3455 }
3456
3457 void ac_build_ifcc(struct ac_llvm_context *ctx, LLVMValueRef cond, int label_id)
3458 {
3459 struct ac_llvm_flow *flow = push_flow(ctx);
3460 LLVMBasicBlockRef if_block;
3461
3462 if_block = append_basic_block(ctx, "IF");
3463 flow->next_block = append_basic_block(ctx, "ELSE");
3464 set_basicblock_name(if_block, "if", label_id);
3465 LLVMBuildCondBr(ctx->builder, cond, if_block, flow->next_block);
3466 LLVMPositionBuilderAtEnd(ctx->builder, if_block);
3467 }
3468
3469 void ac_build_if(struct ac_llvm_context *ctx, LLVMValueRef value,
3470 int label_id)
3471 {
3472 LLVMValueRef cond = LLVMBuildFCmp(ctx->builder, LLVMRealUNE,
3473 value, ctx->f32_0, "");
3474 ac_build_ifcc(ctx, cond, label_id);
3475 }
3476
3477 void ac_build_uif(struct ac_llvm_context *ctx, LLVMValueRef value,
3478 int label_id)
3479 {
3480 LLVMValueRef cond = LLVMBuildICmp(ctx->builder, LLVMIntNE,
3481 ac_to_integer(ctx, value),
3482 ctx->i32_0, "");
3483 ac_build_ifcc(ctx, cond, label_id);
3484 }
3485
3486 LLVMValueRef ac_build_alloca_undef(struct ac_llvm_context *ac, LLVMTypeRef type,
3487 const char *name)
3488 {
3489 LLVMBuilderRef builder = ac->builder;
3490 LLVMBasicBlockRef current_block = LLVMGetInsertBlock(builder);
3491 LLVMValueRef function = LLVMGetBasicBlockParent(current_block);
3492 LLVMBasicBlockRef first_block = LLVMGetEntryBasicBlock(function);
3493 LLVMValueRef first_instr = LLVMGetFirstInstruction(first_block);
3494 LLVMBuilderRef first_builder = LLVMCreateBuilderInContext(ac->context);
3495 LLVMValueRef res;
3496
3497 if (first_instr) {
3498 LLVMPositionBuilderBefore(first_builder, first_instr);
3499 } else {
3500 LLVMPositionBuilderAtEnd(first_builder, first_block);
3501 }
3502
3503 res = LLVMBuildAlloca(first_builder, type, name);
3504 LLVMDisposeBuilder(first_builder);
3505 return res;
3506 }
3507
3508 LLVMValueRef ac_build_alloca(struct ac_llvm_context *ac,
3509 LLVMTypeRef type, const char *name)
3510 {
3511 LLVMValueRef ptr = ac_build_alloca_undef(ac, type, name);
3512 LLVMBuildStore(ac->builder, LLVMConstNull(type), ptr);
3513 return ptr;
3514 }
3515
3516 LLVMValueRef ac_cast_ptr(struct ac_llvm_context *ctx, LLVMValueRef ptr,
3517 LLVMTypeRef type)
3518 {
3519 int addr_space = LLVMGetPointerAddressSpace(LLVMTypeOf(ptr));
3520 return LLVMBuildBitCast(ctx->builder, ptr,
3521 LLVMPointerType(type, addr_space), "");
3522 }
3523
3524 LLVMValueRef ac_trim_vector(struct ac_llvm_context *ctx, LLVMValueRef value,
3525 unsigned count)
3526 {
3527 unsigned num_components = ac_get_llvm_num_components(value);
3528 if (count == num_components)
3529 return value;
3530
3531 LLVMValueRef masks[MAX2(count, 2)];
3532 masks[0] = ctx->i32_0;
3533 masks[1] = ctx->i32_1;
3534 for (unsigned i = 2; i < count; i++)
3535 masks[i] = LLVMConstInt(ctx->i32, i, false);
3536
3537 if (count == 1)
3538 return LLVMBuildExtractElement(ctx->builder, value, masks[0],
3539 "");
3540
3541 LLVMValueRef swizzle = LLVMConstVector(masks, count);
3542 return LLVMBuildShuffleVector(ctx->builder, value, value, swizzle, "");
3543 }
3544
3545 LLVMValueRef ac_unpack_param(struct ac_llvm_context *ctx, LLVMValueRef param,
3546 unsigned rshift, unsigned bitwidth)
3547 {
3548 LLVMValueRef value = param;
3549 if (rshift)
3550 value = LLVMBuildLShr(ctx->builder, value,
3551 LLVMConstInt(ctx->i32, rshift, false), "");
3552
3553 if (rshift + bitwidth < 32) {
3554 unsigned mask = (1 << bitwidth) - 1;
3555 value = LLVMBuildAnd(ctx->builder, value,
3556 LLVMConstInt(ctx->i32, mask, false), "");
3557 }
3558 return value;
3559 }
3560
3561 /* Adjust the sample index according to FMASK.
3562 *
3563 * For uncompressed MSAA surfaces, FMASK should return 0x76543210,
3564 * which is the identity mapping. Each nibble says which physical sample
3565 * should be fetched to get that sample.
3566 *
3567 * For example, 0x11111100 means there are only 2 samples stored and
3568 * the second sample covers 3/4 of the pixel. When reading samples 0
3569 * and 1, return physical sample 0 (determined by the first two 0s
3570 * in FMASK), otherwise return physical sample 1.
3571 *
3572 * The sample index should be adjusted as follows:
3573 * addr[sample_index] = (fmask >> (addr[sample_index] * 4)) & 0xF;
3574 */
3575 void ac_apply_fmask_to_sample(struct ac_llvm_context *ac, LLVMValueRef fmask,
3576 LLVMValueRef *addr, bool is_array_tex)
3577 {
3578 struct ac_image_args fmask_load = {};
3579 fmask_load.opcode = ac_image_load;
3580 fmask_load.resource = fmask;
3581 fmask_load.dmask = 0xf;
3582 fmask_load.dim = is_array_tex ? ac_image_2darray : ac_image_2d;
3583 fmask_load.attributes = AC_FUNC_ATTR_READNONE;
3584
3585 fmask_load.coords[0] = addr[0];
3586 fmask_load.coords[1] = addr[1];
3587 if (is_array_tex)
3588 fmask_load.coords[2] = addr[2];
3589
3590 LLVMValueRef fmask_value = ac_build_image_opcode(ac, &fmask_load);
3591 fmask_value = LLVMBuildExtractElement(ac->builder, fmask_value,
3592 ac->i32_0, "");
3593
3594 /* Apply the formula. */
3595 unsigned sample_chan = is_array_tex ? 3 : 2;
3596 LLVMValueRef final_sample;
3597 final_sample = LLVMBuildMul(ac->builder, addr[sample_chan],
3598 LLVMConstInt(ac->i32, 4, 0), "");
3599 final_sample = LLVMBuildLShr(ac->builder, fmask_value, final_sample, "");
3600 /* Mask the sample index by 0x7, because 0x8 means an unknown value
3601 * with EQAA, so those will map to 0. */
3602 final_sample = LLVMBuildAnd(ac->builder, final_sample,
3603 LLVMConstInt(ac->i32, 0x7, 0), "");
3604
3605 /* Don't rewrite the sample index if WORD1.DATA_FORMAT of the FMASK
3606 * resource descriptor is 0 (invalid).
3607 */
3608 LLVMValueRef tmp;
3609 tmp = LLVMBuildBitCast(ac->builder, fmask, ac->v8i32, "");
3610 tmp = LLVMBuildExtractElement(ac->builder, tmp, ac->i32_1, "");
3611 tmp = LLVMBuildICmp(ac->builder, LLVMIntNE, tmp, ac->i32_0, "");
3612
3613 /* Replace the MSAA sample index. */
3614 addr[sample_chan] = LLVMBuildSelect(ac->builder, tmp, final_sample,
3615 addr[sample_chan], "");
3616 }
3617
3618 static LLVMValueRef
3619 _ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src,
3620 LLVMValueRef lane, bool with_opt_barrier)
3621 {
3622 LLVMTypeRef type = LLVMTypeOf(src);
3623 LLVMValueRef result;
3624
3625 if (with_opt_barrier)
3626 ac_build_optimization_barrier(ctx, &src);
3627
3628 src = LLVMBuildZExt(ctx->builder, src, ctx->i32, "");
3629 if (lane)
3630 lane = LLVMBuildZExt(ctx->builder, lane, ctx->i32, "");
3631
3632 result = ac_build_intrinsic(ctx,
3633 lane == NULL ? "llvm.amdgcn.readfirstlane" : "llvm.amdgcn.readlane",
3634 ctx->i32, (LLVMValueRef []) { src, lane },
3635 lane == NULL ? 1 : 2,
3636 AC_FUNC_ATTR_READNONE |
3637 AC_FUNC_ATTR_CONVERGENT);
3638
3639 return LLVMBuildTrunc(ctx->builder, result, type, "");
3640 }
3641
3642 static LLVMValueRef
3643 ac_build_readlane_common(struct ac_llvm_context *ctx,
3644 LLVMValueRef src, LLVMValueRef lane,
3645 bool with_opt_barrier)
3646 {
3647 LLVMTypeRef src_type = LLVMTypeOf(src);
3648 src = ac_to_integer(ctx, src);
3649 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
3650 LLVMValueRef ret;
3651
3652 if (bits > 32) {
3653 assert(bits % 32 == 0);
3654 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
3655 LLVMValueRef src_vector =
3656 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
3657 ret = LLVMGetUndef(vec_type);
3658 for (unsigned i = 0; i < bits / 32; i++) {
3659 LLVMValueRef ret_comp;
3660
3661 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3662 LLVMConstInt(ctx->i32, i, 0), "");
3663
3664 ret_comp = _ac_build_readlane(ctx, src, lane,
3665 with_opt_barrier);
3666
3667 ret = LLVMBuildInsertElement(ctx->builder, ret, ret_comp,
3668 LLVMConstInt(ctx->i32, i, 0), "");
3669 }
3670 } else {
3671 ret = _ac_build_readlane(ctx, src, lane, with_opt_barrier);
3672 }
3673
3674 if (LLVMGetTypeKind(src_type) == LLVMPointerTypeKind)
3675 return LLVMBuildIntToPtr(ctx->builder, ret, src_type, "");
3676 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3677 }
3678
3679 /**
3680 * Builds the "llvm.amdgcn.readlane" or "llvm.amdgcn.readfirstlane" intrinsic.
3681 *
3682 * The optimization barrier is not needed if the value is the same in all lanes
3683 * or if this is called in the outermost block.
3684 *
3685 * @param ctx
3686 * @param src
3687 * @param lane - id of the lane or NULL for the first active lane
3688 * @return value of the lane
3689 */
3690 LLVMValueRef ac_build_readlane_no_opt_barrier(struct ac_llvm_context *ctx,
3691 LLVMValueRef src, LLVMValueRef lane)
3692 {
3693 return ac_build_readlane_common(ctx, src, lane, false);
3694 }
3695
3696
3697 LLVMValueRef
3698 ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef lane)
3699 {
3700 return ac_build_readlane_common(ctx, src, lane, true);
3701 }
3702
3703 LLVMValueRef
3704 ac_build_writelane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef value, LLVMValueRef lane)
3705 {
3706 return ac_build_intrinsic(ctx, "llvm.amdgcn.writelane", ctx->i32,
3707 (LLVMValueRef []) {value, lane, src}, 3,
3708 AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
3709 }
3710
3711 LLVMValueRef
3712 ac_build_mbcnt(struct ac_llvm_context *ctx, LLVMValueRef mask)
3713 {
3714 if (ctx->wave_size == 32) {
3715 return ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.lo", ctx->i32,
3716 (LLVMValueRef []) { mask, ctx->i32_0 },
3717 2, AC_FUNC_ATTR_READNONE);
3718 }
3719 LLVMValueRef mask_vec = LLVMBuildBitCast(ctx->builder, mask, ctx->v2i32, "");
3720 LLVMValueRef mask_lo = LLVMBuildExtractElement(ctx->builder, mask_vec,
3721 ctx->i32_0, "");
3722 LLVMValueRef mask_hi = LLVMBuildExtractElement(ctx->builder, mask_vec,
3723 ctx->i32_1, "");
3724 LLVMValueRef val =
3725 ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.lo", ctx->i32,
3726 (LLVMValueRef []) { mask_lo, ctx->i32_0 },
3727 2, AC_FUNC_ATTR_READNONE);
3728 val = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi", ctx->i32,
3729 (LLVMValueRef []) { mask_hi, val },
3730 2, AC_FUNC_ATTR_READNONE);
3731 return val;
3732 }
3733
3734 enum dpp_ctrl {
3735 _dpp_quad_perm = 0x000,
3736 _dpp_row_sl = 0x100,
3737 _dpp_row_sr = 0x110,
3738 _dpp_row_rr = 0x120,
3739 dpp_wf_sl1 = 0x130,
3740 dpp_wf_rl1 = 0x134,
3741 dpp_wf_sr1 = 0x138,
3742 dpp_wf_rr1 = 0x13C,
3743 dpp_row_mirror = 0x140,
3744 dpp_row_half_mirror = 0x141,
3745 dpp_row_bcast15 = 0x142,
3746 dpp_row_bcast31 = 0x143
3747 };
3748
3749 static inline enum dpp_ctrl
3750 dpp_quad_perm(unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
3751 {
3752 assert(lane0 < 4 && lane1 < 4 && lane2 < 4 && lane3 < 4);
3753 return _dpp_quad_perm | lane0 | (lane1 << 2) | (lane2 << 4) | (lane3 << 6);
3754 }
3755
3756 static inline enum dpp_ctrl
3757 dpp_row_sl(unsigned amount)
3758 {
3759 assert(amount > 0 && amount < 16);
3760 return _dpp_row_sl | amount;
3761 }
3762
3763 static inline enum dpp_ctrl
3764 dpp_row_sr(unsigned amount)
3765 {
3766 assert(amount > 0 && amount < 16);
3767 return _dpp_row_sr | amount;
3768 }
3769
3770 static LLVMValueRef
3771 _ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
3772 enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
3773 bool bound_ctrl)
3774 {
3775 LLVMTypeRef type = LLVMTypeOf(src);
3776 LLVMValueRef res;
3777
3778 old = LLVMBuildZExt(ctx->builder, old, ctx->i32, "");
3779 src = LLVMBuildZExt(ctx->builder, src, ctx->i32, "");
3780
3781 res = ac_build_intrinsic(ctx, "llvm.amdgcn.update.dpp.i32", ctx->i32,
3782 (LLVMValueRef[]) {
3783 old, src,
3784 LLVMConstInt(ctx->i32, dpp_ctrl, 0),
3785 LLVMConstInt(ctx->i32, row_mask, 0),
3786 LLVMConstInt(ctx->i32, bank_mask, 0),
3787 LLVMConstInt(ctx->i1, bound_ctrl, 0) },
3788 6, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
3789
3790 return LLVMBuildTrunc(ctx->builder, res, type, "");
3791 }
3792
3793 static LLVMValueRef
3794 ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
3795 enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
3796 bool bound_ctrl)
3797 {
3798 LLVMTypeRef src_type = LLVMTypeOf(src);
3799 src = ac_to_integer(ctx, src);
3800 old = ac_to_integer(ctx, old);
3801 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
3802 LLVMValueRef ret;
3803 if (bits > 32) {
3804 assert(bits % 32 == 0);
3805 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
3806 LLVMValueRef src_vector =
3807 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
3808 LLVMValueRef old_vector =
3809 LLVMBuildBitCast(ctx->builder, old, vec_type, "");
3810 ret = LLVMGetUndef(vec_type);
3811 for (unsigned i = 0; i < bits / 32; i++) {
3812 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3813 LLVMConstInt(ctx->i32, i,
3814 0), "");
3815 old = LLVMBuildExtractElement(ctx->builder, old_vector,
3816 LLVMConstInt(ctx->i32, i,
3817 0), "");
3818 LLVMValueRef ret_comp = _ac_build_dpp(ctx, old, src,
3819 dpp_ctrl,
3820 row_mask,
3821 bank_mask,
3822 bound_ctrl);
3823 ret = LLVMBuildInsertElement(ctx->builder, ret,
3824 ret_comp,
3825 LLVMConstInt(ctx->i32, i,
3826 0), "");
3827 }
3828 } else {
3829 ret = _ac_build_dpp(ctx, old, src, dpp_ctrl, row_mask,
3830 bank_mask, bound_ctrl);
3831 }
3832 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3833 }
3834
3835 static LLVMValueRef
3836 _ac_build_permlane16(struct ac_llvm_context *ctx, LLVMValueRef src, uint64_t sel,
3837 bool exchange_rows, bool bound_ctrl)
3838 {
3839 LLVMTypeRef type = LLVMTypeOf(src);
3840 LLVMValueRef result;
3841
3842 src = LLVMBuildZExt(ctx->builder, src, ctx->i32, "");
3843
3844 LLVMValueRef args[6] = {
3845 src,
3846 src,
3847 LLVMConstInt(ctx->i32, sel, false),
3848 LLVMConstInt(ctx->i32, sel >> 32, false),
3849 ctx->i1true, /* fi */
3850 bound_ctrl ? ctx->i1true : ctx->i1false,
3851 };
3852
3853 result = ac_build_intrinsic(ctx, exchange_rows ? "llvm.amdgcn.permlanex16"
3854 : "llvm.amdgcn.permlane16",
3855 ctx->i32, args, 6,
3856 AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
3857
3858 return LLVMBuildTrunc(ctx->builder, result, type, "");
3859 }
3860
3861 static LLVMValueRef
3862 ac_build_permlane16(struct ac_llvm_context *ctx, LLVMValueRef src, uint64_t sel,
3863 bool exchange_rows, bool bound_ctrl)
3864 {
3865 LLVMTypeRef src_type = LLVMTypeOf(src);
3866 src = ac_to_integer(ctx, src);
3867 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
3868 LLVMValueRef ret;
3869 if (bits > 32) {
3870 assert(bits % 32 == 0);
3871 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
3872 LLVMValueRef src_vector =
3873 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
3874 ret = LLVMGetUndef(vec_type);
3875 for (unsigned i = 0; i < bits / 32; i++) {
3876 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3877 LLVMConstInt(ctx->i32, i,
3878 0), "");
3879 LLVMValueRef ret_comp =
3880 _ac_build_permlane16(ctx, src, sel,
3881 exchange_rows,
3882 bound_ctrl);
3883 ret = LLVMBuildInsertElement(ctx->builder, ret,
3884 ret_comp,
3885 LLVMConstInt(ctx->i32, i,
3886 0), "");
3887 }
3888 } else {
3889 ret = _ac_build_permlane16(ctx, src, sel, exchange_rows,
3890 bound_ctrl);
3891 }
3892 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3893 }
3894
3895 static inline unsigned
3896 ds_pattern_bitmode(unsigned and_mask, unsigned or_mask, unsigned xor_mask)
3897 {
3898 assert(and_mask < 32 && or_mask < 32 && xor_mask < 32);
3899 return and_mask | (or_mask << 5) | (xor_mask << 10);
3900 }
3901
3902 static LLVMValueRef
3903 _ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
3904 {
3905 LLVMTypeRef src_type = LLVMTypeOf(src);
3906 LLVMValueRef ret;
3907
3908 src = LLVMBuildZExt(ctx->builder, src, ctx->i32, "");
3909
3910 ret = ac_build_intrinsic(ctx, "llvm.amdgcn.ds.swizzle", ctx->i32,
3911 (LLVMValueRef []) {
3912 src, LLVMConstInt(ctx->i32, mask, 0) },
3913 2, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
3914
3915 return LLVMBuildTrunc(ctx->builder, ret, src_type, "");
3916 }
3917
3918 LLVMValueRef
3919 ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
3920 {
3921 LLVMTypeRef src_type = LLVMTypeOf(src);
3922 src = ac_to_integer(ctx, src);
3923 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
3924 LLVMValueRef ret;
3925 if (bits > 32) {
3926 assert(bits % 32 == 0);
3927 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
3928 LLVMValueRef src_vector =
3929 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
3930 ret = LLVMGetUndef(vec_type);
3931 for (unsigned i = 0; i < bits / 32; i++) {
3932 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3933 LLVMConstInt(ctx->i32, i,
3934 0), "");
3935 LLVMValueRef ret_comp = _ac_build_ds_swizzle(ctx, src,
3936 mask);
3937 ret = LLVMBuildInsertElement(ctx->builder, ret,
3938 ret_comp,
3939 LLVMConstInt(ctx->i32, i,
3940 0), "");
3941 }
3942 } else {
3943 ret = _ac_build_ds_swizzle(ctx, src, mask);
3944 }
3945 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3946 }
3947
3948 static LLVMValueRef
3949 ac_build_wwm(struct ac_llvm_context *ctx, LLVMValueRef src)
3950 {
3951 LLVMTypeRef src_type = LLVMTypeOf(src);
3952 unsigned bitsize = ac_get_elem_bits(ctx, src_type);
3953 char name[32], type[8];
3954 LLVMValueRef ret;
3955
3956 src = ac_to_integer(ctx, src);
3957
3958 if (bitsize < 32)
3959 src = LLVMBuildZExt(ctx->builder, src, ctx->i32, "");
3960
3961 ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
3962 snprintf(name, sizeof(name), "llvm.amdgcn.wwm.%s", type);
3963 ret = ac_build_intrinsic(ctx, name, LLVMTypeOf(src),
3964 (LLVMValueRef []) { src }, 1,
3965 AC_FUNC_ATTR_READNONE);
3966
3967 if (bitsize < 32)
3968 ret = LLVMBuildTrunc(ctx->builder, ret,
3969 ac_to_integer_type(ctx, src_type), "");
3970
3971 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3972 }
3973
3974 static LLVMValueRef
3975 ac_build_set_inactive(struct ac_llvm_context *ctx, LLVMValueRef src,
3976 LLVMValueRef inactive)
3977 {
3978 char name[33], type[8];
3979 LLVMTypeRef src_type = LLVMTypeOf(src);
3980 unsigned bitsize = ac_get_elem_bits(ctx, src_type);
3981 src = ac_to_integer(ctx, src);
3982 inactive = ac_to_integer(ctx, inactive);
3983
3984 if (bitsize < 32) {
3985 src = LLVMBuildZExt(ctx->builder, src, ctx->i32, "");
3986 inactive = LLVMBuildZExt(ctx->builder, inactive, ctx->i32, "");
3987 }
3988
3989 ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
3990 snprintf(name, sizeof(name), "llvm.amdgcn.set.inactive.%s", type);
3991 LLVMValueRef ret =
3992 ac_build_intrinsic(ctx, name,
3993 LLVMTypeOf(src), (LLVMValueRef []) {
3994 src, inactive }, 2,
3995 AC_FUNC_ATTR_READNONE |
3996 AC_FUNC_ATTR_CONVERGENT);
3997 if (bitsize < 32)
3998 ret = LLVMBuildTrunc(ctx->builder, ret, src_type, "");
3999
4000 return ret;
4001 }
4002
4003 static LLVMValueRef
4004 get_reduction_identity(struct ac_llvm_context *ctx, nir_op op, unsigned type_size)
4005 {
4006 if (type_size == 1) {
4007 switch (op) {
4008 case nir_op_iadd: return ctx->i8_0;
4009 case nir_op_imul: return ctx->i8_1;
4010 case nir_op_imin: return LLVMConstInt(ctx->i8, INT8_MAX, 0);
4011 case nir_op_umin: return LLVMConstInt(ctx->i8, UINT8_MAX, 0);
4012 case nir_op_imax: return LLVMConstInt(ctx->i8, INT8_MIN, 0);
4013 case nir_op_umax: return ctx->i8_0;
4014 case nir_op_iand: return LLVMConstInt(ctx->i8, -1, 0);
4015 case nir_op_ior: return ctx->i8_0;
4016 case nir_op_ixor: return ctx->i8_0;
4017 default:
4018 unreachable("bad reduction intrinsic");
4019 }
4020 } else if (type_size == 2) {
4021 switch (op) {
4022 case nir_op_iadd: return ctx->i16_0;
4023 case nir_op_fadd: return ctx->f16_0;
4024 case nir_op_imul: return ctx->i16_1;
4025 case nir_op_fmul: return ctx->f16_1;
4026 case nir_op_imin: return LLVMConstInt(ctx->i16, INT16_MAX, 0);
4027 case nir_op_umin: return LLVMConstInt(ctx->i16, UINT16_MAX, 0);
4028 case nir_op_fmin: return LLVMConstReal(ctx->f16, INFINITY);
4029 case nir_op_imax: return LLVMConstInt(ctx->i16, INT16_MIN, 0);
4030 case nir_op_umax: return ctx->i16_0;
4031 case nir_op_fmax: return LLVMConstReal(ctx->f16, -INFINITY);
4032 case nir_op_iand: return LLVMConstInt(ctx->i16, -1, 0);
4033 case nir_op_ior: return ctx->i16_0;
4034 case nir_op_ixor: return ctx->i16_0;
4035 default:
4036 unreachable("bad reduction intrinsic");
4037 }
4038 } else if (type_size == 4) {
4039 switch (op) {
4040 case nir_op_iadd: return ctx->i32_0;
4041 case nir_op_fadd: return ctx->f32_0;
4042 case nir_op_imul: return ctx->i32_1;
4043 case nir_op_fmul: return ctx->f32_1;
4044 case nir_op_imin: return LLVMConstInt(ctx->i32, INT32_MAX, 0);
4045 case nir_op_umin: return LLVMConstInt(ctx->i32, UINT32_MAX, 0);
4046 case nir_op_fmin: return LLVMConstReal(ctx->f32, INFINITY);
4047 case nir_op_imax: return LLVMConstInt(ctx->i32, INT32_MIN, 0);
4048 case nir_op_umax: return ctx->i32_0;
4049 case nir_op_fmax: return LLVMConstReal(ctx->f32, -INFINITY);
4050 case nir_op_iand: return LLVMConstInt(ctx->i32, -1, 0);
4051 case nir_op_ior: return ctx->i32_0;
4052 case nir_op_ixor: return ctx->i32_0;
4053 default:
4054 unreachable("bad reduction intrinsic");
4055 }
4056 } else { /* type_size == 64bit */
4057 switch (op) {
4058 case nir_op_iadd: return ctx->i64_0;
4059 case nir_op_fadd: return ctx->f64_0;
4060 case nir_op_imul: return ctx->i64_1;
4061 case nir_op_fmul: return ctx->f64_1;
4062 case nir_op_imin: return LLVMConstInt(ctx->i64, INT64_MAX, 0);
4063 case nir_op_umin: return LLVMConstInt(ctx->i64, UINT64_MAX, 0);
4064 case nir_op_fmin: return LLVMConstReal(ctx->f64, INFINITY);
4065 case nir_op_imax: return LLVMConstInt(ctx->i64, INT64_MIN, 0);
4066 case nir_op_umax: return ctx->i64_0;
4067 case nir_op_fmax: return LLVMConstReal(ctx->f64, -INFINITY);
4068 case nir_op_iand: return LLVMConstInt(ctx->i64, -1, 0);
4069 case nir_op_ior: return ctx->i64_0;
4070 case nir_op_ixor: return ctx->i64_0;
4071 default:
4072 unreachable("bad reduction intrinsic");
4073 }
4074 }
4075 }
4076
4077 static LLVMValueRef
4078 ac_build_alu_op(struct ac_llvm_context *ctx, LLVMValueRef lhs, LLVMValueRef rhs, nir_op op)
4079 {
4080 bool _64bit = ac_get_type_size(LLVMTypeOf(lhs)) == 8;
4081 bool _32bit = ac_get_type_size(LLVMTypeOf(lhs)) == 4;
4082 switch (op) {
4083 case nir_op_iadd: return LLVMBuildAdd(ctx->builder, lhs, rhs, "");
4084 case nir_op_fadd: return LLVMBuildFAdd(ctx->builder, lhs, rhs, "");
4085 case nir_op_imul: return LLVMBuildMul(ctx->builder, lhs, rhs, "");
4086 case nir_op_fmul: return LLVMBuildFMul(ctx->builder, lhs, rhs, "");
4087 case nir_op_imin: return LLVMBuildSelect(ctx->builder,
4088 LLVMBuildICmp(ctx->builder, LLVMIntSLT, lhs, rhs, ""),
4089 lhs, rhs, "");
4090 case nir_op_umin: return LLVMBuildSelect(ctx->builder,
4091 LLVMBuildICmp(ctx->builder, LLVMIntULT, lhs, rhs, ""),
4092 lhs, rhs, "");
4093 case nir_op_fmin: return ac_build_intrinsic(ctx,
4094 _64bit ? "llvm.minnum.f64" : _32bit ? "llvm.minnum.f32" : "llvm.minnum.f16",
4095 _64bit ? ctx->f64 : _32bit ? ctx->f32 : ctx->f16,
4096 (LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
4097 case nir_op_imax: return LLVMBuildSelect(ctx->builder,
4098 LLVMBuildICmp(ctx->builder, LLVMIntSGT, lhs, rhs, ""),
4099 lhs, rhs, "");
4100 case nir_op_umax: return LLVMBuildSelect(ctx->builder,
4101 LLVMBuildICmp(ctx->builder, LLVMIntUGT, lhs, rhs, ""),
4102 lhs, rhs, "");
4103 case nir_op_fmax: return ac_build_intrinsic(ctx,
4104 _64bit ? "llvm.maxnum.f64" : _32bit ? "llvm.maxnum.f32" : "llvm.maxnum.f16",
4105 _64bit ? ctx->f64 : _32bit ? ctx->f32 : ctx->f16,
4106 (LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
4107 case nir_op_iand: return LLVMBuildAnd(ctx->builder, lhs, rhs, "");
4108 case nir_op_ior: return LLVMBuildOr(ctx->builder, lhs, rhs, "");
4109 case nir_op_ixor: return LLVMBuildXor(ctx->builder, lhs, rhs, "");
4110 default:
4111 unreachable("bad reduction intrinsic");
4112 }
4113 }
4114
4115 /**
4116 * \param src The value to shift.
4117 * \param identity The value to use the first lane.
4118 * \param maxprefix specifies that the result only needs to be correct for a
4119 * prefix of this many threads
4120 * \return src, shifted 1 lane up, and identity shifted into lane 0.
4121 */
4122 static LLVMValueRef
4123 ac_wavefront_shift_right_1(struct ac_llvm_context *ctx, LLVMValueRef src,
4124 LLVMValueRef identity, unsigned maxprefix)
4125 {
4126 if (ctx->chip_class >= GFX10) {
4127 /* wavefront shift_right by 1 on GFX10 (emulate dpp_wf_sr1) */
4128 LLVMValueRef active, tmp1, tmp2;
4129 LLVMValueRef tid = ac_get_thread_id(ctx);
4130
4131 tmp1 = ac_build_dpp(ctx, identity, src, dpp_row_sr(1), 0xf, 0xf, false);
4132
4133 tmp2 = ac_build_permlane16(ctx, src, (uint64_t)~0, true, false);
4134
4135 if (maxprefix > 32) {
4136 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ, tid,
4137 LLVMConstInt(ctx->i32, 32, false), "");
4138
4139 tmp2 = LLVMBuildSelect(ctx->builder, active,
4140 ac_build_readlane(ctx, src,
4141 LLVMConstInt(ctx->i32, 31, false)),
4142 tmp2, "");
4143
4144 active = LLVMBuildOr(ctx->builder, active,
4145 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
4146 LLVMBuildAnd(ctx->builder, tid,
4147 LLVMConstInt(ctx->i32, 0x1f, false), ""),
4148 LLVMConstInt(ctx->i32, 0x10, false), ""), "");
4149 return LLVMBuildSelect(ctx->builder, active, tmp2, tmp1, "");
4150 } else if (maxprefix > 16) {
4151 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ, tid,
4152 LLVMConstInt(ctx->i32, 16, false), "");
4153
4154 return LLVMBuildSelect(ctx->builder, active, tmp2, tmp1, "");
4155 }
4156 } else if (ctx->chip_class >= GFX8) {
4157 return ac_build_dpp(ctx, identity, src, dpp_wf_sr1, 0xf, 0xf, false);
4158 }
4159
4160 /* wavefront shift_right by 1 on SI/CI */
4161 LLVMValueRef active, tmp1, tmp2;
4162 LLVMValueRef tid = ac_get_thread_id(ctx);
4163 tmp1 = ac_build_ds_swizzle(ctx, src, (1 << 15) | dpp_quad_perm(0, 0, 1, 2));
4164 tmp2 = ac_build_ds_swizzle(ctx, src, ds_pattern_bitmode(0x18, 0x03, 0x00));
4165 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
4166 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 0x7, 0), ""),
4167 LLVMConstInt(ctx->i32, 0x4, 0), "");
4168 tmp1 = LLVMBuildSelect(ctx->builder, active, tmp2, tmp1, "");
4169 tmp2 = ac_build_ds_swizzle(ctx, src, ds_pattern_bitmode(0x10, 0x07, 0x00));
4170 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
4171 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 0xf, 0), ""),
4172 LLVMConstInt(ctx->i32, 0x8, 0), "");
4173 tmp1 = LLVMBuildSelect(ctx->builder, active, tmp2, tmp1, "");
4174 tmp2 = ac_build_ds_swizzle(ctx, src, ds_pattern_bitmode(0x00, 0x0f, 0x00));
4175 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
4176 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 0x1f, 0), ""),
4177 LLVMConstInt(ctx->i32, 0x10, 0), "");
4178 tmp1 = LLVMBuildSelect(ctx->builder, active, tmp2, tmp1, "");
4179 tmp2 = ac_build_readlane(ctx, src, LLVMConstInt(ctx->i32, 31, 0));
4180 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ, tid, LLVMConstInt(ctx->i32, 32, 0), "");
4181 tmp1 = LLVMBuildSelect(ctx->builder, active, tmp2, tmp1, "");
4182 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ, tid, LLVMConstInt(ctx->i32, 0, 0), "");
4183 return LLVMBuildSelect(ctx->builder, active, identity, tmp1, "");
4184 }
4185
4186 /**
4187 * \param maxprefix specifies that the result only needs to be correct for a
4188 * prefix of this many threads
4189 */
4190 static LLVMValueRef
4191 ac_build_scan(struct ac_llvm_context *ctx, nir_op op, LLVMValueRef src, LLVMValueRef identity,
4192 unsigned maxprefix, bool inclusive)
4193 {
4194 LLVMValueRef result, tmp;
4195
4196 if (!inclusive)
4197 src = ac_wavefront_shift_right_1(ctx, src, identity, maxprefix);
4198
4199 result = src;
4200
4201 if (ctx->chip_class <= GFX7) {
4202 assert(maxprefix == 64);
4203 LLVMValueRef tid = ac_get_thread_id(ctx);
4204 LLVMValueRef active;
4205 tmp = ac_build_ds_swizzle(ctx, src, ds_pattern_bitmode(0x1e, 0x00, 0x00));
4206 active = LLVMBuildICmp(ctx->builder, LLVMIntNE,
4207 LLVMBuildAnd(ctx->builder, tid, ctx->i32_1, ""),
4208 ctx->i32_0, "");
4209 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4210 result = ac_build_alu_op(ctx, result, tmp, op);
4211 tmp = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1c, 0x01, 0x00));
4212 active = LLVMBuildICmp(ctx->builder, LLVMIntNE,
4213 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 2, 0), ""),
4214 ctx->i32_0, "");
4215 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4216 result = ac_build_alu_op(ctx, result, tmp, op);
4217 tmp = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x18, 0x03, 0x00));
4218 active = LLVMBuildICmp(ctx->builder, LLVMIntNE,
4219 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 4, 0), ""),
4220 ctx->i32_0, "");
4221 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4222 result = ac_build_alu_op(ctx, result, tmp, op);
4223 tmp = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x10, 0x07, 0x00));
4224 active = LLVMBuildICmp(ctx->builder, LLVMIntNE,
4225 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 8, 0), ""),
4226 ctx->i32_0, "");
4227 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4228 result = ac_build_alu_op(ctx, result, tmp, op);
4229 tmp = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x00, 0x0f, 0x00));
4230 active = LLVMBuildICmp(ctx->builder, LLVMIntNE,
4231 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 16, 0), ""),
4232 ctx->i32_0, "");
4233 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4234 result = ac_build_alu_op(ctx, result, tmp, op);
4235 tmp = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 31, 0));
4236 active = LLVMBuildICmp(ctx->builder, LLVMIntNE,
4237 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 32, 0), ""),
4238 ctx->i32_0, "");
4239 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4240 result = ac_build_alu_op(ctx, result, tmp, op);
4241 return result;
4242 }
4243
4244 if (maxprefix <= 1)
4245 return result;
4246 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(1), 0xf, 0xf, false);
4247 result = ac_build_alu_op(ctx, result, tmp, op);
4248 if (maxprefix <= 2)
4249 return result;
4250 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(2), 0xf, 0xf, false);
4251 result = ac_build_alu_op(ctx, result, tmp, op);
4252 if (maxprefix <= 3)
4253 return result;
4254 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(3), 0xf, 0xf, false);
4255 result = ac_build_alu_op(ctx, result, tmp, op);
4256 if (maxprefix <= 4)
4257 return result;
4258 tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(4), 0xf, 0xe, false);
4259 result = ac_build_alu_op(ctx, result, tmp, op);
4260 if (maxprefix <= 8)
4261 return result;
4262 tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(8), 0xf, 0xc, false);
4263 result = ac_build_alu_op(ctx, result, tmp, op);
4264 if (maxprefix <= 16)
4265 return result;
4266
4267 if (ctx->chip_class >= GFX10) {
4268 LLVMValueRef tid = ac_get_thread_id(ctx);
4269 LLVMValueRef active;
4270
4271 tmp = ac_build_permlane16(ctx, result, ~(uint64_t)0, true, false);
4272
4273 active = LLVMBuildICmp(ctx->builder, LLVMIntNE,
4274 LLVMBuildAnd(ctx->builder, tid,
4275 LLVMConstInt(ctx->i32, 16, false), ""),
4276 ctx->i32_0, "");
4277
4278 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4279
4280 result = ac_build_alu_op(ctx, result, tmp, op);
4281
4282 if (maxprefix <= 32)
4283 return result;
4284
4285 tmp = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 31, false));
4286
4287 active = LLVMBuildICmp(ctx->builder, LLVMIntUGE, tid,
4288 LLVMConstInt(ctx->i32, 32, false), "");
4289
4290 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4291
4292 result = ac_build_alu_op(ctx, result, tmp, op);
4293 return result;
4294 }
4295
4296 tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
4297 result = ac_build_alu_op(ctx, result, tmp, op);
4298 if (maxprefix <= 32)
4299 return result;
4300 tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
4301 result = ac_build_alu_op(ctx, result, tmp, op);
4302 return result;
4303 }
4304
4305 LLVMValueRef
4306 ac_build_inclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
4307 {
4308 LLVMValueRef result;
4309
4310 if (LLVMTypeOf(src) == ctx->i1 && op == nir_op_iadd) {
4311 LLVMBuilderRef builder = ctx->builder;
4312 src = LLVMBuildZExt(builder, src, ctx->i32, "");
4313 result = ac_build_ballot(ctx, src);
4314 result = ac_build_mbcnt(ctx, result);
4315 result = LLVMBuildAdd(builder, result, src, "");
4316 return result;
4317 }
4318
4319 ac_build_optimization_barrier(ctx, &src);
4320
4321 LLVMValueRef identity =
4322 get_reduction_identity(ctx, op, ac_get_type_size(LLVMTypeOf(src)));
4323 result = LLVMBuildBitCast(ctx->builder, ac_build_set_inactive(ctx, src, identity),
4324 LLVMTypeOf(identity), "");
4325 result = ac_build_scan(ctx, op, result, identity, ctx->wave_size, true);
4326
4327 return ac_build_wwm(ctx, result);
4328 }
4329
4330 LLVMValueRef
4331 ac_build_exclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
4332 {
4333 LLVMValueRef result;
4334
4335 if (LLVMTypeOf(src) == ctx->i1 && op == nir_op_iadd) {
4336 LLVMBuilderRef builder = ctx->builder;
4337 src = LLVMBuildZExt(builder, src, ctx->i32, "");
4338 result = ac_build_ballot(ctx, src);
4339 result = ac_build_mbcnt(ctx, result);
4340 return result;
4341 }
4342
4343 ac_build_optimization_barrier(ctx, &src);
4344
4345 LLVMValueRef identity =
4346 get_reduction_identity(ctx, op, ac_get_type_size(LLVMTypeOf(src)));
4347 result = LLVMBuildBitCast(ctx->builder, ac_build_set_inactive(ctx, src, identity),
4348 LLVMTypeOf(identity), "");
4349 result = ac_build_scan(ctx, op, result, identity, ctx->wave_size, false);
4350
4351 return ac_build_wwm(ctx, result);
4352 }
4353
4354 LLVMValueRef
4355 ac_build_reduce(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op, unsigned cluster_size)
4356 {
4357 if (cluster_size == 1) return src;
4358 ac_build_optimization_barrier(ctx, &src);
4359 LLVMValueRef result, swap;
4360 LLVMValueRef identity = get_reduction_identity(ctx, op,
4361 ac_get_type_size(LLVMTypeOf(src)));
4362 result = LLVMBuildBitCast(ctx->builder,
4363 ac_build_set_inactive(ctx, src, identity),
4364 LLVMTypeOf(identity), "");
4365 swap = ac_build_quad_swizzle(ctx, result, 1, 0, 3, 2);
4366 result = ac_build_alu_op(ctx, result, swap, op);
4367 if (cluster_size == 2) return ac_build_wwm(ctx, result);
4368
4369 swap = ac_build_quad_swizzle(ctx, result, 2, 3, 0, 1);
4370 result = ac_build_alu_op(ctx, result, swap, op);
4371 if (cluster_size == 4) return ac_build_wwm(ctx, result);
4372
4373 if (ctx->chip_class >= GFX8)
4374 swap = ac_build_dpp(ctx, identity, result, dpp_row_half_mirror, 0xf, 0xf, false);
4375 else
4376 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x04));
4377 result = ac_build_alu_op(ctx, result, swap, op);
4378 if (cluster_size == 8) return ac_build_wwm(ctx, result);
4379
4380 if (ctx->chip_class >= GFX8)
4381 swap = ac_build_dpp(ctx, identity, result, dpp_row_mirror, 0xf, 0xf, false);
4382 else
4383 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x08));
4384 result = ac_build_alu_op(ctx, result, swap, op);
4385 if (cluster_size == 16) return ac_build_wwm(ctx, result);
4386
4387 if (ctx->chip_class >= GFX10)
4388 swap = ac_build_permlane16(ctx, result, 0, true, false);
4389 else if (ctx->chip_class >= GFX8 && cluster_size != 32)
4390 swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
4391 else
4392 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x10));
4393 result = ac_build_alu_op(ctx, result, swap, op);
4394 if (cluster_size == 32) return ac_build_wwm(ctx, result);
4395
4396 if (ctx->chip_class >= GFX8) {
4397 if (ctx->wave_size == 64) {
4398 if (ctx->chip_class >= GFX10)
4399 swap = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 31, false));
4400 else
4401 swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
4402 result = ac_build_alu_op(ctx, result, swap, op);
4403 result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 63, 0));
4404 }
4405
4406 return ac_build_wwm(ctx, result);
4407 } else {
4408 swap = ac_build_readlane(ctx, result, ctx->i32_0);
4409 result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 32, 0));
4410 result = ac_build_alu_op(ctx, result, swap, op);
4411 return ac_build_wwm(ctx, result);
4412 }
4413 }
4414
4415 /**
4416 * "Top half" of a scan that reduces per-wave values across an entire
4417 * workgroup.
4418 *
4419 * The source value must be present in the highest lane of the wave, and the
4420 * highest lane must be live.
4421 */
4422 void
4423 ac_build_wg_wavescan_top(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4424 {
4425 if (ws->maxwaves <= 1)
4426 return;
4427
4428 const LLVMValueRef last_lane = LLVMConstInt(ctx->i32, ctx->wave_size - 1, false);
4429 LLVMBuilderRef builder = ctx->builder;
4430 LLVMValueRef tid = ac_get_thread_id(ctx);
4431 LLVMValueRef tmp;
4432
4433 tmp = LLVMBuildICmp(builder, LLVMIntEQ, tid, last_lane, "");
4434 ac_build_ifcc(ctx, tmp, 1000);
4435 LLVMBuildStore(builder, ws->src, LLVMBuildGEP(builder, ws->scratch, &ws->waveidx, 1, ""));
4436 ac_build_endif(ctx, 1000);
4437 }
4438
4439 /**
4440 * "Bottom half" of a scan that reduces per-wave values across an entire
4441 * workgroup.
4442 *
4443 * The caller must place a barrier between the top and bottom halves.
4444 */
4445 void
4446 ac_build_wg_wavescan_bottom(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4447 {
4448 const LLVMTypeRef type = LLVMTypeOf(ws->src);
4449 const LLVMValueRef identity =
4450 get_reduction_identity(ctx, ws->op, ac_get_type_size(type));
4451
4452 if (ws->maxwaves <= 1) {
4453 ws->result_reduce = ws->src;
4454 ws->result_inclusive = ws->src;
4455 ws->result_exclusive = identity;
4456 return;
4457 }
4458 assert(ws->maxwaves <= 32);
4459
4460 LLVMBuilderRef builder = ctx->builder;
4461 LLVMValueRef tid = ac_get_thread_id(ctx);
4462 LLVMBasicBlockRef bbs[2];
4463 LLVMValueRef phivalues_scan[2];
4464 LLVMValueRef tmp, tmp2;
4465
4466 bbs[0] = LLVMGetInsertBlock(builder);
4467 phivalues_scan[0] = LLVMGetUndef(type);
4468
4469 if (ws->enable_reduce)
4470 tmp = LLVMBuildICmp(builder, LLVMIntULT, tid, ws->numwaves, "");
4471 else if (ws->enable_inclusive)
4472 tmp = LLVMBuildICmp(builder, LLVMIntULE, tid, ws->waveidx, "");
4473 else
4474 tmp = LLVMBuildICmp(builder, LLVMIntULT, tid, ws->waveidx, "");
4475 ac_build_ifcc(ctx, tmp, 1001);
4476 {
4477 tmp = LLVMBuildLoad(builder, LLVMBuildGEP(builder, ws->scratch, &tid, 1, ""), "");
4478
4479 ac_build_optimization_barrier(ctx, &tmp);
4480
4481 bbs[1] = LLVMGetInsertBlock(builder);
4482 phivalues_scan[1] = ac_build_scan(ctx, ws->op, tmp, identity, ws->maxwaves, true);
4483 }
4484 ac_build_endif(ctx, 1001);
4485
4486 const LLVMValueRef scan = ac_build_phi(ctx, type, 2, phivalues_scan, bbs);
4487
4488 if (ws->enable_reduce) {
4489 tmp = LLVMBuildSub(builder, ws->numwaves, ctx->i32_1, "");
4490 ws->result_reduce = ac_build_readlane(ctx, scan, tmp);
4491 }
4492 if (ws->enable_inclusive)
4493 ws->result_inclusive = ac_build_readlane(ctx, scan, ws->waveidx);
4494 if (ws->enable_exclusive) {
4495 tmp = LLVMBuildSub(builder, ws->waveidx, ctx->i32_1, "");
4496 tmp = ac_build_readlane(ctx, scan, tmp);
4497 tmp2 = LLVMBuildICmp(builder, LLVMIntEQ, ws->waveidx, ctx->i32_0, "");
4498 ws->result_exclusive = LLVMBuildSelect(builder, tmp2, identity, tmp, "");
4499 }
4500 }
4501
4502 /**
4503 * Inclusive scan of a per-wave value across an entire workgroup.
4504 *
4505 * This implies an s_barrier instruction.
4506 *
4507 * Unlike ac_build_inclusive_scan, the caller \em must ensure that all threads
4508 * of the workgroup are live. (This requirement cannot easily be relaxed in a
4509 * useful manner because of the barrier in the algorithm.)
4510 */
4511 void
4512 ac_build_wg_wavescan(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4513 {
4514 ac_build_wg_wavescan_top(ctx, ws);
4515 ac_build_s_barrier(ctx);
4516 ac_build_wg_wavescan_bottom(ctx, ws);
4517 }
4518
4519 /**
4520 * "Top half" of a scan that reduces per-thread values across an entire
4521 * workgroup.
4522 *
4523 * All lanes must be active when this code runs.
4524 */
4525 void
4526 ac_build_wg_scan_top(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4527 {
4528 if (ws->enable_exclusive) {
4529 ws->extra = ac_build_exclusive_scan(ctx, ws->src, ws->op);
4530 if (LLVMTypeOf(ws->src) == ctx->i1 && ws->op == nir_op_iadd)
4531 ws->src = LLVMBuildZExt(ctx->builder, ws->src, ctx->i32, "");
4532 ws->src = ac_build_alu_op(ctx, ws->extra, ws->src, ws->op);
4533 } else {
4534 ws->src = ac_build_inclusive_scan(ctx, ws->src, ws->op);
4535 }
4536
4537 bool enable_inclusive = ws->enable_inclusive;
4538 bool enable_exclusive = ws->enable_exclusive;
4539 ws->enable_inclusive = false;
4540 ws->enable_exclusive = ws->enable_exclusive || enable_inclusive;
4541 ac_build_wg_wavescan_top(ctx, ws);
4542 ws->enable_inclusive = enable_inclusive;
4543 ws->enable_exclusive = enable_exclusive;
4544 }
4545
4546 /**
4547 * "Bottom half" of a scan that reduces per-thread values across an entire
4548 * workgroup.
4549 *
4550 * The caller must place a barrier between the top and bottom halves.
4551 */
4552 void
4553 ac_build_wg_scan_bottom(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4554 {
4555 bool enable_inclusive = ws->enable_inclusive;
4556 bool enable_exclusive = ws->enable_exclusive;
4557 ws->enable_inclusive = false;
4558 ws->enable_exclusive = ws->enable_exclusive || enable_inclusive;
4559 ac_build_wg_wavescan_bottom(ctx, ws);
4560 ws->enable_inclusive = enable_inclusive;
4561 ws->enable_exclusive = enable_exclusive;
4562
4563 /* ws->result_reduce is already the correct value */
4564 if (ws->enable_inclusive)
4565 ws->result_inclusive = ac_build_alu_op(ctx, ws->result_inclusive, ws->src, ws->op);
4566 if (ws->enable_exclusive)
4567 ws->result_exclusive = ac_build_alu_op(ctx, ws->result_exclusive, ws->extra, ws->op);
4568 }
4569
4570 /**
4571 * A scan that reduces per-thread values across an entire workgroup.
4572 *
4573 * The caller must ensure that all lanes are active when this code runs
4574 * (WWM is insufficient!), because there is an implied barrier.
4575 */
4576 void
4577 ac_build_wg_scan(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4578 {
4579 ac_build_wg_scan_top(ctx, ws);
4580 ac_build_s_barrier(ctx);
4581 ac_build_wg_scan_bottom(ctx, ws);
4582 }
4583
4584 LLVMValueRef
4585 ac_build_quad_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src,
4586 unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
4587 {
4588 unsigned mask = dpp_quad_perm(lane0, lane1, lane2, lane3);
4589 if (ctx->chip_class >= GFX8) {
4590 return ac_build_dpp(ctx, src, src, mask, 0xf, 0xf, false);
4591 } else {
4592 return ac_build_ds_swizzle(ctx, src, (1 << 15) | mask);
4593 }
4594 }
4595
4596 LLVMValueRef
4597 ac_build_shuffle(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef index)
4598 {
4599 LLVMTypeRef type = LLVMTypeOf(src);
4600 LLVMValueRef result;
4601
4602 index = LLVMBuildMul(ctx->builder, index, LLVMConstInt(ctx->i32, 4, 0), "");
4603 src = LLVMBuildZExt(ctx->builder, src, ctx->i32, "");
4604
4605 result = ac_build_intrinsic(ctx, "llvm.amdgcn.ds.bpermute", ctx->i32,
4606 (LLVMValueRef []) {index, src}, 2,
4607 AC_FUNC_ATTR_READNONE |
4608 AC_FUNC_ATTR_CONVERGENT);
4609 return LLVMBuildTrunc(ctx->builder, result, type, "");
4610 }
4611
4612 LLVMValueRef
4613 ac_build_frexp_exp(struct ac_llvm_context *ctx, LLVMValueRef src0,
4614 unsigned bitsize)
4615 {
4616 LLVMTypeRef type;
4617 char *intr;
4618
4619 if (bitsize == 16) {
4620 intr = "llvm.amdgcn.frexp.exp.i16.f16";
4621 type = ctx->i16;
4622 } else if (bitsize == 32) {
4623 intr = "llvm.amdgcn.frexp.exp.i32.f32";
4624 type = ctx->i32;
4625 } else {
4626 intr = "llvm.amdgcn.frexp.exp.i32.f64";
4627 type = ctx->i32;
4628 }
4629
4630 LLVMValueRef params[] = {
4631 src0,
4632 };
4633 return ac_build_intrinsic(ctx, intr, type, params, 1,
4634 AC_FUNC_ATTR_READNONE);
4635 }
4636 LLVMValueRef
4637 ac_build_frexp_mant(struct ac_llvm_context *ctx, LLVMValueRef src0,
4638 unsigned bitsize)
4639 {
4640 LLVMTypeRef type;
4641 char *intr;
4642
4643 if (bitsize == 16) {
4644 intr = "llvm.amdgcn.frexp.mant.f16";
4645 type = ctx->f16;
4646 } else if (bitsize == 32) {
4647 intr = "llvm.amdgcn.frexp.mant.f32";
4648 type = ctx->f32;
4649 } else {
4650 intr = "llvm.amdgcn.frexp.mant.f64";
4651 type = ctx->f64;
4652 }
4653
4654 LLVMValueRef params[] = {
4655 src0,
4656 };
4657 return ac_build_intrinsic(ctx, intr, type, params, 1,
4658 AC_FUNC_ATTR_READNONE);
4659 }
4660
4661 LLVMValueRef
4662 ac_build_canonicalize(struct ac_llvm_context *ctx, LLVMValueRef src0,
4663 unsigned bitsize)
4664 {
4665 LLVMTypeRef type;
4666 char *intr;
4667
4668 if (bitsize == 16) {
4669 intr = "llvm.canonicalize.f16";
4670 type = ctx->f16;
4671 } else if (bitsize == 32) {
4672 intr = "llvm.canonicalize.f32";
4673 type = ctx->f32;
4674 } else {
4675 intr = "llvm.canonicalize.f64";
4676 type = ctx->f64;
4677 }
4678
4679 LLVMValueRef params[] = {
4680 src0,
4681 };
4682 return ac_build_intrinsic(ctx, intr, type, params, 1,
4683 AC_FUNC_ATTR_READNONE);
4684 }
4685
4686 /*
4687 * this takes an I,J coordinate pair,
4688 * and works out the X and Y derivatives.
4689 * it returns DDX(I), DDX(J), DDY(I), DDY(J).
4690 */
4691 LLVMValueRef
4692 ac_build_ddxy_interp(struct ac_llvm_context *ctx, LLVMValueRef interp_ij)
4693 {
4694 LLVMValueRef result[4], a;
4695 unsigned i;
4696
4697 for (i = 0; i < 2; i++) {
4698 a = LLVMBuildExtractElement(ctx->builder, interp_ij,
4699 LLVMConstInt(ctx->i32, i, false), "");
4700 result[i] = ac_build_ddxy(ctx, AC_TID_MASK_TOP_LEFT, 1, a);
4701 result[2+i] = ac_build_ddxy(ctx, AC_TID_MASK_TOP_LEFT, 2, a);
4702 }
4703 return ac_build_gather_values(ctx, result, 4);
4704 }
4705
4706 LLVMValueRef
4707 ac_build_load_helper_invocation(struct ac_llvm_context *ctx)
4708 {
4709 LLVMValueRef result = ac_build_intrinsic(ctx, "llvm.amdgcn.ps.live",
4710 ctx->i1, NULL, 0,
4711 AC_FUNC_ATTR_READNONE);
4712 result = LLVMBuildNot(ctx->builder, result, "");
4713 return LLVMBuildSExt(ctx->builder, result, ctx->i32, "");
4714 }
4715
4716 LLVMValueRef
4717 ac_build_is_helper_invocation(struct ac_llvm_context *ctx)
4718 {
4719 if (!ctx->postponed_kill)
4720 return ac_build_load_helper_invocation(ctx);
4721
4722 /* !(exact && postponed) */
4723 LLVMValueRef exact = ac_build_intrinsic(ctx, "llvm.amdgcn.ps.live",
4724 ctx->i1, NULL, 0,
4725 AC_FUNC_ATTR_READNONE);
4726
4727 LLVMValueRef postponed = LLVMBuildLoad(ctx->builder, ctx->postponed_kill, "");
4728 LLVMValueRef result = LLVMBuildAnd(ctx->builder, exact, postponed, "");
4729
4730 return LLVMBuildSelect(ctx->builder, result, ctx->i32_0,
4731 LLVMConstInt(ctx->i32, 0xFFFFFFFF, false), "");
4732 }
4733
4734 LLVMValueRef ac_build_call(struct ac_llvm_context *ctx, LLVMValueRef func,
4735 LLVMValueRef *args, unsigned num_args)
4736 {
4737 LLVMValueRef ret = LLVMBuildCall(ctx->builder, func, args, num_args, "");
4738 LLVMSetInstructionCallConv(ret, LLVMGetFunctionCallConv(func));
4739 return ret;
4740 }
4741
4742 void
4743 ac_export_mrt_z(struct ac_llvm_context *ctx, LLVMValueRef depth,
4744 LLVMValueRef stencil, LLVMValueRef samplemask,
4745 struct ac_export_args *args)
4746 {
4747 unsigned mask = 0;
4748 unsigned format = ac_get_spi_shader_z_format(depth != NULL,
4749 stencil != NULL,
4750 samplemask != NULL);
4751
4752 assert(depth || stencil || samplemask);
4753
4754 memset(args, 0, sizeof(*args));
4755
4756 args->valid_mask = 1; /* whether the EXEC mask is valid */
4757 args->done = 1; /* DONE bit */
4758
4759 /* Specify the target we are exporting */
4760 args->target = V_008DFC_SQ_EXP_MRTZ;
4761
4762 args->compr = 0; /* COMP flag */
4763 args->out[0] = LLVMGetUndef(ctx->f32); /* R, depth */
4764 args->out[1] = LLVMGetUndef(ctx->f32); /* G, stencil test val[0:7], stencil op val[8:15] */
4765 args->out[2] = LLVMGetUndef(ctx->f32); /* B, sample mask */
4766 args->out[3] = LLVMGetUndef(ctx->f32); /* A, alpha to mask */
4767
4768 if (format == V_028710_SPI_SHADER_UINT16_ABGR) {
4769 assert(!depth);
4770 args->compr = 1; /* COMPR flag */
4771
4772 if (stencil) {
4773 /* Stencil should be in X[23:16]. */
4774 stencil = ac_to_integer(ctx, stencil);
4775 stencil = LLVMBuildShl(ctx->builder, stencil,
4776 LLVMConstInt(ctx->i32, 16, 0), "");
4777 args->out[0] = ac_to_float(ctx, stencil);
4778 mask |= 0x3;
4779 }
4780 if (samplemask) {
4781 /* SampleMask should be in Y[15:0]. */
4782 args->out[1] = samplemask;
4783 mask |= 0xc;
4784 }
4785 } else {
4786 if (depth) {
4787 args->out[0] = depth;
4788 mask |= 0x1;
4789 }
4790 if (stencil) {
4791 args->out[1] = stencil;
4792 mask |= 0x2;
4793 }
4794 if (samplemask) {
4795 args->out[2] = samplemask;
4796 mask |= 0x4;
4797 }
4798 }
4799
4800 /* GFX6 (except OLAND and HAINAN) has a bug that it only looks
4801 * at the X writemask component. */
4802 if (ctx->chip_class == GFX6 &&
4803 ctx->family != CHIP_OLAND &&
4804 ctx->family != CHIP_HAINAN)
4805 mask |= 0x1;
4806
4807 /* Specify which components to enable */
4808 args->enabled_channels = mask;
4809 }
4810
4811 /* Send GS Alloc Req message from the first wave of the group to SPI.
4812 * Message payload is:
4813 * - bits 0..10: vertices in group
4814 * - bits 12..22: primitives in group
4815 */
4816 void ac_build_sendmsg_gs_alloc_req(struct ac_llvm_context *ctx, LLVMValueRef wave_id,
4817 LLVMValueRef vtx_cnt, LLVMValueRef prim_cnt)
4818 {
4819 LLVMBuilderRef builder = ctx->builder;
4820 LLVMValueRef tmp;
4821 bool export_dummy_prim = false;
4822
4823 /* HW workaround for a GPU hang with 100% culling.
4824 * We always have to export at least 1 primitive.
4825 * Export a degenerate triangle using vertex 0 for all 3 vertices.
4826 */
4827 if (prim_cnt == ctx->i32_0 && ctx->chip_class == GFX10) {
4828 assert(vtx_cnt == ctx->i32_0);
4829 prim_cnt = ctx->i32_1;
4830 vtx_cnt = ctx->i32_1;
4831 export_dummy_prim = true;
4832 }
4833
4834 ac_build_ifcc(ctx, LLVMBuildICmp(builder, LLVMIntEQ, wave_id, ctx->i32_0, ""), 5020);
4835
4836 tmp = LLVMBuildShl(builder, prim_cnt, LLVMConstInt(ctx->i32, 12, false),"");
4837 tmp = LLVMBuildOr(builder, tmp, vtx_cnt, "");
4838 ac_build_sendmsg(ctx, AC_SENDMSG_GS_ALLOC_REQ, tmp);
4839
4840 if (export_dummy_prim) {
4841 struct ac_ngg_prim prim = {};
4842 /* The vertex indices are 0,0,0. */
4843 prim.passthrough = ctx->i32_0;
4844
4845 struct ac_export_args pos = {};
4846 pos.out[0] = pos.out[1] = pos.out[2] = pos.out[3] = ctx->f32_0;
4847 pos.target = V_008DFC_SQ_EXP_POS;
4848 pos.enabled_channels = 0xf;
4849 pos.done = true;
4850
4851 ac_build_ifcc(ctx, LLVMBuildICmp(builder, LLVMIntEQ, ac_get_thread_id(ctx),
4852 ctx->i32_0, ""), 5021);
4853 ac_build_export_prim(ctx, &prim);
4854 ac_build_export(ctx, &pos);
4855 ac_build_endif(ctx, 5021);
4856 }
4857
4858 ac_build_endif(ctx, 5020);
4859 }
4860
4861 LLVMValueRef ac_pack_prim_export(struct ac_llvm_context *ctx,
4862 const struct ac_ngg_prim *prim)
4863 {
4864 /* The prim export format is:
4865 * - bits 0..8: index 0
4866 * - bit 9: edge flag 0
4867 * - bits 10..18: index 1
4868 * - bit 19: edge flag 1
4869 * - bits 20..28: index 2
4870 * - bit 29: edge flag 2
4871 * - bit 31: null primitive (skip)
4872 */
4873 LLVMBuilderRef builder = ctx->builder;
4874 LLVMValueRef tmp = LLVMBuildZExt(builder, prim->isnull, ctx->i32, "");
4875 LLVMValueRef result = LLVMBuildShl(builder, tmp, LLVMConstInt(ctx->i32, 31, false), "");
4876
4877 for (unsigned i = 0; i < prim->num_vertices; ++i) {
4878 tmp = LLVMBuildShl(builder, prim->index[i],
4879 LLVMConstInt(ctx->i32, 10 * i, false), "");
4880 result = LLVMBuildOr(builder, result, tmp, "");
4881 tmp = LLVMBuildZExt(builder, prim->edgeflag[i], ctx->i32, "");
4882 tmp = LLVMBuildShl(builder, tmp,
4883 LLVMConstInt(ctx->i32, 10 * i + 9, false), "");
4884 result = LLVMBuildOr(builder, result, tmp, "");
4885 }
4886 return result;
4887 }
4888
4889 void ac_build_export_prim(struct ac_llvm_context *ctx,
4890 const struct ac_ngg_prim *prim)
4891 {
4892 struct ac_export_args args;
4893
4894 if (prim->passthrough) {
4895 args.out[0] = prim->passthrough;
4896 } else {
4897 args.out[0] = ac_pack_prim_export(ctx, prim);
4898 }
4899
4900 args.out[0] = LLVMBuildBitCast(ctx->builder, args.out[0], ctx->f32, "");
4901 args.out[1] = LLVMGetUndef(ctx->f32);
4902 args.out[2] = LLVMGetUndef(ctx->f32);
4903 args.out[3] = LLVMGetUndef(ctx->f32);
4904
4905 args.target = V_008DFC_SQ_EXP_PRIM;
4906 args.enabled_channels = 1;
4907 args.done = true;
4908 args.valid_mask = false;
4909 args.compr = false;
4910
4911 ac_build_export(ctx, &args);
4912 }
4913
4914 static LLVMTypeRef
4915 arg_llvm_type(enum ac_arg_type type, unsigned size, struct ac_llvm_context *ctx)
4916 {
4917 if (type == AC_ARG_FLOAT) {
4918 return size == 1 ? ctx->f32 : LLVMVectorType(ctx->f32, size);
4919 } else if (type == AC_ARG_INT) {
4920 return size == 1 ? ctx->i32 : LLVMVectorType(ctx->i32, size);
4921 } else {
4922 LLVMTypeRef ptr_type;
4923 switch (type) {
4924 case AC_ARG_CONST_PTR:
4925 ptr_type = ctx->i8;
4926 break;
4927 case AC_ARG_CONST_FLOAT_PTR:
4928 ptr_type = ctx->f32;
4929 break;
4930 case AC_ARG_CONST_PTR_PTR:
4931 ptr_type = ac_array_in_const32_addr_space(ctx->i8);
4932 break;
4933 case AC_ARG_CONST_DESC_PTR:
4934 ptr_type = ctx->v4i32;
4935 break;
4936 case AC_ARG_CONST_IMAGE_PTR:
4937 ptr_type = ctx->v8i32;
4938 break;
4939 default:
4940 unreachable("unknown arg type");
4941 }
4942 if (size == 1) {
4943 return ac_array_in_const32_addr_space(ptr_type);
4944 } else {
4945 assert(size == 2);
4946 return ac_array_in_const_addr_space(ptr_type);
4947 }
4948 }
4949 }
4950
4951 LLVMValueRef
4952 ac_build_main(const struct ac_shader_args *args,
4953 struct ac_llvm_context *ctx,
4954 enum ac_llvm_calling_convention convention,
4955 const char *name, LLVMTypeRef ret_type,
4956 LLVMModuleRef module)
4957 {
4958 LLVMTypeRef arg_types[AC_MAX_ARGS];
4959
4960 for (unsigned i = 0; i < args->arg_count; i++) {
4961 arg_types[i] = arg_llvm_type(args->args[i].type,
4962 args->args[i].size, ctx);
4963 }
4964
4965 LLVMTypeRef main_function_type =
4966 LLVMFunctionType(ret_type, arg_types, args->arg_count, 0);
4967
4968 LLVMValueRef main_function =
4969 LLVMAddFunction(module, name, main_function_type);
4970 LLVMBasicBlockRef main_function_body =
4971 LLVMAppendBasicBlockInContext(ctx->context, main_function, "main_body");
4972 LLVMPositionBuilderAtEnd(ctx->builder, main_function_body);
4973
4974 LLVMSetFunctionCallConv(main_function, convention);
4975 for (unsigned i = 0; i < args->arg_count; ++i) {
4976 LLVMValueRef P = LLVMGetParam(main_function, i);
4977
4978 if (args->args[i].file != AC_ARG_SGPR)
4979 continue;
4980
4981 ac_add_function_attr(ctx->context, main_function, i + 1, AC_FUNC_ATTR_INREG);
4982
4983 if (LLVMGetTypeKind(LLVMTypeOf(P)) == LLVMPointerTypeKind) {
4984 ac_add_function_attr(ctx->context, main_function, i + 1, AC_FUNC_ATTR_NOALIAS);
4985 ac_add_attr_dereferenceable(P, UINT64_MAX);
4986 }
4987 }
4988
4989 ctx->main_function = main_function;
4990
4991 if (LLVM_VERSION_MAJOR >= 11) {
4992 /* Enable denormals for FP16 and FP64: */
4993 LLVMAddTargetDependentFunctionAttr(main_function, "denormal-fp-math",
4994 "ieee,ieee");
4995 /* Disable denormals for FP32: */
4996 LLVMAddTargetDependentFunctionAttr(main_function, "denormal-fp-math-f32",
4997 "preserve-sign,preserve-sign");
4998 }
4999 return main_function;
5000 }
5001
5002 void ac_build_s_endpgm(struct ac_llvm_context *ctx)
5003 {
5004 LLVMTypeRef calltype = LLVMFunctionType(ctx->voidt, NULL, 0, false);
5005 LLVMValueRef code = LLVMConstInlineAsm(calltype, "s_endpgm", "", true, false);
5006 LLVMBuildCall(ctx->builder, code, NULL, 0, "");
5007 }
5008
5009 LLVMValueRef ac_prefix_bitcount(struct ac_llvm_context *ctx,
5010 LLVMValueRef mask, LLVMValueRef index)
5011 {
5012 LLVMBuilderRef builder = ctx->builder;
5013 LLVMTypeRef type = LLVMTypeOf(mask);
5014
5015 LLVMValueRef bit = LLVMBuildShl(builder, LLVMConstInt(type, 1, 0),
5016 LLVMBuildZExt(builder, index, type, ""), "");
5017 LLVMValueRef prefix_bits = LLVMBuildSub(builder, bit, LLVMConstInt(type, 1, 0), "");
5018 LLVMValueRef prefix_mask = LLVMBuildAnd(builder, mask, prefix_bits, "");
5019 return ac_build_bit_count(ctx, prefix_mask);
5020 }
5021
5022 /* Compute the prefix sum of the "mask" bit array with 128 elements (bits). */
5023 LLVMValueRef ac_prefix_bitcount_2x64(struct ac_llvm_context *ctx,
5024 LLVMValueRef mask[2], LLVMValueRef index)
5025 {
5026 LLVMBuilderRef builder = ctx->builder;
5027 #if 0
5028 /* Reference version using i128. */
5029 LLVMValueRef input_mask =
5030 LLVMBuildBitCast(builder, ac_build_gather_values(ctx, mask, 2), ctx->i128, "");
5031
5032 return ac_prefix_bitcount(ctx, input_mask, index);
5033 #else
5034 /* Optimized version using 2 64-bit masks. */
5035 LLVMValueRef is_hi, is_0, c64, c128, all_bits;
5036 LLVMValueRef prefix_mask[2], shift[2], mask_bcnt0, prefix_bcnt[2];
5037
5038 /* Compute the 128-bit prefix mask. */
5039 c64 = LLVMConstInt(ctx->i32, 64, 0);
5040 c128 = LLVMConstInt(ctx->i32, 128, 0);
5041 all_bits = LLVMConstInt(ctx->i64, UINT64_MAX, 0);
5042 /* The first index that can have non-zero high bits in the prefix mask is 65. */
5043 is_hi = LLVMBuildICmp(builder, LLVMIntUGT, index, c64, "");
5044 is_0 = LLVMBuildICmp(builder, LLVMIntEQ, index, ctx->i32_0, "");
5045 mask_bcnt0 = ac_build_bit_count(ctx, mask[0]);
5046
5047 for (unsigned i = 0; i < 2; i++) {
5048 shift[i] = LLVMBuildSub(builder, i ? c128 : c64, index, "");
5049 /* For i==0, index==0, the right shift by 64 doesn't give the desired result,
5050 * so we handle it by the is_0 select.
5051 * For i==1, index==64, same story, so we handle it by the last is_hi select.
5052 * For i==0, index==64, we shift by 0, which is what we want.
5053 */
5054 prefix_mask[i] = LLVMBuildLShr(builder, all_bits,
5055 LLVMBuildZExt(builder, shift[i], ctx->i64, ""), "");
5056 prefix_mask[i] = LLVMBuildAnd(builder, mask[i], prefix_mask[i], "");
5057 prefix_bcnt[i] = ac_build_bit_count(ctx, prefix_mask[i]);
5058 }
5059
5060 prefix_bcnt[0] = LLVMBuildSelect(builder, is_0, ctx->i32_0, prefix_bcnt[0], "");
5061 prefix_bcnt[0] = LLVMBuildSelect(builder, is_hi, mask_bcnt0, prefix_bcnt[0], "");
5062 prefix_bcnt[1] = LLVMBuildSelect(builder, is_hi, prefix_bcnt[1], ctx->i32_0, "");
5063
5064 return LLVMBuildAdd(builder, prefix_bcnt[0], prefix_bcnt[1], "");
5065 #endif
5066 }
5067
5068 /**
5069 * Convert triangle strip indices to triangle indices. This is used to decompose
5070 * triangle strips into triangles.
5071 */
5072 void ac_build_triangle_strip_indices_to_triangle(struct ac_llvm_context *ctx,
5073 LLVMValueRef is_odd,
5074 LLVMValueRef flatshade_first,
5075 LLVMValueRef index[3])
5076 {
5077 LLVMBuilderRef builder = ctx->builder;
5078 LLVMValueRef out[3];
5079
5080 /* We need to change the vertex order for odd triangles to get correct
5081 * front/back facing by swapping 2 vertex indices, but we also have to
5082 * keep the provoking vertex in the same place.
5083 *
5084 * If the first vertex is provoking, swap index 1 and 2.
5085 * If the last vertex is provoking, swap index 0 and 1.
5086 */
5087 out[0] = LLVMBuildSelect(builder, flatshade_first,
5088 index[0],
5089 LLVMBuildSelect(builder, is_odd,
5090 index[1], index[0], ""), "");
5091 out[1] = LLVMBuildSelect(builder, flatshade_first,
5092 LLVMBuildSelect(builder, is_odd,
5093 index[2], index[1], ""),
5094 LLVMBuildSelect(builder, is_odd,
5095 index[0], index[1], ""), "");
5096 out[2] = LLVMBuildSelect(builder, flatshade_first,
5097 LLVMBuildSelect(builder, is_odd,
5098 index[1], index[2], ""),
5099 index[2], "");
5100 memcpy(index, out, sizeof(out));
5101 }