pan/mdg: Legalize inverts with constants
[mesa.git] / src / panfrost / midgard / midgard_compile.c
1 /*
2 * Copyright (C) 2018-2019 Alyssa Rosenzweig <alyssa@rosenzweig.io>
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 * SOFTWARE.
22 */
23
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <sys/mman.h>
27 #include <fcntl.h>
28 #include <stdint.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <err.h>
32
33 #include "main/mtypes.h"
34 #include "compiler/glsl/glsl_to_nir.h"
35 #include "compiler/nir_types.h"
36 #include "compiler/nir/nir_builder.h"
37 #include "util/half_float.h"
38 #include "util/u_math.h"
39 #include "util/u_debug.h"
40 #include "util/u_dynarray.h"
41 #include "util/list.h"
42 #include "main/mtypes.h"
43
44 #include "midgard.h"
45 #include "midgard_nir.h"
46 #include "midgard_compile.h"
47 #include "midgard_ops.h"
48 #include "helpers.h"
49 #include "compiler.h"
50 #include "midgard_quirks.h"
51
52 #include "disassemble.h"
53
54 static const struct debug_named_value debug_options[] = {
55 {"msgs", MIDGARD_DBG_MSGS, "Print debug messages"},
56 {"shaders", MIDGARD_DBG_SHADERS, "Dump shaders in NIR and MIR"},
57 {"shaderdb", MIDGARD_DBG_SHADERDB, "Prints shader-db statistics"},
58 DEBUG_NAMED_VALUE_END
59 };
60
61 DEBUG_GET_ONCE_FLAGS_OPTION(midgard_debug, "MIDGARD_MESA_DEBUG", debug_options, 0)
62
63 unsigned SHADER_DB_COUNT = 0;
64
65 int midgard_debug = 0;
66
67 #define DBG(fmt, ...) \
68 do { if (midgard_debug & MIDGARD_DBG_MSGS) \
69 fprintf(stderr, "%s:%d: "fmt, \
70 __FUNCTION__, __LINE__, ##__VA_ARGS__); } while (0)
71 static midgard_block *
72 create_empty_block(compiler_context *ctx)
73 {
74 midgard_block *blk = rzalloc(ctx, midgard_block);
75
76 blk->base.predecessors = _mesa_set_create(blk,
77 _mesa_hash_pointer,
78 _mesa_key_pointer_equal);
79
80 blk->base.name = ctx->block_source_count++;
81
82 return blk;
83 }
84
85 static void
86 schedule_barrier(compiler_context *ctx)
87 {
88 midgard_block *temp = ctx->after_block;
89 ctx->after_block = create_empty_block(ctx);
90 ctx->block_count++;
91 list_addtail(&ctx->after_block->base.link, &ctx->blocks);
92 list_inithead(&ctx->after_block->base.instructions);
93 pan_block_add_successor(&ctx->current_block->base, &ctx->after_block->base);
94 ctx->current_block = ctx->after_block;
95 ctx->after_block = temp;
96 }
97
98 /* Helpers to generate midgard_instruction's using macro magic, since every
99 * driver seems to do it that way */
100
101 #define EMIT(op, ...) emit_mir_instruction(ctx, v_##op(__VA_ARGS__));
102
103 #define M_LOAD_STORE(name, store, T) \
104 static midgard_instruction m_##name(unsigned ssa, unsigned address) { \
105 midgard_instruction i = { \
106 .type = TAG_LOAD_STORE_4, \
107 .mask = 0xF, \
108 .dest = ~0, \
109 .src = { ~0, ~0, ~0, ~0 }, \
110 .swizzle = SWIZZLE_IDENTITY_4, \
111 .load_store = { \
112 .op = midgard_op_##name, \
113 .address = address \
114 } \
115 }; \
116 \
117 if (store) { \
118 i.src[0] = ssa; \
119 i.src_types[0] = T; \
120 i.dest_type = T; \
121 } else { \
122 i.dest = ssa; \
123 i.dest_type = T; \
124 } \
125 return i; \
126 }
127
128 #define M_LOAD(name, T) M_LOAD_STORE(name, false, T)
129 #define M_STORE(name, T) M_LOAD_STORE(name, true, T)
130
131 M_LOAD(ld_attr_32, nir_type_uint32);
132 M_LOAD(ld_vary_32, nir_type_uint32);
133 M_LOAD(ld_ubo_int4, nir_type_uint32);
134 M_LOAD(ld_int4, nir_type_uint32);
135 M_STORE(st_int4, nir_type_uint32);
136 M_LOAD(ld_color_buffer_32u, nir_type_uint32);
137 M_LOAD(ld_color_buffer_as_fp16, nir_type_float16);
138 M_STORE(st_vary_32, nir_type_uint32);
139 M_LOAD(ld_cubemap_coords, nir_type_uint32);
140 M_LOAD(ld_compute_id, nir_type_uint32);
141
142 static midgard_instruction
143 v_branch(bool conditional, bool invert)
144 {
145 midgard_instruction ins = {
146 .type = TAG_ALU_4,
147 .unit = ALU_ENAB_BRANCH,
148 .compact_branch = true,
149 .branch = {
150 .conditional = conditional,
151 .invert_conditional = invert
152 },
153 .dest = ~0,
154 .src = { ~0, ~0, ~0, ~0 },
155 };
156
157 return ins;
158 }
159
160 static midgard_branch_extended
161 midgard_create_branch_extended( midgard_condition cond,
162 midgard_jmp_writeout_op op,
163 unsigned dest_tag,
164 signed quadword_offset)
165 {
166 /* The condition code is actually a LUT describing a function to
167 * combine multiple condition codes. However, we only support a single
168 * condition code at the moment, so we just duplicate over a bunch of
169 * times. */
170
171 uint16_t duplicated_cond =
172 (cond << 14) |
173 (cond << 12) |
174 (cond << 10) |
175 (cond << 8) |
176 (cond << 6) |
177 (cond << 4) |
178 (cond << 2) |
179 (cond << 0);
180
181 midgard_branch_extended branch = {
182 .op = op,
183 .dest_tag = dest_tag,
184 .offset = quadword_offset,
185 .cond = duplicated_cond
186 };
187
188 return branch;
189 }
190
191 static void
192 attach_constants(compiler_context *ctx, midgard_instruction *ins, void *constants, int name)
193 {
194 ins->has_constants = true;
195 memcpy(&ins->constants, constants, 16);
196 }
197
198 static int
199 glsl_type_size(const struct glsl_type *type, bool bindless)
200 {
201 return glsl_count_attribute_slots(type, false);
202 }
203
204 /* Lower fdot2 to a vector multiplication followed by channel addition */
205 static void
206 midgard_nir_lower_fdot2_body(nir_builder *b, nir_alu_instr *alu)
207 {
208 if (alu->op != nir_op_fdot2)
209 return;
210
211 b->cursor = nir_before_instr(&alu->instr);
212
213 nir_ssa_def *src0 = nir_ssa_for_alu_src(b, alu, 0);
214 nir_ssa_def *src1 = nir_ssa_for_alu_src(b, alu, 1);
215
216 nir_ssa_def *product = nir_fmul(b, src0, src1);
217
218 nir_ssa_def *sum = nir_fadd(b,
219 nir_channel(b, product, 0),
220 nir_channel(b, product, 1));
221
222 /* Replace the fdot2 with this sum */
223 nir_ssa_def_rewrite_uses(&alu->dest.dest.ssa, nir_src_for_ssa(sum));
224 }
225
226 static bool
227 midgard_nir_lower_fdot2(nir_shader *shader)
228 {
229 bool progress = false;
230
231 nir_foreach_function(function, shader) {
232 if (!function->impl) continue;
233
234 nir_builder _b;
235 nir_builder *b = &_b;
236 nir_builder_init(b, function->impl);
237
238 nir_foreach_block(block, function->impl) {
239 nir_foreach_instr_safe(instr, block) {
240 if (instr->type != nir_instr_type_alu) continue;
241
242 nir_alu_instr *alu = nir_instr_as_alu(instr);
243 midgard_nir_lower_fdot2_body(b, alu);
244
245 progress |= true;
246 }
247 }
248
249 nir_metadata_preserve(function->impl, nir_metadata_block_index | nir_metadata_dominance);
250
251 }
252
253 return progress;
254 }
255
256 /* Midgard can't write depth and stencil separately. It has to happen in a
257 * single store operation containing both. Let's add a panfrost specific
258 * intrinsic and turn all depth/stencil stores into a packed depth+stencil
259 * one.
260 */
261 static bool
262 midgard_nir_lower_zs_store(nir_shader *nir)
263 {
264 if (nir->info.stage != MESA_SHADER_FRAGMENT)
265 return false;
266
267 nir_variable *z_var = NULL, *s_var = NULL;
268
269 nir_foreach_variable(var, &nir->outputs) {
270 if (var->data.location == FRAG_RESULT_DEPTH)
271 z_var = var;
272 else if (var->data.location == FRAG_RESULT_STENCIL)
273 s_var = var;
274 }
275
276 if (!z_var && !s_var)
277 return false;
278
279 bool progress = false;
280
281 nir_foreach_function(function, nir) {
282 if (!function->impl) continue;
283
284 nir_intrinsic_instr *z_store = NULL, *s_store = NULL, *last_store = NULL;
285
286 nir_foreach_block(block, function->impl) {
287 nir_foreach_instr_safe(instr, block) {
288 if (instr->type != nir_instr_type_intrinsic)
289 continue;
290
291 nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
292 if (intr->intrinsic != nir_intrinsic_store_output)
293 continue;
294
295 if (z_var && nir_intrinsic_base(intr) == z_var->data.driver_location) {
296 assert(!z_store);
297 z_store = intr;
298 last_store = intr;
299 }
300
301 if (s_var && nir_intrinsic_base(intr) == s_var->data.driver_location) {
302 assert(!s_store);
303 s_store = intr;
304 last_store = intr;
305 }
306 }
307 }
308
309 if (!z_store && !s_store) continue;
310
311 nir_builder b;
312 nir_builder_init(&b, function->impl);
313
314 b.cursor = nir_before_instr(&last_store->instr);
315
316 nir_ssa_def *zs_store_src;
317
318 if (z_store && s_store) {
319 nir_ssa_def *srcs[2] = {
320 nir_ssa_for_src(&b, z_store->src[0], 1),
321 nir_ssa_for_src(&b, s_store->src[0], 1),
322 };
323
324 zs_store_src = nir_vec(&b, srcs, 2);
325 } else {
326 zs_store_src = nir_ssa_for_src(&b, last_store->src[0], 1);
327 }
328
329 nir_intrinsic_instr *zs_store;
330
331 zs_store = nir_intrinsic_instr_create(b.shader,
332 nir_intrinsic_store_zs_output_pan);
333 zs_store->src[0] = nir_src_for_ssa(zs_store_src);
334 zs_store->num_components = z_store && s_store ? 2 : 1;
335 nir_intrinsic_set_component(zs_store, z_store ? 0 : 1);
336
337 /* Replace the Z and S store by a ZS store */
338 nir_builder_instr_insert(&b, &zs_store->instr);
339
340 if (z_store)
341 nir_instr_remove(&z_store->instr);
342
343 if (s_store)
344 nir_instr_remove(&s_store->instr);
345
346 nir_metadata_preserve(function->impl, nir_metadata_block_index | nir_metadata_dominance);
347 progress = true;
348 }
349
350 return progress;
351 }
352
353 /* Flushes undefined values to zero */
354
355 static void
356 optimise_nir(nir_shader *nir, unsigned quirks, bool is_blend)
357 {
358 bool progress;
359 unsigned lower_flrp =
360 (nir->options->lower_flrp16 ? 16 : 0) |
361 (nir->options->lower_flrp32 ? 32 : 0) |
362 (nir->options->lower_flrp64 ? 64 : 0);
363
364 NIR_PASS(progress, nir, nir_lower_regs_to_ssa);
365 NIR_PASS(progress, nir, nir_lower_idiv, nir_lower_idiv_fast);
366
367 nir_lower_tex_options lower_tex_options = {
368 .lower_txs_lod = true,
369 .lower_txp = ~0,
370 .lower_tex_without_implicit_lod =
371 (quirks & MIDGARD_EXPLICIT_LOD),
372
373 /* TODO: we have native gradient.. */
374 .lower_txd = true,
375 };
376
377 NIR_PASS(progress, nir, nir_lower_tex, &lower_tex_options);
378
379 /* Must lower fdot2 after tex is lowered */
380 NIR_PASS(progress, nir, midgard_nir_lower_fdot2);
381
382 /* T720 is broken. */
383
384 if (quirks & MIDGARD_BROKEN_LOD)
385 NIR_PASS_V(nir, midgard_nir_lod_errata);
386
387 NIR_PASS(progress, nir, midgard_nir_lower_algebraic_early);
388
389 if (!is_blend)
390 NIR_PASS(progress, nir, nir_fuse_io_16);
391
392 do {
393 progress = false;
394
395 NIR_PASS(progress, nir, nir_lower_var_copies);
396 NIR_PASS(progress, nir, nir_lower_vars_to_ssa);
397
398 NIR_PASS(progress, nir, nir_copy_prop);
399 NIR_PASS(progress, nir, nir_opt_remove_phis);
400 NIR_PASS(progress, nir, nir_opt_dce);
401 NIR_PASS(progress, nir, nir_opt_dead_cf);
402 NIR_PASS(progress, nir, nir_opt_cse);
403 NIR_PASS(progress, nir, nir_opt_peephole_select, 64, false, true);
404 NIR_PASS(progress, nir, nir_opt_algebraic);
405 NIR_PASS(progress, nir, nir_opt_constant_folding);
406
407 if (lower_flrp != 0) {
408 bool lower_flrp_progress = false;
409 NIR_PASS(lower_flrp_progress,
410 nir,
411 nir_lower_flrp,
412 lower_flrp,
413 false /* always_precise */,
414 nir->options->lower_ffma);
415 if (lower_flrp_progress) {
416 NIR_PASS(progress, nir,
417 nir_opt_constant_folding);
418 progress = true;
419 }
420
421 /* Nothing should rematerialize any flrps, so we only
422 * need to do this lowering once.
423 */
424 lower_flrp = 0;
425 }
426
427 NIR_PASS(progress, nir, nir_opt_undef);
428 NIR_PASS(progress, nir, nir_undef_to_zero);
429
430 NIR_PASS(progress, nir, nir_opt_loop_unroll,
431 nir_var_shader_in |
432 nir_var_shader_out |
433 nir_var_function_temp);
434
435 NIR_PASS(progress, nir, nir_opt_vectorize);
436 } while (progress);
437
438 /* Must be run at the end to prevent creation of fsin/fcos ops */
439 NIR_PASS(progress, nir, midgard_nir_scale_trig);
440
441 do {
442 progress = false;
443
444 NIR_PASS(progress, nir, nir_opt_dce);
445 NIR_PASS(progress, nir, nir_opt_algebraic);
446 NIR_PASS(progress, nir, nir_opt_constant_folding);
447 NIR_PASS(progress, nir, nir_copy_prop);
448 } while (progress);
449
450 NIR_PASS(progress, nir, nir_opt_algebraic_late);
451 NIR_PASS(progress, nir, nir_opt_algebraic_distribute_src_mods);
452
453 /* We implement booleans as 32-bit 0/~0 */
454 NIR_PASS(progress, nir, nir_lower_bool_to_int32);
455
456 /* Now that booleans are lowered, we can run out late opts */
457 NIR_PASS(progress, nir, midgard_nir_lower_algebraic_late);
458 NIR_PASS(progress, nir, midgard_nir_cancel_inot);
459
460 NIR_PASS(progress, nir, nir_copy_prop);
461 NIR_PASS(progress, nir, nir_opt_dce);
462
463 /* Take us out of SSA */
464 NIR_PASS(progress, nir, nir_lower_locals_to_regs);
465 NIR_PASS(progress, nir, nir_convert_from_ssa, true);
466
467 /* We are a vector architecture; write combine where possible */
468 NIR_PASS(progress, nir, nir_move_vec_src_uses_to_dest);
469 NIR_PASS(progress, nir, nir_lower_vec_to_movs);
470
471 NIR_PASS(progress, nir, nir_opt_dce);
472 }
473
474 /* Do not actually emit a load; instead, cache the constant for inlining */
475
476 static void
477 emit_load_const(compiler_context *ctx, nir_load_const_instr *instr)
478 {
479 nir_ssa_def def = instr->def;
480
481 midgard_constants *consts = rzalloc(NULL, midgard_constants);
482
483 assert(instr->def.num_components * instr->def.bit_size <= sizeof(*consts) * 8);
484
485 #define RAW_CONST_COPY(bits) \
486 nir_const_value_to_array(consts->u##bits, instr->value, \
487 instr->def.num_components, u##bits)
488
489 switch (instr->def.bit_size) {
490 case 64:
491 RAW_CONST_COPY(64);
492 break;
493 case 32:
494 RAW_CONST_COPY(32);
495 break;
496 case 16:
497 RAW_CONST_COPY(16);
498 break;
499 case 8:
500 RAW_CONST_COPY(8);
501 break;
502 default:
503 unreachable("Invalid bit_size for load_const instruction\n");
504 }
505
506 /* Shifted for SSA, +1 for off-by-one */
507 _mesa_hash_table_u64_insert(ctx->ssa_constants, (def.index << 1) + 1, consts);
508 }
509
510 /* Normally constants are embedded implicitly, but for I/O and such we have to
511 * explicitly emit a move with the constant source */
512
513 static void
514 emit_explicit_constant(compiler_context *ctx, unsigned node, unsigned to)
515 {
516 void *constant_value = _mesa_hash_table_u64_search(ctx->ssa_constants, node + 1);
517
518 if (constant_value) {
519 midgard_instruction ins = v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), to);
520 attach_constants(ctx, &ins, constant_value, node + 1);
521 emit_mir_instruction(ctx, ins);
522 }
523 }
524
525 static bool
526 nir_is_non_scalar_swizzle(nir_alu_src *src, unsigned nr_components)
527 {
528 unsigned comp = src->swizzle[0];
529
530 for (unsigned c = 1; c < nr_components; ++c) {
531 if (src->swizzle[c] != comp)
532 return true;
533 }
534
535 return false;
536 }
537
538 #define ALU_CASE(nir, _op) \
539 case nir_op_##nir: \
540 op = midgard_alu_op_##_op; \
541 assert(src_bitsize == dst_bitsize); \
542 break;
543
544 #define ALU_CASE_RTZ(nir, _op) \
545 case nir_op_##nir: \
546 op = midgard_alu_op_##_op; \
547 roundmode = MIDGARD_RTZ; \
548 break;
549
550 #define ALU_CHECK_CMP(sext) \
551 assert(src_bitsize == 16 || src_bitsize == 32); \
552 assert(dst_bitsize == 16 || dst_bitsize == 32); \
553
554 #define ALU_CASE_BCAST(nir, _op, count) \
555 case nir_op_##nir: \
556 op = midgard_alu_op_##_op; \
557 broadcast_swizzle = count; \
558 ALU_CHECK_CMP(true); \
559 break;
560
561 #define ALU_CASE_CMP(nir, _op, sext) \
562 case nir_op_##nir: \
563 op = midgard_alu_op_##_op; \
564 ALU_CHECK_CMP(sext); \
565 break;
566
567 /* Analyze the sizes of the dest and inputs to determine reg mode. */
568
569 static midgard_reg_mode
570 reg_mode_for_nir(nir_alu_instr *instr)
571 {
572 unsigned src_bitsize = nir_src_bit_size(instr->src[0].src);
573 unsigned dst_bitsize = nir_dest_bit_size(instr->dest.dest);
574 unsigned max_bitsize = MAX2(src_bitsize, dst_bitsize);
575
576 /* We don't have fp16 LUTs, so we'll want to emit code like:
577 *
578 * vlut.fsinr hr0, hr0
579 *
580 * where both input and output are 16-bit but the operation is carried
581 * out in 32-bit
582 */
583
584 switch (instr->op) {
585 case nir_op_fsqrt:
586 case nir_op_frcp:
587 case nir_op_frsq:
588 case nir_op_fsin:
589 case nir_op_fcos:
590 case nir_op_fexp2:
591 case nir_op_flog2:
592 max_bitsize = MAX2(max_bitsize, 32);
593 break;
594
595 /* These get lowered to moves */
596 case nir_op_pack_32_4x8:
597 max_bitsize = 8;
598 break;
599 case nir_op_pack_32_2x16:
600 max_bitsize = 16;
601 break;
602 default:
603 break;
604 }
605
606
607 switch (max_bitsize) {
608 /* Use 16 pipe for 8 since we don't support vec16 yet */
609 case 8:
610 case 16:
611 return midgard_reg_mode_16;
612 case 32:
613 return midgard_reg_mode_32;
614 case 64:
615 return midgard_reg_mode_64;
616 default:
617 unreachable("Invalid bit size");
618 }
619 }
620
621 /* Compare mir_lower_invert */
622 static bool
623 nir_accepts_inot(nir_op op, unsigned src)
624 {
625 switch (op) {
626 case nir_op_ior:
627 case nir_op_iand: /* TODO: b2f16 */
628 case nir_op_ixor:
629 return true;
630 case nir_op_b32csel:
631 /* Only the condition */
632 return (src == 0);
633 default:
634 return false;
635 }
636 }
637
638 static bool
639 mir_accept_dest_mod(compiler_context *ctx, nir_dest **dest, nir_op op)
640 {
641 if (pan_has_dest_mod(dest, op)) {
642 assert((*dest)->is_ssa);
643 BITSET_SET(ctx->already_emitted, (*dest)->ssa.index);
644 return true;
645 }
646
647 return false;
648 }
649
650 static void
651 mir_copy_src(midgard_instruction *ins, nir_alu_instr *instr, unsigned i, unsigned to, bool *abs, bool *neg, bool *not, enum midgard_roundmode *roundmode, bool is_int, unsigned bcast_count)
652 {
653 nir_alu_src src = instr->src[i];
654
655 if (!is_int) {
656 if (pan_has_source_mod(&src, nir_op_fneg))
657 *neg = !(*neg);
658
659 if (pan_has_source_mod(&src, nir_op_fabs))
660 *abs = true;
661 }
662
663 if (nir_accepts_inot(instr->op, i) && pan_has_source_mod(&src, nir_op_inot))
664 *not = true;
665
666 if (roundmode) {
667 if (pan_has_source_mod(&src, nir_op_fround_even))
668 *roundmode = MIDGARD_RTE;
669
670 if (pan_has_source_mod(&src, nir_op_ftrunc))
671 *roundmode = MIDGARD_RTZ;
672
673 if (pan_has_source_mod(&src, nir_op_ffloor))
674 *roundmode = MIDGARD_RTN;
675
676 if (pan_has_source_mod(&src, nir_op_fceil))
677 *roundmode = MIDGARD_RTP;
678 }
679
680 unsigned bits = nir_src_bit_size(src.src);
681
682 ins->src[to] = nir_src_index(NULL, &src.src);
683 ins->src_types[to] = nir_op_infos[instr->op].input_types[i] | bits;
684
685 for (unsigned c = 0; c < NIR_MAX_VEC_COMPONENTS; ++c) {
686 ins->swizzle[to][c] = src.swizzle[
687 (!bcast_count || c < bcast_count) ? c :
688 (bcast_count - 1)];
689 }
690 }
691
692 /* Midgard features both fcsel and icsel, depending on whether you want int or
693 * float modifiers. NIR's csel is typeless, so we want a heuristic to guess if
694 * we should emit an int or float csel depending on what modifiers could be
695 * placed. In the absense of modifiers, this is probably arbitrary. */
696
697 static bool
698 mir_is_bcsel_float(nir_alu_instr *instr)
699 {
700 nir_op intmods[] = {
701 nir_op_i2i8, nir_op_i2i16,
702 nir_op_i2i32, nir_op_i2i64
703 };
704
705 nir_op floatmods[] = {
706 nir_op_fabs, nir_op_fneg,
707 nir_op_f2f16, nir_op_f2f32,
708 nir_op_f2f64
709 };
710
711 nir_op floatdestmods[] = {
712 nir_op_fsat, nir_op_fsat_signed, nir_op_fclamp_pos,
713 nir_op_f2f16, nir_op_f2f32
714 };
715
716 signed score = 0;
717
718 for (unsigned i = 1; i < 3; ++i) {
719 nir_alu_src s = instr->src[i];
720 for (unsigned q = 0; q < ARRAY_SIZE(intmods); ++q) {
721 if (pan_has_source_mod(&s, intmods[q]))
722 score--;
723 }
724 }
725
726 for (unsigned i = 1; i < 3; ++i) {
727 nir_alu_src s = instr->src[i];
728 for (unsigned q = 0; q < ARRAY_SIZE(floatmods); ++q) {
729 if (pan_has_source_mod(&s, floatmods[q]))
730 score++;
731 }
732 }
733
734 for (unsigned q = 0; q < ARRAY_SIZE(floatdestmods); ++q) {
735 nir_dest *dest = &instr->dest.dest;
736 if (pan_has_dest_mod(&dest, floatdestmods[q]))
737 score++;
738 }
739
740 return (score > 0);
741 }
742
743 static void
744 emit_alu(compiler_context *ctx, nir_alu_instr *instr)
745 {
746 nir_dest *dest = &instr->dest.dest;
747
748 if (dest->is_ssa && BITSET_TEST(ctx->already_emitted, dest->ssa.index))
749 return;
750
751 /* Derivatives end up emitted on the texture pipe, not the ALUs. This
752 * is handled elsewhere */
753
754 if (instr->op == nir_op_fddx || instr->op == nir_op_fddy) {
755 midgard_emit_derivatives(ctx, instr);
756 return;
757 }
758
759 bool is_ssa = dest->is_ssa;
760
761 unsigned nr_components = nir_dest_num_components(*dest);
762 unsigned nr_inputs = nir_op_infos[instr->op].num_inputs;
763 unsigned op = 0;
764
765 /* Number of components valid to check for the instruction (the rest
766 * will be forced to the last), or 0 to use as-is. Relevant as
767 * ball-type instructions have a channel count in NIR but are all vec4
768 * in Midgard */
769
770 unsigned broadcast_swizzle = 0;
771
772 /* What register mode should we operate in? */
773 midgard_reg_mode reg_mode =
774 reg_mode_for_nir(instr);
775
776 /* Should we swap arguments? */
777 bool flip_src12 = false;
778
779 unsigned src_bitsize = nir_src_bit_size(instr->src[0].src);
780 unsigned dst_bitsize = nir_dest_bit_size(*dest);
781
782 enum midgard_roundmode roundmode = MIDGARD_RTE;
783
784 switch (instr->op) {
785 ALU_CASE(fadd, fadd);
786 ALU_CASE(fmul, fmul);
787 ALU_CASE(fmin, fmin);
788 ALU_CASE(fmax, fmax);
789 ALU_CASE(imin, imin);
790 ALU_CASE(imax, imax);
791 ALU_CASE(umin, umin);
792 ALU_CASE(umax, umax);
793 ALU_CASE(ffloor, ffloor);
794 ALU_CASE(fround_even, froundeven);
795 ALU_CASE(ftrunc, ftrunc);
796 ALU_CASE(fceil, fceil);
797 ALU_CASE(fdot3, fdot3);
798 ALU_CASE(fdot4, fdot4);
799 ALU_CASE(iadd, iadd);
800 ALU_CASE(isub, isub);
801 ALU_CASE(imul, imul);
802
803 /* Zero shoved as second-arg */
804 ALU_CASE(iabs, iabsdiff);
805
806 ALU_CASE(mov, imov);
807
808 ALU_CASE_CMP(feq32, feq, false);
809 ALU_CASE_CMP(fne32, fne, false);
810 ALU_CASE_CMP(flt32, flt, false);
811 ALU_CASE_CMP(ieq32, ieq, true);
812 ALU_CASE_CMP(ine32, ine, true);
813 ALU_CASE_CMP(ilt32, ilt, true);
814 ALU_CASE_CMP(ult32, ult, false);
815
816 /* We don't have a native b2f32 instruction. Instead, like many
817 * GPUs, we exploit booleans as 0/~0 for false/true, and
818 * correspondingly AND
819 * by 1.0 to do the type conversion. For the moment, prime us
820 * to emit:
821 *
822 * iand [whatever], #0
823 *
824 * At the end of emit_alu (as MIR), we'll fix-up the constant
825 */
826
827 ALU_CASE_CMP(b2f32, iand, true);
828 ALU_CASE_CMP(b2f16, iand, true);
829 ALU_CASE_CMP(b2i32, iand, true);
830
831 /* Likewise, we don't have a dedicated f2b32 instruction, but
832 * we can do a "not equal to 0.0" test. */
833
834 ALU_CASE_CMP(f2b32, fne, false);
835 ALU_CASE_CMP(i2b32, ine, true);
836
837 ALU_CASE(frcp, frcp);
838 ALU_CASE(frsq, frsqrt);
839 ALU_CASE(fsqrt, fsqrt);
840 ALU_CASE(fexp2, fexp2);
841 ALU_CASE(flog2, flog2);
842
843 ALU_CASE_RTZ(f2i64, f2i_rte);
844 ALU_CASE_RTZ(f2u64, f2u_rte);
845 ALU_CASE_RTZ(i2f64, i2f_rte);
846 ALU_CASE_RTZ(u2f64, u2f_rte);
847
848 ALU_CASE_RTZ(f2i32, f2i_rte);
849 ALU_CASE_RTZ(f2u32, f2u_rte);
850 ALU_CASE_RTZ(i2f32, i2f_rte);
851 ALU_CASE_RTZ(u2f32, u2f_rte);
852
853 ALU_CASE_RTZ(f2i8, f2i_rte);
854 ALU_CASE_RTZ(f2u8, f2u_rte);
855
856 ALU_CASE_RTZ(f2i16, f2i_rte);
857 ALU_CASE_RTZ(f2u16, f2u_rte);
858 ALU_CASE_RTZ(i2f16, i2f_rte);
859 ALU_CASE_RTZ(u2f16, u2f_rte);
860
861 ALU_CASE(fsin, fsin);
862 ALU_CASE(fcos, fcos);
863
864 /* We'll get 0 in the second arg, so:
865 * ~a = ~(a | 0) = nor(a, 0) */
866 ALU_CASE(inot, inor);
867 ALU_CASE(iand, iand);
868 ALU_CASE(ior, ior);
869 ALU_CASE(ixor, ixor);
870 ALU_CASE(ishl, ishl);
871 ALU_CASE(ishr, iasr);
872 ALU_CASE(ushr, ilsr);
873
874 ALU_CASE_BCAST(b32all_fequal2, fball_eq, 2);
875 ALU_CASE_BCAST(b32all_fequal3, fball_eq, 3);
876 ALU_CASE_CMP(b32all_fequal4, fball_eq, true);
877
878 ALU_CASE_BCAST(b32any_fnequal2, fbany_neq, 2);
879 ALU_CASE_BCAST(b32any_fnequal3, fbany_neq, 3);
880 ALU_CASE_CMP(b32any_fnequal4, fbany_neq, true);
881
882 ALU_CASE_BCAST(b32all_iequal2, iball_eq, 2);
883 ALU_CASE_BCAST(b32all_iequal3, iball_eq, 3);
884 ALU_CASE_CMP(b32all_iequal4, iball_eq, true);
885
886 ALU_CASE_BCAST(b32any_inequal2, ibany_neq, 2);
887 ALU_CASE_BCAST(b32any_inequal3, ibany_neq, 3);
888 ALU_CASE_CMP(b32any_inequal4, ibany_neq, true);
889
890 /* Source mods will be shoved in later */
891 ALU_CASE(fabs, fmov);
892 ALU_CASE(fneg, fmov);
893 ALU_CASE(fsat, fmov);
894 ALU_CASE(fsat_signed, fmov);
895 ALU_CASE(fclamp_pos, fmov);
896
897 /* For size conversion, we use a move. Ideally though we would squash
898 * these ops together; maybe that has to happen after in NIR as part of
899 * propagation...? An earlier algebraic pass ensured we step down by
900 * only / exactly one size. If stepping down, we use a dest override to
901 * reduce the size; if stepping up, we use a larger-sized move with a
902 * half source and a sign/zero-extension modifier */
903
904 case nir_op_i2i8:
905 case nir_op_i2i16:
906 case nir_op_i2i32:
907 case nir_op_i2i64:
908 case nir_op_u2u8:
909 case nir_op_u2u16:
910 case nir_op_u2u32:
911 case nir_op_u2u64:
912 case nir_op_f2f16:
913 case nir_op_f2f32:
914 case nir_op_f2f64: {
915 if (instr->op == nir_op_f2f16 || instr->op == nir_op_f2f32 ||
916 instr->op == nir_op_f2f64)
917 op = midgard_alu_op_fmov;
918 else
919 op = midgard_alu_op_imov;
920
921 break;
922 }
923
924 /* For greater-or-equal, we lower to less-or-equal and flip the
925 * arguments */
926
927 case nir_op_fge:
928 case nir_op_fge32:
929 case nir_op_ige32:
930 case nir_op_uge32: {
931 op =
932 instr->op == nir_op_fge ? midgard_alu_op_fle :
933 instr->op == nir_op_fge32 ? midgard_alu_op_fle :
934 instr->op == nir_op_ige32 ? midgard_alu_op_ile :
935 instr->op == nir_op_uge32 ? midgard_alu_op_ule :
936 0;
937
938 flip_src12 = true;
939 ALU_CHECK_CMP(false);
940 break;
941 }
942
943 case nir_op_b32csel: {
944 bool mixed = nir_is_non_scalar_swizzle(&instr->src[0], nr_components);
945 bool is_float = mir_is_bcsel_float(instr);
946 op = is_float ?
947 (mixed ? midgard_alu_op_fcsel_v : midgard_alu_op_fcsel) :
948 (mixed ? midgard_alu_op_icsel_v : midgard_alu_op_icsel);
949
950 break;
951 }
952
953 case nir_op_unpack_32_2x16:
954 case nir_op_unpack_32_4x8:
955 case nir_op_pack_32_2x16:
956 case nir_op_pack_32_4x8: {
957 op = midgard_alu_op_imov;
958 break;
959 }
960
961 default:
962 DBG("Unhandled ALU op %s\n", nir_op_infos[instr->op].name);
963 assert(0);
964 return;
965 }
966
967 /* Promote imov to fmov if it might help inline a constant */
968 if (op == midgard_alu_op_imov && nir_src_is_const(instr->src[0].src)
969 && nir_src_bit_size(instr->src[0].src) == 32
970 && nir_is_same_comp_swizzle(instr->src[0].swizzle,
971 nir_src_num_components(instr->src[0].src))) {
972 op = midgard_alu_op_fmov;
973 }
974
975 /* Midgard can perform certain modifiers on output of an ALU op */
976
977 unsigned outmod = 0;
978 bool is_int = midgard_is_integer_op(op);
979
980 if (midgard_is_integer_out_op(op)) {
981 outmod = midgard_outmod_int_wrap;
982 } else if (instr->op == nir_op_fsat) {
983 outmod = midgard_outmod_sat;
984 } else if (instr->op == nir_op_fsat_signed) {
985 outmod = midgard_outmod_sat_signed;
986 } else if (instr->op == nir_op_fclamp_pos) {
987 outmod = midgard_outmod_pos;
988 }
989
990 /* Fetch unit, quirks, etc information */
991 unsigned opcode_props = alu_opcode_props[op].props;
992 bool quirk_flipped_r24 = opcode_props & QUIRK_FLIPPED_R24;
993
994 /* Look for floating point mods. We have the mods fsat, fsat_signed,
995 * and fpos. We also have the relations (note 3 * 2 = 6 cases):
996 *
997 * fsat_signed(fpos(x)) = fsat(x)
998 * fsat_signed(fsat(x)) = fsat(x)
999 * fpos(fsat_signed(x)) = fsat(x)
1000 * fpos(fsat(x)) = fsat(x)
1001 * fsat(fsat_signed(x)) = fsat(x)
1002 * fsat(fpos(x)) = fsat(x)
1003 *
1004 * So by cases any composition of output modifiers is equivalent to
1005 * fsat alone.
1006 */
1007
1008 if (!is_int && !(opcode_props & OP_TYPE_CONVERT)) {
1009 bool fpos = mir_accept_dest_mod(ctx, &dest, nir_op_fclamp_pos);
1010 bool fsat = mir_accept_dest_mod(ctx, &dest, nir_op_fsat);
1011 bool ssat = mir_accept_dest_mod(ctx, &dest, nir_op_fsat_signed);
1012 bool prior = (outmod != midgard_outmod_none);
1013 int count = (int) prior + (int) fpos + (int) ssat + (int) fsat;
1014
1015 outmod = ((count > 1) || fsat) ? midgard_outmod_sat :
1016 fpos ? midgard_outmod_pos :
1017 ssat ? midgard_outmod_sat_signed :
1018 outmod;
1019 }
1020
1021 midgard_instruction ins = {
1022 .type = TAG_ALU_4,
1023 .dest = nir_dest_index(dest),
1024 .dest_type = nir_op_infos[instr->op].output_type
1025 | nir_dest_bit_size(*dest),
1026 .roundmode = roundmode,
1027 };
1028
1029 enum midgard_roundmode *roundptr = (opcode_props & MIDGARD_ROUNDS) ?
1030 &ins.roundmode : NULL;
1031
1032 for (unsigned i = nr_inputs; i < ARRAY_SIZE(ins.src); ++i)
1033 ins.src[i] = ~0;
1034
1035 if (quirk_flipped_r24) {
1036 ins.src[0] = ~0;
1037 mir_copy_src(&ins, instr, 0, 1, &ins.src_abs[1], &ins.src_neg[1], &ins.src_invert[1], roundptr, is_int, broadcast_swizzle);
1038 } else {
1039 for (unsigned i = 0; i < nr_inputs; ++i) {
1040 unsigned to = i;
1041
1042 if (instr->op == nir_op_b32csel) {
1043 /* The condition is the first argument; move
1044 * the other arguments up one to be a binary
1045 * instruction for Midgard with the condition
1046 * last */
1047
1048 if (i == 0)
1049 to = 2;
1050 else if (flip_src12)
1051 to = 2 - i;
1052 else
1053 to = i - 1;
1054 } else if (flip_src12) {
1055 to = 1 - to;
1056 }
1057
1058 mir_copy_src(&ins, instr, i, to, &ins.src_abs[to], &ins.src_neg[to], &ins.src_invert[to], roundptr, is_int, broadcast_swizzle);
1059
1060 /* (!c) ? a : b = c ? b : a */
1061 if (instr->op == nir_op_b32csel && ins.src_invert[2]) {
1062 ins.src_invert[2] = false;
1063 flip_src12 ^= true;
1064 }
1065 }
1066 }
1067
1068 if (instr->op == nir_op_fneg || instr->op == nir_op_fabs) {
1069 /* Lowered to move */
1070 if (instr->op == nir_op_fneg)
1071 ins.src_neg[1] ^= true;
1072
1073 if (instr->op == nir_op_fabs)
1074 ins.src_abs[1] = true;
1075 }
1076
1077 ins.mask = mask_of(nr_components);
1078
1079 midgard_vector_alu alu = {
1080 .op = op,
1081 .reg_mode = reg_mode,
1082 .outmod = outmod,
1083 };
1084
1085 /* Apply writemask if non-SSA, keeping in mind that we can't write to
1086 * components that don't exist. Note modifier => SSA => !reg => no
1087 * writemask, so we don't have to worry about writemasks here.*/
1088
1089 if (!is_ssa)
1090 ins.mask &= instr->dest.write_mask;
1091
1092 ins.alu = alu;
1093
1094 /* Late fixup for emulated instructions */
1095
1096 if (instr->op == nir_op_b2f32 || instr->op == nir_op_b2i32) {
1097 /* Presently, our second argument is an inline #0 constant.
1098 * Switch over to an embedded 1.0 constant (that can't fit
1099 * inline, since we're 32-bit, not 16-bit like the inline
1100 * constants) */
1101
1102 ins.has_inline_constant = false;
1103 ins.src[1] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1104 ins.src_types[1] = nir_type_float32;
1105 ins.has_constants = true;
1106
1107 if (instr->op == nir_op_b2f32)
1108 ins.constants.f32[0] = 1.0f;
1109 else
1110 ins.constants.i32[0] = 1;
1111
1112 for (unsigned c = 0; c < 16; ++c)
1113 ins.swizzle[1][c] = 0;
1114 } else if (instr->op == nir_op_b2f16) {
1115 ins.src[1] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1116 ins.src_types[1] = nir_type_float16;
1117 ins.has_constants = true;
1118 ins.constants.i16[0] = _mesa_float_to_half(1.0);
1119
1120 for (unsigned c = 0; c < 16; ++c)
1121 ins.swizzle[1][c] = 0;
1122 } else if (nr_inputs == 1 && !quirk_flipped_r24) {
1123 /* Lots of instructions need a 0 plonked in */
1124 ins.has_inline_constant = false;
1125 ins.src[1] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1126 ins.src_types[1] = nir_type_uint32;
1127 ins.has_constants = true;
1128 ins.constants.u32[0] = 0;
1129
1130 for (unsigned c = 0; c < 16; ++c)
1131 ins.swizzle[1][c] = 0;
1132 } else if (instr->op == nir_op_pack_32_2x16) {
1133 ins.dest_type = nir_type_uint16;
1134 ins.mask = mask_of(nr_components * 2);
1135 ins.is_pack = true;
1136 } else if (instr->op == nir_op_pack_32_4x8) {
1137 ins.dest_type = nir_type_uint8;
1138 ins.mask = mask_of(nr_components * 4);
1139 ins.is_pack = true;
1140 } else if (instr->op == nir_op_unpack_32_2x16) {
1141 ins.dest_type = nir_type_uint32;
1142 ins.mask = mask_of(nr_components >> 1);
1143 ins.is_pack = true;
1144 } else if (instr->op == nir_op_unpack_32_4x8) {
1145 ins.dest_type = nir_type_uint32;
1146 ins.mask = mask_of(nr_components >> 2);
1147 ins.is_pack = true;
1148 }
1149
1150 if ((opcode_props & UNITS_ALL) == UNIT_VLUT) {
1151 /* To avoid duplicating the lookup tables (probably), true LUT
1152 * instructions can only operate as if they were scalars. Lower
1153 * them here by changing the component. */
1154
1155 unsigned orig_mask = ins.mask;
1156
1157 unsigned swizzle_back[MIR_VEC_COMPONENTS];
1158 memcpy(&swizzle_back, ins.swizzle[0], sizeof(swizzle_back));
1159
1160 for (int i = 0; i < nr_components; ++i) {
1161 /* Mask the associated component, dropping the
1162 * instruction if needed */
1163
1164 ins.mask = 1 << i;
1165 ins.mask &= orig_mask;
1166
1167 if (!ins.mask)
1168 continue;
1169
1170 for (unsigned j = 0; j < MIR_VEC_COMPONENTS; ++j)
1171 ins.swizzle[0][j] = swizzle_back[i]; /* Pull from the correct component */
1172
1173 emit_mir_instruction(ctx, ins);
1174 }
1175 } else {
1176 emit_mir_instruction(ctx, ins);
1177 }
1178 }
1179
1180 #undef ALU_CASE
1181
1182 static void
1183 mir_set_intr_mask(nir_instr *instr, midgard_instruction *ins, bool is_read)
1184 {
1185 nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
1186 unsigned nir_mask = 0;
1187 unsigned dsize = 0;
1188
1189 if (is_read) {
1190 nir_mask = mask_of(nir_intrinsic_dest_components(intr));
1191 dsize = nir_dest_bit_size(intr->dest);
1192 } else {
1193 nir_mask = nir_intrinsic_write_mask(intr);
1194 dsize = 32;
1195 }
1196
1197 /* Once we have the NIR mask, we need to normalize to work in 32-bit space */
1198 unsigned bytemask = pan_to_bytemask(dsize, nir_mask);
1199 mir_set_bytemask(ins, bytemask);
1200 ins->dest_type = nir_type_uint | dsize;
1201 }
1202
1203 /* Uniforms and UBOs use a shared code path, as uniforms are just (slightly
1204 * optimized) versions of UBO #0 */
1205
1206 static midgard_instruction *
1207 emit_ubo_read(
1208 compiler_context *ctx,
1209 nir_instr *instr,
1210 unsigned dest,
1211 unsigned offset,
1212 nir_src *indirect_offset,
1213 unsigned indirect_shift,
1214 unsigned index)
1215 {
1216 /* TODO: half-floats */
1217
1218 midgard_instruction ins = m_ld_ubo_int4(dest, 0);
1219 ins.constants.u32[0] = offset;
1220
1221 if (instr->type == nir_instr_type_intrinsic)
1222 mir_set_intr_mask(instr, &ins, true);
1223
1224 if (indirect_offset) {
1225 ins.src[2] = nir_src_index(ctx, indirect_offset);
1226 ins.src_types[2] = nir_type_uint32;
1227 ins.load_store.arg_2 = (indirect_shift << 5);
1228 } else {
1229 ins.load_store.arg_2 = 0x1E;
1230 }
1231
1232 ins.load_store.arg_1 = index;
1233
1234 return emit_mir_instruction(ctx, ins);
1235 }
1236
1237 /* Globals are like UBOs if you squint. And shared memory is like globals if
1238 * you squint even harder */
1239
1240 static void
1241 emit_global(
1242 compiler_context *ctx,
1243 nir_instr *instr,
1244 bool is_read,
1245 unsigned srcdest,
1246 nir_src *offset,
1247 bool is_shared)
1248 {
1249 /* TODO: types */
1250
1251 midgard_instruction ins;
1252
1253 if (is_read)
1254 ins = m_ld_int4(srcdest, 0);
1255 else
1256 ins = m_st_int4(srcdest, 0);
1257
1258 mir_set_offset(ctx, &ins, offset, is_shared);
1259 mir_set_intr_mask(instr, &ins, is_read);
1260
1261 emit_mir_instruction(ctx, ins);
1262 }
1263
1264 static void
1265 emit_varying_read(
1266 compiler_context *ctx,
1267 unsigned dest, unsigned offset,
1268 unsigned nr_comp, unsigned component,
1269 nir_src *indirect_offset, nir_alu_type type, bool flat)
1270 {
1271 /* XXX: Half-floats? */
1272 /* TODO: swizzle, mask */
1273
1274 midgard_instruction ins = m_ld_vary_32(dest, offset);
1275 ins.mask = mask_of(nr_comp);
1276
1277 for (unsigned i = 0; i < ARRAY_SIZE(ins.swizzle[0]); ++i)
1278 ins.swizzle[0][i] = MIN2(i + component, COMPONENT_W);
1279
1280 midgard_varying_parameter p = {
1281 .is_varying = 1,
1282 .interpolation = midgard_interp_default,
1283 .flat = flat,
1284 };
1285
1286 unsigned u;
1287 memcpy(&u, &p, sizeof(p));
1288 ins.load_store.varying_parameters = u;
1289
1290 if (indirect_offset) {
1291 ins.src[2] = nir_src_index(ctx, indirect_offset);
1292 ins.src_types[2] = nir_type_uint32;
1293 } else
1294 ins.load_store.arg_2 = 0x1E;
1295
1296 ins.load_store.arg_1 = 0x9E;
1297
1298 /* Use the type appropriate load */
1299 switch (type) {
1300 case nir_type_uint32:
1301 case nir_type_bool32:
1302 ins.load_store.op = midgard_op_ld_vary_32u;
1303 break;
1304 case nir_type_int32:
1305 ins.load_store.op = midgard_op_ld_vary_32i;
1306 break;
1307 case nir_type_float32:
1308 ins.load_store.op = midgard_op_ld_vary_32;
1309 break;
1310 case nir_type_float16:
1311 ins.load_store.op = midgard_op_ld_vary_16;
1312 break;
1313 default:
1314 unreachable("Attempted to load unknown type");
1315 break;
1316 }
1317
1318 emit_mir_instruction(ctx, ins);
1319 }
1320
1321 static void
1322 emit_attr_read(
1323 compiler_context *ctx,
1324 unsigned dest, unsigned offset,
1325 unsigned nr_comp, nir_alu_type t)
1326 {
1327 midgard_instruction ins = m_ld_attr_32(dest, offset);
1328 ins.load_store.arg_1 = 0x1E;
1329 ins.load_store.arg_2 = 0x1E;
1330 ins.mask = mask_of(nr_comp);
1331
1332 /* Use the type appropriate load */
1333 switch (t) {
1334 case nir_type_uint:
1335 case nir_type_bool:
1336 ins.load_store.op = midgard_op_ld_attr_32u;
1337 break;
1338 case nir_type_int:
1339 ins.load_store.op = midgard_op_ld_attr_32i;
1340 break;
1341 case nir_type_float:
1342 ins.load_store.op = midgard_op_ld_attr_32;
1343 break;
1344 default:
1345 unreachable("Attempted to load unknown type");
1346 break;
1347 }
1348
1349 emit_mir_instruction(ctx, ins);
1350 }
1351
1352 static void
1353 emit_sysval_read(compiler_context *ctx, nir_instr *instr,
1354 unsigned nr_components, unsigned offset)
1355 {
1356 nir_dest nir_dest;
1357
1358 /* Figure out which uniform this is */
1359 int sysval = panfrost_sysval_for_instr(instr, &nir_dest);
1360 void *val = _mesa_hash_table_u64_search(ctx->sysvals.sysval_to_id, sysval);
1361
1362 unsigned dest = nir_dest_index(&nir_dest);
1363
1364 /* Sysvals are prefix uniforms */
1365 unsigned uniform = ((uintptr_t) val) - 1;
1366
1367 /* Emit the read itself -- this is never indirect */
1368 midgard_instruction *ins =
1369 emit_ubo_read(ctx, instr, dest, (uniform * 16) + offset, NULL, 0, 0);
1370
1371 ins->mask = mask_of(nr_components);
1372 }
1373
1374 static unsigned
1375 compute_builtin_arg(nir_op op)
1376 {
1377 switch (op) {
1378 case nir_intrinsic_load_work_group_id:
1379 return 0x14;
1380 case nir_intrinsic_load_local_invocation_id:
1381 return 0x10;
1382 default:
1383 unreachable("Invalid compute paramater loaded");
1384 }
1385 }
1386
1387 static void
1388 emit_fragment_store(compiler_context *ctx, unsigned src, enum midgard_rt_id rt)
1389 {
1390 assert(rt < ARRAY_SIZE(ctx->writeout_branch));
1391
1392 midgard_instruction *br = ctx->writeout_branch[rt];
1393
1394 assert(!br);
1395
1396 emit_explicit_constant(ctx, src, src);
1397
1398 struct midgard_instruction ins =
1399 v_branch(false, false);
1400
1401 ins.writeout = true;
1402
1403 /* Add dependencies */
1404 ins.src[0] = src;
1405 ins.src_types[0] = nir_type_uint32;
1406 ins.constants.u32[0] = rt == MIDGARD_ZS_RT ?
1407 0xFF : (rt - MIDGARD_COLOR_RT0) * 0x100;
1408
1409 /* Emit the branch */
1410 br = emit_mir_instruction(ctx, ins);
1411 schedule_barrier(ctx);
1412 ctx->writeout_branch[rt] = br;
1413
1414 /* Push our current location = current block count - 1 = where we'll
1415 * jump to. Maybe a bit too clever for my own good */
1416
1417 br->branch.target_block = ctx->block_count - 1;
1418 }
1419
1420 static void
1421 emit_compute_builtin(compiler_context *ctx, nir_intrinsic_instr *instr)
1422 {
1423 unsigned reg = nir_dest_index(&instr->dest);
1424 midgard_instruction ins = m_ld_compute_id(reg, 0);
1425 ins.mask = mask_of(3);
1426 ins.swizzle[0][3] = COMPONENT_X; /* xyzx */
1427 ins.load_store.arg_1 = compute_builtin_arg(instr->intrinsic);
1428 emit_mir_instruction(ctx, ins);
1429 }
1430
1431 static unsigned
1432 vertex_builtin_arg(nir_op op)
1433 {
1434 switch (op) {
1435 case nir_intrinsic_load_vertex_id:
1436 return PAN_VERTEX_ID;
1437 case nir_intrinsic_load_instance_id:
1438 return PAN_INSTANCE_ID;
1439 default:
1440 unreachable("Invalid vertex builtin");
1441 }
1442 }
1443
1444 static void
1445 emit_vertex_builtin(compiler_context *ctx, nir_intrinsic_instr *instr)
1446 {
1447 unsigned reg = nir_dest_index(&instr->dest);
1448 emit_attr_read(ctx, reg, vertex_builtin_arg(instr->intrinsic), 1, nir_type_int);
1449 }
1450
1451 static void
1452 emit_control_barrier(compiler_context *ctx)
1453 {
1454 midgard_instruction ins = {
1455 .type = TAG_TEXTURE_4,
1456 .dest = ~0,
1457 .src = { ~0, ~0, ~0, ~0 },
1458 .texture = {
1459 .op = TEXTURE_OP_BARRIER,
1460
1461 /* TODO: optimize */
1462 .out_of_order = MIDGARD_BARRIER_BUFFER |
1463 MIDGARD_BARRIER_SHARED ,
1464 }
1465 };
1466
1467 emit_mir_instruction(ctx, ins);
1468 }
1469
1470 static const nir_variable *
1471 search_var(struct exec_list *vars, unsigned driver_loc)
1472 {
1473 nir_foreach_variable(var, vars) {
1474 if (var->data.driver_location == driver_loc)
1475 return var;
1476 }
1477
1478 return NULL;
1479 }
1480
1481 static unsigned
1482 mir_get_branch_cond(nir_src *src, bool *invert)
1483 {
1484 /* Wrap it. No swizzle since it's a scalar */
1485
1486 nir_alu_src alu = {
1487 .src = *src
1488 };
1489
1490 *invert = pan_has_source_mod(&alu, nir_op_inot);
1491 return nir_src_index(NULL, &alu.src);
1492 }
1493
1494 static void
1495 emit_intrinsic(compiler_context *ctx, nir_intrinsic_instr *instr)
1496 {
1497 unsigned offset = 0, reg;
1498
1499 switch (instr->intrinsic) {
1500 case nir_intrinsic_discard_if:
1501 case nir_intrinsic_discard: {
1502 bool conditional = instr->intrinsic == nir_intrinsic_discard_if;
1503 struct midgard_instruction discard = v_branch(conditional, false);
1504 discard.branch.target_type = TARGET_DISCARD;
1505
1506 if (conditional) {
1507 discard.src[0] = mir_get_branch_cond(&instr->src[0],
1508 &discard.branch.invert_conditional);
1509 discard.src_types[0] = nir_type_uint32;
1510 }
1511
1512 emit_mir_instruction(ctx, discard);
1513 schedule_barrier(ctx);
1514
1515 break;
1516 }
1517
1518 case nir_intrinsic_load_uniform:
1519 case nir_intrinsic_load_ubo:
1520 case nir_intrinsic_load_global:
1521 case nir_intrinsic_load_shared:
1522 case nir_intrinsic_load_input:
1523 case nir_intrinsic_load_interpolated_input: {
1524 bool is_uniform = instr->intrinsic == nir_intrinsic_load_uniform;
1525 bool is_ubo = instr->intrinsic == nir_intrinsic_load_ubo;
1526 bool is_global = instr->intrinsic == nir_intrinsic_load_global;
1527 bool is_shared = instr->intrinsic == nir_intrinsic_load_shared;
1528 bool is_flat = instr->intrinsic == nir_intrinsic_load_input;
1529 bool is_interp = instr->intrinsic == nir_intrinsic_load_interpolated_input;
1530
1531 /* Get the base type of the intrinsic */
1532 /* TODO: Infer type? Does it matter? */
1533 nir_alu_type t =
1534 (is_ubo || is_global || is_shared) ? nir_type_uint :
1535 (is_interp) ? nir_type_float :
1536 nir_intrinsic_type(instr);
1537
1538 t = nir_alu_type_get_base_type(t);
1539
1540 if (!(is_ubo || is_global)) {
1541 offset = nir_intrinsic_base(instr);
1542 }
1543
1544 unsigned nr_comp = nir_intrinsic_dest_components(instr);
1545
1546 nir_src *src_offset = nir_get_io_offset_src(instr);
1547
1548 bool direct = nir_src_is_const(*src_offset);
1549 nir_src *indirect_offset = direct ? NULL : src_offset;
1550
1551 if (direct)
1552 offset += nir_src_as_uint(*src_offset);
1553
1554 /* We may need to apply a fractional offset */
1555 int component = (is_flat || is_interp) ?
1556 nir_intrinsic_component(instr) : 0;
1557 reg = nir_dest_index(&instr->dest);
1558
1559 if (is_uniform && !ctx->is_blend) {
1560 emit_ubo_read(ctx, &instr->instr, reg, (ctx->sysvals.sysval_count + offset) * 16, indirect_offset, 4, 0);
1561 } else if (is_ubo) {
1562 nir_src index = instr->src[0];
1563
1564 /* TODO: Is indirect block number possible? */
1565 assert(nir_src_is_const(index));
1566
1567 uint32_t uindex = nir_src_as_uint(index) + 1;
1568 emit_ubo_read(ctx, &instr->instr, reg, offset, indirect_offset, 0, uindex);
1569 } else if (is_global || is_shared) {
1570 emit_global(ctx, &instr->instr, true, reg, src_offset, is_shared);
1571 } else if (ctx->stage == MESA_SHADER_FRAGMENT && !ctx->is_blend) {
1572 emit_varying_read(ctx, reg, offset, nr_comp, component, indirect_offset, t | nir_dest_bit_size(instr->dest), is_flat);
1573 } else if (ctx->is_blend) {
1574 /* For blend shaders, load the input color, which is
1575 * preloaded to r0 */
1576
1577 midgard_instruction move = v_mov(SSA_FIXED_REGISTER(0), reg);
1578 emit_mir_instruction(ctx, move);
1579 schedule_barrier(ctx);
1580 } else if (ctx->stage == MESA_SHADER_VERTEX) {
1581 emit_attr_read(ctx, reg, offset, nr_comp, t);
1582 } else {
1583 DBG("Unknown load\n");
1584 assert(0);
1585 }
1586
1587 break;
1588 }
1589
1590 /* Artefact of load_interpolated_input. TODO: other barycentric modes */
1591 case nir_intrinsic_load_barycentric_pixel:
1592 case nir_intrinsic_load_barycentric_centroid:
1593 break;
1594
1595 /* Reads 128-bit value raw off the tilebuffer during blending, tasty */
1596
1597 case nir_intrinsic_load_raw_output_pan: {
1598 reg = nir_dest_index(&instr->dest);
1599 assert(ctx->is_blend);
1600
1601 /* T720 and below use different blend opcodes with slightly
1602 * different semantics than T760 and up */
1603
1604 midgard_instruction ld = m_ld_color_buffer_32u(reg, 0);
1605
1606 if (ctx->quirks & MIDGARD_OLD_BLEND) {
1607 ld.load_store.op = midgard_op_ld_color_buffer_32u_old;
1608 ld.load_store.address = 16;
1609 ld.load_store.arg_2 = 0x1E;
1610 }
1611
1612 emit_mir_instruction(ctx, ld);
1613 break;
1614 }
1615
1616 case nir_intrinsic_load_output: {
1617 reg = nir_dest_index(&instr->dest);
1618 assert(ctx->is_blend);
1619
1620 midgard_instruction ld = m_ld_color_buffer_as_fp16(reg, 0);
1621
1622 for (unsigned c = 4; c < 16; ++c)
1623 ld.swizzle[0][c] = 0;
1624
1625 if (ctx->quirks & MIDGARD_OLD_BLEND) {
1626 ld.load_store.op = midgard_op_ld_color_buffer_as_fp16_old;
1627 ld.load_store.address = 1;
1628 ld.load_store.arg_2 = 0x1E;
1629 }
1630
1631 emit_mir_instruction(ctx, ld);
1632 break;
1633 }
1634
1635 case nir_intrinsic_load_blend_const_color_rgba: {
1636 assert(ctx->is_blend);
1637 reg = nir_dest_index(&instr->dest);
1638
1639 /* Blend constants are embedded directly in the shader and
1640 * patched in, so we use some magic routing */
1641
1642 midgard_instruction ins = v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), reg);
1643 ins.has_constants = true;
1644 ins.has_blend_constant = true;
1645 emit_mir_instruction(ctx, ins);
1646 break;
1647 }
1648
1649 case nir_intrinsic_store_zs_output_pan: {
1650 assert(ctx->stage == MESA_SHADER_FRAGMENT);
1651 emit_fragment_store(ctx, nir_src_index(ctx, &instr->src[0]),
1652 MIDGARD_ZS_RT);
1653
1654 midgard_instruction *br = ctx->writeout_branch[MIDGARD_ZS_RT];
1655
1656 if (!nir_intrinsic_component(instr))
1657 br->writeout_depth = true;
1658 if (nir_intrinsic_component(instr) ||
1659 instr->num_components)
1660 br->writeout_stencil = true;
1661 assert(br->writeout_depth | br->writeout_stencil);
1662 break;
1663 }
1664
1665 case nir_intrinsic_store_output:
1666 assert(nir_src_is_const(instr->src[1]) && "no indirect outputs");
1667
1668 offset = nir_intrinsic_base(instr) + nir_src_as_uint(instr->src[1]);
1669
1670 reg = nir_src_index(ctx, &instr->src[0]);
1671
1672 if (ctx->stage == MESA_SHADER_FRAGMENT) {
1673 const nir_variable *var;
1674 enum midgard_rt_id rt;
1675
1676 var = search_var(&ctx->nir->outputs,
1677 nir_intrinsic_base(instr));
1678 assert(var);
1679 if (var->data.location == FRAG_RESULT_COLOR)
1680 rt = MIDGARD_COLOR_RT0;
1681 else if (var->data.location >= FRAG_RESULT_DATA0)
1682 rt = MIDGARD_COLOR_RT0 + var->data.location -
1683 FRAG_RESULT_DATA0;
1684 else
1685 assert(0);
1686
1687 emit_fragment_store(ctx, reg, rt);
1688 } else if (ctx->stage == MESA_SHADER_VERTEX) {
1689 /* We should have been vectorized, though we don't
1690 * currently check that st_vary is emitted only once
1691 * per slot (this is relevant, since there's not a mask
1692 * parameter available on the store [set to 0 by the
1693 * blob]). We do respect the component by adjusting the
1694 * swizzle. If this is a constant source, we'll need to
1695 * emit that explicitly. */
1696
1697 emit_explicit_constant(ctx, reg, reg);
1698
1699 unsigned dst_component = nir_intrinsic_component(instr);
1700 unsigned nr_comp = nir_src_num_components(instr->src[0]);
1701
1702 midgard_instruction st = m_st_vary_32(reg, offset);
1703 st.load_store.arg_1 = 0x9E;
1704 st.load_store.arg_2 = 0x1E;
1705
1706 switch (nir_alu_type_get_base_type(nir_intrinsic_type(instr))) {
1707 case nir_type_uint:
1708 case nir_type_bool:
1709 st.load_store.op = midgard_op_st_vary_32u;
1710 break;
1711 case nir_type_int:
1712 st.load_store.op = midgard_op_st_vary_32i;
1713 break;
1714 case nir_type_float:
1715 st.load_store.op = midgard_op_st_vary_32;
1716 break;
1717 default:
1718 unreachable("Attempted to store unknown type");
1719 break;
1720 }
1721
1722 /* nir_intrinsic_component(store_intr) encodes the
1723 * destination component start. Source component offset
1724 * adjustment is taken care of in
1725 * install_registers_instr(), when offset_swizzle() is
1726 * called.
1727 */
1728 unsigned src_component = COMPONENT_X;
1729
1730 assert(nr_comp > 0);
1731 for (unsigned i = 0; i < ARRAY_SIZE(st.swizzle); ++i) {
1732 st.swizzle[0][i] = src_component;
1733 if (i >= dst_component && i < dst_component + nr_comp - 1)
1734 src_component++;
1735 }
1736
1737 emit_mir_instruction(ctx, st);
1738 } else {
1739 DBG("Unknown store\n");
1740 assert(0);
1741 }
1742
1743 break;
1744
1745 /* Special case of store_output for lowered blend shaders */
1746 case nir_intrinsic_store_raw_output_pan:
1747 assert (ctx->stage == MESA_SHADER_FRAGMENT);
1748 reg = nir_src_index(ctx, &instr->src[0]);
1749 emit_fragment_store(ctx, reg, ctx->blend_rt);
1750 break;
1751
1752 case nir_intrinsic_store_global:
1753 case nir_intrinsic_store_shared:
1754 reg = nir_src_index(ctx, &instr->src[0]);
1755 emit_explicit_constant(ctx, reg, reg);
1756
1757 emit_global(ctx, &instr->instr, false, reg, &instr->src[1], instr->intrinsic == nir_intrinsic_store_shared);
1758 break;
1759
1760 case nir_intrinsic_load_ssbo_address:
1761 emit_sysval_read(ctx, &instr->instr, 1, 0);
1762 break;
1763
1764 case nir_intrinsic_get_buffer_size:
1765 emit_sysval_read(ctx, &instr->instr, 1, 8);
1766 break;
1767
1768 case nir_intrinsic_load_viewport_scale:
1769 case nir_intrinsic_load_viewport_offset:
1770 case nir_intrinsic_load_num_work_groups:
1771 case nir_intrinsic_load_sampler_lod_parameters_pan:
1772 emit_sysval_read(ctx, &instr->instr, 3, 0);
1773 break;
1774
1775 case nir_intrinsic_load_work_group_id:
1776 case nir_intrinsic_load_local_invocation_id:
1777 emit_compute_builtin(ctx, instr);
1778 break;
1779
1780 case nir_intrinsic_load_vertex_id:
1781 case nir_intrinsic_load_instance_id:
1782 emit_vertex_builtin(ctx, instr);
1783 break;
1784
1785 case nir_intrinsic_memory_barrier_buffer:
1786 case nir_intrinsic_memory_barrier_shared:
1787 break;
1788
1789 case nir_intrinsic_control_barrier:
1790 schedule_barrier(ctx);
1791 emit_control_barrier(ctx);
1792 schedule_barrier(ctx);
1793 break;
1794
1795 default:
1796 fprintf(stderr, "Unhandled intrinsic %s\n", nir_intrinsic_infos[instr->intrinsic].name);
1797 assert(0);
1798 break;
1799 }
1800 }
1801
1802 static unsigned
1803 midgard_tex_format(enum glsl_sampler_dim dim)
1804 {
1805 switch (dim) {
1806 case GLSL_SAMPLER_DIM_1D:
1807 case GLSL_SAMPLER_DIM_BUF:
1808 return MALI_TEX_1D;
1809
1810 case GLSL_SAMPLER_DIM_2D:
1811 case GLSL_SAMPLER_DIM_EXTERNAL:
1812 case GLSL_SAMPLER_DIM_RECT:
1813 return MALI_TEX_2D;
1814
1815 case GLSL_SAMPLER_DIM_3D:
1816 return MALI_TEX_3D;
1817
1818 case GLSL_SAMPLER_DIM_CUBE:
1819 return MALI_TEX_CUBE;
1820
1821 default:
1822 DBG("Unknown sampler dim type\n");
1823 assert(0);
1824 return 0;
1825 }
1826 }
1827
1828 /* Tries to attach an explicit LOD or bias as a constant. Returns whether this
1829 * was successful */
1830
1831 static bool
1832 pan_attach_constant_bias(
1833 compiler_context *ctx,
1834 nir_src lod,
1835 midgard_texture_word *word)
1836 {
1837 /* To attach as constant, it has to *be* constant */
1838
1839 if (!nir_src_is_const(lod))
1840 return false;
1841
1842 float f = nir_src_as_float(lod);
1843
1844 /* Break into fixed-point */
1845 signed lod_int = f;
1846 float lod_frac = f - lod_int;
1847
1848 /* Carry over negative fractions */
1849 if (lod_frac < 0.0) {
1850 lod_int--;
1851 lod_frac += 1.0;
1852 }
1853
1854 /* Encode */
1855 word->bias = float_to_ubyte(lod_frac);
1856 word->bias_int = lod_int;
1857
1858 return true;
1859 }
1860
1861 static void
1862 emit_texop_native(compiler_context *ctx, nir_tex_instr *instr,
1863 unsigned midgard_texop)
1864 {
1865 /* TODO */
1866 //assert (!instr->sampler);
1867
1868 int texture_index = instr->texture_index;
1869 int sampler_index = texture_index;
1870
1871 nir_alu_type dest_base = nir_alu_type_get_base_type(instr->dest_type);
1872 nir_alu_type dest_type = dest_base | nir_dest_bit_size(instr->dest);
1873
1874 midgard_instruction ins = {
1875 .type = TAG_TEXTURE_4,
1876 .mask = 0xF,
1877 .dest = nir_dest_index(&instr->dest),
1878 .src = { ~0, ~0, ~0, ~0 },
1879 .dest_type = dest_type,
1880 .swizzle = SWIZZLE_IDENTITY_4,
1881 .texture = {
1882 .op = midgard_texop,
1883 .format = midgard_tex_format(instr->sampler_dim),
1884 .texture_handle = texture_index,
1885 .sampler_handle = sampler_index,
1886 .shadow = instr->is_shadow,
1887 }
1888 };
1889
1890 if (instr->is_shadow && !instr->is_new_style_shadow)
1891 for (int i = 0; i < 4; ++i)
1892 ins.swizzle[0][i] = COMPONENT_X;
1893
1894 /* We may need a temporary for the coordinate */
1895
1896 bool needs_temp_coord =
1897 (midgard_texop == TEXTURE_OP_TEXEL_FETCH) ||
1898 (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) ||
1899 (instr->is_shadow);
1900
1901 unsigned coords = needs_temp_coord ? make_compiler_temp_reg(ctx) : 0;
1902
1903 for (unsigned i = 0; i < instr->num_srcs; ++i) {
1904 int index = nir_src_index(ctx, &instr->src[i].src);
1905 unsigned nr_components = nir_src_num_components(instr->src[i].src);
1906 unsigned sz = nir_src_bit_size(instr->src[i].src);
1907 nir_alu_type T = nir_tex_instr_src_type(instr, i) | sz;
1908
1909 switch (instr->src[i].src_type) {
1910 case nir_tex_src_coord: {
1911 emit_explicit_constant(ctx, index, index);
1912
1913 unsigned coord_mask = mask_of(instr->coord_components);
1914
1915 bool flip_zw = (instr->sampler_dim == GLSL_SAMPLER_DIM_2D) && (coord_mask & (1 << COMPONENT_Z));
1916
1917 if (flip_zw)
1918 coord_mask ^= ((1 << COMPONENT_Z) | (1 << COMPONENT_W));
1919
1920 if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) {
1921 /* texelFetch is undefined on samplerCube */
1922 assert(midgard_texop != TEXTURE_OP_TEXEL_FETCH);
1923
1924 /* For cubemaps, we use a special ld/st op to
1925 * select the face and copy the xy into the
1926 * texture register */
1927
1928 midgard_instruction ld = m_ld_cubemap_coords(coords, 0);
1929 ld.src[1] = index;
1930 ld.src_types[1] = T;
1931 ld.mask = 0x3; /* xy */
1932 ld.load_store.arg_1 = 0x20;
1933 ld.swizzle[1][3] = COMPONENT_X;
1934 emit_mir_instruction(ctx, ld);
1935
1936 /* xyzw -> xyxx */
1937 ins.swizzle[1][2] = instr->is_shadow ? COMPONENT_Z : COMPONENT_X;
1938 ins.swizzle[1][3] = COMPONENT_X;
1939 } else if (needs_temp_coord) {
1940 /* mov coord_temp, coords */
1941 midgard_instruction mov = v_mov(index, coords);
1942 mov.mask = coord_mask;
1943
1944 if (flip_zw)
1945 mov.swizzle[1][COMPONENT_W] = COMPONENT_Z;
1946
1947 emit_mir_instruction(ctx, mov);
1948 } else {
1949 coords = index;
1950 }
1951
1952 ins.src[1] = coords;
1953 ins.src_types[1] = T;
1954
1955 /* Texelfetch coordinates uses all four elements
1956 * (xyz/index) regardless of texture dimensionality,
1957 * which means it's necessary to zero the unused
1958 * components to keep everything happy */
1959
1960 if (midgard_texop == TEXTURE_OP_TEXEL_FETCH) {
1961 /* mov index.zw, #0, or generalized */
1962 midgard_instruction mov =
1963 v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), coords);
1964 mov.has_constants = true;
1965 mov.mask = coord_mask ^ 0xF;
1966 emit_mir_instruction(ctx, mov);
1967 }
1968
1969 if (instr->sampler_dim == GLSL_SAMPLER_DIM_2D) {
1970 /* Array component in w but NIR wants it in z,
1971 * but if we have a temp coord we already fixed
1972 * that up */
1973
1974 if (nr_components == 3) {
1975 ins.swizzle[1][2] = COMPONENT_Z;
1976 ins.swizzle[1][3] = needs_temp_coord ? COMPONENT_W : COMPONENT_Z;
1977 } else if (nr_components == 2) {
1978 ins.swizzle[1][2] =
1979 instr->is_shadow ? COMPONENT_Z : COMPONENT_X;
1980 ins.swizzle[1][3] = COMPONENT_X;
1981 } else
1982 unreachable("Invalid texture 2D components");
1983 }
1984
1985 if (midgard_texop == TEXTURE_OP_TEXEL_FETCH) {
1986 /* We zeroed */
1987 ins.swizzle[1][2] = COMPONENT_Z;
1988 ins.swizzle[1][3] = COMPONENT_W;
1989 }
1990
1991 break;
1992 }
1993
1994 case nir_tex_src_bias:
1995 case nir_tex_src_lod: {
1996 /* Try as a constant if we can */
1997
1998 bool is_txf = midgard_texop == TEXTURE_OP_TEXEL_FETCH;
1999 if (!is_txf && pan_attach_constant_bias(ctx, instr->src[i].src, &ins.texture))
2000 break;
2001
2002 ins.texture.lod_register = true;
2003 ins.src[2] = index;
2004 ins.src_types[2] = T;
2005
2006 for (unsigned c = 0; c < MIR_VEC_COMPONENTS; ++c)
2007 ins.swizzle[2][c] = COMPONENT_X;
2008
2009 emit_explicit_constant(ctx, index, index);
2010
2011 break;
2012 };
2013
2014 case nir_tex_src_offset: {
2015 ins.texture.offset_register = true;
2016 ins.src[3] = index;
2017 ins.src_types[3] = T;
2018
2019 for (unsigned c = 0; c < MIR_VEC_COMPONENTS; ++c)
2020 ins.swizzle[3][c] = (c > COMPONENT_Z) ? 0 : c;
2021
2022 emit_explicit_constant(ctx, index, index);
2023 break;
2024 };
2025
2026 case nir_tex_src_comparator: {
2027 unsigned comp = COMPONENT_Z;
2028
2029 /* mov coord_temp.foo, coords */
2030 midgard_instruction mov = v_mov(index, coords);
2031 mov.mask = 1 << comp;
2032
2033 for (unsigned i = 0; i < MIR_VEC_COMPONENTS; ++i)
2034 mov.swizzle[1][i] = COMPONENT_X;
2035
2036 emit_mir_instruction(ctx, mov);
2037 break;
2038 }
2039
2040 default: {
2041 fprintf(stderr, "Unknown texture source type: %d\n", instr->src[i].src_type);
2042 assert(0);
2043 }
2044 }
2045 }
2046
2047 emit_mir_instruction(ctx, ins);
2048 }
2049
2050 static void
2051 emit_tex(compiler_context *ctx, nir_tex_instr *instr)
2052 {
2053 switch (instr->op) {
2054 case nir_texop_tex:
2055 case nir_texop_txb:
2056 emit_texop_native(ctx, instr, TEXTURE_OP_NORMAL);
2057 break;
2058 case nir_texop_txl:
2059 emit_texop_native(ctx, instr, TEXTURE_OP_LOD);
2060 break;
2061 case nir_texop_txf:
2062 emit_texop_native(ctx, instr, TEXTURE_OP_TEXEL_FETCH);
2063 break;
2064 case nir_texop_txs:
2065 emit_sysval_read(ctx, &instr->instr, 4, 0);
2066 break;
2067 default: {
2068 fprintf(stderr, "Unhandled texture op: %d\n", instr->op);
2069 assert(0);
2070 }
2071 }
2072 }
2073
2074 static void
2075 emit_jump(compiler_context *ctx, nir_jump_instr *instr)
2076 {
2077 switch (instr->type) {
2078 case nir_jump_break: {
2079 /* Emit a branch out of the loop */
2080 struct midgard_instruction br = v_branch(false, false);
2081 br.branch.target_type = TARGET_BREAK;
2082 br.branch.target_break = ctx->current_loop_depth;
2083 emit_mir_instruction(ctx, br);
2084 break;
2085 }
2086
2087 default:
2088 DBG("Unknown jump type %d\n", instr->type);
2089 break;
2090 }
2091 }
2092
2093 static void
2094 emit_instr(compiler_context *ctx, struct nir_instr *instr)
2095 {
2096 switch (instr->type) {
2097 case nir_instr_type_load_const:
2098 emit_load_const(ctx, nir_instr_as_load_const(instr));
2099 break;
2100
2101 case nir_instr_type_intrinsic:
2102 emit_intrinsic(ctx, nir_instr_as_intrinsic(instr));
2103 break;
2104
2105 case nir_instr_type_alu:
2106 emit_alu(ctx, nir_instr_as_alu(instr));
2107 break;
2108
2109 case nir_instr_type_tex:
2110 emit_tex(ctx, nir_instr_as_tex(instr));
2111 break;
2112
2113 case nir_instr_type_jump:
2114 emit_jump(ctx, nir_instr_as_jump(instr));
2115 break;
2116
2117 case nir_instr_type_ssa_undef:
2118 /* Spurious */
2119 break;
2120
2121 default:
2122 DBG("Unhandled instruction type\n");
2123 break;
2124 }
2125 }
2126
2127
2128 /* ALU instructions can inline or embed constants, which decreases register
2129 * pressure and saves space. */
2130
2131 #define CONDITIONAL_ATTACH(idx) { \
2132 void *entry = _mesa_hash_table_u64_search(ctx->ssa_constants, alu->src[idx] + 1); \
2133 \
2134 if (entry) { \
2135 attach_constants(ctx, alu, entry, alu->src[idx] + 1); \
2136 alu->src[idx] = SSA_FIXED_REGISTER(REGISTER_CONSTANT); \
2137 } \
2138 }
2139
2140 static void
2141 inline_alu_constants(compiler_context *ctx, midgard_block *block)
2142 {
2143 mir_foreach_instr_in_block(block, alu) {
2144 /* Other instructions cannot inline constants */
2145 if (alu->type != TAG_ALU_4) continue;
2146 if (alu->compact_branch) continue;
2147
2148 /* If there is already a constant here, we can do nothing */
2149 if (alu->has_constants) continue;
2150
2151 CONDITIONAL_ATTACH(0);
2152
2153 if (!alu->has_constants) {
2154 CONDITIONAL_ATTACH(1)
2155 } else if (!alu->inline_constant) {
2156 /* Corner case: _two_ vec4 constants, for instance with a
2157 * csel. For this case, we can only use a constant
2158 * register for one, we'll have to emit a move for the
2159 * other. */
2160
2161 void *entry = _mesa_hash_table_u64_search(ctx->ssa_constants, alu->src[1] + 1);
2162 unsigned scratch = make_compiler_temp(ctx);
2163
2164 if (entry) {
2165 midgard_instruction ins = v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), scratch);
2166 attach_constants(ctx, &ins, entry, alu->src[1] + 1);
2167
2168 /* Set the source */
2169 alu->src[1] = scratch;
2170
2171 /* Inject us -before- the last instruction which set r31 */
2172 mir_insert_instruction_before(ctx, mir_prev_op(alu), ins);
2173 }
2174 }
2175 }
2176 }
2177
2178 /* Midgard supports two types of constants, embedded constants (128-bit) and
2179 * inline constants (16-bit). Sometimes, especially with scalar ops, embedded
2180 * constants can be demoted to inline constants, for space savings and
2181 * sometimes a performance boost */
2182
2183 static void
2184 embedded_to_inline_constant(compiler_context *ctx, midgard_block *block)
2185 {
2186 mir_foreach_instr_in_block(block, ins) {
2187 if (!ins->has_constants) continue;
2188 if (ins->has_inline_constant) continue;
2189
2190 /* Blend constants must not be inlined by definition */
2191 if (ins->has_blend_constant) continue;
2192
2193 /* We can inline 32-bit (sometimes) or 16-bit (usually) */
2194 bool is_16 = ins->alu.reg_mode == midgard_reg_mode_16;
2195 bool is_32 = ins->alu.reg_mode == midgard_reg_mode_32;
2196
2197 if (!(is_16 || is_32))
2198 continue;
2199
2200 /* src1 cannot be an inline constant due to encoding
2201 * restrictions. So, if possible we try to flip the arguments
2202 * in that case */
2203
2204 int op = ins->alu.op;
2205
2206 if (ins->src[0] == SSA_FIXED_REGISTER(REGISTER_CONSTANT) &&
2207 alu_opcode_props[op].props & OP_COMMUTES) {
2208 mir_flip(ins);
2209 }
2210
2211 if (ins->src[1] == SSA_FIXED_REGISTER(REGISTER_CONSTANT)) {
2212 /* Component is from the swizzle. Take a nonzero component */
2213 assert(ins->mask);
2214 unsigned first_comp = ffs(ins->mask) - 1;
2215 unsigned component = ins->swizzle[1][first_comp];
2216
2217 /* Scale constant appropriately, if we can legally */
2218 uint16_t scaled_constant = 0;
2219
2220 if (is_16) {
2221 scaled_constant = ins->constants.u16[component];
2222 } else if (midgard_is_integer_op(op)) {
2223 scaled_constant = ins->constants.u32[component];
2224
2225 /* Constant overflow after resize */
2226 if (scaled_constant != ins->constants.u32[component])
2227 continue;
2228 } else {
2229 float original = ins->constants.f32[component];
2230 scaled_constant = _mesa_float_to_half(original);
2231
2232 /* Check for loss of precision. If this is
2233 * mediump, we don't care, but for a highp
2234 * shader, we need to pay attention. NIR
2235 * doesn't yet tell us which mode we're in!
2236 * Practically this prevents most constants
2237 * from being inlined, sadly. */
2238
2239 float fp32 = _mesa_half_to_float(scaled_constant);
2240
2241 if (fp32 != original)
2242 continue;
2243 }
2244
2245 /* Should've been const folded */
2246 if (ins->src_abs[1] || ins->src_neg[1])
2247 continue;
2248
2249 /* Make sure that the constant is not itself a vector
2250 * by checking if all accessed values are the same. */
2251
2252 const midgard_constants *cons = &ins->constants;
2253 uint32_t value = is_16 ? cons->u16[component] : cons->u32[component];
2254
2255 bool is_vector = false;
2256 unsigned mask = effective_writemask(&ins->alu, ins->mask);
2257
2258 for (unsigned c = 0; c < MIR_VEC_COMPONENTS; ++c) {
2259 /* We only care if this component is actually used */
2260 if (!(mask & (1 << c)))
2261 continue;
2262
2263 uint32_t test = is_16 ?
2264 cons->u16[ins->swizzle[1][c]] :
2265 cons->u32[ins->swizzle[1][c]];
2266
2267 if (test != value) {
2268 is_vector = true;
2269 break;
2270 }
2271 }
2272
2273 if (is_vector)
2274 continue;
2275
2276 /* Get rid of the embedded constant */
2277 ins->has_constants = false;
2278 ins->src[1] = ~0;
2279 ins->has_inline_constant = true;
2280 ins->inline_constant = scaled_constant;
2281 }
2282 }
2283 }
2284
2285 /* Dead code elimination for branches at the end of a block - only one branch
2286 * per block is legal semantically */
2287
2288 static void
2289 midgard_cull_dead_branch(compiler_context *ctx, midgard_block *block)
2290 {
2291 bool branched = false;
2292
2293 mir_foreach_instr_in_block_safe(block, ins) {
2294 if (!midgard_is_branch_unit(ins->unit)) continue;
2295
2296 if (branched)
2297 mir_remove_instruction(ins);
2298
2299 branched = true;
2300 }
2301 }
2302
2303 /* We want to force the invert on AND/OR to the second slot to legalize into
2304 * iandnot/iornot. The relevant patterns are for AND (and OR respectively)
2305 *
2306 * ~a & #b = ~a & ~(#~b)
2307 * ~a & b = b & ~a
2308 */
2309
2310 static void
2311 midgard_legalize_invert(compiler_context *ctx, midgard_block *block)
2312 {
2313 mir_foreach_instr_in_block(block, ins) {
2314 if (ins->type != TAG_ALU_4) continue;
2315
2316 if (ins->alu.op != midgard_alu_op_iand &&
2317 ins->alu.op != midgard_alu_op_ior) continue;
2318
2319 if (ins->src_invert[1] || !ins->src_invert[0]) continue;
2320
2321 if (ins->has_inline_constant) {
2322 /* ~(#~a) = ~(~#a) = a, so valid, and forces both
2323 * inverts on */
2324 ins->inline_constant = ~ins->inline_constant;
2325 ins->src_invert[1] = true;
2326 } else {
2327 /* Flip to the right invert order. Note
2328 * has_inline_constant false by assumption on the
2329 * branch, so flipping makes sense. */
2330 mir_flip(ins);
2331 }
2332 }
2333 }
2334
2335 static unsigned
2336 emit_fragment_epilogue(compiler_context *ctx, unsigned rt)
2337 {
2338 /* Loop to ourselves */
2339 midgard_instruction *br = ctx->writeout_branch[rt];
2340 struct midgard_instruction ins = v_branch(false, false);
2341 ins.writeout = true;
2342 ins.writeout_depth = br->writeout_depth;
2343 ins.writeout_stencil = br->writeout_stencil;
2344 ins.branch.target_block = ctx->block_count - 1;
2345 ins.constants.u32[0] = br->constants.u32[0];
2346 emit_mir_instruction(ctx, ins);
2347
2348 ctx->current_block->epilogue = true;
2349 schedule_barrier(ctx);
2350 return ins.branch.target_block;
2351 }
2352
2353 static midgard_block *
2354 emit_block(compiler_context *ctx, nir_block *block)
2355 {
2356 midgard_block *this_block = ctx->after_block;
2357 ctx->after_block = NULL;
2358
2359 if (!this_block)
2360 this_block = create_empty_block(ctx);
2361
2362 list_addtail(&this_block->base.link, &ctx->blocks);
2363
2364 this_block->scheduled = false;
2365 ++ctx->block_count;
2366
2367 /* Set up current block */
2368 list_inithead(&this_block->base.instructions);
2369 ctx->current_block = this_block;
2370
2371 nir_foreach_instr(instr, block) {
2372 emit_instr(ctx, instr);
2373 ++ctx->instruction_count;
2374 }
2375
2376 return this_block;
2377 }
2378
2379 static midgard_block *emit_cf_list(struct compiler_context *ctx, struct exec_list *list);
2380
2381 static void
2382 emit_if(struct compiler_context *ctx, nir_if *nif)
2383 {
2384 midgard_block *before_block = ctx->current_block;
2385
2386 /* Speculatively emit the branch, but we can't fill it in until later */
2387 bool inv = false;
2388 EMIT(branch, true, true);
2389 midgard_instruction *then_branch = mir_last_in_block(ctx->current_block);
2390 then_branch->src[0] = mir_get_branch_cond(&nif->condition, &inv);
2391 then_branch->src_types[0] = nir_type_uint32;
2392 then_branch->branch.invert_conditional = !inv;
2393
2394 /* Emit the two subblocks. */
2395 midgard_block *then_block = emit_cf_list(ctx, &nif->then_list);
2396 midgard_block *end_then_block = ctx->current_block;
2397
2398 /* Emit a jump from the end of the then block to the end of the else */
2399 EMIT(branch, false, false);
2400 midgard_instruction *then_exit = mir_last_in_block(ctx->current_block);
2401
2402 /* Emit second block, and check if it's empty */
2403
2404 int else_idx = ctx->block_count;
2405 int count_in = ctx->instruction_count;
2406 midgard_block *else_block = emit_cf_list(ctx, &nif->else_list);
2407 midgard_block *end_else_block = ctx->current_block;
2408 int after_else_idx = ctx->block_count;
2409
2410 /* Now that we have the subblocks emitted, fix up the branches */
2411
2412 assert(then_block);
2413 assert(else_block);
2414
2415 if (ctx->instruction_count == count_in) {
2416 /* The else block is empty, so don't emit an exit jump */
2417 mir_remove_instruction(then_exit);
2418 then_branch->branch.target_block = after_else_idx;
2419 } else {
2420 then_branch->branch.target_block = else_idx;
2421 then_exit->branch.target_block = after_else_idx;
2422 }
2423
2424 /* Wire up the successors */
2425
2426 ctx->after_block = create_empty_block(ctx);
2427
2428 pan_block_add_successor(&before_block->base, &then_block->base);
2429 pan_block_add_successor(&before_block->base, &else_block->base);
2430
2431 pan_block_add_successor(&end_then_block->base, &ctx->after_block->base);
2432 pan_block_add_successor(&end_else_block->base, &ctx->after_block->base);
2433 }
2434
2435 static void
2436 emit_loop(struct compiler_context *ctx, nir_loop *nloop)
2437 {
2438 /* Remember where we are */
2439 midgard_block *start_block = ctx->current_block;
2440
2441 /* Allocate a loop number, growing the current inner loop depth */
2442 int loop_idx = ++ctx->current_loop_depth;
2443
2444 /* Get index from before the body so we can loop back later */
2445 int start_idx = ctx->block_count;
2446
2447 /* Emit the body itself */
2448 midgard_block *loop_block = emit_cf_list(ctx, &nloop->body);
2449
2450 /* Branch back to loop back */
2451 struct midgard_instruction br_back = v_branch(false, false);
2452 br_back.branch.target_block = start_idx;
2453 emit_mir_instruction(ctx, br_back);
2454
2455 /* Mark down that branch in the graph. */
2456 pan_block_add_successor(&start_block->base, &loop_block->base);
2457 pan_block_add_successor(&ctx->current_block->base, &loop_block->base);
2458
2459 /* Find the index of the block about to follow us (note: we don't add
2460 * one; blocks are 0-indexed so we get a fencepost problem) */
2461 int break_block_idx = ctx->block_count;
2462
2463 /* Fix up the break statements we emitted to point to the right place,
2464 * now that we can allocate a block number for them */
2465 ctx->after_block = create_empty_block(ctx);
2466
2467 mir_foreach_block_from(ctx, start_block, _block) {
2468 mir_foreach_instr_in_block(((midgard_block *) _block), ins) {
2469 if (ins->type != TAG_ALU_4) continue;
2470 if (!ins->compact_branch) continue;
2471
2472 /* We found a branch -- check the type to see if we need to do anything */
2473 if (ins->branch.target_type != TARGET_BREAK) continue;
2474
2475 /* It's a break! Check if it's our break */
2476 if (ins->branch.target_break != loop_idx) continue;
2477
2478 /* Okay, cool, we're breaking out of this loop.
2479 * Rewrite from a break to a goto */
2480
2481 ins->branch.target_type = TARGET_GOTO;
2482 ins->branch.target_block = break_block_idx;
2483
2484 pan_block_add_successor(_block, &ctx->after_block->base);
2485 }
2486 }
2487
2488 /* Now that we've finished emitting the loop, free up the depth again
2489 * so we play nice with recursion amid nested loops */
2490 --ctx->current_loop_depth;
2491
2492 /* Dump loop stats */
2493 ++ctx->loop_count;
2494 }
2495
2496 static midgard_block *
2497 emit_cf_list(struct compiler_context *ctx, struct exec_list *list)
2498 {
2499 midgard_block *start_block = NULL;
2500
2501 foreach_list_typed(nir_cf_node, node, node, list) {
2502 switch (node->type) {
2503 case nir_cf_node_block: {
2504 midgard_block *block = emit_block(ctx, nir_cf_node_as_block(node));
2505
2506 if (!start_block)
2507 start_block = block;
2508
2509 break;
2510 }
2511
2512 case nir_cf_node_if:
2513 emit_if(ctx, nir_cf_node_as_if(node));
2514 break;
2515
2516 case nir_cf_node_loop:
2517 emit_loop(ctx, nir_cf_node_as_loop(node));
2518 break;
2519
2520 case nir_cf_node_function:
2521 assert(0);
2522 break;
2523 }
2524 }
2525
2526 return start_block;
2527 }
2528
2529 /* Due to lookahead, we need to report the first tag executed in the command
2530 * stream and in branch targets. An initial block might be empty, so iterate
2531 * until we find one that 'works' */
2532
2533 static unsigned
2534 midgard_get_first_tag_from_block(compiler_context *ctx, unsigned block_idx)
2535 {
2536 midgard_block *initial_block = mir_get_block(ctx, block_idx);
2537
2538 mir_foreach_block_from(ctx, initial_block, _v) {
2539 midgard_block *v = (midgard_block *) _v;
2540 if (v->quadword_count) {
2541 midgard_bundle *initial_bundle =
2542 util_dynarray_element(&v->bundles, midgard_bundle, 0);
2543
2544 return initial_bundle->tag;
2545 }
2546 }
2547
2548 /* Default to a tag 1 which will break from the shader, in case we jump
2549 * to the exit block (i.e. `return` in a compute shader) */
2550
2551 return 1;
2552 }
2553
2554 /* For each fragment writeout instruction, generate a writeout loop to
2555 * associate with it */
2556
2557 static void
2558 mir_add_writeout_loops(compiler_context *ctx)
2559 {
2560 for (unsigned rt = 0; rt < ARRAY_SIZE(ctx->writeout_branch); ++rt) {
2561 midgard_instruction *br = ctx->writeout_branch[rt];
2562 if (!br) continue;
2563
2564 unsigned popped = br->branch.target_block;
2565 pan_block_add_successor(&(mir_get_block(ctx, popped - 1)->base), &ctx->current_block->base);
2566 br->branch.target_block = emit_fragment_epilogue(ctx, rt);
2567 br->branch.target_type = TARGET_GOTO;
2568
2569 /* If we have more RTs, we'll need to restore back after our
2570 * loop terminates */
2571
2572 if ((rt + 1) < ARRAY_SIZE(ctx->writeout_branch) && ctx->writeout_branch[rt + 1]) {
2573 midgard_instruction uncond = v_branch(false, false);
2574 uncond.branch.target_block = popped;
2575 uncond.branch.target_type = TARGET_GOTO;
2576 emit_mir_instruction(ctx, uncond);
2577 pan_block_add_successor(&ctx->current_block->base, &(mir_get_block(ctx, popped)->base));
2578 schedule_barrier(ctx);
2579 } else {
2580 /* We're last, so we can terminate here */
2581 br->last_writeout = true;
2582 }
2583 }
2584 }
2585
2586 int
2587 midgard_compile_shader_nir(nir_shader *nir, panfrost_program *program, bool is_blend, unsigned blend_rt, unsigned gpu_id, bool shaderdb)
2588 {
2589 struct util_dynarray *compiled = &program->compiled;
2590
2591 midgard_debug = debug_get_option_midgard_debug();
2592
2593 /* TODO: Bound against what? */
2594 compiler_context *ctx = rzalloc(NULL, compiler_context);
2595
2596 ctx->nir = nir;
2597 ctx->stage = nir->info.stage;
2598 ctx->is_blend = is_blend;
2599 ctx->alpha_ref = program->alpha_ref;
2600 ctx->blend_rt = MIDGARD_COLOR_RT0 + blend_rt;
2601 ctx->quirks = midgard_get_quirks(gpu_id);
2602
2603 /* Start off with a safe cutoff, allowing usage of all 16 work
2604 * registers. Later, we'll promote uniform reads to uniform registers
2605 * if we determine it is beneficial to do so */
2606 ctx->uniform_cutoff = 8;
2607
2608 /* Initialize at a global (not block) level hash tables */
2609
2610 ctx->ssa_constants = _mesa_hash_table_u64_create(NULL);
2611 ctx->hash_to_temp = _mesa_hash_table_u64_create(NULL);
2612
2613 /* Lower gl_Position pre-optimisation, but after lowering vars to ssa
2614 * (so we don't accidentally duplicate the epilogue since mesa/st has
2615 * messed with our I/O quite a bit already) */
2616
2617 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
2618
2619 if (ctx->stage == MESA_SHADER_VERTEX) {
2620 NIR_PASS_V(nir, nir_lower_viewport_transform);
2621 NIR_PASS_V(nir, nir_lower_point_size, 1.0, 1024.0);
2622 }
2623
2624 NIR_PASS_V(nir, nir_lower_var_copies);
2625 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
2626 NIR_PASS_V(nir, nir_split_var_copies);
2627 NIR_PASS_V(nir, nir_lower_var_copies);
2628 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
2629 NIR_PASS_V(nir, nir_lower_var_copies);
2630 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
2631
2632 NIR_PASS_V(nir, nir_lower_io, nir_var_all, glsl_type_size, 0);
2633 NIR_PASS_V(nir, nir_lower_ssbo);
2634 NIR_PASS_V(nir, midgard_nir_lower_zs_store);
2635
2636 /* Optimisation passes */
2637
2638 optimise_nir(nir, ctx->quirks, is_blend);
2639
2640 if (midgard_debug & MIDGARD_DBG_SHADERS) {
2641 nir_print_shader(nir, stdout);
2642 }
2643
2644 /* Assign sysvals and counts, now that we're sure
2645 * (post-optimisation) */
2646
2647 panfrost_nir_assign_sysvals(&ctx->sysvals, nir);
2648 program->sysval_count = ctx->sysvals.sysval_count;
2649 memcpy(program->sysvals, ctx->sysvals.sysvals, sizeof(ctx->sysvals.sysvals[0]) * ctx->sysvals.sysval_count);
2650
2651 nir_foreach_function(func, nir) {
2652 if (!func->impl)
2653 continue;
2654
2655 list_inithead(&ctx->blocks);
2656 ctx->block_count = 0;
2657 ctx->func = func;
2658 ctx->already_emitted = calloc(BITSET_WORDS(func->impl->ssa_alloc), sizeof(BITSET_WORD));
2659
2660 emit_cf_list(ctx, &func->impl->body);
2661 free(ctx->already_emitted);
2662 break; /* TODO: Multi-function shaders */
2663 }
2664
2665 util_dynarray_init(compiled, NULL);
2666
2667 /* Per-block lowering before opts */
2668
2669 mir_foreach_block(ctx, _block) {
2670 midgard_block *block = (midgard_block *) _block;
2671 inline_alu_constants(ctx, block);
2672 embedded_to_inline_constant(ctx, block);
2673 }
2674 /* MIR-level optimizations */
2675
2676 bool progress = false;
2677
2678 do {
2679 progress = false;
2680 progress |= midgard_opt_dead_code_eliminate(ctx);
2681
2682 mir_foreach_block(ctx, _block) {
2683 midgard_block *block = (midgard_block *) _block;
2684 progress |= midgard_opt_copy_prop(ctx, block);
2685 progress |= midgard_opt_combine_projection(ctx, block);
2686 progress |= midgard_opt_varying_projection(ctx, block);
2687 }
2688 } while (progress);
2689
2690 mir_foreach_block(ctx, _block) {
2691 midgard_block *block = (midgard_block *) _block;
2692 midgard_lower_derivatives(ctx, block);
2693 midgard_legalize_invert(ctx, block);
2694 midgard_cull_dead_branch(ctx, block);
2695 }
2696
2697 if (ctx->stage == MESA_SHADER_FRAGMENT)
2698 mir_add_writeout_loops(ctx);
2699
2700 /* Analyze now that the code is known but before scheduling creates
2701 * pipeline registers which are harder to track */
2702 mir_analyze_helper_terminate(ctx);
2703 mir_analyze_helper_requirements(ctx);
2704
2705 /* Schedule! */
2706 midgard_schedule_program(ctx);
2707 mir_ra(ctx);
2708
2709 /* Now that all the bundles are scheduled and we can calculate block
2710 * sizes, emit actual branch instructions rather than placeholders */
2711
2712 int br_block_idx = 0;
2713
2714 mir_foreach_block(ctx, _block) {
2715 midgard_block *block = (midgard_block *) _block;
2716 util_dynarray_foreach(&block->bundles, midgard_bundle, bundle) {
2717 for (int c = 0; c < bundle->instruction_count; ++c) {
2718 midgard_instruction *ins = bundle->instructions[c];
2719
2720 if (!midgard_is_branch_unit(ins->unit)) continue;
2721
2722 /* Parse some basic branch info */
2723 bool is_compact = ins->unit == ALU_ENAB_BR_COMPACT;
2724 bool is_conditional = ins->branch.conditional;
2725 bool is_inverted = ins->branch.invert_conditional;
2726 bool is_discard = ins->branch.target_type == TARGET_DISCARD;
2727 bool is_writeout = ins->writeout;
2728
2729 /* Determine the block we're jumping to */
2730 int target_number = ins->branch.target_block;
2731
2732 /* Report the destination tag */
2733 int dest_tag = is_discard ? 0 : midgard_get_first_tag_from_block(ctx, target_number);
2734
2735 /* Count up the number of quadwords we're
2736 * jumping over = number of quadwords until
2737 * (br_block_idx, target_number) */
2738
2739 int quadword_offset = 0;
2740
2741 if (is_discard) {
2742 /* Ignored */
2743 } else if (target_number > br_block_idx) {
2744 /* Jump forward */
2745
2746 for (int idx = br_block_idx + 1; idx < target_number; ++idx) {
2747 midgard_block *blk = mir_get_block(ctx, idx);
2748 assert(blk);
2749
2750 quadword_offset += blk->quadword_count;
2751 }
2752 } else {
2753 /* Jump backwards */
2754
2755 for (int idx = br_block_idx; idx >= target_number; --idx) {
2756 midgard_block *blk = mir_get_block(ctx, idx);
2757 assert(blk);
2758
2759 quadword_offset -= blk->quadword_count;
2760 }
2761 }
2762
2763 /* Unconditional extended branches (far jumps)
2764 * have issues, so we always use a conditional
2765 * branch, setting the condition to always for
2766 * unconditional. For compact unconditional
2767 * branches, cond isn't used so it doesn't
2768 * matter what we pick. */
2769
2770 midgard_condition cond =
2771 !is_conditional ? midgard_condition_always :
2772 is_inverted ? midgard_condition_false :
2773 midgard_condition_true;
2774
2775 midgard_jmp_writeout_op op =
2776 is_discard ? midgard_jmp_writeout_op_discard :
2777 is_writeout ? midgard_jmp_writeout_op_writeout :
2778 (is_compact && !is_conditional) ? midgard_jmp_writeout_op_branch_uncond :
2779 midgard_jmp_writeout_op_branch_cond;
2780
2781 if (!is_compact) {
2782 midgard_branch_extended branch =
2783 midgard_create_branch_extended(
2784 cond, op,
2785 dest_tag,
2786 quadword_offset);
2787
2788 memcpy(&ins->branch_extended, &branch, sizeof(branch));
2789 } else if (is_conditional || is_discard) {
2790 midgard_branch_cond branch = {
2791 .op = op,
2792 .dest_tag = dest_tag,
2793 .offset = quadword_offset,
2794 .cond = cond
2795 };
2796
2797 assert(branch.offset == quadword_offset);
2798
2799 memcpy(&ins->br_compact, &branch, sizeof(branch));
2800 } else {
2801 assert(op == midgard_jmp_writeout_op_branch_uncond);
2802
2803 midgard_branch_uncond branch = {
2804 .op = op,
2805 .dest_tag = dest_tag,
2806 .offset = quadword_offset,
2807 .unknown = 1
2808 };
2809
2810 assert(branch.offset == quadword_offset);
2811
2812 memcpy(&ins->br_compact, &branch, sizeof(branch));
2813 }
2814 }
2815 }
2816
2817 ++br_block_idx;
2818 }
2819
2820 /* Emit flat binary from the instruction arrays. Iterate each block in
2821 * sequence. Save instruction boundaries such that lookahead tags can
2822 * be assigned easily */
2823
2824 /* Cache _all_ bundles in source order for lookahead across failed branches */
2825
2826 int bundle_count = 0;
2827 mir_foreach_block(ctx, _block) {
2828 midgard_block *block = (midgard_block *) _block;
2829 bundle_count += block->bundles.size / sizeof(midgard_bundle);
2830 }
2831 midgard_bundle **source_order_bundles = malloc(sizeof(midgard_bundle *) * bundle_count);
2832 int bundle_idx = 0;
2833 mir_foreach_block(ctx, _block) {
2834 midgard_block *block = (midgard_block *) _block;
2835 util_dynarray_foreach(&block->bundles, midgard_bundle, bundle) {
2836 source_order_bundles[bundle_idx++] = bundle;
2837 }
2838 }
2839
2840 int current_bundle = 0;
2841
2842 /* Midgard prefetches instruction types, so during emission we
2843 * need to lookahead. Unless this is the last instruction, in
2844 * which we return 1. */
2845
2846 mir_foreach_block(ctx, _block) {
2847 midgard_block *block = (midgard_block *) _block;
2848 mir_foreach_bundle_in_block(block, bundle) {
2849 int lookahead = 1;
2850
2851 if (!bundle->last_writeout && (current_bundle + 1 < bundle_count))
2852 lookahead = source_order_bundles[current_bundle + 1]->tag;
2853
2854 emit_binary_bundle(ctx, block, bundle, compiled, lookahead);
2855 ++current_bundle;
2856 }
2857
2858 /* TODO: Free deeper */
2859 //util_dynarray_fini(&block->instructions);
2860 }
2861
2862 free(source_order_bundles);
2863
2864 /* Report the very first tag executed */
2865 program->first_tag = midgard_get_first_tag_from_block(ctx, 0);
2866
2867 /* Deal with off-by-one related to the fencepost problem */
2868 program->work_register_count = ctx->work_registers + 1;
2869 program->uniform_cutoff = ctx->uniform_cutoff;
2870
2871 program->blend_patch_offset = ctx->blend_constant_offset;
2872 program->tls_size = ctx->tls_size;
2873
2874 if (midgard_debug & MIDGARD_DBG_SHADERS)
2875 disassemble_midgard(stdout, program->compiled.data, program->compiled.size, gpu_id, ctx->stage);
2876
2877 if (midgard_debug & MIDGARD_DBG_SHADERDB || shaderdb) {
2878 unsigned nr_bundles = 0, nr_ins = 0;
2879
2880 /* Count instructions and bundles */
2881
2882 mir_foreach_block(ctx, _block) {
2883 midgard_block *block = (midgard_block *) _block;
2884 nr_bundles += util_dynarray_num_elements(
2885 &block->bundles, midgard_bundle);
2886
2887 mir_foreach_bundle_in_block(block, bun)
2888 nr_ins += bun->instruction_count;
2889 }
2890
2891 /* Calculate thread count. There are certain cutoffs by
2892 * register count for thread count */
2893
2894 unsigned nr_registers = program->work_register_count;
2895
2896 unsigned nr_threads =
2897 (nr_registers <= 4) ? 4 :
2898 (nr_registers <= 8) ? 2 :
2899 1;
2900
2901 /* Dump stats */
2902
2903 fprintf(stderr, "shader%d - %s shader: "
2904 "%u inst, %u bundles, %u quadwords, "
2905 "%u registers, %u threads, %u loops, "
2906 "%u:%u spills:fills\n",
2907 SHADER_DB_COUNT++,
2908 ctx->is_blend ? "PAN_SHADER_BLEND" :
2909 gl_shader_stage_name(ctx->stage),
2910 nr_ins, nr_bundles, ctx->quadword_count,
2911 nr_registers, nr_threads,
2912 ctx->loop_count,
2913 ctx->spills, ctx->fills);
2914 }
2915
2916 ralloc_free(ctx);
2917
2918 return 0;
2919 }