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