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