1 /*
2 * Copyright (C) 2018-2019 Alyssa Rosenzweig <alyssa@rosenzweig.io>
3 * Copyright (C) 2019-2020 Collabora, Ltd.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice (including the next
13 * paragraph) shall be included in all copies or substantial portions of the
14 * Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <sys/mman.h>
28 #include <fcntl.h>
29 #include <stdint.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <err.h>
33
34 #include "main/mtypes.h"
35 #include "compiler/glsl/glsl_to_nir.h"
36 #include "compiler/nir_types.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 #include "midgard_quirks.h"
52 #include "panfrost-quirks.h"
53 #include "panfrost/util/pan_lower_framebuffer.h"
54
55 #include "disassemble.h"
56
57 static const struct debug_named_value debug_options[] = {
58 {"msgs", MIDGARD_DBG_MSGS, "Print debug messages"},
59 {"shaders", MIDGARD_DBG_SHADERS, "Dump shaders in NIR and MIR"},
60 {"shaderdb", MIDGARD_DBG_SHADERDB, "Prints shader-db statistics"},
61 DEBUG_NAMED_VALUE_END
62 };
63
64 DEBUG_GET_ONCE_FLAGS_OPTION(midgard_debug, "MIDGARD_MESA_DEBUG", debug_options, 0)
65
66 unsigned SHADER_DB_COUNT = 0;
67
68 int midgard_debug = 0;
69
70 #define DBG(fmt, ...) \
71 do { if (midgard_debug & MIDGARD_DBG_MSGS) \
72 fprintf(stderr, "%s:%d: "fmt, \
73 __FUNCTION__, __LINE__, ##__VA_ARGS__); } while (0)
74 static midgard_block *
create_empty_block(compiler_context * ctx)75 create_empty_block(compiler_context *ctx)
76 {
77 midgard_block *blk = rzalloc(ctx, midgard_block);
78
79 blk->base.predecessors = _mesa_set_create(blk,
80 _mesa_hash_pointer,
81 _mesa_key_pointer_equal);
82
83 blk->base.name = ctx->block_source_count++;
84
85 return blk;
86 }
87
88 static void
schedule_barrier(compiler_context * ctx)89 schedule_barrier(compiler_context *ctx)
90 {
91 midgard_block *temp = ctx->after_block;
92 ctx->after_block = create_empty_block(ctx);
93 ctx->block_count++;
94 list_addtail(&ctx->after_block->base.link, &ctx->blocks);
95 list_inithead(&ctx->after_block->base.instructions);
96 pan_block_add_successor(&ctx->current_block->base, &ctx->after_block->base);
97 ctx->current_block = ctx->after_block;
98 ctx->after_block = temp;
99 }
100
101 /* Helpers to generate midgard_instruction's using macro magic, since every
102 * driver seems to do it that way */
103
104 #define EMIT(op, ...) emit_mir_instruction(ctx, v_##op(__VA_ARGS__));
105
106 #define M_LOAD_STORE(name, store, T) \
107 static midgard_instruction m_##name(unsigned ssa, unsigned address) { \
108 midgard_instruction i = { \
109 .type = TAG_LOAD_STORE_4, \
110 .mask = 0xF, \
111 .dest = ~0, \
112 .src = { ~0, ~0, ~0, ~0 }, \
113 .swizzle = SWIZZLE_IDENTITY_4, \
114 .op = midgard_op_##name, \
115 .load_store = { \
116 .address = address \
117 } \
118 }; \
119 \
120 if (store) { \
121 i.src[0] = ssa; \
122 i.src_types[0] = T; \
123 i.dest_type = T; \
124 } else { \
125 i.dest = ssa; \
126 i.dest_type = T; \
127 } \
128 return i; \
129 }
130
131 #define M_LOAD(name, T) M_LOAD_STORE(name, false, T)
132 #define M_STORE(name, T) M_LOAD_STORE(name, true, T)
133
134 M_LOAD(ld_attr_32, nir_type_uint32);
135 M_LOAD(ld_vary_32, nir_type_uint32);
136 M_LOAD(ld_ubo_int4, nir_type_uint32);
137 M_LOAD(ld_int4, nir_type_uint32);
138 M_STORE(st_int4, nir_type_uint32);
139 M_LOAD(ld_color_buffer_32u, nir_type_uint32);
140 M_LOAD(ld_color_buffer_as_fp16, nir_type_float16);
141 M_LOAD(ld_color_buffer_as_fp32, nir_type_float32);
142 M_STORE(st_vary_32, nir_type_uint32);
143 M_LOAD(ld_cubemap_coords, nir_type_uint32);
144 M_LOAD(ld_compute_id, nir_type_uint32);
145
146 static midgard_instruction
v_branch(bool conditional,bool invert)147 v_branch(bool conditional, bool invert)
148 {
149 midgard_instruction ins = {
150 .type = TAG_ALU_4,
151 .unit = ALU_ENAB_BRANCH,
152 .compact_branch = true,
153 .branch = {
154 .conditional = conditional,
155 .invert_conditional = invert
156 },
157 .dest = ~0,
158 .src = { ~0, ~0, ~0, ~0 },
159 };
160
161 return ins;
162 }
163
164 static void
attach_constants(compiler_context * ctx,midgard_instruction * ins,void * constants,int name)165 attach_constants(compiler_context *ctx, midgard_instruction *ins, void *constants, int name)
166 {
167 ins->has_constants = true;
168 memcpy(&ins->constants, constants, 16);
169 }
170
171 static int
glsl_type_size(const struct glsl_type * type,bool bindless)172 glsl_type_size(const struct glsl_type *type, bool bindless)
173 {
174 return glsl_count_attribute_slots(type, false);
175 }
176
177 /* Lower fdot2 to a vector multiplication followed by channel addition */
178 static bool
midgard_nir_lower_fdot2_instr(nir_builder * b,nir_instr * instr,void * data)179 midgard_nir_lower_fdot2_instr(nir_builder *b, nir_instr *instr, void *data)
180 {
181 if (instr->type != nir_instr_type_alu)
182 return false;
183
184 nir_alu_instr *alu = nir_instr_as_alu(instr);
185 if (alu->op != nir_op_fdot2)
186 return false;
187
188 b->cursor = nir_before_instr(&alu->instr);
189
190 nir_ssa_def *src0 = nir_ssa_for_alu_src(b, alu, 0);
191 nir_ssa_def *src1 = nir_ssa_for_alu_src(b, alu, 1);
192
193 nir_ssa_def *product = nir_fmul(b, src0, src1);
194
195 nir_ssa_def *sum = nir_fadd(b,
196 nir_channel(b, product, 0),
197 nir_channel(b, product, 1));
198
199 /* Replace the fdot2 with this sum */
200 nir_ssa_def_rewrite_uses(&alu->dest.dest.ssa, nir_src_for_ssa(sum));
201
202 return true;
203 }
204
205 static bool
midgard_nir_lower_fdot2(nir_shader * shader)206 midgard_nir_lower_fdot2(nir_shader *shader)
207 {
208 return nir_shader_instructions_pass(shader,
209 midgard_nir_lower_fdot2_instr,
210 nir_metadata_block_index | nir_metadata_dominance,
211 NULL);
212 }
213
214 static bool
mdg_is_64(const nir_instr * instr,const void * _unused)215 mdg_is_64(const nir_instr *instr, const void *_unused)
216 {
217 const nir_alu_instr *alu = nir_instr_as_alu(instr);
218
219 if (nir_dest_bit_size(alu->dest.dest) == 64)
220 return true;
221
222 switch (alu->op) {
223 case nir_op_umul_high:
224 case nir_op_imul_high:
225 return true;
226 default:
227 return false;
228 }
229 }
230
231 /* Flushes undefined values to zero */
232
233 static void
optimise_nir(nir_shader * nir,unsigned quirks,bool is_blend)234 optimise_nir(nir_shader *nir, unsigned quirks, bool is_blend)
235 {
236 bool progress;
237 unsigned lower_flrp =
238 (nir->options->lower_flrp16 ? 16 : 0) |
239 (nir->options->lower_flrp32 ? 32 : 0) |
240 (nir->options->lower_flrp64 ? 64 : 0);
241
242 NIR_PASS(progress, nir, nir_lower_regs_to_ssa);
243 NIR_PASS(progress, nir, nir_lower_idiv, nir_lower_idiv_fast);
244
245 nir_lower_tex_options lower_tex_options = {
246 .lower_txs_lod = true,
247 .lower_txp = ~0,
248 .lower_tex_without_implicit_lod =
249 (quirks & MIDGARD_EXPLICIT_LOD),
250 .lower_tg4_broadcom_swizzle = true,
251
252 /* TODO: we have native gradient.. */
253 .lower_txd = true,
254 };
255
256 NIR_PASS(progress, nir, nir_lower_tex, &lower_tex_options);
257
258 /* Must lower fdot2 after tex is lowered */
259 NIR_PASS(progress, nir, midgard_nir_lower_fdot2);
260
261 /* T720 is broken. */
262
263 if (quirks & MIDGARD_BROKEN_LOD)
264 NIR_PASS_V(nir, midgard_nir_lod_errata);
265
266 NIR_PASS(progress, nir, midgard_nir_lower_algebraic_early);
267
268 do {
269 progress = false;
270
271 NIR_PASS(progress, nir, nir_lower_var_copies);
272 NIR_PASS(progress, nir, nir_lower_vars_to_ssa);
273
274 NIR_PASS(progress, nir, nir_copy_prop);
275 NIR_PASS(progress, nir, nir_opt_remove_phis);
276 NIR_PASS(progress, nir, nir_opt_dce);
277 NIR_PASS(progress, nir, nir_opt_dead_cf);
278 NIR_PASS(progress, nir, nir_opt_cse);
279 NIR_PASS(progress, nir, nir_opt_peephole_select, 64, false, true);
280 NIR_PASS(progress, nir, nir_opt_algebraic);
281 NIR_PASS(progress, nir, nir_opt_constant_folding);
282
283 if (lower_flrp != 0) {
284 bool lower_flrp_progress = false;
285 NIR_PASS(lower_flrp_progress,
286 nir,
287 nir_lower_flrp,
288 lower_flrp,
289 false /* always_precise */);
290 if (lower_flrp_progress) {
291 NIR_PASS(progress, nir,
292 nir_opt_constant_folding);
293 progress = true;
294 }
295
296 /* Nothing should rematerialize any flrps, so we only
297 * need to do this lowering once.
298 */
299 lower_flrp = 0;
300 }
301
302 NIR_PASS(progress, nir, nir_opt_undef);
303 NIR_PASS(progress, nir, nir_undef_to_zero);
304
305 NIR_PASS(progress, nir, nir_opt_loop_unroll,
306 nir_var_shader_in |
307 nir_var_shader_out |
308 nir_var_function_temp);
309
310 NIR_PASS(progress, nir, nir_opt_vectorize, NULL, NULL);
311 } while (progress);
312
313 NIR_PASS_V(nir, nir_lower_alu_to_scalar, mdg_is_64, NULL);
314
315 /* Run after opts so it can hit more */
316 if (!is_blend)
317 NIR_PASS(progress, nir, nir_fuse_io_16);
318
319 /* Must be run at the end to prevent creation of fsin/fcos ops */
320 NIR_PASS(progress, nir, midgard_nir_scale_trig);
321
322 do {
323 progress = false;
324
325 NIR_PASS(progress, nir, nir_opt_dce);
326 NIR_PASS(progress, nir, nir_opt_algebraic);
327 NIR_PASS(progress, nir, nir_opt_constant_folding);
328 NIR_PASS(progress, nir, nir_copy_prop);
329 } while (progress);
330
331 NIR_PASS(progress, nir, nir_opt_algebraic_late);
332 NIR_PASS(progress, nir, nir_opt_algebraic_distribute_src_mods);
333
334 /* We implement booleans as 32-bit 0/~0 */
335 NIR_PASS(progress, nir, nir_lower_bool_to_int32);
336
337 /* Now that booleans are lowered, we can run out late opts */
338 NIR_PASS(progress, nir, midgard_nir_lower_algebraic_late);
339 NIR_PASS(progress, nir, midgard_nir_cancel_inot);
340
341 NIR_PASS(progress, nir, nir_copy_prop);
342 NIR_PASS(progress, nir, nir_opt_dce);
343
344 /* Take us out of SSA */
345 NIR_PASS(progress, nir, nir_lower_locals_to_regs);
346 NIR_PASS(progress, nir, nir_convert_from_ssa, true);
347
348 /* We are a vector architecture; write combine where possible */
349 NIR_PASS(progress, nir, nir_move_vec_src_uses_to_dest);
350 NIR_PASS(progress, nir, nir_lower_vec_to_movs);
351
352 NIR_PASS(progress, nir, nir_opt_dce);
353 }
354
355 /* Do not actually emit a load; instead, cache the constant for inlining */
356
357 static void
emit_load_const(compiler_context * ctx,nir_load_const_instr * instr)358 emit_load_const(compiler_context *ctx, nir_load_const_instr *instr)
359 {
360 nir_ssa_def def = instr->def;
361
362 midgard_constants *consts = rzalloc(NULL, midgard_constants);
363
364 assert(instr->def.num_components * instr->def.bit_size <= sizeof(*consts) * 8);
365
366 #define RAW_CONST_COPY(bits) \
367 nir_const_value_to_array(consts->u##bits, instr->value, \
368 instr->def.num_components, u##bits)
369
370 switch (instr->def.bit_size) {
371 case 64:
372 RAW_CONST_COPY(64);
373 break;
374 case 32:
375 RAW_CONST_COPY(32);
376 break;
377 case 16:
378 RAW_CONST_COPY(16);
379 break;
380 case 8:
381 RAW_CONST_COPY(8);
382 break;
383 default:
384 unreachable("Invalid bit_size for load_const instruction\n");
385 }
386
387 /* Shifted for SSA, +1 for off-by-one */
388 _mesa_hash_table_u64_insert(ctx->ssa_constants, (def.index << 1) + 1, consts);
389 }
390
391 /* Normally constants are embedded implicitly, but for I/O and such we have to
392 * explicitly emit a move with the constant source */
393
394 static void
emit_explicit_constant(compiler_context * ctx,unsigned node,unsigned to)395 emit_explicit_constant(compiler_context *ctx, unsigned node, unsigned to)
396 {
397 void *constant_value = _mesa_hash_table_u64_search(ctx->ssa_constants, node + 1);
398
399 if (constant_value) {
400 midgard_instruction ins = v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), to);
401 attach_constants(ctx, &ins, constant_value, node + 1);
402 emit_mir_instruction(ctx, ins);
403 }
404 }
405
406 static bool
nir_is_non_scalar_swizzle(nir_alu_src * src,unsigned nr_components)407 nir_is_non_scalar_swizzle(nir_alu_src *src, unsigned nr_components)
408 {
409 unsigned comp = src->swizzle[0];
410
411 for (unsigned c = 1; c < nr_components; ++c) {
412 if (src->swizzle[c] != comp)
413 return true;
414 }
415
416 return false;
417 }
418
419 #define ATOMIC_CASE_IMPL(ctx, instr, nir, op, is_shared) \
420 case nir_intrinsic_##nir: \
421 emit_atomic(ctx, instr, is_shared, midgard_op_##op); \
422 break;
423
424 #define ATOMIC_CASE(ctx, instr, nir, op) \
425 ATOMIC_CASE_IMPL(ctx, instr, shared_atomic_##nir, atomic_##op, true); \
426 ATOMIC_CASE_IMPL(ctx, instr, global_atomic_##nir, atomic_##op, false);
427
428 #define ALU_CASE(nir, _op) \
429 case nir_op_##nir: \
430 op = midgard_alu_op_##_op; \
431 assert(src_bitsize == dst_bitsize); \
432 break;
433
434 #define ALU_CASE_RTZ(nir, _op) \
435 case nir_op_##nir: \
436 op = midgard_alu_op_##_op; \
437 roundmode = MIDGARD_RTZ; \
438 break;
439
440 #define ALU_CHECK_CMP() \
441 assert(src_bitsize == 16 || src_bitsize == 32); \
442 assert(dst_bitsize == 16 || dst_bitsize == 32); \
443
444 #define ALU_CASE_BCAST(nir, _op, count) \
445 case nir_op_##nir: \
446 op = midgard_alu_op_##_op; \
447 broadcast_swizzle = count; \
448 ALU_CHECK_CMP(); \
449 break;
450
451 #define ALU_CASE_CMP(nir, _op) \
452 case nir_op_##nir: \
453 op = midgard_alu_op_##_op; \
454 ALU_CHECK_CMP(); \
455 break;
456
457 /* Compare mir_lower_invert */
458 static bool
nir_accepts_inot(nir_op op,unsigned src)459 nir_accepts_inot(nir_op op, unsigned src)
460 {
461 switch (op) {
462 case nir_op_ior:
463 case nir_op_iand: /* TODO: b2f16 */
464 case nir_op_ixor:
465 return true;
466 case nir_op_b32csel:
467 /* Only the condition */
468 return (src == 0);
469 default:
470 return false;
471 }
472 }
473
474 static bool
mir_accept_dest_mod(compiler_context * ctx,nir_dest ** dest,nir_op op)475 mir_accept_dest_mod(compiler_context *ctx, nir_dest **dest, nir_op op)
476 {
477 if (pan_has_dest_mod(dest, op)) {
478 assert((*dest)->is_ssa);
479 BITSET_SET(ctx->already_emitted, (*dest)->ssa.index);
480 return true;
481 }
482
483 return false;
484 }
485
486 /* Look for floating point mods. We have the mods fsat, fsat_signed,
487 * and fpos. We also have the relations (note 3 * 2 = 6 cases):
488 *
489 * fsat_signed(fpos(x)) = fsat(x)
490 * fsat_signed(fsat(x)) = fsat(x)
491 * fpos(fsat_signed(x)) = fsat(x)
492 * fpos(fsat(x)) = fsat(x)
493 * fsat(fsat_signed(x)) = fsat(x)
494 * fsat(fpos(x)) = fsat(x)
495 *
496 * So by cases any composition of output modifiers is equivalent to
497 * fsat alone.
498 */
499 static unsigned
mir_determine_float_outmod(compiler_context * ctx,nir_dest ** dest,unsigned prior_outmod)500 mir_determine_float_outmod(compiler_context *ctx, nir_dest **dest, unsigned prior_outmod)
501 {
502 bool fpos = mir_accept_dest_mod(ctx, dest, nir_op_fclamp_pos);
503 bool fsat = mir_accept_dest_mod(ctx, dest, nir_op_fsat);
504 bool ssat = mir_accept_dest_mod(ctx, dest, nir_op_fsat_signed);
505 bool prior = (prior_outmod != midgard_outmod_none);
506 int count = (int) prior + (int) fpos + (int) ssat + (int) fsat;
507
508 return ((count > 1) || fsat) ? midgard_outmod_sat :
509 fpos ? midgard_outmod_pos :
510 ssat ? midgard_outmod_sat_signed :
511 prior_outmod;
512 }
513
514 static void
mir_copy_src(midgard_instruction * ins,nir_alu_instr * instr,unsigned i,unsigned to,bool * abs,bool * neg,bool * not,enum midgard_roundmode * roundmode,bool is_int,unsigned bcast_count)515 mir_copy_src(midgard_instruction *ins, nir_alu_instr *instr, unsigned i, unsigned to, bool *abs, bool *neg, bool *not, enum midgard_roundmode *roundmode, bool is_int, unsigned bcast_count)
516 {
517 nir_alu_src src = instr->src[i];
518
519 if (!is_int) {
520 if (pan_has_source_mod(&src, nir_op_fneg))
521 *neg = !(*neg);
522
523 if (pan_has_source_mod(&src, nir_op_fabs))
524 *abs = true;
525 }
526
527 if (nir_accepts_inot(instr->op, i) && pan_has_source_mod(&src, nir_op_inot))
528 *not = true;
529
530 if (roundmode) {
531 if (pan_has_source_mod(&src, nir_op_fround_even))
532 *roundmode = MIDGARD_RTE;
533
534 if (pan_has_source_mod(&src, nir_op_ftrunc))
535 *roundmode = MIDGARD_RTZ;
536
537 if (pan_has_source_mod(&src, nir_op_ffloor))
538 *roundmode = MIDGARD_RTN;
539
540 if (pan_has_source_mod(&src, nir_op_fceil))
541 *roundmode = MIDGARD_RTP;
542 }
543
544 unsigned bits = nir_src_bit_size(src.src);
545
546 ins->src[to] = nir_src_index(NULL, &src.src);
547 ins->src_types[to] = nir_op_infos[instr->op].input_types[i] | bits;
548
549 for (unsigned c = 0; c < NIR_MAX_VEC_COMPONENTS; ++c) {
550 ins->swizzle[to][c] = src.swizzle[
551 (!bcast_count || c < bcast_count) ? c :
552 (bcast_count - 1)];
553 }
554 }
555
556 /* Midgard features both fcsel and icsel, depending on whether you want int or
557 * float modifiers. NIR's csel is typeless, so we want a heuristic to guess if
558 * we should emit an int or float csel depending on what modifiers could be
559 * placed. In the absense of modifiers, this is probably arbitrary. */
560
561 static bool
mir_is_bcsel_float(nir_alu_instr * instr)562 mir_is_bcsel_float(nir_alu_instr *instr)
563 {
564 nir_op intmods[] = {
565 nir_op_i2i8, nir_op_i2i16,
566 nir_op_i2i32, nir_op_i2i64
567 };
568
569 nir_op floatmods[] = {
570 nir_op_fabs, nir_op_fneg,
571 nir_op_f2f16, nir_op_f2f32,
572 nir_op_f2f64
573 };
574
575 nir_op floatdestmods[] = {
576 nir_op_fsat, nir_op_fsat_signed, nir_op_fclamp_pos,
577 nir_op_f2f16, nir_op_f2f32
578 };
579
580 signed score = 0;
581
582 for (unsigned i = 1; i < 3; ++i) {
583 nir_alu_src s = instr->src[i];
584 for (unsigned q = 0; q < ARRAY_SIZE(intmods); ++q) {
585 if (pan_has_source_mod(&s, intmods[q]))
586 score--;
587 }
588 }
589
590 for (unsigned i = 1; i < 3; ++i) {
591 nir_alu_src s = instr->src[i];
592 for (unsigned q = 0; q < ARRAY_SIZE(floatmods); ++q) {
593 if (pan_has_source_mod(&s, floatmods[q]))
594 score++;
595 }
596 }
597
598 for (unsigned q = 0; q < ARRAY_SIZE(floatdestmods); ++q) {
599 nir_dest *dest = &instr->dest.dest;
600 if (pan_has_dest_mod(&dest, floatdestmods[q]))
601 score++;
602 }
603
604 return (score > 0);
605 }
606
607 static void
emit_alu(compiler_context * ctx,nir_alu_instr * instr)608 emit_alu(compiler_context *ctx, nir_alu_instr *instr)
609 {
610 nir_dest *dest = &instr->dest.dest;
611
612 if (dest->is_ssa && BITSET_TEST(ctx->already_emitted, dest->ssa.index))
613 return;
614
615 /* Derivatives end up emitted on the texture pipe, not the ALUs. This
616 * is handled elsewhere */
617
618 if (instr->op == nir_op_fddx || instr->op == nir_op_fddy) {
619 midgard_emit_derivatives(ctx, instr);
620 return;
621 }
622
623 bool is_ssa = dest->is_ssa;
624
625 unsigned nr_components = nir_dest_num_components(*dest);
626 unsigned nr_inputs = nir_op_infos[instr->op].num_inputs;
627 unsigned op = 0;
628
629 /* Number of components valid to check for the instruction (the rest
630 * will be forced to the last), or 0 to use as-is. Relevant as
631 * ball-type instructions have a channel count in NIR but are all vec4
632 * in Midgard */
633
634 unsigned broadcast_swizzle = 0;
635
636 /* Should we swap arguments? */
637 bool flip_src12 = false;
638
639 ASSERTED unsigned src_bitsize = nir_src_bit_size(instr->src[0].src);
640 ASSERTED unsigned dst_bitsize = nir_dest_bit_size(*dest);
641
642 enum midgard_roundmode roundmode = MIDGARD_RTE;
643
644 switch (instr->op) {
645 ALU_CASE(fadd, fadd);
646 ALU_CASE(fmul, fmul);
647 ALU_CASE(fmin, fmin);
648 ALU_CASE(fmax, fmax);
649 ALU_CASE(imin, imin);
650 ALU_CASE(imax, imax);
651 ALU_CASE(umin, umin);
652 ALU_CASE(umax, umax);
653 ALU_CASE(ffloor, ffloor);
654 ALU_CASE(fround_even, froundeven);
655 ALU_CASE(ftrunc, ftrunc);
656 ALU_CASE(fceil, fceil);
657 ALU_CASE(fdot3, fdot3);
658 ALU_CASE(fdot4, fdot4);
659 ALU_CASE(iadd, iadd);
660 ALU_CASE(isub, isub);
661 ALU_CASE(imul, imul);
662 ALU_CASE(imul_high, imul);
663 ALU_CASE(umul_high, imul);
664
665 /* Zero shoved as second-arg */
666 ALU_CASE(iabs, iabsdiff);
667
668 ALU_CASE(uabs_isub, iabsdiff);
669 ALU_CASE(uabs_usub, uabsdiff);
670
671 ALU_CASE(mov, imov);
672
673 ALU_CASE_CMP(feq32, feq);
674 ALU_CASE_CMP(fneu32, fne);
675 ALU_CASE_CMP(flt32, flt);
676 ALU_CASE_CMP(ieq32, ieq);
677 ALU_CASE_CMP(ine32, ine);
678 ALU_CASE_CMP(ilt32, ilt);
679 ALU_CASE_CMP(ult32, ult);
680
681 /* We don't have a native b2f32 instruction. Instead, like many
682 * GPUs, we exploit booleans as 0/~0 for false/true, and
683 * correspondingly AND
684 * by 1.0 to do the type conversion. For the moment, prime us
685 * to emit:
686 *
687 * iand [whatever], #0
688 *
689 * At the end of emit_alu (as MIR), we'll fix-up the constant
690 */
691
692 ALU_CASE_CMP(b2f32, iand);
693 ALU_CASE_CMP(b2f16, iand);
694 ALU_CASE_CMP(b2i32, iand);
695
696 /* Likewise, we don't have a dedicated f2b32 instruction, but
697 * we can do a "not equal to 0.0" test. */
698
699 ALU_CASE_CMP(f2b32, fne);
700 ALU_CASE_CMP(i2b32, ine);
701
702 ALU_CASE(frcp, frcp);
703 ALU_CASE(frsq, frsqrt);
704 ALU_CASE(fsqrt, fsqrt);
705 ALU_CASE(fexp2, fexp2);
706 ALU_CASE(flog2, flog2);
707
708 ALU_CASE_RTZ(f2i64, f2i_rte);
709 ALU_CASE_RTZ(f2u64, f2u_rte);
710 ALU_CASE_RTZ(i2f64, i2f_rte);
711 ALU_CASE_RTZ(u2f64, u2f_rte);
712
713 ALU_CASE_RTZ(f2i32, f2i_rte);
714 ALU_CASE_RTZ(f2u32, f2u_rte);
715 ALU_CASE_RTZ(i2f32, i2f_rte);
716 ALU_CASE_RTZ(u2f32, u2f_rte);
717
718 ALU_CASE_RTZ(f2i8, f2i_rte);
719 ALU_CASE_RTZ(f2u8, f2u_rte);
720
721 ALU_CASE_RTZ(f2i16, f2i_rte);
722 ALU_CASE_RTZ(f2u16, f2u_rte);
723 ALU_CASE_RTZ(i2f16, i2f_rte);
724 ALU_CASE_RTZ(u2f16, u2f_rte);
725
726 ALU_CASE(fsin, fsin);
727 ALU_CASE(fcos, fcos);
728
729 /* We'll get 0 in the second arg, so:
730 * ~a = ~(a | 0) = nor(a, 0) */
731 ALU_CASE(inot, inor);
732 ALU_CASE(iand, iand);
733 ALU_CASE(ior, ior);
734 ALU_CASE(ixor, ixor);
735 ALU_CASE(ishl, ishl);
736 ALU_CASE(ishr, iasr);
737 ALU_CASE(ushr, ilsr);
738
739 ALU_CASE_BCAST(b32all_fequal2, fball_eq, 2);
740 ALU_CASE_BCAST(b32all_fequal3, fball_eq, 3);
741 ALU_CASE_CMP(b32all_fequal4, fball_eq);
742
743 ALU_CASE_BCAST(b32any_fnequal2, fbany_neq, 2);
744 ALU_CASE_BCAST(b32any_fnequal3, fbany_neq, 3);
745 ALU_CASE_CMP(b32any_fnequal4, fbany_neq);
746
747 ALU_CASE_BCAST(b32all_iequal2, iball_eq, 2);
748 ALU_CASE_BCAST(b32all_iequal3, iball_eq, 3);
749 ALU_CASE_CMP(b32all_iequal4, iball_eq);
750
751 ALU_CASE_BCAST(b32any_inequal2, ibany_neq, 2);
752 ALU_CASE_BCAST(b32any_inequal3, ibany_neq, 3);
753 ALU_CASE_CMP(b32any_inequal4, ibany_neq);
754
755 /* Source mods will be shoved in later */
756 ALU_CASE(fabs, fmov);
757 ALU_CASE(fneg, fmov);
758 ALU_CASE(fsat, fmov);
759 ALU_CASE(fsat_signed, fmov);
760 ALU_CASE(fclamp_pos, fmov);
761
762 /* For size conversion, we use a move. Ideally though we would squash
763 * these ops together; maybe that has to happen after in NIR as part of
764 * propagation...? An earlier algebraic pass ensured we step down by
765 * only / exactly one size. If stepping down, we use a dest override to
766 * reduce the size; if stepping up, we use a larger-sized move with a
767 * half source and a sign/zero-extension modifier */
768
769 case nir_op_i2i8:
770 case nir_op_i2i16:
771 case nir_op_i2i32:
772 case nir_op_i2i64:
773 case nir_op_u2u8:
774 case nir_op_u2u16:
775 case nir_op_u2u32:
776 case nir_op_u2u64:
777 case nir_op_f2f16:
778 case nir_op_f2f32:
779 case nir_op_f2f64: {
780 if (instr->op == nir_op_f2f16 || instr->op == nir_op_f2f32 ||
781 instr->op == nir_op_f2f64)
782 op = midgard_alu_op_fmov;
783 else
784 op = midgard_alu_op_imov;
785
786 break;
787 }
788
789 /* For greater-or-equal, we lower to less-or-equal and flip the
790 * arguments */
791
792 case nir_op_fge:
793 case nir_op_fge32:
794 case nir_op_ige32:
795 case nir_op_uge32: {
796 op =
797 instr->op == nir_op_fge ? midgard_alu_op_fle :
798 instr->op == nir_op_fge32 ? midgard_alu_op_fle :
799 instr->op == nir_op_ige32 ? midgard_alu_op_ile :
800 instr->op == nir_op_uge32 ? midgard_alu_op_ule :
801 0;
802
803 flip_src12 = true;
804 ALU_CHECK_CMP();
805 break;
806 }
807
808 case nir_op_b32csel: {
809 bool mixed = nir_is_non_scalar_swizzle(&instr->src[0], nr_components);
810 bool is_float = mir_is_bcsel_float(instr);
811 op = is_float ?
812 (mixed ? midgard_alu_op_fcsel_v : midgard_alu_op_fcsel) :
813 (mixed ? midgard_alu_op_icsel_v : midgard_alu_op_icsel);
814
815 break;
816 }
817
818 case nir_op_unpack_32_2x16:
819 case nir_op_unpack_32_4x8:
820 case nir_op_pack_32_2x16:
821 case nir_op_pack_32_4x8: {
822 op = midgard_alu_op_imov;
823 break;
824 }
825
826 default:
827 DBG("Unhandled ALU op %s\n", nir_op_infos[instr->op].name);
828 assert(0);
829 return;
830 }
831
832 /* Promote imov to fmov if it might help inline a constant */
833 if (op == midgard_alu_op_imov && nir_src_is_const(instr->src[0].src)
834 && nir_src_bit_size(instr->src[0].src) == 32
835 && nir_is_same_comp_swizzle(instr->src[0].swizzle,
836 nir_src_num_components(instr->src[0].src))) {
837 op = midgard_alu_op_fmov;
838 }
839
840 /* Midgard can perform certain modifiers on output of an ALU op */
841
842 unsigned outmod = 0;
843 bool is_int = midgard_is_integer_op(op);
844
845 if (instr->op == nir_op_umul_high || instr->op == nir_op_imul_high) {
846 outmod = midgard_outmod_int_high;
847 } else if (midgard_is_integer_out_op(op)) {
848 outmod = midgard_outmod_int_wrap;
849 } else if (instr->op == nir_op_fsat) {
850 outmod = midgard_outmod_sat;
851 } else if (instr->op == nir_op_fsat_signed) {
852 outmod = midgard_outmod_sat_signed;
853 } else if (instr->op == nir_op_fclamp_pos) {
854 outmod = midgard_outmod_pos;
855 }
856
857 /* Fetch unit, quirks, etc information */
858 unsigned opcode_props = alu_opcode_props[op].props;
859 bool quirk_flipped_r24 = opcode_props & QUIRK_FLIPPED_R24;
860
861 if (!midgard_is_integer_out_op(op)) {
862 outmod = mir_determine_float_outmod(ctx, &dest, outmod);
863 }
864
865 midgard_instruction ins = {
866 .type = TAG_ALU_4,
867 .dest = nir_dest_index(dest),
868 .dest_type = nir_op_infos[instr->op].output_type
869 | nir_dest_bit_size(*dest),
870 .roundmode = roundmode,
871 };
872
873 enum midgard_roundmode *roundptr = (opcode_props & MIDGARD_ROUNDS) ?
874 &ins.roundmode : NULL;
875
876 for (unsigned i = nr_inputs; i < ARRAY_SIZE(ins.src); ++i)
877 ins.src[i] = ~0;
878
879 if (quirk_flipped_r24) {
880 ins.src[0] = ~0;
881 mir_copy_src(&ins, instr, 0, 1, &ins.src_abs[1], &ins.src_neg[1], &ins.src_invert[1], roundptr, is_int, broadcast_swizzle);
882 } else {
883 for (unsigned i = 0; i < nr_inputs; ++i) {
884 unsigned to = i;
885
886 if (instr->op == nir_op_b32csel) {
887 /* The condition is the first argument; move
888 * the other arguments up one to be a binary
889 * instruction for Midgard with the condition
890 * last */
891
892 if (i == 0)
893 to = 2;
894 else if (flip_src12)
895 to = 2 - i;
896 else
897 to = i - 1;
898 } else if (flip_src12) {
899 to = 1 - to;
900 }
901
902 mir_copy_src(&ins, instr, i, to, &ins.src_abs[to], &ins.src_neg[to], &ins.src_invert[to], roundptr, is_int, broadcast_swizzle);
903
904 /* (!c) ? a : b = c ? b : a */
905 if (instr->op == nir_op_b32csel && ins.src_invert[2]) {
906 ins.src_invert[2] = false;
907 flip_src12 ^= true;
908 }
909 }
910 }
911
912 if (instr->op == nir_op_fneg || instr->op == nir_op_fabs) {
913 /* Lowered to move */
914 if (instr->op == nir_op_fneg)
915 ins.src_neg[1] ^= true;
916
917 if (instr->op == nir_op_fabs)
918 ins.src_abs[1] = true;
919 }
920
921 ins.mask = mask_of(nr_components);
922
923 /* Apply writemask if non-SSA, keeping in mind that we can't write to
924 * components that don't exist. Note modifier => SSA => !reg => no
925 * writemask, so we don't have to worry about writemasks here.*/
926
927 if (!is_ssa)
928 ins.mask &= instr->dest.write_mask;
929
930 ins.op = op;
931 ins.outmod = outmod;
932
933 /* Late fixup for emulated instructions */
934
935 if (instr->op == nir_op_b2f32 || instr->op == nir_op_b2i32) {
936 /* Presently, our second argument is an inline #0 constant.
937 * Switch over to an embedded 1.0 constant (that can't fit
938 * inline, since we're 32-bit, not 16-bit like the inline
939 * constants) */
940
941 ins.has_inline_constant = false;
942 ins.src[1] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
943 ins.src_types[1] = nir_type_float32;
944 ins.has_constants = true;
945
946 if (instr->op == nir_op_b2f32)
947 ins.constants.f32[0] = 1.0f;
948 else
949 ins.constants.i32[0] = 1;
950
951 for (unsigned c = 0; c < 16; ++c)
952 ins.swizzle[1][c] = 0;
953 } else if (instr->op == nir_op_b2f16) {
954 ins.src[1] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
955 ins.src_types[1] = nir_type_float16;
956 ins.has_constants = true;
957 ins.constants.i16[0] = _mesa_float_to_half(1.0);
958
959 for (unsigned c = 0; c < 16; ++c)
960 ins.swizzle[1][c] = 0;
961 } else if (nr_inputs == 1 && !quirk_flipped_r24) {
962 /* Lots of instructions need a 0 plonked in */
963 ins.has_inline_constant = false;
964 ins.src[1] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
965 ins.src_types[1] = ins.src_types[0];
966 ins.has_constants = true;
967 ins.constants.u32[0] = 0;
968
969 for (unsigned c = 0; c < 16; ++c)
970 ins.swizzle[1][c] = 0;
971 } else if (instr->op == nir_op_pack_32_2x16) {
972 ins.dest_type = nir_type_uint16;
973 ins.mask = mask_of(nr_components * 2);
974 ins.is_pack = true;
975 } else if (instr->op == nir_op_pack_32_4x8) {
976 ins.dest_type = nir_type_uint8;
977 ins.mask = mask_of(nr_components * 4);
978 ins.is_pack = true;
979 } else if (instr->op == nir_op_unpack_32_2x16) {
980 ins.dest_type = nir_type_uint32;
981 ins.mask = mask_of(nr_components >> 1);
982 ins.is_pack = true;
983 } else if (instr->op == nir_op_unpack_32_4x8) {
984 ins.dest_type = nir_type_uint32;
985 ins.mask = mask_of(nr_components >> 2);
986 ins.is_pack = true;
987 }
988
989 if ((opcode_props & UNITS_ALL) == UNIT_VLUT) {
990 /* To avoid duplicating the lookup tables (probably), true LUT
991 * instructions can only operate as if they were scalars. Lower
992 * them here by changing the component. */
993
994 unsigned orig_mask = ins.mask;
995
996 unsigned swizzle_back[MIR_VEC_COMPONENTS];
997 memcpy(&swizzle_back, ins.swizzle[0], sizeof(swizzle_back));
998
999 midgard_instruction ins_split[MIR_VEC_COMPONENTS];
1000 unsigned ins_count = 0;
1001
1002 for (int i = 0; i < nr_components; ++i) {
1003 /* Mask the associated component, dropping the
1004 * instruction if needed */
1005
1006 ins.mask = 1 << i;
1007 ins.mask &= orig_mask;
1008
1009 for (unsigned j = 0; j < ins_count; ++j) {
1010 if (swizzle_back[i] == ins_split[j].swizzle[0][0]) {
1011 ins_split[j].mask |= ins.mask;
1012 ins.mask = 0;
1013 break;
1014 }
1015 }
1016
1017 if (!ins.mask)
1018 continue;
1019
1020 for (unsigned j = 0; j < MIR_VEC_COMPONENTS; ++j)
1021 ins.swizzle[0][j] = swizzle_back[i]; /* Pull from the correct component */
1022
1023 ins_split[ins_count] = ins;
1024
1025 ++ins_count;
1026 }
1027
1028 for (unsigned i = 0; i < ins_count; ++i) {
1029 emit_mir_instruction(ctx, ins_split[i]);
1030 }
1031 } else {
1032 emit_mir_instruction(ctx, ins);
1033 }
1034 }
1035
1036 #undef ALU_CASE
1037
1038 static void
mir_set_intr_mask(nir_instr * instr,midgard_instruction * ins,bool is_read)1039 mir_set_intr_mask(nir_instr *instr, midgard_instruction *ins, bool is_read)
1040 {
1041 nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
1042 unsigned nir_mask = 0;
1043 unsigned dsize = 0;
1044
1045 if (is_read) {
1046 nir_mask = mask_of(nir_intrinsic_dest_components(intr));
1047 dsize = nir_dest_bit_size(intr->dest);
1048 } else {
1049 nir_mask = nir_intrinsic_write_mask(intr);
1050 dsize = 32;
1051 }
1052
1053 /* Once we have the NIR mask, we need to normalize to work in 32-bit space */
1054 unsigned bytemask = pan_to_bytemask(dsize, nir_mask);
1055 ins->dest_type = nir_type_uint | dsize;
1056 mir_set_bytemask(ins, bytemask);
1057 }
1058
1059 /* Uniforms and UBOs use a shared code path, as uniforms are just (slightly
1060 * optimized) versions of UBO #0 */
1061
1062 static midgard_instruction *
emit_ubo_read(compiler_context * ctx,nir_instr * instr,unsigned dest,unsigned offset,nir_src * indirect_offset,unsigned indirect_shift,unsigned index)1063 emit_ubo_read(
1064 compiler_context *ctx,
1065 nir_instr *instr,
1066 unsigned dest,
1067 unsigned offset,
1068 nir_src *indirect_offset,
1069 unsigned indirect_shift,
1070 unsigned index)
1071 {
1072 /* TODO: half-floats */
1073
1074 midgard_instruction ins = m_ld_ubo_int4(dest, 0);
1075 ins.constants.u32[0] = offset;
1076
1077 if (instr->type == nir_instr_type_intrinsic)
1078 mir_set_intr_mask(instr, &ins, true);
1079
1080 if (indirect_offset) {
1081 ins.src[2] = nir_src_index(ctx, indirect_offset);
1082 ins.src_types[2] = nir_type_uint32;
1083 ins.load_store.arg_2 = (indirect_shift << 5);
1084
1085 /* X component for the whole swizzle to prevent register
1086 * pressure from ballooning from the extra components */
1087 for (unsigned i = 0; i < ARRAY_SIZE(ins.swizzle[2]); ++i)
1088 ins.swizzle[2][i] = 0;
1089 } else {
1090 ins.load_store.arg_2 = 0x1E;
1091 }
1092
1093 ins.load_store.arg_1 = index;
1094
1095 return emit_mir_instruction(ctx, ins);
1096 }
1097
1098 /* Globals are like UBOs if you squint. And shared memory is like globals if
1099 * you squint even harder */
1100
1101 static void
emit_global(compiler_context * ctx,nir_instr * instr,bool is_read,unsigned srcdest,nir_src * offset,bool is_shared)1102 emit_global(
1103 compiler_context *ctx,
1104 nir_instr *instr,
1105 bool is_read,
1106 unsigned srcdest,
1107 nir_src *offset,
1108 bool is_shared)
1109 {
1110 /* TODO: types */
1111
1112 midgard_instruction ins;
1113
1114 if (is_read)
1115 ins = m_ld_int4(srcdest, 0);
1116 else
1117 ins = m_st_int4(srcdest, 0);
1118
1119 mir_set_offset(ctx, &ins, offset, is_shared);
1120 mir_set_intr_mask(instr, &ins, is_read);
1121
1122 /* Set a valid swizzle for masked out components */
1123 assert(ins.mask);
1124 unsigned first_component = __builtin_ffs(ins.mask) - 1;
1125
1126 for (unsigned i = 0; i < ARRAY_SIZE(ins.swizzle[0]); ++i) {
1127 if (!(ins.mask & (1 << i)))
1128 ins.swizzle[0][i] = first_component;
1129 }
1130
1131 emit_mir_instruction(ctx, ins);
1132 }
1133
1134 /* If is_shared is off, the only other possible value are globals, since
1135 * SSBO's are being lowered to globals through a NIR pass. */
1136 static void
emit_atomic(compiler_context * ctx,nir_intrinsic_instr * instr,bool is_shared,midgard_load_store_op op)1137 emit_atomic(
1138 compiler_context *ctx,
1139 nir_intrinsic_instr *instr,
1140 bool is_shared,
1141 midgard_load_store_op op)
1142 {
1143 unsigned bitsize = nir_src_bit_size(instr->src[1]);
1144 nir_alu_type type =
1145 (op == midgard_op_atomic_imin || op == midgard_op_atomic_imax) ?
1146 nir_type_int : nir_type_uint;
1147
1148 unsigned dest = nir_dest_index(&instr->dest);
1149 unsigned val = nir_src_index(ctx, &instr->src[1]);
1150 emit_explicit_constant(ctx, val, val);
1151
1152 midgard_instruction ins = {
1153 .type = TAG_LOAD_STORE_4,
1154 .mask = 0xF,
1155 .dest = dest,
1156 .src = { ~0, ~0, ~0, val },
1157 .src_types = { 0, 0, 0, type | bitsize },
1158 .op = op
1159 };
1160
1161 nir_src *src_offset = nir_get_io_offset_src(instr);
1162
1163 /* cmpxchg takes an extra value in arg_2, so we don't use it for the offset */
1164 if (op == midgard_op_atomic_cmpxchg) {
1165 unsigned addr = nir_src_index(ctx, src_offset);
1166
1167 ins.src[1] = addr;
1168 ins.src_types[1] = nir_type_uint | nir_src_bit_size(*src_offset);
1169
1170 unsigned xchg_val = nir_src_index(ctx, &instr->src[2]);
1171 emit_explicit_constant(ctx, xchg_val, xchg_val);
1172
1173 ins.src[2] = val;
1174 ins.src_types[2] = type | bitsize;
1175 ins.src[3] = xchg_val;
1176
1177 if (is_shared)
1178 ins.load_store.arg_1 |= 0x6E;
1179 } else {
1180 mir_set_offset(ctx, &ins, src_offset, is_shared);
1181 }
1182
1183 mir_set_intr_mask(&instr->instr, &ins, true);
1184
1185 emit_mir_instruction(ctx, ins);
1186 }
1187
1188 static void
emit_varying_read(compiler_context * ctx,unsigned dest,unsigned offset,unsigned nr_comp,unsigned component,nir_src * indirect_offset,nir_alu_type type,bool flat)1189 emit_varying_read(
1190 compiler_context *ctx,
1191 unsigned dest, unsigned offset,
1192 unsigned nr_comp, unsigned component,
1193 nir_src *indirect_offset, nir_alu_type type, bool flat)
1194 {
1195 /* XXX: Half-floats? */
1196 /* TODO: swizzle, mask */
1197
1198 midgard_instruction ins = m_ld_vary_32(dest, offset);
1199 ins.mask = mask_of(nr_comp);
1200 ins.dest_type = type;
1201
1202 if (type == nir_type_float16) {
1203 /* Ensure we are aligned so we can pack it later */
1204 ins.mask = mask_of(ALIGN_POT(nr_comp, 2));
1205 }
1206
1207 for (unsigned i = 0; i < ARRAY_SIZE(ins.swizzle[0]); ++i)
1208 ins.swizzle[0][i] = MIN2(i + component, COMPONENT_W);
1209
1210 midgard_varying_parameter p = {
1211 .is_varying = 1,
1212 .interpolation = midgard_interp_default,
1213 .flat = flat,
1214 };
1215
1216 unsigned u;
1217 memcpy(&u, &p, sizeof(p));
1218 ins.load_store.varying_parameters = u;
1219
1220 if (indirect_offset) {
1221 ins.src[2] = nir_src_index(ctx, indirect_offset);
1222 ins.src_types[2] = nir_type_uint32;
1223 } else
1224 ins.load_store.arg_2 = 0x1E;
1225
1226 ins.load_store.arg_1 = 0x9E;
1227
1228 /* Use the type appropriate load */
1229 switch (type) {
1230 case nir_type_uint32:
1231 case nir_type_bool32:
1232 ins.op = midgard_op_ld_vary_32u;
1233 break;
1234 case nir_type_int32:
1235 ins.op = midgard_op_ld_vary_32i;
1236 break;
1237 case nir_type_float32:
1238 ins.op = midgard_op_ld_vary_32;
1239 break;
1240 case nir_type_float16:
1241 ins.op = midgard_op_ld_vary_16;
1242 break;
1243 default:
1244 unreachable("Attempted to load unknown type");
1245 break;
1246 }
1247
1248 emit_mir_instruction(ctx, ins);
1249 }
1250
1251 static void
emit_attr_read(compiler_context * ctx,unsigned dest,unsigned offset,unsigned nr_comp,nir_alu_type t)1252 emit_attr_read(
1253 compiler_context *ctx,
1254 unsigned dest, unsigned offset,
1255 unsigned nr_comp, nir_alu_type t)
1256 {
1257 midgard_instruction ins = m_ld_attr_32(dest, offset);
1258 ins.load_store.arg_1 = 0x1E;
1259 ins.load_store.arg_2 = 0x1E;
1260 ins.mask = mask_of(nr_comp);
1261
1262 /* Use the type appropriate load */
1263 switch (t) {
1264 case nir_type_uint:
1265 case nir_type_bool:
1266 ins.op = midgard_op_ld_attr_32u;
1267 break;
1268 case nir_type_int:
1269 ins.op = midgard_op_ld_attr_32i;
1270 break;
1271 case nir_type_float:
1272 ins.op = midgard_op_ld_attr_32;
1273 break;
1274 default:
1275 unreachable("Attempted to load unknown type");
1276 break;
1277 }
1278
1279 emit_mir_instruction(ctx, ins);
1280 }
1281
1282 static void
emit_sysval_read(compiler_context * ctx,nir_instr * instr,unsigned nr_components,unsigned offset)1283 emit_sysval_read(compiler_context *ctx, nir_instr *instr,
1284 unsigned nr_components, unsigned offset)
1285 {
1286 nir_dest nir_dest;
1287
1288 /* Figure out which uniform this is */
1289 int sysval = panfrost_sysval_for_instr(instr, &nir_dest);
1290 void *val = _mesa_hash_table_u64_search(ctx->sysvals.sysval_to_id, sysval);
1291
1292 unsigned dest = nir_dest_index(&nir_dest);
1293
1294 /* Sysvals are prefix uniforms */
1295 unsigned uniform = ((uintptr_t) val) - 1;
1296
1297 /* Emit the read itself -- this is never indirect */
1298 midgard_instruction *ins =
1299 emit_ubo_read(ctx, instr, dest, (uniform * 16) + offset, NULL, 0, 0);
1300
1301 ins->mask = mask_of(nr_components);
1302 }
1303
1304 static unsigned
compute_builtin_arg(nir_op op)1305 compute_builtin_arg(nir_op op)
1306 {
1307 switch (op) {
1308 case nir_intrinsic_load_work_group_id:
1309 return 0x14;
1310 case nir_intrinsic_load_local_invocation_id:
1311 return 0x10;
1312 default:
1313 unreachable("Invalid compute paramater loaded");
1314 }
1315 }
1316
1317 static void
emit_fragment_store(compiler_context * ctx,unsigned src,unsigned src_z,unsigned src_s,enum midgard_rt_id rt)1318 emit_fragment_store(compiler_context *ctx, unsigned src, unsigned src_z, unsigned src_s, enum midgard_rt_id rt)
1319 {
1320 assert(rt < ARRAY_SIZE(ctx->writeout_branch));
1321
1322 midgard_instruction *br = ctx->writeout_branch[rt];
1323
1324 assert(!br);
1325
1326 emit_explicit_constant(ctx, src, src);
1327
1328 struct midgard_instruction ins =
1329 v_branch(false, false);
1330
1331 bool depth_only = (rt == MIDGARD_ZS_RT);
1332
1333 ins.writeout = depth_only ? 0 : PAN_WRITEOUT_C;
1334
1335 /* Add dependencies */
1336 ins.src[0] = src;
1337 ins.src_types[0] = nir_type_uint32;
1338 ins.constants.u32[0] = depth_only ? 0xFF : (rt - MIDGARD_COLOR_RT0) * 0x100;
1339 for (int i = 0; i < 4; ++i)
1340 ins.swizzle[0][i] = i;
1341
1342 if (~src_z) {
1343 emit_explicit_constant(ctx, src_z, src_z);
1344 ins.src[2] = src_z;
1345 ins.src_types[2] = nir_type_uint32;
1346 ins.writeout |= PAN_WRITEOUT_Z;
1347 }
1348 if (~src_s) {
1349 emit_explicit_constant(ctx, src_s, src_s);
1350 ins.src[3] = src_s;
1351 ins.src_types[3] = nir_type_uint32;
1352 ins.writeout |= PAN_WRITEOUT_S;
1353 }
1354
1355 /* Emit the branch */
1356 br = emit_mir_instruction(ctx, ins);
1357 schedule_barrier(ctx);
1358 ctx->writeout_branch[rt] = br;
1359
1360 /* Push our current location = current block count - 1 = where we'll
1361 * jump to. Maybe a bit too clever for my own good */
1362
1363 br->branch.target_block = ctx->block_count - 1;
1364 }
1365
1366 static void
emit_compute_builtin(compiler_context * ctx,nir_intrinsic_instr * instr)1367 emit_compute_builtin(compiler_context *ctx, nir_intrinsic_instr *instr)
1368 {
1369 unsigned reg = nir_dest_index(&instr->dest);
1370 midgard_instruction ins = m_ld_compute_id(reg, 0);
1371 ins.mask = mask_of(3);
1372 ins.swizzle[0][3] = COMPONENT_X; /* xyzx */
1373 ins.load_store.arg_1 = compute_builtin_arg(instr->intrinsic);
1374 emit_mir_instruction(ctx, ins);
1375 }
1376
1377 static unsigned
vertex_builtin_arg(nir_op op)1378 vertex_builtin_arg(nir_op op)
1379 {
1380 switch (op) {
1381 case nir_intrinsic_load_vertex_id:
1382 return PAN_VERTEX_ID;
1383 case nir_intrinsic_load_instance_id:
1384 return PAN_INSTANCE_ID;
1385 default:
1386 unreachable("Invalid vertex builtin");
1387 }
1388 }
1389
1390 static void
emit_vertex_builtin(compiler_context * ctx,nir_intrinsic_instr * instr)1391 emit_vertex_builtin(compiler_context *ctx, nir_intrinsic_instr *instr)
1392 {
1393 unsigned reg = nir_dest_index(&instr->dest);
1394 emit_attr_read(ctx, reg, vertex_builtin_arg(instr->intrinsic), 1, nir_type_int);
1395 }
1396
1397 static void
emit_special(compiler_context * ctx,nir_intrinsic_instr * instr,unsigned idx)1398 emit_special(compiler_context *ctx, nir_intrinsic_instr *instr, unsigned idx)
1399 {
1400 unsigned reg = nir_dest_index(&instr->dest);
1401
1402 midgard_instruction ld = m_ld_color_buffer_32u(reg, 0);
1403 ld.op = midgard_op_ld_color_buffer_32u_old;
1404 ld.load_store.address = idx;
1405 ld.load_store.arg_2 = 0x1E;
1406
1407 for (int i = 0; i < 4; ++i)
1408 ld.swizzle[0][i] = COMPONENT_X;
1409
1410 emit_mir_instruction(ctx, ld);
1411 }
1412
1413 static void
emit_control_barrier(compiler_context * ctx)1414 emit_control_barrier(compiler_context *ctx)
1415 {
1416 midgard_instruction ins = {
1417 .type = TAG_TEXTURE_4,
1418 .dest = ~0,
1419 .src = { ~0, ~0, ~0, ~0 },
1420 .op = TEXTURE_OP_BARRIER,
1421 };
1422
1423 emit_mir_instruction(ctx, ins);
1424 }
1425
1426 static unsigned
mir_get_branch_cond(nir_src * src,bool * invert)1427 mir_get_branch_cond(nir_src *src, bool *invert)
1428 {
1429 /* Wrap it. No swizzle since it's a scalar */
1430
1431 nir_alu_src alu = {
1432 .src = *src
1433 };
1434
1435 *invert = pan_has_source_mod(&alu, nir_op_inot);
1436 return nir_src_index(NULL, &alu.src);
1437 }
1438
1439 static uint8_t
output_load_rt_addr(compiler_context * ctx,nir_intrinsic_instr * instr)1440 output_load_rt_addr(compiler_context *ctx, nir_intrinsic_instr *instr)
1441 {
1442 if (ctx->is_blend)
1443 return ctx->blend_rt;
1444
1445 const nir_variable *var;
1446 var = nir_find_variable_with_driver_location(ctx->nir, nir_var_shader_out, nir_intrinsic_base(instr));
1447 assert(var);
1448
1449 unsigned loc = var->data.location;
1450
1451 if (loc == FRAG_RESULT_COLOR)
1452 loc = FRAG_RESULT_DATA0;
1453
1454 if (loc >= FRAG_RESULT_DATA0)
1455 return loc - FRAG_RESULT_DATA0;
1456
1457 if (loc == FRAG_RESULT_DEPTH)
1458 return 0x1F;
1459 if (loc == FRAG_RESULT_STENCIL)
1460 return 0x1E;
1461
1462 unreachable("Invalid RT to load from");
1463 }
1464
1465 static void
emit_intrinsic(compiler_context * ctx,nir_intrinsic_instr * instr)1466 emit_intrinsic(compiler_context *ctx, nir_intrinsic_instr *instr)
1467 {
1468 unsigned offset = 0, reg;
1469
1470 switch (instr->intrinsic) {
1471 case nir_intrinsic_discard_if:
1472 case nir_intrinsic_discard: {
1473 bool conditional = instr->intrinsic == nir_intrinsic_discard_if;
1474 struct midgard_instruction discard = v_branch(conditional, false);
1475 discard.branch.target_type = TARGET_DISCARD;
1476
1477 if (conditional) {
1478 discard.src[0] = mir_get_branch_cond(&instr->src[0],
1479 &discard.branch.invert_conditional);
1480 discard.src_types[0] = nir_type_uint32;
1481 }
1482
1483 emit_mir_instruction(ctx, discard);
1484 schedule_barrier(ctx);
1485
1486 break;
1487 }
1488
1489 case nir_intrinsic_load_uniform:
1490 case nir_intrinsic_load_ubo:
1491 case nir_intrinsic_load_global:
1492 case nir_intrinsic_load_shared:
1493 case nir_intrinsic_load_input:
1494 case nir_intrinsic_load_interpolated_input: {
1495 bool is_uniform = instr->intrinsic == nir_intrinsic_load_uniform;
1496 bool is_ubo = instr->intrinsic == nir_intrinsic_load_ubo;
1497 bool is_global = instr->intrinsic == nir_intrinsic_load_global;
1498 bool is_shared = instr->intrinsic == nir_intrinsic_load_shared;
1499 bool is_flat = instr->intrinsic == nir_intrinsic_load_input;
1500 bool is_interp = instr->intrinsic == nir_intrinsic_load_interpolated_input;
1501
1502 /* Get the base type of the intrinsic */
1503 /* TODO: Infer type? Does it matter? */
1504 nir_alu_type t =
1505 (is_ubo || is_global || is_shared) ? nir_type_uint :
1506 (is_interp) ? nir_type_float :
1507 nir_intrinsic_dest_type(instr);
1508
1509 t = nir_alu_type_get_base_type(t);
1510
1511 if (!(is_ubo || is_global)) {
1512 offset = nir_intrinsic_base(instr);
1513 }
1514
1515 unsigned nr_comp = nir_intrinsic_dest_components(instr);
1516
1517 nir_src *src_offset = nir_get_io_offset_src(instr);
1518
1519 bool direct = nir_src_is_const(*src_offset);
1520 nir_src *indirect_offset = direct ? NULL : src_offset;
1521
1522 if (direct)
1523 offset += nir_src_as_uint(*src_offset);
1524
1525 /* We may need to apply a fractional offset */
1526 int component = (is_flat || is_interp) ?
1527 nir_intrinsic_component(instr) : 0;
1528 reg = nir_dest_index(&instr->dest);
1529
1530 if (is_uniform && !ctx->is_blend) {
1531 emit_ubo_read(ctx, &instr->instr, reg, (ctx->sysvals.sysval_count + offset) * 16, indirect_offset, 4, 0);
1532 } else if (is_ubo) {
1533 nir_src index = instr->src[0];
1534
1535 /* TODO: Is indirect block number possible? */
1536 assert(nir_src_is_const(index));
1537
1538 uint32_t uindex = nir_src_as_uint(index) + 1;
1539 emit_ubo_read(ctx, &instr->instr, reg, offset, indirect_offset, 0, uindex);
1540 } else if (is_global || is_shared) {
1541 emit_global(ctx, &instr->instr, true, reg, src_offset, is_shared);
1542 } else if (ctx->stage == MESA_SHADER_FRAGMENT && !ctx->is_blend) {
1543 emit_varying_read(ctx, reg, offset, nr_comp, component, indirect_offset, t | nir_dest_bit_size(instr->dest), is_flat);
1544 } else if (ctx->is_blend) {
1545 /* ctx->blend_input will be precoloured to r0/r2, where
1546 * the input is preloaded */
1547
1548 unsigned *input = offset ? &ctx->blend_src1 : &ctx->blend_input;
1549
1550 if (*input == ~0)
1551 *input = reg;
1552 else
1553 emit_mir_instruction(ctx, v_mov(*input, reg));
1554 } else if (ctx->stage == MESA_SHADER_VERTEX) {
1555 emit_attr_read(ctx, reg, offset, nr_comp, t);
1556 } else {
1557 DBG("Unknown load\n");
1558 assert(0);
1559 }
1560
1561 break;
1562 }
1563
1564 /* Artefact of load_interpolated_input. TODO: other barycentric modes */
1565 case nir_intrinsic_load_barycentric_pixel:
1566 case nir_intrinsic_load_barycentric_centroid:
1567 break;
1568
1569 /* Reads 128-bit value raw off the tilebuffer during blending, tasty */
1570
1571 case nir_intrinsic_load_raw_output_pan: {
1572 reg = nir_dest_index(&instr->dest);
1573
1574 /* T720 and below use different blend opcodes with slightly
1575 * different semantics than T760 and up */
1576
1577 midgard_instruction ld = m_ld_color_buffer_32u(reg, 0);
1578
1579 ld.load_store.arg_2 = output_load_rt_addr(ctx, instr);
1580
1581 if (nir_src_is_const(instr->src[0])) {
1582 ld.load_store.arg_1 = nir_src_as_uint(instr->src[0]);
1583 } else {
1584 ld.load_store.varying_parameters = 2;
1585 ld.src[1] = nir_src_index(ctx, &instr->src[0]);
1586 ld.src_types[1] = nir_type_int32;
1587 }
1588
1589 if (ctx->quirks & MIDGARD_OLD_BLEND) {
1590 ld.op = midgard_op_ld_color_buffer_32u_old;
1591 ld.load_store.address = 16;
1592 ld.load_store.arg_2 = 0x1E;
1593 }
1594
1595 emit_mir_instruction(ctx, ld);
1596 break;
1597 }
1598
1599 case nir_intrinsic_load_output: {
1600 reg = nir_dest_index(&instr->dest);
1601
1602 unsigned bits = nir_dest_bit_size(instr->dest);
1603
1604 midgard_instruction ld;
1605 if (bits == 16)
1606 ld = m_ld_color_buffer_as_fp16(reg, 0);
1607 else
1608 ld = m_ld_color_buffer_as_fp32(reg, 0);
1609
1610 ld.load_store.arg_2 = output_load_rt_addr(ctx, instr);
1611
1612 for (unsigned c = 4; c < 16; ++c)
1613 ld.swizzle[0][c] = 0;
1614
1615 if (ctx->quirks & MIDGARD_OLD_BLEND) {
1616 if (bits == 16)
1617 ld.op = midgard_op_ld_color_buffer_as_fp16_old;
1618 else
1619 ld.op = midgard_op_ld_color_buffer_as_fp32_old;
1620 ld.load_store.address = 1;
1621 ld.load_store.arg_2 = 0x1E;
1622 }
1623
1624 emit_mir_instruction(ctx, ld);
1625 break;
1626 }
1627
1628 case nir_intrinsic_load_blend_const_color_rgba: {
1629 assert(ctx->is_blend);
1630 reg = nir_dest_index(&instr->dest);
1631
1632 midgard_instruction ins = v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), reg);
1633 ins.has_constants = true;
1634 memcpy(ins.constants.f32, ctx->blend_constants, sizeof(ctx->blend_constants));
1635 emit_mir_instruction(ctx, ins);
1636 break;
1637 }
1638
1639 case nir_intrinsic_store_output:
1640 case nir_intrinsic_store_combined_output_pan:
1641 assert(nir_src_is_const(instr->src[1]) && "no indirect outputs");
1642
1643 offset = nir_intrinsic_base(instr) + nir_src_as_uint(instr->src[1]);
1644
1645 reg = nir_src_index(ctx, &instr->src[0]);
1646
1647 if (ctx->stage == MESA_SHADER_FRAGMENT) {
1648 bool combined = instr->intrinsic ==
1649 nir_intrinsic_store_combined_output_pan;
1650
1651 const nir_variable *var;
1652 var = nir_find_variable_with_driver_location(ctx->nir, nir_var_shader_out,
1653 nir_intrinsic_base(instr));
1654 assert(var);
1655
1656 /* Dual-source blend writeout is done by leaving the
1657 * value in r2 for the blend shader to use. */
1658 if (var->data.index) {
1659 if (instr->src[0].is_ssa) {
1660 emit_explicit_constant(ctx, reg, reg);
1661
1662 unsigned out = make_compiler_temp(ctx);
1663
1664 midgard_instruction ins = v_mov(reg, out);
1665 emit_mir_instruction(ctx, ins);
1666
1667 ctx->blend_src1 = out;
1668 } else {
1669 ctx->blend_src1 = reg;
1670 }
1671
1672 break;
1673 }
1674
1675 enum midgard_rt_id rt;
1676 if (var->data.location == FRAG_RESULT_COLOR)
1677 rt = MIDGARD_COLOR_RT0;
1678 else if (var->data.location >= FRAG_RESULT_DATA0)
1679 rt = MIDGARD_COLOR_RT0 + var->data.location -
1680 FRAG_RESULT_DATA0;
1681 else if (combined)
1682 rt = MIDGARD_ZS_RT;
1683 else
1684 unreachable("bad rt");
1685
1686 unsigned reg_z = ~0, reg_s = ~0;
1687 if (combined) {
1688 unsigned writeout = nir_intrinsic_component(instr);
1689 if (writeout & PAN_WRITEOUT_Z)
1690 reg_z = nir_src_index(ctx, &instr->src[2]);
1691 if (writeout & PAN_WRITEOUT_S)
1692 reg_s = nir_src_index(ctx, &instr->src[3]);
1693 }
1694
1695 emit_fragment_store(ctx, reg, reg_z, reg_s, rt);
1696 } else if (ctx->stage == MESA_SHADER_VERTEX) {
1697 assert(instr->intrinsic == nir_intrinsic_store_output);
1698
1699 /* We should have been vectorized, though we don't
1700 * currently check that st_vary is emitted only once
1701 * per slot (this is relevant, since there's not a mask
1702 * parameter available on the store [set to 0 by the
1703 * blob]). We do respect the component by adjusting the
1704 * swizzle. If this is a constant source, we'll need to
1705 * emit that explicitly. */
1706
1707 emit_explicit_constant(ctx, reg, reg);
1708
1709 unsigned dst_component = nir_intrinsic_component(instr);
1710 unsigned nr_comp = nir_src_num_components(instr->src[0]);
1711
1712 midgard_instruction st = m_st_vary_32(reg, offset);
1713 st.load_store.arg_1 = 0x9E;
1714 st.load_store.arg_2 = 0x1E;
1715
1716 switch (nir_alu_type_get_base_type(nir_intrinsic_src_type(instr))) {
1717 case nir_type_uint:
1718 case nir_type_bool:
1719 st.op = midgard_op_st_vary_32u;
1720 break;
1721 case nir_type_int:
1722 st.op = midgard_op_st_vary_32i;
1723 break;
1724 case nir_type_float:
1725 st.op = midgard_op_st_vary_32;
1726 break;
1727 default:
1728 unreachable("Attempted to store unknown type");
1729 break;
1730 }
1731
1732 /* nir_intrinsic_component(store_intr) encodes the
1733 * destination component start. Source component offset
1734 * adjustment is taken care of in
1735 * install_registers_instr(), when offset_swizzle() is
1736 * called.
1737 */
1738 unsigned src_component = COMPONENT_X;
1739
1740 assert(nr_comp > 0);
1741 for (unsigned i = 0; i < ARRAY_SIZE(st.swizzle); ++i) {
1742 st.swizzle[0][i] = src_component;
1743 if (i >= dst_component && i < dst_component + nr_comp - 1)
1744 src_component++;
1745 }
1746
1747 emit_mir_instruction(ctx, st);
1748 } else {
1749 DBG("Unknown store\n");
1750 assert(0);
1751 }
1752
1753 break;
1754
1755 /* Special case of store_output for lowered blend shaders */
1756 case nir_intrinsic_store_raw_output_pan:
1757 assert (ctx->stage == MESA_SHADER_FRAGMENT);
1758 reg = nir_src_index(ctx, &instr->src[0]);
1759 emit_fragment_store(ctx, reg, ~0, ~0, ctx->blend_rt);
1760 break;
1761
1762 case nir_intrinsic_store_global:
1763 case nir_intrinsic_store_shared:
1764 reg = nir_src_index(ctx, &instr->src[0]);
1765 emit_explicit_constant(ctx, reg, reg);
1766
1767 emit_global(ctx, &instr->instr, false, reg, &instr->src[1], instr->intrinsic == nir_intrinsic_store_shared);
1768 break;
1769
1770 case nir_intrinsic_load_ssbo_address:
1771 emit_sysval_read(ctx, &instr->instr, 1, 0);
1772 break;
1773
1774 case nir_intrinsic_get_ssbo_size:
1775 emit_sysval_read(ctx, &instr->instr, 1, 8);
1776 break;
1777
1778 case nir_intrinsic_load_viewport_scale:
1779 case nir_intrinsic_load_viewport_offset:
1780 case nir_intrinsic_load_num_work_groups:
1781 case nir_intrinsic_load_sampler_lod_parameters_pan:
1782 emit_sysval_read(ctx, &instr->instr, 3, 0);
1783 break;
1784
1785 case nir_intrinsic_load_work_group_id:
1786 case nir_intrinsic_load_local_invocation_id:
1787 emit_compute_builtin(ctx, instr);
1788 break;
1789
1790 case nir_intrinsic_load_vertex_id:
1791 case nir_intrinsic_load_instance_id:
1792 emit_vertex_builtin(ctx, instr);
1793 break;
1794
1795 case nir_intrinsic_load_sample_mask_in:
1796 emit_special(ctx, instr, 96);
1797 break;
1798
1799 case nir_intrinsic_load_sample_id:
1800 emit_special(ctx, instr, 97);
1801 break;
1802
1803 case nir_intrinsic_memory_barrier_buffer:
1804 case nir_intrinsic_memory_barrier_shared:
1805 break;
1806
1807 case nir_intrinsic_control_barrier:
1808 schedule_barrier(ctx);
1809 emit_control_barrier(ctx);
1810 schedule_barrier(ctx);
1811 break;
1812
1813 ATOMIC_CASE(ctx, instr, add, add);
1814 ATOMIC_CASE(ctx, instr, and, and);
1815 ATOMIC_CASE(ctx, instr, comp_swap, cmpxchg);
1816 ATOMIC_CASE(ctx, instr, exchange, xchg);
1817 ATOMIC_CASE(ctx, instr, imax, imax);
1818 ATOMIC_CASE(ctx, instr, imin, imin);
1819 ATOMIC_CASE(ctx, instr, or, or);
1820 ATOMIC_CASE(ctx, instr, umax, umax);
1821 ATOMIC_CASE(ctx, instr, umin, umin);
1822 ATOMIC_CASE(ctx, instr, xor, xor);
1823
1824 default:
1825 fprintf(stderr, "Unhandled intrinsic %s\n", nir_intrinsic_infos[instr->intrinsic].name);
1826 assert(0);
1827 break;
1828 }
1829 }
1830
1831 /* Returns dimension with 0 special casing cubemaps */
1832 static unsigned
midgard_tex_format(enum glsl_sampler_dim dim)1833 midgard_tex_format(enum glsl_sampler_dim dim)
1834 {
1835 switch (dim) {
1836 case GLSL_SAMPLER_DIM_1D:
1837 case GLSL_SAMPLER_DIM_BUF:
1838 return 1;
1839
1840 case GLSL_SAMPLER_DIM_2D:
1841 case GLSL_SAMPLER_DIM_MS:
1842 case GLSL_SAMPLER_DIM_EXTERNAL:
1843 case GLSL_SAMPLER_DIM_RECT:
1844 return 2;
1845
1846 case GLSL_SAMPLER_DIM_3D:
1847 return 3;
1848
1849 case GLSL_SAMPLER_DIM_CUBE:
1850 return 0;
1851
1852 default:
1853 DBG("Unknown sampler dim type\n");
1854 assert(0);
1855 return 0;
1856 }
1857 }
1858
1859 /* Tries to attach an explicit LOD or bias as a constant. Returns whether this
1860 * was successful */
1861
1862 static bool
pan_attach_constant_bias(compiler_context * ctx,nir_src lod,midgard_texture_word * word)1863 pan_attach_constant_bias(
1864 compiler_context *ctx,
1865 nir_src lod,
1866 midgard_texture_word *word)
1867 {
1868 /* To attach as constant, it has to *be* constant */
1869
1870 if (!nir_src_is_const(lod))
1871 return false;
1872
1873 float f = nir_src_as_float(lod);
1874
1875 /* Break into fixed-point */
1876 signed lod_int = f;
1877 float lod_frac = f - lod_int;
1878
1879 /* Carry over negative fractions */
1880 if (lod_frac < 0.0) {
1881 lod_int--;
1882 lod_frac += 1.0;
1883 }
1884
1885 /* Encode */
1886 word->bias = float_to_ubyte(lod_frac);
1887 word->bias_int = lod_int;
1888
1889 return true;
1890 }
1891
1892 static enum mali_texture_mode
mdg_texture_mode(nir_tex_instr * instr)1893 mdg_texture_mode(nir_tex_instr *instr)
1894 {
1895 if (instr->op == nir_texop_tg4 && instr->is_shadow)
1896 return TEXTURE_GATHER_SHADOW;
1897 else if (instr->op == nir_texop_tg4)
1898 return TEXTURE_GATHER_X + instr->component;
1899 else if (instr->is_shadow)
1900 return TEXTURE_SHADOW;
1901 else
1902 return TEXTURE_NORMAL;
1903 }
1904
1905 static void
emit_texop_native(compiler_context * ctx,nir_tex_instr * instr,unsigned midgard_texop)1906 emit_texop_native(compiler_context *ctx, nir_tex_instr *instr,
1907 unsigned midgard_texop)
1908 {
1909 /* TODO */
1910 //assert (!instr->sampler);
1911
1912 nir_dest *dest = &instr->dest;
1913
1914 int texture_index = instr->texture_index;
1915 int sampler_index = texture_index;
1916
1917 nir_alu_type dest_base = nir_alu_type_get_base_type(instr->dest_type);
1918 nir_alu_type dest_type = dest_base | nir_dest_bit_size(*dest);
1919
1920 /* texture instructions support float outmods */
1921 unsigned outmod = midgard_outmod_none;
1922 if (dest_base == nir_type_float) {
1923 outmod = mir_determine_float_outmod(ctx, &dest, 0);
1924 }
1925
1926 midgard_instruction ins = {
1927 .type = TAG_TEXTURE_4,
1928 .mask = 0xF,
1929 .dest = nir_dest_index(dest),
1930 .src = { ~0, ~0, ~0, ~0 },
1931 .dest_type = dest_type,
1932 .swizzle = SWIZZLE_IDENTITY_4,
1933 .outmod = outmod,
1934 .op = midgard_texop,
1935 .texture = {
1936 .format = midgard_tex_format(instr->sampler_dim),
1937 .texture_handle = texture_index,
1938 .sampler_handle = sampler_index,
1939 .mode = mdg_texture_mode(instr)
1940 }
1941 };
1942
1943 if (instr->is_shadow && !instr->is_new_style_shadow && instr->op != nir_texop_tg4)
1944 for (int i = 0; i < 4; ++i)
1945 ins.swizzle[0][i] = COMPONENT_X;
1946
1947 /* We may need a temporary for the coordinate */
1948
1949 bool needs_temp_coord =
1950 (midgard_texop == TEXTURE_OP_TEXEL_FETCH) ||
1951 (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) ||
1952 (instr->is_shadow);
1953
1954 unsigned coords = needs_temp_coord ? make_compiler_temp_reg(ctx) : 0;
1955
1956 for (unsigned i = 0; i < instr->num_srcs; ++i) {
1957 int index = nir_src_index(ctx, &instr->src[i].src);
1958 unsigned nr_components = nir_src_num_components(instr->src[i].src);
1959 unsigned sz = nir_src_bit_size(instr->src[i].src);
1960 nir_alu_type T = nir_tex_instr_src_type(instr, i) | sz;
1961
1962 switch (instr->src[i].src_type) {
1963 case nir_tex_src_coord: {
1964 emit_explicit_constant(ctx, index, index);
1965
1966 unsigned coord_mask = mask_of(instr->coord_components);
1967
1968 bool flip_zw = (instr->sampler_dim == GLSL_SAMPLER_DIM_2D) && (coord_mask & (1 << COMPONENT_Z));
1969
1970 if (flip_zw)
1971 coord_mask ^= ((1 << COMPONENT_Z) | (1 << COMPONENT_W));
1972
1973 if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) {
1974 /* texelFetch is undefined on samplerCube */
1975 assert(midgard_texop != TEXTURE_OP_TEXEL_FETCH);
1976
1977 /* For cubemaps, we use a special ld/st op to
1978 * select the face and copy the xy into the
1979 * texture register */
1980
1981 midgard_instruction ld = m_ld_cubemap_coords(coords, 0);
1982 ld.src[1] = index;
1983 ld.src_types[1] = T;
1984 ld.mask = 0x3; /* xy */
1985 ld.load_store.arg_1 = 0x20;
1986 ld.swizzle[1][3] = COMPONENT_X;
1987 emit_mir_instruction(ctx, ld);
1988
1989 /* xyzw -> xyxx */
1990 ins.swizzle[1][2] = instr->is_shadow ? COMPONENT_Z : COMPONENT_X;
1991 ins.swizzle[1][3] = COMPONENT_X;
1992 } else if (needs_temp_coord) {
1993 /* mov coord_temp, coords */
1994 midgard_instruction mov = v_mov(index, coords);
1995 mov.mask = coord_mask;
1996
1997 if (flip_zw)
1998 mov.swizzle[1][COMPONENT_W] = COMPONENT_Z;
1999
2000 emit_mir_instruction(ctx, mov);
2001 } else {
2002 coords = index;
2003 }
2004
2005 ins.src[1] = coords;
2006 ins.src_types[1] = T;
2007
2008 /* Texelfetch coordinates uses all four elements
2009 * (xyz/index) regardless of texture dimensionality,
2010 * which means it's necessary to zero the unused
2011 * components to keep everything happy */
2012
2013 if (midgard_texop == TEXTURE_OP_TEXEL_FETCH) {
2014 /* mov index.zw, #0, or generalized */
2015 midgard_instruction mov =
2016 v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), coords);
2017 mov.has_constants = true;
2018 mov.mask = coord_mask ^ 0xF;
2019 emit_mir_instruction(ctx, mov);
2020 }
2021
2022 if (instr->sampler_dim == GLSL_SAMPLER_DIM_2D) {
2023 /* Array component in w but NIR wants it in z,
2024 * but if we have a temp coord we already fixed
2025 * that up */
2026
2027 if (nr_components == 3) {
2028 ins.swizzle[1][2] = COMPONENT_Z;
2029 ins.swizzle[1][3] = needs_temp_coord ? COMPONENT_W : COMPONENT_Z;
2030 } else if (nr_components == 2) {
2031 ins.swizzle[1][2] =
2032 instr->is_shadow ? COMPONENT_Z : COMPONENT_X;
2033 ins.swizzle[1][3] = COMPONENT_X;
2034 } else
2035 unreachable("Invalid texture 2D components");
2036 }
2037
2038 if (midgard_texop == TEXTURE_OP_TEXEL_FETCH) {
2039 /* We zeroed */
2040 ins.swizzle[1][2] = COMPONENT_Z;
2041 ins.swizzle[1][3] = COMPONENT_W;
2042 }
2043
2044 break;
2045 }
2046
2047 case nir_tex_src_bias:
2048 case nir_tex_src_lod: {
2049 /* Try as a constant if we can */
2050
2051 bool is_txf = midgard_texop == TEXTURE_OP_TEXEL_FETCH;
2052 if (!is_txf && pan_attach_constant_bias(ctx, instr->src[i].src, &ins.texture))
2053 break;
2054
2055 ins.texture.lod_register = true;
2056 ins.src[2] = index;
2057 ins.src_types[2] = T;
2058
2059 for (unsigned c = 0; c < MIR_VEC_COMPONENTS; ++c)
2060 ins.swizzle[2][c] = COMPONENT_X;
2061
2062 emit_explicit_constant(ctx, index, index);
2063
2064 break;
2065 };
2066
2067 case nir_tex_src_offset: {
2068 ins.texture.offset_register = true;
2069 ins.src[3] = index;
2070 ins.src_types[3] = T;
2071
2072 for (unsigned c = 0; c < MIR_VEC_COMPONENTS; ++c)
2073 ins.swizzle[3][c] = (c > COMPONENT_Z) ? 0 : c;
2074
2075 emit_explicit_constant(ctx, index, index);
2076 break;
2077 };
2078
2079 case nir_tex_src_comparator:
2080 case nir_tex_src_ms_index: {
2081 unsigned comp = COMPONENT_Z;
2082
2083 /* mov coord_temp.foo, coords */
2084 midgard_instruction mov = v_mov(index, coords);
2085 mov.mask = 1 << comp;
2086
2087 for (unsigned i = 0; i < MIR_VEC_COMPONENTS; ++i)
2088 mov.swizzle[1][i] = COMPONENT_X;
2089
2090 emit_mir_instruction(ctx, mov);
2091 break;
2092 }
2093
2094 default: {
2095 fprintf(stderr, "Unknown texture source type: %d\n", instr->src[i].src_type);
2096 assert(0);
2097 }
2098 }
2099 }
2100
2101 emit_mir_instruction(ctx, ins);
2102 }
2103
2104 static void
emit_tex(compiler_context * ctx,nir_tex_instr * instr)2105 emit_tex(compiler_context *ctx, nir_tex_instr *instr)
2106 {
2107 switch (instr->op) {
2108 case nir_texop_tex:
2109 case nir_texop_txb:
2110 emit_texop_native(ctx, instr, TEXTURE_OP_NORMAL);
2111 break;
2112 case nir_texop_txl:
2113 case nir_texop_tg4:
2114 emit_texop_native(ctx, instr, TEXTURE_OP_LOD);
2115 break;
2116 case nir_texop_txf:
2117 case nir_texop_txf_ms:
2118 emit_texop_native(ctx, instr, TEXTURE_OP_TEXEL_FETCH);
2119 break;
2120 case nir_texop_txs:
2121 emit_sysval_read(ctx, &instr->instr, 4, 0);
2122 break;
2123 default: {
2124 fprintf(stderr, "Unhandled texture op: %d\n", instr->op);
2125 assert(0);
2126 }
2127 }
2128 }
2129
2130 static void
emit_jump(compiler_context * ctx,nir_jump_instr * instr)2131 emit_jump(compiler_context *ctx, nir_jump_instr *instr)
2132 {
2133 switch (instr->type) {
2134 case nir_jump_break: {
2135 /* Emit a branch out of the loop */
2136 struct midgard_instruction br = v_branch(false, false);
2137 br.branch.target_type = TARGET_BREAK;
2138 br.branch.target_break = ctx->current_loop_depth;
2139 emit_mir_instruction(ctx, br);
2140 break;
2141 }
2142
2143 default:
2144 DBG("Unknown jump type %d\n", instr->type);
2145 break;
2146 }
2147 }
2148
2149 static void
emit_instr(compiler_context * ctx,struct nir_instr * instr)2150 emit_instr(compiler_context *ctx, struct nir_instr *instr)
2151 {
2152 switch (instr->type) {
2153 case nir_instr_type_load_const:
2154 emit_load_const(ctx, nir_instr_as_load_const(instr));
2155 break;
2156
2157 case nir_instr_type_intrinsic:
2158 emit_intrinsic(ctx, nir_instr_as_intrinsic(instr));
2159 break;
2160
2161 case nir_instr_type_alu:
2162 emit_alu(ctx, nir_instr_as_alu(instr));
2163 break;
2164
2165 case nir_instr_type_tex:
2166 emit_tex(ctx, nir_instr_as_tex(instr));
2167 break;
2168
2169 case nir_instr_type_jump:
2170 emit_jump(ctx, nir_instr_as_jump(instr));
2171 break;
2172
2173 case nir_instr_type_ssa_undef:
2174 /* Spurious */
2175 break;
2176
2177 default:
2178 DBG("Unhandled instruction type\n");
2179 break;
2180 }
2181 }
2182
2183
2184 /* ALU instructions can inline or embed constants, which decreases register
2185 * pressure and saves space. */
2186
2187 #define CONDITIONAL_ATTACH(idx) { \
2188 void *entry = _mesa_hash_table_u64_search(ctx->ssa_constants, alu->src[idx] + 1); \
2189 \
2190 if (entry) { \
2191 attach_constants(ctx, alu, entry, alu->src[idx] + 1); \
2192 alu->src[idx] = SSA_FIXED_REGISTER(REGISTER_CONSTANT); \
2193 } \
2194 }
2195
2196 static void
inline_alu_constants(compiler_context * ctx,midgard_block * block)2197 inline_alu_constants(compiler_context *ctx, midgard_block *block)
2198 {
2199 mir_foreach_instr_in_block(block, alu) {
2200 /* Other instructions cannot inline constants */
2201 if (alu->type != TAG_ALU_4) continue;
2202 if (alu->compact_branch) continue;
2203
2204 /* If there is already a constant here, we can do nothing */
2205 if (alu->has_constants) continue;
2206
2207 CONDITIONAL_ATTACH(0);
2208
2209 if (!alu->has_constants) {
2210 CONDITIONAL_ATTACH(1)
2211 } else if (!alu->inline_constant) {
2212 /* Corner case: _two_ vec4 constants, for instance with a
2213 * csel. For this case, we can only use a constant
2214 * register for one, we'll have to emit a move for the
2215 * other. */
2216
2217 void *entry = _mesa_hash_table_u64_search(ctx->ssa_constants, alu->src[1] + 1);
2218 unsigned scratch = make_compiler_temp(ctx);
2219
2220 if (entry) {
2221 midgard_instruction ins = v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), scratch);
2222 attach_constants(ctx, &ins, entry, alu->src[1] + 1);
2223
2224 /* Set the source */
2225 alu->src[1] = scratch;
2226
2227 /* Inject us -before- the last instruction which set r31 */
2228 mir_insert_instruction_before(ctx, mir_prev_op(alu), ins);
2229 }
2230 }
2231 }
2232 }
2233
2234 unsigned
max_bitsize_for_alu(midgard_instruction * ins)2235 max_bitsize_for_alu(midgard_instruction *ins)
2236 {
2237 unsigned max_bitsize = 0;
2238 for (int i = 0; i < MIR_SRC_COUNT; i++) {
2239 if (ins->src[i] == ~0) continue;
2240 unsigned src_bitsize = nir_alu_type_get_type_size(ins->src_types[i]);
2241 max_bitsize = MAX2(src_bitsize, max_bitsize);
2242 }
2243 unsigned dst_bitsize = nir_alu_type_get_type_size(ins->dest_type);
2244 max_bitsize = MAX2(dst_bitsize, max_bitsize);
2245
2246 /* We don't have fp16 LUTs, so we'll want to emit code like:
2247 *
2248 * vlut.fsinr hr0, hr0
2249 *
2250 * where both input and output are 16-bit but the operation is carried
2251 * out in 32-bit
2252 */
2253
2254 switch (ins->op) {
2255 case midgard_alu_op_fsqrt:
2256 case midgard_alu_op_frcp:
2257 case midgard_alu_op_frsqrt:
2258 case midgard_alu_op_fsin:
2259 case midgard_alu_op_fcos:
2260 case midgard_alu_op_fexp2:
2261 case midgard_alu_op_flog2:
2262 max_bitsize = MAX2(max_bitsize, 32);
2263 break;
2264
2265 default:
2266 break;
2267 }
2268
2269 /* High implies computing at a higher bitsize, e.g umul_high of 32-bit
2270 * requires computing at 64-bit */
2271 if (midgard_is_integer_out_op(ins->op) && ins->outmod == midgard_outmod_int_high) {
2272 max_bitsize *= 2;
2273 assert(max_bitsize <= 64);
2274 }
2275
2276 return max_bitsize;
2277 }
2278
2279 midgard_reg_mode
reg_mode_for_bitsize(unsigned bitsize)2280 reg_mode_for_bitsize(unsigned bitsize)
2281 {
2282 switch (bitsize) {
2283 /* use 16 pipe for 8 since we don't support vec16 yet */
2284 case 8:
2285 case 16:
2286 return midgard_reg_mode_16;
2287 case 32:
2288 return midgard_reg_mode_32;
2289 case 64:
2290 return midgard_reg_mode_64;
2291 default:
2292 unreachable("invalid bit size");
2293 }
2294 }
2295
2296 /* Midgard supports two types of constants, embedded constants (128-bit) and
2297 * inline constants (16-bit). Sometimes, especially with scalar ops, embedded
2298 * constants can be demoted to inline constants, for space savings and
2299 * sometimes a performance boost */
2300
2301 static void
embedded_to_inline_constant(compiler_context * ctx,midgard_block * block)2302 embedded_to_inline_constant(compiler_context *ctx, midgard_block *block)
2303 {
2304 mir_foreach_instr_in_block(block, ins) {
2305 if (!ins->has_constants) continue;
2306 if (ins->has_inline_constant) continue;
2307
2308 unsigned max_bitsize = max_bitsize_for_alu(ins);
2309
2310 /* We can inline 32-bit (sometimes) or 16-bit (usually) */
2311 bool is_16 = max_bitsize == 16;
2312 bool is_32 = max_bitsize == 32;
2313
2314 if (!(is_16 || is_32))
2315 continue;
2316
2317 /* src1 cannot be an inline constant due to encoding
2318 * restrictions. So, if possible we try to flip the arguments
2319 * in that case */
2320
2321 int op = ins->op;
2322
2323 if (ins->src[0] == SSA_FIXED_REGISTER(REGISTER_CONSTANT) &&
2324 alu_opcode_props[op].props & OP_COMMUTES) {
2325 mir_flip(ins);
2326 }
2327
2328 if (ins->src[1] == SSA_FIXED_REGISTER(REGISTER_CONSTANT)) {
2329 /* Component is from the swizzle. Take a nonzero component */
2330 assert(ins->mask);
2331 unsigned first_comp = ffs(ins->mask) - 1;
2332 unsigned component = ins->swizzle[1][first_comp];
2333
2334 /* Scale constant appropriately, if we can legally */
2335 int16_t scaled_constant = 0;
2336
2337 if (is_16) {
2338 scaled_constant = ins->constants.u16[component];
2339 } else if (midgard_is_integer_op(op)) {
2340 scaled_constant = ins->constants.u32[component];
2341
2342 /* Constant overflow after resize */
2343 if (scaled_constant != ins->constants.u32[component])
2344 continue;
2345 } else {
2346 float original = ins->constants.f32[component];
2347 scaled_constant = _mesa_float_to_half(original);
2348
2349 /* Check for loss of precision. If this is
2350 * mediump, we don't care, but for a highp
2351 * shader, we need to pay attention. NIR
2352 * doesn't yet tell us which mode we're in!
2353 * Practically this prevents most constants
2354 * from being inlined, sadly. */
2355
2356 float fp32 = _mesa_half_to_float(scaled_constant);
2357
2358 if (fp32 != original)
2359 continue;
2360 }
2361
2362 /* Should've been const folded */
2363 if (ins->src_abs[1] || ins->src_neg[1])
2364 continue;
2365
2366 /* Make sure that the constant is not itself a vector
2367 * by checking if all accessed values are the same. */
2368
2369 const midgard_constants *cons = &ins->constants;
2370 uint32_t value = is_16 ? cons->u16[component] : cons->u32[component];
2371
2372 bool is_vector = false;
2373 unsigned mask = effective_writemask(ins->op, ins->mask);
2374
2375 for (unsigned c = 0; c < MIR_VEC_COMPONENTS; ++c) {
2376 /* We only care if this component is actually used */
2377 if (!(mask & (1 << c)))
2378 continue;
2379
2380 uint32_t test = is_16 ?
2381 cons->u16[ins->swizzle[1][c]] :
2382 cons->u32[ins->swizzle[1][c]];
2383
2384 if (test != value) {
2385 is_vector = true;
2386 break;
2387 }
2388 }
2389
2390 if (is_vector)
2391 continue;
2392
2393 /* Get rid of the embedded constant */
2394 ins->has_constants = false;
2395 ins->src[1] = ~0;
2396 ins->has_inline_constant = true;
2397 ins->inline_constant = scaled_constant;
2398 }
2399 }
2400 }
2401
2402 /* Dead code elimination for branches at the end of a block - only one branch
2403 * per block is legal semantically */
2404
2405 static void
midgard_cull_dead_branch(compiler_context * ctx,midgard_block * block)2406 midgard_cull_dead_branch(compiler_context *ctx, midgard_block *block)
2407 {
2408 bool branched = false;
2409
2410 mir_foreach_instr_in_block_safe(block, ins) {
2411 if (!midgard_is_branch_unit(ins->unit)) continue;
2412
2413 if (branched)
2414 mir_remove_instruction(ins);
2415
2416 branched = true;
2417 }
2418 }
2419
2420 /* We want to force the invert on AND/OR to the second slot to legalize into
2421 * iandnot/iornot. The relevant patterns are for AND (and OR respectively)
2422 *
2423 * ~a & #b = ~a & ~(#~b)
2424 * ~a & b = b & ~a
2425 */
2426
2427 static void
midgard_legalize_invert(compiler_context * ctx,midgard_block * block)2428 midgard_legalize_invert(compiler_context *ctx, midgard_block *block)
2429 {
2430 mir_foreach_instr_in_block(block, ins) {
2431 if (ins->type != TAG_ALU_4) continue;
2432
2433 if (ins->op != midgard_alu_op_iand &&
2434 ins->op != midgard_alu_op_ior) continue;
2435
2436 if (ins->src_invert[1] || !ins->src_invert[0]) continue;
2437
2438 if (ins->has_inline_constant) {
2439 /* ~(#~a) = ~(~#a) = a, so valid, and forces both
2440 * inverts on */
2441 ins->inline_constant = ~ins->inline_constant;
2442 ins->src_invert[1] = true;
2443 } else {
2444 /* Flip to the right invert order. Note
2445 * has_inline_constant false by assumption on the
2446 * branch, so flipping makes sense. */
2447 mir_flip(ins);
2448 }
2449 }
2450 }
2451
2452 static unsigned
emit_fragment_epilogue(compiler_context * ctx,unsigned rt)2453 emit_fragment_epilogue(compiler_context *ctx, unsigned rt)
2454 {
2455 /* Loop to ourselves */
2456 midgard_instruction *br = ctx->writeout_branch[rt];
2457 struct midgard_instruction ins = v_branch(false, false);
2458 ins.writeout = br->writeout;
2459 ins.branch.target_block = ctx->block_count - 1;
2460 ins.constants.u32[0] = br->constants.u32[0];
2461 memcpy(&ins.src_types, &br->src_types, sizeof(ins.src_types));
2462 emit_mir_instruction(ctx, ins);
2463
2464 ctx->current_block->epilogue = true;
2465 schedule_barrier(ctx);
2466 return ins.branch.target_block;
2467 }
2468
2469 static midgard_block *
emit_block_init(compiler_context * ctx)2470 emit_block_init(compiler_context *ctx)
2471 {
2472 midgard_block *this_block = ctx->after_block;
2473 ctx->after_block = NULL;
2474
2475 if (!this_block)
2476 this_block = create_empty_block(ctx);
2477
2478 list_addtail(&this_block->base.link, &ctx->blocks);
2479
2480 this_block->scheduled = false;
2481 ++ctx->block_count;
2482
2483 /* Set up current block */
2484 list_inithead(&this_block->base.instructions);
2485 ctx->current_block = this_block;
2486
2487 return this_block;
2488 }
2489
2490 static midgard_block *
emit_block(compiler_context * ctx,nir_block * block)2491 emit_block(compiler_context *ctx, nir_block *block)
2492 {
2493 midgard_block *this_block = emit_block_init(ctx);
2494
2495 nir_foreach_instr(instr, block) {
2496 emit_instr(ctx, instr);
2497 ++ctx->instruction_count;
2498 }
2499
2500 return this_block;
2501 }
2502
2503 static midgard_block *emit_cf_list(struct compiler_context *ctx, struct exec_list *list);
2504
2505 static void
emit_if(struct compiler_context * ctx,nir_if * nif)2506 emit_if(struct compiler_context *ctx, nir_if *nif)
2507 {
2508 midgard_block *before_block = ctx->current_block;
2509
2510 /* Speculatively emit the branch, but we can't fill it in until later */
2511 bool inv = false;
2512 EMIT(branch, true, true);
2513 midgard_instruction *then_branch = mir_last_in_block(ctx->current_block);
2514 then_branch->src[0] = mir_get_branch_cond(&nif->condition, &inv);
2515 then_branch->src_types[0] = nir_type_uint32;
2516 then_branch->branch.invert_conditional = !inv;
2517
2518 /* Emit the two subblocks. */
2519 midgard_block *then_block = emit_cf_list(ctx, &nif->then_list);
2520 midgard_block *end_then_block = ctx->current_block;
2521
2522 /* Emit a jump from the end of the then block to the end of the else */
2523 EMIT(branch, false, false);
2524 midgard_instruction *then_exit = mir_last_in_block(ctx->current_block);
2525
2526 /* Emit second block, and check if it's empty */
2527
2528 int else_idx = ctx->block_count;
2529 int count_in = ctx->instruction_count;
2530 midgard_block *else_block = emit_cf_list(ctx, &nif->else_list);
2531 midgard_block *end_else_block = ctx->current_block;
2532 int after_else_idx = ctx->block_count;
2533
2534 /* Now that we have the subblocks emitted, fix up the branches */
2535
2536 assert(then_block);
2537 assert(else_block);
2538
2539 if (ctx->instruction_count == count_in) {
2540 /* The else block is empty, so don't emit an exit jump */
2541 mir_remove_instruction(then_exit);
2542 then_branch->branch.target_block = after_else_idx;
2543 } else {
2544 then_branch->branch.target_block = else_idx;
2545 then_exit->branch.target_block = after_else_idx;
2546 }
2547
2548 /* Wire up the successors */
2549
2550 ctx->after_block = create_empty_block(ctx);
2551
2552 pan_block_add_successor(&before_block->base, &then_block->base);
2553 pan_block_add_successor(&before_block->base, &else_block->base);
2554
2555 pan_block_add_successor(&end_then_block->base, &ctx->after_block->base);
2556 pan_block_add_successor(&end_else_block->base, &ctx->after_block->base);
2557 }
2558
2559 static void
emit_loop(struct compiler_context * ctx,nir_loop * nloop)2560 emit_loop(struct compiler_context *ctx, nir_loop *nloop)
2561 {
2562 /* Remember where we are */
2563 midgard_block *start_block = ctx->current_block;
2564
2565 /* Allocate a loop number, growing the current inner loop depth */
2566 int loop_idx = ++ctx->current_loop_depth;
2567
2568 /* Get index from before the body so we can loop back later */
2569 int start_idx = ctx->block_count;
2570
2571 /* Emit the body itself */
2572 midgard_block *loop_block = emit_cf_list(ctx, &nloop->body);
2573
2574 /* Branch back to loop back */
2575 struct midgard_instruction br_back = v_branch(false, false);
2576 br_back.branch.target_block = start_idx;
2577 emit_mir_instruction(ctx, br_back);
2578
2579 /* Mark down that branch in the graph. */
2580 pan_block_add_successor(&start_block->base, &loop_block->base);
2581 pan_block_add_successor(&ctx->current_block->base, &loop_block->base);
2582
2583 /* Find the index of the block about to follow us (note: we don't add
2584 * one; blocks are 0-indexed so we get a fencepost problem) */
2585 int break_block_idx = ctx->block_count;
2586
2587 /* Fix up the break statements we emitted to point to the right place,
2588 * now that we can allocate a block number for them */
2589 ctx->after_block = create_empty_block(ctx);
2590
2591 mir_foreach_block_from(ctx, start_block, _block) {
2592 mir_foreach_instr_in_block(((midgard_block *) _block), ins) {
2593 if (ins->type != TAG_ALU_4) continue;
2594 if (!ins->compact_branch) continue;
2595
2596 /* We found a branch -- check the type to see if we need to do anything */
2597 if (ins->branch.target_type != TARGET_BREAK) continue;
2598
2599 /* It's a break! Check if it's our break */
2600 if (ins->branch.target_break != loop_idx) continue;
2601
2602 /* Okay, cool, we're breaking out of this loop.
2603 * Rewrite from a break to a goto */
2604
2605 ins->branch.target_type = TARGET_GOTO;
2606 ins->branch.target_block = break_block_idx;
2607
2608 pan_block_add_successor(_block, &ctx->after_block->base);
2609 }
2610 }
2611
2612 /* Now that we've finished emitting the loop, free up the depth again
2613 * so we play nice with recursion amid nested loops */
2614 --ctx->current_loop_depth;
2615
2616 /* Dump loop stats */
2617 ++ctx->loop_count;
2618 }
2619
2620 static midgard_block *
emit_cf_list(struct compiler_context * ctx,struct exec_list * list)2621 emit_cf_list(struct compiler_context *ctx, struct exec_list *list)
2622 {
2623 midgard_block *start_block = NULL;
2624
2625 foreach_list_typed(nir_cf_node, node, node, list) {
2626 switch (node->type) {
2627 case nir_cf_node_block: {
2628 midgard_block *block = emit_block(ctx, nir_cf_node_as_block(node));
2629
2630 if (!start_block)
2631 start_block = block;
2632
2633 break;
2634 }
2635
2636 case nir_cf_node_if:
2637 emit_if(ctx, nir_cf_node_as_if(node));
2638 break;
2639
2640 case nir_cf_node_loop:
2641 emit_loop(ctx, nir_cf_node_as_loop(node));
2642 break;
2643
2644 case nir_cf_node_function:
2645 assert(0);
2646 break;
2647 }
2648 }
2649
2650 return start_block;
2651 }
2652
2653 /* Due to lookahead, we need to report the first tag executed in the command
2654 * stream and in branch targets. An initial block might be empty, so iterate
2655 * until we find one that 'works' */
2656
2657 unsigned
midgard_get_first_tag_from_block(compiler_context * ctx,unsigned block_idx)2658 midgard_get_first_tag_from_block(compiler_context *ctx, unsigned block_idx)
2659 {
2660 midgard_block *initial_block = mir_get_block(ctx, block_idx);
2661
2662 mir_foreach_block_from(ctx, initial_block, _v) {
2663 midgard_block *v = (midgard_block *) _v;
2664 if (v->quadword_count) {
2665 midgard_bundle *initial_bundle =
2666 util_dynarray_element(&v->bundles, midgard_bundle, 0);
2667
2668 return initial_bundle->tag;
2669 }
2670 }
2671
2672 /* Default to a tag 1 which will break from the shader, in case we jump
2673 * to the exit block (i.e. `return` in a compute shader) */
2674
2675 return 1;
2676 }
2677
2678 /* For each fragment writeout instruction, generate a writeout loop to
2679 * associate with it */
2680
2681 static void
mir_add_writeout_loops(compiler_context * ctx)2682 mir_add_writeout_loops(compiler_context *ctx)
2683 {
2684 for (unsigned rt = 0; rt < ARRAY_SIZE(ctx->writeout_branch); ++rt) {
2685 midgard_instruction *br = ctx->writeout_branch[rt];
2686 if (!br) continue;
2687
2688 unsigned popped = br->branch.target_block;
2689 pan_block_add_successor(&(mir_get_block(ctx, popped - 1)->base), &ctx->current_block->base);
2690 br->branch.target_block = emit_fragment_epilogue(ctx, rt);
2691 br->branch.target_type = TARGET_GOTO;
2692
2693 /* If we have more RTs, we'll need to restore back after our
2694 * loop terminates */
2695
2696 if ((rt + 1) < ARRAY_SIZE(ctx->writeout_branch) && ctx->writeout_branch[rt + 1]) {
2697 midgard_instruction uncond = v_branch(false, false);
2698 uncond.branch.target_block = popped;
2699 uncond.branch.target_type = TARGET_GOTO;
2700 emit_mir_instruction(ctx, uncond);
2701 pan_block_add_successor(&ctx->current_block->base, &(mir_get_block(ctx, popped)->base));
2702 schedule_barrier(ctx);
2703 } else {
2704 /* We're last, so we can terminate here */
2705 br->last_writeout = true;
2706 }
2707 }
2708 }
2709
2710 panfrost_program *
midgard_compile_shader_nir(void * mem_ctx,nir_shader * nir,const struct panfrost_compile_inputs * inputs)2711 midgard_compile_shader_nir(void *mem_ctx, nir_shader *nir,
2712 const struct panfrost_compile_inputs *inputs)
2713 {
2714 panfrost_program *program = rzalloc(mem_ctx, panfrost_program);
2715
2716 struct util_dynarray *compiled = &program->compiled;
2717
2718 midgard_debug = debug_get_option_midgard_debug();
2719
2720 /* TODO: Bound against what? */
2721 compiler_context *ctx = rzalloc(NULL, compiler_context);
2722
2723 ctx->nir = nir;
2724 ctx->stage = nir->info.stage;
2725 ctx->is_blend = inputs->is_blend;
2726 ctx->blend_rt = MIDGARD_COLOR_RT0 + inputs->blend.rt;
2727 memcpy(ctx->blend_constants, inputs->blend.constants, sizeof(ctx->blend_constants));
2728 ctx->blend_input = ~0;
2729 ctx->blend_src1 = ~0;
2730 ctx->quirks = midgard_get_quirks(inputs->gpu_id);
2731
2732 /* Start off with a safe cutoff, allowing usage of all 16 work
2733 * registers. Later, we'll promote uniform reads to uniform registers
2734 * if we determine it is beneficial to do so */
2735 ctx->uniform_cutoff = 8;
2736
2737 /* Initialize at a global (not block) level hash tables */
2738
2739 ctx->ssa_constants = _mesa_hash_table_u64_create(NULL);
2740
2741 /* Lower gl_Position pre-optimisation, but after lowering vars to ssa
2742 * (so we don't accidentally duplicate the epilogue since mesa/st has
2743 * messed with our I/O quite a bit already) */
2744
2745 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
2746
2747 if (ctx->stage == MESA_SHADER_VERTEX) {
2748 NIR_PASS_V(nir, nir_lower_viewport_transform);
2749 NIR_PASS_V(nir, nir_lower_point_size, 1.0, 1024.0);
2750 }
2751
2752 NIR_PASS_V(nir, nir_lower_var_copies);
2753 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
2754 NIR_PASS_V(nir, nir_split_var_copies);
2755 NIR_PASS_V(nir, nir_lower_var_copies);
2756 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
2757 NIR_PASS_V(nir, nir_lower_var_copies);
2758 NIR_PASS_V(nir, nir_lower_vars_to_ssa);
2759
2760 unsigned pan_quirks = panfrost_get_quirks(inputs->gpu_id);
2761 NIR_PASS_V(nir, pan_lower_framebuffer,
2762 inputs->rt_formats, inputs->is_blend, pan_quirks);
2763
2764 NIR_PASS_V(nir, nir_lower_io, nir_var_shader_in | nir_var_shader_out,
2765 glsl_type_size, 0);
2766 NIR_PASS_V(nir, nir_lower_ssbo);
2767 NIR_PASS_V(nir, pan_nir_lower_zs_store);
2768
2769 /* Optimisation passes */
2770
2771 optimise_nir(nir, ctx->quirks, inputs->is_blend);
2772
2773 NIR_PASS_V(nir, pan_nir_reorder_writeout);
2774
2775 if ((midgard_debug & MIDGARD_DBG_SHADERS) && !nir->info.internal) {
2776 nir_print_shader(nir, stdout);
2777 }
2778
2779 /* Assign sysvals and counts, now that we're sure
2780 * (post-optimisation) */
2781
2782 panfrost_nir_assign_sysvals(&ctx->sysvals, ctx, nir);
2783 program->sysval_count = ctx->sysvals.sysval_count;
2784 memcpy(program->sysvals, ctx->sysvals.sysvals, sizeof(ctx->sysvals.sysvals[0]) * ctx->sysvals.sysval_count);
2785
2786 nir_foreach_function(func, nir) {
2787 if (!func->impl)
2788 continue;
2789
2790 list_inithead(&ctx->blocks);
2791 ctx->block_count = 0;
2792 ctx->func = func;
2793 ctx->already_emitted = calloc(BITSET_WORDS(func->impl->ssa_alloc), sizeof(BITSET_WORD));
2794
2795 if (nir->info.outputs_read && !inputs->is_blend) {
2796 emit_block_init(ctx);
2797
2798 struct midgard_instruction wait = v_branch(false, false);
2799 wait.branch.target_type = TARGET_TILEBUF_WAIT;
2800
2801 emit_mir_instruction(ctx, wait);
2802
2803 ++ctx->instruction_count;
2804 }
2805
2806 emit_cf_list(ctx, &func->impl->body);
2807 free(ctx->already_emitted);
2808 break; /* TODO: Multi-function shaders */
2809 }
2810
2811 util_dynarray_init(compiled, program);
2812
2813 /* Per-block lowering before opts */
2814
2815 mir_foreach_block(ctx, _block) {
2816 midgard_block *block = (midgard_block *) _block;
2817 inline_alu_constants(ctx, block);
2818 embedded_to_inline_constant(ctx, block);
2819 }
2820 /* MIR-level optimizations */
2821
2822 bool progress = false;
2823
2824 do {
2825 progress = false;
2826 progress |= midgard_opt_dead_code_eliminate(ctx);
2827
2828 mir_foreach_block(ctx, _block) {
2829 midgard_block *block = (midgard_block *) _block;
2830 progress |= midgard_opt_copy_prop(ctx, block);
2831 progress |= midgard_opt_combine_projection(ctx, block);
2832 progress |= midgard_opt_varying_projection(ctx, block);
2833 }
2834 } while (progress);
2835
2836 mir_foreach_block(ctx, _block) {
2837 midgard_block *block = (midgard_block *) _block;
2838 midgard_lower_derivatives(ctx, block);
2839 midgard_legalize_invert(ctx, block);
2840 midgard_cull_dead_branch(ctx, block);
2841 }
2842
2843 if (ctx->stage == MESA_SHADER_FRAGMENT)
2844 mir_add_writeout_loops(ctx);
2845
2846 /* Analyze now that the code is known but before scheduling creates
2847 * pipeline registers which are harder to track */
2848 mir_analyze_helper_terminate(ctx);
2849 mir_analyze_helper_requirements(ctx);
2850
2851 /* Schedule! */
2852 midgard_schedule_program(ctx);
2853 mir_ra(ctx);
2854
2855 /* Emit flat binary from the instruction arrays. Iterate each block in
2856 * sequence. Save instruction boundaries such that lookahead tags can
2857 * be assigned easily */
2858
2859 /* Cache _all_ bundles in source order for lookahead across failed branches */
2860
2861 int bundle_count = 0;
2862 mir_foreach_block(ctx, _block) {
2863 midgard_block *block = (midgard_block *) _block;
2864 bundle_count += block->bundles.size / sizeof(midgard_bundle);
2865 }
2866 midgard_bundle **source_order_bundles = malloc(sizeof(midgard_bundle *) * bundle_count);
2867 int bundle_idx = 0;
2868 mir_foreach_block(ctx, _block) {
2869 midgard_block *block = (midgard_block *) _block;
2870 util_dynarray_foreach(&block->bundles, midgard_bundle, bundle) {
2871 source_order_bundles[bundle_idx++] = bundle;
2872 }
2873 }
2874
2875 int current_bundle = 0;
2876
2877 /* Midgard prefetches instruction types, so during emission we
2878 * need to lookahead. Unless this is the last instruction, in
2879 * which we return 1. */
2880
2881 mir_foreach_block(ctx, _block) {
2882 midgard_block *block = (midgard_block *) _block;
2883 mir_foreach_bundle_in_block(block, bundle) {
2884 int lookahead = 1;
2885
2886 if (!bundle->last_writeout && (current_bundle + 1 < bundle_count))
2887 lookahead = source_order_bundles[current_bundle + 1]->tag;
2888
2889 emit_binary_bundle(ctx, block, bundle, compiled, lookahead);
2890 ++current_bundle;
2891 }
2892
2893 /* TODO: Free deeper */
2894 //util_dynarray_fini(&block->instructions);
2895 }
2896
2897 free(source_order_bundles);
2898
2899 /* Report the very first tag executed */
2900 program->first_tag = midgard_get_first_tag_from_block(ctx, 0);
2901
2902 /* Deal with off-by-one related to the fencepost problem */
2903 program->work_register_count = ctx->work_registers + 1;
2904 program->uniform_cutoff = ctx->uniform_cutoff;
2905
2906 program->tls_size = ctx->tls_size;
2907
2908 if ((midgard_debug & MIDGARD_DBG_SHADERS) && !nir->info.internal) {
2909 disassemble_midgard(stdout,
2910 program->compiled.data,
2911 program->compiled.size,
2912 inputs->gpu_id, ctx->stage);
2913 }
2914
2915 if ((midgard_debug & MIDGARD_DBG_SHADERDB || inputs->shaderdb) &&
2916 !nir->info.internal) {
2917 unsigned nr_bundles = 0, nr_ins = 0;
2918
2919 /* Count instructions and bundles */
2920
2921 mir_foreach_block(ctx, _block) {
2922 midgard_block *block = (midgard_block *) _block;
2923 nr_bundles += util_dynarray_num_elements(
2924 &block->bundles, midgard_bundle);
2925
2926 mir_foreach_bundle_in_block(block, bun)
2927 nr_ins += bun->instruction_count;
2928 }
2929
2930 /* Calculate thread count. There are certain cutoffs by
2931 * register count for thread count */
2932
2933 unsigned nr_registers = program->work_register_count;
2934
2935 unsigned nr_threads =
2936 (nr_registers <= 4) ? 4 :
2937 (nr_registers <= 8) ? 2 :
2938 1;
2939
2940 /* Dump stats */
2941
2942 fprintf(stderr, "shader%d - %s shader: "
2943 "%u inst, %u bundles, %u quadwords, "
2944 "%u registers, %u threads, %u loops, "
2945 "%u:%u spills:fills\n",
2946 SHADER_DB_COUNT++,
2947 ctx->is_blend ? "PAN_SHADER_BLEND" :
2948 gl_shader_stage_name(ctx->stage),
2949 nr_ins, nr_bundles, ctx->quadword_count,
2950 nr_registers, nr_threads,
2951 ctx->loop_count,
2952 ctx->spills, ctx->fills);
2953 }
2954
2955 ralloc_free(ctx);
2956
2957 return program;
2958 }
2959