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