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