OSDN Git Service

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