• 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 "main/context.h"
34 #include "main/mtypes.h"
35 #include "main/errors.h"
36 #include "main/glspirv.h"
37 #include "main/shaderapi.h"
38 #include "main/uniforms.h"
39 
40 #include "main/shaderobj.h"
41 #include "st_context.h"
42 #include "st_program.h"
43 #include "st_shader_cache.h"
44 
45 #include "compiler/nir/nir.h"
46 #include "compiler/nir/nir_builder.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/linker_util.h"
54 #include "compiler/glsl/shader_cache.h"
55 #include "compiler/glsl/string_to_uint_map.h"
56 
57 #include "util/log.h"
58 
59 static int
type_size(const struct glsl_type * type)60 type_size(const struct glsl_type *type)
61 {
62    return glsl_count_attribute_slots(type, false);
63 }
64 
65 /* Depending on pipe_caps.tgsi_texcoord (st->needs_texcoord_semantic) we
66  * may need to fix up varying slots so the glsl->nir path is aligned
67  * with the anything->tgsi->nir path.
68  */
69 static void
st_nir_fixup_varying_slots(struct st_context * st,nir_shader * shader,nir_variable_mode mode)70 st_nir_fixup_varying_slots(struct st_context *st, nir_shader *shader,
71                            nir_variable_mode mode)
72 {
73    if (st->needs_texcoord_semantic)
74       return;
75 
76    /* This is called from finalize, but we don't want to do this adjustment twice. */
77    assert(!st->allow_st_finalize_nir_twice);
78 
79    nir_foreach_variable_with_modes(var, shader, mode) {
80       if (var->data.location >= VARYING_SLOT_VAR0 && var->data.location < VARYING_SLOT_PATCH0) {
81          var->data.location += 9;
82       } else if (var->data.location == VARYING_SLOT_PNTC) {
83          var->data.location = VARYING_SLOT_VAR8;
84       } else if ((var->data.location >= VARYING_SLOT_TEX0) &&
85                (var->data.location <= VARYING_SLOT_TEX7)) {
86          var->data.location += VARYING_SLOT_VAR0 - VARYING_SLOT_TEX0;
87       }
88    }
89 }
90 
91 /* input location assignment for VS inputs must be handled specially, so
92  * that it is aligned w/ st's vbo state.
93  * (This isn't the case with, for ex, FS inputs, which only need to agree
94  * on varying-slot w/ the VS outputs)
95  */
96 void
st_nir_assign_vs_in_locations(struct nir_shader * nir)97 st_nir_assign_vs_in_locations(struct nir_shader *nir)
98 {
99    if (nir->info.stage != MESA_SHADER_VERTEX || nir->info.io_lowered)
100       return;
101 
102    nir->num_inputs = util_bitcount64(nir->info.inputs_read);
103 
104    bool removed_inputs = false;
105 
106    nir_foreach_shader_in_variable_safe(var, nir) {
107       /* NIR already assigns dual-slot inputs to two locations so all we have
108        * to do is compact everything down.
109        */
110       if (nir->info.inputs_read & BITFIELD64_BIT(var->data.location)) {
111          var->data.driver_location =
112             util_bitcount64(nir->info.inputs_read &
113                               BITFIELD64_MASK(var->data.location));
114       } else {
115          /* Convert unused input variables to shader_temp (with no
116           * initialization), to avoid confusing drivers looking through the
117           * inputs array and expecting to find inputs with a driver_location
118           * set.
119           */
120          var->data.mode = nir_var_shader_temp;
121          removed_inputs = true;
122       }
123    }
124 
125    /* Re-lower global vars, to deal with any dead VS inputs. */
126    if (removed_inputs)
127       NIR_PASS(_, nir, nir_lower_global_vars_to_local);
128 }
129 
130 static int
st_nir_lookup_parameter_index(struct gl_program * prog,nir_variable * var)131 st_nir_lookup_parameter_index(struct gl_program *prog, nir_variable *var)
132 {
133    struct gl_program_parameter_list *params = prog->Parameters;
134 
135    /* Lookup the first parameter that the uniform storage that match the
136     * variable location.
137     */
138    for (unsigned i = 0; i < params->NumParameters; i++) {
139       int index = params->Parameters[i].MainUniformStorageIndex;
140       if (index == var->data.location)
141          return i;
142    }
143 
144    /* TODO: Handle this fallback for SPIR-V.  We need this for GLSL e.g. in
145     * dEQP-GLES2.functional.uniform_api.random.3
146     */
147 
148    /* is there a better way to do this?  If we have something like:
149     *
150     *    struct S {
151     *           float f;
152     *           vec4 v;
153     *    };
154     *    uniform S color;
155     *
156     * Then what we get in prog->Parameters looks like:
157     *
158     *    0: Name=color.f, Type=6, DataType=1406, Size=1
159     *    1: Name=color.v, Type=6, DataType=8b52, Size=4
160     *
161     * So the name doesn't match up and _mesa_lookup_parameter_index()
162     * fails.  In this case just find the first matching "color.*"..
163     *
164     * Note for arrays you could end up w/ color[n].f, for example.
165     */
166    if (!prog->sh.data->spirv) {
167       int namelen = strlen(var->name);
168       for (unsigned i = 0; i < params->NumParameters; i++) {
169          struct gl_program_parameter *p = &params->Parameters[i];
170          if ((strncmp(p->Name, var->name, namelen) == 0) &&
171              ((p->Name[namelen] == '.') || (p->Name[namelen] == '['))) {
172             return i;
173          }
174       }
175    }
176 
177    return -1;
178 }
179 
180 static void
st_nir_assign_uniform_locations(struct gl_context * ctx,struct gl_program * prog,nir_shader * nir)181 st_nir_assign_uniform_locations(struct gl_context *ctx,
182                                 struct gl_program *prog,
183                                 nir_shader *nir)
184 {
185    int shaderidx = 0;
186    int imageidx = 0;
187 
188    nir_foreach_variable_with_modes(uniform, nir, nir_var_uniform |
189                                                  nir_var_image) {
190       int loc;
191 
192       const struct glsl_type *type = glsl_without_array(uniform->type);
193       if (!uniform->data.bindless && (glsl_type_is_sampler(type) || glsl_type_is_image(type))) {
194          if (glsl_type_is_sampler(type)) {
195             loc = shaderidx;
196             shaderidx += type_size(uniform->type);
197          } else {
198             loc = imageidx;
199             imageidx += type_size(uniform->type);
200          }
201       } else if (uniform->state_slots) {
202          const gl_state_index16 *const stateTokens = uniform->state_slots[0].tokens;
203 
204          unsigned comps;
205          if (glsl_type_is_struct_or_ifc(type)) {
206             comps = 4;
207          } else {
208             comps = glsl_get_vector_elements(type);
209          }
210 
211          if (ctx->Const.PackedDriverUniformStorage) {
212             loc = _mesa_add_sized_state_reference(prog->Parameters,
213                                                   stateTokens, comps, false);
214             loc = prog->Parameters->Parameters[loc].ValueOffset;
215          } else {
216             loc = _mesa_add_state_reference(prog->Parameters, stateTokens);
217          }
218       } else {
219          loc = st_nir_lookup_parameter_index(prog, uniform);
220 
221          /* We need to check that loc is not -1 here before accessing the
222           * array. It can be negative for example when we have a struct that
223           * only contains opaque types.
224           */
225          if (loc >= 0 && ctx->Const.PackedDriverUniformStorage) {
226             loc = prog->Parameters->Parameters[loc].ValueOffset;
227          }
228       }
229 
230       uniform->data.driver_location = loc;
231    }
232 }
233 
234 static bool
def_is_64bit(nir_def * def,void * state)235 def_is_64bit(nir_def *def, void *state)
236 {
237    bool *lower = (bool *)state;
238    if (def && (def->bit_size == 64)) {
239       *lower = true;
240       return false;
241    }
242    return true;
243 }
244 
245 static bool
src_is_64bit(nir_src * src,void * state)246 src_is_64bit(nir_src *src, void *state)
247 {
248    bool *lower = (bool *)state;
249    if (src && (nir_src_bit_size(*src) == 64)) {
250       *lower = true;
251       return false;
252    }
253    return true;
254 }
255 
256 static bool
filter_64_bit_instr(const nir_instr * const_instr,UNUSED const void * data)257 filter_64_bit_instr(const nir_instr *const_instr, UNUSED const void *data)
258 {
259    bool lower = false;
260    /* lower_alu_to_scalar required nir_instr to be const, but nir_foreach_*
261     * doesn't have const variants, so do the ugly const_cast here. */
262    nir_instr *instr = const_cast<nir_instr *>(const_instr);
263 
264    nir_foreach_def(instr, def_is_64bit, &lower);
265    if (lower)
266       return true;
267    nir_foreach_src(instr, src_is_64bit, &lower);
268    return lower;
269 }
270 
271 /* Second third of converting glsl_to_nir. This creates uniforms, gathers
272  * info on varyings, etc after NIR link time opts have been applied.
273  */
274 static char *
st_glsl_to_nir_post_opts(struct st_context * st,struct gl_program * prog,struct gl_shader_program * shader_program)275 st_glsl_to_nir_post_opts(struct st_context *st, struct gl_program *prog,
276                          struct gl_shader_program *shader_program)
277 {
278    nir_shader *nir = prog->nir;
279    struct pipe_screen *screen = st->screen;
280 
281    /* Make a pass over the IR to add state references for any built-in
282     * uniforms that are used.  This has to be done now (during linking).
283     * Code generation doesn't happen until the first time this shader is
284     * used for rendering.  Waiting until then to generate the parameters is
285     * too late.  At that point, the values for the built-in uniforms won't
286     * get sent to the shader.
287     */
288    nir_foreach_uniform_variable(var, nir) {
289       const nir_state_slot *const slots = var->state_slots;
290       if (slots != NULL) {
291          const struct glsl_type *type = glsl_without_array(var->type);
292          for (unsigned int i = 0; i < var->num_state_slots; i++) {
293             unsigned comps;
294             if (glsl_type_is_struct_or_ifc(type)) {
295                comps = _mesa_program_state_value_size(slots[i].tokens);
296             } else {
297                comps = glsl_get_vector_elements(type);
298             }
299 
300             if (st->ctx->Const.PackedDriverUniformStorage) {
301                _mesa_add_sized_state_reference(prog->Parameters,
302                                                slots[i].tokens,
303                                                comps, false);
304             } else {
305                _mesa_add_state_reference(prog->Parameters,
306                                          slots[i].tokens);
307             }
308          }
309       }
310    }
311 
312    /* Avoid reallocation of the program parameter list, because the uniform
313     * storage is only associated with the original parameter list.
314     * This should be enough for Bitmap and DrawPixels constants.
315     */
316    _mesa_ensure_and_associate_uniform_storage(st->ctx, shader_program, prog, 28);
317 
318    /* None of the builtins being lowered here can be produced by SPIR-V.  See
319     * _mesa_builtin_uniform_desc. Also drivers that support packed uniform
320     * storage don't need to lower builtins.
321     */
322    if (!shader_program->data->spirv &&
323        !st->ctx->Const.PackedDriverUniformStorage)
324       NIR_PASS(_, nir, st_nir_lower_builtin);
325 
326    if (!screen->caps.nir_atomics_as_deref)
327       NIR_PASS(_, nir, gl_nir_lower_atomics, shader_program, true);
328 
329    NIR_PASS(_, nir, nir_opt_intrinsics);
330 
331    /* Lower 64-bit ops. */
332    if (nir->options->lower_int64_options ||
333        nir->options->lower_doubles_options) {
334       bool lowered_64bit_ops = false;
335       bool revectorize = false;
336 
337       if (nir->options->lower_doubles_options) {
338          /* nir_lower_doubles is not prepared for vector ops, so if the backend doesn't
339           * request lower_alu_to_scalar until now, lower all 64 bit ops, and try to
340           * vectorize them afterwards again */
341          if (!nir->options->lower_to_scalar) {
342             NIR_PASS(revectorize, nir, nir_lower_alu_to_scalar, filter_64_bit_instr, nullptr);
343             NIR_PASS(revectorize, nir, nir_lower_phis_to_scalar, false);
344          }
345          /* doubles lowering requires frexp to be lowered first if it will be,
346           * since the pass generates other 64-bit ops.  Most backends lower
347           * frexp, and using doubles is rare, and using frexp is even more rare
348           * (no instances in shader-db), so we're not too worried about
349           * accidentally lowering a 32-bit frexp here.
350           */
351          NIR_PASS(lowered_64bit_ops, nir, nir_lower_frexp);
352 
353          NIR_PASS(lowered_64bit_ops, nir, nir_lower_doubles,
354                   st->ctx->SoftFP64, nir->options->lower_doubles_options);
355       }
356       if (nir->options->lower_int64_options)
357          NIR_PASS(lowered_64bit_ops, nir, nir_lower_int64);
358 
359       if (revectorize && !nir->options->vectorize_vec2_16bit)
360          NIR_PASS(_, nir, nir_opt_vectorize, nullptr, nullptr);
361 
362       if (revectorize || lowered_64bit_ops)
363          gl_nir_opts(nir);
364    }
365 
366    nir_variable_mode mask =
367       nir_var_shader_in | nir_var_shader_out | nir_var_function_temp;
368    nir_remove_dead_variables(nir, mask, NULL);
369 
370    if (!st->has_hw_atomics && !screen->caps.nir_atomics_as_deref) {
371       unsigned align_offset_state = 0;
372       if (st->ctx->Const.ShaderStorageBufferOffsetAlignment > 4) {
373          struct gl_program_parameter_list *params = prog->Parameters;
374          for (unsigned i = 0; i < shader_program->data->NumAtomicBuffers; i++) {
375             gl_state_index16 state[STATE_LENGTH] = { STATE_ATOMIC_COUNTER_OFFSET, (short)shader_program->data->AtomicBuffers[i].Binding };
376             _mesa_add_state_reference(params, state);
377          }
378          align_offset_state = STATE_ATOMIC_COUNTER_OFFSET;
379       }
380       NIR_PASS(_, nir, nir_lower_atomics_to_ssbo, align_offset_state);
381    }
382 
383    st_set_prog_affected_state_flags(prog);
384 
385    st_finalize_nir_before_variants(nir);
386 
387    char *msg = NULL;
388    if (st->allow_st_finalize_nir_twice) {
389       st_serialize_base_nir(prog, nir);
390       st_finalize_nir(st, prog, shader_program, nir, true, false);
391 
392       if (screen->finalize_nir)
393          msg = screen->finalize_nir(screen, nir);
394    }
395 
396    if (st->ctx->_Shader->Flags & GLSL_DUMP) {
397       _mesa_log("\n");
398       _mesa_log("NIR IR for linked %s program %d:\n",
399              _mesa_shader_stage_to_string(prog->info.stage),
400              shader_program->Name);
401       nir_print_shader(nir, mesa_log_get_file());
402       _mesa_log("\n\n");
403    }
404 
405    return msg;
406 }
407 
408 static void
st_nir_vectorize_io(nir_shader * producer,nir_shader * consumer)409 st_nir_vectorize_io(nir_shader *producer, nir_shader *consumer)
410 {
411    if (consumer)
412       NIR_PASS(_, consumer, nir_lower_io_to_vector, nir_var_shader_in);
413 
414    if (!producer)
415       return;
416 
417    NIR_PASS(_, producer, nir_lower_io_to_vector, nir_var_shader_out);
418 
419    if (producer->info.stage == MESA_SHADER_TESS_CTRL &&
420        producer->options->vectorize_tess_levels)
421       NIR_PASS(_, producer, nir_vectorize_tess_levels);
422 
423    NIR_PASS(_, producer, nir_opt_combine_stores, nir_var_shader_out);
424 
425    if ((producer)->info.stage != MESA_SHADER_TESS_CTRL) {
426       /* Calling lower_io_to_vector creates output variable writes with
427        * write-masks.  We only support these for TCS outputs, so for other
428        * stages, we need to call nir_lower_io_to_temporaries to get rid of
429        * them.  This, in turn, creates temporary variables and extra
430        * copy_deref intrinsics that we need to clean up.
431        */
432       NIR_PASS(_, producer, nir_lower_io_to_temporaries,
433                  nir_shader_get_entrypoint(producer), true, false);
434       NIR_PASS(_, producer, nir_lower_global_vars_to_local);
435       NIR_PASS(_, producer, nir_split_var_copies);
436       NIR_PASS(_, producer, nir_lower_var_copies);
437    }
438 
439    /* Undef scalar store_deref intrinsics are not ignored by nir_lower_io,
440     * so they must be removed before that. These passes remove them.
441     */
442    NIR_PASS(_, producer, nir_lower_vars_to_ssa);
443    NIR_PASS(_, producer, nir_opt_undef);
444    NIR_PASS(_, producer, nir_opt_dce);
445 }
446 
447 extern "C" {
448 
449 bool
st_nir_lower_wpos_ytransform(struct nir_shader * nir,struct gl_program * prog,struct pipe_screen * pscreen)450 st_nir_lower_wpos_ytransform(struct nir_shader *nir,
451                              struct gl_program *prog,
452                              struct pipe_screen *pscreen)
453 {
454    bool progress = false;
455 
456    if (nir->info.stage != MESA_SHADER_FRAGMENT) {
457       nir_shader_preserve_all_metadata(nir);
458       return progress;
459    }
460 
461    static const gl_state_index16 wposTransformState[STATE_LENGTH] = {
462       STATE_FB_WPOS_Y_TRANSFORM
463    };
464    nir_lower_wpos_ytransform_options wpos_options = { { 0 } };
465 
466    memcpy(wpos_options.state_tokens, wposTransformState,
467           sizeof(wpos_options.state_tokens));
468    wpos_options.fs_coord_origin_upper_left =
469       pscreen->caps.fs_coord_origin_upper_left;
470    wpos_options.fs_coord_origin_lower_left =
471       pscreen->caps.fs_coord_origin_lower_left;
472    wpos_options.fs_coord_pixel_center_integer =
473       pscreen->caps.fs_coord_pixel_center_integer;
474    wpos_options.fs_coord_pixel_center_half_integer =
475       pscreen->caps.fs_coord_pixel_center_half_integer;
476 
477    if (nir_lower_wpos_ytransform(nir, &wpos_options)) {
478       _mesa_add_state_reference(prog->Parameters, wposTransformState);
479       progress = true;
480    }
481 
482    static const gl_state_index16 pntcTransformState[STATE_LENGTH] = {
483       STATE_FB_PNTC_Y_TRANSFORM
484    };
485 
486    if (nir_lower_pntc_ytransform(nir, &pntcTransformState)) {
487       _mesa_add_state_reference(prog->Parameters, pntcTransformState);
488       progress = true;
489    }
490 
491    return progress;
492 }
493 
494 static bool
st_link_glsl_to_nir(struct gl_context * ctx,struct gl_shader_program * shader_program)495 st_link_glsl_to_nir(struct gl_context *ctx,
496                     struct gl_shader_program *shader_program)
497 {
498    struct st_context *st = st_context(ctx);
499    struct gl_linked_shader *linked_shader[MESA_SHADER_STAGES];
500    unsigned num_shaders = 0;
501 
502    /* Return early if we are loading the shader from on-disk cache */
503    if (st_load_nir_from_disk_cache(ctx, shader_program)) {
504       return GL_TRUE;
505    }
506 
507    MESA_TRACE_FUNC();
508 
509    assert(shader_program->data->LinkStatus);
510 
511    if (!shader_program->data->spirv) {
512       if (!gl_nir_link_glsl(ctx, shader_program))
513          return GL_FALSE;
514    }
515 
516    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
517       if (shader_program->_LinkedShaders[i])
518          linked_shader[num_shaders++] = shader_program->_LinkedShaders[i];
519    }
520 
521    for (unsigned i = 0; i < num_shaders; i++) {
522       struct gl_linked_shader *shader = linked_shader[i];
523       const nir_shader_compiler_options *options =
524          st->ctx->Const.ShaderCompilerOptions[shader->Stage].NirOptions;
525       struct gl_program *prog = shader->Program;
526 
527       shader->Program->info.separate_shader = shader_program->SeparateShader;
528       prog->state.type = PIPE_SHADER_IR_NIR;
529 
530       if (shader_program->data->spirv) {
531          /* Parameters will be filled during NIR linking. */
532          prog->Parameters = _mesa_new_parameter_list();
533          prog->shader_program = shader_program;
534 
535          assert(!prog->nir);
536          prog->nir = _mesa_spirv_to_nir(ctx, shader_program, shader->Stage, options);
537       } else {
538          assert(prog->nir);
539          prog->nir->info.name =
540             ralloc_asprintf(shader, "GLSL%d", shader_program->Name);
541          if (shader_program->Label)
542             prog->nir->info.label = ralloc_strdup(shader, shader_program->Label);
543       }
544 
545       nir_shader_gather_info(prog->nir, nir_shader_get_entrypoint(prog->nir));
546       if (!st->ctx->SoftFP64 && ((prog->nir->info.bit_sizes_int | prog->nir->info.bit_sizes_float) & 64) &&
547           (options->lower_doubles_options & nir_lower_fp64_full_software) != 0) {
548 
549          /* It's not possible to use float64 on GLSL ES, so don't bother trying to
550           * build the support code.  The support code depends on higher versions of
551           * desktop GLSL, so it will fail to compile (below) anyway.
552           */
553          if (_mesa_is_desktop_gl(st->ctx) && st->ctx->Const.GLSLVersion >= 400)
554             st->ctx->SoftFP64 = glsl_float64_funcs_to_nir(st->ctx, options);
555       }
556    }
557 
558    if (shader_program->data->spirv) {
559       static const gl_nir_linker_options opts = {
560          true /*fill_parameters */
561       };
562       if (!gl_nir_link_spirv(&ctx->Const, &ctx->Extensions, shader_program,
563                              &opts))
564          return GL_FALSE;
565    }
566 
567    for (unsigned i = 0; i < num_shaders; i++) {
568       struct gl_program *prog = linked_shader[i]->Program;
569       prog->ExternalSamplersUsed = gl_external_samplers(prog);
570       _mesa_update_shader_textures_used(shader_program, prog);
571    }
572 
573    nir_build_program_resource_list(&ctx->Const, shader_program,
574                                    shader_program->data->spirv);
575 
576    for (unsigned i = 0; i < num_shaders; i++) {
577       struct gl_linked_shader *shader = linked_shader[i];
578       nir_shader *nir = shader->Program->nir;
579       gl_shader_stage stage = shader->Stage;
580       const struct gl_shader_compiler_options *options =
581             &ctx->Const.ShaderCompilerOptions[stage];
582 
583       if (nir->info.io_lowered) {
584          /* Since IO is lowered, we won't need the IO variables from now on.
585           * nir_build_program_resource_list was the last pass that needed them.
586           */
587          NIR_PASS_V(nir, nir_remove_dead_variables,
588                     nir_var_shader_in | nir_var_shader_out, NULL);
589       }
590 
591       /* If there are forms of indirect addressing that the driver
592        * cannot handle, perform the lowering pass.
593        */
594       if (!(nir->options->support_indirect_inputs & BITFIELD_BIT(stage)) ||
595           !(nir->options->support_indirect_outputs & BITFIELD_BIT(stage)) ||
596           options->EmitNoIndirectTemp || options->EmitNoIndirectUniform) {
597          nir_variable_mode mode = (nir_variable_mode)0;
598 
599          if (!nir->info.io_lowered) {
600             mode |= !(nir->options->support_indirect_inputs & BITFIELD_BIT(stage)) ?
601                nir_var_shader_in : (nir_variable_mode)0;
602             mode |= !(nir->options->support_indirect_outputs & BITFIELD_BIT(stage)) ?
603                nir_var_shader_out : (nir_variable_mode)0;
604          }
605          mode |= options->EmitNoIndirectTemp ?
606             nir_var_function_temp : (nir_variable_mode)0;
607          mode |= options->EmitNoIndirectUniform ?
608             nir_var_uniform | nir_var_mem_ubo | nir_var_mem_ssbo :
609             (nir_variable_mode)0;
610 
611          if (mode)
612             nir_lower_indirect_derefs(nir, mode, UINT32_MAX);
613       }
614 
615       /* This needs to run after the initial pass of nir_lower_vars_to_ssa, so
616        * that the buffer indices are constants in nir where they where
617        * constants in GLSL. */
618       NIR_PASS(_, nir, gl_nir_lower_buffers, shader_program);
619 
620       NIR_PASS(_, nir, st_nir_lower_wpos_ytransform, shader->Program,
621                st->screen);
622 
623       /* needed to lower base_workgroup_id and base_global_invocation_id */
624       struct nir_lower_compute_system_values_options cs_options = {};
625       NIR_PASS(_, nir, nir_lower_system_values);
626       NIR_PASS(_, nir, nir_lower_compute_system_values, &cs_options);
627 
628       if (nir->info.io_lowered)
629          continue; /* the rest is for non-lowered IO only */
630 
631       /* Remap the locations to slots so those requiring two slots will occupy
632        * two locations. For instance, if we have in the IR code a dvec3 attr0 in
633        * location 0 and vec4 attr1 in location 1, in NIR attr0 will use
634        * locations/slots 0 and 1, and attr1 will use location/slot 2
635        */
636       if (nir->info.stage == MESA_SHADER_VERTEX && !shader_program->data->spirv)
637          nir_remap_dual_slot_attributes(nir, &shader->Program->DualSlotInputs);
638 
639       if (i >= 1) {
640          struct gl_program *prev_shader = linked_shader[i - 1]->Program;
641 
642          /* We can't use nir_compact_varyings with transform feedback, since
643           * the pipe_stream_output->output_register field is based on the
644           * pre-compacted driver_locations.
645           */
646          if (!(prev_shader->sh.LinkedTransformFeedback &&
647                prev_shader->sh.LinkedTransformFeedback->NumVarying > 0))
648             nir_compact_varyings(prev_shader->nir,
649                                  nir, ctx->API != API_OPENGL_COMPAT);
650 
651          if (ctx->Const.ShaderCompilerOptions[shader->Stage].NirOptions->vectorize_io)
652             st_nir_vectorize_io(prev_shader->nir, nir);
653       }
654    }
655 
656    /* If the program is a separate shader program check if we need to vectorise
657     * the first and last program interfaces too.
658     */
659    if (shader_program->SeparateShader && num_shaders > 0) {
660       struct gl_linked_shader *first_shader = linked_shader[0];
661       struct gl_linked_shader *last_shader = linked_shader[num_shaders - 1];
662       if (first_shader->Stage != MESA_SHADER_COMPUTE) {
663          if (ctx->Const.ShaderCompilerOptions[first_shader->Stage].NirOptions->vectorize_io &&
664              first_shader->Stage > MESA_SHADER_VERTEX)
665             st_nir_vectorize_io(NULL, first_shader->Program->nir);
666 
667          if (ctx->Const.ShaderCompilerOptions[last_shader->Stage].NirOptions->vectorize_io &&
668              last_shader->Stage < MESA_SHADER_FRAGMENT)
669             st_nir_vectorize_io(last_shader->Program->nir, NULL);
670       }
671    }
672 
673    struct shader_info *prev_info = NULL;
674 
675    for (unsigned i = 0; i < num_shaders; i++) {
676       struct gl_linked_shader *shader = linked_shader[i];
677       struct shader_info *info = &shader->Program->nir->info;
678 
679       char *msg = st_glsl_to_nir_post_opts(st, shader->Program, shader_program);
680       if (msg) {
681          linker_error(shader_program, msg);
682          return false;
683       }
684 
685       if (prev_info &&
686           ctx->Const.ShaderCompilerOptions[shader->Stage].NirOptions->unify_interfaces) {
687          prev_info->outputs_written |= info->inputs_read &
688             ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
689          info->inputs_read |= prev_info->outputs_written &
690             ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
691 
692          prev_info->patch_outputs_written |= info->patch_inputs_read;
693          info->patch_inputs_read |= prev_info->patch_outputs_written;
694       }
695       prev_info = info;
696    }
697 
698    /* Get TCS and TES shader info. */
699    struct shader_info *tcs_info = NULL, *tes_info = NULL;
700 
701    for (unsigned i = 0; i < num_shaders; i++) {
702       struct gl_linked_shader *shader = linked_shader[i];
703       struct shader_info *info = &shader->Program->nir->info;
704 
705       if (info->stage == MESA_SHADER_TESS_CTRL)
706          tcs_info = info;
707       else if (info->stage == MESA_SHADER_TESS_EVAL)
708          tes_info = info;
709    }
710 
711    /* Copy some fields from TES to TCS shader info because some drivers
712     * (radeonsi) need them in TCS.
713     */
714    if (tcs_info && tes_info) {
715       tcs_info->tess._primitive_mode = tes_info->tess._primitive_mode;
716       tcs_info->tess.spacing = tes_info->tess.spacing;
717    }
718 
719    for (unsigned i = 0; i < num_shaders; i++) {
720       struct gl_linked_shader *shader = linked_shader[i];
721       struct gl_program *prog = shader->Program;
722 
723       /* Make sure that prog->info is in sync with nir->info, but st/mesa
724        * expects some of the values to be from before lowering.
725        */
726       shader_info old_info = prog->info;
727       prog->info = prog->nir->info;
728       prog->info.name = old_info.name;
729       prog->info.label = old_info.label;
730       prog->info.num_ssbos = old_info.num_ssbos;
731       prog->info.num_ubos = old_info.num_ubos;
732       prog->info.num_abos = old_info.num_abos;
733 
734       if (prog->info.stage == MESA_SHADER_VERTEX) {
735          if (prog->nir->info.io_lowered) {
736             prog->info.inputs_read = prog->nir->info.inputs_read;
737             prog->DualSlotInputs = prog->nir->info.dual_slot_inputs;
738          } else {
739             /* NIR expands dual-slot inputs out to two locations.  We need to
740              * compact things back down GL-style single-slot inputs to avoid
741              * confusing the state tracker.
742              */
743             prog->info.inputs_read =
744                nir_get_single_slot_attribs_mask(prog->nir->info.inputs_read,
745                                                 prog->DualSlotInputs);
746          }
747 
748          /* Initialize st_vertex_program members. */
749          st_prepare_vertex_program(prog);
750       }
751 
752       /* Get pipe_stream_output_info. */
753       if (shader->Stage == MESA_SHADER_VERTEX ||
754           shader->Stage == MESA_SHADER_TESS_EVAL ||
755           shader->Stage == MESA_SHADER_GEOMETRY)
756          st_translate_stream_output_info(prog);
757 
758       st_store_nir_in_disk_cache(st, prog);
759 
760       st_release_variants(st, prog);
761       st_finalize_program(st, prog);
762    }
763 
764    struct pipe_context *pctx = st_context(ctx)->pipe;
765    if (pctx->link_shader) {
766       void *driver_handles[PIPE_SHADER_TYPES];
767       memset(driver_handles, 0, sizeof(driver_handles));
768 
769       for (uint32_t i = 0; i < MESA_SHADER_STAGES; ++i) {
770          struct gl_linked_shader *shader = shader_program->_LinkedShaders[i];
771          if (shader) {
772             struct gl_program *p = shader->Program;
773             if (p && p->variants) {
774                enum pipe_shader_type type = pipe_shader_type_from_mesa(shader->Stage);
775                driver_handles[type] = p->variants->driver_shader;
776             }
777          }
778       }
779 
780       pctx->link_shader(pctx, driver_handles);
781    }
782 
783    return true;
784 }
785 
786 void
st_nir_assign_varying_locations(struct st_context * st,nir_shader * nir)787 st_nir_assign_varying_locations(struct st_context *st, nir_shader *nir)
788 {
789    /* Lowered IO don't have variables, so exit. */
790    if (nir->info.io_lowered)
791       return;
792 
793    if (nir->info.stage == MESA_SHADER_VERTEX) {
794       nir_assign_io_var_locations(nir, nir_var_shader_out,
795                                   &nir->num_outputs,
796                                   nir->info.stage);
797       st_nir_fixup_varying_slots(st, nir, nir_var_shader_out);
798    } else if (nir->info.stage == MESA_SHADER_GEOMETRY ||
799               nir->info.stage == MESA_SHADER_TESS_CTRL ||
800               nir->info.stage == MESA_SHADER_TESS_EVAL) {
801       nir_assign_io_var_locations(nir, nir_var_shader_in,
802                                   &nir->num_inputs,
803                                   nir->info.stage);
804       st_nir_fixup_varying_slots(st, nir, nir_var_shader_in);
805 
806       nir_assign_io_var_locations(nir, nir_var_shader_out,
807                                   &nir->num_outputs,
808                                   nir->info.stage);
809       st_nir_fixup_varying_slots(st, nir, nir_var_shader_out);
810    } else if (nir->info.stage == MESA_SHADER_FRAGMENT) {
811       nir_assign_io_var_locations(nir, nir_var_shader_in,
812                                   &nir->num_inputs,
813                                   nir->info.stage);
814       st_nir_fixup_varying_slots(st, nir, nir_var_shader_in);
815       nir_assign_io_var_locations(nir, nir_var_shader_out,
816                                   &nir->num_outputs,
817                                   nir->info.stage);
818    } else if (nir->info.stage == MESA_SHADER_COMPUTE) {
819        /* TODO? */
820    } else {
821       unreachable("invalid shader type");
822    }
823 }
824 
825 void
st_nir_lower_samplers(struct pipe_screen * screen,nir_shader * nir,struct gl_shader_program * shader_program,struct gl_program * prog)826 st_nir_lower_samplers(struct pipe_screen *screen, nir_shader *nir,
827                       struct gl_shader_program *shader_program,
828                       struct gl_program *prog)
829 {
830    if (screen->caps.nir_samplers_as_deref)
831       NIR_PASS(_, nir, gl_nir_lower_samplers_as_deref, shader_program);
832    else
833       NIR_PASS(_, nir, gl_nir_lower_samplers, shader_program);
834 
835    if (prog) {
836       BITSET_COPY(prog->info.textures_used, nir->info.textures_used);
837       BITSET_COPY(prog->info.textures_used_by_txf, nir->info.textures_used_by_txf);
838       BITSET_COPY(prog->info.samplers_used, nir->info.samplers_used);
839       BITSET_COPY(prog->info.images_used, nir->info.images_used);
840       BITSET_COPY(prog->info.image_buffers, nir->info.image_buffers);
841       BITSET_COPY(prog->info.msaa_images, nir->info.msaa_images);
842    }
843 }
844 
845 static int
st_packed_uniforms_type_size(const struct glsl_type * type,bool bindless)846 st_packed_uniforms_type_size(const struct glsl_type *type, bool bindless)
847 {
848    return glsl_count_dword_slots(type, bindless);
849 }
850 
851 static int
st_unpacked_uniforms_type_size(const struct glsl_type * type,bool bindless)852 st_unpacked_uniforms_type_size(const struct glsl_type *type, bool bindless)
853 {
854    return glsl_count_vec4_slots(type, false, bindless);
855 }
856 
857 void
st_nir_lower_uniforms(struct st_context * st,nir_shader * nir)858 st_nir_lower_uniforms(struct st_context *st, nir_shader *nir)
859 {
860    if (st->ctx->Const.PackedDriverUniformStorage) {
861       NIR_PASS(_, nir, nir_lower_io, nir_var_uniform,
862                  st_packed_uniforms_type_size,
863                  (nir_lower_io_options)0);
864    } else {
865       NIR_PASS(_, nir, nir_lower_io, nir_var_uniform,
866                  st_unpacked_uniforms_type_size,
867                  (nir_lower_io_options)0);
868    }
869 
870    if (nir->options->lower_uniforms_to_ubo)
871       NIR_PASS(_, nir, nir_lower_uniforms_to_ubo,
872                  st->ctx->Const.PackedDriverUniformStorage,
873                  !st->ctx->Const.NativeIntegers);
874 }
875 
876 /* Last third of preparing nir from glsl, which happens after shader
877  * variant lowering.
878  */
879 void
st_finalize_nir(struct st_context * st,struct gl_program * prog,struct gl_shader_program * shader_program,nir_shader * nir,bool is_before_variants,bool is_draw_shader)880 st_finalize_nir(struct st_context *st, struct gl_program *prog,
881                 struct gl_shader_program *shader_program, nir_shader *nir,
882                 bool is_before_variants, bool is_draw_shader)
883 {
884    struct pipe_screen *screen = st->screen;
885 
886    MESA_TRACE_FUNC();
887 
888    NIR_PASS(_, nir, nir_split_var_copies);
889    NIR_PASS(_, nir, nir_lower_var_copies);
890 
891    const bool lower_tg4_offsets =
892       !is_draw_shader && !st->screen->caps.texture_gather_offsets;
893 
894    if (!is_draw_shader && (st->lower_rect_tex || lower_tg4_offsets)) {
895       struct nir_lower_tex_options opts = {0};
896       opts.lower_rect = !!st->lower_rect_tex;
897       opts.lower_tg4_offsets = lower_tg4_offsets;
898 
899       NIR_PASS(_, nir, nir_lower_tex, &opts);
900    }
901 
902    st_nir_assign_varying_locations(st, nir);
903    st_nir_assign_uniform_locations(st->ctx, prog, nir);
904 
905    /* Set num_uniforms in number of attribute slots (vec4s) */
906    nir->num_uniforms = DIV_ROUND_UP(prog->Parameters->NumParameterValues, 4);
907 
908    st_nir_lower_uniforms(st, nir);
909 
910    if (!is_draw_shader && is_before_variants && nir->options->lower_uniforms_to_ubo) {
911       /* This must be done after uniforms are lowered to UBO and all
912        * nir_var_uniform variables are removed from NIR to prevent conflicts
913        * between state parameter merging and shader variant generation.
914        */
915       _mesa_optimize_state_parameters(&st->ctx->Const, prog->Parameters);
916    }
917 
918    st_nir_lower_samplers(screen, nir, shader_program, prog);
919    if (!is_draw_shader && !screen->caps.nir_images_as_deref)
920       NIR_PASS(_, nir, gl_nir_lower_images, false);
921 }
922 
923 /**
924  * Link a GLSL shader program.  Called via glLinkProgram().
925  */
926 void
st_link_shader(struct gl_context * ctx,struct gl_shader_program * prog)927 st_link_shader(struct gl_context *ctx, struct gl_shader_program *prog)
928 {
929    unsigned int i;
930    bool spirv = false;
931 
932    MESA_TRACE_FUNC();
933 
934    _mesa_clear_shader_program_data(ctx, prog);
935 
936    prog->data = _mesa_create_shader_program_data();
937 
938    prog->data->LinkStatus = LINKING_SUCCESS;
939 
940    for (i = 0; i < prog->NumShaders; i++) {
941       if (!prog->Shaders[i]->CompileStatus) {
942 	 linker_error(prog, "linking with uncompiled/unspecialized shader");
943       }
944 
945       if (!i) {
946          spirv = (prog->Shaders[i]->spirv_data != NULL);
947       } else if (spirv && !prog->Shaders[i]->spirv_data) {
948          /* The GL_ARB_gl_spirv spec adds a new bullet point to the list of
949           * reasons LinkProgram can fail:
950           *
951           *    "All the shader objects attached to <program> do not have the
952           *     same value for the SPIR_V_BINARY_ARB state."
953           */
954          linker_error(prog,
955                       "not all attached shaders have the same "
956                       "SPIR_V_BINARY_ARB state");
957       }
958    }
959    prog->data->spirv = spirv;
960 
961    if (prog->data->LinkStatus) {
962       if (!spirv) {
963          link_shaders_init(ctx, prog);
964 
965 #ifdef ENABLE_SHADER_CACHE
966          shader_cache_read_program_metadata(ctx, prog);
967 #endif
968       } else
969          _mesa_spirv_link_shaders(ctx, prog);
970    }
971 
972    /* If LinkStatus is LINKING_SUCCESS, then reset sampler validated to true.
973     * Validation happens via the LinkShader call below. If LinkStatus is
974     * LINKING_SKIPPED, then SamplersValidated will have been restored from the
975     * shader cache.
976     */
977    if (prog->data->LinkStatus == LINKING_SUCCESS) {
978       prog->SamplersValidated = GL_TRUE;
979    }
980 
981    if (prog->data->LinkStatus && !st_link_glsl_to_nir(ctx, prog)) {
982       prog->data->LinkStatus = LINKING_FAILURE;
983    }
984 
985    if (prog->data->LinkStatus != LINKING_FAILURE)
986       _mesa_create_program_resource_hash(prog);
987 
988    /* Return early if we are loading the shader from on-disk cache */
989    if (prog->data->LinkStatus == LINKING_SKIPPED)
990       return;
991 
992    if (ctx->_Shader->Flags & GLSL_DUMP) {
993       if (!prog->data->LinkStatus) {
994 	 fprintf(stderr, "GLSL shader program %d failed to link\n", prog->Name);
995       }
996 
997       if (prog->data->InfoLog && prog->data->InfoLog[0] != 0) {
998 	 fprintf(stderr, "GLSL shader program %d info log:\n", prog->Name);
999          fprintf(stderr, "%s\n", prog->data->InfoLog);
1000       }
1001    }
1002 
1003 #ifdef ENABLE_SHADER_CACHE
1004    if (prog->data->LinkStatus)
1005       shader_cache_write_program_metadata(ctx, prog);
1006 #endif
1007 }
1008 
1009 } /* extern "C" */
1010