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