xref: /aosp_15_r20/external/mesa3d/src/freedreno/ir3/ir3_shader.c (revision 6104692788411f58d303aa86923a9ff6ecaded22)
1 /*
2  * Copyright © 2014 Rob Clark <[email protected]>
3  * SPDX-License-Identifier: MIT
4  *
5  * Authors:
6  *    Rob Clark <[email protected]>
7  */
8 
9 #include "util/format/u_format.h"
10 #include "util/u_atomic.h"
11 #include "util/u_math.h"
12 #include "util/u_memory.h"
13 #include "util/u_string.h"
14 
15 #include "drm/freedreno_drmif.h"
16 
17 #include "ir3_assembler.h"
18 #include "ir3_compiler.h"
19 #include "ir3_nir.h"
20 #include "ir3_parser.h"
21 #include "ir3_shader.h"
22 
23 #include "freedreno/isa/ir3-isa.h"
24 #include "isa/isa.h"
25 
26 #include "disasm.h"
27 
28 static uint16_t
const_imm_index_to_reg(const struct ir3_const_state * const_state,unsigned i)29 const_imm_index_to_reg(const struct ir3_const_state *const_state, unsigned i)
30 {
31    return i + (4 * const_state->offsets.immediate);
32 }
33 
34 uint16_t
ir3_const_find_imm(struct ir3_shader_variant * v,uint32_t imm)35 ir3_const_find_imm(struct ir3_shader_variant *v, uint32_t imm)
36 {
37    const struct ir3_const_state *const_state = ir3_const_state(v);
38 
39    for (unsigned i = 0; i < const_state->immediates_count; i++) {
40       if (const_state->immediates[i] == imm)
41          return const_imm_index_to_reg(const_state, i);
42    }
43 
44    return INVALID_CONST_REG;
45 }
46 
47 uint16_t
ir3_const_add_imm(struct ir3_shader_variant * v,uint32_t imm)48 ir3_const_add_imm(struct ir3_shader_variant *v, uint32_t imm)
49 {
50    struct ir3_const_state *const_state = ir3_const_state_mut(v);
51 
52    /* Reallocate for 4 more elements whenever it's necessary.  Note that ir3
53     * printing relies on having groups of 4 dwords, so we fill the unused
54     * slots with a dummy value.
55     */
56    if (const_state->immediates_count == const_state->immediates_size) {
57       const_state->immediates = rerzalloc(
58          const_state, const_state->immediates,
59          __typeof__(const_state->immediates[0]), const_state->immediates_size,
60          const_state->immediates_size + 4);
61       const_state->immediates_size += 4;
62 
63       for (int i = const_state->immediates_count;
64            i < const_state->immediates_size; i++) {
65          const_state->immediates[i] = 0xd0d0d0d0;
66       }
67    }
68 
69    /* Add on a new immediate to be pushed, if we have space left in the
70     * constbuf.
71     */
72    if (const_state->offsets.immediate + const_state->immediates_count / 4 >=
73        ir3_max_const(v)) {
74       return INVALID_CONST_REG;
75    }
76 
77    const_state->immediates[const_state->immediates_count] = imm;
78    return const_imm_index_to_reg(const_state, const_state->immediates_count++);
79 }
80 
81 int
ir3_glsl_type_size(const struct glsl_type * type,bool bindless)82 ir3_glsl_type_size(const struct glsl_type *type, bool bindless)
83 {
84    return glsl_count_attribute_slots(type, false);
85 }
86 
87 /* wrapper for ir3_assemble() which does some info fixup based on
88  * shader state.  Non-static since used by ir3_cmdline too.
89  */
90 void *
ir3_shader_assemble(struct ir3_shader_variant * v)91 ir3_shader_assemble(struct ir3_shader_variant *v)
92 {
93    const struct ir3_compiler *compiler = v->compiler;
94    struct ir3_info *info = &v->info;
95    uint32_t *bin;
96 
97    ir3_collect_info(v);
98 
99    if (v->constant_data_size) {
100       /* Make sure that where we're about to place the constant_data is safe
101        * to indirectly upload from.
102        */
103       info->constant_data_offset =
104          align(info->size, v->compiler->const_upload_unit * 16);
105       info->size = info->constant_data_offset + v->constant_data_size;
106    }
107 
108    /* Pad out the size so that when turnip uploads the shaders in
109     * sequence, the starting offset of the next one is properly aligned.
110     */
111    info->size = align(info->size, compiler->instr_align * sizeof(uint64_t));
112 
113    bin = isa_assemble(v);
114    if (!bin)
115       return NULL;
116 
117    /* Append the immediates after the end of the program.  This lets us emit
118     * the immediates as an indirect load, while avoiding creating another BO.
119     */
120    if (v->constant_data_size)
121       memcpy(&bin[info->constant_data_offset / 4], v->constant_data,
122              v->constant_data_size);
123    ralloc_free(v->constant_data);
124    v->constant_data = NULL;
125 
126    /* NOTE: if relative addressing is used, we set constlen in
127     * the compiler (to worst-case value) since we don't know in
128     * the assembler what the max addr reg value can be:
129     */
130    v->constlen = MAX2(v->constlen, info->max_const + 1);
131 
132    if (v->constlen > ir3_const_state(v)->offsets.driver_param)
133       v->need_driver_params = true;
134 
135    /* On a4xx and newer, constlen must be a multiple of 16 dwords even though
136     * uploads are in units of 4 dwords. Round it up here to make calculations
137     * regarding the shared constlen simpler.
138     */
139    if (compiler->gen >= 4)
140       v->constlen = align(v->constlen, 4);
141 
142    /* Use the per-wave layout by default on a6xx for compute shaders. It
143     * should result in better performance when loads/stores are to a uniform
144     * index.
145     */
146    v->pvtmem_per_wave = compiler->gen >= 6 && !info->multi_dword_ldp_stp &&
147                         ((v->type == MESA_SHADER_COMPUTE) ||
148                          (v->type == MESA_SHADER_KERNEL));
149 
150    return bin;
151 }
152 
153 static bool
try_override_shader_variant(struct ir3_shader_variant * v,const char * identifier)154 try_override_shader_variant(struct ir3_shader_variant *v,
155                             const char *identifier)
156 {
157    assert(ir3_shader_override_path);
158 
159    char *name =
160       ralloc_asprintf(NULL, "%s/%s.asm", ir3_shader_override_path, identifier);
161 
162    FILE *f = fopen(name, "r");
163 
164    if (!f) {
165       ralloc_free(name);
166       return false;
167    }
168 
169    struct ir3_kernel_info info;
170    info.numwg = INVALID_REG;
171    v->ir = ir3_parse(v, &info, f);
172 
173    fclose(f);
174 
175    if (!v->ir) {
176       fprintf(stderr, "Failed to parse %s\n", name);
177       exit(1);
178    }
179 
180    v->bin = ir3_shader_assemble(v);
181    if (!v->bin) {
182       fprintf(stderr, "Failed to assemble %s\n", name);
183       exit(1);
184    }
185 
186    ralloc_free(name);
187    return true;
188 }
189 
190 static void
assemble_variant(struct ir3_shader_variant * v,bool internal)191 assemble_variant(struct ir3_shader_variant *v, bool internal)
192 {
193    v->bin = ir3_shader_assemble(v);
194 
195    bool dbg_enabled = shader_debug_enabled(v->type, internal);
196    if (dbg_enabled || ir3_shader_override_path || v->disasm_info.write_disasm) {
197       unsigned char sha1[21];
198       char sha1buf[41];
199 
200       _mesa_sha1_compute(v->bin, v->info.size, sha1);
201       _mesa_sha1_format(sha1buf, sha1);
202 
203       bool shader_overridden =
204          ir3_shader_override_path && try_override_shader_variant(v, sha1buf);
205 
206       if (v->disasm_info.write_disasm) {
207          char *stream_data = NULL;
208          size_t stream_size = 0;
209          FILE *stream = open_memstream(&stream_data, &stream_size);
210 
211          fprintf(stream,
212                  "Native code%s for unnamed %s shader %s with sha1 %s:\n",
213                  shader_overridden ? " (overridden)" : "", ir3_shader_stage(v),
214                  v->name, sha1buf);
215          ir3_shader_disasm(v, v->bin, stream);
216 
217          fclose(stream);
218 
219          v->disasm_info.disasm = ralloc_size(v, stream_size + 1);
220          memcpy(v->disasm_info.disasm, stream_data, stream_size);
221          v->disasm_info.disasm[stream_size] = 0;
222          free(stream_data);
223       }
224 
225       if (dbg_enabled || shader_overridden) {
226          char *stream_data = NULL;
227          size_t stream_size = 0;
228          FILE *stream = open_memstream(&stream_data, &stream_size);
229 
230          fprintf(stream,
231                  "Native code%s for unnamed %s shader %s with sha1 %s:\n",
232                  shader_overridden ? " (overridden)" : "", ir3_shader_stage(v),
233                  v->name, sha1buf);
234          if (v->type == MESA_SHADER_FRAGMENT)
235             fprintf(stream, "SIMD0\n");
236          ir3_shader_disasm(v, v->bin, stream);
237          fclose(stream);
238 
239          mesa_log_multiline(MESA_LOG_INFO, stream_data);
240          free(stream_data);
241       }
242    }
243 
244    /* no need to keep the ir around beyond this point: */
245    ir3_destroy(v->ir);
246    v->ir = NULL;
247 }
248 
249 static bool
compile_variant(struct ir3_shader * shader,struct ir3_shader_variant * v)250 compile_variant(struct ir3_shader *shader, struct ir3_shader_variant *v)
251 {
252    int ret = ir3_compile_shader_nir(shader->compiler, shader, v);
253    if (ret) {
254       mesa_loge("compile failed! (%s:%s)", shader->nir->info.name,
255                 shader->nir->info.label);
256       return false;
257    }
258 
259    assemble_variant(v, shader->nir->info.internal);
260    if (!v->bin) {
261       mesa_loge("assemble failed! (%s:%s)", shader->nir->info.name,
262                 shader->nir->info.label);
263       return false;
264    }
265 
266    return true;
267 }
268 
269 /*
270  * For creating normal shader variants, 'nonbinning' is NULL.  For
271  * creating binning pass shader, it is link to corresponding normal
272  * (non-binning) variant.
273  */
274 static struct ir3_shader_variant *
alloc_variant(struct ir3_shader * shader,const struct ir3_shader_key * key,struct ir3_shader_variant * nonbinning,void * mem_ctx)275 alloc_variant(struct ir3_shader *shader, const struct ir3_shader_key *key,
276               struct ir3_shader_variant *nonbinning, void *mem_ctx)
277 {
278    /* hang the binning variant off it's non-binning counterpart instead
279     * of the shader, to simplify the error cleanup paths
280     */
281    if (nonbinning)
282       mem_ctx = nonbinning;
283    struct ir3_shader_variant *v = rzalloc_size(mem_ctx, sizeof(*v));
284 
285    if (!v)
286       return NULL;
287 
288    v->id = ++shader->variant_count;
289    v->shader_id = shader->id;
290    v->binning_pass = !!nonbinning;
291    v->nonbinning = nonbinning;
292    v->key = *key;
293    v->type = shader->type;
294    v->compiler = shader->compiler;
295    v->mergedregs = shader->compiler->gen >= 6;
296    v->stream_output = shader->stream_output;
297 
298    v->name = ralloc_strdup(v, shader->nir->info.name);
299 
300    struct shader_info *info = &shader->nir->info;
301    switch (v->type) {
302    case MESA_SHADER_TESS_CTRL:
303    case MESA_SHADER_TESS_EVAL:
304       v->tess.primitive_mode = info->tess._primitive_mode;
305       v->tess.tcs_vertices_out = info->tess.tcs_vertices_out;
306       v->tess.spacing = info->tess.spacing;
307       v->tess.ccw = info->tess.ccw;
308       v->tess.point_mode = info->tess.point_mode;
309       break;
310 
311    case MESA_SHADER_GEOMETRY:
312       v->gs.output_primitive = info->gs.output_primitive;
313       v->gs.vertices_out = info->gs.vertices_out;
314       v->gs.invocations = info->gs.invocations;
315       v->gs.vertices_in = info->gs.vertices_in;
316       break;
317 
318    case MESA_SHADER_FRAGMENT:
319       v->fs.early_fragment_tests = info->fs.early_fragment_tests;
320       v->fs.color_is_dual_source = info->fs.color_is_dual_source;
321       v->fs.uses_fbfetch_output  = info->fs.uses_fbfetch_output;
322       v->fs.fbfetch_coherent     = info->fs.fbfetch_coherent;
323       break;
324 
325    case MESA_SHADER_COMPUTE:
326    case MESA_SHADER_KERNEL:
327       v->cs.req_input_mem = shader->cs.req_input_mem;
328       v->cs.req_local_mem = shader->cs.req_local_mem;
329       break;
330 
331    default:
332       break;
333    }
334 
335    v->num_ssbos = info->num_ssbos;
336    v->num_ibos = info->num_ssbos + info->num_images;
337    v->shader_options = shader->options;
338 
339    if (!v->binning_pass) {
340       v->const_state = rzalloc_size(v, sizeof(*v->const_state));
341       v->const_state->push_consts_type = shader->options.push_consts_type;
342       v->const_state->consts_ubo.idx = -1;
343       v->const_state->driver_params_ubo.idx = -1;
344       v->const_state->primitive_map_ubo.idx = -1;
345       v->const_state->primitive_param_ubo.idx = -1;
346    }
347 
348    return v;
349 }
350 
351 static bool
needs_binning_variant(struct ir3_shader_variant * v)352 needs_binning_variant(struct ir3_shader_variant *v)
353 {
354    if ((v->type == MESA_SHADER_VERTEX) && ir3_has_binning_vs(&v->key))
355       return true;
356    return false;
357 }
358 
359 static struct ir3_shader_variant *
create_variant(struct ir3_shader * shader,const struct ir3_shader_key * key,bool write_disasm,void * mem_ctx)360 create_variant(struct ir3_shader *shader, const struct ir3_shader_key *key,
361                bool write_disasm, void *mem_ctx)
362 {
363    struct ir3_shader_variant *v = alloc_variant(shader, key, NULL, mem_ctx);
364 
365    if (!v)
366       goto fail;
367 
368    v->disasm_info.write_disasm = write_disasm;
369 
370    if (needs_binning_variant(v)) {
371       v->binning = alloc_variant(shader, key, v, mem_ctx);
372       if (!v->binning)
373          goto fail;
374       v->binning->disasm_info.write_disasm = write_disasm;
375    }
376 
377    if (ir3_disk_cache_retrieve(shader, v))
378       return v;
379 
380    if (!shader->nir_finalized) {
381       ir3_nir_post_finalize(shader);
382 
383       if (ir3_shader_debug & IR3_DBG_DISASM) {
384          mesa_logi("dump nir%d: type=%d", shader->id, shader->type);
385          nir_log_shaderi(shader->nir);
386       }
387 
388       if (v->disasm_info.write_disasm) {
389          v->disasm_info.nir = nir_shader_as_str(shader->nir, v);
390       }
391 
392       shader->nir_finalized = true;
393    }
394 
395    if (v->type == MESA_SHADER_COMPUTE ||
396        v->type == MESA_SHADER_KERNEL) {
397       v->cs.force_linear_dispatch = shader->cs.force_linear_dispatch;
398    }
399 
400    if (!compile_variant(shader, v))
401       goto fail;
402 
403    if (needs_binning_variant(v) && !compile_variant(shader, v->binning))
404       goto fail;
405 
406    ir3_disk_cache_store(shader, v);
407 
408    return v;
409 
410 fail:
411    ralloc_free(v);
412    return NULL;
413 }
414 
415 struct ir3_shader_variant *
ir3_shader_create_variant(struct ir3_shader * shader,const struct ir3_shader_key * key,bool keep_ir)416 ir3_shader_create_variant(struct ir3_shader *shader,
417                           const struct ir3_shader_key *key,
418                           bool keep_ir)
419 {
420    return create_variant(shader, key, keep_ir, NULL);
421 }
422 
423 static inline struct ir3_shader_variant *
shader_variant(struct ir3_shader * shader,const struct ir3_shader_key * key)424 shader_variant(struct ir3_shader *shader, const struct ir3_shader_key *key)
425 {
426    struct ir3_shader_variant *v;
427 
428    for (v = shader->variants; v; v = v->next)
429       if (ir3_shader_key_equal(key, &v->key))
430          return v;
431 
432    return NULL;
433 }
434 
435 struct ir3_shader_variant *
ir3_shader_get_variant(struct ir3_shader * shader,const struct ir3_shader_key * key,bool binning_pass,bool write_disasm,bool * created)436 ir3_shader_get_variant(struct ir3_shader *shader,
437                        const struct ir3_shader_key *key, bool binning_pass,
438                        bool write_disasm, bool *created)
439 {
440    MESA_TRACE_FUNC();
441 
442    mtx_lock(&shader->variants_lock);
443    struct ir3_shader_variant *v = shader_variant(shader, key);
444 
445    if (!v) {
446       /* compile new variant if it doesn't exist already: */
447       v = create_variant(shader, key, write_disasm, shader);
448       if (v) {
449          v->next = shader->variants;
450          shader->variants = v;
451          *created = true;
452       }
453    }
454 
455    if (v && binning_pass) {
456       v = v->binning;
457       assert(v);
458    }
459 
460    mtx_unlock(&shader->variants_lock);
461 
462    return v;
463 }
464 
465 struct ir3_shader *
ir3_shader_passthrough_tcs(struct ir3_shader * vs,unsigned patch_vertices)466 ir3_shader_passthrough_tcs(struct ir3_shader *vs, unsigned patch_vertices)
467 {
468    assert(vs->type == MESA_SHADER_VERTEX);
469    assert(patch_vertices > 0);
470    assert(patch_vertices <= 32);
471 
472    unsigned n = patch_vertices - 1;
473    if (!vs->vs.passthrough_tcs[n]) {
474       const nir_shader_compiler_options *options =
475             ir3_get_compiler_options(vs->compiler);
476       nir_shader *tcs =
477             nir_create_passthrough_tcs(options, vs->nir, patch_vertices);
478 
479       /* Technically it is an internal shader but it is confusing to
480        * not have it show up in debug output
481        */
482       tcs->info.internal = false;
483 
484       nir_assign_io_var_locations(tcs, nir_var_shader_in,
485                                   &tcs->num_inputs,
486                                   tcs->info.stage);
487 
488       nir_assign_io_var_locations(tcs, nir_var_shader_out,
489                                   &tcs->num_outputs,
490                                   tcs->info.stage);
491 
492       NIR_PASS_V(tcs, nir_lower_system_values);
493 
494       nir_shader_gather_info(tcs, nir_shader_get_entrypoint(tcs));
495 
496       ir3_finalize_nir(vs->compiler, tcs);
497 
498       struct ir3_shader_options ir3_options = {};
499 
500       vs->vs.passthrough_tcs[n] =
501             ir3_shader_from_nir(vs->compiler, tcs, &ir3_options, NULL);
502 
503       vs->vs.passthrough_tcs_compiled |= BITFIELD_BIT(n);
504    }
505 
506    return vs->vs.passthrough_tcs[n];
507 }
508 
509 void
ir3_shader_destroy(struct ir3_shader * shader)510 ir3_shader_destroy(struct ir3_shader *shader)
511 {
512    if (shader->type == MESA_SHADER_VERTEX) {
513       u_foreach_bit (b, shader->vs.passthrough_tcs_compiled) {
514          ir3_shader_destroy(shader->vs.passthrough_tcs[b]);
515       }
516    }
517    ralloc_free(shader->nir);
518    mtx_destroy(&shader->variants_lock);
519    ralloc_free(shader);
520 }
521 
522 /**
523  * Creates a bitmask of the used bits of the shader key by this particular
524  * shader.  Used by the gallium driver to skip state-dependent recompiles when
525  * possible.
526  */
527 static void
ir3_setup_used_key(struct ir3_shader * shader)528 ir3_setup_used_key(struct ir3_shader *shader)
529 {
530    nir_shader *nir = shader->nir;
531    struct shader_info *info = &nir->info;
532    struct ir3_shader_key *key = &shader->key_mask;
533 
534    /* This key flag is just used to make for a cheaper ir3_shader_key_equal
535     * check in the common case.
536     */
537    key->has_per_samp = true;
538 
539    key->safe_constlen = true;
540 
541    /* When clip/cull distances are natively supported, we only use
542     * ucp_enables to determine whether to lower legacy clip planes to
543     * gl_ClipDistance.
544     */
545    if (info->stage != MESA_SHADER_COMPUTE && (info->stage != MESA_SHADER_FRAGMENT || !shader->compiler->has_clip_cull))
546       key->ucp_enables = 0xff;
547 
548    if (info->stage == MESA_SHADER_FRAGMENT) {
549       key->fastc_srgb = ~0;
550       key->fsamples = ~0;
551       memset(key->fsampler_swizzles, 0xff, sizeof(key->fsampler_swizzles));
552 
553       if (info->inputs_read & VARYING_BITS_COLOR) {
554          key->rasterflat = true;
555       }
556 
557       /* Only used for deciding on behavior of
558        * nir_intrinsic_load_barycentric_sample and the centroid demotion
559        * on older HW.
560        */
561       key->msaa = shader->compiler->gen < 6 &&
562                   (info->fs.uses_sample_qualifier ||
563                    (BITSET_TEST(info->system_values_read,
564                                 SYSTEM_VALUE_BARYCENTRIC_PERSP_CENTROID) ||
565                     BITSET_TEST(info->system_values_read,
566                                 SYSTEM_VALUE_BARYCENTRIC_LINEAR_CENTROID)));
567 
568       /* Only enable this shader key bit if "dual_color_blend_by_location" is
569        * enabled:
570        */
571       key->force_dual_color_blend = shader->compiler->options.dual_color_blend_by_location;
572    } else if (info->stage == MESA_SHADER_COMPUTE) {
573       key->fastc_srgb = ~0;
574       key->fsamples = ~0;
575       memset(key->fsampler_swizzles, 0xff, sizeof(key->fsampler_swizzles));
576    } else {
577       key->tessellation = ~0;
578       key->has_gs = true;
579 
580       if (info->stage == MESA_SHADER_VERTEX) {
581          key->vastc_srgb = ~0;
582          key->vsamples = ~0;
583          memset(key->vsampler_swizzles, 0xff, sizeof(key->vsampler_swizzles));
584       }
585 
586       if (info->stage == MESA_SHADER_TESS_CTRL)
587          key->tcs_store_primid = true;
588    }
589 }
590 
591 /* Given an array of constlen's, decrease some of them so that the sum stays
592  * within "combined_limit" while trying to fairly share the reduction. Returns
593  * a bitfield of which stages should be trimmed.
594  */
595 static uint32_t
trim_constlens(unsigned * constlens,unsigned first_stage,unsigned last_stage,unsigned combined_limit,unsigned safe_limit)596 trim_constlens(unsigned *constlens, unsigned first_stage, unsigned last_stage,
597                unsigned combined_limit, unsigned safe_limit)
598 {
599    unsigned cur_total = 0;
600    for (unsigned i = first_stage; i <= last_stage; i++) {
601       cur_total += constlens[i];
602    }
603 
604    unsigned max_stage = 0;
605    unsigned max_const = 0;
606    uint32_t trimmed = 0;
607 
608    while (cur_total > combined_limit) {
609       for (unsigned i = first_stage; i <= last_stage; i++) {
610          if (constlens[i] >= max_const) {
611             max_stage = i;
612             max_const = constlens[i];
613          }
614       }
615 
616       assert(max_const > safe_limit);
617       trimmed |= 1 << max_stage;
618       cur_total = cur_total - max_const + safe_limit;
619       constlens[max_stage] = safe_limit;
620    }
621 
622    return trimmed;
623 }
624 
625 /* Figures out which stages in the pipeline to use the "safe" constlen for, in
626  * order to satisfy all shared constlen limits.
627  */
628 uint32_t
ir3_trim_constlen(const struct ir3_shader_variant ** variants,const struct ir3_compiler * compiler)629 ir3_trim_constlen(const struct ir3_shader_variant **variants,
630                   const struct ir3_compiler *compiler)
631 {
632    unsigned constlens[MESA_SHADER_STAGES] = {};
633 
634    bool shared_consts_enable = false;
635 
636    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
637       if (variants[i]) {
638          constlens[i] = variants[i]->constlen;
639          shared_consts_enable =
640             ir3_const_state(variants[i])->push_consts_type == IR3_PUSH_CONSTS_SHARED;
641       }
642    }
643 
644    uint32_t trimmed = 0;
645    STATIC_ASSERT(MESA_SHADER_STAGES <= 8 * sizeof(trimmed));
646 
647    /* Use a hw quirk for geometry shared consts, not matched with actual
648     * shared consts size (on a6xx).
649     */
650    uint32_t shared_consts_size_geom = shared_consts_enable ?
651       compiler->geom_shared_consts_size_quirk : 0;
652 
653    uint32_t shared_consts_size = shared_consts_enable ?
654       compiler->shared_consts_size : 0;
655 
656    uint32_t safe_shared_consts_size = shared_consts_enable  ?
657       ALIGN_POT(MAX2(DIV_ROUND_UP(shared_consts_size_geom, 4),
658                      DIV_ROUND_UP(shared_consts_size, 5)), 4) : 0;
659 
660    /* There are two shared limits to take into account, the geometry limit on
661     * a6xx and the total limit. The frag limit on a6xx only matters for a
662     * single stage, so it's always satisfied with the first variant.
663     */
664    if (compiler->gen >= 6) {
665       trimmed |=
666          trim_constlens(constlens, MESA_SHADER_VERTEX, MESA_SHADER_GEOMETRY,
667                         compiler->max_const_geom - shared_consts_size_geom,
668                         compiler->max_const_safe - safe_shared_consts_size);
669    }
670    trimmed |=
671       trim_constlens(constlens, MESA_SHADER_VERTEX, MESA_SHADER_FRAGMENT,
672                      compiler->max_const_pipeline - shared_consts_size,
673                      compiler->max_const_safe - safe_shared_consts_size);
674 
675    return trimmed;
676 }
677 
678 struct ir3_shader *
ir3_shader_from_nir(struct ir3_compiler * compiler,nir_shader * nir,const struct ir3_shader_options * options,struct ir3_stream_output_info * stream_output)679 ir3_shader_from_nir(struct ir3_compiler *compiler, nir_shader *nir,
680                     const struct ir3_shader_options *options,
681                     struct ir3_stream_output_info *stream_output)
682 {
683    struct ir3_shader *shader = rzalloc_size(NULL, sizeof(*shader));
684 
685    mtx_init(&shader->variants_lock, mtx_plain);
686    shader->compiler = compiler;
687    shader->id = p_atomic_inc_return(&shader->compiler->shader_count);
688    shader->type = nir->info.stage;
689    if (stream_output)
690       memcpy(&shader->stream_output, stream_output,
691              sizeof(shader->stream_output));
692    shader->options = *options;
693    shader->nir = nir;
694 
695    ir3_disk_cache_init_shader_key(compiler, shader);
696 
697    ir3_setup_used_key(shader);
698 
699    return shader;
700 }
701 
702 static void
dump_reg(FILE * out,const char * name,uint32_t r)703 dump_reg(FILE *out, const char *name, uint32_t r)
704 {
705    if (r != regid(63, 0)) {
706       const char *reg_type = (r & HALF_REG_ID) ? "hr" : "r";
707       fprintf(out, "; %s: %s%d.%c\n", name, reg_type, (r & ~HALF_REG_ID) >> 2,
708               "xyzw"[r & 0x3]);
709    }
710 }
711 
712 static void
dump_output(FILE * out,struct ir3_shader_variant * so,unsigned slot,const char * name)713 dump_output(FILE *out, struct ir3_shader_variant *so, unsigned slot,
714             const char *name)
715 {
716    uint32_t regid;
717    regid = ir3_find_output_regid(so, slot);
718    dump_reg(out, name, regid);
719 }
720 
721 static const char *
input_name(struct ir3_shader_variant * so,int i)722 input_name(struct ir3_shader_variant *so, int i)
723 {
724    if (so->inputs[i].sysval) {
725       return gl_system_value_name(so->inputs[i].slot);
726    } else if (so->type == MESA_SHADER_VERTEX) {
727       return gl_vert_attrib_name(so->inputs[i].slot);
728    } else {
729       return gl_varying_slot_name_for_stage(so->inputs[i].slot, so->type);
730    }
731 }
732 
733 static const char *
output_name(struct ir3_shader_variant * so,int i)734 output_name(struct ir3_shader_variant *so, int i)
735 {
736    if (so->type == MESA_SHADER_FRAGMENT) {
737       return gl_frag_result_name(so->outputs[i].slot);
738    } else {
739       switch (so->outputs[i].slot) {
740       case VARYING_SLOT_GS_HEADER_IR3:
741          return "GS_HEADER";
742       case VARYING_SLOT_GS_VERTEX_FLAGS_IR3:
743          return "GS_VERTEX_FLAGS";
744       case VARYING_SLOT_TCS_HEADER_IR3:
745          return "TCS_HEADER";
746       default:
747          return gl_varying_slot_name_for_stage(so->outputs[i].slot, so->type);
748       }
749    }
750 }
751 
752 static void
dump_const_state(struct ir3_shader_variant * so,FILE * out)753 dump_const_state(struct ir3_shader_variant *so, FILE *out)
754 {
755    const struct ir3_const_state *cs = ir3_const_state(so);
756    const struct ir3_ubo_analysis_state *us = &cs->ubo_state;
757 
758    fprintf(out, "; num_ubos:           %u\n", cs->num_ubos);
759    fprintf(out, "; num_driver_params:  %u\n", cs->num_driver_params);
760    fprintf(out, "; offsets:\n");
761    if (cs->offsets.ubo != ~0)
762       fprintf(out, ";   ubo:              c%u.x\n", cs->offsets.ubo);
763    if (cs->offsets.image_dims != ~0)
764       fprintf(out, ";   image_dims:       c%u.x\n", cs->offsets.image_dims);
765    if (cs->offsets.kernel_params != ~0)
766       fprintf(out, ";   kernel_params:    c%u.x\n", cs->offsets.kernel_params);
767    if (cs->offsets.driver_param != ~0)
768       fprintf(out, ";   driver_param:     c%u.x\n", cs->offsets.driver_param);
769    if (cs->offsets.tfbo != ~0)
770       fprintf(out, ";   tfbo:             c%u.x\n", cs->offsets.tfbo);
771    if (cs->offsets.primitive_param != ~0)
772       fprintf(out, ";   primitive_params: c%u.x\n", cs->offsets.primitive_param);
773    if (cs->offsets.primitive_map != ~0)
774       fprintf(out, ";   primitive_map:    c%u.x\n", cs->offsets.primitive_map);
775    fprintf(out, "; ubo_state:\n");
776    fprintf(out, ";   num_enabled:      %u\n", us->num_enabled);
777    for (unsigned i = 0; i < us->num_enabled; i++) {
778       const struct ir3_ubo_range *r = &us->range[i];
779 
780       assert((r->offset % 16) == 0);
781 
782       fprintf(out, ";   range[%u]:\n", i);
783       fprintf(out, ";     block:          %u\n", r->ubo.block);
784       if (r->ubo.bindless)
785          fprintf(out, ";     bindless_base:  %u\n", r->ubo.bindless_base);
786       fprintf(out, ";     offset:         c%u.x\n", r->offset/16);
787 
788       unsigned size = r->end - r->start;
789       assert((size % 16) == 0);
790 
791       fprintf(out, ";     size:           %u vec4 (%ub -> %ub)\n", (size/16), r->start, r->end);
792    }
793 }
794 
795 static uint8_t
find_input_reg_id(struct ir3_shader_variant * so,uint32_t input_idx)796 find_input_reg_id(struct ir3_shader_variant *so, uint32_t input_idx)
797 {
798    uint8_t reg = so->inputs[input_idx].regid;
799    if (so->type != MESA_SHADER_FRAGMENT || !so->ir || VALIDREG(reg))
800       return reg;
801 
802    reg = INVALID_REG;
803 
804    /* In FS we don't know into which register the input is loaded
805     * until the shader is scanned for the input load instructions.
806     */
807    foreach_block (block, &so->ir->block_list) {
808       foreach_instr_safe (instr, &block->instr_list) {
809          if (instr->opc == OPC_FLAT_B || instr->opc == OPC_BARY_F ||
810              instr->opc == OPC_LDLV) {
811             if (instr->srcs[0]->flags & IR3_REG_IMMED) {
812                unsigned inloc = so->inputs[input_idx].inloc;
813                unsigned instr_inloc = instr->srcs[0]->uim_val;
814                unsigned size = util_bitcount(so->inputs[input_idx].compmask);
815 
816                if (instr_inloc == inloc) {
817                   return instr->dsts[0]->num;
818                }
819 
820                if (instr_inloc > inloc && instr_inloc < (inloc + size)) {
821                   reg = MIN2(reg, instr->dsts[0]->num);
822                }
823 
824                if (instr->dsts[0]->flags & IR3_REG_EI) {
825                   return reg;
826                }
827             }
828          }
829       }
830    }
831 
832    return reg;
833 }
834 
835 void
print_raw(FILE * out,const BITSET_WORD * data,size_t size)836 print_raw(FILE *out, const BITSET_WORD *data, size_t size) {
837    fprintf(out, "raw 0x%X%X\n", data[0], data[1]);
838 }
839 
840 void
ir3_shader_disasm(struct ir3_shader_variant * so,uint32_t * bin,FILE * out)841 ir3_shader_disasm(struct ir3_shader_variant *so, uint32_t *bin, FILE *out)
842 {
843    struct ir3 *ir = so->ir;
844    struct ir3_register *reg;
845    const char *type = ir3_shader_stage(so);
846    uint8_t regid;
847    unsigned i;
848 
849    dump_const_state(so, out);
850 
851    foreach_input_n (instr, i, ir) {
852       reg = instr->dsts[0];
853       regid = reg->num;
854       fprintf(out, "@in(%sr%d.%c)\tin%d",
855               (reg->flags & IR3_REG_HALF) ? "h" : "", (regid >> 2),
856               "xyzw"[regid & 0x3], i);
857 
858       if (reg->wrmask > 0x1)
859          fprintf(out, " (wrmask=0x%x)", reg->wrmask);
860       fprintf(out, "\n");
861    }
862 
863    /* print pre-dispatch texture fetches: */
864    for (i = 0; i < so->num_sampler_prefetch; i++) {
865       const struct ir3_sampler_prefetch *fetch = &so->sampler_prefetch[i];
866       fprintf(out,
867               "@tex(%sr%d.%c)\tsrc=%u, bindless=%u, samp=%u, tex=%u, wrmask=0x%x, opc=%s\n",
868               fetch->half_precision ? "h" : "", fetch->dst >> 2,
869               "xyzw"[fetch->dst & 0x3], fetch->src, fetch->bindless,
870               fetch->bindless ? fetch->samp_bindless_id : fetch->samp_id,
871               fetch->bindless ? fetch->tex_bindless_id : fetch->tex_id,
872               fetch->wrmask, disasm_a3xx_instr_name(fetch->tex_opc));
873    }
874 
875    const struct ir3_const_state *const_state = ir3_const_state(so);
876    for (i = 0; i < DIV_ROUND_UP(const_state->immediates_count, 4); i++) {
877       fprintf(out, "@const(c%d.x)\t", const_state->offsets.immediate + i);
878       fprintf(out, "0x%08x, 0x%08x, 0x%08x, 0x%08x\n",
879               const_state->immediates[i * 4 + 0],
880               const_state->immediates[i * 4 + 1],
881               const_state->immediates[i * 4 + 2],
882               const_state->immediates[i * 4 + 3]);
883    }
884 
885    ir3_isa_disasm(bin, so->info.sizedwords * 4, out,
886                   &(struct isa_decode_options){
887                      .gpu_id = ir->compiler->gen * 100,
888                      .show_errors = true,
889                      .branch_labels = true,
890                      .no_match_cb = print_raw,
891                   });
892 
893    fprintf(out, "; %s: outputs:", type);
894    for (i = 0; i < so->outputs_count; i++) {
895       uint8_t regid = so->outputs[i].regid;
896       const char *reg_type = so->outputs[i].half ? "hr" : "r";
897       fprintf(out, " %s%d.%c (%s)", reg_type, (regid >> 2), "xyzw"[regid & 0x3],
898               output_name(so, i));
899    }
900    fprintf(out, "\n");
901 
902    fprintf(out, "; %s: inputs:", type);
903    for (i = 0; i < so->inputs_count; i++) {
904       uint8_t regid = find_input_reg_id(so, i);
905 
906       fprintf(out, " r%d.%c (%s slot=%d cm=%x,il=%u,b=%u)", (regid >> 2),
907               "xyzw"[regid & 0x3], input_name(so, i), so -> inputs[i].slot,
908               so->inputs[i].compmask, so->inputs[i].inloc, so->inputs[i].bary);
909    }
910    fprintf(out, "\n");
911 
912    /* print generic shader info: */
913    fprintf(
914       out,
915       "; %s prog %d/%d: %u instr, %u nops, %u non-nops, %u mov, %u cov, %u dwords\n",
916       type, so->shader_id, so->id, so->info.instrs_count, so->info.nops_count,
917       so->info.instrs_count - so->info.nops_count, so->info.mov_count,
918       so->info.cov_count, so->info.sizedwords);
919 
920    fprintf(out,
921            "; %s prog %d/%d: %u last-baryf, %u last-helper, %d half, %d full, %u constlen\n",
922            type, so->shader_id, so->id, so->info.last_baryf,
923            so->info.last_helper, so->info.max_half_reg + 1,
924            so->info.max_reg + 1, so->constlen);
925 
926    fprintf(
927       out,
928       "; %s prog %d/%d: %u cat0, %u cat1, %u cat2, %u cat3, %u cat4, %u cat5, %u cat6, %u cat7, \n",
929       type, so->shader_id, so->id, so->info.instrs_per_cat[0],
930       so->info.instrs_per_cat[1], so->info.instrs_per_cat[2],
931       so->info.instrs_per_cat[3], so->info.instrs_per_cat[4],
932       so->info.instrs_per_cat[5], so->info.instrs_per_cat[6],
933       so->info.instrs_per_cat[7]);
934 
935    fprintf(
936       out,
937       "; %s prog %d/%d: %u sstall, %u (ss), %u systall, %u (sy), %d loops\n",
938       type, so->shader_id, so->id, so->info.sstall, so->info.ss,
939       so->info.systall, so->info.sy, so->loops);
940 
941    /* print shader type specific info: */
942    switch (so->type) {
943    case MESA_SHADER_VERTEX:
944       dump_output(out, so, VARYING_SLOT_POS, "pos");
945       dump_output(out, so, VARYING_SLOT_PSIZ, "psize");
946       break;
947    case MESA_SHADER_FRAGMENT:
948       dump_reg(out, "pos (ij_pixel)",
949                ir3_find_sysval_regid(so, SYSTEM_VALUE_BARYCENTRIC_PERSP_PIXEL));
950       dump_reg(
951          out, "pos (ij_centroid)",
952          ir3_find_sysval_regid(so, SYSTEM_VALUE_BARYCENTRIC_PERSP_CENTROID));
953       dump_reg(out, "pos (center_rhw)",
954                ir3_find_sysval_regid(so, SYSTEM_VALUE_BARYCENTRIC_PERSP_CENTER_RHW));
955       dump_output(out, so, FRAG_RESULT_DEPTH, "posz");
956       if (so->color0_mrt) {
957          dump_output(out, so, FRAG_RESULT_COLOR, "color");
958       } else {
959          dump_output(out, so, FRAG_RESULT_DATA0, "data0");
960          dump_output(out, so, FRAG_RESULT_DATA1, "data1");
961          dump_output(out, so, FRAG_RESULT_DATA2, "data2");
962          dump_output(out, so, FRAG_RESULT_DATA3, "data3");
963          dump_output(out, so, FRAG_RESULT_DATA4, "data4");
964          dump_output(out, so, FRAG_RESULT_DATA5, "data5");
965          dump_output(out, so, FRAG_RESULT_DATA6, "data6");
966          dump_output(out, so, FRAG_RESULT_DATA7, "data7");
967       }
968       dump_reg(out, "fragcoord",
969                ir3_find_sysval_regid(so, SYSTEM_VALUE_FRAG_COORD));
970       dump_reg(out, "fragface",
971                ir3_find_sysval_regid(so, SYSTEM_VALUE_FRONT_FACE));
972       break;
973    default:
974       /* TODO */
975       break;
976    }
977 
978    fprintf(out, "\n");
979 }
980 
981 uint64_t
ir3_shader_outputs(const struct ir3_shader * so)982 ir3_shader_outputs(const struct ir3_shader *so)
983 {
984    return so->nir->info.outputs_written;
985 }
986 
987 /* Add any missing varyings needed for stream-out.  Otherwise varyings not
988  * used by fragment shader will be stripped out.
989  */
990 void
ir3_link_stream_out(struct ir3_shader_linkage * l,const struct ir3_shader_variant * v)991 ir3_link_stream_out(struct ir3_shader_linkage *l,
992                     const struct ir3_shader_variant *v)
993 {
994    const struct ir3_stream_output_info *strmout = &v->stream_output;
995 
996    /*
997     * First, any stream-out varyings not already in linkage map (ie. also
998     * consumed by frag shader) need to be added:
999     */
1000    for (unsigned i = 0; i < strmout->num_outputs; i++) {
1001       const struct ir3_stream_output *out = &strmout->output[i];
1002       unsigned k = out->register_index;
1003       unsigned compmask =
1004          (1 << (out->num_components + out->start_component)) - 1;
1005       unsigned idx, nextloc = 0;
1006 
1007       /* psize/pos need to be the last entries in linkage map, and will
1008        * get added link_stream_out, so skip over them:
1009        */
1010       if ((v->outputs[k].slot == VARYING_SLOT_PSIZ) ||
1011           (v->outputs[k].slot == VARYING_SLOT_POS))
1012          continue;
1013 
1014       for (idx = 0; idx < l->cnt; idx++) {
1015          if (l->var[idx].slot == v->outputs[k].slot)
1016             break;
1017          nextloc = MAX2(nextloc, l->var[idx].loc + 4);
1018       }
1019 
1020       /* add if not already in linkage map: */
1021       if (idx == l->cnt) {
1022          ir3_link_add(l, v->outputs[k].slot, v->outputs[k].regid,
1023                       compmask, nextloc);
1024       }
1025 
1026       /* expand component-mask if needed, ie streaming out all components
1027        * but frag shader doesn't consume all components:
1028        */
1029       if (compmask & ~l->var[idx].compmask) {
1030          l->var[idx].compmask |= compmask;
1031          l->max_loc = MAX2(
1032             l->max_loc, l->var[idx].loc + util_last_bit(l->var[idx].compmask));
1033       }
1034    }
1035 }
1036