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