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