2 * Copyright © 2010 Intel Corporation
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:
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
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.
26 * GLSL linker implementation
28 * Given a set of shaders that are to be linked to generate a final program,
29 * there are three distinct stages.
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
35 * - Undefined references in each shader are resolve to definitions in
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.
42 * The result, in the terminology of the GLSL spec, is a set of shader
43 * executables for each processing unit.
45 * After the first stage is complete, a series of semantic checks are performed
46 * on each of the shader executables.
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
53 * In the final stage individual shader executables are linked to create a
54 * complete exectuable.
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.
64 * \author Ian Romanick <ian.d.romanick@intel.com>
67 #include "main/core.h"
68 #include "glsl_symbol_table.h"
69 #include "glsl_parser_extras.h"
72 #include "program/hash_table.h"
74 #include "link_varyings.h"
75 #include "ir_optimization.h"
76 #include "ir_rvalue_visitor.h"
77 #include "ir_uniform.h"
80 #include "main/shaderobj.h"
81 #include "main/enums.h"
84 void linker_error(gl_shader_program
*, const char *, ...);
89 * Visitor that determines whether or not a variable is ever written.
91 class find_assignment_visitor
: public ir_hierarchical_visitor
{
93 find_assignment_visitor(const char *name
)
94 : name(name
), found(false)
99 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
101 ir_variable
*const var
= ir
->lhs
->variable_referenced();
103 if (strcmp(name
, var
->name
) == 0) {
108 return visit_continue_with_parent
;
111 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
113 foreach_two_lists(formal_node
, &ir
->callee
->parameters
,
114 actual_node
, &ir
->actual_parameters
) {
115 ir_rvalue
*param_rval
= (ir_rvalue
*) actual_node
;
116 ir_variable
*sig_param
= (ir_variable
*) formal_node
;
118 if (sig_param
->data
.mode
== ir_var_function_out
||
119 sig_param
->data
.mode
== ir_var_function_inout
) {
120 ir_variable
*var
= param_rval
->variable_referenced();
121 if (var
&& strcmp(name
, var
->name
) == 0) {
128 if (ir
->return_deref
!= NULL
) {
129 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
131 if (strcmp(name
, var
->name
) == 0) {
137 return visit_continue_with_parent
;
140 bool variable_found()
146 const char *name
; /**< Find writes to a variable with this name. */
147 bool found
; /**< Was a write to the variable found? */
152 * Visitor that determines whether or not a variable is ever read.
154 class find_deref_visitor
: public ir_hierarchical_visitor
{
156 find_deref_visitor(const char *name
)
157 : name(name
), found(false)
162 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
164 if (strcmp(this->name
, ir
->var
->name
) == 0) {
169 return visit_continue
;
172 bool variable_found() const
178 const char *name
; /**< Find writes to a variable with this name. */
179 bool found
; /**< Was a write to the variable found? */
183 class geom_array_resize_visitor
: public ir_hierarchical_visitor
{
185 unsigned num_vertices
;
186 gl_shader_program
*prog
;
188 geom_array_resize_visitor(unsigned num_vertices
, gl_shader_program
*prog
)
190 this->num_vertices
= num_vertices
;
194 virtual ~geom_array_resize_visitor()
199 virtual ir_visitor_status
visit(ir_variable
*var
)
201 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
)
202 return visit_continue
;
204 unsigned size
= var
->type
->length
;
206 /* Generate a link error if the shader has declared this array with an
209 if (size
&& size
!= this->num_vertices
) {
210 linker_error(this->prog
, "size of array %s declared as %u, "
211 "but number of input vertices is %u\n",
212 var
->name
, size
, this->num_vertices
);
213 return visit_continue
;
216 /* Generate a link error if the shader attempts to access an input
217 * array using an index too large for its actual size assigned at link
220 if (var
->data
.max_array_access
>= this->num_vertices
) {
221 linker_error(this->prog
, "geometry shader accesses element %i of "
222 "%s, but only %i input vertices\n",
223 var
->data
.max_array_access
, var
->name
, this->num_vertices
);
224 return visit_continue
;
227 var
->type
= glsl_type::get_array_instance(var
->type
->element_type(),
229 var
->data
.max_array_access
= this->num_vertices
- 1;
231 return visit_continue
;
234 /* Dereferences of input variables need to be updated so that their type
235 * matches the newly assigned type of the variable they are accessing. */
236 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
238 ir
->type
= ir
->var
->type
;
239 return visit_continue
;
242 /* Dereferences of 2D input arrays need to be updated so that their type
243 * matches the newly assigned type of the array they are accessing. */
244 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
246 const glsl_type
*const vt
= ir
->array
->type
;
248 ir
->type
= vt
->element_type();
249 return visit_continue
;
255 * Visitor that determines whether or not a shader uses ir_end_primitive.
257 class find_end_primitive_visitor
: public ir_hierarchical_visitor
{
259 find_end_primitive_visitor()
265 virtual ir_visitor_status
visit(ir_end_primitive
*)
271 bool end_primitive_found()
280 } /* anonymous namespace */
283 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
287 ralloc_strcat(&prog
->InfoLog
, "error: ");
289 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
292 prog
->LinkStatus
= false;
297 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
301 ralloc_strcat(&prog
->InfoLog
, "warning: ");
303 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
310 * Given a string identifying a program resource, break it into a base name
311 * and an optional array index in square brackets.
313 * If an array index is present, \c out_base_name_end is set to point to the
314 * "[" that precedes the array index, and the array index itself is returned
317 * If no array index is present (or if the array index is negative or
318 * mal-formed), \c out_base_name_end, is set to point to the null terminator
319 * at the end of the input string, and -1 is returned.
321 * Only the final array index is parsed; if the string contains other array
322 * indices (or structure field accesses), they are left in the base name.
324 * No attempt is made to check that the base name is properly formed;
325 * typically the caller will look up the base name in a hash table, so
326 * ill-formed base names simply turn into hash table lookup failures.
329 parse_program_resource_name(const GLchar
*name
,
330 const GLchar
**out_base_name_end
)
332 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
334 * "When an integer array element or block instance number is part of
335 * the name string, it will be specified in decimal form without a "+"
336 * or "-" sign or any extra leading zeroes. Additionally, the name
337 * string will not include white space anywhere in the string."
340 const size_t len
= strlen(name
);
341 *out_base_name_end
= name
+ len
;
343 if (len
== 0 || name
[len
-1] != ']')
346 /* Walk backwards over the string looking for a non-digit character. This
347 * had better be the opening bracket for an array index.
349 * Initially, i specifies the location of the ']'. Since the string may
350 * contain only the ']' charcater, walk backwards very carefully.
353 for (i
= len
- 1; (i
> 0) && isdigit(name
[i
-1]); --i
)
356 if ((i
== 0) || name
[i
-1] != '[')
359 long array_index
= strtol(&name
[i
], NULL
, 10);
363 *out_base_name_end
= name
+ (i
- 1);
369 link_invalidate_variable_locations(exec_list
*ir
)
371 foreach_list(node
, ir
) {
372 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
377 /* Only assign locations for variables that lack an explicit location.
378 * Explicit locations are set for all built-in variables, generic vertex
379 * shader inputs (via layout(location=...)), and generic fragment shader
380 * outputs (also via layout(location=...)).
382 if (!var
->data
.explicit_location
) {
383 var
->data
.location
= -1;
384 var
->data
.location_frac
= 0;
387 /* ir_variable::is_unmatched_generic_inout is used by the linker while
388 * connecting outputs from one stage to inputs of the next stage.
390 * There are two implicit assumptions here. First, we assume that any
391 * built-in variable (i.e., non-generic in or out) will have
392 * explicit_location set. Second, we assume that any generic in or out
393 * will not have explicit_location set.
395 * This second assumption will only be valid until
396 * GL_ARB_separate_shader_objects is supported. When that extension is
397 * implemented, this function will need some modifications.
399 if (!var
->data
.explicit_location
) {
400 var
->data
.is_unmatched_generic_inout
= 1;
402 var
->data
.is_unmatched_generic_inout
= 0;
409 * Set UsesClipDistance and ClipDistanceArraySize based on the given shader.
411 * Also check for errors based on incorrect usage of gl_ClipVertex and
414 * Return false if an error was reported.
417 analyze_clip_usage(struct gl_shader_program
*prog
,
418 struct gl_shader
*shader
, GLboolean
*UsesClipDistance
,
419 GLuint
*ClipDistanceArraySize
)
421 *ClipDistanceArraySize
= 0;
423 if (!prog
->IsES
&& prog
->Version
>= 130) {
424 /* From section 7.1 (Vertex Shader Special Variables) of the
427 * "It is an error for a shader to statically write both
428 * gl_ClipVertex and gl_ClipDistance."
430 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
431 * gl_ClipVertex nor gl_ClipDistance.
433 find_assignment_visitor
clip_vertex("gl_ClipVertex");
434 find_assignment_visitor
clip_distance("gl_ClipDistance");
436 clip_vertex
.run(shader
->ir
);
437 clip_distance
.run(shader
->ir
);
438 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
439 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
440 "and `gl_ClipDistance'\n",
441 _mesa_shader_stage_to_string(shader
->Stage
));
444 *UsesClipDistance
= clip_distance
.variable_found();
445 ir_variable
*clip_distance_var
=
446 shader
->symbols
->get_variable("gl_ClipDistance");
447 if (clip_distance_var
)
448 *ClipDistanceArraySize
= clip_distance_var
->type
->length
;
450 *UsesClipDistance
= false;
456 * Verify that a vertex shader executable meets all semantic requirements.
458 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
461 * \param shader Vertex shader executable to be verified
464 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
465 struct gl_shader
*shader
)
470 /* From the GLSL 1.10 spec, page 48:
472 * "The variable gl_Position is available only in the vertex
473 * language and is intended for writing the homogeneous vertex
474 * position. All executions of a well-formed vertex shader
475 * executable must write a value into this variable. [...] The
476 * variable gl_Position is available only in the vertex
477 * language and is intended for writing the homogeneous vertex
478 * position. All executions of a well-formed vertex shader
479 * executable must write a value into this variable."
481 * while in GLSL 1.40 this text is changed to:
483 * "The variable gl_Position is available only in the vertex
484 * language and is intended for writing the homogeneous vertex
485 * position. It can be written at any time during shader
486 * execution. It may also be read back by a vertex shader
487 * after being written. This value will be used by primitive
488 * assembly, clipping, culling, and other fixed functionality
489 * operations, if present, that operate on primitives after
490 * vertex processing has occurred. Its value is undefined if
491 * the vertex shader executable does not write gl_Position."
493 * GLSL ES 3.00 is similar to GLSL 1.40--failing to write to gl_Position is
496 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
497 find_assignment_visitor
find("gl_Position");
498 find
.run(shader
->ir
);
499 if (!find
.variable_found()) {
500 linker_error(prog
, "vertex shader does not write to `gl_Position'\n");
505 analyze_clip_usage(prog
, shader
, &prog
->Vert
.UsesClipDistance
,
506 &prog
->Vert
.ClipDistanceArraySize
);
511 * Verify that a fragment shader executable meets all semantic requirements
513 * \param shader Fragment shader executable to be verified
516 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
517 struct gl_shader
*shader
)
522 find_assignment_visitor
frag_color("gl_FragColor");
523 find_assignment_visitor
frag_data("gl_FragData");
525 frag_color
.run(shader
->ir
);
526 frag_data
.run(shader
->ir
);
528 if (frag_color
.variable_found() && frag_data
.variable_found()) {
529 linker_error(prog
, "fragment shader writes to both "
530 "`gl_FragColor' and `gl_FragData'\n");
535 * Verify that a geometry shader executable meets all semantic requirements
537 * Also sets prog->Geom.VerticesIn, prog->Geom.UsesClipDistance, and
538 * prog->Geom.ClipDistanceArraySize as a side effect.
540 * \param shader Geometry shader executable to be verified
543 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
544 struct gl_shader
*shader
)
549 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
550 prog
->Geom
.VerticesIn
= num_vertices
;
552 analyze_clip_usage(prog
, shader
, &prog
->Geom
.UsesClipDistance
,
553 &prog
->Geom
.ClipDistanceArraySize
);
555 find_end_primitive_visitor end_primitive
;
556 end_primitive
.run(shader
->ir
);
557 prog
->Geom
.UsesEndPrimitive
= end_primitive
.end_primitive_found();
562 * Perform validation of global variables used across multiple shaders
565 cross_validate_globals(struct gl_shader_program
*prog
,
566 struct gl_shader
**shader_list
,
567 unsigned num_shaders
,
570 /* Examine all of the uniforms in all of the shaders and cross validate
573 glsl_symbol_table variables
;
574 for (unsigned i
= 0; i
< num_shaders
; i
++) {
575 if (shader_list
[i
] == NULL
)
578 foreach_list(node
, shader_list
[i
]->ir
) {
579 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
584 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
))
587 /* Don't cross validate temporaries that are at global scope. These
588 * will eventually get pulled into the shaders 'main'.
590 if (var
->data
.mode
== ir_var_temporary
)
593 /* If a global with this name has already been seen, verify that the
594 * new instance has the same type. In addition, if the globals have
595 * initializers, the values of the initializers must be the same.
597 ir_variable
*const existing
= variables
.get_variable(var
->name
);
598 if (existing
!= NULL
) {
599 if (var
->type
!= existing
->type
) {
600 /* Consider the types to be "the same" if both types are arrays
601 * of the same type and one of the arrays is implicitly sized.
602 * In addition, set the type of the linked variable to the
603 * explicitly sized array.
605 if (var
->type
->is_array()
606 && existing
->type
->is_array()
607 && (var
->type
->fields
.array
== existing
->type
->fields
.array
)
608 && ((var
->type
->length
== 0)
609 || (existing
->type
->length
== 0))) {
610 if (var
->type
->length
!= 0) {
611 existing
->type
= var
->type
;
613 } else if (var
->type
->is_record()
614 && existing
->type
->is_record()
615 && existing
->type
->record_compare(var
->type
)) {
616 existing
->type
= var
->type
;
618 linker_error(prog
, "%s `%s' declared as type "
619 "`%s' and type `%s'\n",
621 var
->name
, var
->type
->name
,
622 existing
->type
->name
);
627 if (var
->data
.explicit_location
) {
628 if (existing
->data
.explicit_location
629 && (var
->data
.location
!= existing
->data
.location
)) {
630 linker_error(prog
, "explicit locations for %s "
631 "`%s' have differing values\n",
632 mode_string(var
), var
->name
);
636 existing
->data
.location
= var
->data
.location
;
637 existing
->data
.explicit_location
= true;
640 /* From the GLSL 4.20 specification:
641 * "A link error will result if two compilation units in a program
642 * specify different integer-constant bindings for the same
643 * opaque-uniform name. However, it is not an error to specify a
644 * binding on some but not all declarations for the same name"
646 if (var
->data
.explicit_binding
) {
647 if (existing
->data
.explicit_binding
&&
648 var
->data
.binding
!= existing
->data
.binding
) {
649 linker_error(prog
, "explicit bindings for %s "
650 "`%s' have differing values\n",
651 mode_string(var
), var
->name
);
655 existing
->data
.binding
= var
->data
.binding
;
656 existing
->data
.explicit_binding
= true;
659 if (var
->type
->contains_atomic() &&
660 var
->data
.atomic
.offset
!= existing
->data
.atomic
.offset
) {
661 linker_error(prog
, "offset specifications for %s "
662 "`%s' have differing values\n",
663 mode_string(var
), var
->name
);
667 /* Validate layout qualifiers for gl_FragDepth.
669 * From the AMD/ARB_conservative_depth specs:
671 * "If gl_FragDepth is redeclared in any fragment shader in a
672 * program, it must be redeclared in all fragment shaders in
673 * that program that have static assignments to
674 * gl_FragDepth. All redeclarations of gl_FragDepth in all
675 * fragment shaders in a single program must have the same set
678 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
679 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
680 bool layout_differs
=
681 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
683 if (layout_declared
&& layout_differs
) {
685 "All redeclarations of gl_FragDepth in all "
686 "fragment shaders in a single program must have "
687 "the same set of qualifiers.");
690 if (var
->data
.used
&& layout_differs
) {
692 "If gl_FragDepth is redeclared with a layout "
693 "qualifier in any fragment shader, it must be "
694 "redeclared with the same layout qualifier in "
695 "all fragment shaders that have assignments to "
700 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
702 * "If a shared global has multiple initializers, the
703 * initializers must all be constant expressions, and they
704 * must all have the same value. Otherwise, a link error will
705 * result. (A shared global having only one initializer does
706 * not require that initializer to be a constant expression.)"
708 * Previous to 4.20 the GLSL spec simply said that initializers
709 * must have the same value. In this case of non-constant
710 * initializers, this was impossible to determine. As a result,
711 * no vendor actually implemented that behavior. The 4.20
712 * behavior matches the implemented behavior of at least one other
713 * vendor, so we'll implement that for all GLSL versions.
715 if (var
->constant_initializer
!= NULL
) {
716 if (existing
->constant_initializer
!= NULL
) {
717 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
718 linker_error(prog
, "initializers for %s "
719 "`%s' have differing values\n",
720 mode_string(var
), var
->name
);
724 /* If the first-seen instance of a particular uniform did not
725 * have an initializer but a later instance does, copy the
726 * initializer to the version stored in the symbol table.
728 /* FINISHME: This is wrong. The constant_value field should
729 * FINISHME: not be modified! Imagine a case where a shader
730 * FINISHME: without an initializer is linked in two different
731 * FINISHME: programs with shaders that have differing
732 * FINISHME: initializers. Linking with the first will
733 * FINISHME: modify the shader, and linking with the second
734 * FINISHME: will fail.
736 existing
->constant_initializer
=
737 var
->constant_initializer
->clone(ralloc_parent(existing
),
742 if (var
->data
.has_initializer
) {
743 if (existing
->data
.has_initializer
744 && (var
->constant_initializer
== NULL
745 || existing
->constant_initializer
== NULL
)) {
747 "shared global variable `%s' has multiple "
748 "non-constant initializers.\n",
753 /* Some instance had an initializer, so keep track of that. In
754 * this location, all sorts of initializers (constant or
755 * otherwise) will propagate the existence to the variable
756 * stored in the symbol table.
758 existing
->data
.has_initializer
= true;
761 if (existing
->data
.invariant
!= var
->data
.invariant
) {
762 linker_error(prog
, "declarations for %s `%s' have "
763 "mismatching invariant qualifiers\n",
764 mode_string(var
), var
->name
);
767 if (existing
->data
.centroid
!= var
->data
.centroid
) {
768 linker_error(prog
, "declarations for %s `%s' have "
769 "mismatching centroid qualifiers\n",
770 mode_string(var
), var
->name
);
773 if (existing
->data
.sample
!= var
->data
.sample
) {
774 linker_error(prog
, "declarations for %s `%s` have "
775 "mismatching sample qualifiers\n",
776 mode_string(var
), var
->name
);
780 variables
.add_variable(var
);
787 * Perform validation of uniforms used across multiple shader stages
790 cross_validate_uniforms(struct gl_shader_program
*prog
)
792 cross_validate_globals(prog
, prog
->_LinkedShaders
,
793 MESA_SHADER_STAGES
, true);
797 * Accumulates the array of prog->UniformBlocks and checks that all
798 * definitons of blocks agree on their contents.
801 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
)
803 unsigned max_num_uniform_blocks
= 0;
804 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
805 if (prog
->_LinkedShaders
[i
])
806 max_num_uniform_blocks
+= prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
809 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
810 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
812 prog
->UniformBlockStageIndex
[i
] = ralloc_array(prog
, int,
813 max_num_uniform_blocks
);
814 for (unsigned int j
= 0; j
< max_num_uniform_blocks
; j
++)
815 prog
->UniformBlockStageIndex
[i
][j
] = -1;
820 for (unsigned int j
= 0; j
< sh
->NumUniformBlocks
; j
++) {
821 int index
= link_cross_validate_uniform_block(prog
,
822 &prog
->UniformBlocks
,
823 &prog
->NumUniformBlocks
,
824 &sh
->UniformBlocks
[j
]);
827 linker_error(prog
, "uniform block `%s' has mismatching definitions",
828 sh
->UniformBlocks
[j
].Name
);
832 prog
->UniformBlockStageIndex
[i
][index
] = j
;
841 * Populates a shaders symbol table with all global declarations
844 populate_symbol_table(gl_shader
*sh
)
846 sh
->symbols
= new(sh
) glsl_symbol_table
;
848 foreach_list(node
, sh
->ir
) {
849 ir_instruction
*const inst
= (ir_instruction
*) node
;
853 if ((func
= inst
->as_function()) != NULL
) {
854 sh
->symbols
->add_function(func
);
855 } else if ((var
= inst
->as_variable()) != NULL
) {
856 sh
->symbols
->add_variable(var
);
863 * Remap variables referenced in an instruction tree
865 * This is used when instruction trees are cloned from one shader and placed in
866 * another. These trees will contain references to \c ir_variable nodes that
867 * do not exist in the target shader. This function finds these \c ir_variable
868 * references and replaces the references with matching variables in the target
871 * If there is no matching variable in the target shader, a clone of the
872 * \c ir_variable is made and added to the target shader. The new variable is
873 * added to \b both the instruction stream and the symbol table.
875 * \param inst IR tree that is to be processed.
876 * \param symbols Symbol table containing global scope symbols in the
878 * \param instructions Instruction stream where new variable declarations
882 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
885 class remap_visitor
: public ir_hierarchical_visitor
{
887 remap_visitor(struct gl_shader
*target
,
890 this->target
= target
;
891 this->symbols
= target
->symbols
;
892 this->instructions
= target
->ir
;
896 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
898 if (ir
->var
->data
.mode
== ir_var_temporary
) {
899 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
903 return visit_continue
;
906 ir_variable
*const existing
=
907 this->symbols
->get_variable(ir
->var
->name
);
908 if (existing
!= NULL
)
911 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
913 this->symbols
->add_variable(copy
);
914 this->instructions
->push_head(copy
);
918 return visit_continue
;
922 struct gl_shader
*target
;
923 glsl_symbol_table
*symbols
;
924 exec_list
*instructions
;
928 remap_visitor
v(target
, temps
);
935 * Move non-declarations from one instruction stream to another
937 * The intended usage pattern of this function is to pass the pointer to the
938 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
939 * pointer) for \c last and \c false for \c make_copies on the first
940 * call. Successive calls pass the return value of the previous call for
941 * \c last and \c true for \c make_copies.
943 * \param instructions Source instruction stream
944 * \param last Instruction after which new instructions should be
945 * inserted in the target instruction stream
946 * \param make_copies Flag selecting whether instructions in \c instructions
947 * should be copied (via \c ir_instruction::clone) into the
948 * target list or moved.
951 * The new "last" instruction in the target instruction stream. This pointer
952 * is suitable for use as the \c last parameter of a later call to this
956 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
957 bool make_copies
, gl_shader
*target
)
959 hash_table
*temps
= NULL
;
962 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
963 hash_table_pointer_compare
);
965 foreach_list_safe(node
, instructions
) {
966 ir_instruction
*inst
= (ir_instruction
*) node
;
968 if (inst
->as_function())
971 ir_variable
*var
= inst
->as_variable();
972 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
975 assert(inst
->as_assignment()
977 || inst
->as_if() /* for initializers with the ?: operator */
978 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
981 inst
= inst
->clone(target
, NULL
);
984 hash_table_insert(temps
, inst
, var
);
986 remap_variables(inst
, target
, temps
);
991 last
->insert_after(inst
);
996 hash_table_dtor(temps
);
1002 * Get the function signature for main from a shader
1004 static ir_function_signature
*
1005 get_main_function_signature(gl_shader
*sh
)
1007 ir_function
*const f
= sh
->symbols
->get_function("main");
1009 exec_list void_parameters
;
1011 /* Look for the 'void main()' signature and ensure that it's defined.
1012 * This keeps the linker from accidentally pick a shader that just
1013 * contains a prototype for main.
1015 * We don't have to check for multiple definitions of main (in multiple
1016 * shaders) because that would have already been caught above.
1018 ir_function_signature
*sig
= f
->matching_signature(NULL
, &void_parameters
);
1019 if ((sig
!= NULL
) && sig
->is_defined
) {
1029 * This class is only used in link_intrastage_shaders() below but declaring
1030 * it inside that function leads to compiler warnings with some versions of
1033 class array_sizing_visitor
: public ir_hierarchical_visitor
{
1035 array_sizing_visitor()
1036 : mem_ctx(ralloc_context(NULL
)),
1037 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash
,
1038 hash_table_pointer_compare
))
1042 ~array_sizing_visitor()
1044 hash_table_dtor(this->unnamed_interfaces
);
1045 ralloc_free(this->mem_ctx
);
1048 virtual ir_visitor_status
visit(ir_variable
*var
)
1050 fixup_type(&var
->type
, var
->data
.max_array_access
);
1051 if (var
->type
->is_interface()) {
1052 if (interface_contains_unsized_arrays(var
->type
)) {
1053 const glsl_type
*new_type
=
1054 resize_interface_members(var
->type
, var
->max_ifc_array_access
);
1055 var
->type
= new_type
;
1056 var
->change_interface_type(new_type
);
1058 } else if (var
->type
->is_array() &&
1059 var
->type
->fields
.array
->is_interface()) {
1060 if (interface_contains_unsized_arrays(var
->type
->fields
.array
)) {
1061 const glsl_type
*new_type
=
1062 resize_interface_members(var
->type
->fields
.array
,
1063 var
->max_ifc_array_access
);
1064 var
->change_interface_type(new_type
);
1066 glsl_type::get_array_instance(new_type
, var
->type
->length
);
1068 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1069 /* Store a pointer to the variable in the unnamed_interfaces
1072 ir_variable
**interface_vars
= (ir_variable
**)
1073 hash_table_find(this->unnamed_interfaces
, ifc_type
);
1074 if (interface_vars
== NULL
) {
1075 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1077 hash_table_insert(this->unnamed_interfaces
, interface_vars
,
1080 unsigned index
= ifc_type
->field_index(var
->name
);
1081 assert(index
< ifc_type
->length
);
1082 assert(interface_vars
[index
] == NULL
);
1083 interface_vars
[index
] = var
;
1085 return visit_continue
;
1089 * For each unnamed interface block that was discovered while running the
1090 * visitor, adjust the interface type to reflect the newly assigned array
1091 * sizes, and fix up the ir_variable nodes to point to the new interface
1094 void fixup_unnamed_interface_types()
1096 hash_table_call_foreach(this->unnamed_interfaces
,
1097 fixup_unnamed_interface_type
, NULL
);
1102 * If the type pointed to by \c type represents an unsized array, replace
1103 * it with a sized array whose size is determined by max_array_access.
1105 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
)
1107 if ((*type
)->is_unsized_array()) {
1108 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1109 max_array_access
+ 1);
1110 assert(*type
!= NULL
);
1115 * Determine whether the given interface type contains unsized arrays (if
1116 * it doesn't, array_sizing_visitor doesn't need to process it).
1118 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1120 for (unsigned i
= 0; i
< type
->length
; i
++) {
1121 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1122 if (elem_type
->is_unsized_array())
1129 * Create a new interface type based on the given type, with unsized arrays
1130 * replaced by sized arrays whose size is determined by
1131 * max_ifc_array_access.
1133 static const glsl_type
*
1134 resize_interface_members(const glsl_type
*type
,
1135 const unsigned *max_ifc_array_access
)
1137 unsigned num_fields
= type
->length
;
1138 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1139 memcpy(fields
, type
->fields
.structure
,
1140 num_fields
* sizeof(*fields
));
1141 for (unsigned i
= 0; i
< num_fields
; i
++) {
1142 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
]);
1144 glsl_interface_packing packing
=
1145 (glsl_interface_packing
) type
->interface_packing
;
1146 const glsl_type
*new_ifc_type
=
1147 glsl_type::get_interface_instance(fields
, num_fields
,
1148 packing
, type
->name
);
1150 return new_ifc_type
;
1153 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1156 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1157 ir_variable
**interface_vars
= (ir_variable
**) data
;
1158 unsigned num_fields
= ifc_type
->length
;
1159 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1160 memcpy(fields
, ifc_type
->fields
.structure
,
1161 num_fields
* sizeof(*fields
));
1162 bool interface_type_changed
= false;
1163 for (unsigned i
= 0; i
< num_fields
; i
++) {
1164 if (interface_vars
[i
] != NULL
&&
1165 fields
[i
].type
!= interface_vars
[i
]->type
) {
1166 fields
[i
].type
= interface_vars
[i
]->type
;
1167 interface_type_changed
= true;
1170 if (!interface_type_changed
) {
1174 glsl_interface_packing packing
=
1175 (glsl_interface_packing
) ifc_type
->interface_packing
;
1176 const glsl_type
*new_ifc_type
=
1177 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1180 for (unsigned i
= 0; i
< num_fields
; i
++) {
1181 if (interface_vars
[i
] != NULL
)
1182 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1187 * Memory context used to allocate the data in \c unnamed_interfaces.
1192 * Hash table from const glsl_type * to an array of ir_variable *'s
1193 * pointing to the ir_variables constituting each unnamed interface block.
1195 hash_table
*unnamed_interfaces
;
1199 * Performs the cross-validation of layout qualifiers specified in
1200 * redeclaration of gl_FragCoord for the attached fragment shaders,
1201 * and propagates them to the linked FS and linked shader program.
1204 link_fs_input_layout_qualifiers(struct gl_shader_program
*prog
,
1205 struct gl_shader
*linked_shader
,
1206 struct gl_shader
**shader_list
,
1207 unsigned num_shaders
)
1209 linked_shader
->redeclares_gl_fragcoord
= false;
1210 linked_shader
->uses_gl_fragcoord
= false;
1211 linked_shader
->origin_upper_left
= false;
1212 linked_shader
->pixel_center_integer
= false;
1214 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1215 (prog
->Version
< 150 && !prog
->ARB_fragment_coord_conventions_enable
))
1218 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1219 struct gl_shader
*shader
= shader_list
[i
];
1220 /* From the GLSL 1.50 spec, page 39:
1222 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1223 * it must be redeclared in all the fragment shaders in that program
1224 * that have a static use gl_FragCoord."
1226 * Exclude the case when one of the 'linked_shader' or 'shader' redeclares
1227 * gl_FragCoord with no layout qualifiers but the other one doesn't
1228 * redeclare it. If we strictly follow GLSL 1.50 spec's language, it
1229 * should be a link error. But, generating link error for this case will
1230 * be a wrong behaviour which spec didn't intend to do and it could also
1231 * break some applications.
1233 if ((linked_shader
->redeclares_gl_fragcoord
1234 && !shader
->redeclares_gl_fragcoord
1235 && shader
->uses_gl_fragcoord
1236 && (linked_shader
->origin_upper_left
1237 || linked_shader
->pixel_center_integer
))
1238 || (shader
->redeclares_gl_fragcoord
1239 && !linked_shader
->redeclares_gl_fragcoord
1240 && linked_shader
->uses_gl_fragcoord
1241 && (shader
->origin_upper_left
1242 || shader
->pixel_center_integer
))) {
1243 linker_error(prog
, "fragment shader defined with conflicting "
1244 "layout qualifiers for gl_FragCoord\n");
1247 /* From the GLSL 1.50 spec, page 39:
1249 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1250 * single program must have the same set of qualifiers."
1252 if (linked_shader
->redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
1253 && (shader
->origin_upper_left
!= linked_shader
->origin_upper_left
1254 || shader
->pixel_center_integer
!= linked_shader
->pixel_center_integer
)) {
1255 linker_error(prog
, "fragment shader defined with conflicting "
1256 "layout qualifiers for gl_FragCoord\n");
1259 /* Update the linked shader state. Note that uses_gl_fragcoord should
1260 * accumulate the results. The other values should replace. If there
1261 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1262 * are already known to be the same.
1264 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
1265 linked_shader
->redeclares_gl_fragcoord
=
1266 shader
->redeclares_gl_fragcoord
;
1267 linked_shader
->uses_gl_fragcoord
= linked_shader
->uses_gl_fragcoord
1268 || shader
->uses_gl_fragcoord
;
1269 linked_shader
->origin_upper_left
= shader
->origin_upper_left
;
1270 linked_shader
->pixel_center_integer
= shader
->pixel_center_integer
;
1276 * Performs the cross-validation of geometry shader max_vertices and
1277 * primitive type layout qualifiers for the attached geometry shaders,
1278 * and propagates them to the linked GS and linked shader program.
1281 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1282 struct gl_shader
*linked_shader
,
1283 struct gl_shader
**shader_list
,
1284 unsigned num_shaders
)
1286 linked_shader
->Geom
.VerticesOut
= 0;
1287 linked_shader
->Geom
.Invocations
= 0;
1288 linked_shader
->Geom
.InputType
= PRIM_UNKNOWN
;
1289 linked_shader
->Geom
.OutputType
= PRIM_UNKNOWN
;
1291 /* No in/out qualifiers defined for anything but GLSL 1.50+
1292 * geometry shaders so far.
1294 if (linked_shader
->Stage
!= MESA_SHADER_GEOMETRY
|| prog
->Version
< 150)
1297 /* From the GLSL 1.50 spec, page 46:
1299 * "All geometry shader output layout declarations in a program
1300 * must declare the same layout and same value for
1301 * max_vertices. There must be at least one geometry output
1302 * layout declaration somewhere in a program, but not all
1303 * geometry shaders (compilation units) are required to
1307 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1308 struct gl_shader
*shader
= shader_list
[i
];
1310 if (shader
->Geom
.InputType
!= PRIM_UNKNOWN
) {
1311 if (linked_shader
->Geom
.InputType
!= PRIM_UNKNOWN
&&
1312 linked_shader
->Geom
.InputType
!= shader
->Geom
.InputType
) {
1313 linker_error(prog
, "geometry shader defined with conflicting "
1317 linked_shader
->Geom
.InputType
= shader
->Geom
.InputType
;
1320 if (shader
->Geom
.OutputType
!= PRIM_UNKNOWN
) {
1321 if (linked_shader
->Geom
.OutputType
!= PRIM_UNKNOWN
&&
1322 linked_shader
->Geom
.OutputType
!= shader
->Geom
.OutputType
) {
1323 linker_error(prog
, "geometry shader defined with conflicting "
1327 linked_shader
->Geom
.OutputType
= shader
->Geom
.OutputType
;
1330 if (shader
->Geom
.VerticesOut
!= 0) {
1331 if (linked_shader
->Geom
.VerticesOut
!= 0 &&
1332 linked_shader
->Geom
.VerticesOut
!= shader
->Geom
.VerticesOut
) {
1333 linker_error(prog
, "geometry shader defined with conflicting "
1334 "output vertex count (%d and %d)\n",
1335 linked_shader
->Geom
.VerticesOut
,
1336 shader
->Geom
.VerticesOut
);
1339 linked_shader
->Geom
.VerticesOut
= shader
->Geom
.VerticesOut
;
1342 if (shader
->Geom
.Invocations
!= 0) {
1343 if (linked_shader
->Geom
.Invocations
!= 0 &&
1344 linked_shader
->Geom
.Invocations
!= shader
->Geom
.Invocations
) {
1345 linker_error(prog
, "geometry shader defined with conflicting "
1346 "invocation count (%d and %d)\n",
1347 linked_shader
->Geom
.Invocations
,
1348 shader
->Geom
.Invocations
);
1351 linked_shader
->Geom
.Invocations
= shader
->Geom
.Invocations
;
1355 /* Just do the intrastage -> interstage propagation right now,
1356 * since we already know we're in the right type of shader program
1359 if (linked_shader
->Geom
.InputType
== PRIM_UNKNOWN
) {
1361 "geometry shader didn't declare primitive input type\n");
1364 prog
->Geom
.InputType
= linked_shader
->Geom
.InputType
;
1366 if (linked_shader
->Geom
.OutputType
== PRIM_UNKNOWN
) {
1368 "geometry shader didn't declare primitive output type\n");
1371 prog
->Geom
.OutputType
= linked_shader
->Geom
.OutputType
;
1373 if (linked_shader
->Geom
.VerticesOut
== 0) {
1375 "geometry shader didn't declare max_vertices\n");
1378 prog
->Geom
.VerticesOut
= linked_shader
->Geom
.VerticesOut
;
1380 if (linked_shader
->Geom
.Invocations
== 0)
1381 linked_shader
->Geom
.Invocations
= 1;
1383 prog
->Geom
.Invocations
= linked_shader
->Geom
.Invocations
;
1388 * Perform cross-validation of compute shader local_size_{x,y,z} layout
1389 * qualifiers for the attached compute shaders, and propagate them to the
1390 * linked CS and linked shader program.
1393 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
1394 struct gl_shader
*linked_shader
,
1395 struct gl_shader
**shader_list
,
1396 unsigned num_shaders
)
1398 for (int i
= 0; i
< 3; i
++)
1399 linked_shader
->Comp
.LocalSize
[i
] = 0;
1401 /* This function is called for all shader stages, but it only has an effect
1402 * for compute shaders.
1404 if (linked_shader
->Stage
!= MESA_SHADER_COMPUTE
)
1407 /* From the ARB_compute_shader spec, in the section describing local size
1410 * If multiple compute shaders attached to a single program object
1411 * declare local work-group size, the declarations must be identical;
1412 * otherwise a link-time error results. Furthermore, if a program
1413 * object contains any compute shaders, at least one must contain an
1414 * input layout qualifier specifying the local work sizes of the
1415 * program, or a link-time error will occur.
1417 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
1418 struct gl_shader
*shader
= shader_list
[sh
];
1420 if (shader
->Comp
.LocalSize
[0] != 0) {
1421 if (linked_shader
->Comp
.LocalSize
[0] != 0) {
1422 for (int i
= 0; i
< 3; i
++) {
1423 if (linked_shader
->Comp
.LocalSize
[i
] !=
1424 shader
->Comp
.LocalSize
[i
]) {
1425 linker_error(prog
, "compute shader defined with conflicting "
1431 for (int i
= 0; i
< 3; i
++)
1432 linked_shader
->Comp
.LocalSize
[i
] = shader
->Comp
.LocalSize
[i
];
1436 /* Just do the intrastage -> interstage propagation right now,
1437 * since we already know we're in the right type of shader program
1440 if (linked_shader
->Comp
.LocalSize
[0] == 0) {
1441 linker_error(prog
, "compute shader didn't declare local size\n");
1444 for (int i
= 0; i
< 3; i
++)
1445 prog
->Comp
.LocalSize
[i
] = linked_shader
->Comp
.LocalSize
[i
];
1450 * Combine a group of shaders for a single stage to generate a linked shader
1453 * If this function is supplied a single shader, it is cloned, and the new
1454 * shader is returned.
1456 static struct gl_shader
*
1457 link_intrastage_shaders(void *mem_ctx
,
1458 struct gl_context
*ctx
,
1459 struct gl_shader_program
*prog
,
1460 struct gl_shader
**shader_list
,
1461 unsigned num_shaders
)
1463 struct gl_uniform_block
*uniform_blocks
= NULL
;
1465 /* Check that global variables defined in multiple shaders are consistent.
1467 cross_validate_globals(prog
, shader_list
, num_shaders
, false);
1468 if (!prog
->LinkStatus
)
1471 /* Check that interface blocks defined in multiple shaders are consistent.
1473 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
1475 if (!prog
->LinkStatus
)
1478 /* Link up uniform blocks defined within this stage. */
1479 const unsigned num_uniform_blocks
=
1480 link_uniform_blocks(mem_ctx
, prog
, shader_list
, num_shaders
,
1482 if (!prog
->LinkStatus
)
1485 /* Check that there is only a single definition of each function signature
1486 * across all shaders.
1488 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
1489 foreach_list(node
, shader_list
[i
]->ir
) {
1490 ir_function
*const f
= ((ir_instruction
*) node
)->as_function();
1495 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
1496 ir_function
*const other
=
1497 shader_list
[j
]->symbols
->get_function(f
->name
);
1499 /* If the other shader has no function (and therefore no function
1500 * signatures) with the same name, skip to the next shader.
1505 foreach_list(n
, &f
->signatures
) {
1506 ir_function_signature
*sig
= (ir_function_signature
*) n
;
1508 if (!sig
->is_defined
|| sig
->is_builtin())
1511 ir_function_signature
*other_sig
=
1512 other
->exact_matching_signature(NULL
, &sig
->parameters
);
1514 if ((other_sig
!= NULL
) && other_sig
->is_defined
1515 && !other_sig
->is_builtin()) {
1516 linker_error(prog
, "function `%s' is multiply defined",
1525 /* Find the shader that defines main, and make a clone of it.
1527 * Starting with the clone, search for undefined references. If one is
1528 * found, find the shader that defines it. Clone the reference and add
1529 * it to the shader. Repeat until there are no undefined references or
1530 * until a reference cannot be resolved.
1532 gl_shader
*main
= NULL
;
1533 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1534 if (get_main_function_signature(shader_list
[i
]) != NULL
) {
1535 main
= shader_list
[i
];
1541 linker_error(prog
, "%s shader lacks `main'\n",
1542 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
1546 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
1547 linked
->ir
= new(linked
) exec_list
;
1548 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
1550 linked
->UniformBlocks
= uniform_blocks
;
1551 linked
->NumUniformBlocks
= num_uniform_blocks
;
1552 ralloc_steal(linked
, linked
->UniformBlocks
);
1554 link_fs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
1555 link_gs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
1556 link_cs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
1558 populate_symbol_table(linked
);
1560 /* The a pointer to the main function in the final linked shader (i.e., the
1561 * copy of the original shader that contained the main function).
1563 ir_function_signature
*const main_sig
= get_main_function_signature(linked
);
1565 /* Move any instructions other than variable declarations or function
1566 * declarations into main.
1568 exec_node
*insertion_point
=
1569 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
1572 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1573 if (shader_list
[i
] == main
)
1576 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
1577 insertion_point
, true, linked
);
1580 /* Check if any shader needs built-in functions. */
1581 bool need_builtins
= false;
1582 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1583 if (shader_list
[i
]->uses_builtin_functions
) {
1584 need_builtins
= true;
1590 if (need_builtins
) {
1591 /* Make a temporary array one larger than shader_list, which will hold
1592 * the built-in function shader as well.
1594 gl_shader
**linking_shaders
= (gl_shader
**)
1595 calloc(num_shaders
+ 1, sizeof(gl_shader
*));
1596 memcpy(linking_shaders
, shader_list
, num_shaders
* sizeof(gl_shader
*));
1597 linking_shaders
[num_shaders
] = _mesa_glsl_get_builtin_function_shader();
1599 ok
= link_function_calls(prog
, linked
, linking_shaders
, num_shaders
+ 1);
1601 free(linking_shaders
);
1603 ok
= link_function_calls(prog
, linked
, shader_list
, num_shaders
);
1608 ctx
->Driver
.DeleteShader(ctx
, linked
);
1612 /* At this point linked should contain all of the linked IR, so
1613 * validate it to make sure nothing went wrong.
1615 validate_ir_tree(linked
->ir
);
1617 /* Set the size of geometry shader input arrays */
1618 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
1619 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
1620 geom_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
1621 foreach_list(n
, linked
->ir
) {
1622 ir_instruction
*ir
= (ir_instruction
*) n
;
1623 ir
->accept(&input_resize_visitor
);
1627 /* Make a pass over all variable declarations to ensure that arrays with
1628 * unspecified sizes have a size specified. The size is inferred from the
1629 * max_array_access field.
1631 array_sizing_visitor v
;
1633 v
.fixup_unnamed_interface_types();
1639 * Update the sizes of linked shader uniform arrays to the maximum
1642 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1644 * If one or more elements of an array are active,
1645 * GetActiveUniform will return the name of the array in name,
1646 * subject to the restrictions listed above. The type of the array
1647 * is returned in type. The size parameter contains the highest
1648 * array element index used, plus one. The compiler or linker
1649 * determines the highest index used. There will be only one
1650 * active uniform reported by the GL per uniform array.
1654 update_array_sizes(struct gl_shader_program
*prog
)
1656 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1657 if (prog
->_LinkedShaders
[i
] == NULL
)
1660 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
1661 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1663 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
1664 !var
->type
->is_array())
1667 /* GL_ARB_uniform_buffer_object says that std140 uniforms
1668 * will not be eliminated. Since we always do std140, just
1669 * don't resize arrays in UBOs.
1671 * Atomic counters are supposed to get deterministic
1672 * locations assigned based on the declaration ordering and
1673 * sizes, array compaction would mess that up.
1675 if (var
->is_in_uniform_block() || var
->type
->contains_atomic())
1678 unsigned int size
= var
->data
.max_array_access
;
1679 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
1680 if (prog
->_LinkedShaders
[j
] == NULL
)
1683 foreach_list(node2
, prog
->_LinkedShaders
[j
]->ir
) {
1684 ir_variable
*other_var
= ((ir_instruction
*) node2
)->as_variable();
1688 if (strcmp(var
->name
, other_var
->name
) == 0 &&
1689 other_var
->data
.max_array_access
> size
) {
1690 size
= other_var
->data
.max_array_access
;
1695 if (size
+ 1 != var
->type
->length
) {
1696 /* If this is a built-in uniform (i.e., it's backed by some
1697 * fixed-function state), adjust the number of state slots to
1698 * match the new array size. The number of slots per array entry
1699 * is not known. It seems safe to assume that the total number of
1700 * slots is an integer multiple of the number of array elements.
1701 * Determine the number of slots per array element by dividing by
1702 * the old (total) size.
1704 if (var
->num_state_slots
> 0) {
1705 var
->num_state_slots
= (size
+ 1)
1706 * (var
->num_state_slots
/ var
->type
->length
);
1709 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
1711 /* FINISHME: We should update the types of array
1712 * dereferences of this variable now.
1720 * Find a contiguous set of available bits in a bitmask.
1722 * \param used_mask Bits representing used (1) and unused (0) locations
1723 * \param needed_count Number of contiguous bits needed.
1726 * Base location of the available bits on success or -1 on failure.
1729 find_available_slots(unsigned used_mask
, unsigned needed_count
)
1731 unsigned needed_mask
= (1 << needed_count
) - 1;
1732 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
1734 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1735 * cannot optimize possibly infinite loops" for the loop below.
1737 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
1740 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
1741 if ((needed_mask
& ~used_mask
) == needed_mask
)
1752 * Assign locations for either VS inputs for FS outputs
1754 * \param prog Shader program whose variables need locations assigned
1755 * \param target_index Selector for the program target to receive location
1756 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1757 * \c MESA_SHADER_FRAGMENT.
1758 * \param max_index Maximum number of generic locations. This corresponds
1759 * to either the maximum number of draw buffers or the
1760 * maximum number of generic attributes.
1763 * If locations are successfully assigned, true is returned. Otherwise an
1764 * error is emitted to the shader link log and false is returned.
1767 assign_attribute_or_color_locations(gl_shader_program
*prog
,
1768 unsigned target_index
,
1771 /* Mark invalid locations as being used.
1773 unsigned used_locations
= (max_index
>= 32)
1774 ? ~0 : ~((1 << max_index
) - 1);
1776 assert((target_index
== MESA_SHADER_VERTEX
)
1777 || (target_index
== MESA_SHADER_FRAGMENT
));
1779 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
1783 /* Operate in a total of four passes.
1785 * 1. Invalidate the location assignments for all vertex shader inputs.
1787 * 2. Assign locations for inputs that have user-defined (via
1788 * glBindVertexAttribLocation) locations and outputs that have
1789 * user-defined locations (via glBindFragDataLocation).
1791 * 3. Sort the attributes without assigned locations by number of slots
1792 * required in decreasing order. Fragmentation caused by attribute
1793 * locations assigned by the application may prevent large attributes
1794 * from having enough contiguous space.
1796 * 4. Assign locations to any inputs without assigned locations.
1799 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
1800 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
1802 const enum ir_variable_mode direction
=
1803 (target_index
== MESA_SHADER_VERTEX
)
1804 ? ir_var_shader_in
: ir_var_shader_out
;
1807 /* Temporary storage for the set of attributes that need locations assigned.
1813 /* Used below in the call to qsort. */
1814 static int compare(const void *a
, const void *b
)
1816 const temp_attr
*const l
= (const temp_attr
*) a
;
1817 const temp_attr
*const r
= (const temp_attr
*) b
;
1819 /* Reversed because we want a descending order sort below. */
1820 return r
->slots
- l
->slots
;
1824 unsigned num_attr
= 0;
1826 foreach_list(node
, sh
->ir
) {
1827 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1829 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
1832 if (var
->data
.explicit_location
) {
1833 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
1834 || (var
->data
.location
< 0)) {
1836 "invalid explicit location %d specified for `%s'\n",
1837 (var
->data
.location
< 0)
1838 ? var
->data
.location
1839 : var
->data
.location
- generic_base
,
1843 } else if (target_index
== MESA_SHADER_VERTEX
) {
1846 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
1847 assert(binding
>= VERT_ATTRIB_GENERIC0
);
1848 var
->data
.location
= binding
;
1849 var
->data
.is_unmatched_generic_inout
= 0;
1851 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
1855 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
1856 assert(binding
>= FRAG_RESULT_DATA0
);
1857 var
->data
.location
= binding
;
1858 var
->data
.is_unmatched_generic_inout
= 0;
1860 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
1861 var
->data
.index
= index
;
1866 /* If the variable is not a built-in and has a location statically
1867 * assigned in the shader (presumably via a layout qualifier), make sure
1868 * that it doesn't collide with other assigned locations. Otherwise,
1869 * add it to the list of variables that need linker-assigned locations.
1871 const unsigned slots
= var
->type
->count_attribute_slots();
1872 if (var
->data
.location
!= -1) {
1873 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
1874 /* From page 61 of the OpenGL 4.0 spec:
1876 * "LinkProgram will fail if the attribute bindings assigned
1877 * by BindAttribLocation do not leave not enough space to
1878 * assign a location for an active matrix attribute or an
1879 * active attribute array, both of which require multiple
1880 * contiguous generic attributes."
1882 * I think above text prohibits the aliasing of explicit and
1883 * automatic assignments. But, aliasing is allowed in manual
1884 * assignments of attribute locations. See below comments for
1887 * From OpenGL 4.0 spec, page 61:
1889 * "It is possible for an application to bind more than one
1890 * attribute name to the same location. This is referred to as
1891 * aliasing. This will only work if only one of the aliased
1892 * attributes is active in the executable program, or if no
1893 * path through the shader consumes more than one attribute of
1894 * a set of attributes aliased to the same location. A link
1895 * error can occur if the linker determines that every path
1896 * through the shader consumes multiple aliased attributes,
1897 * but implementations are not required to generate an error
1900 * From GLSL 4.30 spec, page 54:
1902 * "A program will fail to link if any two non-vertex shader
1903 * input variables are assigned to the same location. For
1904 * vertex shaders, multiple input variables may be assigned
1905 * to the same location using either layout qualifiers or via
1906 * the OpenGL API. However, such aliasing is intended only to
1907 * support vertex shaders where each execution path accesses
1908 * at most one input per each location. Implementations are
1909 * permitted, but not required, to generate link-time errors
1910 * if they detect that every path through the vertex shader
1911 * executable accesses multiple inputs assigned to any single
1912 * location. For all shader types, a program will fail to link
1913 * if explicit location assignments leave the linker unable
1914 * to find space for other variables without explicit
1917 * From OpenGL ES 3.0 spec, page 56:
1919 * "Binding more than one attribute name to the same location
1920 * is referred to as aliasing, and is not permitted in OpenGL
1921 * ES Shading Language 3.00 vertex shaders. LinkProgram will
1922 * fail when this condition exists. However, aliasing is
1923 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
1924 * This will only work if only one of the aliased attributes
1925 * is active in the executable program, or if no path through
1926 * the shader consumes more than one attribute of a set of
1927 * attributes aliased to the same location. A link error can
1928 * occur if the linker determines that every path through the
1929 * shader consumes multiple aliased attributes, but implemen-
1930 * tations are not required to generate an error in this case."
1932 * After looking at above references from OpenGL, OpenGL ES and
1933 * GLSL specifications, we allow aliasing of vertex input variables
1934 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
1936 * NOTE: This is not required by the spec but its worth mentioning
1937 * here that we're not doing anything to make sure that no path
1938 * through the vertex shader executable accesses multiple inputs
1939 * assigned to any single location.
1942 /* Mask representing the contiguous slots that will be used by
1945 const unsigned attr
= var
->data
.location
- generic_base
;
1946 const unsigned use_mask
= (1 << slots
) - 1;
1947 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
1948 ? "vertex shader input" : "fragment shader output";
1950 /* Generate a link error if the requested locations for this
1951 * attribute exceed the maximum allowed attribute location.
1953 if (attr
+ slots
> max_index
) {
1955 "insufficient contiguous locations "
1956 "available for %s `%s' %d %d %d", string
,
1957 var
->name
, used_locations
, use_mask
, attr
);
1961 /* Generate a link error if the set of bits requested for this
1962 * attribute overlaps any previously allocated bits.
1964 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
1965 if (target_index
== MESA_SHADER_FRAGMENT
||
1966 (prog
->IsES
&& prog
->Version
>= 300)) {
1968 "overlapping location is assigned "
1969 "to %s `%s' %d %d %d\n", string
,
1970 var
->name
, used_locations
, use_mask
, attr
);
1973 linker_warning(prog
,
1974 "overlapping location is assigned "
1975 "to %s `%s' %d %d %d\n", string
,
1976 var
->name
, used_locations
, use_mask
, attr
);
1980 used_locations
|= (use_mask
<< attr
);
1986 to_assign
[num_attr
].slots
= slots
;
1987 to_assign
[num_attr
].var
= var
;
1991 /* If all of the attributes were assigned locations by the application (or
1992 * are built-in attributes with fixed locations), return early. This should
1993 * be the common case.
1998 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
2000 if (target_index
== MESA_SHADER_VERTEX
) {
2001 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2002 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2003 * reserved to prevent it from being automatically allocated below.
2005 find_deref_visitor
find("gl_Vertex");
2007 if (find
.variable_found())
2008 used_locations
|= (1 << 0);
2011 for (unsigned i
= 0; i
< num_attr
; i
++) {
2012 /* Mask representing the contiguous slots that will be used by this
2015 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
2017 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
2020 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2021 ? "vertex shader input" : "fragment shader output";
2024 "insufficient contiguous locations "
2025 "available for %s `%s'",
2026 string
, to_assign
[i
].var
->name
);
2030 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
2031 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
2032 used_locations
|= (use_mask
<< location
);
2040 * Demote shader inputs and outputs that are not used in other stages
2043 demote_shader_inputs_and_outputs(gl_shader
*sh
, enum ir_variable_mode mode
)
2045 foreach_list(node
, sh
->ir
) {
2046 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
2048 if ((var
== NULL
) || (var
->data
.mode
!= int(mode
)))
2051 /* A shader 'in' or 'out' variable is only really an input or output if
2052 * its value is used by other shader stages. This will cause the variable
2053 * to have a location assigned.
2055 if (var
->data
.is_unmatched_generic_inout
) {
2056 var
->data
.mode
= ir_var_auto
;
2063 * Store the gl_FragDepth layout in the gl_shader_program struct.
2066 store_fragdepth_layout(struct gl_shader_program
*prog
)
2068 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
2072 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
2074 /* We don't look up the gl_FragDepth symbol directly because if
2075 * gl_FragDepth is not used in the shader, it's removed from the IR.
2076 * However, the symbol won't be removed from the symbol table.
2078 * We're only interested in the cases where the variable is NOT removed
2081 foreach_list(node
, ir
) {
2082 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
2084 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
2088 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
2089 switch (var
->data
.depth_layout
) {
2090 case ir_depth_layout_none
:
2091 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
2093 case ir_depth_layout_any
:
2094 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
2096 case ir_depth_layout_greater
:
2097 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
2099 case ir_depth_layout_less
:
2100 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
2102 case ir_depth_layout_unchanged
:
2103 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
2114 * Validate the resources used by a program versus the implementation limits
2117 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2119 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2120 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2125 if (sh
->num_samplers
> ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
2126 linker_error(prog
, "Too many %s shader texture samplers",
2127 _mesa_shader_stage_to_string(i
));
2130 if (sh
->num_uniform_components
>
2131 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
2132 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2133 linker_warning(prog
, "Too many %s shader default uniform block "
2134 "components, but the driver will try to optimize "
2135 "them out; this is non-portable out-of-spec "
2137 _mesa_shader_stage_to_string(i
));
2139 linker_error(prog
, "Too many %s shader default uniform block "
2141 _mesa_shader_stage_to_string(i
));
2145 if (sh
->num_combined_uniform_components
>
2146 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
2147 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2148 linker_warning(prog
, "Too many %s shader uniform components, "
2149 "but the driver will try to optimize them out; "
2150 "this is non-portable out-of-spec behavior\n",
2151 _mesa_shader_stage_to_string(i
));
2153 linker_error(prog
, "Too many %s shader uniform components",
2154 _mesa_shader_stage_to_string(i
));
2159 unsigned blocks
[MESA_SHADER_STAGES
] = {0};
2160 unsigned total_uniform_blocks
= 0;
2162 for (unsigned i
= 0; i
< prog
->NumUniformBlocks
; i
++) {
2163 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2164 if (prog
->UniformBlockStageIndex
[j
][i
] != -1) {
2166 total_uniform_blocks
++;
2170 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
2171 linker_error(prog
, "Too many combined uniform blocks (%d/%d)",
2172 prog
->NumUniformBlocks
,
2173 ctx
->Const
.MaxCombinedUniformBlocks
);
2175 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2176 const unsigned max_uniform_blocks
=
2177 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
2178 if (blocks
[i
] > max_uniform_blocks
) {
2179 linker_error(prog
, "Too many %s uniform blocks (%d/%d)",
2180 _mesa_shader_stage_to_string(i
),
2182 max_uniform_blocks
);
2191 * Validate shader image resources.
2194 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2196 unsigned total_image_units
= 0;
2197 unsigned fragment_outputs
= 0;
2199 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
2202 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2203 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2206 if (sh
->NumImages
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
2207 linker_error(prog
, "Too many %s shader image uniforms",
2208 _mesa_shader_stage_to_string(i
));
2210 total_image_units
+= sh
->NumImages
;
2212 if (i
== MESA_SHADER_FRAGMENT
) {
2213 foreach_list(node
, sh
->ir
) {
2214 ir_variable
*var
= ((ir_instruction
*)node
)->as_variable();
2215 if (var
&& var
->data
.mode
== ir_var_shader_out
)
2216 fragment_outputs
+= var
->type
->count_attribute_slots();
2222 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
2223 linker_error(prog
, "Too many combined image uniforms");
2225 if (total_image_units
+ fragment_outputs
>
2226 ctx
->Const
.MaxCombinedImageUnitsAndFragmentOutputs
)
2227 linker_error(prog
, "Too many combined image uniforms and fragment outputs");
2232 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
2233 * for a variable, checks for overlaps between other uniforms using explicit
2237 reserve_explicit_locations(struct gl_shader_program
*prog
,
2238 string_to_uint_map
*map
, ir_variable
*var
)
2240 unsigned slots
= var
->type
->uniform_locations();
2241 unsigned max_loc
= var
->data
.location
+ slots
- 1;
2243 /* Resize remap table if locations do not fit in the current one. */
2244 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
2245 prog
->UniformRemapTable
=
2246 reralloc(prog
, prog
->UniformRemapTable
,
2247 gl_uniform_storage
*,
2250 if (!prog
->UniformRemapTable
) {
2251 linker_error(prog
, "Out of memory during linking.");
2255 /* Initialize allocated space. */
2256 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
2257 prog
->UniformRemapTable
[i
] = NULL
;
2259 prog
->NumUniformRemapTable
= max_loc
+ 1;
2262 for (unsigned i
= 0; i
< slots
; i
++) {
2263 unsigned loc
= var
->data
.location
+ i
;
2265 /* Check if location is already used. */
2266 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
2268 /* Possibly same uniform from a different stage, this is ok. */
2270 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
)
2273 /* ARB_explicit_uniform_location specification states:
2275 * "No two default-block uniform variables in the program can have
2276 * the same location, even if they are unused, otherwise a compiler
2277 * or linker error will be generated."
2280 "location qualifier for uniform %s overlaps"
2281 "previously used location",
2286 /* Initialize location as inactive before optimization
2287 * rounds and location assignment.
2289 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
2292 /* Note, base location used for arrays. */
2293 map
->put(var
->data
.location
, var
->name
);
2299 * Check and reserve all explicit uniform locations, called before
2300 * any optimizations happen to handle also inactive uniforms and
2301 * inactive array elements that may get trimmed away.
2304 check_explicit_uniform_locations(struct gl_context
*ctx
,
2305 struct gl_shader_program
*prog
)
2307 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
2310 /* This map is used to detect if overlapping explicit locations
2311 * occur with the same uniform (from different stage) or a different one.
2313 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
2316 linker_error(prog
, "Out of memory during linking.");
2320 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2321 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2326 foreach_list(node
, sh
->ir
) {
2327 ir_variable
*var
= ((ir_instruction
*)node
)->as_variable();
2328 if ((var
&& var
->data
.mode
== ir_var_uniform
) &&
2329 var
->data
.explicit_location
) {
2330 if (!reserve_explicit_locations(prog
, uniform_map
, var
))
2340 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2342 tfeedback_decl
*tfeedback_decls
= NULL
;
2343 unsigned num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
2345 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
2347 prog
->LinkStatus
= true; /* All error paths will set this to false */
2348 prog
->Validated
= false;
2349 prog
->_Used
= false;
2351 ralloc_free(prog
->InfoLog
);
2352 prog
->InfoLog
= ralloc_strdup(NULL
, "");
2354 ralloc_free(prog
->UniformBlocks
);
2355 prog
->UniformBlocks
= NULL
;
2356 prog
->NumUniformBlocks
= 0;
2357 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2358 ralloc_free(prog
->UniformBlockStageIndex
[i
]);
2359 prog
->UniformBlockStageIndex
[i
] = NULL
;
2362 ralloc_free(prog
->AtomicBuffers
);
2363 prog
->AtomicBuffers
= NULL
;
2364 prog
->NumAtomicBuffers
= 0;
2365 prog
->ARB_fragment_coord_conventions_enable
= false;
2367 /* Separate the shaders into groups based on their type.
2369 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
2370 unsigned num_shaders
[MESA_SHADER_STAGES
];
2372 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2373 shader_list
[i
] = (struct gl_shader
**)
2374 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
2378 unsigned min_version
= UINT_MAX
;
2379 unsigned max_version
= 0;
2380 const bool is_es_prog
=
2381 (prog
->NumShaders
> 0 && prog
->Shaders
[0]->IsES
) ? true : false;
2382 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
2383 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
2384 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
2386 if (prog
->Shaders
[i
]->IsES
!= is_es_prog
) {
2387 linker_error(prog
, "all shaders must use same shading "
2388 "language version\n");
2392 prog
->ARB_fragment_coord_conventions_enable
|=
2393 prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
;
2395 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
2396 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
2397 num_shaders
[shader_type
]++;
2400 /* In desktop GLSL, different shader versions may be linked together. In
2401 * GLSL ES, all shader versions must be the same.
2403 if (is_es_prog
&& min_version
!= max_version
) {
2404 linker_error(prog
, "all shaders must use same shading "
2405 "language version\n");
2409 prog
->Version
= max_version
;
2410 prog
->IsES
= is_es_prog
;
2412 /* Geometry shaders have to be linked with vertex shaders.
2414 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
2415 num_shaders
[MESA_SHADER_VERTEX
] == 0 &&
2416 !prog
->SeparateShader
) {
2417 linker_error(prog
, "Geometry shader must be linked with "
2422 /* Compute shaders have additional restrictions. */
2423 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
2424 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
2425 linker_error(prog
, "Compute shaders may not be linked with any other "
2426 "type of shader\n");
2429 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2430 if (prog
->_LinkedShaders
[i
] != NULL
)
2431 ctx
->Driver
.DeleteShader(ctx
, prog
->_LinkedShaders
[i
]);
2433 prog
->_LinkedShaders
[i
] = NULL
;
2436 /* Link all shaders for a particular stage and validate the result.
2438 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
2439 if (num_shaders
[stage
] > 0) {
2440 gl_shader
*const sh
=
2441 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
2442 num_shaders
[stage
]);
2444 if (!prog
->LinkStatus
)
2448 case MESA_SHADER_VERTEX
:
2449 validate_vertex_shader_executable(prog
, sh
);
2451 case MESA_SHADER_GEOMETRY
:
2452 validate_geometry_shader_executable(prog
, sh
);
2454 case MESA_SHADER_FRAGMENT
:
2455 validate_fragment_shader_executable(prog
, sh
);
2458 if (!prog
->LinkStatus
)
2461 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[stage
], sh
);
2465 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0)
2466 prog
->LastClipDistanceArraySize
= prog
->Geom
.ClipDistanceArraySize
;
2467 else if (num_shaders
[MESA_SHADER_VERTEX
] > 0)
2468 prog
->LastClipDistanceArraySize
= prog
->Vert
.ClipDistanceArraySize
;
2470 prog
->LastClipDistanceArraySize
= 0; /* Not used */
2472 /* Here begins the inter-stage linking phase. Some initial validation is
2473 * performed, then locations are assigned for uniforms, attributes, and
2476 cross_validate_uniforms(prog
);
2477 if (!prog
->LinkStatus
)
2482 for (prev
= 0; prev
<= MESA_SHADER_FRAGMENT
; prev
++) {
2483 if (prog
->_LinkedShaders
[prev
] != NULL
)
2487 check_explicit_uniform_locations(ctx
, prog
);
2488 if (!prog
->LinkStatus
)
2491 /* Validate the inputs of each stage with the output of the preceding
2494 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
2495 if (prog
->_LinkedShaders
[i
] == NULL
)
2498 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
2499 prog
->_LinkedShaders
[i
]);
2500 if (!prog
->LinkStatus
)
2503 cross_validate_outputs_to_inputs(prog
,
2504 prog
->_LinkedShaders
[prev
],
2505 prog
->_LinkedShaders
[i
]);
2506 if (!prog
->LinkStatus
)
2512 /* Cross-validate uniform blocks between shader stages */
2513 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
,
2514 MESA_SHADER_STAGES
);
2515 if (!prog
->LinkStatus
)
2518 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2519 if (prog
->_LinkedShaders
[i
] != NULL
)
2520 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
2523 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
2524 * it before optimization because we want most of the checks to get
2525 * dropped thanks to constant propagation.
2527 * This rule also applies to GLSL ES 3.00.
2529 if (max_version
>= (is_es_prog
? 300 : 130)) {
2530 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
2532 lower_discard_flow(sh
->ir
);
2536 if (!interstage_cross_validate_uniform_blocks(prog
))
2539 /* Do common optimization before assigning storage for attributes,
2540 * uniforms, and varyings. Later optimization could possibly make
2541 * some of that unused.
2543 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2544 if (prog
->_LinkedShaders
[i
] == NULL
)
2547 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
2548 if (!prog
->LinkStatus
)
2551 if (ctx
->ShaderCompilerOptions
[i
].LowerClipDistance
) {
2552 lower_clip_distance(prog
->_LinkedShaders
[i
]);
2555 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false,
2556 &ctx
->ShaderCompilerOptions
[i
],
2557 ctx
->Const
.NativeIntegers
))
2561 /* Mark all generic shader inputs and outputs as unpaired. */
2562 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
2563 if (prog
->_LinkedShaders
[i
] != NULL
) {
2564 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
2568 /* FINISHME: The value of the max_attribute_index parameter is
2569 * FINISHME: implementation dependent based on the value of
2570 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
2571 * FINISHME: at least 16, so hardcode 16 for now.
2573 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_VERTEX
, 16)) {
2577 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_FRAGMENT
, MAX2(ctx
->Const
.MaxDrawBuffers
, ctx
->Const
.MaxDualSourceDrawBuffers
))) {
2582 for (first
= 0; first
<= MESA_SHADER_FRAGMENT
; first
++) {
2583 if (prog
->_LinkedShaders
[first
] != NULL
)
2587 if (num_tfeedback_decls
!= 0) {
2588 /* From GL_EXT_transform_feedback:
2589 * A program will fail to link if:
2591 * * the <count> specified by TransformFeedbackVaryingsEXT is
2592 * non-zero, but the program object has no vertex or geometry
2595 if (first
== MESA_SHADER_FRAGMENT
) {
2596 linker_error(prog
, "Transform feedback varyings specified, but "
2597 "no vertex or geometry shader is present.");
2601 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
2602 prog
->TransformFeedback
.NumVarying
);
2603 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
2604 prog
->TransformFeedback
.VaryingNames
,
2609 /* Linking the stages in the opposite order (from fragment to vertex)
2610 * ensures that inter-shader outputs written to in an earlier stage are
2611 * eliminated if they are (transitively) not used in a later stage.
2614 for (last
= MESA_SHADER_FRAGMENT
; last
>= 0; last
--) {
2615 if (prog
->_LinkedShaders
[last
] != NULL
)
2619 if (last
>= 0 && last
< MESA_SHADER_FRAGMENT
) {
2620 gl_shader
*const sh
= prog
->_LinkedShaders
[last
];
2622 if (num_tfeedback_decls
!= 0 || prog
->SeparateShader
) {
2623 /* There was no fragment shader, but we still have to assign varying
2624 * locations for use by transform feedback.
2626 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
2628 num_tfeedback_decls
, tfeedback_decls
,
2633 do_dead_builtin_varyings(ctx
, sh
, NULL
,
2634 num_tfeedback_decls
, tfeedback_decls
);
2636 if (!prog
->SeparateShader
)
2637 demote_shader_inputs_and_outputs(sh
, ir_var_shader_out
);
2639 /* Eliminate code that is now dead due to unused outputs being demoted.
2641 while (do_dead_code(sh
->ir
, false))
2644 else if (first
== MESA_SHADER_FRAGMENT
) {
2645 /* If the program only contains a fragment shader...
2647 gl_shader
*const sh
= prog
->_LinkedShaders
[first
];
2649 do_dead_builtin_varyings(ctx
, NULL
, sh
,
2650 num_tfeedback_decls
, tfeedback_decls
);
2652 if (prog
->SeparateShader
) {
2653 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
2654 NULL
/* producer */,
2656 0 /* num_tfeedback_decls */,
2657 NULL
/* tfeedback_decls */,
2658 0 /* gs_input_vertices */))
2661 demote_shader_inputs_and_outputs(sh
, ir_var_shader_in
);
2663 while (do_dead_code(sh
->ir
, false))
2668 for (int i
= next
- 1; i
>= 0; i
--) {
2669 if (prog
->_LinkedShaders
[i
] == NULL
)
2672 gl_shader
*const sh_i
= prog
->_LinkedShaders
[i
];
2673 gl_shader
*const sh_next
= prog
->_LinkedShaders
[next
];
2674 unsigned gs_input_vertices
=
2675 next
== MESA_SHADER_GEOMETRY
? prog
->Geom
.VerticesIn
: 0;
2677 if (!assign_varying_locations(ctx
, mem_ctx
, prog
, sh_i
, sh_next
,
2678 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
2679 tfeedback_decls
, gs_input_vertices
))
2682 do_dead_builtin_varyings(ctx
, sh_i
, sh_next
,
2683 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
2686 demote_shader_inputs_and_outputs(sh_i
, ir_var_shader_out
);
2687 demote_shader_inputs_and_outputs(sh_next
, ir_var_shader_in
);
2689 /* Eliminate code that is now dead due to unused outputs being demoted.
2691 while (do_dead_code(sh_i
->ir
, false))
2693 while (do_dead_code(sh_next
->ir
, false))
2696 /* This must be done after all dead varyings are eliminated. */
2697 if (!check_against_output_limit(ctx
, prog
, sh_i
))
2699 if (!check_against_input_limit(ctx
, prog
, sh_next
))
2705 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
))
2708 update_array_sizes(prog
);
2709 link_assign_uniform_locations(prog
);
2710 link_assign_atomic_counter_resources(ctx
, prog
);
2711 store_fragdepth_layout(prog
);
2713 check_resources(ctx
, prog
);
2714 check_image_resources(ctx
, prog
);
2715 link_check_atomic_counter_resources(ctx
, prog
);
2717 if (!prog
->LinkStatus
)
2720 /* OpenGL ES requires that a vertex shader and a fragment shader both be
2721 * present in a linked program. GL_ARB_ES2_compatibility doesn't say
2722 * anything about shader linking when one of the shaders (vertex or
2723 * fragment shader) is absent. So, the extension shouldn't change the
2724 * behavior specified in GLSL specification.
2726 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
) {
2727 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
2728 linker_error(prog
, "program lacks a vertex shader\n");
2729 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
2730 linker_error(prog
, "program lacks a fragment shader\n");
2734 /* FINISHME: Assign fragment shader output locations. */
2737 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2738 free(shader_list
[i
]);
2739 if (prog
->_LinkedShaders
[i
] == NULL
)
2742 /* Do a final validation step to make sure that the IR wasn't
2743 * invalidated by any modifications performed after intrastage linking.
2745 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
2747 /* Retain any live IR, but trash the rest. */
2748 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
2750 /* The symbol table in the linked shaders may contain references to
2751 * variables that were removed (e.g., unused uniforms). Since it may
2752 * contain junk, there is no possible valid use. Delete it and set the
2755 delete prog
->_LinkedShaders
[i
]->symbols
;
2756 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
2759 ralloc_free(mem_ctx
);