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