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