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