1 /*
2 * Copyright © 2010 Intel Corporation
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
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
22 */
23
24 /**
25 * \file linker.cpp
26 * GLSL linker implementation
27 *
28 * Given a set of shaders that are to be linked to generate a final program,
29 * there are three distinct stages.
30 *
31 * In the first stage shaders are partitioned into groups based on the shader
32 * type. All shaders of a particular type (e.g., vertex shaders) are linked
33 * together.
34 *
35 * - Undefined references in each shader are resolve to definitions in
36 * another shader.
37 * - Types and qualifiers of uniforms, outputs, and global variables defined
38 * in multiple shaders with the same name are verified to be the same.
39 * - Initializers for uniforms and global variables defined
40 * in multiple shaders with the same name are verified to be the same.
41 *
42 * The result, in the terminology of the GLSL spec, is a set of shader
43 * executables for each processing unit.
44 *
45 * After the first stage is complete, a series of semantic checks are performed
46 * on each of the shader executables.
47 *
48 * - Each shader executable must define a \c main function.
49 * - Each vertex shader executable must write to \c gl_Position.
50 * - Each fragment shader executable must write to either \c gl_FragData or
51 * \c gl_FragColor.
52 *
53 * In the final stage individual shader executables are linked to create a
54 * complete exectuable.
55 *
56 * - Types of uniforms defined in multiple shader stages with the same name
57 * are verified to be the same.
58 * - Initializers for uniforms defined in multiple shader stages with the
59 * same name are verified to be the same.
60 * - Types and qualifiers of outputs defined in one stage are verified to
61 * be the same as the types and qualifiers of inputs defined with the same
62 * name in a later stage.
63 *
64 * \author Ian Romanick <ian.d.romanick@intel.com>
65 */
66
67 #include <ctype.h>
68 #include "util/strndup.h"
69 #include "glsl_symbol_table.h"
70 #include "glsl_parser_extras.h"
71 #include "ir.h"
72 #include "nir.h"
73 #include "program.h"
74 #include "program/prog_instruction.h"
75 #include "program/program.h"
76 #include "util/mesa-sha1.h"
77 #include "util/set.h"
78 #include "string_to_uint_map.h"
79 #include "linker.h"
80 #include "linker_util.h"
81 #include "ir_optimization.h"
82 #include "ir_rvalue_visitor.h"
83 #include "ir_uniform.h"
84 #include "builtin_functions.h"
85 #include "shader_cache.h"
86 #include "util/u_string.h"
87 #include "util/u_math.h"
88
89
90 #include "main/shaderobj.h"
91 #include "main/enums.h"
92 #include "main/mtypes.h"
93 #include "main/context.h"
94
95
96 namespace {
97
98 struct find_variable {
99 const char *name;
100 bool found;
101
find_variable__anoncffb47c90111::find_variable102 find_variable(const char *name) : name(name), found(false) {}
103 };
104
105 /**
106 * Visitor that determines whether or not a variable is ever written.
107 * Note: this is only considering if the variable is statically written
108 * (= regardless of the runtime flow of control)
109 *
110 * Use \ref find_assignments for convenience.
111 */
112 class find_assignment_visitor : public ir_hierarchical_visitor {
113 public:
find_assignment_visitor(unsigned num_vars,find_variable * const * vars)114 find_assignment_visitor(unsigned num_vars,
115 find_variable * const *vars)
116 : num_variables(num_vars), num_found(0), variables(vars)
117 {
118 }
119
visit_enter(ir_assignment * ir)120 virtual ir_visitor_status visit_enter(ir_assignment *ir)
121 {
122 ir_variable *const var = ir->lhs->variable_referenced();
123
124 return check_variable_name(var->name);
125 }
126
visit_enter(ir_call * ir)127 virtual ir_visitor_status visit_enter(ir_call *ir)
128 {
129 foreach_two_lists(formal_node, &ir->callee->parameters,
130 actual_node, &ir->actual_parameters) {
131 ir_rvalue *param_rval = (ir_rvalue *) actual_node;
132 ir_variable *sig_param = (ir_variable *) formal_node;
133
134 if (sig_param->data.mode == ir_var_function_out ||
135 sig_param->data.mode == ir_var_function_inout) {
136 ir_variable *var = param_rval->variable_referenced();
137 if (var && check_variable_name(var->name) == visit_stop)
138 return visit_stop;
139 }
140 }
141
142 if (ir->return_deref != NULL) {
143 ir_variable *const var = ir->return_deref->variable_referenced();
144
145 if (check_variable_name(var->name) == visit_stop)
146 return visit_stop;
147 }
148
149 return visit_continue_with_parent;
150 }
151
152 private:
check_variable_name(const char * name)153 ir_visitor_status check_variable_name(const char *name)
154 {
155 for (unsigned i = 0; i < num_variables; ++i) {
156 if (strcmp(variables[i]->name, name) == 0) {
157 if (!variables[i]->found) {
158 variables[i]->found = true;
159
160 assert(num_found < num_variables);
161 if (++num_found == num_variables)
162 return visit_stop;
163 }
164 break;
165 }
166 }
167
168 return visit_continue_with_parent;
169 }
170
171 private:
172 unsigned num_variables; /**< Number of variables to find */
173 unsigned num_found; /**< Number of variables already found */
174 find_variable * const *variables; /**< Variables to find */
175 };
176
177 /**
178 * Determine whether or not any of NULL-terminated list of variables is ever
179 * written to.
180 */
181 static void
find_assignments(exec_list * ir,find_variable * const * vars)182 find_assignments(exec_list *ir, find_variable * const *vars)
183 {
184 unsigned num_variables = 0;
185
186 for (find_variable * const *v = vars; *v; ++v)
187 num_variables++;
188
189 find_assignment_visitor visitor(num_variables, vars);
190 visitor.run(ir);
191 }
192
193 /**
194 * Determine whether or not the given variable is ever written to.
195 */
196 static void
find_assignments(exec_list * ir,find_variable * var)197 find_assignments(exec_list *ir, find_variable *var)
198 {
199 find_assignment_visitor visitor(1, &var);
200 visitor.run(ir);
201 }
202
203 /**
204 * Visitor that determines whether or not a variable is ever read.
205 */
206 class find_deref_visitor : public ir_hierarchical_visitor {
207 public:
find_deref_visitor(const char * name)208 find_deref_visitor(const char *name)
209 : name(name), found(false)
210 {
211 /* empty */
212 }
213
visit(ir_dereference_variable * ir)214 virtual ir_visitor_status visit(ir_dereference_variable *ir)
215 {
216 if (strcmp(this->name, ir->var->name) == 0) {
217 this->found = true;
218 return visit_stop;
219 }
220
221 return visit_continue;
222 }
223
variable_found() const224 bool variable_found() const
225 {
226 return this->found;
227 }
228
229 private:
230 const char *name; /**< Find writes to a variable with this name. */
231 bool found; /**< Was a write to the variable found? */
232 };
233
234
235 /**
236 * A visitor helper that provides methods for updating the types of
237 * ir_dereferences. Classes that update variable types (say, updating
238 * array sizes) will want to use this so that dereference types stay in sync.
239 */
240 class deref_type_updater : public ir_hierarchical_visitor {
241 public:
visit(ir_dereference_variable * ir)242 virtual ir_visitor_status visit(ir_dereference_variable *ir)
243 {
244 ir->type = ir->var->type;
245 return visit_continue;
246 }
247
visit_leave(ir_dereference_array * ir)248 virtual ir_visitor_status visit_leave(ir_dereference_array *ir)
249 {
250 const glsl_type *const vt = ir->array->type;
251 if (glsl_type_is_array(vt))
252 ir->type = vt->fields.array;
253 return visit_continue;
254 }
255
visit_leave(ir_dereference_record * ir)256 virtual ir_visitor_status visit_leave(ir_dereference_record *ir)
257 {
258 ir->type = ir->record->type->fields.structure[ir->field_idx].type;
259 return visit_continue;
260 }
261 };
262
263
264 class array_resize_visitor : public deref_type_updater {
265 public:
266 using deref_type_updater::visit;
267
268 unsigned num_vertices;
269 gl_shader_program *prog;
270 gl_shader_stage stage;
271
array_resize_visitor(unsigned num_vertices,gl_shader_program * prog,gl_shader_stage stage)272 array_resize_visitor(unsigned num_vertices,
273 gl_shader_program *prog,
274 gl_shader_stage stage)
275 {
276 this->num_vertices = num_vertices;
277 this->prog = prog;
278 this->stage = stage;
279 }
280
~array_resize_visitor()281 virtual ~array_resize_visitor()
282 {
283 /* empty */
284 }
285
visit(ir_variable * var)286 virtual ir_visitor_status visit(ir_variable *var)
287 {
288 if (!glsl_type_is_array(var->type) || var->data.mode != ir_var_shader_in ||
289 var->data.patch)
290 return visit_continue;
291
292 unsigned size = var->type->length;
293
294 if (stage == MESA_SHADER_GEOMETRY) {
295 /* Generate a link error if the shader has declared this array with
296 * an incorrect size.
297 */
298 if (!var->data.implicit_sized_array &&
299 size && size != this->num_vertices) {
300 linker_error(this->prog, "size of array %s declared as %u, "
301 "but number of input vertices is %u\n",
302 var->name, size, this->num_vertices);
303 return visit_continue;
304 }
305
306 /* Generate a link error if the shader attempts to access an input
307 * array using an index too large for its actual size assigned at
308 * link time.
309 */
310 if (var->data.max_array_access >= (int)this->num_vertices) {
311 linker_error(this->prog, "%s shader accesses element %i of "
312 "%s, but only %i input vertices\n",
313 _mesa_shader_stage_to_string(this->stage),
314 var->data.max_array_access, var->name, this->num_vertices);
315 return visit_continue;
316 }
317 }
318
319 var->type = glsl_array_type(var->type->fields.array,
320 this->num_vertices, 0);
321 var->data.max_array_access = this->num_vertices - 1;
322
323 return visit_continue;
324 }
325 };
326
327 class array_length_to_const_visitor : public ir_rvalue_visitor {
328 public:
array_length_to_const_visitor()329 array_length_to_const_visitor()
330 {
331 this->progress = false;
332 }
333
~array_length_to_const_visitor()334 virtual ~array_length_to_const_visitor()
335 {
336 /* empty */
337 }
338
339 bool progress;
340
handle_rvalue(ir_rvalue ** rvalue)341 virtual void handle_rvalue(ir_rvalue **rvalue)
342 {
343 if (*rvalue == NULL || (*rvalue)->ir_type != ir_type_expression)
344 return;
345
346 ir_expression *expr = (*rvalue)->as_expression();
347 if (expr) {
348 if (expr->operation == ir_unop_implicitly_sized_array_length) {
349 assert(!glsl_type_is_unsized_array(expr->operands[0]->type));
350 ir_constant *constant = new(expr)
351 ir_constant(glsl_array_size(expr->operands[0]->type));
352 if (constant) {
353 *rvalue = constant;
354 }
355 }
356 }
357 }
358 };
359
360 } /* anonymous namespace */
361
362 void
linker_error(gl_shader_program * prog,const char * fmt,...)363 linker_error(gl_shader_program *prog, const char *fmt, ...)
364 {
365 va_list ap;
366
367 ralloc_strcat(&prog->data->InfoLog, "error: ");
368 va_start(ap, fmt);
369 ralloc_vasprintf_append(&prog->data->InfoLog, fmt, ap);
370 va_end(ap);
371
372 prog->data->LinkStatus = LINKING_FAILURE;
373 }
374
375
376 void
linker_warning(gl_shader_program * prog,const char * fmt,...)377 linker_warning(gl_shader_program *prog, const char *fmt, ...)
378 {
379 va_list ap;
380
381 ralloc_strcat(&prog->data->InfoLog, "warning: ");
382 va_start(ap, fmt);
383 ralloc_vasprintf_append(&prog->data->InfoLog, fmt, ap);
384 va_end(ap);
385
386 }
387
388
389 /**
390 * Set clip_distance_array_size based and cull_distance_array_size on the given
391 * shader.
392 *
393 * Also check for errors based on incorrect usage of gl_ClipVertex and
394 * gl_ClipDistance and gl_CullDistance.
395 * Additionally test whether the arrays gl_ClipDistance and gl_CullDistance
396 * exceed the maximum size defined by gl_MaxCombinedClipAndCullDistances.
397 *
398 * Return false if an error was reported.
399 */
400 static void
analyze_clip_cull_usage(struct gl_shader_program * prog,struct gl_linked_shader * shader,const struct gl_constants * consts,struct shader_info * info)401 analyze_clip_cull_usage(struct gl_shader_program *prog,
402 struct gl_linked_shader *shader,
403 const struct gl_constants *consts,
404 struct shader_info *info)
405 {
406 if (consts->DoDCEBeforeClipCullAnalysis) {
407 /* Remove dead functions to avoid raising an error (eg: dead function
408 * writes to gl_ClipVertex, and main() writes to gl_ClipDistance).
409 */
410 do_dead_functions(shader->ir);
411 }
412
413 info->clip_distance_array_size = 0;
414 info->cull_distance_array_size = 0;
415
416 if (prog->GLSL_Version >= (prog->IsES ? 300 : 130)) {
417 /* From section 7.1 (Vertex Shader Special Variables) of the
418 * GLSL 1.30 spec:
419 *
420 * "It is an error for a shader to statically write both
421 * gl_ClipVertex and gl_ClipDistance."
422 *
423 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
424 * gl_ClipVertex nor gl_ClipDistance. However with
425 * GL_EXT_clip_cull_distance, this functionality is exposed in ES 3.0.
426 */
427 find_variable gl_ClipDistance("gl_ClipDistance");
428 find_variable gl_CullDistance("gl_CullDistance");
429 find_variable gl_ClipVertex("gl_ClipVertex");
430 find_variable * const variables[] = {
431 &gl_ClipDistance,
432 &gl_CullDistance,
433 !prog->IsES ? &gl_ClipVertex : NULL,
434 NULL
435 };
436 find_assignments(shader->ir, variables);
437
438 /* From the ARB_cull_distance spec:
439 *
440 * It is a compile-time or link-time error for the set of shaders forming
441 * a program to statically read or write both gl_ClipVertex and either
442 * gl_ClipDistance or gl_CullDistance.
443 *
444 * This does not apply to GLSL ES shaders, since GLSL ES doesn't define
445 * gl_ClipVertex.
446 */
447 if (!prog->IsES) {
448 if (gl_ClipVertex.found && gl_ClipDistance.found) {
449 linker_error(prog, "%s shader writes to both `gl_ClipVertex' "
450 "and `gl_ClipDistance'\n",
451 _mesa_shader_stage_to_string(shader->Stage));
452 return;
453 }
454 if (gl_ClipVertex.found && gl_CullDistance.found) {
455 linker_error(prog, "%s shader writes to both `gl_ClipVertex' "
456 "and `gl_CullDistance'\n",
457 _mesa_shader_stage_to_string(shader->Stage));
458 return;
459 }
460 }
461
462 if (gl_ClipDistance.found) {
463 ir_variable *clip_distance_var =
464 shader->symbols->get_variable("gl_ClipDistance");
465 assert(clip_distance_var);
466 info->clip_distance_array_size = clip_distance_var->type->length;
467 }
468 if (gl_CullDistance.found) {
469 ir_variable *cull_distance_var =
470 shader->symbols->get_variable("gl_CullDistance");
471 assert(cull_distance_var);
472 info->cull_distance_array_size = cull_distance_var->type->length;
473 }
474 /* From the ARB_cull_distance spec:
475 *
476 * It is a compile-time or link-time error for the set of shaders forming
477 * a program to have the sum of the sizes of the gl_ClipDistance and
478 * gl_CullDistance arrays to be larger than
479 * gl_MaxCombinedClipAndCullDistances.
480 */
481 if ((uint32_t)(info->clip_distance_array_size + info->cull_distance_array_size) >
482 consts->MaxClipPlanes) {
483 linker_error(prog, "%s shader: the combined size of "
484 "'gl_ClipDistance' and 'gl_CullDistance' size cannot "
485 "be larger than "
486 "gl_MaxCombinedClipAndCullDistances (%u)",
487 _mesa_shader_stage_to_string(shader->Stage),
488 consts->MaxClipPlanes);
489 }
490 }
491 }
492
493
494 /**
495 * Verify that a vertex shader executable meets all semantic requirements.
496 *
497 * Also sets info.clip_distance_array_size and
498 * info.cull_distance_array_size as a side effect.
499 *
500 * \param shader Vertex shader executable to be verified
501 */
502 static void
validate_vertex_shader_executable(struct gl_shader_program * prog,struct gl_linked_shader * shader,const struct gl_constants * consts)503 validate_vertex_shader_executable(struct gl_shader_program *prog,
504 struct gl_linked_shader *shader,
505 const struct gl_constants *consts)
506 {
507 if (shader == NULL)
508 return;
509
510 /* From the GLSL 1.10 spec, page 48:
511 *
512 * "The variable gl_Position is available only in the vertex
513 * language and is intended for writing the homogeneous vertex
514 * position. All executions of a well-formed vertex shader
515 * executable must write a value into this variable. [...] The
516 * variable gl_Position is available only in the vertex
517 * language and is intended for writing the homogeneous vertex
518 * position. All executions of a well-formed vertex shader
519 * executable must write a value into this variable."
520 *
521 * while in GLSL 1.40 this text is changed to:
522 *
523 * "The variable gl_Position is available only in the vertex
524 * language and is intended for writing the homogeneous vertex
525 * position. It can be written at any time during shader
526 * execution. It may also be read back by a vertex shader
527 * after being written. This value will be used by primitive
528 * assembly, clipping, culling, and other fixed functionality
529 * operations, if present, that operate on primitives after
530 * vertex processing has occurred. Its value is undefined if
531 * the vertex shader executable does not write gl_Position."
532 *
533 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
534 * gl_Position is not an error.
535 */
536 if (prog->GLSL_Version < (prog->IsES ? 300 : 140)) {
537 find_variable gl_Position("gl_Position");
538 find_assignments(shader->ir, &gl_Position);
539 if (!gl_Position.found) {
540 if (prog->IsES) {
541 linker_warning(prog,
542 "vertex shader does not write to `gl_Position'. "
543 "Its value is undefined. \n");
544 } else {
545 linker_error(prog,
546 "vertex shader does not write to `gl_Position'. \n");
547 }
548 return;
549 }
550 }
551
552 analyze_clip_cull_usage(prog, shader, consts, &shader->Program->info);
553 }
554
555 static void
validate_tess_eval_shader_executable(struct gl_shader_program * prog,struct gl_linked_shader * shader,const struct gl_constants * consts)556 validate_tess_eval_shader_executable(struct gl_shader_program *prog,
557 struct gl_linked_shader *shader,
558 const struct gl_constants *consts)
559 {
560 if (shader == NULL)
561 return;
562
563 analyze_clip_cull_usage(prog, shader, consts, &shader->Program->info);
564 }
565
566
567 /**
568 * Verify that a fragment shader executable meets all semantic requirements
569 *
570 * \param shader Fragment shader executable to be verified
571 */
572 static void
validate_fragment_shader_executable(struct gl_shader_program * prog,struct gl_linked_shader * shader)573 validate_fragment_shader_executable(struct gl_shader_program *prog,
574 struct gl_linked_shader *shader)
575 {
576 if (shader == NULL)
577 return;
578
579 find_variable gl_FragColor("gl_FragColor");
580 find_variable gl_FragData("gl_FragData");
581 find_variable * const variables[] = { &gl_FragColor, &gl_FragData, NULL };
582 find_assignments(shader->ir, variables);
583
584 if (gl_FragColor.found && gl_FragData.found) {
585 linker_error(prog, "fragment shader writes to both "
586 "`gl_FragColor' and `gl_FragData'\n");
587 }
588 }
589
590 /**
591 * Verify that a geometry shader executable meets all semantic requirements
592 *
593 * Also sets prog->Geom.VerticesIn, and info.clip_distance_array_sizeand
594 * info.cull_distance_array_size as a side effect.
595 *
596 * \param shader Geometry shader executable to be verified
597 */
598 static void
validate_geometry_shader_executable(struct gl_shader_program * prog,struct gl_linked_shader * shader,const struct gl_constants * consts)599 validate_geometry_shader_executable(struct gl_shader_program *prog,
600 struct gl_linked_shader *shader,
601 const struct gl_constants *consts)
602 {
603 if (shader == NULL)
604 return;
605
606 unsigned num_vertices =
607 mesa_vertices_per_prim(shader->Program->info.gs.input_primitive);
608 prog->Geom.VerticesIn = num_vertices;
609
610 analyze_clip_cull_usage(prog, shader, consts, &shader->Program->info);
611 }
612
613 bool
validate_intrastage_arrays(struct gl_shader_program * prog,ir_variable * const var,ir_variable * const existing,bool match_precision)614 validate_intrastage_arrays(struct gl_shader_program *prog,
615 ir_variable *const var,
616 ir_variable *const existing,
617 bool match_precision)
618 {
619 /* Consider the types to be "the same" if both types are arrays
620 * of the same type and one of the arrays is implicitly sized.
621 * In addition, set the type of the linked variable to the
622 * explicitly sized array.
623 */
624 if (glsl_type_is_array(var->type) && glsl_type_is_array(existing->type)) {
625 const glsl_type *no_array_var = var->type->fields.array;
626 const glsl_type *no_array_existing = existing->type->fields.array;
627 bool type_matches;
628
629 type_matches = (match_precision ?
630 no_array_var == no_array_existing :
631 glsl_type_compare_no_precision(no_array_var, no_array_existing));
632
633 if (type_matches &&
634 ((var->type->length == 0)|| (existing->type->length == 0))) {
635 if (var->type->length != 0) {
636 if ((int)var->type->length <= existing->data.max_array_access) {
637 linker_error(prog, "%s `%s' declared as type "
638 "`%s' but outermost dimension has an index"
639 " of `%i'\n",
640 mode_string(var),
641 var->name, glsl_get_type_name(var->type),
642 existing->data.max_array_access);
643 }
644 existing->type = var->type;
645 return true;
646 } else if (existing->type->length != 0) {
647 if((int)existing->type->length <= var->data.max_array_access &&
648 !existing->data.from_ssbo_unsized_array) {
649 linker_error(prog, "%s `%s' declared as type "
650 "`%s' but outermost dimension has an index"
651 " of `%i'\n",
652 mode_string(var),
653 var->name, glsl_get_type_name(existing->type),
654 var->data.max_array_access);
655 }
656 return true;
657 }
658 }
659 }
660 return false;
661 }
662
663
664 /**
665 * Perform validation of global variables used across multiple shaders
666 */
667 static void
cross_validate_globals(const struct gl_constants * consts,struct gl_shader_program * prog,struct exec_list * ir,glsl_symbol_table * variables,bool uniforms_only)668 cross_validate_globals(const struct gl_constants *consts,
669 struct gl_shader_program *prog,
670 struct exec_list *ir, glsl_symbol_table *variables,
671 bool uniforms_only)
672 {
673 foreach_in_list(ir_instruction, node, ir) {
674 ir_variable *const var = node->as_variable();
675
676 if (var == NULL)
677 continue;
678
679 if (uniforms_only && (var->data.mode != ir_var_uniform && var->data.mode != ir_var_shader_storage))
680 continue;
681
682 /* don't cross validate subroutine uniforms */
683 if (glsl_contains_subroutine(var->type))
684 continue;
685
686 /* Don't cross validate interface instances. These are only relevant
687 * inside a shader. The cross validation is done at the Interface Block
688 * name level.
689 */
690 if (var->is_interface_instance())
691 continue;
692
693 /* Don't cross validate temporaries that are at global scope. These
694 * will eventually get pulled into the shaders 'main'.
695 */
696 if (var->data.mode == ir_var_temporary)
697 continue;
698
699 /* If a global with this name has already been seen, verify that the
700 * new instance has the same type. In addition, if the globals have
701 * initializers, the values of the initializers must be the same.
702 */
703 ir_variable *const existing = variables->get_variable(var->name);
704 if (existing != NULL) {
705 /* Check if types match. */
706 if (var->type != existing->type) {
707 if (!validate_intrastage_arrays(prog, var, existing)) {
708 /* If it is an unsized array in a Shader Storage Block,
709 * two different shaders can access to different elements.
710 * Because of that, they might be converted to different
711 * sized arrays, then check that they are compatible but
712 * ignore the array size.
713 */
714 if (!(var->data.mode == ir_var_shader_storage &&
715 var->data.from_ssbo_unsized_array &&
716 existing->data.mode == ir_var_shader_storage &&
717 existing->data.from_ssbo_unsized_array &&
718 var->type->gl_type == existing->type->gl_type)) {
719 linker_error(prog, "%s `%s' declared as type "
720 "`%s' and type `%s'\n",
721 mode_string(var),
722 var->name, glsl_get_type_name(var->type),
723 glsl_get_type_name(existing->type));
724 return;
725 }
726 }
727 }
728
729 if (var->data.explicit_location) {
730 if (existing->data.explicit_location
731 && (var->data.location != existing->data.location)) {
732 linker_error(prog, "explicit locations for %s "
733 "`%s' have differing values\n",
734 mode_string(var), var->name);
735 return;
736 }
737
738 if (var->data.location_frac != existing->data.location_frac) {
739 linker_error(prog, "explicit components for %s `%s' have "
740 "differing values\n", mode_string(var), var->name);
741 return;
742 }
743
744 existing->data.location = var->data.location;
745 existing->data.explicit_location = true;
746 } else {
747 /* Check if uniform with implicit location was marked explicit
748 * by earlier shader stage. If so, mark it explicit in this stage
749 * too to make sure later processing does not treat it as
750 * implicit one.
751 */
752 if (existing->data.explicit_location) {
753 var->data.location = existing->data.location;
754 var->data.explicit_location = true;
755 }
756 }
757
758 /* From the GLSL 4.20 specification:
759 * "A link error will result if two compilation units in a program
760 * specify different integer-constant bindings for the same
761 * opaque-uniform name. However, it is not an error to specify a
762 * binding on some but not all declarations for the same name"
763 */
764 if (var->data.explicit_binding) {
765 if (existing->data.explicit_binding &&
766 var->data.binding != existing->data.binding) {
767 linker_error(prog, "explicit bindings for %s "
768 "`%s' have differing values\n",
769 mode_string(var), var->name);
770 return;
771 }
772
773 existing->data.binding = var->data.binding;
774 existing->data.explicit_binding = true;
775 }
776
777 if (glsl_contains_atomic(var->type) &&
778 var->data.offset != existing->data.offset) {
779 linker_error(prog, "offset specifications for %s "
780 "`%s' have differing values\n",
781 mode_string(var), var->name);
782 return;
783 }
784
785 /* Validate layout qualifiers for gl_FragDepth.
786 *
787 * From the AMD/ARB_conservative_depth specs:
788 *
789 * "If gl_FragDepth is redeclared in any fragment shader in a
790 * program, it must be redeclared in all fragment shaders in
791 * that program that have static assignments to
792 * gl_FragDepth. All redeclarations of gl_FragDepth in all
793 * fragment shaders in a single program must have the same set
794 * of qualifiers."
795 */
796 if (strcmp(var->name, "gl_FragDepth") == 0) {
797 bool layout_declared = var->data.depth_layout != ir_depth_layout_none;
798 bool layout_differs =
799 var->data.depth_layout != existing->data.depth_layout;
800
801 if (layout_declared && layout_differs) {
802 linker_error(prog,
803 "All redeclarations of gl_FragDepth in all "
804 "fragment shaders in a single program must have "
805 "the same set of qualifiers.\n");
806 }
807
808 if (var->data.used && layout_differs) {
809 linker_error(prog,
810 "If gl_FragDepth is redeclared with a layout "
811 "qualifier in any fragment shader, it must be "
812 "redeclared with the same layout qualifier in "
813 "all fragment shaders that have assignments to "
814 "gl_FragDepth\n");
815 }
816 }
817
818 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
819 *
820 * "If a shared global has multiple initializers, the
821 * initializers must all be constant expressions, and they
822 * must all have the same value. Otherwise, a link error will
823 * result. (A shared global having only one initializer does
824 * not require that initializer to be a constant expression.)"
825 *
826 * Previous to 4.20 the GLSL spec simply said that initializers
827 * must have the same value. In this case of non-constant
828 * initializers, this was impossible to determine. As a result,
829 * no vendor actually implemented that behavior. The 4.20
830 * behavior matches the implemented behavior of at least one other
831 * vendor, so we'll implement that for all GLSL versions.
832 * If (at least) one of these constant expressions is implicit,
833 * because it was added by glsl_zero_init, we skip the verification.
834 */
835 if (var->constant_initializer != NULL) {
836 if (existing->constant_initializer != NULL &&
837 !existing->data.is_implicit_initializer &&
838 !var->data.is_implicit_initializer) {
839 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
840 linker_error(prog, "initializers for %s "
841 "`%s' have differing values\n",
842 mode_string(var), var->name);
843 return;
844 }
845 } else {
846 /* If the first-seen instance of a particular uniform did
847 * not have an initializer but a later instance does,
848 * replace the former with the later.
849 */
850 if (!var->data.is_implicit_initializer)
851 variables->replace_variable(existing->name, var);
852 }
853 }
854
855 if (var->data.has_initializer) {
856 if (existing->data.has_initializer
857 && (var->constant_initializer == NULL
858 || existing->constant_initializer == NULL)) {
859 linker_error(prog,
860 "shared global variable `%s' has multiple "
861 "non-constant initializers.\n",
862 var->name);
863 return;
864 }
865 }
866
867 if (existing->data.explicit_invariant != var->data.explicit_invariant) {
868 linker_error(prog, "declarations for %s `%s' have "
869 "mismatching invariant qualifiers\n",
870 mode_string(var), var->name);
871 return;
872 }
873 if (existing->data.centroid != var->data.centroid) {
874 linker_error(prog, "declarations for %s `%s' have "
875 "mismatching centroid qualifiers\n",
876 mode_string(var), var->name);
877 return;
878 }
879 if (existing->data.sample != var->data.sample) {
880 linker_error(prog, "declarations for %s `%s` have "
881 "mismatching sample qualifiers\n",
882 mode_string(var), var->name);
883 return;
884 }
885 if (existing->data.image_format != var->data.image_format) {
886 linker_error(prog, "declarations for %s `%s` have "
887 "mismatching image format qualifiers\n",
888 mode_string(var), var->name);
889 return;
890 }
891
892 /* Check the precision qualifier matches for uniform variables on
893 * GLSL ES.
894 */
895 if (!consts->AllowGLSLRelaxedES &&
896 prog->IsES && !var->get_interface_type() &&
897 existing->data.precision != var->data.precision) {
898 if ((existing->data.used && var->data.used) ||
899 prog->GLSL_Version >= 300) {
900 linker_error(prog, "declarations for %s `%s` have "
901 "mismatching precision qualifiers\n",
902 mode_string(var), var->name);
903 return;
904 } else {
905 linker_warning(prog, "declarations for %s `%s` have "
906 "mismatching precision qualifiers\n",
907 mode_string(var), var->name);
908 }
909 }
910
911 /* In OpenGL GLSL 3.20 spec, section 4.3.9:
912 *
913 * "It is a link-time error if any particular shader interface
914 * contains:
915 *
916 * - two different blocks, each having no instance name, and each
917 * having a member of the same name, or
918 *
919 * - a variable outside a block, and a block with no instance name,
920 * where the variable has the same name as a member in the block."
921 */
922 const glsl_type *var_itype = var->get_interface_type();
923 const glsl_type *existing_itype = existing->get_interface_type();
924 if (var_itype != existing_itype) {
925 if (!var_itype || !existing_itype) {
926 linker_error(prog, "declarations for %s `%s` are inside block "
927 "`%s` and outside a block",
928 mode_string(var), var->name,
929 glsl_get_type_name(var_itype ? var_itype : existing_itype));
930 return;
931 } else if (strcmp(glsl_get_type_name(var_itype), glsl_get_type_name(existing_itype)) != 0) {
932 linker_error(prog, "declarations for %s `%s` are inside blocks "
933 "`%s` and `%s`",
934 mode_string(var), var->name,
935 glsl_get_type_name(existing_itype),
936 glsl_get_type_name(var_itype));
937 return;
938 }
939 }
940 } else
941 variables->add_variable(var);
942 }
943 }
944
945
946 /**
947 * Perform validation of uniforms used across multiple shader stages
948 */
949 static void
cross_validate_uniforms(const struct gl_constants * consts,struct gl_shader_program * prog)950 cross_validate_uniforms(const struct gl_constants *consts,
951 struct gl_shader_program *prog)
952 {
953 glsl_symbol_table variables;
954 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
955 if (prog->_LinkedShaders[i] == NULL)
956 continue;
957
958 cross_validate_globals(consts, prog, prog->_LinkedShaders[i]->ir,
959 &variables, true);
960 }
961 }
962
963 /**
964 * Verifies the invariance of built-in special variables.
965 */
966 static bool
validate_invariant_builtins(struct gl_shader_program * prog,const gl_linked_shader * vert,const gl_linked_shader * frag)967 validate_invariant_builtins(struct gl_shader_program *prog,
968 const gl_linked_shader *vert,
969 const gl_linked_shader *frag)
970 {
971 const ir_variable *var_vert;
972 const ir_variable *var_frag;
973
974 if (!vert || !frag)
975 return true;
976
977 /*
978 * From OpenGL ES Shading Language 1.0 specification
979 * (4.6.4 Invariance and Linkage):
980 * "The invariance of varyings that are declared in both the vertex and
981 * fragment shaders must match. For the built-in special variables,
982 * gl_FragCoord can only be declared invariant if and only if
983 * gl_Position is declared invariant. Similarly gl_PointCoord can only
984 * be declared invariant if and only if gl_PointSize is declared
985 * invariant. It is an error to declare gl_FrontFacing as invariant.
986 * The invariance of gl_FrontFacing is the same as the invariance of
987 * gl_Position."
988 */
989 var_frag = frag->symbols->get_variable("gl_FragCoord");
990 if (var_frag && var_frag->data.invariant) {
991 var_vert = vert->symbols->get_variable("gl_Position");
992 if (var_vert && !var_vert->data.invariant) {
993 linker_error(prog,
994 "fragment shader built-in `%s' has invariant qualifier, "
995 "but vertex shader built-in `%s' lacks invariant qualifier\n",
996 var_frag->name, var_vert->name);
997 return false;
998 }
999 }
1000
1001 var_frag = frag->symbols->get_variable("gl_PointCoord");
1002 if (var_frag && var_frag->data.invariant) {
1003 var_vert = vert->symbols->get_variable("gl_PointSize");
1004 if (var_vert && !var_vert->data.invariant) {
1005 linker_error(prog,
1006 "fragment shader built-in `%s' has invariant qualifier, "
1007 "but vertex shader built-in `%s' lacks invariant qualifier\n",
1008 var_frag->name, var_vert->name);
1009 return false;
1010 }
1011 }
1012
1013 var_frag = frag->symbols->get_variable("gl_FrontFacing");
1014 if (var_frag && var_frag->data.invariant) {
1015 linker_error(prog,
1016 "fragment shader built-in `%s' can not be declared as invariant\n",
1017 var_frag->name);
1018 return false;
1019 }
1020
1021 return true;
1022 }
1023
1024 /**
1025 * Populates a shaders symbol table with all global declarations
1026 */
1027 static void
populate_symbol_table(gl_linked_shader * sh,glsl_symbol_table * symbols)1028 populate_symbol_table(gl_linked_shader *sh, glsl_symbol_table *symbols)
1029 {
1030 sh->symbols = new(sh) glsl_symbol_table;
1031
1032 _mesa_glsl_copy_symbols_from_table(sh->ir, symbols, sh->symbols);
1033 }
1034
1035
1036 /**
1037 * Remap variables referenced in an instruction tree
1038 *
1039 * This is used when instruction trees are cloned from one shader and placed in
1040 * another. These trees will contain references to \c ir_variable nodes that
1041 * do not exist in the target shader. This function finds these \c ir_variable
1042 * references and replaces the references with matching variables in the target
1043 * shader.
1044 *
1045 * If there is no matching variable in the target shader, a clone of the
1046 * \c ir_variable is made and added to the target shader. The new variable is
1047 * added to \b both the instruction stream and the symbol table.
1048 *
1049 * \param inst IR tree that is to be processed.
1050 * \param symbols Symbol table containing global scope symbols in the
1051 * linked shader.
1052 * \param instructions Instruction stream where new variable declarations
1053 * should be added.
1054 */
1055 static void
remap_variables(ir_instruction * inst,struct gl_linked_shader * target,hash_table * temps)1056 remap_variables(ir_instruction *inst, struct gl_linked_shader *target,
1057 hash_table *temps)
1058 {
1059 class remap_visitor : public ir_hierarchical_visitor {
1060 public:
1061 remap_visitor(struct gl_linked_shader *target, hash_table *temps)
1062 {
1063 this->target = target;
1064 this->symbols = target->symbols;
1065 this->instructions = target->ir;
1066 this->temps = temps;
1067 }
1068
1069 virtual ir_visitor_status visit(ir_dereference_variable *ir)
1070 {
1071 if (ir->var->data.mode == ir_var_temporary) {
1072 hash_entry *entry = _mesa_hash_table_search(temps, ir->var);
1073 ir_variable *var = entry ? (ir_variable *) entry->data : NULL;
1074
1075 assert(var != NULL);
1076 ir->var = var;
1077 return visit_continue;
1078 }
1079
1080 ir_variable *const existing =
1081 this->symbols->get_variable(ir->var->name);
1082 if (existing != NULL)
1083 ir->var = existing;
1084 else {
1085 ir_variable *copy = ir->var->clone(this->target, NULL);
1086
1087 this->symbols->add_variable(copy);
1088 this->instructions->push_head(copy);
1089 ir->var = copy;
1090 }
1091
1092 return visit_continue;
1093 }
1094
1095 private:
1096 struct gl_linked_shader *target;
1097 glsl_symbol_table *symbols;
1098 exec_list *instructions;
1099 hash_table *temps;
1100 };
1101
1102 remap_visitor v(target, temps);
1103
1104 inst->accept(&v);
1105 }
1106
1107
1108 /**
1109 * Move non-declarations from one instruction stream to another
1110 *
1111 * The intended usage pattern of this function is to pass the pointer to the
1112 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1113 * pointer) for \c last and \c false for \c make_copies on the first
1114 * call. Successive calls pass the return value of the previous call for
1115 * \c last and \c true for \c make_copies.
1116 *
1117 * \param instructions Source instruction stream
1118 * \param last Instruction after which new instructions should be
1119 * inserted in the target instruction stream
1120 * \param make_copies Flag selecting whether instructions in \c instructions
1121 * should be copied (via \c ir_instruction::clone) into the
1122 * target list or moved.
1123 *
1124 * \return
1125 * The new "last" instruction in the target instruction stream. This pointer
1126 * is suitable for use as the \c last parameter of a later call to this
1127 * function.
1128 */
1129 static exec_node *
move_non_declarations(exec_list * instructions,exec_node * last,bool make_copies,gl_linked_shader * target)1130 move_non_declarations(exec_list *instructions, exec_node *last,
1131 bool make_copies, gl_linked_shader *target)
1132 {
1133 hash_table *temps = NULL;
1134
1135 if (make_copies)
1136 temps = _mesa_pointer_hash_table_create(NULL);
1137
1138 foreach_in_list_safe(ir_instruction, inst, instructions) {
1139 if (inst->as_function())
1140 continue;
1141
1142 ir_variable *var = inst->as_variable();
1143 if ((var != NULL) && (var->data.mode != ir_var_temporary))
1144 continue;
1145
1146 assert(inst->as_assignment()
1147 || inst->as_call()
1148 || inst->as_if() /* for initializers with the ?: operator */
1149 || ((var != NULL) && (var->data.mode == ir_var_temporary)));
1150
1151 if (make_copies) {
1152 inst = inst->clone(target, NULL);
1153
1154 if (var != NULL)
1155 _mesa_hash_table_insert(temps, var, inst);
1156 else
1157 remap_variables(inst, target, temps);
1158 } else {
1159 inst->remove();
1160 }
1161
1162 last->insert_after(inst);
1163 last = inst;
1164 }
1165
1166 if (make_copies)
1167 _mesa_hash_table_destroy(temps, NULL);
1168
1169 return last;
1170 }
1171
1172
1173 /**
1174 * This class is only used in link_intrastage_shaders() below but declaring
1175 * it inside that function leads to compiler warnings with some versions of
1176 * gcc.
1177 */
1178 class array_sizing_visitor : public deref_type_updater {
1179 public:
1180 using deref_type_updater::visit;
1181
array_sizing_visitor()1182 array_sizing_visitor()
1183 : mem_ctx(ralloc_context(NULL)),
1184 unnamed_interfaces(_mesa_pointer_hash_table_create(NULL))
1185 {
1186 }
1187
~array_sizing_visitor()1188 ~array_sizing_visitor()
1189 {
1190 _mesa_hash_table_destroy(this->unnamed_interfaces, NULL);
1191 ralloc_free(this->mem_ctx);
1192 }
1193
visit(ir_variable * var)1194 virtual ir_visitor_status visit(ir_variable *var)
1195 {
1196 const glsl_type *type_without_array;
1197 bool implicit_sized_array = var->data.implicit_sized_array;
1198 fixup_type(&var->type, var->data.max_array_access,
1199 var->data.from_ssbo_unsized_array,
1200 &implicit_sized_array);
1201 var->data.implicit_sized_array = implicit_sized_array;
1202 type_without_array = glsl_without_array(var->type);
1203 if (glsl_type_is_interface(var->type)) {
1204 if (interface_contains_unsized_arrays(var->type)) {
1205 const glsl_type *new_type =
1206 resize_interface_members(var->type,
1207 var->get_max_ifc_array_access(),
1208 var->is_in_shader_storage_block());
1209 var->type = new_type;
1210 var->change_interface_type(new_type);
1211 }
1212 } else if (glsl_type_is_interface(type_without_array)) {
1213 if (interface_contains_unsized_arrays(type_without_array)) {
1214 const glsl_type *new_type =
1215 resize_interface_members(type_without_array,
1216 var->get_max_ifc_array_access(),
1217 var->is_in_shader_storage_block());
1218 var->change_interface_type(new_type);
1219 var->type = update_interface_members_array(var->type, new_type);
1220 }
1221 } else if (const glsl_type *ifc_type = var->get_interface_type()) {
1222 /* Store a pointer to the variable in the unnamed_interfaces
1223 * hashtable.
1224 */
1225 hash_entry *entry =
1226 _mesa_hash_table_search(this->unnamed_interfaces,
1227 ifc_type);
1228
1229 ir_variable **interface_vars = entry ? (ir_variable **) entry->data : NULL;
1230
1231 if (interface_vars == NULL) {
1232 interface_vars = rzalloc_array(mem_ctx, ir_variable *,
1233 ifc_type->length);
1234 _mesa_hash_table_insert(this->unnamed_interfaces, ifc_type,
1235 interface_vars);
1236 }
1237 unsigned index = glsl_get_field_index(ifc_type, var->name);
1238 assert(index < ifc_type->length);
1239 assert(interface_vars[index] == NULL);
1240 interface_vars[index] = var;
1241 }
1242 return visit_continue;
1243 }
1244
1245 /**
1246 * For each unnamed interface block that was discovered while running the
1247 * visitor, adjust the interface type to reflect the newly assigned array
1248 * sizes, and fix up the ir_variable nodes to point to the new interface
1249 * type.
1250 */
fixup_unnamed_interface_types()1251 void fixup_unnamed_interface_types()
1252 {
1253 hash_table_call_foreach(this->unnamed_interfaces,
1254 fixup_unnamed_interface_type, NULL);
1255 }
1256
1257 private:
1258 /**
1259 * If the type pointed to by \c type represents an unsized array, replace
1260 * it with a sized array whose size is determined by max_array_access.
1261 */
fixup_type(const glsl_type ** type,unsigned max_array_access,bool from_ssbo_unsized_array,bool * implicit_sized)1262 static void fixup_type(const glsl_type **type, unsigned max_array_access,
1263 bool from_ssbo_unsized_array, bool *implicit_sized)
1264 {
1265 if (!from_ssbo_unsized_array && glsl_type_is_unsized_array(*type)) {
1266 *type = glsl_array_type((*type)->fields.array,
1267 max_array_access + 1, 0);
1268 *implicit_sized = true;
1269 assert(*type != NULL);
1270 }
1271 }
1272
1273 static const glsl_type *
update_interface_members_array(const glsl_type * type,const glsl_type * new_interface_type)1274 update_interface_members_array(const glsl_type *type,
1275 const glsl_type *new_interface_type)
1276 {
1277 const glsl_type *element_type = type->fields.array;
1278 if (glsl_type_is_array(element_type)) {
1279 const glsl_type *new_array_type =
1280 update_interface_members_array(element_type, new_interface_type);
1281 return glsl_array_type(new_array_type, type->length, 0);
1282 } else {
1283 return glsl_array_type(new_interface_type, type->length, 0);
1284 }
1285 }
1286
1287 /**
1288 * Determine whether the given interface type contains unsized arrays (if
1289 * it doesn't, array_sizing_visitor doesn't need to process it).
1290 */
interface_contains_unsized_arrays(const glsl_type * type)1291 static bool interface_contains_unsized_arrays(const glsl_type *type)
1292 {
1293 for (unsigned i = 0; i < type->length; i++) {
1294 const glsl_type *elem_type = type->fields.structure[i].type;
1295 if (glsl_type_is_unsized_array(elem_type))
1296 return true;
1297 }
1298 return false;
1299 }
1300
1301 /**
1302 * Create a new interface type based on the given type, with unsized arrays
1303 * replaced by sized arrays whose size is determined by
1304 * max_ifc_array_access.
1305 */
1306 static const glsl_type *
resize_interface_members(const glsl_type * type,const int * max_ifc_array_access,bool is_ssbo)1307 resize_interface_members(const glsl_type *type,
1308 const int *max_ifc_array_access,
1309 bool is_ssbo)
1310 {
1311 unsigned num_fields = type->length;
1312 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1313 memcpy(fields, type->fields.structure,
1314 num_fields * sizeof(*fields));
1315 for (unsigned i = 0; i < num_fields; i++) {
1316 bool implicit_sized_array = fields[i].implicit_sized_array;
1317 /* If SSBO last member is unsized array, we don't replace it by a sized
1318 * array.
1319 */
1320 if (is_ssbo && i == (num_fields - 1))
1321 fixup_type(&fields[i].type, max_ifc_array_access[i],
1322 true, &implicit_sized_array);
1323 else
1324 fixup_type(&fields[i].type, max_ifc_array_access[i],
1325 false, &implicit_sized_array);
1326 fields[i].implicit_sized_array = implicit_sized_array;
1327 }
1328 glsl_interface_packing packing =
1329 (glsl_interface_packing) type->interface_packing;
1330 bool row_major = (bool) type->interface_row_major;
1331 const glsl_type *new_ifc_type =
1332 glsl_interface_type(fields, num_fields,
1333 packing, row_major, glsl_get_type_name(type));
1334 delete [] fields;
1335 return new_ifc_type;
1336 }
1337
fixup_unnamed_interface_type(const void * key,void * data,void *)1338 static void fixup_unnamed_interface_type(const void *key, void *data,
1339 void *)
1340 {
1341 const glsl_type *ifc_type = (const glsl_type *) key;
1342 ir_variable **interface_vars = (ir_variable **) data;
1343 unsigned num_fields = ifc_type->length;
1344 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1345 memcpy(fields, ifc_type->fields.structure,
1346 num_fields * sizeof(*fields));
1347 bool interface_type_changed = false;
1348 for (unsigned i = 0; i < num_fields; i++) {
1349 if (interface_vars[i] != NULL &&
1350 fields[i].type != interface_vars[i]->type) {
1351 fields[i].type = interface_vars[i]->type;
1352 interface_type_changed = true;
1353 }
1354 }
1355 if (!interface_type_changed) {
1356 delete [] fields;
1357 return;
1358 }
1359 glsl_interface_packing packing =
1360 (glsl_interface_packing) ifc_type->interface_packing;
1361 bool row_major = (bool) ifc_type->interface_row_major;
1362 const glsl_type *new_ifc_type =
1363 glsl_interface_type(fields, num_fields, packing,
1364 row_major, glsl_get_type_name(ifc_type));
1365 delete [] fields;
1366 for (unsigned i = 0; i < num_fields; i++) {
1367 if (interface_vars[i] != NULL)
1368 interface_vars[i]->change_interface_type(new_ifc_type);
1369 }
1370 }
1371
1372 /**
1373 * Memory context used to allocate the data in \c unnamed_interfaces.
1374 */
1375 void *mem_ctx;
1376
1377 /**
1378 * Hash table from const glsl_type * to an array of ir_variable *'s
1379 * pointing to the ir_variables constituting each unnamed interface block.
1380 */
1381 hash_table *unnamed_interfaces;
1382 };
1383
1384 static bool
validate_xfb_buffer_stride(const struct gl_constants * consts,unsigned idx,struct gl_shader_program * prog)1385 validate_xfb_buffer_stride(const struct gl_constants *consts, unsigned idx,
1386 struct gl_shader_program *prog)
1387 {
1388 /* We will validate doubles at a later stage */
1389 if (prog->TransformFeedback.BufferStride[idx] % 4) {
1390 linker_error(prog, "invalid qualifier xfb_stride=%d must be a "
1391 "multiple of 4 or if its applied to a type that is "
1392 "or contains a double a multiple of 8.",
1393 prog->TransformFeedback.BufferStride[idx]);
1394 return false;
1395 }
1396
1397 if (prog->TransformFeedback.BufferStride[idx] / 4 >
1398 consts->MaxTransformFeedbackInterleavedComponents) {
1399 linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1400 "limit has been exceeded.");
1401 return false;
1402 }
1403
1404 return true;
1405 }
1406
1407 /**
1408 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1409 * for later use.
1410 */
1411 static void
link_xfb_stride_layout_qualifiers(const struct gl_constants * consts,struct gl_shader_program * prog,struct gl_shader ** shader_list,unsigned num_shaders)1412 link_xfb_stride_layout_qualifiers(const struct gl_constants *consts,
1413 struct gl_shader_program *prog,
1414 struct gl_shader **shader_list,
1415 unsigned num_shaders)
1416 {
1417 for (unsigned i = 0; i < MAX_FEEDBACK_BUFFERS; i++) {
1418 prog->TransformFeedback.BufferStride[i] = 0;
1419 }
1420
1421 for (unsigned i = 0; i < num_shaders; i++) {
1422 struct gl_shader *shader = shader_list[i];
1423
1424 for (unsigned j = 0; j < MAX_FEEDBACK_BUFFERS; j++) {
1425 if (shader->TransformFeedbackBufferStride[j]) {
1426 if (prog->TransformFeedback.BufferStride[j] == 0) {
1427 prog->TransformFeedback.BufferStride[j] =
1428 shader->TransformFeedbackBufferStride[j];
1429 if (!validate_xfb_buffer_stride(consts, j, prog))
1430 return;
1431 } else if (prog->TransformFeedback.BufferStride[j] !=
1432 shader->TransformFeedbackBufferStride[j]){
1433 linker_error(prog,
1434 "intrastage shaders defined with conflicting "
1435 "xfb_stride for buffer %d (%d and %d)\n", j,
1436 prog->TransformFeedback.BufferStride[j],
1437 shader->TransformFeedbackBufferStride[j]);
1438 return;
1439 }
1440 }
1441 }
1442 }
1443 }
1444
1445 /**
1446 * Check for conflicting bindless/bound sampler/image layout qualifiers at
1447 * global scope.
1448 */
1449 static void
link_bindless_layout_qualifiers(struct gl_shader_program * prog,struct gl_shader ** shader_list,unsigned num_shaders)1450 link_bindless_layout_qualifiers(struct gl_shader_program *prog,
1451 struct gl_shader **shader_list,
1452 unsigned num_shaders)
1453 {
1454 bool bindless_sampler, bindless_image;
1455 bool bound_sampler, bound_image;
1456
1457 bindless_sampler = bindless_image = false;
1458 bound_sampler = bound_image = false;
1459
1460 for (unsigned i = 0; i < num_shaders; i++) {
1461 struct gl_shader *shader = shader_list[i];
1462
1463 if (shader->bindless_sampler)
1464 bindless_sampler = true;
1465 if (shader->bindless_image)
1466 bindless_image = true;
1467 if (shader->bound_sampler)
1468 bound_sampler = true;
1469 if (shader->bound_image)
1470 bound_image = true;
1471
1472 if ((bindless_sampler && bound_sampler) ||
1473 (bindless_image && bound_image)) {
1474 /* From section 4.4.6 of the ARB_bindless_texture spec:
1475 *
1476 * "If both bindless_sampler and bound_sampler, or bindless_image
1477 * and bound_image, are declared at global scope in any
1478 * compilation unit, a link- time error will be generated."
1479 */
1480 linker_error(prog, "both bindless_sampler and bound_sampler, or "
1481 "bindless_image and bound_image, can't be declared at "
1482 "global scope");
1483 }
1484 }
1485 }
1486
1487 /**
1488 * Check for conflicting viewport_relative settings across shaders, and sets
1489 * the value for the linked shader.
1490 */
1491 static void
link_layer_viewport_relative_qualifier(struct gl_shader_program * prog,struct gl_program * gl_prog,struct gl_shader ** shader_list,unsigned num_shaders)1492 link_layer_viewport_relative_qualifier(struct gl_shader_program *prog,
1493 struct gl_program *gl_prog,
1494 struct gl_shader **shader_list,
1495 unsigned num_shaders)
1496 {
1497 unsigned i;
1498
1499 /* Find first shader with explicit layer declaration */
1500 for (i = 0; i < num_shaders; i++) {
1501 if (shader_list[i]->redeclares_gl_layer) {
1502 gl_prog->info.layer_viewport_relative =
1503 shader_list[i]->layer_viewport_relative;
1504 break;
1505 }
1506 }
1507
1508 /* Now make sure that each subsequent shader's explicit layer declaration
1509 * matches the first one's.
1510 */
1511 for (; i < num_shaders; i++) {
1512 if (shader_list[i]->redeclares_gl_layer &&
1513 shader_list[i]->layer_viewport_relative !=
1514 gl_prog->info.layer_viewport_relative) {
1515 linker_error(prog, "all gl_Layer redeclarations must have identical "
1516 "viewport_relative settings");
1517 }
1518 }
1519 }
1520
1521 /**
1522 * Performs the cross-validation of tessellation control shader vertices and
1523 * layout qualifiers for the attached tessellation control shaders,
1524 * and propagates them to the linked TCS and linked shader program.
1525 */
1526 static void
link_tcs_out_layout_qualifiers(struct gl_shader_program * prog,struct gl_program * gl_prog,struct gl_shader ** shader_list,unsigned num_shaders)1527 link_tcs_out_layout_qualifiers(struct gl_shader_program *prog,
1528 struct gl_program *gl_prog,
1529 struct gl_shader **shader_list,
1530 unsigned num_shaders)
1531 {
1532 if (gl_prog->info.stage != MESA_SHADER_TESS_CTRL)
1533 return;
1534
1535 gl_prog->info.tess.tcs_vertices_out = 0;
1536
1537 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1538 *
1539 * "All tessellation control shader layout declarations in a program
1540 * must specify the same output patch vertex count. There must be at
1541 * least one layout qualifier specifying an output patch vertex count
1542 * in any program containing tessellation control shaders; however,
1543 * such a declaration is not required in all tessellation control
1544 * shaders."
1545 */
1546
1547 for (unsigned i = 0; i < num_shaders; i++) {
1548 struct gl_shader *shader = shader_list[i];
1549
1550 if (shader->info.TessCtrl.VerticesOut != 0) {
1551 if (gl_prog->info.tess.tcs_vertices_out != 0 &&
1552 gl_prog->info.tess.tcs_vertices_out !=
1553 (unsigned) shader->info.TessCtrl.VerticesOut) {
1554 linker_error(prog, "tessellation control shader defined with "
1555 "conflicting output vertex count (%d and %d)\n",
1556 gl_prog->info.tess.tcs_vertices_out,
1557 shader->info.TessCtrl.VerticesOut);
1558 return;
1559 }
1560 gl_prog->info.tess.tcs_vertices_out =
1561 shader->info.TessCtrl.VerticesOut;
1562 }
1563 }
1564
1565 /* Just do the intrastage -> interstage propagation right now,
1566 * since we already know we're in the right type of shader program
1567 * for doing it.
1568 */
1569 if (gl_prog->info.tess.tcs_vertices_out == 0) {
1570 linker_error(prog, "tessellation control shader didn't declare "
1571 "vertices out layout qualifier\n");
1572 return;
1573 }
1574 }
1575
1576
1577 /**
1578 * Performs the cross-validation of tessellation evaluation shader
1579 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1580 * for the attached tessellation evaluation shaders, and propagates them
1581 * to the linked TES and linked shader program.
1582 */
1583 static void
link_tes_in_layout_qualifiers(struct gl_shader_program * prog,struct gl_program * gl_prog,struct gl_shader ** shader_list,unsigned num_shaders)1584 link_tes_in_layout_qualifiers(struct gl_shader_program *prog,
1585 struct gl_program *gl_prog,
1586 struct gl_shader **shader_list,
1587 unsigned num_shaders)
1588 {
1589 if (gl_prog->info.stage != MESA_SHADER_TESS_EVAL)
1590 return;
1591
1592 int point_mode = -1;
1593 unsigned vertex_order = 0;
1594
1595 gl_prog->info.tess._primitive_mode = TESS_PRIMITIVE_UNSPECIFIED;
1596 gl_prog->info.tess.spacing = TESS_SPACING_UNSPECIFIED;
1597
1598 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1599 *
1600 * "At least one tessellation evaluation shader (compilation unit) in
1601 * a program must declare a primitive mode in its input layout.
1602 * Declaration vertex spacing, ordering, and point mode identifiers is
1603 * optional. It is not required that all tessellation evaluation
1604 * shaders in a program declare a primitive mode. If spacing or
1605 * vertex ordering declarations are omitted, the tessellation
1606 * primitive generator will use equal spacing or counter-clockwise
1607 * vertex ordering, respectively. If a point mode declaration is
1608 * omitted, the tessellation primitive generator will produce lines or
1609 * triangles according to the primitive mode."
1610 */
1611
1612 for (unsigned i = 0; i < num_shaders; i++) {
1613 struct gl_shader *shader = shader_list[i];
1614
1615 if (shader->info.TessEval._PrimitiveMode != TESS_PRIMITIVE_UNSPECIFIED) {
1616 if (gl_prog->info.tess._primitive_mode != TESS_PRIMITIVE_UNSPECIFIED &&
1617 gl_prog->info.tess._primitive_mode !=
1618 shader->info.TessEval._PrimitiveMode) {
1619 linker_error(prog, "tessellation evaluation shader defined with "
1620 "conflicting input primitive modes.\n");
1621 return;
1622 }
1623 gl_prog->info.tess._primitive_mode =
1624 shader->info.TessEval._PrimitiveMode;
1625 }
1626
1627 if (shader->info.TessEval.Spacing != 0) {
1628 if (gl_prog->info.tess.spacing != 0 && gl_prog->info.tess.spacing !=
1629 shader->info.TessEval.Spacing) {
1630 linker_error(prog, "tessellation evaluation shader defined with "
1631 "conflicting vertex spacing.\n");
1632 return;
1633 }
1634 gl_prog->info.tess.spacing = shader->info.TessEval.Spacing;
1635 }
1636
1637 if (shader->info.TessEval.VertexOrder != 0) {
1638 if (vertex_order != 0 &&
1639 vertex_order != shader->info.TessEval.VertexOrder) {
1640 linker_error(prog, "tessellation evaluation shader defined with "
1641 "conflicting ordering.\n");
1642 return;
1643 }
1644 vertex_order = shader->info.TessEval.VertexOrder;
1645 }
1646
1647 if (shader->info.TessEval.PointMode != -1) {
1648 if (point_mode != -1 &&
1649 point_mode != shader->info.TessEval.PointMode) {
1650 linker_error(prog, "tessellation evaluation shader defined with "
1651 "conflicting point modes.\n");
1652 return;
1653 }
1654 point_mode = shader->info.TessEval.PointMode;
1655 }
1656
1657 }
1658
1659 /* Just do the intrastage -> interstage propagation right now,
1660 * since we already know we're in the right type of shader program
1661 * for doing it.
1662 */
1663 if (gl_prog->info.tess._primitive_mode == TESS_PRIMITIVE_UNSPECIFIED) {
1664 linker_error(prog,
1665 "tessellation evaluation shader didn't declare input "
1666 "primitive modes.\n");
1667 return;
1668 }
1669
1670 if (gl_prog->info.tess.spacing == TESS_SPACING_UNSPECIFIED)
1671 gl_prog->info.tess.spacing = TESS_SPACING_EQUAL;
1672
1673 if (vertex_order == 0 || vertex_order == GL_CCW)
1674 gl_prog->info.tess.ccw = true;
1675 else
1676 gl_prog->info.tess.ccw = false;
1677
1678
1679 if (point_mode == -1 || point_mode == GL_FALSE)
1680 gl_prog->info.tess.point_mode = false;
1681 else
1682 gl_prog->info.tess.point_mode = true;
1683 }
1684
1685
1686 /**
1687 * Performs the cross-validation of layout qualifiers specified in
1688 * redeclaration of gl_FragCoord for the attached fragment shaders,
1689 * and propagates them to the linked FS and linked shader program.
1690 */
1691 static void
link_fs_inout_layout_qualifiers(struct gl_shader_program * prog,struct gl_linked_shader * linked_shader,struct gl_shader ** shader_list,unsigned num_shaders,bool arb_fragment_coord_conventions_enable)1692 link_fs_inout_layout_qualifiers(struct gl_shader_program *prog,
1693 struct gl_linked_shader *linked_shader,
1694 struct gl_shader **shader_list,
1695 unsigned num_shaders,
1696 bool arb_fragment_coord_conventions_enable)
1697 {
1698 bool redeclares_gl_fragcoord = false;
1699 bool uses_gl_fragcoord = false;
1700 bool origin_upper_left = false;
1701 bool pixel_center_integer = false;
1702
1703 if (linked_shader->Stage != MESA_SHADER_FRAGMENT ||
1704 (prog->GLSL_Version < 150 && !arb_fragment_coord_conventions_enable))
1705 return;
1706
1707 for (unsigned i = 0; i < num_shaders; i++) {
1708 struct gl_shader *shader = shader_list[i];
1709 /* From the GLSL 1.50 spec, page 39:
1710 *
1711 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1712 * it must be redeclared in all the fragment shaders in that program
1713 * that have a static use gl_FragCoord."
1714 */
1715 if ((redeclares_gl_fragcoord && !shader->redeclares_gl_fragcoord &&
1716 shader->uses_gl_fragcoord)
1717 || (shader->redeclares_gl_fragcoord && !redeclares_gl_fragcoord &&
1718 uses_gl_fragcoord)) {
1719 linker_error(prog, "fragment shader defined with conflicting "
1720 "layout qualifiers for gl_FragCoord\n");
1721 }
1722
1723 /* From the GLSL 1.50 spec, page 39:
1724 *
1725 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1726 * single program must have the same set of qualifiers."
1727 */
1728 if (redeclares_gl_fragcoord && shader->redeclares_gl_fragcoord &&
1729 (shader->origin_upper_left != origin_upper_left ||
1730 shader->pixel_center_integer != pixel_center_integer)) {
1731 linker_error(prog, "fragment shader defined with conflicting "
1732 "layout qualifiers for gl_FragCoord\n");
1733 }
1734
1735 /* Update the linked shader state. Note that uses_gl_fragcoord should
1736 * accumulate the results. The other values should replace. If there
1737 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1738 * are already known to be the same.
1739 */
1740 if (shader->redeclares_gl_fragcoord || shader->uses_gl_fragcoord) {
1741 redeclares_gl_fragcoord = shader->redeclares_gl_fragcoord;
1742 uses_gl_fragcoord |= shader->uses_gl_fragcoord;
1743 origin_upper_left = shader->origin_upper_left;
1744 pixel_center_integer = shader->pixel_center_integer;
1745 }
1746
1747 linked_shader->Program->info.fs.early_fragment_tests |=
1748 shader->EarlyFragmentTests || shader->PostDepthCoverage;
1749 linked_shader->Program->info.fs.inner_coverage |= shader->InnerCoverage;
1750 linked_shader->Program->info.fs.post_depth_coverage |=
1751 shader->PostDepthCoverage;
1752 linked_shader->Program->info.fs.pixel_interlock_ordered |=
1753 shader->PixelInterlockOrdered;
1754 linked_shader->Program->info.fs.pixel_interlock_unordered |=
1755 shader->PixelInterlockUnordered;
1756 linked_shader->Program->info.fs.sample_interlock_ordered |=
1757 shader->SampleInterlockOrdered;
1758 linked_shader->Program->info.fs.sample_interlock_unordered |=
1759 shader->SampleInterlockUnordered;
1760 linked_shader->Program->info.fs.advanced_blend_modes |= shader->BlendSupport;
1761 }
1762
1763 linked_shader->Program->info.fs.pixel_center_integer = pixel_center_integer;
1764 linked_shader->Program->info.fs.origin_upper_left = origin_upper_left;
1765 }
1766
1767 /**
1768 * Performs the cross-validation of geometry shader max_vertices and
1769 * primitive type layout qualifiers for the attached geometry shaders,
1770 * and propagates them to the linked GS and linked shader program.
1771 */
1772 static void
link_gs_inout_layout_qualifiers(struct gl_shader_program * prog,struct gl_program * gl_prog,struct gl_shader ** shader_list,unsigned num_shaders)1773 link_gs_inout_layout_qualifiers(struct gl_shader_program *prog,
1774 struct gl_program *gl_prog,
1775 struct gl_shader **shader_list,
1776 unsigned num_shaders)
1777 {
1778 /* No in/out qualifiers defined for anything but GLSL 1.50+
1779 * geometry shaders so far.
1780 */
1781 if (gl_prog->info.stage != MESA_SHADER_GEOMETRY || prog->GLSL_Version < 150)
1782 return;
1783
1784 int vertices_out = -1;
1785
1786 gl_prog->info.gs.invocations = 0;
1787 gl_prog->info.gs.input_primitive = MESA_PRIM_UNKNOWN;
1788 gl_prog->info.gs.output_primitive = MESA_PRIM_UNKNOWN;
1789
1790 /* From the GLSL 1.50 spec, page 46:
1791 *
1792 * "All geometry shader output layout declarations in a program
1793 * must declare the same layout and same value for
1794 * max_vertices. There must be at least one geometry output
1795 * layout declaration somewhere in a program, but not all
1796 * geometry shaders (compilation units) are required to
1797 * declare it."
1798 */
1799
1800 for (unsigned i = 0; i < num_shaders; i++) {
1801 struct gl_shader *shader = shader_list[i];
1802
1803 if (shader->info.Geom.InputType != MESA_PRIM_UNKNOWN) {
1804 if (gl_prog->info.gs.input_primitive != MESA_PRIM_UNKNOWN &&
1805 gl_prog->info.gs.input_primitive !=
1806 shader->info.Geom.InputType) {
1807 linker_error(prog, "geometry shader defined with conflicting "
1808 "input types\n");
1809 return;
1810 }
1811 gl_prog->info.gs.input_primitive = (enum mesa_prim)shader->info.Geom.InputType;
1812 }
1813
1814 if (shader->info.Geom.OutputType != MESA_PRIM_UNKNOWN) {
1815 if (gl_prog->info.gs.output_primitive != MESA_PRIM_UNKNOWN &&
1816 gl_prog->info.gs.output_primitive !=
1817 shader->info.Geom.OutputType) {
1818 linker_error(prog, "geometry shader defined with conflicting "
1819 "output types\n");
1820 return;
1821 }
1822 gl_prog->info.gs.output_primitive = (enum mesa_prim)shader->info.Geom.OutputType;
1823 }
1824
1825 if (shader->info.Geom.VerticesOut != -1) {
1826 if (vertices_out != -1 &&
1827 vertices_out != shader->info.Geom.VerticesOut) {
1828 linker_error(prog, "geometry shader defined with conflicting "
1829 "output vertex count (%d and %d)\n",
1830 vertices_out, shader->info.Geom.VerticesOut);
1831 return;
1832 }
1833 vertices_out = shader->info.Geom.VerticesOut;
1834 }
1835
1836 if (shader->info.Geom.Invocations != 0) {
1837 if (gl_prog->info.gs.invocations != 0 &&
1838 gl_prog->info.gs.invocations !=
1839 (unsigned) shader->info.Geom.Invocations) {
1840 linker_error(prog, "geometry shader defined with conflicting "
1841 "invocation count (%d and %d)\n",
1842 gl_prog->info.gs.invocations,
1843 shader->info.Geom.Invocations);
1844 return;
1845 }
1846 gl_prog->info.gs.invocations = shader->info.Geom.Invocations;
1847 }
1848 }
1849
1850 /* Just do the intrastage -> interstage propagation right now,
1851 * since we already know we're in the right type of shader program
1852 * for doing it.
1853 */
1854 if (gl_prog->info.gs.input_primitive == MESA_PRIM_UNKNOWN) {
1855 linker_error(prog,
1856 "geometry shader didn't declare primitive input type\n");
1857 return;
1858 }
1859
1860 if (gl_prog->info.gs.output_primitive == MESA_PRIM_UNKNOWN) {
1861 linker_error(prog,
1862 "geometry shader didn't declare primitive output type\n");
1863 return;
1864 }
1865
1866 if (vertices_out == -1) {
1867 linker_error(prog,
1868 "geometry shader didn't declare max_vertices\n");
1869 return;
1870 } else {
1871 gl_prog->info.gs.vertices_out = vertices_out;
1872 }
1873
1874 if (gl_prog->info.gs.invocations == 0)
1875 gl_prog->info.gs.invocations = 1;
1876 }
1877
1878
1879 /**
1880 * Perform cross-validation of compute shader local_size_{x,y,z} layout and
1881 * derivative arrangement qualifiers for the attached compute shaders, and
1882 * propagate them to the linked CS and linked shader program.
1883 */
1884 static void
link_cs_input_layout_qualifiers(struct gl_shader_program * prog,struct gl_program * gl_prog,struct gl_shader ** shader_list,unsigned num_shaders)1885 link_cs_input_layout_qualifiers(struct gl_shader_program *prog,
1886 struct gl_program *gl_prog,
1887 struct gl_shader **shader_list,
1888 unsigned num_shaders)
1889 {
1890 /* This function is called for all shader stages, but it only has an effect
1891 * for compute shaders.
1892 */
1893 if (gl_prog->info.stage != MESA_SHADER_COMPUTE)
1894 return;
1895
1896 for (int i = 0; i < 3; i++)
1897 gl_prog->info.workgroup_size[i] = 0;
1898
1899 gl_prog->info.workgroup_size_variable = false;
1900
1901 gl_prog->info.cs.derivative_group = DERIVATIVE_GROUP_NONE;
1902
1903 /* From the ARB_compute_shader spec, in the section describing local size
1904 * declarations:
1905 *
1906 * If multiple compute shaders attached to a single program object
1907 * declare local work-group size, the declarations must be identical;
1908 * otherwise a link-time error results. Furthermore, if a program
1909 * object contains any compute shaders, at least one must contain an
1910 * input layout qualifier specifying the local work sizes of the
1911 * program, or a link-time error will occur.
1912 */
1913 for (unsigned sh = 0; sh < num_shaders; sh++) {
1914 struct gl_shader *shader = shader_list[sh];
1915
1916 if (shader->info.Comp.LocalSize[0] != 0) {
1917 if (gl_prog->info.workgroup_size[0] != 0) {
1918 for (int i = 0; i < 3; i++) {
1919 if (gl_prog->info.workgroup_size[i] !=
1920 shader->info.Comp.LocalSize[i]) {
1921 linker_error(prog, "compute shader defined with conflicting "
1922 "local sizes\n");
1923 return;
1924 }
1925 }
1926 }
1927 for (int i = 0; i < 3; i++) {
1928 gl_prog->info.workgroup_size[i] =
1929 shader->info.Comp.LocalSize[i];
1930 }
1931 } else if (shader->info.Comp.LocalSizeVariable) {
1932 if (gl_prog->info.workgroup_size[0] != 0) {
1933 /* The ARB_compute_variable_group_size spec says:
1934 *
1935 * If one compute shader attached to a program declares a
1936 * variable local group size and a second compute shader
1937 * attached to the same program declares a fixed local group
1938 * size, a link-time error results.
1939 */
1940 linker_error(prog, "compute shader defined with both fixed and "
1941 "variable local group size\n");
1942 return;
1943 }
1944 gl_prog->info.workgroup_size_variable = true;
1945 }
1946
1947 enum gl_derivative_group group = shader->info.Comp.DerivativeGroup;
1948 if (group != DERIVATIVE_GROUP_NONE) {
1949 if (gl_prog->info.cs.derivative_group != DERIVATIVE_GROUP_NONE &&
1950 gl_prog->info.cs.derivative_group != group) {
1951 linker_error(prog, "compute shader defined with conflicting "
1952 "derivative groups\n");
1953 return;
1954 }
1955 gl_prog->info.cs.derivative_group = group;
1956 }
1957 }
1958
1959 /* Just do the intrastage -> interstage propagation right now,
1960 * since we already know we're in the right type of shader program
1961 * for doing it.
1962 */
1963 if (gl_prog->info.workgroup_size[0] == 0 &&
1964 !gl_prog->info.workgroup_size_variable) {
1965 linker_error(prog, "compute shader must contain a fixed or a variable "
1966 "local group size\n");
1967 return;
1968 }
1969
1970 if (gl_prog->info.cs.derivative_group == DERIVATIVE_GROUP_QUADS) {
1971 if (gl_prog->info.workgroup_size[0] % 2 != 0) {
1972 linker_error(prog, "derivative_group_quadsNV must be used with a "
1973 "local group size whose first dimension "
1974 "is a multiple of 2\n");
1975 return;
1976 }
1977 if (gl_prog->info.workgroup_size[1] % 2 != 0) {
1978 linker_error(prog, "derivative_group_quadsNV must be used with a local"
1979 "group size whose second dimension "
1980 "is a multiple of 2\n");
1981 return;
1982 }
1983 } else if (gl_prog->info.cs.derivative_group == DERIVATIVE_GROUP_LINEAR) {
1984 if ((gl_prog->info.workgroup_size[0] *
1985 gl_prog->info.workgroup_size[1] *
1986 gl_prog->info.workgroup_size[2]) % 4 != 0) {
1987 linker_error(prog, "derivative_group_linearNV must be used with a "
1988 "local group size whose total number of invocations "
1989 "is a multiple of 4\n");
1990 return;
1991 }
1992 }
1993 }
1994
1995 /**
1996 * Link all out variables on a single stage which are not
1997 * directly used in a shader with the main function.
1998 */
1999 static void
link_output_variables(struct gl_linked_shader * linked_shader,struct gl_shader ** shader_list,unsigned num_shaders)2000 link_output_variables(struct gl_linked_shader *linked_shader,
2001 struct gl_shader **shader_list,
2002 unsigned num_shaders)
2003 {
2004 struct glsl_symbol_table *symbols = linked_shader->symbols;
2005
2006 for (unsigned i = 0; i < num_shaders; i++) {
2007
2008 /* Skip shader object with main function */
2009 if (shader_list[i]->symbols->get_function("main"))
2010 continue;
2011
2012 foreach_in_list(ir_instruction, ir, shader_list[i]->ir) {
2013 if (ir->ir_type != ir_type_variable)
2014 continue;
2015
2016 ir_variable *var = (ir_variable *) ir;
2017
2018 if (var->data.mode == ir_var_shader_out &&
2019 !symbols->get_variable(var->name)) {
2020 var = var->clone(linked_shader, NULL);
2021 symbols->add_variable(var);
2022 linked_shader->ir->push_head(var);
2023 }
2024 }
2025 }
2026
2027 return;
2028 }
2029
2030
2031 /**
2032 * Combine a group of shaders for a single stage to generate a linked shader
2033 *
2034 * \note
2035 * If this function is supplied a single shader, it is cloned, and the new
2036 * shader is returned.
2037 */
2038 struct gl_linked_shader *
link_intrastage_shaders(void * mem_ctx,struct gl_context * ctx,struct gl_shader_program * prog,struct gl_shader ** shader_list,unsigned num_shaders,bool allow_missing_main)2039 link_intrastage_shaders(void *mem_ctx,
2040 struct gl_context *ctx,
2041 struct gl_shader_program *prog,
2042 struct gl_shader **shader_list,
2043 unsigned num_shaders,
2044 bool allow_missing_main)
2045 {
2046 bool arb_fragment_coord_conventions_enable = false;
2047
2048 /* Check that global variables defined in multiple shaders are consistent.
2049 */
2050 glsl_symbol_table variables;
2051 for (unsigned i = 0; i < num_shaders; i++) {
2052 if (shader_list[i] == NULL)
2053 continue;
2054 cross_validate_globals(&ctx->Const, prog, shader_list[i]->ir, &variables,
2055 false);
2056 if (shader_list[i]->ARB_fragment_coord_conventions_enable)
2057 arb_fragment_coord_conventions_enable = true;
2058 }
2059
2060 if (!prog->data->LinkStatus)
2061 return NULL;
2062
2063 /* Check that interface blocks defined in multiple shaders are consistent.
2064 */
2065 validate_intrastage_interface_blocks(prog, (const gl_shader **)shader_list,
2066 num_shaders);
2067 if (!prog->data->LinkStatus)
2068 return NULL;
2069
2070 /* Check that there is only a single definition of each function signature
2071 * across all shaders.
2072 */
2073 for (unsigned i = 0; i < (num_shaders - 1); i++) {
2074 foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
2075 ir_function *const f = node->as_function();
2076
2077 if (f == NULL)
2078 continue;
2079
2080 for (unsigned j = i + 1; j < num_shaders; j++) {
2081 ir_function *const other =
2082 shader_list[j]->symbols->get_function(f->name);
2083
2084 /* If the other shader has no function (and therefore no function
2085 * signatures) with the same name, skip to the next shader.
2086 */
2087 if (other == NULL)
2088 continue;
2089
2090 foreach_in_list(ir_function_signature, sig, &f->signatures) {
2091 if (!sig->is_defined)
2092 continue;
2093
2094 ir_function_signature *other_sig =
2095 other->exact_matching_signature(NULL, &sig->parameters);
2096
2097 if (other_sig != NULL && other_sig->is_defined) {
2098 linker_error(prog, "function `%s' is multiply defined\n",
2099 f->name);
2100 return NULL;
2101 }
2102 }
2103 }
2104 }
2105 }
2106
2107 /* Find the shader that defines main, and make a clone of it.
2108 *
2109 * Starting with the clone, search for undefined references. If one is
2110 * found, find the shader that defines it. Clone the reference and add
2111 * it to the shader. Repeat until there are no undefined references or
2112 * until a reference cannot be resolved.
2113 */
2114 gl_shader *main = NULL;
2115 for (unsigned i = 0; i < num_shaders; i++) {
2116 if (_mesa_get_main_function_signature(shader_list[i]->symbols)) {
2117 main = shader_list[i];
2118 break;
2119 }
2120 }
2121
2122 if (main == NULL && allow_missing_main)
2123 main = shader_list[0];
2124
2125 if (main == NULL) {
2126 linker_error(prog, "%s shader lacks `main'\n",
2127 _mesa_shader_stage_to_string(shader_list[0]->Stage));
2128 return NULL;
2129 }
2130
2131 gl_linked_shader *linked = rzalloc(NULL, struct gl_linked_shader);
2132 linked->Stage = shader_list[0]->Stage;
2133
2134 /* Create program and attach it to the linked shader */
2135 struct gl_program *gl_prog =
2136 ctx->Driver.NewProgram(ctx, shader_list[0]->Stage, prog->Name, false);
2137 if (!gl_prog) {
2138 prog->data->LinkStatus = LINKING_FAILURE;
2139 _mesa_delete_linked_shader(ctx, linked);
2140 return NULL;
2141 }
2142
2143 _mesa_reference_shader_program_data(&gl_prog->sh.data, prog->data);
2144
2145 /* Don't use _mesa_reference_program() just take ownership */
2146 linked->Program = gl_prog;
2147
2148 linked->ir = new(linked) exec_list;
2149 clone_ir_list(mem_ctx, linked->ir, main->ir);
2150
2151 link_fs_inout_layout_qualifiers(prog, linked, shader_list, num_shaders,
2152 arb_fragment_coord_conventions_enable);
2153 link_tcs_out_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2154 link_tes_in_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2155 link_gs_inout_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2156 link_cs_input_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2157
2158 if (linked->Stage != MESA_SHADER_FRAGMENT)
2159 link_xfb_stride_layout_qualifiers(&ctx->Const, prog, shader_list, num_shaders);
2160
2161 link_bindless_layout_qualifiers(prog, shader_list, num_shaders);
2162
2163 link_layer_viewport_relative_qualifier(prog, gl_prog, shader_list, num_shaders);
2164
2165 populate_symbol_table(linked, shader_list[0]->symbols);
2166
2167 /* The pointer to the main function in the final linked shader (i.e., the
2168 * copy of the original shader that contained the main function).
2169 */
2170 ir_function_signature *const main_sig =
2171 _mesa_get_main_function_signature(linked->symbols);
2172
2173 /* Move any instructions other than variable declarations or function
2174 * declarations into main.
2175 */
2176 if (main_sig != NULL) {
2177 exec_node *insertion_point =
2178 move_non_declarations(linked->ir, &main_sig->body.head_sentinel, false,
2179 linked);
2180
2181 for (unsigned i = 0; i < num_shaders; i++) {
2182 if (shader_list[i] == main)
2183 continue;
2184
2185 insertion_point = move_non_declarations(shader_list[i]->ir,
2186 insertion_point, true, linked);
2187 }
2188 }
2189
2190 if (!link_function_calls(prog, linked, shader_list, num_shaders)) {
2191 _mesa_delete_linked_shader(ctx, linked);
2192 return NULL;
2193 }
2194
2195 if (linked->Stage != MESA_SHADER_FRAGMENT)
2196 link_output_variables(linked, shader_list, num_shaders);
2197
2198 /* Make a pass over all variable declarations to ensure that arrays with
2199 * unspecified sizes have a size specified. The size is inferred from the
2200 * max_array_access field.
2201 */
2202 array_sizing_visitor v;
2203 v.run(linked->ir);
2204 v.fixup_unnamed_interface_types();
2205
2206 /* Now that we know the sizes of all the arrays, we can replace .length()
2207 * calls with a constant expression.
2208 */
2209 array_length_to_const_visitor len_v;
2210 len_v.run(linked->ir);
2211
2212 if (!prog->data->LinkStatus) {
2213 _mesa_delete_linked_shader(ctx, linked);
2214 return NULL;
2215 }
2216
2217 /* At this point linked should contain all of the linked IR, so
2218 * validate it to make sure nothing went wrong.
2219 */
2220 validate_ir_tree(linked->ir);
2221
2222 /* Set the size of geometry shader input arrays */
2223 if (linked->Stage == MESA_SHADER_GEOMETRY) {
2224 unsigned num_vertices =
2225 mesa_vertices_per_prim(gl_prog->info.gs.input_primitive);
2226 array_resize_visitor input_resize_visitor(num_vertices, prog,
2227 MESA_SHADER_GEOMETRY);
2228 foreach_in_list(ir_instruction, ir, linked->ir) {
2229 ir->accept(&input_resize_visitor);
2230 }
2231 }
2232
2233 /* Set the linked source SHA1. */
2234 if (num_shaders == 1) {
2235 memcpy(linked->linked_source_sha1, shader_list[0]->compiled_source_sha1,
2236 SHA1_DIGEST_LENGTH);
2237 } else {
2238 struct mesa_sha1 sha1_ctx;
2239 _mesa_sha1_init(&sha1_ctx);
2240
2241 for (unsigned i = 0; i < num_shaders; i++) {
2242 if (shader_list[i] == NULL)
2243 continue;
2244
2245 _mesa_sha1_update(&sha1_ctx, shader_list[i]->compiled_source_sha1,
2246 SHA1_DIGEST_LENGTH);
2247 }
2248 _mesa_sha1_final(&sha1_ctx, linked->linked_source_sha1);
2249 }
2250
2251 return linked;
2252 }
2253
2254 /**
2255 * Resize tessellation evaluation per-vertex inputs to the size of
2256 * tessellation control per-vertex outputs.
2257 */
2258 static void
resize_tes_inputs(const struct gl_constants * consts,struct gl_shader_program * prog)2259 resize_tes_inputs(const struct gl_constants *consts,
2260 struct gl_shader_program *prog)
2261 {
2262 if (prog->_LinkedShaders[MESA_SHADER_TESS_EVAL] == NULL)
2263 return;
2264
2265 gl_linked_shader *const tcs = prog->_LinkedShaders[MESA_SHADER_TESS_CTRL];
2266 gl_linked_shader *const tes = prog->_LinkedShaders[MESA_SHADER_TESS_EVAL];
2267
2268 /* If no control shader is present, then the TES inputs are statically
2269 * sized to MaxPatchVertices; the actual size of the arrays won't be
2270 * known until draw time.
2271 */
2272 const int num_vertices = tcs
2273 ? tcs->Program->info.tess.tcs_vertices_out
2274 : consts->MaxPatchVertices;
2275
2276 array_resize_visitor input_resize_visitor(num_vertices, prog,
2277 MESA_SHADER_TESS_EVAL);
2278 foreach_in_list(ir_instruction, ir, tes->ir) {
2279 ir->accept(&input_resize_visitor);
2280 }
2281
2282 if (tcs) {
2283 /* Convert the gl_PatchVerticesIn system value into a constant, since
2284 * the value is known at this point.
2285 */
2286 foreach_in_list(ir_instruction, ir, tes->ir) {
2287 ir_variable *var = ir->as_variable();
2288 if (var && var->data.mode == ir_var_system_value &&
2289 var->data.location == SYSTEM_VALUE_VERTICES_IN) {
2290 void *mem_ctx = ralloc_parent(var);
2291 var->data.location = 0;
2292 var->data.explicit_location = false;
2293 var->data.mode = ir_var_auto;
2294 var->constant_value = new(mem_ctx) ir_constant(num_vertices);
2295 }
2296 }
2297 }
2298 }
2299
2300
2301 /**
2302 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
2303 * for a variable, checks for overlaps between other uniforms using explicit
2304 * locations.
2305 */
2306 static int
reserve_explicit_locations(struct gl_shader_program * prog,string_to_uint_map * map,ir_variable * var)2307 reserve_explicit_locations(struct gl_shader_program *prog,
2308 string_to_uint_map *map, ir_variable *var)
2309 {
2310 unsigned slots = glsl_type_uniform_locations(var->type);
2311 unsigned max_loc = var->data.location + slots - 1;
2312 unsigned return_value = slots;
2313
2314 /* Resize remap table if locations do not fit in the current one. */
2315 if (max_loc + 1 > prog->NumUniformRemapTable) {
2316 prog->UniformRemapTable =
2317 reralloc(prog, prog->UniformRemapTable,
2318 gl_uniform_storage *,
2319 max_loc + 1);
2320
2321 if (!prog->UniformRemapTable) {
2322 linker_error(prog, "Out of memory during linking.\n");
2323 return -1;
2324 }
2325
2326 /* Initialize allocated space. */
2327 for (unsigned i = prog->NumUniformRemapTable; i < max_loc + 1; i++)
2328 prog->UniformRemapTable[i] = NULL;
2329
2330 prog->NumUniformRemapTable = max_loc + 1;
2331 }
2332
2333 for (unsigned i = 0; i < slots; i++) {
2334 unsigned loc = var->data.location + i;
2335
2336 /* Check if location is already used. */
2337 if (prog->UniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
2338
2339 /* Possibly same uniform from a different stage, this is ok. */
2340 unsigned hash_loc;
2341 if (map->get(hash_loc, var->name) && hash_loc == loc - i) {
2342 return_value = 0;
2343 continue;
2344 }
2345
2346 /* ARB_explicit_uniform_location specification states:
2347 *
2348 * "No two default-block uniform variables in the program can have
2349 * the same location, even if they are unused, otherwise a compiler
2350 * or linker error will be generated."
2351 */
2352 linker_error(prog,
2353 "location qualifier for uniform %s overlaps "
2354 "previously used location\n",
2355 var->name);
2356 return -1;
2357 }
2358
2359 /* Initialize location as inactive before optimization
2360 * rounds and location assignment.
2361 */
2362 prog->UniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
2363 }
2364
2365 /* Note, base location used for arrays. */
2366 map->put(var->data.location, var->name);
2367
2368 return return_value;
2369 }
2370
2371 static bool
reserve_subroutine_explicit_locations(struct gl_shader_program * prog,struct gl_program * p,ir_variable * var)2372 reserve_subroutine_explicit_locations(struct gl_shader_program *prog,
2373 struct gl_program *p,
2374 ir_variable *var)
2375 {
2376 unsigned slots = glsl_type_uniform_locations(var->type);
2377 unsigned max_loc = var->data.location + slots - 1;
2378
2379 /* Resize remap table if locations do not fit in the current one. */
2380 if (max_loc + 1 > p->sh.NumSubroutineUniformRemapTable) {
2381 p->sh.SubroutineUniformRemapTable =
2382 reralloc(p, p->sh.SubroutineUniformRemapTable,
2383 gl_uniform_storage *,
2384 max_loc + 1);
2385
2386 if (!p->sh.SubroutineUniformRemapTable) {
2387 linker_error(prog, "Out of memory during linking.\n");
2388 return false;
2389 }
2390
2391 /* Initialize allocated space. */
2392 for (unsigned i = p->sh.NumSubroutineUniformRemapTable; i < max_loc + 1; i++)
2393 p->sh.SubroutineUniformRemapTable[i] = NULL;
2394
2395 p->sh.NumSubroutineUniformRemapTable = max_loc + 1;
2396 }
2397
2398 for (unsigned i = 0; i < slots; i++) {
2399 unsigned loc = var->data.location + i;
2400
2401 /* Check if location is already used. */
2402 if (p->sh.SubroutineUniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
2403
2404 /* ARB_explicit_uniform_location specification states:
2405 * "No two subroutine uniform variables can have the same location
2406 * in the same shader stage, otherwise a compiler or linker error
2407 * will be generated."
2408 */
2409 linker_error(prog,
2410 "location qualifier for uniform %s overlaps "
2411 "previously used location\n",
2412 var->name);
2413 return false;
2414 }
2415
2416 /* Initialize location as inactive before optimization
2417 * rounds and location assignment.
2418 */
2419 p->sh.SubroutineUniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
2420 }
2421
2422 return true;
2423 }
2424 /**
2425 * Check and reserve all explicit uniform locations, called before
2426 * any optimizations happen to handle also inactive uniforms and
2427 * inactive array elements that may get trimmed away.
2428 */
2429 static void
check_explicit_uniform_locations(const struct gl_extensions * exts,struct gl_shader_program * prog)2430 check_explicit_uniform_locations(const struct gl_extensions *exts,
2431 struct gl_shader_program *prog)
2432 {
2433 prog->NumExplicitUniformLocations = 0;
2434
2435 if (!exts->ARB_explicit_uniform_location)
2436 return;
2437
2438 /* This map is used to detect if overlapping explicit locations
2439 * occur with the same uniform (from different stage) or a different one.
2440 */
2441 string_to_uint_map *uniform_map = new string_to_uint_map;
2442
2443 if (!uniform_map) {
2444 linker_error(prog, "Out of memory during linking.\n");
2445 return;
2446 }
2447
2448 unsigned entries_total = 0;
2449 unsigned mask = prog->data->linked_stages;
2450 while (mask) {
2451 const int i = u_bit_scan(&mask);
2452 struct gl_program *p = prog->_LinkedShaders[i]->Program;
2453
2454 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
2455 ir_variable *var = node->as_variable();
2456 if (!var || var->data.mode != ir_var_uniform)
2457 continue;
2458
2459 if (var->data.explicit_location) {
2460 bool ret = false;
2461 if (glsl_type_is_subroutine(glsl_without_array(var->type)))
2462 ret = reserve_subroutine_explicit_locations(prog, p, var);
2463 else {
2464 int slots = reserve_explicit_locations(prog, uniform_map,
2465 var);
2466 if (slots != -1) {
2467 ret = true;
2468 entries_total += slots;
2469 }
2470 }
2471 if (!ret) {
2472 delete uniform_map;
2473 return;
2474 }
2475 }
2476 }
2477 }
2478
2479 link_util_update_empty_uniform_locations(prog);
2480
2481 delete uniform_map;
2482 prog->NumExplicitUniformLocations = entries_total;
2483 }
2484
2485 static void
link_assign_subroutine_types(struct gl_shader_program * prog)2486 link_assign_subroutine_types(struct gl_shader_program *prog)
2487 {
2488 unsigned mask = prog->data->linked_stages;
2489 while (mask) {
2490 const int i = u_bit_scan(&mask);
2491 gl_program *p = prog->_LinkedShaders[i]->Program;
2492
2493 p->sh.MaxSubroutineFunctionIndex = 0;
2494 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
2495 ir_function *fn = node->as_function();
2496 if (!fn)
2497 continue;
2498
2499 if (fn->is_subroutine)
2500 p->sh.NumSubroutineUniformTypes++;
2501
2502 if (!fn->num_subroutine_types)
2503 continue;
2504
2505 /* these should have been calculated earlier. */
2506 assert(fn->subroutine_index != -1);
2507 if (p->sh.NumSubroutineFunctions + 1 > MAX_SUBROUTINES) {
2508 linker_error(prog, "Too many subroutine functions declared.\n");
2509 return;
2510 }
2511 p->sh.SubroutineFunctions = reralloc(p, p->sh.SubroutineFunctions,
2512 struct gl_subroutine_function,
2513 p->sh.NumSubroutineFunctions + 1);
2514 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].name.string = ralloc_strdup(p, fn->name);
2515 resource_name_updated(&p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].name);
2516 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].num_compat_types = fn->num_subroutine_types;
2517 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].types =
2518 ralloc_array(p, const struct glsl_type *,
2519 fn->num_subroutine_types);
2520
2521 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
2522 * GLSL 4.5 spec:
2523 *
2524 * "Each subroutine with an index qualifier in the shader must be
2525 * given a unique index, otherwise a compile or link error will be
2526 * generated."
2527 */
2528 for (unsigned j = 0; j < p->sh.NumSubroutineFunctions; j++) {
2529 if (p->sh.SubroutineFunctions[j].index != -1 &&
2530 p->sh.SubroutineFunctions[j].index == fn->subroutine_index) {
2531 linker_error(prog, "each subroutine index qualifier in the "
2532 "shader must be unique\n");
2533 return;
2534 }
2535 }
2536 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].index =
2537 fn->subroutine_index;
2538
2539 if (fn->subroutine_index > (int)p->sh.MaxSubroutineFunctionIndex)
2540 p->sh.MaxSubroutineFunctionIndex = fn->subroutine_index;
2541
2542 for (int j = 0; j < fn->num_subroutine_types; j++)
2543 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].types[j] = fn->subroutine_types[j];
2544 p->sh.NumSubroutineFunctions++;
2545 }
2546 }
2547 }
2548
2549 static void
verify_subroutine_associated_funcs(struct gl_shader_program * prog)2550 verify_subroutine_associated_funcs(struct gl_shader_program *prog)
2551 {
2552 unsigned mask = prog->data->linked_stages;
2553 while (mask) {
2554 const int i = u_bit_scan(&mask);
2555 gl_program *p = prog->_LinkedShaders[i]->Program;
2556 glsl_symbol_table *symbols = prog->_LinkedShaders[i]->symbols;
2557
2558 /* Section 6.1.2 (Subroutines) of the GLSL 4.00 spec says:
2559 *
2560 * "A program will fail to compile or link if any shader
2561 * or stage contains two or more functions with the same
2562 * name if the name is associated with a subroutine type."
2563 */
2564 for (unsigned j = 0; j < p->sh.NumSubroutineFunctions; j++) {
2565 unsigned definitions = 0;
2566 char *name = p->sh.SubroutineFunctions[j].name.string;
2567 ir_function *fn = symbols->get_function(name);
2568
2569 /* Calculate number of function definitions with the same name */
2570 foreach_in_list(ir_function_signature, sig, &fn->signatures) {
2571 if (sig->is_defined) {
2572 if (++definitions > 1) {
2573 linker_error(prog, "%s shader contains two or more function "
2574 "definitions with name `%s', which is "
2575 "associated with a subroutine type.\n",
2576 _mesa_shader_stage_to_string(i),
2577 fn->name);
2578 return;
2579 }
2580 }
2581 }
2582 }
2583 }
2584 }
2585
2586 /* glsl_to_nir can only handle converting certain function paramaters
2587 * to NIR. This visitor checks for parameters it can't currently handle.
2588 */
2589 class ir_function_param_visitor : public ir_hierarchical_visitor
2590 {
2591 public:
ir_function_param_visitor()2592 ir_function_param_visitor()
2593 : unsupported(false)
2594 {
2595 }
2596
visit_enter(ir_function_signature * ir)2597 virtual ir_visitor_status visit_enter(ir_function_signature *ir)
2598 {
2599
2600 if (ir->is_intrinsic())
2601 return visit_continue;
2602
2603 foreach_in_list(ir_variable, param, &ir->parameters) {
2604 if (!glsl_type_is_vector_or_scalar(param->type)) {
2605 unsupported = true;
2606 return visit_stop;
2607 }
2608
2609 if (param->data.mode != ir_var_function_in &&
2610 param->data.mode != ir_var_const_in)
2611 continue;
2612
2613 /* SSBO and shared vars might be passed to a built-in such as an
2614 * atomic memory function, where copying these to a temp before
2615 * passing to the atomic function is not valid so we must replace
2616 * these instead. Also, shader inputs for interpolateAt functions
2617 * also need to be replaced.
2618 *
2619 * We have no way to handle this in NIR or the glsl to nir pass
2620 * currently so let the GLSL IR lowering handle it.
2621 */
2622 if (ir->is_builtin()) {
2623 unsupported = true;
2624 return visit_stop;
2625 }
2626
2627 /* For opaque types, we want the inlined variable references
2628 * referencing the passed in variable, since that will have
2629 * the location information, which an assignment of an opaque
2630 * variable wouldn't.
2631 *
2632 * We have no way to handle this in NIR or the glsl to nir pass
2633 * currently so let the GLSL IR lowering handle it.
2634 */
2635 if (glsl_contains_opaque(param->type)) {
2636 unsupported = true;
2637 return visit_stop;
2638 }
2639 }
2640
2641 if (!glsl_type_is_vector_or_scalar(ir->return_type) &&
2642 !glsl_type_is_void(ir->return_type)) {
2643 unsupported = true;
2644 return visit_stop;
2645 }
2646
2647 return visit_continue;
2648 }
2649
2650 bool unsupported;
2651 };
2652
2653 static bool
has_unsupported_function_param(exec_list * ir)2654 has_unsupported_function_param(exec_list *ir)
2655 {
2656 ir_function_param_visitor visitor;
2657 visit_list_elements(&visitor, ir);
2658 return visitor.unsupported;
2659 }
2660
2661 void
link_shaders(struct gl_context * ctx,struct gl_shader_program * prog)2662 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
2663 {
2664 const struct gl_constants *consts = &ctx->Const;
2665 prog->data->LinkStatus = LINKING_SUCCESS; /* All error paths will set this to false */
2666 prog->data->Validated = false;
2667
2668 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
2669 *
2670 * "Linking can fail for a variety of reasons as specified in the
2671 * OpenGL Shading Language Specification, as well as any of the
2672 * following reasons:
2673 *
2674 * - No shader objects are attached to program."
2675 *
2676 * The Compatibility Profile specification does not list the error. In
2677 * Compatibility Profile missing shader stages are replaced by
2678 * fixed-function. This applies to the case where all stages are
2679 * missing.
2680 */
2681 if (prog->NumShaders == 0) {
2682 if (ctx->API != API_OPENGL_COMPAT)
2683 linker_error(prog, "no shaders attached to the program\n");
2684 return;
2685 }
2686
2687 #ifdef ENABLE_SHADER_CACHE
2688 if (shader_cache_read_program_metadata(ctx, prog))
2689 return;
2690 #endif
2691
2692 void *mem_ctx = ralloc_context(NULL); // temporary linker context
2693 unsigned prev = MESA_SHADER_STAGES;
2694
2695 /* Separate the shaders into groups based on their type.
2696 */
2697 struct gl_shader **shader_list[MESA_SHADER_STAGES];
2698 unsigned num_shaders[MESA_SHADER_STAGES];
2699
2700 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
2701 shader_list[i] = (struct gl_shader **)
2702 calloc(prog->NumShaders, sizeof(struct gl_shader *));
2703 num_shaders[i] = 0;
2704 }
2705
2706 unsigned min_version = UINT_MAX;
2707 unsigned max_version = 0;
2708 for (unsigned i = 0; i < prog->NumShaders; i++) {
2709 min_version = MIN2(min_version, prog->Shaders[i]->Version);
2710 max_version = MAX2(max_version, prog->Shaders[i]->Version);
2711
2712 if (!consts->AllowGLSLRelaxedES &&
2713 prog->Shaders[i]->IsES != prog->Shaders[0]->IsES) {
2714 linker_error(prog, "all shaders must use same shading "
2715 "language version\n");
2716 goto done;
2717 }
2718
2719 gl_shader_stage shader_type = prog->Shaders[i]->Stage;
2720 shader_list[shader_type][num_shaders[shader_type]] = prog->Shaders[i];
2721 num_shaders[shader_type]++;
2722 }
2723
2724 /* In desktop GLSL, different shader versions may be linked together. In
2725 * GLSL ES, all shader versions must be the same.
2726 */
2727 if (!consts->AllowGLSLRelaxedES && prog->Shaders[0]->IsES &&
2728 min_version != max_version) {
2729 linker_error(prog, "all shaders must use same shading "
2730 "language version\n");
2731 goto done;
2732 }
2733
2734 prog->GLSL_Version = max_version;
2735 prog->IsES = prog->Shaders[0]->IsES;
2736
2737 /* Some shaders have to be linked with some other shaders present.
2738 */
2739 if (!prog->SeparateShader) {
2740 if (num_shaders[MESA_SHADER_GEOMETRY] > 0 &&
2741 num_shaders[MESA_SHADER_VERTEX] == 0) {
2742 linker_error(prog, "Geometry shader must be linked with "
2743 "vertex shader\n");
2744 goto done;
2745 }
2746 if (num_shaders[MESA_SHADER_TESS_EVAL] > 0 &&
2747 num_shaders[MESA_SHADER_VERTEX] == 0) {
2748 linker_error(prog, "Tessellation evaluation shader must be linked "
2749 "with vertex shader\n");
2750 goto done;
2751 }
2752 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
2753 num_shaders[MESA_SHADER_VERTEX] == 0) {
2754 linker_error(prog, "Tessellation control shader must be linked with "
2755 "vertex shader\n");
2756 goto done;
2757 }
2758
2759 /* Section 7.3 of the OpenGL ES 3.2 specification says:
2760 *
2761 * "Linking can fail for [...] any of the following reasons:
2762 *
2763 * * program contains an object to form a tessellation control
2764 * shader [...] and [...] the program is not separable and
2765 * contains no object to form a tessellation evaluation shader"
2766 *
2767 * The OpenGL spec is contradictory. It allows linking without a tess
2768 * eval shader, but that can only be used with transform feedback and
2769 * rasterization disabled. However, transform feedback isn't allowed
2770 * with GL_PATCHES, so it can't be used.
2771 *
2772 * More investigation showed that the idea of transform feedback after
2773 * a tess control shader was dropped, because some hw vendors couldn't
2774 * support tessellation without a tess eval shader, but the linker
2775 * section wasn't updated to reflect that.
2776 *
2777 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
2778 * spec bug.
2779 *
2780 * Do what's reasonable and always require a tess eval shader if a tess
2781 * control shader is present.
2782 */
2783 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
2784 num_shaders[MESA_SHADER_TESS_EVAL] == 0) {
2785 linker_error(prog, "Tessellation control shader must be linked with "
2786 "tessellation evaluation shader\n");
2787 goto done;
2788 }
2789
2790 if (prog->IsES) {
2791 if (num_shaders[MESA_SHADER_TESS_EVAL] > 0 &&
2792 num_shaders[MESA_SHADER_TESS_CTRL] == 0) {
2793 linker_error(prog, "GLSL ES requires non-separable programs "
2794 "containing a tessellation evaluation shader to also "
2795 "be linked with a tessellation control shader\n");
2796 goto done;
2797 }
2798 }
2799 }
2800
2801 /* Compute shaders have additional restrictions. */
2802 if (num_shaders[MESA_SHADER_COMPUTE] > 0 &&
2803 num_shaders[MESA_SHADER_COMPUTE] != prog->NumShaders) {
2804 linker_error(prog, "Compute shaders may not be linked with any other "
2805 "type of shader\n");
2806 }
2807
2808 /* Link all shaders for a particular stage and validate the result.
2809 */
2810 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
2811 if (num_shaders[stage] > 0) {
2812 gl_linked_shader *const sh =
2813 link_intrastage_shaders(mem_ctx, ctx, prog, shader_list[stage],
2814 num_shaders[stage], false);
2815
2816 if (!prog->data->LinkStatus) {
2817 if (sh)
2818 _mesa_delete_linked_shader(ctx, sh);
2819 goto done;
2820 }
2821
2822 switch (stage) {
2823 case MESA_SHADER_VERTEX:
2824 validate_vertex_shader_executable(prog, sh, consts);
2825 break;
2826 case MESA_SHADER_TESS_CTRL:
2827 /* nothing to be done */
2828 break;
2829 case MESA_SHADER_TESS_EVAL:
2830 validate_tess_eval_shader_executable(prog, sh, consts);
2831 break;
2832 case MESA_SHADER_GEOMETRY:
2833 validate_geometry_shader_executable(prog, sh, consts);
2834 break;
2835 case MESA_SHADER_FRAGMENT:
2836 validate_fragment_shader_executable(prog, sh);
2837 break;
2838 }
2839 if (!prog->data->LinkStatus) {
2840 if (sh)
2841 _mesa_delete_linked_shader(ctx, sh);
2842 goto done;
2843 }
2844
2845 prog->_LinkedShaders[stage] = sh;
2846 prog->data->linked_stages |= 1 << stage;
2847 }
2848 }
2849
2850 /* Here begins the inter-stage linking phase. Some initial validation is
2851 * performed, then locations are assigned for uniforms, attributes, and
2852 * varyings.
2853 */
2854 cross_validate_uniforms(consts, prog);
2855 if (!prog->data->LinkStatus)
2856 goto done;
2857
2858 check_explicit_uniform_locations(&ctx->Extensions, prog);
2859 link_assign_subroutine_types(prog);
2860 verify_subroutine_associated_funcs(prog);
2861
2862 if (!prog->data->LinkStatus)
2863 goto done;
2864
2865 resize_tes_inputs(consts, prog);
2866
2867 /* Validate the inputs of each stage with the output of the preceding
2868 * stage.
2869 */
2870 for (unsigned i = 0; i <= MESA_SHADER_FRAGMENT; i++) {
2871 if (prog->_LinkedShaders[i] == NULL)
2872 continue;
2873
2874 if (prev == MESA_SHADER_STAGES) {
2875 prev = i;
2876 continue;
2877 }
2878
2879 validate_interstage_inout_blocks(prog, prog->_LinkedShaders[prev],
2880 prog->_LinkedShaders[i]);
2881 if (!prog->data->LinkStatus)
2882 goto done;
2883
2884 prev = i;
2885 }
2886
2887 /* Cross-validate uniform blocks between shader stages */
2888 validate_interstage_uniform_blocks(prog, prog->_LinkedShaders);
2889 if (!prog->data->LinkStatus)
2890 goto done;
2891
2892 if (prog->IsES && prog->GLSL_Version == 100)
2893 if (!validate_invariant_builtins(prog,
2894 prog->_LinkedShaders[MESA_SHADER_VERTEX],
2895 prog->_LinkedShaders[MESA_SHADER_FRAGMENT]))
2896 goto done;
2897
2898 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
2899 * it before optimization because we want most of the checks to get
2900 * dropped thanks to constant propagation.
2901 *
2902 * This rule also applies to GLSL ES 3.00.
2903 */
2904 if (max_version >= (prog->IsES ? 300 : 130)) {
2905 struct gl_linked_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2906 if (sh) {
2907 lower_discard_flow(sh->ir);
2908 }
2909 }
2910
2911 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2912 if (prog->_LinkedShaders[i] == NULL)
2913 continue;
2914
2915 struct gl_linked_shader *shader = prog->_LinkedShaders[i];
2916 exec_list *ir = shader->ir;
2917
2918 detect_recursion_linked(prog, ir);
2919 if (!prog->data->LinkStatus)
2920 goto done;
2921
2922 const struct gl_shader_compiler_options *gl_options =
2923 &consts->ShaderCompilerOptions[i];
2924
2925 /* NIR cannot handle instructions after a break so we use the GLSL IR do
2926 * lower jumps pass to clean those up for now.
2927 */
2928 do_lower_jumps(ir, true, true, gl_options->EmitNoMainReturn,
2929 gl_options->EmitNoCont);
2930
2931 /* glsl_to_nir can only handle converting certain function paramaters
2932 * to NIR. If we find something we can't handle then we get the GLSL IR
2933 * opts to remove it before we continue on.
2934 *
2935 * TODO: add missing glsl ir to nir support and remove this loop.
2936 */
2937 while (has_unsupported_function_param(ir)) {
2938 do_common_optimization(ir, true, gl_options, consts->NativeIntegers);
2939 }
2940 }
2941
2942 done:
2943 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2944 free(shader_list[i]);
2945 if (prog->_LinkedShaders[i] == NULL)
2946 continue;
2947
2948 /* Do a final validation step to make sure that the IR wasn't
2949 * invalidated by any modifications performed after intrastage linking.
2950 */
2951 validate_ir_tree(prog->_LinkedShaders[i]->ir);
2952
2953 /* Retain any live IR, but trash the rest. */
2954 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
2955
2956 /* The symbol table in the linked shaders may contain references to
2957 * variables that were removed (e.g., unused uniforms). Since it may
2958 * contain junk, there is no possible valid use. Delete it and set the
2959 * pointer to NULL.
2960 */
2961 delete prog->_LinkedShaders[i]->symbols;
2962 prog->_LinkedShaders[i]->symbols = NULL;
2963 }
2964
2965 ralloc_free(mem_ctx);
2966 }
2967
2968 void
resource_name_updated(struct gl_resource_name * name)2969 resource_name_updated(struct gl_resource_name *name)
2970 {
2971 if (name->string) {
2972 name->length = strlen(name->string);
2973
2974 const char *last_square_bracket = strrchr(name->string, '[');
2975 if (last_square_bracket) {
2976 name->last_square_bracket = last_square_bracket - name->string;
2977 name->suffix_is_zero_square_bracketed =
2978 strcmp(last_square_bracket, "[0]") == 0;
2979 } else {
2980 name->last_square_bracket = -1;
2981 name->suffix_is_zero_square_bracketed = false;
2982 }
2983 } else {
2984 name->length = 0;
2985 name->last_square_bracket = -1;
2986 name->suffix_is_zero_square_bracketed = false;
2987 }
2988 }
2989