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