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