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"
78 #include "main/shaderobj.h"
82 * Visitor that determines whether or not a variable is ever written.
84 class find_assignment_visitor
: public ir_hierarchical_visitor
{
86 find_assignment_visitor(const char *name
)
87 : name(name
), found(false)
92 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
94 ir_variable
*const var
= ir
->lhs
->variable_referenced();
96 if (strcmp(name
, var
->name
) == 0) {
101 return visit_continue_with_parent
;
104 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
106 exec_list_iterator sig_iter
= ir
->callee
->parameters
.iterator();
107 foreach_iter(exec_list_iterator
, iter
, *ir
) {
108 ir_rvalue
*param_rval
= (ir_rvalue
*)iter
.get();
109 ir_variable
*sig_param
= (ir_variable
*)sig_iter
.get();
111 if (sig_param
->mode
== ir_var_function_out
||
112 sig_param
->mode
== ir_var_function_inout
) {
113 ir_variable
*var
= param_rval
->variable_referenced();
114 if (var
&& strcmp(name
, var
->name
) == 0) {
122 if (ir
->return_deref
!= NULL
) {
123 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
125 if (strcmp(name
, var
->name
) == 0) {
131 return visit_continue_with_parent
;
134 bool variable_found()
140 const char *name
; /**< Find writes to a variable with this name. */
141 bool found
; /**< Was a write to the variable found? */
146 * Visitor that determines whether or not a variable is ever read.
148 class find_deref_visitor
: public ir_hierarchical_visitor
{
150 find_deref_visitor(const char *name
)
151 : name(name
), found(false)
156 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
158 if (strcmp(this->name
, ir
->var
->name
) == 0) {
163 return visit_continue
;
166 bool variable_found() const
172 const char *name
; /**< Find writes to a variable with this name. */
173 bool found
; /**< Was a write to the variable found? */
178 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
182 ralloc_strcat(&prog
->InfoLog
, "error: ");
184 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
187 prog
->LinkStatus
= false;
192 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
196 ralloc_strcat(&prog
->InfoLog
, "error: ");
198 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
205 * Given a string identifying a program resource, break it into a base name
206 * and an optional array index in square brackets.
208 * If an array index is present, \c out_base_name_end is set to point to the
209 * "[" that precedes the array index, and the array index itself is returned
212 * If no array index is present (or if the array index is negative or
213 * mal-formed), \c out_base_name_end, is set to point to the null terminator
214 * at the end of the input string, and -1 is returned.
216 * Only the final array index is parsed; if the string contains other array
217 * indices (or structure field accesses), they are left in the base name.
219 * No attempt is made to check that the base name is properly formed;
220 * typically the caller will look up the base name in a hash table, so
221 * ill-formed base names simply turn into hash table lookup failures.
224 parse_program_resource_name(const GLchar
*name
,
225 const GLchar
**out_base_name_end
)
227 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
229 * "When an integer array element or block instance number is part of
230 * the name string, it will be specified in decimal form without a "+"
231 * or "-" sign or any extra leading zeroes. Additionally, the name
232 * string will not include white space anywhere in the string."
235 const size_t len
= strlen(name
);
236 *out_base_name_end
= name
+ len
;
238 if (len
== 0 || name
[len
-1] != ']')
241 /* Walk backwards over the string looking for a non-digit character. This
242 * had better be the opening bracket for an array index.
244 * Initially, i specifies the location of the ']'. Since the string may
245 * contain only the ']' charcater, walk backwards very carefully.
248 for (i
= len
- 1; (i
> 0) && isdigit(name
[i
-1]); --i
)
251 if ((i
== 0) || name
[i
-1] != '[')
254 long array_index
= strtol(&name
[i
], NULL
, 10);
258 *out_base_name_end
= name
+ (i
- 1);
264 link_invalidate_variable_locations(gl_shader
*sh
, int input_base
,
267 foreach_list(node
, sh
->ir
) {
268 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
275 case ir_var_shader_in
:
278 case ir_var_shader_out
:
285 /* Only assign locations for generic attributes / varyings / etc.
287 if ((var
->location
>= base
) && !var
->explicit_location
)
290 if ((var
->location
== -1) && !var
->explicit_location
) {
291 var
->is_unmatched_generic_inout
= 1;
292 var
->location_frac
= 0;
294 var
->is_unmatched_generic_inout
= 0;
301 * Determine the number of attribute slots required for a particular type
303 * This code is here because it implements the language rules of a specific
304 * GLSL version. Since it's a property of the language and not a property of
305 * types in general, it doesn't really belong in glsl_type.
308 count_attribute_slots(const glsl_type
*t
)
310 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
312 * "A scalar input counts the same amount against this limit as a vec4,
313 * so applications may want to consider packing groups of four
314 * unrelated float inputs together into a vector to better utilize the
315 * capabilities of the underlying hardware. A matrix input will use up
316 * multiple locations. The number of locations used will equal the
317 * number of columns in the matrix."
319 * The spec does not explicitly say how arrays are counted. However, it
320 * should be safe to assume the total number of slots consumed by an array
321 * is the number of entries in the array multiplied by the number of slots
322 * consumed by a single element of the array.
326 return t
->array_size() * count_attribute_slots(t
->element_type());
329 return t
->matrix_columns
;
336 * Verify that a vertex shader executable meets all semantic requirements.
338 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
341 * \param shader Vertex shader executable to be verified
344 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
345 struct gl_shader
*shader
)
350 /* From the GLSL 1.10 spec, page 48:
352 * "The variable gl_Position is available only in the vertex
353 * language and is intended for writing the homogeneous vertex
354 * position. All executions of a well-formed vertex shader
355 * executable must write a value into this variable. [...] The
356 * variable gl_Position is available only in the vertex
357 * language and is intended for writing the homogeneous vertex
358 * position. All executions of a well-formed vertex shader
359 * executable must write a value into this variable."
361 * while in GLSL 1.40 this text is changed to:
363 * "The variable gl_Position is available only in the vertex
364 * language and is intended for writing the homogeneous vertex
365 * position. It can be written at any time during shader
366 * execution. It may also be read back by a vertex shader
367 * after being written. This value will be used by primitive
368 * assembly, clipping, culling, and other fixed functionality
369 * operations, if present, that operate on primitives after
370 * vertex processing has occurred. Its value is undefined if
371 * the vertex shader executable does not write gl_Position."
373 * GLSL ES 3.00 is similar to GLSL 1.40--failing to write to gl_Position is
376 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
377 find_assignment_visitor
find("gl_Position");
378 find
.run(shader
->ir
);
379 if (!find
.variable_found()) {
380 linker_error(prog
, "vertex shader does not write to `gl_Position'\n");
385 prog
->Vert
.ClipDistanceArraySize
= 0;
387 if (!prog
->IsES
&& prog
->Version
>= 130) {
388 /* From section 7.1 (Vertex Shader Special Variables) of the
391 * "It is an error for a shader to statically write both
392 * gl_ClipVertex and gl_ClipDistance."
394 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
395 * gl_ClipVertex nor gl_ClipDistance.
397 find_assignment_visitor
clip_vertex("gl_ClipVertex");
398 find_assignment_visitor
clip_distance("gl_ClipDistance");
400 clip_vertex
.run(shader
->ir
);
401 clip_distance
.run(shader
->ir
);
402 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
403 linker_error(prog
, "vertex shader writes to both `gl_ClipVertex' "
404 "and `gl_ClipDistance'\n");
407 prog
->Vert
.UsesClipDistance
= clip_distance
.variable_found();
408 ir_variable
*clip_distance_var
=
409 shader
->symbols
->get_variable("gl_ClipDistance");
410 if (clip_distance_var
)
411 prog
->Vert
.ClipDistanceArraySize
= clip_distance_var
->type
->length
;
419 * Verify that a fragment shader executable meets all semantic requirements
421 * \param shader Fragment shader executable to be verified
424 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
425 struct gl_shader
*shader
)
430 find_assignment_visitor
frag_color("gl_FragColor");
431 find_assignment_visitor
frag_data("gl_FragData");
433 frag_color
.run(shader
->ir
);
434 frag_data
.run(shader
->ir
);
436 if (frag_color
.variable_found() && frag_data
.variable_found()) {
437 linker_error(prog
, "fragment shader writes to both "
438 "`gl_FragColor' and `gl_FragData'\n");
447 * Generate a string describing the mode of a variable
450 mode_string(const ir_variable
*var
)
454 return (var
->read_only
) ? "global constant" : "global variable";
456 case ir_var_uniform
: return "uniform";
457 case ir_var_shader_in
: return "shader input";
458 case ir_var_shader_out
: return "shader output";
460 case ir_var_const_in
:
461 case ir_var_temporary
:
463 assert(!"Should not get here.");
464 return "invalid variable";
470 * Perform validation of global variables used across multiple shaders
473 cross_validate_globals(struct gl_shader_program
*prog
,
474 struct gl_shader
**shader_list
,
475 unsigned num_shaders
,
478 /* Examine all of the uniforms in all of the shaders and cross validate
481 glsl_symbol_table variables
;
482 for (unsigned i
= 0; i
< num_shaders
; i
++) {
483 if (shader_list
[i
] == NULL
)
486 foreach_list(node
, shader_list
[i
]->ir
) {
487 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
492 if (uniforms_only
&& (var
->mode
!= ir_var_uniform
))
495 /* Don't cross validate temporaries that are at global scope. These
496 * will eventually get pulled into the shaders 'main'.
498 if (var
->mode
== ir_var_temporary
)
501 /* If a global with this name has already been seen, verify that the
502 * new instance has the same type. In addition, if the globals have
503 * initializers, the values of the initializers must be the same.
505 ir_variable
*const existing
= variables
.get_variable(var
->name
);
506 if (existing
!= NULL
) {
507 if (var
->type
!= existing
->type
) {
508 /* Consider the types to be "the same" if both types are arrays
509 * of the same type and one of the arrays is implicitly sized.
510 * In addition, set the type of the linked variable to the
511 * explicitly sized array.
513 if (var
->type
->is_array()
514 && existing
->type
->is_array()
515 && (var
->type
->fields
.array
== existing
->type
->fields
.array
)
516 && ((var
->type
->length
== 0)
517 || (existing
->type
->length
== 0))) {
518 if (var
->type
->length
!= 0) {
519 existing
->type
= var
->type
;
522 linker_error(prog
, "%s `%s' declared as type "
523 "`%s' and type `%s'\n",
525 var
->name
, var
->type
->name
,
526 existing
->type
->name
);
531 if (var
->explicit_location
) {
532 if (existing
->explicit_location
533 && (var
->location
!= existing
->location
)) {
534 linker_error(prog
, "explicit locations for %s "
535 "`%s' have differing values\n",
536 mode_string(var
), var
->name
);
540 existing
->location
= var
->location
;
541 existing
->explicit_location
= true;
544 /* Validate layout qualifiers for gl_FragDepth.
546 * From the AMD/ARB_conservative_depth specs:
548 * "If gl_FragDepth is redeclared in any fragment shader in a
549 * program, it must be redeclared in all fragment shaders in
550 * that program that have static assignments to
551 * gl_FragDepth. All redeclarations of gl_FragDepth in all
552 * fragment shaders in a single program must have the same set
555 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
556 bool layout_declared
= var
->depth_layout
!= ir_depth_layout_none
;
557 bool layout_differs
=
558 var
->depth_layout
!= existing
->depth_layout
;
560 if (layout_declared
&& layout_differs
) {
562 "All redeclarations of gl_FragDepth in all "
563 "fragment shaders in a single program must have "
564 "the same set of qualifiers.");
567 if (var
->used
&& layout_differs
) {
569 "If gl_FragDepth is redeclared with a layout "
570 "qualifier in any fragment shader, it must be "
571 "redeclared with the same layout qualifier in "
572 "all fragment shaders that have assignments to "
577 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
579 * "If a shared global has multiple initializers, the
580 * initializers must all be constant expressions, and they
581 * must all have the same value. Otherwise, a link error will
582 * result. (A shared global having only one initializer does
583 * not require that initializer to be a constant expression.)"
585 * Previous to 4.20 the GLSL spec simply said that initializers
586 * must have the same value. In this case of non-constant
587 * initializers, this was impossible to determine. As a result,
588 * no vendor actually implemented that behavior. The 4.20
589 * behavior matches the implemented behavior of at least one other
590 * vendor, so we'll implement that for all GLSL versions.
592 if (var
->constant_initializer
!= NULL
) {
593 if (existing
->constant_initializer
!= NULL
) {
594 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
595 linker_error(prog
, "initializers for %s "
596 "`%s' have differing values\n",
597 mode_string(var
), var
->name
);
601 /* If the first-seen instance of a particular uniform did not
602 * have an initializer but a later instance does, copy the
603 * initializer to the version stored in the symbol table.
605 /* FINISHME: This is wrong. The constant_value field should
606 * FINISHME: not be modified! Imagine a case where a shader
607 * FINISHME: without an initializer is linked in two different
608 * FINISHME: programs with shaders that have differing
609 * FINISHME: initializers. Linking with the first will
610 * FINISHME: modify the shader, and linking with the second
611 * FINISHME: will fail.
613 existing
->constant_initializer
=
614 var
->constant_initializer
->clone(ralloc_parent(existing
),
619 if (var
->has_initializer
) {
620 if (existing
->has_initializer
621 && (var
->constant_initializer
== NULL
622 || existing
->constant_initializer
== NULL
)) {
624 "shared global variable `%s' has multiple "
625 "non-constant initializers.\n",
630 /* Some instance had an initializer, so keep track of that. In
631 * this location, all sorts of initializers (constant or
632 * otherwise) will propagate the existence to the variable
633 * stored in the symbol table.
635 existing
->has_initializer
= true;
638 if (existing
->invariant
!= var
->invariant
) {
639 linker_error(prog
, "declarations for %s `%s' have "
640 "mismatching invariant qualifiers\n",
641 mode_string(var
), var
->name
);
644 if (existing
->centroid
!= var
->centroid
) {
645 linker_error(prog
, "declarations for %s `%s' have "
646 "mismatching centroid qualifiers\n",
647 mode_string(var
), var
->name
);
651 variables
.add_variable(var
);
660 * Perform validation of uniforms used across multiple shader stages
663 cross_validate_uniforms(struct gl_shader_program
*prog
)
665 return cross_validate_globals(prog
, prog
->_LinkedShaders
,
666 MESA_SHADER_TYPES
, true);
670 * Accumulates the array of prog->UniformBlocks and checks that all
671 * definitons of blocks agree on their contents.
674 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
)
676 unsigned max_num_uniform_blocks
= 0;
677 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
678 if (prog
->_LinkedShaders
[i
])
679 max_num_uniform_blocks
+= prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
682 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
683 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
685 prog
->UniformBlockStageIndex
[i
] = ralloc_array(prog
, int,
686 max_num_uniform_blocks
);
687 for (unsigned int j
= 0; j
< max_num_uniform_blocks
; j
++)
688 prog
->UniformBlockStageIndex
[i
][j
] = -1;
693 for (unsigned int j
= 0; j
< sh
->NumUniformBlocks
; j
++) {
694 int index
= link_cross_validate_uniform_block(prog
,
695 &prog
->UniformBlocks
,
696 &prog
->NumUniformBlocks
,
697 &sh
->UniformBlocks
[j
]);
700 linker_error(prog
, "uniform block `%s' has mismatching definitions",
701 sh
->UniformBlocks
[j
].Name
);
705 prog
->UniformBlockStageIndex
[i
][index
] = j
;
714 * Populates a shaders symbol table with all global declarations
717 populate_symbol_table(gl_shader
*sh
)
719 sh
->symbols
= new(sh
) glsl_symbol_table
;
721 foreach_list(node
, sh
->ir
) {
722 ir_instruction
*const inst
= (ir_instruction
*) node
;
726 if ((func
= inst
->as_function()) != NULL
) {
727 sh
->symbols
->add_function(func
);
728 } else if ((var
= inst
->as_variable()) != NULL
) {
729 sh
->symbols
->add_variable(var
);
736 * Remap variables referenced in an instruction tree
738 * This is used when instruction trees are cloned from one shader and placed in
739 * another. These trees will contain references to \c ir_variable nodes that
740 * do not exist in the target shader. This function finds these \c ir_variable
741 * references and replaces the references with matching variables in the target
744 * If there is no matching variable in the target shader, a clone of the
745 * \c ir_variable is made and added to the target shader. The new variable is
746 * added to \b both the instruction stream and the symbol table.
748 * \param inst IR tree that is to be processed.
749 * \param symbols Symbol table containing global scope symbols in the
751 * \param instructions Instruction stream where new variable declarations
755 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
758 class remap_visitor
: public ir_hierarchical_visitor
{
760 remap_visitor(struct gl_shader
*target
,
763 this->target
= target
;
764 this->symbols
= target
->symbols
;
765 this->instructions
= target
->ir
;
769 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
771 if (ir
->var
->mode
== ir_var_temporary
) {
772 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
776 return visit_continue
;
779 ir_variable
*const existing
=
780 this->symbols
->get_variable(ir
->var
->name
);
781 if (existing
!= NULL
)
784 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
786 this->symbols
->add_variable(copy
);
787 this->instructions
->push_head(copy
);
791 return visit_continue
;
795 struct gl_shader
*target
;
796 glsl_symbol_table
*symbols
;
797 exec_list
*instructions
;
801 remap_visitor
v(target
, temps
);
808 * Move non-declarations from one instruction stream to another
810 * The intended usage pattern of this function is to pass the pointer to the
811 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
812 * pointer) for \c last and \c false for \c make_copies on the first
813 * call. Successive calls pass the return value of the previous call for
814 * \c last and \c true for \c make_copies.
816 * \param instructions Source instruction stream
817 * \param last Instruction after which new instructions should be
818 * inserted in the target instruction stream
819 * \param make_copies Flag selecting whether instructions in \c instructions
820 * should be copied (via \c ir_instruction::clone) into the
821 * target list or moved.
824 * The new "last" instruction in the target instruction stream. This pointer
825 * is suitable for use as the \c last parameter of a later call to this
829 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
830 bool make_copies
, gl_shader
*target
)
832 hash_table
*temps
= NULL
;
835 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
836 hash_table_pointer_compare
);
838 foreach_list_safe(node
, instructions
) {
839 ir_instruction
*inst
= (ir_instruction
*) node
;
841 if (inst
->as_function())
844 ir_variable
*var
= inst
->as_variable();
845 if ((var
!= NULL
) && (var
->mode
!= ir_var_temporary
))
848 assert(inst
->as_assignment()
850 || inst
->as_if() /* for initializers with the ?: operator */
851 || ((var
!= NULL
) && (var
->mode
== ir_var_temporary
)));
854 inst
= inst
->clone(target
, NULL
);
857 hash_table_insert(temps
, inst
, var
);
859 remap_variables(inst
, target
, temps
);
864 last
->insert_after(inst
);
869 hash_table_dtor(temps
);
875 * Get the function signature for main from a shader
877 static ir_function_signature
*
878 get_main_function_signature(gl_shader
*sh
)
880 ir_function
*const f
= sh
->symbols
->get_function("main");
882 exec_list void_parameters
;
884 /* Look for the 'void main()' signature and ensure that it's defined.
885 * This keeps the linker from accidentally pick a shader that just
886 * contains a prototype for main.
888 * We don't have to check for multiple definitions of main (in multiple
889 * shaders) because that would have already been caught above.
891 ir_function_signature
*sig
= f
->matching_signature(&void_parameters
);
892 if ((sig
!= NULL
) && sig
->is_defined
) {
902 * This class is only used in link_intrastage_shaders() below but declaring
903 * it inside that function leads to compiler warnings with some versions of
906 class array_sizing_visitor
: public ir_hierarchical_visitor
{
908 virtual ir_visitor_status
visit(ir_variable
*var
)
910 if (var
->type
->is_array() && (var
->type
->length
== 0)) {
911 const glsl_type
*type
=
912 glsl_type::get_array_instance(var
->type
->fields
.array
,
913 var
->max_array_access
+ 1);
914 assert(type
!= NULL
);
917 return visit_continue
;
922 * Combine a group of shaders for a single stage to generate a linked shader
925 * If this function is supplied a single shader, it is cloned, and the new
926 * shader is returned.
928 static struct gl_shader
*
929 link_intrastage_shaders(void *mem_ctx
,
930 struct gl_context
*ctx
,
931 struct gl_shader_program
*prog
,
932 struct gl_shader
**shader_list
,
933 unsigned num_shaders
)
935 struct gl_uniform_block
*uniform_blocks
= NULL
;
937 /* Check that global variables defined in multiple shaders are consistent.
939 if (!cross_validate_globals(prog
, shader_list
, num_shaders
, false))
942 /* Check that interface blocks defined in multiple shaders are consistent.
944 if (!validate_intrastage_interface_blocks((const gl_shader
**)shader_list
,
948 /* Check that uniform blocks between shaders for a stage agree. */
949 const int num_uniform_blocks
=
950 link_uniform_blocks(mem_ctx
, prog
, shader_list
, num_shaders
,
952 if (num_uniform_blocks
< 0)
955 /* Check that there is only a single definition of each function signature
956 * across all shaders.
958 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
959 foreach_list(node
, shader_list
[i
]->ir
) {
960 ir_function
*const f
= ((ir_instruction
*) node
)->as_function();
965 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
966 ir_function
*const other
=
967 shader_list
[j
]->symbols
->get_function(f
->name
);
969 /* If the other shader has no function (and therefore no function
970 * signatures) with the same name, skip to the next shader.
975 foreach_iter (exec_list_iterator
, iter
, *f
) {
976 ir_function_signature
*sig
=
977 (ir_function_signature
*) iter
.get();
979 if (!sig
->is_defined
|| sig
->is_builtin
)
982 ir_function_signature
*other_sig
=
983 other
->exact_matching_signature(& sig
->parameters
);
985 if ((other_sig
!= NULL
) && other_sig
->is_defined
986 && !other_sig
->is_builtin
) {
987 linker_error(prog
, "function `%s' is multiply defined",
996 /* Find the shader that defines main, and make a clone of it.
998 * Starting with the clone, search for undefined references. If one is
999 * found, find the shader that defines it. Clone the reference and add
1000 * it to the shader. Repeat until there are no undefined references or
1001 * until a reference cannot be resolved.
1003 gl_shader
*main
= NULL
;
1004 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1005 if (get_main_function_signature(shader_list
[i
]) != NULL
) {
1006 main
= shader_list
[i
];
1012 linker_error(prog
, "%s shader lacks `main'\n",
1013 _mesa_glsl_shader_target_name(shader_list
[0]->Type
));
1017 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
1018 linked
->ir
= new(linked
) exec_list
;
1019 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
1021 linked
->UniformBlocks
= uniform_blocks
;
1022 linked
->NumUniformBlocks
= num_uniform_blocks
;
1023 ralloc_steal(linked
, linked
->UniformBlocks
);
1025 populate_symbol_table(linked
);
1027 /* The a pointer to the main function in the final linked shader (i.e., the
1028 * copy of the original shader that contained the main function).
1030 ir_function_signature
*const main_sig
= get_main_function_signature(linked
);
1032 /* Move any instructions other than variable declarations or function
1033 * declarations into main.
1035 exec_node
*insertion_point
=
1036 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
1039 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1040 if (shader_list
[i
] == main
)
1043 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
1044 insertion_point
, true, linked
);
1047 /* Resolve initializers for global variables in the linked shader.
1049 unsigned num_linking_shaders
= num_shaders
;
1050 for (unsigned i
= 0; i
< num_shaders
; i
++)
1051 num_linking_shaders
+= shader_list
[i
]->num_builtins_to_link
;
1053 gl_shader
**linking_shaders
=
1054 (gl_shader
**) calloc(num_linking_shaders
, sizeof(gl_shader
*));
1056 memcpy(linking_shaders
, shader_list
,
1057 sizeof(linking_shaders
[0]) * num_shaders
);
1059 unsigned idx
= num_shaders
;
1060 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1061 memcpy(&linking_shaders
[idx
], shader_list
[i
]->builtins_to_link
,
1062 sizeof(linking_shaders
[0]) * shader_list
[i
]->num_builtins_to_link
);
1063 idx
+= shader_list
[i
]->num_builtins_to_link
;
1066 assert(idx
== num_linking_shaders
);
1068 if (!link_function_calls(prog
, linked
, linking_shaders
,
1069 num_linking_shaders
)) {
1070 ctx
->Driver
.DeleteShader(ctx
, linked
);
1074 free(linking_shaders
);
1076 /* At this point linked should contain all of the linked IR, so
1077 * validate it to make sure nothing went wrong.
1080 validate_ir_tree(linked
->ir
);
1082 /* Make a pass over all variable declarations to ensure that arrays with
1083 * unspecified sizes have a size specified. The size is inferred from the
1084 * max_array_access field.
1086 if (linked
!= NULL
) {
1087 array_sizing_visitor v
;
1096 * Update the sizes of linked shader uniform arrays to the maximum
1099 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1101 * If one or more elements of an array are active,
1102 * GetActiveUniform will return the name of the array in name,
1103 * subject to the restrictions listed above. The type of the array
1104 * is returned in type. The size parameter contains the highest
1105 * array element index used, plus one. The compiler or linker
1106 * determines the highest index used. There will be only one
1107 * active uniform reported by the GL per uniform array.
1111 update_array_sizes(struct gl_shader_program
*prog
)
1113 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1114 if (prog
->_LinkedShaders
[i
] == NULL
)
1117 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
1118 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1120 if ((var
== NULL
) || (var
->mode
!= ir_var_uniform
&&
1121 var
->mode
!= ir_var_shader_in
&&
1122 var
->mode
!= ir_var_shader_out
) ||
1123 !var
->type
->is_array())
1126 /* GL_ARB_uniform_buffer_object says that std140 uniforms
1127 * will not be eliminated. Since we always do std140, just
1128 * don't resize arrays in UBOs.
1130 if (var
->is_in_uniform_block())
1133 unsigned int size
= var
->max_array_access
;
1134 for (unsigned j
= 0; j
< MESA_SHADER_TYPES
; j
++) {
1135 if (prog
->_LinkedShaders
[j
] == NULL
)
1138 foreach_list(node2
, prog
->_LinkedShaders
[j
]->ir
) {
1139 ir_variable
*other_var
= ((ir_instruction
*) node2
)->as_variable();
1143 if (strcmp(var
->name
, other_var
->name
) == 0 &&
1144 other_var
->max_array_access
> size
) {
1145 size
= other_var
->max_array_access
;
1150 if (size
+ 1 != var
->type
->fields
.array
->length
) {
1151 /* If this is a built-in uniform (i.e., it's backed by some
1152 * fixed-function state), adjust the number of state slots to
1153 * match the new array size. The number of slots per array entry
1154 * is not known. It seems safe to assume that the total number of
1155 * slots is an integer multiple of the number of array elements.
1156 * Determine the number of slots per array element by dividing by
1157 * the old (total) size.
1159 if (var
->num_state_slots
> 0) {
1160 var
->num_state_slots
= (size
+ 1)
1161 * (var
->num_state_slots
/ var
->type
->length
);
1164 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
1166 /* FINISHME: We should update the types of array
1167 * dereferences of this variable now.
1175 * Find a contiguous set of available bits in a bitmask.
1177 * \param used_mask Bits representing used (1) and unused (0) locations
1178 * \param needed_count Number of contiguous bits needed.
1181 * Base location of the available bits on success or -1 on failure.
1184 find_available_slots(unsigned used_mask
, unsigned needed_count
)
1186 unsigned needed_mask
= (1 << needed_count
) - 1;
1187 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
1189 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1190 * cannot optimize possibly infinite loops" for the loop below.
1192 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
1195 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
1196 if ((needed_mask
& ~used_mask
) == needed_mask
)
1207 * Assign locations for either VS inputs for FS outputs
1209 * \param prog Shader program whose variables need locations assigned
1210 * \param target_index Selector for the program target to receive location
1211 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1212 * \c MESA_SHADER_FRAGMENT.
1213 * \param max_index Maximum number of generic locations. This corresponds
1214 * to either the maximum number of draw buffers or the
1215 * maximum number of generic attributes.
1218 * If locations are successfully assigned, true is returned. Otherwise an
1219 * error is emitted to the shader link log and false is returned.
1222 assign_attribute_or_color_locations(gl_shader_program
*prog
,
1223 unsigned target_index
,
1226 /* Mark invalid locations as being used.
1228 unsigned used_locations
= (max_index
>= 32)
1229 ? ~0 : ~((1 << max_index
) - 1);
1231 assert((target_index
== MESA_SHADER_VERTEX
)
1232 || (target_index
== MESA_SHADER_FRAGMENT
));
1234 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
1238 /* Operate in a total of four passes.
1240 * 1. Invalidate the location assignments for all vertex shader inputs.
1242 * 2. Assign locations for inputs that have user-defined (via
1243 * glBindVertexAttribLocation) locations and outputs that have
1244 * user-defined locations (via glBindFragDataLocation).
1246 * 3. Sort the attributes without assigned locations by number of slots
1247 * required in decreasing order. Fragmentation caused by attribute
1248 * locations assigned by the application may prevent large attributes
1249 * from having enough contiguous space.
1251 * 4. Assign locations to any inputs without assigned locations.
1254 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
1255 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
1257 const enum ir_variable_mode direction
=
1258 (target_index
== MESA_SHADER_VERTEX
)
1259 ? ir_var_shader_in
: ir_var_shader_out
;
1262 /* Temporary storage for the set of attributes that need locations assigned.
1268 /* Used below in the call to qsort. */
1269 static int compare(const void *a
, const void *b
)
1271 const temp_attr
*const l
= (const temp_attr
*) a
;
1272 const temp_attr
*const r
= (const temp_attr
*) b
;
1274 /* Reversed because we want a descending order sort below. */
1275 return r
->slots
- l
->slots
;
1279 unsigned num_attr
= 0;
1281 foreach_list(node
, sh
->ir
) {
1282 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1284 if ((var
== NULL
) || (var
->mode
!= (unsigned) direction
))
1287 if (var
->explicit_location
) {
1288 if ((var
->location
>= (int)(max_index
+ generic_base
))
1289 || (var
->location
< 0)) {
1291 "invalid explicit location %d specified for `%s'\n",
1293 ? var
->location
: var
->location
- generic_base
,
1297 } else if (target_index
== MESA_SHADER_VERTEX
) {
1300 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
1301 assert(binding
>= VERT_ATTRIB_GENERIC0
);
1302 var
->location
= binding
;
1303 var
->is_unmatched_generic_inout
= 0;
1305 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
1309 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
1310 assert(binding
>= FRAG_RESULT_DATA0
);
1311 var
->location
= binding
;
1312 var
->is_unmatched_generic_inout
= 0;
1314 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
1320 /* If the variable is not a built-in and has a location statically
1321 * assigned in the shader (presumably via a layout qualifier), make sure
1322 * that it doesn't collide with other assigned locations. Otherwise,
1323 * add it to the list of variables that need linker-assigned locations.
1325 const unsigned slots
= count_attribute_slots(var
->type
);
1326 if (var
->location
!= -1) {
1327 if (var
->location
>= generic_base
&& var
->index
< 1) {
1328 /* From page 61 of the OpenGL 4.0 spec:
1330 * "LinkProgram will fail if the attribute bindings assigned
1331 * by BindAttribLocation do not leave not enough space to
1332 * assign a location for an active matrix attribute or an
1333 * active attribute array, both of which require multiple
1334 * contiguous generic attributes."
1336 * Previous versions of the spec contain similar language but omit
1337 * the bit about attribute arrays.
1339 * Page 61 of the OpenGL 4.0 spec also says:
1341 * "It is possible for an application to bind more than one
1342 * attribute name to the same location. This is referred to as
1343 * aliasing. This will only work if only one of the aliased
1344 * attributes is active in the executable program, or if no
1345 * path through the shader consumes more than one attribute of
1346 * a set of attributes aliased to the same location. A link
1347 * error can occur if the linker determines that every path
1348 * through the shader consumes multiple aliased attributes,
1349 * but implementations are not required to generate an error
1352 * These two paragraphs are either somewhat contradictory, or I
1353 * don't fully understand one or both of them.
1355 /* FINISHME: The code as currently written does not support
1356 * FINISHME: attribute location aliasing (see comment above).
1358 /* Mask representing the contiguous slots that will be used by
1361 const unsigned attr
= var
->location
- generic_base
;
1362 const unsigned use_mask
= (1 << slots
) - 1;
1364 /* Generate a link error if the set of bits requested for this
1365 * attribute overlaps any previously allocated bits.
1367 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
1368 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
1369 ? "vertex shader input" : "fragment shader output";
1371 "insufficient contiguous locations "
1372 "available for %s `%s' %d %d %d", string
,
1373 var
->name
, used_locations
, use_mask
, attr
);
1377 used_locations
|= (use_mask
<< attr
);
1383 to_assign
[num_attr
].slots
= slots
;
1384 to_assign
[num_attr
].var
= var
;
1388 /* If all of the attributes were assigned locations by the application (or
1389 * are built-in attributes with fixed locations), return early. This should
1390 * be the common case.
1395 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
1397 if (target_index
== MESA_SHADER_VERTEX
) {
1398 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1399 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1400 * reserved to prevent it from being automatically allocated below.
1402 find_deref_visitor
find("gl_Vertex");
1404 if (find
.variable_found())
1405 used_locations
|= (1 << 0);
1408 for (unsigned i
= 0; i
< num_attr
; i
++) {
1409 /* Mask representing the contiguous slots that will be used by this
1412 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
1414 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
1417 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
1418 ? "vertex shader input" : "fragment shader output";
1421 "insufficient contiguous locations "
1422 "available for %s `%s'",
1423 string
, to_assign
[i
].var
->name
);
1427 to_assign
[i
].var
->location
= generic_base
+ location
;
1428 to_assign
[i
].var
->is_unmatched_generic_inout
= 0;
1429 used_locations
|= (use_mask
<< location
);
1437 * Demote shader inputs and outputs that are not used in other stages
1440 demote_shader_inputs_and_outputs(gl_shader
*sh
, enum ir_variable_mode mode
)
1442 foreach_list(node
, sh
->ir
) {
1443 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1445 if ((var
== NULL
) || (var
->mode
!= int(mode
)))
1448 /* A shader 'in' or 'out' variable is only really an input or output if
1449 * its value is used by other shader stages. This will cause the variable
1450 * to have a location assigned.
1452 if (var
->is_unmatched_generic_inout
) {
1453 var
->mode
= ir_var_auto
;
1460 * Store the gl_FragDepth layout in the gl_shader_program struct.
1463 store_fragdepth_layout(struct gl_shader_program
*prog
)
1465 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
1469 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
1471 /* We don't look up the gl_FragDepth symbol directly because if
1472 * gl_FragDepth is not used in the shader, it's removed from the IR.
1473 * However, the symbol won't be removed from the symbol table.
1475 * We're only interested in the cases where the variable is NOT removed
1478 foreach_list(node
, ir
) {
1479 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1481 if (var
== NULL
|| var
->mode
!= ir_var_shader_out
) {
1485 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1486 switch (var
->depth_layout
) {
1487 case ir_depth_layout_none
:
1488 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
1490 case ir_depth_layout_any
:
1491 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
1493 case ir_depth_layout_greater
:
1494 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
1496 case ir_depth_layout_less
:
1497 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
1499 case ir_depth_layout_unchanged
:
1500 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
1511 * Validate the resources used by a program versus the implementation limits
1514 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
1516 static const char *const shader_names
[MESA_SHADER_TYPES
] = {
1517 "vertex", "geometry", "fragment"
1520 const unsigned max_samplers
[MESA_SHADER_TYPES
] = {
1521 ctx
->Const
.VertexProgram
.MaxTextureImageUnits
,
1522 ctx
->Const
.GeometryProgram
.MaxTextureImageUnits
,
1523 ctx
->Const
.FragmentProgram
.MaxTextureImageUnits
1526 const unsigned max_default_uniform_components
[MESA_SHADER_TYPES
] = {
1527 ctx
->Const
.VertexProgram
.MaxUniformComponents
,
1528 ctx
->Const
.GeometryProgram
.MaxUniformComponents
,
1529 ctx
->Const
.FragmentProgram
.MaxUniformComponents
1532 const unsigned max_combined_uniform_components
[MESA_SHADER_TYPES
] = {
1533 ctx
->Const
.VertexProgram
.MaxCombinedUniformComponents
,
1534 ctx
->Const
.GeometryProgram
.MaxCombinedUniformComponents
,
1535 ctx
->Const
.FragmentProgram
.MaxCombinedUniformComponents
1538 const unsigned max_uniform_blocks
[MESA_SHADER_TYPES
] = {
1539 ctx
->Const
.VertexProgram
.MaxUniformBlocks
,
1540 ctx
->Const
.GeometryProgram
.MaxUniformBlocks
,
1541 ctx
->Const
.FragmentProgram
.MaxUniformBlocks
1544 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1545 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1550 if (sh
->num_samplers
> max_samplers
[i
]) {
1551 linker_error(prog
, "Too many %s shader texture samplers",
1555 if (sh
->num_uniform_components
> max_default_uniform_components
[i
]) {
1556 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
1557 linker_warning(prog
, "Too many %s shader default uniform block "
1558 "components, but the driver will try to optimize "
1559 "them out; this is non-portable out-of-spec "
1563 linker_error(prog
, "Too many %s shader default uniform block "
1569 if (sh
->num_combined_uniform_components
>
1570 max_combined_uniform_components
[i
]) {
1571 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
1572 linker_warning(prog
, "Too many %s shader uniform components, "
1573 "but the driver will try to optimize them out; "
1574 "this is non-portable out-of-spec behavior\n",
1577 linker_error(prog
, "Too many %s shader uniform components",
1583 unsigned blocks
[MESA_SHADER_TYPES
] = {0};
1584 unsigned total_uniform_blocks
= 0;
1586 for (unsigned i
= 0; i
< prog
->NumUniformBlocks
; i
++) {
1587 for (unsigned j
= 0; j
< MESA_SHADER_TYPES
; j
++) {
1588 if (prog
->UniformBlockStageIndex
[j
][i
] != -1) {
1590 total_uniform_blocks
++;
1594 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
1595 linker_error(prog
, "Too many combined uniform blocks (%d/%d)",
1596 prog
->NumUniformBlocks
,
1597 ctx
->Const
.MaxCombinedUniformBlocks
);
1599 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1600 if (blocks
[i
] > max_uniform_blocks
[i
]) {
1601 linker_error(prog
, "Too many %s uniform blocks (%d/%d)",
1604 max_uniform_blocks
[i
]);
1611 return prog
->LinkStatus
;
1615 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
1617 tfeedback_decl
*tfeedback_decls
= NULL
;
1618 unsigned num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
1620 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
1622 prog
->LinkStatus
= false;
1623 prog
->Validated
= false;
1624 prog
->_Used
= false;
1626 ralloc_free(prog
->InfoLog
);
1627 prog
->InfoLog
= ralloc_strdup(NULL
, "");
1629 ralloc_free(prog
->UniformBlocks
);
1630 prog
->UniformBlocks
= NULL
;
1631 prog
->NumUniformBlocks
= 0;
1632 for (int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1633 ralloc_free(prog
->UniformBlockStageIndex
[i
]);
1634 prog
->UniformBlockStageIndex
[i
] = NULL
;
1637 /* Separate the shaders into groups based on their type.
1639 struct gl_shader
**vert_shader_list
;
1640 unsigned num_vert_shaders
= 0;
1641 struct gl_shader
**frag_shader_list
;
1642 unsigned num_frag_shaders
= 0;
1644 vert_shader_list
= (struct gl_shader
**)
1645 calloc(2 * prog
->NumShaders
, sizeof(struct gl_shader
*));
1646 frag_shader_list
= &vert_shader_list
[prog
->NumShaders
];
1648 unsigned min_version
= UINT_MAX
;
1649 unsigned max_version
= 0;
1650 const bool is_es_prog
=
1651 (prog
->NumShaders
> 0 && prog
->Shaders
[0]->IsES
) ? true : false;
1652 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
1653 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
1654 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
1656 if (prog
->Shaders
[i
]->IsES
!= is_es_prog
) {
1657 linker_error(prog
, "all shaders must use same shading "
1658 "language version\n");
1662 switch (prog
->Shaders
[i
]->Type
) {
1663 case GL_VERTEX_SHADER
:
1664 vert_shader_list
[num_vert_shaders
] = prog
->Shaders
[i
];
1667 case GL_FRAGMENT_SHADER
:
1668 frag_shader_list
[num_frag_shaders
] = prog
->Shaders
[i
];
1671 case GL_GEOMETRY_SHADER
:
1672 /* FINISHME: Support geometry shaders. */
1673 assert(prog
->Shaders
[i
]->Type
!= GL_GEOMETRY_SHADER
);
1678 /* Previous to GLSL version 1.30, different compilation units could mix and
1679 * match shading language versions. With GLSL 1.30 and later, the versions
1680 * of all shaders must match.
1682 * GLSL ES has never allowed mixing of shading language versions.
1684 if ((is_es_prog
|| max_version
>= 130)
1685 && min_version
!= max_version
) {
1686 linker_error(prog
, "all shaders must use same shading "
1687 "language version\n");
1691 prog
->Version
= max_version
;
1692 prog
->IsES
= is_es_prog
;
1694 for (unsigned int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1695 if (prog
->_LinkedShaders
[i
] != NULL
)
1696 ctx
->Driver
.DeleteShader(ctx
, prog
->_LinkedShaders
[i
]);
1698 prog
->_LinkedShaders
[i
] = NULL
;
1701 /* Link all shaders for a particular stage and validate the result.
1703 if (num_vert_shaders
> 0) {
1704 gl_shader
*const sh
=
1705 link_intrastage_shaders(mem_ctx
, ctx
, prog
, vert_shader_list
,
1711 if (!validate_vertex_shader_executable(prog
, sh
))
1714 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
1718 if (num_frag_shaders
> 0) {
1719 gl_shader
*const sh
=
1720 link_intrastage_shaders(mem_ctx
, ctx
, prog
, frag_shader_list
,
1726 if (!validate_fragment_shader_executable(prog
, sh
))
1729 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
],
1733 /* Here begins the inter-stage linking phase. Some initial validation is
1734 * performed, then locations are assigned for uniforms, attributes, and
1737 if (cross_validate_uniforms(prog
)) {
1740 for (prev
= 0; prev
< MESA_SHADER_TYPES
; prev
++) {
1741 if (prog
->_LinkedShaders
[prev
] != NULL
)
1745 /* Validate the inputs of each stage with the output of the preceding
1748 for (unsigned i
= prev
+ 1; i
< MESA_SHADER_TYPES
; i
++) {
1749 if (prog
->_LinkedShaders
[i
] == NULL
)
1752 if (!validate_interstage_interface_blocks(prog
->_LinkedShaders
[prev
],
1753 prog
->_LinkedShaders
[i
])) {
1754 linker_error(prog
, "interface block mismatch between shader stages\n");
1758 if (!cross_validate_outputs_to_inputs(prog
,
1759 prog
->_LinkedShaders
[prev
],
1760 prog
->_LinkedShaders
[i
]))
1766 prog
->LinkStatus
= true;
1770 for (unsigned int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1771 if (prog
->_LinkedShaders
[i
] != NULL
)
1772 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
1775 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
1776 * it before optimization because we want most of the checks to get
1777 * dropped thanks to constant propagation.
1779 * This rule also applies to GLSL ES 3.00.
1781 if (max_version
>= (is_es_prog
? 300 : 130)) {
1782 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
1784 lower_discard_flow(sh
->ir
);
1788 if (!interstage_cross_validate_uniform_blocks(prog
))
1791 /* Do common optimization before assigning storage for attributes,
1792 * uniforms, and varyings. Later optimization could possibly make
1793 * some of that unused.
1795 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1796 if (prog
->_LinkedShaders
[i
] == NULL
)
1799 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
1800 if (!prog
->LinkStatus
)
1803 if (ctx
->ShaderCompilerOptions
[i
].LowerClipDistance
) {
1804 lower_clip_distance(prog
->_LinkedShaders
[i
]);
1807 unsigned max_unroll
= ctx
->ShaderCompilerOptions
[i
].MaxUnrollIterations
;
1809 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false, max_unroll
, &ctx
->ShaderCompilerOptions
[i
]))
1813 /* Mark all generic shader inputs and outputs as unpaired. */
1814 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] != NULL
) {
1815 link_invalidate_variable_locations(
1816 prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
1817 VERT_ATTRIB_GENERIC0
, VARYING_SLOT_VAR0
);
1819 /* FINISHME: Geometry shaders not implemented yet */
1820 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] != NULL
) {
1821 link_invalidate_variable_locations(
1822 prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
],
1823 VARYING_SLOT_VAR0
, FRAG_RESULT_DATA0
);
1826 /* FINISHME: The value of the max_attribute_index parameter is
1827 * FINISHME: implementation dependent based on the value of
1828 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1829 * FINISHME: at least 16, so hardcode 16 for now.
1831 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_VERTEX
, 16)) {
1835 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_FRAGMENT
, MAX2(ctx
->Const
.MaxDrawBuffers
, ctx
->Const
.MaxDualSourceDrawBuffers
))) {
1840 for (first
= 0; first
< MESA_SHADER_TYPES
; first
++) {
1841 if (prog
->_LinkedShaders
[first
] != NULL
)
1845 if (num_tfeedback_decls
!= 0) {
1846 /* From GL_EXT_transform_feedback:
1847 * A program will fail to link if:
1849 * * the <count> specified by TransformFeedbackVaryingsEXT is
1850 * non-zero, but the program object has no vertex or geometry
1853 if (first
>= MESA_SHADER_FRAGMENT
) {
1854 linker_error(prog
, "Transform feedback varyings specified, but "
1855 "no vertex or geometry shader is present.");
1859 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
1860 prog
->TransformFeedback
.NumVarying
);
1861 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
1862 prog
->TransformFeedback
.VaryingNames
,
1867 /* Linking the stages in the opposite order (from fragment to vertex)
1868 * ensures that inter-shader outputs written to in an earlier stage are
1869 * eliminated if they are (transitively) not used in a later stage.
1872 for (last
= MESA_SHADER_TYPES
-1; last
>= 0; last
--) {
1873 if (prog
->_LinkedShaders
[last
] != NULL
)
1877 if (last
>= 0 && last
< MESA_SHADER_FRAGMENT
) {
1878 gl_shader
*const sh
= prog
->_LinkedShaders
[last
];
1880 if (num_tfeedback_decls
!= 0) {
1881 /* There was no fragment shader, but we still have to assign varying
1882 * locations for use by transform feedback.
1884 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
1886 num_tfeedback_decls
, tfeedback_decls
))
1890 demote_shader_inputs_and_outputs(sh
, ir_var_shader_out
);
1892 /* Eliminate code that is now dead due to unused outputs being demoted.
1894 while (do_dead_code(sh
->ir
, false))
1897 else if (first
== MESA_SHADER_FRAGMENT
) {
1898 /* If the program only contains a fragment shader, just demote
1899 * user-defined varyings.
1901 gl_shader
*const sh
= prog
->_LinkedShaders
[first
];
1903 demote_shader_inputs_and_outputs(sh
, ir_var_shader_in
);
1905 while (do_dead_code(sh
->ir
, false))
1910 for (int i
= next
- 1; i
>= 0; i
--) {
1911 if (prog
->_LinkedShaders
[i
] == NULL
)
1914 gl_shader
*const sh_i
= prog
->_LinkedShaders
[i
];
1915 gl_shader
*const sh_next
= prog
->_LinkedShaders
[next
];
1917 if (!assign_varying_locations(ctx
, mem_ctx
, prog
, sh_i
, sh_next
,
1918 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
1922 demote_shader_inputs_and_outputs(sh_i
, ir_var_shader_out
);
1923 demote_shader_inputs_and_outputs(sh_next
, ir_var_shader_in
);
1925 /* Eliminate code that is now dead due to unused outputs being demoted.
1927 while (do_dead_code(sh_i
->ir
, false))
1929 while (do_dead_code(sh_next
->ir
, false))
1932 /* This must be done after all dead varyings are eliminated. */
1933 if (!check_against_varying_limit(ctx
, prog
, sh_next
))
1939 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
))
1942 update_array_sizes(prog
);
1943 link_assign_uniform_locations(prog
);
1944 store_fragdepth_layout(prog
);
1946 if (!check_resources(ctx
, prog
))
1949 /* OpenGL ES requires that a vertex shader and a fragment shader both be
1950 * present in a linked program. By checking prog->IsES, we also
1951 * catch the GL_ARB_ES2_compatibility case.
1953 if (!prog
->InternalSeparateShader
&&
1954 (ctx
->API
== API_OPENGLES2
|| prog
->IsES
)) {
1955 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
1956 linker_error(prog
, "program lacks a vertex shader\n");
1957 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
1958 linker_error(prog
, "program lacks a fragment shader\n");
1962 /* FINISHME: Assign fragment shader output locations. */
1965 free(vert_shader_list
);
1967 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1968 if (prog
->_LinkedShaders
[i
] == NULL
)
1971 /* Retain any live IR, but trash the rest. */
1972 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
1974 /* The symbol table in the linked shaders may contain references to
1975 * variables that were removed (e.g., unused uniforms). Since it may
1976 * contain junk, there is no possible valid use. Delete it and set the
1979 delete prog
->_LinkedShaders
[i
]->symbols
;
1980 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
1983 ralloc_free(mem_ctx
);