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