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