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