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>
75 #include "main/mtypes.h"
76 #include "main/macros.h"
77 #include "glsl_symbol_table.h"
80 #include "hash_table.h"
81 #include "shader_api.h"
83 #include "ir_optimization.h"
86 * Visitor that determines whether or not a variable is ever written.
88 class find_assignment_visitor
: public ir_hierarchical_visitor
{
90 find_assignment_visitor(const char *name
)
91 : name(name
), found(false)
96 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
98 ir_variable
*const var
= ir
->lhs
->variable_referenced();
100 if (strcmp(name
, var
->name
) == 0) {
105 return visit_continue_with_parent
;
108 bool variable_found()
114 const char *name
; /**< Find writes to a variable with this name. */
115 bool found
; /**< Was a write to the variable found? */
120 linker_error_printf(gl_shader_program
*prog
, const char *fmt
, ...)
124 prog
->InfoLog
= talloc_strdup_append(prog
->InfoLog
, "error: ");
126 prog
->InfoLog
= talloc_vasprintf_append(prog
->InfoLog
, fmt
, ap
);
132 invalidate_variable_locations(gl_shader
*sh
, enum ir_variable_mode mode
,
135 foreach_list(node
, sh
->ir
) {
136 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
138 if ((var
== NULL
) || (var
->mode
!= (unsigned) mode
))
141 /* Only assign locations for generic attributes / varyings / etc.
143 if (var
->location
>= generic_base
)
150 * Determine the number of attribute slots required for a particular type
152 * This code is here because it implements the language rules of a specific
153 * GLSL version. Since it's a property of the language and not a property of
154 * types in general, it doesn't really belong in glsl_type.
157 count_attribute_slots(const glsl_type
*t
)
159 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
161 * "A scalar input counts the same amount against this limit as a vec4,
162 * so applications may want to consider packing groups of four
163 * unrelated float inputs together into a vector to better utilize the
164 * capabilities of the underlying hardware. A matrix input will use up
165 * multiple locations. The number of locations used will equal the
166 * number of columns in the matrix."
168 * The spec does not explicitly say how arrays are counted. However, it
169 * should be safe to assume the total number of slots consumed by an array
170 * is the number of entries in the array multiplied by the number of slots
171 * consumed by a single element of the array.
175 return t
->array_size() * count_attribute_slots(t
->element_type());
178 return t
->matrix_columns
;
185 * Verify that a vertex shader executable meets all semantic requirements
187 * \param shader Vertex shader executable to be verified
190 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
191 struct gl_shader
*shader
)
196 find_assignment_visitor
find("gl_Position");
197 find
.run(shader
->ir
);
198 if (!find
.variable_found()) {
199 linker_error_printf(prog
,
200 "vertex shader does not write to `gl_Position'\n");
209 * Verify that a fragment shader executable meets all semantic requirements
211 * \param shader Fragment shader executable to be verified
214 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
215 struct gl_shader
*shader
)
220 find_assignment_visitor
frag_color("gl_FragColor");
221 find_assignment_visitor
frag_data("gl_FragData");
223 frag_color
.run(shader
->ir
);
224 frag_data
.run(shader
->ir
);
226 if (frag_color
.variable_found() && frag_data
.variable_found()) {
227 linker_error_printf(prog
, "fragment shader writes to both "
228 "`gl_FragColor' and `gl_FragData'\n");
237 * Generate a string describing the mode of a variable
240 mode_string(const ir_variable
*var
)
244 return (var
->read_only
) ? "global constant" : "global variable";
246 case ir_var_uniform
: return "uniform";
247 case ir_var_in
: return "shader input";
248 case ir_var_out
: return "shader output";
249 case ir_var_inout
: return "shader inout";
251 case ir_var_temporary
:
253 assert(!"Should not get here.");
254 return "invalid variable";
260 * Perform validation of global variables used across multiple shaders
263 cross_validate_globals(struct gl_shader_program
*prog
,
264 struct gl_shader
**shader_list
,
265 unsigned num_shaders
,
268 /* Examine all of the uniforms in all of the shaders and cross validate
271 glsl_symbol_table variables
;
272 for (unsigned i
= 0; i
< num_shaders
; i
++) {
273 foreach_list(node
, shader_list
[i
]->ir
) {
274 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
279 if (uniforms_only
&& (var
->mode
!= ir_var_uniform
))
282 /* Don't cross validate temporaries that are at global scope. These
283 * will eventually get pulled into the shaders 'main'.
285 if (var
->mode
== ir_var_temporary
)
288 /* If a global with this name has already been seen, verify that the
289 * new instance has the same type. In addition, if the globals have
290 * initializers, the values of the initializers must be the same.
292 ir_variable
*const existing
= variables
.get_variable(var
->name
);
293 if (existing
!= NULL
) {
294 if (var
->type
!= existing
->type
) {
295 linker_error_printf(prog
, "%s `%s' declared as type "
296 "`%s' and type `%s'\n",
298 var
->name
, var
->type
->name
,
299 existing
->type
->name
);
303 /* FINISHME: Handle non-constant initializers.
305 if (var
->constant_value
!= NULL
) {
306 if (existing
->constant_value
!= NULL
) {
307 if (!var
->constant_value
->has_value(existing
->constant_value
)) {
308 linker_error_printf(prog
, "initializers for %s "
309 "`%s' have differing values\n",
310 mode_string(var
), var
->name
);
314 /* If the first-seen instance of a particular uniform did not
315 * have an initializer but a later instance does, copy the
316 * initializer to the version stored in the symbol table.
318 /* FINISHME: This is wrong. The constant_value field should
319 * FINISHME: not be modified! Imagine a case where a shader
320 * FINISHME: without an initializer is linked in two different
321 * FINISHME: programs with shaders that have differing
322 * FINISHME: initializers. Linking with the first will
323 * FINISHME: modify the shader, and linking with the second
324 * FINISHME: will fail.
326 existing
->constant_value
= var
->constant_value
->clone(NULL
);
329 variables
.add_variable(var
->name
, var
);
338 * Perform validation of uniforms used across multiple shader stages
341 cross_validate_uniforms(struct gl_shader_program
*prog
)
343 return cross_validate_globals(prog
, prog
->_LinkedShaders
,
344 prog
->_NumLinkedShaders
, true);
349 * Validate that outputs from one stage match inputs of another
352 cross_validate_outputs_to_inputs(struct gl_shader_program
*prog
,
353 gl_shader
*producer
, gl_shader
*consumer
)
355 glsl_symbol_table parameters
;
356 /* FINISHME: Figure these out dynamically. */
357 const char *const producer_stage
= "vertex";
358 const char *const consumer_stage
= "fragment";
360 /* Find all shader outputs in the "producer" stage.
362 foreach_list(node
, producer
->ir
) {
363 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
365 /* FINISHME: For geometry shaders, this should also look for inout
366 * FINISHME: variables.
368 if ((var
== NULL
) || (var
->mode
!= ir_var_out
))
371 parameters
.add_variable(var
->name
, var
);
375 /* Find all shader inputs in the "consumer" stage. Any variables that have
376 * matching outputs already in the symbol table must have the same type and
379 foreach_list(node
, consumer
->ir
) {
380 ir_variable
*const input
= ((ir_instruction
*) node
)->as_variable();
382 /* FINISHME: For geometry shaders, this should also look for inout
383 * FINISHME: variables.
385 if ((input
== NULL
) || (input
->mode
!= ir_var_in
))
388 ir_variable
*const output
= parameters
.get_variable(input
->name
);
389 if (output
!= NULL
) {
390 /* Check that the types match between stages.
392 if (input
->type
!= output
->type
) {
393 linker_error_printf(prog
,
394 "%s shader output `%s' delcared as "
395 "type `%s', but %s shader input declared "
397 producer_stage
, output
->name
,
399 consumer_stage
, input
->type
->name
);
403 /* Check that all of the qualifiers match between stages.
405 if (input
->centroid
!= output
->centroid
) {
406 linker_error_printf(prog
,
407 "%s shader output `%s' %s centroid qualifier, "
408 "but %s shader input %s centroid qualifier\n",
411 (output
->centroid
) ? "has" : "lacks",
413 (input
->centroid
) ? "has" : "lacks");
417 if (input
->invariant
!= output
->invariant
) {
418 linker_error_printf(prog
,
419 "%s shader output `%s' %s invariant qualifier, "
420 "but %s shader input %s invariant qualifier\n",
423 (output
->invariant
) ? "has" : "lacks",
425 (input
->invariant
) ? "has" : "lacks");
429 if (input
->interpolation
!= output
->interpolation
) {
430 linker_error_printf(prog
,
431 "%s shader output `%s' specifies %s "
432 "interpolation qualifier, "
433 "but %s shader input specifies %s "
434 "interpolation qualifier\n",
437 output
->interpolation_string(),
439 input
->interpolation_string());
450 * Populates a shaders symbol table with all global declarations
453 populate_symbol_table(gl_shader
*sh
)
455 sh
->symbols
= new(sh
) glsl_symbol_table
;
457 foreach_list(node
, sh
->ir
) {
458 ir_instruction
*const inst
= (ir_instruction
*) node
;
462 if ((func
= inst
->as_function()) != NULL
) {
463 sh
->symbols
->add_function(func
->name
, func
);
464 } else if ((var
= inst
->as_variable()) != NULL
) {
465 sh
->symbols
->add_variable(var
->name
, var
);
472 * Remap variables referenced in an instruction tree
474 * This is used when instruction trees are cloned from one shader and placed in
475 * another. These trees will contain references to \c ir_variable nodes that
476 * do not exist in the target shader. This function finds these \c ir_variable
477 * references and replaces the references with matching variables in the target
480 * If there is no matching variable in the target shader, a clone of the
481 * \c ir_variable is made and added to the target shader. The new variable is
482 * added to \b both the instruction stream and the symbol table.
484 * \param inst IR tree that is to be processed.
485 * \param symbols Symbol table containing global scope symbols in the
487 * \param instructions Instruction stream where new variable declarations
491 remap_variables(ir_instruction
*inst
, glsl_symbol_table
*symbols
,
492 exec_list
*instructions
, hash_table
*temps
)
494 class remap_visitor
: public ir_hierarchical_visitor
{
496 remap_visitor(glsl_symbol_table
*symbols
, exec_list
*instructions
,
499 this->symbols
= symbols
;
500 this->instructions
= instructions
;
504 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
506 if (ir
->var
->mode
== ir_var_temporary
) {
507 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
511 return visit_continue
;
514 ir_variable
*const existing
=
515 this->symbols
->get_variable(ir
->var
->name
);
516 if (existing
!= NULL
)
519 ir_variable
*copy
= ir
->var
->clone(NULL
);
521 this->symbols
->add_variable(copy
->name
, copy
);
522 this->instructions
->push_head(copy
);
526 return visit_continue
;
530 glsl_symbol_table
*symbols
;
531 exec_list
*instructions
;
535 remap_visitor
v(symbols
, instructions
, temps
);
542 * Move non-declarations from one instruction stream to another
544 * The intended usage pattern of this function is to pass the pointer to the
545 * head sentinal of a list (i.e., a pointer to the list cast to an \c exec_node
546 * pointer) for \c last and \c false for \c make_copies on the first
547 * call. Successive calls pass the return value of the previous call for
548 * \c last and \c true for \c make_copies.
550 * \param instructions Source instruction stream
551 * \param last Instruction after which new instructions should be
552 * inserted in the target instruction stream
553 * \param make_copies Flag selecting whether instructions in \c instructions
554 * should be copied (via \c ir_instruction::clone) into the
555 * target list or moved.
558 * The new "last" instruction in the target instruction stream. This pointer
559 * is suitable for use as the \c last parameter of a later call to this
563 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
564 bool make_copies
, gl_shader
*target
)
566 hash_table
*temps
= NULL
;
569 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
570 hash_table_pointer_compare
);
572 foreach_list_safe(node
, instructions
) {
573 ir_instruction
*inst
= (ir_instruction
*) node
;
575 if (inst
->as_function())
578 ir_variable
*var
= inst
->as_variable();
579 if ((var
!= NULL
) && (var
->mode
!= ir_var_temporary
))
582 assert(inst
->as_assignment()
583 || ((var
!= NULL
) && (var
->mode
== ir_var_temporary
)));
586 inst
= inst
->clone(NULL
);
589 hash_table_insert(temps
, inst
, var
);
591 remap_variables(inst
, target
->symbols
, target
->ir
, temps
);
596 last
->insert_after(inst
);
601 hash_table_dtor(temps
);
607 * Get the function signature for main from a shader
609 static ir_function_signature
*
610 get_main_function_signature(gl_shader
*sh
)
612 ir_function
*const f
= sh
->symbols
->get_function("main");
614 exec_list void_parameters
;
616 /* Look for the 'void main()' signature and ensure that it's defined.
617 * This keeps the linker from accidentally pick a shader that just
618 * contains a prototype for main.
620 * We don't have to check for multiple definitions of main (in multiple
621 * shaders) because that would have already been caught above.
623 ir_function_signature
*sig
= f
->matching_signature(&void_parameters
);
624 if ((sig
!= NULL
) && sig
->is_defined
) {
634 * Combine a group of shaders for a single stage to generate a linked shader
637 * If this function is supplied a single shader, it is cloned, and the new
638 * shader is returned.
640 static struct gl_shader
*
641 link_intrastage_shaders(struct gl_shader_program
*prog
,
642 struct gl_shader
**shader_list
,
643 unsigned num_shaders
)
645 /* Check that global variables defined in multiple shaders are consistent.
647 if (!cross_validate_globals(prog
, shader_list
, num_shaders
, false))
650 /* Check that there is only a single definition of each function signature
651 * across all shaders.
653 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
654 foreach_list(node
, shader_list
[i
]->ir
) {
655 ir_function
*const f
= ((ir_instruction
*) node
)->as_function();
660 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
661 ir_function
*const other
=
662 shader_list
[j
]->symbols
->get_function(f
->name
);
664 /* If the other shader has no function (and therefore no function
665 * signatures) with the same name, skip to the next shader.
670 foreach_iter (exec_list_iterator
, iter
, *f
) {
671 ir_function_signature
*sig
=
672 (ir_function_signature
*) iter
.get();
674 if (!sig
->is_defined
|| sig
->is_built_in
)
677 ir_function_signature
*other_sig
=
678 other
->exact_matching_signature(& sig
->parameters
);
680 if ((other_sig
!= NULL
) && other_sig
->is_defined
681 && !other_sig
->is_built_in
) {
682 linker_error_printf(prog
,
683 "function `%s' is multiply defined",
692 /* Find the shader that defines main, and make a clone of it.
694 * Starting with the clone, search for undefined references. If one is
695 * found, find the shader that defines it. Clone the reference and add
696 * it to the shader. Repeat until there are no undefined references or
697 * until a reference cannot be resolved.
699 gl_shader
*main
= NULL
;
700 for (unsigned i
= 0; i
< num_shaders
; i
++) {
701 if (get_main_function_signature(shader_list
[i
]) != NULL
) {
702 main
= shader_list
[i
];
708 linker_error_printf(prog
, "%s shader lacks `main'\n",
709 (shader_list
[0]->Type
== GL_VERTEX_SHADER
)
710 ? "vertex" : "fragment");
714 gl_shader
*const linked
= _mesa_new_shader(NULL
, 0, main
->Type
);
715 linked
->ir
= new(linked
) exec_list
;
716 clone_ir_list(linked
->ir
, main
->ir
);
718 populate_symbol_table(linked
);
720 /* The a pointer to the main function in the final linked shader (i.e., the
721 * copy of the original shader that contained the main function).
723 ir_function_signature
*const main_sig
= get_main_function_signature(linked
);
725 /* Move any instructions other than variable declarations or function
726 * declarations into main.
728 exec_node
*insertion_point
=
729 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
732 for (unsigned i
= 0; i
< num_shaders
; i
++) {
733 if (shader_list
[i
] == main
)
736 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
737 insertion_point
, true, linked
);
740 /* Resolve initializers for global variables in the linked shader.
742 link_function_calls(prog
, linked
, shader_list
, num_shaders
);
748 struct uniform_node
{
750 struct gl_uniform
*u
;
755 assign_uniform_locations(struct gl_shader_program
*prog
)
759 unsigned total_uniforms
= 0;
760 hash_table
*ht
= hash_table_ctor(32, hash_table_string_hash
,
761 hash_table_string_compare
);
763 for (unsigned i
= 0; i
< prog
->_NumLinkedShaders
; i
++) {
764 unsigned next_position
= 0;
766 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
767 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
769 if ((var
== NULL
) || (var
->mode
!= ir_var_uniform
))
772 const unsigned vec4_slots
= (var
->component_slots() + 3) / 4;
773 assert(vec4_slots
!= 0);
775 uniform_node
*n
= (uniform_node
*) hash_table_find(ht
, var
->name
);
777 n
= (uniform_node
*) calloc(1, sizeof(struct uniform_node
));
778 n
->u
= (gl_uniform
*) calloc(vec4_slots
, sizeof(struct gl_uniform
));
779 n
->slots
= vec4_slots
;
781 n
->u
[0].Name
= strdup(var
->name
);
782 for (unsigned j
= 1; j
< vec4_slots
; j
++)
783 n
->u
[j
].Name
= n
->u
[0].Name
;
785 hash_table_insert(ht
, n
, n
->u
[0].Name
);
786 uniforms
.push_tail(& n
->link
);
787 total_uniforms
+= vec4_slots
;
790 if (var
->constant_value
!= NULL
)
791 for (unsigned j
= 0; j
< vec4_slots
; j
++)
792 n
->u
[j
].Initialized
= true;
794 var
->location
= next_position
;
796 for (unsigned j
= 0; j
< vec4_slots
; j
++) {
797 switch (prog
->_LinkedShaders
[i
]->Type
) {
798 case GL_VERTEX_SHADER
:
799 n
->u
[j
].VertPos
= next_position
;
801 case GL_FRAGMENT_SHADER
:
802 n
->u
[j
].FragPos
= next_position
;
804 case GL_GEOMETRY_SHADER
:
805 /* FINISHME: Support geometry shaders. */
806 assert(prog
->_LinkedShaders
[i
]->Type
!= GL_GEOMETRY_SHADER
);
815 gl_uniform_list
*ul
= (gl_uniform_list
*)
816 calloc(1, sizeof(gl_uniform_list
));
818 ul
->Size
= total_uniforms
;
819 ul
->NumUniforms
= total_uniforms
;
820 ul
->Uniforms
= (gl_uniform
*) calloc(total_uniforms
, sizeof(gl_uniform
));
824 for (uniform_node
*node
= (uniform_node
*) uniforms
.head
825 ; node
->link
.next
!= NULL
827 next
= (uniform_node
*) node
->link
.next
;
830 memcpy(&ul
->Uniforms
[idx
], node
->u
, sizeof(gl_uniform
) * node
->slots
);
844 * Find a contiguous set of available bits in a bitmask
846 * \param used_mask Bits representing used (1) and unused (0) locations
847 * \param needed_count Number of contiguous bits needed.
850 * Base location of the available bits on success or -1 on failure.
853 find_available_slots(unsigned used_mask
, unsigned needed_count
)
855 unsigned needed_mask
= (1 << needed_count
) - 1;
856 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
858 /* The comparison to 32 is redundant, but without it GCC emits "warning:
859 * cannot optimize possibly infinite loops" for the loop below.
861 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
864 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
865 if ((needed_mask
& ~used_mask
) == needed_mask
)
876 assign_attribute_locations(gl_shader_program
*prog
, unsigned max_attribute_index
)
878 /* Mark invalid attribute locations as being used.
880 unsigned used_locations
= (max_attribute_index
>= 32)
881 ? ~0 : ~((1 << max_attribute_index
) - 1);
883 gl_shader
*const sh
= prog
->_LinkedShaders
[0];
884 assert(sh
->Type
== GL_VERTEX_SHADER
);
886 /* Operate in a total of four passes.
888 * 1. Invalidate the location assignments for all vertex shader inputs.
890 * 2. Assign locations for inputs that have user-defined (via
891 * glBindVertexAttribLocation) locatoins.
893 * 3. Sort the attributes without assigned locations by number of slots
894 * required in decreasing order. Fragmentation caused by attribute
895 * locations assigned by the application may prevent large attributes
896 * from having enough contiguous space.
898 * 4. Assign locations to any inputs without assigned locations.
901 invalidate_variable_locations(sh
, ir_var_in
, VERT_ATTRIB_GENERIC0
);
903 if (prog
->Attributes
!= NULL
) {
904 for (unsigned i
= 0; i
< prog
->Attributes
->NumParameters
; i
++) {
905 ir_variable
*const var
=
906 sh
->symbols
->get_variable(prog
->Attributes
->Parameters
[i
].Name
);
908 /* Note: attributes that occupy multiple slots, such as arrays or
909 * matrices, may appear in the attrib array multiple times.
911 if ((var
== NULL
) || (var
->location
!= -1))
914 /* From page 61 of the OpenGL 4.0 spec:
916 * "LinkProgram will fail if the attribute bindings assigned by
917 * BindAttribLocation do not leave not enough space to assign a
918 * location for an active matrix attribute or an active attribute
919 * array, both of which require multiple contiguous generic
922 * Previous versions of the spec contain similar language but omit the
923 * bit about attribute arrays.
925 * Page 61 of the OpenGL 4.0 spec also says:
927 * "It is possible for an application to bind more than one
928 * attribute name to the same location. This is referred to as
929 * aliasing. This will only work if only one of the aliased
930 * attributes is active in the executable program, or if no path
931 * through the shader consumes more than one attribute of a set
932 * of attributes aliased to the same location. A link error can
933 * occur if the linker determines that every path through the
934 * shader consumes multiple aliased attributes, but
935 * implementations are not required to generate an error in this
938 * These two paragraphs are either somewhat contradictory, or I don't
939 * fully understand one or both of them.
941 /* FINISHME: The code as currently written does not support attribute
942 * FINISHME: location aliasing (see comment above).
944 const int attr
= prog
->Attributes
->Parameters
[i
].StateIndexes
[0];
945 const unsigned slots
= count_attribute_slots(var
->type
);
947 /* Mask representing the contiguous slots that will be used by this
950 const unsigned use_mask
= (1 << slots
) - 1;
952 /* Generate a link error if the set of bits requested for this
953 * attribute overlaps any previously allocated bits.
955 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
956 linker_error_printf(prog
,
957 "insufficient contiguous attribute locations "
958 "available for vertex shader input `%s'",
963 var
->location
= VERT_ATTRIB_GENERIC0
+ attr
;
964 used_locations
|= (use_mask
<< attr
);
968 /* Temporary storage for the set of attributes that need locations assigned.
974 /* Used below in the call to qsort. */
975 static int compare(const void *a
, const void *b
)
977 const temp_attr
*const l
= (const temp_attr
*) a
;
978 const temp_attr
*const r
= (const temp_attr
*) b
;
980 /* Reversed because we want a descending order sort below. */
981 return r
->slots
- l
->slots
;
985 unsigned num_attr
= 0;
987 foreach_list(node
, sh
->ir
) {
988 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
990 if ((var
== NULL
) || (var
->mode
!= ir_var_in
))
993 /* The location was explicitly assigned, nothing to do here.
995 if (var
->location
!= -1)
998 to_assign
[num_attr
].slots
= count_attribute_slots(var
->type
);
999 to_assign
[num_attr
].var
= var
;
1003 /* If all of the attributes were assigned locations by the application (or
1004 * are built-in attributes with fixed locations), return early. This should
1005 * be the common case.
1010 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
1012 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
1013 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
1014 * to prevent it from being automatically allocated below.
1016 used_locations
|= (1 << 0);
1018 for (unsigned i
= 0; i
< num_attr
; i
++) {
1019 /* Mask representing the contiguous slots that will be used by this
1022 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
1024 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
1027 linker_error_printf(prog
,
1028 "insufficient contiguous attribute locations "
1029 "available for vertex shader input `%s'",
1030 to_assign
[i
].var
->name
);
1034 to_assign
[i
].var
->location
= VERT_ATTRIB_GENERIC0
+ location
;
1035 used_locations
|= (use_mask
<< location
);
1043 assign_varying_locations(gl_shader
*producer
, gl_shader
*consumer
)
1045 /* FINISHME: Set dynamically when geometry shader support is added. */
1046 unsigned output_index
= VERT_RESULT_VAR0
;
1047 unsigned input_index
= FRAG_ATTRIB_VAR0
;
1049 /* Operate in a total of three passes.
1051 * 1. Assign locations for any matching inputs and outputs.
1053 * 2. Mark output variables in the producer that do not have locations as
1054 * not being outputs. This lets the optimizer eliminate them.
1056 * 3. Mark input variables in the consumer that do not have locations as
1057 * not being inputs. This lets the optimizer eliminate them.
1060 invalidate_variable_locations(producer
, ir_var_out
, VERT_RESULT_VAR0
);
1061 invalidate_variable_locations(consumer
, ir_var_in
, FRAG_ATTRIB_VAR0
);
1063 foreach_list(node
, producer
->ir
) {
1064 ir_variable
*const output_var
= ((ir_instruction
*) node
)->as_variable();
1066 if ((output_var
== NULL
) || (output_var
->mode
!= ir_var_out
)
1067 || (output_var
->location
!= -1))
1070 ir_variable
*const input_var
=
1071 consumer
->symbols
->get_variable(output_var
->name
);
1073 if ((input_var
== NULL
) || (input_var
->mode
!= ir_var_in
))
1076 assert(input_var
->location
== -1);
1078 /* FINISHME: Location assignment will need some changes when arrays,
1079 * FINISHME: matrices, and structures are allowed as shader inputs /
1080 * FINISHME: outputs.
1082 output_var
->location
= output_index
;
1083 input_var
->location
= input_index
;
1089 foreach_list(node
, producer
->ir
) {
1090 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1092 if ((var
== NULL
) || (var
->mode
!= ir_var_out
))
1095 /* An 'out' variable is only really a shader output if its value is read
1096 * by the following stage.
1098 if (var
->location
== -1) {
1099 var
->shader_out
= false;
1100 var
->mode
= ir_var_auto
;
1104 foreach_list(node
, consumer
->ir
) {
1105 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1107 if ((var
== NULL
) || (var
->mode
!= ir_var_in
))
1110 /* An 'in' variable is only really a shader input if its value is written
1111 * by the previous stage.
1113 var
->shader_in
= (var
->location
!= -1);
1119 link_shaders(struct gl_shader_program
*prog
)
1121 prog
->LinkStatus
= false;
1122 prog
->Validated
= false;
1123 prog
->_Used
= false;
1125 if (prog
->InfoLog
!= NULL
)
1126 talloc_free(prog
->InfoLog
);
1128 prog
->InfoLog
= talloc_strdup(NULL
, "");
1130 /* Separate the shaders into groups based on their type.
1132 struct gl_shader
**vert_shader_list
;
1133 unsigned num_vert_shaders
= 0;
1134 struct gl_shader
**frag_shader_list
;
1135 unsigned num_frag_shaders
= 0;
1137 vert_shader_list
= (struct gl_shader
**)
1138 calloc(2 * prog
->NumShaders
, sizeof(struct gl_shader
*));
1139 frag_shader_list
= &vert_shader_list
[prog
->NumShaders
];
1141 unsigned min_version
= UINT_MAX
;
1142 unsigned max_version
= 0;
1143 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
1144 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
1145 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
1147 switch (prog
->Shaders
[i
]->Type
) {
1148 case GL_VERTEX_SHADER
:
1149 vert_shader_list
[num_vert_shaders
] = prog
->Shaders
[i
];
1152 case GL_FRAGMENT_SHADER
:
1153 frag_shader_list
[num_frag_shaders
] = prog
->Shaders
[i
];
1156 case GL_GEOMETRY_SHADER
:
1157 /* FINISHME: Support geometry shaders. */
1158 assert(prog
->Shaders
[i
]->Type
!= GL_GEOMETRY_SHADER
);
1163 /* Previous to GLSL version 1.30, different compilation units could mix and
1164 * match shading language versions. With GLSL 1.30 and later, the versions
1165 * of all shaders must match.
1167 assert(min_version
>= 110);
1168 assert(max_version
<= 130);
1169 if ((max_version
>= 130) && (min_version
!= max_version
)) {
1170 linker_error_printf(prog
, "all shaders must use same shading "
1171 "language version\n");
1175 prog
->Version
= max_version
;
1177 /* Link all shaders for a particular stage and validate the result.
1179 prog
->_NumLinkedShaders
= 0;
1180 if (num_vert_shaders
> 0) {
1181 gl_shader
*const sh
=
1182 link_intrastage_shaders(prog
, vert_shader_list
, num_vert_shaders
);
1187 if (!validate_vertex_shader_executable(prog
, sh
))
1190 prog
->_LinkedShaders
[prog
->_NumLinkedShaders
] = sh
;
1191 prog
->_NumLinkedShaders
++;
1194 if (num_frag_shaders
> 0) {
1195 gl_shader
*const sh
=
1196 link_intrastage_shaders(prog
, frag_shader_list
, num_frag_shaders
);
1201 if (!validate_fragment_shader_executable(prog
, sh
))
1204 prog
->_LinkedShaders
[prog
->_NumLinkedShaders
] = sh
;
1205 prog
->_NumLinkedShaders
++;
1208 /* Here begins the inter-stage linking phase. Some initial validation is
1209 * performed, then locations are assigned for uniforms, attributes, and
1212 if (cross_validate_uniforms(prog
)) {
1213 /* Validate the inputs of each stage with the output of the preceeding
1216 for (unsigned i
= 1; i
< prog
->_NumLinkedShaders
; i
++) {
1217 if (!cross_validate_outputs_to_inputs(prog
,
1218 prog
->_LinkedShaders
[i
- 1],
1219 prog
->_LinkedShaders
[i
]))
1223 prog
->LinkStatus
= true;
1226 /* FINISHME: Perform whole-program optimization here. */
1227 for (unsigned i
= 0; i
< prog
->_NumLinkedShaders
; i
++) {
1228 /* Optimization passes */
1230 exec_list
*ir
= prog
->_LinkedShaders
[i
]->ir
;
1233 do_mat_op_to_vec(ir
);
1234 do_mod_to_fract(ir
);
1235 do_div_to_mul_rcp(ir
);
1240 progress
= do_function_inlining(ir
) || progress
;
1241 progress
= do_if_simplification(ir
) || progress
;
1242 progress
= do_copy_propagation(ir
) || progress
;
1243 progress
= do_dead_code_local(ir
) || progress
;
1245 progress
= do_dead_code_unlinked(state
, ir
) || progress
;
1247 progress
= do_constant_variable_unlinked(ir
) || progress
;
1248 progress
= do_constant_folding(ir
) || progress
;
1249 progress
= do_if_return(ir
) || progress
;
1251 if (ctx
->Shader
.EmitNoIfs
)
1252 progress
= do_if_to_cond_assign(ir
) || progress
;
1255 progress
= do_vec_index_to_swizzle(ir
) || progress
;
1256 /* Do this one after the previous to let the easier pass handle
1257 * constant vector indexing.
1259 progress
= do_vec_index_to_cond_assign(ir
) || progress
;
1261 progress
= do_swizzle_swizzle(ir
) || progress
;
1265 assign_uniform_locations(prog
);
1267 if (prog
->_LinkedShaders
[0]->Type
== GL_VERTEX_SHADER
)
1268 /* FINISHME: The value of the max_attribute_index parameter is
1269 * FINISHME: implementation dependent based on the value of
1270 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1271 * FINISHME: at least 16, so hardcode 16 for now.
1273 if (!assign_attribute_locations(prog
, 16))
1276 for (unsigned i
= 1; i
< prog
->_NumLinkedShaders
; i
++)
1277 assign_varying_locations(prog
->_LinkedShaders
[i
- 1],
1278 prog
->_LinkedShaders
[i
]);
1280 /* FINISHME: Assign fragment shader output locations. */
1283 free(vert_shader_list
);