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 * Verify that a vertex shader executable meets all semantic requirements.
303 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
306 * \param shader Vertex shader executable to be verified
309 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
310 struct gl_shader
*shader
)
315 /* From the GLSL 1.10 spec, page 48:
317 * "The variable gl_Position is available only in the vertex
318 * language and is intended for writing the homogeneous vertex
319 * position. All executions of a well-formed vertex shader
320 * executable must write a value into this variable. [...] The
321 * variable gl_Position is available only in the vertex
322 * language and is intended for writing the homogeneous vertex
323 * position. All executions of a well-formed vertex shader
324 * executable must write a value into this variable."
326 * while in GLSL 1.40 this text is changed to:
328 * "The variable gl_Position is available only in the vertex
329 * language and is intended for writing the homogeneous vertex
330 * position. It can be written at any time during shader
331 * execution. It may also be read back by a vertex shader
332 * after being written. This value will be used by primitive
333 * assembly, clipping, culling, and other fixed functionality
334 * operations, if present, that operate on primitives after
335 * vertex processing has occurred. Its value is undefined if
336 * the vertex shader executable does not write gl_Position."
338 * GLSL ES 3.00 is similar to GLSL 1.40--failing to write to gl_Position is
341 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
342 find_assignment_visitor
find("gl_Position");
343 find
.run(shader
->ir
);
344 if (!find
.variable_found()) {
345 linker_error(prog
, "vertex shader does not write to `gl_Position'\n");
350 prog
->Vert
.ClipDistanceArraySize
= 0;
352 if (!prog
->IsES
&& prog
->Version
>= 130) {
353 /* From section 7.1 (Vertex Shader Special Variables) of the
356 * "It is an error for a shader to statically write both
357 * gl_ClipVertex and gl_ClipDistance."
359 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
360 * gl_ClipVertex nor gl_ClipDistance.
362 find_assignment_visitor
clip_vertex("gl_ClipVertex");
363 find_assignment_visitor
clip_distance("gl_ClipDistance");
365 clip_vertex
.run(shader
->ir
);
366 clip_distance
.run(shader
->ir
);
367 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
368 linker_error(prog
, "vertex shader writes to both `gl_ClipVertex' "
369 "and `gl_ClipDistance'\n");
372 prog
->Vert
.UsesClipDistance
= clip_distance
.variable_found();
373 ir_variable
*clip_distance_var
=
374 shader
->symbols
->get_variable("gl_ClipDistance");
375 if (clip_distance_var
)
376 prog
->Vert
.ClipDistanceArraySize
= clip_distance_var
->type
->length
;
382 * Verify that a fragment shader executable meets all semantic requirements
384 * \param shader Fragment shader executable to be verified
387 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
388 struct gl_shader
*shader
)
393 find_assignment_visitor
frag_color("gl_FragColor");
394 find_assignment_visitor
frag_data("gl_FragData");
396 frag_color
.run(shader
->ir
);
397 frag_data
.run(shader
->ir
);
399 if (frag_color
.variable_found() && frag_data
.variable_found()) {
400 linker_error(prog
, "fragment shader writes to both "
401 "`gl_FragColor' and `gl_FragData'\n");
407 * Generate a string describing the mode of a variable
410 mode_string(const ir_variable
*var
)
414 return (var
->read_only
) ? "global constant" : "global variable";
416 case ir_var_uniform
: return "uniform";
417 case ir_var_shader_in
: return "shader input";
418 case ir_var_shader_out
: return "shader output";
420 case ir_var_const_in
:
421 case ir_var_temporary
:
423 assert(!"Should not get here.");
424 return "invalid variable";
430 * Perform validation of global variables used across multiple shaders
433 cross_validate_globals(struct gl_shader_program
*prog
,
434 struct gl_shader
**shader_list
,
435 unsigned num_shaders
,
438 /* Examine all of the uniforms in all of the shaders and cross validate
441 glsl_symbol_table variables
;
442 for (unsigned i
= 0; i
< num_shaders
; i
++) {
443 if (shader_list
[i
] == NULL
)
446 foreach_list(node
, shader_list
[i
]->ir
) {
447 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
452 if (uniforms_only
&& (var
->mode
!= ir_var_uniform
))
455 /* Don't cross validate temporaries that are at global scope. These
456 * will eventually get pulled into the shaders 'main'.
458 if (var
->mode
== ir_var_temporary
)
461 /* If a global with this name has already been seen, verify that the
462 * new instance has the same type. In addition, if the globals have
463 * initializers, the values of the initializers must be the same.
465 ir_variable
*const existing
= variables
.get_variable(var
->name
);
466 if (existing
!= NULL
) {
467 if (var
->type
!= existing
->type
) {
468 /* Consider the types to be "the same" if both types are arrays
469 * of the same type and one of the arrays is implicitly sized.
470 * In addition, set the type of the linked variable to the
471 * explicitly sized array.
473 if (var
->type
->is_array()
474 && existing
->type
->is_array()
475 && (var
->type
->fields
.array
== existing
->type
->fields
.array
)
476 && ((var
->type
->length
== 0)
477 || (existing
->type
->length
== 0))) {
478 if (var
->type
->length
!= 0) {
479 existing
->type
= var
->type
;
482 linker_error(prog
, "%s `%s' declared as type "
483 "`%s' and type `%s'\n",
485 var
->name
, var
->type
->name
,
486 existing
->type
->name
);
491 if (var
->explicit_location
) {
492 if (existing
->explicit_location
493 && (var
->location
!= existing
->location
)) {
494 linker_error(prog
, "explicit locations for %s "
495 "`%s' have differing values\n",
496 mode_string(var
), var
->name
);
500 existing
->location
= var
->location
;
501 existing
->explicit_location
= true;
504 /* From the GLSL 4.20 specification:
505 * "A link error will result if two compilation units in a program
506 * specify different integer-constant bindings for the same
507 * opaque-uniform name. However, it is not an error to specify a
508 * binding on some but not all declarations for the same name"
510 if (var
->explicit_binding
) {
511 if (existing
->explicit_binding
&&
512 var
->binding
!= existing
->binding
) {
513 linker_error(prog
, "explicit bindings for %s "
514 "`%s' have differing values\n",
515 mode_string(var
), var
->name
);
519 existing
->binding
= var
->binding
;
520 existing
->explicit_binding
= true;
523 /* Validate layout qualifiers for gl_FragDepth.
525 * From the AMD/ARB_conservative_depth specs:
527 * "If gl_FragDepth is redeclared in any fragment shader in a
528 * program, it must be redeclared in all fragment shaders in
529 * that program that have static assignments to
530 * gl_FragDepth. All redeclarations of gl_FragDepth in all
531 * fragment shaders in a single program must have the same set
534 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
535 bool layout_declared
= var
->depth_layout
!= ir_depth_layout_none
;
536 bool layout_differs
=
537 var
->depth_layout
!= existing
->depth_layout
;
539 if (layout_declared
&& layout_differs
) {
541 "All redeclarations of gl_FragDepth in all "
542 "fragment shaders in a single program must have "
543 "the same set of qualifiers.");
546 if (var
->used
&& layout_differs
) {
548 "If gl_FragDepth is redeclared with a layout "
549 "qualifier in any fragment shader, it must be "
550 "redeclared with the same layout qualifier in "
551 "all fragment shaders that have assignments to "
556 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
558 * "If a shared global has multiple initializers, the
559 * initializers must all be constant expressions, and they
560 * must all have the same value. Otherwise, a link error will
561 * result. (A shared global having only one initializer does
562 * not require that initializer to be a constant expression.)"
564 * Previous to 4.20 the GLSL spec simply said that initializers
565 * must have the same value. In this case of non-constant
566 * initializers, this was impossible to determine. As a result,
567 * no vendor actually implemented that behavior. The 4.20
568 * behavior matches the implemented behavior of at least one other
569 * vendor, so we'll implement that for all GLSL versions.
571 if (var
->constant_initializer
!= NULL
) {
572 if (existing
->constant_initializer
!= NULL
) {
573 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
574 linker_error(prog
, "initializers for %s "
575 "`%s' have differing values\n",
576 mode_string(var
), var
->name
);
580 /* If the first-seen instance of a particular uniform did not
581 * have an initializer but a later instance does, copy the
582 * initializer to the version stored in the symbol table.
584 /* FINISHME: This is wrong. The constant_value field should
585 * FINISHME: not be modified! Imagine a case where a shader
586 * FINISHME: without an initializer is linked in two different
587 * FINISHME: programs with shaders that have differing
588 * FINISHME: initializers. Linking with the first will
589 * FINISHME: modify the shader, and linking with the second
590 * FINISHME: will fail.
592 existing
->constant_initializer
=
593 var
->constant_initializer
->clone(ralloc_parent(existing
),
598 if (var
->has_initializer
) {
599 if (existing
->has_initializer
600 && (var
->constant_initializer
== NULL
601 || existing
->constant_initializer
== NULL
)) {
603 "shared global variable `%s' has multiple "
604 "non-constant initializers.\n",
609 /* Some instance had an initializer, so keep track of that. In
610 * this location, all sorts of initializers (constant or
611 * otherwise) will propagate the existence to the variable
612 * stored in the symbol table.
614 existing
->has_initializer
= true;
617 if (existing
->invariant
!= var
->invariant
) {
618 linker_error(prog
, "declarations for %s `%s' have "
619 "mismatching invariant qualifiers\n",
620 mode_string(var
), var
->name
);
623 if (existing
->centroid
!= var
->centroid
) {
624 linker_error(prog
, "declarations for %s `%s' have "
625 "mismatching centroid qualifiers\n",
626 mode_string(var
), var
->name
);
630 variables
.add_variable(var
);
637 * Perform validation of uniforms used across multiple shader stages
640 cross_validate_uniforms(struct gl_shader_program
*prog
)
642 cross_validate_globals(prog
, prog
->_LinkedShaders
,
643 MESA_SHADER_TYPES
, true);
647 * Accumulates the array of prog->UniformBlocks and checks that all
648 * definitons of blocks agree on their contents.
651 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
)
653 unsigned max_num_uniform_blocks
= 0;
654 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
655 if (prog
->_LinkedShaders
[i
])
656 max_num_uniform_blocks
+= prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
659 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
660 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
662 prog
->UniformBlockStageIndex
[i
] = ralloc_array(prog
, int,
663 max_num_uniform_blocks
);
664 for (unsigned int j
= 0; j
< max_num_uniform_blocks
; j
++)
665 prog
->UniformBlockStageIndex
[i
][j
] = -1;
670 for (unsigned int j
= 0; j
< sh
->NumUniformBlocks
; j
++) {
671 int index
= link_cross_validate_uniform_block(prog
,
672 &prog
->UniformBlocks
,
673 &prog
->NumUniformBlocks
,
674 &sh
->UniformBlocks
[j
]);
677 linker_error(prog
, "uniform block `%s' has mismatching definitions",
678 sh
->UniformBlocks
[j
].Name
);
682 prog
->UniformBlockStageIndex
[i
][index
] = j
;
691 * Populates a shaders symbol table with all global declarations
694 populate_symbol_table(gl_shader
*sh
)
696 sh
->symbols
= new(sh
) glsl_symbol_table
;
698 foreach_list(node
, sh
->ir
) {
699 ir_instruction
*const inst
= (ir_instruction
*) node
;
703 if ((func
= inst
->as_function()) != NULL
) {
704 sh
->symbols
->add_function(func
);
705 } else if ((var
= inst
->as_variable()) != NULL
) {
706 sh
->symbols
->add_variable(var
);
713 * Remap variables referenced in an instruction tree
715 * This is used when instruction trees are cloned from one shader and placed in
716 * another. These trees will contain references to \c ir_variable nodes that
717 * do not exist in the target shader. This function finds these \c ir_variable
718 * references and replaces the references with matching variables in the target
721 * If there is no matching variable in the target shader, a clone of the
722 * \c ir_variable is made and added to the target shader. The new variable is
723 * added to \b both the instruction stream and the symbol table.
725 * \param inst IR tree that is to be processed.
726 * \param symbols Symbol table containing global scope symbols in the
728 * \param instructions Instruction stream where new variable declarations
732 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
735 class remap_visitor
: public ir_hierarchical_visitor
{
737 remap_visitor(struct gl_shader
*target
,
740 this->target
= target
;
741 this->symbols
= target
->symbols
;
742 this->instructions
= target
->ir
;
746 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
748 if (ir
->var
->mode
== ir_var_temporary
) {
749 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
753 return visit_continue
;
756 ir_variable
*const existing
=
757 this->symbols
->get_variable(ir
->var
->name
);
758 if (existing
!= NULL
)
761 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
763 this->symbols
->add_variable(copy
);
764 this->instructions
->push_head(copy
);
768 return visit_continue
;
772 struct gl_shader
*target
;
773 glsl_symbol_table
*symbols
;
774 exec_list
*instructions
;
778 remap_visitor
v(target
, temps
);
785 * Move non-declarations from one instruction stream to another
787 * The intended usage pattern of this function is to pass the pointer to the
788 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
789 * pointer) for \c last and \c false for \c make_copies on the first
790 * call. Successive calls pass the return value of the previous call for
791 * \c last and \c true for \c make_copies.
793 * \param instructions Source instruction stream
794 * \param last Instruction after which new instructions should be
795 * inserted in the target instruction stream
796 * \param make_copies Flag selecting whether instructions in \c instructions
797 * should be copied (via \c ir_instruction::clone) into the
798 * target list or moved.
801 * The new "last" instruction in the target instruction stream. This pointer
802 * is suitable for use as the \c last parameter of a later call to this
806 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
807 bool make_copies
, gl_shader
*target
)
809 hash_table
*temps
= NULL
;
812 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
813 hash_table_pointer_compare
);
815 foreach_list_safe(node
, instructions
) {
816 ir_instruction
*inst
= (ir_instruction
*) node
;
818 if (inst
->as_function())
821 ir_variable
*var
= inst
->as_variable();
822 if ((var
!= NULL
) && (var
->mode
!= ir_var_temporary
))
825 assert(inst
->as_assignment()
827 || inst
->as_if() /* for initializers with the ?: operator */
828 || ((var
!= NULL
) && (var
->mode
== ir_var_temporary
)));
831 inst
= inst
->clone(target
, NULL
);
834 hash_table_insert(temps
, inst
, var
);
836 remap_variables(inst
, target
, temps
);
841 last
->insert_after(inst
);
846 hash_table_dtor(temps
);
852 * Get the function signature for main from a shader
854 static ir_function_signature
*
855 get_main_function_signature(gl_shader
*sh
)
857 ir_function
*const f
= sh
->symbols
->get_function("main");
859 exec_list void_parameters
;
861 /* Look for the 'void main()' signature and ensure that it's defined.
862 * This keeps the linker from accidentally pick a shader that just
863 * contains a prototype for main.
865 * We don't have to check for multiple definitions of main (in multiple
866 * shaders) because that would have already been caught above.
868 ir_function_signature
*sig
= f
->matching_signature(&void_parameters
);
869 if ((sig
!= NULL
) && sig
->is_defined
) {
879 * This class is only used in link_intrastage_shaders() below but declaring
880 * it inside that function leads to compiler warnings with some versions of
883 class array_sizing_visitor
: public ir_hierarchical_visitor
{
885 virtual ir_visitor_status
visit(ir_variable
*var
)
887 if (var
->type
->is_array() && (var
->type
->length
== 0)) {
888 const glsl_type
*type
=
889 glsl_type::get_array_instance(var
->type
->fields
.array
,
890 var
->max_array_access
+ 1);
891 assert(type
!= NULL
);
894 return visit_continue
;
899 * Combine a group of shaders for a single stage to generate a linked shader
902 * If this function is supplied a single shader, it is cloned, and the new
903 * shader is returned.
905 static struct gl_shader
*
906 link_intrastage_shaders(void *mem_ctx
,
907 struct gl_context
*ctx
,
908 struct gl_shader_program
*prog
,
909 struct gl_shader
**shader_list
,
910 unsigned num_shaders
)
912 struct gl_uniform_block
*uniform_blocks
= NULL
;
914 /* Check that global variables defined in multiple shaders are consistent.
916 cross_validate_globals(prog
, shader_list
, num_shaders
, false);
917 if (!prog
->LinkStatus
)
920 /* Check that interface blocks defined in multiple shaders are consistent.
922 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
924 if (!prog
->LinkStatus
)
927 /* Link up uniform blocks defined within this stage. */
928 const unsigned num_uniform_blocks
=
929 link_uniform_blocks(mem_ctx
, prog
, shader_list
, num_shaders
,
932 /* Check that there is only a single definition of each function signature
933 * across all shaders.
935 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
936 foreach_list(node
, shader_list
[i
]->ir
) {
937 ir_function
*const f
= ((ir_instruction
*) node
)->as_function();
942 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
943 ir_function
*const other
=
944 shader_list
[j
]->symbols
->get_function(f
->name
);
946 /* If the other shader has no function (and therefore no function
947 * signatures) with the same name, skip to the next shader.
952 foreach_iter (exec_list_iterator
, iter
, *f
) {
953 ir_function_signature
*sig
=
954 (ir_function_signature
*) iter
.get();
956 if (!sig
->is_defined
|| sig
->is_builtin
)
959 ir_function_signature
*other_sig
=
960 other
->exact_matching_signature(& sig
->parameters
);
962 if ((other_sig
!= NULL
) && other_sig
->is_defined
963 && !other_sig
->is_builtin
) {
964 linker_error(prog
, "function `%s' is multiply defined",
973 /* Find the shader that defines main, and make a clone of it.
975 * Starting with the clone, search for undefined references. If one is
976 * found, find the shader that defines it. Clone the reference and add
977 * it to the shader. Repeat until there are no undefined references or
978 * until a reference cannot be resolved.
980 gl_shader
*main
= NULL
;
981 for (unsigned i
= 0; i
< num_shaders
; i
++) {
982 if (get_main_function_signature(shader_list
[i
]) != NULL
) {
983 main
= shader_list
[i
];
989 linker_error(prog
, "%s shader lacks `main'\n",
990 _mesa_glsl_shader_target_name(shader_list
[0]->Type
));
994 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
995 linked
->ir
= new(linked
) exec_list
;
996 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
998 linked
->UniformBlocks
= uniform_blocks
;
999 linked
->NumUniformBlocks
= num_uniform_blocks
;
1000 ralloc_steal(linked
, linked
->UniformBlocks
);
1002 populate_symbol_table(linked
);
1004 /* The a pointer to the main function in the final linked shader (i.e., the
1005 * copy of the original shader that contained the main function).
1007 ir_function_signature
*const main_sig
= get_main_function_signature(linked
);
1009 /* Move any instructions other than variable declarations or function
1010 * declarations into main.
1012 exec_node
*insertion_point
=
1013 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
1016 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1017 if (shader_list
[i
] == main
)
1020 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
1021 insertion_point
, true, linked
);
1024 /* Resolve initializers for global variables in the linked shader.
1026 unsigned num_linking_shaders
= num_shaders
;
1027 for (unsigned i
= 0; i
< num_shaders
; i
++)
1028 num_linking_shaders
+= shader_list
[i
]->num_builtins_to_link
;
1030 gl_shader
**linking_shaders
=
1031 (gl_shader
**) calloc(num_linking_shaders
, sizeof(gl_shader
*));
1033 memcpy(linking_shaders
, shader_list
,
1034 sizeof(linking_shaders
[0]) * num_shaders
);
1036 unsigned idx
= num_shaders
;
1037 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1038 memcpy(&linking_shaders
[idx
], shader_list
[i
]->builtins_to_link
,
1039 sizeof(linking_shaders
[0]) * shader_list
[i
]->num_builtins_to_link
);
1040 idx
+= shader_list
[i
]->num_builtins_to_link
;
1043 assert(idx
== num_linking_shaders
);
1045 if (!link_function_calls(prog
, linked
, linking_shaders
,
1046 num_linking_shaders
)) {
1047 ctx
->Driver
.DeleteShader(ctx
, linked
);
1051 free(linking_shaders
);
1053 /* At this point linked should contain all of the linked IR, so
1054 * validate it to make sure nothing went wrong.
1057 validate_ir_tree(linked
->ir
);
1059 /* Make a pass over all variable declarations to ensure that arrays with
1060 * unspecified sizes have a size specified. The size is inferred from the
1061 * max_array_access field.
1063 if (linked
!= NULL
) {
1064 array_sizing_visitor v
;
1073 * Update the sizes of linked shader uniform arrays to the maximum
1076 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1078 * If one or more elements of an array are active,
1079 * GetActiveUniform will return the name of the array in name,
1080 * subject to the restrictions listed above. The type of the array
1081 * is returned in type. The size parameter contains the highest
1082 * array element index used, plus one. The compiler or linker
1083 * determines the highest index used. There will be only one
1084 * active uniform reported by the GL per uniform array.
1088 update_array_sizes(struct gl_shader_program
*prog
)
1090 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1091 if (prog
->_LinkedShaders
[i
] == NULL
)
1094 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
1095 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1097 if ((var
== NULL
) || (var
->mode
!= ir_var_uniform
) ||
1098 !var
->type
->is_array())
1101 /* GL_ARB_uniform_buffer_object says that std140 uniforms
1102 * will not be eliminated. Since we always do std140, just
1103 * don't resize arrays in UBOs.
1105 if (var
->is_in_uniform_block())
1108 unsigned int size
= var
->max_array_access
;
1109 for (unsigned j
= 0; j
< MESA_SHADER_TYPES
; j
++) {
1110 if (prog
->_LinkedShaders
[j
] == NULL
)
1113 foreach_list(node2
, prog
->_LinkedShaders
[j
]->ir
) {
1114 ir_variable
*other_var
= ((ir_instruction
*) node2
)->as_variable();
1118 if (strcmp(var
->name
, other_var
->name
) == 0 &&
1119 other_var
->max_array_access
> size
) {
1120 size
= other_var
->max_array_access
;
1125 if (size
+ 1 != var
->type
->length
) {
1126 /* If this is a built-in uniform (i.e., it's backed by some
1127 * fixed-function state), adjust the number of state slots to
1128 * match the new array size. The number of slots per array entry
1129 * is not known. It seems safe to assume that the total number of
1130 * slots is an integer multiple of the number of array elements.
1131 * Determine the number of slots per array element by dividing by
1132 * the old (total) size.
1134 if (var
->num_state_slots
> 0) {
1135 var
->num_state_slots
= (size
+ 1)
1136 * (var
->num_state_slots
/ var
->type
->length
);
1139 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
1141 /* FINISHME: We should update the types of array
1142 * dereferences of this variable now.
1150 * Find a contiguous set of available bits in a bitmask.
1152 * \param used_mask Bits representing used (1) and unused (0) locations
1153 * \param needed_count Number of contiguous bits needed.
1156 * Base location of the available bits on success or -1 on failure.
1159 find_available_slots(unsigned used_mask
, unsigned needed_count
)
1161 unsigned needed_mask
= (1 << needed_count
) - 1;
1162 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
1164 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1165 * cannot optimize possibly infinite loops" for the loop below.
1167 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
1170 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
1171 if ((needed_mask
& ~used_mask
) == needed_mask
)
1182 * Assign locations for either VS inputs for FS outputs
1184 * \param prog Shader program whose variables need locations assigned
1185 * \param target_index Selector for the program target to receive location
1186 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1187 * \c MESA_SHADER_FRAGMENT.
1188 * \param max_index Maximum number of generic locations. This corresponds
1189 * to either the maximum number of draw buffers or the
1190 * maximum number of generic attributes.
1193 * If locations are successfully assigned, true is returned. Otherwise an
1194 * error is emitted to the shader link log and false is returned.
1197 assign_attribute_or_color_locations(gl_shader_program
*prog
,
1198 unsigned target_index
,
1201 /* Mark invalid locations as being used.
1203 unsigned used_locations
= (max_index
>= 32)
1204 ? ~0 : ~((1 << max_index
) - 1);
1206 assert((target_index
== MESA_SHADER_VERTEX
)
1207 || (target_index
== MESA_SHADER_FRAGMENT
));
1209 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
1213 /* Operate in a total of four passes.
1215 * 1. Invalidate the location assignments for all vertex shader inputs.
1217 * 2. Assign locations for inputs that have user-defined (via
1218 * glBindVertexAttribLocation) locations and outputs that have
1219 * user-defined locations (via glBindFragDataLocation).
1221 * 3. Sort the attributes without assigned locations by number of slots
1222 * required in decreasing order. Fragmentation caused by attribute
1223 * locations assigned by the application may prevent large attributes
1224 * from having enough contiguous space.
1226 * 4. Assign locations to any inputs without assigned locations.
1229 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
1230 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
1232 const enum ir_variable_mode direction
=
1233 (target_index
== MESA_SHADER_VERTEX
)
1234 ? ir_var_shader_in
: ir_var_shader_out
;
1237 /* Temporary storage for the set of attributes that need locations assigned.
1243 /* Used below in the call to qsort. */
1244 static int compare(const void *a
, const void *b
)
1246 const temp_attr
*const l
= (const temp_attr
*) a
;
1247 const temp_attr
*const r
= (const temp_attr
*) b
;
1249 /* Reversed because we want a descending order sort below. */
1250 return r
->slots
- l
->slots
;
1254 unsigned num_attr
= 0;
1256 foreach_list(node
, sh
->ir
) {
1257 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1259 if ((var
== NULL
) || (var
->mode
!= (unsigned) direction
))
1262 if (var
->explicit_location
) {
1263 if ((var
->location
>= (int)(max_index
+ generic_base
))
1264 || (var
->location
< 0)) {
1266 "invalid explicit location %d specified for `%s'\n",
1268 ? var
->location
: var
->location
- generic_base
,
1272 } else if (target_index
== MESA_SHADER_VERTEX
) {
1275 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
1276 assert(binding
>= VERT_ATTRIB_GENERIC0
);
1277 var
->location
= binding
;
1278 var
->is_unmatched_generic_inout
= 0;
1280 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
1284 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
1285 assert(binding
>= FRAG_RESULT_DATA0
);
1286 var
->location
= binding
;
1287 var
->is_unmatched_generic_inout
= 0;
1289 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
1295 /* If the variable is not a built-in and has a location statically
1296 * assigned in the shader (presumably via a layout qualifier), make sure
1297 * that it doesn't collide with other assigned locations. Otherwise,
1298 * add it to the list of variables that need linker-assigned locations.
1300 const unsigned slots
= var
->type
->count_attribute_slots();
1301 if (var
->location
!= -1) {
1302 if (var
->location
>= generic_base
&& var
->index
< 1) {
1303 /* From page 61 of the OpenGL 4.0 spec:
1305 * "LinkProgram will fail if the attribute bindings assigned
1306 * by BindAttribLocation do not leave not enough space to
1307 * assign a location for an active matrix attribute or an
1308 * active attribute array, both of which require multiple
1309 * contiguous generic attributes."
1311 * Previous versions of the spec contain similar language but omit
1312 * the bit about attribute arrays.
1314 * Page 61 of the OpenGL 4.0 spec also says:
1316 * "It is possible for an application to bind more than one
1317 * attribute name to the same location. This is referred to as
1318 * aliasing. This will only work if only one of the aliased
1319 * attributes is active in the executable program, or if no
1320 * path through the shader consumes more than one attribute of
1321 * a set of attributes aliased to the same location. A link
1322 * error can occur if the linker determines that every path
1323 * through the shader consumes multiple aliased attributes,
1324 * but implementations are not required to generate an error
1327 * These two paragraphs are either somewhat contradictory, or I
1328 * don't fully understand one or both of them.
1330 /* FINISHME: The code as currently written does not support
1331 * FINISHME: attribute location aliasing (see comment above).
1333 /* Mask representing the contiguous slots that will be used by
1336 const unsigned attr
= var
->location
- generic_base
;
1337 const unsigned use_mask
= (1 << slots
) - 1;
1339 /* Generate a link error if the set of bits requested for this
1340 * attribute overlaps any previously allocated bits.
1342 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
1343 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
1344 ? "vertex shader input" : "fragment shader output";
1346 "insufficient contiguous locations "
1347 "available for %s `%s' %d %d %d", string
,
1348 var
->name
, used_locations
, use_mask
, attr
);
1352 used_locations
|= (use_mask
<< attr
);
1358 to_assign
[num_attr
].slots
= slots
;
1359 to_assign
[num_attr
].var
= var
;
1363 /* If all of the attributes were assigned locations by the application (or
1364 * are built-in attributes with fixed locations), return early. This should
1365 * be the common case.
1370 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
1372 if (target_index
== MESA_SHADER_VERTEX
) {
1373 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1374 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1375 * reserved to prevent it from being automatically allocated below.
1377 find_deref_visitor
find("gl_Vertex");
1379 if (find
.variable_found())
1380 used_locations
|= (1 << 0);
1383 for (unsigned i
= 0; i
< num_attr
; i
++) {
1384 /* Mask representing the contiguous slots that will be used by this
1387 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
1389 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
1392 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
1393 ? "vertex shader input" : "fragment shader output";
1396 "insufficient contiguous locations "
1397 "available for %s `%s'",
1398 string
, to_assign
[i
].var
->name
);
1402 to_assign
[i
].var
->location
= generic_base
+ location
;
1403 to_assign
[i
].var
->is_unmatched_generic_inout
= 0;
1404 used_locations
|= (use_mask
<< location
);
1412 * Demote shader inputs and outputs that are not used in other stages
1415 demote_shader_inputs_and_outputs(gl_shader
*sh
, enum ir_variable_mode mode
)
1417 foreach_list(node
, sh
->ir
) {
1418 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1420 if ((var
== NULL
) || (var
->mode
!= int(mode
)))
1423 /* A shader 'in' or 'out' variable is only really an input or output if
1424 * its value is used by other shader stages. This will cause the variable
1425 * to have a location assigned.
1427 if (var
->is_unmatched_generic_inout
) {
1428 var
->mode
= ir_var_auto
;
1435 * Store the gl_FragDepth layout in the gl_shader_program struct.
1438 store_fragdepth_layout(struct gl_shader_program
*prog
)
1440 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
1444 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
1446 /* We don't look up the gl_FragDepth symbol directly because if
1447 * gl_FragDepth is not used in the shader, it's removed from the IR.
1448 * However, the symbol won't be removed from the symbol table.
1450 * We're only interested in the cases where the variable is NOT removed
1453 foreach_list(node
, ir
) {
1454 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1456 if (var
== NULL
|| var
->mode
!= ir_var_shader_out
) {
1460 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1461 switch (var
->depth_layout
) {
1462 case ir_depth_layout_none
:
1463 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
1465 case ir_depth_layout_any
:
1466 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
1468 case ir_depth_layout_greater
:
1469 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
1471 case ir_depth_layout_less
:
1472 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
1474 case ir_depth_layout_unchanged
:
1475 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
1486 * Validate the resources used by a program versus the implementation limits
1489 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
1491 static const char *const shader_names
[MESA_SHADER_TYPES
] = {
1492 "vertex", "geometry", "fragment"
1495 const unsigned max_samplers
[MESA_SHADER_TYPES
] = {
1496 ctx
->Const
.VertexProgram
.MaxTextureImageUnits
,
1497 ctx
->Const
.GeometryProgram
.MaxTextureImageUnits
,
1498 ctx
->Const
.FragmentProgram
.MaxTextureImageUnits
1501 const unsigned max_default_uniform_components
[MESA_SHADER_TYPES
] = {
1502 ctx
->Const
.VertexProgram
.MaxUniformComponents
,
1503 ctx
->Const
.GeometryProgram
.MaxUniformComponents
,
1504 ctx
->Const
.FragmentProgram
.MaxUniformComponents
1507 const unsigned max_combined_uniform_components
[MESA_SHADER_TYPES
] = {
1508 ctx
->Const
.VertexProgram
.MaxCombinedUniformComponents
,
1509 ctx
->Const
.GeometryProgram
.MaxCombinedUniformComponents
,
1510 ctx
->Const
.FragmentProgram
.MaxCombinedUniformComponents
1513 const unsigned max_uniform_blocks
[MESA_SHADER_TYPES
] = {
1514 ctx
->Const
.VertexProgram
.MaxUniformBlocks
,
1515 ctx
->Const
.GeometryProgram
.MaxUniformBlocks
,
1516 ctx
->Const
.FragmentProgram
.MaxUniformBlocks
1519 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1520 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1525 if (sh
->num_samplers
> max_samplers
[i
]) {
1526 linker_error(prog
, "Too many %s shader texture samplers",
1530 if (sh
->num_uniform_components
> max_default_uniform_components
[i
]) {
1531 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
1532 linker_warning(prog
, "Too many %s shader default uniform block "
1533 "components, but the driver will try to optimize "
1534 "them out; this is non-portable out-of-spec "
1538 linker_error(prog
, "Too many %s shader default uniform block "
1544 if (sh
->num_combined_uniform_components
>
1545 max_combined_uniform_components
[i
]) {
1546 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
1547 linker_warning(prog
, "Too many %s shader uniform components, "
1548 "but the driver will try to optimize them out; "
1549 "this is non-portable out-of-spec behavior\n",
1552 linker_error(prog
, "Too many %s shader uniform components",
1558 unsigned blocks
[MESA_SHADER_TYPES
] = {0};
1559 unsigned total_uniform_blocks
= 0;
1561 for (unsigned i
= 0; i
< prog
->NumUniformBlocks
; i
++) {
1562 for (unsigned j
= 0; j
< MESA_SHADER_TYPES
; j
++) {
1563 if (prog
->UniformBlockStageIndex
[j
][i
] != -1) {
1565 total_uniform_blocks
++;
1569 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
1570 linker_error(prog
, "Too many combined uniform blocks (%d/%d)",
1571 prog
->NumUniformBlocks
,
1572 ctx
->Const
.MaxCombinedUniformBlocks
);
1574 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1575 if (blocks
[i
] > max_uniform_blocks
[i
]) {
1576 linker_error(prog
, "Too many %s uniform blocks (%d/%d)",
1579 max_uniform_blocks
[i
]);
1588 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
1590 tfeedback_decl
*tfeedback_decls
= NULL
;
1591 unsigned num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
1593 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
1595 prog
->LinkStatus
= true; /* All error paths will set this to false */
1596 prog
->Validated
= false;
1597 prog
->_Used
= false;
1599 ralloc_free(prog
->InfoLog
);
1600 prog
->InfoLog
= ralloc_strdup(NULL
, "");
1602 ralloc_free(prog
->UniformBlocks
);
1603 prog
->UniformBlocks
= NULL
;
1604 prog
->NumUniformBlocks
= 0;
1605 for (int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1606 ralloc_free(prog
->UniformBlockStageIndex
[i
]);
1607 prog
->UniformBlockStageIndex
[i
] = NULL
;
1610 /* Separate the shaders into groups based on their type.
1612 struct gl_shader
**vert_shader_list
;
1613 unsigned num_vert_shaders
= 0;
1614 struct gl_shader
**frag_shader_list
;
1615 unsigned num_frag_shaders
= 0;
1617 vert_shader_list
= (struct gl_shader
**)
1618 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
1619 frag_shader_list
= (struct gl_shader
**)
1620 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
1622 unsigned min_version
= UINT_MAX
;
1623 unsigned max_version
= 0;
1624 const bool is_es_prog
=
1625 (prog
->NumShaders
> 0 && prog
->Shaders
[0]->IsES
) ? true : false;
1626 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
1627 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
1628 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
1630 if (prog
->Shaders
[i
]->IsES
!= is_es_prog
) {
1631 linker_error(prog
, "all shaders must use same shading "
1632 "language version\n");
1636 switch (prog
->Shaders
[i
]->Type
) {
1637 case GL_VERTEX_SHADER
:
1638 vert_shader_list
[num_vert_shaders
] = prog
->Shaders
[i
];
1641 case GL_FRAGMENT_SHADER
:
1642 frag_shader_list
[num_frag_shaders
] = prog
->Shaders
[i
];
1645 case GL_GEOMETRY_SHADER
:
1646 /* FINISHME: Support geometry shaders. */
1647 assert(prog
->Shaders
[i
]->Type
!= GL_GEOMETRY_SHADER
);
1652 /* Previous to GLSL version 1.30, different compilation units could mix and
1653 * match shading language versions. With GLSL 1.30 and later, the versions
1654 * of all shaders must match.
1656 * GLSL ES has never allowed mixing of shading language versions.
1658 if ((is_es_prog
|| max_version
>= 130)
1659 && min_version
!= max_version
) {
1660 linker_error(prog
, "all shaders must use same shading "
1661 "language version\n");
1665 prog
->Version
= max_version
;
1666 prog
->IsES
= is_es_prog
;
1668 for (unsigned int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1669 if (prog
->_LinkedShaders
[i
] != NULL
)
1670 ctx
->Driver
.DeleteShader(ctx
, prog
->_LinkedShaders
[i
]);
1672 prog
->_LinkedShaders
[i
] = NULL
;
1675 /* Link all shaders for a particular stage and validate the result.
1677 if (num_vert_shaders
> 0) {
1678 gl_shader
*const sh
=
1679 link_intrastage_shaders(mem_ctx
, ctx
, prog
, vert_shader_list
,
1682 if (!prog
->LinkStatus
)
1685 validate_vertex_shader_executable(prog
, sh
);
1686 if (!prog
->LinkStatus
)
1689 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
1693 if (num_frag_shaders
> 0) {
1694 gl_shader
*const sh
=
1695 link_intrastage_shaders(mem_ctx
, ctx
, prog
, frag_shader_list
,
1698 if (!prog
->LinkStatus
)
1701 validate_fragment_shader_executable(prog
, sh
);
1702 if (!prog
->LinkStatus
)
1705 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
],
1709 /* Here begins the inter-stage linking phase. Some initial validation is
1710 * performed, then locations are assigned for uniforms, attributes, and
1713 cross_validate_uniforms(prog
);
1714 if (!prog
->LinkStatus
)
1719 for (prev
= 0; prev
< MESA_SHADER_TYPES
; prev
++) {
1720 if (prog
->_LinkedShaders
[prev
] != NULL
)
1724 /* Validate the inputs of each stage with the output of the preceding
1727 for (unsigned i
= prev
+ 1; i
< MESA_SHADER_TYPES
; i
++) {
1728 if (prog
->_LinkedShaders
[i
] == NULL
)
1731 validate_interstage_interface_blocks(prog
, prog
->_LinkedShaders
[prev
],
1732 prog
->_LinkedShaders
[i
]);
1733 if (!prog
->LinkStatus
)
1736 cross_validate_outputs_to_inputs(prog
,
1737 prog
->_LinkedShaders
[prev
],
1738 prog
->_LinkedShaders
[i
]);
1739 if (!prog
->LinkStatus
)
1746 for (unsigned int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1747 if (prog
->_LinkedShaders
[i
] != NULL
)
1748 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
1751 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
1752 * it before optimization because we want most of the checks to get
1753 * dropped thanks to constant propagation.
1755 * This rule also applies to GLSL ES 3.00.
1757 if (max_version
>= (is_es_prog
? 300 : 130)) {
1758 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
1760 lower_discard_flow(sh
->ir
);
1764 if (!interstage_cross_validate_uniform_blocks(prog
))
1767 /* Do common optimization before assigning storage for attributes,
1768 * uniforms, and varyings. Later optimization could possibly make
1769 * some of that unused.
1771 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1772 if (prog
->_LinkedShaders
[i
] == NULL
)
1775 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
1776 if (!prog
->LinkStatus
)
1779 if (ctx
->ShaderCompilerOptions
[i
].LowerClipDistance
) {
1780 lower_clip_distance(prog
->_LinkedShaders
[i
]);
1783 unsigned max_unroll
= ctx
->ShaderCompilerOptions
[i
].MaxUnrollIterations
;
1785 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false, max_unroll
, &ctx
->ShaderCompilerOptions
[i
]))
1789 /* Mark all generic shader inputs and outputs as unpaired. */
1790 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] != NULL
) {
1791 link_invalidate_variable_locations(
1792 prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
1793 VERT_ATTRIB_GENERIC0
, VARYING_SLOT_VAR0
);
1795 /* FINISHME: Geometry shaders not implemented yet */
1796 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] != NULL
) {
1797 link_invalidate_variable_locations(
1798 prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
],
1799 VARYING_SLOT_VAR0
, FRAG_RESULT_DATA0
);
1802 /* FINISHME: The value of the max_attribute_index parameter is
1803 * FINISHME: implementation dependent based on the value of
1804 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1805 * FINISHME: at least 16, so hardcode 16 for now.
1807 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_VERTEX
, 16)) {
1811 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_FRAGMENT
, MAX2(ctx
->Const
.MaxDrawBuffers
, ctx
->Const
.MaxDualSourceDrawBuffers
))) {
1816 for (first
= 0; first
< MESA_SHADER_TYPES
; first
++) {
1817 if (prog
->_LinkedShaders
[first
] != NULL
)
1821 if (num_tfeedback_decls
!= 0) {
1822 /* From GL_EXT_transform_feedback:
1823 * A program will fail to link if:
1825 * * the <count> specified by TransformFeedbackVaryingsEXT is
1826 * non-zero, but the program object has no vertex or geometry
1829 if (first
>= MESA_SHADER_FRAGMENT
) {
1830 linker_error(prog
, "Transform feedback varyings specified, but "
1831 "no vertex or geometry shader is present.");
1835 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
1836 prog
->TransformFeedback
.NumVarying
);
1837 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
1838 prog
->TransformFeedback
.VaryingNames
,
1843 /* Linking the stages in the opposite order (from fragment to vertex)
1844 * ensures that inter-shader outputs written to in an earlier stage are
1845 * eliminated if they are (transitively) not used in a later stage.
1848 for (last
= MESA_SHADER_TYPES
-1; last
>= 0; last
--) {
1849 if (prog
->_LinkedShaders
[last
] != NULL
)
1853 if (last
>= 0 && last
< MESA_SHADER_FRAGMENT
) {
1854 gl_shader
*const sh
= prog
->_LinkedShaders
[last
];
1856 if (num_tfeedback_decls
!= 0) {
1857 /* There was no fragment shader, but we still have to assign varying
1858 * locations for use by transform feedback.
1860 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
1862 num_tfeedback_decls
, tfeedback_decls
))
1866 do_dead_builtin_varyings(ctx
, sh
->ir
, NULL
,
1867 num_tfeedback_decls
, tfeedback_decls
);
1869 demote_shader_inputs_and_outputs(sh
, ir_var_shader_out
);
1871 /* Eliminate code that is now dead due to unused outputs being demoted.
1873 while (do_dead_code(sh
->ir
, false))
1876 else if (first
== MESA_SHADER_FRAGMENT
) {
1877 /* If the program only contains a fragment shader...
1879 gl_shader
*const sh
= prog
->_LinkedShaders
[first
];
1881 do_dead_builtin_varyings(ctx
, NULL
, sh
->ir
,
1882 num_tfeedback_decls
, tfeedback_decls
);
1884 demote_shader_inputs_and_outputs(sh
, ir_var_shader_in
);
1886 while (do_dead_code(sh
->ir
, false))
1891 for (int i
= next
- 1; i
>= 0; i
--) {
1892 if (prog
->_LinkedShaders
[i
] == NULL
)
1895 gl_shader
*const sh_i
= prog
->_LinkedShaders
[i
];
1896 gl_shader
*const sh_next
= prog
->_LinkedShaders
[next
];
1898 if (!assign_varying_locations(ctx
, mem_ctx
, prog
, sh_i
, sh_next
,
1899 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
1903 do_dead_builtin_varyings(ctx
, sh_i
->ir
, sh_next
->ir
,
1904 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
1907 demote_shader_inputs_and_outputs(sh_i
, ir_var_shader_out
);
1908 demote_shader_inputs_and_outputs(sh_next
, ir_var_shader_in
);
1910 /* Eliminate code that is now dead due to unused outputs being demoted.
1912 while (do_dead_code(sh_i
->ir
, false))
1914 while (do_dead_code(sh_next
->ir
, false))
1917 /* This must be done after all dead varyings are eliminated. */
1918 if (!check_against_varying_limit(ctx
, prog
, sh_next
))
1924 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
))
1927 update_array_sizes(prog
);
1928 link_assign_uniform_locations(prog
);
1929 store_fragdepth_layout(prog
);
1931 check_resources(ctx
, prog
);
1932 if (!prog
->LinkStatus
)
1935 /* OpenGL ES requires that a vertex shader and a fragment shader both be
1936 * present in a linked program. By checking prog->IsES, we also
1937 * catch the GL_ARB_ES2_compatibility case.
1939 if (!prog
->InternalSeparateShader
&&
1940 (ctx
->API
== API_OPENGLES2
|| prog
->IsES
)) {
1941 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
1942 linker_error(prog
, "program lacks a vertex shader\n");
1943 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
1944 linker_error(prog
, "program lacks a fragment shader\n");
1948 /* FINISHME: Assign fragment shader output locations. */
1951 free(vert_shader_list
);
1952 free(frag_shader_list
);
1954 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1955 if (prog
->_LinkedShaders
[i
] == NULL
)
1958 /* Retain any live IR, but trash the rest. */
1959 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
1961 /* The symbol table in the linked shaders may contain references to
1962 * variables that were removed (e.g., unused uniforms). Since it may
1963 * contain junk, there is no possible valid use. Delete it and set the
1966 delete prog
->_LinkedShaders
[i
]->symbols
;
1967 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
1970 ralloc_free(mem_ctx
);