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"
71 #include "program/hash_table.h"
73 #include "link_varyings.h"
74 #include "ir_optimization.h"
77 #include "main/shaderobj.h"
81 * Visitor that determines whether or not a variable is ever written.
83 class find_assignment_visitor
: public ir_hierarchical_visitor
{
85 find_assignment_visitor(const char *name
)
86 : name(name
), found(false)
91 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
93 ir_variable
*const var
= ir
->lhs
->variable_referenced();
95 if (strcmp(name
, var
->name
) == 0) {
100 return visit_continue_with_parent
;
103 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
105 exec_list_iterator sig_iter
= ir
->callee
->parameters
.iterator();
106 foreach_iter(exec_list_iterator
, iter
, *ir
) {
107 ir_rvalue
*param_rval
= (ir_rvalue
*)iter
.get();
108 ir_variable
*sig_param
= (ir_variable
*)sig_iter
.get();
110 if (sig_param
->mode
== ir_var_function_out
||
111 sig_param
->mode
== ir_var_function_inout
) {
112 ir_variable
*var
= param_rval
->variable_referenced();
113 if (var
&& strcmp(name
, var
->name
) == 0) {
121 if (ir
->return_deref
!= NULL
) {
122 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
124 if (strcmp(name
, var
->name
) == 0) {
130 return visit_continue_with_parent
;
133 bool variable_found()
139 const char *name
; /**< Find writes to a variable with this name. */
140 bool found
; /**< Was a write to the variable found? */
145 * Visitor that determines whether or not a variable is ever read.
147 class find_deref_visitor
: public ir_hierarchical_visitor
{
149 find_deref_visitor(const char *name
)
150 : name(name
), found(false)
155 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
157 if (strcmp(this->name
, ir
->var
->name
) == 0) {
162 return visit_continue
;
165 bool variable_found() const
171 const char *name
; /**< Find writes to a variable with this name. */
172 bool found
; /**< Was a write to the variable found? */
177 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
181 ralloc_strcat(&prog
->InfoLog
, "error: ");
183 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
186 prog
->LinkStatus
= false;
191 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
195 ralloc_strcat(&prog
->InfoLog
, "error: ");
197 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
204 link_invalidate_variable_locations(gl_shader
*sh
, int input_base
,
207 foreach_list(node
, sh
->ir
) {
208 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
215 case ir_var_shader_in
:
218 case ir_var_shader_out
:
225 /* Only assign locations for generic attributes / varyings / etc.
227 if ((var
->location
>= base
) && !var
->explicit_location
)
230 if ((var
->location
== -1) && !var
->explicit_location
) {
231 var
->is_unmatched_generic_inout
= 1;
232 var
->location_frac
= 0;
234 var
->is_unmatched_generic_inout
= 0;
241 * Determine the number of attribute slots required for a particular type
243 * This code is here because it implements the language rules of a specific
244 * GLSL version. Since it's a property of the language and not a property of
245 * types in general, it doesn't really belong in glsl_type.
248 count_attribute_slots(const glsl_type
*t
)
250 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
252 * "A scalar input counts the same amount against this limit as a vec4,
253 * so applications may want to consider packing groups of four
254 * unrelated float inputs together into a vector to better utilize the
255 * capabilities of the underlying hardware. A matrix input will use up
256 * multiple locations. The number of locations used will equal the
257 * number of columns in the matrix."
259 * The spec does not explicitly say how arrays are counted. However, it
260 * should be safe to assume the total number of slots consumed by an array
261 * is the number of entries in the array multiplied by the number of slots
262 * consumed by a single element of the array.
266 return t
->array_size() * count_attribute_slots(t
->element_type());
269 return t
->matrix_columns
;
276 * Verify that a vertex shader executable meets all semantic requirements.
278 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
281 * \param shader Vertex shader executable to be verified
284 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
285 struct gl_shader
*shader
)
290 /* From the GLSL 1.10 spec, page 48:
292 * "The variable gl_Position is available only in the vertex
293 * language and is intended for writing the homogeneous vertex
294 * position. All executions of a well-formed vertex shader
295 * executable must write a value into this variable. [...] The
296 * variable gl_Position is available only in the vertex
297 * language and is intended for writing the homogeneous vertex
298 * position. All executions of a well-formed vertex shader
299 * executable must write a value into this variable."
301 * while in GLSL 1.40 this text is changed to:
303 * "The variable gl_Position is available only in the vertex
304 * language and is intended for writing the homogeneous vertex
305 * position. It can be written at any time during shader
306 * execution. It may also be read back by a vertex shader
307 * after being written. This value will be used by primitive
308 * assembly, clipping, culling, and other fixed functionality
309 * operations, if present, that operate on primitives after
310 * vertex processing has occurred. Its value is undefined if
311 * the vertex shader executable does not write gl_Position."
313 * GLSL ES 3.00 is similar to GLSL 1.40--failing to write to gl_Position is
316 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
317 find_assignment_visitor
find("gl_Position");
318 find
.run(shader
->ir
);
319 if (!find
.variable_found()) {
320 linker_error(prog
, "vertex shader does not write to `gl_Position'\n");
325 prog
->Vert
.ClipDistanceArraySize
= 0;
327 if (!prog
->IsES
&& prog
->Version
>= 130) {
328 /* From section 7.1 (Vertex Shader Special Variables) of the
331 * "It is an error for a shader to statically write both
332 * gl_ClipVertex and gl_ClipDistance."
334 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
335 * gl_ClipVertex nor gl_ClipDistance.
337 find_assignment_visitor
clip_vertex("gl_ClipVertex");
338 find_assignment_visitor
clip_distance("gl_ClipDistance");
340 clip_vertex
.run(shader
->ir
);
341 clip_distance
.run(shader
->ir
);
342 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
343 linker_error(prog
, "vertex shader writes to both `gl_ClipVertex' "
344 "and `gl_ClipDistance'\n");
347 prog
->Vert
.UsesClipDistance
= clip_distance
.variable_found();
348 ir_variable
*clip_distance_var
=
349 shader
->symbols
->get_variable("gl_ClipDistance");
350 if (clip_distance_var
)
351 prog
->Vert
.ClipDistanceArraySize
= clip_distance_var
->type
->length
;
359 * Verify that a fragment shader executable meets all semantic requirements
361 * \param shader Fragment shader executable to be verified
364 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
365 struct gl_shader
*shader
)
370 find_assignment_visitor
frag_color("gl_FragColor");
371 find_assignment_visitor
frag_data("gl_FragData");
373 frag_color
.run(shader
->ir
);
374 frag_data
.run(shader
->ir
);
376 if (frag_color
.variable_found() && frag_data
.variable_found()) {
377 linker_error(prog
, "fragment shader writes to both "
378 "`gl_FragColor' and `gl_FragData'\n");
387 * Generate a string describing the mode of a variable
390 mode_string(const ir_variable
*var
)
394 return (var
->read_only
) ? "global constant" : "global variable";
396 case ir_var_uniform
: return "uniform";
397 case ir_var_shader_in
: return "shader input";
398 case ir_var_shader_out
: return "shader output";
400 case ir_var_const_in
:
401 case ir_var_temporary
:
403 assert(!"Should not get here.");
404 return "invalid variable";
410 * Perform validation of global variables used across multiple shaders
413 cross_validate_globals(struct gl_shader_program
*prog
,
414 struct gl_shader
**shader_list
,
415 unsigned num_shaders
,
418 /* Examine all of the uniforms in all of the shaders and cross validate
421 glsl_symbol_table variables
;
422 for (unsigned i
= 0; i
< num_shaders
; i
++) {
423 if (shader_list
[i
] == NULL
)
426 foreach_list(node
, shader_list
[i
]->ir
) {
427 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
432 if (uniforms_only
&& (var
->mode
!= ir_var_uniform
))
435 /* Don't cross validate temporaries that are at global scope. These
436 * will eventually get pulled into the shaders 'main'.
438 if (var
->mode
== ir_var_temporary
)
441 /* If a global with this name has already been seen, verify that the
442 * new instance has the same type. In addition, if the globals have
443 * initializers, the values of the initializers must be the same.
445 ir_variable
*const existing
= variables
.get_variable(var
->name
);
446 if (existing
!= NULL
) {
447 if (var
->type
!= existing
->type
) {
448 /* Consider the types to be "the same" if both types are arrays
449 * of the same type and one of the arrays is implicitly sized.
450 * In addition, set the type of the linked variable to the
451 * explicitly sized array.
453 if (var
->type
->is_array()
454 && existing
->type
->is_array()
455 && (var
->type
->fields
.array
== existing
->type
->fields
.array
)
456 && ((var
->type
->length
== 0)
457 || (existing
->type
->length
== 0))) {
458 if (var
->type
->length
!= 0) {
459 existing
->type
= var
->type
;
462 linker_error(prog
, "%s `%s' declared as type "
463 "`%s' and type `%s'\n",
465 var
->name
, var
->type
->name
,
466 existing
->type
->name
);
471 if (var
->explicit_location
) {
472 if (existing
->explicit_location
473 && (var
->location
!= existing
->location
)) {
474 linker_error(prog
, "explicit locations for %s "
475 "`%s' have differing values\n",
476 mode_string(var
), var
->name
);
480 existing
->location
= var
->location
;
481 existing
->explicit_location
= true;
484 /* Validate layout qualifiers for gl_FragDepth.
486 * From the AMD/ARB_conservative_depth specs:
488 * "If gl_FragDepth is redeclared in any fragment shader in a
489 * program, it must be redeclared in all fragment shaders in
490 * that program that have static assignments to
491 * gl_FragDepth. All redeclarations of gl_FragDepth in all
492 * fragment shaders in a single program must have the same set
495 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
496 bool layout_declared
= var
->depth_layout
!= ir_depth_layout_none
;
497 bool layout_differs
=
498 var
->depth_layout
!= existing
->depth_layout
;
500 if (layout_declared
&& layout_differs
) {
502 "All redeclarations of gl_FragDepth in all "
503 "fragment shaders in a single program must have "
504 "the same set of qualifiers.");
507 if (var
->used
&& layout_differs
) {
509 "If gl_FragDepth is redeclared with a layout "
510 "qualifier in any fragment shader, it must be "
511 "redeclared with the same layout qualifier in "
512 "all fragment shaders that have assignments to "
517 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
519 * "If a shared global has multiple initializers, the
520 * initializers must all be constant expressions, and they
521 * must all have the same value. Otherwise, a link error will
522 * result. (A shared global having only one initializer does
523 * not require that initializer to be a constant expression.)"
525 * Previous to 4.20 the GLSL spec simply said that initializers
526 * must have the same value. In this case of non-constant
527 * initializers, this was impossible to determine. As a result,
528 * no vendor actually implemented that behavior. The 4.20
529 * behavior matches the implemented behavior of at least one other
530 * vendor, so we'll implement that for all GLSL versions.
532 if (var
->constant_initializer
!= NULL
) {
533 if (existing
->constant_initializer
!= NULL
) {
534 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
535 linker_error(prog
, "initializers for %s "
536 "`%s' have differing values\n",
537 mode_string(var
), var
->name
);
541 /* If the first-seen instance of a particular uniform did not
542 * have an initializer but a later instance does, copy the
543 * initializer to the version stored in the symbol table.
545 /* FINISHME: This is wrong. The constant_value field should
546 * FINISHME: not be modified! Imagine a case where a shader
547 * FINISHME: without an initializer is linked in two different
548 * FINISHME: programs with shaders that have differing
549 * FINISHME: initializers. Linking with the first will
550 * FINISHME: modify the shader, and linking with the second
551 * FINISHME: will fail.
553 existing
->constant_initializer
=
554 var
->constant_initializer
->clone(ralloc_parent(existing
),
559 if (var
->has_initializer
) {
560 if (existing
->has_initializer
561 && (var
->constant_initializer
== NULL
562 || existing
->constant_initializer
== NULL
)) {
564 "shared global variable `%s' has multiple "
565 "non-constant initializers.\n",
570 /* Some instance had an initializer, so keep track of that. In
571 * this location, all sorts of initializers (constant or
572 * otherwise) will propagate the existence to the variable
573 * stored in the symbol table.
575 existing
->has_initializer
= true;
578 if (existing
->invariant
!= var
->invariant
) {
579 linker_error(prog
, "declarations for %s `%s' have "
580 "mismatching invariant qualifiers\n",
581 mode_string(var
), var
->name
);
584 if (existing
->centroid
!= var
->centroid
) {
585 linker_error(prog
, "declarations for %s `%s' have "
586 "mismatching centroid qualifiers\n",
587 mode_string(var
), var
->name
);
591 variables
.add_variable(var
);
600 * Perform validation of uniforms used across multiple shader stages
603 cross_validate_uniforms(struct gl_shader_program
*prog
)
605 return cross_validate_globals(prog
, prog
->_LinkedShaders
,
606 MESA_SHADER_TYPES
, true);
610 * Accumulates the array of prog->UniformBlocks and checks that all
611 * definitons of blocks agree on their contents.
614 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
)
616 unsigned max_num_uniform_blocks
= 0;
617 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
618 if (prog
->_LinkedShaders
[i
])
619 max_num_uniform_blocks
+= prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
622 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
623 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
625 prog
->UniformBlockStageIndex
[i
] = ralloc_array(prog
, int,
626 max_num_uniform_blocks
);
627 for (unsigned int j
= 0; j
< max_num_uniform_blocks
; j
++)
628 prog
->UniformBlockStageIndex
[i
][j
] = -1;
633 for (unsigned int j
= 0; j
< sh
->NumUniformBlocks
; j
++) {
634 int index
= link_cross_validate_uniform_block(prog
,
635 &prog
->UniformBlocks
,
636 &prog
->NumUniformBlocks
,
637 &sh
->UniformBlocks
[j
]);
640 linker_error(prog
, "uniform block `%s' has mismatching definitions",
641 sh
->UniformBlocks
[j
].Name
);
645 prog
->UniformBlockStageIndex
[i
][index
] = j
;
654 * Populates a shaders symbol table with all global declarations
657 populate_symbol_table(gl_shader
*sh
)
659 sh
->symbols
= new(sh
) glsl_symbol_table
;
661 foreach_list(node
, sh
->ir
) {
662 ir_instruction
*const inst
= (ir_instruction
*) node
;
666 if ((func
= inst
->as_function()) != NULL
) {
667 sh
->symbols
->add_function(func
);
668 } else if ((var
= inst
->as_variable()) != NULL
) {
669 sh
->symbols
->add_variable(var
);
676 * Remap variables referenced in an instruction tree
678 * This is used when instruction trees are cloned from one shader and placed in
679 * another. These trees will contain references to \c ir_variable nodes that
680 * do not exist in the target shader. This function finds these \c ir_variable
681 * references and replaces the references with matching variables in the target
684 * If there is no matching variable in the target shader, a clone of the
685 * \c ir_variable is made and added to the target shader. The new variable is
686 * added to \b both the instruction stream and the symbol table.
688 * \param inst IR tree that is to be processed.
689 * \param symbols Symbol table containing global scope symbols in the
691 * \param instructions Instruction stream where new variable declarations
695 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
698 class remap_visitor
: public ir_hierarchical_visitor
{
700 remap_visitor(struct gl_shader
*target
,
703 this->target
= target
;
704 this->symbols
= target
->symbols
;
705 this->instructions
= target
->ir
;
709 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
711 if (ir
->var
->mode
== ir_var_temporary
) {
712 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
716 return visit_continue
;
719 ir_variable
*const existing
=
720 this->symbols
->get_variable(ir
->var
->name
);
721 if (existing
!= NULL
)
724 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
726 this->symbols
->add_variable(copy
);
727 this->instructions
->push_head(copy
);
731 return visit_continue
;
735 struct gl_shader
*target
;
736 glsl_symbol_table
*symbols
;
737 exec_list
*instructions
;
741 remap_visitor
v(target
, temps
);
748 * Move non-declarations from one instruction stream to another
750 * The intended usage pattern of this function is to pass the pointer to the
751 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
752 * pointer) for \c last and \c false for \c make_copies on the first
753 * call. Successive calls pass the return value of the previous call for
754 * \c last and \c true for \c make_copies.
756 * \param instructions Source instruction stream
757 * \param last Instruction after which new instructions should be
758 * inserted in the target instruction stream
759 * \param make_copies Flag selecting whether instructions in \c instructions
760 * should be copied (via \c ir_instruction::clone) into the
761 * target list or moved.
764 * The new "last" instruction in the target instruction stream. This pointer
765 * is suitable for use as the \c last parameter of a later call to this
769 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
770 bool make_copies
, gl_shader
*target
)
772 hash_table
*temps
= NULL
;
775 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
776 hash_table_pointer_compare
);
778 foreach_list_safe(node
, instructions
) {
779 ir_instruction
*inst
= (ir_instruction
*) node
;
781 if (inst
->as_function())
784 ir_variable
*var
= inst
->as_variable();
785 if ((var
!= NULL
) && (var
->mode
!= ir_var_temporary
))
788 assert(inst
->as_assignment()
790 || inst
->as_if() /* for initializers with the ?: operator */
791 || ((var
!= NULL
) && (var
->mode
== ir_var_temporary
)));
794 inst
= inst
->clone(target
, NULL
);
797 hash_table_insert(temps
, inst
, var
);
799 remap_variables(inst
, target
, temps
);
804 last
->insert_after(inst
);
809 hash_table_dtor(temps
);
815 * Get the function signature for main from a shader
817 static ir_function_signature
*
818 get_main_function_signature(gl_shader
*sh
)
820 ir_function
*const f
= sh
->symbols
->get_function("main");
822 exec_list void_parameters
;
824 /* Look for the 'void main()' signature and ensure that it's defined.
825 * This keeps the linker from accidentally pick a shader that just
826 * contains a prototype for main.
828 * We don't have to check for multiple definitions of main (in multiple
829 * shaders) because that would have already been caught above.
831 ir_function_signature
*sig
= f
->matching_signature(&void_parameters
);
832 if ((sig
!= NULL
) && sig
->is_defined
) {
842 * This class is only used in link_intrastage_shaders() below but declaring
843 * it inside that function leads to compiler warnings with some versions of
846 class array_sizing_visitor
: public ir_hierarchical_visitor
{
848 virtual ir_visitor_status
visit(ir_variable
*var
)
850 if (var
->type
->is_array() && (var
->type
->length
== 0)) {
851 const glsl_type
*type
=
852 glsl_type::get_array_instance(var
->type
->fields
.array
,
853 var
->max_array_access
+ 1);
854 assert(type
!= NULL
);
857 return visit_continue
;
862 * Combine a group of shaders for a single stage to generate a linked shader
865 * If this function is supplied a single shader, it is cloned, and the new
866 * shader is returned.
868 static struct gl_shader
*
869 link_intrastage_shaders(void *mem_ctx
,
870 struct gl_context
*ctx
,
871 struct gl_shader_program
*prog
,
872 struct gl_shader
**shader_list
,
873 unsigned num_shaders
)
875 struct gl_uniform_block
*uniform_blocks
= NULL
;
876 unsigned num_uniform_blocks
= 0;
878 /* Check that global variables defined in multiple shaders are consistent.
880 if (!cross_validate_globals(prog
, shader_list
, num_shaders
, false))
883 /* Check that uniform blocks between shaders for a stage agree. */
884 for (unsigned i
= 0; i
< num_shaders
; i
++) {
885 struct gl_shader
*sh
= shader_list
[i
];
887 for (unsigned j
= 0; j
< sh
->NumUniformBlocks
; j
++) {
888 link_assign_uniform_block_offsets(sh
);
890 int index
= link_cross_validate_uniform_block(mem_ctx
,
893 &sh
->UniformBlocks
[j
]);
895 linker_error(prog
, "uniform block `%s' has mismatching definitions",
896 sh
->UniformBlocks
[j
].Name
);
902 /* Check that there is only a single definition of each function signature
903 * across all shaders.
905 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
906 foreach_list(node
, shader_list
[i
]->ir
) {
907 ir_function
*const f
= ((ir_instruction
*) node
)->as_function();
912 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
913 ir_function
*const other
=
914 shader_list
[j
]->symbols
->get_function(f
->name
);
916 /* If the other shader has no function (and therefore no function
917 * signatures) with the same name, skip to the next shader.
922 foreach_iter (exec_list_iterator
, iter
, *f
) {
923 ir_function_signature
*sig
=
924 (ir_function_signature
*) iter
.get();
926 if (!sig
->is_defined
|| sig
->is_builtin
)
929 ir_function_signature
*other_sig
=
930 other
->exact_matching_signature(& sig
->parameters
);
932 if ((other_sig
!= NULL
) && other_sig
->is_defined
933 && !other_sig
->is_builtin
) {
934 linker_error(prog
, "function `%s' is multiply defined",
943 /* Find the shader that defines main, and make a clone of it.
945 * Starting with the clone, search for undefined references. If one is
946 * found, find the shader that defines it. Clone the reference and add
947 * it to the shader. Repeat until there are no undefined references or
948 * until a reference cannot be resolved.
950 gl_shader
*main
= NULL
;
951 for (unsigned i
= 0; i
< num_shaders
; i
++) {
952 if (get_main_function_signature(shader_list
[i
]) != NULL
) {
953 main
= shader_list
[i
];
959 linker_error(prog
, "%s shader lacks `main'\n",
960 (shader_list
[0]->Type
== GL_VERTEX_SHADER
)
961 ? "vertex" : "fragment");
965 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
966 linked
->ir
= new(linked
) exec_list
;
967 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
969 linked
->UniformBlocks
= uniform_blocks
;
970 linked
->NumUniformBlocks
= num_uniform_blocks
;
971 ralloc_steal(linked
, linked
->UniformBlocks
);
973 populate_symbol_table(linked
);
975 /* The a pointer to the main function in the final linked shader (i.e., the
976 * copy of the original shader that contained the main function).
978 ir_function_signature
*const main_sig
= get_main_function_signature(linked
);
980 /* Move any instructions other than variable declarations or function
981 * declarations into main.
983 exec_node
*insertion_point
=
984 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
987 for (unsigned i
= 0; i
< num_shaders
; i
++) {
988 if (shader_list
[i
] == main
)
991 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
992 insertion_point
, true, linked
);
995 /* Resolve initializers for global variables in the linked shader.
997 unsigned num_linking_shaders
= num_shaders
;
998 for (unsigned i
= 0; i
< num_shaders
; i
++)
999 num_linking_shaders
+= shader_list
[i
]->num_builtins_to_link
;
1001 gl_shader
**linking_shaders
=
1002 (gl_shader
**) calloc(num_linking_shaders
, sizeof(gl_shader
*));
1004 memcpy(linking_shaders
, shader_list
,
1005 sizeof(linking_shaders
[0]) * num_shaders
);
1007 unsigned idx
= num_shaders
;
1008 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1009 memcpy(&linking_shaders
[idx
], shader_list
[i
]->builtins_to_link
,
1010 sizeof(linking_shaders
[0]) * shader_list
[i
]->num_builtins_to_link
);
1011 idx
+= shader_list
[i
]->num_builtins_to_link
;
1014 assert(idx
== num_linking_shaders
);
1016 if (!link_function_calls(prog
, linked
, linking_shaders
,
1017 num_linking_shaders
)) {
1018 ctx
->Driver
.DeleteShader(ctx
, linked
);
1022 free(linking_shaders
);
1025 /* At this point linked should contain all of the linked IR, so
1026 * validate it to make sure nothing went wrong.
1029 validate_ir_tree(linked
->ir
);
1032 /* Make a pass over all variable declarations to ensure that arrays with
1033 * unspecified sizes have a size specified. The size is inferred from the
1034 * max_array_access field.
1036 if (linked
!= NULL
) {
1037 array_sizing_visitor v
;
1046 * Update the sizes of linked shader uniform arrays to the maximum
1049 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1051 * If one or more elements of an array are active,
1052 * GetActiveUniform will return the name of the array in name,
1053 * subject to the restrictions listed above. The type of the array
1054 * is returned in type. The size parameter contains the highest
1055 * array element index used, plus one. The compiler or linker
1056 * determines the highest index used. There will be only one
1057 * active uniform reported by the GL per uniform array.
1061 update_array_sizes(struct gl_shader_program
*prog
)
1063 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1064 if (prog
->_LinkedShaders
[i
] == NULL
)
1067 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
1068 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1070 if ((var
== NULL
) || (var
->mode
!= ir_var_uniform
&&
1071 var
->mode
!= ir_var_shader_in
&&
1072 var
->mode
!= ir_var_shader_out
) ||
1073 !var
->type
->is_array())
1076 /* GL_ARB_uniform_buffer_object says that std140 uniforms
1077 * will not be eliminated. Since we always do std140, just
1078 * don't resize arrays in UBOs.
1080 if (var
->uniform_block
!= -1)
1083 unsigned int size
= var
->max_array_access
;
1084 for (unsigned j
= 0; j
< MESA_SHADER_TYPES
; j
++) {
1085 if (prog
->_LinkedShaders
[j
] == NULL
)
1088 foreach_list(node2
, prog
->_LinkedShaders
[j
]->ir
) {
1089 ir_variable
*other_var
= ((ir_instruction
*) node2
)->as_variable();
1093 if (strcmp(var
->name
, other_var
->name
) == 0 &&
1094 other_var
->max_array_access
> size
) {
1095 size
= other_var
->max_array_access
;
1100 if (size
+ 1 != var
->type
->fields
.array
->length
) {
1101 /* If this is a built-in uniform (i.e., it's backed by some
1102 * fixed-function state), adjust the number of state slots to
1103 * match the new array size. The number of slots per array entry
1104 * is not known. It seems safe to assume that the total number of
1105 * slots is an integer multiple of the number of array elements.
1106 * Determine the number of slots per array element by dividing by
1107 * the old (total) size.
1109 if (var
->num_state_slots
> 0) {
1110 var
->num_state_slots
= (size
+ 1)
1111 * (var
->num_state_slots
/ var
->type
->length
);
1114 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
1116 /* FINISHME: We should update the types of array
1117 * dereferences of this variable now.
1125 * Find a contiguous set of available bits in a bitmask.
1127 * \param used_mask Bits representing used (1) and unused (0) locations
1128 * \param needed_count Number of contiguous bits needed.
1131 * Base location of the available bits on success or -1 on failure.
1134 find_available_slots(unsigned used_mask
, unsigned needed_count
)
1136 unsigned needed_mask
= (1 << needed_count
) - 1;
1137 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
1139 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1140 * cannot optimize possibly infinite loops" for the loop below.
1142 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
1145 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
1146 if ((needed_mask
& ~used_mask
) == needed_mask
)
1157 * Assign locations for either VS inputs for FS outputs
1159 * \param prog Shader program whose variables need locations assigned
1160 * \param target_index Selector for the program target to receive location
1161 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1162 * \c MESA_SHADER_FRAGMENT.
1163 * \param max_index Maximum number of generic locations. This corresponds
1164 * to either the maximum number of draw buffers or the
1165 * maximum number of generic attributes.
1168 * If locations are successfully assigned, true is returned. Otherwise an
1169 * error is emitted to the shader link log and false is returned.
1172 assign_attribute_or_color_locations(gl_shader_program
*prog
,
1173 unsigned target_index
,
1176 /* Mark invalid locations as being used.
1178 unsigned used_locations
= (max_index
>= 32)
1179 ? ~0 : ~((1 << max_index
) - 1);
1181 assert((target_index
== MESA_SHADER_VERTEX
)
1182 || (target_index
== MESA_SHADER_FRAGMENT
));
1184 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
1188 /* Operate in a total of four passes.
1190 * 1. Invalidate the location assignments for all vertex shader inputs.
1192 * 2. Assign locations for inputs that have user-defined (via
1193 * glBindVertexAttribLocation) locations and outputs that have
1194 * user-defined locations (via glBindFragDataLocation).
1196 * 3. Sort the attributes without assigned locations by number of slots
1197 * required in decreasing order. Fragmentation caused by attribute
1198 * locations assigned by the application may prevent large attributes
1199 * from having enough contiguous space.
1201 * 4. Assign locations to any inputs without assigned locations.
1204 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
1205 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
1207 const enum ir_variable_mode direction
=
1208 (target_index
== MESA_SHADER_VERTEX
)
1209 ? ir_var_shader_in
: ir_var_shader_out
;
1212 /* Temporary storage for the set of attributes that need locations assigned.
1218 /* Used below in the call to qsort. */
1219 static int compare(const void *a
, const void *b
)
1221 const temp_attr
*const l
= (const temp_attr
*) a
;
1222 const temp_attr
*const r
= (const temp_attr
*) b
;
1224 /* Reversed because we want a descending order sort below. */
1225 return r
->slots
- l
->slots
;
1229 unsigned num_attr
= 0;
1231 foreach_list(node
, sh
->ir
) {
1232 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1234 if ((var
== NULL
) || (var
->mode
!= (unsigned) direction
))
1237 if (var
->explicit_location
) {
1238 if ((var
->location
>= (int)(max_index
+ generic_base
))
1239 || (var
->location
< 0)) {
1241 "invalid explicit location %d specified for `%s'\n",
1243 ? var
->location
: var
->location
- generic_base
,
1247 } else if (target_index
== MESA_SHADER_VERTEX
) {
1250 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
1251 assert(binding
>= VERT_ATTRIB_GENERIC0
);
1252 var
->location
= binding
;
1253 var
->is_unmatched_generic_inout
= 0;
1255 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
1259 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
1260 assert(binding
>= FRAG_RESULT_DATA0
);
1261 var
->location
= binding
;
1262 var
->is_unmatched_generic_inout
= 0;
1264 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
1270 /* If the variable is not a built-in and has a location statically
1271 * assigned in the shader (presumably via a layout qualifier), make sure
1272 * that it doesn't collide with other assigned locations. Otherwise,
1273 * add it to the list of variables that need linker-assigned locations.
1275 const unsigned slots
= count_attribute_slots(var
->type
);
1276 if (var
->location
!= -1) {
1277 if (var
->location
>= generic_base
&& var
->index
< 1) {
1278 /* From page 61 of the OpenGL 4.0 spec:
1280 * "LinkProgram will fail if the attribute bindings assigned
1281 * by BindAttribLocation do not leave not enough space to
1282 * assign a location for an active matrix attribute or an
1283 * active attribute array, both of which require multiple
1284 * contiguous generic attributes."
1286 * Previous versions of the spec contain similar language but omit
1287 * the bit about attribute arrays.
1289 * Page 61 of the OpenGL 4.0 spec also says:
1291 * "It is possible for an application to bind more than one
1292 * attribute name to the same location. This is referred to as
1293 * aliasing. This will only work if only one of the aliased
1294 * attributes is active in the executable program, or if no
1295 * path through the shader consumes more than one attribute of
1296 * a set of attributes aliased to the same location. A link
1297 * error can occur if the linker determines that every path
1298 * through the shader consumes multiple aliased attributes,
1299 * but implementations are not required to generate an error
1302 * These two paragraphs are either somewhat contradictory, or I
1303 * don't fully understand one or both of them.
1305 /* FINISHME: The code as currently written does not support
1306 * FINISHME: attribute location aliasing (see comment above).
1308 /* Mask representing the contiguous slots that will be used by
1311 const unsigned attr
= var
->location
- generic_base
;
1312 const unsigned use_mask
= (1 << slots
) - 1;
1314 /* Generate a link error if the set of bits requested for this
1315 * attribute overlaps any previously allocated bits.
1317 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
1318 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
1319 ? "vertex shader input" : "fragment shader output";
1321 "insufficient contiguous locations "
1322 "available for %s `%s' %d %d %d", string
,
1323 var
->name
, used_locations
, use_mask
, attr
);
1327 used_locations
|= (use_mask
<< attr
);
1333 to_assign
[num_attr
].slots
= slots
;
1334 to_assign
[num_attr
].var
= var
;
1338 /* If all of the attributes were assigned locations by the application (or
1339 * are built-in attributes with fixed locations), return early. This should
1340 * be the common case.
1345 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
1347 if (target_index
== MESA_SHADER_VERTEX
) {
1348 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1349 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1350 * reserved to prevent it from being automatically allocated below.
1352 find_deref_visitor
find("gl_Vertex");
1354 if (find
.variable_found())
1355 used_locations
|= (1 << 0);
1358 for (unsigned i
= 0; i
< num_attr
; i
++) {
1359 /* Mask representing the contiguous slots that will be used by this
1362 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
1364 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
1367 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
1368 ? "vertex shader input" : "fragment shader output";
1371 "insufficient contiguous locations "
1372 "available for %s `%s'",
1373 string
, to_assign
[i
].var
->name
);
1377 to_assign
[i
].var
->location
= generic_base
+ location
;
1378 to_assign
[i
].var
->is_unmatched_generic_inout
= 0;
1379 used_locations
|= (use_mask
<< location
);
1387 * Demote shader inputs and outputs that are not used in other stages
1390 demote_shader_inputs_and_outputs(gl_shader
*sh
, enum ir_variable_mode mode
)
1392 foreach_list(node
, sh
->ir
) {
1393 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1395 if ((var
== NULL
) || (var
->mode
!= int(mode
)))
1398 /* A shader 'in' or 'out' variable is only really an input or output if
1399 * its value is used by other shader stages. This will cause the variable
1400 * to have a location assigned.
1402 if (var
->is_unmatched_generic_inout
) {
1403 var
->mode
= ir_var_auto
;
1410 * Store the gl_FragDepth layout in the gl_shader_program struct.
1413 store_fragdepth_layout(struct gl_shader_program
*prog
)
1415 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
1419 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
1421 /* We don't look up the gl_FragDepth symbol directly because if
1422 * gl_FragDepth is not used in the shader, it's removed from the IR.
1423 * However, the symbol won't be removed from the symbol table.
1425 * We're only interested in the cases where the variable is NOT removed
1428 foreach_list(node
, ir
) {
1429 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1431 if (var
== NULL
|| var
->mode
!= ir_var_shader_out
) {
1435 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1436 switch (var
->depth_layout
) {
1437 case ir_depth_layout_none
:
1438 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
1440 case ir_depth_layout_any
:
1441 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
1443 case ir_depth_layout_greater
:
1444 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
1446 case ir_depth_layout_less
:
1447 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
1449 case ir_depth_layout_unchanged
:
1450 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
1461 * Validate the resources used by a program versus the implementation limits
1464 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
1466 static const char *const shader_names
[MESA_SHADER_TYPES
] = {
1467 "vertex", "fragment", "geometry"
1470 const unsigned max_samplers
[MESA_SHADER_TYPES
] = {
1471 ctx
->Const
.MaxVertexTextureImageUnits
,
1472 ctx
->Const
.MaxTextureImageUnits
,
1473 ctx
->Const
.MaxGeometryTextureImageUnits
1476 const unsigned max_uniform_components
[MESA_SHADER_TYPES
] = {
1477 ctx
->Const
.VertexProgram
.MaxUniformComponents
,
1478 ctx
->Const
.FragmentProgram
.MaxUniformComponents
,
1479 0 /* FINISHME: Geometry shaders. */
1482 const unsigned max_uniform_blocks
[MESA_SHADER_TYPES
] = {
1483 ctx
->Const
.VertexProgram
.MaxUniformBlocks
,
1484 ctx
->Const
.FragmentProgram
.MaxUniformBlocks
,
1485 ctx
->Const
.GeometryProgram
.MaxUniformBlocks
,
1488 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1489 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1494 if (sh
->num_samplers
> max_samplers
[i
]) {
1495 linker_error(prog
, "Too many %s shader texture samplers",
1499 if (sh
->num_uniform_components
> max_uniform_components
[i
]) {
1500 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
1501 linker_warning(prog
, "Too many %s shader uniform components, "
1502 "but the driver will try to optimize them out; "
1503 "this is non-portable out-of-spec behavior\n",
1506 linker_error(prog
, "Too many %s shader uniform components",
1512 unsigned blocks
[MESA_SHADER_TYPES
] = {0};
1513 unsigned total_uniform_blocks
= 0;
1515 for (unsigned i
= 0; i
< prog
->NumUniformBlocks
; i
++) {
1516 for (unsigned j
= 0; j
< MESA_SHADER_TYPES
; j
++) {
1517 if (prog
->UniformBlockStageIndex
[j
][i
] != -1) {
1519 total_uniform_blocks
++;
1523 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
1524 linker_error(prog
, "Too many combined uniform blocks (%d/%d)",
1525 prog
->NumUniformBlocks
,
1526 ctx
->Const
.MaxCombinedUniformBlocks
);
1528 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1529 if (blocks
[i
] > max_uniform_blocks
[i
]) {
1530 linker_error(prog
, "Too many %s uniform blocks (%d/%d)",
1533 max_uniform_blocks
[i
]);
1540 return prog
->LinkStatus
;
1544 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
1546 tfeedback_decl
*tfeedback_decls
= NULL
;
1547 unsigned num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
1549 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
1551 prog
->LinkStatus
= false;
1552 prog
->Validated
= false;
1553 prog
->_Used
= false;
1555 ralloc_free(prog
->InfoLog
);
1556 prog
->InfoLog
= ralloc_strdup(NULL
, "");
1558 ralloc_free(prog
->UniformBlocks
);
1559 prog
->UniformBlocks
= NULL
;
1560 prog
->NumUniformBlocks
= 0;
1561 for (int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1562 ralloc_free(prog
->UniformBlockStageIndex
[i
]);
1563 prog
->UniformBlockStageIndex
[i
] = NULL
;
1566 /* Separate the shaders into groups based on their type.
1568 struct gl_shader
**vert_shader_list
;
1569 unsigned num_vert_shaders
= 0;
1570 struct gl_shader
**frag_shader_list
;
1571 unsigned num_frag_shaders
= 0;
1573 vert_shader_list
= (struct gl_shader
**)
1574 calloc(2 * prog
->NumShaders
, sizeof(struct gl_shader
*));
1575 frag_shader_list
= &vert_shader_list
[prog
->NumShaders
];
1577 unsigned min_version
= UINT_MAX
;
1578 unsigned max_version
= 0;
1579 const bool is_es_prog
=
1580 (prog
->NumShaders
> 0 && prog
->Shaders
[0]->IsES
) ? true : false;
1581 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
1582 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
1583 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
1585 if (prog
->Shaders
[i
]->IsES
!= is_es_prog
) {
1586 linker_error(prog
, "all shaders must use same shading "
1587 "language version\n");
1591 switch (prog
->Shaders
[i
]->Type
) {
1592 case GL_VERTEX_SHADER
:
1593 vert_shader_list
[num_vert_shaders
] = prog
->Shaders
[i
];
1596 case GL_FRAGMENT_SHADER
:
1597 frag_shader_list
[num_frag_shaders
] = prog
->Shaders
[i
];
1600 case GL_GEOMETRY_SHADER
:
1601 /* FINISHME: Support geometry shaders. */
1602 assert(prog
->Shaders
[i
]->Type
!= GL_GEOMETRY_SHADER
);
1607 /* Previous to GLSL version 1.30, different compilation units could mix and
1608 * match shading language versions. With GLSL 1.30 and later, the versions
1609 * of all shaders must match.
1611 * GLSL ES has never allowed mixing of shading language versions.
1613 if ((is_es_prog
|| max_version
>= 130)
1614 && min_version
!= max_version
) {
1615 linker_error(prog
, "all shaders must use same shading "
1616 "language version\n");
1620 prog
->Version
= max_version
;
1621 prog
->IsES
= is_es_prog
;
1623 for (unsigned int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1624 if (prog
->_LinkedShaders
[i
] != NULL
)
1625 ctx
->Driver
.DeleteShader(ctx
, prog
->_LinkedShaders
[i
]);
1627 prog
->_LinkedShaders
[i
] = NULL
;
1630 /* Link all shaders for a particular stage and validate the result.
1632 if (num_vert_shaders
> 0) {
1633 gl_shader
*const sh
=
1634 link_intrastage_shaders(mem_ctx
, ctx
, prog
, vert_shader_list
,
1640 if (!validate_vertex_shader_executable(prog
, sh
))
1643 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
1647 if (num_frag_shaders
> 0) {
1648 gl_shader
*const sh
=
1649 link_intrastage_shaders(mem_ctx
, ctx
, prog
, frag_shader_list
,
1655 if (!validate_fragment_shader_executable(prog
, sh
))
1658 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
],
1662 /* Here begins the inter-stage linking phase. Some initial validation is
1663 * performed, then locations are assigned for uniforms, attributes, and
1666 if (cross_validate_uniforms(prog
)) {
1669 for (prev
= 0; prev
< MESA_SHADER_TYPES
; prev
++) {
1670 if (prog
->_LinkedShaders
[prev
] != NULL
)
1674 /* Validate the inputs of each stage with the output of the preceding
1677 for (unsigned i
= prev
+ 1; i
< MESA_SHADER_TYPES
; i
++) {
1678 if (prog
->_LinkedShaders
[i
] == NULL
)
1681 if (!cross_validate_outputs_to_inputs(prog
,
1682 prog
->_LinkedShaders
[prev
],
1683 prog
->_LinkedShaders
[i
]))
1689 prog
->LinkStatus
= true;
1692 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
1693 * it before optimization because we want most of the checks to get
1694 * dropped thanks to constant propagation.
1696 * This rule also applies to GLSL ES 3.00.
1698 if (max_version
>= (is_es_prog
? 300 : 130)) {
1699 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
1701 lower_discard_flow(sh
->ir
);
1705 if (!interstage_cross_validate_uniform_blocks(prog
))
1708 /* Do common optimization before assigning storage for attributes,
1709 * uniforms, and varyings. Later optimization could possibly make
1710 * some of that unused.
1712 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1713 if (prog
->_LinkedShaders
[i
] == NULL
)
1716 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
1717 if (!prog
->LinkStatus
)
1720 if (ctx
->ShaderCompilerOptions
[i
].LowerClipDistance
) {
1721 lower_clip_distance(prog
->_LinkedShaders
[i
]);
1724 unsigned max_unroll
= ctx
->ShaderCompilerOptions
[i
].MaxUnrollIterations
;
1726 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false, max_unroll
))
1730 /* Mark all generic shader inputs and outputs as unpaired. */
1731 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] != NULL
) {
1732 link_invalidate_variable_locations(
1733 prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
1734 VERT_ATTRIB_GENERIC0
, VERT_RESULT_VAR0
);
1736 /* FINISHME: Geometry shaders not implemented yet */
1737 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] != NULL
) {
1738 link_invalidate_variable_locations(
1739 prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
],
1740 FRAG_ATTRIB_VAR0
, FRAG_RESULT_DATA0
);
1743 /* FINISHME: The value of the max_attribute_index parameter is
1744 * FINISHME: implementation dependent based on the value of
1745 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1746 * FINISHME: at least 16, so hardcode 16 for now.
1748 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_VERTEX
, 16)) {
1752 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_FRAGMENT
, MAX2(ctx
->Const
.MaxDrawBuffers
, ctx
->Const
.MaxDualSourceDrawBuffers
))) {
1757 for (prev
= 0; prev
< MESA_SHADER_TYPES
; prev
++) {
1758 if (prog
->_LinkedShaders
[prev
] != NULL
)
1762 if (num_tfeedback_decls
!= 0) {
1763 /* From GL_EXT_transform_feedback:
1764 * A program will fail to link if:
1766 * * the <count> specified by TransformFeedbackVaryingsEXT is
1767 * non-zero, but the program object has no vertex or geometry
1770 if (prev
>= MESA_SHADER_FRAGMENT
) {
1771 linker_error(prog
, "Transform feedback varyings specified, but "
1772 "no vertex or geometry shader is present.");
1776 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
1777 prog
->TransformFeedback
.NumVarying
);
1778 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
1779 prog
->TransformFeedback
.VaryingNames
,
1784 for (unsigned i
= prev
+ 1; i
< MESA_SHADER_TYPES
; i
++) {
1785 if (prog
->_LinkedShaders
[i
] == NULL
)
1788 if (!assign_varying_locations(
1789 ctx
, mem_ctx
, prog
, prog
->_LinkedShaders
[prev
], prog
->_LinkedShaders
[i
],
1790 i
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
1797 if (prev
!= MESA_SHADER_FRAGMENT
&& num_tfeedback_decls
!= 0) {
1798 /* There was no fragment shader, but we still have to assign varying
1799 * locations for use by transform feedback.
1801 if (!assign_varying_locations(
1802 ctx
, mem_ctx
, prog
, prog
->_LinkedShaders
[prev
], NULL
, num_tfeedback_decls
,
1807 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
))
1810 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] != NULL
) {
1811 demote_shader_inputs_and_outputs(prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
1814 /* Eliminate code that is now dead due to unused vertex outputs being
1817 while (do_dead_code(prog
->_LinkedShaders
[MESA_SHADER_VERTEX
]->ir
, false))
1821 if (prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
] != NULL
) {
1822 gl_shader
*const sh
= prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
];
1824 demote_shader_inputs_and_outputs(sh
, ir_var_shader_in
);
1825 demote_shader_inputs_and_outputs(sh
, ir_var_shader_out
);
1827 /* Eliminate code that is now dead due to unused geometry outputs being
1830 while (do_dead_code(prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
]->ir
, false))
1834 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] != NULL
) {
1835 gl_shader
*const sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
1837 demote_shader_inputs_and_outputs(sh
, ir_var_shader_in
);
1839 /* Eliminate code that is now dead due to unused fragment inputs being
1840 * demoted. This shouldn't actually do anything other than remove
1841 * declarations of the (now unused) global variables.
1843 while (do_dead_code(prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
, false))
1847 update_array_sizes(prog
);
1848 link_assign_uniform_locations(prog
);
1849 store_fragdepth_layout(prog
);
1851 if (!check_resources(ctx
, prog
))
1854 /* OpenGL ES requires that a vertex shader and a fragment shader both be
1855 * present in a linked program. By checking prog->IsES, we also
1856 * catch the GL_ARB_ES2_compatibility case.
1858 if (!prog
->InternalSeparateShader
&&
1859 (ctx
->API
== API_OPENGLES2
|| prog
->IsES
)) {
1860 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
1861 linker_error(prog
, "program lacks a vertex shader\n");
1862 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
1863 linker_error(prog
, "program lacks a fragment shader\n");
1867 /* FINISHME: Assign fragment shader output locations. */
1870 free(vert_shader_list
);
1872 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1873 if (prog
->_LinkedShaders
[i
] == NULL
)
1876 /* Retain any live IR, but trash the rest. */
1877 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
1879 /* The symbol table in the linked shaders may contain references to
1880 * variables that were removed (e.g., unused uniforms). Since it may
1881 * contain junk, there is no possible valid use. Delete it and set the
1884 delete prog
->_LinkedShaders
[i
]->symbols
;
1885 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
1888 ralloc_free(mem_ctx
);