panfrost/midgard: Broadcast swizzle
[mesa.git] / src / gallium / drivers / 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 "main/imports.h"
37 #include "compiler/nir/nir_builder.h"
38 #include "util/half_float.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
51 #include "disassemble.h"
52
53 static const struct debug_named_value debug_options[] = {
54 {"msgs", MIDGARD_DBG_MSGS, "Print debug messages"},
55 {"shaders", MIDGARD_DBG_SHADERS, "Dump shaders in NIR and MIR"},
56 DEBUG_NAMED_VALUE_END
57 };
58
59 DEBUG_GET_ONCE_FLAGS_OPTION(midgard_debug, "MIDGARD_MESA_DEBUG", debug_options, 0)
60
61 int midgard_debug = 0;
62
63 #define DBG(fmt, ...) \
64 do { if (midgard_debug & MIDGARD_DBG_MSGS) \
65 fprintf(stderr, "%s:%d: "fmt, \
66 __FUNCTION__, __LINE__, ##__VA_ARGS__); } while (0)
67
68 static bool
69 midgard_is_branch_unit(unsigned unit)
70 {
71 return (unit == ALU_ENAB_BRANCH) || (unit == ALU_ENAB_BR_COMPACT);
72 }
73
74 static void
75 midgard_block_add_successor(midgard_block *block, midgard_block *successor)
76 {
77 block->successors[block->nr_successors++] = successor;
78 assert(block->nr_successors <= ARRAY_SIZE(block->successors));
79 }
80
81 /* Helpers to generate midgard_instruction's using macro magic, since every
82 * driver seems to do it that way */
83
84 #define EMIT(op, ...) emit_mir_instruction(ctx, v_##op(__VA_ARGS__));
85 #define SWIZZLE_XXXX SWIZZLE(COMPONENT_X, COMPONENT_X, COMPONENT_X, COMPONENT_X)
86 #define SWIZZLE_XYXX SWIZZLE(COMPONENT_X, COMPONENT_Y, COMPONENT_X, COMPONENT_X)
87 #define SWIZZLE_XYZX SWIZZLE(COMPONENT_X, COMPONENT_Y, COMPONENT_Z, COMPONENT_X)
88 #define SWIZZLE_XYZW SWIZZLE(COMPONENT_X, COMPONENT_Y, COMPONENT_Z, COMPONENT_W)
89 #define SWIZZLE_XYXZ SWIZZLE(COMPONENT_X, COMPONENT_Y, COMPONENT_X, COMPONENT_Z)
90 #define SWIZZLE_WWWW SWIZZLE(COMPONENT_W, COMPONENT_W, COMPONENT_W, COMPONENT_W)
91
92 static inline unsigned
93 swizzle_of(unsigned comp)
94 {
95 switch (comp) {
96 case 1:
97 return SWIZZLE_XXXX;
98 case 2:
99 return SWIZZLE_XYXX;
100 case 3:
101 return SWIZZLE_XYZX;
102 case 4:
103 return SWIZZLE_XYZW;
104 default:
105 unreachable("Invalid component count");
106 }
107 }
108
109 static inline unsigned
110 mask_of(unsigned nr_comp)
111 {
112 return (1 << nr_comp) - 1;
113 }
114
115 #define M_LOAD_STORE(name, rname, uname) \
116 static midgard_instruction m_##name(unsigned ssa, unsigned address) { \
117 midgard_instruction i = { \
118 .type = TAG_LOAD_STORE_4, \
119 .ssa_args = { \
120 .rname = ssa, \
121 .uname = -1, \
122 .src1 = -1 \
123 }, \
124 .load_store = { \
125 .op = midgard_op_##name, \
126 .mask = 0xF, \
127 .swizzle = SWIZZLE_XYZW, \
128 .address = address \
129 } \
130 }; \
131 \
132 return i; \
133 }
134
135 #define M_LOAD(name) M_LOAD_STORE(name, dest, src0)
136 #define M_STORE(name) M_LOAD_STORE(name, src0, dest)
137
138 /* Inputs a NIR ALU source, with modifiers attached if necessary, and outputs
139 * the corresponding Midgard source */
140
141 static midgard_vector_alu_src
142 vector_alu_modifiers(nir_alu_src *src, bool is_int, unsigned broadcast_count)
143 {
144 if (!src) return blank_alu_src;
145
146 /* Figure out how many components there are so we can adjust the
147 * swizzle. Specifically we want to broadcast the last channel so
148 * things like ball2/3 work
149 */
150
151 if (broadcast_count) {
152 uint8_t last_component = src->swizzle[broadcast_count - 1];
153
154 for (unsigned c = broadcast_count; c < NIR_MAX_VEC_COMPONENTS; ++c) {
155 src->swizzle[c] = last_component;
156 }
157 }
158
159 midgard_vector_alu_src alu_src = {
160 .rep_low = 0,
161 .rep_high = 0,
162 .half = 0, /* TODO */
163 .swizzle = SWIZZLE_FROM_ARRAY(src->swizzle)
164 };
165
166 if (is_int) {
167 /* TODO: sign-extend/zero-extend */
168 alu_src.mod = midgard_int_normal;
169
170 /* These should have been lowered away */
171 assert(!(src->abs || src->negate));
172 } else {
173 alu_src.mod = (src->abs << 0) | (src->negate << 1);
174 }
175
176 return alu_src;
177 }
178
179 /* load/store instructions have both 32-bit and 16-bit variants, depending on
180 * whether we are using vectors composed of highp or mediump. At the moment, we
181 * don't support half-floats -- this requires changes in other parts of the
182 * compiler -- therefore the 16-bit versions are commented out. */
183
184 //M_LOAD(ld_attr_16);
185 M_LOAD(ld_attr_32);
186 //M_LOAD(ld_vary_16);
187 M_LOAD(ld_vary_32);
188 //M_LOAD(ld_uniform_16);
189 M_LOAD(ld_uniform_32);
190 M_LOAD(ld_color_buffer_8);
191 //M_STORE(st_vary_16);
192 M_STORE(st_vary_32);
193 M_STORE(st_cubemap_coords);
194
195 static midgard_instruction
196 v_alu_br_compact_cond(midgard_jmp_writeout_op op, unsigned tag, signed offset, unsigned cond)
197 {
198 midgard_branch_cond branch = {
199 .op = op,
200 .dest_tag = tag,
201 .offset = offset,
202 .cond = cond
203 };
204
205 uint16_t compact;
206 memcpy(&compact, &branch, sizeof(branch));
207
208 midgard_instruction ins = {
209 .type = TAG_ALU_4,
210 .unit = ALU_ENAB_BR_COMPACT,
211 .prepacked_branch = true,
212 .compact_branch = true,
213 .br_compact = compact
214 };
215
216 if (op == midgard_jmp_writeout_op_writeout)
217 ins.writeout = true;
218
219 return ins;
220 }
221
222 static midgard_instruction
223 v_branch(bool conditional, bool invert)
224 {
225 midgard_instruction ins = {
226 .type = TAG_ALU_4,
227 .unit = ALU_ENAB_BRANCH,
228 .compact_branch = true,
229 .branch = {
230 .conditional = conditional,
231 .invert_conditional = invert
232 }
233 };
234
235 return ins;
236 }
237
238 static midgard_branch_extended
239 midgard_create_branch_extended( midgard_condition cond,
240 midgard_jmp_writeout_op op,
241 unsigned dest_tag,
242 signed quadword_offset)
243 {
244 /* For unclear reasons, the condition code is repeated 8 times */
245 uint16_t duplicated_cond =
246 (cond << 14) |
247 (cond << 12) |
248 (cond << 10) |
249 (cond << 8) |
250 (cond << 6) |
251 (cond << 4) |
252 (cond << 2) |
253 (cond << 0);
254
255 midgard_branch_extended branch = {
256 .op = op,
257 .dest_tag = dest_tag,
258 .offset = quadword_offset,
259 .cond = duplicated_cond
260 };
261
262 return branch;
263 }
264
265 static void
266 attach_constants(compiler_context *ctx, midgard_instruction *ins, void *constants, int name)
267 {
268 ins->has_constants = true;
269 memcpy(&ins->constants, constants, 16);
270 }
271
272 static int
273 glsl_type_size(const struct glsl_type *type, bool bindless)
274 {
275 return glsl_count_attribute_slots(type, false);
276 }
277
278 /* Lower fdot2 to a vector multiplication followed by channel addition */
279 static void
280 midgard_nir_lower_fdot2_body(nir_builder *b, nir_alu_instr *alu)
281 {
282 if (alu->op != nir_op_fdot2)
283 return;
284
285 b->cursor = nir_before_instr(&alu->instr);
286
287 nir_ssa_def *src0 = nir_ssa_for_alu_src(b, alu, 0);
288 nir_ssa_def *src1 = nir_ssa_for_alu_src(b, alu, 1);
289
290 nir_ssa_def *product = nir_fmul(b, src0, src1);
291
292 nir_ssa_def *sum = nir_fadd(b,
293 nir_channel(b, product, 0),
294 nir_channel(b, product, 1));
295
296 /* Replace the fdot2 with this sum */
297 nir_ssa_def_rewrite_uses(&alu->dest.dest.ssa, nir_src_for_ssa(sum));
298 }
299
300 static int
301 midgard_nir_sysval_for_intrinsic(nir_intrinsic_instr *instr)
302 {
303 switch (instr->intrinsic) {
304 case nir_intrinsic_load_viewport_scale:
305 return PAN_SYSVAL_VIEWPORT_SCALE;
306 case nir_intrinsic_load_viewport_offset:
307 return PAN_SYSVAL_VIEWPORT_OFFSET;
308 default:
309 return -1;
310 }
311 }
312
313 static unsigned
314 nir_dest_index(compiler_context *ctx, nir_dest *dst)
315 {
316 if (dst->is_ssa)
317 return dst->ssa.index;
318 else {
319 assert(!dst->reg.indirect);
320 return ctx->func->impl->ssa_alloc + dst->reg.reg->index;
321 }
322 }
323
324 static int sysval_for_instr(compiler_context *ctx, nir_instr *instr,
325 unsigned *dest)
326 {
327 nir_intrinsic_instr *intr;
328 nir_dest *dst = NULL;
329 nir_tex_instr *tex;
330 int sysval = -1;
331
332 switch (instr->type) {
333 case nir_instr_type_intrinsic:
334 intr = nir_instr_as_intrinsic(instr);
335 sysval = midgard_nir_sysval_for_intrinsic(intr);
336 dst = &intr->dest;
337 break;
338 case nir_instr_type_tex:
339 tex = nir_instr_as_tex(instr);
340 if (tex->op != nir_texop_txs)
341 break;
342
343 sysval = PAN_SYSVAL(TEXTURE_SIZE,
344 PAN_TXS_SYSVAL_ID(tex->texture_index,
345 nir_tex_instr_dest_size(tex) -
346 (tex->is_array ? 1 : 0),
347 tex->is_array));
348 dst = &tex->dest;
349 break;
350 default:
351 break;
352 }
353
354 if (dest && dst)
355 *dest = nir_dest_index(ctx, dst);
356
357 return sysval;
358 }
359
360 static void
361 midgard_nir_assign_sysval_body(compiler_context *ctx, nir_instr *instr)
362 {
363 int sysval;
364
365 sysval = sysval_for_instr(ctx, instr, NULL);
366 if (sysval < 0)
367 return;
368
369 /* We have a sysval load; check if it's already been assigned */
370
371 if (_mesa_hash_table_u64_search(ctx->sysval_to_id, sysval))
372 return;
373
374 /* It hasn't -- so assign it now! */
375
376 unsigned id = ctx->sysval_count++;
377 _mesa_hash_table_u64_insert(ctx->sysval_to_id, sysval, (void *) ((uintptr_t) id + 1));
378 ctx->sysvals[id] = sysval;
379 }
380
381 static void
382 midgard_nir_assign_sysvals(compiler_context *ctx, nir_shader *shader)
383 {
384 ctx->sysval_count = 0;
385
386 nir_foreach_function(function, shader) {
387 if (!function->impl) continue;
388
389 nir_foreach_block(block, function->impl) {
390 nir_foreach_instr_safe(instr, block) {
391 midgard_nir_assign_sysval_body(ctx, instr);
392 }
393 }
394 }
395 }
396
397 static bool
398 midgard_nir_lower_fdot2(nir_shader *shader)
399 {
400 bool progress = false;
401
402 nir_foreach_function(function, shader) {
403 if (!function->impl) continue;
404
405 nir_builder _b;
406 nir_builder *b = &_b;
407 nir_builder_init(b, function->impl);
408
409 nir_foreach_block(block, function->impl) {
410 nir_foreach_instr_safe(instr, block) {
411 if (instr->type != nir_instr_type_alu) continue;
412
413 nir_alu_instr *alu = nir_instr_as_alu(instr);
414 midgard_nir_lower_fdot2_body(b, alu);
415
416 progress |= true;
417 }
418 }
419
420 nir_metadata_preserve(function->impl, nir_metadata_block_index | nir_metadata_dominance);
421
422 }
423
424 return progress;
425 }
426
427 static void
428 optimise_nir(nir_shader *nir)
429 {
430 bool progress;
431 unsigned lower_flrp =
432 (nir->options->lower_flrp16 ? 16 : 0) |
433 (nir->options->lower_flrp32 ? 32 : 0) |
434 (nir->options->lower_flrp64 ? 64 : 0);
435
436 NIR_PASS(progress, nir, nir_lower_regs_to_ssa);
437 NIR_PASS(progress, nir, midgard_nir_lower_fdot2);
438 NIR_PASS(progress, nir, nir_lower_idiv);
439
440 nir_lower_tex_options lower_tex_1st_pass_options = {
441 .lower_rect = true,
442 .lower_txp = ~0
443 };
444
445 nir_lower_tex_options lower_tex_2nd_pass_options = {
446 .lower_txs_lod = true,
447 };
448
449 NIR_PASS(progress, nir, nir_lower_tex, &lower_tex_1st_pass_options);
450 NIR_PASS(progress, nir, nir_lower_tex, &lower_tex_2nd_pass_options);
451
452 do {
453 progress = false;
454
455 NIR_PASS(progress, nir, nir_lower_var_copies);
456 NIR_PASS(progress, nir, nir_lower_vars_to_ssa);
457
458 NIR_PASS(progress, nir, nir_copy_prop);
459 NIR_PASS(progress, nir, nir_opt_dce);
460 NIR_PASS(progress, nir, nir_opt_dead_cf);
461 NIR_PASS(progress, nir, nir_opt_cse);
462 NIR_PASS(progress, nir, nir_opt_peephole_select, 64, false, true);
463 NIR_PASS(progress, nir, nir_opt_algebraic);
464 NIR_PASS(progress, nir, nir_opt_constant_folding);
465
466 if (lower_flrp != 0) {
467 bool lower_flrp_progress = false;
468 NIR_PASS(lower_flrp_progress,
469 nir,
470 nir_lower_flrp,
471 lower_flrp,
472 false /* always_precise */,
473 nir->options->lower_ffma);
474 if (lower_flrp_progress) {
475 NIR_PASS(progress, nir,
476 nir_opt_constant_folding);
477 progress = true;
478 }
479
480 /* Nothing should rematerialize any flrps, so we only
481 * need to do this lowering once.
482 */
483 lower_flrp = 0;
484 }
485
486 NIR_PASS(progress, nir, nir_opt_undef);
487 NIR_PASS(progress, nir, nir_opt_loop_unroll,
488 nir_var_shader_in |
489 nir_var_shader_out |
490 nir_var_function_temp);
491
492 NIR_PASS(progress, nir, nir_opt_vectorize);
493 } while (progress);
494
495 /* Must be run at the end to prevent creation of fsin/fcos ops */
496 NIR_PASS(progress, nir, midgard_nir_scale_trig);
497
498 do {
499 progress = false;
500
501 NIR_PASS(progress, nir, nir_opt_dce);
502 NIR_PASS(progress, nir, nir_opt_algebraic);
503 NIR_PASS(progress, nir, nir_opt_constant_folding);
504 NIR_PASS(progress, nir, nir_copy_prop);
505 } while (progress);
506
507 NIR_PASS(progress, nir, nir_opt_algebraic_late);
508
509 /* We implement booleans as 32-bit 0/~0 */
510 NIR_PASS(progress, nir, nir_lower_bool_to_int32);
511
512 /* Now that booleans are lowered, we can run out late opts */
513 NIR_PASS(progress, nir, midgard_nir_lower_algebraic_late);
514
515 /* Lower mods for float ops only. Integer ops don't support modifiers
516 * (saturate doesn't make sense on integers, neg/abs require dedicated
517 * instructions) */
518
519 NIR_PASS(progress, nir, nir_lower_to_source_mods, nir_lower_float_source_mods);
520 NIR_PASS(progress, nir, nir_copy_prop);
521 NIR_PASS(progress, nir, nir_opt_dce);
522
523 /* Take us out of SSA */
524 NIR_PASS(progress, nir, nir_lower_locals_to_regs);
525 NIR_PASS(progress, nir, nir_convert_from_ssa, true);
526
527 /* We are a vector architecture; write combine where possible */
528 NIR_PASS(progress, nir, nir_move_vec_src_uses_to_dest);
529 NIR_PASS(progress, nir, nir_lower_vec_to_movs);
530
531 NIR_PASS(progress, nir, nir_opt_dce);
532 }
533
534 /* Front-half of aliasing the SSA slots, merely by inserting the flag in the
535 * appropriate hash table. Intentional off-by-one to avoid confusing NULL with
536 * r0. See the comments in compiler_context */
537
538 static void
539 alias_ssa(compiler_context *ctx, int dest, int src)
540 {
541 _mesa_hash_table_u64_insert(ctx->ssa_to_alias, dest + 1, (void *) ((uintptr_t) src + 1));
542 _mesa_set_add(ctx->leftover_ssa_to_alias, (void *) (uintptr_t) (dest + 1));
543 }
544
545 /* ...or undo it, after which the original index will be used (dummy move should be emitted alongside this) */
546
547 static void
548 unalias_ssa(compiler_context *ctx, int dest)
549 {
550 _mesa_hash_table_u64_remove(ctx->ssa_to_alias, dest + 1);
551 /* TODO: Remove from leftover or no? */
552 }
553
554 /* Do not actually emit a load; instead, cache the constant for inlining */
555
556 static void
557 emit_load_const(compiler_context *ctx, nir_load_const_instr *instr)
558 {
559 nir_ssa_def def = instr->def;
560
561 float *v = rzalloc_array(NULL, float, 4);
562 nir_const_load_to_arr(v, instr, f32);
563 _mesa_hash_table_u64_insert(ctx->ssa_constants, def.index + 1, v);
564 }
565
566 static unsigned
567 nir_src_index(compiler_context *ctx, nir_src *src)
568 {
569 if (src->is_ssa)
570 return src->ssa->index;
571 else {
572 assert(!src->reg.indirect);
573 return ctx->func->impl->ssa_alloc + src->reg.reg->index;
574 }
575 }
576
577 static unsigned
578 nir_alu_src_index(compiler_context *ctx, nir_alu_src *src)
579 {
580 return nir_src_index(ctx, &src->src);
581 }
582
583 static bool
584 nir_is_non_scalar_swizzle(nir_alu_src *src, unsigned nr_components)
585 {
586 unsigned comp = src->swizzle[0];
587
588 for (unsigned c = 1; c < nr_components; ++c) {
589 if (src->swizzle[c] != comp)
590 return true;
591 }
592
593 return false;
594 }
595
596 /* Midgard puts scalar conditionals in r31.w; move an arbitrary source (the
597 * output of a conditional test) into that register */
598
599 static void
600 emit_condition(compiler_context *ctx, nir_src *src, bool for_branch, unsigned component)
601 {
602 int condition = nir_src_index(ctx, src);
603
604 /* Source to swizzle the desired component into w */
605
606 const midgard_vector_alu_src alu_src = {
607 .swizzle = SWIZZLE(component, component, component, component),
608 };
609
610 /* There is no boolean move instruction. Instead, we simulate a move by
611 * ANDing the condition with itself to get it into r31.w */
612
613 midgard_instruction ins = {
614 .type = TAG_ALU_4,
615
616 /* We need to set the conditional as close as possible */
617 .precede_break = true,
618 .unit = for_branch ? UNIT_SMUL : UNIT_SADD,
619
620 .ssa_args = {
621 .src0 = condition,
622 .src1 = condition,
623 .dest = SSA_FIXED_REGISTER(31),
624 },
625
626 .alu = {
627 .op = midgard_alu_op_iand,
628 .outmod = midgard_outmod_int_wrap,
629 .reg_mode = midgard_reg_mode_32,
630 .dest_override = midgard_dest_override_none,
631 .mask = (0x3 << 6), /* w */
632 .src1 = vector_alu_srco_unsigned(alu_src),
633 .src2 = vector_alu_srco_unsigned(alu_src)
634 },
635 };
636
637 emit_mir_instruction(ctx, ins);
638 }
639
640 /* Or, for mixed conditions (with csel_v), here's a vector version using all of
641 * r31 instead */
642
643 static void
644 emit_condition_mixed(compiler_context *ctx, nir_alu_src *src, unsigned nr_comp)
645 {
646 int condition = nir_src_index(ctx, &src->src);
647
648 /* Source to swizzle the desired component into w */
649
650 const midgard_vector_alu_src alu_src = {
651 .swizzle = SWIZZLE_FROM_ARRAY(src->swizzle),
652 };
653
654 /* There is no boolean move instruction. Instead, we simulate a move by
655 * ANDing the condition with itself to get it into r31.w */
656
657 midgard_instruction ins = {
658 .type = TAG_ALU_4,
659 .precede_break = true,
660 .ssa_args = {
661 .src0 = condition,
662 .src1 = condition,
663 .dest = SSA_FIXED_REGISTER(31),
664 },
665 .alu = {
666 .op = midgard_alu_op_iand,
667 .outmod = midgard_outmod_int_wrap,
668 .reg_mode = midgard_reg_mode_32,
669 .dest_override = midgard_dest_override_none,
670 .mask = expand_writemask(mask_of(nr_comp)),
671 .src1 = vector_alu_srco_unsigned(alu_src),
672 .src2 = vector_alu_srco_unsigned(alu_src)
673 },
674 };
675
676 emit_mir_instruction(ctx, ins);
677 }
678
679
680
681 /* Likewise, indirect offsets are put in r27.w. TODO: Allow componentwise
682 * pinning to eliminate this move in all known cases */
683
684 static void
685 emit_indirect_offset(compiler_context *ctx, nir_src *src)
686 {
687 int offset = nir_src_index(ctx, src);
688
689 midgard_instruction ins = {
690 .type = TAG_ALU_4,
691 .ssa_args = {
692 .src0 = SSA_UNUSED_1,
693 .src1 = offset,
694 .dest = SSA_FIXED_REGISTER(REGISTER_OFFSET),
695 },
696 .alu = {
697 .op = midgard_alu_op_imov,
698 .outmod = midgard_outmod_int_wrap,
699 .reg_mode = midgard_reg_mode_32,
700 .dest_override = midgard_dest_override_none,
701 .mask = (0x3 << 6), /* w */
702 .src1 = vector_alu_srco_unsigned(zero_alu_src),
703 .src2 = vector_alu_srco_unsigned(blank_alu_src_xxxx)
704 },
705 };
706
707 emit_mir_instruction(ctx, ins);
708 }
709
710 #define ALU_CASE(nir, _op) \
711 case nir_op_##nir: \
712 op = midgard_alu_op_##_op; \
713 break;
714
715 #define ALU_CASE_BCAST(nir, _op, count) \
716 case nir_op_##nir: \
717 op = midgard_alu_op_##_op; \
718 broadcast_swizzle = count; \
719 break;
720 static bool
721 nir_is_fzero_constant(nir_src src)
722 {
723 if (!nir_src_is_const(src))
724 return false;
725
726 for (unsigned c = 0; c < nir_src_num_components(src); ++c) {
727 if (nir_src_comp_as_float(src, c) != 0.0)
728 return false;
729 }
730
731 return true;
732 }
733
734 static void
735 emit_alu(compiler_context *ctx, nir_alu_instr *instr)
736 {
737 bool is_ssa = instr->dest.dest.is_ssa;
738
739 unsigned dest = nir_dest_index(ctx, &instr->dest.dest);
740 unsigned nr_components = is_ssa ? instr->dest.dest.ssa.num_components : instr->dest.dest.reg.reg->num_components;
741 unsigned nr_inputs = nir_op_infos[instr->op].num_inputs;
742
743 /* Most Midgard ALU ops have a 1:1 correspondance to NIR ops; these are
744 * supported. A few do not and are commented for now. Also, there are a
745 * number of NIR ops which Midgard does not support and need to be
746 * lowered, also TODO. This switch block emits the opcode and calling
747 * convention of the Midgard instruction; actual packing is done in
748 * emit_alu below */
749
750 unsigned op;
751
752 /* Number of components valid to check for the instruction (the rest
753 * will be forced to the last), or 0 to use as-is. Relevant as
754 * ball-type instructions have a channel count in NIR but are all vec4
755 * in Midgard */
756
757 unsigned broadcast_swizzle = 0;
758
759 switch (instr->op) {
760 ALU_CASE(fadd, fadd);
761 ALU_CASE(fmul, fmul);
762 ALU_CASE(fmin, fmin);
763 ALU_CASE(fmax, fmax);
764 ALU_CASE(imin, imin);
765 ALU_CASE(imax, imax);
766 ALU_CASE(umin, umin);
767 ALU_CASE(umax, umax);
768 ALU_CASE(ffloor, ffloor);
769 ALU_CASE(fround_even, froundeven);
770 ALU_CASE(ftrunc, ftrunc);
771 ALU_CASE(fceil, fceil);
772 ALU_CASE(fdot3, fdot3);
773 ALU_CASE(fdot4, fdot4);
774 ALU_CASE(iadd, iadd);
775 ALU_CASE(isub, isub);
776 ALU_CASE(imul, imul);
777
778 /* Zero shoved as second-arg */
779 ALU_CASE(iabs, iabsdiff);
780
781 ALU_CASE(mov, imov);
782
783 ALU_CASE(feq32, feq);
784 ALU_CASE(fne32, fne);
785 ALU_CASE(flt32, flt);
786 ALU_CASE(ieq32, ieq);
787 ALU_CASE(ine32, ine);
788 ALU_CASE(ilt32, ilt);
789 ALU_CASE(ult32, ult);
790
791 /* We don't have a native b2f32 instruction. Instead, like many
792 * GPUs, we exploit booleans as 0/~0 for false/true, and
793 * correspondingly AND
794 * by 1.0 to do the type conversion. For the moment, prime us
795 * to emit:
796 *
797 * iand [whatever], #0
798 *
799 * At the end of emit_alu (as MIR), we'll fix-up the constant
800 */
801
802 ALU_CASE(b2f32, iand);
803 ALU_CASE(b2i32, iand);
804
805 /* Likewise, we don't have a dedicated f2b32 instruction, but
806 * we can do a "not equal to 0.0" test. */
807
808 ALU_CASE(f2b32, fne);
809 ALU_CASE(i2b32, ine);
810
811 ALU_CASE(frcp, frcp);
812 ALU_CASE(frsq, frsqrt);
813 ALU_CASE(fsqrt, fsqrt);
814 ALU_CASE(fexp2, fexp2);
815 ALU_CASE(flog2, flog2);
816
817 ALU_CASE(f2i32, f2i_rtz);
818 ALU_CASE(f2u32, f2u_rtz);
819 ALU_CASE(i2f32, i2f_rtz);
820 ALU_CASE(u2f32, u2f_rtz);
821
822 ALU_CASE(fsin, fsin);
823 ALU_CASE(fcos, fcos);
824
825 /* Second op implicit #0 */
826 ALU_CASE(inot, inor);
827 ALU_CASE(iand, iand);
828 ALU_CASE(ior, ior);
829 ALU_CASE(ixor, ixor);
830 ALU_CASE(ishl, ishl);
831 ALU_CASE(ishr, iasr);
832 ALU_CASE(ushr, ilsr);
833
834 ALU_CASE_BCAST(b32all_fequal2, fball_eq, 2);
835 ALU_CASE_BCAST(b32all_fequal3, fball_eq, 3);
836 ALU_CASE(b32all_fequal4, fball_eq);
837
838 ALU_CASE_BCAST(b32any_fnequal2, fbany_neq, 2);
839 ALU_CASE_BCAST(b32any_fnequal3, fbany_neq, 3);
840 ALU_CASE(b32any_fnequal4, fbany_neq);
841
842 ALU_CASE_BCAST(b32all_iequal2, iball_eq, 2);
843 ALU_CASE_BCAST(b32all_iequal3, iball_eq, 3);
844 ALU_CASE(b32all_iequal4, iball_eq);
845
846 ALU_CASE_BCAST(b32any_inequal2, ibany_neq, 2);
847 ALU_CASE_BCAST(b32any_inequal3, ibany_neq, 3);
848 ALU_CASE(b32any_inequal4, ibany_neq);
849
850 /* Source mods will be shoved in later */
851 ALU_CASE(fabs, fmov);
852 ALU_CASE(fneg, fmov);
853 ALU_CASE(fsat, fmov);
854
855 /* For greater-or-equal, we lower to less-or-equal and flip the
856 * arguments */
857
858 case nir_op_fge:
859 case nir_op_fge32:
860 case nir_op_ige32:
861 case nir_op_uge32: {
862 op =
863 instr->op == nir_op_fge ? midgard_alu_op_fle :
864 instr->op == nir_op_fge32 ? midgard_alu_op_fle :
865 instr->op == nir_op_ige32 ? midgard_alu_op_ile :
866 instr->op == nir_op_uge32 ? midgard_alu_op_ule :
867 0;
868
869 /* Swap via temporary */
870 nir_alu_src temp = instr->src[1];
871 instr->src[1] = instr->src[0];
872 instr->src[0] = temp;
873
874 break;
875 }
876
877 case nir_op_b32csel: {
878 /* Midgard features both fcsel and icsel, depending on
879 * the type of the arguments/output. However, as long
880 * as we're careful we can _always_ use icsel and
881 * _never_ need fcsel, since the latter does additional
882 * floating-point-specific processing whereas the
883 * former just moves bits on the wire. It's not obvious
884 * why these are separate opcodes, save for the ability
885 * to do things like sat/pos/abs/neg for free */
886
887 bool mixed = nir_is_non_scalar_swizzle(&instr->src[0], nr_components);
888 op = mixed ? midgard_alu_op_icsel_v : midgard_alu_op_icsel;
889
890 /* csel works as a two-arg in Midgard, since the condition is hardcoded in r31.w */
891 nr_inputs = 2;
892
893 /* Emit the condition into r31 */
894
895 if (mixed)
896 emit_condition_mixed(ctx, &instr->src[0], nr_components);
897 else
898 emit_condition(ctx, &instr->src[0].src, false, instr->src[0].swizzle[0]);
899
900 /* The condition is the first argument; move the other
901 * arguments up one to be a binary instruction for
902 * Midgard */
903
904 memmove(instr->src, instr->src + 1, 2 * sizeof(nir_alu_src));
905 break;
906 }
907
908 default:
909 DBG("Unhandled ALU op %s\n", nir_op_infos[instr->op].name);
910 assert(0);
911 return;
912 }
913
914 /* Midgard can perform certain modifiers on output of an ALU op */
915 unsigned outmod;
916
917 if (midgard_is_integer_out_op(op)) {
918 outmod = midgard_outmod_int_wrap;
919 } else {
920 bool sat = instr->dest.saturate || instr->op == nir_op_fsat;
921 outmod = sat ? midgard_outmod_sat : midgard_outmod_none;
922 }
923
924 /* fmax(a, 0.0) can turn into a .pos modifier as an optimization */
925
926 if (instr->op == nir_op_fmax) {
927 if (nir_is_fzero_constant(instr->src[0].src)) {
928 op = midgard_alu_op_fmov;
929 nr_inputs = 1;
930 outmod = midgard_outmod_pos;
931 instr->src[0] = instr->src[1];
932 } else if (nir_is_fzero_constant(instr->src[1].src)) {
933 op = midgard_alu_op_fmov;
934 nr_inputs = 1;
935 outmod = midgard_outmod_pos;
936 }
937 }
938
939 /* Fetch unit, quirks, etc information */
940 unsigned opcode_props = alu_opcode_props[op].props;
941 bool quirk_flipped_r24 = opcode_props & QUIRK_FLIPPED_R24;
942
943 /* src0 will always exist afaik, but src1 will not for 1-argument
944 * instructions. The latter can only be fetched if the instruction
945 * needs it, or else we may segfault. */
946
947 unsigned src0 = nir_alu_src_index(ctx, &instr->src[0]);
948 unsigned src1 = nr_inputs == 2 ? nir_alu_src_index(ctx, &instr->src[1]) : SSA_UNUSED_0;
949
950 /* Rather than use the instruction generation helpers, we do it
951 * ourselves here to avoid the mess */
952
953 midgard_instruction ins = {
954 .type = TAG_ALU_4,
955 .ssa_args = {
956 .src0 = quirk_flipped_r24 ? SSA_UNUSED_1 : src0,
957 .src1 = quirk_flipped_r24 ? src0 : src1,
958 .dest = dest,
959 }
960 };
961
962 nir_alu_src *nirmods[2] = { NULL };
963
964 if (nr_inputs == 2) {
965 nirmods[0] = &instr->src[0];
966 nirmods[1] = &instr->src[1];
967 } else if (nr_inputs == 1) {
968 nirmods[quirk_flipped_r24] = &instr->src[0];
969 } else {
970 assert(0);
971 }
972
973 /* These were lowered to a move, so apply the corresponding mod */
974
975 if (instr->op == nir_op_fneg || instr->op == nir_op_fabs) {
976 nir_alu_src *s = nirmods[quirk_flipped_r24];
977
978 if (instr->op == nir_op_fneg)
979 s->negate = !s->negate;
980
981 if (instr->op == nir_op_fabs)
982 s->abs = !s->abs;
983 }
984
985 bool is_int = midgard_is_integer_op(op);
986
987 midgard_vector_alu alu = {
988 .op = op,
989 .reg_mode = midgard_reg_mode_32,
990 .dest_override = midgard_dest_override_none,
991 .outmod = outmod,
992
993 /* Writemask only valid for non-SSA NIR */
994 .mask = expand_writemask(mask_of(nr_components)),
995
996 .src1 = vector_alu_srco_unsigned(vector_alu_modifiers(nirmods[0], is_int, broadcast_swizzle)),
997 .src2 = vector_alu_srco_unsigned(vector_alu_modifiers(nirmods[1], is_int, broadcast_swizzle)),
998 };
999
1000 /* Apply writemask if non-SSA, keeping in mind that we can't write to components that don't exist */
1001
1002 if (!is_ssa)
1003 alu.mask &= expand_writemask(instr->dest.write_mask);
1004
1005 ins.alu = alu;
1006
1007 /* Late fixup for emulated instructions */
1008
1009 if (instr->op == nir_op_b2f32 || instr->op == nir_op_b2i32) {
1010 /* Presently, our second argument is an inline #0 constant.
1011 * Switch over to an embedded 1.0 constant (that can't fit
1012 * inline, since we're 32-bit, not 16-bit like the inline
1013 * constants) */
1014
1015 ins.ssa_args.inline_constant = false;
1016 ins.ssa_args.src1 = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1017 ins.has_constants = true;
1018
1019 if (instr->op == nir_op_b2f32) {
1020 ins.constants[0] = 1.0f;
1021 } else {
1022 /* Type pun it into place */
1023 uint32_t one = 0x1;
1024 memcpy(&ins.constants[0], &one, sizeof(uint32_t));
1025 }
1026
1027 ins.alu.src2 = vector_alu_srco_unsigned(blank_alu_src_xxxx);
1028 } else if (nr_inputs == 1 && !quirk_flipped_r24) {
1029 /* Lots of instructions need a 0 plonked in */
1030 ins.ssa_args.inline_constant = false;
1031 ins.ssa_args.src1 = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1032 ins.has_constants = true;
1033 ins.constants[0] = 0.0f;
1034 ins.alu.src2 = vector_alu_srco_unsigned(blank_alu_src_xxxx);
1035 } else if (instr->op == nir_op_inot) {
1036 /* ~b = ~(b & b), so duplicate the source */
1037 ins.ssa_args.src1 = ins.ssa_args.src0;
1038 ins.alu.src2 = ins.alu.src1;
1039 }
1040
1041 if ((opcode_props & UNITS_ALL) == UNIT_VLUT) {
1042 /* To avoid duplicating the lookup tables (probably), true LUT
1043 * instructions can only operate as if they were scalars. Lower
1044 * them here by changing the component. */
1045
1046 uint8_t original_swizzle[4];
1047 memcpy(original_swizzle, nirmods[0]->swizzle, sizeof(nirmods[0]->swizzle));
1048
1049 for (int i = 0; i < nr_components; ++i) {
1050 /* Mask the associated component, dropping the
1051 * instruction if needed */
1052
1053 ins.alu.mask = (0x3) << (2 * i);
1054 ins.alu.mask &= alu.mask;
1055
1056 if (!ins.alu.mask)
1057 continue;
1058
1059 for (int j = 0; j < 4; ++j)
1060 nirmods[0]->swizzle[j] = original_swizzle[i]; /* Pull from the correct component */
1061
1062 ins.alu.src1 = vector_alu_srco_unsigned(vector_alu_modifiers(nirmods[0], is_int, broadcast_swizzle));
1063 emit_mir_instruction(ctx, ins);
1064 }
1065 } else {
1066 emit_mir_instruction(ctx, ins);
1067 }
1068 }
1069
1070 #undef ALU_CASE
1071
1072 static void
1073 emit_uniform_read(compiler_context *ctx, unsigned dest, unsigned offset, nir_src *indirect_offset)
1074 {
1075 /* TODO: half-floats */
1076
1077 if (!indirect_offset && offset < ctx->uniform_cutoff) {
1078 /* Fast path: For the first 16 uniforms, direct accesses are
1079 * 0-cycle, since they're just a register fetch in the usual
1080 * case. So, we alias the registers while we're still in
1081 * SSA-space */
1082
1083 int reg_slot = 23 - offset;
1084 alias_ssa(ctx, dest, SSA_FIXED_REGISTER(reg_slot));
1085 } else {
1086 /* Otherwise, read from the 'special' UBO to access
1087 * higher-indexed uniforms, at a performance cost. More
1088 * generally, we're emitting a UBO read instruction. */
1089
1090 midgard_instruction ins = m_ld_uniform_32(dest, offset);
1091
1092 /* TODO: Don't split */
1093 ins.load_store.varying_parameters = (offset & 7) << 7;
1094 ins.load_store.address = offset >> 3;
1095
1096 if (indirect_offset) {
1097 emit_indirect_offset(ctx, indirect_offset);
1098 ins.load_store.unknown = 0x8700; /* xxx: what is this? */
1099 } else {
1100 ins.load_store.unknown = 0x1E00; /* xxx: what is this? */
1101 }
1102
1103 emit_mir_instruction(ctx, ins);
1104 }
1105 }
1106
1107 static void
1108 emit_varying_read(
1109 compiler_context *ctx,
1110 unsigned dest, unsigned offset,
1111 unsigned nr_comp, unsigned component,
1112 nir_src *indirect_offset)
1113 {
1114 /* XXX: Half-floats? */
1115 /* TODO: swizzle, mask */
1116
1117 midgard_instruction ins = m_ld_vary_32(dest, offset);
1118 ins.load_store.mask = mask_of(nr_comp);
1119 ins.load_store.swizzle = SWIZZLE_XYZW >> (2 * component);
1120
1121 midgard_varying_parameter p = {
1122 .is_varying = 1,
1123 .interpolation = midgard_interp_default,
1124 .flat = /*var->data.interpolation == INTERP_MODE_FLAT*/ 0
1125 };
1126
1127 unsigned u;
1128 memcpy(&u, &p, sizeof(p));
1129 ins.load_store.varying_parameters = u;
1130
1131 if (indirect_offset) {
1132 /* We need to add in the dynamic index, moved to r27.w */
1133 emit_indirect_offset(ctx, indirect_offset);
1134 ins.load_store.unknown = 0x79e; /* xxx: what is this? */
1135 } else {
1136 /* Just a direct load */
1137 ins.load_store.unknown = 0x1e9e; /* xxx: what is this? */
1138 }
1139
1140 emit_mir_instruction(ctx, ins);
1141 }
1142
1143 static void
1144 emit_sysval_read(compiler_context *ctx, nir_instr *instr)
1145 {
1146 unsigned dest;
1147 /* Figure out which uniform this is */
1148 int sysval = sysval_for_instr(ctx, instr, &dest);
1149 void *val = _mesa_hash_table_u64_search(ctx->sysval_to_id, sysval);
1150
1151 /* Sysvals are prefix uniforms */
1152 unsigned uniform = ((uintptr_t) val) - 1;
1153
1154 /* Emit the read itself -- this is never indirect */
1155 emit_uniform_read(ctx, dest, uniform, NULL);
1156 }
1157
1158 /* Reads RGBA8888 value from the tilebuffer and converts to a RGBA32F register,
1159 * using scalar ops functional on earlier Midgard generations. Newer Midgard
1160 * generations have faster vectorized reads. This operation is for blend
1161 * shaders in particular; reading the tilebuffer from the fragment shader
1162 * remains an open problem. */
1163
1164 static void
1165 emit_fb_read_blend_scalar(compiler_context *ctx, unsigned reg)
1166 {
1167 midgard_instruction ins = m_ld_color_buffer_8(reg, 0);
1168 ins.load_store.swizzle = 0; /* xxxx */
1169
1170 /* Read each component sequentially */
1171
1172 for (unsigned c = 0; c < 4; ++c) {
1173 ins.load_store.mask = (1 << c);
1174 ins.load_store.unknown = c;
1175 emit_mir_instruction(ctx, ins);
1176 }
1177
1178 /* vadd.u2f hr2, zext(hr2), #0 */
1179
1180 midgard_vector_alu_src alu_src = blank_alu_src;
1181 alu_src.mod = midgard_int_zero_extend;
1182 alu_src.half = true;
1183
1184 midgard_instruction u2f = {
1185 .type = TAG_ALU_4,
1186 .ssa_args = {
1187 .src0 = reg,
1188 .src1 = SSA_UNUSED_0,
1189 .dest = reg,
1190 .inline_constant = true
1191 },
1192 .alu = {
1193 .op = midgard_alu_op_u2f_rtz,
1194 .reg_mode = midgard_reg_mode_16,
1195 .dest_override = midgard_dest_override_none,
1196 .mask = 0xF,
1197 .src1 = vector_alu_srco_unsigned(alu_src),
1198 .src2 = vector_alu_srco_unsigned(blank_alu_src),
1199 }
1200 };
1201
1202 emit_mir_instruction(ctx, u2f);
1203
1204 /* vmul.fmul.sat r1, hr2, #0.00392151 */
1205
1206 alu_src.mod = 0;
1207
1208 midgard_instruction fmul = {
1209 .type = TAG_ALU_4,
1210 .inline_constant = _mesa_float_to_half(1.0 / 255.0),
1211 .ssa_args = {
1212 .src0 = reg,
1213 .dest = reg,
1214 .src1 = SSA_UNUSED_0,
1215 .inline_constant = true
1216 },
1217 .alu = {
1218 .op = midgard_alu_op_fmul,
1219 .reg_mode = midgard_reg_mode_32,
1220 .dest_override = midgard_dest_override_none,
1221 .outmod = midgard_outmod_sat,
1222 .mask = 0xFF,
1223 .src1 = vector_alu_srco_unsigned(alu_src),
1224 .src2 = vector_alu_srco_unsigned(blank_alu_src),
1225 }
1226 };
1227
1228 emit_mir_instruction(ctx, fmul);
1229 }
1230
1231 static void
1232 emit_intrinsic(compiler_context *ctx, nir_intrinsic_instr *instr)
1233 {
1234 unsigned offset, reg;
1235
1236 switch (instr->intrinsic) {
1237 case nir_intrinsic_discard_if:
1238 emit_condition(ctx, &instr->src[0], true, COMPONENT_X);
1239
1240 /* fallthrough */
1241
1242 case nir_intrinsic_discard: {
1243 bool conditional = instr->intrinsic == nir_intrinsic_discard_if;
1244 struct midgard_instruction discard = v_branch(conditional, false);
1245 discard.branch.target_type = TARGET_DISCARD;
1246 emit_mir_instruction(ctx, discard);
1247
1248 ctx->can_discard = true;
1249 break;
1250 }
1251
1252 case nir_intrinsic_load_uniform:
1253 case nir_intrinsic_load_input:
1254 offset = nir_intrinsic_base(instr);
1255
1256 unsigned nr_comp = nir_intrinsic_dest_components(instr);
1257 bool direct = nir_src_is_const(instr->src[0]);
1258
1259 if (direct) {
1260 offset += nir_src_as_uint(instr->src[0]);
1261 }
1262
1263 /* We may need to apply a fractional offset */
1264 int component = instr->intrinsic == nir_intrinsic_load_input ?
1265 nir_intrinsic_component(instr) : 0;
1266 reg = nir_dest_index(ctx, &instr->dest);
1267
1268 if (instr->intrinsic == nir_intrinsic_load_uniform && !ctx->is_blend) {
1269 emit_uniform_read(ctx, reg, ctx->sysval_count + offset, !direct ? &instr->src[0] : NULL);
1270 } else if (ctx->stage == MESA_SHADER_FRAGMENT && !ctx->is_blend) {
1271 emit_varying_read(ctx, reg, offset, nr_comp, component, !direct ? &instr->src[0] : NULL);
1272 } else if (ctx->is_blend) {
1273 /* For blend shaders, load the input color, which is
1274 * preloaded to r0 */
1275
1276 midgard_instruction move = v_mov(reg, blank_alu_src, SSA_FIXED_REGISTER(0));
1277 emit_mir_instruction(ctx, move);
1278 } else if (ctx->stage == MESA_SHADER_VERTEX) {
1279 midgard_instruction ins = m_ld_attr_32(reg, offset);
1280 ins.load_store.unknown = 0x1E1E; /* XXX: What is this? */
1281 ins.load_store.mask = mask_of(nr_comp);
1282 emit_mir_instruction(ctx, ins);
1283 } else {
1284 DBG("Unknown load\n");
1285 assert(0);
1286 }
1287
1288 break;
1289
1290 case nir_intrinsic_load_output:
1291 assert(nir_src_is_const(instr->src[0]));
1292 reg = nir_dest_index(ctx, &instr->dest);
1293
1294 if (ctx->is_blend) {
1295 /* TODO: MRT */
1296 emit_fb_read_blend_scalar(ctx, reg);
1297 } else {
1298 DBG("Unknown output load\n");
1299 assert(0);
1300 }
1301
1302 break;
1303
1304 case nir_intrinsic_load_blend_const_color_rgba: {
1305 assert(ctx->is_blend);
1306 reg = nir_dest_index(ctx, &instr->dest);
1307
1308 /* Blend constants are embedded directly in the shader and
1309 * patched in, so we use some magic routing */
1310
1311 midgard_instruction ins = v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), blank_alu_src, reg);
1312 ins.has_constants = true;
1313 ins.has_blend_constant = true;
1314 emit_mir_instruction(ctx, ins);
1315 break;
1316 }
1317
1318 case nir_intrinsic_store_output:
1319 assert(nir_src_is_const(instr->src[1]) && "no indirect outputs");
1320
1321 offset = nir_intrinsic_base(instr) + nir_src_as_uint(instr->src[1]);
1322
1323 reg = nir_src_index(ctx, &instr->src[0]);
1324
1325 if (ctx->stage == MESA_SHADER_FRAGMENT) {
1326 /* gl_FragColor is not emitted with load/store
1327 * instructions. Instead, it gets plonked into
1328 * r0 at the end of the shader and we do the
1329 * framebuffer writeout dance. TODO: Defer
1330 * writes */
1331
1332 midgard_instruction move = v_mov(reg, blank_alu_src, SSA_FIXED_REGISTER(0));
1333 emit_mir_instruction(ctx, move);
1334
1335 /* Save the index we're writing to for later reference
1336 * in the epilogue */
1337
1338 ctx->fragment_output = reg;
1339 } else if (ctx->stage == MESA_SHADER_VERTEX) {
1340 /* Varyings are written into one of two special
1341 * varying register, r26 or r27. The register itself is
1342 * selected as the register in the st_vary instruction,
1343 * minus the base of 26. E.g. write into r27 and then
1344 * call st_vary(1) */
1345
1346 midgard_instruction ins = v_mov(reg, blank_alu_src, SSA_FIXED_REGISTER(26));
1347 emit_mir_instruction(ctx, ins);
1348
1349 /* We should have been vectorized, though we don't
1350 * currently check that st_vary is emitted only once
1351 * per slot (this is relevant, since there's not a mask
1352 * parameter available on the store [set to 0 by the
1353 * blob]). We do respect the component by adjusting the
1354 * swizzle. */
1355
1356 unsigned component = nir_intrinsic_component(instr);
1357
1358 midgard_instruction st = m_st_vary_32(SSA_FIXED_REGISTER(0), offset);
1359 st.load_store.unknown = 0x1E9E; /* XXX: What is this? */
1360 st.load_store.swizzle = SWIZZLE_XYZW << (2*component);
1361 emit_mir_instruction(ctx, st);
1362 } else {
1363 DBG("Unknown store\n");
1364 assert(0);
1365 }
1366
1367 break;
1368
1369 case nir_intrinsic_load_alpha_ref_float:
1370 assert(instr->dest.is_ssa);
1371
1372 float ref_value = ctx->alpha_ref;
1373
1374 float *v = ralloc_array(NULL, float, 4);
1375 memcpy(v, &ref_value, sizeof(float));
1376 _mesa_hash_table_u64_insert(ctx->ssa_constants, instr->dest.ssa.index + 1, v);
1377 break;
1378
1379 case nir_intrinsic_load_viewport_scale:
1380 case nir_intrinsic_load_viewport_offset:
1381 emit_sysval_read(ctx, &instr->instr);
1382 break;
1383
1384 default:
1385 printf ("Unhandled intrinsic\n");
1386 assert(0);
1387 break;
1388 }
1389 }
1390
1391 static unsigned
1392 midgard_tex_format(enum glsl_sampler_dim dim)
1393 {
1394 switch (dim) {
1395 case GLSL_SAMPLER_DIM_1D:
1396 case GLSL_SAMPLER_DIM_BUF:
1397 return MALI_TEX_1D;
1398
1399 case GLSL_SAMPLER_DIM_2D:
1400 case GLSL_SAMPLER_DIM_EXTERNAL:
1401 return MALI_TEX_2D;
1402
1403 case GLSL_SAMPLER_DIM_3D:
1404 return MALI_TEX_3D;
1405
1406 case GLSL_SAMPLER_DIM_CUBE:
1407 return MALI_TEX_CUBE;
1408
1409 default:
1410 DBG("Unknown sampler dim type\n");
1411 assert(0);
1412 return 0;
1413 }
1414 }
1415
1416 static void
1417 emit_texop_native(compiler_context *ctx, nir_tex_instr *instr,
1418 unsigned midgard_texop)
1419 {
1420 /* TODO */
1421 //assert (!instr->sampler);
1422 //assert (!instr->texture_array_size);
1423
1424 /* Allocate registers via a round robin scheme to alternate between the two registers */
1425 int reg = ctx->texture_op_count & 1;
1426 int in_reg = reg, out_reg = reg;
1427
1428 /* Make room for the reg */
1429
1430 if (ctx->texture_index[reg] > -1)
1431 unalias_ssa(ctx, ctx->texture_index[reg]);
1432
1433 int texture_index = instr->texture_index;
1434 int sampler_index = texture_index;
1435
1436 unsigned position_swizzle = 0;
1437
1438 for (unsigned i = 0; i < instr->num_srcs; ++i) {
1439 int reg = SSA_FIXED_REGISTER(REGISTER_TEXTURE_BASE + in_reg);
1440 int index = nir_src_index(ctx, &instr->src[i].src);
1441 int nr_comp = nir_src_num_components(instr->src[i].src);
1442 midgard_vector_alu_src alu_src = blank_alu_src;
1443
1444 switch (instr->src[i].src_type) {
1445 case nir_tex_src_coord: {
1446 if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) {
1447 /* For cubemaps, we need to load coords into
1448 * special r27, and then use a special ld/st op
1449 * to select the face and copy the xy into the
1450 * texture register */
1451
1452 alu_src.swizzle = SWIZZLE(COMPONENT_X, COMPONENT_Y, COMPONENT_Z, COMPONENT_X);
1453
1454 midgard_instruction move = v_mov(index, alu_src, SSA_FIXED_REGISTER(27));
1455 emit_mir_instruction(ctx, move);
1456
1457 midgard_instruction st = m_st_cubemap_coords(reg, 0);
1458 st.load_store.unknown = 0x24; /* XXX: What is this? */
1459 st.load_store.mask = 0x3; /* xy */
1460 st.load_store.swizzle = alu_src.swizzle;
1461 emit_mir_instruction(ctx, st);
1462
1463 position_swizzle = swizzle_of(2);
1464 } else {
1465 position_swizzle = alu_src.swizzle = swizzle_of(nr_comp);
1466
1467 midgard_instruction ins = v_mov(index, alu_src, reg);
1468 ins.alu.mask = expand_writemask(mask_of(nr_comp));
1469 emit_mir_instruction(ctx, ins);
1470
1471 /* To the hardware, z is depth, w is array
1472 * layer. To NIR, z is array layer for a 2D
1473 * array */
1474
1475 if (instr->sampler_dim == GLSL_SAMPLER_DIM_2D)
1476 position_swizzle = SWIZZLE_XYXZ;
1477 }
1478
1479 break;
1480 }
1481
1482 case nir_tex_src_bias:
1483 case nir_tex_src_lod: {
1484 /* To keep RA simple, we put the bias/LOD into the w
1485 * component of the input source, which is otherwise in xy */
1486
1487 alu_src.swizzle = SWIZZLE_XXXX;
1488
1489 midgard_instruction ins = v_mov(index, alu_src, reg);
1490 ins.alu.mask = expand_writemask(1 << COMPONENT_W);
1491 emit_mir_instruction(ctx, ins);
1492 break;
1493 };
1494
1495 default:
1496 unreachable("Unknown texture source type\n");
1497 }
1498 }
1499
1500 /* No helper to build texture words -- we do it all here */
1501 midgard_instruction ins = {
1502 .type = TAG_TEXTURE_4,
1503 .texture = {
1504 .op = midgard_texop,
1505 .format = midgard_tex_format(instr->sampler_dim),
1506 .texture_handle = texture_index,
1507 .sampler_handle = sampler_index,
1508
1509 /* TODO: Regalloc it in */
1510 .swizzle = SWIZZLE_XYZW,
1511 .mask = 0xF,
1512
1513 /* TODO: half */
1514 .in_reg_full = 1,
1515 .in_reg_swizzle = position_swizzle,
1516 .out_full = 1,
1517
1518 /* Always 1 */
1519 .unknown7 = 1,
1520 }
1521 };
1522
1523 /* Set registers to read and write from the same place */
1524 ins.texture.in_reg_select = in_reg;
1525 ins.texture.out_reg_select = out_reg;
1526
1527 /* Setup bias/LOD if necessary. Only register mode support right now.
1528 * TODO: Immediate mode for performance gains */
1529
1530 if (instr->op == nir_texop_txb || instr->op == nir_texop_txl) {
1531 ins.texture.lod_register = true;
1532
1533 midgard_tex_register_select sel = {
1534 .select = in_reg,
1535 .full = 1,
1536
1537 /* w */
1538 .component_lo = 1,
1539 .component_hi = 1
1540 };
1541
1542 uint8_t packed;
1543 memcpy(&packed, &sel, sizeof(packed));
1544 ins.texture.bias = packed;
1545 }
1546
1547 emit_mir_instruction(ctx, ins);
1548
1549 /* Simultaneously alias the destination and emit a move for it. The move will be eliminated if possible */
1550
1551 int o_reg = REGISTER_TEXTURE_BASE + out_reg, o_index = nir_dest_index(ctx, &instr->dest);
1552 alias_ssa(ctx, o_index, SSA_FIXED_REGISTER(o_reg));
1553 ctx->texture_index[reg] = o_index;
1554
1555 midgard_instruction ins2 = v_mov(SSA_FIXED_REGISTER(o_reg), blank_alu_src, o_index);
1556 emit_mir_instruction(ctx, ins2);
1557
1558 /* Used for .cont and .last hinting */
1559 ctx->texture_op_count++;
1560 }
1561
1562 static void
1563 emit_tex(compiler_context *ctx, nir_tex_instr *instr)
1564 {
1565 switch (instr->op) {
1566 case nir_texop_tex:
1567 case nir_texop_txb:
1568 emit_texop_native(ctx, instr, TEXTURE_OP_NORMAL);
1569 break;
1570 case nir_texop_txl:
1571 emit_texop_native(ctx, instr, TEXTURE_OP_LOD);
1572 break;
1573 case nir_texop_txs:
1574 emit_sysval_read(ctx, &instr->instr);
1575 break;
1576 default:
1577 unreachable("Unhanlded texture op");
1578 }
1579 }
1580
1581 static void
1582 emit_jump(compiler_context *ctx, nir_jump_instr *instr)
1583 {
1584 switch (instr->type) {
1585 case nir_jump_break: {
1586 /* Emit a branch out of the loop */
1587 struct midgard_instruction br = v_branch(false, false);
1588 br.branch.target_type = TARGET_BREAK;
1589 br.branch.target_break = ctx->current_loop_depth;
1590 emit_mir_instruction(ctx, br);
1591
1592 DBG("break..\n");
1593 break;
1594 }
1595
1596 default:
1597 DBG("Unknown jump type %d\n", instr->type);
1598 break;
1599 }
1600 }
1601
1602 static void
1603 emit_instr(compiler_context *ctx, struct nir_instr *instr)
1604 {
1605 switch (instr->type) {
1606 case nir_instr_type_load_const:
1607 emit_load_const(ctx, nir_instr_as_load_const(instr));
1608 break;
1609
1610 case nir_instr_type_intrinsic:
1611 emit_intrinsic(ctx, nir_instr_as_intrinsic(instr));
1612 break;
1613
1614 case nir_instr_type_alu:
1615 emit_alu(ctx, nir_instr_as_alu(instr));
1616 break;
1617
1618 case nir_instr_type_tex:
1619 emit_tex(ctx, nir_instr_as_tex(instr));
1620 break;
1621
1622 case nir_instr_type_jump:
1623 emit_jump(ctx, nir_instr_as_jump(instr));
1624 break;
1625
1626 case nir_instr_type_ssa_undef:
1627 /* Spurious */
1628 break;
1629
1630 default:
1631 DBG("Unhandled instruction type\n");
1632 break;
1633 }
1634 }
1635
1636
1637 /* ALU instructions can inline or embed constants, which decreases register
1638 * pressure and saves space. */
1639
1640 #define CONDITIONAL_ATTACH(src) { \
1641 void *entry = _mesa_hash_table_u64_search(ctx->ssa_constants, alu->ssa_args.src + 1); \
1642 \
1643 if (entry) { \
1644 attach_constants(ctx, alu, entry, alu->ssa_args.src + 1); \
1645 alu->ssa_args.src = SSA_FIXED_REGISTER(REGISTER_CONSTANT); \
1646 } \
1647 }
1648
1649 static void
1650 inline_alu_constants(compiler_context *ctx)
1651 {
1652 mir_foreach_instr(ctx, alu) {
1653 /* Other instructions cannot inline constants */
1654 if (alu->type != TAG_ALU_4) continue;
1655
1656 /* If there is already a constant here, we can do nothing */
1657 if (alu->has_constants) continue;
1658
1659 /* It makes no sense to inline constants on a branch */
1660 if (alu->compact_branch || alu->prepacked_branch) continue;
1661
1662 CONDITIONAL_ATTACH(src0);
1663
1664 if (!alu->has_constants) {
1665 CONDITIONAL_ATTACH(src1)
1666 } else if (!alu->inline_constant) {
1667 /* Corner case: _two_ vec4 constants, for instance with a
1668 * csel. For this case, we can only use a constant
1669 * register for one, we'll have to emit a move for the
1670 * other. Note, if both arguments are constants, then
1671 * necessarily neither argument depends on the value of
1672 * any particular register. As the destination register
1673 * will be wiped, that means we can spill the constant
1674 * to the destination register.
1675 */
1676
1677 void *entry = _mesa_hash_table_u64_search(ctx->ssa_constants, alu->ssa_args.src1 + 1);
1678 unsigned scratch = alu->ssa_args.dest;
1679
1680 if (entry) {
1681 midgard_instruction ins = v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), blank_alu_src, scratch);
1682 attach_constants(ctx, &ins, entry, alu->ssa_args.src1 + 1);
1683
1684 /* Force a break XXX Defer r31 writes */
1685 ins.unit = UNIT_VLUT;
1686
1687 /* Set the source */
1688 alu->ssa_args.src1 = scratch;
1689
1690 /* Inject us -before- the last instruction which set r31 */
1691 mir_insert_instruction_before(mir_prev_op(alu), ins);
1692 }
1693 }
1694 }
1695 }
1696
1697 /* Midgard supports two types of constants, embedded constants (128-bit) and
1698 * inline constants (16-bit). Sometimes, especially with scalar ops, embedded
1699 * constants can be demoted to inline constants, for space savings and
1700 * sometimes a performance boost */
1701
1702 static void
1703 embedded_to_inline_constant(compiler_context *ctx)
1704 {
1705 mir_foreach_instr(ctx, ins) {
1706 if (!ins->has_constants) continue;
1707
1708 if (ins->ssa_args.inline_constant) continue;
1709
1710 /* Blend constants must not be inlined by definition */
1711 if (ins->has_blend_constant) continue;
1712
1713 /* src1 cannot be an inline constant due to encoding
1714 * restrictions. So, if possible we try to flip the arguments
1715 * in that case */
1716
1717 int op = ins->alu.op;
1718
1719 if (ins->ssa_args.src0 == SSA_FIXED_REGISTER(REGISTER_CONSTANT)) {
1720 switch (op) {
1721 /* These ops require an operational change to flip
1722 * their arguments TODO */
1723 case midgard_alu_op_flt:
1724 case midgard_alu_op_fle:
1725 case midgard_alu_op_ilt:
1726 case midgard_alu_op_ile:
1727 case midgard_alu_op_fcsel:
1728 case midgard_alu_op_icsel:
1729 DBG("Missed non-commutative flip (%s)\n", alu_opcode_props[op].name);
1730 default:
1731 break;
1732 }
1733
1734 if (alu_opcode_props[op].props & OP_COMMUTES) {
1735 /* Flip the SSA numbers */
1736 ins->ssa_args.src0 = ins->ssa_args.src1;
1737 ins->ssa_args.src1 = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1738
1739 /* And flip the modifiers */
1740
1741 unsigned src_temp;
1742
1743 src_temp = ins->alu.src2;
1744 ins->alu.src2 = ins->alu.src1;
1745 ins->alu.src1 = src_temp;
1746 }
1747 }
1748
1749 if (ins->ssa_args.src1 == SSA_FIXED_REGISTER(REGISTER_CONSTANT)) {
1750 /* Extract the source information */
1751
1752 midgard_vector_alu_src *src;
1753 int q = ins->alu.src2;
1754 midgard_vector_alu_src *m = (midgard_vector_alu_src *) &q;
1755 src = m;
1756
1757 /* Component is from the swizzle, e.g. r26.w -> w component. TODO: What if x is masked out? */
1758 int component = src->swizzle & 3;
1759
1760 /* Scale constant appropriately, if we can legally */
1761 uint16_t scaled_constant = 0;
1762
1763 if (midgard_is_integer_op(op)) {
1764 unsigned int *iconstants = (unsigned int *) ins->constants;
1765 scaled_constant = (uint16_t) iconstants[component];
1766
1767 /* Constant overflow after resize */
1768 if (scaled_constant != iconstants[component])
1769 continue;
1770 } else {
1771 float original = (float) ins->constants[component];
1772 scaled_constant = _mesa_float_to_half(original);
1773
1774 /* Check for loss of precision. If this is
1775 * mediump, we don't care, but for a highp
1776 * shader, we need to pay attention. NIR
1777 * doesn't yet tell us which mode we're in!
1778 * Practically this prevents most constants
1779 * from being inlined, sadly. */
1780
1781 float fp32 = _mesa_half_to_float(scaled_constant);
1782
1783 if (fp32 != original)
1784 continue;
1785 }
1786
1787 /* We don't know how to handle these with a constant */
1788
1789 if (src->mod || src->half || src->rep_low || src->rep_high) {
1790 DBG("Bailing inline constant...\n");
1791 continue;
1792 }
1793
1794 /* Make sure that the constant is not itself a
1795 * vector by checking if all accessed values
1796 * (by the swizzle) are the same. */
1797
1798 uint32_t *cons = (uint32_t *) ins->constants;
1799 uint32_t value = cons[component];
1800
1801 bool is_vector = false;
1802 unsigned mask = effective_writemask(&ins->alu);
1803
1804 for (int c = 1; c < 4; ++c) {
1805 /* We only care if this component is actually used */
1806 if (!(mask & (1 << c)))
1807 continue;
1808
1809 uint32_t test = cons[(src->swizzle >> (2 * c)) & 3];
1810
1811 if (test != value) {
1812 is_vector = true;
1813 break;
1814 }
1815 }
1816
1817 if (is_vector)
1818 continue;
1819
1820 /* Get rid of the embedded constant */
1821 ins->has_constants = false;
1822 ins->ssa_args.src1 = SSA_UNUSED_0;
1823 ins->ssa_args.inline_constant = true;
1824 ins->inline_constant = scaled_constant;
1825 }
1826 }
1827 }
1828
1829 /* Map normal SSA sources to other SSA sources / fixed registers (like
1830 * uniforms) */
1831
1832 static void
1833 map_ssa_to_alias(compiler_context *ctx, int *ref)
1834 {
1835 /* Sign is used quite deliberately for unused */
1836 if (*ref < 0)
1837 return;
1838
1839 unsigned int alias = (uintptr_t) _mesa_hash_table_u64_search(ctx->ssa_to_alias, *ref + 1);
1840
1841 if (alias) {
1842 /* Remove entry in leftovers to avoid a redunant fmov */
1843
1844 struct set_entry *leftover = _mesa_set_search(ctx->leftover_ssa_to_alias, ((void *) (uintptr_t) (*ref + 1)));
1845
1846 if (leftover)
1847 _mesa_set_remove(ctx->leftover_ssa_to_alias, leftover);
1848
1849 /* Assign the alias map */
1850 *ref = alias - 1;
1851 return;
1852 }
1853 }
1854
1855 /* Basic dead code elimination on the MIR itself, which cleans up e.g. the
1856 * texture pipeline */
1857
1858 static bool
1859 midgard_opt_dead_code_eliminate(compiler_context *ctx, midgard_block *block)
1860 {
1861 bool progress = false;
1862
1863 mir_foreach_instr_in_block_safe(block, ins) {
1864 if (ins->type != TAG_ALU_4) continue;
1865 if (ins->compact_branch) continue;
1866
1867 if (ins->ssa_args.dest >= SSA_FIXED_MINIMUM) continue;
1868 if (mir_is_live_after(ctx, block, ins, ins->ssa_args.dest)) continue;
1869
1870 mir_remove_instruction(ins);
1871 progress = true;
1872 }
1873
1874 return progress;
1875 }
1876
1877 /* Dead code elimination for branches at the end of a block - only one branch
1878 * per block is legal semantically */
1879
1880 static void
1881 midgard_opt_cull_dead_branch(compiler_context *ctx, midgard_block *block)
1882 {
1883 bool branched = false;
1884
1885 mir_foreach_instr_in_block_safe(block, ins) {
1886 if (!midgard_is_branch_unit(ins->unit)) continue;
1887
1888 /* We ignore prepacked branches since the fragment epilogue is
1889 * just generally special */
1890 if (ins->prepacked_branch) continue;
1891
1892 /* Discards are similarly special and may not correspond to the
1893 * end of a block */
1894
1895 if (ins->branch.target_type == TARGET_DISCARD) continue;
1896
1897 if (branched) {
1898 /* We already branched, so this is dead */
1899 mir_remove_instruction(ins);
1900 }
1901
1902 branched = true;
1903 }
1904 }
1905
1906 static bool
1907 mir_nontrivial_mod(midgard_vector_alu_src src, bool is_int, unsigned mask)
1908 {
1909 /* abs or neg */
1910 if (!is_int && src.mod) return true;
1911
1912 /* swizzle */
1913 for (unsigned c = 0; c < 4; ++c) {
1914 if (!(mask & (1 << c))) continue;
1915 if (((src.swizzle >> (2*c)) & 3) != c) return true;
1916 }
1917
1918 return false;
1919 }
1920
1921 static bool
1922 mir_nontrivial_source2_mod(midgard_instruction *ins)
1923 {
1924 unsigned mask = squeeze_writemask(ins->alu.mask);
1925 bool is_int = midgard_is_integer_op(ins->alu.op);
1926
1927 midgard_vector_alu_src src2 =
1928 vector_alu_from_unsigned(ins->alu.src2);
1929
1930 return mir_nontrivial_mod(src2, is_int, mask);
1931 }
1932
1933 static bool
1934 mir_nontrivial_outmod(midgard_instruction *ins)
1935 {
1936 bool is_int = midgard_is_integer_op(ins->alu.op);
1937 unsigned mod = ins->alu.outmod;
1938
1939 if (is_int)
1940 return mod != midgard_outmod_int_wrap;
1941 else
1942 return mod != midgard_outmod_none;
1943 }
1944
1945 static bool
1946 midgard_opt_copy_prop(compiler_context *ctx, midgard_block *block)
1947 {
1948 bool progress = false;
1949
1950 mir_foreach_instr_in_block_safe(block, ins) {
1951 if (ins->type != TAG_ALU_4) continue;
1952 if (!OP_IS_MOVE(ins->alu.op)) continue;
1953
1954 unsigned from = ins->ssa_args.src1;
1955 unsigned to = ins->ssa_args.dest;
1956
1957 /* We only work on pure SSA */
1958
1959 if (to >= SSA_FIXED_MINIMUM) continue;
1960 if (from >= SSA_FIXED_MINIMUM) continue;
1961 if (to >= ctx->func->impl->ssa_alloc) continue;
1962 if (from >= ctx->func->impl->ssa_alloc) continue;
1963
1964 /* Constant propagation is not handled here, either */
1965 if (ins->ssa_args.inline_constant) continue;
1966 if (ins->has_constants) continue;
1967
1968 if (mir_nontrivial_source2_mod(ins)) continue;
1969 if (mir_nontrivial_outmod(ins)) continue;
1970
1971 /* We're clear -- rewrite */
1972 mir_rewrite_index_src(ctx, to, from);
1973 mir_remove_instruction(ins);
1974 progress |= true;
1975 }
1976
1977 return progress;
1978 }
1979
1980 /* fmov.pos is an idiom for fpos. Propoagate the .pos up to the source, so then
1981 * the move can be propagated away entirely */
1982
1983 static bool
1984 mir_compose_float_outmod(midgard_outmod_float *outmod, midgard_outmod_float comp)
1985 {
1986 /* Nothing to do */
1987 if (comp == midgard_outmod_none)
1988 return true;
1989
1990 if (*outmod == midgard_outmod_none) {
1991 *outmod = comp;
1992 return true;
1993 }
1994
1995 /* TODO: Compose rules */
1996 return false;
1997 }
1998
1999 static bool
2000 midgard_opt_pos_propagate(compiler_context *ctx, midgard_block *block)
2001 {
2002 bool progress = false;
2003
2004 mir_foreach_instr_in_block_safe(block, ins) {
2005 if (ins->type != TAG_ALU_4) continue;
2006 if (ins->alu.op != midgard_alu_op_fmov) continue;
2007 if (ins->alu.outmod != midgard_outmod_pos) continue;
2008
2009 /* TODO: Registers? */
2010 unsigned src = ins->ssa_args.src1;
2011 if (src >= ctx->func->impl->ssa_alloc) continue;
2012 assert(!mir_has_multiple_writes(ctx, src));
2013
2014 /* There might be a source modifier, too */
2015 if (mir_nontrivial_source2_mod(ins)) continue;
2016
2017 /* Backpropagate the modifier */
2018 mir_foreach_instr_in_block_from_rev(block, v, mir_prev_op(ins)) {
2019 if (v->type != TAG_ALU_4) continue;
2020 if (v->ssa_args.dest != src) continue;
2021
2022 /* Can we even take a float outmod? */
2023 if (midgard_is_integer_out_op(v->alu.op)) continue;
2024
2025 midgard_outmod_float temp = v->alu.outmod;
2026 progress |= mir_compose_float_outmod(&temp, ins->alu.outmod);
2027
2028 /* Throw in the towel.. */
2029 if (!progress) break;
2030
2031 /* Otherwise, transfer the modifier */
2032 v->alu.outmod = temp;
2033 ins->alu.outmod = midgard_outmod_none;
2034
2035 break;
2036 }
2037 }
2038
2039 return progress;
2040 }
2041
2042 static bool
2043 midgard_opt_copy_prop_tex(compiler_context *ctx, midgard_block *block)
2044 {
2045 bool progress = false;
2046
2047 mir_foreach_instr_in_block_safe(block, ins) {
2048 if (ins->type != TAG_ALU_4) continue;
2049 if (!OP_IS_MOVE(ins->alu.op)) continue;
2050
2051 unsigned from = ins->ssa_args.src1;
2052 unsigned to = ins->ssa_args.dest;
2053
2054 /* Make sure it's simple enough for us to handle */
2055
2056 if (from >= SSA_FIXED_MINIMUM) continue;
2057 if (from >= ctx->func->impl->ssa_alloc) continue;
2058 if (to < SSA_FIXED_REGISTER(REGISTER_TEXTURE_BASE)) continue;
2059 if (to > SSA_FIXED_REGISTER(REGISTER_TEXTURE_BASE + 1)) continue;
2060
2061 bool eliminated = false;
2062
2063 mir_foreach_instr_in_block_from_rev(block, v, mir_prev_op(ins)) {
2064 /* The texture registers are not SSA so be careful.
2065 * Conservatively, just stop if we hit a texture op
2066 * (even if it may not write) to where we are */
2067
2068 if (v->type != TAG_ALU_4)
2069 break;
2070
2071 if (v->ssa_args.dest == from) {
2072 /* We don't want to track partial writes ... */
2073 if (v->alu.mask == 0xF) {
2074 v->ssa_args.dest = to;
2075 eliminated = true;
2076 }
2077
2078 break;
2079 }
2080 }
2081
2082 if (eliminated)
2083 mir_remove_instruction(ins);
2084
2085 progress |= eliminated;
2086 }
2087
2088 return progress;
2089 }
2090
2091 /* The following passes reorder MIR instructions to enable better scheduling */
2092
2093 static void
2094 midgard_pair_load_store(compiler_context *ctx, midgard_block *block)
2095 {
2096 mir_foreach_instr_in_block_safe(block, ins) {
2097 if (ins->type != TAG_LOAD_STORE_4) continue;
2098
2099 /* We've found a load/store op. Check if next is also load/store. */
2100 midgard_instruction *next_op = mir_next_op(ins);
2101 if (&next_op->link != &block->instructions) {
2102 if (next_op->type == TAG_LOAD_STORE_4) {
2103 /* If so, we're done since we're a pair */
2104 ins = mir_next_op(ins);
2105 continue;
2106 }
2107
2108 /* Maximum search distance to pair, to avoid register pressure disasters */
2109 int search_distance = 8;
2110
2111 /* Otherwise, we have an orphaned load/store -- search for another load */
2112 mir_foreach_instr_in_block_from(block, c, mir_next_op(ins)) {
2113 /* Terminate search if necessary */
2114 if (!(search_distance--)) break;
2115
2116 if (c->type != TAG_LOAD_STORE_4) continue;
2117
2118 /* Stores cannot be reordered, since they have
2119 * dependencies. For the same reason, indirect
2120 * loads cannot be reordered as their index is
2121 * loaded in r27.w */
2122
2123 if (OP_IS_STORE(c->load_store.op)) continue;
2124
2125 /* It appears the 0x800 bit is set whenever a
2126 * load is direct, unset when it is indirect.
2127 * Skip indirect loads. */
2128
2129 if (!(c->load_store.unknown & 0x800)) continue;
2130
2131 /* We found one! Move it up to pair and remove it from the old location */
2132
2133 mir_insert_instruction_before(ins, *c);
2134 mir_remove_instruction(c);
2135
2136 break;
2137 }
2138 }
2139 }
2140 }
2141
2142 /* If there are leftovers after the below pass, emit actual fmov
2143 * instructions for the slow-but-correct path */
2144
2145 static void
2146 emit_leftover_move(compiler_context *ctx)
2147 {
2148 set_foreach(ctx->leftover_ssa_to_alias, leftover) {
2149 int base = ((uintptr_t) leftover->key) - 1;
2150 int mapped = base;
2151
2152 map_ssa_to_alias(ctx, &mapped);
2153 EMIT(mov, mapped, blank_alu_src, base);
2154 }
2155 }
2156
2157 static void
2158 actualise_ssa_to_alias(compiler_context *ctx)
2159 {
2160 mir_foreach_instr(ctx, ins) {
2161 map_ssa_to_alias(ctx, &ins->ssa_args.src0);
2162 map_ssa_to_alias(ctx, &ins->ssa_args.src1);
2163 }
2164
2165 emit_leftover_move(ctx);
2166 }
2167
2168 static void
2169 emit_fragment_epilogue(compiler_context *ctx)
2170 {
2171 /* Special case: writing out constants requires us to include the move
2172 * explicitly now, so shove it into r0 */
2173
2174 void *constant_value = _mesa_hash_table_u64_search(ctx->ssa_constants, ctx->fragment_output + 1);
2175
2176 if (constant_value) {
2177 midgard_instruction ins = v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), blank_alu_src, SSA_FIXED_REGISTER(0));
2178 attach_constants(ctx, &ins, constant_value, ctx->fragment_output + 1);
2179 emit_mir_instruction(ctx, ins);
2180 }
2181
2182 /* Perform the actual fragment writeout. We have two writeout/branch
2183 * instructions, forming a loop until writeout is successful as per the
2184 * docs. TODO: gl_FragDepth */
2185
2186 EMIT(alu_br_compact_cond, midgard_jmp_writeout_op_writeout, TAG_ALU_4, 0, midgard_condition_always);
2187 EMIT(alu_br_compact_cond, midgard_jmp_writeout_op_writeout, TAG_ALU_4, -1, midgard_condition_always);
2188 }
2189
2190 /* For the blend epilogue, we need to convert the blended fragment vec4 (stored
2191 * in r0) to a RGBA8888 value by scaling and type converting. We then output it
2192 * with the int8 analogue to the fragment epilogue */
2193
2194 static void
2195 emit_blend_epilogue(compiler_context *ctx)
2196 {
2197 /* vmul.fmul.none.fulllow hr48, r0, #255 */
2198
2199 midgard_instruction scale = {
2200 .type = TAG_ALU_4,
2201 .unit = UNIT_VMUL,
2202 .inline_constant = _mesa_float_to_half(255.0),
2203 .ssa_args = {
2204 .src0 = SSA_FIXED_REGISTER(0),
2205 .src1 = SSA_UNUSED_0,
2206 .dest = SSA_FIXED_REGISTER(24),
2207 .inline_constant = true
2208 },
2209 .alu = {
2210 .op = midgard_alu_op_fmul,
2211 .reg_mode = midgard_reg_mode_32,
2212 .dest_override = midgard_dest_override_lower,
2213 .mask = 0xFF,
2214 .src1 = vector_alu_srco_unsigned(blank_alu_src),
2215 .src2 = vector_alu_srco_unsigned(blank_alu_src),
2216 }
2217 };
2218
2219 emit_mir_instruction(ctx, scale);
2220
2221 /* vadd.f2u_rte.pos.low hr0, hr48, #0 */
2222
2223 midgard_vector_alu_src alu_src = blank_alu_src;
2224 alu_src.half = true;
2225
2226 midgard_instruction f2u_rte = {
2227 .type = TAG_ALU_4,
2228 .ssa_args = {
2229 .src0 = SSA_FIXED_REGISTER(24),
2230 .src1 = SSA_UNUSED_0,
2231 .dest = SSA_FIXED_REGISTER(0),
2232 .inline_constant = true
2233 },
2234 .alu = {
2235 .op = midgard_alu_op_f2u_rte,
2236 .reg_mode = midgard_reg_mode_16,
2237 .dest_override = midgard_dest_override_lower,
2238 .outmod = midgard_outmod_pos,
2239 .mask = 0xF,
2240 .src1 = vector_alu_srco_unsigned(alu_src),
2241 .src2 = vector_alu_srco_unsigned(blank_alu_src),
2242 }
2243 };
2244
2245 emit_mir_instruction(ctx, f2u_rte);
2246
2247 EMIT(alu_br_compact_cond, midgard_jmp_writeout_op_writeout, TAG_ALU_4, 0, midgard_condition_always);
2248 EMIT(alu_br_compact_cond, midgard_jmp_writeout_op_writeout, TAG_ALU_4, -1, midgard_condition_always);
2249 }
2250
2251 static midgard_block *
2252 emit_block(compiler_context *ctx, nir_block *block)
2253 {
2254 midgard_block *this_block = calloc(sizeof(midgard_block), 1);
2255 list_addtail(&this_block->link, &ctx->blocks);
2256
2257 this_block->is_scheduled = false;
2258 ++ctx->block_count;
2259
2260 ctx->texture_index[0] = -1;
2261 ctx->texture_index[1] = -1;
2262
2263 /* Add us as a successor to the block we are following */
2264 if (ctx->current_block)
2265 midgard_block_add_successor(ctx->current_block, this_block);
2266
2267 /* Set up current block */
2268 list_inithead(&this_block->instructions);
2269 ctx->current_block = this_block;
2270
2271 nir_foreach_instr(instr, block) {
2272 emit_instr(ctx, instr);
2273 ++ctx->instruction_count;
2274 }
2275
2276 inline_alu_constants(ctx);
2277 embedded_to_inline_constant(ctx);
2278
2279 /* Perform heavylifting for aliasing */
2280 actualise_ssa_to_alias(ctx);
2281
2282 midgard_pair_load_store(ctx, this_block);
2283
2284 /* Append fragment shader epilogue (value writeout) */
2285 if (ctx->stage == MESA_SHADER_FRAGMENT) {
2286 if (block == nir_impl_last_block(ctx->func->impl)) {
2287 if (ctx->is_blend)
2288 emit_blend_epilogue(ctx);
2289 else
2290 emit_fragment_epilogue(ctx);
2291 }
2292 }
2293
2294 if (block == nir_start_block(ctx->func->impl))
2295 ctx->initial_block = this_block;
2296
2297 if (block == nir_impl_last_block(ctx->func->impl))
2298 ctx->final_block = this_block;
2299
2300 /* Allow the next control flow to access us retroactively, for
2301 * branching etc */
2302 ctx->current_block = this_block;
2303
2304 /* Document the fallthrough chain */
2305 ctx->previous_source_block = this_block;
2306
2307 return this_block;
2308 }
2309
2310 static midgard_block *emit_cf_list(struct compiler_context *ctx, struct exec_list *list);
2311
2312 static void
2313 emit_if(struct compiler_context *ctx, nir_if *nif)
2314 {
2315 /* Conditional branches expect the condition in r31.w; emit a move for
2316 * that in the _previous_ block (which is the current block). */
2317 emit_condition(ctx, &nif->condition, true, COMPONENT_X);
2318
2319 /* Speculatively emit the branch, but we can't fill it in until later */
2320 EMIT(branch, true, true);
2321 midgard_instruction *then_branch = mir_last_in_block(ctx->current_block);
2322
2323 /* Emit the two subblocks */
2324 midgard_block *then_block = emit_cf_list(ctx, &nif->then_list);
2325
2326 /* Emit a jump from the end of the then block to the end of the else */
2327 EMIT(branch, false, false);
2328 midgard_instruction *then_exit = mir_last_in_block(ctx->current_block);
2329
2330 /* Emit second block, and check if it's empty */
2331
2332 int else_idx = ctx->block_count;
2333 int count_in = ctx->instruction_count;
2334 midgard_block *else_block = emit_cf_list(ctx, &nif->else_list);
2335 int after_else_idx = ctx->block_count;
2336
2337 /* Now that we have the subblocks emitted, fix up the branches */
2338
2339 assert(then_block);
2340 assert(else_block);
2341
2342 if (ctx->instruction_count == count_in) {
2343 /* The else block is empty, so don't emit an exit jump */
2344 mir_remove_instruction(then_exit);
2345 then_branch->branch.target_block = after_else_idx;
2346 } else {
2347 then_branch->branch.target_block = else_idx;
2348 then_exit->branch.target_block = after_else_idx;
2349 }
2350 }
2351
2352 static void
2353 emit_loop(struct compiler_context *ctx, nir_loop *nloop)
2354 {
2355 /* Remember where we are */
2356 midgard_block *start_block = ctx->current_block;
2357
2358 /* Allocate a loop number, growing the current inner loop depth */
2359 int loop_idx = ++ctx->current_loop_depth;
2360
2361 /* Get index from before the body so we can loop back later */
2362 int start_idx = ctx->block_count;
2363
2364 /* Emit the body itself */
2365 emit_cf_list(ctx, &nloop->body);
2366
2367 /* Branch back to loop back */
2368 struct midgard_instruction br_back = v_branch(false, false);
2369 br_back.branch.target_block = start_idx;
2370 emit_mir_instruction(ctx, br_back);
2371
2372 /* Mark down that branch in the graph. Note that we're really branching
2373 * to the block *after* we started in. TODO: Why doesn't the branch
2374 * itself have an off-by-one then...? */
2375 midgard_block_add_successor(ctx->current_block, start_block->successors[0]);
2376
2377 /* Find the index of the block about to follow us (note: we don't add
2378 * one; blocks are 0-indexed so we get a fencepost problem) */
2379 int break_block_idx = ctx->block_count;
2380
2381 /* Fix up the break statements we emitted to point to the right place,
2382 * now that we can allocate a block number for them */
2383
2384 list_for_each_entry_from(struct midgard_block, block, start_block, &ctx->blocks, link) {
2385 mir_foreach_instr_in_block(block, ins) {
2386 if (ins->type != TAG_ALU_4) continue;
2387 if (!ins->compact_branch) continue;
2388 if (ins->prepacked_branch) continue;
2389
2390 /* We found a branch -- check the type to see if we need to do anything */
2391 if (ins->branch.target_type != TARGET_BREAK) continue;
2392
2393 /* It's a break! Check if it's our break */
2394 if (ins->branch.target_break != loop_idx) continue;
2395
2396 /* Okay, cool, we're breaking out of this loop.
2397 * Rewrite from a break to a goto */
2398
2399 ins->branch.target_type = TARGET_GOTO;
2400 ins->branch.target_block = break_block_idx;
2401 }
2402 }
2403
2404 /* Now that we've finished emitting the loop, free up the depth again
2405 * so we play nice with recursion amid nested loops */
2406 --ctx->current_loop_depth;
2407 }
2408
2409 static midgard_block *
2410 emit_cf_list(struct compiler_context *ctx, struct exec_list *list)
2411 {
2412 midgard_block *start_block = NULL;
2413
2414 foreach_list_typed(nir_cf_node, node, node, list) {
2415 switch (node->type) {
2416 case nir_cf_node_block: {
2417 midgard_block *block = emit_block(ctx, nir_cf_node_as_block(node));
2418
2419 if (!start_block)
2420 start_block = block;
2421
2422 break;
2423 }
2424
2425 case nir_cf_node_if:
2426 emit_if(ctx, nir_cf_node_as_if(node));
2427 break;
2428
2429 case nir_cf_node_loop:
2430 emit_loop(ctx, nir_cf_node_as_loop(node));
2431 break;
2432
2433 case nir_cf_node_function:
2434 assert(0);
2435 break;
2436 }
2437 }
2438
2439 return start_block;
2440 }
2441
2442 /* Due to lookahead, we need to report the first tag executed in the command
2443 * stream and in branch targets. An initial block might be empty, so iterate
2444 * until we find one that 'works' */
2445
2446 static unsigned
2447 midgard_get_first_tag_from_block(compiler_context *ctx, unsigned block_idx)
2448 {
2449 midgard_block *initial_block = mir_get_block(ctx, block_idx);
2450
2451 unsigned first_tag = 0;
2452
2453 do {
2454 midgard_bundle *initial_bundle = util_dynarray_element(&initial_block->bundles, midgard_bundle, 0);
2455
2456 if (initial_bundle) {
2457 first_tag = initial_bundle->tag;
2458 break;
2459 }
2460
2461 /* Initial block is empty, try the next block */
2462 initial_block = list_first_entry(&(initial_block->link), midgard_block, link);
2463 } while(initial_block != NULL);
2464
2465 assert(first_tag);
2466 return first_tag;
2467 }
2468
2469 int
2470 midgard_compile_shader_nir(nir_shader *nir, midgard_program *program, bool is_blend)
2471 {
2472 struct util_dynarray *compiled = &program->compiled;
2473
2474 midgard_debug = debug_get_option_midgard_debug();
2475
2476 compiler_context ictx = {
2477 .nir = nir,
2478 .stage = nir->info.stage,
2479
2480 .is_blend = is_blend,
2481 .blend_constant_offset = -1,
2482
2483 .alpha_ref = program->alpha_ref
2484 };
2485
2486 compiler_context *ctx = &ictx;
2487
2488 /* TODO: Decide this at runtime */
2489 ctx->uniform_cutoff = 8;
2490
2491 /* Initialize at a global (not block) level hash tables */
2492
2493 ctx->ssa_constants = _mesa_hash_table_u64_create(NULL);
2494 ctx->ssa_to_alias = _mesa_hash_table_u64_create(NULL);
2495 ctx->hash_to_temp = _mesa_hash_table_u64_create(NULL);
2496 ctx->sysval_to_id = _mesa_hash_table_u64_create(NULL);
2497 ctx->leftover_ssa_to_alias = _mesa_set_create(NULL, _mesa_hash_pointer, _mesa_key_pointer_equal);
2498
2499 /* Record the varying mapping for the command stream's bookkeeping */
2500
2501 struct exec_list *varyings =
2502 ctx->stage == MESA_SHADER_VERTEX ? &nir->outputs : &nir->inputs;
2503
2504 unsigned max_varying = 0;
2505 nir_foreach_variable(var, varyings) {
2506 unsigned loc = var->data.driver_location;
2507 unsigned sz = glsl_type_size(var->type, FALSE);
2508
2509 for (int c = 0; c < sz; ++c) {
2510 program->varyings[loc + c] = var->data.location + c;
2511 max_varying = MAX2(max_varying, loc + c);
2512 }
2513 }
2514
2515 /* Lower gl_Position pre-optimisation, but after lowering vars to ssa
2516 * (so we don't accidentally duplicate the epilogue since mesa/st has
2517 * messed with our I/O quite a bit already) */
2518
2519 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
2520
2521 if (ctx->stage == MESA_SHADER_VERTEX)
2522 NIR_PASS_V(nir, nir_lower_viewport_transform);
2523
2524 NIR_PASS_V(nir, nir_lower_var_copies);
2525 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
2526 NIR_PASS_V(nir, nir_split_var_copies);
2527 NIR_PASS_V(nir, nir_lower_var_copies);
2528 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
2529 NIR_PASS_V(nir, nir_lower_var_copies);
2530 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
2531
2532 NIR_PASS_V(nir, nir_lower_io, nir_var_all, glsl_type_size, 0);
2533
2534 /* Optimisation passes */
2535
2536 optimise_nir(nir);
2537
2538 if (midgard_debug & MIDGARD_DBG_SHADERS) {
2539 nir_print_shader(nir, stdout);
2540 }
2541
2542 /* Assign sysvals and counts, now that we're sure
2543 * (post-optimisation) */
2544
2545 midgard_nir_assign_sysvals(ctx, nir);
2546
2547 program->uniform_count = nir->num_uniforms;
2548 program->sysval_count = ctx->sysval_count;
2549 memcpy(program->sysvals, ctx->sysvals, sizeof(ctx->sysvals[0]) * ctx->sysval_count);
2550
2551 program->attribute_count = (ctx->stage == MESA_SHADER_VERTEX) ? nir->num_inputs : 0;
2552 program->varying_count = max_varying + 1; /* Fencepost off-by-one */
2553
2554 nir_foreach_function(func, nir) {
2555 if (!func->impl)
2556 continue;
2557
2558 list_inithead(&ctx->blocks);
2559 ctx->block_count = 0;
2560 ctx->func = func;
2561
2562 emit_cf_list(ctx, &func->impl->body);
2563 emit_block(ctx, func->impl->end_block);
2564
2565 break; /* TODO: Multi-function shaders */
2566 }
2567
2568 util_dynarray_init(compiled, NULL);
2569
2570 /* MIR-level optimizations */
2571
2572 bool progress = false;
2573
2574 do {
2575 progress = false;
2576
2577 mir_foreach_block(ctx, block) {
2578 progress |= midgard_opt_pos_propagate(ctx, block);
2579 progress |= midgard_opt_copy_prop(ctx, block);
2580 progress |= midgard_opt_copy_prop_tex(ctx, block);
2581 progress |= midgard_opt_dead_code_eliminate(ctx, block);
2582 }
2583 } while (progress);
2584
2585 /* Nested control-flow can result in dead branches at the end of the
2586 * block. This messes with our analysis and is just dead code, so cull
2587 * them */
2588 mir_foreach_block(ctx, block) {
2589 midgard_opt_cull_dead_branch(ctx, block);
2590 }
2591
2592 /* Schedule! */
2593 schedule_program(ctx);
2594
2595 /* Now that all the bundles are scheduled and we can calculate block
2596 * sizes, emit actual branch instructions rather than placeholders */
2597
2598 int br_block_idx = 0;
2599
2600 mir_foreach_block(ctx, block) {
2601 util_dynarray_foreach(&block->bundles, midgard_bundle, bundle) {
2602 for (int c = 0; c < bundle->instruction_count; ++c) {
2603 midgard_instruction *ins = bundle->instructions[c];
2604
2605 if (!midgard_is_branch_unit(ins->unit)) continue;
2606
2607 if (ins->prepacked_branch) continue;
2608
2609 /* Parse some basic branch info */
2610 bool is_compact = ins->unit == ALU_ENAB_BR_COMPACT;
2611 bool is_conditional = ins->branch.conditional;
2612 bool is_inverted = ins->branch.invert_conditional;
2613 bool is_discard = ins->branch.target_type == TARGET_DISCARD;
2614
2615 /* Determine the block we're jumping to */
2616 int target_number = ins->branch.target_block;
2617
2618 /* Report the destination tag */
2619 int dest_tag = is_discard ? 0 : midgard_get_first_tag_from_block(ctx, target_number);
2620
2621 /* Count up the number of quadwords we're
2622 * jumping over = number of quadwords until
2623 * (br_block_idx, target_number) */
2624
2625 int quadword_offset = 0;
2626
2627 if (is_discard) {
2628 /* Jump to the end of the shader. We
2629 * need to include not only the
2630 * following blocks, but also the
2631 * contents of our current block (since
2632 * discard can come in the middle of
2633 * the block) */
2634
2635 midgard_block *blk = mir_get_block(ctx, br_block_idx + 1);
2636
2637 for (midgard_bundle *bun = bundle + 1; bun < (midgard_bundle *)((char*) block->bundles.data + block->bundles.size); ++bun) {
2638 quadword_offset += quadword_size(bun->tag);
2639 }
2640
2641 mir_foreach_block_from(ctx, blk, b) {
2642 quadword_offset += b->quadword_count;
2643 }
2644
2645 } else if (target_number > br_block_idx) {
2646 /* Jump forward */
2647
2648 for (int idx = br_block_idx + 1; idx < target_number; ++idx) {
2649 midgard_block *blk = mir_get_block(ctx, idx);
2650 assert(blk);
2651
2652 quadword_offset += blk->quadword_count;
2653 }
2654 } else {
2655 /* Jump backwards */
2656
2657 for (int idx = br_block_idx; idx >= target_number; --idx) {
2658 midgard_block *blk = mir_get_block(ctx, idx);
2659 assert(blk);
2660
2661 quadword_offset -= blk->quadword_count;
2662 }
2663 }
2664
2665 /* Unconditional extended branches (far jumps)
2666 * have issues, so we always use a conditional
2667 * branch, setting the condition to always for
2668 * unconditional. For compact unconditional
2669 * branches, cond isn't used so it doesn't
2670 * matter what we pick. */
2671
2672 midgard_condition cond =
2673 !is_conditional ? midgard_condition_always :
2674 is_inverted ? midgard_condition_false :
2675 midgard_condition_true;
2676
2677 midgard_jmp_writeout_op op =
2678 is_discard ? midgard_jmp_writeout_op_discard :
2679 (is_compact && !is_conditional) ? midgard_jmp_writeout_op_branch_uncond :
2680 midgard_jmp_writeout_op_branch_cond;
2681
2682 if (!is_compact) {
2683 midgard_branch_extended branch =
2684 midgard_create_branch_extended(
2685 cond, op,
2686 dest_tag,
2687 quadword_offset);
2688
2689 memcpy(&ins->branch_extended, &branch, sizeof(branch));
2690 } else if (is_conditional || is_discard) {
2691 midgard_branch_cond branch = {
2692 .op = op,
2693 .dest_tag = dest_tag,
2694 .offset = quadword_offset,
2695 .cond = cond
2696 };
2697
2698 assert(branch.offset == quadword_offset);
2699
2700 memcpy(&ins->br_compact, &branch, sizeof(branch));
2701 } else {
2702 assert(op == midgard_jmp_writeout_op_branch_uncond);
2703
2704 midgard_branch_uncond branch = {
2705 .op = op,
2706 .dest_tag = dest_tag,
2707 .offset = quadword_offset,
2708 .unknown = 1
2709 };
2710
2711 assert(branch.offset == quadword_offset);
2712
2713 memcpy(&ins->br_compact, &branch, sizeof(branch));
2714 }
2715 }
2716 }
2717
2718 ++br_block_idx;
2719 }
2720
2721 /* Emit flat binary from the instruction arrays. Iterate each block in
2722 * sequence. Save instruction boundaries such that lookahead tags can
2723 * be assigned easily */
2724
2725 /* Cache _all_ bundles in source order for lookahead across failed branches */
2726
2727 int bundle_count = 0;
2728 mir_foreach_block(ctx, block) {
2729 bundle_count += block->bundles.size / sizeof(midgard_bundle);
2730 }
2731 midgard_bundle **source_order_bundles = malloc(sizeof(midgard_bundle *) * bundle_count);
2732 int bundle_idx = 0;
2733 mir_foreach_block(ctx, block) {
2734 util_dynarray_foreach(&block->bundles, midgard_bundle, bundle) {
2735 source_order_bundles[bundle_idx++] = bundle;
2736 }
2737 }
2738
2739 int current_bundle = 0;
2740
2741 /* Midgard prefetches instruction types, so during emission we
2742 * need to lookahead. Unless this is the last instruction, in
2743 * which we return 1. Or if this is the second to last and the
2744 * last is an ALU, then it's also 1... */
2745
2746 mir_foreach_block(ctx, block) {
2747 mir_foreach_bundle_in_block(block, bundle) {
2748 int lookahead = 1;
2749
2750 if (current_bundle + 1 < bundle_count) {
2751 uint8_t next = source_order_bundles[current_bundle + 1]->tag;
2752
2753 if (!(current_bundle + 2 < bundle_count) && IS_ALU(next)) {
2754 lookahead = 1;
2755 } else {
2756 lookahead = next;
2757 }
2758 }
2759
2760 emit_binary_bundle(ctx, bundle, compiled, lookahead);
2761 ++current_bundle;
2762 }
2763
2764 /* TODO: Free deeper */
2765 //util_dynarray_fini(&block->instructions);
2766 }
2767
2768 free(source_order_bundles);
2769
2770 /* Report the very first tag executed */
2771 program->first_tag = midgard_get_first_tag_from_block(ctx, 0);
2772
2773 /* Deal with off-by-one related to the fencepost problem */
2774 program->work_register_count = ctx->work_registers + 1;
2775
2776 program->can_discard = ctx->can_discard;
2777 program->uniform_cutoff = ctx->uniform_cutoff;
2778
2779 program->blend_patch_offset = ctx->blend_constant_offset;
2780
2781 if (midgard_debug & MIDGARD_DBG_SHADERS)
2782 disassemble_midgard(program->compiled.data, program->compiled.size);
2783
2784 return 0;
2785 }