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