st/glsl_to_nir: pass gl_shader_program to st_finalize_nir()
[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 "st_context.h"
40 #include "st_program.h"
41
42 #include "compiler/nir/nir.h"
43 #include "compiler/glsl_types.h"
44 #include "compiler/glsl/glsl_to_nir.h"
45 #include "compiler/glsl/ir.h"
46 #include "compiler/glsl/string_to_uint_map.h"
47
48
49 static int
50 type_size(const struct glsl_type *type)
51 {
52 return type->count_attribute_slots(false);
53 }
54
55 /* Depending on PIPE_CAP_TGSI_TEXCOORD (st->needs_texcoord_semantic) we
56 * may need to fix up varying slots so the glsl->nir path is aligned
57 * with the anything->tgsi->nir path.
58 */
59 static void
60 st_nir_fixup_varying_slots(struct st_context *st, struct exec_list *var_list)
61 {
62 if (st->needs_texcoord_semantic)
63 return;
64
65 nir_foreach_variable(var, var_list) {
66 if (var->data.location >= VARYING_SLOT_VAR0) {
67 var->data.location += 9;
68 } else if ((var->data.location >= VARYING_SLOT_TEX0) &&
69 (var->data.location <= VARYING_SLOT_TEX7)) {
70 var->data.location += VARYING_SLOT_VAR0 - VARYING_SLOT_TEX0;
71 }
72 }
73 }
74
75 /* input location assignment for VS inputs must be handled specially, so
76 * that it is aligned w/ st's vbo state.
77 * (This isn't the case with, for ex, FS inputs, which only need to agree
78 * on varying-slot w/ the VS outputs)
79 */
80 static void
81 st_nir_assign_vs_in_locations(struct gl_program *prog, nir_shader *nir)
82 {
83 unsigned attr, num_inputs = 0;
84 unsigned input_to_index[VERT_ATTRIB_MAX] = {0};
85
86 /* TODO de-duplicate w/ similar code in st_translate_vertex_program()? */
87 for (attr = 0; attr < VERT_ATTRIB_MAX; attr++) {
88 if ((prog->info.inputs_read & BITFIELD64_BIT(attr)) != 0) {
89 input_to_index[attr] = num_inputs;
90 num_inputs++;
91 if ((prog->info.double_inputs_read & BITFIELD64_BIT(attr)) != 0) {
92 /* add placeholder for second part of a double attribute */
93 num_inputs++;
94 }
95 } else {
96 input_to_index[attr] = ~0;
97 }
98 }
99
100 /* bit of a hack, mirroring st_translate_vertex_program */
101 input_to_index[VERT_ATTRIB_EDGEFLAG] = num_inputs;
102
103 nir->num_inputs = 0;
104 nir_foreach_variable_safe(var, &nir->inputs) {
105 attr = var->data.location;
106 assert(attr < ARRAY_SIZE(input_to_index));
107
108 if (input_to_index[attr] != ~0u) {
109 var->data.driver_location = input_to_index[attr];
110 nir->num_inputs++;
111 } else {
112 /* Move unused input variables to the globals list (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 exec_node_remove(&var->node);
118 var->data.mode = nir_var_global;
119 exec_list_push_tail(&nir->globals, &var->node);
120 }
121 }
122 }
123
124 static int
125 st_nir_lookup_parameter_index(const struct gl_program_parameter_list *params,
126 const char *name)
127 {
128 int loc = _mesa_lookup_parameter_index(params, name);
129
130 /* is there a better way to do this? If we have something like:
131 *
132 * struct S {
133 * float f;
134 * vec4 v;
135 * };
136 * uniform S color;
137 *
138 * Then what we get in prog->Parameters looks like:
139 *
140 * 0: Name=color.f, Type=6, DataType=1406, Size=1
141 * 1: Name=color.v, Type=6, DataType=8b52, Size=4
142 *
143 * So the name doesn't match up and _mesa_lookup_parameter_index()
144 * fails. In this case just find the first matching "color.*"..
145 *
146 * Note for arrays you could end up w/ color[n].f, for example.
147 *
148 * glsl_to_tgsi works slightly differently in this regard. It is
149 * emitting something more low level, so it just translates the
150 * params list 1:1 to CONST[] regs. Going from GLSL IR to TGSI,
151 * it just calculates the additional offset of struct field members
152 * in glsl_to_tgsi_visitor::visit(ir_dereference_record *ir) or
153 * glsl_to_tgsi_visitor::visit(ir_dereference_array *ir). It never
154 * needs to work backwards to get base var loc from the param-list
155 * which already has them separated out.
156 */
157 if (loc < 0) {
158 int namelen = strlen(name);
159 for (unsigned i = 0; i < params->NumParameters; i++) {
160 struct gl_program_parameter *p = &params->Parameters[i];
161 if ((strncmp(p->Name, name, namelen) == 0) &&
162 ((p->Name[namelen] == '.') || (p->Name[namelen] == '['))) {
163 loc = i;
164 break;
165 }
166 }
167 }
168
169 return loc;
170 }
171
172 static void
173 st_nir_assign_uniform_locations(struct gl_program *prog,
174 struct gl_shader_program *shader_program,
175 struct exec_list *uniform_list, unsigned *size)
176 {
177 int max = 0;
178 int shaderidx = 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_uniform || uniform->data.mode == nir_var_shader_storage) &&
188 uniform->interface_type != NULL)
189 continue;
190
191 if (uniform->type->is_sampler()) {
192 unsigned val = 0;
193 bool found = shader_program->UniformHash->get(val, uniform->name);
194 loc = shaderidx++;
195 assert(found);
196 (void) found; /* silence unused var warning */
197 /* this ensure that nir_lower_samplers looks at the correct
198 * shader_program->UniformStorage[location]:
199 */
200 uniform->data.location = val;
201 } else if (strncmp(uniform->name, "gl_", 3) == 0) {
202 const gl_state_index *const stateTokens = (gl_state_index *)uniform->state_slots[0].tokens;
203 /* This state reference has already been setup by ir_to_mesa, but we'll
204 * get the same index back here.
205 */
206 loc = _mesa_add_state_reference(prog->Parameters, stateTokens);
207 } else {
208 loc = st_nir_lookup_parameter_index(prog->Parameters, uniform->name);
209 }
210
211 uniform->data.driver_location = loc;
212
213 max = MAX2(max, loc + type_size(uniform->type));
214 }
215 *size = max;
216 }
217
218 extern "C" {
219
220 /* First half of converting glsl_to_nir.. this leaves things in a pre-
221 * nir_lower_io state, so that shader variants can more easily insert/
222 * replace variables, etc.
223 */
224 nir_shader *
225 st_glsl_to_nir(struct st_context *st, struct gl_program *prog,
226 struct gl_shader_program *shader_program,
227 gl_shader_stage stage)
228 {
229 struct pipe_screen *pscreen = st->pipe->screen;
230 enum pipe_shader_type ptarget = pipe_shader_type_from_mesa(stage);
231 const nir_shader_compiler_options *options;
232 nir_shader *nir;
233
234 assert(pscreen->get_compiler_options); /* drivers using NIR must implement this */
235
236 options = (const nir_shader_compiler_options *)
237 pscreen->get_compiler_options(pscreen, PIPE_SHADER_IR_NIR, ptarget);
238 assert(options);
239
240 if (prog->nir)
241 return prog->nir;
242
243 nir = glsl_to_nir(shader_program, stage, options);
244
245 NIR_PASS_V(nir, nir_lower_io_to_temporaries,
246 nir_shader_get_entrypoint(nir),
247 true, true);
248 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
249 NIR_PASS_V(nir, nir_split_var_copies);
250 NIR_PASS_V(nir, nir_lower_var_copies);
251 NIR_PASS_V(nir, st_nir_lower_builtin);
252 NIR_PASS_V(nir, nir_lower_atomics, shader_program);
253
254 /* fragment shaders may need : */
255 if (stage == MESA_SHADER_FRAGMENT) {
256 static const gl_state_index wposTransformState[STATE_LENGTH] = {
257 STATE_INTERNAL, STATE_FB_WPOS_Y_TRANSFORM
258 };
259 nir_lower_wpos_ytransform_options wpos_options = { { 0 } };
260 struct pipe_screen *pscreen = st->pipe->screen;
261
262 memcpy(wpos_options.state_tokens, wposTransformState,
263 sizeof(wpos_options.state_tokens));
264 wpos_options.fs_coord_origin_upper_left =
265 pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT);
266 wpos_options.fs_coord_origin_lower_left =
267 pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT);
268 wpos_options.fs_coord_pixel_center_integer =
269 pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER);
270 wpos_options.fs_coord_pixel_center_half_integer =
271 pscreen->get_param(pscreen, PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER);
272
273 if (nir_lower_wpos_ytransform(nir, &wpos_options)) {
274 nir_validate_shader(nir);
275 _mesa_add_state_reference(prog->Parameters, wposTransformState);
276 }
277 }
278
279 if (st->ctx->_Shader->Flags & GLSL_DUMP) {
280 _mesa_log("\n");
281 _mesa_log("NIR IR for linked %s program %d:\n",
282 _mesa_shader_stage_to_string(stage),
283 shader_program->Name);
284 nir_print_shader(nir, _mesa_get_log_file());
285 _mesa_log("\n\n");
286 }
287
288 prog->nir = nir;
289
290 return nir;
291 }
292
293 /* TODO any better helper somewhere to sort a list? */
294
295 static void
296 insert_sorted(struct exec_list *var_list, nir_variable *new_var)
297 {
298 nir_foreach_variable(var, var_list) {
299 if (var->data.location > new_var->data.location) {
300 exec_node_insert_node_before(&var->node, &new_var->node);
301 return;
302 }
303 }
304 exec_list_push_tail(var_list, &new_var->node);
305 }
306
307 static void
308 sort_varyings(struct exec_list *var_list)
309 {
310 struct exec_list new_list;
311 exec_list_make_empty(&new_list);
312 nir_foreach_variable_safe(var, var_list) {
313 exec_node_remove(&var->node);
314 insert_sorted(&new_list, var);
315 }
316 exec_list_move_nodes_to(&new_list, var_list);
317 }
318
319 /* Second half of preparing nir from glsl, which happens after shader
320 * variant lowering.
321 */
322 void
323 st_finalize_nir(struct st_context *st, struct gl_program *prog,
324 struct gl_shader_program *shader_program, nir_shader *nir)
325 {
326 struct pipe_screen *screen = st->pipe->screen;
327
328 NIR_PASS_V(nir, nir_split_var_copies);
329 NIR_PASS_V(nir, nir_lower_var_copies);
330 NIR_PASS_V(nir, nir_lower_io_types);
331
332 if (nir->info.stage == MESA_SHADER_VERTEX) {
333 /* Needs special handling so drvloc matches the vbo state: */
334 st_nir_assign_vs_in_locations(prog, nir);
335 /* Re-lower global vars, to deal with any dead VS inputs. */
336 NIR_PASS_V(nir, nir_lower_global_vars_to_local);
337
338 sort_varyings(&nir->outputs);
339 nir_assign_var_locations(&nir->outputs,
340 &nir->num_outputs,
341 type_size);
342 st_nir_fixup_varying_slots(st, &nir->outputs);
343 } else if (nir->info.stage == MESA_SHADER_FRAGMENT) {
344 sort_varyings(&nir->inputs);
345 nir_assign_var_locations(&nir->inputs,
346 &nir->num_inputs,
347 type_size);
348 st_nir_fixup_varying_slots(st, &nir->inputs);
349 nir_assign_var_locations(&nir->outputs,
350 &nir->num_outputs,
351 type_size);
352 } else if (nir->info.stage == MESA_SHADER_COMPUTE) {
353 /* TODO? */
354 } else {
355 unreachable("invalid shader type for tgsi bypass\n");
356 }
357
358 NIR_PASS_V(nir, nir_lower_atomics_to_ssbo,
359 st->ctx->Const.Program[nir->info.stage].MaxAtomicBuffers);
360
361 st_nir_assign_uniform_locations(prog, shader_program,
362 &nir->uniforms, &nir->num_uniforms);
363
364 NIR_PASS_V(nir, nir_lower_system_values);
365
366 if (screen->get_param(screen, PIPE_CAP_NIR_SAMPLERS_AS_DEREF))
367 NIR_PASS_V(nir, nir_lower_samplers_as_deref, shader_program);
368 else
369 NIR_PASS_V(nir, nir_lower_samplers, shader_program);
370 }
371
372 struct gl_program *
373 st_nir_get_mesa_program(struct gl_context *ctx,
374 struct gl_shader_program *shader_program,
375 struct gl_linked_shader *shader)
376 {
377 struct gl_program *prog;
378
379 validate_ir_tree(shader->ir);
380
381 prog = shader->Program;
382
383 prog->Parameters = _mesa_new_parameter_list();
384
385 do_set_program_inouts(shader->ir, prog, shader->Stage);
386
387 _mesa_copy_linked_program_data(shader_program, shader);
388 _mesa_generate_parameters_list_for_uniforms(ctx, shader_program, shader,
389 prog->Parameters);
390
391 /* Make a pass over the IR to add state references for any built-in
392 * uniforms that are used. This has to be done now (during linking).
393 * Code generation doesn't happen until the first time this shader is
394 * used for rendering. Waiting until then to generate the parameters is
395 * too late. At that point, the values for the built-in uniforms won't
396 * get sent to the shader.
397 */
398 foreach_in_list(ir_instruction, node, shader->ir) {
399 ir_variable *var = node->as_variable();
400
401 if ((var == NULL) || (var->data.mode != ir_var_uniform) ||
402 (strncmp(var->name, "gl_", 3) != 0))
403 continue;
404
405 const ir_state_slot *const slots = var->get_state_slots();
406 assert(slots != NULL);
407
408 for (unsigned int i = 0; i < var->get_num_state_slots(); i++) {
409 _mesa_add_state_reference(prog->Parameters,
410 (gl_state_index *) slots[i].tokens);
411 }
412 }
413
414 if (ctx->_Shader->Flags & GLSL_DUMP) {
415 _mesa_log("\n");
416 _mesa_log("GLSL IR for linked %s program %d:\n",
417 _mesa_shader_stage_to_string(shader->Stage),
418 shader_program->Name);
419 _mesa_print_ir(_mesa_get_log_file(), shader->ir, NULL);
420 _mesa_log("\n\n");
421 }
422
423 prog->ExternalSamplersUsed = gl_external_samplers(prog);
424 _mesa_update_shader_textures_used(shader_program, prog);
425
426 /* Avoid reallocation of the program parameter list, because the uniform
427 * storage is only associated with the original parameter list.
428 * This should be enough for Bitmap and DrawPixels constants.
429 */
430 _mesa_reserve_parameter_storage(prog->Parameters, 8);
431
432 /* This has to be done last. Any operation the can cause
433 * prog->ParameterValues to get reallocated (e.g., anything that adds a
434 * program constant) has to happen before creating this linkage.
435 */
436 _mesa_associate_uniform_storage(ctx, shader_program, prog, true);
437
438 struct st_vertex_program *stvp;
439 struct st_common_program *stp;
440 struct st_fragment_program *stfp;
441 struct st_compute_program *stcp;
442
443 switch (shader->Stage) {
444 case MESA_SHADER_VERTEX:
445 stvp = (struct st_vertex_program *)prog;
446 stvp->shader_program = shader_program;
447 break;
448 case MESA_SHADER_GEOMETRY:
449 case MESA_SHADER_TESS_CTRL:
450 case MESA_SHADER_TESS_EVAL:
451 stp = (struct st_common_program *)prog;
452 stp->shader_program = shader_program;
453 break;
454 case MESA_SHADER_FRAGMENT:
455 stfp = (struct st_fragment_program *)prog;
456 stfp->shader_program = shader_program;
457 break;
458 case MESA_SHADER_COMPUTE:
459 stcp = (struct st_compute_program *)prog;
460 stcp->shader_program = shader_program;
461 break;
462 default:
463 assert(!"should not be reached");
464 return NULL;
465 }
466
467 return prog;
468 }
469
470 } /* extern "C" */