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 "main/context.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_program.h"
43 #include "st_shader_cache.h"
44
45 #include "compiler/nir/nir.h"
46 #include "compiler/nir/nir_builder.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/linker_util.h"
54 #include "compiler/glsl/string_to_uint_map.h"
55
56 static int
type_size(const struct glsl_type * type)57 type_size(const struct glsl_type *type)
58 {
59 return type->count_attribute_slots(false);
60 }
61
62 /* Depending on PIPE_CAP_TGSI_TEXCOORD (st->needs_texcoord_semantic) we
63 * may need to fix up varying slots so the glsl->nir path is aligned
64 * with the anything->tgsi->nir path.
65 */
66 static void
st_nir_fixup_varying_slots(struct st_context * st,nir_shader * shader,nir_variable_mode mode)67 st_nir_fixup_varying_slots(struct st_context *st, nir_shader *shader,
68 nir_variable_mode mode)
69 {
70 if (st->needs_texcoord_semantic)
71 return;
72
73 /* This is called from finalize, but we don't want to do this adjustment twice. */
74 assert(!st->allow_st_finalize_nir_twice);
75
76 nir_foreach_variable_with_modes(var, shader, mode) {
77 if (var->data.location >= VARYING_SLOT_VAR0 && var->data.location < VARYING_SLOT_PATCH0) {
78 var->data.location += 9;
79 } else if (var->data.location == VARYING_SLOT_PNTC) {
80 var->data.location = VARYING_SLOT_VAR8;
81 } else if ((var->data.location >= VARYING_SLOT_TEX0) &&
82 (var->data.location <= VARYING_SLOT_TEX7)) {
83 var->data.location += VARYING_SLOT_VAR0 - VARYING_SLOT_TEX0;
84 }
85 }
86 }
87
88 /* input location assignment for VS inputs must be handled specially, so
89 * that it is aligned w/ st's vbo state.
90 * (This isn't the case with, for ex, FS inputs, which only need to agree
91 * on varying-slot w/ the VS outputs)
92 */
93 void
st_nir_assign_vs_in_locations(struct nir_shader * nir)94 st_nir_assign_vs_in_locations(struct nir_shader *nir)
95 {
96 if (nir->info.stage != MESA_SHADER_VERTEX || nir->info.io_lowered)
97 return;
98
99 nir->num_inputs = util_bitcount64(nir->info.inputs_read);
100
101 bool removed_inputs = false;
102
103 nir_foreach_shader_in_variable_safe(var, nir) {
104 /* NIR already assigns dual-slot inputs to two locations so all we have
105 * to do is compact everything down.
106 */
107 if (nir->info.inputs_read & BITFIELD64_BIT(var->data.location)) {
108 var->data.driver_location =
109 util_bitcount64(nir->info.inputs_read &
110 BITFIELD64_MASK(var->data.location));
111 } else {
112 /* Convert unused input variables to shader_temp (with no
113 * initialization), to avoid confusing drivers looking through the
114 * inputs array and expecting to find inputs with a driver_location
115 * set.
116 */
117 var->data.mode = nir_var_shader_temp;
118 removed_inputs = true;
119 }
120 }
121
122 /* Re-lower global vars, to deal with any dead VS inputs. */
123 if (removed_inputs)
124 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
125 }
126
127 static int
st_nir_lookup_parameter_index(struct gl_program * prog,nir_variable * var)128 st_nir_lookup_parameter_index(struct gl_program *prog, nir_variable *var)
129 {
130 struct gl_program_parameter_list *params = prog->Parameters;
131
132 /* Lookup the first parameter that the uniform storage that match the
133 * variable location.
134 */
135 for (unsigned i = 0; i < params->NumParameters; i++) {
136 int index = params->Parameters[i].MainUniformStorageIndex;
137 if (index == var->data.location)
138 return i;
139 }
140
141 /* TODO: Handle this fallback for SPIR-V. We need this for GLSL e.g. in
142 * dEQP-GLES2.functional.uniform_api.random.3
143 */
144
145 /* is there a better way to do this? If we have something like:
146 *
147 * struct S {
148 * float f;
149 * vec4 v;
150 * };
151 * uniform S color;
152 *
153 * Then what we get in prog->Parameters looks like:
154 *
155 * 0: Name=color.f, Type=6, DataType=1406, Size=1
156 * 1: Name=color.v, Type=6, DataType=8b52, Size=4
157 *
158 * So the name doesn't match up and _mesa_lookup_parameter_index()
159 * fails. In this case just find the first matching "color.*"..
160 *
161 * Note for arrays you could end up w/ color[n].f, for example.
162 */
163 if (!prog->sh.data->spirv) {
164 int namelen = strlen(var->name);
165 for (unsigned i = 0; i < params->NumParameters; i++) {
166 struct gl_program_parameter *p = ¶ms->Parameters[i];
167 if ((strncmp(p->Name, var->name, namelen) == 0) &&
168 ((p->Name[namelen] == '.') || (p->Name[namelen] == '['))) {
169 return i;
170 }
171 }
172 }
173
174 return -1;
175 }
176
177 static void
st_nir_assign_uniform_locations(struct gl_context * ctx,struct gl_program * prog,nir_shader * nir)178 st_nir_assign_uniform_locations(struct gl_context *ctx,
179 struct gl_program *prog,
180 nir_shader *nir)
181 {
182 int shaderidx = 0;
183 int imageidx = 0;
184
185 nir_foreach_variable_with_modes(uniform, nir, nir_var_uniform |
186 nir_var_image) {
187 int loc;
188
189 const struct glsl_type *type = glsl_without_array(uniform->type);
190 if (!uniform->data.bindless && (type->is_sampler() || type->is_image())) {
191 if (type->is_sampler()) {
192 loc = shaderidx;
193 shaderidx += type_size(uniform->type);
194 } else {
195 loc = imageidx;
196 imageidx += type_size(uniform->type);
197 }
198 } else if (uniform->state_slots) {
199 const gl_state_index16 *const stateTokens = uniform->state_slots[0].tokens;
200
201 unsigned comps;
202 if (glsl_type_is_struct_or_ifc(type)) {
203 comps = 4;
204 } else {
205 comps = glsl_get_vector_elements(type);
206 }
207
208 if (ctx->Const.PackedDriverUniformStorage) {
209 loc = _mesa_add_sized_state_reference(prog->Parameters,
210 stateTokens, comps, false);
211 loc = prog->Parameters->Parameters[loc].ValueOffset;
212 } else {
213 loc = _mesa_add_state_reference(prog->Parameters, stateTokens);
214 }
215 } else {
216 loc = st_nir_lookup_parameter_index(prog, uniform);
217
218 /* We need to check that loc is not -1 here before accessing the
219 * array. It can be negative for example when we have a struct that
220 * only contains opaque types.
221 */
222 if (loc >= 0 && ctx->Const.PackedDriverUniformStorage) {
223 loc = prog->Parameters->Parameters[loc].ValueOffset;
224 }
225 }
226
227 uniform->data.driver_location = loc;
228 }
229 }
230
231 /* - create a gl_PointSizeMESA variable
232 * - find every gl_Position write
233 * - store 1.0 to gl_PointSizeMESA after every gl_Position write
234 */
235 void
st_nir_add_point_size(nir_shader * nir)236 st_nir_add_point_size(nir_shader *nir)
237 {
238 nir_variable *psiz = nir_variable_create(nir, nir_var_shader_out, glsl_float_type(), "gl_PointSizeMESA");
239 psiz->data.location = VARYING_SLOT_PSIZ;
240 psiz->data.how_declared = nir_var_hidden;
241
242 nir_builder b;
243 nir_function_impl *impl = nir_shader_get_entrypoint(nir);
244 nir_builder_init(&b, impl);
245 bool found = false;
246 nir_foreach_block_safe(block, impl) {
247 nir_foreach_instr_safe(instr, block) {
248 if (instr->type == nir_instr_type_intrinsic) {
249 nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
250 if (intr->intrinsic == nir_intrinsic_store_deref ||
251 intr->intrinsic == nir_intrinsic_copy_deref) {
252 nir_variable *var = nir_intrinsic_get_var(intr, 0);
253 if (var->data.location == VARYING_SLOT_POS) {
254 b.cursor = nir_after_instr(instr);
255 nir_deref_instr *deref = nir_build_deref_var(&b, psiz);
256 nir_store_deref(&b, deref, nir_imm_float(&b, 1.0), BITFIELD_BIT(0));
257 found = true;
258 }
259 }
260 }
261 }
262 }
263 if (!found) {
264 b.cursor = nir_before_cf_list(&impl->body);
265 nir_deref_instr *deref = nir_build_deref_var(&b, psiz);
266 nir_store_deref(&b, deref, nir_imm_float(&b, 1.0), BITFIELD_BIT(0));
267 }
268 }
269
270 static void
shared_type_info(const struct glsl_type * type,unsigned * size,unsigned * align)271 shared_type_info(const struct glsl_type *type, unsigned *size, unsigned *align)
272 {
273 assert(glsl_type_is_vector_or_scalar(type));
274
275 uint32_t comp_size = glsl_type_is_boolean(type)
276 ? 4 : glsl_get_bit_size(type) / 8;
277 unsigned length = glsl_get_vector_elements(type);
278 *size = comp_size * length,
279 *align = comp_size * (length == 3 ? 4 : length);
280 }
281
282 static bool
st_can_remove_varying_before_linking(nir_variable * var,void * data)283 st_can_remove_varying_before_linking(nir_variable *var, void *data)
284 {
285 bool *is_sso = (bool *) data;
286 if (*is_sso) {
287 /* Allow the removal of unused builtins in SSO */
288 return var->data.location > -1 && var->data.location < VARYING_SLOT_VAR0;
289 } else
290 return true;
291 }
292
293 static void
zero_array_members(nir_builder * b,nir_variable * var)294 zero_array_members(nir_builder *b, nir_variable *var)
295 {
296 nir_deref_instr *deref = nir_build_deref_var(b, var);
297 nir_ssa_def *zero = nir_imm_zero(b, 4, 32);
298 for (int i = 0; i < glsl_array_size(var->type); i++) {
299 nir_deref_instr *arr = nir_build_deref_array_imm(b, deref, i);
300 uint32_t mask = BITFIELD_MASK(glsl_get_vector_elements(arr->type));
301 nir_store_deref(b, arr, nir_channels(b, zero, mask), mask);
302 }
303 }
304
305 /* GL has an implicit default of 0 for unwritten gl_ClipDistance members;
306 * to achieve this, write 0 to all members at the start of the shader and
307 * let them be naturally overwritten later
308 */
309 static bool
st_nir_zero_initialize_clip_distance(nir_shader * nir)310 st_nir_zero_initialize_clip_distance(nir_shader *nir)
311 {
312 nir_variable *clip_dist0 = nir_find_variable_with_location(nir, nir_var_shader_out, VARYING_SLOT_CLIP_DIST0);
313 nir_variable *clip_dist1 = nir_find_variable_with_location(nir, nir_var_shader_out, VARYING_SLOT_CLIP_DIST1);
314 if (!clip_dist0 && !clip_dist1)
315 return false;
316 nir_builder b;
317 nir_function_impl *impl = nir_shader_get_entrypoint(nir);
318 nir_builder_init(&b, impl);
319 b.cursor = nir_before_block(nir_start_block(impl));
320 if (clip_dist0)
321 zero_array_members(&b, clip_dist0);
322 if (clip_dist1)
323 zero_array_members(&b, clip_dist1);
324 return true;
325 }
326
327 /* First third of converting glsl_to_nir.. this leaves things in a pre-
328 * nir_lower_io state, so that shader variants can more easily insert/
329 * replace variables, etc.
330 */
331 static void
st_nir_preprocess(struct st_context * st,struct gl_program * prog,struct gl_shader_program * shader_program,gl_shader_stage stage)332 st_nir_preprocess(struct st_context *st, struct gl_program *prog,
333 struct gl_shader_program *shader_program,
334 gl_shader_stage stage)
335 {
336 struct pipe_screen *screen = st->screen;
337 const nir_shader_compiler_options *options =
338 st->ctx->Const.ShaderCompilerOptions[prog->info.stage].NirOptions;
339 assert(options);
340 nir_shader *nir = prog->nir;
341
342 /* Set the next shader stage hint for VS and TES. */
343 if (!nir->info.separate_shader &&
344 (nir->info.stage == MESA_SHADER_VERTEX ||
345 nir->info.stage == MESA_SHADER_TESS_EVAL)) {
346
347 unsigned prev_stages = (1 << (prog->info.stage + 1)) - 1;
348 unsigned stages_mask =
349 ~prev_stages & shader_program->data->linked_stages;
350
351 nir->info.next_stage = stages_mask ?
352 (gl_shader_stage) u_bit_scan(&stages_mask) : MESA_SHADER_FRAGMENT;
353 } else {
354 nir->info.next_stage = MESA_SHADER_FRAGMENT;
355 }
356
357 nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
358 if (!st->ctx->SoftFP64 && ((nir->info.bit_sizes_int | nir->info.bit_sizes_float) & 64) &&
359 (options->lower_doubles_options & nir_lower_fp64_full_software) != 0) {
360
361 /* It's not possible to use float64 on GLSL ES, so don't bother trying to
362 * build the support code. The support code depends on higher versions of
363 * desktop GLSL, so it will fail to compile (below) anyway.
364 */
365 if (_mesa_is_desktop_gl(st->ctx) && st->ctx->Const.GLSLVersion >= 400)
366 st->ctx->SoftFP64 = glsl_float64_funcs_to_nir(st->ctx, options);
367 }
368
369 prog->skip_pointsize_xfb = !(nir->info.outputs_written & VARYING_BIT_PSIZ);
370 if (st->lower_point_size && prog->skip_pointsize_xfb &&
371 stage < MESA_SHADER_FRAGMENT && stage != MESA_SHADER_TESS_CTRL &&
372 st_can_add_pointsize_to_program(st, prog)) {
373 NIR_PASS_V(nir, st_nir_add_point_size);
374 }
375
376 if (stage < MESA_SHADER_FRAGMENT && stage != MESA_SHADER_TESS_CTRL &&
377 (nir->info.outputs_written & (VARYING_BIT_CLIP_DIST0 | VARYING_BIT_CLIP_DIST1)))
378 NIR_PASS_V(nir, st_nir_zero_initialize_clip_distance);
379
380 struct nir_remove_dead_variables_options opts;
381 bool is_sso = nir->info.separate_shader;
382 opts.can_remove_var_data = &is_sso;
383 opts.can_remove_var = &st_can_remove_varying_before_linking;
384 nir_variable_mode mask = nir_var_shader_in | nir_var_shader_out;
385 nir_remove_dead_variables(nir, mask, &opts);
386
387 if (options->lower_all_io_to_temps ||
388 nir->info.stage == MESA_SHADER_VERTEX ||
389 nir->info.stage == MESA_SHADER_GEOMETRY) {
390 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
391 nir_shader_get_entrypoint(nir),
392 true, true);
393 } else if (nir->info.stage == MESA_SHADER_FRAGMENT ||
394 !screen->get_param(screen, PIPE_CAP_SHADER_CAN_READ_OUTPUTS)) {
395 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
396 nir_shader_get_entrypoint(nir),
397 true, false);
398 }
399
400 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
401 NIR_PASS_V(nir, nir_split_var_copies);
402 NIR_PASS_V(nir, nir_lower_var_copies);
403
404 if (options->lower_to_scalar) {
405 NIR_PASS_V(nir, nir_lower_alu_to_scalar,
406 options->lower_to_scalar_filter, NULL);
407 }
408
409 /* before buffers and vars_to_ssa */
410 NIR_PASS_V(nir, gl_nir_lower_images, true);
411
412 if (prog->nir->info.stage == MESA_SHADER_COMPUTE) {
413 NIR_PASS_V(prog->nir, nir_lower_vars_to_explicit_types,
414 nir_var_mem_shared, shared_type_info);
415 NIR_PASS_V(prog->nir, nir_lower_explicit_io,
416 nir_var_mem_shared, nir_address_format_32bit_offset);
417 }
418
419 /* Do a round of constant folding to clean up address calculations */
420 NIR_PASS_V(nir, nir_opt_constant_folding);
421 }
422
423 static bool
dest_is_64bit(nir_dest * dest,void * state)424 dest_is_64bit(nir_dest *dest, void *state)
425 {
426 bool *lower = (bool *)state;
427 if (dest && (nir_dest_bit_size(*dest) == 64)) {
428 *lower = true;
429 return false;
430 }
431 return true;
432 }
433
434 static bool
src_is_64bit(nir_src * src,void * state)435 src_is_64bit(nir_src *src, void *state)
436 {
437 bool *lower = (bool *)state;
438 if (src && (nir_src_bit_size(*src) == 64)) {
439 *lower = true;
440 return false;
441 }
442 return true;
443 }
444
445 static bool
filter_64_bit_instr(const nir_instr * const_instr,UNUSED const void * data)446 filter_64_bit_instr(const nir_instr *const_instr, UNUSED const void *data)
447 {
448 bool lower = false;
449 /* lower_alu_to_scalar required nir_instr to be const, but nir_foreach_*
450 * doesn't have const variants, so do the ugly const_cast here. */
451 nir_instr *instr = const_cast<nir_instr *>(const_instr);
452
453 nir_foreach_dest(instr, dest_is_64bit, &lower);
454 if (lower)
455 return true;
456 nir_foreach_src(instr, src_is_64bit, &lower);
457 return lower;
458 }
459
460 /* Second third of converting glsl_to_nir. This creates uniforms, gathers
461 * info on varyings, etc after NIR link time opts have been applied.
462 */
463 static char *
st_glsl_to_nir_post_opts(struct st_context * st,struct gl_program * prog,struct gl_shader_program * shader_program)464 st_glsl_to_nir_post_opts(struct st_context *st, struct gl_program *prog,
465 struct gl_shader_program *shader_program)
466 {
467 nir_shader *nir = prog->nir;
468 struct pipe_screen *screen = st->screen;
469
470 /* Make a pass over the IR to add state references for any built-in
471 * uniforms that are used. This has to be done now (during linking).
472 * Code generation doesn't happen until the first time this shader is
473 * used for rendering. Waiting until then to generate the parameters is
474 * too late. At that point, the values for the built-in uniforms won't
475 * get sent to the shader.
476 */
477 nir_foreach_uniform_variable(var, nir) {
478 const nir_state_slot *const slots = var->state_slots;
479 if (slots != NULL) {
480 const struct glsl_type *type = glsl_without_array(var->type);
481 for (unsigned int i = 0; i < var->num_state_slots; i++) {
482 unsigned comps;
483 if (glsl_type_is_struct_or_ifc(type)) {
484 comps = _mesa_program_state_value_size(slots[i].tokens);
485 } else {
486 comps = glsl_get_vector_elements(type);
487 }
488
489 if (st->ctx->Const.PackedDriverUniformStorage) {
490 _mesa_add_sized_state_reference(prog->Parameters,
491 slots[i].tokens,
492 comps, false);
493 } else {
494 _mesa_add_state_reference(prog->Parameters,
495 slots[i].tokens);
496 }
497 }
498 }
499 }
500
501 /* Avoid reallocation of the program parameter list, because the uniform
502 * storage is only associated with the original parameter list.
503 * This should be enough for Bitmap and DrawPixels constants.
504 */
505 _mesa_ensure_and_associate_uniform_storage(st->ctx, shader_program, prog, 28);
506
507 /* None of the builtins being lowered here can be produced by SPIR-V. See
508 * _mesa_builtin_uniform_desc. Also drivers that support packed uniform
509 * storage don't need to lower builtins.
510 */
511 if (!shader_program->data->spirv &&
512 !st->ctx->Const.PackedDriverUniformStorage)
513 NIR_PASS_V(nir, st_nir_lower_builtin);
514
515 if (!screen->get_param(screen, PIPE_CAP_NIR_ATOMICS_AS_DEREF))
516 NIR_PASS_V(nir, gl_nir_lower_atomics, shader_program, true);
517
518 NIR_PASS_V(nir, nir_opt_intrinsics);
519 NIR_PASS_V(nir, nir_opt_fragdepth);
520
521 /* Lower 64-bit ops. */
522 if (nir->options->lower_int64_options ||
523 nir->options->lower_doubles_options) {
524 bool lowered_64bit_ops = false;
525 bool revectorize = false;
526
527 if (nir->options->lower_doubles_options) {
528 /* nir_lower_doubles is not prepared for vector ops, so if the backend doesn't
529 * request lower_alu_to_scalar until now, lower all 64 bit ops, and try to
530 * vectorize them afterwards again */
531 if (!nir->options->lower_to_scalar) {
532 NIR_PASS(revectorize, nir, nir_lower_alu_to_scalar, filter_64_bit_instr, nullptr);
533 NIR_PASS(revectorize, nir, nir_lower_phis_to_scalar, false);
534 }
535 NIR_PASS(lowered_64bit_ops, nir, nir_lower_doubles,
536 st->ctx->SoftFP64, nir->options->lower_doubles_options);
537 }
538 if (nir->options->lower_int64_options)
539 NIR_PASS(lowered_64bit_ops, nir, nir_lower_int64);
540
541 if (revectorize && !nir->options->vectorize_vec2_16bit)
542 NIR_PASS_V(nir, nir_opt_vectorize, nullptr, nullptr);
543
544 if (revectorize || lowered_64bit_ops)
545 gl_nir_opts(nir);
546 }
547
548 nir_variable_mode mask =
549 nir_var_shader_in | nir_var_shader_out | nir_var_function_temp;
550 nir_remove_dead_variables(nir, mask, NULL);
551
552 if (!st->has_hw_atomics && !screen->get_param(screen, PIPE_CAP_NIR_ATOMICS_AS_DEREF)) {
553 unsigned align_offset_state = 0;
554 if (st->ctx->Const.ShaderStorageBufferOffsetAlignment > 4) {
555 struct gl_program_parameter_list *params = prog->Parameters;
556 for (unsigned i = 0; i < shader_program->data->NumAtomicBuffers; i++) {
557 gl_state_index16 state[STATE_LENGTH] = { STATE_ATOMIC_COUNTER_OFFSET, (short)shader_program->data->AtomicBuffers[i].Binding };
558 _mesa_add_state_reference(params, state);
559 }
560 align_offset_state = STATE_ATOMIC_COUNTER_OFFSET;
561 }
562 NIR_PASS_V(nir, nir_lower_atomics_to_ssbo, align_offset_state);
563 }
564
565 st_set_prog_affected_state_flags(prog);
566
567 st_finalize_nir_before_variants(nir);
568
569 char *msg = NULL;
570 if (st->allow_st_finalize_nir_twice)
571 msg = st_finalize_nir(st, prog, shader_program, nir, true, true);
572
573 if (st->ctx->_Shader->Flags & GLSL_DUMP) {
574 _mesa_log("\n");
575 _mesa_log("NIR IR for linked %s program %d:\n",
576 _mesa_shader_stage_to_string(prog->info.stage),
577 shader_program->Name);
578 nir_print_shader(nir, _mesa_get_log_file());
579 _mesa_log("\n\n");
580 }
581
582 return msg;
583 }
584
585 static void
st_nir_vectorize_io(nir_shader * producer,nir_shader * consumer)586 st_nir_vectorize_io(nir_shader *producer, nir_shader *consumer)
587 {
588 if (consumer)
589 NIR_PASS_V(consumer, nir_lower_io_to_vector, nir_var_shader_in);
590
591 if (!producer)
592 return;
593
594 NIR_PASS_V(producer, nir_lower_io_to_vector, nir_var_shader_out);
595 NIR_PASS_V(producer, nir_opt_combine_stores, nir_var_shader_out);
596
597 if ((producer)->info.stage != MESA_SHADER_TESS_CTRL) {
598 /* Calling lower_io_to_vector creates output variable writes with
599 * write-masks. We only support these for TCS outputs, so for other
600 * stages, we need to call nir_lower_io_to_temporaries to get rid of
601 * them. This, in turn, creates temporary variables and extra
602 * copy_deref intrinsics that we need to clean up.
603 */
604 NIR_PASS_V(producer, nir_lower_io_to_temporaries,
605 nir_shader_get_entrypoint(producer), true, false);
606 NIR_PASS_V(producer, nir_lower_global_vars_to_local);
607 NIR_PASS_V(producer, nir_split_var_copies);
608 NIR_PASS_V(producer, nir_lower_var_copies);
609 }
610
611 /* Undef scalar store_deref intrinsics are not ignored by nir_lower_io,
612 * so they must be removed before that. These passes remove them.
613 */
614 NIR_PASS_V(producer, nir_lower_vars_to_ssa);
615 NIR_PASS_V(producer, nir_opt_undef);
616 NIR_PASS_V(producer, nir_opt_dce);
617 }
618
619 static void
st_lower_patch_vertices_in(struct gl_shader_program * shader_prog)620 st_lower_patch_vertices_in(struct gl_shader_program *shader_prog)
621 {
622 struct gl_linked_shader *linked_tcs =
623 shader_prog->_LinkedShaders[MESA_SHADER_TESS_CTRL];
624 struct gl_linked_shader *linked_tes =
625 shader_prog->_LinkedShaders[MESA_SHADER_TESS_EVAL];
626
627 /* If we have a TCS and TES linked together, lower TES patch vertices. */
628 if (linked_tcs && linked_tes) {
629 nir_shader *tcs_nir = linked_tcs->Program->nir;
630 nir_shader *tes_nir = linked_tes->Program->nir;
631
632 /* The TES input vertex count is the TCS output vertex count,
633 * lower TES gl_PatchVerticesIn to a constant.
634 */
635 uint32_t tes_patch_verts = tcs_nir->info.tess.tcs_vertices_out;
636 NIR_PASS_V(tes_nir, nir_lower_patch_vertices, tes_patch_verts, NULL);
637 }
638 }
639
640 extern "C" {
641
642 void
st_nir_lower_wpos_ytransform(struct nir_shader * nir,struct gl_program * prog,struct pipe_screen * pscreen)643 st_nir_lower_wpos_ytransform(struct nir_shader *nir,
644 struct gl_program *prog,
645 struct pipe_screen *pscreen)
646 {
647 if (nir->info.stage != MESA_SHADER_FRAGMENT)
648 return;
649
650 static const gl_state_index16 wposTransformState[STATE_LENGTH] = {
651 STATE_FB_WPOS_Y_TRANSFORM
652 };
653 nir_lower_wpos_ytransform_options wpos_options = { { 0 } };
654
655 memcpy(wpos_options.state_tokens, wposTransformState,
656 sizeof(wpos_options.state_tokens));
657 wpos_options.fs_coord_origin_upper_left =
658 pscreen->get_param(pscreen,
659 PIPE_CAP_FS_COORD_ORIGIN_UPPER_LEFT);
660 wpos_options.fs_coord_origin_lower_left =
661 pscreen->get_param(pscreen,
662 PIPE_CAP_FS_COORD_ORIGIN_LOWER_LEFT);
663 wpos_options.fs_coord_pixel_center_integer =
664 pscreen->get_param(pscreen,
665 PIPE_CAP_FS_COORD_PIXEL_CENTER_INTEGER);
666 wpos_options.fs_coord_pixel_center_half_integer =
667 pscreen->get_param(pscreen,
668 PIPE_CAP_FS_COORD_PIXEL_CENTER_HALF_INTEGER);
669
670 if (nir_lower_wpos_ytransform(nir, &wpos_options)) {
671 nir_validate_shader(nir, "after nir_lower_wpos_ytransform");
672 _mesa_add_state_reference(prog->Parameters, wposTransformState);
673 }
674
675 static const gl_state_index16 pntcTransformState[STATE_LENGTH] = {
676 STATE_FB_PNTC_Y_TRANSFORM
677 };
678
679 if (nir_lower_pntc_ytransform(nir, &pntcTransformState)) {
680 _mesa_add_state_reference(prog->Parameters, pntcTransformState);
681 }
682 }
683
684 bool
st_link_nir(struct gl_context * ctx,struct gl_shader_program * shader_program)685 st_link_nir(struct gl_context *ctx,
686 struct gl_shader_program *shader_program)
687 {
688 struct st_context *st = st_context(ctx);
689 struct gl_linked_shader *linked_shader[MESA_SHADER_STAGES];
690 unsigned num_shaders = 0;
691
692 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
693 if (shader_program->_LinkedShaders[i])
694 linked_shader[num_shaders++] = shader_program->_LinkedShaders[i];
695 }
696
697 for (unsigned i = 0; i < num_shaders; i++) {
698 struct gl_linked_shader *shader = linked_shader[i];
699 const nir_shader_compiler_options *options =
700 st->ctx->Const.ShaderCompilerOptions[shader->Stage].NirOptions;
701 struct gl_program *prog = shader->Program;
702
703 _mesa_copy_linked_program_data(shader_program, shader);
704
705 assert(!prog->nir);
706 prog->shader_program = shader_program;
707 prog->state.type = PIPE_SHADER_IR_NIR;
708
709 /* Parameters will be filled during NIR linking. */
710 prog->Parameters = _mesa_new_parameter_list();
711
712 if (shader_program->data->spirv) {
713 prog->nir = _mesa_spirv_to_nir(ctx, shader_program, shader->Stage, options);
714 } else {
715 validate_ir_tree(shader->ir);
716
717 if (ctx->_Shader->Flags & GLSL_DUMP) {
718 _mesa_log("\n");
719 _mesa_log("GLSL IR for linked %s program %d:\n",
720 _mesa_shader_stage_to_string(shader->Stage),
721 shader_program->Name);
722 _mesa_print_ir(_mesa_get_log_file(), shader->ir, NULL);
723 _mesa_log("\n\n");
724 }
725
726 prog->nir = glsl_to_nir(&st->ctx->Const, shader_program, shader->Stage, options);
727 }
728
729 memcpy(prog->nir->info.source_sha1, shader->linked_source_sha1,
730 SHA1_DIGEST_LENGTH);
731 st_nir_preprocess(st, prog, shader_program, shader->Stage);
732
733 if (prog->nir->info.shared_size > ctx->Const.MaxComputeSharedMemorySize) {
734 linker_error(shader_program, "Too much shared memory used (%u/%u)\n",
735 prog->nir->info.shared_size,
736 ctx->Const.MaxComputeSharedMemorySize);
737 return GL_FALSE;
738 }
739
740 if (options->lower_to_scalar) {
741 NIR_PASS_V(shader->Program->nir, nir_lower_load_const_to_scalar);
742 }
743 }
744
745 st_lower_patch_vertices_in(shader_program);
746
747 /* Linking shaders also optimizes them. Separate shaders, compute shaders
748 * and shaders with a fixed-func VS or FS that don't need linking are
749 * optimized here.
750 */
751 if (num_shaders == 1)
752 gl_nir_opts(linked_shader[0]->Program->nir);
753
754 if (shader_program->data->spirv) {
755 static const gl_nir_linker_options opts = {
756 true /*fill_parameters */
757 };
758 if (!gl_nir_link_spirv(&ctx->Const, shader_program, &opts))
759 return GL_FALSE;
760 } else {
761 if (!gl_nir_link_glsl(&ctx->Const, &ctx->Extensions, ctx->API,
762 shader_program))
763 return GL_FALSE;
764 }
765
766 for (unsigned i = 0; i < num_shaders; i++) {
767 struct gl_program *prog = linked_shader[i]->Program;
768 prog->ExternalSamplersUsed = gl_external_samplers(prog);
769 _mesa_update_shader_textures_used(shader_program, prog);
770 }
771
772 nir_build_program_resource_list(&ctx->Const, shader_program,
773 shader_program->data->spirv);
774
775 for (unsigned i = 0; i < num_shaders; i++) {
776 struct gl_linked_shader *shader = linked_shader[i];
777 nir_shader *nir = shader->Program->nir;
778 gl_shader_stage stage = shader->Stage;
779 const struct gl_shader_compiler_options *options =
780 &ctx->Const.ShaderCompilerOptions[stage];
781
782 /* If there are forms of indirect addressing that the driver
783 * cannot handle, perform the lowering pass.
784 */
785 if (options->EmitNoIndirectInput || options->EmitNoIndirectOutput ||
786 options->EmitNoIndirectTemp || options->EmitNoIndirectUniform) {
787 nir_variable_mode mode = options->EmitNoIndirectInput ?
788 nir_var_shader_in : (nir_variable_mode)0;
789 mode |= options->EmitNoIndirectOutput ?
790 nir_var_shader_out : (nir_variable_mode)0;
791 mode |= options->EmitNoIndirectTemp ?
792 nir_var_function_temp : (nir_variable_mode)0;
793 mode |= options->EmitNoIndirectUniform ?
794 nir_var_uniform | nir_var_mem_ubo | nir_var_mem_ssbo :
795 (nir_variable_mode)0;
796
797 nir_lower_indirect_derefs(nir, mode, UINT32_MAX);
798 }
799
800 /* don't infer ACCESS_NON_READABLE so that Program->sh.ImageAccess is
801 * correct: https://gitlab.freedesktop.org/mesa/mesa/-/issues/3278
802 */
803 nir_opt_access_options opt_access_options;
804 opt_access_options.is_vulkan = false;
805 opt_access_options.infer_non_readable = false;
806 NIR_PASS_V(nir, nir_opt_access, &opt_access_options);
807
808 /* This needs to run after the initial pass of nir_lower_vars_to_ssa, so
809 * that the buffer indices are constants in nir where they where
810 * constants in GLSL. */
811 NIR_PASS_V(nir, gl_nir_lower_buffers, shader_program);
812
813 /* Remap the locations to slots so those requiring two slots will occupy
814 * two locations. For instance, if we have in the IR code a dvec3 attr0 in
815 * location 0 and vec4 attr1 in location 1, in NIR attr0 will use
816 * locations/slots 0 and 1, and attr1 will use location/slot 2
817 */
818 if (nir->info.stage == MESA_SHADER_VERTEX && !shader_program->data->spirv)
819 nir_remap_dual_slot_attributes(nir, &shader->Program->DualSlotInputs);
820
821 NIR_PASS_V(nir, st_nir_lower_wpos_ytransform, shader->Program,
822 st->screen);
823
824 NIR_PASS_V(nir, nir_lower_system_values);
825 NIR_PASS_V(nir, nir_lower_compute_system_values, NULL);
826
827 if (!st->screen->get_param(st->screen, PIPE_CAP_CULL_DISTANCE_NOCOMBINE))
828 NIR_PASS_V(nir, nir_lower_clip_cull_distance_arrays);
829
830 if (i >= 1) {
831 struct gl_program *prev_shader = linked_shader[i - 1]->Program;
832
833 /* We can't use nir_compact_varyings with transform feedback, since
834 * the pipe_stream_output->output_register field is based on the
835 * pre-compacted driver_locations.
836 */
837 if (!(prev_shader->sh.LinkedTransformFeedback &&
838 prev_shader->sh.LinkedTransformFeedback->NumVarying > 0))
839 nir_compact_varyings(prev_shader->nir,
840 nir, ctx->API != API_OPENGL_COMPAT);
841
842 if (ctx->Const.ShaderCompilerOptions[shader->Stage].NirOptions->vectorize_io)
843 st_nir_vectorize_io(prev_shader->nir, nir);
844 }
845 }
846
847 /* If the program is a separate shader program check if we need to vectorise
848 * the first and last program interfaces too.
849 */
850 if (shader_program->SeparateShader && num_shaders > 0) {
851 struct gl_linked_shader *first_shader = linked_shader[0];
852 struct gl_linked_shader *last_shader = linked_shader[num_shaders - 1];
853 if (first_shader->Stage != MESA_SHADER_COMPUTE) {
854 if (ctx->Const.ShaderCompilerOptions[first_shader->Stage].NirOptions->vectorize_io &&
855 first_shader->Stage > MESA_SHADER_VERTEX)
856 st_nir_vectorize_io(NULL, first_shader->Program->nir);
857
858 if (ctx->Const.ShaderCompilerOptions[last_shader->Stage].NirOptions->vectorize_io &&
859 last_shader->Stage < MESA_SHADER_FRAGMENT)
860 st_nir_vectorize_io(last_shader->Program->nir, NULL);
861 }
862 }
863
864 struct shader_info *prev_info = NULL;
865
866 for (unsigned i = 0; i < num_shaders; i++) {
867 struct gl_linked_shader *shader = linked_shader[i];
868 struct shader_info *info = &shader->Program->nir->info;
869
870 char *msg = st_glsl_to_nir_post_opts(st, shader->Program, shader_program);
871 if (msg) {
872 linker_error(shader_program, msg);
873 return false;
874 }
875
876 if (prev_info &&
877 ctx->Const.ShaderCompilerOptions[shader->Stage].NirOptions->unify_interfaces) {
878 prev_info->outputs_written |= info->inputs_read &
879 ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
880 info->inputs_read |= prev_info->outputs_written &
881 ~(VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER);
882
883 prev_info->patch_outputs_written |= info->patch_inputs_read;
884 info->patch_inputs_read |= prev_info->patch_outputs_written;
885 }
886 prev_info = info;
887 }
888
889 for (unsigned i = 0; i < num_shaders; i++) {
890 struct gl_linked_shader *shader = linked_shader[i];
891 struct gl_program *prog = shader->Program;
892
893 /* Make sure that prog->info is in sync with nir->info, but st/mesa
894 * expects some of the values to be from before lowering.
895 */
896 shader_info old_info = prog->info;
897 prog->info = prog->nir->info;
898 prog->info.name = old_info.name;
899 prog->info.label = old_info.label;
900 prog->info.num_ssbos = old_info.num_ssbos;
901 prog->info.num_ubos = old_info.num_ubos;
902 prog->info.num_abos = old_info.num_abos;
903
904 if (prog->info.stage == MESA_SHADER_VERTEX) {
905 /* NIR expands dual-slot inputs out to two locations. We need to
906 * compact things back down GL-style single-slot inputs to avoid
907 * confusing the state tracker.
908 */
909 prog->info.inputs_read =
910 nir_get_single_slot_attribs_mask(prog->nir->info.inputs_read,
911 prog->DualSlotInputs);
912
913 /* Initialize st_vertex_program members. */
914 st_prepare_vertex_program(prog);
915 }
916
917 /* Get pipe_stream_output_info. */
918 if (shader->Stage == MESA_SHADER_VERTEX ||
919 shader->Stage == MESA_SHADER_TESS_EVAL ||
920 shader->Stage == MESA_SHADER_GEOMETRY)
921 st_translate_stream_output_info(prog);
922
923 st_store_nir_in_disk_cache(st, prog);
924
925 st_release_variants(st, prog);
926 st_finalize_program(st, prog);
927 }
928
929 return true;
930 }
931
932 void
st_nir_assign_varying_locations(struct st_context * st,nir_shader * nir)933 st_nir_assign_varying_locations(struct st_context *st, nir_shader *nir)
934 {
935 if (nir->info.stage == MESA_SHADER_VERTEX) {
936 nir_assign_io_var_locations(nir, nir_var_shader_out,
937 &nir->num_outputs,
938 nir->info.stage);
939 st_nir_fixup_varying_slots(st, nir, nir_var_shader_out);
940 } else if (nir->info.stage == MESA_SHADER_GEOMETRY ||
941 nir->info.stage == MESA_SHADER_TESS_CTRL ||
942 nir->info.stage == MESA_SHADER_TESS_EVAL) {
943 nir_assign_io_var_locations(nir, nir_var_shader_in,
944 &nir->num_inputs,
945 nir->info.stage);
946 st_nir_fixup_varying_slots(st, nir, nir_var_shader_in);
947
948 nir_assign_io_var_locations(nir, nir_var_shader_out,
949 &nir->num_outputs,
950 nir->info.stage);
951 st_nir_fixup_varying_slots(st, nir, nir_var_shader_out);
952 } else if (nir->info.stage == MESA_SHADER_FRAGMENT) {
953 nir_assign_io_var_locations(nir, nir_var_shader_in,
954 &nir->num_inputs,
955 nir->info.stage);
956 st_nir_fixup_varying_slots(st, nir, nir_var_shader_in);
957 nir_assign_io_var_locations(nir, nir_var_shader_out,
958 &nir->num_outputs,
959 nir->info.stage);
960 } else if (nir->info.stage == MESA_SHADER_COMPUTE) {
961 /* TODO? */
962 } else {
963 unreachable("invalid shader type");
964 }
965 }
966
967 void
st_nir_lower_samplers(struct pipe_screen * screen,nir_shader * nir,struct gl_shader_program * shader_program,struct gl_program * prog)968 st_nir_lower_samplers(struct pipe_screen *screen, nir_shader *nir,
969 struct gl_shader_program *shader_program,
970 struct gl_program *prog)
971 {
972 if (screen->get_param(screen, PIPE_CAP_NIR_SAMPLERS_AS_DEREF))
973 NIR_PASS_V(nir, gl_nir_lower_samplers_as_deref, shader_program);
974 else
975 NIR_PASS_V(nir, gl_nir_lower_samplers, shader_program);
976
977 if (prog) {
978 BITSET_COPY(prog->info.textures_used, nir->info.textures_used);
979 BITSET_COPY(prog->info.textures_used_by_txf, nir->info.textures_used_by_txf);
980 BITSET_COPY(prog->info.samplers_used, nir->info.samplers_used);
981 BITSET_COPY(prog->info.images_used, nir->info.images_used);
982 BITSET_COPY(prog->info.image_buffers, nir->info.image_buffers);
983 BITSET_COPY(prog->info.msaa_images, nir->info.msaa_images);
984 }
985 }
986
987 static int
st_packed_uniforms_type_size(const struct glsl_type * type,bool bindless)988 st_packed_uniforms_type_size(const struct glsl_type *type, bool bindless)
989 {
990 return glsl_count_dword_slots(type, bindless);
991 }
992
993 static int
st_unpacked_uniforms_type_size(const struct glsl_type * type,bool bindless)994 st_unpacked_uniforms_type_size(const struct glsl_type *type, bool bindless)
995 {
996 return glsl_count_vec4_slots(type, false, bindless);
997 }
998
999 void
st_nir_lower_uniforms(struct st_context * st,nir_shader * nir)1000 st_nir_lower_uniforms(struct st_context *st, nir_shader *nir)
1001 {
1002 if (st->ctx->Const.PackedDriverUniformStorage) {
1003 NIR_PASS_V(nir, nir_lower_io, nir_var_uniform,
1004 st_packed_uniforms_type_size,
1005 (nir_lower_io_options)0);
1006 } else {
1007 NIR_PASS_V(nir, nir_lower_io, nir_var_uniform,
1008 st_unpacked_uniforms_type_size,
1009 (nir_lower_io_options)0);
1010 }
1011
1012 if (nir->options->lower_uniforms_to_ubo)
1013 NIR_PASS_V(nir, nir_lower_uniforms_to_ubo,
1014 st->ctx->Const.PackedDriverUniformStorage,
1015 !st->ctx->Const.NativeIntegers);
1016 }
1017
1018 /* Last third of preparing nir from glsl, which happens after shader
1019 * variant lowering.
1020 */
1021 char *
st_finalize_nir(struct st_context * st,struct gl_program * prog,struct gl_shader_program * shader_program,nir_shader * nir,bool finalize_by_driver,bool is_before_variants)1022 st_finalize_nir(struct st_context *st, struct gl_program *prog,
1023 struct gl_shader_program *shader_program,
1024 nir_shader *nir, bool finalize_by_driver,
1025 bool is_before_variants)
1026 {
1027 struct pipe_screen *screen = st->screen;
1028
1029 NIR_PASS_V(nir, nir_split_var_copies);
1030 NIR_PASS_V(nir, nir_lower_var_copies);
1031
1032 const bool lower_tg4_offsets =
1033 !st->screen->get_param(screen, PIPE_CAP_TEXTURE_GATHER_OFFSETS);
1034
1035 if (st->lower_rect_tex || lower_tg4_offsets) {
1036 struct nir_lower_tex_options opts = {0};
1037 opts.lower_rect = !!st->lower_rect_tex;
1038 opts.lower_tg4_offsets = lower_tg4_offsets;
1039
1040 NIR_PASS_V(nir, nir_lower_tex, &opts);
1041 }
1042
1043 st_nir_assign_varying_locations(st, nir);
1044 st_nir_assign_uniform_locations(st->ctx, prog, nir);
1045
1046 /* Lower load_deref/store_deref of inputs and outputs.
1047 * This depends on st_nir_assign_varying_locations.
1048 */
1049 if (nir->options->lower_io_variables)
1050 nir_lower_io_passes(nir);
1051
1052 /* Set num_uniforms in number of attribute slots (vec4s) */
1053 nir->num_uniforms = DIV_ROUND_UP(prog->Parameters->NumParameterValues, 4);
1054
1055 st_nir_lower_uniforms(st, nir);
1056
1057 if (is_before_variants && nir->options->lower_uniforms_to_ubo) {
1058 /* This must be done after uniforms are lowered to UBO and all
1059 * nir_var_uniform variables are removed from NIR to prevent conflicts
1060 * between state parameter merging and shader variant generation.
1061 */
1062 _mesa_optimize_state_parameters(&st->ctx->Const, prog->Parameters);
1063 }
1064
1065 st_nir_lower_samplers(screen, nir, shader_program, prog);
1066 if (!screen->get_param(screen, PIPE_CAP_NIR_IMAGES_AS_DEREF))
1067 NIR_PASS_V(nir, gl_nir_lower_images, false);
1068
1069 char *msg = NULL;
1070 if (finalize_by_driver && screen->finalize_nir)
1071 msg = screen->finalize_nir(screen, nir);
1072
1073 return msg;
1074 }
1075
1076 } /* extern "C" */
1077