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