panfrost/midgard: Split up midgard_compile.c (RA)
[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_XYZW SWIZZLE(COMPONENT_X, COMPONENT_Y, COMPONENT_Z, COMPONENT_W)
86
87 #define M_LOAD_STORE(name, rname, uname) \
88 static midgard_instruction m_##name(unsigned ssa, unsigned address) { \
89 midgard_instruction i = { \
90 .type = TAG_LOAD_STORE_4, \
91 .ssa_args = { \
92 .rname = ssa, \
93 .uname = -1, \
94 .src1 = -1 \
95 }, \
96 .load_store = { \
97 .op = midgard_op_##name, \
98 .mask = 0xF, \
99 .swizzle = SWIZZLE_XYZW, \
100 .address = address \
101 } \
102 }; \
103 \
104 return i; \
105 }
106
107 #define M_LOAD(name) M_LOAD_STORE(name, dest, src0)
108 #define M_STORE(name) M_LOAD_STORE(name, src0, dest)
109
110 const midgard_vector_alu_src blank_alu_src = {
111 .swizzle = SWIZZLE(COMPONENT_X, COMPONENT_Y, COMPONENT_Z, COMPONENT_W),
112 };
113
114 const midgard_vector_alu_src blank_alu_src_xxxx = {
115 .swizzle = SWIZZLE(COMPONENT_X, COMPONENT_X, COMPONENT_X, COMPONENT_X),
116 };
117
118 const midgard_scalar_alu_src blank_scalar_alu_src = {
119 .full = true
120 };
121
122 /* Used for encoding the unused source of 1-op instructions */
123 const midgard_vector_alu_src zero_alu_src = { 0 };
124
125 /* Coerce structs to integer */
126
127 static unsigned
128 vector_alu_srco_unsigned(midgard_vector_alu_src src)
129 {
130 unsigned u;
131 memcpy(&u, &src, sizeof(src));
132 return u;
133 }
134
135 static midgard_vector_alu_src
136 vector_alu_from_unsigned(unsigned u)
137 {
138 midgard_vector_alu_src s;
139 memcpy(&s, &u, sizeof(s));
140 return s;
141 }
142
143 /* Inputs a NIR ALU source, with modifiers attached if necessary, and outputs
144 * the corresponding Midgard source */
145
146 static midgard_vector_alu_src
147 vector_alu_modifiers(nir_alu_src *src, bool is_int)
148 {
149 if (!src) return blank_alu_src;
150
151 midgard_vector_alu_src alu_src = {
152 .rep_low = 0,
153 .rep_high = 0,
154 .half = 0, /* TODO */
155 .swizzle = SWIZZLE_FROM_ARRAY(src->swizzle)
156 };
157
158 if (is_int) {
159 /* TODO: sign-extend/zero-extend */
160 alu_src.mod = midgard_int_normal;
161
162 /* These should have been lowered away */
163 assert(!(src->abs || src->negate));
164 } else {
165 alu_src.mod = (src->abs << 0) | (src->negate << 1);
166 }
167
168 return alu_src;
169 }
170
171 /* 'Intrinsic' move for misc aliasing uses independent of actual NIR ALU code */
172
173 static midgard_instruction
174 v_fmov(unsigned src, midgard_vector_alu_src mod, unsigned dest)
175 {
176 midgard_instruction ins = {
177 .type = TAG_ALU_4,
178 .ssa_args = {
179 .src0 = SSA_UNUSED_1,
180 .src1 = src,
181 .dest = dest,
182 },
183 .alu = {
184 .op = midgard_alu_op_fmov,
185 .reg_mode = midgard_reg_mode_32,
186 .dest_override = midgard_dest_override_none,
187 .mask = 0xFF,
188 .src1 = vector_alu_srco_unsigned(zero_alu_src),
189 .src2 = vector_alu_srco_unsigned(mod)
190 },
191 };
192
193 return ins;
194 }
195
196 /* load/store instructions have both 32-bit and 16-bit variants, depending on
197 * whether we are using vectors composed of highp or mediump. At the moment, we
198 * don't support half-floats -- this requires changes in other parts of the
199 * compiler -- therefore the 16-bit versions are commented out. */
200
201 //M_LOAD(ld_attr_16);
202 M_LOAD(ld_attr_32);
203 //M_LOAD(ld_vary_16);
204 M_LOAD(ld_vary_32);
205 //M_LOAD(ld_uniform_16);
206 M_LOAD(ld_uniform_32);
207 M_LOAD(ld_color_buffer_8);
208 //M_STORE(st_vary_16);
209 M_STORE(st_vary_32);
210 M_STORE(st_cubemap_coords);
211
212 static midgard_instruction
213 v_alu_br_compact_cond(midgard_jmp_writeout_op op, unsigned tag, signed offset, unsigned cond)
214 {
215 midgard_branch_cond branch = {
216 .op = op,
217 .dest_tag = tag,
218 .offset = offset,
219 .cond = cond
220 };
221
222 uint16_t compact;
223 memcpy(&compact, &branch, sizeof(branch));
224
225 midgard_instruction ins = {
226 .type = TAG_ALU_4,
227 .unit = ALU_ENAB_BR_COMPACT,
228 .prepacked_branch = true,
229 .compact_branch = true,
230 .br_compact = compact
231 };
232
233 if (op == midgard_jmp_writeout_op_writeout)
234 ins.writeout = true;
235
236 return ins;
237 }
238
239 static midgard_instruction
240 v_branch(bool conditional, bool invert)
241 {
242 midgard_instruction ins = {
243 .type = TAG_ALU_4,
244 .unit = ALU_ENAB_BRANCH,
245 .compact_branch = true,
246 .branch = {
247 .conditional = conditional,
248 .invert_conditional = invert
249 }
250 };
251
252 return ins;
253 }
254
255 static midgard_branch_extended
256 midgard_create_branch_extended( midgard_condition cond,
257 midgard_jmp_writeout_op op,
258 unsigned dest_tag,
259 signed quadword_offset)
260 {
261 /* For unclear reasons, the condition code is repeated 8 times */
262 uint16_t duplicated_cond =
263 (cond << 14) |
264 (cond << 12) |
265 (cond << 10) |
266 (cond << 8) |
267 (cond << 6) |
268 (cond << 4) |
269 (cond << 2) |
270 (cond << 0);
271
272 midgard_branch_extended branch = {
273 .op = op,
274 .dest_tag = dest_tag,
275 .offset = quadword_offset,
276 .cond = duplicated_cond
277 };
278
279 return branch;
280 }
281
282 static void
283 attach_constants(compiler_context *ctx, midgard_instruction *ins, void *constants, int name)
284 {
285 ins->has_constants = true;
286 memcpy(&ins->constants, constants, 16);
287 }
288
289 static int
290 glsl_type_size(const struct glsl_type *type, bool bindless)
291 {
292 return glsl_count_attribute_slots(type, false);
293 }
294
295 /* Lower fdot2 to a vector multiplication followed by channel addition */
296 static void
297 midgard_nir_lower_fdot2_body(nir_builder *b, nir_alu_instr *alu)
298 {
299 if (alu->op != nir_op_fdot2)
300 return;
301
302 b->cursor = nir_before_instr(&alu->instr);
303
304 nir_ssa_def *src0 = nir_ssa_for_alu_src(b, alu, 0);
305 nir_ssa_def *src1 = nir_ssa_for_alu_src(b, alu, 1);
306
307 nir_ssa_def *product = nir_fmul(b, src0, src1);
308
309 nir_ssa_def *sum = nir_fadd(b,
310 nir_channel(b, product, 0),
311 nir_channel(b, product, 1));
312
313 /* Replace the fdot2 with this sum */
314 nir_ssa_def_rewrite_uses(&alu->dest.dest.ssa, nir_src_for_ssa(sum));
315 }
316
317 static int
318 midgard_nir_sysval_for_intrinsic(nir_intrinsic_instr *instr)
319 {
320 switch (instr->intrinsic) {
321 case nir_intrinsic_load_viewport_scale:
322 return PAN_SYSVAL_VIEWPORT_SCALE;
323 case nir_intrinsic_load_viewport_offset:
324 return PAN_SYSVAL_VIEWPORT_OFFSET;
325 default:
326 return -1;
327 }
328 }
329
330 static void
331 midgard_nir_assign_sysval_body(compiler_context *ctx, nir_instr *instr)
332 {
333 int sysval = -1;
334
335 if (instr->type == nir_instr_type_intrinsic) {
336 nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
337 sysval = midgard_nir_sysval_for_intrinsic(intr);
338 }
339
340 if (sysval < 0)
341 return;
342
343 /* We have a sysval load; check if it's already been assigned */
344
345 if (_mesa_hash_table_u64_search(ctx->sysval_to_id, sysval))
346 return;
347
348 /* It hasn't -- so assign it now! */
349
350 unsigned id = ctx->sysval_count++;
351 _mesa_hash_table_u64_insert(ctx->sysval_to_id, sysval, (void *) ((uintptr_t) id + 1));
352 ctx->sysvals[id] = sysval;
353 }
354
355 static void
356 midgard_nir_assign_sysvals(compiler_context *ctx, nir_shader *shader)
357 {
358 ctx->sysval_count = 0;
359
360 nir_foreach_function(function, shader) {
361 if (!function->impl) continue;
362
363 nir_foreach_block(block, function->impl) {
364 nir_foreach_instr_safe(instr, block) {
365 midgard_nir_assign_sysval_body(ctx, instr);
366 }
367 }
368 }
369 }
370
371 static bool
372 midgard_nir_lower_fdot2(nir_shader *shader)
373 {
374 bool progress = false;
375
376 nir_foreach_function(function, shader) {
377 if (!function->impl) continue;
378
379 nir_builder _b;
380 nir_builder *b = &_b;
381 nir_builder_init(b, function->impl);
382
383 nir_foreach_block(block, function->impl) {
384 nir_foreach_instr_safe(instr, block) {
385 if (instr->type != nir_instr_type_alu) continue;
386
387 nir_alu_instr *alu = nir_instr_as_alu(instr);
388 midgard_nir_lower_fdot2_body(b, alu);
389
390 progress |= true;
391 }
392 }
393
394 nir_metadata_preserve(function->impl, nir_metadata_block_index | nir_metadata_dominance);
395
396 }
397
398 return progress;
399 }
400
401 static void
402 optimise_nir(nir_shader *nir)
403 {
404 bool progress;
405 unsigned lower_flrp =
406 (nir->options->lower_flrp16 ? 16 : 0) |
407 (nir->options->lower_flrp32 ? 32 : 0) |
408 (nir->options->lower_flrp64 ? 64 : 0);
409
410 NIR_PASS(progress, nir, nir_lower_regs_to_ssa);
411 NIR_PASS(progress, nir, midgard_nir_lower_fdot2);
412
413 nir_lower_tex_options lower_tex_options = {
414 .lower_rect = true
415 };
416
417 NIR_PASS(progress, nir, nir_lower_tex, &lower_tex_options);
418
419 do {
420 progress = false;
421
422 NIR_PASS(progress, nir, nir_lower_var_copies);
423 NIR_PASS(progress, nir, nir_lower_vars_to_ssa);
424
425 NIR_PASS(progress, nir, nir_copy_prop);
426 NIR_PASS(progress, nir, nir_opt_dce);
427 NIR_PASS(progress, nir, nir_opt_dead_cf);
428 NIR_PASS(progress, nir, nir_opt_cse);
429 NIR_PASS(progress, nir, nir_opt_peephole_select, 64, false, true);
430 NIR_PASS(progress, nir, nir_opt_algebraic);
431 NIR_PASS(progress, nir, nir_opt_constant_folding);
432
433 if (lower_flrp != 0) {
434 bool lower_flrp_progress = false;
435 NIR_PASS(lower_flrp_progress,
436 nir,
437 nir_lower_flrp,
438 lower_flrp,
439 false /* always_precise */,
440 nir->options->lower_ffma);
441 if (lower_flrp_progress) {
442 NIR_PASS(progress, nir,
443 nir_opt_constant_folding);
444 progress = true;
445 }
446
447 /* Nothing should rematerialize any flrps, so we only
448 * need to do this lowering once.
449 */
450 lower_flrp = 0;
451 }
452
453 NIR_PASS(progress, nir, nir_opt_undef);
454 NIR_PASS(progress, nir, nir_opt_loop_unroll,
455 nir_var_shader_in |
456 nir_var_shader_out |
457 nir_var_function_temp);
458
459 /* TODO: Enable vectorize when merged upstream */
460 // NIR_PASS(progress, nir, nir_opt_vectorize);
461 } while (progress);
462
463 /* Must be run at the end to prevent creation of fsin/fcos ops */
464 NIR_PASS(progress, nir, midgard_nir_scale_trig);
465
466 do {
467 progress = false;
468
469 NIR_PASS(progress, nir, nir_opt_dce);
470 NIR_PASS(progress, nir, nir_opt_algebraic);
471 NIR_PASS(progress, nir, nir_opt_constant_folding);
472 NIR_PASS(progress, nir, nir_copy_prop);
473 } while (progress);
474
475 NIR_PASS(progress, nir, nir_opt_algebraic_late);
476
477 /* We implement booleans as 32-bit 0/~0 */
478 NIR_PASS(progress, nir, nir_lower_bool_to_int32);
479
480 /* Now that booleans are lowered, we can run out late opts */
481 NIR_PASS(progress, nir, midgard_nir_lower_algebraic_late);
482
483 /* Lower mods for float ops only. Integer ops don't support modifiers
484 * (saturate doesn't make sense on integers, neg/abs require dedicated
485 * instructions) */
486
487 NIR_PASS(progress, nir, nir_lower_to_source_mods, nir_lower_float_source_mods);
488 NIR_PASS(progress, nir, nir_copy_prop);
489 NIR_PASS(progress, nir, nir_opt_dce);
490
491 /* Take us out of SSA */
492 NIR_PASS(progress, nir, nir_lower_locals_to_regs);
493 NIR_PASS(progress, nir, nir_convert_from_ssa, true);
494
495 /* We are a vector architecture; write combine where possible */
496 NIR_PASS(progress, nir, nir_move_vec_src_uses_to_dest);
497 NIR_PASS(progress, nir, nir_lower_vec_to_movs);
498
499 NIR_PASS(progress, nir, nir_opt_dce);
500 }
501
502 /* Front-half of aliasing the SSA slots, merely by inserting the flag in the
503 * appropriate hash table. Intentional off-by-one to avoid confusing NULL with
504 * r0. See the comments in compiler_context */
505
506 static void
507 alias_ssa(compiler_context *ctx, int dest, int src)
508 {
509 _mesa_hash_table_u64_insert(ctx->ssa_to_alias, dest + 1, (void *) ((uintptr_t) src + 1));
510 _mesa_set_add(ctx->leftover_ssa_to_alias, (void *) (uintptr_t) (dest + 1));
511 }
512
513 /* ...or undo it, after which the original index will be used (dummy move should be emitted alongside this) */
514
515 static void
516 unalias_ssa(compiler_context *ctx, int dest)
517 {
518 _mesa_hash_table_u64_remove(ctx->ssa_to_alias, dest + 1);
519 /* TODO: Remove from leftover or no? */
520 }
521
522 static void
523 midgard_pin_output(compiler_context *ctx, int index, int reg)
524 {
525 _mesa_hash_table_u64_insert(ctx->ssa_to_register, index + 1, (void *) ((uintptr_t) reg + 1));
526 }
527
528 static bool
529 midgard_is_pinned(compiler_context *ctx, int index)
530 {
531 return _mesa_hash_table_u64_search(ctx->ssa_to_register, index + 1) != NULL;
532 }
533
534 /* Do not actually emit a load; instead, cache the constant for inlining */
535
536 static void
537 emit_load_const(compiler_context *ctx, nir_load_const_instr *instr)
538 {
539 nir_ssa_def def = instr->def;
540
541 float *v = rzalloc_array(NULL, float, 4);
542 nir_const_load_to_arr(v, instr, f32);
543 _mesa_hash_table_u64_insert(ctx->ssa_constants, def.index + 1, v);
544 }
545
546 /* Duplicate bits to convert sane 4-bit writemask to obscure 8-bit format (or
547 * do the inverse) */
548
549 static unsigned
550 expand_writemask(unsigned mask)
551 {
552 unsigned o = 0;
553
554 for (int i = 0; i < 4; ++i)
555 if (mask & (1 << i))
556 o |= (3 << (2 * i));
557
558 return o;
559 }
560
561 static unsigned
562 squeeze_writemask(unsigned mask)
563 {
564 unsigned o = 0;
565
566 for (int i = 0; i < 4; ++i)
567 if (mask & (3 << (2 * i)))
568 o |= (1 << i);
569
570 return o;
571
572 }
573
574 /* Determines effective writemask, taking quirks and expansion into account */
575 static unsigned
576 effective_writemask(midgard_vector_alu *alu)
577 {
578 /* Channel count is off-by-one to fit in two-bits (0 channel makes no
579 * sense) */
580
581 unsigned channel_count = GET_CHANNEL_COUNT(alu_opcode_props[alu->op].props);
582
583 /* If there is a fixed channel count, construct the appropriate mask */
584
585 if (channel_count)
586 return (1 << channel_count) - 1;
587
588 /* Otherwise, just squeeze the existing mask */
589 return squeeze_writemask(alu->mask);
590 }
591
592 static unsigned
593 nir_src_index(compiler_context *ctx, nir_src *src)
594 {
595 if (src->is_ssa)
596 return src->ssa->index;
597 else {
598 assert(!src->reg.indirect);
599 return ctx->func->impl->ssa_alloc + src->reg.reg->index;
600 }
601 }
602
603 static unsigned
604 nir_dest_index(compiler_context *ctx, nir_dest *dst)
605 {
606 if (dst->is_ssa)
607 return dst->ssa.index;
608 else {
609 assert(!dst->reg.indirect);
610 return ctx->func->impl->ssa_alloc + dst->reg.reg->index;
611 }
612 }
613
614 static unsigned
615 nir_alu_src_index(compiler_context *ctx, nir_alu_src *src)
616 {
617 return nir_src_index(ctx, &src->src);
618 }
619
620 static bool
621 nir_is_non_scalar_swizzle(nir_alu_src *src, unsigned nr_components)
622 {
623 unsigned comp = src->swizzle[0];
624
625 for (unsigned c = 1; c < nr_components; ++c) {
626 if (src->swizzle[c] != comp)
627 return true;
628 }
629
630 return false;
631 }
632
633 /* Midgard puts scalar conditionals in r31.w; move an arbitrary source (the
634 * output of a conditional test) into that register */
635
636 static void
637 emit_condition(compiler_context *ctx, nir_src *src, bool for_branch, unsigned component)
638 {
639 int condition = nir_src_index(ctx, src);
640
641 /* Source to swizzle the desired component into w */
642
643 const midgard_vector_alu_src alu_src = {
644 .swizzle = SWIZZLE(component, component, component, component),
645 };
646
647 /* There is no boolean move instruction. Instead, we simulate a move by
648 * ANDing the condition with itself to get it into r31.w */
649
650 midgard_instruction ins = {
651 .type = TAG_ALU_4,
652
653 /* We need to set the conditional as close as possible */
654 .precede_break = true,
655 .unit = for_branch ? UNIT_SMUL : UNIT_SADD,
656
657 .ssa_args = {
658
659 .src0 = condition,
660 .src1 = condition,
661 .dest = SSA_FIXED_REGISTER(31),
662 },
663 .alu = {
664 .op = midgard_alu_op_iand,
665 .reg_mode = midgard_reg_mode_32,
666 .dest_override = midgard_dest_override_none,
667 .mask = (0x3 << 6), /* w */
668 .src1 = vector_alu_srco_unsigned(alu_src),
669 .src2 = vector_alu_srco_unsigned(alu_src)
670 },
671 };
672
673 emit_mir_instruction(ctx, ins);
674 }
675
676 /* Or, for mixed conditions (with csel_v), here's a vector version using all of
677 * r31 instead */
678
679 static void
680 emit_condition_mixed(compiler_context *ctx, nir_alu_src *src, unsigned nr_comp)
681 {
682 int condition = nir_src_index(ctx, &src->src);
683
684 /* Source to swizzle the desired component into w */
685
686 const midgard_vector_alu_src alu_src = {
687 .swizzle = SWIZZLE_FROM_ARRAY(src->swizzle),
688 };
689
690 /* There is no boolean move instruction. Instead, we simulate a move by
691 * ANDing the condition with itself to get it into r31.w */
692
693 midgard_instruction ins = {
694 .type = TAG_ALU_4,
695 .precede_break = true,
696 .ssa_args = {
697 .src0 = condition,
698 .src1 = condition,
699 .dest = SSA_FIXED_REGISTER(31),
700 },
701 .alu = {
702 .op = midgard_alu_op_iand,
703 .reg_mode = midgard_reg_mode_32,
704 .dest_override = midgard_dest_override_none,
705 .mask = expand_writemask((1 << nr_comp) - 1),
706 .src1 = vector_alu_srco_unsigned(alu_src),
707 .src2 = vector_alu_srco_unsigned(alu_src)
708 },
709 };
710
711 emit_mir_instruction(ctx, ins);
712 }
713
714
715
716 /* Likewise, indirect offsets are put in r27.w. TODO: Allow componentwise
717 * pinning to eliminate this move in all known cases */
718
719 static void
720 emit_indirect_offset(compiler_context *ctx, nir_src *src)
721 {
722 int offset = nir_src_index(ctx, src);
723
724 midgard_instruction ins = {
725 .type = TAG_ALU_4,
726 .ssa_args = {
727 .src0 = SSA_UNUSED_1,
728 .src1 = offset,
729 .dest = SSA_FIXED_REGISTER(REGISTER_OFFSET),
730 },
731 .alu = {
732 .op = midgard_alu_op_imov,
733 .reg_mode = midgard_reg_mode_32,
734 .dest_override = midgard_dest_override_none,
735 .mask = (0x3 << 6), /* w */
736 .src1 = vector_alu_srco_unsigned(zero_alu_src),
737 .src2 = vector_alu_srco_unsigned(blank_alu_src_xxxx)
738 },
739 };
740
741 emit_mir_instruction(ctx, ins);
742 }
743
744 #define ALU_CASE(nir, _op) \
745 case nir_op_##nir: \
746 op = midgard_alu_op_##_op; \
747 break;
748 static bool
749 nir_is_fzero_constant(nir_src src)
750 {
751 if (!nir_src_is_const(src))
752 return false;
753
754 for (unsigned c = 0; c < nir_src_num_components(src); ++c) {
755 if (nir_src_comp_as_float(src, c) != 0.0)
756 return false;
757 }
758
759 return true;
760 }
761
762 static void
763 emit_alu(compiler_context *ctx, nir_alu_instr *instr)
764 {
765 bool is_ssa = instr->dest.dest.is_ssa;
766
767 unsigned dest = nir_dest_index(ctx, &instr->dest.dest);
768 unsigned nr_components = is_ssa ? instr->dest.dest.ssa.num_components : instr->dest.dest.reg.reg->num_components;
769 unsigned nr_inputs = nir_op_infos[instr->op].num_inputs;
770
771 /* Most Midgard ALU ops have a 1:1 correspondance to NIR ops; these are
772 * supported. A few do not and are commented for now. Also, there are a
773 * number of NIR ops which Midgard does not support and need to be
774 * lowered, also TODO. This switch block emits the opcode and calling
775 * convention of the Midgard instruction; actual packing is done in
776 * emit_alu below */
777
778 unsigned op;
779
780 switch (instr->op) {
781 ALU_CASE(fadd, fadd);
782 ALU_CASE(fmul, fmul);
783 ALU_CASE(fmin, fmin);
784 ALU_CASE(fmax, fmax);
785 ALU_CASE(imin, imin);
786 ALU_CASE(imax, imax);
787 ALU_CASE(umin, umin);
788 ALU_CASE(umax, umax);
789 ALU_CASE(fmov, fmov);
790 ALU_CASE(ffloor, ffloor);
791 ALU_CASE(fround_even, froundeven);
792 ALU_CASE(ftrunc, ftrunc);
793 ALU_CASE(fceil, fceil);
794 ALU_CASE(fdot3, fdot3);
795 ALU_CASE(fdot4, fdot4);
796 ALU_CASE(iadd, iadd);
797 ALU_CASE(isub, isub);
798 ALU_CASE(imul, imul);
799 ALU_CASE(iabs, iabs);
800 ALU_CASE(imov, imov);
801
802 ALU_CASE(feq32, feq);
803 ALU_CASE(fne32, fne);
804 ALU_CASE(flt32, flt);
805 ALU_CASE(ieq32, ieq);
806 ALU_CASE(ine32, ine);
807 ALU_CASE(ilt32, ilt);
808 ALU_CASE(ult32, ult);
809
810 /* We don't have a native b2f32 instruction. Instead, like many
811 * GPUs, we exploit booleans as 0/~0 for false/true, and
812 * correspondingly AND
813 * by 1.0 to do the type conversion. For the moment, prime us
814 * to emit:
815 *
816 * iand [whatever], #0
817 *
818 * At the end of emit_alu (as MIR), we'll fix-up the constant
819 */
820
821 ALU_CASE(b2f32, iand);
822 ALU_CASE(b2i32, iand);
823
824 /* Likewise, we don't have a dedicated f2b32 instruction, but
825 * we can do a "not equal to 0.0" test. */
826
827 ALU_CASE(f2b32, fne);
828 ALU_CASE(i2b32, ine);
829
830 ALU_CASE(frcp, frcp);
831 ALU_CASE(frsq, frsqrt);
832 ALU_CASE(fsqrt, fsqrt);
833 ALU_CASE(fexp2, fexp2);
834 ALU_CASE(flog2, flog2);
835
836 ALU_CASE(f2i32, f2i);
837 ALU_CASE(f2u32, f2u);
838 ALU_CASE(i2f32, i2f);
839 ALU_CASE(u2f32, u2f);
840
841 ALU_CASE(fsin, fsin);
842 ALU_CASE(fcos, fcos);
843
844 ALU_CASE(iand, iand);
845 ALU_CASE(ior, ior);
846 ALU_CASE(ixor, ixor);
847 ALU_CASE(inot, inand);
848 ALU_CASE(ishl, ishl);
849 ALU_CASE(ishr, iasr);
850 ALU_CASE(ushr, ilsr);
851
852 ALU_CASE(b32all_fequal2, fball_eq);
853 ALU_CASE(b32all_fequal3, fball_eq);
854 ALU_CASE(b32all_fequal4, fball_eq);
855
856 ALU_CASE(b32any_fnequal2, fbany_neq);
857 ALU_CASE(b32any_fnequal3, fbany_neq);
858 ALU_CASE(b32any_fnequal4, fbany_neq);
859
860 ALU_CASE(b32all_iequal2, iball_eq);
861 ALU_CASE(b32all_iequal3, iball_eq);
862 ALU_CASE(b32all_iequal4, iball_eq);
863
864 ALU_CASE(b32any_inequal2, ibany_neq);
865 ALU_CASE(b32any_inequal3, ibany_neq);
866 ALU_CASE(b32any_inequal4, ibany_neq);
867
868 /* For greater-or-equal, we lower to less-or-equal and flip the
869 * arguments */
870
871 case nir_op_fge:
872 case nir_op_fge32:
873 case nir_op_ige32:
874 case nir_op_uge32: {
875 op =
876 instr->op == nir_op_fge ? midgard_alu_op_fle :
877 instr->op == nir_op_fge32 ? midgard_alu_op_fle :
878 instr->op == nir_op_ige32 ? midgard_alu_op_ile :
879 instr->op == nir_op_uge32 ? midgard_alu_op_ule :
880 0;
881
882 /* Swap via temporary */
883 nir_alu_src temp = instr->src[1];
884 instr->src[1] = instr->src[0];
885 instr->src[0] = temp;
886
887 break;
888 }
889
890 case nir_op_b32csel: {
891 /* Midgard features both fcsel and icsel, depending on
892 * the type of the arguments/output. However, as long
893 * as we're careful we can _always_ use icsel and
894 * _never_ need fcsel, since the latter does additional
895 * floating-point-specific processing whereas the
896 * former just moves bits on the wire. It's not obvious
897 * why these are separate opcodes, save for the ability
898 * to do things like sat/pos/abs/neg for free */
899
900 bool mixed = nir_is_non_scalar_swizzle(&instr->src[0], nr_components);
901 op = mixed ? midgard_alu_op_icsel_v : midgard_alu_op_icsel;
902
903 /* csel works as a two-arg in Midgard, since the condition is hardcoded in r31.w */
904 nr_inputs = 2;
905
906 /* Emit the condition into r31 */
907
908 if (mixed)
909 emit_condition_mixed(ctx, &instr->src[0], nr_components);
910 else
911 emit_condition(ctx, &instr->src[0].src, false, instr->src[0].swizzle[0]);
912
913 /* The condition is the first argument; move the other
914 * arguments up one to be a binary instruction for
915 * Midgard */
916
917 memmove(instr->src, instr->src + 1, 2 * sizeof(nir_alu_src));
918 break;
919 }
920
921 default:
922 DBG("Unhandled ALU op %s\n", nir_op_infos[instr->op].name);
923 assert(0);
924 return;
925 }
926
927 /* Midgard can perform certain modifiers on output of an ALU op */
928 midgard_outmod outmod =
929 midgard_is_integer_out_op(op) ? midgard_outmod_int :
930 instr->dest.saturate ? midgard_outmod_sat : midgard_outmod_none;
931
932 /* fmax(a, 0.0) can turn into a .pos modifier as an optimization */
933
934 if (instr->op == nir_op_fmax) {
935 if (nir_is_fzero_constant(instr->src[0].src)) {
936 op = midgard_alu_op_fmov;
937 nr_inputs = 1;
938 outmod = midgard_outmod_pos;
939 instr->src[0] = instr->src[1];
940 } else if (nir_is_fzero_constant(instr->src[1].src)) {
941 op = midgard_alu_op_fmov;
942 nr_inputs = 1;
943 outmod = midgard_outmod_pos;
944 }
945 }
946
947 /* Fetch unit, quirks, etc information */
948 unsigned opcode_props = alu_opcode_props[op].props;
949 bool quirk_flipped_r24 = opcode_props & QUIRK_FLIPPED_R24;
950
951 /* src0 will always exist afaik, but src1 will not for 1-argument
952 * instructions. The latter can only be fetched if the instruction
953 * needs it, or else we may segfault. */
954
955 unsigned src0 = nir_alu_src_index(ctx, &instr->src[0]);
956 unsigned src1 = nr_inputs == 2 ? nir_alu_src_index(ctx, &instr->src[1]) : SSA_UNUSED_0;
957
958 /* Rather than use the instruction generation helpers, we do it
959 * ourselves here to avoid the mess */
960
961 midgard_instruction ins = {
962 .type = TAG_ALU_4,
963 .ssa_args = {
964 .src0 = quirk_flipped_r24 ? SSA_UNUSED_1 : src0,
965 .src1 = quirk_flipped_r24 ? src0 : src1,
966 .dest = dest,
967 }
968 };
969
970 nir_alu_src *nirmods[2] = { NULL };
971
972 if (nr_inputs == 2) {
973 nirmods[0] = &instr->src[0];
974 nirmods[1] = &instr->src[1];
975 } else if (nr_inputs == 1) {
976 nirmods[quirk_flipped_r24] = &instr->src[0];
977 } else {
978 assert(0);
979 }
980
981 bool is_int = midgard_is_integer_op(op);
982
983 midgard_vector_alu alu = {
984 .op = op,
985 .reg_mode = midgard_reg_mode_32,
986 .dest_override = midgard_dest_override_none,
987 .outmod = outmod,
988
989 /* Writemask only valid for non-SSA NIR */
990 .mask = expand_writemask((1 << nr_components) - 1),
991
992 .src1 = vector_alu_srco_unsigned(vector_alu_modifiers(nirmods[0], is_int)),
993 .src2 = vector_alu_srco_unsigned(vector_alu_modifiers(nirmods[1], is_int)),
994 };
995
996 /* Apply writemask if non-SSA, keeping in mind that we can't write to components that don't exist */
997
998 if (!is_ssa)
999 alu.mask &= expand_writemask(instr->dest.write_mask);
1000
1001 ins.alu = alu;
1002
1003 /* Late fixup for emulated instructions */
1004
1005 if (instr->op == nir_op_b2f32 || instr->op == nir_op_b2i32) {
1006 /* Presently, our second argument is an inline #0 constant.
1007 * Switch over to an embedded 1.0 constant (that can't fit
1008 * inline, since we're 32-bit, not 16-bit like the inline
1009 * constants) */
1010
1011 ins.ssa_args.inline_constant = false;
1012 ins.ssa_args.src1 = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1013 ins.has_constants = true;
1014
1015 if (instr->op == nir_op_b2f32) {
1016 ins.constants[0] = 1.0f;
1017 } else {
1018 /* Type pun it into place */
1019 uint32_t one = 0x1;
1020 memcpy(&ins.constants[0], &one, sizeof(uint32_t));
1021 }
1022
1023 ins.alu.src2 = vector_alu_srco_unsigned(blank_alu_src_xxxx);
1024 } else if (instr->op == nir_op_f2b32 || instr->op == nir_op_i2b32) {
1025 ins.ssa_args.inline_constant = false;
1026 ins.ssa_args.src1 = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1027 ins.has_constants = true;
1028 ins.constants[0] = 0.0f;
1029 ins.alu.src2 = vector_alu_srco_unsigned(blank_alu_src_xxxx);
1030 } else if (instr->op == nir_op_inot) {
1031 /* ~b = ~(b & b), so duplicate the source */
1032 ins.ssa_args.src1 = ins.ssa_args.src0;
1033 ins.alu.src2 = ins.alu.src1;
1034 }
1035
1036 if ((opcode_props & UNITS_ALL) == UNIT_VLUT) {
1037 /* To avoid duplicating the lookup tables (probably), true LUT
1038 * instructions can only operate as if they were scalars. Lower
1039 * them here by changing the component. */
1040
1041 uint8_t original_swizzle[4];
1042 memcpy(original_swizzle, nirmods[0]->swizzle, sizeof(nirmods[0]->swizzle));
1043
1044 for (int i = 0; i < nr_components; ++i) {
1045 ins.alu.mask = (0x3) << (2 * i); /* Mask the associated component */
1046
1047 for (int j = 0; j < 4; ++j)
1048 nirmods[0]->swizzle[j] = original_swizzle[i]; /* Pull from the correct component */
1049
1050 ins.alu.src1 = vector_alu_srco_unsigned(vector_alu_modifiers(nirmods[0], is_int));
1051 emit_mir_instruction(ctx, ins);
1052 }
1053 } else {
1054 emit_mir_instruction(ctx, ins);
1055 }
1056 }
1057
1058 #undef ALU_CASE
1059
1060 static void
1061 emit_uniform_read(compiler_context *ctx, unsigned dest, unsigned offset, nir_src *indirect_offset)
1062 {
1063 /* TODO: half-floats */
1064
1065 if (!indirect_offset && offset < ctx->uniform_cutoff) {
1066 /* Fast path: For the first 16 uniforms, direct accesses are
1067 * 0-cycle, since they're just a register fetch in the usual
1068 * case. So, we alias the registers while we're still in
1069 * SSA-space */
1070
1071 int reg_slot = 23 - offset;
1072 alias_ssa(ctx, dest, SSA_FIXED_REGISTER(reg_slot));
1073 } else {
1074 /* Otherwise, read from the 'special' UBO to access
1075 * higher-indexed uniforms, at a performance cost. More
1076 * generally, we're emitting a UBO read instruction. */
1077
1078 midgard_instruction ins = m_ld_uniform_32(dest, offset);
1079
1080 /* TODO: Don't split */
1081 ins.load_store.varying_parameters = (offset & 7) << 7;
1082 ins.load_store.address = offset >> 3;
1083
1084 if (indirect_offset) {
1085 emit_indirect_offset(ctx, indirect_offset);
1086 ins.load_store.unknown = 0x8700; /* xxx: what is this? */
1087 } else {
1088 ins.load_store.unknown = 0x1E00; /* xxx: what is this? */
1089 }
1090
1091 emit_mir_instruction(ctx, ins);
1092 }
1093 }
1094
1095 static void
1096 emit_sysval_read(compiler_context *ctx, nir_intrinsic_instr *instr)
1097 {
1098 /* First, pull out the destination */
1099 unsigned dest = nir_dest_index(ctx, &instr->dest);
1100
1101 /* Now, figure out which uniform this is */
1102 int sysval = midgard_nir_sysval_for_intrinsic(instr);
1103 void *val = _mesa_hash_table_u64_search(ctx->sysval_to_id, sysval);
1104
1105 /* Sysvals are prefix uniforms */
1106 unsigned uniform = ((uintptr_t) val) - 1;
1107
1108 /* Emit the read itself -- this is never indirect */
1109 emit_uniform_read(ctx, dest, uniform, NULL);
1110 }
1111
1112 /* Reads RGBA8888 value from the tilebuffer and converts to a RGBA32F register,
1113 * using scalar ops functional on earlier Midgard generations. Newer Midgard
1114 * generations have faster vectorized reads. This operation is for blend
1115 * shaders in particular; reading the tilebuffer from the fragment shader
1116 * remains an open problem. */
1117
1118 static void
1119 emit_fb_read_blend_scalar(compiler_context *ctx, unsigned reg)
1120 {
1121 midgard_instruction ins = m_ld_color_buffer_8(reg, 0);
1122 ins.load_store.swizzle = 0; /* xxxx */
1123
1124 /* Read each component sequentially */
1125
1126 for (unsigned c = 0; c < 4; ++c) {
1127 ins.load_store.mask = (1 << c);
1128 ins.load_store.unknown = c;
1129 emit_mir_instruction(ctx, ins);
1130 }
1131
1132 /* vadd.u2f hr2, zext(hr2), #0 */
1133
1134 midgard_vector_alu_src alu_src = blank_alu_src;
1135 alu_src.mod = midgard_int_zero_extend;
1136 alu_src.half = true;
1137
1138 midgard_instruction u2f = {
1139 .type = TAG_ALU_4,
1140 .ssa_args = {
1141 .src0 = reg,
1142 .src1 = SSA_UNUSED_0,
1143 .dest = reg,
1144 .inline_constant = true
1145 },
1146 .alu = {
1147 .op = midgard_alu_op_u2f,
1148 .reg_mode = midgard_reg_mode_16,
1149 .dest_override = midgard_dest_override_none,
1150 .mask = 0xF,
1151 .src1 = vector_alu_srco_unsigned(alu_src),
1152 .src2 = vector_alu_srco_unsigned(blank_alu_src),
1153 }
1154 };
1155
1156 emit_mir_instruction(ctx, u2f);
1157
1158 /* vmul.fmul.sat r1, hr2, #0.00392151 */
1159
1160 alu_src.mod = 0;
1161
1162 midgard_instruction fmul = {
1163 .type = TAG_ALU_4,
1164 .inline_constant = _mesa_float_to_half(1.0 / 255.0),
1165 .ssa_args = {
1166 .src0 = reg,
1167 .dest = reg,
1168 .src1 = SSA_UNUSED_0,
1169 .inline_constant = true
1170 },
1171 .alu = {
1172 .op = midgard_alu_op_fmul,
1173 .reg_mode = midgard_reg_mode_32,
1174 .dest_override = midgard_dest_override_none,
1175 .outmod = midgard_outmod_sat,
1176 .mask = 0xFF,
1177 .src1 = vector_alu_srco_unsigned(alu_src),
1178 .src2 = vector_alu_srco_unsigned(blank_alu_src),
1179 }
1180 };
1181
1182 emit_mir_instruction(ctx, fmul);
1183 }
1184
1185 static void
1186 emit_intrinsic(compiler_context *ctx, nir_intrinsic_instr *instr)
1187 {
1188 unsigned offset, reg;
1189
1190 switch (instr->intrinsic) {
1191 case nir_intrinsic_discard_if:
1192 emit_condition(ctx, &instr->src[0], true, COMPONENT_X);
1193
1194 /* fallthrough */
1195
1196 case nir_intrinsic_discard: {
1197 bool conditional = instr->intrinsic == nir_intrinsic_discard_if;
1198 struct midgard_instruction discard = v_branch(conditional, false);
1199 discard.branch.target_type = TARGET_DISCARD;
1200 emit_mir_instruction(ctx, discard);
1201
1202 ctx->can_discard = true;
1203 break;
1204 }
1205
1206 case nir_intrinsic_load_uniform:
1207 case nir_intrinsic_load_input:
1208 offset = nir_intrinsic_base(instr);
1209
1210 bool direct = nir_src_is_const(instr->src[0]);
1211
1212 if (direct) {
1213 offset += nir_src_as_uint(instr->src[0]);
1214 }
1215
1216 reg = nir_dest_index(ctx, &instr->dest);
1217
1218 if (instr->intrinsic == nir_intrinsic_load_uniform && !ctx->is_blend) {
1219 emit_uniform_read(ctx, reg, ctx->sysval_count + offset, !direct ? &instr->src[0] : NULL);
1220 } else if (ctx->stage == MESA_SHADER_FRAGMENT && !ctx->is_blend) {
1221 /* XXX: Half-floats? */
1222 /* TODO: swizzle, mask */
1223
1224 midgard_instruction ins = m_ld_vary_32(reg, offset);
1225
1226 midgard_varying_parameter p = {
1227 .is_varying = 1,
1228 .interpolation = midgard_interp_default,
1229 .flat = /*var->data.interpolation == INTERP_MODE_FLAT*/ 0
1230 };
1231
1232 unsigned u;
1233 memcpy(&u, &p, sizeof(p));
1234 ins.load_store.varying_parameters = u;
1235
1236 if (direct) {
1237 /* We have the offset totally ready */
1238 ins.load_store.unknown = 0x1e9e; /* xxx: what is this? */
1239 } else {
1240 /* We have it partially ready, but we need to
1241 * add in the dynamic index, moved to r27.w */
1242 emit_indirect_offset(ctx, &instr->src[0]);
1243 ins.load_store.unknown = 0x79e; /* xxx: what is this? */
1244 }
1245
1246 emit_mir_instruction(ctx, ins);
1247 } else if (ctx->is_blend) {
1248 /* For blend shaders, load the input color, which is
1249 * preloaded to r0 */
1250
1251 midgard_pin_output(ctx, reg, 0);
1252 } else if (ctx->stage == MESA_SHADER_VERTEX) {
1253 midgard_instruction ins = m_ld_attr_32(reg, offset);
1254 ins.load_store.unknown = 0x1E1E; /* XXX: What is this? */
1255 ins.load_store.mask = (1 << instr->num_components) - 1;
1256 emit_mir_instruction(ctx, ins);
1257 } else {
1258 DBG("Unknown load\n");
1259 assert(0);
1260 }
1261
1262 break;
1263
1264 case nir_intrinsic_load_output:
1265 assert(nir_src_is_const(instr->src[0]));
1266 reg = nir_dest_index(ctx, &instr->dest);
1267
1268 if (ctx->is_blend) {
1269 /* TODO: MRT */
1270 emit_fb_read_blend_scalar(ctx, reg);
1271 } else {
1272 DBG("Unknown output load\n");
1273 assert(0);
1274 }
1275
1276 break;
1277
1278 case nir_intrinsic_load_blend_const_color_rgba: {
1279 assert(ctx->is_blend);
1280 reg = nir_dest_index(ctx, &instr->dest);
1281
1282 /* Blend constants are embedded directly in the shader and
1283 * patched in, so we use some magic routing */
1284
1285 midgard_instruction ins = v_fmov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), blank_alu_src, reg);
1286 ins.has_constants = true;
1287 ins.has_blend_constant = true;
1288 emit_mir_instruction(ctx, ins);
1289 break;
1290 }
1291
1292 case nir_intrinsic_store_output:
1293 assert(nir_src_is_const(instr->src[1]) && "no indirect outputs");
1294
1295 offset = nir_intrinsic_base(instr) + nir_src_as_uint(instr->src[1]);
1296
1297 reg = nir_src_index(ctx, &instr->src[0]);
1298
1299 if (ctx->stage == MESA_SHADER_FRAGMENT) {
1300 /* gl_FragColor is not emitted with load/store
1301 * instructions. Instead, it gets plonked into
1302 * r0 at the end of the shader and we do the
1303 * framebuffer writeout dance. TODO: Defer
1304 * writes */
1305
1306 midgard_instruction move = v_fmov(reg, blank_alu_src, SSA_FIXED_REGISTER(0));
1307 emit_mir_instruction(ctx, move);
1308
1309 //midgard_pin_output(ctx, reg, 0);
1310
1311 /* Save the index we're writing to for later reference
1312 * in the epilogue */
1313
1314 ctx->fragment_output = reg;
1315 } else if (ctx->stage == MESA_SHADER_VERTEX) {
1316 /* Varyings are written into one of two special
1317 * varying register, r26 or r27. The register itself is selected as the register
1318 * in the st_vary instruction, minus the base of 26. E.g. write into r27 and then call st_vary(1)
1319 *
1320 * Normally emitting fmov's is frowned upon,
1321 * but due to unique constraints of
1322 * REGISTER_VARYING, fmov emission + a
1323 * dedicated cleanup pass is the only way to
1324 * guarantee correctness when considering some
1325 * (common) edge cases XXX: FIXME */
1326
1327 /* If this varying corresponds to a constant (why?!),
1328 * emit that now since it won't get picked up by
1329 * hoisting (since there is no corresponding move
1330 * emitted otherwise) */
1331
1332 void *constant_value = _mesa_hash_table_u64_search(ctx->ssa_constants, reg + 1);
1333
1334 if (constant_value) {
1335 /* Special case: emit the varying write
1336 * directly to r26 (looks funny in asm but it's
1337 * fine) and emit the store _now_. Possibly
1338 * slightly slower, but this is a really stupid
1339 * special case anyway (why on earth would you
1340 * have a constant varying? Your own fault for
1341 * slightly worse perf :P) */
1342
1343 midgard_instruction ins = v_fmov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), blank_alu_src, SSA_FIXED_REGISTER(26));
1344 attach_constants(ctx, &ins, constant_value, reg + 1);
1345 emit_mir_instruction(ctx, ins);
1346
1347 midgard_instruction st = m_st_vary_32(SSA_FIXED_REGISTER(0), offset);
1348 st.load_store.unknown = 0x1E9E; /* XXX: What is this? */
1349 emit_mir_instruction(ctx, st);
1350 } else {
1351 /* Do not emit the varying yet -- instead, just mark down that we need to later */
1352
1353 _mesa_hash_table_u64_insert(ctx->ssa_varyings, reg + 1, (void *) ((uintptr_t) (offset + 1)));
1354 }
1355 } else {
1356 DBG("Unknown store\n");
1357 assert(0);
1358 }
1359
1360 break;
1361
1362 case nir_intrinsic_load_alpha_ref_float:
1363 assert(instr->dest.is_ssa);
1364
1365 float ref_value = ctx->alpha_ref;
1366
1367 float *v = ralloc_array(NULL, float, 4);
1368 memcpy(v, &ref_value, sizeof(float));
1369 _mesa_hash_table_u64_insert(ctx->ssa_constants, instr->dest.ssa.index + 1, v);
1370 break;
1371
1372 case nir_intrinsic_load_viewport_scale:
1373 case nir_intrinsic_load_viewport_offset:
1374 emit_sysval_read(ctx, instr);
1375 break;
1376
1377 default:
1378 printf ("Unhandled intrinsic\n");
1379 assert(0);
1380 break;
1381 }
1382 }
1383
1384 static unsigned
1385 midgard_tex_format(enum glsl_sampler_dim dim)
1386 {
1387 switch (dim) {
1388 case GLSL_SAMPLER_DIM_2D:
1389 case GLSL_SAMPLER_DIM_EXTERNAL:
1390 return TEXTURE_2D;
1391
1392 case GLSL_SAMPLER_DIM_3D:
1393 return TEXTURE_3D;
1394
1395 case GLSL_SAMPLER_DIM_CUBE:
1396 return TEXTURE_CUBE;
1397
1398 default:
1399 DBG("Unknown sampler dim type\n");
1400 assert(0);
1401 return 0;
1402 }
1403 }
1404
1405 static void
1406 emit_tex(compiler_context *ctx, nir_tex_instr *instr)
1407 {
1408 /* TODO */
1409 //assert (!instr->sampler);
1410 //assert (!instr->texture_array_size);
1411 assert (instr->op == nir_texop_tex);
1412
1413 /* Allocate registers via a round robin scheme to alternate between the two registers */
1414 int reg = ctx->texture_op_count & 1;
1415 int in_reg = reg, out_reg = reg;
1416
1417 /* Make room for the reg */
1418
1419 if (ctx->texture_index[reg] > -1)
1420 unalias_ssa(ctx, ctx->texture_index[reg]);
1421
1422 int texture_index = instr->texture_index;
1423 int sampler_index = texture_index;
1424
1425 for (unsigned i = 0; i < instr->num_srcs; ++i) {
1426 switch (instr->src[i].src_type) {
1427 case nir_tex_src_coord: {
1428 int index = nir_src_index(ctx, &instr->src[i].src);
1429
1430 midgard_vector_alu_src alu_src = blank_alu_src;
1431
1432 int reg = SSA_FIXED_REGISTER(REGISTER_TEXTURE_BASE + in_reg);
1433
1434 if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) {
1435 /* For cubemaps, we need to load coords into
1436 * special r27, and then use a special ld/st op
1437 * to copy into the texture register */
1438
1439 alu_src.swizzle = SWIZZLE(COMPONENT_X, COMPONENT_Y, COMPONENT_Z, COMPONENT_X);
1440
1441 midgard_instruction move = v_fmov(index, alu_src, SSA_FIXED_REGISTER(27));
1442 emit_mir_instruction(ctx, move);
1443
1444 midgard_instruction st = m_st_cubemap_coords(reg, 0);
1445 st.load_store.unknown = 0x24; /* XXX: What is this? */
1446 st.load_store.mask = 0x3; /* xy? */
1447 st.load_store.swizzle = alu_src.swizzle;
1448 emit_mir_instruction(ctx, st);
1449
1450 } else {
1451 alu_src.swizzle = SWIZZLE(COMPONENT_X, COMPONENT_Y, COMPONENT_X, COMPONENT_X);
1452
1453 midgard_instruction ins = v_fmov(index, alu_src, reg);
1454 emit_mir_instruction(ctx, ins);
1455 }
1456
1457 break;
1458 }
1459
1460 default: {
1461 DBG("Unknown source type\n");
1462 //assert(0);
1463 break;
1464 }
1465 }
1466 }
1467
1468 /* No helper to build texture words -- we do it all here */
1469 midgard_instruction ins = {
1470 .type = TAG_TEXTURE_4,
1471 .texture = {
1472 .op = TEXTURE_OP_NORMAL,
1473 .format = midgard_tex_format(instr->sampler_dim),
1474 .texture_handle = texture_index,
1475 .sampler_handle = sampler_index,
1476
1477 /* TODO: Don't force xyzw */
1478 .swizzle = SWIZZLE(COMPONENT_X, COMPONENT_Y, COMPONENT_Z, COMPONENT_W),
1479 .mask = 0xF,
1480
1481 /* TODO: half */
1482 //.in_reg_full = 1,
1483 .out_full = 1,
1484
1485 .filter = 1,
1486
1487 /* Always 1 */
1488 .unknown7 = 1,
1489
1490 /* Assume we can continue; hint it out later */
1491 .cont = 1,
1492 }
1493 };
1494
1495 /* Set registers to read and write from the same place */
1496 ins.texture.in_reg_select = in_reg;
1497 ins.texture.out_reg_select = out_reg;
1498
1499 /* TODO: Dynamic swizzle input selection, half-swizzles? */
1500 if (instr->sampler_dim == GLSL_SAMPLER_DIM_3D) {
1501 ins.texture.in_reg_swizzle_right = COMPONENT_X;
1502 ins.texture.in_reg_swizzle_left = COMPONENT_Y;
1503 //ins.texture.in_reg_swizzle_third = COMPONENT_Z;
1504 } else {
1505 ins.texture.in_reg_swizzle_left = COMPONENT_X;
1506 ins.texture.in_reg_swizzle_right = COMPONENT_Y;
1507 //ins.texture.in_reg_swizzle_third = COMPONENT_X;
1508 }
1509
1510 emit_mir_instruction(ctx, ins);
1511
1512 /* Simultaneously alias the destination and emit a move for it. The move will be eliminated if possible */
1513
1514 int o_reg = REGISTER_TEXTURE_BASE + out_reg, o_index = nir_dest_index(ctx, &instr->dest);
1515 alias_ssa(ctx, o_index, SSA_FIXED_REGISTER(o_reg));
1516 ctx->texture_index[reg] = o_index;
1517
1518 midgard_instruction ins2 = v_fmov(SSA_FIXED_REGISTER(o_reg), blank_alu_src, o_index);
1519 emit_mir_instruction(ctx, ins2);
1520
1521 /* Used for .cont and .last hinting */
1522 ctx->texture_op_count++;
1523 }
1524
1525 static void
1526 emit_jump(compiler_context *ctx, nir_jump_instr *instr)
1527 {
1528 switch (instr->type) {
1529 case nir_jump_break: {
1530 /* Emit a branch out of the loop */
1531 struct midgard_instruction br = v_branch(false, false);
1532 br.branch.target_type = TARGET_BREAK;
1533 br.branch.target_break = ctx->current_loop_depth;
1534 emit_mir_instruction(ctx, br);
1535
1536 DBG("break..\n");
1537 break;
1538 }
1539
1540 default:
1541 DBG("Unknown jump type %d\n", instr->type);
1542 break;
1543 }
1544 }
1545
1546 static void
1547 emit_instr(compiler_context *ctx, struct nir_instr *instr)
1548 {
1549 switch (instr->type) {
1550 case nir_instr_type_load_const:
1551 emit_load_const(ctx, nir_instr_as_load_const(instr));
1552 break;
1553
1554 case nir_instr_type_intrinsic:
1555 emit_intrinsic(ctx, nir_instr_as_intrinsic(instr));
1556 break;
1557
1558 case nir_instr_type_alu:
1559 emit_alu(ctx, nir_instr_as_alu(instr));
1560 break;
1561
1562 case nir_instr_type_tex:
1563 emit_tex(ctx, nir_instr_as_tex(instr));
1564 break;
1565
1566 case nir_instr_type_jump:
1567 emit_jump(ctx, nir_instr_as_jump(instr));
1568 break;
1569
1570 case nir_instr_type_ssa_undef:
1571 /* Spurious */
1572 break;
1573
1574 default:
1575 DBG("Unhandled instruction type\n");
1576 break;
1577 }
1578 }
1579
1580 /* Midgard IR only knows vector ALU types, but we sometimes need to actually
1581 * use scalar ALU instructions, for functional or performance reasons. To do
1582 * this, we just demote vector ALU payloads to scalar. */
1583
1584 static int
1585 component_from_mask(unsigned mask)
1586 {
1587 for (int c = 0; c < 4; ++c) {
1588 if (mask & (3 << (2 * c)))
1589 return c;
1590 }
1591
1592 assert(0);
1593 return 0;
1594 }
1595
1596 static bool
1597 is_single_component_mask(unsigned mask)
1598 {
1599 int components = 0;
1600
1601 for (int c = 0; c < 4; ++c)
1602 if (mask & (3 << (2 * c)))
1603 components++;
1604
1605 return components == 1;
1606 }
1607
1608 /* Create a mask of accessed components from a swizzle to figure out vector
1609 * dependencies */
1610
1611 static unsigned
1612 swizzle_to_access_mask(unsigned swizzle)
1613 {
1614 unsigned component_mask = 0;
1615
1616 for (int i = 0; i < 4; ++i) {
1617 unsigned c = (swizzle >> (2 * i)) & 3;
1618 component_mask |= (1 << c);
1619 }
1620
1621 return component_mask;
1622 }
1623
1624 static unsigned
1625 vector_to_scalar_source(unsigned u, bool is_int)
1626 {
1627 midgard_vector_alu_src v;
1628 memcpy(&v, &u, sizeof(v));
1629
1630 /* TODO: Integers */
1631
1632 midgard_scalar_alu_src s = {
1633 .full = !v.half,
1634 .component = (v.swizzle & 3) << 1
1635 };
1636
1637 if (is_int) {
1638 /* TODO */
1639 } else {
1640 s.abs = v.mod & MIDGARD_FLOAT_MOD_ABS;
1641 s.negate = v.mod & MIDGARD_FLOAT_MOD_NEG;
1642 }
1643
1644 unsigned o;
1645 memcpy(&o, &s, sizeof(s));
1646
1647 return o & ((1 << 6) - 1);
1648 }
1649
1650 static midgard_scalar_alu
1651 vector_to_scalar_alu(midgard_vector_alu v, midgard_instruction *ins)
1652 {
1653 bool is_int = midgard_is_integer_op(v.op);
1654
1655 /* The output component is from the mask */
1656 midgard_scalar_alu s = {
1657 .op = v.op,
1658 .src1 = vector_to_scalar_source(v.src1, is_int),
1659 .src2 = vector_to_scalar_source(v.src2, is_int),
1660 .unknown = 0,
1661 .outmod = v.outmod,
1662 .output_full = 1, /* TODO: Half */
1663 .output_component = component_from_mask(v.mask) << 1,
1664 };
1665
1666 /* Inline constant is passed along rather than trying to extract it
1667 * from v */
1668
1669 if (ins->ssa_args.inline_constant) {
1670 uint16_t imm = 0;
1671 int lower_11 = ins->inline_constant & ((1 << 12) - 1);
1672 imm |= (lower_11 >> 9) & 3;
1673 imm |= (lower_11 >> 6) & 4;
1674 imm |= (lower_11 >> 2) & 0x38;
1675 imm |= (lower_11 & 63) << 6;
1676
1677 s.src2 = imm;
1678 }
1679
1680 return s;
1681 }
1682
1683 /* Midgard prefetches instruction types, so during emission we need to
1684 * lookahead too. Unless this is the last instruction, in which we return 1. Or
1685 * if this is the second to last and the last is an ALU, then it's also 1... */
1686
1687 #define IS_ALU(tag) (tag == TAG_ALU_4 || tag == TAG_ALU_8 || \
1688 tag == TAG_ALU_12 || tag == TAG_ALU_16)
1689
1690 #define EMIT_AND_COUNT(type, val) util_dynarray_append(emission, type, val); \
1691 bytes_emitted += sizeof(type)
1692
1693 static void
1694 emit_binary_vector_instruction(midgard_instruction *ains,
1695 uint16_t *register_words, int *register_words_count,
1696 uint64_t *body_words, size_t *body_size, int *body_words_count,
1697 size_t *bytes_emitted)
1698 {
1699 memcpy(&register_words[(*register_words_count)++], &ains->registers, sizeof(ains->registers));
1700 *bytes_emitted += sizeof(midgard_reg_info);
1701
1702 body_size[*body_words_count] = sizeof(midgard_vector_alu);
1703 memcpy(&body_words[(*body_words_count)++], &ains->alu, sizeof(ains->alu));
1704 *bytes_emitted += sizeof(midgard_vector_alu);
1705 }
1706
1707 /* Checks for an SSA data hazard between two adjacent instructions, keeping in
1708 * mind that we are a vector architecture and we can write to different
1709 * components simultaneously */
1710
1711 static bool
1712 can_run_concurrent_ssa(midgard_instruction *first, midgard_instruction *second)
1713 {
1714 /* Each instruction reads some registers and writes to a register. See
1715 * where the first writes */
1716
1717 /* Figure out where exactly we wrote to */
1718 int source = first->ssa_args.dest;
1719 int source_mask = first->type == TAG_ALU_4 ? squeeze_writemask(first->alu.mask) : 0xF;
1720
1721 /* As long as the second doesn't read from the first, we're okay */
1722 if (second->ssa_args.src0 == source) {
1723 if (first->type == TAG_ALU_4) {
1724 /* Figure out which components we just read from */
1725
1726 int q = second->alu.src1;
1727 midgard_vector_alu_src *m = (midgard_vector_alu_src *) &q;
1728
1729 /* Check if there are components in common, and fail if so */
1730 if (swizzle_to_access_mask(m->swizzle) & source_mask)
1731 return false;
1732 } else
1733 return false;
1734
1735 }
1736
1737 if (second->ssa_args.src1 == source)
1738 return false;
1739
1740 /* Otherwise, it's safe in that regard. Another data hazard is both
1741 * writing to the same place, of course */
1742
1743 if (second->ssa_args.dest == source) {
1744 /* ...but only if the components overlap */
1745 int dest_mask = second->type == TAG_ALU_4 ? squeeze_writemask(second->alu.mask) : 0xF;
1746
1747 if (dest_mask & source_mask)
1748 return false;
1749 }
1750
1751 /* ...That's it */
1752 return true;
1753 }
1754
1755 static bool
1756 midgard_has_hazard(
1757 midgard_instruction **segment, unsigned segment_size,
1758 midgard_instruction *ains)
1759 {
1760 for (int s = 0; s < segment_size; ++s)
1761 if (!can_run_concurrent_ssa(segment[s], ains))
1762 return true;
1763
1764 return false;
1765
1766
1767 }
1768
1769 /* Schedules, but does not emit, a single basic block. After scheduling, the
1770 * final tag and size of the block are known, which are necessary for branching
1771 * */
1772
1773 static midgard_bundle
1774 schedule_bundle(compiler_context *ctx, midgard_block *block, midgard_instruction *ins, int *skip)
1775 {
1776 int instructions_emitted = 0, instructions_consumed = -1;
1777 midgard_bundle bundle = { 0 };
1778
1779 uint8_t tag = ins->type;
1780
1781 /* Default to the instruction's tag */
1782 bundle.tag = tag;
1783
1784 switch (ins->type) {
1785 case TAG_ALU_4: {
1786 uint32_t control = 0;
1787 size_t bytes_emitted = sizeof(control);
1788
1789 /* TODO: Constant combining */
1790 int index = 0, last_unit = 0;
1791
1792 /* Previous instructions, for the purpose of parallelism */
1793 midgard_instruction *segment[4] = {0};
1794 int segment_size = 0;
1795
1796 instructions_emitted = -1;
1797 midgard_instruction *pins = ins;
1798
1799 for (;;) {
1800 midgard_instruction *ains = pins;
1801
1802 /* Advance instruction pointer */
1803 if (index) {
1804 ains = mir_next_op(pins);
1805 pins = ains;
1806 }
1807
1808 /* Out-of-work condition */
1809 if ((struct list_head *) ains == &block->instructions)
1810 break;
1811
1812 /* Ensure that the chain can continue */
1813 if (ains->type != TAG_ALU_4) break;
1814
1815 /* If there's already something in the bundle and we
1816 * have weird scheduler constraints, break now */
1817 if (ains->precede_break && index) break;
1818
1819 /* According to the presentation "The ARM
1820 * Mali-T880 Mobile GPU" from HotChips 27,
1821 * there are two pipeline stages. Branching
1822 * position determined experimentally. Lines
1823 * are executed in parallel:
1824 *
1825 * [ VMUL ] [ SADD ]
1826 * [ VADD ] [ SMUL ] [ LUT ] [ BRANCH ]
1827 *
1828 * Verify that there are no ordering dependencies here.
1829 *
1830 * TODO: Allow for parallelism!!!
1831 */
1832
1833 /* Pick a unit for it if it doesn't force a particular unit */
1834
1835 int unit = ains->unit;
1836
1837 if (!unit) {
1838 int op = ains->alu.op;
1839 int units = alu_opcode_props[op].props;
1840
1841 /* TODO: Promotion of scalars to vectors */
1842 int vector = ((!is_single_component_mask(ains->alu.mask)) || ((units & UNITS_SCALAR) == 0)) && (units & UNITS_ANY_VECTOR);
1843
1844 if (!vector)
1845 assert(units & UNITS_SCALAR);
1846
1847 if (vector) {
1848 if (last_unit >= UNIT_VADD) {
1849 if (units & UNIT_VLUT)
1850 unit = UNIT_VLUT;
1851 else
1852 break;
1853 } else {
1854 if ((units & UNIT_VMUL) && !(control & UNIT_VMUL))
1855 unit = UNIT_VMUL;
1856 else if ((units & UNIT_VADD) && !(control & UNIT_VADD))
1857 unit = UNIT_VADD;
1858 else if (units & UNIT_VLUT)
1859 unit = UNIT_VLUT;
1860 else
1861 break;
1862 }
1863 } else {
1864 if (last_unit >= UNIT_VADD) {
1865 if ((units & UNIT_SMUL) && !(control & UNIT_SMUL))
1866 unit = UNIT_SMUL;
1867 else if (units & UNIT_VLUT)
1868 unit = UNIT_VLUT;
1869 else
1870 break;
1871 } else {
1872 if ((units & UNIT_SADD) && !(control & UNIT_SADD) && !midgard_has_hazard(segment, segment_size, ains))
1873 unit = UNIT_SADD;
1874 else if (units & UNIT_SMUL)
1875 unit = ((units & UNIT_VMUL) && !(control & UNIT_VMUL)) ? UNIT_VMUL : UNIT_SMUL;
1876 else if ((units & UNIT_VADD) && !(control & UNIT_VADD))
1877 unit = UNIT_VADD;
1878 else
1879 break;
1880 }
1881 }
1882
1883 assert(unit & units);
1884 }
1885
1886 /* Late unit check, this time for encoding (not parallelism) */
1887 if (unit <= last_unit) break;
1888
1889 /* Clear the segment */
1890 if (last_unit < UNIT_VADD && unit >= UNIT_VADD)
1891 segment_size = 0;
1892
1893 if (midgard_has_hazard(segment, segment_size, ains))
1894 break;
1895
1896 /* We're good to go -- emit the instruction */
1897 ains->unit = unit;
1898
1899 segment[segment_size++] = ains;
1900
1901 /* Only one set of embedded constants per
1902 * bundle possible; if we have more, we must
1903 * break the chain early, unfortunately */
1904
1905 if (ains->has_constants) {
1906 if (bundle.has_embedded_constants) {
1907 /* The blend constant needs to be
1908 * alone, since it conflicts with
1909 * everything by definition*/
1910
1911 if (ains->has_blend_constant || bundle.has_blend_constant)
1912 break;
1913
1914 /* ...but if there are already
1915 * constants but these are the
1916 * *same* constants, we let it
1917 * through */
1918
1919 if (memcmp(bundle.constants, ains->constants, sizeof(bundle.constants)))
1920 break;
1921 } else {
1922 bundle.has_embedded_constants = true;
1923 memcpy(bundle.constants, ains->constants, sizeof(bundle.constants));
1924
1925 /* If this is a blend shader special constant, track it for patching */
1926 bundle.has_blend_constant |= ains->has_blend_constant;
1927 }
1928 }
1929
1930 if (ains->unit & UNITS_ANY_VECTOR) {
1931 emit_binary_vector_instruction(ains, bundle.register_words,
1932 &bundle.register_words_count, bundle.body_words,
1933 bundle.body_size, &bundle.body_words_count, &bytes_emitted);
1934 } else if (ains->compact_branch) {
1935 /* All of r0 has to be written out
1936 * along with the branch writeout.
1937 * (slow!) */
1938
1939 if (ains->writeout) {
1940 if (index == 0) {
1941 midgard_instruction ins = v_fmov(0, blank_alu_src, SSA_FIXED_REGISTER(0));
1942 ins.unit = UNIT_VMUL;
1943
1944 control |= ins.unit;
1945
1946 emit_binary_vector_instruction(&ins, bundle.register_words,
1947 &bundle.register_words_count, bundle.body_words,
1948 bundle.body_size, &bundle.body_words_count, &bytes_emitted);
1949 } else {
1950 /* Analyse the group to see if r0 is written in full, on-time, without hanging dependencies*/
1951 bool written_late = false;
1952 bool components[4] = { 0 };
1953 uint16_t register_dep_mask = 0;
1954 uint16_t written_mask = 0;
1955
1956 midgard_instruction *qins = ins;
1957 for (int t = 0; t < index; ++t) {
1958 if (qins->registers.out_reg != 0) {
1959 /* Mark down writes */
1960
1961 written_mask |= (1 << qins->registers.out_reg);
1962 } else {
1963 /* Mark down the register dependencies for errata check */
1964
1965 if (qins->registers.src1_reg < 16)
1966 register_dep_mask |= (1 << qins->registers.src1_reg);
1967
1968 if (qins->registers.src2_reg < 16)
1969 register_dep_mask |= (1 << qins->registers.src2_reg);
1970
1971 int mask = qins->alu.mask;
1972
1973 for (int c = 0; c < 4; ++c)
1974 if (mask & (0x3 << (2 * c)))
1975 components[c] = true;
1976
1977 /* ..but if the writeout is too late, we have to break up anyway... for some reason */
1978
1979 if (qins->unit == UNIT_VLUT)
1980 written_late = true;
1981 }
1982
1983 /* Advance instruction pointer */
1984 qins = mir_next_op(qins);
1985 }
1986
1987
1988 /* ERRATA (?): In a bundle ending in a fragment writeout, the register dependencies of r0 cannot be written within this bundle (discovered in -bshading:shading=phong) */
1989 if (register_dep_mask & written_mask) {
1990 DBG("ERRATA WORKAROUND: Breakup for writeout dependency masks %X vs %X (common %X)\n", register_dep_mask, written_mask, register_dep_mask & written_mask);
1991 break;
1992 }
1993
1994 if (written_late)
1995 break;
1996
1997 /* If even a single component is not written, break it up (conservative check). */
1998 bool breakup = false;
1999
2000 for (int c = 0; c < 4; ++c)
2001 if (!components[c])
2002 breakup = true;
2003
2004 if (breakup)
2005 break;
2006
2007 /* Otherwise, we're free to proceed */
2008 }
2009 }
2010
2011 if (ains->unit == ALU_ENAB_BRANCH) {
2012 bundle.body_size[bundle.body_words_count] = sizeof(midgard_branch_extended);
2013 memcpy(&bundle.body_words[bundle.body_words_count++], &ains->branch_extended, sizeof(midgard_branch_extended));
2014 bytes_emitted += sizeof(midgard_branch_extended);
2015 } else {
2016 bundle.body_size[bundle.body_words_count] = sizeof(ains->br_compact);
2017 memcpy(&bundle.body_words[bundle.body_words_count++], &ains->br_compact, sizeof(ains->br_compact));
2018 bytes_emitted += sizeof(ains->br_compact);
2019 }
2020 } else {
2021 memcpy(&bundle.register_words[bundle.register_words_count++], &ains->registers, sizeof(ains->registers));
2022 bytes_emitted += sizeof(midgard_reg_info);
2023
2024 bundle.body_size[bundle.body_words_count] = sizeof(midgard_scalar_alu);
2025 bundle.body_words_count++;
2026 bytes_emitted += sizeof(midgard_scalar_alu);
2027 }
2028
2029 /* Defer marking until after writing to allow for break */
2030 control |= ains->unit;
2031 last_unit = ains->unit;
2032 ++instructions_emitted;
2033 ++index;
2034 }
2035
2036 /* Bubble up the number of instructions for skipping */
2037 instructions_consumed = index - 1;
2038
2039 int padding = 0;
2040
2041 /* Pad ALU op to nearest word */
2042
2043 if (bytes_emitted & 15) {
2044 padding = 16 - (bytes_emitted & 15);
2045 bytes_emitted += padding;
2046 }
2047
2048 /* Constants must always be quadwords */
2049 if (bundle.has_embedded_constants)
2050 bytes_emitted += 16;
2051
2052 /* Size ALU instruction for tag */
2053 bundle.tag = (TAG_ALU_4) + (bytes_emitted / 16) - 1;
2054 bundle.padding = padding;
2055 bundle.control = bundle.tag | control;
2056
2057 break;
2058 }
2059
2060 case TAG_LOAD_STORE_4: {
2061 /* Load store instructions have two words at once. If
2062 * we only have one queued up, we need to NOP pad.
2063 * Otherwise, we store both in succession to save space
2064 * and cycles -- letting them go in parallel -- skip
2065 * the next. The usefulness of this optimisation is
2066 * greatly dependent on the quality of the instruction
2067 * scheduler.
2068 */
2069
2070 midgard_instruction *next_op = mir_next_op(ins);
2071
2072 if ((struct list_head *) next_op != &block->instructions && next_op->type == TAG_LOAD_STORE_4) {
2073 /* As the two operate concurrently, make sure
2074 * they are not dependent */
2075
2076 if (can_run_concurrent_ssa(ins, next_op) || true) {
2077 /* Skip ahead, since it's redundant with the pair */
2078 instructions_consumed = 1 + (instructions_emitted++);
2079 }
2080 }
2081
2082 break;
2083 }
2084
2085 default:
2086 /* Texture ops default to single-op-per-bundle scheduling */
2087 break;
2088 }
2089
2090 /* Copy the instructions into the bundle */
2091 bundle.instruction_count = instructions_emitted + 1;
2092
2093 int used_idx = 0;
2094
2095 midgard_instruction *uins = ins;
2096 for (int i = 0; used_idx < bundle.instruction_count; ++i) {
2097 bundle.instructions[used_idx++] = *uins;
2098 uins = mir_next_op(uins);
2099 }
2100
2101 *skip = (instructions_consumed == -1) ? instructions_emitted : instructions_consumed;
2102
2103 return bundle;
2104 }
2105
2106 static int
2107 quadword_size(int tag)
2108 {
2109 switch (tag) {
2110 case TAG_ALU_4:
2111 return 1;
2112
2113 case TAG_ALU_8:
2114 return 2;
2115
2116 case TAG_ALU_12:
2117 return 3;
2118
2119 case TAG_ALU_16:
2120 return 4;
2121
2122 case TAG_LOAD_STORE_4:
2123 return 1;
2124
2125 case TAG_TEXTURE_4:
2126 return 1;
2127
2128 default:
2129 assert(0);
2130 return 0;
2131 }
2132 }
2133
2134 /* Schedule a single block by iterating its instruction to create bundles.
2135 * While we go, tally about the bundle sizes to compute the block size. */
2136
2137 static void
2138 schedule_block(compiler_context *ctx, midgard_block *block)
2139 {
2140 util_dynarray_init(&block->bundles, NULL);
2141
2142 block->quadword_count = 0;
2143
2144 mir_foreach_instr_in_block(block, ins) {
2145 int skip;
2146 midgard_bundle bundle = schedule_bundle(ctx, block, ins, &skip);
2147 util_dynarray_append(&block->bundles, midgard_bundle, bundle);
2148
2149 if (bundle.has_blend_constant) {
2150 /* TODO: Multiblock? */
2151 int quadwords_within_block = block->quadword_count + quadword_size(bundle.tag) - 1;
2152 ctx->blend_constant_offset = quadwords_within_block * 0x10;
2153 }
2154
2155 while(skip--)
2156 ins = mir_next_op(ins);
2157
2158 block->quadword_count += quadword_size(bundle.tag);
2159 }
2160
2161 block->is_scheduled = true;
2162 }
2163
2164 static void
2165 schedule_program(compiler_context *ctx)
2166 {
2167 /* We run RA prior to scheduling */
2168 struct ra_graph *g = allocate_registers(ctx);
2169 install_registers(ctx, g);
2170
2171 mir_foreach_block(ctx, block) {
2172 schedule_block(ctx, block);
2173 }
2174 }
2175
2176 /* After everything is scheduled, emit whole bundles at a time */
2177
2178 static void
2179 emit_binary_bundle(compiler_context *ctx, midgard_bundle *bundle, struct util_dynarray *emission, int next_tag)
2180 {
2181 int lookahead = next_tag << 4;
2182
2183 switch (bundle->tag) {
2184 case TAG_ALU_4:
2185 case TAG_ALU_8:
2186 case TAG_ALU_12:
2187 case TAG_ALU_16: {
2188 /* Actually emit each component */
2189 util_dynarray_append(emission, uint32_t, bundle->control | lookahead);
2190
2191 for (int i = 0; i < bundle->register_words_count; ++i)
2192 util_dynarray_append(emission, uint16_t, bundle->register_words[i]);
2193
2194 /* Emit body words based on the instructions bundled */
2195 for (int i = 0; i < bundle->instruction_count; ++i) {
2196 midgard_instruction *ins = &bundle->instructions[i];
2197
2198 if (ins->unit & UNITS_ANY_VECTOR) {
2199 memcpy(util_dynarray_grow(emission, sizeof(midgard_vector_alu)), &ins->alu, sizeof(midgard_vector_alu));
2200 } else if (ins->compact_branch) {
2201 /* Dummy move, XXX DRY */
2202 if ((i == 0) && ins->writeout) {
2203 midgard_instruction ins = v_fmov(0, blank_alu_src, SSA_FIXED_REGISTER(0));
2204 memcpy(util_dynarray_grow(emission, sizeof(midgard_vector_alu)), &ins.alu, sizeof(midgard_vector_alu));
2205 }
2206
2207 if (ins->unit == ALU_ENAB_BR_COMPACT) {
2208 memcpy(util_dynarray_grow(emission, sizeof(ins->br_compact)), &ins->br_compact, sizeof(ins->br_compact));
2209 } else {
2210 memcpy(util_dynarray_grow(emission, sizeof(ins->branch_extended)), &ins->branch_extended, sizeof(ins->branch_extended));
2211 }
2212 } else {
2213 /* Scalar */
2214 midgard_scalar_alu scalarised = vector_to_scalar_alu(ins->alu, ins);
2215 memcpy(util_dynarray_grow(emission, sizeof(scalarised)), &scalarised, sizeof(scalarised));
2216 }
2217 }
2218
2219 /* Emit padding (all zero) */
2220 memset(util_dynarray_grow(emission, bundle->padding), 0, bundle->padding);
2221
2222 /* Tack on constants */
2223
2224 if (bundle->has_embedded_constants) {
2225 util_dynarray_append(emission, float, bundle->constants[0]);
2226 util_dynarray_append(emission, float, bundle->constants[1]);
2227 util_dynarray_append(emission, float, bundle->constants[2]);
2228 util_dynarray_append(emission, float, bundle->constants[3]);
2229 }
2230
2231 break;
2232 }
2233
2234 case TAG_LOAD_STORE_4: {
2235 /* One or two composing instructions */
2236
2237 uint64_t current64, next64 = LDST_NOP;
2238
2239 memcpy(&current64, &bundle->instructions[0].load_store, sizeof(current64));
2240
2241 if (bundle->instruction_count == 2)
2242 memcpy(&next64, &bundle->instructions[1].load_store, sizeof(next64));
2243
2244 midgard_load_store instruction = {
2245 .type = bundle->tag,
2246 .next_type = next_tag,
2247 .word1 = current64,
2248 .word2 = next64
2249 };
2250
2251 util_dynarray_append(emission, midgard_load_store, instruction);
2252
2253 break;
2254 }
2255
2256 case TAG_TEXTURE_4: {
2257 /* Texture instructions are easy, since there is no
2258 * pipelining nor VLIW to worry about. We may need to set the .last flag */
2259
2260 midgard_instruction *ins = &bundle->instructions[0];
2261
2262 ins->texture.type = TAG_TEXTURE_4;
2263 ins->texture.next_type = next_tag;
2264
2265 ctx->texture_op_count--;
2266
2267 if (!ctx->texture_op_count) {
2268 ins->texture.cont = 0;
2269 ins->texture.last = 1;
2270 }
2271
2272 util_dynarray_append(emission, midgard_texture_word, ins->texture);
2273 break;
2274 }
2275
2276 default:
2277 DBG("Unknown midgard instruction type\n");
2278 assert(0);
2279 break;
2280 }
2281 }
2282
2283
2284 /* ALU instructions can inline or embed constants, which decreases register
2285 * pressure and saves space. */
2286
2287 #define CONDITIONAL_ATTACH(src) { \
2288 void *entry = _mesa_hash_table_u64_search(ctx->ssa_constants, alu->ssa_args.src + 1); \
2289 \
2290 if (entry) { \
2291 attach_constants(ctx, alu, entry, alu->ssa_args.src + 1); \
2292 alu->ssa_args.src = SSA_FIXED_REGISTER(REGISTER_CONSTANT); \
2293 } \
2294 }
2295
2296 static void
2297 inline_alu_constants(compiler_context *ctx)
2298 {
2299 mir_foreach_instr(ctx, alu) {
2300 /* Other instructions cannot inline constants */
2301 if (alu->type != TAG_ALU_4) continue;
2302
2303 /* If there is already a constant here, we can do nothing */
2304 if (alu->has_constants) continue;
2305
2306 /* It makes no sense to inline constants on a branch */
2307 if (alu->compact_branch || alu->prepacked_branch) continue;
2308
2309 CONDITIONAL_ATTACH(src0);
2310
2311 if (!alu->has_constants) {
2312 CONDITIONAL_ATTACH(src1)
2313 } else if (!alu->inline_constant) {
2314 /* Corner case: _two_ vec4 constants, for instance with a
2315 * csel. For this case, we can only use a constant
2316 * register for one, we'll have to emit a move for the
2317 * other. Note, if both arguments are constants, then
2318 * necessarily neither argument depends on the value of
2319 * any particular register. As the destination register
2320 * will be wiped, that means we can spill the constant
2321 * to the destination register.
2322 */
2323
2324 void *entry = _mesa_hash_table_u64_search(ctx->ssa_constants, alu->ssa_args.src1 + 1);
2325 unsigned scratch = alu->ssa_args.dest;
2326
2327 if (entry) {
2328 midgard_instruction ins = v_fmov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), blank_alu_src, scratch);
2329 attach_constants(ctx, &ins, entry, alu->ssa_args.src1 + 1);
2330
2331 /* Force a break XXX Defer r31 writes */
2332 ins.unit = UNIT_VLUT;
2333
2334 /* Set the source */
2335 alu->ssa_args.src1 = scratch;
2336
2337 /* Inject us -before- the last instruction which set r31 */
2338 mir_insert_instruction_before(mir_prev_op(alu), ins);
2339 }
2340 }
2341 }
2342 }
2343
2344 /* Midgard supports two types of constants, embedded constants (128-bit) and
2345 * inline constants (16-bit). Sometimes, especially with scalar ops, embedded
2346 * constants can be demoted to inline constants, for space savings and
2347 * sometimes a performance boost */
2348
2349 static void
2350 embedded_to_inline_constant(compiler_context *ctx)
2351 {
2352 mir_foreach_instr(ctx, ins) {
2353 if (!ins->has_constants) continue;
2354
2355 if (ins->ssa_args.inline_constant) continue;
2356
2357 /* Blend constants must not be inlined by definition */
2358 if (ins->has_blend_constant) continue;
2359
2360 /* src1 cannot be an inline constant due to encoding
2361 * restrictions. So, if possible we try to flip the arguments
2362 * in that case */
2363
2364 int op = ins->alu.op;
2365
2366 if (ins->ssa_args.src0 == SSA_FIXED_REGISTER(REGISTER_CONSTANT)) {
2367 switch (op) {
2368 /* These ops require an operational change to flip
2369 * their arguments TODO */
2370 case midgard_alu_op_flt:
2371 case midgard_alu_op_fle:
2372 case midgard_alu_op_ilt:
2373 case midgard_alu_op_ile:
2374 case midgard_alu_op_fcsel:
2375 case midgard_alu_op_icsel:
2376 DBG("Missed non-commutative flip (%s)\n", alu_opcode_props[op].name);
2377 default:
2378 break;
2379 }
2380
2381 if (alu_opcode_props[op].props & OP_COMMUTES) {
2382 /* Flip the SSA numbers */
2383 ins->ssa_args.src0 = ins->ssa_args.src1;
2384 ins->ssa_args.src1 = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
2385
2386 /* And flip the modifiers */
2387
2388 unsigned src_temp;
2389
2390 src_temp = ins->alu.src2;
2391 ins->alu.src2 = ins->alu.src1;
2392 ins->alu.src1 = src_temp;
2393 }
2394 }
2395
2396 if (ins->ssa_args.src1 == SSA_FIXED_REGISTER(REGISTER_CONSTANT)) {
2397 /* Extract the source information */
2398
2399 midgard_vector_alu_src *src;
2400 int q = ins->alu.src2;
2401 midgard_vector_alu_src *m = (midgard_vector_alu_src *) &q;
2402 src = m;
2403
2404 /* Component is from the swizzle, e.g. r26.w -> w component. TODO: What if x is masked out? */
2405 int component = src->swizzle & 3;
2406
2407 /* Scale constant appropriately, if we can legally */
2408 uint16_t scaled_constant = 0;
2409
2410 if (midgard_is_integer_op(op)) {
2411 unsigned int *iconstants = (unsigned int *) ins->constants;
2412 scaled_constant = (uint16_t) iconstants[component];
2413
2414 /* Constant overflow after resize */
2415 if (scaled_constant != iconstants[component])
2416 continue;
2417 } else {
2418 float original = (float) ins->constants[component];
2419 scaled_constant = _mesa_float_to_half(original);
2420
2421 /* Check for loss of precision. If this is
2422 * mediump, we don't care, but for a highp
2423 * shader, we need to pay attention. NIR
2424 * doesn't yet tell us which mode we're in!
2425 * Practically this prevents most constants
2426 * from being inlined, sadly. */
2427
2428 float fp32 = _mesa_half_to_float(scaled_constant);
2429
2430 if (fp32 != original)
2431 continue;
2432 }
2433
2434 /* We don't know how to handle these with a constant */
2435
2436 if (src->mod || src->half || src->rep_low || src->rep_high) {
2437 DBG("Bailing inline constant...\n");
2438 continue;
2439 }
2440
2441 /* Make sure that the constant is not itself a
2442 * vector by checking if all accessed values
2443 * (by the swizzle) are the same. */
2444
2445 uint32_t *cons = (uint32_t *) ins->constants;
2446 uint32_t value = cons[component];
2447
2448 bool is_vector = false;
2449 unsigned mask = effective_writemask(&ins->alu);
2450
2451 for (int c = 1; c < 4; ++c) {
2452 /* We only care if this component is actually used */
2453 if (!(mask & (1 << c)))
2454 continue;
2455
2456 uint32_t test = cons[(src->swizzle >> (2 * c)) & 3];
2457
2458 if (test != value) {
2459 is_vector = true;
2460 break;
2461 }
2462 }
2463
2464 if (is_vector)
2465 continue;
2466
2467 /* Get rid of the embedded constant */
2468 ins->has_constants = false;
2469 ins->ssa_args.src1 = SSA_UNUSED_0;
2470 ins->ssa_args.inline_constant = true;
2471 ins->inline_constant = scaled_constant;
2472 }
2473 }
2474 }
2475
2476 /* Map normal SSA sources to other SSA sources / fixed registers (like
2477 * uniforms) */
2478
2479 static void
2480 map_ssa_to_alias(compiler_context *ctx, int *ref)
2481 {
2482 unsigned int alias = (uintptr_t) _mesa_hash_table_u64_search(ctx->ssa_to_alias, *ref + 1);
2483
2484 if (alias) {
2485 /* Remove entry in leftovers to avoid a redunant fmov */
2486
2487 struct set_entry *leftover = _mesa_set_search(ctx->leftover_ssa_to_alias, ((void *) (uintptr_t) (*ref + 1)));
2488
2489 if (leftover)
2490 _mesa_set_remove(ctx->leftover_ssa_to_alias, leftover);
2491
2492 /* Assign the alias map */
2493 *ref = alias - 1;
2494 return;
2495 }
2496 }
2497
2498 /* Basic dead code elimination on the MIR itself, which cleans up e.g. the
2499 * texture pipeline */
2500
2501 static bool
2502 midgard_opt_dead_code_eliminate(compiler_context *ctx, midgard_block *block)
2503 {
2504 bool progress = false;
2505
2506 mir_foreach_instr_in_block_safe(block, ins) {
2507 if (ins->type != TAG_ALU_4) continue;
2508 if (ins->compact_branch) continue;
2509
2510 if (ins->ssa_args.dest >= SSA_FIXED_MINIMUM) continue;
2511 if (midgard_is_pinned(ctx, ins->ssa_args.dest)) continue;
2512 if (mir_is_live_after(ctx, block, ins, ins->ssa_args.dest)) continue;
2513
2514 mir_remove_instruction(ins);
2515 progress = true;
2516 }
2517
2518 return progress;
2519 }
2520
2521 static bool
2522 mir_nontrivial_mod(midgard_vector_alu_src src, bool is_int, unsigned mask)
2523 {
2524 /* abs or neg */
2525 if (!is_int && src.mod) return true;
2526
2527 /* swizzle */
2528 for (unsigned c = 0; c < 4; ++c) {
2529 if (!(mask & (1 << c))) continue;
2530 if (((src.swizzle >> (2*c)) & 3) != c) return true;
2531 }
2532
2533 return false;
2534 }
2535
2536 static bool
2537 midgard_opt_copy_prop(compiler_context *ctx, midgard_block *block)
2538 {
2539 bool progress = false;
2540
2541 mir_foreach_instr_in_block_safe(block, ins) {
2542 if (ins->type != TAG_ALU_4) continue;
2543 if (!OP_IS_MOVE(ins->alu.op)) continue;
2544
2545 unsigned from = ins->ssa_args.src1;
2546 unsigned to = ins->ssa_args.dest;
2547
2548 /* We only work on pure SSA */
2549
2550 if (to >= SSA_FIXED_MINIMUM) continue;
2551 if (from >= SSA_FIXED_MINIMUM) continue;
2552 if (to >= ctx->func->impl->ssa_alloc) continue;
2553 if (from >= ctx->func->impl->ssa_alloc) continue;
2554
2555 /* Constant propagation is not handled here, either */
2556 if (ins->ssa_args.inline_constant) continue;
2557 if (ins->has_constants) continue;
2558
2559 /* Also, if the move has side effects, we're helpless */
2560
2561 midgard_vector_alu_src src =
2562 vector_alu_from_unsigned(ins->alu.src2);
2563 unsigned mask = squeeze_writemask(ins->alu.mask);
2564 bool is_int = midgard_is_integer_op(ins->alu.op);
2565
2566 if (mir_nontrivial_mod(src, is_int, mask)) continue;
2567 if (ins->alu.outmod != midgard_outmod_none) continue;
2568
2569 mir_foreach_instr_in_block_from(block, v, mir_next_op(ins)) {
2570 if (v->ssa_args.src0 == to) {
2571 v->ssa_args.src0 = from;
2572 progress = true;
2573 }
2574
2575 if (v->ssa_args.src1 == to && !v->ssa_args.inline_constant) {
2576 v->ssa_args.src1 = from;
2577 progress = true;
2578 }
2579 }
2580 }
2581
2582 return progress;
2583 }
2584
2585 static bool
2586 midgard_opt_copy_prop_tex(compiler_context *ctx, midgard_block *block)
2587 {
2588 bool progress = false;
2589
2590 mir_foreach_instr_in_block_safe(block, ins) {
2591 if (ins->type != TAG_ALU_4) continue;
2592 if (!OP_IS_MOVE(ins->alu.op)) continue;
2593
2594 unsigned from = ins->ssa_args.src1;
2595 unsigned to = ins->ssa_args.dest;
2596
2597 /* Make sure it's simple enough for us to handle */
2598
2599 if (from >= SSA_FIXED_MINIMUM) continue;
2600 if (from >= ctx->func->impl->ssa_alloc) continue;
2601 if (to < SSA_FIXED_REGISTER(REGISTER_TEXTURE_BASE)) continue;
2602 if (to > SSA_FIXED_REGISTER(REGISTER_TEXTURE_BASE + 1)) continue;
2603
2604 bool eliminated = false;
2605
2606 mir_foreach_instr_in_block_from_rev(block, v, mir_prev_op(ins)) {
2607 /* The texture registers are not SSA so be careful.
2608 * Conservatively, just stop if we hit a texture op
2609 * (even if it may not write) to where we are */
2610
2611 if (v->type != TAG_ALU_4)
2612 break;
2613
2614 if (v->ssa_args.dest == from) {
2615 /* We don't want to track partial writes ... */
2616 if (v->alu.mask == 0xF) {
2617 v->ssa_args.dest = to;
2618 eliminated = true;
2619 }
2620
2621 break;
2622 }
2623 }
2624
2625 if (eliminated)
2626 mir_remove_instruction(ins);
2627
2628 progress |= eliminated;
2629 }
2630
2631 return progress;
2632 }
2633
2634 /* The following passes reorder MIR instructions to enable better scheduling */
2635
2636 static void
2637 midgard_pair_load_store(compiler_context *ctx, midgard_block *block)
2638 {
2639 mir_foreach_instr_in_block_safe(block, ins) {
2640 if (ins->type != TAG_LOAD_STORE_4) continue;
2641
2642 /* We've found a load/store op. Check if next is also load/store. */
2643 midgard_instruction *next_op = mir_next_op(ins);
2644 if (&next_op->link != &block->instructions) {
2645 if (next_op->type == TAG_LOAD_STORE_4) {
2646 /* If so, we're done since we're a pair */
2647 ins = mir_next_op(ins);
2648 continue;
2649 }
2650
2651 /* Maximum search distance to pair, to avoid register pressure disasters */
2652 int search_distance = 8;
2653
2654 /* Otherwise, we have an orphaned load/store -- search for another load */
2655 mir_foreach_instr_in_block_from(block, c, mir_next_op(ins)) {
2656 /* Terminate search if necessary */
2657 if (!(search_distance--)) break;
2658
2659 if (c->type != TAG_LOAD_STORE_4) continue;
2660
2661 /* Stores cannot be reordered, since they have
2662 * dependencies. For the same reason, indirect
2663 * loads cannot be reordered as their index is
2664 * loaded in r27.w */
2665
2666 if (OP_IS_STORE(c->load_store.op)) continue;
2667
2668 /* It appears the 0x800 bit is set whenever a
2669 * load is direct, unset when it is indirect.
2670 * Skip indirect loads. */
2671
2672 if (!(c->load_store.unknown & 0x800)) continue;
2673
2674 /* We found one! Move it up to pair and remove it from the old location */
2675
2676 mir_insert_instruction_before(ins, *c);
2677 mir_remove_instruction(c);
2678
2679 break;
2680 }
2681 }
2682 }
2683 }
2684
2685 /* Emit varying stores late */
2686
2687 static void
2688 midgard_emit_store(compiler_context *ctx, midgard_block *block) {
2689 /* Iterate in reverse to get the final write, rather than the first */
2690
2691 mir_foreach_instr_in_block_safe_rev(block, ins) {
2692 /* Check if what we just wrote needs a store */
2693 int idx = ins->ssa_args.dest;
2694 uintptr_t varying = ((uintptr_t) _mesa_hash_table_u64_search(ctx->ssa_varyings, idx + 1));
2695
2696 if (!varying) continue;
2697
2698 varying -= 1;
2699
2700 /* We need to store to the appropriate varying, so emit the
2701 * move/store */
2702
2703 /* TODO: Integrate with special purpose RA (and scheduler?) */
2704 bool high_varying_register = false;
2705
2706 midgard_instruction mov = v_fmov(idx, blank_alu_src, SSA_FIXED_REGISTER(REGISTER_VARYING_BASE + high_varying_register));
2707
2708 midgard_instruction st = m_st_vary_32(SSA_FIXED_REGISTER(high_varying_register), varying);
2709 st.load_store.unknown = 0x1E9E; /* XXX: What is this? */
2710
2711 mir_insert_instruction_before(mir_next_op(ins), st);
2712 mir_insert_instruction_before(mir_next_op(ins), mov);
2713
2714 /* We no longer need to store this varying */
2715 _mesa_hash_table_u64_remove(ctx->ssa_varyings, idx + 1);
2716 }
2717 }
2718
2719 /* If there are leftovers after the below pass, emit actual fmov
2720 * instructions for the slow-but-correct path */
2721
2722 static void
2723 emit_leftover_move(compiler_context *ctx)
2724 {
2725 set_foreach(ctx->leftover_ssa_to_alias, leftover) {
2726 int base = ((uintptr_t) leftover->key) - 1;
2727 int mapped = base;
2728
2729 map_ssa_to_alias(ctx, &mapped);
2730 EMIT(fmov, mapped, blank_alu_src, base);
2731 }
2732 }
2733
2734 static void
2735 actualise_ssa_to_alias(compiler_context *ctx)
2736 {
2737 mir_foreach_instr(ctx, ins) {
2738 map_ssa_to_alias(ctx, &ins->ssa_args.src0);
2739 map_ssa_to_alias(ctx, &ins->ssa_args.src1);
2740 }
2741
2742 emit_leftover_move(ctx);
2743 }
2744
2745 static void
2746 emit_fragment_epilogue(compiler_context *ctx)
2747 {
2748 /* Special case: writing out constants requires us to include the move
2749 * explicitly now, so shove it into r0 */
2750
2751 void *constant_value = _mesa_hash_table_u64_search(ctx->ssa_constants, ctx->fragment_output + 1);
2752
2753 if (constant_value) {
2754 midgard_instruction ins = v_fmov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), blank_alu_src, SSA_FIXED_REGISTER(0));
2755 attach_constants(ctx, &ins, constant_value, ctx->fragment_output + 1);
2756 emit_mir_instruction(ctx, ins);
2757 }
2758
2759 /* Perform the actual fragment writeout. We have two writeout/branch
2760 * instructions, forming a loop until writeout is successful as per the
2761 * docs. TODO: gl_FragDepth */
2762
2763 EMIT(alu_br_compact_cond, midgard_jmp_writeout_op_writeout, TAG_ALU_4, 0, midgard_condition_always);
2764 EMIT(alu_br_compact_cond, midgard_jmp_writeout_op_writeout, TAG_ALU_4, -1, midgard_condition_always);
2765 }
2766
2767 /* For the blend epilogue, we need to convert the blended fragment vec4 (stored
2768 * in r0) to a RGBA8888 value by scaling and type converting. We then output it
2769 * with the int8 analogue to the fragment epilogue */
2770
2771 static void
2772 emit_blend_epilogue(compiler_context *ctx)
2773 {
2774 /* vmul.fmul.none.fulllow hr48, r0, #255 */
2775
2776 midgard_instruction scale = {
2777 .type = TAG_ALU_4,
2778 .unit = UNIT_VMUL,
2779 .inline_constant = _mesa_float_to_half(255.0),
2780 .ssa_args = {
2781 .src0 = SSA_FIXED_REGISTER(0),
2782 .src1 = SSA_UNUSED_0,
2783 .dest = SSA_FIXED_REGISTER(24),
2784 .inline_constant = true
2785 },
2786 .alu = {
2787 .op = midgard_alu_op_fmul,
2788 .reg_mode = midgard_reg_mode_32,
2789 .dest_override = midgard_dest_override_lower,
2790 .mask = 0xFF,
2791 .src1 = vector_alu_srco_unsigned(blank_alu_src),
2792 .src2 = vector_alu_srco_unsigned(blank_alu_src),
2793 }
2794 };
2795
2796 emit_mir_instruction(ctx, scale);
2797
2798 /* vadd.f2u8.pos.low hr0, hr48, #0 */
2799
2800 midgard_vector_alu_src alu_src = blank_alu_src;
2801 alu_src.half = true;
2802
2803 midgard_instruction f2u8 = {
2804 .type = TAG_ALU_4,
2805 .ssa_args = {
2806 .src0 = SSA_FIXED_REGISTER(24),
2807 .src1 = SSA_UNUSED_0,
2808 .dest = SSA_FIXED_REGISTER(0),
2809 .inline_constant = true
2810 },
2811 .alu = {
2812 .op = midgard_alu_op_f2u8,
2813 .reg_mode = midgard_reg_mode_16,
2814 .dest_override = midgard_dest_override_lower,
2815 .outmod = midgard_outmod_pos,
2816 .mask = 0xF,
2817 .src1 = vector_alu_srco_unsigned(alu_src),
2818 .src2 = vector_alu_srco_unsigned(blank_alu_src),
2819 }
2820 };
2821
2822 emit_mir_instruction(ctx, f2u8);
2823
2824 /* vmul.imov.quarter r0, r0, r0 */
2825
2826 midgard_instruction imov_8 = {
2827 .type = TAG_ALU_4,
2828 .ssa_args = {
2829 .src0 = SSA_UNUSED_1,
2830 .src1 = SSA_FIXED_REGISTER(0),
2831 .dest = SSA_FIXED_REGISTER(0),
2832 },
2833 .alu = {
2834 .op = midgard_alu_op_imov,
2835 .reg_mode = midgard_reg_mode_8,
2836 .dest_override = midgard_dest_override_none,
2837 .mask = 0xFF,
2838 .src1 = vector_alu_srco_unsigned(blank_alu_src),
2839 .src2 = vector_alu_srco_unsigned(blank_alu_src),
2840 }
2841 };
2842
2843 /* Emit branch epilogue with the 8-bit move as the source */
2844
2845 emit_mir_instruction(ctx, imov_8);
2846 EMIT(alu_br_compact_cond, midgard_jmp_writeout_op_writeout, TAG_ALU_4, 0, midgard_condition_always);
2847
2848 emit_mir_instruction(ctx, imov_8);
2849 EMIT(alu_br_compact_cond, midgard_jmp_writeout_op_writeout, TAG_ALU_4, -1, midgard_condition_always);
2850 }
2851
2852 static midgard_block *
2853 emit_block(compiler_context *ctx, nir_block *block)
2854 {
2855 midgard_block *this_block = calloc(sizeof(midgard_block), 1);
2856 list_addtail(&this_block->link, &ctx->blocks);
2857
2858 this_block->is_scheduled = false;
2859 ++ctx->block_count;
2860
2861 ctx->texture_index[0] = -1;
2862 ctx->texture_index[1] = -1;
2863
2864 /* Add us as a successor to the block we are following */
2865 if (ctx->current_block)
2866 midgard_block_add_successor(ctx->current_block, this_block);
2867
2868 /* Set up current block */
2869 list_inithead(&this_block->instructions);
2870 ctx->current_block = this_block;
2871
2872 nir_foreach_instr(instr, block) {
2873 emit_instr(ctx, instr);
2874 ++ctx->instruction_count;
2875 }
2876
2877 inline_alu_constants(ctx);
2878 embedded_to_inline_constant(ctx);
2879
2880 /* Perform heavylifting for aliasing */
2881 actualise_ssa_to_alias(ctx);
2882
2883 midgard_emit_store(ctx, this_block);
2884 midgard_pair_load_store(ctx, this_block);
2885
2886 /* Append fragment shader epilogue (value writeout) */
2887 if (ctx->stage == MESA_SHADER_FRAGMENT) {
2888 if (block == nir_impl_last_block(ctx->func->impl)) {
2889 if (ctx->is_blend)
2890 emit_blend_epilogue(ctx);
2891 else
2892 emit_fragment_epilogue(ctx);
2893 }
2894 }
2895
2896 if (block == nir_start_block(ctx->func->impl))
2897 ctx->initial_block = this_block;
2898
2899 if (block == nir_impl_last_block(ctx->func->impl))
2900 ctx->final_block = this_block;
2901
2902 /* Allow the next control flow to access us retroactively, for
2903 * branching etc */
2904 ctx->current_block = this_block;
2905
2906 /* Document the fallthrough chain */
2907 ctx->previous_source_block = this_block;
2908
2909 return this_block;
2910 }
2911
2912 static midgard_block *emit_cf_list(struct compiler_context *ctx, struct exec_list *list);
2913
2914 static void
2915 emit_if(struct compiler_context *ctx, nir_if *nif)
2916 {
2917 /* Conditional branches expect the condition in r31.w; emit a move for
2918 * that in the _previous_ block (which is the current block). */
2919 emit_condition(ctx, &nif->condition, true, COMPONENT_X);
2920
2921 /* Speculatively emit the branch, but we can't fill it in until later */
2922 EMIT(branch, true, true);
2923 midgard_instruction *then_branch = mir_last_in_block(ctx->current_block);
2924
2925 /* Emit the two subblocks */
2926 midgard_block *then_block = emit_cf_list(ctx, &nif->then_list);
2927
2928 /* Emit a jump from the end of the then block to the end of the else */
2929 EMIT(branch, false, false);
2930 midgard_instruction *then_exit = mir_last_in_block(ctx->current_block);
2931
2932 /* Emit second block, and check if it's empty */
2933
2934 int else_idx = ctx->block_count;
2935 int count_in = ctx->instruction_count;
2936 midgard_block *else_block = emit_cf_list(ctx, &nif->else_list);
2937 int after_else_idx = ctx->block_count;
2938
2939 /* Now that we have the subblocks emitted, fix up the branches */
2940
2941 assert(then_block);
2942 assert(else_block);
2943
2944 if (ctx->instruction_count == count_in) {
2945 /* The else block is empty, so don't emit an exit jump */
2946 mir_remove_instruction(then_exit);
2947 then_branch->branch.target_block = after_else_idx;
2948 } else {
2949 then_branch->branch.target_block = else_idx;
2950 then_exit->branch.target_block = after_else_idx;
2951 }
2952 }
2953
2954 static void
2955 emit_loop(struct compiler_context *ctx, nir_loop *nloop)
2956 {
2957 /* Remember where we are */
2958 midgard_block *start_block = ctx->current_block;
2959
2960 /* Allocate a loop number, growing the current inner loop depth */
2961 int loop_idx = ++ctx->current_loop_depth;
2962
2963 /* Get index from before the body so we can loop back later */
2964 int start_idx = ctx->block_count;
2965
2966 /* Emit the body itself */
2967 emit_cf_list(ctx, &nloop->body);
2968
2969 /* Branch back to loop back */
2970 struct midgard_instruction br_back = v_branch(false, false);
2971 br_back.branch.target_block = start_idx;
2972 emit_mir_instruction(ctx, br_back);
2973
2974 /* Mark down that branch in the graph. Note that we're really branching
2975 * to the block *after* we started in. TODO: Why doesn't the branch
2976 * itself have an off-by-one then...? */
2977 midgard_block_add_successor(ctx->current_block, start_block->successors[0]);
2978
2979 /* Find the index of the block about to follow us (note: we don't add
2980 * one; blocks are 0-indexed so we get a fencepost problem) */
2981 int break_block_idx = ctx->block_count;
2982
2983 /* Fix up the break statements we emitted to point to the right place,
2984 * now that we can allocate a block number for them */
2985
2986 list_for_each_entry_from(struct midgard_block, block, start_block, &ctx->blocks, link) {
2987 mir_foreach_instr_in_block(block, ins) {
2988 if (ins->type != TAG_ALU_4) continue;
2989 if (!ins->compact_branch) continue;
2990 if (ins->prepacked_branch) continue;
2991
2992 /* We found a branch -- check the type to see if we need to do anything */
2993 if (ins->branch.target_type != TARGET_BREAK) continue;
2994
2995 /* It's a break! Check if it's our break */
2996 if (ins->branch.target_break != loop_idx) continue;
2997
2998 /* Okay, cool, we're breaking out of this loop.
2999 * Rewrite from a break to a goto */
3000
3001 ins->branch.target_type = TARGET_GOTO;
3002 ins->branch.target_block = break_block_idx;
3003 }
3004 }
3005
3006 /* Now that we've finished emitting the loop, free up the depth again
3007 * so we play nice with recursion amid nested loops */
3008 --ctx->current_loop_depth;
3009 }
3010
3011 static midgard_block *
3012 emit_cf_list(struct compiler_context *ctx, struct exec_list *list)
3013 {
3014 midgard_block *start_block = NULL;
3015
3016 foreach_list_typed(nir_cf_node, node, node, list) {
3017 switch (node->type) {
3018 case nir_cf_node_block: {
3019 midgard_block *block = emit_block(ctx, nir_cf_node_as_block(node));
3020
3021 if (!start_block)
3022 start_block = block;
3023
3024 break;
3025 }
3026
3027 case nir_cf_node_if:
3028 emit_if(ctx, nir_cf_node_as_if(node));
3029 break;
3030
3031 case nir_cf_node_loop:
3032 emit_loop(ctx, nir_cf_node_as_loop(node));
3033 break;
3034
3035 case nir_cf_node_function:
3036 assert(0);
3037 break;
3038 }
3039 }
3040
3041 return start_block;
3042 }
3043
3044 /* Due to lookahead, we need to report the first tag executed in the command
3045 * stream and in branch targets. An initial block might be empty, so iterate
3046 * until we find one that 'works' */
3047
3048 static unsigned
3049 midgard_get_first_tag_from_block(compiler_context *ctx, unsigned block_idx)
3050 {
3051 midgard_block *initial_block = mir_get_block(ctx, block_idx);
3052
3053 unsigned first_tag = 0;
3054
3055 do {
3056 midgard_bundle *initial_bundle = util_dynarray_element(&initial_block->bundles, midgard_bundle, 0);
3057
3058 if (initial_bundle) {
3059 first_tag = initial_bundle->tag;
3060 break;
3061 }
3062
3063 /* Initial block is empty, try the next block */
3064 initial_block = list_first_entry(&(initial_block->link), midgard_block, link);
3065 } while(initial_block != NULL);
3066
3067 assert(first_tag);
3068 return first_tag;
3069 }
3070
3071 int
3072 midgard_compile_shader_nir(nir_shader *nir, midgard_program *program, bool is_blend)
3073 {
3074 struct util_dynarray *compiled = &program->compiled;
3075
3076 midgard_debug = debug_get_option_midgard_debug();
3077
3078 compiler_context ictx = {
3079 .nir = nir,
3080 .stage = nir->info.stage,
3081
3082 .is_blend = is_blend,
3083 .blend_constant_offset = -1,
3084
3085 .alpha_ref = program->alpha_ref
3086 };
3087
3088 compiler_context *ctx = &ictx;
3089
3090 /* TODO: Decide this at runtime */
3091 ctx->uniform_cutoff = 8;
3092
3093 /* Assign var locations early, so the epilogue can use them if necessary */
3094
3095 nir_assign_var_locations(&nir->outputs, &nir->num_outputs, glsl_type_size);
3096 nir_assign_var_locations(&nir->inputs, &nir->num_inputs, glsl_type_size);
3097 nir_assign_var_locations(&nir->uniforms, &nir->num_uniforms, glsl_type_size);
3098
3099 /* Initialize at a global (not block) level hash tables */
3100
3101 ctx->ssa_constants = _mesa_hash_table_u64_create(NULL);
3102 ctx->ssa_varyings = _mesa_hash_table_u64_create(NULL);
3103 ctx->ssa_to_alias = _mesa_hash_table_u64_create(NULL);
3104 ctx->ssa_to_register = _mesa_hash_table_u64_create(NULL);
3105 ctx->hash_to_temp = _mesa_hash_table_u64_create(NULL);
3106 ctx->sysval_to_id = _mesa_hash_table_u64_create(NULL);
3107 ctx->leftover_ssa_to_alias = _mesa_set_create(NULL, _mesa_hash_pointer, _mesa_key_pointer_equal);
3108
3109 /* Record the varying mapping for the command stream's bookkeeping */
3110
3111 struct exec_list *varyings =
3112 ctx->stage == MESA_SHADER_VERTEX ? &nir->outputs : &nir->inputs;
3113
3114 nir_foreach_variable(var, varyings) {
3115 unsigned loc = var->data.driver_location;
3116 unsigned sz = glsl_type_size(var->type, FALSE);
3117
3118 for (int c = 0; c < sz; ++c) {
3119 program->varyings[loc + c] = var->data.location;
3120 }
3121 }
3122
3123 /* Lower gl_Position pre-optimisation */
3124
3125 if (ctx->stage == MESA_SHADER_VERTEX)
3126 NIR_PASS_V(nir, nir_lower_viewport_transform);
3127
3128 NIR_PASS_V(nir, nir_lower_var_copies);
3129 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
3130 NIR_PASS_V(nir, nir_split_var_copies);
3131 NIR_PASS_V(nir, nir_lower_var_copies);
3132 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
3133 NIR_PASS_V(nir, nir_lower_var_copies);
3134 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
3135
3136 NIR_PASS_V(nir, nir_lower_io, nir_var_all, glsl_type_size, 0);
3137
3138 /* Optimisation passes */
3139
3140 optimise_nir(nir);
3141
3142 if (midgard_debug & MIDGARD_DBG_SHADERS) {
3143 nir_print_shader(nir, stdout);
3144 }
3145
3146 /* Assign sysvals and counts, now that we're sure
3147 * (post-optimisation) */
3148
3149 midgard_nir_assign_sysvals(ctx, nir);
3150
3151 program->uniform_count = nir->num_uniforms;
3152 program->sysval_count = ctx->sysval_count;
3153 memcpy(program->sysvals, ctx->sysvals, sizeof(ctx->sysvals[0]) * ctx->sysval_count);
3154
3155 program->attribute_count = (ctx->stage == MESA_SHADER_VERTEX) ? nir->num_inputs : 0;
3156 program->varying_count = (ctx->stage == MESA_SHADER_VERTEX) ? nir->num_outputs : ((ctx->stage == MESA_SHADER_FRAGMENT) ? nir->num_inputs : 0);
3157
3158 nir_foreach_function(func, nir) {
3159 if (!func->impl)
3160 continue;
3161
3162 list_inithead(&ctx->blocks);
3163 ctx->block_count = 0;
3164 ctx->func = func;
3165
3166 emit_cf_list(ctx, &func->impl->body);
3167 emit_block(ctx, func->impl->end_block);
3168
3169 break; /* TODO: Multi-function shaders */
3170 }
3171
3172 util_dynarray_init(compiled, NULL);
3173
3174 /* MIR-level optimizations */
3175
3176 bool progress = false;
3177
3178 do {
3179 progress = false;
3180
3181 mir_foreach_block(ctx, block) {
3182 progress |= midgard_opt_copy_prop(ctx, block);
3183 progress |= midgard_opt_copy_prop_tex(ctx, block);
3184 progress |= midgard_opt_dead_code_eliminate(ctx, block);
3185 }
3186 } while (progress);
3187
3188 /* Schedule! */
3189 schedule_program(ctx);
3190
3191 /* Now that all the bundles are scheduled and we can calculate block
3192 * sizes, emit actual branch instructions rather than placeholders */
3193
3194 int br_block_idx = 0;
3195
3196 mir_foreach_block(ctx, block) {
3197 util_dynarray_foreach(&block->bundles, midgard_bundle, bundle) {
3198 for (int c = 0; c < bundle->instruction_count; ++c) {
3199 midgard_instruction *ins = &bundle->instructions[c];
3200
3201 if (!midgard_is_branch_unit(ins->unit)) continue;
3202
3203 if (ins->prepacked_branch) continue;
3204
3205 /* Parse some basic branch info */
3206 bool is_compact = ins->unit == ALU_ENAB_BR_COMPACT;
3207 bool is_conditional = ins->branch.conditional;
3208 bool is_inverted = ins->branch.invert_conditional;
3209 bool is_discard = ins->branch.target_type == TARGET_DISCARD;
3210
3211 /* Determine the block we're jumping to */
3212 int target_number = ins->branch.target_block;
3213
3214 /* Report the destination tag. Discards don't need this */
3215 int dest_tag = is_discard ? 0 : midgard_get_first_tag_from_block(ctx, target_number);
3216
3217 /* Count up the number of quadwords we're jumping over. That is, the number of quadwords in each of the blocks between (br_block_idx, target_number) */
3218 int quadword_offset = 0;
3219
3220 if (is_discard) {
3221 /* Jump to the end of the shader. We
3222 * need to include not only the
3223 * following blocks, but also the
3224 * contents of our current block (since
3225 * discard can come in the middle of
3226 * the block) */
3227
3228 midgard_block *blk = mir_get_block(ctx, br_block_idx + 1);
3229
3230 for (midgard_bundle *bun = bundle + 1; bun < (midgard_bundle *)((char*) block->bundles.data + block->bundles.size); ++bun) {
3231 quadword_offset += quadword_size(bun->tag);
3232 }
3233
3234 mir_foreach_block_from(ctx, blk, b) {
3235 quadword_offset += b->quadword_count;
3236 }
3237
3238 } else if (target_number > br_block_idx) {
3239 /* Jump forward */
3240
3241 for (int idx = br_block_idx + 1; idx < target_number; ++idx) {
3242 midgard_block *blk = mir_get_block(ctx, idx);
3243 assert(blk);
3244
3245 quadword_offset += blk->quadword_count;
3246 }
3247 } else {
3248 /* Jump backwards */
3249
3250 for (int idx = br_block_idx; idx >= target_number; --idx) {
3251 midgard_block *blk = mir_get_block(ctx, idx);
3252 assert(blk);
3253
3254 quadword_offset -= blk->quadword_count;
3255 }
3256 }
3257
3258 /* Unconditional extended branches (far jumps)
3259 * have issues, so we always use a conditional
3260 * branch, setting the condition to always for
3261 * unconditional. For compact unconditional
3262 * branches, cond isn't used so it doesn't
3263 * matter what we pick. */
3264
3265 midgard_condition cond =
3266 !is_conditional ? midgard_condition_always :
3267 is_inverted ? midgard_condition_false :
3268 midgard_condition_true;
3269
3270 midgard_jmp_writeout_op op =
3271 is_discard ? midgard_jmp_writeout_op_discard :
3272 (is_compact && !is_conditional) ? midgard_jmp_writeout_op_branch_uncond :
3273 midgard_jmp_writeout_op_branch_cond;
3274
3275 if (!is_compact) {
3276 midgard_branch_extended branch =
3277 midgard_create_branch_extended(
3278 cond, op,
3279 dest_tag,
3280 quadword_offset);
3281
3282 memcpy(&ins->branch_extended, &branch, sizeof(branch));
3283 } else if (is_conditional || is_discard) {
3284 midgard_branch_cond branch = {
3285 .op = op,
3286 .dest_tag = dest_tag,
3287 .offset = quadword_offset,
3288 .cond = cond
3289 };
3290
3291 assert(branch.offset == quadword_offset);
3292
3293 memcpy(&ins->br_compact, &branch, sizeof(branch));
3294 } else {
3295 assert(op == midgard_jmp_writeout_op_branch_uncond);
3296
3297 midgard_branch_uncond branch = {
3298 .op = op,
3299 .dest_tag = dest_tag,
3300 .offset = quadword_offset,
3301 .unknown = 1
3302 };
3303
3304 assert(branch.offset == quadword_offset);
3305
3306 memcpy(&ins->br_compact, &branch, sizeof(branch));
3307 }
3308 }
3309 }
3310
3311 ++br_block_idx;
3312 }
3313
3314 /* Emit flat binary from the instruction arrays. Iterate each block in
3315 * sequence. Save instruction boundaries such that lookahead tags can
3316 * be assigned easily */
3317
3318 /* Cache _all_ bundles in source order for lookahead across failed branches */
3319
3320 int bundle_count = 0;
3321 mir_foreach_block(ctx, block) {
3322 bundle_count += block->bundles.size / sizeof(midgard_bundle);
3323 }
3324 midgard_bundle **source_order_bundles = malloc(sizeof(midgard_bundle *) * bundle_count);
3325 int bundle_idx = 0;
3326 mir_foreach_block(ctx, block) {
3327 util_dynarray_foreach(&block->bundles, midgard_bundle, bundle) {
3328 source_order_bundles[bundle_idx++] = bundle;
3329 }
3330 }
3331
3332 int current_bundle = 0;
3333
3334 mir_foreach_block(ctx, block) {
3335 util_dynarray_foreach(&block->bundles, midgard_bundle, bundle) {
3336 int lookahead = 1;
3337
3338 if (current_bundle + 1 < bundle_count) {
3339 uint8_t next = source_order_bundles[current_bundle + 1]->tag;
3340
3341 if (!(current_bundle + 2 < bundle_count) && IS_ALU(next)) {
3342 lookahead = 1;
3343 } else {
3344 lookahead = next;
3345 }
3346 }
3347
3348 emit_binary_bundle(ctx, bundle, compiled, lookahead);
3349 ++current_bundle;
3350 }
3351
3352 /* TODO: Free deeper */
3353 //util_dynarray_fini(&block->instructions);
3354 }
3355
3356 free(source_order_bundles);
3357
3358 /* Report the very first tag executed */
3359 program->first_tag = midgard_get_first_tag_from_block(ctx, 0);
3360
3361 /* Deal with off-by-one related to the fencepost problem */
3362 program->work_register_count = ctx->work_registers + 1;
3363
3364 program->can_discard = ctx->can_discard;
3365 program->uniform_cutoff = ctx->uniform_cutoff;
3366
3367 program->blend_patch_offset = ctx->blend_constant_offset;
3368
3369 if (midgard_debug & MIDGARD_DBG_SHADERS)
3370 disassemble_midgard(program->compiled.data, program->compiled.size);
3371
3372 return 0;
3373 }