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