Debian Codegraph @

src/panfrost/compiler/bifrost/bifrost_compile.c

raw
1 /*
2 * Copyright (C) 2020,2026 Collabora Ltd.
3 * Copyright (C) 2022 Alyssa Rosenzweig
4 * Copyright (C) 2025 Arm Ltd.
5 * SPDX-License-Identifier: MIT
6 */
7
8 #include "compiler/nir/nir_builder.h"
9 #include "panfrost/compiler/pan_compiler.h"
10 #include "util/u_qsort.h"
11
12 #include "bifrost/bi_debug.h"
13 #include "bifrost/disassemble.h"
14 #include "panfrost/lib/pan_props.h"
15 #include "valhall/disassemble.h"
16 #include "valhall/va_compiler.h"
17 #include "bi_builder.h"
18 #include "bi_quirks.h"
19 #include "bifrost_compile.h"
20 #include "bifrost_nir.h"
21 #include "compiler.h"
22
23 static void pan_stats_verbose(FILE *f, const char *prefix, bi_context *ctx,
24 const struct pan_stats *stats,
25 const struct pan_shader_info *info);
26
27
28 /* How many bytes are prefetched by the Bifrost shader core. From the final
29 * clause of the shader, this range must be valid instructions or zero. */
30 #define BIFROST_SHADER_PREFETCH 128
31
32 static bi_block *emit_cf_list(bi_context *ctx, struct exec_list *list);
33
34 static bi_index
35 bi_preload(bi_builder *b, enum bi_preload val)
36 {
37 unsigned reg = bi_preload_reg(val, b->shader->arch);
38 if (bi_is_null(b->shader->preloaded[reg])) {
39 /* Insert at the beginning of the shader */
40 bi_builder b_ = *b;
41 b_.cursor = bi_before_block(bi_start_block(&b->shader->blocks));
42
43 /* Cache the result */
44 b->shader->preloaded[reg] = bi_mov_i32(&b_, bi_register(reg));
45 }
46
47 return b->shader->preloaded[reg];
48 }
49
50 static bi_index
51 bi_coverage(bi_builder *b)
52 {
53 if (bi_is_null(b->shader->coverage))
54 b->shader->coverage = bi_preload(b, BI_PRELOAD_CUMULATIVE_COVERAGE);
55
56 return b->shader->coverage;
57 }
58
59 /*
60 * Vertex ID and Instance ID are preloaded registers. Where they are preloaded
61 * changed from Bifrost to Valhall. Provide helpers that smooth over the
62 * architectural difference.
63 */
64 static inline bi_index
65 bi_vertex_id(bi_builder *b)
66 {
67 return bi_preload(b, BI_PRELOAD_VERTEX_ID);
68 }
69
70 static inline bi_index
71 bi_instance_id(bi_builder *b)
72 {
73 return bi_preload(b, BI_PRELOAD_INSTANCE_ID);
74 }
75
76 static inline bi_index
77 bi_draw_id(bi_builder *b)
78 {
79 assert(b->shader->arch >= 9);
80 return bi_preload(b, BI_PRELOAD_DRAW_ID);
81 }
82
83 static void
84 bi_emit_jump(bi_builder *b, nir_jump_instr *instr)
85 {
86 bi_instr *branch = bi_jump(b, bi_zero());
87
88 switch (instr->type) {
89 case nir_jump_break:
90 branch->branch_target = b->shader->break_block;
91 break;
92 case nir_jump_continue:
93 branch->branch_target = b->shader->continue_block;
94 break;
95 default:
96 UNREACHABLE("Unhandled jump type");
97 }
98
99 bi_block_add_successor(b->shader->current_block, branch->branch_target);
100 b->shader->current_block->unconditional_jumps = true;
101 }
102
103 /* Builds a 64-bit hash table key for an index */
104 static uint64_t
105 bi_index_to_key(bi_index idx)
106 {
107 static_assert(sizeof(idx) <= sizeof(uint64_t), "too much padding");
108
109 uint64_t key = 0;
110 memcpy(&key, &idx, sizeof(idx));
111 return key;
112 }
113
114 /*
115 * Extract a single channel out of a vector source. We split vectors with SPLIT
116 * so we can use the split components directly, without emitting an extract.
117 * This has advantages of RA, as the split can usually be optimized away.
118 */
119 static bi_index
120 bi_extract(bi_builder *b, bi_index vec, unsigned channel)
121 {
122 bi_index *components = _mesa_hash_table_u64_search(b->shader->allocated_vec,
123 bi_index_to_key(vec));
124
125 /* No extract needed for scalars.
126 *
127 * This is a bit imprecise, but actual bugs (missing splits for vectors)
128 * should be caught by the following assertion. It is too difficult to
129 * ensure bi_extract is only called for real vectors.
130 */
131 if (components == NULL && channel == 0)
132 return vec;
133
134 assert(components != NULL && "missing bi_cache_collect()");
135 return components[channel];
136 }
137
138 static void
139 bi_cache_collect(bi_builder *b, bi_index dst, bi_index *s, unsigned n)
140 {
141 /* Lifetime of a hash table entry has to be at least as long as the table */
142 bi_index *channels = ralloc_array(b->shader, bi_index, n);
143 memcpy(channels, s, sizeof(bi_index) * n);
144
145 _mesa_hash_table_u64_insert(b->shader->allocated_vec, bi_index_to_key(dst),
146 channels);
147 }
148
149 /*
150 * Splits an n-component vector (vec) into n scalar destinations (dests) using a
151 * split pseudo-instruction.
152 *
153 * Pre-condition: dests is filled with bi_null().
154 */
155 static void
156 bi_emit_split_i32(bi_builder *b, bi_index dests[4], bi_index vec, unsigned n)
157 {
158 assert(n <= 4);
159 /* Setup the destinations */
160 for (unsigned i = 0; i < n; ++i) {
161 dests[i] = bi_temp(b->shader);
162 }
163
164 /* Emit the split */
165 if (n == 1) {
166 bi_mov_i32_to(b, dests[0], vec);
167 } else {
168 bi_instr *I = bi_split_i32_to(b, n, vec);
169
170 bi_foreach_dest(I, j)
171 I->dest[j] = dests[j];
172 }
173 }
174
175 static void
176 bi_emit_cached_split_i32(bi_builder *b, bi_index vec, unsigned n)
177 {
178 bi_index dests[4] = {bi_null(), bi_null(), bi_null(), bi_null()};
179 bi_emit_split_i32(b, dests, vec, n);
180 bi_cache_collect(b, vec, dests, n);
181 }
182
183 /*
184 * Emit and cache a split for a vector of a given bitsize. The vector may not be
185 * composed of 32-bit words, but it will be split at 32-bit word boundaries.
186 */
187 static void
188 bi_emit_cached_split(bi_builder *b, bi_index vec, unsigned bits)
189 {
190 bi_emit_cached_split_i32(b, vec, DIV_ROUND_UP(bits, 32));
191 }
192
193 static void
194 bi_split_def(bi_builder *b, nir_def *def)
195 {
196 bi_emit_cached_split(b, bi_def_index(def),
197 def->bit_size * def->num_components);
198 }
199
200 static bi_instr *
201 bi_emit_collect_to(bi_builder *b, bi_index dst, bi_index *chan, unsigned n)
202 {
203 /* Special case: COLLECT of a single value is a scalar move */
204 if (n == 1)
205 return bi_mov_i32_to(b, dst, chan[0]);
206
207 bi_instr *I = bi_collect_i32_to(b, dst, n);
208
209 bi_foreach_src(I, i)
210 I->src[i] = chan[i];
211
212 bi_cache_collect(b, dst, chan, n);
213 return I;
214 }
215
216 static bi_instr *
217 bi_collect_v2i32_to(bi_builder *b, bi_index dst, bi_index s0, bi_index s1)
218 {
219 return bi_emit_collect_to(b, dst, (bi_index[]){s0, s1}, 2);
220 }
221
222 static bi_instr *
223 bi_collect_v3i32_to(bi_builder *b, bi_index dst, bi_index s0, bi_index s1,
224 bi_index s2)
225 {
226 return bi_emit_collect_to(b, dst, (bi_index[]){s0, s1, s2}, 3);
227 }
228
229 static bi_index
230 bi_collect_v2i32(bi_builder *b, bi_index s0, bi_index s1)
231 {
232 bi_index dst = bi_temp(b->shader);
233 bi_collect_v2i32_to(b, dst, s0, s1);
234 return dst;
235 }
236
237 static inline bi_instr *
238 bi_f32_to_f16_to(bi_builder *b, bi_index dest, bi_index src)
239 {
240 /* Use V2F32_TO_V2F16 on Bifrost, FADD otherwise */
241 if (b->shader->arch < 9)
242 return bi_v2f32_to_v2f16_to(b, dest, src, src);
243
244 assert(dest.swizzle != BI_SWIZZLE_H01);
245
246 /* FADD with -0 and force convertion to F16 on Valhall and later. Negative
247 * zero is used to preserve signed zero, since 0 + -0 = 0 and -0 + -0 = -0.
248 */
249 bi_instr *I = bi_fadd_f32_to(b, dest, src, bi_imm_f32(-0.0));
250
251 /* The builder defaults to 32-bit rounding mode */
252 I->round = bi_round_mode(b->shader, 16);
253
254 return I;
255 }
256
257 static bi_index
258 bi_varying_src0_for_barycentric(bi_builder *b, nir_intrinsic_instr *intr)
259 {
260 switch (intr->intrinsic) {
261 case nir_intrinsic_load_barycentric_centroid:
262 return bi_preload(b, BI_PRELOAD_CENTROID_ID);
263 case nir_intrinsic_load_barycentric_sample:
264 return bi_preload(b, BI_PRELOAD_SAMPLE_ID);
265
266 /* Need to put the sample ID in the top 16-bits */
267 case nir_intrinsic_load_barycentric_at_sample:
268 return bi_mkvec_v2i16(b, bi_half(bi_dontcare(b), false),
269 bi_half(bi_src_index(&intr->src[0]), false));
270
271 /* Interpret as 8:8 signed fixed point positions in pixels along X and
272 * Y axes respectively, relative to top-left of pixel. In NIR, (0, 0)
273 * is the center of the pixel so we first fixup and then convert. For
274 * fp16 input:
275 *
276 * f2i16(((x, y) + (0.5, 0.5)) * 2**8) =
277 * f2i16((256 * (x, y)) + (128, 128)) =
278 * V2F16_TO_V2S16(FMA.v2f16((x, y), #256, #128))
279 *
280 * For fp32 input, that lacks enough precision for MSAA 16x, but the
281 * idea is the same. FIXME: still doesn't pass
282 */
283 case nir_intrinsic_load_barycentric_at_offset: {
284 bi_index offset = bi_src_index(&intr->src[0]);
285 bi_index f16 = bi_null();
286 unsigned sz = nir_src_bit_size(intr->src[0]);
287
288 if (sz == 16) {
289 f16 = bi_fma_v2f16(b, offset, bi_imm_f16(256.0), bi_imm_f16(128.0));
290 } else {
291 assert(sz == 32);
292 bi_index f[2];
293 for (unsigned i = 0; i < 2; ++i) {
294 f[i] =
295 bi_fadd_rscale_f32(b, bi_extract(b, offset, i), bi_imm_f32(0.5),
296 bi_imm_u32(8), BI_SPECIAL_NONE);
297 }
298
299 /* On v11+, V2F32_TO_V2F16 is gone */
300 if (b->shader->arch >= 11) {
301 bi_index tmp[2];
302
303 for (int i = 0; i < 2; i++) {
304 tmp[i] = bi_half(bi_temp(b->shader), false);
305 bi_f32_to_f16_to(b, tmp[i], f[i]);
306 }
307
308 f16 = bi_mkvec_v2i16(b, tmp[0], tmp[1]);
309 } else {
310 f16 = bi_v2f32_to_v2f16(b, f[0], f[1]);
311 }
312 }
313
314 /* v11 removed V2F16_TO_V2S16 */
315 if (b->shader->arch >= 11) {
316 bi_index f[2];
317
318 for (int i = 0; i < 2; i++) {
319 bi_index tmp = bi_half(f16, i == 1);
320 tmp = bi_f16_to_f32(b, tmp);
321 tmp = bi_f32_to_s32(b, tmp);
322 f[i] = bi_half(tmp, false);
323 }
324
325 return bi_mkvec_v2i16(b, f[0], f[1]);
326 } else {
327 return bi_v2f16_to_v2s16(b, f16);
328 }
329 }
330
331 case nir_intrinsic_load_barycentric_pixel:
332 default:
333 return b->shader->arch >= 9 ? bi_preload(b, BI_PRELOAD_CENTROID_ID)
334 : bi_dontcare(b);
335 }
336 }
337
338 static enum bi_sample
339 bi_interp_for_intrinsic(nir_intrinsic_op op)
340 {
341 switch (op) {
342 case nir_intrinsic_load_barycentric_centroid:
343 return BI_SAMPLE_CENTROID;
344 case nir_intrinsic_load_barycentric_sample:
345 case nir_intrinsic_load_barycentric_at_sample:
346 return BI_SAMPLE_SAMPLE;
347 case nir_intrinsic_load_barycentric_at_offset:
348 return BI_SAMPLE_EXPLICIT;
349 case nir_intrinsic_load_barycentric_pixel:
350 default:
351 return BI_SAMPLE_CENTER;
352 }
353 }
354
355 /* auto, 64-bit omitted */
356 static enum bi_register_format
357 bi_reg_fmt_for_nir(nir_alu_type T)
358 {
359 switch (T) {
360 case nir_type_float16:
361 return BI_REGISTER_FORMAT_F16;
362 case nir_type_float32:
363 return BI_REGISTER_FORMAT_F32;
364 case nir_type_int16:
365 return BI_REGISTER_FORMAT_S16;
366 case nir_type_uint16:
367 return BI_REGISTER_FORMAT_U16;
368 case nir_type_int32:
369 return BI_REGISTER_FORMAT_S32;
370 case nir_type_uint32:
371 return BI_REGISTER_FORMAT_U32;
372 default:
373 UNREACHABLE("Invalid type for register format");
374 }
375 }
376
377 static bool
378 va_is_valid_const_narrow_index(bi_index idx)
379 {
380 if (idx.type != BI_INDEX_CONSTANT)
381 return false;
382
383 unsigned index = pan_res_handle_get_index(idx.value);
384 unsigned table_index = pan_res_handle_get_table(idx.value);
385
386 return index < 1024 && va_is_valid_const_table(table_index);
387 }
388
389 /* Checks if the _IMM variant of an intrinsic can be used, returning in imm the
390 * immediate to be used (which applies even if _IMM can't be used) */
391
392 static bool
393 bi_is_intr_immediate(nir_intrinsic_instr *instr, unsigned *immediate,
394 unsigned max)
395 {
396 nir_src *offset = nir_get_io_offset_src(instr);
397
398 if (!nir_src_is_const(*offset))
399 return false;
400
401 *immediate = nir_intrinsic_base(instr) + nir_src_as_uint(*offset);
402 return (*immediate) < max;
403 }
404
405 static bool
406 bi_is_imm_desc_handle(bi_builder *b, nir_intrinsic_instr *instr,
407 uint32_t *immediate, unsigned max)
408 {
409 nir_src *offset = nir_get_io_offset_src(instr);
410
411 if (!nir_src_is_const(*offset))
412 return false;
413
414 if (b->shader->arch >= 9) {
415 uint32_t res_handle =
416 nir_intrinsic_base(instr) + nir_src_as_uint(*offset);
417 uint32_t table_index = pan_res_handle_get_table(res_handle);
418 uint32_t res_index = pan_res_handle_get_index(res_handle);
419
420 *immediate = res_handle;
421
422 if (!va_is_valid_const_table(table_index) || res_index >= max)
423 return false;
424
425 return true;
426 }
427
428 return bi_is_intr_immediate(instr, immediate, max);
429 }
430
431 static bool
432 bi_is_imm_var_desc_handle(bi_builder *b, nir_intrinsic_instr *instr,
433 uint32_t *immediate)
434 {
435 unsigned max = b->shader->arch >= 9 ? 256 : 20;
436
437 return bi_is_imm_desc_handle(b, instr, immediate, max);
438 }
439
440 bi_instr *bi_make_vec_to(bi_builder *b, bi_index final_dst, bi_index *src,
441 unsigned *channel, unsigned count, unsigned bitsize);
442
443 /* Bifrost's load instructions lack a component offset despite operating in
444 * terms of vec4 slots. Usually I/O vectorization avoids nonzero components,
445 * but they may be unavoidable with separate shaders in use. To solve this, we
446 * lower to a larger load and an explicit copy of the desired components. */
447
448 static void
449 bi_copy_component(bi_builder *b, nir_intrinsic_instr *instr, bi_index tmp)
450 {
451 unsigned component = nir_intrinsic_component(instr);
452 unsigned nr = instr->num_components;
453 unsigned total = nr + component;
454 unsigned bitsize = instr->def.bit_size;
455
456 assert(total <= 4 && "should be vec4");
457 bi_emit_cached_split(b, tmp, total * bitsize);
458
459 if (component == 0)
460 return;
461
462 bi_index srcs[] = {tmp, tmp, tmp};
463 unsigned channels[] = {component, component + 1, component + 2};
464
465 bi_make_vec_to(b, bi_def_index(&instr->def), srcs, channels, nr,
466 instr->def.bit_size);
467 }
468
469 static void
470 bi_emit_load_attr(bi_builder *b, nir_intrinsic_instr *instr)
471 {
472 bi_index vertex_id =
473 instr->intrinsic == nir_intrinsic_load_attribute_pan ?
474 bi_src_index(&instr->src[0]) :
475 bi_vertex_id(b);
476 bi_index instance_id =
477 instr->intrinsic == nir_intrinsic_load_attribute_pan ?
478 bi_src_index(&instr->src[1]) :
479 bi_instance_id(b);
480
481 /* Disregard the signedness of an integer, since loading 32-bits into a
482 * 32-bit register should be bit exact so should not incur any clamping.
483 *
484 * If we are reading as a u32, then it must be paired with an integer (u32 or
485 * s32) source, so use .auto32 to disregard.
486 */
487 nir_alu_type T = nir_intrinsic_dest_type(instr);
488 enum bi_register_format regfmt = BI_REGISTER_FORMAT_AUTO;
489 switch (T) {
490 case nir_type_uint32:
491 case nir_type_int32:
492 regfmt = BI_REGISTER_FORMAT_AUTO;
493 break;
494 case nir_type_float32:
495 regfmt = BI_REGISTER_FORMAT_F32;
496 break;
497 case nir_type_uint16:
498 regfmt = BI_REGISTER_FORMAT_U16;
499 break;
500 case nir_type_int16:
501 regfmt = BI_REGISTER_FORMAT_S16;
502 break;
503 case nir_type_float16:
504 regfmt = BI_REGISTER_FORMAT_F16;
505 break;
506 default:
507 assert("unsupported attribute type" && false);
508 }
509
510 nir_src *offset = nir_get_io_offset_src(instr);
511 unsigned component = nir_intrinsic_component(instr);
512 enum bi_vecsize vecsize = (instr->num_components + component - 1);
513 unsigned imm_index = 0;
514 unsigned base = nir_intrinsic_base(instr);
515 bool constant = nir_src_is_const(*offset);
516 bool immediate = bi_is_imm_desc_handle(b, instr, &imm_index, 16);
517 bi_index dest =
518 (component == 0) ? bi_def_index(&instr->def) : bi_temp(b->shader);
519 bi_instr *I;
520
521 if (immediate) {
522 I = bi_ld_attr_imm_to(b, dest, vertex_id, instance_id, regfmt,
523 vecsize, pan_res_handle_get_index(imm_index));
524
525 if (b->shader->arch >= 9)
526 I->table = va_res_fold_table_idx(pan_res_handle_get_table(base));
527 } else {
528 bi_index idx = bi_src_index(&instr->src[0]);
529
530 if (constant)
531 idx = bi_imm_u32(imm_index);
532 else if (base != 0)
533 idx = bi_iadd_u32(b, idx, bi_imm_u32(base), false);
534
535 I = bi_ld_attr_to(b, dest, vertex_id, instance_id, idx, regfmt, vecsize);
536 }
537
538 bi_copy_component(b, instr, dest);
539 }
540
541 static void
542 bi_emit_lea_attr(bi_builder *b, nir_intrinsic_instr *intr)
543 {
544 assert(intr->intrinsic == nir_intrinsic_lea_attr_pan);
545 const nir_alu_type src_fmt = nir_intrinsic_src_type(intr);
546
547 if (b->shader->arch < 9 && b->shader->idvs == BI_IDVS_POSITION) {
548 /* Bifrost position shaders have a fast path */
549 assert(nir_src_is_zero(intr->src[0]));
550 assert(src_fmt == nir_type_float32);
551 unsigned regfmt = BI_REGISTER_FORMAT_F32;
552 unsigned identity = (b->shader->arch == 6) ? 0x688 : 0;
553 unsigned snap4 = 0x5E;
554 uint32_t format = identity | (snap4 << 12) | (regfmt << 24);
555 bi_collect_v3i32_to(b, bi_def_index(&intr->def),
556 bi_preload(b, BI_PRELOAD_POS_RESULT_PTR_LO),
557 bi_preload(b, BI_PRELOAD_POS_RESULT_PTR_HI),
558 bi_imm_u32(format));
559 return;
560 }
561
562 bi_index vertex_id = bi_src_index(&intr->src[1]);
563 bi_index instance_id = bi_src_index(&intr->src[2]);
564 enum bi_register_format regfmt = bi_reg_fmt_for_nir(src_fmt);
565
566 /* Check if the index can fit in LEA_ATTR_IMM */
567 uint32_t imm_res = 0;
568 bool use_imm_form = false;
569 if (nir_src_is_const(intr->src[0])) {
570 imm_res = nir_src_as_uint(intr->src[0]);
571 use_imm_form = pan_res_handle_get_index(imm_res) < 0x10;
572 }
573
574 bi_index address = bi_def_index(&intr->def);
575 if (use_imm_form) {
576 bi_instr *I = bi_lea_attr_imm_to(b, address, vertex_id, instance_id,
577 regfmt,
578 pan_res_handle_get_index(imm_res));
579 if (b->shader->arch >= 9)
580 I->table = va_res_fold_table_idx(pan_res_handle_get_table(imm_res));
581 } else {
582 bi_index res = bi_src_index(&intr->src[0]);
583 bi_lea_attr_to(b, address, vertex_id, instance_id, res, regfmt);
584 }
585 bi_split_def(b, &intr->def);
586 }
587
588 static void
589 bi_emit_lea_buf(bi_builder *b, nir_intrinsic_instr *intr)
590 {
591 assert(intr->intrinsic == nir_intrinsic_lea_buf_pan);
592 assert(b->shader->arch >= 9);
593 bi_index index = bi_src_index(&intr->src[1]);
594
595 uint32_t imm_res;
596 bool use_imm_form = false;
597 if (nir_src_is_const(intr->src[0])) {
598 imm_res = nir_src_as_uint(intr->src[0]);
599 uint32_t table_index = pan_res_handle_get_table(imm_res);
600 uint32_t res_index = pan_res_handle_get_index(imm_res);
601 use_imm_form = va_is_valid_const_table(table_index) && res_index < 256;
602 }
603
604 bi_index address = bi_def_index(&intr->def);
605 if (use_imm_form) {
606 bi_instr *I = bi_lea_buf_imm_to(b, address, index);
607 I->table = va_res_fold_table_idx(pan_res_handle_get_table(imm_res));
608 I->index = pan_res_handle_get_index(imm_res);
609 } else {
610 bi_index res = bi_src_index(&intr->src[0]);
611 bi_lea_buf_to(b, address, index, res);
612 }
613 bi_split_def(b, &intr->def);
614 }
615
616 static void
617 bi_emit_load_var(bi_builder *b, nir_intrinsic_instr *intr)
618 {
619 assert(intr->intrinsic == nir_intrinsic_load_var_pan ||
620 intr->intrinsic == nir_intrinsic_load_var_flat_pan);
621 const bool flat = intr->intrinsic == nir_intrinsic_load_var_flat_pan;
622
623 enum bi_sample sample = BI_SAMPLE_CENTER;
624 bi_index src0 = bi_null();
625
626 const nir_alu_type dest_type = nir_intrinsic_dest_type(intr);
627 ASSERTED const nir_alu_type base_type = nir_alu_type_get_base_type(dest_type);
628 const unsigned sz = nir_alu_type_get_type_size(dest_type);
629 assert(intr->def.bit_size == sz);
630 enum bi_register_format regfmt;
631
632 if (flat) {
633 b->shader->info.bifrost->uses_flat_shading = true;
634
635 /* Flat loading with i16/u16 is not encodable */
636 assert(base_type == nir_type_float || sz == 32);
637 regfmt = bi_reg_fmt_for_nir(dest_type);
638 } else {
639 nir_intrinsic_instr *bary = nir_src_as_intrinsic(intr->src[1]);
640 sample = bi_interp_for_intrinsic(bary->intrinsic);
641 src0 = bi_varying_src0_for_barycentric(b, bary);
642
643 /* Smooth ints don't exist */
644 assert(base_type == nir_type_float);
645 regfmt = (sz == 16) ? BI_REGISTER_FORMAT_F16 : BI_REGISTER_FORMAT_F32;
646 }
647
648 const enum bi_vecsize vecsize = intr->num_components - 1;
649 bi_index dest = bi_def_index(&intr->def);
650
651 uint32_t imm_res = 0;
652 bool use_imm_form = false;
653 if (nir_src_is_const(intr->src[0])) {
654 imm_res = nir_src_as_uint(intr->src[0]);
655 if (b->shader->arch >= 9) {
656 uint32_t table_index = pan_res_handle_get_table(imm_res);
657 uint32_t res_index = pan_res_handle_get_index(imm_res);
658 use_imm_form = va_is_valid_const_table(table_index) &&
659 res_index < 256;
660 } else {
661 use_imm_form = imm_res < 20;
662 }
663 }
664
665 if (use_imm_form) {
666 bi_instr *I;
667 if (flat) {
668 I = bi_ld_var_flat_imm_to(b, dest, BI_FUNCTION_NONE, regfmt, vecsize,
669 pan_res_handle_get_index(imm_res));
670 } else {
671 I = bi_ld_var_imm_to(b, dest, src0, regfmt, sample, BI_UPDATE_STORE,
672 vecsize, pan_res_handle_get_index(imm_res));
673 }
674
675 if (b->shader->arch >= 9)
676 I->table = va_res_fold_table_idx(pan_res_handle_get_table(imm_res));
677 } else {
678 bi_index res = bi_src_index(&intr->src[0]);
679 if (flat) {
680 bi_ld_var_flat_to(b, dest, res, BI_FUNCTION_NONE, regfmt, vecsize);
681 } else {
682 bi_ld_var_to(b, dest, src0, res, regfmt, sample,
683 BI_UPDATE_STORE, vecsize);
684 }
685 }
686 bi_split_def(b, &intr->def);
687 }
688
689 static void
690 bi_emit_load_var_buf(bi_builder *b, nir_intrinsic_instr *intr)
691 {
692 assert(intr->intrinsic == nir_intrinsic_load_var_buf_pan ||
693 intr->intrinsic == nir_intrinsic_load_var_buf_flat_pan);
694
695 /* These are only available on Valhall+ */
696 assert(b->shader->arch >= 9);
697
698 const bool flat = intr->intrinsic == nir_intrinsic_load_var_buf_flat_pan;
699 const nir_alu_type src_type = nir_intrinsic_src_type(intr);
700 ASSERTED const nir_alu_type base_type = nir_alu_type_get_base_type(src_type);
701 const nir_alu_type src_sz = nir_alu_type_get_type_size(src_type);
702 const unsigned sz = intr->def.bit_size;
703 assert(src_sz == 16 || src_sz == 32);
704 assert(sz == 16 || sz == 32);
705
706 enum bi_sample sample = BI_SAMPLE_CENTER;
707 bi_index src0 = bi_null();
708
709 if (flat) {
710 /* The source is not used for flat loads but we still need to encode
711 * something.
712 */
713 src0 = bi_zero();
714
715 /* Gather info as we go */
716 b->shader->info.bifrost->uses_flat_shading = true;
717 } else {
718 nir_intrinsic_instr *bary = nir_src_as_intrinsic(intr->src[1]);
719 sample = bi_interp_for_intrinsic(bary->intrinsic);
720 src0 = bi_varying_src0_for_barycentric(b, bary);
721 }
722
723 enum bi_source_format source_format;
724 enum bi_register_format regfmt;
725 if (flat) {
726 /* conversion MUST be a noop for int varyings to work correctly */
727 assert(base_type == nir_type_float || src_sz == sz);
728 /* integer regfmt are not supported by LD_VAR_BUF, but using float
729 * src_types for integers is okay if the source_format is flat and uses
730 * the same bit size. The conversion is a no-op. */
731 regfmt = (sz == 16) ? BI_REGISTER_FORMAT_F16 : BI_REGISTER_FORMAT_F32;
732 source_format = (src_sz == 16) ? BI_SOURCE_FORMAT_FLAT16 :
733 BI_SOURCE_FORMAT_FLAT32;
734 } else {
735 /* Smooth ints don't exist */
736 assert(base_type == nir_type_float);
737 regfmt = (sz == 16) ? BI_REGISTER_FORMAT_F16 : BI_REGISTER_FORMAT_F32;
738 source_format = (src_sz == 16) ? BI_SOURCE_FORMAT_F16 :
739 BI_SOURCE_FORMAT_F32;
740 }
741
742 const enum bi_vecsize vecsize = intr->num_components - 1;
743 bi_index dest = bi_def_index(&intr->def);
744
745 uint32_t imm_offset = 0;
746 bool use_imm_form = false;
747 if (nir_src_is_const(intr->src[0])) {
748 imm_offset = nir_src_as_uint(intr->src[0]);
749 assert(imm_offset < pan_ld_var_buf_off_size(b->shader->arch));
750
751 use_imm_form = true;
752 }
753
754 if (use_imm_form) {
755 bi_ld_var_buf_imm_to(b, sz, dest, src0, regfmt, sample, source_format,
756 BI_UPDATE_STORE, vecsize, imm_offset);
757 } else {
758 bi_index offset = bi_src_index(&intr->src[0]);
759 bi_ld_var_buf_to(b, sz, dest, src0, offset, regfmt, sample,
760 source_format, BI_UPDATE_STORE, vecsize);
761 }
762 bi_split_def(b, &intr->def);
763 }
764
765 bi_instr *
766 bi_make_vec_to(bi_builder *b, bi_index dst, bi_index *src, unsigned *channel,
767 unsigned count, unsigned bitsize)
768 {
769 assert(DIV_ROUND_UP(count * bitsize, 32) <= BI_MAX_SRCS &&
770 "unnecessarily large vector should have been lowered");
771
772 assert(count <= BI_MAX_VEC);
773 bi_index srcs[BI_MAX_VEC];
774
775 if (bitsize == 64) {
776 for (unsigned i = 0; i < count; i++) {
777 const unsigned c = channel ? channel[i] : 0;
778 srcs[i * 2 + 0] = bi_extract(b, src[i], c * 2 + 0);
779 srcs[i * 2 + 1] = bi_extract(b, src[i], c * 2 + 1);
780 }
781 return bi_emit_collect_to(b, dst, srcs, count * 2);
782 } else if (bitsize == 32) {
783 for (unsigned i = 0; i < count; i++) {
784 const unsigned c = channel ? channel[i] : 0;
785 srcs[i] = bi_extract(b, src[i], c);
786 }
787 return bi_emit_collect_to(b, dst, srcs, count);
788 } else if (bitsize == 16) {
789 for (unsigned i = 0; i < count; i++) {
790 const unsigned c = channel ? channel[i] : 0;
791 srcs[i] = bi_half(bi_extract(b, src[i], c >> 1), c & 1);
792 }
793
794 for (unsigned i = count; i < align(count, 2); i++)
795 srcs[i] = bi_imm_u16(0);
796
797 for (unsigned i = 0; i < count; i += 2)
798 srcs[i / 2] = bi_mkvec_v2i16(b, srcs[i], srcs[i + 1]);
799
800 return bi_emit_collect_to(b, dst, srcs, DIV_ROUND_UP(count, 2));
801 } else if (bitsize == 8) {
802 for (unsigned i = 0; i < count; i++) {
803 const unsigned c = channel ? channel[i] : 0;
804 srcs[i] = bi_byte(bi_extract(b, src[i], c >> 2), c & 3);
805 }
806
807 for (unsigned i = count; i < align(count, 4); i++)
808 srcs[i] = bi_imm_u8(0);
809
810 for (unsigned i = 0; i < count; i += 4) {
811 srcs[i / 4] = bi_mkvec_v4i8(b, srcs[i], srcs[i + 1],
812 srcs[i + 2], srcs[i + 3]);
813 }
814
815 return bi_emit_collect_to(b, dst, srcs, DIV_ROUND_UP(count, 4));
816 } else {
817 UNREACHABLE("Unsupported bit size");
818 }
819 }
820
821 static inline bi_instr *
822 bi_load_ubo_to(bi_builder *b, unsigned bitsize, bi_index dest0, bi_index src0,
823 bi_index src1)
824 {
825 bi_instr *I;
826
827 if (b->shader->arch >= 9) {
828 I = bi_ld_pka_to(b, bitsize, dest0, src0, src1);
829 I->seg = BI_SEG_UBO;
830 } else {
831 I = bi_load_to(b, bitsize, dest0, src0, src1, BI_SEG_UBO, 0);
832 }
833
834 bi_emit_cached_split(b, dest0, bitsize);
835 return I;
836 }
837
838 static void
839 bi_load_sample_id_to(bi_builder *b, bi_index dst)
840 {
841 /* r61[16:23] contains the sampleID, mask it out. Upper bits
842 * seem to read garbage (despite being architecturally defined
843 * as zero), so use a 5-bit mask instead of 8-bits */
844
845 bi_rshift_and_i32_to(b, dst, bi_preload(b, BI_PRELOAD_SAMPLE_ID),
846 bi_imm_u32(0x1f), bi_imm_u8(16), false);
847 }
848
849 static bi_index
850 bi_load_sample_id(bi_builder *b)
851 {
852 bi_index sample_id = bi_temp(b->shader);
853 bi_load_sample_id_to(b, sample_id);
854 return sample_id;
855 }
856
857 static bi_index
858 bi_pixel_indices(bi_builder *b, unsigned rt, unsigned sample)
859 {
860 /* We want to load the current pixel. */
861 struct bifrost_pixel_indices pix = {
862 .y = BIFROST_CURRENT_PIXEL,
863 .rt = rt,
864 .sample = sample,
865 };
866
867 uint32_t indices_u32 = 0;
868 memcpy(&indices_u32, &pix, sizeof(indices_u32));
869 return bi_imm_u32(indices_u32);
870 }
871
872 /* Source color is passed through r0-r3, or r4-r7 for the second source when
873 * dual-source blending. Preload the corresponding vector.
874 */
875 static void
876 bi_emit_load_blend_input(bi_builder *b, nir_intrinsic_instr *instr)
877 {
878 nir_io_semantics sem = nir_intrinsic_io_semantics(instr);
879 unsigned size = nir_alu_type_get_type_size(nir_intrinsic_dest_type(instr));
880 assert(size == 16 || size == 32);
881
882 bi_index srcs[4];
883 switch (sem.dual_source_blend_index) {
884 case 0:
885 srcs[0] = bi_preload(b, BI_PRELOAD_BLEND_SRC0_C0);
886 srcs[1] = bi_preload(b, BI_PRELOAD_BLEND_SRC0_C1);
887 srcs[2] = bi_preload(b, BI_PRELOAD_BLEND_SRC0_C2);
888 srcs[3] = bi_preload(b, BI_PRELOAD_BLEND_SRC0_C3);
889 break;
890 case 1:
891 srcs[0] = bi_preload(b, BI_PRELOAD_BLEND_SRC1_C0);
892 srcs[1] = bi_preload(b, BI_PRELOAD_BLEND_SRC1_C1);
893 srcs[2] = bi_preload(b, BI_PRELOAD_BLEND_SRC1_C2);
894 srcs[3] = bi_preload(b, BI_PRELOAD_BLEND_SRC1_C3);
895 break;
896 }
897
898 bi_emit_collect_to(b, bi_def_index(&instr->def), srcs, size == 32 ? 4 : 2);
899 }
900
901 static bi_index
902 bi_src_color_vec4(bi_builder *b, nir_src *src, nir_alu_type T)
903 {
904 unsigned num_components = nir_src_num_components(*src);
905 bi_index base = bi_src_index(src);
906
907 /* short-circuit the common case */
908 if (num_components == 4)
909 return base;
910
911 unsigned size = nir_alu_type_get_type_size(T);
912 assert(size == 16 || size == 32);
913
914 bi_index src_vals[4];
915
916 unsigned i;
917 for (i = 0; i < num_components; i++)
918 src_vals[i] = bi_extract(b, base, i);
919
920 for (; i < 3; i++)
921 src_vals[i] = (size == 16) ? bi_imm_f16(0.0) : bi_imm_f32(0.0);
922 src_vals[3] = (size == 16) ? bi_imm_f16(1.0) : bi_imm_f32(1.0);
923 bi_index temp = bi_temp(b->shader);
924 bi_make_vec_to(b, temp, src_vals, NULL, 4, size);
925 return temp;
926 }
927
928 static unsigned
929 bi_is_zs(unsigned location)
930 {
931 return location == FRAG_RESULT_DEPTH || location == FRAG_RESULT_STENCIL;
932 }
933
934 static void
935 bi_emit_load_ubo(bi_builder *b, nir_intrinsic_instr *instr)
936 {
937 nir_src *offset = nir_get_io_offset_src(instr);
938
939 bool offset_is_const = nir_src_is_const(*offset);
940 bi_index dyn_offset = bi_src_index(offset);
941 uint32_t const_offset = offset_is_const ? nir_src_as_uint(*offset) : 0;
942
943 bi_load_ubo_to(b, instr->num_components * instr->def.bit_size,
944 bi_def_index(&instr->def),
945 offset_is_const ? bi_imm_u32(const_offset) : dyn_offset,
946 bi_src_index(&instr->src[0]));
947 }
948
949 static void
950 bi_emit_load_push_constant(bi_builder *b, nir_intrinsic_instr *instr)
951 {
952 assert(!b->shader->inputs->pushable_ubos && "can't mix push constant forms");
953
954 nir_src *offset = &instr->src[0];
955 assert(!nir_intrinsic_base(instr) && "base must be zero");
956 assert(!nir_intrinsic_range(instr) && "range must be zero");
957 assert(nir_src_is_const(*offset) && "no indirect push constants");
958 uint32_t base = nir_src_as_uint(*offset);
959 assert((base & 3) == 0 && "unaligned push constants");
960
961 unsigned bits = instr->def.bit_size * instr->def.num_components;
962
963 unsigned n = DIV_ROUND_UP(bits, 32);
964 assert(n <= 4);
965 bi_index channels[4] = {bi_null()};
966
967 for (unsigned i = 0; i < n; ++i) {
968 unsigned word = (base >> 2) + i;
969
970 channels[i] = bi_fau(BIR_FAU_UNIFORM | (word >> 1), word & 1);
971 }
972
973 bi_emit_collect_to(b, bi_def_index(&instr->def), channels, n);
974
975 /* Update push->count to report the highest push constant word being accessed
976 * by this shader.
977 */
978 b->shader->info.push->count =
979 MAX2((base / 4) + n, b->shader->info.push->count);
980 }
981
982 /* Split a 32/64-bit address into low and high parts. 64-bit addresses are
983 * checked to be split and cached. 64-bit address happens on `store_scratch`
984 * produced by `nir_lower_vars_to_scratch`
985 */
986
987 static void
988 bi_addr_split(bi_builder *b, nir_src *src, bi_index *addr_lo, bi_index *addr_hi)
989 {
990 bi_index addr = bi_src_index(src);
991 if (nir_src_bit_size(*src) == 32) {
992 *addr_lo = addr;
993 *addr_hi = bi_zero();
994 return;
995 }
996 bi_index *components = _mesa_hash_table_u64_search(b->shader->allocated_vec,
997 bi_index_to_key(addr));
998 if (components == NULL) {
999 bi_emit_cached_split(b, addr, 64);
1000 }
1001 *addr_lo = bi_extract(b, addr, 0);
1002 *addr_hi = bi_extract(b, addr, 1);
1003 }
1004
1005 static void
1006 bi_handle_segment(bi_builder *b, bi_index *addr_lo, bi_index *addr_hi,
1007 enum bi_seg seg, int16_t *offset)
1008 {
1009 /* Not needed on Bifrost or for global accesses */
1010 if (b->shader->arch < 9 || seg == BI_SEG_NONE)
1011 return;
1012
1013 /* There is no segment modifier on Valhall. Instead, we need to
1014 * emit the arithmetic ourselves. We do have an offset
1015 * available, which saves an instruction for constant offsets.
1016 */
1017 bool wls = (seg == BI_SEG_WLS);
1018 assert(wls || (seg == BI_SEG_TL));
1019
1020 enum bir_fau fau = wls ? BIR_FAU_WLS_PTR : BIR_FAU_TLS_PTR;
1021
1022 bi_index base_lo = bi_fau(fau, false);
1023
1024 if (offset && addr_lo->type == BI_INDEX_CONSTANT &&
1025 addr_lo->value == (int16_t)addr_lo->value) {
1026 *offset = addr_lo->value;
1027 *addr_lo = base_lo;
1028 } else {
1029 *addr_lo = bi_iadd_u32(b, base_lo, *addr_lo, false);
1030 }
1031
1032 /* Do not allow overflow for WLS or TLS */
1033 *addr_hi = bi_fau(fau, true);
1034 }
1035
1036 static void
1037 bi_emit_load(bi_builder *b, nir_intrinsic_instr *instr, enum bi_seg seg,
1038 enum va_memory_access mem_access)
1039 {
1040 int16_t offset = 0;
1041 unsigned bits = instr->num_components * instr->def.bit_size;
1042 bi_index dest = bi_def_index(&instr->def);
1043 bi_index addr_lo, addr_hi;
1044 bi_addr_split(b, &instr->src[0], &addr_lo, &addr_hi);
1045
1046 bi_handle_segment(b, &addr_lo, &addr_hi, seg, &offset);
1047
1048 bi_instr *I = bi_load_to(b, bits, dest, addr_lo, addr_hi, seg, offset);
1049 I->mem_access = mem_access;
1050 bi_emit_cached_split(b, dest, bits);
1051 }
1052
1053 static bi_instr *
1054 bi_emit_store(bi_builder *b, nir_intrinsic_instr *instr, enum bi_seg seg,
1055 enum va_memory_access mem_access)
1056 {
1057 /* Require contiguous masks, gauranteed by nir_lower_wrmasks */
1058 assert(nir_intrinsic_write_mask(instr) ==
1059 BITFIELD_MASK(instr->num_components));
1060
1061 int16_t offset = 0;
1062 bi_index addr_lo, addr_hi;
1063 bi_addr_split(b, &instr->src[1], &addr_lo, &addr_hi);
1064
1065 bi_handle_segment(b, &addr_lo, &addr_hi, seg, &offset);
1066
1067 bi_instr *I =
1068 bi_store(b, instr->num_components * nir_src_bit_size(instr->src[0]),
1069 bi_src_index(&instr->src[0]), addr_lo, addr_hi, seg, offset);
1070 I->mem_access = mem_access;
1071 return I;
1072 }
1073
1074 /* Exchanges the staging register with memory */
1075
1076 static void
1077 bi_emit_axchg_to(bi_builder *b, bi_index dst, bi_index addr, nir_src *arg,
1078 enum bi_seg seg)
1079 {
1080 assert(seg == BI_SEG_NONE || seg == BI_SEG_WLS);
1081
1082 unsigned sz = nir_src_bit_size(*arg);
1083 assert(sz == 32 || sz == 64);
1084
1085 bi_index data = bi_src_index(arg);
1086
1087 bi_index addr_hi = (seg == BI_SEG_WLS) ? bi_zero() : bi_extract(b, addr, 1);
1088
1089 if (b->shader->arch >= 9)
1090 bi_handle_segment(b, &addr, &addr_hi, seg, NULL);
1091 else if (seg == BI_SEG_WLS)
1092 addr_hi = bi_zero();
1093
1094 bi_axchg_to(b, sz, dst, data, bi_extract(b, addr, 0), addr_hi, seg);
1095 }
1096
1097 /* Exchanges the second staging register with memory if comparison with first
1098 * staging register passes */
1099
1100 static void
1101 bi_emit_acmpxchg_to(bi_builder *b, bi_index dst, bi_index addr, nir_src *arg_1,
1102 nir_src *arg_2, enum bi_seg seg)
1103 {
1104 assert(seg == BI_SEG_NONE || seg == BI_SEG_WLS);
1105
1106 /* hardware is swapped from NIR */
1107 bi_index src0 = bi_src_index(arg_2);
1108 bi_index src1 = bi_src_index(arg_1);
1109
1110 unsigned sz = nir_src_bit_size(*arg_1);
1111 assert(sz == 32 || sz == 64);
1112
1113 bi_index data_words[] = {
1114 bi_extract(b, src0, 0),
1115 sz == 32 ? bi_extract(b, src1, 0) : bi_extract(b, src0, 1),
1116
1117 /* 64-bit */
1118 bi_extract(b, src1, 0),
1119 sz == 32 ? bi_extract(b, src1, 0) : bi_extract(b, src1, 1),
1120 };
1121
1122 bi_index in = bi_temp(b->shader);
1123 bi_emit_collect_to(b, in, data_words, 2 * (sz / 32));
1124 bi_index addr_hi = (seg == BI_SEG_WLS) ? bi_zero() : bi_extract(b, addr, 1);
1125
1126 if (b->shader->arch >= 9)
1127 bi_handle_segment(b, &addr, &addr_hi, seg, NULL);
1128 else if (seg == BI_SEG_WLS)
1129 addr_hi = bi_zero();
1130
1131 bi_index out = bi_acmpxchg(b, sz, in, bi_extract(b, addr, 0), addr_hi, seg);
1132 bi_emit_cached_split(b, out, sz);
1133
1134 bi_index inout_words[] = {bi_extract(b, out, 0),
1135 sz == 64 ? bi_extract(b, out, 1) : bi_null()};
1136
1137 bi_make_vec_to(b, dst, inout_words, NULL, sz / 32, 32);
1138 }
1139
1140 static enum bi_atom_opc
1141 bi_atom_opc_for_nir(nir_atomic_op op)
1142 {
1143 /* clang-format off */
1144 switch (op) {
1145 case nir_atomic_op_iadd: return BI_ATOM_OPC_AADD;
1146 case nir_atomic_op_imin: return BI_ATOM_OPC_ASMIN;
1147 case nir_atomic_op_umin: return BI_ATOM_OPC_AUMIN;
1148 case nir_atomic_op_imax: return BI_ATOM_OPC_ASMAX;
1149 case nir_atomic_op_umax: return BI_ATOM_OPC_AUMAX;
1150 case nir_atomic_op_iand: return BI_ATOM_OPC_AAND;
1151 case nir_atomic_op_ior: return BI_ATOM_OPC_AOR;
1152 case nir_atomic_op_ixor: return BI_ATOM_OPC_AXOR;
1153 case nir_atomic_op_xchg: return BI_ATOM_OPC_AXCHG;
1154 case nir_atomic_op_cmpxchg: return BI_ATOM_OPC_AXCHG;
1155 default: UNREACHABLE("Unexpected computational atomic");
1156 }
1157 /* clang-format on */
1158 }
1159
1160 /* Optimized unary atomics are available with an implied #1 argument */
1161
1162 static bool
1163 bi_promote_atom_c1(enum bi_atom_opc op, bi_index arg, enum bi_atom_opc *out)
1164 {
1165 /* Check we have a compatible constant */
1166 if (arg.type != BI_INDEX_CONSTANT)
1167 return false;
1168
1169 if (!(arg.value == 1 || (arg.value == -1 && op == BI_ATOM_OPC_AADD)))
1170 return false;
1171
1172 /* Check for a compatible operation */
1173 switch (op) {
1174 case BI_ATOM_OPC_AADD:
1175 *out = (arg.value == 1) ? BI_ATOM_OPC_AINC : BI_ATOM_OPC_ADEC;
1176 return true;
1177 case BI_ATOM_OPC_ASMAX:
1178 *out = BI_ATOM_OPC_ASMAX1;
1179 return true;
1180 case BI_ATOM_OPC_AUMAX:
1181 *out = BI_ATOM_OPC_AUMAX1;
1182 return true;
1183 case BI_ATOM_OPC_AOR:
1184 *out = BI_ATOM_OPC_AOR1;
1185 return true;
1186 default:
1187 return false;
1188 }
1189 }
1190
1191 /*
1192 * Coordinates are 16-bit integers in Bifrost but 32-bit in NIR. We need to
1193 * translate between these forms (with MKVEC.v2i16).
1194 *
1195 * Aditionally on Valhall, cube maps in the attribute pipe are treated as 2D
1196 * arrays. For uniform handling, we also treat 3D textures like 2D arrays.
1197 *
1198 * Our indexing needs to reflects this. Since Valhall and Bifrost are quite
1199 * different, we provide separate functions for these.
1200 */
1201 static bi_index
1202 bi_emit_image_coord(bi_builder *b, bi_index coord, unsigned src_idx,
1203 unsigned coord_comps, bool is_array, bool is_msaa)
1204 {
1205 assert(coord_comps > 0 && coord_comps <= 3);
1206
1207 /* MSAA load store should have been lowered */
1208 assert(!is_msaa);
1209 if (src_idx == 0) {
1210 if (coord_comps == 1 || (coord_comps == 2 && is_array))
1211 return bi_extract(b, coord, 0);
1212 else
1213 return bi_mkvec_v2i16(b, bi_half(bi_extract(b, coord, 0), false),
1214 bi_half(bi_extract(b, coord, 1), false));
1215 } else {
1216 if (coord_comps == 3)
1217 return bi_extract(b, coord, 2);
1218 else if (coord_comps == 2 && is_array)
1219 return bi_extract(b, coord, 1);
1220 else
1221 return bi_zero();
1222 }
1223 }
1224
1225 static bi_index
1226 va_emit_image_coord(bi_builder *b, bi_index coord, bi_index sample_index,
1227 unsigned src_idx, unsigned coord_comps, bool is_array,
1228 bool is_msaa)
1229 {
1230 assert(coord_comps > 0 && coord_comps <= 3);
1231 if (src_idx == 0) {
1232 if (coord_comps == 1 || (coord_comps == 2 && is_array))
1233 return bi_extract(b, coord, 0);
1234 else
1235 return bi_mkvec_v2i16(b, bi_half(bi_extract(b, coord, 0), false),
1236 bi_half(bi_extract(b, coord, 1), false));
1237 } else if (is_msaa) {
1238 bi_index array_idx = bi_extract(b, sample_index, 0);
1239 if (coord_comps == 3)
1240 return bi_mkvec_v2i16(b, bi_half(array_idx, false),
1241 bi_half(bi_extract(b, coord, 2), false));
1242 else if (coord_comps == 2)
1243 return array_idx;
1244 } else if (coord_comps == 3 && is_array) {
1245 return bi_mkvec_v2i16(b, bi_imm_u16(0),
1246 bi_half(bi_extract(b, coord, 2), false));
1247 } else if (coord_comps == 3 && !is_array) {
1248 return bi_mkvec_v2i16(b, bi_half(bi_extract(b, coord, 2), false),
1249 bi_imm_u16(0));
1250 } else if (coord_comps == 2 && is_array) {
1251 return bi_mkvec_v2i16(b, bi_imm_u16(0),
1252 bi_half(bi_extract(b, coord, 1), false));
1253 }
1254 return bi_zero();
1255 }
1256
1257 static void
1258 bi_emit_image_load(bi_builder *b, nir_intrinsic_instr *instr)
1259 {
1260 enum glsl_sampler_dim dim = nir_intrinsic_image_dim(instr);
1261 assert((dim != GLSL_SAMPLER_DIM_BUF) &&
1262 "Texel buffers should already have been lowered");
1263 unsigned coord_comps = nir_image_intrinsic_coord_components(instr);
1264 bool array =
1265 nir_intrinsic_image_array(instr) || dim == GLSL_SAMPLER_DIM_CUBE;
1266
1267 bi_index coords = bi_src_index(&instr->src[1]);
1268 bi_index indexvar = bi_src_index(&instr->src[2]);
1269 bi_index xy, zw;
1270 bool is_ms = (dim == GLSL_SAMPLER_DIM_MS);
1271 if (b->shader->arch < 9) {
1272 xy = bi_emit_image_coord(b, coords, 0, coord_comps, array, is_ms);
1273 zw = bi_emit_image_coord(b, coords, 1, coord_comps, array, is_ms);
1274 } else {
1275 xy =
1276 va_emit_image_coord(b, coords, indexvar, 0, coord_comps, array, is_ms);
1277 zw =
1278 va_emit_image_coord(b, coords, indexvar, 1, coord_comps, array, is_ms);
1279 }
1280 bi_index dest = bi_def_index(&instr->def);
1281 enum bi_register_format regfmt =
1282 bi_reg_fmt_for_nir(nir_intrinsic_dest_type(instr));
1283 enum bi_vecsize vecsize = instr->num_components - 1;
1284
1285 if (b->shader->arch >= 9 && nir_src_is_const(instr->src[0])) {
1286 const unsigned raw_value = nir_src_as_uint(instr->src[0]);
1287 const unsigned table_index = pan_res_handle_get_table(raw_value);
1288 const unsigned texture_index = pan_res_handle_get_index(raw_value);
1289
1290 if (texture_index < 16 && va_is_valid_const_table(table_index)) {
1291 bi_instr *I =
1292 bi_ld_tex_imm_to(b, dest, xy, zw, regfmt, vecsize, texture_index);
1293 I->table = va_res_fold_table_idx(table_index);
1294 } else {
1295 bi_ld_tex_to(b, dest, xy, zw, bi_src_index(&instr->src[0]), regfmt,
1296 vecsize);
1297 }
1298 } else if (b->shader->arch >= 9) {
1299 bi_ld_tex_to(b, dest, xy, zw, bi_src_index(&instr->src[0]), regfmt,
1300 vecsize);
1301 } else {
1302 bi_ld_attr_tex_to(b, dest, xy, zw, bi_src_index(&instr->src[0]), regfmt,
1303 vecsize);
1304 }
1305
1306 bi_split_def(b, &instr->def);
1307 }
1308
1309 static void
1310 bi_emit_lea_image_to(bi_builder *b, bi_index dest, nir_intrinsic_instr *instr)
1311 {
1312 enum glsl_sampler_dim dim = nir_intrinsic_image_dim(instr);
1313 assert((dim != GLSL_SAMPLER_DIM_BUF) &&
1314 "Texel buffers should already have been lowered");
1315 bool array =
1316 nir_intrinsic_image_array(instr) || dim == GLSL_SAMPLER_DIM_CUBE;
1317 unsigned coord_comps = nir_image_intrinsic_coord_components(instr);
1318
1319 enum bi_register_format type =
1320 (instr->intrinsic == nir_intrinsic_image_store)
1321 ? bi_reg_fmt_for_nir(nir_intrinsic_src_type(instr))
1322 : BI_REGISTER_FORMAT_AUTO;
1323
1324 bi_index coords = bi_src_index(&instr->src[1]);
1325 bi_index indices = bi_src_index(&instr->src[2]);
1326 bi_index xy, zw;
1327 bool is_ms = dim == GLSL_SAMPLER_DIM_MS;
1328 if (b->shader->arch < 9) {
1329 xy = bi_emit_image_coord(b, coords, 0, coord_comps, array, is_ms);
1330 zw = bi_emit_image_coord(b, coords, 1, coord_comps, array, is_ms);
1331 } else {
1332 xy =
1333 va_emit_image_coord(b, coords, indices, 0, coord_comps, array, is_ms);
1334 zw =
1335 va_emit_image_coord(b, coords, indices, 1, coord_comps, array, is_ms);
1336 }
1337
1338 if (b->shader->arch >= 9 && nir_src_is_const(instr->src[0])) {
1339 const unsigned raw_value = nir_src_as_uint(instr->src[0]);
1340 unsigned table_index = pan_res_handle_get_table(raw_value);
1341 unsigned texture_index = pan_res_handle_get_index(raw_value);
1342
1343 if (texture_index < 16 && va_is_valid_const_table(table_index)) {
1344 bi_instr *I = bi_lea_tex_imm_to(b, dest, xy, zw, false, texture_index);
1345 I->table = va_res_fold_table_idx(table_index);
1346 } else {
1347 bi_lea_tex_to(b, dest, xy, zw, bi_src_index(&instr->src[0]), false);
1348 }
1349 } else if (b->shader->arch >= 9) {
1350 bi_lea_tex_to(b, dest, xy, zw, bi_src_index(&instr->src[0]), false);
1351 } else {
1352 bi_instr *I = bi_lea_attr_tex_to(b, dest, xy, zw,
1353 bi_src_index(&instr->src[0]), type);
1354
1355 /* LEA_ATTR_TEX defaults to the secondary attribute table, but
1356 * our ABI has all images in the primary attribute table
1357 */
1358 I->table = BI_TABLE_ATTRIBUTE_1;
1359 }
1360
1361 bi_emit_cached_split(b, dest, 3 * 32);
1362 }
1363
1364 static bi_index
1365 bi_emit_lea_image(bi_builder *b, nir_intrinsic_instr *instr)
1366 {
1367 bi_index dest = bi_temp(b->shader);
1368 bi_emit_lea_image_to(b, dest, instr);
1369 return dest;
1370 }
1371
1372 static void
1373 bi_emit_image_store(bi_builder *b, nir_intrinsic_instr *instr)
1374 {
1375 bi_index a[4] = {bi_null()};
1376 bi_emit_split_i32(b, a, bi_emit_lea_image(b, instr), 3);
1377
1378 /* Due to SPIR-V limitations, the source type is not fully reliable: it
1379 * reports uint32 even for write_imagei. This causes an incorrect
1380 * u32->s32->u32 roundtrip which incurs an unwanted clamping. Use auto32
1381 * instead, which will match per the OpenCL spec. Of course this does
1382 * not work for 16-bit stores, but those are not available in OpenCL.
1383 */
1384 ASSERTED nir_alu_type T = nir_intrinsic_src_type(instr);
1385 assert(nir_alu_type_get_type_size(T) == 32);
1386
1387 bi_st_cvt(b, bi_src_index(&instr->src[3]), a[0], a[1], a[2],
1388 BI_REGISTER_FORMAT_AUTO, instr->num_components - 1);
1389 }
1390
1391 static void
1392 va_emit_load_texel_buf_conversion_desc(bi_builder *b, bi_index dst,
1393 nir_intrinsic_instr *instr)
1394 {
1395 assert(b->shader->arch >= 9);
1396 bi_index table_address, icd_offset;
1397 if (nir_src_is_const(instr->src[0])) {
1398 unsigned res_handle = nir_src_as_uint(instr->src[0]);
1399 unsigned buf_res_table = pan_res_handle_get_table(res_handle);
1400 unsigned buf_res_index = pan_res_handle_get_index(res_handle);
1401 table_address = bi_imm_u32(pan_res_handle(62, buf_res_table));
1402 icd_offset = bi_imm_u32(32 * buf_res_index + 4 * 7);
1403 } else {
1404 bi_index res_handle = bi_src_index(&instr->src[0]);
1405 bi_index buf_res_table = bi_rshift_and_i32(
1406 b, res_handle, bi_imm_u32(BITFIELD_MASK(8)), bi_imm_u8(24), false);
1407 bi_index buf_res_index = bi_lshift_and_i32(
1408 b, res_handle, bi_imm_u32(BITFIELD_MASK(24)), bi_imm_u8(0));
1409 table_address = bi_iadd_imm_i32(b, buf_res_table, pan_res_handle(62, 0));
1410 bi_index buf_desc_offset = bi_imul_i32(b, buf_res_index, bi_imm_u32(32));
1411 icd_offset = bi_iadd_imm_i32(b, buf_desc_offset, 4 * 7);
1412 }
1413
1414 /* Check for zeroed ICD in case robustness is enabled. */
1415 if (b->shader->inputs->robust_descriptors) {
1416 bi_index loaded_icd = bi_temp(b->shader);
1417 bi_ld_pka_i32_to(b, loaded_icd, icd_offset, table_address);
1418 /* CONSTANT 0000 L */
1419 bi_index predefined_icd = bi_imm_u32(95 << 12 | 231);
1420 bi_mux_i32_to(b, dst, predefined_icd, loaded_icd, loaded_icd,
1421 BI_MUX_INT_ZERO);
1422 } else
1423 bi_ld_pka_i32_to(b, dst, icd_offset, table_address);
1424 }
1425
1426 static void
1427 bi_emit_load_texel_buf_index_address(bi_builder *b, bi_index dst,
1428 nir_intrinsic_instr *instr)
1429 {
1430 assert(b->shader->arch < 9);
1431
1432 /* LEA_ATTR_IMM can only be used for the first 0-15 indices. */
1433 bool can_use_imm = false;
1434 unsigned imm_index = 0;
1435 if (nir_src_is_const(instr->src[0])) {
1436 imm_index = nir_src_as_uint(instr->src[0]);
1437 can_use_imm = (imm_index < 16);
1438 }
1439
1440 /* LEA_ATTR[_IMM] defaults to the secondary attribute table, but
1441 * our ABI has all images in the primary attribute table
1442 */
1443 if (can_use_imm) {
1444 bi_instr *I =
1445 bi_lea_attr_imm_to(b, dst, bi_src_index(&instr->src[1]), bi_imm_u32(0),
1446 BI_REGISTER_FORMAT_AUTO, imm_index);
1447 I->table = BI_TABLE_ATTRIBUTE_1;
1448 } else {
1449 bi_instr *I =
1450 bi_lea_attr_to(b, dst, bi_src_index(&instr->src[1]), bi_imm_u32(0),
1451 bi_src_index(&instr->src[0]), BI_REGISTER_FORMAT_AUTO);
1452 I->table = BI_TABLE_ATTRIBUTE_1;
1453 }
1454 bi_emit_cached_split(b, dst, 96);
1455 }
1456
1457 static void
1458 va_emit_load_texel_buf_index_address(bi_builder *b, bi_index dst,
1459 nir_intrinsic_instr *instr)
1460 {
1461 assert(b->shader->arch >= 9);
1462 if (nir_src_is_const(instr->src[0])) {
1463 unsigned res_handle = nir_src_as_uint(instr->src[0]);
1464 bi_instr *I = bi_lea_buf_imm_to(b, dst, bi_src_index(&instr->src[1]));
1465 I->table = pan_res_handle_get_table(res_handle);
1466 I->index = pan_res_handle_get_index(res_handle);
1467 } else {
1468 bi_lea_buf_to(b, dst, bi_src_index(&instr->src[1]),
1469 bi_src_index(&instr->src[0]));
1470 }
1471 bi_emit_cached_split(b, dst, 64);
1472 }
1473
1474 static void
1475 bi_emit_load_cvt(bi_builder *b, bi_index dst, nir_intrinsic_instr *instr,
1476 enum va_memory_access mem_access)
1477 {
1478 bi_index addr = bi_src_index(&instr->src[0]);
1479 bi_index icd = bi_src_index(&instr->src[1]);
1480
1481 bi_instr *I =
1482 bi_ld_cvt_to(b, dst, bi_extract(b, addr, 0), bi_extract(b, addr, 1), icd,
1483 bi_reg_fmt_for_nir(nir_intrinsic_dest_type(instr)),
1484 instr->def.num_components - 1);
1485 I->mem_access = mem_access;
1486 bi_emit_cached_split_i32(b, dst, instr->def.num_components);
1487 }
1488
1489 static void
1490 bi_emit_store_cvt(bi_builder *b, nir_intrinsic_instr *instr,
1491 enum va_memory_access mem_access)
1492 {
1493 bi_index value = bi_src_index(&instr->src[0]);
1494 bi_index addr = bi_src_index(&instr->src[1]);
1495 bi_index icd = bi_src_index(&instr->src[2]);
1496
1497 const nir_alu_type src_type = nir_intrinsic_src_type(instr);
1498 enum bi_register_format regfmt;
1499 if (src_type == 32) {
1500 assert(nir_src_bit_size(instr->src[0]) == 32);
1501 regfmt = BI_REGISTER_FORMAT_AUTO;
1502 } else {
1503 assert(nir_src_bit_size(instr->src[0]) ==
1504 nir_alu_type_get_type_size(src_type));
1505 regfmt = bi_reg_fmt_for_nir(src_type);
1506 }
1507
1508 bi_instr *I =
1509 bi_st_cvt(b, value, bi_extract(b, addr, 0), bi_extract(b, addr, 1), icd,
1510 regfmt, instr->num_components - 1);
1511 I->mem_access = mem_access;
1512 }
1513
1514 static void
1515 bi_emit_atomic_i64_to(bi_builder *b, bi_index dst, bi_index addr, bi_index arg,
1516 nir_atomic_op op)
1517 {
1518 enum bi_atom_opc opc = bi_atom_opc_for_nir(op);
1519 enum bi_atom_opc post_opc = opc;
1520 bool bifrost = b->shader->arch <= 8;
1521
1522 /* ATOM_C.i64 takes a vector with {arg, coalesced}, ATOM_C1.i64 doesn't
1523 * take any vector but can still output in RETURN mode */
1524 bi_index tmp_dest = bifrost ? bi_temp(b->shader) : dst;
1525 unsigned sr_count = bifrost ? 4 : 2;
1526
1527 /* Generate either ATOM or ATOM1 as required */
1528 if (bi_promote_atom_c1(opc, arg, &opc)) {
1529 bi_atom1_return_i64_to(b, tmp_dest, bi_extract(b, addr, 0),
1530 bi_extract(b, addr, 1), opc, sr_count);
1531 } else {
1532 bi_atom_return_i64_to(b, tmp_dest, arg, bi_extract(b, addr, 0),
1533 bi_extract(b, addr, 1), opc, sr_count);
1534 }
1535
1536 if (bifrost) {
1537 /* Post-process it */
1538 bi_emit_cached_split(b, tmp_dest, 64 * 2);
1539 bi_atom_post_i64_to(b, dst, bi_extract(b, tmp_dest, 0),
1540 bi_extract(b, tmp_dest, 2), post_opc);
1541 bi_emit_cached_split(b, dst, 64);
1542 }
1543 }
1544 static void
1545 bi_emit_atomic_i32_to(bi_builder *b, bi_index dst, bi_index addr, bi_index arg,
1546 nir_atomic_op op)
1547 {
1548 enum bi_atom_opc opc = bi_atom_opc_for_nir(op);
1549 enum bi_atom_opc post_opc = opc;
1550 bool bifrost = b->shader->arch <= 8;
1551
1552 /* ATOM_C.i32 takes a vector with {arg, coalesced}, ATOM_C1.i32 doesn't
1553 * take any vector but can still output in RETURN mode */
1554 bi_index tmp_dest = bifrost ? bi_temp(b->shader) : dst;
1555 unsigned sr_count = bifrost ? 2 : 1;
1556
1557 /* Generate either ATOM or ATOM1 as required */
1558 if (bi_promote_atom_c1(opc, arg, &opc)) {
1559 bi_atom1_return_i32_to(b, tmp_dest, bi_extract(b, addr, 0),
1560 bi_extract(b, addr, 1), opc, sr_count);
1561 } else {
1562 bi_atom_return_i32_to(b, tmp_dest, arg, bi_extract(b, addr, 0),
1563 bi_extract(b, addr, 1), opc, sr_count);
1564 }
1565
1566 if (bifrost) {
1567 /* Post-process it */
1568 bi_emit_cached_split_i32(b, tmp_dest, 2);
1569 bi_atom_post_i32_to(b, dst, bi_extract(b, tmp_dest, 0),
1570 bi_extract(b, tmp_dest, 1), post_opc);
1571 }
1572 }
1573
1574 static void
1575 bi_emit_load_var_special_pan(bi_builder *b, nir_intrinsic_instr *instr)
1576 {
1577 bi_index dst = bi_def_index(&instr->def);
1578 enum bi_varying_name var_name = nir_intrinsic_flags(instr);
1579 nir_intrinsic_instr *bary = nir_src_as_intrinsic(instr->src[0]);
1580
1581 enum bi_sample sample = bi_interp_for_intrinsic(bary->intrinsic);
1582 bi_index src0 = bi_varying_src0_for_barycentric(b, bary);
1583 unsigned nr = instr->num_components;
1584 assert(instr->def.bit_size == 32);
1585
1586
1587 /* .explicit is not supported with frag_z */
1588 if (var_name == BI_VARYING_NAME_FRAG_Z)
1589 assert(sample != BI_SAMPLE_EXPLICIT);
1590
1591 /* TODO: v10 adds BI_UPDATE_NONE and v14 introduces store/retrieve updates
1592 * and the barycentric coordinate special varying */
1593 bi_ld_var_special_to(
1594 b, dst, src0, BI_REGISTER_FORMAT_F32, sample, BI_UPDATE_CLOBBER,
1595 (enum bi_varying_name) var_name, nr - 1);
1596 bi_emit_cached_split_i32(b, dst, nr);
1597 }
1598
1599 static void
1600 bi_emit_ld_tile(bi_builder *b, nir_intrinsic_instr *instr)
1601 {
1602 bi_index dest = bi_def_index(&instr->def);
1603 nir_alu_type T = nir_intrinsic_dest_type(instr);
1604 nir_io_semantics sem = nir_intrinsic_io_semantics(instr);
1605 enum bi_register_format regfmt = bi_reg_fmt_for_nir(T);
1606 unsigned size = instr->def.bit_size;
1607 unsigned nr = instr->num_components;
1608
1609 bi_index pi = bi_src_index(&instr->src[0]);
1610 bi_index coverage = bi_src_index(&instr->src[1]);
1611 bi_index conversion = bi_src_index(&instr->src[2]);
1612
1613 bi_instr *I = bi_ld_tile_to(b, dest, pi, coverage, conversion,
1614 regfmt, nr - 1);
1615 I->z_stencil = bi_is_zs(sem.location);
1616
1617 if (instr->intrinsic == nir_intrinsic_load_tile_res_pan)
1618 I->wait_resource = true;
1619
1620 bi_emit_cached_split(b, dest, size * nr);
1621 }
1622
1623 static void
1624 bi_emit_st_tile(bi_builder *b, nir_intrinsic_instr *instr)
1625 {
1626 nir_alu_type T = nir_intrinsic_src_type(instr);
1627 assert(!bi_is_zs(nir_intrinsic_io_semantics(instr).location));
1628 enum bi_register_format regfmt = bi_reg_fmt_for_nir(T);
1629 unsigned nr = instr->num_components;
1630
1631 bi_index rgba = bi_src_index(&instr->src[0]);
1632 bi_index pi = bi_src_index(&instr->src[1]);
1633 bi_index coverage = bi_src_index(&instr->src[2]);
1634 bi_index conversion = bi_src_index(&instr->src[3]);
1635
1636 bi_st_tile(b, rgba, pi, coverage, conversion, regfmt, nr - 1);
1637 }
1638
1639 /*
1640 * Older Bifrost hardware has a limited CLPER instruction. Add a safe helper
1641 * that uses the hardware functionality if available and lowers otherwise.
1642 */
1643 static bi_index
1644 bi_clper(bi_builder *b, bi_index s0, bi_index s1, enum bi_lane_op lop)
1645 {
1646 if (b->shader->quirks & BIFROST_LIMITED_CLPER) {
1647 if (lop == BI_LANE_OP_XOR) {
1648 bi_index lane_id = bi_fau(BIR_FAU_LANE_ID, false);
1649 s1 = bi_lshift_xor_i32(b, lane_id, s1, bi_imm_u8(0));
1650 } else {
1651 assert(lop == BI_LANE_OP_NONE);
1652 }
1653
1654 return bi_clper_old_i32(b, s0, s1);
1655 } else {
1656 return bi_clper_i32(b, s0, s1, BI_INACTIVE_RESULT_ZERO, lop,
1657 BI_SUBGROUP_SUBGROUP4);
1658 }
1659 }
1660
1661 static void
1662 bi_emit_derivative(bi_builder *b, bi_index dst, nir_intrinsic_instr *instr,
1663 unsigned axis, bool coarse)
1664 {
1665 assert(axis == 1 || axis == 2);
1666
1667 bi_index left, right;
1668 bi_index s0 = bi_src_index(&instr->src[0]);
1669
1670 unsigned sz = instr->def.bit_size;
1671
1672 /* If all uses are fabs, the sign of the derivative doesn't matter. This is
1673 * inherently based on fine derivatives so we can't do it for coarse.
1674 */
1675 if (coarse) {
1676 left = bi_clper(b, s0, bi_imm_u8(0), BI_LANE_OP_NONE);
1677 right = bi_clper(b, s0, bi_imm_u8(axis), BI_LANE_OP_NONE);
1678 } else {
1679 left = s0;
1680 right = bi_clper(b, s0, bi_imm_u8(axis), BI_LANE_OP_XOR);
1681 }
1682
1683 if (!coarse && !nir_def_all_uses_ignore_sign_bit(&instr->def)) {
1684 /* If the user cares about the sign, we need to take into account the fact
1685 * left/right (or top/bottom) might be inverted. Instead of using a couple
1686 * CSEL, we just invert the sign bit with
1687 *
1688 * sign_bit = XOR(sign_bit, axis_bit(lane_id)).
1689 */
1690 bi_index res = bi_fadd(b, sz, right, bi_neg(left));
1691 bi_index lane = bi_fau(BIR_FAU_LANE_ID, false);
1692 bi_index lane_shift = bi_imm_u8(sz - ffs(axis));
1693
1694 /* Clear the low bit before the shift if this is the Y-axis we want.
1695 * We skip it on the X-axis, because the lshift-by-31 will get us a
1696 * clean mask. */
1697 if (axis == 2)
1698 lane = bi_lshift_and_i32(b, lane, bi_imm_u32(2), bi_imm_u8(0));
1699
1700 if (sz == 16)
1701 lane = bi_half(lane, false);
1702
1703 /* And here comes the final XOR on the sign bit. */
1704 bi_lshift_xor_to(b, sz, dst, lane, res, lane_shift);
1705 } else {
1706 bi_fadd_to(b, sz, dst, right, bi_neg(left));
1707 }
1708 }
1709
1710 static enum bi_subgroup
1711 bi_subgroup_from_cluster_size(unsigned cluster_size)
1712 {
1713 switch (cluster_size) {
1714 case 2: return BI_SUBGROUP_SUBGROUP2;
1715 case 4: return BI_SUBGROUP_SUBGROUP4;
1716 case 8: return BI_SUBGROUP_SUBGROUP8;
1717 case 16: return BI_SUBGROUP_SUBGROUP16;
1718 default: UNREACHABLE("Unsupported cluster size");
1719 }
1720 }
1721
1722 static enum va_memory_access
1723 va_memory_access_from_nir(const nir_intrinsic_instr *intr)
1724 {
1725 const enum gl_access_qualifier access = nir_intrinsic_access(intr);
1726 if (access & ACCESS_ISTREAM_PAN)
1727 return VA_MEMORY_ACCESS_ISTREAM;
1728 if (access & ACCESS_ESTREAM_PAN)
1729 return VA_MEMORY_ACCESS_ESTREAM;
1730 return VA_MEMORY_ACCESS_NONE;
1731 }
1732
1733 static void
1734 bi_emit_intrinsic(bi_builder *b, nir_intrinsic_instr *instr)
1735 {
1736 bi_index dst = nir_intrinsic_infos[instr->intrinsic].has_dest
1737 ? bi_def_index(&instr->def)
1738 : bi_null();
1739 mesa_shader_stage stage = b->shader->stage;
1740
1741 switch (instr->intrinsic) {
1742 case nir_intrinsic_load_barycentric_pixel:
1743 case nir_intrinsic_load_barycentric_centroid:
1744 case nir_intrinsic_load_barycentric_sample:
1745 case nir_intrinsic_load_barycentric_at_sample:
1746 case nir_intrinsic_load_barycentric_at_offset:
1747 /* handled later via load_fs_input */
1748 break;
1749 case nir_intrinsic_load_attribute_pan:
1750 assert(stage == MESA_SHADER_VERTEX);
1751 bi_emit_load_attr(b, instr);
1752 break;
1753
1754 case nir_intrinsic_load_blend_input_pan:
1755 bi_emit_load_blend_input(b, instr);
1756 break;
1757
1758 case nir_intrinsic_load_interpolated_input:
1759 case nir_intrinsic_load_input:
1760 assert(!b->shader->inputs->is_blend);
1761 if (stage == MESA_SHADER_VERTEX)
1762 bi_emit_load_attr(b, instr);
1763 else
1764 UNREACHABLE("Unsupported shader stage");
1765 break;
1766
1767 case nir_intrinsic_load_var_pan:
1768 case nir_intrinsic_load_var_flat_pan:
1769 bi_emit_load_var(b, instr);
1770 break;
1771
1772 case nir_intrinsic_load_var_buf_pan:
1773 case nir_intrinsic_load_var_buf_flat_pan:
1774 bi_emit_load_var_buf(b, instr);
1775 break;
1776
1777 case nir_intrinsic_load_cumulative_coverage_pan:
1778 bi_mov_i32_to(b, dst, bi_preload(b, BI_PRELOAD_CUMULATIVE_COVERAGE));
1779 break;
1780
1781 case nir_intrinsic_load_blend_descriptor_pan: {
1782 unsigned rt = nir_intrinsic_base(instr);
1783 bi_collect_v2i32_to(b, dst, bi_fau(BIR_FAU_BLEND_0 + rt, false),
1784 bi_fau(BIR_FAU_BLEND_0 + rt, true));
1785 break;
1786 }
1787
1788 case nir_intrinsic_atest_pan: {
1789 bi_index coverage = bi_src_index(&instr->src[0]);
1790 bi_index alpha = bi_src_index(&instr->src[1]);
1791 bi_atest_to(b, dst, coverage, alpha, bi_fau(BIR_FAU_ATEST_PARAM, false));
1792 break;
1793 }
1794
1795 case nir_intrinsic_zs_emit_pan: {
1796 bi_index coverage = bi_src_index(&instr->src[0]);
1797 unsigned flags = nir_intrinsic_flags(instr);
1798 uint32_t has_z = flags & BITFIELD_BIT(FRAG_RESULT_DEPTH);
1799 uint32_t has_s = flags & BITFIELD_BIT(FRAG_RESULT_STENCIL);
1800 bi_index z = has_z ? bi_src_index(&instr->src[1]) : bi_dontcare(b);
1801 bi_index s = has_s ? bi_src_index(&instr->src[2]) : bi_dontcare(b);
1802 bi_zs_emit_to(b, dst, z, s, coverage, has_s, has_z);
1803 break;
1804 }
1805
1806 case nir_intrinsic_blend_pan:
1807 case nir_intrinsic_blend2_pan: {
1808 bi_index coverage = bi_src_index(&instr->src[0]);
1809 bi_index desc = bi_src_index(&instr->src[1]);
1810 bi_index rgba = bi_src_index(&instr->src[2]);
1811 nir_alu_type T = nir_intrinsic_src_type(instr);
1812
1813 bi_index rgba2 = bi_null();
1814 nir_alu_type T2 = nir_type_invalid;
1815 if (instr->intrinsic == nir_intrinsic_blend2_pan) {
1816 rgba2 = bi_src_index(&instr->src[3]);
1817 T2 = nir_intrinsic_dest_type(instr);
1818 }
1819
1820 unsigned size = nir_alu_type_get_type_size(T);
1821 unsigned size_2 = nir_alu_type_get_type_size(T2);
1822 unsigned sr_count = (size <= 16) ? 2 : 4;
1823 unsigned sr_count_2 = (size_2 <= 16) ? 2 : 4;
1824
1825 enum bi_register_format regfmt = bi_reg_fmt_for_nir(T);
1826 if (b->shader->nir->info.fs.untyped_color_outputs)
1827 regfmt = BI_REGISTER_FORMAT_AUTO;
1828
1829 /* If we have more than one color target, explicit copy since BLEND
1830 * inputs are precoloured to R0-R3.
1831 *
1832 * TODO: maybe schedule around this or implement in RA as a spill
1833 */
1834 if (b->shader->nir->info.outputs_written >> FRAG_RESULT_DATA1) {
1835 bi_index srcs[4] = {rgba, rgba, rgba, rgba};
1836 unsigned channels[4] = {0, 1, 2, 3};
1837 rgba = bi_temp(b->shader);
1838 bi_make_vec_to(b, rgba, srcs, channels, 4, size);
1839 }
1840
1841 nir_io_semantics io = nir_intrinsic_io_semantics(instr);
1842 assert(io.location >= FRAG_RESULT_DATA0);
1843 assert(io.location <= FRAG_RESULT_DATA7);
1844 unsigned rt = io.location - FRAG_RESULT_DATA0;
1845
1846 bi_instr *I = bi_blend_to(b, bi_temp(b->shader), rgba, coverage,
1847 bi_extract(b, desc, 0), bi_extract(b, desc, 1),
1848 rgba2, regfmt, sr_count, sr_count_2);
1849 I->blend_target = rt;
1850
1851 b->shader->info.bifrost->blend[rt].type = T;
1852 if (instr->intrinsic == nir_intrinsic_blend2_pan) {
1853 assert(b->shader->info.bifrost->blend_src1_type == nir_type_invalid);
1854 b->shader->info.bifrost->blend_src1_type = T2;
1855 }
1856 break;
1857 }
1858
1859 case nir_intrinsic_blend_return_pan:
1860 /* Jump back to the fragment shader. On Valhall, only jump if the address
1861 * is nonzero. The check is free there and it implements the "jump to 0
1862 * terminates the blend shader" that's automatic on Bifrost.
1863 */
1864 if (b->shader->arch >= 9)
1865 bi_branchzi(b, bi_preload(b, BI_PRELOAD_BLEND_LINK),
1866 bi_preload(b, BI_PRELOAD_BLEND_LINK), BI_CMPF_NE);
1867 else
1868 bi_jump(b, bi_preload(b, BI_PRELOAD_BLEND_LINK));
1869 break;
1870
1871 case nir_intrinsic_load_ubo:
1872 bi_emit_load_ubo(b, instr);
1873 break;
1874
1875 case nir_intrinsic_load_push_constant:
1876 bi_emit_load_push_constant(b, instr);
1877 break;
1878
1879 case nir_intrinsic_load_global:
1880 case nir_intrinsic_load_global_constant:
1881 bi_emit_load(b, instr, BI_SEG_NONE, va_memory_access_from_nir(instr));
1882 break;
1883
1884 case nir_intrinsic_store_global:
1885 case nir_intrinsic_store_global_psiz_pan: {
1886 bi_instr *I = bi_emit_store(b, instr, BI_SEG_NONE,
1887 va_memory_access_from_nir(instr));
1888 I->is_psiz_write = instr->intrinsic == nir_intrinsic_store_global_psiz_pan;
1889 break;
1890 }
1891
1892 case nir_intrinsic_load_scratch:
1893 bi_emit_load(b, instr, BI_SEG_TL, VA_MEMORY_ACCESS_FORCE);
1894 break;
1895
1896 case nir_intrinsic_store_scratch:
1897 bi_emit_store(b, instr, BI_SEG_TL, VA_MEMORY_ACCESS_FORCE);
1898 break;
1899
1900 case nir_intrinsic_load_shared:
1901 bi_emit_load(b, instr, BI_SEG_WLS, VA_MEMORY_ACCESS_NONE);
1902 break;
1903
1904 case nir_intrinsic_store_shared:
1905 bi_emit_store(b, instr, BI_SEG_WLS, VA_MEMORY_ACCESS_NONE);
1906 break;
1907
1908 case nir_intrinsic_barrier:
1909 switch (nir_intrinsic_execution_scope(instr)) {
1910 case SCOPE_NONE:
1911 case SCOPE_SUBGROUP:
1912 /*
1913 * To implement none and subgroup barriers, we only need to prevent
1914 * the scheduler from reordering operations with side-effects around
1915 * the barrier. Avail and vis are trivially established.
1916 */
1917 bi_nop(b)->scheduling_barrier = true;
1918 break;
1919
1920 case SCOPE_WORKGROUP:
1921 assert(mesa_shader_stage_is_compute(b->shader->stage));
1922 bi_barrier(b);
1923 /*
1924 * Blob doesn't seem to do anything for memory barriers, so no need to
1925 * check nir_intrinsic_memory_scope().
1926 */
1927 break;
1928
1929 default:
1930 UNREACHABLE("Unsupported barrier scope");
1931 }
1932
1933 break;
1934
1935 case nir_intrinsic_shared_atomic: {
1936 nir_atomic_op op = nir_intrinsic_atomic_op(instr);
1937
1938 bi_index addr = bi_src_index(&instr->src[0]);
1939 bi_index addr_hi;
1940
1941 if (b->shader->arch >= 9) {
1942 bi_handle_segment(b, &addr, &addr_hi, BI_SEG_WLS, NULL);
1943 addr = bi_collect_v2i32(b, addr, addr_hi);
1944
1945 if (nir_src_bit_size(instr->src[1]) == 32) {
1946 bi_emit_atomic_i32_to(b, dst, addr, bi_src_index(&instr->src[1]), op);
1947 } else {
1948 bi_emit_atomic_i64_to(b, dst, addr, bi_src_index(&instr->src[1]), op);
1949 }
1950 } else {
1951 if (op == nir_atomic_op_xchg) {
1952 bi_emit_axchg_to(b, dst, addr, &instr->src[1],
1953 BI_SEG_WLS);
1954 } else {
1955 addr = bi_seg_add_i64(b, addr, bi_zero(), false, BI_SEG_WLS);
1956 bi_emit_cached_split(b, addr, 64);
1957
1958 if (nir_src_bit_size(instr->src[1]) == 32) {
1959 bi_emit_atomic_i32_to(b, dst, addr, bi_src_index(&instr->src[1]), op);
1960 } else {
1961 bi_emit_atomic_i64_to(b, dst, addr, bi_src_index(&instr->src[1]), op);
1962 }
1963 }
1964 }
1965
1966 bi_split_def(b, &instr->def);
1967 break;
1968 }
1969
1970 case nir_intrinsic_global_atomic: {
1971 nir_atomic_op op = nir_intrinsic_atomic_op(instr);
1972
1973 if (b->shader->arch >= 9) {
1974 if (nir_src_bit_size(instr->src[1]) == 32) {
1975 bi_emit_atomic_i32_to(b, dst, bi_src_index(&instr->src[0]),
1976 bi_src_index(&instr->src[1]), op);
1977 } else {
1978 bi_emit_atomic_i64_to(b, dst, bi_src_index(&instr->src[0]),
1979 bi_src_index(&instr->src[1]), op);
1980 }
1981 } else {
1982
1983 if (op == nir_atomic_op_xchg) {
1984 bi_emit_axchg_to(b, dst, bi_src_index(&instr->src[0]), &instr->src[1], BI_SEG_NONE);
1985 } else {
1986 if (nir_src_bit_size(instr->src[1]) == 32) {
1987 bi_emit_atomic_i32_to(b, dst, bi_src_index(&instr->src[0]),
1988 bi_src_index(&instr->src[1]), op);
1989 } else {
1990 bi_emit_atomic_i64_to(b, dst, bi_src_index(&instr->src[0]),
1991 bi_src_index(&instr->src[1]), op);
1992 }
1993 }
1994 }
1995
1996 bi_split_def(b, &instr->def);
1997 break;
1998 }
1999
2000 case nir_intrinsic_image_texel_address:
2001 bi_emit_lea_image_to(b, dst, instr);
2002 break;
2003
2004 case nir_intrinsic_image_load:
2005 bi_emit_image_load(b, instr);
2006 break;
2007
2008 case nir_intrinsic_image_store:
2009 bi_emit_image_store(b, instr);
2010 break;
2011
2012 case nir_intrinsic_global_atomic_swap:
2013 bi_emit_acmpxchg_to(b, dst, bi_src_index(&instr->src[0]), &instr->src[1],
2014 &instr->src[2], BI_SEG_NONE);
2015 bi_split_def(b, &instr->def);
2016 break;
2017
2018 case nir_intrinsic_shared_atomic_swap:
2019 bi_emit_acmpxchg_to(b, dst, bi_src_index(&instr->src[0]), &instr->src[1],
2020 &instr->src[2], BI_SEG_WLS);
2021 bi_split_def(b, &instr->def);
2022 break;
2023
2024 case nir_intrinsic_load_pixel_coord:
2025 /* Vectorized load of the preloaded i16vec2 */
2026 bi_mov_i32_to(b, dst, bi_preload(b, BI_PRELOAD_POSITION_XY));
2027 break;
2028
2029 case nir_intrinsic_load_texel_buf_conv_pan:
2030 assert(b->shader->arch >= 9 &&
2031 "conv desc is loaded with the texel_buf_addr on Bifrost");
2032 va_emit_load_texel_buf_conversion_desc(b, dst, instr);
2033 break;
2034
2035 case nir_intrinsic_load_texel_buf_index_address_pan:
2036 if (b->shader->arch >= 9)
2037 va_emit_load_texel_buf_index_address(b, dst, instr);
2038 else
2039 bi_emit_load_texel_buf_index_address(b, dst, instr);
2040 break;
2041
2042 case nir_intrinsic_load_global_cvt_pan:
2043 bi_emit_load_cvt(b, dst, instr, va_memory_access_from_nir(instr));
2044 break;
2045
2046 case nir_intrinsic_store_global_cvt_pan:
2047 bi_emit_store_cvt(b, instr, va_memory_access_from_nir(instr));
2048 break;
2049
2050 case nir_intrinsic_load_idvs_output_buf_index_pan:
2051 bi_mov_i32_to(b, dst, bi_preload(b, BI_PRELOAD_INTERNAL_ID));
2052 break;
2053
2054 case nir_intrinsic_lea_attr_pan:
2055 bi_emit_lea_attr(b, instr);
2056 break;
2057
2058 case nir_intrinsic_lea_buf_pan:
2059 bi_emit_lea_buf(b, instr);
2060 break;
2061
2062 case nir_intrinsic_load_tile_pan:
2063 case nir_intrinsic_load_tile_res_pan:
2064 bi_emit_ld_tile(b, instr);
2065 break;
2066
2067 case nir_intrinsic_store_tile_pan:
2068 bi_emit_st_tile(b, instr);
2069 break;
2070
2071 case nir_intrinsic_demote_if:
2072 bi_discard_b32(b, bi_src_index(&instr->src[0]));
2073 break;
2074
2075 case nir_intrinsic_demote:
2076 bi_discard_f32(b, bi_zero(), bi_zero(), BI_CMPF_EQ);
2077 break;
2078
2079 case nir_intrinsic_load_sample_positions_pan:
2080 bi_collect_v2i32_to(b, dst, bi_fau(BIR_FAU_SAMPLE_POS_ARRAY, false),
2081 bi_fau(BIR_FAU_SAMPLE_POS_ARRAY, true));
2082 break;
2083
2084 case nir_intrinsic_load_sample_mask_in:
2085 /* [0:15] contains the coverage bitmap */
2086 bi_u16_to_u32_to(
2087 b, dst, bi_half(bi_preload(b, BI_PRELOAD_RASTERIZER_COVERAGE), false));
2088 break;
2089
2090 case nir_intrinsic_load_sample_mask:
2091 bi_mov_i32_to(b, dst, bi_coverage(b));
2092 break;
2093
2094 case nir_intrinsic_load_sample_id:
2095 bi_load_sample_id_to(b, dst);
2096 break;
2097
2098 case nir_intrinsic_load_primitive_id:
2099 bi_mov_i32_to(b, dst, bi_preload(b, BI_PRELOAD_PRIMITIVE_ID));
2100 break;
2101
2102 case nir_intrinsic_load_front_face: {
2103 /* (primitive_flags & 1) == 0 means primitive is front facing */
2104 bi_index primitive_facing = bi_preload(b, BI_PRELOAD_PRIMITIVE_FLAGS);
2105
2106 /* Starting with v11, there is more fields defined in the primitive flags */
2107 if (b->shader->arch >= 11)
2108 primitive_facing =
2109 bi_lshift_and_i32(b, primitive_facing, bi_imm_u32(1), bi_imm_u8(0));
2110
2111 bi_icmp_i32_to(b, dst, primitive_facing, bi_zero(), BI_CMPF_EQ,
2112 BI_RESULT_TYPE_M1);
2113 break;
2114 }
2115
2116 case nir_intrinsic_load_var_special_pan:
2117 bi_emit_load_var_special_pan(b, instr);
2118 break;
2119
2120 /* It appears vertex_id is zero-based with Bifrost geometry flows, but
2121 * not with Valhall's memory-allocation IDVS geometry flow. We only support
2122 * the new flow on Valhall so this is lowered in NIR.
2123 */
2124 case nir_intrinsic_load_vertex_id:
2125 assert(b->shader->malloc_idvs);
2126 bi_mov_i32_to(b, dst, bi_vertex_id(b));
2127 break;
2128
2129 case nir_intrinsic_load_raw_vertex_id_pan:
2130 assert(!b->shader->malloc_idvs);
2131 bi_mov_i32_to(b, dst, bi_vertex_id(b));
2132 break;
2133
2134 case nir_intrinsic_load_instance_id:
2135 bi_mov_i32_to(b, dst, bi_instance_id(b));
2136 break;
2137
2138 case nir_intrinsic_load_draw_id:
2139 bi_mov_i32_to(b, dst, bi_draw_id(b));
2140 break;
2141
2142 case nir_intrinsic_load_subgroup_invocation:
2143 bi_mov_i32_to(b, dst, bi_fau(BIR_FAU_LANE_ID, false));
2144 break;
2145
2146 case nir_intrinsic_ballot:
2147 case nir_intrinsic_ballot_relaxed: {
2148 assert(instr->src[0].ssa->bit_size == 32);
2149 enum bi_subgroup subgroup =
2150 bi_subgroup_from_cluster_size(pan_subgroup_size(b->shader->arch));
2151 bi_wmask_to(b, dst, bi_src_index(&instr->src[0]), subgroup, 0);
2152 break;
2153 }
2154
2155 case nir_intrinsic_read_invocation: {
2156 assert(instr->src[0].ssa->bit_size <= 32);
2157 enum bi_inactive_result inactive_result = BI_INACTIVE_RESULT_ZERO;
2158 enum bi_lane_op lane_op = BI_LANE_OP_NONE;
2159 enum bi_subgroup subgroup =
2160 bi_subgroup_from_cluster_size(pan_subgroup_size(b->shader->arch));
2161 bi_clper_i32_to(b, dst,
2162 bi_src_index(&instr->src[0]),
2163 bi_byte(bi_src_index(&instr->src[1]), 0),
2164 inactive_result, lane_op, subgroup);
2165 break;
2166 }
2167
2168 case nir_intrinsic_load_local_invocation_id:
2169 bi_collect_v3i32_to(
2170 b, dst,
2171 bi_u16_to_u32(b, bi_half(bi_preload(b, BI_PRELOAD_LOCAL_ID_0), 0)),
2172 bi_u16_to_u32(b, bi_half(bi_preload(b, BI_PRELOAD_LOCAL_ID_1), 1)),
2173 bi_u16_to_u32(b, bi_half(bi_preload(b, BI_PRELOAD_LOCAL_ID_2), 0)));
2174 break;
2175
2176 case nir_intrinsic_load_workgroup_id:
2177 bi_collect_v3i32_to(b, dst, bi_preload(b, BI_PRELOAD_WORKGROUP_ID_0),
2178 bi_preload(b, BI_PRELOAD_WORKGROUP_ID_1),
2179 bi_preload(b, BI_PRELOAD_WORKGROUP_ID_2));
2180 break;
2181
2182 case nir_intrinsic_load_global_invocation_id:
2183 bi_collect_v3i32_to(b, dst, bi_preload(b, BI_PRELOAD_GLOBAL_ID_0),
2184 bi_preload(b, BI_PRELOAD_GLOBAL_ID_1),
2185 bi_preload(b, BI_PRELOAD_GLOBAL_ID_2));
2186 break;
2187
2188 case nir_intrinsic_shader_clock:
2189 bi_ld_gclk_u64_to(b, dst, BI_SOURCE_CYCLE_COUNTER);
2190 bi_split_def(b, &instr->def);
2191 b->shader->info.has_ld_gclk_instr = true;
2192 break;
2193
2194 case nir_intrinsic_ddx:
2195 case nir_intrinsic_ddx_fine:
2196 bi_emit_derivative(b, dst, instr, 1, false);
2197 break;
2198 case nir_intrinsic_ddx_coarse:
2199 bi_emit_derivative(b, dst, instr, 1, true);
2200 break;
2201 case nir_intrinsic_ddy:
2202 case nir_intrinsic_ddy_fine:
2203 bi_emit_derivative(b, dst, instr, 2, false);
2204 break;
2205 case nir_intrinsic_ddy_coarse:
2206 bi_emit_derivative(b, dst, instr, 2, true);
2207 break;
2208
2209 case nir_intrinsic_load_view_index:
2210 case nir_intrinsic_load_layer_id:
2211 assert(b->shader->arch >= 9);
2212 bi_mov_i32_to(
2213 b, dst,
2214 bi_u8_to_u32(b, bi_byte(bi_preload(b, BI_PRELOAD_FRAME_ARG), 0)));
2215 break;
2216
2217 case nir_intrinsic_load_ssbo_address:
2218 assert(b->shader->arch >= 9);
2219 bi_lea_pka_to(b, dst, bi_src_index(&instr->src[1]),
2220 bi_src_index(&instr->src[0]));
2221 bi_emit_cached_split(b, dst, 64);
2222 break;
2223
2224 case nir_intrinsic_load_ssbo: {
2225 assert(b->shader->arch >= 9);
2226 unsigned dst_bits = instr->num_components * instr->def.bit_size;
2227 bi_ld_pka_to(b, dst_bits, dst, bi_src_index(&instr->src[1]),
2228 bi_src_index(&instr->src[0]));
2229 bi_emit_cached_split(b, dst, dst_bits);
2230 break;
2231 }
2232
2233 case nir_intrinsic_as_uniform:
2234 /*
2235 * We don't have uniform registers (registers shared by all threads in the
2236 * warp) like some other hardware does so this is just a simple mov for
2237 * us.
2238 */
2239 bi_mov_i32_to(b, dst, bi_src_index(&instr->src[0]));
2240 break;
2241
2242 case nir_intrinsic_load_shader_output_pan:
2243 assert(b->shader->arch >= 12 && "load_shader_output_pan should have been lowered!");
2244 bi_mov_i32_to(b, dst, bi_fau(BIR_FAU_SHADER_OUTPUT, false));
2245 break;
2246
2247 case nir_intrinsic_load_core_id:
2248 assert(b->shader->arch >= 9);
2249 bi_mov_i32_to(b, dst, bi_fau(BIR_FAU_CORE_ID, false));
2250 break;
2251
2252 case nir_intrinsic_load_core_count_arm:
2253 assert(b->shader->arch >= 9);
2254 bi_mov_i32_to(b, dst, bi_iadd_u32(b, bi_fau(BIR_FAU_CORE_ID, true), bi_imm_u32(1), false));
2255 break;
2256
2257 case nir_intrinsic_load_warp_id_arm:
2258 assert(b->shader->arch >= 9);
2259 bi_mov_i32_to(b, dst, bi_fau(BIR_FAU_WARP_ID, false));
2260 break;
2261
2262 case nir_intrinsic_load_warp_max_id_arm:
2263 assert(b->shader->arch >= 9);
2264 bi_mov_i32_to(b, dst, bi_fau(BIR_FAU_WARP_ID, true));
2265 break;
2266
2267 default:
2268 fprintf(stderr, "Unhandled intrinsic %s\n",
2269 nir_intrinsic_infos[instr->intrinsic].name);
2270 assert(0);
2271 }
2272 }
2273
2274 static void
2275 bi_emit_load_const(bi_builder *b, nir_load_const_instr *instr)
2276 {
2277 const unsigned sz = instr->def.bit_size;
2278 const unsigned comps = instr->def.num_components;
2279 bi_index temp[BI_MAX_VEC];
2280
2281 if (sz == 64) {
2282 for (unsigned i = 0; i < comps; ++i) {
2283 uint64_t v = nir_const_value_as_uint(instr->value[i], 64);
2284 temp[i * 2 + 0] = bi_mov_i32(b, bi_imm_u32(v));
2285 temp[i * 2 + 1] = bi_mov_i32(b, bi_imm_u32(v >> 32));
2286 }
2287 bi_emit_collect_to(b, bi_get_index(instr->def.index), temp, comps * 2);
2288 } else {
2289 assert(sz == 8 || sz == 16 || sz == 32);
2290 const unsigned comps_per_word = 32 / sz;
2291 const unsigned words = DIV_ROUND_UP(comps, comps_per_word);
2292 for (unsigned w = 0; w < words; w++) {
2293 uint32_t acc = 0;
2294 for (unsigned i = 0; i < comps_per_word; i++) {
2295 unsigned c = w * comps_per_word + i;
2296 if (c >= comps)
2297 break;
2298
2299 uint32_t v = nir_const_value_as_uint(instr->value[c], sz);
2300 acc |= v << (i * sz);
2301 }
2302 temp[w] = bi_mov_i32(b, bi_imm_u32(acc));
2303 }
2304 bi_emit_collect_to(b, bi_get_index(instr->def.index), temp, words);
2305 }
2306 }
2307
2308 static bi_index
2309 bi_alu_src_index(bi_builder *b, nir_alu_src src, unsigned comps)
2310 {
2311 unsigned bitsize = nir_src_bit_size(src.src);
2312
2313 if (b->shader->arch >= 9 && bitsize == 64) {
2314 /* For Valhall, 64-bit instructions only encode one register but will read
2315 * the adjacent register that comes right after as well. Therefore we
2316 * don't need to extract a single register here.
2317 */
2318 assert(comps == 1);
2319 return bi_src_index(&src.src);
2320 }
2321
2322 /* the bi_index carries the 32-bit (word) offset separate from the
2323 * subword swizzle, first handle the offset */
2324
2325 unsigned offset = 0;
2326
2327 assert(bitsize == 8 || bitsize == 16 || bitsize == 32 || bitsize == 64);
2328 for (unsigned i = 0; i < comps; ++i) {
2329 unsigned new_offset = (src.swizzle[i] * bitsize) / 32;
2330
2331 if (i > 0)
2332 assert(offset == new_offset && "wrong vectorization");
2333
2334 offset = new_offset;
2335 }
2336
2337 bi_index idx = bi_extract(b, bi_src_index(&src.src), offset);
2338
2339 /* Compose the subword swizzle with existing (identity) swizzle */
2340 assert(idx.swizzle == BI_SWIZZLE_H01);
2341
2342 if (bitsize == 16) {
2343 unsigned c0 = src.swizzle[0] & 1;
2344 unsigned c1 = (comps > 1) ? src.swizzle[1] & 1 : c0;
2345 idx.swizzle = BI_SWIZZLE_H00 + c1 + (c0 << 1);
2346 } else if (bitsize == 8 && comps == 1) {
2347 idx.swizzle = BI_SWIZZLE_B0000 + (src.swizzle[0] & 3);
2348 } else if (bitsize == 8) {
2349 bool has_swizzle = false;
2350 enum bi_swizzle swizzle = BI_SWIZZLE_H01;
2351 if (comps == 3) {
2352 unsigned c[4];
2353 for (unsigned i = 0; i < 3; ++i)
2354 c[i] = src.swizzle[i] & 3;
2355
2356 /* Try to find a swizzle that starts with the given v3i8 swizzle */
2357 for (unsigned i = 0; i < 4; i++) {
2358 c[3] = i;
2359 if (bi_swizzle_from_byte_channels(c, &swizzle)) {
2360 has_swizzle = true;
2361 break;
2362 }
2363 }
2364 } else {
2365 /* For 1 and 2-component, repeat the swizzle to increase the chances
2366 * that it's a valid bi_swizzle.
2367 */
2368 unsigned c[4];
2369 for (unsigned i = 0; i < 4; ++i)
2370 c[i] = src.swizzle[i % comps] & 3;
2371 has_swizzle = bi_swizzle_from_byte_channels(c, &swizzle);
2372 }
2373
2374 if (has_swizzle) {
2375 idx.swizzle = swizzle;
2376 return idx;
2377 }
2378
2379 bi_index v4_srcs[4];
2380 for (unsigned i = 0; i < comps; i++) {
2381 v4_srcs[i] = idx;
2382 v4_srcs[i].swizzle = BI_SWIZZLE_B0 + src.swizzle[i];
2383 }
2384 for (unsigned i = comps; i < 4; i++)
2385 v4_srcs[i] = bi_imm_u8(0);
2386
2387 bi_index temp = bi_mkvec_v4i8(b, v4_srcs[0], v4_srcs[1],
2388 v4_srcs[2], v4_srcs[3]);
2389
2390 static const enum bi_swizzle swizzle_lut[] = {
2391 BI_SWIZZLE_B0000, BI_SWIZZLE_B0101, BI_SWIZZLE_B0123, BI_SWIZZLE_B0123
2392 };
2393 assert(comps - 1 < ARRAY_SIZE(swizzle_lut));
2394
2395 /* Assign a coherent swizzle for the vector */
2396 temp.swizzle = swizzle_lut[comps - 1];
2397
2398 return temp;
2399 }
2400
2401 return idx;
2402 }
2403
2404 static bi_index
2405 bi_swiz_b01(bi_index idx)
2406 {
2407 enum bi_swizzle swizzle;
2408 bool valid = bi_try_compose_swizzles(&swizzle, BI_SWIZZLE_B01, idx.swizzle);
2409 assert(valid);
2410
2411 idx.swizzle = swizzle;
2412 return idx;
2413 }
2414
2415 static enum bi_round
2416 bi_nir_round(nir_op op)
2417 {
2418 switch (op) {
2419 case nir_op_fround_even:
2420 return BI_ROUND_NONE;
2421 case nir_op_ftrunc:
2422 return BI_ROUND_RTZ;
2423 case nir_op_fceil:
2424 return BI_ROUND_RTP;
2425 case nir_op_ffloor:
2426 return BI_ROUND_RTN;
2427 default:
2428 UNREACHABLE("invalid nir round op");
2429 }
2430 }
2431
2432 /* Convenience for lowered transcendentals */
2433
2434 static bi_index
2435 bi_fmul_f32(bi_builder *b, bi_index s0, bi_index s1)
2436 {
2437 return bi_fma_f32(b, s0, s1, bi_imm_f32(-0.0f));
2438 }
2439
2440 /* Approximate with FRCP_APPROX.f32 and apply a single iteration of
2441 * Newton-Raphson to improve precision */
2442
2443 static void
2444 bi_lower_frcp_32(bi_builder *b, bi_index dst, bi_index s0)
2445 {
2446 bi_index x1 = bi_frcp_approx_f32(b, s0);
2447 bi_index m = bi_frexpm_f32(b, s0, false, false);
2448 bi_index e = bi_frexpe_f32(b, bi_neg(s0), false, false);
2449 bi_index t1 = bi_fma_rscale_f32(b, m, bi_neg(x1), bi_imm_f32(1.0), bi_zero(),
2450 BI_SPECIAL_N);
2451 bi_fma_rscale_f32_to(b, dst, t1, x1, x1, e, BI_SPECIAL_NONE);
2452 }
2453
2454 static void
2455 bi_lower_frsq_32(bi_builder *b, bi_index dst, bi_index s0)
2456 {
2457 bi_index x1 = bi_frsq_approx_f32(b, s0);
2458 bi_index m = bi_frexpm_f32(b, s0, false, true);
2459 bi_index e = bi_frexpe_f32(b, bi_neg(s0), false, true);
2460 bi_index t1 = bi_fmul_f32(b, x1, x1);
2461 bi_index t2 = bi_fma_rscale_f32(b, m, bi_neg(t1), bi_imm_f32(1.0),
2462 bi_imm_u32(-1), BI_SPECIAL_N);
2463 bi_fma_rscale_f32_to(b, dst, t2, x1, x1, e, BI_SPECIAL_N);
2464 }
2465
2466 /* More complex transcendentals, see
2467 * https://gitlab.freedesktop.org/panfrost/mali-isa-docs/-/blob/master/Bifrost.adoc
2468 * for documentation */
2469
2470 static void
2471 bi_lower_fexp2_32(bi_builder *b, bi_index dst, bi_index s0)
2472 {
2473 bi_index t1 = bi_temp(b->shader);
2474 bi_instr *t1_instr = bi_fadd_f32_to(b, t1, s0, bi_imm_u32(0x49400000));
2475 t1_instr->clamp = BI_CLAMP_CLAMP_0_INF;
2476
2477 bi_index t2 = bi_fadd_f32(b, t1, bi_imm_u32(0xc9400000));
2478
2479 bi_instr *a2 = bi_fadd_f32_to(b, bi_temp(b->shader), s0, bi_neg(t2));
2480 a2->clamp = BI_CLAMP_CLAMP_M1_1;
2481
2482 bi_index a1t = bi_fexp_table_u4(b, t1, BI_ADJ_NONE);
2483 bi_index t3 = bi_isub_u32(b, t1, bi_imm_u32(0x49400000), false);
2484 bi_index a1i = bi_arshift_i32(b, t3, bi_null(), bi_imm_u8(4));
2485 bi_index p1 = bi_fma_f32(b, a2->dest[0], bi_imm_u32(0x3d635635),
2486 bi_imm_u32(0x3e75fffa));
2487 bi_index p2 = bi_fma_f32(b, p1, a2->dest[0], bi_imm_u32(0x3f317218));
2488 bi_index p3 = bi_fmul_f32(b, a2->dest[0], p2);
2489 bi_instr *x = bi_fma_rscale_f32_to(b, bi_temp(b->shader), p3, a1t, a1t, a1i,
2490 BI_SPECIAL_NONE);
2491 x->clamp = BI_CLAMP_CLAMP_0_INF;
2492
2493 bi_instr *max = bi_fmax_f32_to(b, dst, x->dest[0], s0);
2494 max->sem = BI_SEM_NAN_PROPAGATE;
2495 }
2496
2497 static void
2498 bi_fexp_32(bi_builder *b, bi_index dst, bi_index s0, bi_index log2_base)
2499 {
2500 /* Scale by base, Multiply by 2*24 and convert to integer to get a 8:24
2501 * fixed-point input */
2502 bi_index scale = bi_fma_rscale_f32(b, s0, log2_base, bi_negzero(),
2503 bi_imm_u32(24), BI_SPECIAL_NONE);
2504 bi_instr *fixed_pt = bi_f32_to_s32_to(b, bi_temp(b->shader), scale);
2505 fixed_pt->round = BI_ROUND_NONE; // XXX
2506
2507 /* Compute the result for the fixed-point input, but pass along
2508 * the floating-point scale for correct NaN propagation */
2509 bi_fexp_f32_to(b, dst, fixed_pt->dest[0], scale);
2510 }
2511
2512 static void
2513 bi_lower_flog2_32(bi_builder *b, bi_index dst, bi_index s0)
2514 {
2515 /* s0 = a1 * 2^e, with a1 in [0.75, 1.5) */
2516 bi_index a1 = bi_frexpm_f32(b, s0, true, false);
2517 bi_index ei = bi_frexpe_f32(b, s0, true, false);
2518 bi_index ef = bi_s32_to_f32(b, ei);
2519
2520 /* xt estimates -log(r1), a coarse approximation of log(a1) */
2521 bi_index r1 = bi_flog_table_f32(b, s0, BI_MODE_RED, BI_PRECISION_NONE);
2522 bi_index xt = bi_flog_table_f32(b, s0, BI_MODE_BASE2, BI_PRECISION_NONE);
2523
2524 /* log(s0) = log(a1 * 2^e) = e + log(a1) = e + log(a1 * r1) -
2525 * log(r1), so let x1 = e - log(r1) ~= e + xt and x2 = log(a1 * r1),
2526 * and then log(s0) = x1 + x2 */
2527 bi_index x1 = bi_fadd_f32(b, ef, xt);
2528
2529 /* Since a1 * r1 is close to 1, x2 = log(a1 * r1) may be computed by
2530 * polynomial approximation around 1. The series is expressed around
2531 * 1, so set y = (a1 * r1) - 1.0 */
2532 bi_index y = bi_fma_f32(b, a1, r1, bi_imm_f32(-1.0));
2533
2534 /* x2 = log_2(1 + y) = log_e(1 + y) * (1/log_e(2)), so approximate
2535 * log_e(1 + y) by the Taylor series (lower precision than the blob):
2536 * y - y^2/2 + O(y^3) = y(1 - y/2) + O(y^3) */
2537 bi_index loge =
2538 bi_fmul_f32(b, y, bi_fma_f32(b, y, bi_imm_f32(-0.5), bi_imm_f32(1.0)));
2539
2540 bi_index x2 = bi_fmul_f32(b, loge, bi_imm_f32(1.0 / logf(2.0)));
2541
2542 /* log(s0) = x1 + x2 */
2543 bi_fadd_f32_to(b, dst, x1, x2);
2544 }
2545
2546 static void
2547 bi_flog2_32(bi_builder *b, bi_index dst, bi_index s0)
2548 {
2549 bi_index frexp = bi_frexpe_f32(b, s0, true, false);
2550 bi_index frexpi = bi_s32_to_f32(b, frexp);
2551 bi_index add = bi_fadd_lscale_f32(b, bi_imm_f32(-1.0f), s0);
2552 bi_fma_f32_to(b, dst, bi_flogd_f32(b, s0), add, frexpi);
2553 }
2554
2555 static void
2556 bi_lower_fpow_32(bi_builder *b, bi_index dst, bi_index base, bi_index exp)
2557 {
2558 bi_index log2_base = bi_null();
2559
2560 if (base.type == BI_INDEX_CONSTANT) {
2561 log2_base = bi_imm_f32(log2f(uif(base.value)));
2562 } else {
2563 log2_base = bi_temp(b->shader);
2564 bi_lower_flog2_32(b, log2_base, base);
2565 }
2566
2567 return bi_lower_fexp2_32(b, dst, bi_fmul_f32(b, exp, log2_base));
2568 }
2569
2570 static void
2571 bi_fpow_32(bi_builder *b, bi_index dst, bi_index base, bi_index exp)
2572 {
2573 bi_index log2_base = bi_null();
2574
2575 if (base.type == BI_INDEX_CONSTANT) {
2576 log2_base = bi_imm_f32(log2f(uif(base.value)));
2577 } else {
2578 log2_base = bi_temp(b->shader);
2579 bi_flog2_32(b, log2_base, base);
2580 }
2581
2582 return bi_fexp_32(b, dst, exp, log2_base);
2583 }
2584
2585 /* Bifrost has extremely coarse tables for approximating sin/cos, accessible as
2586 * FSIN/COS_TABLE.u6, which multiplies the bottom 6-bits by pi/32 and
2587 * calculates the results. We use them to calculate sin/cos via a Taylor
2588 * approximation:
2589 *
2590 * f(x + e) = f(x) + e f'(x) + (e^2)/2 f''(x)
2591 * sin(x + e) = sin(x) + e cos(x) - (e^2)/2 sin(x)
2592 * cos(x + e) = cos(x) - e sin(x) - (e^2)/2 cos(x)
2593 */
2594
2595 #define TWO_OVER_PI bi_imm_f32(2.0f / 3.14159f)
2596 #define MPI_OVER_TWO bi_imm_f32(-3.14159f / 2.0)
2597 #define SINCOS_BIAS bi_imm_u32(0x49400000)
2598
2599 static void
2600 bi_lower_fsincos_32(bi_builder *b, bi_index dst, bi_index s0, bool cos)
2601 {
2602 /* bottom 6-bits of result times pi/32 approximately s0 mod 2pi */
2603 bi_index x_u6 = bi_fma_f32(b, s0, TWO_OVER_PI, SINCOS_BIAS);
2604
2605 /* Approximate domain error (small) */
2606 bi_index e = bi_fma_f32(b, bi_fadd_f32(b, x_u6, bi_neg(SINCOS_BIAS)),
2607 MPI_OVER_TWO, s0);
2608
2609 /* Lookup sin(x), cos(x) */
2610 bi_index sinx = bi_fsin_table_u6(b, x_u6, false);
2611 bi_index cosx = bi_fcos_table_u6(b, x_u6, false);
2612
2613 /* e^2 / 2 */
2614 bi_index e2_over_2 =
2615 bi_fma_rscale_f32(b, e, e, bi_negzero(), bi_imm_u32(-1), BI_SPECIAL_NONE);
2616
2617 /* (-e^2)/2 f''(x) */
2618 bi_index quadratic =
2619 bi_fma_f32(b, bi_neg(e2_over_2), cos ? cosx : sinx, bi_negzero());
2620
2621 /* e f'(x) - (e^2/2) f''(x) */
2622 bi_instr *I = bi_fma_f32_to(b, bi_temp(b->shader), e,
2623 cos ? bi_neg(sinx) : cosx, quadratic);
2624 I->clamp = BI_CLAMP_CLAMP_M1_1;
2625
2626 /* f(x) + e f'(x) - (e^2/2) f''(x) */
2627 bi_fadd_f32_to(b, dst, I->dest[0], cos ? cosx : sinx);
2628 }
2629
2630 static enum bi_cmpf
2631 bi_translate_cmpf(nir_op op)
2632 {
2633 switch (op) {
2634 case nir_op_ieq8:
2635 case nir_op_ieq16:
2636 case nir_op_ieq32:
2637 case nir_op_feq16:
2638 case nir_op_feq32:
2639 return BI_CMPF_EQ;
2640
2641 case nir_op_ine8:
2642 case nir_op_ine16:
2643 case nir_op_ine32:
2644 case nir_op_fneu16:
2645 case nir_op_fneu32:
2646 return BI_CMPF_NE;
2647
2648 case nir_op_ilt8:
2649 case nir_op_ilt16:
2650 case nir_op_ilt32:
2651 case nir_op_flt16:
2652 case nir_op_flt32:
2653 case nir_op_ult8:
2654 case nir_op_ult16:
2655 case nir_op_ult32:
2656 return BI_CMPF_LT;
2657
2658 case nir_op_ige8:
2659 case nir_op_ige16:
2660 case nir_op_ige32:
2661 case nir_op_fge16:
2662 case nir_op_fge32:
2663 case nir_op_uge8:
2664 case nir_op_uge16:
2665 case nir_op_uge32:
2666 return BI_CMPF_GE;
2667
2668 default:
2669 UNREACHABLE("invalid comparison");
2670 }
2671 }
2672
2673 static bool
2674 bi_nir_is_replicated(nir_alu_src *src)
2675 {
2676 for (unsigned i = 1; i < nir_src_num_components(src->src); ++i) {
2677 if (src->swizzle[0] != src->swizzle[i])
2678 return false;
2679 }
2680
2681 return true;
2682 }
2683
2684 static void
2685 bi_emit_alu(bi_builder *b, nir_alu_instr *instr)
2686 {
2687 bi_index dst = bi_def_index(&instr->def);
2688 unsigned srcs = nir_op_infos[instr->op].num_inputs;
2689 unsigned sz = instr->def.bit_size;
2690 unsigned comps = instr->def.num_components;
2691 unsigned src_sz = srcs > 0 ? nir_src_bit_size(instr->src[0].src) : 0;
2692
2693 /* Indicate scalarness */
2694 if (sz == 16 && comps == 1)
2695 dst.swizzle = BI_SWIZZLE_H00;
2696
2697 /* First, match against the various moves in NIR. These are
2698 * special-cased because they can operate on vectors even after
2699 * lowering ALU to scalar. For Bifrost, bi_alu_src_index assumes the
2700 * instruction is no "bigger" than SIMD-within-a-register. These moves
2701 * are the exceptions that need to handle swizzles specially. */
2702
2703 switch (instr->op) {
2704 case nir_op_mov: {
2705 bi_index idx = bi_src_index(&instr->src[0].src);
2706 bi_index unoffset_srcs[4] = {idx, idx, idx, idx};
2707
2708 unsigned channels[4] = {
2709 comps > 0 ? instr->src[0].swizzle[0] : 0,
2710 comps > 1 ? instr->src[0].swizzle[1] : 0,
2711 comps > 2 ? instr->src[0].swizzle[2] : 0,
2712 comps > 3 ? instr->src[0].swizzle[3] : 0,
2713 };
2714
2715 bi_make_vec_to(b, dst, unoffset_srcs, channels, comps, src_sz);
2716 return;
2717 }
2718
2719 case nir_op_vec2:
2720 case nir_op_vec3:
2721 case nir_op_vec4:
2722 case nir_op_vec8:
2723 case nir_op_vec16:
2724 case nir_op_pack_32_2x16_split:
2725 case nir_op_pack_32_4x8_split:
2726 case nir_op_pack_64_2x32_split: {
2727 bi_index unoffset_srcs[16] = {bi_null()};
2728 unsigned channels[16] = {0};
2729
2730 for (unsigned i = 0; i < srcs; ++i) {
2731 assert(nir_src_bit_size(instr->src[i].src) == src_sz);
2732 unoffset_srcs[i] = bi_src_index(&instr->src[i].src);
2733 channels[i] = instr->src[i].swizzle[0];
2734 }
2735
2736 bi_make_vec_to(b, dst, unoffset_srcs, channels, srcs, src_sz);
2737 return;
2738 }
2739
2740 case nir_op_pack_32_2x16:
2741 case nir_op_pack_32_4x8:
2742 case nir_op_pack_64_2x32:
2743 case nir_op_pack_64_4x16: {
2744 bi_index idx = bi_src_index(&instr->src[0].src);
2745 bi_index unoffset_srcs[4] = { idx, idx, idx, idx };
2746
2747 unsigned src_comps = nir_op_infos[instr->op].input_sizes[0];
2748 assert(src_sz * src_comps == sz);
2749
2750 unsigned channels[4] = { 0 };
2751 for (uint32_t i = 0; i < src_comps; i++)
2752 channels[i] = instr->src[0].swizzle[i];
2753
2754 bi_make_vec_to(b, dst, unoffset_srcs, channels, src_comps, src_sz);
2755 return;
2756 }
2757
2758 case nir_op_unpack_32_2x16:
2759 case nir_op_unpack_32_4x8:
2760 case nir_op_unpack_64_2x32:
2761 case nir_op_unpack_64_4x16: {
2762 assert(comps * sz == src_sz);
2763 bi_index idx = bi_src_index(&instr->src[0].src);
2764 unsigned chan = instr->src[0].swizzle[0];
2765 bi_make_vec_to(b, dst, &idx, &chan, 1, src_sz);
2766 return;
2767 }
2768
2769 case nir_op_unpack_32_2x16_split_x:
2770 case nir_op_unpack_32_2x16_split_y: {
2771 assert(comps <= 2);
2772
2773 bi_index idx = bi_src_index(&instr->src[0].src);
2774 bi_index srcs[2] = {idx, idx};
2775
2776 unsigned offset = instr->op == nir_op_unpack_32_2x16_split_x ? 0 : 1;
2777 unsigned channels[2] = {
2778 comps > 0 ? instr->src[0].swizzle[0] * 2 + offset : 0,
2779 comps > 1 ? instr->src[0].swizzle[1] * 2 + offset : 0,
2780 };
2781
2782 bi_make_vec_to(b, dst, srcs, channels, comps, 16);
2783 return;
2784 }
2785
2786 case nir_op_unpack_64_2x32_split_x:
2787 case nir_op_unpack_64_2x32_split_y: {
2788 bi_index idx = bi_src_index(&instr->src[0].src);
2789
2790 unsigned offset = instr->op == nir_op_unpack_64_2x32_split_x ? 0 : 1;
2791 unsigned chan = instr->src[0].swizzle[0] * 2 + offset;
2792
2793 bi_mov_i32_to(b, dst, bi_extract(b, idx, chan));
2794 return;
2795 }
2796
2797 case nir_op_pack_uvec2_to_uint: {
2798 bi_index src = bi_src_index(&instr->src[0].src);
2799
2800 assert(sz == 32 && src_sz == 32);
2801 bi_mkvec_v2i16_to(
2802 b, dst, bi_half(bi_extract(b, src, instr->src[0].swizzle[0]), false),
2803 bi_half(bi_extract(b, src, instr->src[0].swizzle[1]), false));
2804 return;
2805 }
2806
2807 case nir_op_pack_uvec4_to_uint: {
2808 bi_index src = bi_src_index(&instr->src[0].src);
2809
2810 assert(sz == 32 && src_sz == 32);
2811
2812 bi_index srcs[4] = {
2813 bi_extract(b, src, instr->src[0].swizzle[0]),
2814 bi_extract(b, src, instr->src[0].swizzle[1]),
2815 bi_extract(b, src, instr->src[0].swizzle[2]),
2816 bi_extract(b, src, instr->src[0].swizzle[3]),
2817 };
2818 unsigned channels[4] = {0};
2819 bi_make_vec_to(b, dst, srcs, channels, 4, 8);
2820 return;
2821 }
2822
2823 case nir_op_f2f16:
2824 case nir_op_f2f16_rtz:
2825 case nir_op_f2f16_rtne: {
2826 /* Starting with v11, we don't have V2XXX_TO_V2F16, this should have been
2827 * lowered before if there is more than one components */
2828 assert(b->shader->arch < 11 || comps == 1);
2829 assert(src_sz == 32);
2830 bi_index idx = bi_src_index(&instr->src[0].src);
2831 bi_index s0 = bi_extract(b, idx, instr->src[0].swizzle[0]);
2832
2833 bi_instr *I;
2834
2835 /* Use V2F32_TO_V2F16 if vectorized */
2836 if (comps == 2) {
2837 /* Starting with v11, we don't have V2F32_TO_V2F16, this should have
2838 * been lowered before if there is more than one components */
2839 assert(b->shader->arch < 11);
2840 bi_index s1 = bi_extract(b, idx, instr->src[0].swizzle[1]);
2841 I = bi_v2f32_to_v2f16_to(b, dst, s0, s1);
2842 } else {
2843 assert(comps == 1);
2844 I = bi_f32_to_f16_to(b, dst, s0);
2845 }
2846
2847 /* Override rounding if explicitly requested. Otherwise, the
2848 * default rounding mode is selected by the builder. Depending
2849 * on the float controls required by the shader, the default
2850 * mode may not be nearest-even.
2851 */
2852 if (instr->op == nir_op_f2f16_rtz)
2853 I->round = BI_ROUND_RTZ;
2854 else if (instr->op == nir_op_f2f16_rtne)
2855 I->round = BI_ROUND_NONE; /* Nearest even */
2856
2857 return;
2858 }
2859
2860 /* Vectorized downcasts */
2861 case nir_op_u2u16:
2862 case nir_op_i2i16: {
2863 if (!(src_sz == 32 && comps == 2))
2864 break;
2865
2866 bi_index idx = bi_src_index(&instr->src[0].src);
2867 bi_index s0 = bi_extract(b, idx, instr->src[0].swizzle[0]);
2868 bi_index s1 = bi_extract(b, idx, instr->src[0].swizzle[1]);
2869
2870 bi_mkvec_v2i16_to(b, dst, bi_half(s0, false), bi_half(s1, false));
2871 return;
2872 }
2873
2874 /* Pre-v11, we can get vector i2f32 by lowering 32-bit vector i2f16 to
2875 * i2f32 + f2f16 in bifrost_nir_lower_algebraic_late, which runs after
2876 * nir_opt_vectorize. We don't scalarize i2f32 earlier because we have
2877 * vector V2F16_TO_V2F32. */
2878 case nir_op_i2f32:
2879 case nir_op_u2f32: {
2880 if (!(src_sz == 32 && comps == 2))
2881 break;
2882
2883 assert(b->shader->arch < 11);
2884
2885 nir_alu_src *src = &instr->src[0];
2886 bi_index idx = bi_src_index(&src->src);
2887 bi_index s0 = bi_extract(b, idx, src->swizzle[0]);
2888 bi_index s1 = bi_extract(b, idx, src->swizzle[1]);
2889
2890 bi_index d0, d1;
2891 if (instr->op == nir_op_i2f32) {
2892 d0 = bi_s32_to_f32(b, s0);
2893 d1 = bi_s32_to_f32(b, s1);
2894 } else {
2895 d0 = bi_u32_to_f32(b, s0);
2896 d1 = bi_u32_to_f32(b, s1);
2897 }
2898
2899 bi_collect_v2i32_to(b, dst, d0, d1);
2900
2901 return;
2902 }
2903
2904 case nir_op_i2i8:
2905 case nir_op_u2u8: {
2906 /* Acts like an 8-bit swizzle */
2907 bi_index idx = bi_src_index(&instr->src[0].src);
2908 unsigned factor = src_sz / 8;
2909 unsigned chan[4] = {0};
2910 bi_index idxs[4];
2911
2912 for (unsigned i = 0; i < comps; ++i) {
2913 idxs[i] = idx;
2914 chan[i] = instr->src[0].swizzle[i] * factor;
2915 }
2916
2917 bi_make_vec_to(b, dst, idxs, chan, comps, 8);
2918 return;
2919 }
2920
2921 default:
2922 break;
2923 }
2924
2925 bi_index s0 =
2926 srcs > 0 ? bi_alu_src_index(b, instr->src[0], comps) : bi_null();
2927 bi_index s1 =
2928 srcs > 1 ? bi_alu_src_index(b, instr->src[1], comps) : bi_null();
2929 bi_index s2 =
2930 srcs > 2 ? bi_alu_src_index(b, instr->src[2], comps) : bi_null();
2931
2932 switch (instr->op) {
2933 case nir_op_ffma:
2934 bi_fma_to(b, sz, dst, s0, s1, s2);
2935 break;
2936
2937 case nir_op_fmul:
2938 bi_fma_to(b, sz, dst, s0, s1, bi_negzero());
2939 break;
2940
2941 case nir_op_fadd:
2942 bi_fadd_to(b, sz, dst, s0, s1);
2943 break;
2944
2945 case nir_op_fsat: {
2946 bi_instr *I = bi_fclamp_to(b, sz, dst, s0);
2947 I->clamp = BI_CLAMP_CLAMP_0_1;
2948 break;
2949 }
2950
2951 case nir_op_fsat_signed: {
2952 bi_instr *I = bi_fclamp_to(b, sz, dst, s0);
2953 I->clamp = BI_CLAMP_CLAMP_M1_1;
2954 break;
2955 }
2956
2957 case nir_op_fclamp_pos: {
2958 bi_instr *I = bi_fclamp_to(b, sz, dst, s0);
2959 I->clamp = BI_CLAMP_CLAMP_0_INF;
2960 break;
2961 }
2962
2963 case nir_op_fneg:
2964 bi_fabsneg_to(b, sz, dst, bi_neg(s0));
2965 break;
2966
2967 case nir_op_fabs:
2968 bi_fabsneg_to(b, sz, dst, bi_abs(s0));
2969 break;
2970
2971 case nir_op_fsin:
2972 bi_lower_fsincos_32(b, dst, s0, false);
2973 break;
2974
2975 case nir_op_fcos:
2976 bi_lower_fsincos_32(b, dst, s0, true);
2977 break;
2978
2979 case nir_op_fexp2:
2980 assert(sz == 32); /* should've been lowered */
2981
2982 if (b->shader->quirks & BIFROST_NO_FP32_TRANSCENDENTALS)
2983 bi_lower_fexp2_32(b, dst, s0);
2984 else
2985 bi_fexp_32(b, dst, s0, bi_imm_f32(1.0f));
2986
2987 break;
2988
2989 case nir_op_flog2:
2990 assert(sz == 32); /* should've been lowered */
2991
2992 if (b->shader->quirks & BIFROST_NO_FP32_TRANSCENDENTALS)
2993 bi_lower_flog2_32(b, dst, s0);
2994 else
2995 bi_flog2_32(b, dst, s0);
2996
2997 break;
2998
2999 case nir_op_fpow:
3000 assert(sz == 32); /* should've been lowered */
3001
3002 if (b->shader->quirks & BIFROST_NO_FP32_TRANSCENDENTALS)
3003 bi_lower_fpow_32(b, dst, s0, s1);
3004 else
3005 bi_fpow_32(b, dst, s0, s1);
3006
3007 break;
3008
3009 case nir_op_frexp_exp:
3010 /* v11 removed FREXPE.v2f16 */
3011 assert(src_sz == 32 || (b->shader->arch < 11 && src_sz == 16));
3012 bi_frexpe_to(b, sz, dst, s0, false, false);
3013 break;
3014
3015 case nir_op_frexp_sig:
3016 /* v11 removed FREXPM.v2f16 */
3017 assert(src_sz == 32 || (b->shader->arch < 11 && src_sz == 16));
3018 bi_frexpm_to(b, sz, dst, s0, false, false);
3019 break;
3020
3021 case nir_op_ldexp:
3022 assert(sz == 32 && "should be lowered");
3023 bi_ldexp_to(b, sz, dst, s0, s1);
3024 break;
3025
3026 case nir_op_ldexp16_pan:
3027 assert(sz == 16);
3028 bi_ldexp_to(b, sz, dst, s0, s1);
3029 break;
3030
3031 case nir_op_b8csel:
3032 assert(sz == 8);
3033 bi_mux_v4i8_to(b, dst, s2, s1, s0, BI_MUX_INT_ZERO);
3034 break;
3035
3036 case nir_op_b16csel:
3037 assert(sz == 16);
3038 bi_mux_v2i16_to(b, dst, s2, s1, s0, BI_MUX_INT_ZERO);
3039 break;
3040
3041 case nir_op_b32csel:
3042 assert(sz == 32);
3043 bi_mux_i32_to(b, dst, s2, s1, s0, BI_MUX_INT_ZERO);
3044 break;
3045
3046 case nir_op_extract_u8:
3047 case nir_op_extract_i8: {
3048 if (sz == 32) {
3049 assert(comps == 1 && "should be scalarized");
3050 unsigned byte = nir_alu_src_as_uint(instr->src[1]);
3051 if (instr->op == nir_op_extract_i8)
3052 bi_s8_to_s32_to(b, dst, bi_byte(s0, byte));
3053 else
3054 bi_u8_to_u32_to(b, dst, bi_byte(s0, byte));
3055 } else if (sz == 16) {
3056 assert(comps <= 2);
3057 const unsigned byte_x = nir_alu_src_comp_as_uint(instr->src[1], 0);
3058 const unsigned byte_y = comps == 1 ? byte_x :
3059 nir_alu_src_comp_as_uint(instr->src[1], 1);
3060 assert(byte_x < 2 && byte_y < 2);
3061
3062 /* Construct the swizzle for the select. We know it's valid because
3063 * it's guaranteed to be a BXXYY swizzle, even when composed with
3064 * s0.swizzle.
3065 */
3066 enum bi_swizzle swizzle = BI_SWIZZLE_H01;
3067 const unsigned bytes[4] = { byte_x, byte_x, 2 + byte_y, 2 + byte_y };
3068 bool valid = bi_swizzle_from_byte_channels(bytes, &swizzle);
3069 assert(valid);
3070
3071 valid = bi_try_compose_swizzles(&swizzle, swizzle, s0.swizzle);
3072 assert(valid);
3073
3074 bi_index src = s0;
3075 src.swizzle = swizzle;
3076
3077 if (instr->op == nir_op_extract_i8)
3078 bi_v2s8_to_v2s16_to(b, dst, src);
3079 else
3080 bi_v2u8_to_v2u16_to(b, dst, src);
3081 } else {
3082 UNREACHABLE("should be lowered");
3083 }
3084 break;
3085 }
3086
3087 case nir_op_extract_u16:
3088 case nir_op_extract_i16: {
3089 assert(comps == 1 && "should be scalarized");
3090 assert(src_sz == 32 && "should be lowered");
3091 unsigned half = nir_alu_src_as_uint(instr->src[1]);
3092 assert(half == 0 || half == 1);
3093
3094 if (instr->op == nir_op_extract_i16)
3095 bi_s16_to_s32_to(b, dst, bi_half(s0, half));
3096 else
3097 bi_u16_to_u32_to(b, dst, bi_half(s0, half));
3098 break;
3099 }
3100
3101 case nir_op_insert_u16: {
3102 assert(comps == 1 && "should be scalarized");
3103 unsigned half = nir_alu_src_as_uint(instr->src[1]);
3104 assert(half == 0 || half == 1);
3105
3106 if (half == 0)
3107 bi_u16_to_u32_to(b, dst, bi_half(s0, 0));
3108 else
3109 bi_mkvec_v2i16_to(b, dst, bi_imm_u16(0), bi_half(s0, 0));
3110 break;
3111 }
3112
3113 case nir_op_pack_half_2x16_split:
3114 /* On v11+, V2F32_TO_V2F16 is gone. This should be lowered in
3115 * bifrost_nir_lower_algebraic_late. */
3116 assert(b->shader->arch < 11);
3117
3118 bi_v2f32_to_v2f16_to(b, dst, s0, s1);
3119 break;
3120
3121 case nir_op_ishl:
3122 bi_lshift_or_to(b, sz, dst, s0, bi_zero(), bi_byte(s1, 0));
3123 break;
3124 case nir_op_ushr:
3125 bi_rshift_or_to(b, sz, dst, s0, bi_zero(), bi_byte(s1, 0), false);
3126 break;
3127
3128 case nir_op_ishr:
3129 if (b->shader->arch >= 9)
3130 bi_rshift_or_to(b, sz, dst, s0, bi_zero(), bi_byte(s1, 0), true);
3131 else
3132 bi_arshift_to(b, sz, dst, s0, bi_null(), bi_byte(s1, 0));
3133 break;
3134
3135 case nir_op_imin:
3136 case nir_op_umin:
3137 bi_csel_to(b, nir_op_infos[instr->op].input_types[0], sz, dst, s0, s1, s0,
3138 s1, BI_CMPF_LT);
3139 break;
3140
3141 case nir_op_imax:
3142 case nir_op_umax:
3143 bi_csel_to(b, nir_op_infos[instr->op].input_types[0], sz, dst, s0, s1, s0,
3144 s1, BI_CMPF_GT);
3145 break;
3146
3147 case nir_op_f2f32:
3148 bi_f16_to_f32_to(b, dst, s0);
3149 break;
3150
3151 case nir_op_fquantize2f16: {
3152 bi_instr *f16 =
3153 bi_f32_to_f16_to(b, bi_half(bi_temp(b->shader), false), s0);
3154
3155 if (b->shader->arch < 9) {
3156 /* Bifrost has psuedo-ftz on conversions, that is lowered to an ftz
3157 * flag in the clause header */
3158 f16->ftz = true;
3159 } else {
3160 /* Valhall doesn't have clauses, and uses a separate flush
3161 * instruction */
3162 f16 = bi_flush_to(b, 16, bi_half(bi_temp(b->shader), false), f16->dest[0]);
3163 f16->ftz = true;
3164 }
3165
3166 bi_instr *f32 = bi_f16_to_f32_to(b, dst, f16->dest[0]);
3167
3168 if (b->shader->arch < 9)
3169 f32->ftz = true;
3170
3171 break;
3172 }
3173
3174 case nir_op_f2i32:
3175 /* v11 removed F16_TO_S32 */
3176 assert(src_sz == 32 || (b->shader->arch < 11 && src_sz == 16));
3177
3178 if (src_sz == 32)
3179 bi_f32_to_s32_to(b, dst, s0);
3180 else
3181 bi_f16_to_s32_to(b, dst, s0);
3182 break;
3183
3184 /* Note 32-bit sources => no vectorization, so 32-bit works */
3185 case nir_op_f2u16:
3186 /* v11 removed V2F16_TO_V2U16 */
3187 assert(src_sz == 32 || (b->shader->arch < 11 && src_sz == 16));
3188
3189 if (src_sz == 32)
3190 bi_f32_to_u32_to(b, dst, s0);
3191 else
3192 bi_v2f16_to_v2u16_to(b, dst, s0);
3193 break;
3194
3195 case nir_op_f2i16:
3196 /* v11 removed V2F16_TO_V2S16 */
3197 assert(src_sz == 32 || (b->shader->arch < 11 && src_sz == 16));
3198
3199 if (src_sz == 32)
3200 bi_f32_to_s32_to(b, dst, s0);
3201 else
3202 bi_v2f16_to_v2s16_to(b, dst, s0);
3203 break;
3204
3205 case nir_op_f2u32:
3206 /* v11 removed F16_TO_U32 */
3207 assert(src_sz == 32 || (b->shader->arch < 11 && src_sz == 16));
3208
3209 if (src_sz == 32)
3210 bi_f32_to_u32_to(b, dst, s0);
3211 else
3212 bi_f16_to_u32_to(b, dst, s0);
3213 break;
3214
3215 case nir_op_u2f16:
3216 /* Starting with v11, we don't have V2XXX_TO_V2F16, this should have been
3217 * lowered before by algebraic. */
3218 assert(b->shader->arch < 11);
3219
3220 /* V2I32_TO_V2F16 does not exist */
3221 assert((src_sz == 16 || src_sz == 8) && "should be lowered");
3222
3223 if (src_sz == 16)
3224 bi_v2u16_to_v2f16_to(b, dst, s0);
3225 else if (src_sz == 8)
3226 bi_v2u8_to_v2f16_to(b, dst, bi_swiz_b01(s0));
3227 break;
3228
3229 case nir_op_u2f32:
3230 /* v11 removed U16_TO_F32 and U8_TO_F32 */
3231 assert(src_sz == 32 || (b->shader->arch < 11 && (src_sz == 16 || src_sz == 8)));
3232
3233 if (src_sz == 32)
3234 bi_u32_to_f32_to(b, dst, s0);
3235 else if (src_sz == 16)
3236 bi_u16_to_f32_to(b, dst, s0);
3237 else
3238 bi_u8_to_f32_to(b, dst, s0);
3239 break;
3240
3241 case nir_op_i2f16:
3242 /* Starting with v11, we don't have V2XXX_TO_V2F16, this should have been
3243 * lowered before by algebraic. */
3244 assert(b->shader->arch < 11);
3245
3246 /* V2I32_TO_V2F16 does not exist */
3247 assert((src_sz == 16 || src_sz == 8) && "should be lowered");
3248
3249 if (src_sz == 16)
3250 bi_v2s16_to_v2f16_to(b, dst, s0);
3251 else if (src_sz == 8)
3252 bi_v2s8_to_v2f16_to(b, dst, bi_swiz_b01(s0));
3253 break;
3254
3255 case nir_op_i2f32:
3256 /* v11 removed S16_TO_F32 and S8_TO_F32 */
3257 assert(src_sz == 32 || (b->shader->arch < 11 && (src_sz == 16 || src_sz == 8)));
3258
3259 if (src_sz == 32)
3260 bi_s32_to_f32_to(b, dst, s0);
3261 else if (src_sz == 16)
3262 bi_s16_to_f32_to(b, dst, s0);
3263 else if (src_sz == 8)
3264 bi_s8_to_f32_to(b, dst, s0);
3265 break;
3266
3267 case nir_op_i2i32:
3268 assert(src_sz == 32 || src_sz == 16 || src_sz == 8);
3269
3270 if (src_sz == 32)
3271 bi_mov_i32_to(b, dst, s0);
3272 else if (src_sz == 16)
3273 bi_s16_to_s32_to(b, dst, s0);
3274 else if (src_sz == 8)
3275 bi_s8_to_s32_to(b, dst, s0);
3276 break;
3277
3278 case nir_op_u2u32:
3279 assert(src_sz == 32 || src_sz == 16 || src_sz == 8);
3280
3281 if (src_sz == 32)
3282 bi_mov_i32_to(b, dst, s0);
3283 else if (src_sz == 16)
3284 bi_u16_to_u32_to(b, dst, s0);
3285 else if (src_sz == 8)
3286 bi_u8_to_u32_to(b, dst, s0);
3287
3288 break;
3289
3290 case nir_op_i2i16:
3291 assert(src_sz == 8 || src_sz == 32);
3292
3293 if (src_sz == 8)
3294 bi_v2s8_to_v2s16_to(b, dst, bi_swiz_b01(s0));
3295 else
3296 bi_mov_i32_to(b, dst, s0);
3297 break;
3298
3299 case nir_op_u2u16:
3300 assert(src_sz == 8 || src_sz == 32);
3301
3302 if (src_sz == 8)
3303 bi_v2u8_to_v2u16_to(b, dst, bi_swiz_b01(s0));
3304 else
3305 bi_mov_i32_to(b, dst, s0);
3306 break;
3307
3308 case nir_op_b2i8:
3309 case nir_op_b2i16:
3310 case nir_op_b2i32:
3311 bi_mux_to(b, sz, dst, bi_imm_u8(0), bi_imm_uintN(1, sz), s0,
3312 BI_MUX_INT_ZERO);
3313 break;
3314
3315 case nir_op_ieq8:
3316 case nir_op_ine8:
3317 case nir_op_ilt8:
3318 case nir_op_ige8:
3319 case nir_op_ieq16:
3320 case nir_op_ine16:
3321 case nir_op_ilt16:
3322 case nir_op_ige16:
3323 case nir_op_ieq32:
3324 case nir_op_ine32:
3325 case nir_op_ilt32:
3326 case nir_op_ige32:
3327 bi_icmp_to(b, nir_type_int, sz, dst, s0, s1, bi_translate_cmpf(instr->op),
3328 BI_RESULT_TYPE_M1);
3329 break;
3330
3331 case nir_op_ult8:
3332 case nir_op_uge8:
3333 case nir_op_ult16:
3334 case nir_op_uge16:
3335 case nir_op_ult32:
3336 case nir_op_uge32:
3337 bi_icmp_to(b, nir_type_uint, sz, dst, s0, s1,
3338 bi_translate_cmpf(instr->op), BI_RESULT_TYPE_M1);
3339 break;
3340
3341 case nir_op_feq32:
3342 case nir_op_feq16:
3343 case nir_op_flt32:
3344 case nir_op_flt16:
3345 case nir_op_fge32:
3346 case nir_op_fge16:
3347 case nir_op_fneu32:
3348 case nir_op_fneu16:
3349 bi_fcmp_to(b, sz, dst, s0, s1, bi_translate_cmpf(instr->op),
3350 BI_RESULT_TYPE_M1);
3351 break;
3352
3353 case nir_op_fround_even:
3354 case nir_op_fceil:
3355 case nir_op_ffloor:
3356 case nir_op_ftrunc: {
3357 /* On v11+, FROUND.v2s16 is gone, we lower this in nir_lower_bit_size */
3358 assert(sz != 16 || b->shader->arch < 11);
3359
3360 enum bi_round round = bi_nir_round(instr->op);
3361
3362 /* On v11+, FROUND does not flush subnormals to zero even when configured
3363 * in the shader program header */
3364 if (b->shader->arch >= 11 &&
3365 (round == BI_ROUND_RTP || round == BI_ROUND_RTN) &&
3366 b->shader->ftz_fp32) {
3367 bi_instr *flush = bi_flush_to(b, 32, bi_temp(b->shader), s0);
3368 flush->ftz = true;
3369 s0 = flush->dest[0];
3370 }
3371
3372 bi_fround_to(b, sz, dst, s0, round);
3373 break;
3374 }
3375
3376 case nir_op_fmin:
3377 bi_fmin_to(b, sz, dst, s0, s1);
3378 break;
3379
3380 case nir_op_fmax:
3381 bi_fmax_to(b, sz, dst, s0, s1);
3382 break;
3383
3384 case nir_op_iadd:
3385 if (sz == 64) {
3386 assert(b->shader->arch >= 9);
3387 bi_shaddx_s64_to(b, dst, s0, s1, 0);
3388 bi_index dsts[4] = {bi_null(), bi_null(), bi_null(), bi_null()};
3389 bi_emit_split_i32(b, dsts, dst, 2);
3390 bi_cache_collect(b, dst, dsts, 2);
3391 } else
3392 bi_iadd_to(b, nir_type_int, sz, dst, s0, s1, false);
3393 break;
3394
3395 case nir_op_iadd_sat:
3396 bi_iadd_to(b, nir_type_int, sz, dst, s0, s1, true);
3397 break;
3398
3399 case nir_op_uadd_sat:
3400 bi_iadd_to(b, nir_type_uint, sz, dst, s0, s1, true);
3401 break;
3402
3403 case nir_op_ihadd:
3404 /* v11 removed HADD */
3405 assert(b->shader->arch < 11);
3406 bi_hadd_to(b, nir_type_int, sz, dst, s0, s1, BI_ROUND_RTN);
3407 break;
3408
3409 case nir_op_irhadd:
3410 /* v11 removed HADD */
3411 assert(b->shader->arch < 11);
3412 bi_hadd_to(b, nir_type_int, sz, dst, s0, s1, BI_ROUND_RTP);
3413 break;
3414
3415 case nir_op_uhadd:
3416 /* v11 removed HADD */
3417 assert(b->shader->arch < 11);
3418 bi_hadd_to(b, nir_type_uint, sz, dst, s0, s1, BI_ROUND_RTN);
3419 break;
3420
3421 case nir_op_urhadd:
3422 /* v11 removed HADD */
3423 assert(b->shader->arch < 11);
3424 bi_hadd_to(b, nir_type_uint, sz, dst, s0, s1, BI_ROUND_RTP);
3425 break;
3426
3427 case nir_op_ineg:
3428 bi_isub_to(b, nir_type_int, sz, dst, bi_zero(), s0, false);
3429 break;
3430
3431 case nir_op_isub:
3432 bi_isub_to(b, nir_type_int, sz, dst, s0, s1, false);
3433 break;
3434
3435 case nir_op_isub_sat:
3436 bi_isub_to(b, nir_type_int, sz, dst, s0, s1, true);
3437 break;
3438
3439 case nir_op_usub_sat:
3440 bi_isub_to(b, nir_type_uint, sz, dst, s0, s1, true);
3441 break;
3442
3443 case nir_op_imul:
3444 bi_imul_to(b, sz, dst, s0, s1);
3445 break;
3446
3447 case nir_op_iabs:
3448 bi_iabs_to(b, sz, dst, s0);
3449 break;
3450
3451 case nir_op_iand:
3452 bi_lshift_and_to(b, sz, dst, s0, s1, bi_imm_u8(0));
3453 break;
3454
3455 case nir_op_ior:
3456 bi_lshift_or_to(b, sz, dst, s0, s1, bi_imm_u8(0));
3457 break;
3458
3459 case nir_op_ixor:
3460 bi_lshift_xor_to(b, sz, dst, s0, s1, bi_imm_u8(0));
3461 break;
3462
3463 case nir_op_inot:
3464 bi_lshift_or_to(b, sz, dst, bi_zero(), bi_not(s0), bi_imm_u8(0));
3465 break;
3466
3467 case nir_op_frsq:
3468 if (sz == 32 && b->shader->quirks & BIFROST_NO_FP32_TRANSCENDENTALS)
3469 bi_lower_frsq_32(b, dst, s0);
3470 else
3471 bi_frsq_to(b, sz, dst, s0);
3472 break;
3473
3474 case nir_op_frcp:
3475 if (sz == 32 && b->shader->quirks & BIFROST_NO_FP32_TRANSCENDENTALS)
3476 bi_lower_frcp_32(b, dst, s0);
3477 else
3478 bi_frcp_to(b, sz, dst, s0);
3479 break;
3480
3481 case nir_op_uclz:
3482 bi_clz_to(b, sz, dst, s0, false);
3483 break;
3484
3485 case nir_op_bit_count:
3486 assert(sz == 32 && src_sz == 32 && "should've been lowered");
3487 bi_popcount_i32_to(b, dst, s0);
3488 break;
3489
3490 case nir_op_bitfield_reverse:
3491 assert(sz == 32 && src_sz == 32 && "should've been lowered");
3492 bi_bitrev_i32_to(b, dst, s0);
3493 break;
3494
3495 case nir_op_ufind_msb: {
3496 bi_index clz = bi_clz(b, src_sz, s0, false);
3497
3498 if (sz == 8)
3499 clz = bi_byte(clz, 0);
3500 else if (sz == 16)
3501 clz = bi_half(clz, false);
3502
3503 bi_isub_u32_to(b, dst, bi_imm_u32(src_sz - 1), clz, false);
3504 break;
3505 }
3506 case nir_op_udot_4x8_uadd_sat:
3507 case nir_op_udot_4x8_uadd: {
3508 assert(b->shader->arch >= 9);
3509 bi_idpadd_v4u8_to(b, dst, s0, s1, s2,
3510 instr->op == nir_op_udot_4x8_uadd_sat);
3511 break;
3512 }
3513 case nir_op_sdot_4x8_iadd_sat:
3514 case nir_op_sdot_4x8_iadd: {
3515 assert(b->shader->arch >= 9);
3516 bi_idpadd_v4s8_to(b, dst, s0, s1, s2,
3517 instr->op == nir_op_sdot_4x8_iadd_sat);
3518 break;
3519 }
3520
3521 default:
3522 fprintf(stderr, "Unhandled ALU op %s\n", nir_op_infos[instr->op].name);
3523 UNREACHABLE("Unknown ALU op");
3524 }
3525 }
3526
3527 /* Returns dimension with 0 special casing cubemaps. Shamelessly copied from
3528 * Midgard */
3529 static unsigned
3530 bifrost_tex_format(enum glsl_sampler_dim dim)
3531 {
3532 switch (dim) {
3533 case GLSL_SAMPLER_DIM_1D:
3534 case GLSL_SAMPLER_DIM_BUF:
3535 return 1;
3536
3537 case GLSL_SAMPLER_DIM_2D:
3538 case GLSL_SAMPLER_DIM_MS:
3539 case GLSL_SAMPLER_DIM_EXTERNAL:
3540 case GLSL_SAMPLER_DIM_RECT:
3541 case GLSL_SAMPLER_DIM_SUBPASS:
3542 case GLSL_SAMPLER_DIM_SUBPASS_MS:
3543 return 2;
3544
3545 case GLSL_SAMPLER_DIM_3D:
3546 return 3;
3547
3548 case GLSL_SAMPLER_DIM_CUBE:
3549 return 0;
3550
3551 default:
3552 UNREACHABLE("Unknown sampler dim type\n");
3553 }
3554 }
3555
3556 static enum bi_dimension
3557 valhall_tex_dimension(enum glsl_sampler_dim dim)
3558 {
3559 switch (dim) {
3560 case GLSL_SAMPLER_DIM_1D:
3561 case GLSL_SAMPLER_DIM_BUF:
3562 return BI_DIMENSION_1D;
3563
3564 case GLSL_SAMPLER_DIM_2D:
3565 case GLSL_SAMPLER_DIM_MS:
3566 case GLSL_SAMPLER_DIM_EXTERNAL:
3567 case GLSL_SAMPLER_DIM_RECT:
3568 case GLSL_SAMPLER_DIM_SUBPASS:
3569 case GLSL_SAMPLER_DIM_SUBPASS_MS:
3570 return BI_DIMENSION_2D;
3571
3572 case GLSL_SAMPLER_DIM_3D:
3573 return BI_DIMENSION_3D;
3574
3575 case GLSL_SAMPLER_DIM_CUBE:
3576 return BI_DIMENSION_CUBE;
3577
3578 default:
3579 UNREACHABLE("Unknown sampler dim type");
3580 }
3581 }
3582
3583 static enum bifrost_texture_format_full
3584 bi_texture_format(nir_alu_type T, enum bi_clamp clamp)
3585 {
3586 switch (T) {
3587 case nir_type_float16:
3588 return BIFROST_TEXTURE_FORMAT_F16 + clamp;
3589 case nir_type_float32:
3590 return BIFROST_TEXTURE_FORMAT_F32 + clamp;
3591 case nir_type_uint16:
3592 return BIFROST_TEXTURE_FORMAT_U16;
3593 case nir_type_int16:
3594 return BIFROST_TEXTURE_FORMAT_S16;
3595 case nir_type_uint32:
3596 return BIFROST_TEXTURE_FORMAT_U32;
3597 case nir_type_int32:
3598 return BIFROST_TEXTURE_FORMAT_S32;
3599 default:
3600 UNREACHABLE("Invalid type for texturing");
3601 }
3602 }
3603
3604 /* Array indices are specified as 32-bit uints, need to convert. In .z component
3605 * from NIR */
3606 static bi_index
3607 bi_emit_texc_array_index(bi_builder *b, bi_index idx, nir_alu_type T)
3608 {
3609 /* For (u)int we can just passthrough */
3610 nir_alu_type base = nir_alu_type_get_base_type(T);
3611 if (base == nir_type_int || base == nir_type_uint)
3612 return idx;
3613
3614 /* Otherwise we convert */
3615 assert(T == nir_type_float32);
3616
3617 /* OpenGL ES 3.2 specification section 8.14.2 ("Coordinate Wrapping and
3618 * Texel Selection") defines the layer to be taken from clamp(RNE(r),
3619 * 0, dt - 1). So we use round RTE, clamping is handled at the data
3620 * structure level */
3621
3622 bi_instr *I = bi_f32_to_u32_to(b, bi_temp(b->shader), idx);
3623 I->round = BI_ROUND_NONE;
3624 return I->dest[0];
3625 }
3626
3627 /* TEXC's explicit and bias LOD modes requires the LOD to be transformed to a
3628 * 16-bit 8:8 fixed-point format. We lower as:
3629 *
3630 * F32_TO_S32(clamp(x, -16.0, +16.0) * 256.0) & 0xFFFF =
3631 * MKVEC(F32_TO_S32(clamp(x * 1.0/16.0, -1.0, 1.0) * (16.0 * 256.0)), #0)
3632 */
3633
3634 static bi_index
3635 bi_emit_texc_lod_88(bi_builder *b, bi_index lod, bool fp16)
3636 {
3637 /* Precompute for constant LODs to avoid general constant folding */
3638 if (lod.type == BI_INDEX_CONSTANT) {
3639 uint32_t raw = lod.value;
3640 float x = fp16 ? _mesa_half_to_float(raw) : uif(raw);
3641 int32_t s32 = CLAMP(x, -16.0f, 16.0f) * 256.0f;
3642 return bi_imm_u32(s32 & 0xFFFF);
3643 }
3644
3645 /* Sort of arbitrary. Must be less than 128.0, greater than or equal to
3646 * the max LOD (16 since we cap at 2^16 texture dimensions), and
3647 * preferably small to minimize precision loss */
3648 const float max_lod = 16.0;
3649
3650 bi_instr *fsat =
3651 bi_fma_f32_to(b, bi_temp(b->shader), fp16 ? bi_half(lod, false) : lod,
3652 bi_imm_f32(1.0f / max_lod), bi_negzero());
3653
3654 fsat->clamp = BI_CLAMP_CLAMP_M1_1;
3655
3656 bi_index fmul =
3657 bi_fma_f32(b, fsat->dest[0], bi_imm_f32(max_lod * 256.0f), bi_negzero());
3658
3659 return bi_mkvec_v2i16(b, bi_half(bi_f32_to_s32(b, fmul), false),
3660 bi_imm_u16(0));
3661 }
3662
3663 /* FETCH takes a 32-bit staging register containing the LOD as an integer in
3664 * the bottom 16-bits and (if present) the cube face index in the top 16-bits.
3665 * TODO: Cube face.
3666 */
3667
3668 static bi_index
3669 bi_emit_texc_lod_cube(bi_builder *b, bi_index lod)
3670 {
3671 return bi_lshift_or_i32(b, lod, bi_zero(), bi_imm_u8(8));
3672 }
3673
3674 /* The hardware specifies texel offsets and multisample indices together as a
3675 * u8vec4 <offset, ms index>. By default all are zero, so if have either a
3676 * nonzero texel offset or a nonzero multisample index, we build a u8vec4 with
3677 * the bits we need and return that to be passed as a staging register. Else we
3678 * return 0 to avoid allocating a data register when everything is zero. */
3679
3680 static bi_index
3681 bi_emit_texc_offset_ms_index(bi_builder *b, nir_tex_instr *instr)
3682 {
3683 bi_index dest = bi_zero();
3684
3685 int offs_idx = nir_tex_instr_src_index(instr, nir_tex_src_offset);
3686 if (offs_idx >= 0 && !nir_src_is_zero(instr->src[offs_idx].src)) {
3687 unsigned nr = nir_src_num_components(instr->src[offs_idx].src);
3688 bi_index idx = bi_src_index(&instr->src[offs_idx].src);
3689 dest = bi_mkvec_v4i8(
3690 b, (nr > 0) ? bi_byte(bi_extract(b, idx, 0), 0) : bi_imm_u8(0),
3691 (nr > 1) ? bi_byte(bi_extract(b, idx, 1), 0) : bi_imm_u8(0),
3692 (nr > 2) ? bi_byte(bi_extract(b, idx, 2), 0) : bi_imm_u8(0),
3693 bi_imm_u8(0));
3694 }
3695
3696 int ms_idx = nir_tex_instr_src_index(instr, nir_tex_src_ms_index);
3697 if (ms_idx >= 0 && !nir_src_is_zero(instr->src[ms_idx].src)) {
3698 dest = bi_lshift_or_i32(b, bi_src_index(&instr->src[ms_idx].src), dest,
3699 bi_imm_u8(24));
3700 }
3701
3702 return dest;
3703 }
3704
3705 /*
3706 * Valhall specifies specifies texel offsets, multisample indices, and (for
3707 * fetches) LOD together as a u8vec4 <offset.xyz, LOD>, where the third
3708 * component is either offset.z or multisample index depending on context. Build
3709 * this register.
3710 */
3711 static bi_index
3712 bi_emit_valhall_offsets(bi_builder *b, nir_tex_instr *instr)
3713 {
3714 bi_index dest = bi_zero();
3715
3716 int offs_idx = nir_tex_instr_src_index(instr, nir_tex_src_offset);
3717 int ms_idx = nir_tex_instr_src_index(instr, nir_tex_src_ms_index);
3718 int lod_idx = nir_tex_instr_src_index(instr, nir_tex_src_lod);
3719
3720 /* Components 0-2: offsets */
3721 if (offs_idx >= 0 && !nir_src_is_zero(instr->src[offs_idx].src)) {
3722 unsigned nr = nir_src_num_components(instr->src[offs_idx].src);
3723 bi_index idx = bi_src_index(&instr->src[offs_idx].src);
3724
3725 /* No multisample index with 3D */
3726 assert((nr <= 2) || (ms_idx < 0));
3727
3728 /* Zero extend the Z byte so we can use it with MKVEC.v2i8 */
3729 bi_index z = (nr > 2)
3730 ? bi_mkvec_v2i8(b, bi_byte(bi_extract(b, idx, 2), 0),
3731 bi_imm_u8(0), bi_zero())
3732 : bi_zero();
3733
3734 dest = bi_mkvec_v2i8(
3735 b, (nr > 0) ? bi_byte(bi_extract(b, idx, 0), 0) : bi_imm_u8(0),
3736 (nr > 1) ? bi_byte(bi_extract(b, idx, 1), 0) : bi_imm_u8(0), z);
3737 }
3738
3739 /* Component 2: multisample index */
3740 if (ms_idx >= 0 && !nir_src_is_zero(instr->src[ms_idx].src)) {
3741 bi_index ms = bi_src_index(&instr->src[ms_idx].src);
3742 dest = bi_mkvec_v2i16(b, bi_half(dest, false), bi_half(ms, false));
3743 }
3744
3745 /* Component 3: 8-bit LOD */
3746 if (lod_idx >= 0 && !nir_src_is_zero(instr->src[lod_idx].src) &&
3747 nir_tex_instr_src_type(instr, lod_idx) != nir_type_float) {
3748 dest = bi_lshift_or_i32(b, bi_src_index(&instr->src[lod_idx].src), dest,
3749 bi_imm_u8(24));
3750 }
3751
3752 return dest;
3753 }
3754
3755 static void
3756 bi_emit_cube_coord(bi_builder *b, bi_index coord, bi_index *face, bi_index *s,
3757 bi_index *t)
3758 {
3759 /* Compute max { |x|, |y|, |z| } */
3760 bi_index maxxyz = bi_temp(b->shader);
3761 *face = bi_temp(b->shader);
3762
3763 bi_index cx = bi_extract(b, coord, 0), cy = bi_extract(b, coord, 1),
3764 cz = bi_extract(b, coord, 2);
3765
3766 /* Use a pseudo op on Bifrost due to tuple restrictions */
3767 if (b->shader->arch <= 8) {
3768 bi_cubeface_to(b, maxxyz, *face, cx, cy, cz);
3769 } else {
3770 bi_cubeface1_to(b, maxxyz, cx, cy, cz);
3771 bi_cubeface2_v9_to(b, *face, cx, cy, cz);
3772 }
3773
3774 /* Select coordinates */
3775 bi_index ssel =
3776 bi_cube_ssel(b, bi_extract(b, coord, 2), bi_extract(b, coord, 0), *face);
3777 bi_index tsel =
3778 bi_cube_tsel(b, bi_extract(b, coord, 1), bi_extract(b, coord, 2), *face);
3779
3780 /* The OpenGL ES specification requires us to transform an input vector
3781 * (x, y, z) to the coordinate, given the selected S/T:
3782 *
3783 * (1/2 ((s / max{x,y,z}) + 1), 1/2 ((t / max{x, y, z}) + 1))
3784 *
3785 * We implement (s shown, t similar) in a form friendlier to FMA
3786 * instructions, and clamp coordinates at the end for correct
3787 * NaN/infinity handling:
3788 *
3789 * fsat(s * (0.5 * (1 / max{x, y, z})) + 0.5)
3790 *
3791 * Take the reciprocal of max{x, y, z}
3792 */
3793 bi_index rcp = bi_frcp_f32(b, maxxyz);
3794
3795 /* Calculate 0.5 * (1.0 / max{x, y, z}) */
3796 bi_index fma1 = bi_fma_f32(b, rcp, bi_imm_f32(0.5f), bi_negzero());
3797
3798 /* Transform the coordinates */
3799 *s = bi_temp(b->shader);
3800 *t = bi_temp(b->shader);
3801
3802 bi_instr *S = bi_fma_f32_to(b, *s, fma1, ssel, bi_imm_f32(0.5f));
3803 bi_instr *T = bi_fma_f32_to(b, *t, fma1, tsel, bi_imm_f32(0.5f));
3804
3805 S->clamp = BI_CLAMP_CLAMP_0_1;
3806 T->clamp = BI_CLAMP_CLAMP_0_1;
3807 }
3808
3809 /* Emits a cube map descriptor, returning lower 32-bits and putting upper
3810 * 32-bits in passed pointer t. The packing of the face with the S coordinate
3811 * exploits the redundancy of floating points with the range restriction of
3812 * CUBEFACE output.
3813 *
3814 * struct cube_map_descriptor {
3815 * float s : 29;
3816 * unsigned face : 3;
3817 * float t : 32;
3818 * }
3819 *
3820 * Since the cube face index is preshifted, this is easy to pack with a bitwise
3821 * MUX.i32 and a fixed mask, selecting the lower bits 29 from s and the upper 3
3822 * bits from face.
3823 */
3824
3825 static bi_index
3826 bi_emit_texc_cube_coord(bi_builder *b, bi_index coord, bi_index *t)
3827 {
3828 bi_index face, s;
3829 bi_emit_cube_coord(b, coord, &face, &s, t);
3830 bi_index mask = bi_imm_u32(BITFIELD_MASK(29));
3831 return bi_mux_i32(b, s, face, mask, BI_MUX_BIT);
3832 }
3833
3834 /* Map to the main texture op used. Some of these (txd in particular) will
3835 * lower to multiple texture ops with different opcodes (GRDESC_DER + TEX in
3836 * sequence). We assume that lowering is handled elsewhere.
3837 */
3838
3839 static enum bifrost_tex_op
3840 bi_tex_op(nir_texop op)
3841 {
3842 switch (op) {
3843 case nir_texop_tex:
3844 case nir_texop_txb:
3845 case nir_texop_txl:
3846 case nir_texop_txd:
3847 return BIFROST_TEX_OP_TEX;
3848 case nir_texop_txf:
3849 case nir_texop_txf_ms:
3850 case nir_texop_tg4:
3851 return BIFROST_TEX_OP_FETCH;
3852 case nir_texop_lod:
3853 return BIFROST_TEX_OP_GRDESC;
3854 case nir_texop_txs:
3855 case nir_texop_query_levels:
3856 case nir_texop_texture_samples:
3857 case nir_texop_samples_identical:
3858 UNREACHABLE("should've been lowered");
3859 default:
3860 UNREACHABLE("unsupported tex op");
3861 }
3862 }
3863
3864 /* Data registers required by texturing in the order they appear. All are
3865 * optional, the texture operation descriptor determines which are present.
3866 * Note since 3D arrays are not permitted at an API level, Z_COORD and
3867 * ARRAY/SHADOW are exlusive, so TEXC in practice reads at most 8 registers */
3868
3869 enum bifrost_tex_dreg {
3870 BIFROST_TEX_DREG_Z_COORD = 0,
3871 BIFROST_TEX_DREG_Y_DELTAS = 1,
3872 BIFROST_TEX_DREG_LOD = 2,
3873 BIFROST_TEX_DREG_GRDESC_HI = 3,
3874 BIFROST_TEX_DREG_SHADOW = 4,
3875 BIFROST_TEX_DREG_ARRAY = 5,
3876 BIFROST_TEX_DREG_OFFSETMS = 6,
3877 BIFROST_TEX_DREG_SAMPLER = 7,
3878 BIFROST_TEX_DREG_TEXTURE = 8,
3879 BIFROST_TEX_DREG_COUNT,
3880 };
3881
3882 static void
3883 bi_emit_texc(bi_builder *b, nir_tex_instr *instr)
3884 {
3885 assert((instr->op != nir_texop_txf ||
3886 instr->sampler_dim != GLSL_SAMPLER_DIM_BUF) &&
3887 "Texel buffers should already have been lowered");
3888
3889 struct bifrost_texture_operation desc = {
3890 .op = bi_tex_op(instr->op),
3891 .offset_or_bias_disable = false, /* TODO */
3892 .shadow_or_clamp_disable = instr->is_shadow,
3893 .array = instr->is_array && instr->op != nir_texop_lod,
3894 .dimension = bifrost_tex_format(instr->sampler_dim),
3895 .format = bi_texture_format(instr->dest_type | instr->def.bit_size,
3896 BI_CLAMP_NONE), /* TODO */
3897 .mask = 0xF,
3898 };
3899
3900 switch (desc.op) {
3901 case BIFROST_TEX_OP_TEX:
3902 desc.lod_or_fetch = BIFROST_LOD_MODE_COMPUTE;
3903 break;
3904 case BIFROST_TEX_OP_FETCH:
3905 desc.lod_or_fetch = (enum bifrost_lod_mode)(
3906 instr->op == nir_texop_tg4
3907 ? BIFROST_TEXTURE_FETCH_GATHER4_R + instr->component
3908 : BIFROST_TEXTURE_FETCH_TEXEL);
3909 break;
3910 case BIFROST_TEX_OP_GRDESC:
3911 break;
3912 default:
3913 UNREACHABLE("texture op unsupported");
3914 }
3915
3916 /* 32-bit indices to be allocated as consecutive staging registers */
3917 bi_index dregs[BIFROST_TEX_DREG_COUNT] = {};
3918 bi_index cx = bi_null(), cy = bi_null();
3919 bi_index ddx = bi_null();
3920 bi_index ddy = bi_null();
3921
3922 for (unsigned i = 0; i < instr->num_srcs; ++i) {
3923 bi_index index = bi_src_index(&instr->src[i].src);
3924 unsigned sz = nir_src_bit_size(instr->src[i].src);
3925 unsigned components = nir_src_num_components(instr->src[i].src);
3926 ASSERTED nir_alu_type base = nir_tex_instr_src_type(instr, i);
3927 nir_alu_type T = base | sz;
3928
3929 switch (instr->src[i].src_type) {
3930 case nir_tex_src_coord:
3931 if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) {
3932 cx = bi_emit_texc_cube_coord(b, index, &cy);
3933 } else {
3934 /* Copy XY (for 2D+) or XX (for 1D) */
3935 cx = bi_extract(b, index, 0);
3936 cy = bi_extract(b, index, MIN2(1, components - 1));
3937
3938 assert(components >= 1 && components <= 3);
3939
3940 if (components == 3 && !desc.array) {
3941 /* 3D */
3942 dregs[BIFROST_TEX_DREG_Z_COORD] = bi_extract(b, index, 2);
3943 }
3944 }
3945
3946 if (desc.array) {
3947 dregs[BIFROST_TEX_DREG_ARRAY] = bi_emit_texc_array_index(
3948 b, bi_extract(b, index, components - 1), T);
3949 }
3950
3951 break;
3952
3953 case nir_tex_src_lod:
3954 if (desc.op == BIFROST_TEX_OP_TEX &&
3955 nir_src_is_zero(instr->src[i].src)) {
3956 desc.lod_or_fetch = BIFROST_LOD_MODE_ZERO;
3957 } else if (desc.op == BIFROST_TEX_OP_TEX) {
3958 assert(base == nir_type_float);
3959
3960 assert(sz == 16 || sz == 32);
3961 dregs[BIFROST_TEX_DREG_LOD] =
3962 bi_emit_texc_lod_88(b, index, sz == 16);
3963 desc.lod_or_fetch = BIFROST_LOD_MODE_EXPLICIT;
3964 } else {
3965 assert(desc.op == BIFROST_TEX_OP_FETCH);
3966 assert(base == nir_type_uint || base == nir_type_int);
3967 assert(sz == 16 || sz == 32);
3968
3969 dregs[BIFROST_TEX_DREG_LOD] = bi_emit_texc_lod_cube(b, index);
3970 }
3971
3972 break;
3973
3974 case nir_tex_src_ddx:
3975 ddx = index;
3976 break;
3977
3978 case nir_tex_src_ddy:
3979 ddy = index;
3980 break;
3981
3982 case nir_tex_src_bias:
3983 /* Upper 16-bits interpreted as a clamp, leave zero */
3984 assert(desc.op == BIFROST_TEX_OP_TEX);
3985 assert(base == nir_type_float);
3986 assert(sz == 16 || sz == 32);
3987 dregs[BIFROST_TEX_DREG_LOD] = bi_emit_texc_lod_88(b, index, sz == 16);
3988 desc.lod_or_fetch = BIFROST_LOD_MODE_BIAS;
3989 break;
3990
3991 case nir_tex_src_ms_index:
3992 case nir_tex_src_offset:
3993 if (desc.offset_or_bias_disable)
3994 break;
3995
3996 dregs[BIFROST_TEX_DREG_OFFSETMS] =
3997 bi_emit_texc_offset_ms_index(b, instr);
3998 if (!bi_is_equiv(dregs[BIFROST_TEX_DREG_OFFSETMS], bi_zero()))
3999 desc.offset_or_bias_disable = true;
4000 break;
4001
4002 case nir_tex_src_comparator:
4003 dregs[BIFROST_TEX_DREG_SHADOW] = index;
4004 break;
4005
4006 case nir_tex_src_texture_offset:
4007 dregs[BIFROST_TEX_DREG_TEXTURE] = index;
4008 break;
4009
4010 case nir_tex_src_sampler_offset:
4011 dregs[BIFROST_TEX_DREG_SAMPLER] = index;
4012 break;
4013
4014 default:
4015 UNREACHABLE("Unhandled src type in texc emit");
4016 }
4017 }
4018
4019 if (desc.op == BIFROST_TEX_OP_FETCH &&
4020 bi_is_null(dregs[BIFROST_TEX_DREG_LOD])) {
4021 dregs[BIFROST_TEX_DREG_LOD] = bi_emit_texc_lod_cube(b, bi_zero());
4022 }
4023
4024 /* Choose an index mode */
4025
4026 bool direct_tex = bi_is_null(dregs[BIFROST_TEX_DREG_TEXTURE]);
4027 bool direct_samp = bi_is_null(dregs[BIFROST_TEX_DREG_SAMPLER]);
4028 bool direct = direct_tex && direct_samp;
4029
4030 desc.immediate_indices =
4031 direct && (instr->sampler_index < 16 && instr->texture_index < 128);
4032
4033 if (desc.immediate_indices) {
4034 desc.sampler_index_or_mode = instr->sampler_index;
4035 desc.index = instr->texture_index;
4036 } else {
4037 unsigned mode = 0;
4038
4039 if (direct && instr->sampler_index == instr->texture_index &&
4040 instr->sampler_index < 128) {
4041 mode = BIFROST_INDEX_IMMEDIATE_SHARED;
4042 desc.index = instr->texture_index;
4043 } else if (direct && instr->sampler_index < 128) {
4044 mode = BIFROST_INDEX_IMMEDIATE_SAMPLER;
4045 desc.index = instr->sampler_index;
4046 dregs[BIFROST_TEX_DREG_TEXTURE] =
4047 bi_mov_i32(b, bi_imm_u32(instr->texture_index));
4048 } else if (direct_tex && instr->texture_index < 128) {
4049 mode = BIFROST_INDEX_IMMEDIATE_TEXTURE;
4050 desc.index = instr->texture_index;
4051
4052 if (direct_samp) {
4053 dregs[BIFROST_TEX_DREG_SAMPLER] =
4054 bi_mov_i32(b, bi_imm_u32(instr->sampler_index));
4055 }
4056 } else if (direct_samp && instr->sampler_index < 128) {
4057 mode = BIFROST_INDEX_IMMEDIATE_SAMPLER;
4058 desc.index = instr->sampler_index;
4059
4060 if (direct_tex) {
4061 dregs[BIFROST_TEX_DREG_TEXTURE] =
4062 bi_mov_i32(b, bi_imm_u32(instr->texture_index));
4063 }
4064 } else {
4065 mode = BIFROST_INDEX_REGISTER;
4066
4067 if (direct_tex) {
4068 dregs[BIFROST_TEX_DREG_TEXTURE] =
4069 bi_mov_i32(b, bi_imm_u32(instr->texture_index));
4070 }
4071
4072 if (direct_samp) {
4073 dregs[BIFROST_TEX_DREG_SAMPLER] =
4074 bi_mov_i32(b, bi_imm_u32(instr->sampler_index));
4075 }
4076 }
4077
4078 mode |= (BIFROST_TEXTURE_OPERATION_SINGLE << 2);
4079 desc.sampler_index_or_mode = mode;
4080 }
4081
4082 if (!bi_is_null(ddx) || !bi_is_null(ddy)) {
4083 assert(!bi_is_null(ddx) && !bi_is_null(ddy));
4084 struct bifrost_texture_operation gropdesc = {
4085 .sampler_index_or_mode = desc.sampler_index_or_mode,
4086 .index = desc.index,
4087 .immediate_indices = desc.immediate_indices,
4088 .op = BIFROST_TEX_OP_GRDESC_DER,
4089 .offset_or_bias_disable = true,
4090 .shadow_or_clamp_disable = true,
4091 .array = false,
4092 .dimension = desc.dimension,
4093 .format = desc.format,
4094 .mask = desc.mask,
4095 };
4096
4097 unsigned coords_comp_count =
4098 instr->coord_components -
4099 (instr->is_array || instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE);
4100 bi_index derivs[4];
4101 unsigned sr_count = 0;
4102
4103 if (coords_comp_count > 2)
4104 derivs[sr_count++] = bi_extract(b, ddx, 2);
4105 derivs[sr_count++] = bi_extract(b, ddy, 0);
4106 if (coords_comp_count > 1)
4107 derivs[sr_count++] = bi_extract(b, ddy, 1);
4108 if (coords_comp_count > 2)
4109 derivs[sr_count++] = bi_extract(b, ddy, 2);
4110
4111 bi_index derivs_packed = bi_temp(b->shader);
4112 bi_make_vec_to(b, derivs_packed, derivs, NULL, sr_count, 32);
4113 bi_index grdesc = bi_temp(b->shader);
4114 bi_instr *I =
4115 bi_texc_to(b, grdesc, derivs_packed, bi_extract(b, ddx, 0),
4116 coords_comp_count > 1 ? bi_extract(b, ddx, 1) : bi_zero(),
4117 bi_imm_u32(gropdesc.packed), true, sr_count, 0);
4118 I->register_format = BI_REGISTER_FORMAT_U32;
4119
4120 bi_emit_cached_split_i32(b, grdesc, 4);
4121
4122 dregs[BIFROST_TEX_DREG_LOD] = bi_extract(b, grdesc, 0);
4123 desc.lod_or_fetch = BIFROST_LOD_MODE_EXPLICIT;
4124 }
4125
4126 /* Allocate staging registers contiguously by compacting the array. */
4127 unsigned sr_count = 0;
4128
4129 for (unsigned i = 0; i < ARRAY_SIZE(dregs); ++i) {
4130 if (!bi_is_null(dregs[i]))
4131 dregs[sr_count++] = dregs[i];
4132 }
4133
4134 unsigned res_size = instr->def.bit_size == 16 ? 2 : 4;
4135
4136 bi_index sr = sr_count ? bi_temp(b->shader) : bi_null();
4137
4138 if (sr_count)
4139 bi_emit_collect_to(b, sr, dregs, sr_count);
4140
4141 if (instr->op == nir_texop_lod) {
4142 assert(instr->def.num_components == 2 && instr->def.bit_size == 32);
4143
4144 bi_index res[2];
4145 for (unsigned i = 0; i < 2; i++) {
4146 desc.shadow_or_clamp_disable = i != 0;
4147
4148 bi_index grdesc = bi_temp(b->shader);
4149 bi_instr *I = bi_texc_to(b, grdesc, sr, cx, cy,
4150 bi_imm_u32(desc.packed), false, sr_count, 0);
4151 I->register_format = BI_REGISTER_FORMAT_U32;
4152
4153 bi_emit_cached_split_i32(b, grdesc, 4);
4154
4155 bi_index lod = bi_s16_to_f32(b, bi_half(bi_extract(b, grdesc, 0), 0));
4156
4157 lod = bi_fmul_f32(b, lod, bi_imm_f32(1.0f / 256));
4158
4159 if (i == 0)
4160 lod = bi_fround_f32(b, lod, BI_ROUND_NONE);
4161
4162 res[i] = lod;
4163 }
4164
4165 bi_make_vec_to(b, bi_def_index(&instr->def), res, NULL, 2, 32);
4166 return;
4167 }
4168
4169 bi_index dst = bi_temp(b->shader);
4170
4171 bi_instr *I =
4172 bi_texc_to(b, dst, sr, cx, cy, bi_imm_u32(desc.packed),
4173 !nir_tex_instr_has_implicit_derivative(instr), sr_count, 0);
4174 I->register_format = bi_reg_fmt_for_nir(instr->dest_type);
4175
4176 bi_index w[4] = {bi_null(), bi_null(), bi_null(), bi_null()};
4177 bi_emit_split_i32(b, w, dst, res_size);
4178 bi_emit_collect_to(b, bi_def_index(&instr->def), w,
4179 DIV_ROUND_UP(instr->def.num_components * res_size, 4));
4180 }
4181
4182 /* Staging registers required by texturing in the order they appear (Valhall) */
4183
4184 enum valhall_tex_sreg {
4185 VALHALL_TEX_SREG_X_COORD = 0,
4186 VALHALL_TEX_SREG_Y_COORD = 1,
4187 VALHALL_TEX_SREG_Z_COORD = 2,
4188 VALHALL_TEX_SREG_Y_DELTAS = 3,
4189 VALHALL_TEX_SREG_ARRAY = 4,
4190 VALHALL_TEX_SREG_SHADOW = 5,
4191 VALHALL_TEX_SREG_OFFSETMS = 6,
4192 VALHALL_TEX_SREG_LOD = 7,
4193 VALHALL_TEX_SREG_GRDESC0 = 8,
4194 VALHALL_TEX_SREG_GRDESC1 = 9,
4195 VALHALL_TEX_SREG_COUNT,
4196 };
4197
4198 static void
4199 bi_emit_tex_valhall(bi_builder *b, nir_tex_instr *instr)
4200 {
4201 bool explicit_offset = false;
4202 enum bi_va_lod_mode lod_mode = BI_VA_LOD_MODE_COMPUTED_LOD;
4203
4204 bool has_lod_mode = (instr->op == nir_texop_tex) ||
4205 (instr->op == nir_texop_txl) ||
4206 (instr->op == nir_texop_txd) ||
4207 (instr->op == nir_texop_txb);
4208
4209 /* 32-bit indices to be allocated as consecutive staging registers */
4210 bi_index sregs[VALHALL_TEX_SREG_COUNT] = {};
4211 bi_index sampler = bi_imm_u32(instr->sampler_index);
4212 bi_index texture = bi_imm_u32(instr->texture_index);
4213 bi_index ddx = bi_null();
4214 bi_index ddy = bi_null();
4215
4216 for (unsigned i = 0; i < instr->num_srcs; ++i) {
4217 bi_index index = bi_src_index(&instr->src[i].src);
4218 unsigned sz = nir_src_bit_size(instr->src[i].src);
4219
4220 switch (instr->src[i].src_type) {
4221 case nir_tex_src_coord: {
4222 bool is_array = instr->is_array && instr->op != nir_texop_lod;
4223 unsigned components = nir_tex_instr_src_size(instr, i) - is_array;
4224
4225 if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) {
4226 sregs[VALHALL_TEX_SREG_X_COORD] = bi_emit_texc_cube_coord(
4227 b, index, &sregs[VALHALL_TEX_SREG_Y_COORD]);
4228 } else {
4229 assert(components >= 1 && components <= 3);
4230
4231 /* Copy XY (for 2D+) or XX (for 1D) */
4232 sregs[VALHALL_TEX_SREG_X_COORD] = index;
4233
4234 if (components >= 2)
4235 sregs[VALHALL_TEX_SREG_Y_COORD] = bi_extract(b, index, 1);
4236
4237 if (components == 3)
4238 sregs[VALHALL_TEX_SREG_Z_COORD] = bi_extract(b, index, 2);
4239 }
4240
4241 if (is_array)
4242 sregs[VALHALL_TEX_SREG_ARRAY] = bi_extract(b, index, components);
4243
4244 break;
4245 }
4246
4247 case nir_tex_src_lod:
4248 if (nir_src_is_zero(instr->src[i].src)) {
4249 lod_mode = BI_VA_LOD_MODE_ZERO_LOD;
4250 } else if (has_lod_mode) {
4251 lod_mode = BI_VA_LOD_MODE_EXPLICIT;
4252
4253 assert(sz == 16 || sz == 32);
4254 sregs[VALHALL_TEX_SREG_LOD] =
4255 bi_emit_texc_lod_88(b, index, sz == 16);
4256 }
4257 break;
4258
4259 case nir_tex_src_ddx:
4260 ddx = index;
4261 break;
4262
4263 case nir_tex_src_ddy:
4264 ddy = index;
4265 break;
4266
4267 case nir_tex_src_bias:
4268 /* Upper 16-bits interpreted as a clamp, leave zero */
4269 assert(sz == 16 || sz == 32);
4270 sregs[VALHALL_TEX_SREG_LOD] = bi_emit_texc_lod_88(b, index, sz == 16);
4271
4272 lod_mode = BI_VA_LOD_MODE_COMPUTED_BIAS;
4273 break;
4274 case nir_tex_src_ms_index:
4275 case nir_tex_src_offset:
4276 /* Handled below */
4277 break;
4278
4279 case nir_tex_src_comparator:
4280 sregs[VALHALL_TEX_SREG_SHADOW] = index;
4281 break;
4282
4283 case nir_tex_src_texture_offset:
4284 /* This should always be 0 as lower_index_to_offset is expected to be
4285 * set */
4286 assert(instr->texture_index == 0);
4287 texture = index;
4288 break;
4289
4290 case nir_tex_src_sampler_offset:
4291 /* This should always be 0 as lower_index_to_offset is expected to be
4292 * set */
4293 assert(instr->sampler_index == 0);
4294 sampler = index;
4295 break;
4296
4297 default:
4298 UNREACHABLE("Unhandled src type in tex emit");
4299 }
4300 }
4301
4302 /* Generate packed offset + ms index + LOD register. These default to
4303 * zero so we only need to encode if these features are actually in use.
4304 */
4305 bi_index offsets = bi_emit_valhall_offsets(b, instr);
4306
4307 if (!bi_is_equiv(offsets, bi_zero())) {
4308 sregs[VALHALL_TEX_SREG_OFFSETMS] = offsets;
4309 explicit_offset = true;
4310 }
4311
4312 bool narrow_indices = va_is_valid_const_narrow_index(texture) &&
4313 va_is_valid_const_narrow_index(sampler);
4314
4315 bi_index src0;
4316 bi_index src1;
4317
4318 if (narrow_indices) {
4319 unsigned tex_set =
4320 va_res_fold_table_idx(pan_res_handle_get_table(texture.value));
4321 unsigned sampler_set =
4322 va_res_fold_table_idx(pan_res_handle_get_table(sampler.value));
4323 unsigned texture_index = pan_res_handle_get_index(texture.value);
4324 unsigned sampler_index = pan_res_handle_get_index(sampler.value);
4325
4326 unsigned packed_handle = (tex_set << 27) | (texture_index << 16) |
4327 (sampler_set << 11) | sampler_index;
4328
4329 src0 = bi_imm_u32(packed_handle);
4330
4331 /* TODO: narrow offsetms. (only when offsetms is dynamically uniform) */
4332 src1 = bi_zero();
4333 } else {
4334 src0 = sampler;
4335 src1 = texture;
4336 }
4337
4338 enum bi_dimension dim = valhall_tex_dimension(instr->sampler_dim);
4339
4340 if (!bi_is_null(ddx) || !bi_is_null(ddy)) {
4341 unsigned coords_comp_count =
4342 instr->coord_components -
4343 (instr->is_array || instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE);
4344 assert(!bi_is_null(ddx) && !bi_is_null(ddy));
4345
4346 lod_mode = BI_VA_LOD_MODE_GRDESC;
4347
4348 bi_index derivs[6] = {
4349 bi_extract(b, ddx, 0),
4350 bi_extract(b, ddy, 0),
4351 coords_comp_count > 1 ? bi_extract(b, ddx, 1) : bi_null(),
4352 coords_comp_count > 1 ? bi_extract(b, ddy, 1) : bi_null(),
4353 coords_comp_count > 2 ? bi_extract(b, ddx, 2) : bi_null(),
4354 coords_comp_count > 2 ? bi_extract(b, ddy, 2) : bi_null(),
4355 };
4356 bi_index derivs_packed = bi_temp(b->shader);
4357 bi_make_vec_to(b, derivs_packed, derivs, NULL, coords_comp_count * 2, 32);
4358 bi_index grdesc = bi_temp(b->shader);
4359 bi_instr *I = bi_tex_gradient_to(b, grdesc, derivs_packed, src0, src1, dim,
4360 !narrow_indices, 3, coords_comp_count * 2);
4361 I->derivative_enable = true;
4362 I->force_delta_enable = false;
4363 I->lod_clamp_disable = true;
4364 I->lod_bias_disable = true;
4365 I->register_format = BI_REGISTER_FORMAT_U32;
4366
4367 bi_emit_cached_split_i32(b, grdesc, 2);
4368 sregs[VALHALL_TEX_SREG_GRDESC0] = bi_extract(b, grdesc, 0);
4369 sregs[VALHALL_TEX_SREG_GRDESC1] = bi_extract(b, grdesc, 1);
4370 }
4371
4372 /* Allocate staging registers contiguously by compacting the array. */
4373 unsigned sr_count = 0;
4374 for (unsigned i = 0; i < ARRAY_SIZE(sregs); ++i) {
4375 if (!bi_is_null(sregs[i]))
4376 sregs[sr_count++] = sregs[i];
4377 }
4378
4379 bi_index idx = sr_count ? bi_temp(b->shader) : bi_null();
4380
4381 if (sr_count)
4382 bi_make_vec_to(b, idx, sregs, NULL, sr_count, 32);
4383
4384 if (instr->op == nir_texop_lod) {
4385 assert(instr->def.num_components == 2 && instr->def.bit_size == 32);
4386
4387 bi_index res[2];
4388
4389 for (unsigned i = 0; i < 2; i++) {
4390 bi_index grdesc = bi_temp(b->shader);
4391 bi_instr *I = bi_tex_gradient_to(b, grdesc, idx, src0, src1, dim,
4392 !narrow_indices, 1, sr_count);
4393 I->derivative_enable = false;
4394 I->force_delta_enable = false;
4395 I->lod_clamp_disable = i != 0;
4396 I->register_format = BI_REGISTER_FORMAT_U32;
4397 bi_index lod;
4398
4399 /* v11 removed S16_TO_F32 */
4400 if (b->shader->arch >= 11) {
4401 lod = bi_s32_to_f32(b, bi_s16_to_s32(b, bi_half(grdesc, 0)));
4402 } else {
4403 lod = bi_s16_to_f32(b, bi_half(grdesc, 0));
4404 }
4405
4406 lod = bi_fmul_f32(b, lod, bi_imm_f32(1.0f / 256));
4407
4408 if (i == 0)
4409 lod = bi_fround_f32(b, lod, BI_ROUND_NONE);
4410
4411 res[i] = lod;
4412 }
4413
4414 bi_make_vec_to(b, bi_def_index(&instr->def), res, NULL, 2, 32);
4415 return;
4416 }
4417
4418 /* Only write the components that we actually read */
4419 unsigned mask = nir_def_components_read(&instr->def);
4420 unsigned comps_per_reg = instr->def.bit_size == 16 ? 2 : 1;
4421 unsigned res_size = DIV_ROUND_UP(util_bitcount(mask), comps_per_reg);
4422
4423 enum bi_register_format regfmt = bi_reg_fmt_for_nir(instr->dest_type);
4424 bi_index dest = bi_temp(b->shader);
4425
4426 switch (instr->op) {
4427 case nir_texop_tex:
4428 case nir_texop_txb:
4429 case nir_texop_txl:
4430 case nir_texop_txd:
4431 bi_tex_single_to(b, dest, idx, src0, src1, instr->is_array, dim, regfmt,
4432 instr->is_shadow, explicit_offset, lod_mode,
4433 !narrow_indices, mask, sr_count);
4434 break;
4435 case nir_texop_txf:
4436 case nir_texop_txf_ms: {
4437 assert(instr->sampler_dim != GLSL_SAMPLER_DIM_BUF &&
4438 "Texel buffers should already have been lowered");
4439 /* On Valhall, TEX_FETCH doesn't have CUBE support. This is not a problem
4440 * as a cube is just a 2D array in any cases. */
4441 if (dim == BI_DIMENSION_CUBE)
4442 dim = BI_DIMENSION_2D;
4443
4444 bi_tex_fetch_to(b, dest, idx, src0, src1, instr->is_array, dim, regfmt,
4445 explicit_offset, !narrow_indices, mask, sr_count);
4446 break;
4447 }
4448 case nir_texop_tg4:
4449 bi_tex_gather_to(b, dest, idx, src0, src1, instr->is_array, dim,
4450 instr->component, false, regfmt, instr->is_shadow,
4451 explicit_offset, !narrow_indices, mask, sr_count);
4452 break;
4453 default:
4454 UNREACHABLE("Unhandled Valhall texture op");
4455 }
4456
4457 /* The hardware will write only what we read, and it will into
4458 * contiguous registers without gaps (different from Bifrost). NIR
4459 * expects the gaps, so fill in the holes (they'll be copypropped and
4460 * DCE'd away later).
4461 */
4462 bi_index unpacked[4] = {bi_null(), bi_null(), bi_null(), bi_null()};
4463
4464 bi_emit_cached_split_i32(b, dest, res_size);
4465
4466 /* Index into the packed component array */
4467 unsigned j = 0;
4468 unsigned comps[4] = {0};
4469 unsigned nr_components = instr->def.num_components;
4470
4471 for (unsigned i = 0; i < nr_components; ++i) {
4472 if (mask & BITFIELD_BIT(i)) {
4473 unpacked[i] = dest;
4474 comps[i] = j++;
4475 } else {
4476 unpacked[i] = bi_zero();
4477 }
4478 }
4479
4480 bi_make_vec_to(b, bi_def_index(&instr->def), unpacked, comps,
4481 instr->def.num_components, instr->def.bit_size);
4482 }
4483
4484 /* Simple textures ops correspond to NIR tex or txl with LOD = 0 on 2D/cube
4485 * textures with sufficiently small immediate indices. Anything else
4486 * needs a complete texture op. */
4487
4488 static void
4489 bi_emit_texs(bi_builder *b, nir_tex_instr *instr)
4490 {
4491 int coord_idx = nir_tex_instr_src_index(instr, nir_tex_src_coord);
4492 assert(coord_idx >= 0);
4493 bi_index coords = bi_src_index(&instr->src[coord_idx].src);
4494
4495 if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) {
4496 bi_index face, s, t;
4497 bi_emit_cube_coord(b, coords, &face, &s, &t);
4498
4499 bi_texs_cube_to(b, instr->def.bit_size, bi_def_index(&instr->def), s, t,
4500 face, instr->sampler_index, instr->texture_index);
4501 } else {
4502 bi_texs_2d_to(b, instr->def.bit_size, bi_def_index(&instr->def),
4503 bi_extract(b, coords, 0), bi_extract(b, coords, 1),
4504 instr->op != nir_texop_tex, /* zero LOD */
4505 instr->sampler_index, instr->texture_index);
4506 }
4507
4508 bi_split_def(b, &instr->def);
4509 }
4510
4511 static bool
4512 bi_is_simple_tex(nir_tex_instr *instr)
4513 {
4514 if (instr->op != nir_texop_tex && instr->op != nir_texop_txl)
4515 return false;
4516
4517 if (instr->dest_type != nir_type_float32 &&
4518 instr->dest_type != nir_type_float16)
4519 return false;
4520
4521 if (instr->is_shadow || instr->is_array)
4522 return false;
4523
4524 switch (instr->sampler_dim) {
4525 case GLSL_SAMPLER_DIM_2D:
4526 case GLSL_SAMPLER_DIM_EXTERNAL:
4527 case GLSL_SAMPLER_DIM_RECT:
4528 break;
4529
4530 case GLSL_SAMPLER_DIM_CUBE:
4531 /* LOD can't be specified with TEXS_CUBE */
4532 if (instr->op == nir_texop_txl)
4533 return false;
4534 break;
4535
4536 default:
4537 return false;
4538 }
4539
4540 for (unsigned i = 0; i < instr->num_srcs; ++i) {
4541 if (instr->src[i].src_type != nir_tex_src_lod &&
4542 instr->src[i].src_type != nir_tex_src_coord)
4543 return false;
4544 }
4545
4546 /* Indices need to fit in provided bits */
4547 unsigned idx_bits = instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE ? 2 : 3;
4548 if (MAX2(instr->sampler_index, instr->texture_index) >= (1 << idx_bits))
4549 return false;
4550
4551 int lod_idx = nir_tex_instr_src_index(instr, nir_tex_src_lod);
4552 if (lod_idx < 0)
4553 return true;
4554
4555 nir_src lod = instr->src[lod_idx].src;
4556 return nir_src_is_zero(lod);
4557 }
4558
4559 static void
4560 bi_emit_tex(bi_builder *b, nir_tex_instr *instr)
4561 {
4562 /* If txf is used, we assume there is a valid sampler bound at index 0. Use
4563 * it for txf operations, since there may be no other valid samplers. This is
4564 * a workaround: txf does not require a sampler in NIR (so sampler_index is
4565 * undefined) but we need one in the hardware. This is ABI with the driver.
4566 *
4567 * On Valhall, as the descriptor table is encoded in the index, this should
4568 * be handled by the driver.
4569 */
4570 if (!nir_tex_instr_need_sampler(instr) && b->shader->arch < 9)
4571 instr->sampler_index = 0;
4572
4573 if (b->shader->arch >= 9)
4574 bi_emit_tex_valhall(b, instr);
4575 else if (bi_is_simple_tex(instr))
4576 bi_emit_texs(b, instr);
4577 else
4578 bi_emit_texc(b, instr);
4579 }
4580
4581 static void
4582 bi_emit_phi(bi_builder *b, nir_phi_instr *instr)
4583 {
4584 unsigned nr_srcs = exec_list_length(&instr->srcs);
4585 bi_instr *I = bi_phi_to(b, bi_def_index(&instr->def), nr_srcs);
4586
4587 /* Deferred */
4588 I->phi = instr;
4589 }
4590
4591 /* Look up the AGX block corresponding to a given NIR block. Used when
4592 * translating phi nodes after emitting all blocks.
4593 */
4594 static bi_block *
4595 bi_from_nir_block(bi_context *ctx, nir_block *block)
4596 {
4597 return ctx->indexed_nir_blocks[block->index];
4598 }
4599
4600 static void
4601 bi_emit_phi_deferred(bi_context *ctx, bi_block *block, bi_instr *I)
4602 {
4603 nir_phi_instr *phi = I->phi;
4604
4605 /* Guaranteed by lower_phis_to_scalar */
4606 assert(phi->def.bit_size * phi->def.num_components <= 32);
4607
4608 nir_foreach_phi_src(src, phi) {
4609 bi_block *pred = bi_from_nir_block(ctx, src->pred);
4610 unsigned i = bi_predecessor_index(block, pred);
4611 assert(i < I->nr_srcs);
4612
4613 I->src[i] = bi_src_index(&src->src);
4614 }
4615
4616 I->phi = NULL;
4617 }
4618
4619 static void
4620 bi_emit_phis_deferred(bi_context *ctx)
4621 {
4622 bi_foreach_block(ctx, block) {
4623 bi_foreach_instr_in_block(block, I) {
4624 if (I->op == BI_OPCODE_PHI)
4625 bi_emit_phi_deferred(ctx, block, I);
4626 }
4627 }
4628 }
4629
4630 static void
4631 bi_emit_instr(bi_builder *b, struct nir_instr *instr)
4632 {
4633 switch (instr->type) {
4634 case nir_instr_type_load_const:
4635 bi_emit_load_const(b, nir_instr_as_load_const(instr));
4636 break;
4637
4638 case nir_instr_type_intrinsic:
4639 bi_emit_intrinsic(b, nir_instr_as_intrinsic(instr));
4640 break;
4641
4642 case nir_instr_type_alu:
4643 bi_emit_alu(b, nir_instr_as_alu(instr));
4644 break;
4645
4646 case nir_instr_type_tex:
4647 bi_emit_tex(b, nir_instr_as_tex(instr));
4648 break;
4649
4650 case nir_instr_type_jump:
4651 bi_emit_jump(b, nir_instr_as_jump(instr));
4652 break;
4653
4654 case nir_instr_type_phi:
4655 bi_emit_phi(b, nir_instr_as_phi(instr));
4656 break;
4657
4658 default:
4659 UNREACHABLE("should've been lowered");
4660 }
4661 }
4662
4663 static bi_block *
4664 create_empty_block(bi_context *ctx)
4665 {
4666 bi_block *blk = rzalloc(ctx, bi_block);
4667
4668 util_dynarray_init(&blk->predecessors, blk);
4669
4670 _mesa_pointer_set_init(&blk->dom_frontier, ctx);
4671
4672 return blk;
4673 }
4674
4675 static bi_block *
4676 emit_block(bi_context *ctx, nir_block *block)
4677 {
4678 if (ctx->after_block) {
4679 ctx->current_block = ctx->after_block;
4680 ctx->after_block = NULL;
4681 } else {
4682 ctx->current_block = create_empty_block(ctx);
4683 }
4684
4685 list_addtail(&ctx->current_block->link, &ctx->blocks);
4686 list_inithead(&ctx->current_block->instructions);
4687
4688 bi_builder _b = bi_init_builder(ctx, bi_after_block(ctx->current_block));
4689
4690 ctx->indexed_nir_blocks[block->index] = ctx->current_block;
4691
4692 nir_foreach_instr(instr, block) {
4693 _b.debug_info = instr->has_debug_info ? nir_instr_get_debug_info(instr) : NULL;
4694 bi_emit_instr(&_b, instr);
4695 }
4696
4697 return ctx->current_block;
4698 }
4699
4700 static void
4701 emit_if(bi_context *ctx, nir_if *nif)
4702 {
4703 bi_block *before_block = ctx->current_block;
4704
4705 /* Speculatively emit the branch, but we can't fill it in until later */
4706 bi_builder _b = bi_init_builder(ctx, bi_after_block(ctx->current_block));
4707 bi_instr *then_branch =
4708 bi_branchz_i16(&_b, bi_half(bi_src_index(&nif->condition), false),
4709 bi_zero(), BI_CMPF_EQ);
4710
4711 /* Emit the two subblocks. */
4712 bi_block *then_block = emit_cf_list(ctx, &nif->then_list);
4713 bi_block *end_then_block = ctx->current_block;
4714
4715 /* Emit second block */
4716
4717 bi_block *else_block = emit_cf_list(ctx, &nif->else_list);
4718 bi_block *end_else_block = ctx->current_block;
4719 ctx->after_block = create_empty_block(ctx);
4720
4721 /* Now that we have the subblocks emitted, fix up the branches */
4722
4723 assert(then_block);
4724 assert(else_block);
4725
4726 then_branch->branch_target = else_block;
4727
4728 /* Emit a jump from the end of the then block to the end of the else */
4729 _b.cursor = bi_after_block(end_then_block);
4730 bi_instr *then_exit = bi_jump(&_b, bi_zero());
4731 then_exit->branch_target = ctx->after_block;
4732
4733 bi_block_add_successor(end_then_block, then_exit->branch_target);
4734 bi_block_add_successor(end_else_block, ctx->after_block); /* fallthrough */
4735
4736 bi_block_add_successor(before_block,
4737 then_branch->branch_target); /* then_branch */
4738 bi_block_add_successor(before_block, then_block); /* fallthrough */
4739 }
4740
4741 static void
4742 emit_loop(bi_context *ctx, nir_loop *nloop)
4743 {
4744 assert(!nir_loop_has_continue_construct(nloop));
4745
4746 /* Remember where we are */
4747 bi_block *start_block = ctx->current_block;
4748
4749 bi_block *saved_break = ctx->break_block;
4750 bi_block *saved_continue = ctx->continue_block;
4751
4752 ctx->continue_block = create_empty_block(ctx);
4753 ctx->break_block = create_empty_block(ctx);
4754 ctx->after_block = ctx->continue_block;
4755 ctx->after_block->loop_header = true;
4756
4757 /* Emit the body itself */
4758 emit_cf_list(ctx, &nloop->body);
4759
4760 /* Branch back to loop back */
4761 bi_builder _b = bi_init_builder(ctx, bi_after_block(ctx->current_block));
4762 bi_instr *I = bi_jump(&_b, bi_zero());
4763 I->branch_target = ctx->continue_block;
4764 bi_block_add_successor(start_block, ctx->continue_block);
4765 bi_block_add_successor(ctx->current_block, ctx->continue_block);
4766
4767 ctx->after_block = ctx->break_block;
4768
4769 /* Pop off */
4770 ctx->break_block = saved_break;
4771 ctx->continue_block = saved_continue;
4772 ++ctx->loop_count;
4773 }
4774
4775 static bi_block *
4776 emit_cf_list(bi_context *ctx, struct exec_list *list)
4777 {
4778 bi_block *start_block = NULL;
4779
4780 foreach_list_typed(nir_cf_node, node, node, list) {
4781 switch (node->type) {
4782 case nir_cf_node_block: {
4783 bi_block *block = emit_block(ctx, nir_cf_node_as_block(node));
4784
4785 if (!start_block)
4786 start_block = block;
4787
4788 break;
4789 }
4790
4791 case nir_cf_node_if:
4792 emit_if(ctx, nir_cf_node_as_if(node));
4793 break;
4794
4795 case nir_cf_node_loop:
4796 emit_loop(ctx, nir_cf_node_as_loop(node));
4797 break;
4798
4799 default:
4800 UNREACHABLE("Unknown control flow");
4801 }
4802 }
4803
4804 return start_block;
4805 }
4806
4807 /* shader-db stuff */
4808
4809 struct bi_stats {
4810 unsigned nr_clauses, nr_tuples, nr_ins;
4811 unsigned nr_arith, nr_texture, nr_varying, nr_ldst;
4812 unsigned nr_fau_uniforms;
4813 uint64_t reg_mask;
4814 };
4815
4816 static uint64_t
4817 bi_tuple_regs_used(const bi_registers *regs)
4818 {
4819 uint64_t mask = 0;
4820
4821 /* note: the stats gathering runs before final packing,
4822 * so no need to handle the 63-x trick and similar issues
4823 */
4824 if (regs->enabled[0]) {
4825 mask |= BITFIELD64_BIT(regs->slot[0]);
4826 }
4827 if (regs->enabled[1]) {
4828 mask |= BITFIELD64_BIT(regs->slot[1]);
4829 }
4830 if (regs->slot23.slot2) {
4831 mask |= BITFIELD64_BIT(regs->slot[2]);
4832 }
4833 if (regs->slot23.slot3) {
4834 mask |= BITFIELD64_BIT(regs->slot[3]);
4835 }
4836 return mask;
4837 }
4838
4839 static void
4840 bi_count_tuple_stats(bi_clause *clause, bi_tuple *tuple, struct bi_stats *stats)
4841 {
4842 /* check for FAU access */
4843 if (tuple->fau_idx & 0x80) {
4844 unsigned ureg = 1 + (tuple->fau_idx & 0x7f);
4845 stats->nr_fau_uniforms = MAX2(stats->nr_fau_uniforms, 2*ureg);
4846 }
4847 stats->reg_mask |= bi_tuple_regs_used(&tuple->regs);
4848
4849 /* Count instructions */
4850 stats->nr_ins += (tuple->fma ? 1 : 0) + (tuple->add ? 1 : 0);
4851
4852 /* Non-message passing tuples are always arithmetic */
4853 if (tuple->add != clause->message) {
4854 stats->nr_arith++;
4855 return;
4856 }
4857
4858 /* Message + FMA we'll count as arithmetic _and_ message */
4859 if (tuple->fma)
4860 stats->nr_arith++;
4861
4862 switch (clause->message_type) {
4863 case BIFROST_MESSAGE_VARYING:
4864 /* Check components interpolated */
4865 stats->nr_varying +=
4866 (clause->message->vecsize + 1) *
4867 (bi_is_regfmt_16(clause->message->register_format) ? 1 : 2);
4868 break;
4869
4870 case BIFROST_MESSAGE_VARTEX:
4871 /* 2 coordinates, fp32 each */
4872 stats->nr_varying += (2 * 2);
4873 FALLTHROUGH;
4874 case BIFROST_MESSAGE_TEX:
4875 stats->nr_texture++;
4876 break;
4877
4878 case BIFROST_MESSAGE_ATTRIBUTE:
4879 case BIFROST_MESSAGE_LOAD:
4880 case BIFROST_MESSAGE_STORE:
4881 case BIFROST_MESSAGE_ATOMIC:
4882 stats->nr_ldst++;
4883 break;
4884
4885 case BIFROST_MESSAGE_NONE:
4886 case BIFROST_MESSAGE_BARRIER:
4887 case BIFROST_MESSAGE_BLEND:
4888 case BIFROST_MESSAGE_TILE:
4889 case BIFROST_MESSAGE_Z_STENCIL:
4890 case BIFROST_MESSAGE_ATEST:
4891 case BIFROST_MESSAGE_JOB:
4892 case BIFROST_MESSAGE_64BIT:
4893 /* Nothing to do */
4894 break;
4895 };
4896 }
4897
4898 /*
4899 * v7 allows preloading LD_VAR or VAR_TEX messages that must complete before the
4900 * shader completes. These costs are not accounted for in the general cycle
4901 * counts, so this function calculates the effective cost of these messages, as
4902 * if they were executed by shader code.
4903 */
4904 static unsigned
4905 bi_count_preload_cost(bi_context *ctx)
4906 {
4907 /* Units: 1/16 of a normalized cycle, assuming that we may interpolate
4908 * 16 fp16 varying components per cycle or fetch two texels per cycle.
4909 */
4910 unsigned cost = 0;
4911
4912 for (unsigned i = 0; i < ARRAY_SIZE(ctx->info.bifrost->messages); ++i) {
4913 struct bifrost_message_preload msg = ctx->info.bifrost->messages[i];
4914
4915 if (msg.enabled && msg.texture) {
4916 /* 2 coordinate, 2 half-words each, plus texture */
4917 cost += 12;
4918 } else if (msg.enabled) {
4919 cost += (msg.num_components * (msg.fp16 ? 1 : 2));
4920 }
4921 }
4922
4923 return cost;
4924 }
4925
4926 static const char *
4927 bi_shader_stage_name(bi_context *ctx)
4928 {
4929 if (ctx->idvs == BI_IDVS_VARYING)
4930 return "MESA_SHADER_VARYING";
4931 else if (ctx->idvs == BI_IDVS_POSITION)
4932 return "MESA_SHADER_POSITION";
4933 else if (ctx->inputs->is_blend)
4934 return "MESA_SHADER_BLEND";
4935 else
4936 return mesa_shader_stage_name(ctx->stage);
4937 }
4938
4939 static void
4940 bi_gather_stats(bi_context *ctx, unsigned size, struct bifrost_stats *out)
4941 {
4942 struct bi_stats counts = {0};
4943
4944 /* Count instructions, clauses, and tuples. Also attempt to construct
4945 * normalized execution engine cycle counts, using the following ratio:
4946 *
4947 * 24 arith tuples/cycle
4948 * 2 texture messages/cycle
4949 * 16 x 16-bit varying channels interpolated/cycle
4950 * 1 load store message/cycle
4951 *
4952 * These numbers seem to match Arm Mobile Studio's heuristic. The real
4953 * cycle counts are surely more complicated.
4954 */
4955
4956 bi_foreach_block(ctx, block) {
4957 bi_foreach_clause_in_block(block, clause) {
4958 counts.nr_clauses++;
4959 counts.nr_tuples += clause->tuple_count;
4960
4961 for (unsigned i = 0; i < clause->tuple_count; ++i)
4962 bi_count_tuple_stats(clause, &clause->tuples[i], &counts);
4963 }
4964 }
4965
4966 /* Thread count and register pressure are traded off only on v7 */
4967 bool full_threads = (ctx->arch == 7 && ctx->info.work_reg_count <= 32);
4968
4969 *out = (struct bifrost_stats){
4970 .instrs = counts.nr_ins,
4971 .tuples = counts.nr_tuples,
4972 .clauses = counts.nr_clauses,
4973 .arith = ((float)counts.nr_arith) / 24.0,
4974 .t = ((float)counts.nr_texture) / 2.0,
4975 .v = ((float)counts.nr_varying) / 16.0,
4976 .ldst = ((float)counts.nr_ldst) / 1.0,
4977 .code_size = size,
4978 .preloads = ctx->arch == 7 ? bi_count_preload_cost(ctx) : 0,
4979 .threads = full_threads ? 2 : 1,
4980 .loops = ctx->loop_count,
4981 .spills = ctx->spills,
4982 .fills = ctx->fills,
4983 .spill_cost = ctx->spill_cost,
4984 .registers_used = util_bitcount64(counts.reg_mask),
4985 .uniforms_used = counts.nr_fau_uniforms,
4986 };
4987
4988 out->cycles = MAX2(out->arith, MAX3(out->t, out->v, out->ldst));
4989 }
4990
4991 static void
4992 va_count_stats(bi_context *ctx, unsigned nr_ins, unsigned size,
4993 const struct va_stats *counts,
4994 struct valhall_stats *out)
4995 {
4996 const struct pan_model *model =
4997 pan_get_model(ctx->inputs->gpu_id, ctx->inputs->gpu_variant);
4998
4999 if (model == NULL) {
5000 /* Get G57 by default: */
5001 model = pan_get_model(((uint64_t)0x9001) << 16, 0);
5002 assert(model);
5003 }
5004
5005 struct valhall_stats stats_abs = {
5006 .instrs = nr_ins,
5007 .code_size = size,
5008 .fma = ((float)counts->fma),
5009 .cvt = ((float)counts->cvt),
5010 .sfu = ((float)counts->sfu),
5011 .v = ((float)counts->v),
5012 .t = ((float)counts->t),
5013 .ls = ((float)counts->ls),
5014 .threads = (ctx->info.work_reg_count <= 32) ? 2 : 1,
5015 .loops = ctx->loop_count,
5016 .spills = ctx->spills,
5017 .fills = ctx->fills,
5018 .spill_cost = ctx->spill_cost,
5019 .registers_used = util_bitcount64(counts->reg_mask),
5020 .uniforms_used = counts->nr_fau_uniforms,
5021 };
5022 struct valhall_stats stats = stats_abs;
5023 stats.fma /= model->rates.fma;
5024 stats.cvt /= model->rates.fma;
5025 stats.sfu /= (model->rates.fma / 4.0);
5026 stats.v /= 16.0;
5027 stats.t /= model->rates.texel;
5028 stats.ls /= 1.0;
5029
5030 const bool output_normalized = !(bifrost_debug & BIFROST_DBG_STATSABS);
5031 *out = output_normalized ? stats : stats_abs;
5032
5033 /* Calculate the bound */
5034 out->cycles = MAX2(MAX3(stats.fma, stats.cvt, stats.sfu),
5035 MAX3(stats.v, stats.t, stats.ls));
5036 }
5037
5038 static unsigned
5039 va_gather_stats_block(bi_block *block, struct va_stats *counts)
5040 {
5041 unsigned nr_ins = 0;
5042
5043 bi_foreach_instr_in_block(block, I) {
5044 nr_ins++;
5045 va_count_instr_stats(I, counts);
5046 }
5047 return nr_ins;
5048 }
5049
5050 /*
5051 * Gather stats for a minimum length path through the shader.
5052 */
5053 static unsigned
5054 va_gather_min_path_stats(bi_block *block, struct va_stats *counts)
5055 {
5056 struct va_stats min_counts;
5057 struct va_stats save_counts = *counts;
5058 unsigned min_ins = 0;
5059 unsigned nr_ins;
5060
5061 bi_foreach_successor(block, next) {
5062 // if following a path leads to a loop, do not do it
5063 if (bi_block_dominates(next, block)) {
5064 continue;
5065 }
5066 nr_ins = va_gather_min_path_stats(next, counts);
5067 if (min_ins == 0 || nr_ins < min_ins) {
5068 min_ins = nr_ins;
5069 min_counts = *counts;
5070 }
5071 *counts = save_counts;
5072 }
5073 if (min_ins != 0) {
5074 *counts = min_counts;
5075 }
5076 nr_ins = min_ins + va_gather_stats_block(block, counts);
5077 return nr_ins;
5078 }
5079
5080 /*
5081 * Gather stats for a maximum length path through the shader.
5082 * This is slightly tricky because we do want to count loops,
5083 * but at most once. If we see we've visited a block already,
5084 * bail out.
5085 */
5086 static unsigned
5087 va_gather_max_path_stats(bi_block *block, struct va_stats *counts, BITSET_WORD *visited)
5088 {
5089 struct va_stats max_counts;
5090 struct va_stats save_counts = *counts;
5091 unsigned max_ins = 0;
5092 unsigned nr_ins;
5093
5094 BITSET_SET(visited, block->index);
5095 bi_foreach_successor(block, next) {
5096 // if we've already visited this block, skip it
5097 if (BITSET_TEST(visited, next->index)) {
5098 continue;
5099 }
5100 nr_ins = va_gather_max_path_stats(next, counts, visited);
5101 if (nr_ins > max_ins) {
5102 max_ins = nr_ins;
5103 max_counts = *counts;
5104 }
5105 *counts = save_counts;
5106 }
5107 if (max_ins != 0) {
5108 *counts = max_counts;
5109 }
5110 nr_ins = max_ins + va_gather_stats_block(block, counts);
5111 return nr_ins;
5112 }
5113
5114 enum gather_stats_mode {
5115 GATHER_STATS_FULL = 0,
5116 GATHER_STATS_MIN,
5117 GATHER_STATS_MAX
5118 };
5119
5120 static void
5121 va_gather_stats(bi_context *ctx, unsigned size, struct valhall_stats *out,
5122 enum gather_stats_mode mode)
5123 {
5124 unsigned nr_ins = 0;
5125 struct va_stats counts = {0};
5126 bi_block *first_block = bi_start_block(&ctx->blocks);
5127 BITSET_WORD *visited;
5128
5129 /* Count instructions */
5130 switch (mode) {
5131 case GATHER_STATS_FULL:
5132 bi_foreach_instr_global(ctx, I) {
5133 nr_ins++;
5134 va_count_instr_stats(I, &counts);
5135 }
5136 break;
5137 case GATHER_STATS_MIN:
5138 nr_ins = va_gather_min_path_stats(first_block, &counts);
5139 break;
5140 case GATHER_STATS_MAX:
5141 visited = BITSET_RZALLOC(NULL, ctx->num_blocks);
5142 nr_ins = va_gather_max_path_stats(first_block, &counts, visited);
5143 ralloc_free(visited);
5144 break;
5145 }
5146 /* convert to stats */
5147 va_count_stats(ctx, nr_ins, size, &counts, out);
5148 }
5149
5150 static void
5151 bi_opt_post_ra(bi_context *ctx)
5152 {
5153 bi_foreach_instr_global_safe(ctx, ins) {
5154 if (ins->op == BI_OPCODE_MOV_I32 &&
5155 bi_is_equiv(ins->dest[0], ins->src[0]))
5156 bi_remove_instruction(ins);
5157 }
5158 }
5159
5160 /* Dead code elimination for branches at the end of a block - only one branch
5161 * per block is legal semantically, but unreachable jumps can be generated.
5162 * Likewise on Bifrost we can generate jumps to the terminal block which need
5163 * to be lowered away to a jump to #0x0, which induces successful termination.
5164 * That trick doesn't work on Valhall, which needs a NOP inserted in the
5165 * terminal block instead.
5166 */
5167 static void
5168 bi_lower_branch(bi_context *ctx, bi_block *block)
5169 {
5170 bool cull_terminal = (ctx->arch <= 8);
5171 bool branched = false;
5172
5173 bi_foreach_instr_in_block_safe(block, ins) {
5174 if (!ins->branch_target)
5175 continue;
5176
5177 if (branched) {
5178 bi_remove_instruction(ins);
5179 continue;
5180 }
5181
5182 branched = true;
5183
5184 if (!bi_is_terminal_block(ins->branch_target))
5185 continue;
5186
5187 if (cull_terminal)
5188 ins->branch_target = NULL;
5189 else if (ins->branch_target)
5190 ins->branch_target->needs_nop = true;
5191 }
5192 }
5193
5194 static void
5195 bi_pack_clauses(bi_context *ctx, struct util_dynarray *binary, unsigned offset)
5196 {
5197 unsigned final_clause = bi_pack(ctx, binary);
5198
5199 /* If we need to wait for ATEST or BLEND in the first clause, pass the
5200 * corresponding bits through to the renderer state descriptor */
5201 bi_block *first_block = list_first_entry(&ctx->blocks, bi_block, link);
5202 bi_clause *first_clause = bi_next_clause(ctx, first_block, NULL);
5203
5204 unsigned first_deps = first_clause ? first_clause->dependencies : 0;
5205 ctx->info.bifrost->wait_6 = (first_deps & (1 << 6));
5206 ctx->info.bifrost->wait_7 = (first_deps & (1 << 7));
5207
5208 /* Pad the shader with enough zero bytes to trick the prefetcher,
5209 * unless we're compiling an empty shader (in which case we don't pad
5210 * so the size remains 0) */
5211 unsigned prefetch_size = BIFROST_SHADER_PREFETCH - final_clause;
5212
5213 if (binary->size - offset) {
5214 memset(util_dynarray_grow(binary, uint8_t, prefetch_size), 0,
5215 prefetch_size);
5216 }
5217 }
5218
5219 static int
5220 compare_u32(const void* a, const void* b, void* _)
5221 {
5222 const uint32_t va = (uintptr_t)a;
5223 const uint32_t vb = (uintptr_t)b;
5224 return va - vb;
5225 }
5226
5227 static bi_context *
5228 bi_compile_variant_nir(nir_shader *nir,
5229 const struct pan_compile_inputs *inputs,
5230 struct util_dynarray *binary, struct pan_shader_info *pinfo,
5231 struct pan_stats *stats, enum bi_idvs_mode idvs)
5232 {
5233 bi_context *ctx = rzalloc(NULL, bi_context);
5234 struct bi_shader_info info = {
5235 .push = &pinfo->push,
5236 .bifrost = &pinfo->bifrost,
5237 .tls_size = pinfo->tls_size,
5238 .push_offset = pinfo->push.count,
5239 .init_fau_consts_count = pinfo->fau_consts_count,
5240 };
5241
5242 /* There may be another program in the dynarray, start at the end */
5243 unsigned offset = binary->size;
5244
5245 ctx->inputs = inputs;
5246 ctx->nir = nir;
5247 ctx->stage = nir->info.stage;
5248 ctx->quirks = bifrost_get_quirks(inputs->gpu_id);
5249 ctx->arch = pan_arch(inputs->gpu_id);
5250 ctx->info = info;
5251 ctx->idvs = idvs;
5252 ctx->malloc_idvs = (ctx->arch >= 9) && !inputs->no_idvs;
5253 ctx->fau_consts_count = info.init_fau_consts_count;
5254
5255 unsigned execution_mode = nir->info.float_controls_execution_mode;
5256 ctx->rtz_fp16 = nir_is_rounding_mode_rtz(execution_mode, 16);
5257 ctx->rtz_fp32 = nir_is_rounding_mode_rtz(execution_mode, 32);
5258 ctx->ftz_fp32 = nir_is_denorm_flush_to_zero(execution_mode, 32);
5259
5260 if (idvs == BI_IDVS_POSITION || idvs == BI_IDVS_VARYING) {
5261 /* Specializing shaders for IDVS is destructive, so we need to
5262 * clone. However, the last (second) IDVS shader does not need
5263 * to be preserved so we can skip cloning that one.
5264 */
5265 if (offset == 0)
5266 ctx->nir = nir = nir_shader_clone(ctx, nir);
5267
5268 uint64_t position = VA_SHADER_OUTPUT_POSITION_BIT |
5269 VA_SHADER_OUTPUT_ATTRIB_BIT;
5270
5271 NIR_PASS(_, nir, nir_inline_sysval, nir_intrinsic_load_shader_output_pan,
5272 (idvs == BI_IDVS_POSITION) ? position : VA_SHADER_OUTPUT_VARY_BIT);
5273
5274 /* After specializing, clean up the mess */
5275 bool progress = true;
5276
5277 while (progress) {
5278 progress = false;
5279
5280 NIR_PASS(progress, nir, nir_opt_constant_folding);
5281 NIR_PASS(progress, nir, nir_opt_dce);
5282 NIR_PASS(progress, nir, nir_opt_dead_cf);
5283 NIR_PASS(progress, nir, nir_opt_cse);
5284 }
5285 }
5286
5287 /* If nothing is pushed, all UBOs need to be uploaded */
5288 ctx->ubo_mask = ~0;
5289
5290 list_inithead(&ctx->blocks);
5291
5292 bool skip_internal = nir->info.internal;
5293 skip_internal &= !(bifrost_debug & BIFROST_DBG_INTERNAL);
5294
5295 if (bifrost_debug & BIFROST_DBG_SHADERS && !skip_internal) {
5296 /* Assign lines. Must be done last. */
5297 if (bifrost_debug & BIFROST_DBG_DEBUGINFO)
5298 ralloc_free(nir_shader_gather_debug_info(nir, "", 1));
5299
5300 nir_print_shader(nir, stderr);
5301 }
5302
5303 ctx->allocated_vec = _mesa_hash_table_u64_create(ctx);
5304
5305 nir_foreach_function_impl(impl, nir) {
5306 nir_index_blocks(impl);
5307 nir_index_ssa_defs(impl);
5308
5309 ctx->indexed_nir_blocks =
5310 rzalloc_array(ctx, bi_block *, impl->num_blocks);
5311
5312 ctx->ssa_alloc += impl->ssa_alloc;
5313
5314 emit_cf_list(ctx, &impl->body);
5315 bi_emit_phis_deferred(ctx);
5316 break; /* TODO: Multi-function shaders */
5317 }
5318
5319 /* Index blocks now that we're done emitting */
5320 bi_foreach_block(ctx, block) {
5321 block->index = ctx->num_blocks++;
5322 }
5323
5324 bi_validate(ctx, "NIR -> BIR");
5325
5326 bool optimize = !(bifrost_debug & BIFROST_DBG_NOOPT);
5327
5328 /* Runs before constant folding */
5329 bi_lower_swizzle(ctx);
5330 bi_validate(ctx, "Early lowering");
5331
5332 /* Runs before copy prop */
5333 if (optimize && ctx->inputs->pushable_ubos) {
5334 bi_opt_push_ubo(ctx);
5335 }
5336
5337 if (likely(optimize)) {
5338 bi_opt_copy_prop(ctx);
5339
5340 while (bi_opt_constant_fold(ctx))
5341 bi_opt_copy_prop(ctx);
5342
5343 bi_opt_mod_prop_forward(ctx);
5344 bi_opt_mod_prop_backward(ctx);
5345
5346 /* Push LD_VAR_IMM/VAR_TEX instructions. Must run after
5347 * mod_prop_backward to fuse VAR_TEX */
5348 if (ctx->arch == 7 && ctx->stage == MESA_SHADER_FRAGMENT &&
5349 !(bifrost_debug & BIFROST_DBG_NOPRELOAD)) {
5350 bi_opt_dce(ctx, false);
5351 bi_opt_message_preload(ctx);
5352 bi_opt_copy_prop(ctx);
5353 }
5354
5355 bi_opt_dce(ctx, false);
5356 bi_opt_cse(ctx);
5357 bi_opt_dce(ctx, false);
5358 if (ctx->inputs->pushable_ubos)
5359 bi_opt_reorder_push(ctx);
5360 bi_validate(ctx, "Optimization passes");
5361 }
5362
5363 bi_lower_opt_instructions(ctx);
5364 bi_lower_mkvec_swz(ctx);
5365
5366 if (ctx->arch >= 9) {
5367 va_lower_isel(ctx);
5368 va_optimize(ctx);
5369
5370 /* Count how often a specific constant appears. */
5371 struct hash_table_u64 *const_hist = _mesa_hash_table_u64_create(ctx);
5372 bi_foreach_instr_global_safe(ctx, I) {
5373 /* Phis become single moves so shouldn't be affected */
5374 if (I->op == BI_OPCODE_PHI)
5375 continue;
5376
5377 va_count_constants(ctx, I, const_hist);
5378 }
5379
5380 uint32_t const_amount = _mesa_hash_table_u64_num_entries(const_hist);
5381 uint32_t *sorted = rzalloc_array(ctx, uint32_t, const_amount);
5382
5383 uint32_t idx = 0;
5384 hash_table_u64_foreach(const_hist, entry)
5385 {
5386 sorted[idx++] = (uintptr_t)entry.data;
5387 }
5388
5389 util_qsort_r(sorted, const_amount, sizeof(uint32_t), compare_u32, NULL);
5390 uint32_t max_amount = MIN2(const_amount, ctx->inputs->fau_consts.max_amount);
5391 uint32_t min_count_for_fau = max_amount > 0 ? sorted[max_amount - 1] : 0;
5392 ralloc_free(sorted);
5393
5394 bi_foreach_instr_global_safe(ctx, I) {
5395 /* Phis become single moves so shouldn't be affected */
5396 if (I->op == BI_OPCODE_PHI)
5397 continue;
5398
5399 va_lower_constants(ctx, I, const_hist, min_count_for_fau);
5400
5401 bi_builder b = bi_init_builder(ctx, bi_before_instr(I));
5402 va_repair_fau(&b, I);
5403 }
5404
5405 _mesa_hash_table_u64_destroy(const_hist);
5406
5407 /* We need to clean up after constant lowering */
5408 if (likely(optimize)) {
5409 bi_opt_cse(ctx);
5410 bi_opt_dce(ctx, false);
5411 }
5412
5413 bi_validate(ctx, "Valhall passes");
5414 }
5415
5416 bi_foreach_block(ctx, block) {
5417 bi_lower_branch(ctx, block);
5418 }
5419
5420 if (bifrost_debug & BIFROST_DBG_SHADERS && !skip_internal)
5421 bi_print_shader(ctx, stderr);
5422
5423 /* Analyze before register allocation to avoid false dependencies. The
5424 * skip bit is a function of only the data flow graph and is invariant
5425 * under valid scheduling. Helpers are only defined for fragment
5426 * shaders, so this analysis is only required in fragment shaders.
5427 */
5428 if (ctx->stage == MESA_SHADER_FRAGMENT) {
5429 bi_opt_dce(ctx, false);
5430 bi_analyze_helper_requirements(ctx);
5431 }
5432
5433 /* Fuse TEXC after analyzing helper requirements so the analysis
5434 * doesn't have to know about dual textures */
5435 if (likely(optimize)) {
5436 bi_opt_fuse_dual_texture(ctx);
5437 }
5438
5439 /* Lower FAU after fusing dual texture, because fusing dual texture
5440 * creates new immediates that themselves may need lowering.
5441 */
5442 if (ctx->arch <= 8) {
5443 bi_lower_fau(ctx);
5444 }
5445
5446 /* Lowering FAU can create redundant moves. Run CSE+DCE to clean up. */
5447 if (likely(optimize)) {
5448 bi_opt_cse(ctx);
5449 bi_opt_dce(ctx, false);
5450 }
5451
5452 bi_validate(ctx, "Late lowering");
5453
5454 bi_iterator_schedule(ctx);
5455
5456 if (likely(!(bifrost_debug & BIFROST_DBG_NOPSCHED))) {
5457 bi_pressure_schedule(ctx);
5458 bi_validate(ctx, "Pre-RA scheduling");
5459 }
5460
5461 bi_register_allocate(ctx);
5462
5463 if (likely(optimize))
5464 bi_opt_post_ra(ctx);
5465
5466 if (bifrost_debug & BIFROST_DBG_SHADERS && !skip_internal)
5467 bi_print_shader(ctx, stderr);
5468
5469 bi_opt_control_flow(ctx);
5470
5471 if (ctx->arch >= 9) {
5472 va_assign_slots(ctx);
5473 va_insert_flow_control_nops(ctx);
5474 va_merge_flow(ctx);
5475 va_mark_last(ctx);
5476 } else {
5477 bi_schedule(ctx);
5478 bi_assign_scoreboard(ctx);
5479
5480 /* Analyze after scheduling since we depend on instruction
5481 * order. Valhall calls as part of va_insert_flow_control_nops,
5482 * as the handling for clauses differs from instructions.
5483 */
5484 bi_analyze_helper_terminate(ctx);
5485 bi_mark_clauses_td(ctx);
5486 }
5487
5488 if (bifrost_debug & BIFROST_DBG_SHADERS && !skip_internal)
5489 bi_print_shader(ctx, stderr);
5490
5491 if (ctx->arch <= 8) {
5492 bi_pack_clauses(ctx, binary, offset);
5493 } else {
5494 bi_pack_valhall(ctx, binary);
5495 }
5496
5497 if (bifrost_debug & BIFROST_DBG_SHADERS && !skip_internal) {
5498 if (ctx->arch <= 8) {
5499 disassemble_bifrost(stderr, binary->data + offset,
5500 binary->size - offset,
5501 bifrost_debug & BIFROST_DBG_VERBOSE);
5502 } else {
5503 disassemble_valhall(stderr, binary->data + offset,
5504 binary->size - offset,
5505 bifrost_debug & BIFROST_DBG_VERBOSE);
5506 }
5507
5508 fflush(stderr);
5509 }
5510
5511 /* gather instruction statistics */
5512 if (ctx->arch >= 9) {
5513 stats->isa = PAN_STAT_VALHALL;
5514 va_gather_stats(ctx, binary->size - offset, &stats->valhall, GATHER_STATS_FULL);
5515 } else {
5516 stats->isa = PAN_STAT_BIFROST;
5517 bi_gather_stats(ctx, binary->size - offset, &stats->bifrost);
5518 }
5519
5520 if (ctx->arch >= 13)
5521 va_gather_hsr_info(ctx, pinfo);
5522
5523 /* update info struct */
5524 pan_shader_update_info(pinfo, ctx->nir, inputs);
5525
5526 if ((bifrost_debug & (BIFROST_DBG_SHADERDB|BIFROST_DBG_STATSFULL))
5527 && !skip_internal) {
5528 const char *prefix = bi_shader_stage_name(ctx);
5529 if (bifrost_debug & BIFROST_DBG_STATSFULL) {
5530 pan_stats_verbose(stderr, prefix, ctx, stats, pinfo);
5531 } else {
5532 pan_stats_fprintf(stderr, prefix, stats);
5533 }
5534 }
5535
5536 return ctx;
5537 }
5538
5539 void
5540 bi_compile_variant(nir_shader *nir,
5541 const struct pan_compile_inputs *inputs,
5542 struct util_dynarray *binary, struct pan_shader_info *info,
5543 enum bi_idvs_mode idvs)
5544 {
5545 unsigned offset = binary->size;
5546
5547 /* If there is no position shader (gl_Position is not written), then
5548 * there is no need to build a varying shader either. This case is hit
5549 * for transform feedback only vertex shaders which only make sense with
5550 * rasterizer discard.
5551 */
5552 if ((offset == 0) && (idvs == BI_IDVS_VARYING))
5553 return;
5554
5555 /* Software invariant: Only a secondary shader can appear at a nonzero
5556 * offset, to keep the ABI simple. */
5557 assert((offset == 0) ^ (idvs == BI_IDVS_VARYING));
5558
5559 struct pan_stats *stats =
5560 idvs == BI_IDVS_VARYING ? &info->stats_idvs_varying : &info->stats;
5561
5562 bi_context *ctx =
5563 bi_compile_variant_nir(nir, inputs, binary, info, stats, idvs);
5564
5565 info->fau_consts_count = ctx->fau_consts_count;
5566
5567 /* A register is preloaded <==> it is live before the first block */
5568 bi_block *first_block = list_first_entry(&ctx->blocks, bi_block, link);
5569 uint64_t preload = first_block->reg_live_in;
5570
5571 /* If multisampling is used with a blend shader, the blend shader needs
5572 * to access the sample coverage mask in r60 and the sample ID in r61.
5573 * Blend shaders run in the same context as fragment shaders, so if a
5574 * blend shader could run, we need to preload these registers
5575 * conservatively. There is believed to be little cost to doing so, so
5576 * do so always to avoid variants of the preload descriptor.
5577 *
5578 * We only do this on Valhall, as Bifrost has to update the RSD for
5579 * multisampling w/ blend shader anyway, so this is handled in the
5580 * driver. We could unify the paths if the cost is acceptable.
5581 */
5582 if (nir->info.stage == MESA_SHADER_FRAGMENT && ctx->arch >= 9)
5583 preload |= BITFIELD64_BIT(60) | BITFIELD64_BIT(61);
5584
5585 info->ubo_mask |= ctx->ubo_mask;
5586 info->tls_size = MAX2(info->tls_size, ctx->info.tls_size);
5587 info->has_shader_clk_instr = ctx->info.has_ld_gclk_instr;
5588
5589 if (idvs == BI_IDVS_VARYING) {
5590 info->vs.secondary_enable = (binary->size > offset);
5591 info->vs.secondary_offset = offset;
5592 info->vs.secondary_preload = preload;
5593 info->vs.secondary_work_reg_count = ctx->info.work_reg_count;
5594 } else {
5595 info->preload = preload;
5596 info->work_reg_count = ctx->info.work_reg_count;
5597
5598 if (idvs == BI_IDVS_ALL) {
5599 /* Varying shader is only enabled if we can have any kind of varying
5600 * written (that mean not position, or an extended FIFO attribute) */
5601 info->vs.secondary_enable =
5602 (nir->info.outputs_written &
5603 ~(VARYING_BIT_POS | VALHAL_EX_FIFO_VARYING_BITS)) != 0;
5604 }
5605 }
5606
5607 if ((idvs == BI_IDVS_POSITION || idvs == BI_IDVS_ALL) &&
5608 !nir->info.internal &&
5609 nir->info.outputs_written & VARYING_BIT_PSIZ) {
5610 /* Find the psiz write */
5611 bi_instr *write = NULL;
5612
5613 bi_foreach_instr_global(ctx, I) {
5614 if (I->is_psiz_write) {
5615 write = I;
5616 break;
5617 }
5618 }
5619
5620 assert(write != NULL);
5621
5622 /* NOP it out, preserving its flow control. TODO: maybe DCE */
5623 if (write->flow) {
5624 bi_builder b = bi_init_builder(ctx, bi_before_instr(write));
5625 bi_instr *nop = bi_nop(&b);
5626 nop->flow = write->flow;
5627 }
5628
5629 bi_remove_instruction(write);
5630
5631 info->vs.no_psiz_offset = binary->size;
5632 bi_pack_valhall(ctx, binary);
5633 }
5634
5635 ralloc_free(ctx);
5636 }
5637
5638 static void
5639 find_all_predecessors(const bi_context *ctx, bi_block *b, BITSET_WORD *out)
5640 {
5641 assert(out);
5642 assert(b);
5643
5644 BITSET_CLEAR_COUNT(out, 0, ctx->num_blocks);
5645
5646 /* If the CFG was one long chain, we would require |blocks|-1 iters to
5647 * propagate the in_loop info all the way through.
5648 */
5649 for (uint32_t iter = 0; iter < ctx->num_blocks - 1; ++iter) {
5650 bi_foreach_block(ctx, block) {
5651 bi_foreach_successor(block, succ) {
5652 if (succ == b || BITSET_TEST(out, succ->index)) {
5653 BITSET_SET(out, block->index);
5654 break;
5655 }
5656 }
5657 }
5658 }
5659 }
5660
5661 void
5662 bi_find_loop_blocks(const bi_context *ctx, bi_block *header, BITSET_WORD *out)
5663 {
5664 find_all_predecessors(ctx, header, out);
5665
5666 BITSET_WORD *dominators = BITSET_RZALLOC(NULL, ctx->num_blocks);
5667 bi_foreach_block(ctx, b) {
5668 if (bi_block_dominates(header, b)) {
5669 BITSET_SET(dominators, b->index);
5670 }
5671 }
5672
5673 /* If the header dominates b and is also the successor of b, then b
5674 * is in the loop of that header.
5675 */
5676 __bitset_and(out, out, dominators, BITSET_WORDS(ctx->num_blocks));
5677
5678 /* The header is not a predecessor of itself, so add it separately. */
5679 BITSET_SET(out, header->index);
5680
5681 ralloc_free(dominators);
5682 }
5683
5684 /*
5685 * verbose stat printing
5686 * enable with BIFROST_MESA_DEBUG=statsfull
5687 */
5688 static unsigned
5689 percent_used(unsigned cur, unsigned max)
5690 {
5691 return (unsigned)(0.5 + 100 * cur / (double)max);
5692 }
5693
5694 static void
5695 report_regs(FILE *f, unsigned registers_used, unsigned uniforms_used)
5696 {
5697 fprintf(f, "Work registers: %u ", registers_used);
5698 if (registers_used <= 32) {
5699 fprintf(f, "(%u%% used at 100%% occupancy)\n",
5700 percent_used(registers_used, 32));
5701 } else {
5702 fprintf(f, "(%u%% used at 50%% occupancy)\n",
5703 percent_used(registers_used, 64));
5704 }
5705 fprintf(f, "Uniform registers: %u (%u%% used)\n",
5706 uniforms_used,
5707 percent_used(uniforms_used, 128));
5708 }
5709
5710 /*
5711 * This function prints the pipe statistics in statval[], with `prefix` as
5712 * a leading message (e.g. prefix can indicate total stats, max path, etc.).
5713 * As a special case, if prefix is empty, only the column headings are
5714 * printed.
5715 */
5716 static void
5717 do_report_pipes(FILE *f, const char *prefix, unsigned n, const char *statname[], float statval[])
5718 {
5719 unsigned limit_idx = 0;
5720 float limit_val = statval[0];
5721
5722 fprintf(f, "%-25s", prefix);
5723 if (*prefix == 0) {
5724 /* just print column headings, no stats */
5725 for (unsigned i = 0; i < n; i++) {
5726 fprintf(f, " %6s", statname[i]);
5727 }
5728 fprintf(f, " %6s\n", "Bound");
5729 return;
5730 }
5731 for (unsigned i = 0; i < n; i++) {
5732 fprintf(f, " %6.3f", statval[i]);
5733 if (statval[i] > limit_val) {
5734 limit_idx = i;
5735 limit_val = statval[i];
5736 }
5737 }
5738 /* print the first thing that matches the bound */
5739 char bound_str[256];
5740 unsigned max_str = sizeof(bound_str) - 1; /* leave room for trailing 0 */
5741 strncpy(bound_str, statname[limit_idx], max_str);
5742 /* now print any others that match */
5743 for (unsigned i = limit_idx + 1; i < n; i++) {
5744 if (statval[i] == limit_val) {
5745 strncat(bound_str, ", ", max_str);
5746 strncat(bound_str, statname[i], max_str);
5747 }
5748 }
5749 fprintf(f, " %6s\n", bound_str);
5750 }
5751 static void
5752 bifrost_stats_verbose(FILE *f, bi_context *ctx, const struct bifrost_stats *stats,
5753 const struct pan_shader_info *info)
5754 {
5755 report_regs(f, stats->registers_used, stats->uniforms_used);
5756 fprintf(f, "Code size: %u bytes\n", stats->code_size);
5757 fprintf(f, "Loops: %u\n", stats->loops);
5758 fprintf(f, "Spills/fills: %u/%u\n", stats->spills, stats->fills);
5759 fprintf(f, "Stack size: %u bytes\n", ctx->info.tls_size);
5760
5761 /* now print instruction statistics */
5762 static const char *statname[] = {
5763 "A", "LS", "V", "T"
5764 };
5765 float statval[] = {
5766 stats->arith, stats->ldst, stats->v, stats->t,
5767 };
5768 unsigned n = ARRAY_SIZE(statname);
5769 assert(n == ARRAY_SIZE(statval));
5770
5771 /* special case, empty prefix prints column headings */
5772 do_report_pipes(f, "", n, statname, statval);
5773 do_report_pipes(f, "Total instruction cycles:", n, statname, statval);
5774 fprintf(f, "\nA = Arithmetic, LS = Load/Store, V = Varying, T = Texture\n");
5775 }
5776
5777 static void
5778 valhall_stats_verbose(FILE *f, bi_context *ctx, const struct valhall_stats *stats,
5779 const struct pan_shader_info *info)
5780 {
5781 struct valhall_stats min_stats = { 0 };
5782 struct valhall_stats max_stats = { 0 };
5783
5784 report_regs(f, stats->registers_used, stats->uniforms_used);
5785 fprintf(f, "Code size: %u bytes\n", stats->code_size);
5786 fprintf(f, "Loops: %u\n", stats->loops);
5787 fprintf(f, "Spills/fills: %u/%u\n", stats->spills, stats->fills);
5788 fprintf(f, "Stack size: %u bytes\n", ctx->info.tls_size);
5789
5790 va_gather_stats(ctx, stats->code_size, &min_stats, GATHER_STATS_MIN);
5791 va_gather_stats(ctx, stats->code_size, &max_stats, GATHER_STATS_MAX);
5792
5793 /* now print instruction statistics */
5794 float arith = MAX3(stats->fma, stats->sfu, stats->cvt);
5795 float min_arith = MAX3(min_stats.fma, min_stats.sfu, min_stats.cvt);
5796 float max_arith = MAX3(max_stats.fma, max_stats.sfu, max_stats.cvt);
5797 static const char *statname[] = {
5798 "A", "FMA", "CVT", "SFU", "LS", "V", "T"
5799 };
5800 float statval[] = {
5801 arith, stats->fma, stats->cvt, stats->sfu, stats->ls, stats->v, stats->t,
5802 };
5803 float min_statval[] = {
5804 min_arith, min_stats.fma, min_stats.cvt, min_stats.sfu,
5805 min_stats.ls, min_stats.v, min_stats.t,
5806 };
5807 float max_statval[] = {
5808 max_arith, max_stats.fma, max_stats.cvt, max_stats.sfu,
5809 max_stats.ls, max_stats.v, max_stats.t,
5810 };
5811 unsigned n = ARRAY_SIZE(statval);
5812 assert(n == ARRAY_SIZE(statname));
5813 do_report_pipes(f, "", n, statname, statval);
5814 do_report_pipes(f, "Total instruction cycles:", n, statname, statval);
5815 do_report_pipes(f, "Shortest path cycles:", n, statname, min_statval);
5816 do_report_pipes(f, "Longest path cycles:", n, statname, max_statval);
5817 fprintf(f, "\nA = Arithmetic, FMA = Arith FMA, CVT = Arith CVT, SFU = Arith SFU\n");
5818 fprintf(f, "LS = Load/Store, V = Varying, T = Texture\n");
5819 }
5820
5821 static const char *bool_str(bool x) {
5822 return x ? "true" : "false";
5823 }
5824
5825 static void
5826 pan_stats_verbose(FILE *f, const char *prefix, bi_context *ctx, const struct pan_stats *stats,
5827 const struct pan_shader_info *info)
5828 {
5829 const struct pan_model *model = pan_get_model(ctx->inputs->gpu_id, ctx->inputs->gpu_variant);
5830 unsigned arch = (ctx->arch > 12) ? 0 : ctx->arch;
5831 const char *archname[] = {
5832 "Unknown", /* 0 must always be "Unknown" */
5833 "Lima", "Lima", "Lima", /* 1-3 */
5834 "Utgard", "Midgard", "Bifrost", "Bifrost", /* 4-7 */
5835 "Valhall", "Valhall", "Valhall", "Valhall", /* 8-11 */
5836 "Arm 5th Gen", /* 12 */
5837 };
5838
5839 fprintf(f, "\n");
5840 fprintf(f, "Model: %s\n", model->name);
5841 fprintf(f, "Shader type: %s\n", prefix);
5842 fprintf(f, "Architecture: %s\n", archname[arch]);
5843 switch (stats->isa) {
5844 case PAN_STAT_VALHALL:
5845 valhall_stats_verbose(f, ctx, &stats->valhall, info);
5846 break;
5847 case PAN_STAT_BIFROST:
5848 bifrost_stats_verbose(f, ctx, &stats->bifrost, info);
5849 break;
5850 default:
5851 pan_stats_fprintf(f, prefix, stats);
5852 break;
5853 }
5854 fprintf(f, "\n");
5855 fprintf(f, "Shader properties\n");
5856 fprintf(f, "=================\n");
5857 fprintf(f, "Contains barrier: %s\n", bool_str(info->contains_barrier));
5858 switch (info->stage) {
5859 case MESA_SHADER_FRAGMENT:
5860 fprintf(f, "Has side-effects: %s\n", bool_str(info->fs.sidefx));
5861 fprintf(f, "Modifies coverage: %s\n", bool_str(info->fs.writes_coverage));
5862 fprintf(f, "Reads color buffer: %s\n", bool_str(info->fs.outputs_read != 0));
5863 break;
5864 default:
5865 break;
5866 }
5867 fprintf(f, "\n");
5868 }