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 "ir_optimization.h"
76 #include "main/shaderobj.h"
80 * Visitor that determines whether or not a variable is ever written.
82 class find_assignment_visitor
: public ir_hierarchical_visitor
{
84 find_assignment_visitor(const char *name
)
85 : name(name
), found(false)
90 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
92 ir_variable
*const var
= ir
->lhs
->variable_referenced();
94 if (strcmp(name
, var
->name
) == 0) {
99 return visit_continue_with_parent
;
102 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
104 exec_list_iterator sig_iter
= ir
->callee
->parameters
.iterator();
105 foreach_iter(exec_list_iterator
, iter
, *ir
) {
106 ir_rvalue
*param_rval
= (ir_rvalue
*)iter
.get();
107 ir_variable
*sig_param
= (ir_variable
*)sig_iter
.get();
109 if (sig_param
->mode
== ir_var_out
||
110 sig_param
->mode
== ir_var_inout
) {
111 ir_variable
*var
= param_rval
->variable_referenced();
112 if (var
&& strcmp(name
, var
->name
) == 0) {
120 if (ir
->return_deref
!= NULL
) {
121 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
123 if (strcmp(name
, var
->name
) == 0) {
129 return visit_continue_with_parent
;
132 bool variable_found()
138 const char *name
; /**< Find writes to a variable with this name. */
139 bool found
; /**< Was a write to the variable found? */
144 * Visitor that determines whether or not a variable is ever read.
146 class find_deref_visitor
: public ir_hierarchical_visitor
{
148 find_deref_visitor(const char *name
)
149 : name(name
), found(false)
154 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
156 if (strcmp(this->name
, ir
->var
->name
) == 0) {
161 return visit_continue
;
164 bool variable_found() const
170 const char *name
; /**< Find writes to a variable with this name. */
171 bool found
; /**< Was a write to the variable found? */
176 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
180 ralloc_strcat(&prog
->InfoLog
, "error: ");
182 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
185 prog
->LinkStatus
= false;
190 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
194 ralloc_strcat(&prog
->InfoLog
, "error: ");
196 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
203 link_invalidate_variable_locations(gl_shader
*sh
, int input_base
,
206 foreach_list(node
, sh
->ir
) {
207 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
224 /* Only assign locations for generic attributes / varyings / etc.
226 if ((var
->location
>= base
) && !var
->explicit_location
)
229 if ((var
->location
== -1) && !var
->explicit_location
) {
230 var
->is_unmatched_generic_inout
= 1;
231 var
->location_frac
= 0;
233 var
->is_unmatched_generic_inout
= 0;
240 * Determine the number of attribute slots required for a particular type
242 * This code is here because it implements the language rules of a specific
243 * GLSL version. Since it's a property of the language and not a property of
244 * types in general, it doesn't really belong in glsl_type.
247 count_attribute_slots(const glsl_type
*t
)
249 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
251 * "A scalar input counts the same amount against this limit as a vec4,
252 * so applications may want to consider packing groups of four
253 * unrelated float inputs together into a vector to better utilize the
254 * capabilities of the underlying hardware. A matrix input will use up
255 * multiple locations. The number of locations used will equal the
256 * number of columns in the matrix."
258 * The spec does not explicitly say how arrays are counted. However, it
259 * should be safe to assume the total number of slots consumed by an array
260 * is the number of entries in the array multiplied by the number of slots
261 * consumed by a single element of the array.
265 return t
->array_size() * count_attribute_slots(t
->element_type());
268 return t
->matrix_columns
;
275 * Verify that a vertex shader executable meets all semantic requirements.
277 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
280 * \param shader Vertex shader executable to be verified
283 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
284 struct gl_shader
*shader
)
289 /* From the GLSL 1.10 spec, page 48:
291 * "The variable gl_Position is available only in the vertex
292 * language and is intended for writing the homogeneous vertex
293 * position. All executions of a well-formed vertex shader
294 * executable must write a value into this variable. [...] The
295 * variable gl_Position is available only in the vertex
296 * language and is intended for writing the homogeneous vertex
297 * position. All executions of a well-formed vertex shader
298 * executable must write a value into this variable."
300 * while in GLSL 1.40 this text is changed to:
302 * "The variable gl_Position is available only in the vertex
303 * language and is intended for writing the homogeneous vertex
304 * position. It can be written at any time during shader
305 * execution. It may also be read back by a vertex shader
306 * after being written. This value will be used by primitive
307 * assembly, clipping, culling, and other fixed functionality
308 * operations, if present, that operate on primitives after
309 * vertex processing has occurred. Its value is undefined if
310 * the vertex shader executable does not write gl_Position."
312 * GLSL ES 3.00 is similar to GLSL 1.40--failing to write to gl_Position is
315 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
316 find_assignment_visitor
find("gl_Position");
317 find
.run(shader
->ir
);
318 if (!find
.variable_found()) {
319 linker_error(prog
, "vertex shader does not write to `gl_Position'\n");
324 prog
->Vert
.ClipDistanceArraySize
= 0;
326 if (!prog
->IsES
&& prog
->Version
>= 130) {
327 /* From section 7.1 (Vertex Shader Special Variables) of the
330 * "It is an error for a shader to statically write both
331 * gl_ClipVertex and gl_ClipDistance."
333 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
334 * gl_ClipVertex nor gl_ClipDistance.
336 find_assignment_visitor
clip_vertex("gl_ClipVertex");
337 find_assignment_visitor
clip_distance("gl_ClipDistance");
339 clip_vertex
.run(shader
->ir
);
340 clip_distance
.run(shader
->ir
);
341 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
342 linker_error(prog
, "vertex shader writes to both `gl_ClipVertex' "
343 "and `gl_ClipDistance'\n");
346 prog
->Vert
.UsesClipDistance
= clip_distance
.variable_found();
347 ir_variable
*clip_distance_var
=
348 shader
->symbols
->get_variable("gl_ClipDistance");
349 if (clip_distance_var
)
350 prog
->Vert
.ClipDistanceArraySize
= clip_distance_var
->type
->length
;
358 * Verify that a fragment shader executable meets all semantic requirements
360 * \param shader Fragment shader executable to be verified
363 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
364 struct gl_shader
*shader
)
369 find_assignment_visitor
frag_color("gl_FragColor");
370 find_assignment_visitor
frag_data("gl_FragData");
372 frag_color
.run(shader
->ir
);
373 frag_data
.run(shader
->ir
);
375 if (frag_color
.variable_found() && frag_data
.variable_found()) {
376 linker_error(prog
, "fragment shader writes to both "
377 "`gl_FragColor' and `gl_FragData'\n");
386 * Generate a string describing the mode of a variable
389 mode_string(const ir_variable
*var
)
393 return (var
->read_only
) ? "global constant" : "global variable";
395 case ir_var_uniform
: return "uniform";
396 case ir_var_in
: return "shader input";
397 case ir_var_out
: return "shader output";
398 case ir_var_inout
: return "shader inout";
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
;
653 * Validate that outputs from one stage match inputs of another
656 cross_validate_outputs_to_inputs(struct gl_shader_program
*prog
,
657 gl_shader
*producer
, gl_shader
*consumer
)
659 glsl_symbol_table parameters
;
660 /* FINISHME: Figure these out dynamically. */
661 const char *const producer_stage
= "vertex";
662 const char *const consumer_stage
= "fragment";
664 /* Find all shader outputs in the "producer" stage.
666 foreach_list(node
, producer
->ir
) {
667 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
669 /* FINISHME: For geometry shaders, this should also look for inout
670 * FINISHME: variables.
672 if ((var
== NULL
) || (var
->mode
!= ir_var_out
))
675 parameters
.add_variable(var
);
679 /* Find all shader inputs in the "consumer" stage. Any variables that have
680 * matching outputs already in the symbol table must have the same type and
683 foreach_list(node
, consumer
->ir
) {
684 ir_variable
*const input
= ((ir_instruction
*) node
)->as_variable();
686 /* FINISHME: For geometry shaders, this should also look for inout
687 * FINISHME: variables.
689 if ((input
== NULL
) || (input
->mode
!= ir_var_in
))
692 ir_variable
*const output
= parameters
.get_variable(input
->name
);
693 if (output
!= NULL
) {
694 /* Check that the types match between stages.
696 if (input
->type
!= output
->type
) {
697 /* There is a bit of a special case for gl_TexCoord. This
698 * built-in is unsized by default. Applications that variable
699 * access it must redeclare it with a size. There is some
700 * language in the GLSL spec that implies the fragment shader
701 * and vertex shader do not have to agree on this size. Other
702 * driver behave this way, and one or two applications seem to
705 * Neither declaration needs to be modified here because the array
706 * sizes are fixed later when update_array_sizes is called.
708 * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
710 * "Unlike user-defined varying variables, the built-in
711 * varying variables don't have a strict one-to-one
712 * correspondence between the vertex language and the
713 * fragment language."
715 if (!output
->type
->is_array()
716 || (strncmp("gl_", output
->name
, 3) != 0)) {
718 "%s shader output `%s' declared as type `%s', "
719 "but %s shader input declared as type `%s'\n",
720 producer_stage
, output
->name
,
722 consumer_stage
, input
->type
->name
);
727 /* Check that all of the qualifiers match between stages.
729 if (input
->centroid
!= output
->centroid
) {
731 "%s shader output `%s' %s centroid qualifier, "
732 "but %s shader input %s centroid qualifier\n",
735 (output
->centroid
) ? "has" : "lacks",
737 (input
->centroid
) ? "has" : "lacks");
741 if (input
->invariant
!= output
->invariant
) {
743 "%s shader output `%s' %s invariant qualifier, "
744 "but %s shader input %s invariant qualifier\n",
747 (output
->invariant
) ? "has" : "lacks",
749 (input
->invariant
) ? "has" : "lacks");
753 if (input
->interpolation
!= output
->interpolation
) {
755 "%s shader output `%s' specifies %s "
756 "interpolation qualifier, "
757 "but %s shader input specifies %s "
758 "interpolation qualifier\n",
761 output
->interpolation_string(),
763 input
->interpolation_string());
774 * Populates a shaders symbol table with all global declarations
777 populate_symbol_table(gl_shader
*sh
)
779 sh
->symbols
= new(sh
) glsl_symbol_table
;
781 foreach_list(node
, sh
->ir
) {
782 ir_instruction
*const inst
= (ir_instruction
*) node
;
786 if ((func
= inst
->as_function()) != NULL
) {
787 sh
->symbols
->add_function(func
);
788 } else if ((var
= inst
->as_variable()) != NULL
) {
789 sh
->symbols
->add_variable(var
);
796 * Remap variables referenced in an instruction tree
798 * This is used when instruction trees are cloned from one shader and placed in
799 * another. These trees will contain references to \c ir_variable nodes that
800 * do not exist in the target shader. This function finds these \c ir_variable
801 * references and replaces the references with matching variables in the target
804 * If there is no matching variable in the target shader, a clone of the
805 * \c ir_variable is made and added to the target shader. The new variable is
806 * added to \b both the instruction stream and the symbol table.
808 * \param inst IR tree that is to be processed.
809 * \param symbols Symbol table containing global scope symbols in the
811 * \param instructions Instruction stream where new variable declarations
815 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
818 class remap_visitor
: public ir_hierarchical_visitor
{
820 remap_visitor(struct gl_shader
*target
,
823 this->target
= target
;
824 this->symbols
= target
->symbols
;
825 this->instructions
= target
->ir
;
829 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
831 if (ir
->var
->mode
== ir_var_temporary
) {
832 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
836 return visit_continue
;
839 ir_variable
*const existing
=
840 this->symbols
->get_variable(ir
->var
->name
);
841 if (existing
!= NULL
)
844 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
846 this->symbols
->add_variable(copy
);
847 this->instructions
->push_head(copy
);
851 return visit_continue
;
855 struct gl_shader
*target
;
856 glsl_symbol_table
*symbols
;
857 exec_list
*instructions
;
861 remap_visitor
v(target
, temps
);
868 * Move non-declarations from one instruction stream to another
870 * The intended usage pattern of this function is to pass the pointer to the
871 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
872 * pointer) for \c last and \c false for \c make_copies on the first
873 * call. Successive calls pass the return value of the previous call for
874 * \c last and \c true for \c make_copies.
876 * \param instructions Source instruction stream
877 * \param last Instruction after which new instructions should be
878 * inserted in the target instruction stream
879 * \param make_copies Flag selecting whether instructions in \c instructions
880 * should be copied (via \c ir_instruction::clone) into the
881 * target list or moved.
884 * The new "last" instruction in the target instruction stream. This pointer
885 * is suitable for use as the \c last parameter of a later call to this
889 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
890 bool make_copies
, gl_shader
*target
)
892 hash_table
*temps
= NULL
;
895 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
896 hash_table_pointer_compare
);
898 foreach_list_safe(node
, instructions
) {
899 ir_instruction
*inst
= (ir_instruction
*) node
;
901 if (inst
->as_function())
904 ir_variable
*var
= inst
->as_variable();
905 if ((var
!= NULL
) && (var
->mode
!= ir_var_temporary
))
908 assert(inst
->as_assignment()
910 || inst
->as_if() /* for initializers with the ?: operator */
911 || ((var
!= NULL
) && (var
->mode
== ir_var_temporary
)));
914 inst
= inst
->clone(target
, NULL
);
917 hash_table_insert(temps
, inst
, var
);
919 remap_variables(inst
, target
, temps
);
924 last
->insert_after(inst
);
929 hash_table_dtor(temps
);
935 * Get the function signature for main from a shader
937 static ir_function_signature
*
938 get_main_function_signature(gl_shader
*sh
)
940 ir_function
*const f
= sh
->symbols
->get_function("main");
942 exec_list void_parameters
;
944 /* Look for the 'void main()' signature and ensure that it's defined.
945 * This keeps the linker from accidentally pick a shader that just
946 * contains a prototype for main.
948 * We don't have to check for multiple definitions of main (in multiple
949 * shaders) because that would have already been caught above.
951 ir_function_signature
*sig
= f
->matching_signature(&void_parameters
);
952 if ((sig
!= NULL
) && sig
->is_defined
) {
962 * This class is only used in link_intrastage_shaders() below but declaring
963 * it inside that function leads to compiler warnings with some versions of
966 class array_sizing_visitor
: public ir_hierarchical_visitor
{
968 virtual ir_visitor_status
visit(ir_variable
*var
)
970 if (var
->type
->is_array() && (var
->type
->length
== 0)) {
971 const glsl_type
*type
=
972 glsl_type::get_array_instance(var
->type
->fields
.array
,
973 var
->max_array_access
+ 1);
974 assert(type
!= NULL
);
977 return visit_continue
;
982 * Combine a group of shaders for a single stage to generate a linked shader
985 * If this function is supplied a single shader, it is cloned, and the new
986 * shader is returned.
988 static struct gl_shader
*
989 link_intrastage_shaders(void *mem_ctx
,
990 struct gl_context
*ctx
,
991 struct gl_shader_program
*prog
,
992 struct gl_shader
**shader_list
,
993 unsigned num_shaders
)
995 struct gl_uniform_block
*uniform_blocks
= NULL
;
996 unsigned num_uniform_blocks
= 0;
998 /* Check that global variables defined in multiple shaders are consistent.
1000 if (!cross_validate_globals(prog
, shader_list
, num_shaders
, false))
1003 /* Check that uniform blocks between shaders for a stage agree. */
1004 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1005 struct gl_shader
*sh
= shader_list
[i
];
1007 for (unsigned j
= 0; j
< shader_list
[i
]->NumUniformBlocks
; j
++) {
1008 link_assign_uniform_block_offsets(shader_list
[i
]);
1010 int index
= link_cross_validate_uniform_block(mem_ctx
,
1012 &num_uniform_blocks
,
1013 &sh
->UniformBlocks
[j
]);
1015 linker_error(prog
, "uniform block `%s' has mismatching definitions",
1016 sh
->UniformBlocks
[j
].Name
);
1022 /* Check that there is only a single definition of each function signature
1023 * across all shaders.
1025 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
1026 foreach_list(node
, shader_list
[i
]->ir
) {
1027 ir_function
*const f
= ((ir_instruction
*) node
)->as_function();
1032 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
1033 ir_function
*const other
=
1034 shader_list
[j
]->symbols
->get_function(f
->name
);
1036 /* If the other shader has no function (and therefore no function
1037 * signatures) with the same name, skip to the next shader.
1042 foreach_iter (exec_list_iterator
, iter
, *f
) {
1043 ir_function_signature
*sig
=
1044 (ir_function_signature
*) iter
.get();
1046 if (!sig
->is_defined
|| sig
->is_builtin
)
1049 ir_function_signature
*other_sig
=
1050 other
->exact_matching_signature(& sig
->parameters
);
1052 if ((other_sig
!= NULL
) && other_sig
->is_defined
1053 && !other_sig
->is_builtin
) {
1054 linker_error(prog
, "function `%s' is multiply defined",
1063 /* Find the shader that defines main, and make a clone of it.
1065 * Starting with the clone, search for undefined references. If one is
1066 * found, find the shader that defines it. Clone the reference and add
1067 * it to the shader. Repeat until there are no undefined references or
1068 * until a reference cannot be resolved.
1070 gl_shader
*main
= NULL
;
1071 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1072 if (get_main_function_signature(shader_list
[i
]) != NULL
) {
1073 main
= shader_list
[i
];
1079 linker_error(prog
, "%s shader lacks `main'\n",
1080 (shader_list
[0]->Type
== GL_VERTEX_SHADER
)
1081 ? "vertex" : "fragment");
1085 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
1086 linked
->ir
= new(linked
) exec_list
;
1087 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
1089 linked
->UniformBlocks
= uniform_blocks
;
1090 linked
->NumUniformBlocks
= num_uniform_blocks
;
1091 ralloc_steal(linked
, linked
->UniformBlocks
);
1093 populate_symbol_table(linked
);
1095 /* The a pointer to the main function in the final linked shader (i.e., the
1096 * copy of the original shader that contained the main function).
1098 ir_function_signature
*const main_sig
= get_main_function_signature(linked
);
1100 /* Move any instructions other than variable declarations or function
1101 * declarations into main.
1103 exec_node
*insertion_point
=
1104 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
1107 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1108 if (shader_list
[i
] == main
)
1111 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
1112 insertion_point
, true, linked
);
1115 /* Resolve initializers for global variables in the linked shader.
1117 unsigned num_linking_shaders
= num_shaders
;
1118 for (unsigned i
= 0; i
< num_shaders
; i
++)
1119 num_linking_shaders
+= shader_list
[i
]->num_builtins_to_link
;
1121 gl_shader
**linking_shaders
=
1122 (gl_shader
**) calloc(num_linking_shaders
, sizeof(gl_shader
*));
1124 memcpy(linking_shaders
, shader_list
,
1125 sizeof(linking_shaders
[0]) * num_shaders
);
1127 unsigned idx
= num_shaders
;
1128 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1129 memcpy(&linking_shaders
[idx
], shader_list
[i
]->builtins_to_link
,
1130 sizeof(linking_shaders
[0]) * shader_list
[i
]->num_builtins_to_link
);
1131 idx
+= shader_list
[i
]->num_builtins_to_link
;
1134 assert(idx
== num_linking_shaders
);
1136 if (!link_function_calls(prog
, linked
, linking_shaders
,
1137 num_linking_shaders
)) {
1138 ctx
->Driver
.DeleteShader(ctx
, linked
);
1142 free(linking_shaders
);
1145 /* At this point linked should contain all of the linked IR, so
1146 * validate it to make sure nothing went wrong.
1149 validate_ir_tree(linked
->ir
);
1152 /* Make a pass over all variable declarations to ensure that arrays with
1153 * unspecified sizes have a size specified. The size is inferred from the
1154 * max_array_access field.
1156 if (linked
!= NULL
) {
1157 array_sizing_visitor v
;
1166 * Update the sizes of linked shader uniform arrays to the maximum
1169 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1171 * If one or more elements of an array are active,
1172 * GetActiveUniform will return the name of the array in name,
1173 * subject to the restrictions listed above. The type of the array
1174 * is returned in type. The size parameter contains the highest
1175 * array element index used, plus one. The compiler or linker
1176 * determines the highest index used. There will be only one
1177 * active uniform reported by the GL per uniform array.
1181 update_array_sizes(struct gl_shader_program
*prog
)
1183 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
1184 if (prog
->_LinkedShaders
[i
] == NULL
)
1187 foreach_list(node
, prog
->_LinkedShaders
[i
]->ir
) {
1188 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1190 if ((var
== NULL
) || (var
->mode
!= ir_var_uniform
&&
1191 var
->mode
!= ir_var_in
&&
1192 var
->mode
!= ir_var_out
) ||
1193 !var
->type
->is_array())
1196 /* GL_ARB_uniform_buffer_object says that std140 uniforms
1197 * will not be eliminated. Since we always do std140, just
1198 * don't resize arrays in UBOs.
1200 if (var
->uniform_block
!= -1)
1203 unsigned int size
= var
->max_array_access
;
1204 for (unsigned j
= 0; j
< MESA_SHADER_TYPES
; j
++) {
1205 if (prog
->_LinkedShaders
[j
] == NULL
)
1208 foreach_list(node2
, prog
->_LinkedShaders
[j
]->ir
) {
1209 ir_variable
*other_var
= ((ir_instruction
*) node2
)->as_variable();
1213 if (strcmp(var
->name
, other_var
->name
) == 0 &&
1214 other_var
->max_array_access
> size
) {
1215 size
= other_var
->max_array_access
;
1220 if (size
+ 1 != var
->type
->fields
.array
->length
) {
1221 /* If this is a built-in uniform (i.e., it's backed by some
1222 * fixed-function state), adjust the number of state slots to
1223 * match the new array size. The number of slots per array entry
1224 * is not known. It seems safe to assume that the total number of
1225 * slots is an integer multiple of the number of array elements.
1226 * Determine the number of slots per array element by dividing by
1227 * the old (total) size.
1229 if (var
->num_state_slots
> 0) {
1230 var
->num_state_slots
= (size
+ 1)
1231 * (var
->num_state_slots
/ var
->type
->length
);
1234 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
1236 /* FINISHME: We should update the types of array
1237 * dereferences of this variable now.
1245 * Find a contiguous set of available bits in a bitmask.
1247 * \param used_mask Bits representing used (1) and unused (0) locations
1248 * \param needed_count Number of contiguous bits needed.
1251 * Base location of the available bits on success or -1 on failure.
1254 find_available_slots(unsigned used_mask
, unsigned needed_count
)
1256 unsigned needed_mask
= (1 << needed_count
) - 1;
1257 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
1259 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1260 * cannot optimize possibly infinite loops" for the loop below.
1262 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
1265 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
1266 if ((needed_mask
& ~used_mask
) == needed_mask
)
1277 * Assign locations for either VS inputs for FS outputs
1279 * \param prog Shader program whose variables need locations assigned
1280 * \param target_index Selector for the program target to receive location
1281 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1282 * \c MESA_SHADER_FRAGMENT.
1283 * \param max_index Maximum number of generic locations. This corresponds
1284 * to either the maximum number of draw buffers or the
1285 * maximum number of generic attributes.
1288 * If locations are successfully assigned, true is returned. Otherwise an
1289 * error is emitted to the shader link log and false is returned.
1292 assign_attribute_or_color_locations(gl_shader_program
*prog
,
1293 unsigned target_index
,
1296 /* Mark invalid locations as being used.
1298 unsigned used_locations
= (max_index
>= 32)
1299 ? ~0 : ~((1 << max_index
) - 1);
1301 assert((target_index
== MESA_SHADER_VERTEX
)
1302 || (target_index
== MESA_SHADER_FRAGMENT
));
1304 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
1308 /* Operate in a total of four passes.
1310 * 1. Invalidate the location assignments for all vertex shader inputs.
1312 * 2. Assign locations for inputs that have user-defined (via
1313 * glBindVertexAttribLocation) locations and outputs that have
1314 * user-defined locations (via glBindFragDataLocation).
1316 * 3. Sort the attributes without assigned locations by number of slots
1317 * required in decreasing order. Fragmentation caused by attribute
1318 * locations assigned by the application may prevent large attributes
1319 * from having enough contiguous space.
1321 * 4. Assign locations to any inputs without assigned locations.
1324 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
1325 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
1327 const enum ir_variable_mode direction
=
1328 (target_index
== MESA_SHADER_VERTEX
) ? ir_var_in
: ir_var_out
;
1331 /* Temporary storage for the set of attributes that need locations assigned.
1337 /* Used below in the call to qsort. */
1338 static int compare(const void *a
, const void *b
)
1340 const temp_attr
*const l
= (const temp_attr
*) a
;
1341 const temp_attr
*const r
= (const temp_attr
*) b
;
1343 /* Reversed because we want a descending order sort below. */
1344 return r
->slots
- l
->slots
;
1348 unsigned num_attr
= 0;
1350 foreach_list(node
, sh
->ir
) {
1351 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1353 if ((var
== NULL
) || (var
->mode
!= (unsigned) direction
))
1356 if (var
->explicit_location
) {
1357 if ((var
->location
>= (int)(max_index
+ generic_base
))
1358 || (var
->location
< 0)) {
1360 "invalid explicit location %d specified for `%s'\n",
1362 ? var
->location
: var
->location
- generic_base
,
1366 } else if (target_index
== MESA_SHADER_VERTEX
) {
1369 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
1370 assert(binding
>= VERT_ATTRIB_GENERIC0
);
1371 var
->location
= binding
;
1372 var
->is_unmatched_generic_inout
= 0;
1374 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
1378 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
1379 assert(binding
>= FRAG_RESULT_DATA0
);
1380 var
->location
= binding
;
1381 var
->is_unmatched_generic_inout
= 0;
1383 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
1389 /* If the variable is not a built-in and has a location statically
1390 * assigned in the shader (presumably via a layout qualifier), make sure
1391 * that it doesn't collide with other assigned locations. Otherwise,
1392 * add it to the list of variables that need linker-assigned locations.
1394 const unsigned slots
= count_attribute_slots(var
->type
);
1395 if (var
->location
!= -1) {
1396 if (var
->location
>= generic_base
&& var
->index
< 1) {
1397 /* From page 61 of the OpenGL 4.0 spec:
1399 * "LinkProgram will fail if the attribute bindings assigned
1400 * by BindAttribLocation do not leave not enough space to
1401 * assign a location for an active matrix attribute or an
1402 * active attribute array, both of which require multiple
1403 * contiguous generic attributes."
1405 * Previous versions of the spec contain similar language but omit
1406 * the bit about attribute arrays.
1408 * Page 61 of the OpenGL 4.0 spec also says:
1410 * "It is possible for an application to bind more than one
1411 * attribute name to the same location. This is referred to as
1412 * aliasing. This will only work if only one of the aliased
1413 * attributes is active in the executable program, or if no
1414 * path through the shader consumes more than one attribute of
1415 * a set of attributes aliased to the same location. A link
1416 * error can occur if the linker determines that every path
1417 * through the shader consumes multiple aliased attributes,
1418 * but implementations are not required to generate an error
1421 * These two paragraphs are either somewhat contradictory, or I
1422 * don't fully understand one or both of them.
1424 /* FINISHME: The code as currently written does not support
1425 * FINISHME: attribute location aliasing (see comment above).
1427 /* Mask representing the contiguous slots that will be used by
1430 const unsigned attr
= var
->location
- generic_base
;
1431 const unsigned use_mask
= (1 << slots
) - 1;
1433 /* Generate a link error if the set of bits requested for this
1434 * attribute overlaps any previously allocated bits.
1436 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
1437 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
1438 ? "vertex shader input" : "fragment shader output";
1440 "insufficient contiguous locations "
1441 "available for %s `%s' %d %d %d", string
,
1442 var
->name
, used_locations
, use_mask
, attr
);
1446 used_locations
|= (use_mask
<< attr
);
1452 to_assign
[num_attr
].slots
= slots
;
1453 to_assign
[num_attr
].var
= var
;
1457 /* If all of the attributes were assigned locations by the application (or
1458 * are built-in attributes with fixed locations), return early. This should
1459 * be the common case.
1464 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
1466 if (target_index
== MESA_SHADER_VERTEX
) {
1467 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1468 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1469 * reserved to prevent it from being automatically allocated below.
1471 find_deref_visitor
find("gl_Vertex");
1473 if (find
.variable_found())
1474 used_locations
|= (1 << 0);
1477 for (unsigned i
= 0; i
< num_attr
; i
++) {
1478 /* Mask representing the contiguous slots that will be used by this
1481 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
1483 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
1486 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
1487 ? "vertex shader input" : "fragment shader output";
1490 "insufficient contiguous locations "
1491 "available for %s `%s'",
1492 string
, to_assign
[i
].var
->name
);
1496 to_assign
[i
].var
->location
= generic_base
+ location
;
1497 to_assign
[i
].var
->is_unmatched_generic_inout
= 0;
1498 used_locations
|= (use_mask
<< location
);
1506 * Demote shader inputs and outputs that are not used in other stages
1509 demote_shader_inputs_and_outputs(gl_shader
*sh
, enum ir_variable_mode mode
)
1511 foreach_list(node
, sh
->ir
) {
1512 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
1514 if ((var
== NULL
) || (var
->mode
!= int(mode
)))
1517 /* A shader 'in' or 'out' variable is only really an input or output if
1518 * its value is used by other shader stages. This will cause the variable
1519 * to have a location assigned.
1521 if (var
->is_unmatched_generic_inout
) {
1522 var
->mode
= ir_var_auto
;
1529 * Data structure tracking information about a transform feedback declaration
1532 class tfeedback_decl
1535 bool init(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
1536 const void *mem_ctx
, const char *input
);
1537 static bool is_same(const tfeedback_decl
&x
, const tfeedback_decl
&y
);
1538 bool assign_location(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
1539 ir_variable
*output_var
);
1540 unsigned get_num_outputs() const;
1541 bool store(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
1542 struct gl_transform_feedback_info
*info
, unsigned buffer
,
1543 const unsigned max_outputs
) const;
1544 ir_variable
*find_output_var(gl_shader_program
*prog
,
1545 gl_shader
*producer
) const;
1547 bool is_next_buffer_separator() const
1549 return this->next_buffer_separator
;
1552 bool is_varying() const
1554 return !this->next_buffer_separator
&& !this->skip_components
;
1558 * The total number of varying components taken up by this variable. Only
1559 * valid if assign_location() has been called.
1561 unsigned num_components() const
1563 if (this->is_clip_distance_mesa
)
1566 return this->vector_elements
* this->matrix_columns
* this->size
;
1571 * The name that was supplied to glTransformFeedbackVaryings. Used for
1572 * error reporting and glGetTransformFeedbackVarying().
1574 const char *orig_name
;
1577 * The name of the variable, parsed from orig_name.
1579 const char *var_name
;
1582 * True if the declaration in orig_name represents an array.
1584 bool is_subscripted
;
1587 * If is_subscripted is true, the subscript that was specified in orig_name.
1589 unsigned array_subscript
;
1592 * True if the variable is gl_ClipDistance and the driver lowers
1593 * gl_ClipDistance to gl_ClipDistanceMESA.
1595 bool is_clip_distance_mesa
;
1598 * The vertex shader output location that the linker assigned for this
1599 * variable. -1 if a location hasn't been assigned yet.
1604 * If location != -1, the number of vector elements in this variable, or 1
1605 * if this variable is a scalar.
1607 unsigned vector_elements
;
1610 * If location != -1, the number of matrix columns in this variable, or 1
1611 * if this variable is not a matrix.
1613 unsigned matrix_columns
;
1615 /** Type of the varying returned by glGetTransformFeedbackVarying() */
1619 * If location != -1, the size that should be returned by
1620 * glGetTransformFeedbackVarying().
1625 * How many components to skip. If non-zero, this is
1626 * gl_SkipComponents{1,2,3,4} from ARB_transform_feedback3.
1628 unsigned skip_components
;
1631 * Whether this is gl_NextBuffer from ARB_transform_feedback3.
1633 bool next_buffer_separator
;
1638 * Initialize this object based on a string that was passed to
1639 * glTransformFeedbackVaryings. If there is a parse error, the error is
1640 * reported using linker_error(), and false is returned.
1643 tfeedback_decl::init(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
1644 const void *mem_ctx
, const char *input
)
1646 /* We don't have to be pedantic about what is a valid GLSL variable name,
1647 * because any variable with an invalid name can't exist in the IR anyway.
1650 this->location
= -1;
1651 this->orig_name
= input
;
1652 this->is_clip_distance_mesa
= false;
1653 this->skip_components
= 0;
1654 this->next_buffer_separator
= false;
1656 if (ctx
->Extensions
.ARB_transform_feedback3
) {
1657 /* Parse gl_NextBuffer. */
1658 if (strcmp(input
, "gl_NextBuffer") == 0) {
1659 this->next_buffer_separator
= true;
1663 /* Parse gl_SkipComponents. */
1664 if (strcmp(input
, "gl_SkipComponents1") == 0)
1665 this->skip_components
= 1;
1666 else if (strcmp(input
, "gl_SkipComponents2") == 0)
1667 this->skip_components
= 2;
1668 else if (strcmp(input
, "gl_SkipComponents3") == 0)
1669 this->skip_components
= 3;
1670 else if (strcmp(input
, "gl_SkipComponents4") == 0)
1671 this->skip_components
= 4;
1673 if (this->skip_components
)
1677 /* Parse a declaration. */
1678 const char *bracket
= strrchr(input
, '[');
1681 this->var_name
= ralloc_strndup(mem_ctx
, input
, bracket
- input
);
1682 if (sscanf(bracket
, "[%u]", &this->array_subscript
) != 1) {
1683 linker_error(prog
, "Cannot parse transform feedback varying %s", input
);
1686 this->is_subscripted
= true;
1688 this->var_name
= ralloc_strdup(mem_ctx
, input
);
1689 this->is_subscripted
= false;
1692 /* For drivers that lower gl_ClipDistance to gl_ClipDistanceMESA, this
1693 * class must behave specially to account for the fact that gl_ClipDistance
1694 * is converted from a float[8] to a vec4[2].
1696 if (ctx
->ShaderCompilerOptions
[MESA_SHADER_VERTEX
].LowerClipDistance
&&
1697 strcmp(this->var_name
, "gl_ClipDistance") == 0) {
1698 this->is_clip_distance_mesa
= true;
1706 * Determine whether two tfeedback_decl objects refer to the same variable and
1707 * array index (if applicable).
1710 tfeedback_decl::is_same(const tfeedback_decl
&x
, const tfeedback_decl
&y
)
1712 assert(x
.is_varying() && y
.is_varying());
1714 if (strcmp(x
.var_name
, y
.var_name
) != 0)
1716 if (x
.is_subscripted
!= y
.is_subscripted
)
1718 if (x
.is_subscripted
&& x
.array_subscript
!= y
.array_subscript
)
1725 * Assign a location for this tfeedback_decl object based on the location
1726 * assignment in output_var.
1728 * If an error occurs, the error is reported through linker_error() and false
1732 tfeedback_decl::assign_location(struct gl_context
*ctx
,
1733 struct gl_shader_program
*prog
,
1734 ir_variable
*output_var
)
1736 assert(this->is_varying());
1738 if (output_var
->type
->is_array()) {
1739 /* Array variable */
1740 const unsigned matrix_cols
=
1741 output_var
->type
->fields
.array
->matrix_columns
;
1742 unsigned actual_array_size
= this->is_clip_distance_mesa
?
1743 prog
->Vert
.ClipDistanceArraySize
: output_var
->type
->array_size();
1745 if (this->is_subscripted
) {
1746 /* Check array bounds. */
1747 if (this->array_subscript
>= actual_array_size
) {
1748 linker_error(prog
, "Transform feedback varying %s has index "
1749 "%i, but the array size is %u.",
1750 this->orig_name
, this->array_subscript
,
1754 if (this->is_clip_distance_mesa
) {
1756 output_var
->location
+ this->array_subscript
/ 4;
1759 output_var
->location
+ this->array_subscript
* matrix_cols
;
1763 this->location
= output_var
->location
;
1764 this->size
= actual_array_size
;
1766 this->vector_elements
= output_var
->type
->fields
.array
->vector_elements
;
1767 this->matrix_columns
= matrix_cols
;
1768 if (this->is_clip_distance_mesa
)
1769 this->type
= GL_FLOAT
;
1771 this->type
= output_var
->type
->fields
.array
->gl_type
;
1773 /* Regular variable (scalar, vector, or matrix) */
1774 if (this->is_subscripted
) {
1775 linker_error(prog
, "Transform feedback varying %s requested, "
1776 "but %s is not an array.",
1777 this->orig_name
, this->var_name
);
1780 this->location
= output_var
->location
;
1782 this->vector_elements
= output_var
->type
->vector_elements
;
1783 this->matrix_columns
= output_var
->type
->matrix_columns
;
1784 this->type
= output_var
->type
->gl_type
;
1787 /* From GL_EXT_transform_feedback:
1788 * A program will fail to link if:
1790 * * the total number of components to capture in any varying
1791 * variable in <varyings> is greater than the constant
1792 * MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT and the
1793 * buffer mode is SEPARATE_ATTRIBS_EXT;
1795 if (prog
->TransformFeedback
.BufferMode
== GL_SEPARATE_ATTRIBS
&&
1796 this->num_components() >
1797 ctx
->Const
.MaxTransformFeedbackSeparateComponents
) {
1798 linker_error(prog
, "Transform feedback varying %s exceeds "
1799 "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS.",
1809 tfeedback_decl::get_num_outputs() const
1811 if (!this->is_varying()) {
1815 unsigned translated_size
= this->size
;
1816 if (this->is_clip_distance_mesa
)
1817 translated_size
= (translated_size
+ 3) / 4;
1819 return translated_size
* this->matrix_columns
;
1824 * Update gl_transform_feedback_info to reflect this tfeedback_decl.
1826 * If an error occurs, the error is reported through linker_error() and false
1830 tfeedback_decl::store(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
1831 struct gl_transform_feedback_info
*info
,
1832 unsigned buffer
, const unsigned max_outputs
) const
1834 assert(!this->next_buffer_separator
);
1836 /* Handle gl_SkipComponents. */
1837 if (this->skip_components
) {
1838 info
->BufferStride
[buffer
] += this->skip_components
;
1842 /* From GL_EXT_transform_feedback:
1843 * A program will fail to link if:
1845 * * the total number of components to capture is greater than
1846 * the constant MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT
1847 * and the buffer mode is INTERLEAVED_ATTRIBS_EXT.
1849 if (prog
->TransformFeedback
.BufferMode
== GL_INTERLEAVED_ATTRIBS
&&
1850 info
->BufferStride
[buffer
] + this->num_components() >
1851 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1852 linker_error(prog
, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1853 "limit has been exceeded.");
1857 unsigned translated_size
= this->size
;
1858 if (this->is_clip_distance_mesa
)
1859 translated_size
= (translated_size
+ 3) / 4;
1860 unsigned components_so_far
= 0;
1861 for (unsigned index
= 0; index
< translated_size
; ++index
) {
1862 for (unsigned v
= 0; v
< this->matrix_columns
; ++v
) {
1863 unsigned num_components
= this->vector_elements
;
1864 assert(info
->NumOutputs
< max_outputs
);
1865 info
->Outputs
[info
->NumOutputs
].ComponentOffset
= 0;
1866 if (this->is_clip_distance_mesa
) {
1867 if (this->is_subscripted
) {
1869 info
->Outputs
[info
->NumOutputs
].ComponentOffset
=
1870 this->array_subscript
% 4;
1872 num_components
= MIN2(4, this->size
- components_so_far
);
1875 info
->Outputs
[info
->NumOutputs
].OutputRegister
=
1876 this->location
+ v
+ index
* this->matrix_columns
;
1877 info
->Outputs
[info
->NumOutputs
].NumComponents
= num_components
;
1878 info
->Outputs
[info
->NumOutputs
].OutputBuffer
= buffer
;
1879 info
->Outputs
[info
->NumOutputs
].DstOffset
= info
->BufferStride
[buffer
];
1881 info
->BufferStride
[buffer
] += num_components
;
1882 components_so_far
+= num_components
;
1885 assert(components_so_far
== this->num_components());
1887 info
->Varyings
[info
->NumVarying
].Name
= ralloc_strdup(prog
, this->orig_name
);
1888 info
->Varyings
[info
->NumVarying
].Type
= this->type
;
1889 info
->Varyings
[info
->NumVarying
].Size
= this->size
;
1897 tfeedback_decl::find_output_var(gl_shader_program
*prog
,
1898 gl_shader
*producer
) const
1900 const char *name
= this->is_clip_distance_mesa
1901 ? "gl_ClipDistanceMESA" : this->var_name
;
1902 ir_variable
*var
= producer
->symbols
->get_variable(name
);
1903 if (var
&& var
->mode
== ir_var_out
)
1906 /* From GL_EXT_transform_feedback:
1907 * A program will fail to link if:
1909 * * any variable name specified in the <varyings> array is not
1910 * declared as an output in the geometry shader (if present) or
1911 * the vertex shader (if no geometry shader is present);
1913 linker_error(prog
, "Transform feedback varying %s undeclared.",
1920 * Parse all the transform feedback declarations that were passed to
1921 * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
1923 * If an error occurs, the error is reported through linker_error() and false
1927 parse_tfeedback_decls(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
1928 const void *mem_ctx
, unsigned num_names
,
1929 char **varying_names
, tfeedback_decl
*decls
)
1931 for (unsigned i
= 0; i
< num_names
; ++i
) {
1932 if (!decls
[i
].init(ctx
, prog
, mem_ctx
, varying_names
[i
]))
1935 if (!decls
[i
].is_varying())
1938 /* From GL_EXT_transform_feedback:
1939 * A program will fail to link if:
1941 * * any two entries in the <varyings> array specify the same varying
1944 * We interpret this to mean "any two entries in the <varyings> array
1945 * specify the same varying variable and array index", since transform
1946 * feedback of arrays would be useless otherwise.
1948 for (unsigned j
= 0; j
< i
; ++j
) {
1949 if (!decls
[j
].is_varying())
1952 if (tfeedback_decl::is_same(decls
[i
], decls
[j
])) {
1953 linker_error(prog
, "Transform feedback varying %s specified "
1954 "more than once.", varying_names
[i
]);
1964 * Data structure recording the relationship between outputs of one shader
1965 * stage (the "producer") and inputs of another (the "consumer").
1967 class varying_matches
1972 void record(ir_variable
*producer_var
, ir_variable
*consumer_var
);
1973 unsigned assign_locations();
1974 void store_locations(unsigned producer_base
, unsigned consumer_base
) const;
1978 * Enum representing the order in which varyings are packed within a
1981 * Currently we pack vec4's first, then vec2's, then scalar values, then
1982 * vec3's. This order ensures that the only vectors that are at risk of
1983 * having to be "double parked" (split between two adjacent varying slots)
1986 enum packing_order_enum
{
1989 PACKING_ORDER_SCALAR
,
1993 static unsigned compute_packing_class(ir_variable
*var
);
1994 static packing_order_enum
compute_packing_order(ir_variable
*var
);
1995 static int match_comparator(const void *x_generic
, const void *y_generic
);
1998 * Structure recording the relationship between a single producer output
1999 * and a single consumer input.
2003 * Packing class for this varying, computed by compute_packing_class().
2005 unsigned packing_class
;
2008 * Packing order for this varying, computed by compute_packing_order().
2010 packing_order_enum packing_order
;
2013 * The output variable in the producer stage.
2015 ir_variable
*producer_var
;
2018 * The input variable in the consumer stage.
2020 ir_variable
*consumer_var
;
2023 * The location which has been assigned for this varying. This is
2024 * expressed in multiples of a float, with the first generic varying
2025 * (i.e. the one referred to by VERT_RESULT_VAR0 or FRAG_ATTRIB_VAR0)
2026 * represented by the value 0.
2028 unsigned generic_location
;
2032 * The number of elements in the \c matches array that are currently in
2035 unsigned num_matches
;
2038 * The number of elements that were set aside for the \c matches array when
2041 unsigned matches_capacity
;
2045 varying_matches::varying_matches()
2047 /* Note: this initial capacity is rather arbitrarily chosen to be large
2048 * enough for many cases without wasting an unreasonable amount of space.
2049 * varying_matches::record() will resize the array if there are more than
2050 * this number of varyings.
2052 this->matches_capacity
= 8;
2053 this->matches
= (match
*)
2054 malloc(sizeof(*this->matches
) * this->matches_capacity
);
2055 this->num_matches
= 0;
2059 varying_matches::~varying_matches()
2061 free(this->matches
);
2066 * Record the given producer/consumer variable pair in the list of variables
2067 * that should later be assigned locations.
2069 * It is permissible for \c consumer_var to be NULL (this happens if a
2070 * variable is output by the producer and consumed by transform feedback, but
2071 * not consumed by the consumer).
2073 * If \c producer_var has already been paired up with a consumer_var, or
2074 * producer_var is part of fixed pipeline functionality (and hence already has
2075 * a location assigned), this function has no effect.
2078 varying_matches::record(ir_variable
*producer_var
, ir_variable
*consumer_var
)
2080 if (!producer_var
->is_unmatched_generic_inout
) {
2081 /* Either a location already exists for this variable (since it is part
2082 * of fixed functionality), or it has already been recorded as part of a
2088 if (this->num_matches
== this->matches_capacity
) {
2089 this->matches_capacity
*= 2;
2090 this->matches
= (match
*)
2091 realloc(this->matches
,
2092 sizeof(*this->matches
) * this->matches_capacity
);
2094 this->matches
[this->num_matches
].packing_class
2095 = this->compute_packing_class(producer_var
);
2096 this->matches
[this->num_matches
].packing_order
2097 = this->compute_packing_order(producer_var
);
2098 this->matches
[this->num_matches
].producer_var
= producer_var
;
2099 this->matches
[this->num_matches
].consumer_var
= consumer_var
;
2100 this->num_matches
++;
2101 producer_var
->is_unmatched_generic_inout
= 0;
2103 consumer_var
->is_unmatched_generic_inout
= 0;
2108 * Choose locations for all of the variable matches that were previously
2109 * passed to varying_matches::record().
2112 varying_matches::assign_locations()
2114 /* Sort varying matches into an order that makes them easy to pack. */
2115 qsort(this->matches
, this->num_matches
, sizeof(*this->matches
),
2116 &varying_matches::match_comparator
);
2118 unsigned generic_location
= 0;
2120 for (unsigned i
= 0; i
< this->num_matches
; i
++) {
2121 this->matches
[i
].generic_location
= generic_location
;
2123 ir_variable
*producer_var
= this->matches
[i
].producer_var
;
2125 if (producer_var
->type
->is_array()) {
2126 const unsigned slots
= producer_var
->type
->length
2127 * producer_var
->type
->fields
.array
->matrix_columns
;
2129 generic_location
+= 4 * slots
;
2131 const unsigned slots
= producer_var
->type
->matrix_columns
;
2133 generic_location
+= 4 * slots
;
2137 return (generic_location
+ 3) / 4;
2142 * Update the producer and consumer shaders to reflect the locations
2143 * assignments that were made by varying_matches::assign_locations().
2146 varying_matches::store_locations(unsigned producer_base
,
2147 unsigned consumer_base
) const
2149 for (unsigned i
= 0; i
< this->num_matches
; i
++) {
2150 ir_variable
*producer_var
= this->matches
[i
].producer_var
;
2151 ir_variable
*consumer_var
= this->matches
[i
].consumer_var
;
2152 unsigned generic_location
= this->matches
[i
].generic_location
;
2153 unsigned slot
= generic_location
/ 4;
2154 unsigned offset
= generic_location
% 4;
2156 producer_var
->location
= producer_base
+ slot
;
2157 producer_var
->location_frac
= offset
;
2159 assert(consumer_var
->location
== -1);
2160 consumer_var
->location
= consumer_base
+ slot
;
2161 consumer_var
->location_frac
= offset
;
2168 * Compute the "packing class" of the given varying. This is an unsigned
2169 * integer with the property that two variables in the same packing class can
2170 * be safely backed into the same vec4.
2173 varying_matches::compute_packing_class(ir_variable
*var
)
2175 /* In this initial implementation we conservatively assume that variables
2176 * can only be packed if their base type (float/int/uint/bool) matches and
2177 * their interpolation and centroid qualifiers match.
2179 * TODO: relax these restrictions when the driver back-end permits.
2181 unsigned packing_class
= var
->centroid
? 1 : 0;
2183 packing_class
+= var
->interpolation
;
2184 packing_class
*= GLSL_TYPE_ERROR
;
2185 packing_class
+= var
->type
->get_scalar_type()->base_type
;
2186 return packing_class
;
2191 * Compute the "packing order" of the given varying. This is a sort key we
2192 * use to determine when to attempt to pack the given varying relative to
2193 * other varyings in the same packing class.
2195 varying_matches::packing_order_enum
2196 varying_matches::compute_packing_order(ir_variable
*var
)
2198 const glsl_type
*element_type
= var
->type
;
2200 /* FINISHME: Support for "varying" records in GLSL 1.50. */
2201 while (element_type
->base_type
== GLSL_TYPE_ARRAY
) {
2202 element_type
= element_type
->fields
.array
;
2205 switch (element_type
->vector_elements
) {
2206 case 1: return PACKING_ORDER_SCALAR
;
2207 case 2: return PACKING_ORDER_VEC2
;
2208 case 3: return PACKING_ORDER_VEC3
;
2209 case 4: return PACKING_ORDER_VEC4
;
2211 assert(!"Unexpected value of vector_elements");
2212 return PACKING_ORDER_VEC4
;
2218 * Comparison function passed to qsort() to sort varyings by packing_class and
2219 * then by packing_order.
2222 varying_matches::match_comparator(const void *x_generic
, const void *y_generic
)
2224 const match
*x
= (const match
*) x_generic
;
2225 const match
*y
= (const match
*) y_generic
;
2227 if (x
->packing_class
!= y
->packing_class
)
2228 return x
->packing_class
- y
->packing_class
;
2229 return x
->packing_order
- y
->packing_order
;
2234 * Is the given variable a varying variable to be counted against the
2235 * limit in ctx->Const.MaxVarying?
2236 * This includes variables such as texcoords, colors and generic
2237 * varyings, but excludes variables such as gl_FrontFacing and gl_FragCoord.
2240 is_varying_var(GLenum shaderType
, const ir_variable
*var
)
2242 /* Only fragment shaders will take a varying variable as an input */
2243 if (shaderType
== GL_FRAGMENT_SHADER
&&
2244 var
->mode
== ir_var_in
) {
2245 switch (var
->location
) {
2246 case FRAG_ATTRIB_WPOS
:
2247 case FRAG_ATTRIB_FACE
:
2248 case FRAG_ATTRIB_PNTC
:
2259 * Assign locations for all variables that are produced in one pipeline stage
2260 * (the "producer") and consumed in the next stage (the "consumer").
2262 * Variables produced by the producer may also be consumed by transform
2265 * \param num_tfeedback_decls is the number of declarations indicating
2266 * variables that may be consumed by transform feedback.
2268 * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
2269 * representing the result of parsing the strings passed to
2270 * glTransformFeedbackVaryings(). assign_location() will be called for
2271 * each of these objects that matches one of the outputs of the
2274 * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
2275 * be NULL. In this case, varying locations are assigned solely based on the
2276 * requirements of transform feedback.
2279 assign_varying_locations(struct gl_context
*ctx
,
2280 struct gl_shader_program
*prog
,
2281 gl_shader
*producer
, gl_shader
*consumer
,
2282 unsigned num_tfeedback_decls
,
2283 tfeedback_decl
*tfeedback_decls
)
2285 /* FINISHME: Set dynamically when geometry shader support is added. */
2286 const unsigned producer_base
= VERT_RESULT_VAR0
;
2287 const unsigned consumer_base
= FRAG_ATTRIB_VAR0
;
2288 varying_matches matches
;
2290 /* Operate in a total of three passes.
2292 * 1. Assign locations for any matching inputs and outputs.
2294 * 2. Mark output variables in the producer that do not have locations as
2295 * not being outputs. This lets the optimizer eliminate them.
2297 * 3. Mark input variables in the consumer that do not have locations as
2298 * not being inputs. This lets the optimizer eliminate them.
2301 foreach_list(node
, producer
->ir
) {
2302 ir_variable
*const output_var
= ((ir_instruction
*) node
)->as_variable();
2304 if ((output_var
== NULL
) || (output_var
->mode
!= ir_var_out
))
2307 ir_variable
*input_var
=
2308 consumer
? consumer
->symbols
->get_variable(output_var
->name
) : NULL
;
2310 if (input_var
&& input_var
->mode
!= ir_var_in
)
2314 matches
.record(output_var
, input_var
);
2318 for (unsigned i
= 0; i
< num_tfeedback_decls
; ++i
) {
2319 if (!tfeedback_decls
[i
].is_varying())
2322 ir_variable
*output_var
2323 = tfeedback_decls
[i
].find_output_var(prog
, producer
);
2325 if (output_var
== NULL
)
2328 if (output_var
->is_unmatched_generic_inout
) {
2329 matches
.record(output_var
, NULL
);
2333 matches
.assign_locations();
2334 matches
.store_locations(producer_base
, consumer_base
);
2336 for (unsigned i
= 0; i
< num_tfeedback_decls
; ++i
) {
2337 if (!tfeedback_decls
[i
].is_varying())
2340 ir_variable
*output_var
2341 = tfeedback_decls
[i
].find_output_var(prog
, producer
);
2343 if (!tfeedback_decls
[i
].assign_location(ctx
, prog
, output_var
))
2347 unsigned varying_vectors
= 0;
2350 foreach_list(node
, consumer
->ir
) {
2351 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
2353 if ((var
== NULL
) || (var
->mode
!= ir_var_in
))
2356 if (var
->is_unmatched_generic_inout
) {
2357 if (prog
->Version
<= 120) {
2358 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
2360 * Only those varying variables used (i.e. read) in
2361 * the fragment shader executable must be written to
2362 * by the vertex shader executable; declaring
2363 * superfluous varying variables in a vertex shader is
2366 * We interpret this text as meaning that the VS must
2367 * write the variable for the FS to read it. See
2368 * "glsl1-varying read but not written" in piglit.
2371 linker_error(prog
, "fragment shader varying %s not written "
2372 "by vertex shader\n.", var
->name
);
2375 /* An 'in' variable is only really a shader input if its
2376 * value is written by the previous stage.
2378 var
->mode
= ir_var_auto
;
2379 } else if (is_varying_var(consumer
->Type
, var
)) {
2380 /* The packing rules are used for vertex shader inputs are also
2381 * used for fragment shader inputs.
2383 varying_vectors
+= count_attribute_slots(var
->type
);
2388 if (ctx
->API
== API_OPENGLES2
|| prog
->IsES
) {
2389 if (varying_vectors
> ctx
->Const
.MaxVarying
) {
2390 if (ctx
->Const
.GLSLSkipStrictMaxVaryingLimitCheck
) {
2391 linker_warning(prog
, "shader uses too many varying vectors "
2392 "(%u > %u), but the driver will try to optimize "
2393 "them out; this is non-portable out-of-spec "
2395 varying_vectors
, ctx
->Const
.MaxVarying
);
2397 linker_error(prog
, "shader uses too many varying vectors "
2399 varying_vectors
, ctx
->Const
.MaxVarying
);
2404 const unsigned float_components
= varying_vectors
* 4;
2405 if (float_components
> ctx
->Const
.MaxVarying
* 4) {
2406 if (ctx
->Const
.GLSLSkipStrictMaxVaryingLimitCheck
) {
2407 linker_warning(prog
, "shader uses too many varying components "
2408 "(%u > %u), but the driver will try to optimize "
2409 "them out; this is non-portable out-of-spec "
2411 float_components
, ctx
->Const
.MaxVarying
* 4);
2413 linker_error(prog
, "shader uses too many varying components "
2415 float_components
, ctx
->Const
.MaxVarying
* 4);
2426 * Store transform feedback location assignments into
2427 * prog->LinkedTransformFeedback based on the data stored in tfeedback_decls.
2429 * If an error occurs, the error is reported through linker_error() and false
2433 store_tfeedback_info(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
2434 unsigned num_tfeedback_decls
,
2435 tfeedback_decl
*tfeedback_decls
)
2437 bool separate_attribs_mode
=
2438 prog
->TransformFeedback
.BufferMode
== GL_SEPARATE_ATTRIBS
;
2440 ralloc_free(prog
->LinkedTransformFeedback
.Varyings
);
2441 ralloc_free(prog
->LinkedTransformFeedback
.Outputs
);
2443 memset(&prog
->LinkedTransformFeedback
, 0,
2444 sizeof(prog
->LinkedTransformFeedback
));
2446 prog
->LinkedTransformFeedback
.Varyings
=
2448 struct gl_transform_feedback_varying_info
,
2449 num_tfeedback_decls
);
2451 unsigned num_outputs
= 0;
2452 for (unsigned i
= 0; i
< num_tfeedback_decls
; ++i
)
2453 num_outputs
+= tfeedback_decls
[i
].get_num_outputs();
2455 prog
->LinkedTransformFeedback
.Outputs
=
2457 struct gl_transform_feedback_output
,
2460 unsigned num_buffers
= 0;
2462 if (separate_attribs_mode
) {
2463 /* GL_SEPARATE_ATTRIBS */
2464 for (unsigned i
= 0; i
< num_tfeedback_decls
; ++i
) {
2465 if (!tfeedback_decls
[i
].store(ctx
, prog
, &prog
->LinkedTransformFeedback
,
2466 num_buffers
, num_outputs
))
2473 /* GL_INVERLEAVED_ATTRIBS */
2474 for (unsigned i
= 0; i
< num_tfeedback_decls
; ++i
) {
2475 if (tfeedback_decls
[i
].is_next_buffer_separator()) {
2480 if (!tfeedback_decls
[i
].store(ctx
, prog
,
2481 &prog
->LinkedTransformFeedback
,
2482 num_buffers
, num_outputs
))
2488 assert(prog
->LinkedTransformFeedback
.NumOutputs
== num_outputs
);
2490 prog
->LinkedTransformFeedback
.NumBuffers
= num_buffers
;
2495 * Store the gl_FragDepth layout in the gl_shader_program struct.
2498 store_fragdepth_layout(struct gl_shader_program
*prog
)
2500 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
2504 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
2506 /* We don't look up the gl_FragDepth symbol directly because if
2507 * gl_FragDepth is not used in the shader, it's removed from the IR.
2508 * However, the symbol won't be removed from the symbol table.
2510 * We're only interested in the cases where the variable is NOT removed
2513 foreach_list(node
, ir
) {
2514 ir_variable
*const var
= ((ir_instruction
*) node
)->as_variable();
2516 if (var
== NULL
|| var
->mode
!= ir_var_out
) {
2520 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
2521 switch (var
->depth_layout
) {
2522 case ir_depth_layout_none
:
2523 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
2525 case ir_depth_layout_any
:
2526 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
2528 case ir_depth_layout_greater
:
2529 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
2531 case ir_depth_layout_less
:
2532 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
2534 case ir_depth_layout_unchanged
:
2535 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
2546 * Validate the resources used by a program versus the implementation limits
2549 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2551 static const char *const shader_names
[MESA_SHADER_TYPES
] = {
2552 "vertex", "fragment", "geometry"
2555 const unsigned max_samplers
[MESA_SHADER_TYPES
] = {
2556 ctx
->Const
.MaxVertexTextureImageUnits
,
2557 ctx
->Const
.MaxTextureImageUnits
,
2558 ctx
->Const
.MaxGeometryTextureImageUnits
2561 const unsigned max_uniform_components
[MESA_SHADER_TYPES
] = {
2562 ctx
->Const
.VertexProgram
.MaxUniformComponents
,
2563 ctx
->Const
.FragmentProgram
.MaxUniformComponents
,
2564 0 /* FINISHME: Geometry shaders. */
2567 const unsigned max_uniform_blocks
[MESA_SHADER_TYPES
] = {
2568 ctx
->Const
.VertexProgram
.MaxUniformBlocks
,
2569 ctx
->Const
.FragmentProgram
.MaxUniformBlocks
,
2570 ctx
->Const
.GeometryProgram
.MaxUniformBlocks
,
2573 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2574 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2579 if (sh
->num_samplers
> max_samplers
[i
]) {
2580 linker_error(prog
, "Too many %s shader texture samplers",
2584 if (sh
->num_uniform_components
> max_uniform_components
[i
]) {
2585 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2586 linker_warning(prog
, "Too many %s shader uniform components, "
2587 "but the driver will try to optimize them out; "
2588 "this is non-portable out-of-spec behavior\n",
2591 linker_error(prog
, "Too many %s shader uniform components",
2597 unsigned blocks
[MESA_SHADER_TYPES
] = {0};
2598 unsigned total_uniform_blocks
= 0;
2600 for (unsigned i
= 0; i
< prog
->NumUniformBlocks
; i
++) {
2601 for (unsigned j
= 0; j
< MESA_SHADER_TYPES
; j
++) {
2602 if (prog
->UniformBlockStageIndex
[j
][i
] != -1) {
2604 total_uniform_blocks
++;
2608 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
2609 linker_error(prog
, "Too many combined uniform blocks (%d/%d)",
2610 prog
->NumUniformBlocks
,
2611 ctx
->Const
.MaxCombinedUniformBlocks
);
2613 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2614 if (blocks
[i
] > max_uniform_blocks
[i
]) {
2615 linker_error(prog
, "Too many %s uniform blocks (%d/%d)",
2618 max_uniform_blocks
[i
]);
2625 return prog
->LinkStatus
;
2629 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2631 tfeedback_decl
*tfeedback_decls
= NULL
;
2632 unsigned num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
2634 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
2636 prog
->LinkStatus
= false;
2637 prog
->Validated
= false;
2638 prog
->_Used
= false;
2640 ralloc_free(prog
->InfoLog
);
2641 prog
->InfoLog
= ralloc_strdup(NULL
, "");
2643 ralloc_free(prog
->UniformBlocks
);
2644 prog
->UniformBlocks
= NULL
;
2645 prog
->NumUniformBlocks
= 0;
2646 for (int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2647 ralloc_free(prog
->UniformBlockStageIndex
[i
]);
2648 prog
->UniformBlockStageIndex
[i
] = NULL
;
2651 /* Separate the shaders into groups based on their type.
2653 struct gl_shader
**vert_shader_list
;
2654 unsigned num_vert_shaders
= 0;
2655 struct gl_shader
**frag_shader_list
;
2656 unsigned num_frag_shaders
= 0;
2658 vert_shader_list
= (struct gl_shader
**)
2659 calloc(2 * prog
->NumShaders
, sizeof(struct gl_shader
*));
2660 frag_shader_list
= &vert_shader_list
[prog
->NumShaders
];
2662 unsigned min_version
= UINT_MAX
;
2663 unsigned max_version
= 0;
2664 const bool is_es_prog
=
2665 (prog
->NumShaders
> 0 && prog
->Shaders
[0]->IsES
) ? true : false;
2666 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
2667 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
2668 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
2670 if (prog
->Shaders
[i
]->IsES
!= is_es_prog
) {
2671 linker_error(prog
, "all shaders must use same shading "
2672 "language version\n");
2676 switch (prog
->Shaders
[i
]->Type
) {
2677 case GL_VERTEX_SHADER
:
2678 vert_shader_list
[num_vert_shaders
] = prog
->Shaders
[i
];
2681 case GL_FRAGMENT_SHADER
:
2682 frag_shader_list
[num_frag_shaders
] = prog
->Shaders
[i
];
2685 case GL_GEOMETRY_SHADER
:
2686 /* FINISHME: Support geometry shaders. */
2687 assert(prog
->Shaders
[i
]->Type
!= GL_GEOMETRY_SHADER
);
2692 /* Previous to GLSL version 1.30, different compilation units could mix and
2693 * match shading language versions. With GLSL 1.30 and later, the versions
2694 * of all shaders must match.
2696 * GLSL ES has never allowed mixing of shading language versions.
2698 if ((is_es_prog
|| max_version
>= 130)
2699 && min_version
!= max_version
) {
2700 linker_error(prog
, "all shaders must use same shading "
2701 "language version\n");
2705 prog
->Version
= max_version
;
2706 prog
->IsES
= is_es_prog
;
2708 for (unsigned int i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2709 if (prog
->_LinkedShaders
[i
] != NULL
)
2710 ctx
->Driver
.DeleteShader(ctx
, prog
->_LinkedShaders
[i
]);
2712 prog
->_LinkedShaders
[i
] = NULL
;
2715 /* Link all shaders for a particular stage and validate the result.
2717 if (num_vert_shaders
> 0) {
2718 gl_shader
*const sh
=
2719 link_intrastage_shaders(mem_ctx
, ctx
, prog
, vert_shader_list
,
2725 if (!validate_vertex_shader_executable(prog
, sh
))
2728 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
2732 if (num_frag_shaders
> 0) {
2733 gl_shader
*const sh
=
2734 link_intrastage_shaders(mem_ctx
, ctx
, prog
, frag_shader_list
,
2740 if (!validate_fragment_shader_executable(prog
, sh
))
2743 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
],
2747 /* Here begins the inter-stage linking phase. Some initial validation is
2748 * performed, then locations are assigned for uniforms, attributes, and
2751 if (cross_validate_uniforms(prog
)) {
2754 for (prev
= 0; prev
< MESA_SHADER_TYPES
; prev
++) {
2755 if (prog
->_LinkedShaders
[prev
] != NULL
)
2759 /* Validate the inputs of each stage with the output of the preceding
2762 for (unsigned i
= prev
+ 1; i
< MESA_SHADER_TYPES
; i
++) {
2763 if (prog
->_LinkedShaders
[i
] == NULL
)
2766 if (!cross_validate_outputs_to_inputs(prog
,
2767 prog
->_LinkedShaders
[prev
],
2768 prog
->_LinkedShaders
[i
]))
2774 prog
->LinkStatus
= true;
2777 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
2778 * it before optimization because we want most of the checks to get
2779 * dropped thanks to constant propagation.
2781 * This rule also applies to GLSL ES 3.00.
2783 if (max_version
>= (is_es_prog
? 300 : 130)) {
2784 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
2786 lower_discard_flow(sh
->ir
);
2790 if (!interstage_cross_validate_uniform_blocks(prog
))
2793 /* Do common optimization before assigning storage for attributes,
2794 * uniforms, and varyings. Later optimization could possibly make
2795 * some of that unused.
2797 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2798 if (prog
->_LinkedShaders
[i
] == NULL
)
2801 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
2802 if (!prog
->LinkStatus
)
2805 if (ctx
->ShaderCompilerOptions
[i
].LowerClipDistance
) {
2806 lower_clip_distance(prog
->_LinkedShaders
[i
]);
2809 unsigned max_unroll
= ctx
->ShaderCompilerOptions
[i
].MaxUnrollIterations
;
2811 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false, max_unroll
))
2815 /* Mark all generic shader inputs and outputs as unpaired. */
2816 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] != NULL
) {
2817 link_invalidate_variable_locations(
2818 prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
2819 VERT_ATTRIB_GENERIC0
, VERT_RESULT_VAR0
);
2821 /* FINISHME: Geometry shaders not implemented yet */
2822 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] != NULL
) {
2823 link_invalidate_variable_locations(
2824 prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
],
2825 FRAG_ATTRIB_VAR0
, FRAG_RESULT_DATA0
);
2828 /* FINISHME: The value of the max_attribute_index parameter is
2829 * FINISHME: implementation dependent based on the value of
2830 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
2831 * FINISHME: at least 16, so hardcode 16 for now.
2833 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_VERTEX
, 16)) {
2837 if (!assign_attribute_or_color_locations(prog
, MESA_SHADER_FRAGMENT
, MAX2(ctx
->Const
.MaxDrawBuffers
, ctx
->Const
.MaxDualSourceDrawBuffers
))) {
2842 for (prev
= 0; prev
< MESA_SHADER_TYPES
; prev
++) {
2843 if (prog
->_LinkedShaders
[prev
] != NULL
)
2847 if (num_tfeedback_decls
!= 0) {
2848 /* From GL_EXT_transform_feedback:
2849 * A program will fail to link if:
2851 * * the <count> specified by TransformFeedbackVaryingsEXT is
2852 * non-zero, but the program object has no vertex or geometry
2855 if (prev
>= MESA_SHADER_FRAGMENT
) {
2856 linker_error(prog
, "Transform feedback varyings specified, but "
2857 "no vertex or geometry shader is present.");
2861 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
2862 prog
->TransformFeedback
.NumVarying
);
2863 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
2864 prog
->TransformFeedback
.VaryingNames
,
2869 for (unsigned i
= prev
+ 1; i
< MESA_SHADER_TYPES
; i
++) {
2870 if (prog
->_LinkedShaders
[i
] == NULL
)
2873 if (!assign_varying_locations(
2874 ctx
, prog
, prog
->_LinkedShaders
[prev
], prog
->_LinkedShaders
[i
],
2875 i
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
2882 if (prev
!= MESA_SHADER_FRAGMENT
&& num_tfeedback_decls
!= 0) {
2883 /* There was no fragment shader, but we still have to assign varying
2884 * locations for use by transform feedback.
2886 if (!assign_varying_locations(
2887 ctx
, prog
, prog
->_LinkedShaders
[prev
], NULL
, num_tfeedback_decls
,
2892 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
))
2895 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] != NULL
) {
2896 demote_shader_inputs_and_outputs(prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
2899 /* Eliminate code that is now dead due to unused vertex outputs being
2902 while (do_dead_code(prog
->_LinkedShaders
[MESA_SHADER_VERTEX
]->ir
, false))
2906 if (prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
] != NULL
) {
2907 gl_shader
*const sh
= prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
];
2909 demote_shader_inputs_and_outputs(sh
, ir_var_in
);
2910 demote_shader_inputs_and_outputs(sh
, ir_var_inout
);
2911 demote_shader_inputs_and_outputs(sh
, ir_var_out
);
2913 /* Eliminate code that is now dead due to unused geometry outputs being
2916 while (do_dead_code(prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
]->ir
, false))
2920 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] != NULL
) {
2921 gl_shader
*const sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
2923 demote_shader_inputs_and_outputs(sh
, ir_var_in
);
2925 /* Eliminate code that is now dead due to unused fragment inputs being
2926 * demoted. This shouldn't actually do anything other than remove
2927 * declarations of the (now unused) global variables.
2929 while (do_dead_code(prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
, false))
2933 update_array_sizes(prog
);
2934 link_assign_uniform_locations(prog
);
2935 store_fragdepth_layout(prog
);
2937 if (!check_resources(ctx
, prog
))
2940 /* OpenGL ES requires that a vertex shader and a fragment shader both be
2941 * present in a linked program. By checking prog->IsES, we also
2942 * catch the GL_ARB_ES2_compatibility case.
2944 if (!prog
->InternalSeparateShader
&&
2945 (ctx
->API
== API_OPENGLES2
|| prog
->IsES
)) {
2946 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
2947 linker_error(prog
, "program lacks a vertex shader\n");
2948 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
2949 linker_error(prog
, "program lacks a fragment shader\n");
2953 /* FINISHME: Assign fragment shader output locations. */
2956 free(vert_shader_list
);
2958 for (unsigned i
= 0; i
< MESA_SHADER_TYPES
; i
++) {
2959 if (prog
->_LinkedShaders
[i
] == NULL
)
2962 /* Retain any live IR, but trash the rest. */
2963 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
2965 /* The symbol table in the linked shaders may contain references to
2966 * variables that were removed (e.g., unused uniforms). Since it may
2967 * contain junk, there is no possible valid use. Delete it and set the
2970 delete prog
->_LinkedShaders
[i
]->symbols
;
2971 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
2974 ralloc_free(mem_ctx
);