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"
79 #include "main/shaderobj.h"
80 #include "main/enums.h"
83 void linker_error(gl_shader_program
*, const char *, ...);
88 * Visitor that determines whether or not a variable is ever written.
90 class find_assignment_visitor
: public ir_hierarchical_visitor
{
92 find_assignment_visitor(const char *name
)
93 : name(name
), found(false)
98 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
100 ir_variable
*const var
= ir
->lhs
->variable_referenced();
102 if (strcmp(name
, var
->name
) == 0) {
107 return visit_continue_with_parent
;
110 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
112 exec_list_iterator sig_iter
= ir
->callee
->parameters
.iterator();
113 foreach_iter(exec_list_iterator
, iter
, *ir
) {
114 ir_rvalue
*param_rval
= (ir_rvalue
*)iter
.get();
115 ir_variable
*sig_param
= (ir_variable
*)sig_iter
.get();
117 if (sig_param
->mode
== ir_var_function_out
||
118 sig_param
->mode
== ir_var_function_inout
) {
119 ir_variable
*var
= param_rval
->variable_referenced();
120 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
->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
->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
->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
->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
, "error: ");
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(gl_shader
*sh
, int input_base
,
372 foreach_list(node
, sh
->ir
) {
373 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
380 case ir_var_shader_in
:
383 case ir_var_shader_out
:
390 /* Only assign locations for generic attributes / varyings / etc.
392 if ((var
->location
>= base
) && !var
->explicit_location
)
395 if ((var
->location
== -1) && !var
->explicit_location
) {
396 var
->is_unmatched_generic_inout
= 1;
397 var
->location_frac
= 0;
399 var
->is_unmatched_generic_inout
= 0;
406 * Set UsesClipDistance and ClipDistanceArraySize based on the given shader.
408 * Also check for errors based on incorrect usage of gl_ClipVertex and
411 * Return false if an error was reported.
414 analyze_clip_usage(const char *shader_type
, struct gl_shader_program
*prog
,
415 struct gl_shader
*shader
, GLboolean
*UsesClipDistance
,
416 GLuint
*ClipDistanceArraySize
)
418 *ClipDistanceArraySize
= 0;
420 if (!prog
->IsES
&& prog
->Version
>= 130) {
421 /* From section 7.1 (Vertex Shader Special Variables) of the
424 * "It is an error for a shader to statically write both
425 * gl_ClipVertex and gl_ClipDistance."
427 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
428 * gl_ClipVertex nor gl_ClipDistance.
430 find_assignment_visitor
clip_vertex("gl_ClipVertex");
431 find_assignment_visitor
clip_distance("gl_ClipDistance");
433 clip_vertex
.run(shader
->ir
);
434 clip_distance
.run(shader
->ir
);
435 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
436 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
437 "and `gl_ClipDistance'\n", shader_type
);
440 *UsesClipDistance
= clip_distance
.variable_found();
441 ir_variable
*clip_distance_var
=
442 shader
->symbols
->get_variable("gl_ClipDistance");
443 if (clip_distance_var
)
444 *ClipDistanceArraySize
= clip_distance_var
->type
->length
;
446 *UsesClipDistance
= false;
452 * Verify that a vertex shader executable meets all semantic requirements.
454 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
457 * \param shader Vertex shader executable to be verified
460 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
461 struct gl_shader
*shader
)
466 /* From the GLSL 1.10 spec, page 48:
468 * "The variable gl_Position is available only in the vertex
469 * language and is intended for writing the homogeneous vertex
470 * position. All executions of a well-formed vertex shader
471 * executable must write a value into this variable. [...] The
472 * 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."
477 * while in GLSL 1.40 this text is changed to:
479 * "The variable gl_Position is available only in the vertex
480 * language and is intended for writing the homogeneous vertex
481 * position. It can be written at any time during shader
482 * execution. It may also be read back by a vertex shader
483 * after being written. This value will be used by primitive
484 * assembly, clipping, culling, and other fixed functionality
485 * operations, if present, that operate on primitives after
486 * vertex processing has occurred. Its value is undefined if
487 * the vertex shader executable does not write gl_Position."
489 * GLSL ES 3.00 is similar to GLSL 1.40--failing to write to gl_Position is
492 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
493 find_assignment_visitor
find("gl_Position");
494 find
.run(shader
->ir
);
495 if (!find
.variable_found()) {
496 linker_error(prog
, "vertex shader does not write to `gl_Position'\n");
501 analyze_clip_usage("vertex", prog
, shader
, &prog
->Vert
.UsesClipDistance
,
502 &prog
->Vert
.ClipDistanceArraySize
);
507 * Verify that a fragment shader executable meets all semantic requirements
509 * \param shader Fragment shader executable to be verified
512 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
513 struct gl_shader
*shader
)
518 find_assignment_visitor
frag_color("gl_FragColor");
519 find_assignment_visitor
frag_data("gl_FragData");
521 frag_color
.run(shader
->ir
);
522 frag_data
.run(shader
->ir
);
524 if (frag_color
.variable_found() && frag_data
.variable_found()) {
525 linker_error(prog
, "fragment shader writes to both "
526 "`gl_FragColor' and `gl_FragData'\n");
531 * Verify that a geometry shader executable meets all semantic requirements
533 * Also sets prog->Geom.VerticesIn, prog->Geom.UsesClipDistance, and
534 * prog->Geom.ClipDistanceArraySize as a side effect.
536 * \param shader Geometry shader executable to be verified
539 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
540 struct gl_shader
*shader
)
545 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
546 prog
->Geom
.VerticesIn
= num_vertices
;
548 analyze_clip_usage("geometry", prog
, shader
, &prog
->Geom
.UsesClipDistance
,
549 &prog
->Geom
.ClipDistanceArraySize
);
551 find_end_primitive_visitor end_primitive
;
552 end_primitive
.run(shader
->ir
);
553 prog
->Geom
.UsesEndPrimitive
= end_primitive
.end_primitive_found();
558 * Generate a string describing the mode of a variable
561 mode_string(const ir_variable
*var
)
565 return (var
->read_only
) ? "global constant" : "global variable";
567 case ir_var_uniform
: return "uniform";
568 case ir_var_shader_in
: return "shader input";
569 case ir_var_shader_out
: return "shader output";
571 case ir_var_const_in
:
572 case ir_var_temporary
:
574 assert(!"Should not get here.");
575 return "invalid variable";
581 * Perform validation of global variables used across multiple shaders
584 cross_validate_globals(struct gl_shader_program
*prog
,
585 struct gl_shader
**shader_list
,
586 unsigned num_shaders
,
589 /* Examine all of the uniforms in all of the shaders and cross validate
592 glsl_symbol_table variables
;
593 for (unsigned i
= 0; i
< num_shaders
; i
++) {
594 if (shader_list
[i
] == NULL
)
597 foreach_list(node
, shader_list
[i
]->ir
) {
598 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
603 if (uniforms_only
&& (var
->mode
!= ir_var_uniform
))
606 /* Don't cross validate temporaries that are at global scope. These
607 * will eventually get pulled into the shaders 'main'.
609 if (var
->mode
== ir_var_temporary
)
612 /* If a global with this name has already been seen, verify that the
613 * new instance has the same type. In addition, if the globals have
614 * initializers, the values of the initializers must be the same.
616 ir_variable
*const existing
= variables
.get_variable(var
->name
);
617 if (existing
!= NULL
) {
618 if (var
->type
!= existing
->type
) {
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.
624 if (var
->type
->is_array()
625 && existing
->type
->is_array()
626 && (var
->type
->fields
.array
== existing
->type
->fields
.array
)
627 && ((var
->type
->length
== 0)
628 || (existing
->type
->length
== 0))) {
629 if (var
->type
->length
!= 0) {
630 existing
->type
= var
->type
;
633 linker_error(prog
, "%s `%s' declared as type "
634 "`%s' and type `%s'\n",
636 var
->name
, var
->type
->name
,
637 existing
->type
->name
);
642 if (var
->explicit_location
) {
643 if (existing
->explicit_location
644 && (var
->location
!= existing
->location
)) {
645 linker_error(prog
, "explicit locations for %s "
646 "`%s' have differing values\n",
647 mode_string(var
), var
->name
);
651 existing
->location
= var
->location
;
652 existing
->explicit_location
= true;
655 /* From the GLSL 4.20 specification:
656 * "A link error will result if two compilation units in a program
657 * specify different integer-constant bindings for the same
658 * opaque-uniform name. However, it is not an error to specify a
659 * binding on some but not all declarations for the same name"
661 if (var
->explicit_binding
) {
662 if (existing
->explicit_binding
&&
663 var
->binding
!= existing
->binding
) {
664 linker_error(prog
, "explicit bindings for %s "
665 "`%s' have differing values\n",
666 mode_string(var
), var
->name
);
670 existing
->binding
= var
->binding
;
671 existing
->explicit_binding
= true;
674 /* Validate layout qualifiers for gl_FragDepth.
676 * From the AMD/ARB_conservative_depth specs:
678 * "If gl_FragDepth is redeclared in any fragment shader in a
679 * program, it must be redeclared in all fragment shaders in
680 * that program that have static assignments to
681 * gl_FragDepth. All redeclarations of gl_FragDepth in all
682 * fragment shaders in a single program must have the same set
685 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
686 bool layout_declared
= var
->depth_layout
!= ir_depth_layout_none
;
687 bool layout_differs
=
688 var
->depth_layout
!= existing
->depth_layout
;
690 if (layout_declared
&& layout_differs
) {
692 "All redeclarations of gl_FragDepth in all "
693 "fragment shaders in a single program must have "
694 "the same set of qualifiers.");
697 if (var
->used
&& layout_differs
) {
699 "If gl_FragDepth is redeclared with a layout "
700 "qualifier in any fragment shader, it must be "
701 "redeclared with the same layout qualifier in "
702 "all fragment shaders that have assignments to "
707 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
709 * "If a shared global has multiple initializers, the
710 * initializers must all be constant expressions, and they
711 * must all have the same value. Otherwise, a link error will
712 * result. (A shared global having only one initializer does
713 * not require that initializer to be a constant expression.)"
715 * Previous to 4.20 the GLSL spec simply said that initializers
716 * must have the same value. In this case of non-constant
717 * initializers, this was impossible to determine. As a result,
718 * no vendor actually implemented that behavior. The 4.20
719 * behavior matches the implemented behavior of at least one other
720 * vendor, so we'll implement that for all GLSL versions.
722 if (var
->constant_initializer
!= NULL
) {
723 if (existing
->constant_initializer
!= NULL
) {
724 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
725 linker_error(prog
, "initializers for %s "
726 "`%s' have differing values\n",
727 mode_string(var
), var
->name
);
731 /* If the first-seen instance of a particular uniform did not
732 * have an initializer but a later instance does, copy the
733 * initializer to the version stored in the symbol table.
735 /* FINISHME: This is wrong. The constant_value field should
736 * FINISHME: not be modified! Imagine a case where a shader
737 * FINISHME: without an initializer is linked in two different
738 * FINISHME: programs with shaders that have differing
739 * FINISHME: initializers. Linking with the first will
740 * FINISHME: modify the shader, and linking with the second
741 * FINISHME: will fail.
743 existing
->constant_initializer
=
744 var
->constant_initializer
->clone(ralloc_parent(existing
),
749 if (var
->has_initializer
) {
750 if (existing
->has_initializer
751 && (var
->constant_initializer
== NULL
752 || existing
->constant_initializer
== NULL
)) {
754 "shared global variable `%s' has multiple "
755 "non-constant initializers.\n",
760 /* Some instance had an initializer, so keep track of that. In
761 * this location, all sorts of initializers (constant or
762 * otherwise) will propagate the existence to the variable
763 * stored in the symbol table.
765 existing
->has_initializer
= true;
768 if (existing
->invariant
!= var
->invariant
) {
769 linker_error(prog
, "declarations for %s `%s' have "
770 "mismatching invariant qualifiers\n",
771 mode_string(var
), var
->name
);
774 if (existing
->centroid
!= var
->centroid
) {
775 linker_error(prog
, "declarations for %s `%s' have "
776 "mismatching centroid qualifiers\n",
777 mode_string(var
), var
->name
);
781 variables
.add_variable(var
);
788 * Perform validation of uniforms used across multiple shader stages
791 cross_validate_uniforms(struct gl_shader_program
*prog
)
793 cross_validate_globals(prog
, prog
->_LinkedShaders
,
794 MESA_SHADER_TYPES
, true);
798 * Accumulates the array of prog->UniformBlocks and checks that all
799 * definitons of blocks agree on their contents.
802 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
)
804 unsigned max_num_uniform_blocks
= 0;
805 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
806 if (prog
->_LinkedShaders
[i
])
807 max_num_uniform_blocks
+= prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
810 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
811 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
813 prog
->UniformBlockStageIndex
[i
] = ralloc_array(prog
, int,
814 max_num_uniform_blocks
);
815 for (unsigned int j
= 0; j
< max_num_uniform_blocks
; j
++)
816 prog
->UniformBlockStageIndex
[i
][j
] = -1;
821 for (unsigned int j
= 0; j
< sh
->NumUniformBlocks
; j
++) {
822 int index
= link_cross_validate_uniform_block(prog
,
823 &prog
->UniformBlocks
,
824 &prog
->NumUniformBlocks
,
825 &sh
->UniformBlocks
[j
]);
828 linker_error(prog
, "uniform block `%s' has mismatching definitions",
829 sh
->UniformBlocks
[j
].Name
);
833 prog
->UniformBlockStageIndex
[i
][index
] = j
;
842 * Populates a shaders symbol table with all global declarations
845 populate_symbol_table(gl_shader
*sh
)
847 sh
->symbols
= new(sh
) glsl_symbol_table
;
849 foreach_list(node
, sh
->ir
) {
850 ir_instruction
*const inst
= (ir_instruction
*) node
;
854 if ((func
= inst
->as_function()) != NULL
) {
855 sh
->symbols
->add_function(func
);
856 } else if ((var
= inst
->as_variable()) != NULL
) {
857 sh
->symbols
->add_variable(var
);
864 * Remap variables referenced in an instruction tree
866 * This is used when instruction trees are cloned from one shader and placed in
867 * another. These trees will contain references to \c ir_variable nodes that
868 * do not exist in the target shader. This function finds these \c ir_variable
869 * references and replaces the references with matching variables in the target
872 * If there is no matching variable in the target shader, a clone of the
873 * \c ir_variable is made and added to the target shader. The new variable is
874 * added to \b both the instruction stream and the symbol table.
876 * \param inst IR tree that is to be processed.
877 * \param symbols Symbol table containing global scope symbols in the
879 * \param instructions Instruction stream where new variable declarations
883 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
886 class remap_visitor
: public ir_hierarchical_visitor
{
888 remap_visitor(struct gl_shader
*target
,
891 this->target
= target
;
892 this->symbols
= target
->symbols
;
893 this->instructions
= target
->ir
;
897 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
899 if (ir
->var
->mode
== ir_var_temporary
) {
900 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
904 return visit_continue
;
907 ir_variable
*const existing
=
908 this->symbols
->get_variable(ir
->var
->name
);
909 if (existing
!= NULL
)
912 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
914 this->symbols
->add_variable(copy
);
915 this->instructions
->push_head(copy
);
919 return visit_continue
;
923 struct gl_shader
*target
;
924 glsl_symbol_table
*symbols
;
925 exec_list
*instructions
;
929 remap_visitor
v(target
, temps
);
936 * Move non-declarations from one instruction stream to another
938 * The intended usage pattern of this function is to pass the pointer to the
939 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
940 * pointer) for \c last and \c false for \c make_copies on the first
941 * call. Successive calls pass the return value of the previous call for
942 * \c last and \c true for \c make_copies.
944 * \param instructions Source instruction stream
945 * \param last Instruction after which new instructions should be
946 * inserted in the target instruction stream
947 * \param make_copies Flag selecting whether instructions in \c instructions
948 * should be copied (via \c ir_instruction::clone) into the
949 * target list or moved.
952 * The new "last" instruction in the target instruction stream. This pointer
953 * is suitable for use as the \c last parameter of a later call to this
957 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
958 bool make_copies
, gl_shader
*target
)
960 hash_table
*temps
= NULL
;
963 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
964 hash_table_pointer_compare
);
966 foreach_list_safe(node
, instructions
) {
967 ir_instruction
*inst
= (ir_instruction
*) node
;
969 if (inst
->as_function())
972 ir_variable
*var
= inst
->as_variable();
973 if ((var
!= NULL
) && (var
->mode
!= ir_var_temporary
))
976 assert(inst
->as_assignment()
978 || inst
->as_if() /* for initializers with the ?: operator */
979 || ((var
!= NULL
) && (var
->mode
== ir_var_temporary
)));
982 inst
= inst
->clone(target
, NULL
);
985 hash_table_insert(temps
, inst
, var
);
987 remap_variables(inst
, target
, temps
);
992 last
->insert_after(inst
);
997 hash_table_dtor(temps
);
1003 * Get the function signature for main from a shader
1005 static ir_function_signature
*
1006 get_main_function_signature(gl_shader
*sh
)
1008 ir_function
*const f
= sh
->symbols
->get_function("main");
1010 exec_list void_parameters
;
1012 /* Look for the 'void main()' signature and ensure that it's defined.
1013 * This keeps the linker from accidentally pick a shader that just
1014 * contains a prototype for main.
1016 * We don't have to check for multiple definitions of main (in multiple
1017 * shaders) because that would have already been caught above.
1019 ir_function_signature
*sig
= f
->matching_signature(NULL
, &void_parameters
);
1020 if ((sig
!= NULL
) && sig
->is_defined
) {
1030 * This class is only used in link_intrastage_shaders() below but declaring
1031 * it inside that function leads to compiler warnings with some versions of
1034 class array_sizing_visitor
: public ir_hierarchical_visitor
{
1036 virtual ir_visitor_status
visit(ir_variable
*var
)
1038 if (var
->type
->is_array() && (var
->type
->length
== 0)) {
1039 const glsl_type
*type
=
1040 glsl_type::get_array_instance(var
->type
->fields
.array
,
1041 var
->max_array_access
+ 1);
1042 assert(type
!= NULL
);
1045 return visit_continue
;
1050 * Performs the cross-validation of geometry shader max_vertices and
1051 * primitive type layout qualifiers for the attached geometry shaders,
1052 * and propagates them to the linked GS and linked shader program.
1055 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1056 struct gl_shader
*linked_shader
,
1057 struct gl_shader
**shader_list
,
1058 unsigned num_shaders
)
1060 linked_shader
->Geom
.VerticesOut
= 0;
1061 linked_shader
->Geom
.InputType
= PRIM_UNKNOWN
;
1062 linked_shader
->Geom
.OutputType
= PRIM_UNKNOWN
;
1064 /* No in/out qualifiers defined for anything but GLSL 1.50+
1065 * geometry shaders so far.
1067 if (linked_shader
->Type
!= GL_GEOMETRY_SHADER
|| prog
->Version
< 150)
1070 /* From the GLSL 1.50 spec, page 46:
1072 * "All geometry shader output layout declarations in a program
1073 * must declare the same layout and same value for
1074 * max_vertices. There must be at least one geometry output
1075 * layout declaration somewhere in a program, but not all
1076 * geometry shaders (compilation units) are required to
1080 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1081 struct gl_shader
*shader
= shader_list
[i
];
1083 if (shader
->Geom
.InputType
!= PRIM_UNKNOWN
) {
1084 if (linked_shader
->Geom
.InputType
!= PRIM_UNKNOWN
&&
1085 linked_shader
->Geom
.InputType
!= shader
->Geom
.InputType
) {
1086 linker_error(prog
, "geometry shader defined with conflicting "
1090 linked_shader
->Geom
.InputType
= shader
->Geom
.InputType
;
1093 if (shader
->Geom
.OutputType
!= PRIM_UNKNOWN
) {
1094 if (linked_shader
->Geom
.OutputType
!= PRIM_UNKNOWN
&&
1095 linked_shader
->Geom
.OutputType
!= shader
->Geom
.OutputType
) {
1096 linker_error(prog
, "geometry shader defined with conflicting "
1100 linked_shader
->Geom
.OutputType
= shader
->Geom
.OutputType
;
1103 if (shader
->Geom
.VerticesOut
!= 0) {
1104 if (linked_shader
->Geom
.VerticesOut
!= 0 &&
1105 linked_shader
->Geom
.VerticesOut
!= shader
->Geom
.VerticesOut
) {
1106 linker_error(prog
, "geometry shader defined with conflicting "
1107 "output vertex count (%d and %d)\n",
1108 linked_shader
->Geom
.VerticesOut
,
1109 shader
->Geom
.VerticesOut
);
1112 linked_shader
->Geom
.VerticesOut
= shader
->Geom
.VerticesOut
;
1116 /* Just do the intrastage -> interstage propagation right now,
1117 * since we already know we're in the right type of shader program
1120 if (linked_shader
->Geom
.InputType
== PRIM_UNKNOWN
) {
1122 "geometry shader didn't declare primitive input type\n");
1125 prog
->Geom
.InputType
= linked_shader
->Geom
.InputType
;
1127 if (linked_shader
->Geom
.OutputType
== PRIM_UNKNOWN
) {
1129 "geometry shader didn't declare primitive output type\n");
1132 prog
->Geom
.OutputType
= linked_shader
->Geom
.OutputType
;
1134 if (linked_shader
->Geom
.VerticesOut
== 0) {
1136 "geometry shader didn't declare max_vertices\n");
1139 prog
->Geom
.VerticesOut
= linked_shader
->Geom
.VerticesOut
;
1143 * Combine a group of shaders for a single stage to generate a linked shader
1146 * If this function is supplied a single shader, it is cloned, and the new
1147 * shader is returned.
1149 static struct gl_shader
*
1150 link_intrastage_shaders(void *mem_ctx
,
1151 struct gl_context
*ctx
,
1152 struct gl_shader_program
*prog
,
1153 struct gl_shader
**shader_list
,
1154 unsigned num_shaders
)
1156 struct gl_uniform_block
*uniform_blocks
= NULL
;
1158 /* Check that global variables defined in multiple shaders are consistent.
1160 cross_validate_globals(prog
, shader_list
, num_shaders
, false);
1161 if (!prog
->LinkStatus
)
1164 /* Check that interface blocks defined in multiple shaders are consistent.
1166 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
1168 if (!prog
->LinkStatus
)
1171 /* Link up uniform blocks defined within this stage. */
1172 const unsigned num_uniform_blocks
=
1173 link_uniform_blocks(mem_ctx
, prog
, shader_list
, num_shaders
,
1176 /* Check that there is only a single definition of each function signature
1177 * across all shaders.
1179 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
1180 foreach_list(node
, shader_list
[i
]->ir
) {
1181 ir_function
*const f
= ((ir_instruction
*) node
)->as_function();
1186 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
1187 ir_function
*const other
=
1188 shader_list
[j
]->symbols
->get_function(f
->name
);
1190 /* If the other shader has no function (and therefore no function
1191 * signatures) with the same name, skip to the next shader.
1196 foreach_iter (exec_list_iterator
, iter
, *f
) {
1197 ir_function_signature
*sig
=
1198 (ir_function_signature
*) iter
.get();
1200 if (!sig
->is_defined
|| sig
->is_builtin())
1203 ir_function_signature
*other_sig
=
1204 other
->exact_matching_signature(NULL
, &sig
->parameters
);
1206 if ((other_sig
!= NULL
) && other_sig
->is_defined
1207 && !other_sig
->is_builtin()) {
1208 linker_error(prog
, "function `%s' is multiply defined",
1217 /* Find the shader that defines main, and make a clone of it.
1219 * Starting with the clone, search for undefined references. If one is
1220 * found, find the shader that defines it. Clone the reference and add
1221 * it to the shader. Repeat until there are no undefined references or
1222 * until a reference cannot be resolved.
1224 gl_shader
*main
= NULL
;
1225 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1226 if (get_main_function_signature(shader_list
[i
]) != NULL
) {
1227 main
= shader_list
[i
];
1233 linker_error(prog
, "%s shader lacks `main'\n",
1234 _mesa_glsl_shader_target_name(shader_list
[0]->Type
));
1238 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
1239 linked
->ir
= new(linked
) exec_list
;
1240 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
1242 linked
->UniformBlocks
= uniform_blocks
;
1243 linked
->NumUniformBlocks
= num_uniform_blocks
;
1244 ralloc_steal(linked
, linked
->UniformBlocks
);
1246 link_gs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
1248 populate_symbol_table(linked
);
1250 /* The a pointer to the main function in the final linked shader (i.e., the
1251 * copy of the original shader that contained the main function).
1253 ir_function_signature
*const main_sig
= get_main_function_signature(linked
);
1255 /* Move any instructions other than variable declarations or function
1256 * declarations into main.
1258 exec_node
*insertion_point
=
1259 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
1262 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1263 if (shader_list
[i
] == main
)
1266 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
1267 insertion_point
, true, linked
);
1270 /* Resolve initializers for global variables in the linked shader.
1272 unsigned num_linking_shaders
= num_shaders
;
1273 for (unsigned i
= 0; i
< num_shaders
; i
++)
1274 num_linking_shaders
+= shader_list
[i
]->num_builtins_to_link
;
1276 gl_shader
**linking_shaders
=
1277 (gl_shader
**) calloc(num_linking_shaders
, sizeof(gl_shader
*));
1279 memcpy(linking_shaders
, shader_list
,
1280 sizeof(linking_shaders
[0]) * num_shaders
);
1282 unsigned idx
= num_shaders
;
1283 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1284 memcpy(&linking_shaders
[idx
], shader_list
[i
]->builtins_to_link
,
1285 sizeof(linking_shaders
[0]) * shader_list
[i
]->num_builtins_to_link
);
1286 idx
+= shader_list
[i
]->num_builtins_to_link
;
1289 assert(idx
== num_linking_shaders
);
1291 if (!link_function_calls(prog
, linked
, linking_shaders
,
1292 num_linking_shaders
)) {
1293 ctx
->Driver
.DeleteShader(ctx
, linked
);
1294 free(linking_shaders
);
1298 free(linking_shaders
);
1300 /* At this point linked should contain all of the linked IR, so
1301 * validate it to make sure nothing went wrong.
1303 validate_ir_tree(linked
->ir
);
1305 /* Set the size of geometry shader input arrays */
1306 if (linked
->Type
== GL_GEOMETRY_SHADER
) {
1307 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
1308 geom_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
1309 foreach_iter(exec_list_iterator
, iter
, *linked
->ir
) {
1310 ir_instruction
*ir
= (ir_instruction
*)iter
.get();
1311 ir
->accept(&input_resize_visitor
);
1315 /* Make a pass over all variable declarations to ensure that arrays with
1316 * unspecified sizes have a size specified. The size is inferred from the
1317 * max_array_access field.
1319 array_sizing_visitor v
;
1326 * Update the sizes of linked shader uniform arrays to the maximum
1329 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1331 * If one or more elements of an array are active,
1332 * GetActiveUniform will return the name of the array in name,
1333 * subject to the restrictions listed above. The type of the array
1334 * is returned in type. The size parameter contains the highest
1335 * array element index used, plus one. The compiler or linker
1336 * determines the highest index used. There will be only one
1337 * active uniform reported by the GL per uniform array.
1341 update_array_sizes(struct gl_shader_program
*prog
)
1343 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1344 if (prog
->_LinkedShaders
[i
] == NULL
)
1347 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
1348 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1350 if ((var
== NULL
) || (var
->mode
!= ir_var_uniform
) ||
1351 !var
->type
->is_array())
1354 /* GL_ARB_uniform_buffer_object says that std140 uniforms
1355 * will not be eliminated. Since we always do std140, just
1356 * don't resize arrays in UBOs.
1358 if (var
->is_in_uniform_block())
1361 unsigned int size
= var
->max_array_access
;
1362 for (unsigned j
= 0; j
< MESA_SHADER_TYPES
; j
++) {
1363 if (prog
->_LinkedShaders
[j
] == NULL
)
1366 foreach_list(node2
, prog
->_LinkedShaders
[j
]->ir
) {
1367 ir_variable
*other_var
= ((ir_instruction
*) node2
)->as_variable();
1371 if (strcmp(var
->name
, other_var
->name
) == 0 &&
1372 other_var
->max_array_access
> size
) {
1373 size
= other_var
->max_array_access
;
1378 if (size
+ 1 != var
->type
->length
) {
1379 /* If this is a built-in uniform (i.e., it's backed by some
1380 * fixed-function state), adjust the number of state slots to
1381 * match the new array size. The number of slots per array entry
1382 * is not known. It seems safe to assume that the total number of
1383 * slots is an integer multiple of the number of array elements.
1384 * Determine the number of slots per array element by dividing by
1385 * the old (total) size.
1387 if (var
->num_state_slots
> 0) {
1388 var
->num_state_slots
= (size
+ 1)
1389 * (var
->num_state_slots
/ var
->type
->length
);
1392 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
1394 /* FINISHME: We should update the types of array
1395 * dereferences of this variable now.
1403 * Find a contiguous set of available bits in a bitmask.
1405 * \param used_mask Bits representing used (1) and unused (0) locations
1406 * \param needed_count Number of contiguous bits needed.
1409 * Base location of the available bits on success or -1 on failure.
1412 find_available_slots(unsigned used_mask
, unsigned needed_count
)
1414 unsigned needed_mask
= (1 << needed_count
) - 1;
1415 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
1417 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1418 * cannot optimize possibly infinite loops" for the loop below.
1420 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
1423 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
1424 if ((needed_mask
& ~used_mask
) == needed_mask
)
1435 * Assign locations for either VS inputs for FS outputs
1437 * \param prog Shader program whose variables need locations assigned
1438 * \param target_index Selector for the program target to receive location
1439 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1440 * \c MESA_SHADER_FRAGMENT.
1441 * \param max_index Maximum number of generic locations. This corresponds
1442 * to either the maximum number of draw buffers or the
1443 * maximum number of generic attributes.
1446 * If locations are successfully assigned, true is returned. Otherwise an
1447 * error is emitted to the shader link log and false is returned.
1450 assign_attribute_or_color_locations(gl_shader_program
*prog
,
1451 unsigned target_index
,
1454 /* Mark invalid locations as being used.
1456 unsigned used_locations
= (max_index
>= 32)
1457 ? ~0 : ~((1 << max_index
) - 1);
1459 assert((target_index
== MESA_SHADER_VERTEX
)
1460 || (target_index
== MESA_SHADER_FRAGMENT
));
1462 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
1466 /* Operate in a total of four passes.
1468 * 1. Invalidate the location assignments for all vertex shader inputs.
1470 * 2. Assign locations for inputs that have user-defined (via
1471 * glBindVertexAttribLocation) locations and outputs that have
1472 * user-defined locations (via glBindFragDataLocation).
1474 * 3. Sort the attributes without assigned locations by number of slots
1475 * required in decreasing order. Fragmentation caused by attribute
1476 * locations assigned by the application may prevent large attributes
1477 * from having enough contiguous space.
1479 * 4. Assign locations to any inputs without assigned locations.
1482 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
1483 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
1485 const enum ir_variable_mode direction
=
1486 (target_index
== MESA_SHADER_VERTEX
)
1487 ? ir_var_shader_in
: ir_var_shader_out
;
1490 /* Temporary storage for the set of attributes that need locations assigned.
1496 /* Used below in the call to qsort. */
1497 static int compare(const void *a
, const void *b
)
1499 const temp_attr
*const l
= (const temp_attr
*) a
;
1500 const temp_attr
*const r
= (const temp_attr
*) b
;
1502 /* Reversed because we want a descending order sort below. */
1503 return r
->slots
- l
->slots
;
1507 unsigned num_attr
= 0;
1509 foreach_list(node
, sh
->ir
) {
1510 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1512 if ((var
== NULL
) || (var
->mode
!= (unsigned) direction
))
1515 if (var
->explicit_location
) {
1516 if ((var
->location
>= (int)(max_index
+ generic_base
))
1517 || (var
->location
< 0)) {
1519 "invalid explicit location %d specified for `%s'\n",
1521 ? var
->location
: var
->location
- generic_base
,
1525 } else if (target_index
== MESA_SHADER_VERTEX
) {
1528 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
1529 assert(binding
>= VERT_ATTRIB_GENERIC0
);
1530 var
->location
= binding
;
1531 var
->is_unmatched_generic_inout
= 0;
1533 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
1537 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
1538 assert(binding
>= FRAG_RESULT_DATA0
);
1539 var
->location
= binding
;
1540 var
->is_unmatched_generic_inout
= 0;
1542 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
1548 /* If the variable is not a built-in and has a location statically
1549 * assigned in the shader (presumably via a layout qualifier), make sure
1550 * that it doesn't collide with other assigned locations. Otherwise,
1551 * add it to the list of variables that need linker-assigned locations.
1553 const unsigned slots
= var
->type
->count_attribute_slots();
1554 if (var
->location
!= -1) {
1555 if (var
->location
>= generic_base
&& var
->index
< 1) {
1556 /* From page 61 of the OpenGL 4.0 spec:
1558 * "LinkProgram will fail if the attribute bindings assigned
1559 * by BindAttribLocation do not leave not enough space to
1560 * assign a location for an active matrix attribute or an
1561 * active attribute array, both of which require multiple
1562 * contiguous generic attributes."
1564 * Previous versions of the spec contain similar language but omit
1565 * the bit about attribute arrays.
1567 * Page 61 of the OpenGL 4.0 spec also says:
1569 * "It is possible for an application to bind more than one
1570 * attribute name to the same location. This is referred to as
1571 * aliasing. This will only work if only one of the aliased
1572 * attributes is active in the executable program, or if no
1573 * path through the shader consumes more than one attribute of
1574 * a set of attributes aliased to the same location. A link
1575 * error can occur if the linker determines that every path
1576 * through the shader consumes multiple aliased attributes,
1577 * but implementations are not required to generate an error
1580 * These two paragraphs are either somewhat contradictory, or I
1581 * don't fully understand one or both of them.
1583 /* FINISHME: The code as currently written does not support
1584 * FINISHME: attribute location aliasing (see comment above).
1586 /* Mask representing the contiguous slots that will be used by
1589 const unsigned attr
= var
->location
- generic_base
;
1590 const unsigned use_mask
= (1 << slots
) - 1;
1592 /* Generate a link error if the set of bits requested for this
1593 * attribute overlaps any previously allocated bits.
1595 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
1596 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
1597 ? "vertex shader input" : "fragment shader output";
1599 "insufficient contiguous locations "
1600 "available for %s `%s' %d %d %d", string
,
1601 var
->name
, used_locations
, use_mask
, attr
);
1605 used_locations
|= (use_mask
<< attr
);
1611 to_assign
[num_attr
].slots
= slots
;
1612 to_assign
[num_attr
].var
= var
;
1616 /* If all of the attributes were assigned locations by the application (or
1617 * are built-in attributes with fixed locations), return early. This should
1618 * be the common case.
1623 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
1625 if (target_index
== MESA_SHADER_VERTEX
) {
1626 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1627 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1628 * reserved to prevent it from being automatically allocated below.
1630 find_deref_visitor
find("gl_Vertex");
1632 if (find
.variable_found())
1633 used_locations
|= (1 << 0);
1636 for (unsigned i
= 0; i
< num_attr
; i
++) {
1637 /* Mask representing the contiguous slots that will be used by this
1640 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
1642 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
1645 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
1646 ? "vertex shader input" : "fragment shader output";
1649 "insufficient contiguous locations "
1650 "available for %s `%s'",
1651 string
, to_assign
[i
].var
->name
);
1655 to_assign
[i
].var
->location
= generic_base
+ location
;
1656 to_assign
[i
].var
->is_unmatched_generic_inout
= 0;
1657 used_locations
|= (use_mask
<< location
);
1665 * Demote shader inputs and outputs that are not used in other stages
1668 demote_shader_inputs_and_outputs(gl_shader
*sh
, enum ir_variable_mode mode
)
1670 foreach_list(node
, sh
->ir
) {
1671 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1673 if ((var
== NULL
) || (var
->mode
!= int(mode
)))
1676 /* A shader 'in' or 'out' variable is only really an input or output if
1677 * its value is used by other shader stages. This will cause the variable
1678 * to have a location assigned.
1680 if (var
->is_unmatched_generic_inout
) {
1681 var
->mode
= ir_var_auto
;
1688 * Store the gl_FragDepth layout in the gl_shader_program struct.
1691 store_fragdepth_layout(struct gl_shader_program
*prog
)
1693 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
1697 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
1699 /* We don't look up the gl_FragDepth symbol directly because if
1700 * gl_FragDepth is not used in the shader, it's removed from the IR.
1701 * However, the symbol won't be removed from the symbol table.
1703 * We're only interested in the cases where the variable is NOT removed
1706 foreach_list(node
, ir
) {
1707 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1709 if (var
== NULL
|| var
->mode
!= ir_var_shader_out
) {
1713 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1714 switch (var
->depth_layout
) {
1715 case ir_depth_layout_none
:
1716 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
1718 case ir_depth_layout_any
:
1719 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
1721 case ir_depth_layout_greater
:
1722 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
1724 case ir_depth_layout_less
:
1725 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
1727 case ir_depth_layout_unchanged
:
1728 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
1739 * Validate the resources used by a program versus the implementation limits
1742 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
1744 static const char *const shader_names
[MESA_SHADER_TYPES
] = {
1745 "vertex", "geometry", "fragment"
1748 const unsigned max_samplers
[MESA_SHADER_TYPES
] = {
1749 ctx
->Const
.VertexProgram
.MaxTextureImageUnits
,
1750 ctx
->Const
.GeometryProgram
.MaxTextureImageUnits
,
1751 ctx
->Const
.FragmentProgram
.MaxTextureImageUnits
1754 const unsigned max_default_uniform_components
[MESA_SHADER_TYPES
] = {
1755 ctx
->Const
.VertexProgram
.MaxUniformComponents
,
1756 ctx
->Const
.GeometryProgram
.MaxUniformComponents
,
1757 ctx
->Const
.FragmentProgram
.MaxUniformComponents
1760 const unsigned max_combined_uniform_components
[MESA_SHADER_TYPES
] = {
1761 ctx
->Const
.VertexProgram
.MaxCombinedUniformComponents
,
1762 ctx
->Const
.GeometryProgram
.MaxCombinedUniformComponents
,
1763 ctx
->Const
.FragmentProgram
.MaxCombinedUniformComponents
1766 const unsigned max_uniform_blocks
[MESA_SHADER_TYPES
] = {
1767 ctx
->Const
.VertexProgram
.MaxUniformBlocks
,
1768 ctx
->Const
.GeometryProgram
.MaxUniformBlocks
,
1769 ctx
->Const
.FragmentProgram
.MaxUniformBlocks
1772 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1773 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1778 if (sh
->num_samplers
> max_samplers
[i
]) {
1779 linker_error(prog
, "Too many %s shader texture samplers",
1783 if (sh
->num_uniform_components
> max_default_uniform_components
[i
]) {
1784 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
1785 linker_warning(prog
, "Too many %s shader default uniform block "
1786 "components, but the driver will try to optimize "
1787 "them out; this is non-portable out-of-spec "
1791 linker_error(prog
, "Too many %s shader default uniform block "
1797 if (sh
->num_combined_uniform_components
>
1798 max_combined_uniform_components
[i
]) {
1799 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
1800 linker_warning(prog
, "Too many %s shader uniform components, "
1801 "but the driver will try to optimize them out; "
1802 "this is non-portable out-of-spec behavior\n",
1805 linker_error(prog
, "Too many %s shader uniform components",
1811 unsigned blocks
[MESA_SHADER_TYPES
] = {0};
1812 unsigned total_uniform_blocks
= 0;
1814 for (unsigned i
= 0; i
< prog
->NumUniformBlocks
; i
++) {
1815 for (unsigned j
= 0; j
< MESA_SHADER_TYPES
; j
++) {
1816 if (prog
->UniformBlockStageIndex
[j
][i
] != -1) {
1818 total_uniform_blocks
++;
1822 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
1823 linker_error(prog
, "Too many combined uniform blocks (%d/%d)",
1824 prog
->NumUniformBlocks
,
1825 ctx
->Const
.MaxCombinedUniformBlocks
);
1827 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1828 if (blocks
[i
] > max_uniform_blocks
[i
]) {
1829 linker_error(prog
, "Too many %s uniform blocks (%d/%d)",
1832 max_uniform_blocks
[i
]);
1841 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
1843 tfeedback_decl
*tfeedback_decls
= NULL
;
1844 unsigned num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
1846 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
1848 prog
->LinkStatus
= true; /* All error paths will set this to false */
1849 prog
->Validated
= false;
1850 prog
->_Used
= false;
1852 ralloc_free(prog
->InfoLog
);
1853 prog
->InfoLog
= ralloc_strdup(NULL
, "");
1855 ralloc_free(prog
->UniformBlocks
);
1856 prog
->UniformBlocks
= NULL
;
1857 prog
->NumUniformBlocks
= 0;
1858 for (int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1859 ralloc_free(prog
->UniformBlockStageIndex
[i
]);
1860 prog
->UniformBlockStageIndex
[i
] = NULL
;
1863 /* Separate the shaders into groups based on their type.
1865 struct gl_shader
**vert_shader_list
;
1866 unsigned num_vert_shaders
= 0;
1867 struct gl_shader
**frag_shader_list
;
1868 unsigned num_frag_shaders
= 0;
1869 struct gl_shader
**geom_shader_list
;
1870 unsigned num_geom_shaders
= 0;
1872 vert_shader_list
= (struct gl_shader
**)
1873 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
1874 frag_shader_list
= (struct gl_shader
**)
1875 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
1876 geom_shader_list
= (struct gl_shader
**)
1877 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
1879 unsigned min_version
= UINT_MAX
;
1880 unsigned max_version
= 0;
1881 const bool is_es_prog
=
1882 (prog
->NumShaders
> 0 && prog
->Shaders
[0]->IsES
) ? true : false;
1883 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
1884 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
1885 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
1887 if (prog
->Shaders
[i
]->IsES
!= is_es_prog
) {
1888 linker_error(prog
, "all shaders must use same shading "
1889 "language version\n");
1893 switch (prog
->Shaders
[i
]->Type
) {
1894 case GL_VERTEX_SHADER
:
1895 vert_shader_list
[num_vert_shaders
] = prog
->Shaders
[i
];
1898 case GL_FRAGMENT_SHADER
:
1899 frag_shader_list
[num_frag_shaders
] = prog
->Shaders
[i
];
1902 case GL_GEOMETRY_SHADER
:
1903 geom_shader_list
[num_geom_shaders
] = prog
->Shaders
[i
];
1909 /* Previous to GLSL version 1.30, different compilation units could mix and
1910 * match shading language versions. With GLSL 1.30 and later, the versions
1911 * of all shaders must match.
1913 * GLSL ES has never allowed mixing of shading language versions.
1915 if ((is_es_prog
|| max_version
>= 130)
1916 && min_version
!= max_version
) {
1917 linker_error(prog
, "all shaders must use same shading "
1918 "language version\n");
1922 prog
->Version
= max_version
;
1923 prog
->IsES
= is_es_prog
;
1925 /* Geometry shaders have to be linked with vertex shaders.
1927 if (num_geom_shaders
> 0 && num_vert_shaders
== 0) {
1928 linker_error(prog
, "Geometry shader must be linked with "
1933 for (unsigned int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1934 if (prog
->_LinkedShaders
[i
] != NULL
)
1935 ctx
->Driver
.DeleteShader(ctx
, prog
->_LinkedShaders
[i
]);
1937 prog
->_LinkedShaders
[i
] = NULL
;
1940 /* Link all shaders for a particular stage and validate the result.
1942 if (num_vert_shaders
> 0) {
1943 gl_shader
*const sh
=
1944 link_intrastage_shaders(mem_ctx
, ctx
, prog
, vert_shader_list
,
1947 if (!prog
->LinkStatus
)
1950 validate_vertex_shader_executable(prog
, sh
);
1951 if (!prog
->LinkStatus
)
1954 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
1958 if (num_frag_shaders
> 0) {
1959 gl_shader
*const sh
=
1960 link_intrastage_shaders(mem_ctx
, ctx
, prog
, frag_shader_list
,
1963 if (!prog
->LinkStatus
)
1966 validate_fragment_shader_executable(prog
, sh
);
1967 if (!prog
->LinkStatus
)
1970 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
],
1974 if (num_geom_shaders
> 0) {
1975 gl_shader
*const sh
=
1976 link_intrastage_shaders(mem_ctx
, ctx
, prog
, geom_shader_list
,
1979 if (!prog
->LinkStatus
)
1982 validate_geometry_shader_executable(prog
, sh
);
1983 if (!prog
->LinkStatus
)
1986 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
],
1990 /* Here begins the inter-stage linking phase. Some initial validation is
1991 * performed, then locations are assigned for uniforms, attributes, and
1994 cross_validate_uniforms(prog
);
1995 if (!prog
->LinkStatus
)
2000 for (prev
= 0; prev
< MESA_SHADER_TYPES
; prev
++) {
2001 if (prog
->_LinkedShaders
[prev
] != NULL
)
2005 /* Validate the inputs of each stage with the output of the preceding
2008 for (unsigned i
= prev
+ 1; i
< MESA_SHADER_TYPES
; i
++) {
2009 if (prog
->_LinkedShaders
[i
] == NULL
)
2012 validate_interstage_interface_blocks(prog
, prog
->_LinkedShaders
[prev
],
2013 prog
->_LinkedShaders
[i
]);
2014 if (!prog
->LinkStatus
)
2017 cross_validate_outputs_to_inputs(prog
,
2018 prog
->_LinkedShaders
[prev
],
2019 prog
->_LinkedShaders
[i
]);
2020 if (!prog
->LinkStatus
)
2027 for (unsigned int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2028 if (prog
->_LinkedShaders
[i
] != NULL
)
2029 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
2032 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
2033 * it before optimization because we want most of the checks to get
2034 * dropped thanks to constant propagation.
2036 * This rule also applies to GLSL ES 3.00.
2038 if (max_version
>= (is_es_prog
? 300 : 130)) {
2039 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
2041 lower_discard_flow(sh
->ir
);
2045 if (!interstage_cross_validate_uniform_blocks(prog
))
2048 /* Do common optimization before assigning storage for attributes,
2049 * uniforms, and varyings. Later optimization could possibly make
2050 * some of that unused.
2052 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2053 if (prog
->_LinkedShaders
[i
] == NULL
)
2056 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
2057 if (!prog
->LinkStatus
)
2060 if (ctx
->ShaderCompilerOptions
[i
].LowerClipDistance
) {
2061 lower_clip_distance(prog
->_LinkedShaders
[i
]);
2064 unsigned max_unroll
= ctx
->ShaderCompilerOptions
[i
].MaxUnrollIterations
;
2066 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false, max_unroll
, &ctx
->ShaderCompilerOptions
[i
]))
2070 /* Mark all generic shader inputs and outputs as unpaired. */
2071 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] != NULL
) {
2072 link_invalidate_variable_locations(
2073 prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
2074 VERT_ATTRIB_GENERIC0
, VARYING_SLOT_VAR0
);
2076 if (prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
] != NULL
) {
2077 link_invalidate_variable_locations(
2078 prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
],
2079 VARYING_SLOT_VAR0
, VARYING_SLOT_VAR0
);
2081 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] != NULL
) {
2082 link_invalidate_variable_locations(
2083 prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
],
2084 VARYING_SLOT_VAR0
, FRAG_RESULT_DATA0
);
2087 /* FINISHME: The value of the max_attribute_index parameter is
2088 * FINISHME: implementation dependent based on the value of
2089 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
2090 * FINISHME: at least 16, so hardcode 16 for now.
2092 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_VERTEX
, 16)) {
2096 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_FRAGMENT
, MAX2(ctx
->Const
.MaxDrawBuffers
, ctx
->Const
.MaxDualSourceDrawBuffers
))) {
2101 for (first
= 0; first
< MESA_SHADER_TYPES
; first
++) {
2102 if (prog
->_LinkedShaders
[first
] != NULL
)
2106 if (num_tfeedback_decls
!= 0) {
2107 /* From GL_EXT_transform_feedback:
2108 * A program will fail to link if:
2110 * * the <count> specified by TransformFeedbackVaryingsEXT is
2111 * non-zero, but the program object has no vertex or geometry
2114 if (first
== MESA_SHADER_FRAGMENT
) {
2115 linker_error(prog
, "Transform feedback varyings specified, but "
2116 "no vertex or geometry shader is present.");
2120 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
2121 prog
->TransformFeedback
.NumVarying
);
2122 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
2123 prog
->TransformFeedback
.VaryingNames
,
2128 /* Linking the stages in the opposite order (from fragment to vertex)
2129 * ensures that inter-shader outputs written to in an earlier stage are
2130 * eliminated if they are (transitively) not used in a later stage.
2133 for (last
= MESA_SHADER_TYPES
-1; last
>= 0; last
--) {
2134 if (prog
->_LinkedShaders
[last
] != NULL
)
2138 if (last
>= 0 && last
< MESA_SHADER_FRAGMENT
) {
2139 gl_shader
*const sh
= prog
->_LinkedShaders
[last
];
2141 if (num_tfeedback_decls
!= 0) {
2142 /* There was no fragment shader, but we still have to assign varying
2143 * locations for use by transform feedback.
2145 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
2147 num_tfeedback_decls
, tfeedback_decls
,
2152 do_dead_builtin_varyings(ctx
, sh
, NULL
,
2153 num_tfeedback_decls
, tfeedback_decls
);
2155 demote_shader_inputs_and_outputs(sh
, ir_var_shader_out
);
2157 /* Eliminate code that is now dead due to unused outputs being demoted.
2159 while (do_dead_code(sh
->ir
, false))
2162 else if (first
== MESA_SHADER_FRAGMENT
) {
2163 /* If the program only contains a fragment shader...
2165 gl_shader
*const sh
= prog
->_LinkedShaders
[first
];
2167 do_dead_builtin_varyings(ctx
, NULL
, sh
,
2168 num_tfeedback_decls
, tfeedback_decls
);
2170 demote_shader_inputs_and_outputs(sh
, ir_var_shader_in
);
2172 while (do_dead_code(sh
->ir
, false))
2177 for (int i
= next
- 1; i
>= 0; i
--) {
2178 if (prog
->_LinkedShaders
[i
] == NULL
)
2181 gl_shader
*const sh_i
= prog
->_LinkedShaders
[i
];
2182 gl_shader
*const sh_next
= prog
->_LinkedShaders
[next
];
2183 unsigned gs_input_vertices
=
2184 next
== MESA_SHADER_GEOMETRY
? prog
->Geom
.VerticesIn
: 0;
2186 if (!assign_varying_locations(ctx
, mem_ctx
, prog
, sh_i
, sh_next
,
2187 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
2188 tfeedback_decls
, gs_input_vertices
))
2191 do_dead_builtin_varyings(ctx
, sh_i
, sh_next
,
2192 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
2195 demote_shader_inputs_and_outputs(sh_i
, ir_var_shader_out
);
2196 demote_shader_inputs_and_outputs(sh_next
, ir_var_shader_in
);
2198 /* Eliminate code that is now dead due to unused outputs being demoted.
2200 while (do_dead_code(sh_i
->ir
, false))
2202 while (do_dead_code(sh_next
->ir
, false))
2205 /* This must be done after all dead varyings are eliminated. */
2206 if (!check_against_varying_limit(ctx
, prog
, sh_next
))
2212 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
))
2215 update_array_sizes(prog
);
2216 link_assign_uniform_locations(prog
);
2217 store_fragdepth_layout(prog
);
2219 check_resources(ctx
, prog
);
2220 if (!prog
->LinkStatus
)
2223 /* OpenGL ES requires that a vertex shader and a fragment shader both be
2224 * present in a linked program. By checking prog->IsES, we also
2225 * catch the GL_ARB_ES2_compatibility case.
2227 if (!prog
->InternalSeparateShader
&&
2228 (ctx
->API
== API_OPENGLES2
|| prog
->IsES
)) {
2229 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
2230 linker_error(prog
, "program lacks a vertex shader\n");
2231 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
2232 linker_error(prog
, "program lacks a fragment shader\n");
2236 /* FINISHME: Assign fragment shader output locations. */
2239 free(vert_shader_list
);
2240 free(frag_shader_list
);
2241 free(geom_shader_list
);
2243 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2244 if (prog
->_LinkedShaders
[i
] == NULL
)
2247 /* Retain any live IR, but trash the rest. */
2248 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
2250 /* The symbol table in the linked shaders may contain references to
2251 * variables that were removed (e.g., unused uniforms). Since it may
2252 * contain junk, there is no possible valid use. Delete it and set the
2255 delete prog
->_LinkedShaders
[i
]->symbols
;
2256 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
2259 ralloc_free(mem_ctx
);