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