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