• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2015 Red Hat
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 
24 #include "st_nir.h"
25 
26 #include "pipe/p_defines.h"
27 #include "pipe/p_screen.h"
28 #include "pipe/p_context.h"
29 
30 #include "program/program.h"
31 #include "program/prog_statevars.h"
32 #include "program/prog_parameter.h"
33 #include "program/ir_to_mesa.h"
34 #include "main/context.h"
35 #include "main/mtypes.h"
36 #include "main/errors.h"
37 #include "main/glspirv.h"
38 #include "main/shaderapi.h"
39 #include "main/uniforms.h"
40 
41 #include "main/shaderobj.h"
42 #include "st_context.h"
43 #include "st_program.h"
44 #include "st_shader_cache.h"
45 
46 #include "compiler/nir/nir.h"
47 #include "compiler/glsl_types.h"
48 #include "compiler/glsl/glsl_to_nir.h"
49 #include "compiler/glsl/gl_nir.h"
50 #include "compiler/glsl/gl_nir_linker.h"
51 #include "compiler/glsl/ir.h"
52 #include "compiler/glsl/ir_optimization.h"
53 #include "compiler/glsl/string_to_uint_map.h"
54 
55 static int
type_size(const struct glsl_type * type)56 type_size(const struct glsl_type *type)
57 {
58    return type->count_attribute_slots(false);
59 }
60 
61 /* Depending on PIPE_CAP_TGSI_TEXCOORD (st->needs_texcoord_semantic) we
62  * may need to fix up varying slots so the glsl->nir path is aligned
63  * with the anything->tgsi->nir path.
64  */
65 static void
st_nir_fixup_varying_slots(struct st_context * st,nir_shader * shader,nir_variable_mode mode)66 st_nir_fixup_varying_slots(struct st_context *st, nir_shader *shader,
67                            nir_variable_mode mode)
68 {
69    if (st->needs_texcoord_semantic)
70       return;
71 
72    nir_foreach_variable_with_modes(var, shader, mode) {
73       if (var->data.location >= VARYING_SLOT_VAR0) {
74          var->data.location += 9;
75       } else if (var->data.location == VARYING_SLOT_PNTC) {
76          var->data.location = VARYING_SLOT_VAR8;
77       } else if ((var->data.location >= VARYING_SLOT_TEX0) &&
78                (var->data.location <= VARYING_SLOT_TEX7)) {
79          var->data.location += VARYING_SLOT_VAR0 - VARYING_SLOT_TEX0;
80       }
81    }
82 }
83 
84 static void
st_shader_gather_info(nir_shader * nir,struct gl_program * prog)85 st_shader_gather_info(nir_shader *nir, struct gl_program *prog)
86 {
87    nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
88 
89    /* Copy the info we just generated back into the gl_program */
90    const char *prog_name = prog->info.name;
91    const char *prog_label = prog->info.label;
92    prog->info = nir->info;
93    prog->info.name = prog_name;
94    prog->info.label = prog_label;
95 }
96 
97 /* input location assignment for VS inputs must be handled specially, so
98  * that it is aligned w/ st's vbo state.
99  * (This isn't the case with, for ex, FS inputs, which only need to agree
100  * on varying-slot w/ the VS outputs)
101  */
102 void
st_nir_assign_vs_in_locations(struct nir_shader * nir)103 st_nir_assign_vs_in_locations(struct nir_shader *nir)
104 {
105    if (nir->info.stage != MESA_SHADER_VERTEX || nir->info.io_lowered)
106       return;
107 
108    nir->num_inputs = util_bitcount64(nir->info.inputs_read);
109 
110    bool removed_inputs = false;
111 
112    nir_foreach_shader_in_variable_safe(var, nir) {
113       /* NIR already assigns dual-slot inputs to two locations so all we have
114        * to do is compact everything down.
115        */
116       if (nir->info.inputs_read & BITFIELD64_BIT(var->data.location)) {
117          var->data.driver_location =
118             util_bitcount64(nir->info.inputs_read &
119                               BITFIELD64_MASK(var->data.location));
120       } else {
121          /* Convert unused input variables to shader_temp (with no
122           * initialization), to avoid confusing drivers looking through the
123           * inputs array and expecting to find inputs with a driver_location
124           * set.
125           */
126          var->data.mode = nir_var_shader_temp;
127          removed_inputs = true;
128       }
129    }
130 
131    /* Re-lower global vars, to deal with any dead VS inputs. */
132    if (removed_inputs)
133       NIR_PASS_V(nir, nir_lower_global_vars_to_local);
134 }
135 
136 static int
st_nir_lookup_parameter_index(struct gl_program * prog,nir_variable * var)137 st_nir_lookup_parameter_index(struct gl_program *prog, nir_variable *var)
138 {
139    struct gl_program_parameter_list *params = prog->Parameters;
140 
141    /* Lookup the first parameter that the uniform storage that match the
142     * variable location.
143     */
144    for (unsigned i = 0; i < params->NumParameters; i++) {
145       int index = params->Parameters[i].MainUniformStorageIndex;
146       if (index == var->data.location)
147          return i;
148    }
149 
150    /* TODO: Handle this fallback for SPIR-V.  We need this for GLSL e.g. in
151     * dEQP-GLES2.functional.uniform_api.random.3
152     */
153 
154    /* is there a better way to do this?  If we have something like:
155     *
156     *    struct S {
157     *           float f;
158     *           vec4 v;
159     *    };
160     *    uniform S color;
161     *
162     * Then what we get in prog->Parameters looks like:
163     *
164     *    0: Name=color.f, Type=6, DataType=1406, Size=1
165     *    1: Name=color.v, Type=6, DataType=8b52, Size=4
166     *
167     * So the name doesn't match up and _mesa_lookup_parameter_index()
168     * fails.  In this case just find the first matching "color.*"..
169     *
170     * Note for arrays you could end up w/ color[n].f, for example.
171     *
172     * glsl_to_tgsi works slightly differently in this regard.  It is
173     * emitting something more low level, so it just translates the
174     * params list 1:1 to CONST[] regs.  Going from GLSL IR to TGSI,
175     * it just calculates the additional offset of struct field members
176     * in glsl_to_tgsi_visitor::visit(ir_dereference_record *ir) or
177     * glsl_to_tgsi_visitor::visit(ir_dereference_array *ir).  It never
178     * needs to work backwards to get base var loc from the param-list
179     * which already has them separated out.
180     */
181    if (!prog->sh.data->spirv) {
182       int namelen = strlen(var->name);
183       for (unsigned i = 0; i < params->NumParameters; i++) {
184          struct gl_program_parameter *p = &params->Parameters[i];
185          if ((strncmp(p->Name, var->name, namelen) == 0) &&
186              ((p->Name[namelen] == '.') || (p->Name[namelen] == '['))) {
187             return i;
188          }
189       }
190    }
191 
192    return -1;
193 }
194 
195 static void
st_nir_assign_uniform_locations(struct gl_context * ctx,struct gl_program * prog,nir_shader * nir)196 st_nir_assign_uniform_locations(struct gl_context *ctx,
197                                 struct gl_program *prog,
198                                 nir_shader *nir)
199 {
200    int shaderidx = 0;
201    int imageidx = 0;
202 
203    nir_foreach_uniform_variable(uniform, nir) {
204       int loc;
205 
206       const struct glsl_type *type = glsl_without_array(uniform->type);
207       if (!uniform->data.bindless && (type->is_sampler() || type->is_image())) {
208          if (type->is_sampler()) {
209             loc = shaderidx;
210             shaderidx += type_size(uniform->type);
211          } else {
212             loc = imageidx;
213             imageidx += type_size(uniform->type);
214          }
215       } else if (uniform->state_slots) {
216          const gl_state_index16 *const stateTokens = uniform->state_slots[0].tokens;
217          /* This state reference has already been setup by ir_to_mesa, but we'll
218           * get the same index back here.
219           */
220 
221          unsigned comps;
222          if (glsl_type_is_struct_or_ifc(type)) {
223             comps = 4;
224          } else {
225             comps = glsl_get_vector_elements(type);
226          }
227 
228          if (ctx->Const.PackedDriverUniformStorage) {
229             loc = _mesa_add_sized_state_reference(prog->Parameters,
230                                                   stateTokens, comps, false);
231             loc = prog->Parameters->ParameterValueOffset[loc];
232          } else {
233             loc = _mesa_add_state_reference(prog->Parameters, stateTokens);
234          }
235       } else {
236          loc = st_nir_lookup_parameter_index(prog, uniform);
237 
238          /* We need to check that loc is not -1 here before accessing the
239           * array. It can be negative for example when we have a struct that
240           * only contains opaque types.
241           */
242          if (loc >= 0 && ctx->Const.PackedDriverUniformStorage) {
243             loc = prog->Parameters->ParameterValueOffset[loc];
244          }
245       }
246 
247       uniform->data.driver_location = loc;
248    }
249 }
250 
251 void
st_nir_opts(nir_shader * nir)252 st_nir_opts(nir_shader *nir)
253 {
254    bool progress;
255 
256    do {
257       progress = false;
258 
259       NIR_PASS_V(nir, nir_lower_vars_to_ssa);
260 
261       /* Linking deals with unused inputs/outputs, but here we can remove
262        * things local to the shader in the hopes that we can cleanup other
263        * things. This pass will also remove variables with only stores, so we
264        * might be able to make progress after it.
265        */
266       NIR_PASS(progress, nir, nir_remove_dead_variables,
267                nir_var_function_temp | nir_var_shader_temp |
268                nir_var_mem_shared,
269                NULL);
270 
271       NIR_PASS(progress, nir, nir_opt_copy_prop_vars);
272       NIR_PASS(progress, nir, nir_opt_dead_write_vars);
273 
274       if (nir->options->lower_to_scalar) {
275          NIR_PASS_V(nir, nir_lower_alu_to_scalar, NULL, NULL);
276          NIR_PASS_V(nir, nir_lower_phis_to_scalar);
277       }
278 
279       NIR_PASS_V(nir, nir_lower_alu);
280       NIR_PASS_V(nir, nir_lower_pack);
281       NIR_PASS(progress, nir, nir_copy_prop);
282       NIR_PASS(progress, nir, nir_opt_remove_phis);
283       NIR_PASS(progress, nir, nir_opt_dce);
284       if (nir_opt_trivial_continues(nir)) {
285          progress = true;
286          NIR_PASS(progress, nir, nir_copy_prop);
287          NIR_PASS(progress, nir, nir_opt_dce);
288       }
289       NIR_PASS(progress, nir, nir_opt_if, false);
290       NIR_PASS(progress, nir, nir_opt_dead_cf);
291       NIR_PASS(progress, nir, nir_opt_cse);
292       NIR_PASS(progress, nir, nir_opt_peephole_select, 8, true, true);
293 
294       NIR_PASS(progress, nir, nir_opt_algebraic);
295       NIR_PASS(progress, nir, nir_opt_constant_folding);
296 
297       if (!nir->info.flrp_lowered) {
298          unsigned lower_flrp =
299             (nir->options->lower_flrp16 ? 16 : 0) |
300             (nir->options->lower_flrp32 ? 32 : 0) |
301             (nir->options->lower_flrp64 ? 64 : 0);
302 
303          if (lower_flrp) {
304             bool lower_flrp_progress = false;
305 
306             NIR_PASS(lower_flrp_progress, nir, nir_lower_flrp,
307                      lower_flrp,
308                      false /* always_precise */);
309             if (lower_flrp_progress) {
310                NIR_PASS(progress, nir,
311                         nir_opt_constant_folding);
312                progress = true;
313             }
314          }
315 
316          /* Nothing should rematerialize any flrps, so we only need to do this
317           * lowering once.
318           */
319          nir->info.flrp_lowered = true;
320       }
321 
322       NIR_PASS(progress, nir, nir_opt_undef);
323       NIR_PASS(progress, nir, nir_opt_conditional_discard);
324       if (nir->options->max_unroll_iterations) {
325          NIR_PASS(progress, nir, nir_opt_loop_unroll, (nir_variable_mode)0);
326       }
327    } while (progress);
328 }
329 
330 static void
shared_type_info(const struct glsl_type * type,unsigned * size,unsigned * align)331 shared_type_info(const struct glsl_type *type, unsigned *size, unsigned *align)
332 {
333    assert(glsl_type_is_vector_or_scalar(type));
334 
335    uint32_t comp_size = glsl_type_is_boolean(type)
336       ? 4 : glsl_get_bit_size(type) / 8;
337    unsigned length = glsl_get_vector_elements(type);
338    *size = comp_size * length,
339    *align = comp_size * (length == 3 ? 4 : length);
340 }
341 
342 /* First third of converting glsl_to_nir.. this leaves things in a pre-
343  * nir_lower_io state, so that shader variants can more easily insert/
344  * replace variables, etc.
345  */
346 static void
st_nir_preprocess(struct st_context * st,struct gl_program * prog,struct gl_shader_program * shader_program,gl_shader_stage stage)347 st_nir_preprocess(struct st_context *st, struct gl_program *prog,
348                   struct gl_shader_program *shader_program,
349                   gl_shader_stage stage)
350 {
351    struct pipe_screen *screen = st->pipe->screen;
352    const nir_shader_compiler_options *options =
353       st->ctx->Const.ShaderCompilerOptions[prog->info.stage].NirOptions;
354    assert(options);
355    nir_shader *nir = prog->nir;
356 
357    /* Set the next shader stage hint for VS and TES. */
358    if (!nir->info.separate_shader &&
359        (nir->info.stage == MESA_SHADER_VERTEX ||
360         nir->info.stage == MESA_SHADER_TESS_EVAL)) {
361 
362       unsigned prev_stages = (1 << (prog->info.stage + 1)) - 1;
363       unsigned stages_mask =
364          ~prev_stages & shader_program->data->linked_stages;
365 
366       nir->info.next_stage = stages_mask ?
367          (gl_shader_stage) u_bit_scan(&stages_mask) : MESA_SHADER_FRAGMENT;
368    } else {
369       nir->info.next_stage = MESA_SHADER_FRAGMENT;
370    }
371 
372    nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
373    if (!st->ctx->SoftFP64 && ((nir->info.bit_sizes_int | nir->info.bit_sizes_float) & 64) &&
374        (options->lower_doubles_options & nir_lower_fp64_full_software) != 0) {
375       st->ctx->SoftFP64 = glsl_float64_funcs_to_nir(st->ctx, options);
376    }
377 
378    /* ES has strict SSO validation rules for shader IO matching so we can't
379     * remove dead IO until the resource list has been built. Here we skip
380     * removing them until later. This will potentially make the IO lowering
381     * calls below do a little extra work but should otherwise have no impact.
382     */
383    if (!_mesa_is_gles(st->ctx) || !nir->info.separate_shader) {
384       nir_variable_mode mask = nir_var_shader_in | nir_var_shader_out;
385       nir_remove_dead_variables(nir, mask, NULL);
386    }
387 
388    if (options->lower_all_io_to_temps ||
389        nir->info.stage == MESA_SHADER_VERTEX ||
390        nir->info.stage == MESA_SHADER_GEOMETRY) {
391       NIR_PASS_V(nir, nir_lower_io_to_temporaries,
392                  nir_shader_get_entrypoint(nir),
393                  true, true);
394    } else if (nir->info.stage == MESA_SHADER_FRAGMENT ||
395               !screen->get_param(screen, PIPE_CAP_TGSI_CAN_READ_OUTPUTS)) {
396       NIR_PASS_V(nir, nir_lower_io_to_temporaries,
397                  nir_shader_get_entrypoint(nir),
398                  true, false);
399    }
400 
401    NIR_PASS_V(nir, nir_lower_global_vars_to_local);
402    NIR_PASS_V(nir, nir_split_var_copies);
403    NIR_PASS_V(nir, nir_lower_var_copies);
404 
405    if (options->lower_to_scalar) {
406      NIR_PASS_V(nir, nir_lower_alu_to_scalar, NULL, NULL);
407    }
408 
409    /* before buffers and vars_to_ssa */
410    NIR_PASS_V(nir, gl_nir_lower_images, true);
411 
412    /* TODO: Change GLSL to not lower shared memory. */
413    if (prog->nir->info.stage == MESA_SHADER_COMPUTE &&
414        shader_program->data->spirv) {
415       NIR_PASS_V(prog->nir, nir_lower_vars_to_explicit_types,
416                  nir_var_mem_shared, shared_type_info);
417       NIR_PASS_V(prog->nir, nir_lower_explicit_io,
418                  nir_var_mem_shared, nir_address_format_32bit_offset);
419    }
420 
421    /* Do a round of constant folding to clean up address calculations */
422    NIR_PASS_V(nir, nir_opt_constant_folding);
423 }
424 
425 /* Second third of converting glsl_to_nir. This creates uniforms, gathers
426  * info on varyings, etc after NIR link time opts have been applied.
427  */
428 static void
st_glsl_to_nir_post_opts(struct st_context * st,struct gl_program * prog,struct gl_shader_program * shader_program)429 st_glsl_to_nir_post_opts(struct st_context *st, struct gl_program *prog,
430                          struct gl_shader_program *shader_program)
431 {
432    nir_shader *nir = prog->nir;
433    struct pipe_screen *screen = st->pipe->screen;
434 
435    /* Make a pass over the IR to add state references for any built-in
436     * uniforms that are used.  This has to be done now (during linking).
437     * Code generation doesn't happen until the first time this shader is
438     * used for rendering.  Waiting until then to generate the parameters is
439     * too late.  At that point, the values for the built-in uniforms won't
440     * get sent to the shader.
441     */
442    nir_foreach_uniform_variable(var, nir) {
443       const nir_state_slot *const slots = var->state_slots;
444       if (slots != NULL) {
445          const struct glsl_type *type = glsl_without_array(var->type);
446          for (unsigned int i = 0; i < var->num_state_slots; i++) {
447             unsigned comps;
448             if (glsl_type_is_struct_or_ifc(type)) {
449                comps = _mesa_program_state_value_size(slots[i].tokens);
450             } else {
451                comps = glsl_get_vector_elements(type);
452             }
453 
454             if (st->ctx->Const.PackedDriverUniformStorage) {
455                _mesa_add_sized_state_reference(prog->Parameters,
456                                                slots[i].tokens,
457                                                comps, false);
458             } else {
459                _mesa_add_state_reference(prog->Parameters,
460                                          slots[i].tokens);
461             }
462          }
463       }
464    }
465 
466    /* Avoid reallocation of the program parameter list, because the uniform
467     * storage is only associated with the original parameter list.
468     * This should be enough for Bitmap and DrawPixels constants.
469     */
470    _mesa_reserve_parameter_storage(prog->Parameters, 8);
471 
472    /* This has to be done last.  Any operation the can cause
473     * prog->ParameterValues to get reallocated (e.g., anything that adds a
474     * program constant) has to happen before creating this linkage.
475     */
476    _mesa_associate_uniform_storage(st->ctx, shader_program, prog);
477 
478    st_set_prog_affected_state_flags(prog);
479 
480    /* None of the builtins being lowered here can be produced by SPIR-V.  See
481     * _mesa_builtin_uniform_desc. Also drivers that support packed uniform
482     * storage don't need to lower builtins.
483     */
484    if (!shader_program->data->spirv &&
485        !st->ctx->Const.PackedDriverUniformStorage)
486       NIR_PASS_V(nir, st_nir_lower_builtin);
487 
488    if (!screen->get_param(screen, PIPE_CAP_NIR_ATOMICS_AS_DEREF))
489       NIR_PASS_V(nir, gl_nir_lower_atomics, shader_program, true);
490 
491    NIR_PASS_V(nir, nir_opt_intrinsics);
492 
493    /* Lower 64-bit ops. */
494    if (nir->options->lower_int64_options ||
495        nir->options->lower_doubles_options) {
496       bool lowered_64bit_ops = false;
497       if (nir->options->lower_doubles_options) {
498          NIR_PASS(lowered_64bit_ops, nir, nir_lower_doubles,
499                   st->ctx->SoftFP64, nir->options->lower_doubles_options);
500       }
501       if (nir->options->lower_int64_options)
502          NIR_PASS(lowered_64bit_ops, nir, nir_lower_int64);
503 
504       if (lowered_64bit_ops)
505          st_nir_opts(nir);
506    }
507 
508    nir_variable_mode mask =
509       nir_var_shader_in | nir_var_shader_out | nir_var_function_temp;
510    nir_remove_dead_variables(nir, mask, NULL);
511 
512    if (!st->has_hw_atomics && !screen->get_param(screen, PIPE_CAP_NIR_ATOMICS_AS_DEREF))
513       NIR_PASS_V(nir, nir_lower_atomics_to_ssbo);
514 
515    st_finalize_nir_before_variants(nir);
516 
517    if (st->allow_st_finalize_nir_twice)
518       st_finalize_nir(st, prog, shader_program, nir, true);
519 
520    if (st->ctx->_Shader->Flags & GLSL_DUMP) {
521       _mesa_log("\n");
522       _mesa_log("NIR IR for linked %s program %d:\n",
523              _mesa_shader_stage_to_string(prog->info.stage),
524              shader_program->Name);
525       nir_print_shader(nir, _mesa_get_log_file());
526       _mesa_log("\n\n");
527    }
528 }
529 
530 static void
st_nir_vectorize_io(nir_shader * producer,nir_shader * consumer)531 st_nir_vectorize_io(nir_shader *producer, nir_shader *consumer)
532 {
533    NIR_PASS_V(producer, nir_lower_io_to_vector, nir_var_shader_out);
534    NIR_PASS_V(producer, nir_opt_combine_stores, nir_var_shader_out);
535    NIR_PASS_V(consumer, nir_lower_io_to_vector, nir_var_shader_in);
536 
537    if ((producer)->info.stage != MESA_SHADER_TESS_CTRL) {
538       /* Calling lower_io_to_vector creates output variable writes with
539        * write-masks.  We only support these for TCS outputs, so for other
540        * stages, we need to call nir_lower_io_to_temporaries to get rid of
541        * them.  This, in turn, creates temporary variables and extra
542        * copy_deref intrinsics that we need to clean up.
543        */
544       NIR_PASS_V(producer, nir_lower_io_to_temporaries,
545                  nir_shader_get_entrypoint(producer), true, false);
546       NIR_PASS_V(producer, nir_lower_global_vars_to_local);
547       NIR_PASS_V(producer, nir_split_var_copies);
548       NIR_PASS_V(producer, nir_lower_var_copies);
549    }
550 }
551 
552 static void
st_nir_link_shaders(nir_shader * producer,nir_shader * consumer)553 st_nir_link_shaders(nir_shader *producer, nir_shader *consumer)
554 {
555    if (producer->options->lower_to_scalar) {
556       NIR_PASS_V(producer, nir_lower_io_to_scalar_early, nir_var_shader_out);
557       NIR_PASS_V(consumer, nir_lower_io_to_scalar_early, nir_var_shader_in);
558    }
559 
560    nir_lower_io_arrays_to_elements(producer, consumer);
561 
562    st_nir_opts(producer);
563    st_nir_opts(consumer);
564 
565    if (nir_link_opt_varyings(producer, consumer))
566       st_nir_opts(consumer);
567 
568    NIR_PASS_V(producer, nir_remove_dead_variables, nir_var_shader_out, NULL);
569    NIR_PASS_V(consumer, nir_remove_dead_variables, nir_var_shader_in, NULL);
570 
571    if (nir_remove_unused_varyings(producer, consumer)) {
572       NIR_PASS_V(producer, nir_lower_global_vars_to_local);
573       NIR_PASS_V(consumer, nir_lower_global_vars_to_local);
574 
575       st_nir_opts(producer);
576       st_nir_opts(consumer);
577 
578       /* Optimizations can cause varyings to become unused.
579        * nir_compact_varyings() depends on all dead varyings being removed so
580        * we need to call nir_remove_dead_variables() again here.
581        */
582       NIR_PASS_V(producer, nir_remove_dead_variables, nir_var_shader_out,
583                  NULL);
584       NIR_PASS_V(consumer, nir_remove_dead_variables, nir_var_shader_in,
585                  NULL);
586    }
587 }
588 
589 static void
st_lower_patch_vertices_in(struct gl_shader_program * shader_prog)590 st_lower_patch_vertices_in(struct gl_shader_program *shader_prog)
591 {
592    struct gl_linked_shader *linked_tcs =
593       shader_prog->_LinkedShaders[MESA_SHADER_TESS_CTRL];
594    struct gl_linked_shader *linked_tes =
595       shader_prog->_LinkedShaders[MESA_SHADER_TESS_EVAL];
596 
597    /* If we have a TCS and TES linked together, lower TES patch vertices. */
598    if (linked_tcs && linked_tes) {
599       nir_shader *tcs_nir = linked_tcs->Program->nir;
600       nir_shader *tes_nir = linked_tes->Program->nir;
601 
602       /* The TES input vertex count is the TCS output vertex count,
603        * lower TES gl_PatchVerticesIn to a constant.
604        */
605       uint32_t tes_patch_verts = tcs_nir->info.tess.tcs_vertices_out;
606       NIR_PASS_V(tes_nir, nir_lower_patch_vertices, tes_patch_verts, NULL);
607    }
608 }
609 
610 extern "C" {
611 
612 void
st_nir_lower_wpos_ytransform(struct nir_shader * nir,struct gl_program * prog,struct pipe_screen * pscreen)613 st_nir_lower_wpos_ytransform(struct nir_shader *nir,
614                              struct gl_program *prog,
615                              struct pipe_screen *pscreen)
616 {
617    if (nir->info.stage != MESA_SHADER_FRAGMENT)
618       return;
619 
620    static const gl_state_index16 wposTransformState[STATE_LENGTH] = {
621       STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM
622    };
623    nir_lower_wpos_ytransform_options wpos_options = { { 0 } };
624 
625    memcpy(wpos_options.state_tokens, wposTransformState,
626           sizeof(wpos_options.state_tokens));
627    wpos_options.fs_coord_origin_upper_left =
628       pscreen->get_param(pscreen,
629                          PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT);
630    wpos_options.fs_coord_origin_lower_left =
631       pscreen->get_param(pscreen,
632                          PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
633    wpos_options.fs_coord_pixel_center_integer =
634       pscreen->get_param(pscreen,
635                          PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
636    wpos_options.fs_coord_pixel_center_half_integer =
637       pscreen->get_param(pscreen,
638                          PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER);
639 
640    if (nir_lower_wpos_ytransform(nir, &wpos_options)) {
641       nir_validate_shader(nir, "after nir_lower_wpos_ytransform");
642       _mesa_add_state_reference(prog->Parameters, wposTransformState);
643    }
644 
645    static const gl_state_index16 pntcTransformState[STATE_LENGTH] = {
646       STATE_INTERNAL, STATE_FB_PNTC_Y_TRANSFORM
647    };
648 
649    if (nir_lower_pntc_ytransform(nir, &pntcTransformState)) {
650       _mesa_add_state_reference(prog->Parameters, pntcTransformState);
651    }
652 }
653 
654 bool
st_link_nir(struct gl_context * ctx,struct gl_shader_program * shader_program)655 st_link_nir(struct gl_context *ctx,
656             struct gl_shader_program *shader_program)
657 {
658    struct st_context *st = st_context(ctx);
659    struct gl_linked_shader *linked_shader[MESA_SHADER_STAGES];
660    unsigned num_shaders = 0;
661 
662    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
663       if (shader_program->_LinkedShaders[i])
664          linked_shader[num_shaders++] = shader_program->_LinkedShaders[i];
665    }
666 
667    for (unsigned i = 0; i < num_shaders; i++) {
668       struct gl_linked_shader *shader = linked_shader[i];
669       const nir_shader_compiler_options *options =
670          st->ctx->Const.ShaderCompilerOptions[shader->Stage].NirOptions;
671       struct gl_program *prog = shader->Program;
672       struct st_program *stp = (struct st_program *)prog;
673 
674       _mesa_copy_linked_program_data(shader_program, shader);
675 
676       assert(!prog->nir);
677       stp->shader_program = shader_program;
678       stp->state.type = PIPE_SHADER_IR_NIR;
679 
680       /* Parameters will be filled during NIR linking. */
681       prog->Parameters = _mesa_new_parameter_list();
682 
683       if (shader_program->data->spirv) {
684          prog->nir = _mesa_spirv_to_nir(ctx, shader_program, shader->Stage, options);
685       } else {
686          validate_ir_tree(shader->ir);
687 
688          if (ctx->_Shader->Flags & GLSL_DUMP) {
689             _mesa_log("\n");
690             _mesa_log("GLSL IR for linked %s program %d:\n",
691                       _mesa_shader_stage_to_string(shader->Stage),
692                       shader_program->Name);
693             _mesa_print_ir(_mesa_get_log_file(), shader->ir, NULL);
694             _mesa_log("\n\n");
695          }
696 
697          prog->nir = glsl_to_nir(st->ctx, shader_program, shader->Stage, options);
698          st_nir_preprocess(st, prog, shader_program, shader->Stage);
699       }
700 
701       if (options->lower_to_scalar) {
702          NIR_PASS_V(shader->Program->nir, nir_lower_load_const_to_scalar);
703       }
704    }
705 
706    st_lower_patch_vertices_in(shader_program);
707 
708    /* For SPIR-V, we have to perform the NIR linking before applying
709     * st_nir_preprocess.
710     */
711    if (shader_program->data->spirv) {
712       static const gl_nir_linker_options opts = {
713          true /*fill_parameters */
714       };
715       if (!gl_nir_link_spirv(ctx, shader_program, &opts))
716          return GL_FALSE;
717 
718       nir_build_program_resource_list(ctx, shader_program, true);
719 
720       for (unsigned i = 0; i < num_shaders; i++) {
721          struct gl_linked_shader *shader = linked_shader[i];
722          struct gl_program *prog = shader->Program;
723 
724          prog->ExternalSamplersUsed = gl_external_samplers(prog);
725          _mesa_update_shader_textures_used(shader_program, prog);
726          st_nir_preprocess(st, prog, shader_program, shader->Stage);
727       }
728    }
729 
730    /* Linking the stages in the opposite order (from fragment to vertex)
731     * ensures that inter-shader outputs written to in an earlier stage
732     * are eliminated if they are (transitively) not used in a later
733     * stage.
734     */
735    for (int i = num_shaders - 2; i >= 0; i--) {
736       st_nir_link_shaders(linked_shader[i]->Program->nir,
737                           linked_shader[i + 1]->Program->nir);
738    }
739    /* Linking shaders also optimizes them. Separate shaders, compute shaders
740     * and shaders with a fixed-func VS or FS that don't need linking are
741     * optimized here.
742     */
743    if (num_shaders == 1)
744       st_nir_opts(linked_shader[0]->Program->nir);
745 
746    if (!shader_program->data->spirv) {
747       if (!gl_nir_link_glsl(ctx, shader_program))
748          return GL_FALSE;
749 
750       for (unsigned i = 0; i < num_shaders; i++) {
751          struct gl_program *prog = linked_shader[i]->Program;
752          prog->ExternalSamplersUsed = gl_external_samplers(prog);
753          _mesa_update_shader_textures_used(shader_program, prog);
754       }
755 
756       nir_build_program_resource_list(ctx, shader_program, false);
757    }
758 
759    for (unsigned i = 0; i < num_shaders; i++) {
760       struct gl_linked_shader *shader = linked_shader[i];
761       nir_shader *nir = shader->Program->nir;
762 
763       NIR_PASS_V(nir, nir_opt_access);
764 
765       /* This needs to run after the initial pass of nir_lower_vars_to_ssa, so
766        * that the buffer indices are constants in nir where they where
767        * constants in GLSL. */
768       NIR_PASS_V(nir, gl_nir_lower_buffers, shader_program);
769 
770       /* Remap the locations to slots so those requiring two slots will occupy
771        * two locations. For instance, if we have in the IR code a dvec3 attr0 in
772        * location 0 and vec4 attr1 in location 1, in NIR attr0 will use
773        * locations/slots 0 and 1, and attr1 will use location/slot 2
774        */
775       if (nir->info.stage == MESA_SHADER_VERTEX && !shader_program->data->spirv)
776          nir_remap_dual_slot_attributes(nir, &shader->Program->DualSlotInputs);
777 
778       NIR_PASS_V(nir, st_nir_lower_wpos_ytransform, shader->Program,
779                  st->pipe->screen);
780 
781       NIR_PASS_V(nir, nir_lower_system_values);
782       NIR_PASS_V(nir, nir_lower_compute_system_values, NULL);
783 
784       NIR_PASS_V(nir, nir_lower_clip_cull_distance_arrays);
785 
786       st_shader_gather_info(nir, shader->Program);
787       if (shader->Stage == MESA_SHADER_VERTEX) {
788          /* NIR expands dual-slot inputs out to two locations.  We need to
789           * compact things back down GL-style single-slot inputs to avoid
790           * confusing the state tracker.
791           */
792          shader->Program->info.inputs_read =
793             nir_get_single_slot_attribs_mask(nir->info.inputs_read,
794                                              shader->Program->DualSlotInputs);
795       }
796 
797       if (i >= 1) {
798          struct gl_program *prev_shader = linked_shader[i - 1]->Program;
799 
800          /* We can't use nir_compact_varyings with transform feedback, since
801           * the pipe_stream_output->output_register field is based on the
802           * pre-compacted driver_locations.
803           */
804          if (!(prev_shader->sh.LinkedTransformFeedback &&
805                prev_shader->sh.LinkedTransformFeedback->NumVarying > 0))
806             nir_compact_varyings(prev_shader->nir,
807                                  nir, ctx->API != API_OPENGL_COMPAT);
808 
809          if (ctx->Const.ShaderCompilerOptions[shader->Stage].NirOptions->vectorize_io)
810             st_nir_vectorize_io(prev_shader->nir, nir);
811       }
812    }
813 
814    struct shader_info *prev_info = NULL;
815 
816    for (unsigned i = 0; i < num_shaders; i++) {
817       struct gl_linked_shader *shader = linked_shader[i];
818       struct shader_info *info = &shader->Program->nir->info;
819 
820       st_glsl_to_nir_post_opts(st, shader->Program, shader_program);
821 
822       if (prev_info &&
823           ctx->Const.ShaderCompilerOptions[shader->Stage].NirOptions->unify_interfaces) {
824          prev_info->outputs_written |= info->inputs_read &
825             ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
826          info->inputs_read |= prev_info->outputs_written &
827             ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
828 
829          prev_info->patch_outputs_written |= info->patch_inputs_read;
830          info->patch_inputs_read |= prev_info->patch_outputs_written;
831       }
832       prev_info = info;
833    }
834 
835    for (unsigned i = 0; i < num_shaders; i++) {
836       struct gl_linked_shader *shader = linked_shader[i];
837       struct gl_program *prog = shader->Program;
838       struct st_program *stp = st_program(prog);
839 
840       /* Make sure that prog->info is in sync with nir->info, but st/mesa
841        * expects some of the values to be from before lowering.
842        */
843       shader_info old_info = prog->info;
844       prog->info = prog->nir->info;
845       prog->info.name = old_info.name;
846       prog->info.label = old_info.label;
847       prog->info.num_ssbos = old_info.num_ssbos;
848       prog->info.num_ubos = old_info.num_ubos;
849       prog->info.num_abos = old_info.num_abos;
850       if (prog->info.stage == MESA_SHADER_VERTEX)
851          prog->info.inputs_read = old_info.inputs_read;
852 
853       /* Initialize st_vertex_program members. */
854       if (shader->Stage == MESA_SHADER_VERTEX)
855          st_prepare_vertex_program(stp);
856 
857       /* Get pipe_stream_output_info. */
858       if (shader->Stage == MESA_SHADER_VERTEX ||
859           shader->Stage == MESA_SHADER_TESS_EVAL ||
860           shader->Stage == MESA_SHADER_GEOMETRY)
861          st_translate_stream_output_info(prog);
862 
863       st_store_ir_in_disk_cache(st, prog, true);
864 
865       st_release_variants(st, stp);
866       st_finalize_program(st, prog);
867 
868       /* The GLSL IR won't be needed anymore. */
869       ralloc_free(shader->ir);
870       shader->ir = NULL;
871    }
872 
873    return true;
874 }
875 
876 void
st_nir_assign_varying_locations(struct st_context * st,nir_shader * nir)877 st_nir_assign_varying_locations(struct st_context *st, nir_shader *nir)
878 {
879    if (nir->info.stage == MESA_SHADER_VERTEX) {
880       nir_assign_io_var_locations(nir, nir_var_shader_out,
881                                   &nir->num_outputs,
882                                   nir->info.stage);
883       st_nir_fixup_varying_slots(st, nir, nir_var_shader_out);
884    } else if (nir->info.stage == MESA_SHADER_GEOMETRY ||
885               nir->info.stage == MESA_SHADER_TESS_CTRL ||
886               nir->info.stage == MESA_SHADER_TESS_EVAL) {
887       nir_assign_io_var_locations(nir, nir_var_shader_in,
888                                   &nir->num_inputs,
889                                   nir->info.stage);
890       st_nir_fixup_varying_slots(st, nir, nir_var_shader_in);
891 
892       nir_assign_io_var_locations(nir, nir_var_shader_out,
893                                   &nir->num_outputs,
894                                   nir->info.stage);
895       st_nir_fixup_varying_slots(st, nir, nir_var_shader_out);
896    } else if (nir->info.stage == MESA_SHADER_FRAGMENT) {
897       nir_assign_io_var_locations(nir, nir_var_shader_in,
898                                   &nir->num_inputs,
899                                   nir->info.stage);
900       st_nir_fixup_varying_slots(st, nir, nir_var_shader_in);
901       nir_assign_io_var_locations(nir, nir_var_shader_out,
902                                   &nir->num_outputs,
903                                   nir->info.stage);
904    } else if (nir->info.stage == MESA_SHADER_COMPUTE) {
905        /* TODO? */
906    } else {
907       unreachable("invalid shader type");
908    }
909 }
910 
911 void
st_nir_lower_samplers(struct pipe_screen * screen,nir_shader * nir,struct gl_shader_program * shader_program,struct gl_program * prog)912 st_nir_lower_samplers(struct pipe_screen *screen, nir_shader *nir,
913                       struct gl_shader_program *shader_program,
914                       struct gl_program *prog)
915 {
916    if (screen->get_param(screen, PIPE_CAP_NIR_SAMPLERS_AS_DEREF))
917       NIR_PASS_V(nir, gl_nir_lower_samplers_as_deref, shader_program);
918    else
919       NIR_PASS_V(nir, gl_nir_lower_samplers, shader_program);
920 
921    if (prog) {
922       prog->info.textures_used = nir->info.textures_used;
923       prog->info.textures_used_by_txf = nir->info.textures_used_by_txf;
924       prog->info.images_used = nir->info.images_used;
925    }
926 }
927 
928 static int
st_packed_uniforms_type_size(const struct glsl_type * type,bool bindless)929 st_packed_uniforms_type_size(const struct glsl_type *type, bool bindless)
930 {
931    return glsl_count_dword_slots(type, bindless);
932 }
933 
934 static int
st_unpacked_uniforms_type_size(const struct glsl_type * type,bool bindless)935 st_unpacked_uniforms_type_size(const struct glsl_type *type, bool bindless)
936 {
937    return glsl_count_vec4_slots(type, false, bindless);
938 }
939 
940 void
st_nir_lower_uniforms(struct st_context * st,nir_shader * nir)941 st_nir_lower_uniforms(struct st_context *st, nir_shader *nir)
942 {
943    unsigned multiplier = 16;
944    if (st->ctx->Const.PackedDriverUniformStorage) {
945       NIR_PASS_V(nir, nir_lower_io, nir_var_uniform,
946                  st_packed_uniforms_type_size,
947                  (nir_lower_io_options)0);
948       multiplier = 4;
949    } else {
950       NIR_PASS_V(nir, nir_lower_io, nir_var_uniform,
951                  st_unpacked_uniforms_type_size,
952                  (nir_lower_io_options)0);
953    }
954 
955    if (nir->options->lower_uniforms_to_ubo)
956       NIR_PASS_V(nir, nir_lower_uniforms_to_ubo, multiplier);
957 }
958 
959 /* Last third of preparing nir from glsl, which happens after shader
960  * variant lowering.
961  */
962 void
st_finalize_nir(struct st_context * st,struct gl_program * prog,struct gl_shader_program * shader_program,nir_shader * nir,bool finalize_by_driver)963 st_finalize_nir(struct st_context *st, struct gl_program *prog,
964                 struct gl_shader_program *shader_program,
965                 nir_shader *nir, bool finalize_by_driver)
966 {
967    struct pipe_screen *screen = st->pipe->screen;
968 
969    NIR_PASS_V(nir, nir_split_var_copies);
970    NIR_PASS_V(nir, nir_lower_var_copies);
971 
972    st_nir_assign_varying_locations(st, nir);
973    st_nir_assign_uniform_locations(st->ctx, prog, nir);
974 
975    /* Set num_uniforms in number of attribute slots (vec4s) */
976    nir->num_uniforms = DIV_ROUND_UP(prog->Parameters->NumParameterValues, 4);
977 
978    st_nir_lower_uniforms(st, nir);
979    st_nir_lower_samplers(screen, nir, shader_program, prog);
980    if (!screen->get_param(screen, PIPE_CAP_NIR_IMAGES_AS_DEREF))
981       NIR_PASS_V(nir, gl_nir_lower_images, false);
982 
983    if (finalize_by_driver && screen->finalize_nir)
984       screen->finalize_nir(screen, nir, false);
985 }
986 
987 } /* extern "C" */
988