• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <err.h>
26 #include <fcntl.h>
27 #include <stdint.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <sys/mman.h>
31 #include <sys/stat.h>
32 #include <sys/types.h>
33 
34 #include "compiler/glsl/glsl_to_nir.h"
35 #include "compiler/glsl_types.h"
36 #include "compiler/nir/nir_builder.h"
37 #include "util/half_float.h"
38 #include "util/list.h"
39 #include "util/u_debug.h"
40 #include "util/u_dynarray.h"
41 #include "util/u_math.h"
42 
43 #include "compiler.h"
44 #include "helpers.h"
45 #include "midgard.h"
46 #include "midgard_compile.h"
47 #include "midgard_nir.h"
48 #include "midgard_ops.h"
49 #include "midgard_quirks.h"
50 
51 #include "disassemble.h"
52 
53 static const struct debug_named_value midgard_debug_options[] = {
54    {"shaders", MIDGARD_DBG_SHADERS, "Dump shaders in NIR and MIR"},
55    {"shaderdb", MIDGARD_DBG_SHADERDB, "Prints shader-db statistics"},
56    {"inorder", MIDGARD_DBG_INORDER, "Disables out-of-order scheduling"},
57    {"verbose", MIDGARD_DBG_VERBOSE, "Dump shaders verbosely"},
58    {"internal", MIDGARD_DBG_INTERNAL, "Dump internal shaders"},
59    DEBUG_NAMED_VALUE_END};
60 
61 DEBUG_GET_ONCE_FLAGS_OPTION(midgard_debug, "MIDGARD_MESA_DEBUG",
62                             midgard_debug_options, 0)
63 
64 int midgard_debug = 0;
65 
66 static midgard_block *
create_empty_block(compiler_context * ctx)67 create_empty_block(compiler_context *ctx)
68 {
69    midgard_block *blk = rzalloc(ctx, midgard_block);
70 
71    blk->base.predecessors =
72       _mesa_set_create(blk, _mesa_hash_pointer, _mesa_key_pointer_equal);
73 
74    blk->base.name = ctx->block_source_count++;
75 
76    return blk;
77 }
78 
79 static void
schedule_barrier(compiler_context * ctx)80 schedule_barrier(compiler_context *ctx)
81 {
82    midgard_block *temp = ctx->after_block;
83    ctx->after_block = create_empty_block(ctx);
84    ctx->block_count++;
85    list_addtail(&ctx->after_block->base.link, &ctx->blocks);
86    list_inithead(&ctx->after_block->base.instructions);
87    pan_block_add_successor(&ctx->current_block->base, &ctx->after_block->base);
88    ctx->current_block = ctx->after_block;
89    ctx->after_block = temp;
90 }
91 
92 /* Helpers to generate midgard_instruction's using macro magic, since every
93  * driver seems to do it that way */
94 
95 #define EMIT(op, ...) do {                                                     \
96    struct midgard_instruction ins = v_##op(__VA_ARGS__);                       \
97    emit_mir_instruction(ctx, &ins);                                            \
98 } while(0)
99 
100 #define M_LOAD_STORE(name, store, T)                                           \
101    static midgard_instruction m_##name(unsigned ssa, unsigned address)         \
102    {                                                                           \
103       midgard_instruction i = {                                                \
104          .type = TAG_LOAD_STORE_4,                                             \
105          .mask = 0xF,                                                          \
106          .dest = ~0,                                                           \
107          .src = {~0, ~0, ~0, ~0},                                              \
108          .swizzle = SWIZZLE_IDENTITY_4,                                        \
109          .op = midgard_op_##name,                                              \
110          .load_store =                                                         \
111             {                                                                  \
112                .signed_offset = address,                                       \
113             },                                                                 \
114       };                                                                       \
115                                                                                \
116       if (store) {                                                             \
117          i.src[0] = ssa;                                                       \
118          i.src_types[0] = T;                                                   \
119          i.dest_type = T;                                                      \
120       } else {                                                                 \
121          i.dest = ssa;                                                         \
122          i.dest_type = T;                                                      \
123       }                                                                        \
124       return i;                                                                \
125    }
126 
127 #define M_LOAD(name, T)  M_LOAD_STORE(name, false, T)
128 #define M_STORE(name, T) M_LOAD_STORE(name, true, T)
129 
130 M_LOAD(ld_attr_32, nir_type_uint32);
131 M_LOAD(ld_vary_32, nir_type_uint32);
132 M_LOAD(ld_ubo_u8, nir_type_uint32); /* mandatory extension to 32-bit */
133 M_LOAD(ld_ubo_u16, nir_type_uint32);
134 M_LOAD(ld_ubo_32, nir_type_uint32);
135 M_LOAD(ld_ubo_64, nir_type_uint32);
136 M_LOAD(ld_ubo_128, nir_type_uint32);
137 M_LOAD(ld_u8, nir_type_uint8);
138 M_LOAD(ld_u16, nir_type_uint16);
139 M_LOAD(ld_32, nir_type_uint32);
140 M_LOAD(ld_64, nir_type_uint32);
141 M_LOAD(ld_128, nir_type_uint32);
142 M_STORE(st_u8, nir_type_uint8);
143 M_STORE(st_u16, nir_type_uint16);
144 M_STORE(st_32, nir_type_uint32);
145 M_STORE(st_64, nir_type_uint32);
146 M_STORE(st_128, nir_type_uint32);
147 M_LOAD(ld_tilebuffer_raw, nir_type_uint32);
148 M_LOAD(ld_tilebuffer_16f, nir_type_float16);
149 M_LOAD(ld_tilebuffer_32f, nir_type_float32);
150 M_STORE(st_vary_32, nir_type_uint32);
151 M_LOAD(ld_cubemap_coords, nir_type_uint32);
152 M_LOAD(ldst_mov, nir_type_uint32);
153 M_LOAD(ld_image_32f, nir_type_float32);
154 M_LOAD(ld_image_16f, nir_type_float16);
155 M_LOAD(ld_image_32u, nir_type_uint32);
156 M_LOAD(ld_image_32i, nir_type_int32);
157 M_STORE(st_image_32f, nir_type_float32);
158 M_STORE(st_image_16f, nir_type_float16);
159 M_STORE(st_image_32u, nir_type_uint32);
160 M_STORE(st_image_32i, nir_type_int32);
161 M_LOAD(lea_image, nir_type_uint64);
162 
163 #define M_IMAGE(op)                                                            \
164    static midgard_instruction op##_image(nir_alu_type type, unsigned val,      \
165                                          unsigned address)                     \
166    {                                                                           \
167       switch (type) {                                                          \
168       case nir_type_float32:                                                   \
169          return m_##op##_image_32f(val, address);                              \
170       case nir_type_float16:                                                   \
171          return m_##op##_image_16f(val, address);                              \
172       case nir_type_uint32:                                                    \
173          return m_##op##_image_32u(val, address);                              \
174       case nir_type_int32:                                                     \
175          return m_##op##_image_32i(val, address);                              \
176       default:                                                                 \
177          unreachable("Invalid image type");                                    \
178       }                                                                        \
179    }
180 
181 M_IMAGE(ld);
182 M_IMAGE(st);
183 
184 static midgard_instruction
v_branch(bool conditional,bool invert)185 v_branch(bool conditional, bool invert)
186 {
187    midgard_instruction ins = {
188       .type = TAG_ALU_4,
189       .unit = ALU_ENAB_BRANCH,
190       .compact_branch = true,
191       .branch =
192          {
193             .conditional = conditional,
194             .invert_conditional = invert,
195          },
196       .dest = ~0,
197       .src = {~0, ~0, ~0, ~0},
198    };
199 
200    return ins;
201 }
202 
203 static void
attach_constants(compiler_context * ctx,midgard_instruction * ins,void * constants,int name)204 attach_constants(compiler_context *ctx, midgard_instruction *ins,
205                  void *constants, int name)
206 {
207    ins->has_constants = true;
208    memcpy(&ins->constants, constants, 16);
209 }
210 
211 static int
glsl_type_size(const struct glsl_type * type,bool bindless)212 glsl_type_size(const struct glsl_type *type, bool bindless)
213 {
214    return glsl_count_attribute_slots(type, false);
215 }
216 
217 static bool
midgard_nir_lower_global_load_instr(nir_builder * b,nir_intrinsic_instr * intr,void * data)218 midgard_nir_lower_global_load_instr(nir_builder *b, nir_intrinsic_instr *intr,
219                                     void *data)
220 {
221    if (intr->intrinsic != nir_intrinsic_load_global &&
222        intr->intrinsic != nir_intrinsic_load_shared)
223       return false;
224 
225    unsigned compsz = intr->def.bit_size;
226    unsigned totalsz = compsz * intr->def.num_components;
227    /* 8, 16, 32, 64 and 128 bit loads don't need to be lowered */
228    if (util_bitcount(totalsz) < 2 && totalsz <= 128)
229       return false;
230 
231    b->cursor = nir_before_instr(&intr->instr);
232 
233    nir_def *addr = intr->src[0].ssa;
234 
235    nir_def *comps[MIR_VEC_COMPONENTS];
236    unsigned ncomps = 0;
237 
238    while (totalsz) {
239       unsigned loadsz = MIN2(1 << (util_last_bit(totalsz) - 1), 128);
240       unsigned loadncomps = loadsz / compsz;
241 
242       nir_def *load;
243       if (intr->intrinsic == nir_intrinsic_load_global) {
244          load = nir_load_global(b, addr, compsz / 8, loadncomps, compsz);
245       } else {
246          assert(intr->intrinsic == nir_intrinsic_load_shared);
247          nir_intrinsic_instr *shared_load =
248             nir_intrinsic_instr_create(b->shader, nir_intrinsic_load_shared);
249          shared_load->num_components = loadncomps;
250          shared_load->src[0] = nir_src_for_ssa(addr);
251          nir_intrinsic_set_align(shared_load, compsz / 8, 0);
252          nir_intrinsic_set_base(shared_load, nir_intrinsic_base(intr));
253          nir_def_init(&shared_load->instr, &shared_load->def,
254                       shared_load->num_components, compsz);
255          nir_builder_instr_insert(b, &shared_load->instr);
256          load = &shared_load->def;
257       }
258 
259       for (unsigned i = 0; i < loadncomps; i++)
260          comps[ncomps++] = nir_channel(b, load, i);
261 
262       totalsz -= loadsz;
263       addr = nir_iadd_imm(b, addr, loadsz / 8);
264    }
265 
266    assert(ncomps == intr->def.num_components);
267    nir_def_rewrite_uses(&intr->def, nir_vec(b, comps, ncomps));
268 
269    return true;
270 }
271 
272 static bool
midgard_nir_lower_global_load(nir_shader * shader)273 midgard_nir_lower_global_load(nir_shader *shader)
274 {
275    return nir_shader_intrinsics_pass(
276       shader, midgard_nir_lower_global_load_instr,
277       nir_metadata_control_flow, NULL);
278 }
279 
280 static bool
mdg_should_scalarize(const nir_instr * instr,const void * _unused)281 mdg_should_scalarize(const nir_instr *instr, const void *_unused)
282 {
283    const nir_alu_instr *alu = nir_instr_as_alu(instr);
284 
285    if (nir_src_bit_size(alu->src[0].src) == 64)
286       return true;
287 
288    if (alu->def.bit_size == 64)
289       return true;
290 
291    switch (alu->op) {
292    case nir_op_fdot2:
293    case nir_op_umul_high:
294    case nir_op_imul_high:
295    case nir_op_pack_half_2x16:
296    case nir_op_unpack_half_2x16:
297 
298    /* The LUT unit is scalar */
299    case nir_op_fsqrt:
300    case nir_op_frcp:
301    case nir_op_frsq:
302    case nir_op_fsin_mdg:
303    case nir_op_fcos_mdg:
304    case nir_op_fexp2:
305    case nir_op_flog2:
306       return true;
307    default:
308       return false;
309    }
310 }
311 
312 /* Only vectorize int64 up to vec2 */
313 static uint8_t
midgard_vectorize_filter(const nir_instr * instr,const void * data)314 midgard_vectorize_filter(const nir_instr *instr, const void *data)
315 {
316    if (instr->type != nir_instr_type_alu)
317       return 0;
318 
319    const nir_alu_instr *alu = nir_instr_as_alu(instr);
320    int src_bit_size = nir_src_bit_size(alu->src[0].src);
321    int dst_bit_size = alu->def.bit_size;
322 
323    if (src_bit_size == 64 || dst_bit_size == 64)
324       return 2;
325 
326    return 4;
327 }
328 
329 static nir_mem_access_size_align
mem_access_size_align_cb(nir_intrinsic_op intrin,uint8_t bytes,uint8_t bit_size,uint32_t align_mul,uint32_t align_offset,bool offset_is_const,enum gl_access_qualifier access,const void * cb_data)330 mem_access_size_align_cb(nir_intrinsic_op intrin, uint8_t bytes,
331                          uint8_t bit_size, uint32_t align_mul,
332                          uint32_t align_offset, bool offset_is_const,
333                          enum gl_access_qualifier access, const void *cb_data)
334 {
335    uint32_t align = nir_combined_align(align_mul, align_offset);
336    assert(util_is_power_of_two_nonzero(align));
337 
338    /* No more than 16 bytes at a time. */
339    bytes = MIN2(bytes, 16);
340 
341    /* If the number of bytes is a multiple of 4, use 32-bit loads. Else if it's
342     * a multiple of 2, use 16-bit loads. Else use 8-bit loads.
343     *
344     * But if we're only aligned to 1 byte, use 8-bit loads. If we're only
345     * aligned to 2 bytes, use 16-bit loads, unless we needed 8-bit loads due to
346     * the size.
347     */
348    if ((bytes & 1) || (align == 1))
349       bit_size = 8;
350    else if ((bytes & 2) || (align == 2))
351       bit_size = 16;
352    else if (bit_size >= 32)
353       bit_size = 32;
354 
355    unsigned num_comps = MIN2(bytes / (bit_size / 8), 4);
356 
357    return (nir_mem_access_size_align){
358       .num_components = num_comps,
359       .bit_size = bit_size,
360       .align = bit_size / 8,
361       .shift = nir_mem_access_shift_method_scalar,
362    };
363 }
364 
365 static uint8_t
lower_vec816_alu(const nir_instr * instr,const void * cb_data)366 lower_vec816_alu(const nir_instr *instr, const void *cb_data)
367 {
368   return 4;
369 }
370 
371 void
midgard_preprocess_nir(nir_shader * nir,unsigned gpu_id)372 midgard_preprocess_nir(nir_shader *nir, unsigned gpu_id)
373 {
374    unsigned quirks = midgard_get_quirks(gpu_id);
375 
376    /* Lower gl_Position pre-optimisation, but after lowering vars to ssa
377     * (so we don't accidentally duplicate the epilogue since mesa/st has
378     * messed with our I/O quite a bit already).
379     */
380    NIR_PASS(_, nir, nir_lower_vars_to_ssa);
381 
382    if (nir->info.stage == MESA_SHADER_VERTEX) {
383       NIR_PASS(_, nir, pan_nir_lower_vertex_id);
384       NIR_PASS(_, nir, nir_lower_viewport_transform);
385       NIR_PASS(_, nir, nir_lower_point_size, 1.0, 0.0);
386    }
387 
388    NIR_PASS(_, nir, nir_lower_var_copies);
389    NIR_PASS(_, nir, nir_lower_vars_to_ssa);
390    NIR_PASS(_, nir, nir_split_var_copies);
391    NIR_PASS(_, nir, nir_lower_var_copies);
392    NIR_PASS(_, nir, nir_lower_global_vars_to_local);
393    NIR_PASS(_, nir, nir_lower_var_copies);
394    NIR_PASS(_, nir, nir_lower_vars_to_ssa);
395 
396    NIR_PASS(_, nir, nir_lower_io, nir_var_shader_in | nir_var_shader_out,
397             glsl_type_size, nir_lower_io_use_interpolated_input_intrinsics);
398 
399    if (nir->info.stage == MESA_SHADER_VERTEX) {
400       /* nir_lower[_explicit]_io is lazy and emits mul+add chains even
401        * for offsets it could figure out are constant.  Do some
402        * constant folding before pan_nir_lower_store_component below.
403        */
404       NIR_PASS(_, nir, nir_opt_constant_folding);
405       NIR_PASS(_, nir, pan_nir_lower_store_component);
406    }
407 
408    /* Could be eventually useful for Vulkan, but we don't expect it to have
409     * the support, so limit it to compute */
410    if (gl_shader_stage_is_compute(nir->info.stage)) {
411       nir_lower_mem_access_bit_sizes_options mem_size_options = {
412          .modes = nir_var_mem_ubo | nir_var_mem_ssbo |
413                   nir_var_mem_constant | nir_var_mem_task_payload |
414                   nir_var_shader_temp | nir_var_function_temp |
415                   nir_var_mem_global | nir_var_mem_shared,
416          .callback = mem_access_size_align_cb,
417       };
418 
419       NIR_PASS(_, nir, nir_lower_mem_access_bit_sizes, &mem_size_options);
420       NIR_PASS(_, nir, nir_lower_alu_width, lower_vec816_alu, NULL);
421       NIR_PASS(_, nir, nir_lower_alu_vec8_16_srcs);
422    }
423 
424    NIR_PASS(_, nir, nir_lower_ssbo, NULL);
425    NIR_PASS(_, nir, pan_nir_lower_zs_store);
426 
427    NIR_PASS(_, nir, nir_lower_frexp);
428    NIR_PASS(_, nir, midgard_nir_lower_global_load);
429 
430    nir_lower_idiv_options idiv_options = {
431       .allow_fp16 = true,
432    };
433 
434    NIR_PASS(_, nir, nir_lower_idiv, &idiv_options);
435 
436    nir_lower_tex_options lower_tex_options = {
437       .lower_txs_lod = true,
438       .lower_txp = ~0,
439       .lower_tg4_broadcom_swizzle = true,
440       .lower_txd = true,
441       .lower_invalid_implicit_lod = true,
442    };
443 
444    NIR_PASS(_, nir, nir_lower_tex, &lower_tex_options);
445    NIR_PASS(_, nir, nir_lower_image_atomics_to_global);
446 
447    /* TEX_GRAD fails to apply sampler descriptor settings on some
448     * implementations, requiring a lowering.
449     */
450    if (quirks & MIDGARD_BROKEN_LOD)
451       NIR_PASS(_, nir, midgard_nir_lod_errata);
452 
453    /* lower MSAA image operations to 3D load before coordinate lowering */
454    NIR_PASS(_, nir, pan_nir_lower_image_ms);
455 
456    /* Midgard image ops coordinates are 16-bit instead of 32-bit */
457    NIR_PASS(_, nir, midgard_nir_lower_image_bitsize);
458 
459    if (nir->info.stage == MESA_SHADER_FRAGMENT)
460       NIR_PASS(_, nir, nir_lower_helper_writes, true);
461 
462    NIR_PASS(_, nir, pan_lower_helper_invocation);
463    NIR_PASS(_, nir, pan_lower_sample_pos);
464    NIR_PASS(_, nir, midgard_nir_lower_algebraic_early);
465    NIR_PASS(_, nir, nir_lower_alu_to_scalar, mdg_should_scalarize, NULL);
466    NIR_PASS(_, nir, nir_lower_flrp, 16 | 32 | 64, false /* always_precise */);
467    NIR_PASS(_, nir, nir_lower_var_copies);
468 }
469 
470 static void
optimise_nir(nir_shader * nir,unsigned quirks,bool is_blend)471 optimise_nir(nir_shader *nir, unsigned quirks, bool is_blend)
472 {
473    bool progress;
474 
475    do {
476       progress = false;
477 
478       NIR_PASS(progress, nir, nir_lower_vars_to_ssa);
479 
480       NIR_PASS(progress, nir, nir_copy_prop);
481       NIR_PASS(progress, nir, nir_opt_remove_phis);
482       NIR_PASS(progress, nir, nir_opt_dce);
483       NIR_PASS(progress, nir, nir_opt_dead_cf);
484       NIR_PASS(progress, nir, nir_opt_cse);
485       NIR_PASS(progress, nir, nir_opt_peephole_select, 64, false, true);
486       NIR_PASS(progress, nir, nir_opt_algebraic);
487       NIR_PASS(progress, nir, nir_opt_constant_folding);
488       NIR_PASS(progress, nir, nir_opt_undef);
489       NIR_PASS(progress, nir, nir_lower_undef_to_zero);
490 
491       NIR_PASS(progress, nir, nir_opt_loop_unroll);
492 
493       NIR_PASS(progress, nir, nir_opt_vectorize, midgard_vectorize_filter,
494                NULL);
495    } while (progress);
496 
497    NIR_PASS(_, nir, nir_lower_alu_to_scalar, mdg_should_scalarize, NULL);
498 
499    /* Run after opts so it can hit more */
500    if (!is_blend)
501       NIR_PASS(progress, nir, nir_fuse_io_16);
502 
503    do {
504       progress = false;
505 
506       NIR_PASS(progress, nir, nir_opt_dce);
507       NIR_PASS(progress, nir, nir_opt_algebraic);
508       NIR_PASS(progress, nir, nir_opt_constant_folding);
509       NIR_PASS(progress, nir, nir_copy_prop);
510    } while (progress);
511 
512    NIR_PASS(progress, nir, nir_opt_algebraic_late);
513    NIR_PASS(progress, nir, nir_opt_algebraic_distribute_src_mods);
514 
515    /* We implement booleans as 32-bit 0/~0 */
516    NIR_PASS(progress, nir, nir_lower_bool_to_int32);
517 
518    /* Now that booleans are lowered, we can run out late opts */
519    NIR_PASS(progress, nir, midgard_nir_lower_algebraic_late);
520    NIR_PASS(progress, nir, midgard_nir_cancel_inot);
521    NIR_PASS(_, nir, midgard_nir_type_csel);
522 
523    /* Clean up after late opts */
524    do {
525       progress = false;
526 
527       NIR_PASS(progress, nir, nir_opt_dce);
528       NIR_PASS(progress, nir, nir_opt_constant_folding);
529       NIR_PASS(progress, nir, nir_copy_prop);
530    } while (progress);
531 
532    /* Backend scheduler is purely local, so do some global optimizations
533     * to reduce register pressure. */
534    nir_move_options move_all = nir_move_const_undef | nir_move_load_ubo |
535                                nir_move_load_input | nir_move_comparisons |
536                                nir_move_copies | nir_move_load_ssbo;
537 
538    NIR_PASS(_, nir, nir_opt_sink, move_all);
539    NIR_PASS(_, nir, nir_opt_move, move_all);
540 
541    /* Take us out of SSA */
542    NIR_PASS(progress, nir, nir_convert_from_ssa, true, false);
543 
544    /* We are a vector architecture; write combine where possible */
545    NIR_PASS(progress, nir, nir_move_vec_src_uses_to_dest, false);
546    NIR_PASS(progress, nir, nir_lower_vec_to_regs, NULL, NULL);
547 
548    NIR_PASS(progress, nir, nir_opt_dce);
549    nir_trivialize_registers(nir);
550 }
551 
552 /* Do not actually emit a load; instead, cache the constant for inlining */
553 
554 static void
emit_load_const(compiler_context * ctx,nir_load_const_instr * instr)555 emit_load_const(compiler_context *ctx, nir_load_const_instr *instr)
556 {
557    nir_def def = instr->def;
558 
559    midgard_constants *consts = rzalloc(ctx, midgard_constants);
560 
561    assert(instr->def.num_components * instr->def.bit_size <=
562           sizeof(*consts) * 8);
563 
564 #define RAW_CONST_COPY(bits)                                                   \
565    nir_const_value_to_array(consts->u##bits, instr->value,                     \
566                             instr->def.num_components, u##bits)
567 
568    switch (instr->def.bit_size) {
569    case 64:
570       RAW_CONST_COPY(64);
571       break;
572    case 32:
573       RAW_CONST_COPY(32);
574       break;
575    case 16:
576       RAW_CONST_COPY(16);
577       break;
578    case 8:
579       RAW_CONST_COPY(8);
580       break;
581    default:
582       unreachable("Invalid bit_size for load_const instruction\n");
583    }
584 
585    /* Shifted for SSA, +1 for off-by-one */
586    _mesa_hash_table_u64_insert(ctx->ssa_constants, (def.index << 1) + 1,
587                                consts);
588 }
589 
590 /* Normally constants are embedded implicitly, but for I/O and such we have to
591  * explicitly emit a move with the constant source */
592 
593 static void
emit_explicit_constant(compiler_context * ctx,unsigned node)594 emit_explicit_constant(compiler_context *ctx, unsigned node)
595 {
596    void *constant_value =
597       _mesa_hash_table_u64_search(ctx->ssa_constants, node + 1);
598 
599    if (constant_value) {
600       midgard_instruction ins =
601          v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), node);
602       attach_constants(ctx, &ins, constant_value, node + 1);
603       emit_mir_instruction(ctx, &ins);
604    }
605 }
606 
607 static bool
nir_is_non_scalar_swizzle(nir_alu_src * src,unsigned nr_components)608 nir_is_non_scalar_swizzle(nir_alu_src *src, unsigned nr_components)
609 {
610    unsigned comp = src->swizzle[0];
611 
612    for (unsigned c = 1; c < nr_components; ++c) {
613       if (src->swizzle[c] != comp)
614          return true;
615    }
616 
617    return false;
618 }
619 
620 #define ALU_CASE(nir, _op)                                                     \
621    case nir_op_##nir:                                                          \
622       op = midgard_alu_op_##_op;                                               \
623       assert(src_bitsize == dst_bitsize);                                      \
624       break;
625 
626 #define ALU_CASE_RTZ(nir, _op)                                                 \
627    case nir_op_##nir:                                                          \
628       op = midgard_alu_op_##_op;                                               \
629       roundmode = MIDGARD_RTZ;                                                 \
630       break;
631 
632 #define ALU_CHECK_CMP()                                                        \
633    assert(src_bitsize == 16 || src_bitsize == 32 || src_bitsize == 64);        \
634    assert(dst_bitsize == 16 || dst_bitsize == 32);
635 
636 #define ALU_CASE_BCAST(nir, _op, count)                                        \
637    case nir_op_##nir:                                                          \
638       op = midgard_alu_op_##_op;                                               \
639       broadcast_swizzle = count;                                               \
640       ALU_CHECK_CMP();                                                         \
641       break;
642 
643 #define ALU_CASE_CMP(nir, _op)                                                 \
644    case nir_op_##nir:                                                          \
645       op = midgard_alu_op_##_op;                                               \
646       ALU_CHECK_CMP();                                                         \
647       break;
648 
649 static void
mir_copy_src(midgard_instruction * ins,nir_alu_instr * instr,unsigned i,unsigned to,bool is_int,unsigned bcast_count)650 mir_copy_src(midgard_instruction *ins, nir_alu_instr *instr, unsigned i,
651              unsigned to, bool is_int, unsigned bcast_count)
652 {
653    nir_alu_src src = instr->src[i];
654    unsigned bits = nir_src_bit_size(src.src);
655 
656    ins->src[to] = nir_src_index(NULL, &src.src);
657    ins->src_types[to] = nir_op_infos[instr->op].input_types[i] | bits;
658 
659    /* Figure out which component we should fill unused channels with. This
660     * doesn't matter too much in the non-broadcast case, but it makes
661     * should that scalar sources are packed with replicated swizzles,
662     * which works around issues seen with the combination of source
663     * expansion and destination shrinking.
664     */
665    unsigned replicate_c = 0;
666    if (bcast_count) {
667       replicate_c = bcast_count - 1;
668    } else {
669       for (unsigned c = 0; c < NIR_MAX_VEC_COMPONENTS; ++c) {
670          if (nir_alu_instr_channel_used(instr, i, c))
671             replicate_c = c;
672       }
673    }
674 
675    for (unsigned c = 0; c < NIR_MAX_VEC_COMPONENTS; ++c) {
676       ins->swizzle[to][c] =
677          src.swizzle[((!bcast_count || c < bcast_count) &&
678                       nir_alu_instr_channel_used(instr, i, c))
679                         ? c
680                         : replicate_c];
681    }
682 }
683 
684 static void
emit_alu(compiler_context * ctx,nir_alu_instr * instr)685 emit_alu(compiler_context *ctx, nir_alu_instr *instr)
686 {
687    unsigned nr_components = instr->def.num_components;
688    unsigned nr_inputs = nir_op_infos[instr->op].num_inputs;
689    unsigned op = 0;
690 
691    /* Number of components valid to check for the instruction (the rest
692     * will be forced to the last), or 0 to use as-is. Relevant as
693     * ball-type instructions have a channel count in NIR but are all vec4
694     * in Midgard */
695 
696    unsigned broadcast_swizzle = 0;
697 
698    /* Should we swap arguments? */
699    bool flip_src12 = false;
700 
701    ASSERTED unsigned src_bitsize = nir_src_bit_size(instr->src[0].src);
702    unsigned dst_bitsize = instr->def.bit_size;
703 
704    enum midgard_roundmode roundmode = MIDGARD_RTE;
705 
706    switch (instr->op) {
707       ALU_CASE(fadd, fadd);
708       ALU_CASE(fmul, fmul);
709       ALU_CASE(fmin, fmin);
710       ALU_CASE(fmax, fmax);
711       ALU_CASE(imin, imin);
712       ALU_CASE(imax, imax);
713       ALU_CASE(umin, umin);
714       ALU_CASE(umax, umax);
715       ALU_CASE(ffloor, ffloor);
716       ALU_CASE(fround_even, froundeven);
717       ALU_CASE(ftrunc, ftrunc);
718       ALU_CASE(fceil, fceil);
719       ALU_CASE(fdot3, fdot3);
720       ALU_CASE(fdot4, fdot4);
721       ALU_CASE(iadd, iadd);
722       ALU_CASE(isub, isub);
723       ALU_CASE(iadd_sat, iaddsat);
724       ALU_CASE(isub_sat, isubsat);
725       ALU_CASE(uadd_sat, uaddsat);
726       ALU_CASE(usub_sat, usubsat);
727       ALU_CASE(imul, imul);
728       ALU_CASE(imul_high, imul);
729       ALU_CASE(umul_high, imul);
730       ALU_CASE(uclz, iclz);
731 
732       /* Zero shoved as second-arg */
733       ALU_CASE(iabs, iabsdiff);
734 
735       ALU_CASE(uabs_isub, iabsdiff);
736       ALU_CASE(uabs_usub, uabsdiff);
737 
738       ALU_CASE(mov, imov);
739 
740       ALU_CASE_CMP(feq32, feq);
741       ALU_CASE_CMP(fneu32, fne);
742       ALU_CASE_CMP(flt32, flt);
743       ALU_CASE_CMP(ieq32, ieq);
744       ALU_CASE_CMP(ine32, ine);
745       ALU_CASE_CMP(ilt32, ilt);
746       ALU_CASE_CMP(ult32, ult);
747 
748       /* We don't have a native b2f32 instruction. Instead, like many
749        * GPUs, we exploit booleans as 0/~0 for false/true, and
750        * correspondingly AND
751        * by 1.0 to do the type conversion. For the moment, prime us
752        * to emit:
753        *
754        * iand [whatever], #0
755        *
756        * At the end of emit_alu (as MIR), we'll fix-up the constant
757        */
758 
759       ALU_CASE_CMP(b2f32, iand);
760       ALU_CASE_CMP(b2f16, iand);
761       ALU_CASE_CMP(b2i32, iand);
762       ALU_CASE_CMP(b2i16, iand);
763 
764       ALU_CASE(frcp, frcp);
765       ALU_CASE(frsq, frsqrt);
766       ALU_CASE(fsqrt, fsqrt);
767       ALU_CASE(fexp2, fexp2);
768       ALU_CASE(flog2, flog2);
769 
770       ALU_CASE_RTZ(f2i64, f2i_rte);
771       ALU_CASE_RTZ(f2u64, f2u_rte);
772       ALU_CASE_RTZ(i2f64, i2f_rte);
773       ALU_CASE_RTZ(u2f64, u2f_rte);
774 
775       ALU_CASE_RTZ(f2i32, f2i_rte);
776       ALU_CASE_RTZ(f2u32, f2u_rte);
777       ALU_CASE_RTZ(i2f32, i2f_rte);
778       ALU_CASE_RTZ(u2f32, u2f_rte);
779 
780       ALU_CASE_RTZ(f2i8, f2i_rte);
781       ALU_CASE_RTZ(f2u8, f2u_rte);
782 
783       ALU_CASE_RTZ(f2i16, f2i_rte);
784       ALU_CASE_RTZ(f2u16, f2u_rte);
785       ALU_CASE_RTZ(i2f16, i2f_rte);
786       ALU_CASE_RTZ(u2f16, u2f_rte);
787 
788       ALU_CASE(fsin_mdg, fsinpi);
789       ALU_CASE(fcos_mdg, fcospi);
790 
791       /* We'll get 0 in the second arg, so:
792        * ~a = ~(a | 0) = nor(a, 0) */
793       ALU_CASE(inot, inor);
794       ALU_CASE(iand, iand);
795       ALU_CASE(ior, ior);
796       ALU_CASE(ixor, ixor);
797       ALU_CASE(ishl, ishl);
798       ALU_CASE(ishr, iasr);
799       ALU_CASE(ushr, ilsr);
800 
801       ALU_CASE_BCAST(b32all_fequal2, fball_eq, 2);
802       ALU_CASE_BCAST(b32all_fequal3, fball_eq, 3);
803       ALU_CASE_CMP(b32all_fequal4, fball_eq);
804 
805       ALU_CASE_BCAST(b32any_fnequal2, fbany_neq, 2);
806       ALU_CASE_BCAST(b32any_fnequal3, fbany_neq, 3);
807       ALU_CASE_CMP(b32any_fnequal4, fbany_neq);
808 
809       ALU_CASE_BCAST(b32all_iequal2, iball_eq, 2);
810       ALU_CASE_BCAST(b32all_iequal3, iball_eq, 3);
811       ALU_CASE_CMP(b32all_iequal4, iball_eq);
812 
813       ALU_CASE_BCAST(b32any_inequal2, ibany_neq, 2);
814       ALU_CASE_BCAST(b32any_inequal3, ibany_neq, 3);
815       ALU_CASE_CMP(b32any_inequal4, ibany_neq);
816 
817       /* Source mods will be shoved in later */
818       ALU_CASE(fabs, fmov);
819       ALU_CASE(fneg, fmov);
820       ALU_CASE(fsat, fmov);
821       ALU_CASE(fsat_signed, fmov);
822       ALU_CASE(fclamp_pos, fmov);
823 
824       /* For size conversion, we use a move. Ideally though we would squash
825        * these ops together; maybe that has to happen after in NIR as part of
826        * propagation...? An earlier algebraic pass ensured we step down by
827        * only / exactly one size. If stepping down, we use a dest override to
828        * reduce the size; if stepping up, we use a larger-sized move with a
829        * half source and a sign/zero-extension modifier */
830 
831    case nir_op_i2i8:
832    case nir_op_i2i16:
833    case nir_op_i2i32:
834    case nir_op_i2i64:
835    case nir_op_u2u8:
836    case nir_op_u2u16:
837    case nir_op_u2u32:
838    case nir_op_u2u64:
839    case nir_op_f2f16:
840    case nir_op_f2f32:
841    case nir_op_f2f64: {
842       if (instr->op == nir_op_f2f16 || instr->op == nir_op_f2f32 ||
843           instr->op == nir_op_f2f64)
844          op = midgard_alu_op_fmov;
845       else
846          op = midgard_alu_op_imov;
847 
848       break;
849    }
850 
851       /* For greater-or-equal, we lower to less-or-equal and flip the
852        * arguments */
853 
854    case nir_op_fge:
855    case nir_op_fge32:
856    case nir_op_ige32:
857    case nir_op_uge32: {
858       op = instr->op == nir_op_fge     ? midgard_alu_op_fle
859            : instr->op == nir_op_fge32 ? midgard_alu_op_fle
860            : instr->op == nir_op_ige32 ? midgard_alu_op_ile
861            : instr->op == nir_op_uge32 ? midgard_alu_op_ule
862                                        : 0;
863 
864       flip_src12 = true;
865       ALU_CHECK_CMP();
866       break;
867    }
868 
869    case nir_op_b32csel:
870    case nir_op_b32fcsel_mdg: {
871       bool mixed = nir_is_non_scalar_swizzle(&instr->src[0], nr_components);
872       bool is_float = instr->op == nir_op_b32fcsel_mdg;
873       op = is_float ? (mixed ? midgard_alu_op_fcsel_v : midgard_alu_op_fcsel)
874                     : (mixed ? midgard_alu_op_icsel_v : midgard_alu_op_icsel);
875 
876       int index = nir_src_index(ctx, &instr->src[0].src);
877       emit_explicit_constant(ctx, index);
878 
879       break;
880    }
881 
882    case nir_op_unpack_32_2x16:
883    case nir_op_unpack_32_4x8:
884    case nir_op_pack_32_2x16:
885    case nir_op_pack_32_4x8: {
886       op = midgard_alu_op_imov;
887       break;
888    }
889 
890    case nir_op_unpack_64_2x32:
891    case nir_op_unpack_64_4x16:
892    case nir_op_pack_64_2x32:
893    case nir_op_pack_64_4x16: {
894       op = midgard_alu_op_imov;
895       break;
896    }
897 
898    default:
899       mesa_loge("Unhandled ALU op %s\n", nir_op_infos[instr->op].name);
900       assert(0);
901       return;
902    }
903 
904    /* Promote imov to fmov if it might help inline a constant */
905    if (op == midgard_alu_op_imov && nir_src_is_const(instr->src[0].src) &&
906        nir_src_bit_size(instr->src[0].src) == 32 &&
907        nir_is_same_comp_swizzle(instr->src[0].swizzle,
908                                 nir_src_num_components(instr->src[0].src))) {
909       op = midgard_alu_op_fmov;
910    }
911 
912    /* Midgard can perform certain modifiers on output of an ALU op */
913 
914    unsigned outmod = 0;
915    bool is_int = midgard_is_integer_op(op);
916 
917    if (instr->op == nir_op_umul_high || instr->op == nir_op_imul_high) {
918       outmod = midgard_outmod_keephi;
919    } else if (midgard_is_integer_out_op(op)) {
920       outmod = midgard_outmod_keeplo;
921    } else if (instr->op == nir_op_fsat) {
922       outmod = midgard_outmod_clamp_0_1;
923    } else if (instr->op == nir_op_fsat_signed) {
924       outmod = midgard_outmod_clamp_m1_1;
925    } else if (instr->op == nir_op_fclamp_pos) {
926       outmod = midgard_outmod_clamp_0_inf;
927    }
928 
929    /* Fetch unit, quirks, etc information */
930    unsigned opcode_props = alu_opcode_props[op].props;
931    bool quirk_flipped_r24 = opcode_props & QUIRK_FLIPPED_R24;
932 
933    midgard_instruction ins = {
934       .type = TAG_ALU_4,
935       .dest_type = nir_op_infos[instr->op].output_type | dst_bitsize,
936       .roundmode = roundmode,
937    };
938 
939    ins.dest = nir_def_index_with_mask(&instr->def, &ins.mask);
940 
941    for (unsigned i = nr_inputs; i < ARRAY_SIZE(ins.src); ++i)
942       ins.src[i] = ~0;
943 
944    if (quirk_flipped_r24) {
945       ins.src[0] = ~0;
946       mir_copy_src(&ins, instr, 0, 1, is_int, broadcast_swizzle);
947    } else {
948       for (unsigned i = 0; i < nr_inputs; ++i) {
949          unsigned to = i;
950 
951          if (instr->op == nir_op_b32csel || instr->op == nir_op_b32fcsel_mdg) {
952             /* The condition is the first argument; move
953              * the other arguments up one to be a binary
954              * instruction for Midgard with the condition
955              * last */
956 
957             if (i == 0)
958                to = 2;
959             else if (flip_src12)
960                to = 2 - i;
961             else
962                to = i - 1;
963          } else if (flip_src12) {
964             to = 1 - to;
965          }
966 
967          mir_copy_src(&ins, instr, i, to, is_int, broadcast_swizzle);
968       }
969    }
970 
971    if (instr->op == nir_op_fneg || instr->op == nir_op_fabs) {
972       /* Lowered to move */
973       if (instr->op == nir_op_fneg)
974          ins.src_neg[1] ^= true;
975 
976       if (instr->op == nir_op_fabs)
977          ins.src_abs[1] = true;
978    }
979 
980    ins.op = op;
981    ins.outmod = outmod;
982 
983    /* Late fixup for emulated instructions */
984 
985    if (instr->op == nir_op_b2f32 || instr->op == nir_op_b2i32) {
986       /* Presently, our second argument is an inline #0 constant.
987        * Switch over to an embedded 1.0 constant (that can't fit
988        * inline, since we're 32-bit, not 16-bit like the inline
989        * constants) */
990 
991       ins.has_inline_constant = false;
992       ins.src[1] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
993       ins.src_types[1] = nir_type_float32;
994       ins.has_constants = true;
995 
996       if (instr->op == nir_op_b2f32)
997          ins.constants.f32[0] = 1.0f;
998       else
999          ins.constants.i32[0] = 1;
1000 
1001       for (unsigned c = 0; c < 16; ++c)
1002          ins.swizzle[1][c] = 0;
1003    } else if (instr->op == nir_op_b2f16) {
1004       ins.src[1] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1005       ins.src_types[1] = nir_type_float16;
1006       ins.has_constants = true;
1007       ins.constants.i16[0] = _mesa_float_to_half(1.0);
1008 
1009       for (unsigned c = 0; c < 16; ++c)
1010          ins.swizzle[1][c] = 0;
1011    } else if (nr_inputs == 1 && !quirk_flipped_r24) {
1012       /* Lots of instructions need a 0 plonked in */
1013       ins.has_inline_constant = false;
1014       ins.src[1] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
1015       ins.src_types[1] = ins.src_types[0];
1016       ins.has_constants = true;
1017       ins.constants.u32[0] = 0;
1018 
1019       for (unsigned c = 0; c < 16; ++c)
1020          ins.swizzle[1][c] = 0;
1021    } else if (instr->op == nir_op_pack_32_2x16) {
1022       ins.dest_type = nir_type_uint16;
1023       ins.mask = mask_of(nr_components * 2);
1024       ins.is_pack = true;
1025    } else if (instr->op == nir_op_pack_32_4x8) {
1026       ins.dest_type = nir_type_uint8;
1027       ins.mask = mask_of(nr_components * 4);
1028       ins.is_pack = true;
1029    } else if (instr->op == nir_op_unpack_32_2x16) {
1030       ins.dest_type = nir_type_uint32;
1031       ins.mask = mask_of(nr_components >> 1);
1032       ins.is_pack = true;
1033    } else if (instr->op == nir_op_unpack_32_4x8) {
1034       ins.dest_type = nir_type_uint32;
1035       ins.mask = mask_of(nr_components >> 2);
1036       ins.is_pack = true;
1037    }
1038 
1039    emit_mir_instruction(ctx, &ins);
1040 }
1041 
1042 #undef ALU_CASE
1043 
1044 static void
mir_set_intr_mask(nir_instr * instr,midgard_instruction * ins,bool is_read)1045 mir_set_intr_mask(nir_instr *instr, midgard_instruction *ins, bool is_read)
1046 {
1047    nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
1048    unsigned nir_mask = 0;
1049    unsigned dsize = 0;
1050 
1051    if (is_read) {
1052       nir_mask = mask_of(nir_intrinsic_dest_components(intr));
1053 
1054       /* Extension is mandatory for 8/16-bit loads */
1055       dsize = intr->def.bit_size == 64 ? 64 : 32;
1056    } else {
1057       nir_mask = nir_intrinsic_write_mask(intr);
1058       dsize = OP_IS_COMMON_STORE(ins->op) ? nir_src_bit_size(intr->src[0]) : 32;
1059    }
1060 
1061    /* Once we have the NIR mask, we need to normalize to work in 32-bit space */
1062    unsigned bytemask = pan_to_bytemask(dsize, nir_mask);
1063    ins->dest_type = nir_type_uint | dsize;
1064    mir_set_bytemask(ins, bytemask);
1065 }
1066 
1067 /* Uniforms and UBOs use a shared code path, as uniforms are just (slightly
1068  * optimized) versions of UBO #0 */
1069 
1070 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,unsigned nr_comps)1071 emit_ubo_read(compiler_context *ctx, nir_instr *instr, unsigned dest,
1072               unsigned offset, nir_src *indirect_offset,
1073               unsigned indirect_shift, unsigned index, unsigned nr_comps)
1074 {
1075    midgard_instruction ins;
1076 
1077    unsigned dest_size = (instr->type == nir_instr_type_intrinsic)
1078                            ? nir_instr_as_intrinsic(instr)->def.bit_size
1079                            : 32;
1080 
1081    unsigned bitsize = dest_size * nr_comps;
1082 
1083    /* Pick the smallest intrinsic to avoid out-of-bounds reads */
1084    if (bitsize <= 8)
1085       ins = m_ld_ubo_u8(dest, 0);
1086    else if (bitsize <= 16)
1087       ins = m_ld_ubo_u16(dest, 0);
1088    else if (bitsize <= 32)
1089       ins = m_ld_ubo_32(dest, 0);
1090    else if (bitsize <= 64)
1091       ins = m_ld_ubo_64(dest, 0);
1092    else if (bitsize <= 128)
1093       ins = m_ld_ubo_128(dest, 0);
1094    else
1095       unreachable("Invalid UBO read size");
1096 
1097    ins.constants.u32[0] = offset;
1098 
1099    if (instr->type == nir_instr_type_intrinsic)
1100       mir_set_intr_mask(instr, &ins, true);
1101 
1102    if (indirect_offset) {
1103       ins.src[2] = nir_src_index(ctx, indirect_offset);
1104       ins.src_types[2] = nir_type_uint32;
1105       ins.load_store.index_shift = indirect_shift;
1106 
1107       /* X component for the whole swizzle to prevent register
1108        * pressure from ballooning from the extra components */
1109       for (unsigned i = 0; i < ARRAY_SIZE(ins.swizzle[2]); ++i)
1110          ins.swizzle[2][i] = 0;
1111    } else {
1112       ins.load_store.index_reg = REGISTER_LDST_ZERO;
1113    }
1114 
1115    if (indirect_offset && !indirect_shift)
1116       mir_set_ubo_offset(&ins, indirect_offset, offset);
1117 
1118    midgard_pack_ubo_index_imm(&ins.load_store, index);
1119 
1120    return emit_mir_instruction(ctx, &ins);
1121 }
1122 
1123 /* Globals are like UBOs if you squint. And shared memory is like globals if
1124  * you squint even harder */
1125 
1126 static void
emit_global(compiler_context * ctx,nir_instr * instr,bool is_read,unsigned srcdest,nir_src * offset,unsigned seg)1127 emit_global(compiler_context *ctx, nir_instr *instr, bool is_read,
1128             unsigned srcdest, nir_src *offset, unsigned seg)
1129 {
1130    midgard_instruction ins;
1131 
1132    nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
1133    if (is_read) {
1134       unsigned bitsize = intr->def.bit_size * intr->def.num_components;
1135 
1136       switch (bitsize) {
1137       case 8:
1138          ins = m_ld_u8(srcdest, 0);
1139          break;
1140       case 16:
1141          ins = m_ld_u16(srcdest, 0);
1142          break;
1143       case 32:
1144          ins = m_ld_32(srcdest, 0);
1145          break;
1146       case 64:
1147          ins = m_ld_64(srcdest, 0);
1148          break;
1149       case 128:
1150          ins = m_ld_128(srcdest, 0);
1151          break;
1152       default:
1153          unreachable("Invalid global read size");
1154       }
1155 
1156       mir_set_intr_mask(instr, &ins, is_read);
1157 
1158       /* For anything not aligned on 32bit, make sure we write full
1159        * 32 bits registers. */
1160       if (bitsize & 31) {
1161          unsigned comps_per_32b = 32 / intr->def.bit_size;
1162 
1163          for (unsigned c = 0; c < 4 * comps_per_32b; c += comps_per_32b) {
1164             if (!(ins.mask & BITFIELD_RANGE(c, comps_per_32b)))
1165                continue;
1166 
1167             unsigned base = ~0;
1168             for (unsigned i = 0; i < comps_per_32b; i++) {
1169                if (ins.mask & BITFIELD_BIT(c + i)) {
1170                   base = ins.swizzle[0][c + i];
1171                   break;
1172                }
1173             }
1174 
1175             assert(base != ~0);
1176 
1177             for (unsigned i = 0; i < comps_per_32b; i++) {
1178                if (!(ins.mask & BITFIELD_BIT(c + i))) {
1179                   ins.swizzle[0][c + i] = base + i;
1180                   ins.mask |= BITFIELD_BIT(c + i);
1181                }
1182                assert(ins.swizzle[0][c + i] == base + i);
1183             }
1184          }
1185       }
1186    } else {
1187       unsigned bitsize =
1188          nir_src_bit_size(intr->src[0]) * nir_src_num_components(intr->src[0]);
1189 
1190       if (bitsize == 8)
1191          ins = m_st_u8(srcdest, 0);
1192       else if (bitsize == 16)
1193          ins = m_st_u16(srcdest, 0);
1194       else if (bitsize <= 32)
1195          ins = m_st_32(srcdest, 0);
1196       else if (bitsize <= 64)
1197          ins = m_st_64(srcdest, 0);
1198       else if (bitsize <= 128)
1199          ins = m_st_128(srcdest, 0);
1200       else
1201          unreachable("Invalid global store size");
1202 
1203       mir_set_intr_mask(instr, &ins, is_read);
1204    }
1205 
1206    mir_set_offset(ctx, &ins, offset, seg);
1207 
1208    /* Set a valid swizzle for masked out components */
1209    assert(ins.mask);
1210    unsigned first_component = __builtin_ffs(ins.mask) - 1;
1211 
1212    for (unsigned i = 0; i < ARRAY_SIZE(ins.swizzle[0]); ++i) {
1213       if (!(ins.mask & (1 << i)))
1214          ins.swizzle[0][i] = first_component;
1215    }
1216 
1217    emit_mir_instruction(ctx, &ins);
1218 }
1219 
1220 static midgard_load_store_op
translate_atomic_op(nir_atomic_op op)1221 translate_atomic_op(nir_atomic_op op)
1222 {
1223    /* clang-format off */
1224    switch (op) {
1225    case nir_atomic_op_xchg:    return midgard_op_atomic_xchg;
1226    case nir_atomic_op_cmpxchg: return midgard_op_atomic_cmpxchg;
1227    case nir_atomic_op_iadd:    return midgard_op_atomic_add;
1228    case nir_atomic_op_iand:    return midgard_op_atomic_and;
1229    case nir_atomic_op_imax:    return midgard_op_atomic_imax;
1230    case nir_atomic_op_imin:    return midgard_op_atomic_imin;
1231    case nir_atomic_op_ior:     return midgard_op_atomic_or;
1232    case nir_atomic_op_umax:    return midgard_op_atomic_umax;
1233    case nir_atomic_op_umin:    return midgard_op_atomic_umin;
1234    case nir_atomic_op_ixor:    return midgard_op_atomic_xor;
1235    default: unreachable("Unexpected atomic");
1236    }
1237    /* clang-format on */
1238 }
1239 
1240 /* Emit an atomic to shared memory or global memory. */
1241 static void
emit_atomic(compiler_context * ctx,nir_intrinsic_instr * instr)1242 emit_atomic(compiler_context *ctx, nir_intrinsic_instr *instr)
1243 {
1244    midgard_load_store_op op =
1245       translate_atomic_op(nir_intrinsic_atomic_op(instr));
1246 
1247    nir_alu_type type =
1248       (op == midgard_op_atomic_imin || op == midgard_op_atomic_imax)
1249          ? nir_type_int
1250          : nir_type_uint;
1251 
1252    bool is_shared = (instr->intrinsic == nir_intrinsic_shared_atomic) ||
1253                     (instr->intrinsic == nir_intrinsic_shared_atomic_swap);
1254 
1255    unsigned dest = nir_def_index(&instr->def);
1256    unsigned val = nir_src_index(ctx, &instr->src[1]);
1257    unsigned bitsize = nir_src_bit_size(instr->src[1]);
1258    emit_explicit_constant(ctx, val);
1259 
1260    midgard_instruction ins = {
1261       .type = TAG_LOAD_STORE_4,
1262       .mask = 0xF,
1263       .dest = dest,
1264       .src = {~0, ~0, ~0, val},
1265       .src_types = {0, 0, 0, type | bitsize},
1266       .op = op,
1267    };
1268 
1269    nir_src *src_offset = nir_get_io_offset_src(instr);
1270 
1271    if (op == midgard_op_atomic_cmpxchg) {
1272       unsigned xchg_val = nir_src_index(ctx, &instr->src[2]);
1273       emit_explicit_constant(ctx, xchg_val);
1274 
1275       ins.src[2] = val;
1276       ins.src_types[2] = type | bitsize;
1277       ins.src[3] = xchg_val;
1278 
1279       if (is_shared) {
1280          ins.load_store.arg_reg = REGISTER_LDST_LOCAL_STORAGE_PTR;
1281          ins.load_store.arg_comp = COMPONENT_Z;
1282          ins.load_store.bitsize_toggle = true;
1283       } else {
1284          for (unsigned i = 0; i < 2; ++i)
1285             ins.swizzle[1][i] = i;
1286 
1287          ins.src[1] = nir_src_index(ctx, src_offset);
1288          ins.src_types[1] = nir_type_uint64;
1289       }
1290    } else
1291       mir_set_offset(ctx, &ins, src_offset,
1292                      is_shared ? LDST_SHARED : LDST_GLOBAL);
1293 
1294    mir_set_intr_mask(&instr->instr, &ins, true);
1295 
1296    emit_mir_instruction(ctx, &ins);
1297 }
1298 
1299 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)1300 emit_varying_read(compiler_context *ctx, unsigned dest, unsigned offset,
1301                   unsigned nr_comp, unsigned component,
1302                   nir_src *indirect_offset, nir_alu_type type, bool flat)
1303 {
1304    midgard_instruction ins = m_ld_vary_32(dest, PACK_LDST_ATTRIB_OFS(offset));
1305    ins.mask = mask_of(nr_comp);
1306    ins.dest_type = type;
1307 
1308    if (type == nir_type_float16) {
1309       /* Ensure we are aligned so we can pack it later */
1310       ins.mask = mask_of(ALIGN_POT(nr_comp, 2));
1311    }
1312 
1313    for (unsigned i = 0; i < ARRAY_SIZE(ins.swizzle[0]); ++i)
1314       ins.swizzle[0][i] = MIN2(i + component, COMPONENT_W);
1315 
1316    midgard_varying_params p = {
1317       .flat_shading = flat,
1318       .perspective_correction = 1,
1319       .interpolate_sample = true,
1320    };
1321    midgard_pack_varying_params(&ins.load_store, p);
1322 
1323    if (indirect_offset) {
1324       ins.src[2] = nir_src_index(ctx, indirect_offset);
1325       ins.src_types[2] = nir_type_uint32;
1326    } else
1327       ins.load_store.index_reg = REGISTER_LDST_ZERO;
1328 
1329    ins.load_store.arg_reg = REGISTER_LDST_ZERO;
1330    ins.load_store.index_format = midgard_index_address_u32;
1331 
1332    /* For flat shading, for GPUs supporting auto32, we always use .u32 and
1333     * require 32-bit mode. For smooth shading, we use the appropriate
1334     * floating-point type.
1335     *
1336     * This could be optimized, but it makes it easy to check correctness.
1337     */
1338    if (ctx->quirks & MIDGARD_NO_AUTO32) {
1339       switch (type) {
1340       case nir_type_uint32:
1341       case nir_type_bool32:
1342          ins.op = midgard_op_ld_vary_32u;
1343          break;
1344       case nir_type_int32:
1345          ins.op = midgard_op_ld_vary_32i;
1346          break;
1347       case nir_type_float32:
1348          ins.op = midgard_op_ld_vary_32;
1349          break;
1350       case nir_type_float16:
1351          ins.op = midgard_op_ld_vary_16;
1352          break;
1353       default:
1354          unreachable("Attempted to load unknown type");
1355          break;
1356       }
1357    } else if (flat) {
1358       assert(nir_alu_type_get_type_size(type) == 32);
1359       ins.op = midgard_op_ld_vary_32u;
1360    } else {
1361       assert(nir_alu_type_get_base_type(type) == nir_type_float);
1362 
1363       ins.op = (nir_alu_type_get_type_size(type) == 32) ? midgard_op_ld_vary_32
1364                                                         : midgard_op_ld_vary_16;
1365    }
1366 
1367    emit_mir_instruction(ctx, &ins);
1368 }
1369 
1370 static midgard_instruction
emit_image_op(compiler_context * ctx,nir_intrinsic_instr * instr)1371 emit_image_op(compiler_context *ctx, nir_intrinsic_instr *instr)
1372 {
1373    enum glsl_sampler_dim dim = nir_intrinsic_image_dim(instr);
1374    unsigned nr_dim = glsl_get_sampler_dim_coordinate_components(dim);
1375    bool is_array = nir_intrinsic_image_array(instr);
1376    bool is_store = instr->intrinsic == nir_intrinsic_image_store;
1377 
1378    assert(dim != GLSL_SAMPLER_DIM_MS && "MSAA'd image not lowered");
1379 
1380    unsigned coord_reg = nir_src_index(ctx, &instr->src[1]);
1381    emit_explicit_constant(ctx, coord_reg);
1382 
1383    nir_src *index = &instr->src[0];
1384    bool is_direct = nir_src_is_const(*index);
1385 
1386    /* For image opcodes, address is used as an index into the attribute
1387     * descriptor */
1388    unsigned address = is_direct ? nir_src_as_uint(*index) : 0;
1389 
1390    midgard_instruction ins;
1391    if (is_store) { /* emit st_image_* */
1392       unsigned val = nir_src_index(ctx, &instr->src[3]);
1393       emit_explicit_constant(ctx, val);
1394 
1395       nir_alu_type type = nir_intrinsic_src_type(instr);
1396       ins = st_image(type, val, PACK_LDST_ATTRIB_OFS(address));
1397       nir_alu_type base_type = nir_alu_type_get_base_type(type);
1398       ins.src_types[0] = base_type | nir_src_bit_size(instr->src[3]);
1399    } else if (instr->intrinsic == nir_intrinsic_image_texel_address) {
1400       ins =
1401          m_lea_image(nir_def_index(&instr->def), PACK_LDST_ATTRIB_OFS(address));
1402       ins.mask = mask_of(2); /* 64-bit memory address */
1403    } else {                  /* emit ld_image_* */
1404       nir_alu_type type = nir_intrinsic_dest_type(instr);
1405       ins = ld_image(type, nir_def_index(&instr->def),
1406                      PACK_LDST_ATTRIB_OFS(address));
1407       ins.mask = mask_of(nir_intrinsic_dest_components(instr));
1408       ins.dest_type = type;
1409    }
1410 
1411    /* Coord reg */
1412    ins.src[1] = coord_reg;
1413    ins.src_types[1] = nir_type_uint16;
1414    if (nr_dim == 3 || is_array) {
1415       ins.load_store.bitsize_toggle = true;
1416    }
1417 
1418    /* Image index reg */
1419    if (!is_direct) {
1420       ins.src[2] = nir_src_index(ctx, index);
1421       ins.src_types[2] = nir_type_uint32;
1422    } else
1423       ins.load_store.index_reg = REGISTER_LDST_ZERO;
1424 
1425    emit_mir_instruction(ctx, &ins);
1426 
1427    return ins;
1428 }
1429 
1430 static void
emit_attr_read(compiler_context * ctx,unsigned dest,unsigned offset,unsigned nr_comp,nir_alu_type t)1431 emit_attr_read(compiler_context *ctx, unsigned dest, unsigned offset,
1432                unsigned nr_comp, nir_alu_type t)
1433 {
1434    midgard_instruction ins = m_ld_attr_32(dest, PACK_LDST_ATTRIB_OFS(offset));
1435    ins.load_store.arg_reg = REGISTER_LDST_ZERO;
1436    ins.load_store.index_reg = REGISTER_LDST_ZERO;
1437    ins.mask = mask_of(nr_comp);
1438 
1439    /* Use the type appropriate load */
1440    switch (t) {
1441    case nir_type_uint:
1442    case nir_type_bool:
1443       ins.op = midgard_op_ld_attr_32u;
1444       break;
1445    case nir_type_int:
1446       ins.op = midgard_op_ld_attr_32i;
1447       break;
1448    case nir_type_float:
1449       ins.op = midgard_op_ld_attr_32;
1450       break;
1451    default:
1452       unreachable("Attempted to load unknown type");
1453       break;
1454    }
1455 
1456    emit_mir_instruction(ctx, &ins);
1457 }
1458 
1459 static unsigned
compute_builtin_arg(nir_intrinsic_op op)1460 compute_builtin_arg(nir_intrinsic_op op)
1461 {
1462    switch (op) {
1463    case nir_intrinsic_load_workgroup_id:
1464       return REGISTER_LDST_GROUP_ID;
1465    case nir_intrinsic_load_local_invocation_id:
1466       return REGISTER_LDST_LOCAL_THREAD_ID;
1467    case nir_intrinsic_load_global_invocation_id:
1468       return REGISTER_LDST_GLOBAL_THREAD_ID;
1469    default:
1470       unreachable("Invalid compute paramater loaded");
1471    }
1472 }
1473 
1474 static void
emit_fragment_store(compiler_context * ctx,unsigned src,unsigned src_z,unsigned src_s,enum midgard_rt_id rt,unsigned sample_iter)1475 emit_fragment_store(compiler_context *ctx, unsigned src, unsigned src_z,
1476                     unsigned src_s, enum midgard_rt_id rt, unsigned sample_iter)
1477 {
1478    assert(rt < ARRAY_SIZE(ctx->writeout_branch));
1479    assert(sample_iter < ARRAY_SIZE(ctx->writeout_branch[0]));
1480 
1481    midgard_instruction *br = ctx->writeout_branch[rt][sample_iter];
1482 
1483    assert(!br);
1484 
1485    emit_explicit_constant(ctx, src);
1486 
1487    struct midgard_instruction ins = v_branch(false, false);
1488 
1489    bool depth_only = (rt == MIDGARD_ZS_RT);
1490 
1491    ins.writeout = depth_only ? 0 : PAN_WRITEOUT_C;
1492 
1493    /* Add dependencies */
1494    ins.src[0] = src;
1495    ins.src_types[0] = nir_type_uint32;
1496 
1497    if (depth_only)
1498       ins.constants.u32[0] = 0xFF;
1499    else
1500       ins.constants.u32[0] = ((rt - MIDGARD_COLOR_RT0) << 8) | sample_iter;
1501 
1502    for (int i = 0; i < 4; ++i)
1503       ins.swizzle[0][i] = i;
1504 
1505    if (~src_z) {
1506       emit_explicit_constant(ctx, src_z);
1507       ins.src[2] = src_z;
1508       ins.src_types[2] = nir_type_uint32;
1509       ins.writeout |= PAN_WRITEOUT_Z;
1510    }
1511    if (~src_s) {
1512       emit_explicit_constant(ctx, src_s);
1513       ins.src[3] = src_s;
1514       ins.src_types[3] = nir_type_uint32;
1515       ins.writeout |= PAN_WRITEOUT_S;
1516    }
1517 
1518    /* Emit the branch */
1519    br = emit_mir_instruction(ctx, &ins);
1520    schedule_barrier(ctx);
1521    ctx->writeout_branch[rt][sample_iter] = br;
1522 
1523    /* Push our current location = current block count - 1 = where we'll
1524     * jump to. Maybe a bit too clever for my own good */
1525 
1526    br->branch.target_block = ctx->block_count - 1;
1527 }
1528 
1529 static void
emit_compute_builtin(compiler_context * ctx,nir_intrinsic_instr * instr)1530 emit_compute_builtin(compiler_context *ctx, nir_intrinsic_instr *instr)
1531 {
1532    unsigned reg = nir_def_index(&instr->def);
1533    midgard_instruction ins = m_ldst_mov(reg, 0);
1534    ins.mask = mask_of(3);
1535    ins.swizzle[0][3] = COMPONENT_X; /* xyzx */
1536    ins.load_store.arg_reg = compute_builtin_arg(instr->intrinsic);
1537    emit_mir_instruction(ctx, &ins);
1538 }
1539 
1540 static unsigned
vertex_builtin_arg(nir_intrinsic_op op)1541 vertex_builtin_arg(nir_intrinsic_op op)
1542 {
1543    switch (op) {
1544    case nir_intrinsic_load_raw_vertex_id_pan:
1545       return PAN_VERTEX_ID;
1546    case nir_intrinsic_load_instance_id:
1547       return PAN_INSTANCE_ID;
1548    default:
1549       unreachable("Invalid vertex builtin");
1550    }
1551 }
1552 
1553 static void
emit_vertex_builtin(compiler_context * ctx,nir_intrinsic_instr * instr)1554 emit_vertex_builtin(compiler_context *ctx, nir_intrinsic_instr *instr)
1555 {
1556    unsigned reg = nir_def_index(&instr->def);
1557    emit_attr_read(ctx, reg, vertex_builtin_arg(instr->intrinsic), 1,
1558                   nir_type_int);
1559 }
1560 
1561 static void
emit_special(compiler_context * ctx,nir_intrinsic_instr * instr,unsigned idx)1562 emit_special(compiler_context *ctx, nir_intrinsic_instr *instr, unsigned idx)
1563 {
1564    unsigned reg = nir_def_index(&instr->def);
1565 
1566    midgard_instruction ld = m_ld_tilebuffer_raw(reg, 0);
1567    ld.op = midgard_op_ld_special_32u;
1568    ld.load_store.signed_offset = PACK_LDST_SELECTOR_OFS(idx);
1569    ld.load_store.index_reg = REGISTER_LDST_ZERO;
1570 
1571    for (int i = 0; i < 4; ++i)
1572       ld.swizzle[0][i] = COMPONENT_X;
1573 
1574    emit_mir_instruction(ctx, &ld);
1575 }
1576 
1577 static void
emit_control_barrier(compiler_context * ctx)1578 emit_control_barrier(compiler_context *ctx)
1579 {
1580    midgard_instruction ins = {
1581       .type = TAG_TEXTURE_4,
1582       .dest = ~0,
1583       .src = {~0, ~0, ~0, ~0},
1584       .op = midgard_tex_op_barrier,
1585    };
1586 
1587    emit_mir_instruction(ctx, &ins);
1588 }
1589 
1590 static uint8_t
output_load_rt_addr(compiler_context * ctx,nir_intrinsic_instr * instr)1591 output_load_rt_addr(compiler_context *ctx, nir_intrinsic_instr *instr)
1592 {
1593    unsigned loc = nir_intrinsic_io_semantics(instr).location;
1594 
1595    if (loc >= FRAG_RESULT_DATA0)
1596       return loc - FRAG_RESULT_DATA0;
1597 
1598    if (loc == FRAG_RESULT_DEPTH)
1599       return 0x1F;
1600    if (loc == FRAG_RESULT_STENCIL)
1601       return 0x1E;
1602 
1603    unreachable("Invalid RT to load from");
1604 }
1605 
1606 static void
emit_intrinsic(compiler_context * ctx,nir_intrinsic_instr * instr)1607 emit_intrinsic(compiler_context *ctx, nir_intrinsic_instr *instr)
1608 {
1609    unsigned offset = 0, reg;
1610 
1611    switch (instr->intrinsic) {
1612    case nir_intrinsic_decl_reg:
1613    case nir_intrinsic_store_reg:
1614       /* Always fully consumed */
1615       break;
1616 
1617    case nir_intrinsic_load_reg: {
1618       /* NIR guarantees that, for typical isel, this will always be fully
1619        * consumed. However, we also do our own nir_scalar chasing for
1620        * address arithmetic, bypassing the source chasing helpers. So we can end
1621        * up with unconsumed load_register instructions. Translate them here. 99%
1622        * of the time, these moves will be DCE'd away.
1623        */
1624       nir_def *handle = instr->src[0].ssa;
1625 
1626       midgard_instruction ins =
1627          v_mov(nir_reg_index(handle), nir_def_index(&instr->def));
1628 
1629       ins.dest_type = ins.src_types[1] = nir_type_uint | instr->def.bit_size;
1630 
1631       ins.mask = BITFIELD_MASK(instr->def.num_components);
1632       emit_mir_instruction(ctx, &ins);
1633       break;
1634    }
1635 
1636    case nir_intrinsic_terminate_if:
1637    case nir_intrinsic_terminate: {
1638       bool conditional = instr->intrinsic == nir_intrinsic_terminate_if;
1639       struct midgard_instruction discard = v_branch(conditional, false);
1640       discard.branch.target_type = TARGET_DISCARD;
1641 
1642       if (conditional) {
1643          discard.src[0] = nir_src_index(ctx, &instr->src[0]);
1644          discard.src_types[0] = nir_type_uint32;
1645       }
1646 
1647       emit_mir_instruction(ctx, &discard);
1648       schedule_barrier(ctx);
1649 
1650       break;
1651    }
1652 
1653    case nir_intrinsic_image_load:
1654    case nir_intrinsic_image_store:
1655    case nir_intrinsic_image_texel_address:
1656       emit_image_op(ctx, instr);
1657       break;
1658 
1659    case nir_intrinsic_load_ubo:
1660    case nir_intrinsic_load_global:
1661    case nir_intrinsic_load_global_constant:
1662    case nir_intrinsic_load_shared:
1663    case nir_intrinsic_load_scratch:
1664    case nir_intrinsic_load_input:
1665    case nir_intrinsic_load_interpolated_input: {
1666       bool is_ubo = instr->intrinsic == nir_intrinsic_load_ubo;
1667       bool is_global = instr->intrinsic == nir_intrinsic_load_global ||
1668                        instr->intrinsic == nir_intrinsic_load_global_constant;
1669       bool is_shared = instr->intrinsic == nir_intrinsic_load_shared;
1670       bool is_scratch = instr->intrinsic == nir_intrinsic_load_scratch;
1671       bool is_flat = instr->intrinsic == nir_intrinsic_load_input;
1672       bool is_interp =
1673          instr->intrinsic == nir_intrinsic_load_interpolated_input;
1674 
1675       /* Get the base type of the intrinsic */
1676       /* TODO: Infer type? Does it matter? */
1677       nir_alu_type t = (is_interp) ? nir_type_float
1678                        : (is_flat) ? nir_intrinsic_dest_type(instr)
1679                                    : nir_type_uint;
1680 
1681       t = nir_alu_type_get_base_type(t);
1682 
1683       if (!(is_ubo || is_global || is_scratch)) {
1684          offset = nir_intrinsic_base(instr);
1685       }
1686 
1687       unsigned nr_comp = nir_intrinsic_dest_components(instr);
1688 
1689       nir_src *src_offset = nir_get_io_offset_src(instr);
1690 
1691       bool direct = nir_src_is_const(*src_offset);
1692       nir_src *indirect_offset = direct ? NULL : src_offset;
1693 
1694       if (direct)
1695          offset += nir_src_as_uint(*src_offset);
1696 
1697       /* We may need to apply a fractional offset */
1698       int component =
1699          (is_flat || is_interp) ? nir_intrinsic_component(instr) : 0;
1700       reg = nir_def_index(&instr->def);
1701 
1702       if (is_ubo) {
1703          nir_src index = instr->src[0];
1704 
1705          /* TODO: Is indirect block number possible? */
1706          assert(nir_src_is_const(index));
1707 
1708          uint32_t uindex = nir_src_as_uint(index);
1709          emit_ubo_read(ctx, &instr->instr, reg, offset, indirect_offset, 0,
1710                        uindex, nr_comp);
1711       } else if (is_global || is_shared || is_scratch) {
1712          unsigned seg =
1713             is_global ? LDST_GLOBAL : (is_shared ? LDST_SHARED : LDST_SCRATCH);
1714          emit_global(ctx, &instr->instr, true, reg, src_offset, seg);
1715       } else if (ctx->stage == MESA_SHADER_FRAGMENT && !ctx->inputs->is_blend) {
1716          emit_varying_read(ctx, reg, offset, nr_comp, component,
1717                            indirect_offset, t | instr->def.bit_size, is_flat);
1718       } else if (ctx->inputs->is_blend) {
1719          /* ctx->blend_input will be precoloured to r0/r2, where
1720           * the input is preloaded */
1721 
1722          unsigned *input = offset ? &ctx->blend_src1 : &ctx->blend_input;
1723 
1724          if (*input == ~0)
1725             *input = reg;
1726          else {
1727             struct midgard_instruction ins = v_mov(*input, reg);
1728             emit_mir_instruction(ctx, &ins);
1729          }
1730       } else if (ctx->stage == MESA_SHADER_VERTEX) {
1731          emit_attr_read(ctx, reg, offset, nr_comp, t);
1732       } else {
1733          unreachable("Unknown load");
1734       }
1735 
1736       break;
1737    }
1738 
1739    /* Handled together with load_interpolated_input */
1740    case nir_intrinsic_load_barycentric_pixel:
1741    case nir_intrinsic_load_barycentric_centroid:
1742    case nir_intrinsic_load_barycentric_sample:
1743       break;
1744 
1745       /* Reads 128-bit value raw off the tilebuffer during blending, tasty */
1746 
1747    case nir_intrinsic_load_raw_output_pan: {
1748       reg = nir_def_index(&instr->def);
1749 
1750       /* T720 and below use different blend opcodes with slightly
1751        * different semantics than T760 and up */
1752 
1753       midgard_instruction ld = m_ld_tilebuffer_raw(reg, 0);
1754 
1755       unsigned target = output_load_rt_addr(ctx, instr);
1756       ld.load_store.index_comp = target & 0x3;
1757       ld.load_store.index_reg = target >> 2;
1758 
1759       if (nir_src_is_const(instr->src[0])) {
1760          unsigned sample = nir_src_as_uint(instr->src[0]);
1761          ld.load_store.arg_comp = sample & 0x3;
1762          ld.load_store.arg_reg = sample >> 2;
1763       } else {
1764          /* Enable sample index via register. */
1765          ld.load_store.signed_offset |= 1;
1766          ld.src[1] = nir_src_index(ctx, &instr->src[0]);
1767          ld.src_types[1] = nir_type_int32;
1768       }
1769 
1770       if (ctx->quirks & MIDGARD_OLD_BLEND) {
1771          ld.op = midgard_op_ld_special_32u;
1772          ld.load_store.signed_offset = PACK_LDST_SELECTOR_OFS(16);
1773          ld.load_store.index_reg = REGISTER_LDST_ZERO;
1774       }
1775 
1776       emit_mir_instruction(ctx, &ld);
1777       break;
1778    }
1779 
1780    case nir_intrinsic_load_output: {
1781       reg = nir_def_index(&instr->def);
1782 
1783       unsigned bits = instr->def.bit_size;
1784 
1785       midgard_instruction ld;
1786       if (bits == 16)
1787          ld = m_ld_tilebuffer_16f(reg, 0);
1788       else
1789          ld = m_ld_tilebuffer_32f(reg, 0);
1790 
1791       unsigned index = output_load_rt_addr(ctx, instr);
1792       ld.load_store.index_comp = index & 0x3;
1793       ld.load_store.index_reg = index >> 2;
1794 
1795       for (unsigned c = 4; c < 16; ++c)
1796          ld.swizzle[0][c] = 0;
1797 
1798       if (ctx->quirks & MIDGARD_OLD_BLEND) {
1799          if (bits == 16)
1800             ld.op = midgard_op_ld_special_16f;
1801          else
1802             ld.op = midgard_op_ld_special_32f;
1803          ld.load_store.signed_offset = PACK_LDST_SELECTOR_OFS(1);
1804          ld.load_store.index_reg = REGISTER_LDST_ZERO;
1805       }
1806 
1807       emit_mir_instruction(ctx, &ld);
1808       break;
1809    }
1810 
1811    case nir_intrinsic_store_output:
1812    case nir_intrinsic_store_combined_output_pan:
1813       assert(nir_src_is_const(instr->src[1]) && "no indirect outputs");
1814 
1815       reg = nir_src_index(ctx, &instr->src[0]);
1816 
1817       if (ctx->stage == MESA_SHADER_FRAGMENT) {
1818          bool combined =
1819             instr->intrinsic == nir_intrinsic_store_combined_output_pan;
1820 
1821          enum midgard_rt_id rt;
1822 
1823          unsigned reg_z = ~0, reg_s = ~0, reg_2 = ~0;
1824          unsigned writeout = PAN_WRITEOUT_C;
1825          if (combined) {
1826             writeout = nir_intrinsic_component(instr);
1827             if (writeout & PAN_WRITEOUT_Z)
1828                reg_z = nir_src_index(ctx, &instr->src[2]);
1829             if (writeout & PAN_WRITEOUT_S)
1830                reg_s = nir_src_index(ctx, &instr->src[3]);
1831             if (writeout & PAN_WRITEOUT_2)
1832                reg_2 = nir_src_index(ctx, &instr->src[4]);
1833          }
1834 
1835          if (writeout & PAN_WRITEOUT_C) {
1836             nir_io_semantics sem = nir_intrinsic_io_semantics(instr);
1837 
1838             rt = MIDGARD_COLOR_RT0 + (sem.location - FRAG_RESULT_DATA0);
1839          } else {
1840             rt = MIDGARD_ZS_RT;
1841          }
1842 
1843          /* Dual-source blend writeout is done by leaving the
1844           * value in r2 for the blend shader to use. */
1845          if (~reg_2) {
1846             emit_explicit_constant(ctx, reg_2);
1847 
1848             unsigned out = make_compiler_temp(ctx);
1849 
1850             midgard_instruction ins = v_mov(reg_2, out);
1851             emit_mir_instruction(ctx, &ins);
1852 
1853             ctx->blend_src1 = out;
1854          }
1855 
1856          emit_fragment_store(ctx, reg, reg_z, reg_s, rt, 0);
1857       } else if (ctx->stage == MESA_SHADER_VERTEX) {
1858          assert(instr->intrinsic == nir_intrinsic_store_output);
1859 
1860          /* We should have been vectorized, though we don't
1861           * currently check that st_vary is emitted only once
1862           * per slot (this is relevant, since there's not a mask
1863           * parameter available on the store [set to 0 by the
1864           * blob]). We do respect the component by adjusting the
1865           * swizzle. If this is a constant source, we'll need to
1866           * emit that explicitly. */
1867 
1868          emit_explicit_constant(ctx, reg);
1869 
1870          offset = nir_intrinsic_base(instr) + nir_src_as_uint(instr->src[1]);
1871 
1872          unsigned dst_component = nir_intrinsic_component(instr);
1873          unsigned nr_comp = nir_src_num_components(instr->src[0]);
1874 
1875          /* ABI: Format controlled by the attribute descriptor.
1876           * This simplifies flat shading, although it prevents
1877           * certain (unimplemented) 16-bit optimizations.
1878           *
1879           * In particular, it lets the driver handle internal
1880           * TGSI shaders that set flat in the VS but smooth in
1881           * the FS. This matches our handling on Bifrost.
1882           */
1883          bool auto32 = true;
1884          assert(nir_alu_type_get_type_size(nir_intrinsic_src_type(instr)) ==
1885                 32);
1886 
1887          /* ABI: varyings in the secondary attribute table */
1888          bool secondary_table = true;
1889 
1890          midgard_instruction st =
1891             m_st_vary_32(reg, PACK_LDST_ATTRIB_OFS(offset));
1892          st.load_store.arg_reg = REGISTER_LDST_ZERO;
1893          st.load_store.index_reg = REGISTER_LDST_ZERO;
1894 
1895          /* Attribute instruction uses these 2-bits for the
1896           * a32 and table bits, pack this specially.
1897           */
1898          st.load_store.index_format =
1899             (auto32 ? (1 << 0) : 0) | (secondary_table ? (1 << 1) : 0);
1900 
1901          /* nir_intrinsic_component(store_intr) encodes the
1902           * destination component start. Source component offset
1903           * adjustment is taken care of in
1904           * install_registers_instr(), when offset_swizzle() is
1905           * called.
1906           */
1907          unsigned src_component = COMPONENT_X;
1908 
1909          assert(nr_comp > 0);
1910          for (unsigned i = 0; i < ARRAY_SIZE(st.swizzle); ++i) {
1911             st.swizzle[0][i] = src_component;
1912             if (i >= dst_component && i < dst_component + nr_comp - 1)
1913                src_component++;
1914          }
1915 
1916          emit_mir_instruction(ctx, &st);
1917       } else {
1918          unreachable("Unknown store");
1919       }
1920 
1921       break;
1922 
1923    /* Special case of store_output for lowered blend shaders */
1924    case nir_intrinsic_store_raw_output_pan: {
1925       assert(ctx->stage == MESA_SHADER_FRAGMENT);
1926       reg = nir_src_index(ctx, &instr->src[0]);
1927 
1928       nir_io_semantics sem = nir_intrinsic_io_semantics(instr);
1929       assert(sem.location >= FRAG_RESULT_DATA0);
1930       unsigned rt = sem.location - FRAG_RESULT_DATA0;
1931 
1932       emit_fragment_store(ctx, reg, ~0, ~0, rt + MIDGARD_COLOR_RT0,
1933                           nir_intrinsic_base(instr));
1934       break;
1935    }
1936 
1937    case nir_intrinsic_store_global:
1938    case nir_intrinsic_store_shared:
1939    case nir_intrinsic_store_scratch:
1940       reg = nir_src_index(ctx, &instr->src[0]);
1941       emit_explicit_constant(ctx, reg);
1942 
1943       unsigned seg;
1944       if (instr->intrinsic == nir_intrinsic_store_global)
1945          seg = LDST_GLOBAL;
1946       else if (instr->intrinsic == nir_intrinsic_store_shared)
1947          seg = LDST_SHARED;
1948       else
1949          seg = LDST_SCRATCH;
1950 
1951       emit_global(ctx, &instr->instr, false, reg, &instr->src[1], seg);
1952       break;
1953 
1954    case nir_intrinsic_load_workgroup_id:
1955    case nir_intrinsic_load_local_invocation_id:
1956    case nir_intrinsic_load_global_invocation_id:
1957       emit_compute_builtin(ctx, instr);
1958       break;
1959 
1960    case nir_intrinsic_load_raw_vertex_id_pan:
1961       ctx->info->midgard.vs.reads_raw_vertex_id = true;
1962       FALLTHROUGH;
1963    case nir_intrinsic_load_instance_id:
1964       emit_vertex_builtin(ctx, instr);
1965       break;
1966 
1967    case nir_intrinsic_load_sample_mask_in:
1968       emit_special(ctx, instr, 96);
1969       break;
1970 
1971    case nir_intrinsic_load_sample_id:
1972       emit_special(ctx, instr, 97);
1973       break;
1974 
1975    case nir_intrinsic_barrier:
1976       if (nir_intrinsic_execution_scope(instr) != SCOPE_NONE) {
1977          schedule_barrier(ctx);
1978          emit_control_barrier(ctx);
1979          schedule_barrier(ctx);
1980       } else if (nir_intrinsic_memory_scope(instr) != SCOPE_NONE) {
1981          /* Midgard doesn't seem to want special handling, though we do need to
1982           * take care when scheduling to avoid incorrect reordering.
1983           *
1984           * Note this is an "else if" since the handling for the execution scope
1985           * case already covers the case when both scopes are present.
1986           */
1987          schedule_barrier(ctx);
1988       }
1989       break;
1990 
1991    case nir_intrinsic_shared_atomic:
1992    case nir_intrinsic_shared_atomic_swap:
1993    case nir_intrinsic_global_atomic:
1994    case nir_intrinsic_global_atomic_swap:
1995       emit_atomic(ctx, instr);
1996       break;
1997 
1998    case nir_intrinsic_ddx:
1999    case nir_intrinsic_ddy:
2000       midgard_emit_derivatives(ctx, instr);
2001       break;
2002 
2003    default:
2004       fprintf(stderr, "Unhandled intrinsic %s\n",
2005               nir_intrinsic_infos[instr->intrinsic].name);
2006       assert(0);
2007       break;
2008    }
2009 }
2010 
2011 /* Returns dimension with 0 special casing cubemaps */
2012 static unsigned
midgard_tex_format(enum glsl_sampler_dim dim)2013 midgard_tex_format(enum glsl_sampler_dim dim)
2014 {
2015    switch (dim) {
2016    case GLSL_SAMPLER_DIM_1D:
2017    case GLSL_SAMPLER_DIM_BUF:
2018       return 1;
2019 
2020    case GLSL_SAMPLER_DIM_2D:
2021    case GLSL_SAMPLER_DIM_MS:
2022    case GLSL_SAMPLER_DIM_EXTERNAL:
2023    case GLSL_SAMPLER_DIM_RECT:
2024       return 2;
2025 
2026    case GLSL_SAMPLER_DIM_3D:
2027       return 3;
2028 
2029    case GLSL_SAMPLER_DIM_CUBE:
2030       return 0;
2031 
2032    default:
2033       unreachable("Unknown sampler dim type");
2034    }
2035 }
2036 
2037 /* Tries to attach an explicit LOD or bias as a constant. Returns whether this
2038  * was successful */
2039 
2040 static bool
pan_attach_constant_bias(compiler_context * ctx,nir_src lod,midgard_texture_word * word)2041 pan_attach_constant_bias(compiler_context *ctx, nir_src lod,
2042                          midgard_texture_word *word)
2043 {
2044    /* To attach as constant, it has to *be* constant */
2045 
2046    if (!nir_src_is_const(lod))
2047       return false;
2048 
2049    float f = nir_src_as_float(lod);
2050 
2051    /* Break into fixed-point */
2052    signed lod_int = f;
2053    float lod_frac = f - lod_int;
2054 
2055    /* Carry over negative fractions */
2056    if (lod_frac < 0.0) {
2057       lod_int--;
2058       lod_frac += 1.0;
2059    }
2060 
2061    /* Encode */
2062    word->bias = float_to_ubyte(lod_frac);
2063    word->bias_int = lod_int;
2064 
2065    return true;
2066 }
2067 
2068 static enum mali_texture_mode
mdg_texture_mode(nir_tex_instr * instr)2069 mdg_texture_mode(nir_tex_instr *instr)
2070 {
2071    if (instr->op == nir_texop_tg4 && instr->is_shadow)
2072       return TEXTURE_GATHER_SHADOW;
2073    else if (instr->op == nir_texop_tg4)
2074       return TEXTURE_GATHER_X + instr->component;
2075    else if (instr->is_shadow)
2076       return TEXTURE_SHADOW;
2077    else
2078       return TEXTURE_NORMAL;
2079 }
2080 
2081 static void
set_tex_coord(compiler_context * ctx,nir_tex_instr * instr,midgard_instruction * ins)2082 set_tex_coord(compiler_context *ctx, nir_tex_instr *instr,
2083               midgard_instruction *ins)
2084 {
2085    int coord_idx = nir_tex_instr_src_index(instr, nir_tex_src_coord);
2086 
2087    assert(coord_idx >= 0);
2088 
2089    int comparator_idx = nir_tex_instr_src_index(instr, nir_tex_src_comparator);
2090    int ms_idx = nir_tex_instr_src_index(instr, nir_tex_src_ms_index);
2091    assert(comparator_idx < 0 || ms_idx < 0);
2092    int ms_or_comparator_idx = ms_idx >= 0 ? ms_idx : comparator_idx;
2093 
2094    unsigned coords = nir_src_index(ctx, &instr->src[coord_idx].src);
2095 
2096    emit_explicit_constant(ctx, coords);
2097 
2098    ins->src_types[1] = nir_tex_instr_src_type(instr, coord_idx) |
2099                        nir_src_bit_size(instr->src[coord_idx].src);
2100 
2101    unsigned nr_comps = instr->coord_components;
2102    unsigned written_mask = 0, write_mask = 0;
2103 
2104    /* Initialize all components to coord.x which is expected to always be
2105     * present. Swizzle is updated below based on the texture dimension
2106     * and extra attributes that are packed in the coordinate argument.
2107     */
2108    for (unsigned c = 0; c < MIR_VEC_COMPONENTS; c++)
2109       ins->swizzle[1][c] = COMPONENT_X;
2110 
2111    /* Shadow ref value is part of the coordinates if there's no comparator
2112     * source, in that case it's always placed in the last component.
2113     * Midgard wants the ref value in coord.z.
2114     */
2115    if (instr->is_shadow && comparator_idx < 0) {
2116       ins->swizzle[1][COMPONENT_Z] = --nr_comps;
2117       write_mask |= 1 << COMPONENT_Z;
2118    }
2119 
2120    /* The array index is the last component if there's no shadow ref value
2121     * or second last if there's one. We already decremented the number of
2122     * components to account for the shadow ref value above.
2123     * Midgard wants the array index in coord.w.
2124     */
2125    if (instr->is_array) {
2126       ins->swizzle[1][COMPONENT_W] = --nr_comps;
2127       write_mask |= 1 << COMPONENT_W;
2128    }
2129 
2130    if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE) {
2131       /* texelFetch is undefined on samplerCube */
2132       assert(ins->op != midgard_tex_op_fetch);
2133 
2134       ins->src[1] = make_compiler_temp_reg(ctx);
2135 
2136       /* For cubemaps, we use a special ld/st op to select the face
2137        * and copy the xy into the texture register
2138        */
2139       midgard_instruction ld = m_ld_cubemap_coords(ins->src[1], 0);
2140       ld.src[1] = coords;
2141       ld.src_types[1] = ins->src_types[1];
2142       ld.mask = 0x3; /* xy */
2143       ld.load_store.bitsize_toggle = true;
2144       ld.swizzle[1][3] = COMPONENT_X;
2145       emit_mir_instruction(ctx, &ld);
2146 
2147       /* We packed cube coordiates (X,Y,Z) into (X,Y), update the
2148        * written mask accordingly and decrement the number of
2149        * components
2150        */
2151       nr_comps--;
2152       written_mask |= 3;
2153    }
2154 
2155    /* Now flag tex coord components that have not been written yet */
2156    write_mask |= mask_of(nr_comps) & ~written_mask;
2157    for (unsigned c = 0; c < nr_comps; c++)
2158       ins->swizzle[1][c] = c;
2159 
2160    /* Sample index and shadow ref are expected in coord.z */
2161    if (ms_or_comparator_idx >= 0) {
2162       assert(!((write_mask | written_mask) & (1 << COMPONENT_Z)));
2163 
2164       unsigned sample_or_ref =
2165          nir_src_index(ctx, &instr->src[ms_or_comparator_idx].src);
2166 
2167       emit_explicit_constant(ctx, sample_or_ref);
2168 
2169       if (ins->src[1] == ~0)
2170          ins->src[1] = make_compiler_temp_reg(ctx);
2171 
2172       midgard_instruction mov = v_mov(sample_or_ref, ins->src[1]);
2173 
2174       for (unsigned c = 0; c < MIR_VEC_COMPONENTS; c++)
2175          mov.swizzle[1][c] = COMPONENT_X;
2176 
2177       mov.mask = 1 << COMPONENT_Z;
2178       written_mask |= 1 << COMPONENT_Z;
2179       ins->swizzle[1][COMPONENT_Z] = COMPONENT_Z;
2180       emit_mir_instruction(ctx, &mov);
2181    }
2182 
2183    /* Texelfetch coordinates uses all four elements (xyz/index) regardless
2184     * of texture dimensionality, which means it's necessary to zero the
2185     * unused components to keep everything happy.
2186     */
2187    if (ins->op == midgard_tex_op_fetch && (written_mask | write_mask) != 0xF) {
2188       if (ins->src[1] == ~0)
2189          ins->src[1] = make_compiler_temp_reg(ctx);
2190 
2191       /* mov index.zw, #0, or generalized */
2192       midgard_instruction mov =
2193          v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), ins->src[1]);
2194       mov.has_constants = true;
2195       mov.mask = (written_mask | write_mask) ^ 0xF;
2196       emit_mir_instruction(ctx, &mov);
2197       for (unsigned c = 0; c < MIR_VEC_COMPONENTS; c++) {
2198          if (mov.mask & (1 << c))
2199             ins->swizzle[1][c] = c;
2200       }
2201    }
2202 
2203    if (ins->src[1] == ~0) {
2204       /* No temporary reg created, use the src coords directly */
2205       ins->src[1] = coords;
2206    } else if (write_mask) {
2207       /* Move the remaining coordinates to the temporary reg */
2208       midgard_instruction mov = v_mov(coords, ins->src[1]);
2209 
2210       for (unsigned c = 0; c < MIR_VEC_COMPONENTS; c++) {
2211          if ((1 << c) & write_mask) {
2212             mov.swizzle[1][c] = ins->swizzle[1][c];
2213             ins->swizzle[1][c] = c;
2214          } else {
2215             mov.swizzle[1][c] = COMPONENT_X;
2216          }
2217       }
2218 
2219       mov.mask = write_mask;
2220       emit_mir_instruction(ctx, &mov);
2221    }
2222 }
2223 
2224 static void
emit_texop_native(compiler_context * ctx,nir_tex_instr * instr,unsigned midgard_texop)2225 emit_texop_native(compiler_context *ctx, nir_tex_instr *instr,
2226                   unsigned midgard_texop)
2227 {
2228    int texture_index = instr->texture_index;
2229    int sampler_index = instr->sampler_index;
2230 
2231    /* If txf is used, we assume there is a valid sampler bound at index 0. Use
2232     * it for txf operations, since there may be no other valid samplers. This is
2233     * a workaround: txf does not require a sampler in NIR (so sampler_index is
2234     * undefined) but we need one in the hardware. This is ABI with the driver.
2235     */
2236    if (!nir_tex_instr_need_sampler(instr))
2237       sampler_index = 0;
2238 
2239    midgard_instruction ins = {
2240       .type = TAG_TEXTURE_4,
2241       .mask = 0xF,
2242       .dest = nir_def_index(&instr->def),
2243       .src = {~0, ~0, ~0, ~0},
2244       .dest_type = instr->dest_type,
2245       .swizzle = SWIZZLE_IDENTITY_4,
2246       .outmod = midgard_outmod_none,
2247       .op = midgard_texop,
2248       .texture = {
2249          .format = midgard_tex_format(instr->sampler_dim),
2250          .texture_handle = texture_index,
2251          .sampler_handle = sampler_index,
2252          .mode = mdg_texture_mode(instr),
2253       }};
2254 
2255    if (instr->is_shadow && !instr->is_new_style_shadow &&
2256        instr->op != nir_texop_tg4)
2257       for (int i = 0; i < 4; ++i)
2258          ins.swizzle[0][i] = COMPONENT_X;
2259 
2260    for (unsigned i = 0; i < instr->num_srcs; ++i) {
2261       int index = nir_src_index(ctx, &instr->src[i].src);
2262       unsigned sz = nir_src_bit_size(instr->src[i].src);
2263       nir_alu_type T = nir_tex_instr_src_type(instr, i) | sz;
2264 
2265       switch (instr->src[i].src_type) {
2266       case nir_tex_src_coord:
2267          set_tex_coord(ctx, instr, &ins);
2268          break;
2269 
2270       case nir_tex_src_bias:
2271       case nir_tex_src_lod: {
2272          /* Try as a constant if we can */
2273 
2274          bool is_txf = midgard_texop == midgard_tex_op_fetch;
2275          if (!is_txf &&
2276              pan_attach_constant_bias(ctx, instr->src[i].src, &ins.texture))
2277             break;
2278 
2279          ins.texture.lod_register = true;
2280          ins.src[2] = index;
2281          ins.src_types[2] = T;
2282 
2283          for (unsigned c = 0; c < MIR_VEC_COMPONENTS; ++c)
2284             ins.swizzle[2][c] = COMPONENT_X;
2285 
2286          emit_explicit_constant(ctx, index);
2287 
2288          break;
2289       };
2290 
2291       case nir_tex_src_offset: {
2292          ins.texture.offset_register = true;
2293          ins.src[3] = index;
2294          ins.src_types[3] = T;
2295 
2296          for (unsigned c = 0; c < MIR_VEC_COMPONENTS; ++c)
2297             ins.swizzle[3][c] = (c > COMPONENT_Z) ? 0 : c;
2298 
2299          emit_explicit_constant(ctx, index);
2300          break;
2301       };
2302 
2303       case nir_tex_src_comparator:
2304       case nir_tex_src_ms_index:
2305          /* Nothing to do, handled in set_tex_coord() */
2306          break;
2307 
2308       default: {
2309          fprintf(stderr, "Unknown texture source type: %d\n",
2310                  instr->src[i].src_type);
2311          assert(0);
2312       }
2313       }
2314    }
2315 
2316    emit_mir_instruction(ctx, &ins);
2317 }
2318 
2319 static void
emit_tex(compiler_context * ctx,nir_tex_instr * instr)2320 emit_tex(compiler_context *ctx, nir_tex_instr *instr)
2321 {
2322    switch (instr->op) {
2323    case nir_texop_tex:
2324    case nir_texop_txb:
2325       emit_texop_native(ctx, instr, midgard_tex_op_normal);
2326       break;
2327    case nir_texop_txl:
2328    case nir_texop_tg4:
2329       emit_texop_native(ctx, instr, midgard_tex_op_gradient);
2330       break;
2331    case nir_texop_txf:
2332    case nir_texop_txf_ms:
2333       emit_texop_native(ctx, instr, midgard_tex_op_fetch);
2334       break;
2335    default: {
2336       fprintf(stderr, "Unhandled texture op: %d\n", instr->op);
2337       assert(0);
2338    }
2339    }
2340 }
2341 
2342 static void
emit_jump(compiler_context * ctx,nir_jump_instr * instr)2343 emit_jump(compiler_context *ctx, nir_jump_instr *instr)
2344 {
2345    switch (instr->type) {
2346    case nir_jump_break: {
2347       /* Emit a branch out of the loop */
2348       struct midgard_instruction br = v_branch(false, false);
2349       br.branch.target_type = TARGET_BREAK;
2350       br.branch.target_break = ctx->current_loop_depth;
2351       emit_mir_instruction(ctx, &br);
2352       break;
2353    }
2354 
2355    default:
2356       unreachable("Unhandled jump");
2357    }
2358 }
2359 
2360 static void
emit_instr(compiler_context * ctx,struct nir_instr * instr)2361 emit_instr(compiler_context *ctx, struct nir_instr *instr)
2362 {
2363    switch (instr->type) {
2364    case nir_instr_type_load_const:
2365       emit_load_const(ctx, nir_instr_as_load_const(instr));
2366       break;
2367 
2368    case nir_instr_type_intrinsic:
2369       emit_intrinsic(ctx, nir_instr_as_intrinsic(instr));
2370       break;
2371 
2372    case nir_instr_type_alu:
2373       emit_alu(ctx, nir_instr_as_alu(instr));
2374       break;
2375 
2376    case nir_instr_type_tex:
2377       emit_tex(ctx, nir_instr_as_tex(instr));
2378       break;
2379 
2380    case nir_instr_type_jump:
2381       emit_jump(ctx, nir_instr_as_jump(instr));
2382       break;
2383 
2384    case nir_instr_type_undef:
2385       /* Spurious */
2386       break;
2387 
2388    default:
2389       unreachable("Unhandled instruction type");
2390    }
2391 }
2392 
2393 /* ALU instructions can inline or embed constants, which decreases register
2394  * pressure and saves space. */
2395 
2396 #define CONDITIONAL_ATTACH(idx)                                                \
2397    {                                                                           \
2398       void *entry =                                                            \
2399          _mesa_hash_table_u64_search(ctx->ssa_constants, alu->src[idx] + 1);   \
2400                                                                                \
2401       if (entry) {                                                             \
2402          attach_constants(ctx, alu, entry, alu->src[idx] + 1);                 \
2403          alu->src[idx] = SSA_FIXED_REGISTER(REGISTER_CONSTANT);                \
2404       }                                                                        \
2405    }
2406 
2407 static void
inline_alu_constants(compiler_context * ctx,midgard_block * block)2408 inline_alu_constants(compiler_context *ctx, midgard_block *block)
2409 {
2410    mir_foreach_instr_in_block(block, alu) {
2411       /* Other instructions cannot inline constants */
2412       if (alu->type != TAG_ALU_4)
2413          continue;
2414       if (alu->compact_branch)
2415          continue;
2416 
2417       /* If there is already a constant here, we can do nothing */
2418       if (alu->has_constants)
2419          continue;
2420 
2421       CONDITIONAL_ATTACH(0);
2422 
2423       if (!alu->has_constants) {
2424          CONDITIONAL_ATTACH(1)
2425       } else if (!alu->inline_constant) {
2426          /* Corner case: _two_ vec4 constants, for instance with a
2427           * csel. For this case, we can only use a constant
2428           * register for one, we'll have to emit a move for the
2429           * other. */
2430 
2431          void *entry =
2432             _mesa_hash_table_u64_search(ctx->ssa_constants, alu->src[1] + 1);
2433          unsigned scratch = make_compiler_temp(ctx);
2434 
2435          if (entry) {
2436             midgard_instruction ins =
2437                v_mov(SSA_FIXED_REGISTER(REGISTER_CONSTANT), scratch);
2438             attach_constants(ctx, &ins, entry, alu->src[1] + 1);
2439 
2440             /* Set the source */
2441             alu->src[1] = scratch;
2442 
2443             /* Inject us -before- the last instruction which set r31, if
2444              * possible.
2445              */
2446             midgard_instruction *first = list_first_entry(
2447                &block->base.instructions, midgard_instruction, link);
2448 
2449             if (alu == first) {
2450                mir_insert_instruction_before(ctx, alu, &ins);
2451             } else {
2452                mir_insert_instruction_before(ctx, mir_prev_op(alu), &ins);
2453             }
2454          }
2455       }
2456    }
2457 }
2458 
2459 unsigned
max_bitsize_for_alu(const midgard_instruction * ins)2460 max_bitsize_for_alu(const midgard_instruction *ins)
2461 {
2462    unsigned max_bitsize = 0;
2463    for (int i = 0; i < MIR_SRC_COUNT; i++) {
2464       if (ins->src[i] == ~0)
2465          continue;
2466       unsigned src_bitsize = nir_alu_type_get_type_size(ins->src_types[i]);
2467       max_bitsize = MAX2(src_bitsize, max_bitsize);
2468    }
2469    unsigned dst_bitsize = nir_alu_type_get_type_size(ins->dest_type);
2470    max_bitsize = MAX2(dst_bitsize, max_bitsize);
2471 
2472    /* We emulate 8-bit as 16-bit for simplicity of packing */
2473    max_bitsize = MAX2(max_bitsize, 16);
2474 
2475    /* We don't have fp16 LUTs, so we'll want to emit code like:
2476     *
2477     *      vlut.fsinr hr0, hr0
2478     *
2479     * where both input and output are 16-bit but the operation is carried
2480     * out in 32-bit
2481     */
2482 
2483    switch (ins->op) {
2484    case midgard_alu_op_fsqrt:
2485    case midgard_alu_op_frcp:
2486    case midgard_alu_op_frsqrt:
2487    case midgard_alu_op_fsinpi:
2488    case midgard_alu_op_fcospi:
2489    case midgard_alu_op_fexp2:
2490    case midgard_alu_op_flog2:
2491       max_bitsize = MAX2(max_bitsize, 32);
2492       break;
2493 
2494    default:
2495       break;
2496    }
2497 
2498    /* High implies computing at a higher bitsize, e.g umul_high of 32-bit
2499     * requires computing at 64-bit */
2500    if (midgard_is_integer_out_op(ins->op) &&
2501        ins->outmod == midgard_outmod_keephi) {
2502       max_bitsize *= 2;
2503       assert(max_bitsize <= 64);
2504    }
2505 
2506    return max_bitsize;
2507 }
2508 
2509 midgard_reg_mode
reg_mode_for_bitsize(unsigned bitsize)2510 reg_mode_for_bitsize(unsigned bitsize)
2511 {
2512    switch (bitsize) {
2513       /* use 16 pipe for 8 since we don't support vec16 yet */
2514    case 8:
2515    case 16:
2516       return midgard_reg_mode_16;
2517    case 32:
2518       return midgard_reg_mode_32;
2519    case 64:
2520       return midgard_reg_mode_64;
2521    default:
2522       unreachable("invalid bit size");
2523    }
2524 }
2525 
2526 /* Midgard supports two types of constants, embedded constants (128-bit) and
2527  * inline constants (16-bit). Sometimes, especially with scalar ops, embedded
2528  * constants can be demoted to inline constants, for space savings and
2529  * sometimes a performance boost */
2530 
2531 static void
embedded_to_inline_constant(compiler_context * ctx,midgard_block * block)2532 embedded_to_inline_constant(compiler_context *ctx, midgard_block *block)
2533 {
2534    mir_foreach_instr_in_block(block, ins) {
2535       if (!ins->has_constants)
2536          continue;
2537       if (ins->has_inline_constant)
2538          continue;
2539 
2540       unsigned max_bitsize = max_bitsize_for_alu(ins);
2541 
2542       /* We can inline 32-bit (sometimes) or 16-bit (usually) */
2543       bool is_16 = max_bitsize == 16;
2544       bool is_32 = max_bitsize == 32;
2545 
2546       if (!(is_16 || is_32))
2547          continue;
2548 
2549       /* src1 cannot be an inline constant due to encoding
2550        * restrictions. So, if possible we try to flip the arguments
2551        * in that case */
2552 
2553       int op = ins->op;
2554 
2555       if (ins->src[0] == SSA_FIXED_REGISTER(REGISTER_CONSTANT) &&
2556           alu_opcode_props[op].props & OP_COMMUTES) {
2557          mir_flip(ins);
2558       }
2559 
2560       if (ins->src[1] == SSA_FIXED_REGISTER(REGISTER_CONSTANT)) {
2561          /* Component is from the swizzle. Take a nonzero component */
2562          assert(ins->mask);
2563          unsigned first_comp = ffs(ins->mask) - 1;
2564          unsigned component = ins->swizzle[1][first_comp];
2565 
2566          /* Scale constant appropriately, if we can legally */
2567          int16_t scaled_constant = 0;
2568 
2569          if (is_16) {
2570             scaled_constant = ins->constants.u16[component];
2571          } else if (midgard_is_integer_op(op)) {
2572             scaled_constant = ins->constants.u32[component];
2573 
2574             /* Constant overflow after resize */
2575             if (scaled_constant != ins->constants.u32[component])
2576                continue;
2577          } else {
2578             float original = ins->constants.f32[component];
2579             scaled_constant = _mesa_float_to_half(original);
2580 
2581             /* Check for loss of precision. If this is
2582              * mediump, we don't care, but for a highp
2583              * shader, we need to pay attention. NIR
2584              * doesn't yet tell us which mode we're in!
2585              * Practically this prevents most constants
2586              * from being inlined, sadly. */
2587 
2588             float fp32 = _mesa_half_to_float(scaled_constant);
2589 
2590             if (fp32 != original)
2591                continue;
2592          }
2593 
2594          /* Should've been const folded */
2595          if (ins->src_abs[1] || ins->src_neg[1])
2596             continue;
2597 
2598          /* Make sure that the constant is not itself a vector
2599           * by checking if all accessed values are the same. */
2600 
2601          const midgard_constants *cons = &ins->constants;
2602          uint32_t value = is_16 ? cons->u16[component] : cons->u32[component];
2603 
2604          bool is_vector = false;
2605          unsigned mask = effective_writemask(ins->op, ins->mask);
2606 
2607          for (unsigned c = 0; c < MIR_VEC_COMPONENTS; ++c) {
2608             /* We only care if this component is actually used */
2609             if (!(mask & (1 << c)))
2610                continue;
2611 
2612             uint32_t test = is_16 ? cons->u16[ins->swizzle[1][c]]
2613                                   : cons->u32[ins->swizzle[1][c]];
2614 
2615             if (test != value) {
2616                is_vector = true;
2617                break;
2618             }
2619          }
2620 
2621          if (is_vector)
2622             continue;
2623 
2624          /* Get rid of the embedded constant */
2625          ins->has_constants = false;
2626          ins->src[1] = ~0;
2627          ins->has_inline_constant = true;
2628          ins->inline_constant = scaled_constant;
2629       }
2630    }
2631 }
2632 
2633 /* Dead code elimination for branches at the end of a block - only one branch
2634  * per block is legal semantically */
2635 
2636 static void
midgard_cull_dead_branch(compiler_context * ctx,midgard_block * block)2637 midgard_cull_dead_branch(compiler_context *ctx, midgard_block *block)
2638 {
2639    bool branched = false;
2640 
2641    mir_foreach_instr_in_block_safe(block, ins) {
2642       if (!midgard_is_branch_unit(ins->unit))
2643          continue;
2644 
2645       if (branched)
2646          mir_remove_instruction(ins);
2647 
2648       branched = true;
2649    }
2650 }
2651 
2652 /* We want to force the invert on AND/OR to the second slot to legalize into
2653  * iandnot/iornot. The relevant patterns are for AND (and OR respectively)
2654  *
2655  *   ~a & #b = ~a & ~(#~b)
2656  *   ~a & b = b & ~a
2657  */
2658 
2659 static void
midgard_legalize_invert(compiler_context * ctx,midgard_block * block)2660 midgard_legalize_invert(compiler_context *ctx, midgard_block *block)
2661 {
2662    mir_foreach_instr_in_block(block, ins) {
2663       if (ins->type != TAG_ALU_4)
2664          continue;
2665 
2666       if (ins->op != midgard_alu_op_iand && ins->op != midgard_alu_op_ior)
2667          continue;
2668 
2669       if (ins->src_invert[1] || !ins->src_invert[0])
2670          continue;
2671 
2672       if (ins->has_inline_constant) {
2673          /* ~(#~a) = ~(~#a) = a, so valid, and forces both
2674           * inverts on */
2675          ins->inline_constant = ~ins->inline_constant;
2676          ins->src_invert[1] = true;
2677       } else {
2678          /* Flip to the right invert order. Note
2679           * has_inline_constant false by assumption on the
2680           * branch, so flipping makes sense. */
2681          mir_flip(ins);
2682       }
2683    }
2684 }
2685 
2686 static unsigned
emit_fragment_epilogue(compiler_context * ctx,unsigned rt,unsigned sample_iter)2687 emit_fragment_epilogue(compiler_context *ctx, unsigned rt, unsigned sample_iter)
2688 {
2689    /* Loop to ourselves */
2690    midgard_instruction *br = ctx->writeout_branch[rt][sample_iter];
2691    struct midgard_instruction ins = v_branch(false, false);
2692    ins.writeout = br->writeout;
2693    ins.branch.target_block = ctx->block_count - 1;
2694    ins.constants.u32[0] = br->constants.u32[0];
2695    memcpy(&ins.src_types, &br->src_types, sizeof(ins.src_types));
2696    emit_mir_instruction(ctx, &ins);
2697 
2698    ctx->current_block->epilogue = true;
2699    schedule_barrier(ctx);
2700    return ins.branch.target_block;
2701 }
2702 
2703 static midgard_block *
emit_block_init(compiler_context * ctx)2704 emit_block_init(compiler_context *ctx)
2705 {
2706    midgard_block *this_block = ctx->after_block;
2707    ctx->after_block = NULL;
2708 
2709    if (!this_block)
2710       this_block = create_empty_block(ctx);
2711 
2712    list_addtail(&this_block->base.link, &ctx->blocks);
2713 
2714    this_block->scheduled = false;
2715    ++ctx->block_count;
2716 
2717    /* Set up current block */
2718    list_inithead(&this_block->base.instructions);
2719    ctx->current_block = this_block;
2720 
2721    return this_block;
2722 }
2723 
2724 static midgard_block *
emit_block(compiler_context * ctx,nir_block * block)2725 emit_block(compiler_context *ctx, nir_block *block)
2726 {
2727    midgard_block *this_block = emit_block_init(ctx);
2728 
2729    nir_foreach_instr(instr, block) {
2730       emit_instr(ctx, instr);
2731       ++ctx->instruction_count;
2732    }
2733 
2734    return this_block;
2735 }
2736 
2737 static midgard_block *emit_cf_list(struct compiler_context *ctx,
2738                                    struct exec_list *list);
2739 
2740 static void
emit_if(struct compiler_context * ctx,nir_if * nif)2741 emit_if(struct compiler_context *ctx, nir_if *nif)
2742 {
2743    midgard_block *before_block = ctx->current_block;
2744 
2745    /* Speculatively emit the branch, but we can't fill it in until later */
2746    EMIT(branch, true, true);
2747    midgard_instruction *then_branch = mir_last_in_block(ctx->current_block);
2748    then_branch->src[0] = nir_src_index(ctx, &nif->condition);
2749    then_branch->src_types[0] = nir_type_uint32;
2750 
2751    /* Emit the two subblocks. */
2752    midgard_block *then_block = emit_cf_list(ctx, &nif->then_list);
2753    midgard_block *end_then_block = ctx->current_block;
2754 
2755    /* Emit a jump from the end of the then block to the end of the else */
2756    EMIT(branch, false, false);
2757    midgard_instruction *then_exit = mir_last_in_block(ctx->current_block);
2758 
2759    /* Emit second block, and check if it's empty */
2760 
2761    int else_idx = ctx->block_count;
2762    int count_in = ctx->instruction_count;
2763    midgard_block *else_block = emit_cf_list(ctx, &nif->else_list);
2764    midgard_block *end_else_block = ctx->current_block;
2765    int after_else_idx = ctx->block_count;
2766 
2767    /* Now that we have the subblocks emitted, fix up the branches */
2768 
2769    assert(then_block);
2770    assert(else_block);
2771 
2772    if (ctx->instruction_count == count_in) {
2773       /* The else block is empty, so don't emit an exit jump */
2774       mir_remove_instruction(then_exit);
2775       then_branch->branch.target_block = after_else_idx;
2776    } else {
2777       then_branch->branch.target_block = else_idx;
2778       then_exit->branch.target_block = after_else_idx;
2779    }
2780 
2781    /* Wire up the successors */
2782 
2783    ctx->after_block = create_empty_block(ctx);
2784 
2785    pan_block_add_successor(&before_block->base, &then_block->base);
2786    pan_block_add_successor(&before_block->base, &else_block->base);
2787 
2788    pan_block_add_successor(&end_then_block->base, &ctx->after_block->base);
2789    pan_block_add_successor(&end_else_block->base, &ctx->after_block->base);
2790 }
2791 
2792 static void
emit_loop(struct compiler_context * ctx,nir_loop * nloop)2793 emit_loop(struct compiler_context *ctx, nir_loop *nloop)
2794 {
2795    assert(!nir_loop_has_continue_construct(nloop));
2796 
2797    /* Remember where we are */
2798    midgard_block *start_block = ctx->current_block;
2799 
2800    /* Allocate a loop number, growing the current inner loop depth */
2801    int loop_idx = ++ctx->current_loop_depth;
2802 
2803    /* Get index from before the body so we can loop back later */
2804    int start_idx = ctx->block_count;
2805 
2806    /* Emit the body itself */
2807    midgard_block *loop_block = emit_cf_list(ctx, &nloop->body);
2808 
2809    /* Branch back to loop back */
2810    struct midgard_instruction br_back = v_branch(false, false);
2811    br_back.branch.target_block = start_idx;
2812    emit_mir_instruction(ctx, &br_back);
2813 
2814    /* Mark down that branch in the graph. */
2815    pan_block_add_successor(&start_block->base, &loop_block->base);
2816    pan_block_add_successor(&ctx->current_block->base, &loop_block->base);
2817 
2818    /* Find the index of the block about to follow us (note: we don't add
2819     * one; blocks are 0-indexed so we get a fencepost problem) */
2820    int break_block_idx = ctx->block_count;
2821 
2822    /* Fix up the break statements we emitted to point to the right place,
2823     * now that we can allocate a block number for them */
2824    ctx->after_block = create_empty_block(ctx);
2825 
2826    mir_foreach_block_from(ctx, start_block, _block) {
2827       mir_foreach_instr_in_block(((midgard_block *)_block), ins) {
2828          if (ins->type != TAG_ALU_4)
2829             continue;
2830          if (!ins->compact_branch)
2831             continue;
2832 
2833          /* We found a branch -- check the type to see if we need to do anything
2834           */
2835          if (ins->branch.target_type != TARGET_BREAK)
2836             continue;
2837 
2838          /* It's a break! Check if it's our break */
2839          if (ins->branch.target_break != loop_idx)
2840             continue;
2841 
2842          /* Okay, cool, we're breaking out of this loop.
2843           * Rewrite from a break to a goto */
2844 
2845          ins->branch.target_type = TARGET_GOTO;
2846          ins->branch.target_block = break_block_idx;
2847 
2848          pan_block_add_successor(_block, &ctx->after_block->base);
2849       }
2850    }
2851 
2852    /* Now that we've finished emitting the loop, free up the depth again
2853     * so we play nice with recursion amid nested loops */
2854    --ctx->current_loop_depth;
2855 
2856    /* Dump loop stats */
2857    ++ctx->loop_count;
2858 }
2859 
2860 static midgard_block *
emit_cf_list(struct compiler_context * ctx,struct exec_list * list)2861 emit_cf_list(struct compiler_context *ctx, struct exec_list *list)
2862 {
2863    midgard_block *start_block = NULL;
2864 
2865    foreach_list_typed(nir_cf_node, node, node, list) {
2866       switch (node->type) {
2867       case nir_cf_node_block: {
2868          midgard_block *block = emit_block(ctx, nir_cf_node_as_block(node));
2869 
2870          if (!start_block)
2871             start_block = block;
2872 
2873          break;
2874       }
2875 
2876       case nir_cf_node_if:
2877          emit_if(ctx, nir_cf_node_as_if(node));
2878          break;
2879 
2880       case nir_cf_node_loop:
2881          emit_loop(ctx, nir_cf_node_as_loop(node));
2882          break;
2883 
2884       case nir_cf_node_function:
2885          assert(0);
2886          break;
2887       }
2888    }
2889 
2890    return start_block;
2891 }
2892 
2893 /* Due to lookahead, we need to report the first tag executed in the command
2894  * stream and in branch targets. An initial block might be empty, so iterate
2895  * until we find one that 'works' */
2896 
2897 unsigned
midgard_get_first_tag_from_block(compiler_context * ctx,unsigned block_idx)2898 midgard_get_first_tag_from_block(compiler_context *ctx, unsigned block_idx)
2899 {
2900    midgard_block *initial_block = mir_get_block(ctx, block_idx);
2901 
2902    mir_foreach_block_from(ctx, initial_block, _v) {
2903       midgard_block *v = (midgard_block *)_v;
2904       if (v->quadword_count) {
2905          midgard_bundle *initial_bundle =
2906             util_dynarray_element(&v->bundles, midgard_bundle, 0);
2907 
2908          return initial_bundle->tag;
2909       }
2910    }
2911 
2912    /* Default to a tag 1 which will break from the shader, in case we jump
2913     * to the exit block (i.e. `return` in a compute shader) */
2914 
2915    return 1;
2916 }
2917 
2918 /* For each fragment writeout instruction, generate a writeout loop to
2919  * associate with it */
2920 
2921 static void
mir_add_writeout_loops(compiler_context * ctx)2922 mir_add_writeout_loops(compiler_context *ctx)
2923 {
2924    for (unsigned rt = 0; rt < ARRAY_SIZE(ctx->writeout_branch); ++rt) {
2925       for (unsigned s = 0; s < MIDGARD_MAX_SAMPLE_ITER; ++s) {
2926          midgard_instruction *br = ctx->writeout_branch[rt][s];
2927          if (!br)
2928             continue;
2929 
2930          unsigned popped = br->branch.target_block;
2931          pan_block_add_successor(&(mir_get_block(ctx, popped - 1)->base),
2932                                  &ctx->current_block->base);
2933          br->branch.target_block = emit_fragment_epilogue(ctx, rt, s);
2934          br->branch.target_type = TARGET_GOTO;
2935 
2936          /* If we have more RTs, we'll need to restore back after our
2937           * loop terminates */
2938          midgard_instruction *next_br = NULL;
2939 
2940          if ((s + 1) < MIDGARD_MAX_SAMPLE_ITER)
2941             next_br = ctx->writeout_branch[rt][s + 1];
2942 
2943          if (!next_br && (rt + 1) < ARRAY_SIZE(ctx->writeout_branch))
2944             next_br = ctx->writeout_branch[rt + 1][0];
2945 
2946          if (next_br) {
2947             midgard_instruction uncond = v_branch(false, false);
2948             uncond.branch.target_block = popped;
2949             uncond.branch.target_type = TARGET_GOTO;
2950             emit_mir_instruction(ctx, &uncond);
2951             pan_block_add_successor(&ctx->current_block->base,
2952                                     &(mir_get_block(ctx, popped)->base));
2953             schedule_barrier(ctx);
2954          } else {
2955             /* We're last, so we can terminate here */
2956             br->last_writeout = true;
2957          }
2958       }
2959    }
2960 }
2961 
2962 void
midgard_compile_shader_nir(nir_shader * nir,const struct panfrost_compile_inputs * inputs,struct util_dynarray * binary,struct pan_shader_info * info)2963 midgard_compile_shader_nir(nir_shader *nir,
2964                            const struct panfrost_compile_inputs *inputs,
2965                            struct util_dynarray *binary,
2966                            struct pan_shader_info *info)
2967 {
2968    midgard_debug = debug_get_option_midgard_debug();
2969 
2970    /* TODO: Bound against what? */
2971    compiler_context *ctx = rzalloc(NULL, compiler_context);
2972 
2973    ctx->inputs = inputs;
2974    ctx->nir = nir;
2975    ctx->info = info;
2976    ctx->stage = nir->info.stage;
2977    ctx->blend_input = ~0;
2978    ctx->blend_src1 = ~0;
2979    ctx->quirks = midgard_get_quirks(inputs->gpu_id);
2980 
2981    /* Initialize at a global (not block) level hash tables */
2982 
2983    ctx->ssa_constants = _mesa_hash_table_u64_create(ctx);
2984 
2985    /* Collect varyings after lowering I/O */
2986    info->quirk_no_auto32 = (ctx->quirks & MIDGARD_NO_AUTO32);
2987    pan_nir_collect_varyings(nir, info);
2988 
2989    /* Optimisation passes */
2990    optimise_nir(nir, ctx->quirks, inputs->is_blend);
2991 
2992    bool skip_internal = nir->info.internal;
2993    skip_internal &= !(midgard_debug & MIDGARD_DBG_INTERNAL);
2994 
2995    if (midgard_debug & MIDGARD_DBG_SHADERS && !skip_internal)
2996       nir_print_shader(nir, stdout);
2997 
2998    info->tls_size = nir->scratch_size;
2999 
3000    nir_foreach_function_with_impl(func, impl, nir) {
3001       list_inithead(&ctx->blocks);
3002       ctx->block_count = 0;
3003       ctx->func = func;
3004 
3005       if (nir->info.outputs_read && !inputs->is_blend) {
3006          emit_block_init(ctx);
3007 
3008          struct midgard_instruction wait = v_branch(false, false);
3009          wait.branch.target_type = TARGET_TILEBUF_WAIT;
3010 
3011          emit_mir_instruction(ctx, &wait);
3012 
3013          ++ctx->instruction_count;
3014       }
3015 
3016       emit_cf_list(ctx, &impl->body);
3017       break; /* TODO: Multi-function shaders */
3018    }
3019 
3020    /* Per-block lowering before opts */
3021 
3022    mir_foreach_block(ctx, _block) {
3023       midgard_block *block = (midgard_block *)_block;
3024       inline_alu_constants(ctx, block);
3025       embedded_to_inline_constant(ctx, block);
3026    }
3027    /* MIR-level optimizations */
3028 
3029    bool progress = false;
3030 
3031    do {
3032       progress = false;
3033       progress |= midgard_opt_dead_code_eliminate(ctx);
3034       progress |= midgard_opt_prop(ctx);
3035 
3036       mir_foreach_block(ctx, _block) {
3037          midgard_block *block = (midgard_block *)_block;
3038          progress |= midgard_opt_copy_prop(ctx, block);
3039          progress |= midgard_opt_combine_projection(ctx, block);
3040          progress |= midgard_opt_varying_projection(ctx, block);
3041       }
3042    } while (progress);
3043 
3044    mir_foreach_block(ctx, _block) {
3045       midgard_block *block = (midgard_block *)_block;
3046       midgard_lower_derivatives(ctx, block);
3047       midgard_legalize_invert(ctx, block);
3048       midgard_cull_dead_branch(ctx, block);
3049    }
3050 
3051    if (ctx->stage == MESA_SHADER_FRAGMENT)
3052       mir_add_writeout_loops(ctx);
3053 
3054    /* Analyze now that the code is known but before scheduling creates
3055     * pipeline registers which are harder to track */
3056    mir_analyze_helper_requirements(ctx);
3057 
3058    if (midgard_debug & MIDGARD_DBG_SHADERS && !skip_internal)
3059       mir_print_shader(ctx);
3060 
3061    /* Schedule! */
3062    midgard_schedule_program(ctx);
3063    mir_ra(ctx);
3064 
3065    if (midgard_debug & MIDGARD_DBG_SHADERS && !skip_internal)
3066       mir_print_shader(ctx);
3067 
3068    /* Analyze after scheduling since this is order-dependent */
3069    mir_analyze_helper_terminate(ctx);
3070 
3071    /* Emit flat binary from the instruction arrays. Iterate each block in
3072     * sequence. Save instruction boundaries such that lookahead tags can
3073     * be assigned easily */
3074 
3075    /* Cache _all_ bundles in source order for lookahead across failed branches */
3076 
3077    int bundle_count = 0;
3078    mir_foreach_block(ctx, _block) {
3079       midgard_block *block = (midgard_block *)_block;
3080       bundle_count += block->bundles.size / sizeof(midgard_bundle);
3081    }
3082    midgard_bundle **source_order_bundles =
3083       malloc(sizeof(midgard_bundle *) * bundle_count);
3084    int bundle_idx = 0;
3085    mir_foreach_block(ctx, _block) {
3086       midgard_block *block = (midgard_block *)_block;
3087       util_dynarray_foreach(&block->bundles, midgard_bundle, bundle) {
3088          source_order_bundles[bundle_idx++] = bundle;
3089       }
3090    }
3091 
3092    int current_bundle = 0;
3093 
3094    /* Midgard prefetches instruction types, so during emission we
3095     * need to lookahead. Unless this is the last instruction, in
3096     * which we return 1. */
3097 
3098    mir_foreach_block(ctx, _block) {
3099       midgard_block *block = (midgard_block *)_block;
3100       mir_foreach_bundle_in_block(block, bundle) {
3101          int lookahead = 1;
3102 
3103          if (!bundle->last_writeout && (current_bundle + 1 < bundle_count))
3104             lookahead = source_order_bundles[current_bundle + 1]->tag;
3105 
3106          emit_binary_bundle(ctx, block, bundle, binary, lookahead);
3107          ++current_bundle;
3108       }
3109 
3110       /* TODO: Free deeper */
3111       // util_dynarray_fini(&block->instructions);
3112    }
3113 
3114    free(source_order_bundles);
3115 
3116    /* Report the very first tag executed */
3117    info->midgard.first_tag = midgard_get_first_tag_from_block(ctx, 0);
3118 
3119    info->ubo_mask = ctx->ubo_mask & ((1 << ctx->nir->info.num_ubos) - 1);
3120 
3121    if (midgard_debug & MIDGARD_DBG_SHADERS && !skip_internal) {
3122       disassemble_midgard(stdout, binary->data, binary->size, inputs->gpu_id,
3123                           midgard_debug & MIDGARD_DBG_VERBOSE);
3124       fflush(stdout);
3125    }
3126 
3127    /* A shader ending on a 16MB boundary causes INSTR_INVALID_PC faults,
3128     * workaround by adding some padding to the end of the shader. (The
3129     * kernel makes sure shader BOs can't cross 16MB boundaries.) */
3130    if (binary->size)
3131       memset(util_dynarray_grow(binary, uint8_t, 16), 0, 16);
3132 
3133    if ((midgard_debug & MIDGARD_DBG_SHADERDB || inputs->debug) &&
3134        !nir->info.internal) {
3135       unsigned nr_bundles = 0, nr_ins = 0;
3136 
3137       /* Count instructions and bundles */
3138 
3139       mir_foreach_block(ctx, _block) {
3140          midgard_block *block = (midgard_block *)_block;
3141          nr_bundles +=
3142             util_dynarray_num_elements(&block->bundles, midgard_bundle);
3143 
3144          mir_foreach_bundle_in_block(block, bun)
3145             nr_ins += bun->instruction_count;
3146       }
3147 
3148       /* Calculate thread count. There are certain cutoffs by
3149        * register count for thread count */
3150 
3151       unsigned nr_registers = info->work_reg_count;
3152 
3153       unsigned nr_threads = (nr_registers <= 4)   ? 4
3154                             : (nr_registers <= 8) ? 2
3155                                                   : 1;
3156 
3157       char *shaderdb = NULL;
3158 
3159       /* Dump stats */
3160 
3161       asprintf(&shaderdb,
3162                "%s shader: "
3163                "%u inst, %u bundles, %u quadwords, "
3164                "%u registers, %u threads, %u loops, "
3165                "%u:%u spills:fills",
3166                ctx->inputs->is_blend ? "PAN_SHADER_BLEND"
3167                                      : gl_shader_stage_name(ctx->stage),
3168                nr_ins, nr_bundles, ctx->quadword_count, nr_registers,
3169                nr_threads, ctx->loop_count, ctx->spills, ctx->fills);
3170 
3171       if (midgard_debug & MIDGARD_DBG_SHADERDB)
3172          fprintf(stderr, "SHADER-DB: %s\n", shaderdb);
3173 
3174       if (inputs->debug)
3175          util_debug_message(inputs->debug, SHADER_INFO, "%s", shaderdb);
3176 
3177       free(shaderdb);
3178    }
3179 
3180    _mesa_hash_table_u64_destroy(ctx->ssa_constants);
3181    ralloc_free(ctx);
3182 }
3183