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>
68 #include "util/strndup.h"
69 #include "main/core.h"
70 #include "glsl_symbol_table.h"
71 #include "glsl_parser_extras.h"
74 #include "program/hash_table.h"
76 #include "link_varyings.h"
77 #include "ir_optimization.h"
78 #include "ir_rvalue_visitor.h"
79 #include "ir_uniform.h"
81 #include "main/shaderobj.h"
82 #include "main/enums.h"
88 * Visitor that determines whether or not a variable is ever written.
90 class find_assignment_visitor
: public ir_hierarchical_visitor
{
92 find_assignment_visitor(const char *name
)
93 : name(name
), found(false)
98 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
100 ir_variable
*const var
= ir
->lhs
->variable_referenced();
102 if (strcmp(name
, var
->name
) == 0) {
107 return visit_continue_with_parent
;
110 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
112 foreach_two_lists(formal_node
, &ir
->callee
->parameters
,
113 actual_node
, &ir
->actual_parameters
) {
114 ir_rvalue
*param_rval
= (ir_rvalue
*) actual_node
;
115 ir_variable
*sig_param
= (ir_variable
*) formal_node
;
117 if (sig_param
->data
.mode
== ir_var_function_out
||
118 sig_param
->data
.mode
== ir_var_function_inout
) {
119 ir_variable
*var
= param_rval
->variable_referenced();
120 if (var
&& strcmp(name
, var
->name
) == 0) {
127 if (ir
->return_deref
!= NULL
) {
128 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
130 if (strcmp(name
, var
->name
) == 0) {
136 return visit_continue_with_parent
;
139 bool variable_found()
145 const char *name
; /**< Find writes to a variable with this name. */
146 bool found
; /**< Was a write to the variable found? */
151 * Visitor that determines whether or not a variable is ever read.
153 class find_deref_visitor
: public ir_hierarchical_visitor
{
155 find_deref_visitor(const char *name
)
156 : name(name
), found(false)
161 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
163 if (strcmp(this->name
, ir
->var
->name
) == 0) {
168 return visit_continue
;
171 bool variable_found() const
177 const char *name
; /**< Find writes to a variable with this name. */
178 bool found
; /**< Was a write to the variable found? */
182 class geom_array_resize_visitor
: public ir_hierarchical_visitor
{
184 unsigned num_vertices
;
185 gl_shader_program
*prog
;
187 geom_array_resize_visitor(unsigned num_vertices
, gl_shader_program
*prog
)
189 this->num_vertices
= num_vertices
;
193 virtual ~geom_array_resize_visitor()
198 virtual ir_visitor_status
visit(ir_variable
*var
)
200 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
)
201 return visit_continue
;
203 unsigned size
= var
->type
->length
;
205 /* Generate a link error if the shader has declared this array with an
208 if (size
&& size
!= this->num_vertices
) {
209 linker_error(this->prog
, "size of array %s declared as %u, "
210 "but number of input vertices is %u\n",
211 var
->name
, size
, this->num_vertices
);
212 return visit_continue
;
215 /* Generate a link error if the shader attempts to access an input
216 * array using an index too large for its actual size assigned at link
219 if (var
->data
.max_array_access
>= this->num_vertices
) {
220 linker_error(this->prog
, "geometry shader accesses element %i of "
221 "%s, but only %i input vertices\n",
222 var
->data
.max_array_access
, var
->name
, this->num_vertices
);
223 return visit_continue
;
226 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
228 var
->data
.max_array_access
= this->num_vertices
- 1;
230 return visit_continue
;
233 /* Dereferences of input variables need to be updated so that their type
234 * matches the newly assigned type of the variable they are accessing. */
235 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
237 ir
->type
= ir
->var
->type
;
238 return visit_continue
;
241 /* Dereferences of 2D input arrays need to be updated so that their type
242 * matches the newly assigned type of the array they are accessing. */
243 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
245 const glsl_type
*const vt
= ir
->array
->type
;
247 ir
->type
= vt
->fields
.array
;
248 return visit_continue
;
252 class tess_eval_array_resize_visitor
: public ir_hierarchical_visitor
{
254 unsigned num_vertices
;
255 gl_shader_program
*prog
;
257 tess_eval_array_resize_visitor(unsigned num_vertices
, gl_shader_program
*prog
)
259 this->num_vertices
= num_vertices
;
263 virtual ~tess_eval_array_resize_visitor()
268 virtual ir_visitor_status
visit(ir_variable
*var
)
270 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
|| var
->data
.patch
)
271 return visit_continue
;
273 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
275 var
->data
.max_array_access
= this->num_vertices
- 1;
277 return visit_continue
;
280 /* Dereferences of input variables need to be updated so that their type
281 * matches the newly assigned type of the variable they are accessing. */
282 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
284 ir
->type
= ir
->var
->type
;
285 return visit_continue
;
288 /* Dereferences of 2D input arrays need to be updated so that their type
289 * matches the newly assigned type of the array they are accessing. */
290 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
292 const glsl_type
*const vt
= ir
->array
->type
;
294 ir
->type
= vt
->fields
.array
;
295 return visit_continue
;
299 class barrier_use_visitor
: public ir_hierarchical_visitor
{
301 barrier_use_visitor(gl_shader_program
*prog
)
302 : prog(prog
), in_main(false), after_return(false), control_flow(0)
306 virtual ~barrier_use_visitor()
311 virtual ir_visitor_status
visit_enter(ir_function
*ir
)
313 if (strcmp(ir
->name
, "main") == 0)
316 return visit_continue
;
319 virtual ir_visitor_status
visit_leave(ir_function
*)
322 after_return
= false;
323 return visit_continue
;
326 virtual ir_visitor_status
visit_leave(ir_return
*)
329 return visit_continue
;
332 virtual ir_visitor_status
visit_enter(ir_if
*)
335 return visit_continue
;
338 virtual ir_visitor_status
visit_leave(ir_if
*)
341 return visit_continue
;
344 virtual ir_visitor_status
visit_enter(ir_loop
*)
347 return visit_continue
;
350 virtual ir_visitor_status
visit_leave(ir_loop
*)
353 return visit_continue
;
356 /* FINISHME: `switch` is not expressed at the IR level -- it's already
357 * been lowered to a mess of `if`s. We'll correctly disallow any use of
358 * barrier() in a conditional path within the switch, but not in a path
359 * which is always hit.
362 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
364 if (ir
->use_builtin
&& strcmp(ir
->callee_name(), "barrier") == 0) {
365 /* Use of barrier(); determine if it is legal: */
367 linker_error(prog
, "Builtin barrier() may only be used in main");
372 linker_error(prog
, "Builtin barrier() may not be used after return");
376 if (control_flow
!= 0) {
377 linker_error(prog
, "Builtin barrier() may not be used inside control flow");
381 return visit_continue
;
385 gl_shader_program
*prog
;
386 bool in_main
, after_return
;
391 * Visitor that determines the highest stream id to which a (geometry) shader
392 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
394 class find_emit_vertex_visitor
: public ir_hierarchical_visitor
{
396 find_emit_vertex_visitor(int max_allowed
)
397 : max_stream_allowed(max_allowed
),
398 invalid_stream_id(0),
399 invalid_stream_id_from_emit_vertex(false),
400 end_primitive_found(false),
401 uses_non_zero_stream(false)
406 virtual ir_visitor_status
visit_leave(ir_emit_vertex
*ir
)
408 int stream_id
= ir
->stream_id();
411 invalid_stream_id
= stream_id
;
412 invalid_stream_id_from_emit_vertex
= true;
416 if (stream_id
> max_stream_allowed
) {
417 invalid_stream_id
= stream_id
;
418 invalid_stream_id_from_emit_vertex
= true;
423 uses_non_zero_stream
= true;
425 return visit_continue
;
428 virtual ir_visitor_status
visit_leave(ir_end_primitive
*ir
)
430 end_primitive_found
= true;
432 int stream_id
= ir
->stream_id();
435 invalid_stream_id
= stream_id
;
436 invalid_stream_id_from_emit_vertex
= false;
440 if (stream_id
> max_stream_allowed
) {
441 invalid_stream_id
= stream_id
;
442 invalid_stream_id_from_emit_vertex
= false;
447 uses_non_zero_stream
= true;
449 return visit_continue
;
454 return invalid_stream_id
!= 0;
457 const char *error_func()
459 return invalid_stream_id_from_emit_vertex
?
460 "EmitStreamVertex" : "EndStreamPrimitive";
465 return invalid_stream_id
;
470 return uses_non_zero_stream
;
473 bool uses_end_primitive()
475 return end_primitive_found
;
479 int max_stream_allowed
;
480 int invalid_stream_id
;
481 bool invalid_stream_id_from_emit_vertex
;
482 bool end_primitive_found
;
483 bool uses_non_zero_stream
;
486 /* Class that finds array derefs and check if indexes are dynamic. */
487 class dynamic_sampler_array_indexing_visitor
: public ir_hierarchical_visitor
490 dynamic_sampler_array_indexing_visitor() :
491 dynamic_sampler_array_indexing(false)
495 ir_visitor_status
visit_enter(ir_dereference_array
*ir
)
497 if (!ir
->variable_referenced())
498 return visit_continue
;
500 if (!ir
->variable_referenced()->type
->contains_sampler())
501 return visit_continue
;
503 if (!ir
->array_index
->constant_expression_value()) {
504 dynamic_sampler_array_indexing
= true;
507 return visit_continue
;
510 bool uses_dynamic_sampler_array_indexing()
512 return dynamic_sampler_array_indexing
;
516 bool dynamic_sampler_array_indexing
;
519 } /* anonymous namespace */
522 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
526 ralloc_strcat(&prog
->InfoLog
, "error: ");
528 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
531 prog
->LinkStatus
= false;
536 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
540 ralloc_strcat(&prog
->InfoLog
, "warning: ");
542 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
549 * Given a string identifying a program resource, break it into a base name
550 * and an optional array index in square brackets.
552 * If an array index is present, \c out_base_name_end is set to point to the
553 * "[" that precedes the array index, and the array index itself is returned
556 * If no array index is present (or if the array index is negative or
557 * mal-formed), \c out_base_name_end, is set to point to the null terminator
558 * at the end of the input string, and -1 is returned.
560 * Only the final array index is parsed; if the string contains other array
561 * indices (or structure field accesses), they are left in the base name.
563 * No attempt is made to check that the base name is properly formed;
564 * typically the caller will look up the base name in a hash table, so
565 * ill-formed base names simply turn into hash table lookup failures.
568 parse_program_resource_name(const GLchar
*name
,
569 const GLchar
**out_base_name_end
)
571 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
573 * "When an integer array element or block instance number is part of
574 * the name string, it will be specified in decimal form without a "+"
575 * or "-" sign or any extra leading zeroes. Additionally, the name
576 * string will not include white space anywhere in the string."
579 const size_t len
= strlen(name
);
580 *out_base_name_end
= name
+ len
;
582 if (len
== 0 || name
[len
-1] != ']')
585 /* Walk backwards over the string looking for a non-digit character. This
586 * had better be the opening bracket for an array index.
588 * Initially, i specifies the location of the ']'. Since the string may
589 * contain only the ']' charcater, walk backwards very carefully.
592 for (i
= len
- 1; (i
> 0) && isdigit(name
[i
-1]); --i
)
595 if ((i
== 0) || name
[i
-1] != '[')
598 long array_index
= strtol(&name
[i
], NULL
, 10);
602 /* Check for leading zero */
603 if (name
[i
] == '0' && name
[i
+1] != ']')
606 *out_base_name_end
= name
+ (i
- 1);
612 link_invalidate_variable_locations(exec_list
*ir
)
614 foreach_in_list(ir_instruction
, node
, ir
) {
615 ir_variable
*const var
= node
->as_variable();
620 /* Only assign locations for variables that lack an explicit location.
621 * Explicit locations are set for all built-in variables, generic vertex
622 * shader inputs (via layout(location=...)), and generic fragment shader
623 * outputs (also via layout(location=...)).
625 if (!var
->data
.explicit_location
) {
626 var
->data
.location
= -1;
627 var
->data
.location_frac
= 0;
630 /* ir_variable::is_unmatched_generic_inout is used by the linker while
631 * connecting outputs from one stage to inputs of the next stage.
633 if (var
->data
.explicit_location
&&
634 var
->data
.location
< VARYING_SLOT_VAR0
) {
635 var
->data
.is_unmatched_generic_inout
= 0;
637 var
->data
.is_unmatched_generic_inout
= 1;
644 * Set clip_distance_array_size based on the given shader.
646 * Also check for errors based on incorrect usage of gl_ClipVertex and
649 * Return false if an error was reported.
652 analyze_clip_usage(struct gl_shader_program
*prog
,
653 struct gl_shader
*shader
,
654 GLuint
*clip_distance_array_size
)
656 *clip_distance_array_size
= 0;
658 if (!prog
->IsES
&& prog
->Version
>= 130) {
659 /* From section 7.1 (Vertex Shader Special Variables) of the
662 * "It is an error for a shader to statically write both
663 * gl_ClipVertex and gl_ClipDistance."
665 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
666 * gl_ClipVertex nor gl_ClipDistance.
668 find_assignment_visitor
clip_vertex("gl_ClipVertex");
669 find_assignment_visitor
clip_distance("gl_ClipDistance");
671 clip_vertex
.run(shader
->ir
);
672 clip_distance
.run(shader
->ir
);
673 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
674 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
675 "and `gl_ClipDistance'\n",
676 _mesa_shader_stage_to_string(shader
->Stage
));
680 if (clip_distance
.variable_found()) {
681 ir_variable
*clip_distance_var
=
682 shader
->symbols
->get_variable("gl_ClipDistance");
684 assert(clip_distance_var
);
685 *clip_distance_array_size
= clip_distance_var
->type
->length
;
692 * Verify that a vertex shader executable meets all semantic requirements.
694 * Also sets prog->Vert.ClipDistanceArraySize as a side effect.
696 * \param shader Vertex shader executable to be verified
699 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
700 struct gl_shader
*shader
)
705 /* From the GLSL 1.10 spec, page 48:
707 * "The variable gl_Position is available only in the vertex
708 * language and is intended for writing the homogeneous vertex
709 * position. All executions of a well-formed vertex shader
710 * executable must write a value into this variable. [...] The
711 * variable gl_Position is available only in the vertex
712 * language and is intended for writing the homogeneous vertex
713 * position. All executions of a well-formed vertex shader
714 * executable must write a value into this variable."
716 * while in GLSL 1.40 this text is changed to:
718 * "The variable gl_Position is available only in the vertex
719 * language and is intended for writing the homogeneous vertex
720 * position. It can be written at any time during shader
721 * execution. It may also be read back by a vertex shader
722 * after being written. This value will be used by primitive
723 * assembly, clipping, culling, and other fixed functionality
724 * operations, if present, that operate on primitives after
725 * vertex processing has occurred. Its value is undefined if
726 * the vertex shader executable does not write gl_Position."
728 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
729 * gl_Position is not an error.
731 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
732 find_assignment_visitor
find("gl_Position");
733 find
.run(shader
->ir
);
734 if (!find
.variable_found()) {
737 "vertex shader does not write to `gl_Position'."
738 "It's value is undefined. \n");
741 "vertex shader does not write to `gl_Position'. \n");
747 analyze_clip_usage(prog
, shader
, &prog
->Vert
.ClipDistanceArraySize
);
751 validate_tess_eval_shader_executable(struct gl_shader_program
*prog
,
752 struct gl_shader
*shader
)
757 analyze_clip_usage(prog
, shader
, &prog
->TessEval
.ClipDistanceArraySize
);
762 * Verify that a fragment shader executable meets all semantic requirements
764 * \param shader Fragment shader executable to be verified
767 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
768 struct gl_shader
*shader
)
773 find_assignment_visitor
frag_color("gl_FragColor");
774 find_assignment_visitor
frag_data("gl_FragData");
776 frag_color
.run(shader
->ir
);
777 frag_data
.run(shader
->ir
);
779 if (frag_color
.variable_found() && frag_data
.variable_found()) {
780 linker_error(prog
, "fragment shader writes to both "
781 "`gl_FragColor' and `gl_FragData'\n");
786 * Verify that a geometry shader executable meets all semantic requirements
788 * Also sets prog->Geom.VerticesIn, and prog->Geom.ClipDistanceArraySize as
791 * \param shader Geometry shader executable to be verified
794 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
795 struct gl_shader
*shader
)
800 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
801 prog
->Geom
.VerticesIn
= num_vertices
;
803 analyze_clip_usage(prog
, shader
, &prog
->Geom
.ClipDistanceArraySize
);
807 * Check if geometry shaders emit to non-zero streams and do corresponding
811 validate_geometry_shader_emissions(struct gl_context
*ctx
,
812 struct gl_shader_program
*prog
)
814 if (prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
] != NULL
) {
815 find_emit_vertex_visitor
emit_vertex(ctx
->Const
.MaxVertexStreams
- 1);
816 emit_vertex
.run(prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
]->ir
);
817 if (emit_vertex
.error()) {
818 linker_error(prog
, "Invalid call %s(%d). Accepted values for the "
819 "stream parameter are in the range [0, %d].\n",
820 emit_vertex
.error_func(),
821 emit_vertex
.error_stream(),
822 ctx
->Const
.MaxVertexStreams
- 1);
824 prog
->Geom
.UsesStreams
= emit_vertex
.uses_streams();
825 prog
->Geom
.UsesEndPrimitive
= emit_vertex
.uses_end_primitive();
827 /* From the ARB_gpu_shader5 spec:
829 * "Multiple vertex streams are supported only if the output primitive
830 * type is declared to be "points". A program will fail to link if it
831 * contains a geometry shader calling EmitStreamVertex() or
832 * EndStreamPrimitive() if its output primitive type is not "points".
834 * However, in the same spec:
836 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
837 * with <stream> set to zero."
841 * "The function EndPrimitive() is equivalent to calling
842 * EndStreamPrimitive() with <stream> set to zero."
844 * Since we can call EmitVertex() and EndPrimitive() when we output
845 * primitives other than points, calling EmitStreamVertex(0) or
846 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
847 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
848 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
851 if (prog
->Geom
.UsesStreams
&& prog
->Geom
.OutputType
!= GL_POINTS
) {
852 linker_error(prog
, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
853 "with n>0 requires point output\n");
859 validate_intrastage_arrays(struct gl_shader_program
*prog
,
860 ir_variable
*const var
,
861 ir_variable
*const existing
)
863 /* Consider the types to be "the same" if both types are arrays
864 * of the same type and one of the arrays is implicitly sized.
865 * In addition, set the type of the linked variable to the
866 * explicitly sized array.
868 if (var
->type
->is_array() && existing
->type
->is_array()) {
869 if ((var
->type
->fields
.array
== existing
->type
->fields
.array
) &&
870 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
871 if (var
->type
->length
!= 0) {
872 if (var
->type
->length
<= existing
->data
.max_array_access
) {
873 linker_error(prog
, "%s `%s' declared as type "
874 "`%s' but outermost dimension has an index"
877 var
->name
, var
->type
->name
,
878 existing
->data
.max_array_access
);
880 existing
->type
= var
->type
;
882 } else if (existing
->type
->length
!= 0) {
883 if(existing
->type
->length
<= var
->data
.max_array_access
&&
884 !existing
->data
.from_ssbo_unsized_array
) {
885 linker_error(prog
, "%s `%s' declared as type "
886 "`%s' but outermost dimension has an index"
889 var
->name
, existing
->type
->name
,
890 var
->data
.max_array_access
);
895 /* The arrays of structs could have different glsl_type pointers but
896 * they are actually the same type. Use record_compare() to check that.
898 if (existing
->type
->fields
.array
->is_record() &&
899 var
->type
->fields
.array
->is_record() &&
900 existing
->type
->fields
.array
->record_compare(var
->type
->fields
.array
))
909 * Perform validation of global variables used across multiple shaders
912 cross_validate_globals(struct gl_shader_program
*prog
,
913 struct gl_shader
**shader_list
,
914 unsigned num_shaders
,
917 /* Examine all of the uniforms in all of the shaders and cross validate
920 glsl_symbol_table variables
;
921 for (unsigned i
= 0; i
< num_shaders
; i
++) {
922 if (shader_list
[i
] == NULL
)
925 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
926 ir_variable
*const var
= node
->as_variable();
931 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
934 /* don't cross validate subroutine uniforms */
935 if (var
->type
->contains_subroutine())
938 /* Don't cross validate temporaries that are at global scope. These
939 * will eventually get pulled into the shaders 'main'.
941 if (var
->data
.mode
== ir_var_temporary
)
944 /* If a global with this name has already been seen, verify that the
945 * new instance has the same type. In addition, if the globals have
946 * initializers, the values of the initializers must be the same.
948 ir_variable
*const existing
= variables
.get_variable(var
->name
);
949 if (existing
!= NULL
) {
950 /* Check if types match. Interface blocks have some special
951 * rules so we handle those elsewhere.
953 if (var
->type
!= existing
->type
&&
954 !var
->is_interface_instance()) {
955 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
956 if (var
->type
->is_record() && existing
->type
->is_record()
957 && existing
->type
->record_compare(var
->type
)) {
958 existing
->type
= var
->type
;
960 /* If it is an unsized array in a Shader Storage Block,
961 * two different shaders can access to different elements.
962 * Because of that, they might be converted to different
963 * sized arrays, then check that they are compatible but
964 * ignore the array size.
966 if (!(var
->data
.mode
== ir_var_shader_storage
&&
967 var
->data
.from_ssbo_unsized_array
&&
968 existing
->data
.mode
== ir_var_shader_storage
&&
969 existing
->data
.from_ssbo_unsized_array
&&
970 var
->type
->gl_type
== existing
->type
->gl_type
)) {
971 linker_error(prog
, "%s `%s' declared as type "
972 "`%s' and type `%s'\n",
974 var
->name
, var
->type
->name
,
975 existing
->type
->name
);
982 if (var
->data
.explicit_location
) {
983 if (existing
->data
.explicit_location
984 && (var
->data
.location
!= existing
->data
.location
)) {
985 linker_error(prog
, "explicit locations for %s "
986 "`%s' have differing values\n",
987 mode_string(var
), var
->name
);
991 if (var
->data
.location_frac
!= existing
->data
.location_frac
) {
992 linker_error(prog
, "explicit components for %s "
993 "`%s' have differing values\n",
994 mode_string(var
), var
->name
);
998 existing
->data
.location
= var
->data
.location
;
999 existing
->data
.explicit_location
= true;
1001 /* Check if uniform with implicit location was marked explicit
1002 * by earlier shader stage. If so, mark it explicit in this stage
1003 * too to make sure later processing does not treat it as
1006 if (existing
->data
.explicit_location
) {
1007 var
->data
.location
= existing
->data
.location
;
1008 var
->data
.explicit_location
= true;
1012 /* From the GLSL 4.20 specification:
1013 * "A link error will result if two compilation units in a program
1014 * specify different integer-constant bindings for the same
1015 * opaque-uniform name. However, it is not an error to specify a
1016 * binding on some but not all declarations for the same name"
1018 if (var
->data
.explicit_binding
) {
1019 if (existing
->data
.explicit_binding
&&
1020 var
->data
.binding
!= existing
->data
.binding
) {
1021 linker_error(prog
, "explicit bindings for %s "
1022 "`%s' have differing values\n",
1023 mode_string(var
), var
->name
);
1027 existing
->data
.binding
= var
->data
.binding
;
1028 existing
->data
.explicit_binding
= true;
1031 if (var
->type
->contains_atomic() &&
1032 var
->data
.offset
!= existing
->data
.offset
) {
1033 linker_error(prog
, "offset specifications for %s "
1034 "`%s' have differing values\n",
1035 mode_string(var
), var
->name
);
1039 /* Validate layout qualifiers for gl_FragDepth.
1041 * From the AMD/ARB_conservative_depth specs:
1043 * "If gl_FragDepth is redeclared in any fragment shader in a
1044 * program, it must be redeclared in all fragment shaders in
1045 * that program that have static assignments to
1046 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1047 * fragment shaders in a single program must have the same set
1050 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1051 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1052 bool layout_differs
=
1053 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1055 if (layout_declared
&& layout_differs
) {
1057 "All redeclarations of gl_FragDepth in all "
1058 "fragment shaders in a single program must have "
1059 "the same set of qualifiers.\n");
1062 if (var
->data
.used
&& layout_differs
) {
1064 "If gl_FragDepth is redeclared with a layout "
1065 "qualifier in any fragment shader, it must be "
1066 "redeclared with the same layout qualifier in "
1067 "all fragment shaders that have assignments to "
1072 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1074 * "If a shared global has multiple initializers, the
1075 * initializers must all be constant expressions, and they
1076 * must all have the same value. Otherwise, a link error will
1077 * result. (A shared global having only one initializer does
1078 * not require that initializer to be a constant expression.)"
1080 * Previous to 4.20 the GLSL spec simply said that initializers
1081 * must have the same value. In this case of non-constant
1082 * initializers, this was impossible to determine. As a result,
1083 * no vendor actually implemented that behavior. The 4.20
1084 * behavior matches the implemented behavior of at least one other
1085 * vendor, so we'll implement that for all GLSL versions.
1087 if (var
->constant_initializer
!= NULL
) {
1088 if (existing
->constant_initializer
!= NULL
) {
1089 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1090 linker_error(prog
, "initializers for %s "
1091 "`%s' have differing values\n",
1092 mode_string(var
), var
->name
);
1096 /* If the first-seen instance of a particular uniform did
1097 * not have an initializer but a later instance does,
1098 * replace the former with the later.
1100 variables
.replace_variable(existing
->name
, var
);
1104 if (var
->data
.has_initializer
) {
1105 if (existing
->data
.has_initializer
1106 && (var
->constant_initializer
== NULL
1107 || existing
->constant_initializer
== NULL
)) {
1109 "shared global variable `%s' has multiple "
1110 "non-constant initializers.\n",
1116 if (existing
->data
.invariant
!= var
->data
.invariant
) {
1117 linker_error(prog
, "declarations for %s `%s' have "
1118 "mismatching invariant qualifiers\n",
1119 mode_string(var
), var
->name
);
1122 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1123 linker_error(prog
, "declarations for %s `%s' have "
1124 "mismatching centroid qualifiers\n",
1125 mode_string(var
), var
->name
);
1128 if (existing
->data
.sample
!= var
->data
.sample
) {
1129 linker_error(prog
, "declarations for %s `%s` have "
1130 "mismatching sample qualifiers\n",
1131 mode_string(var
), var
->name
);
1134 if (existing
->data
.image_format
!= var
->data
.image_format
) {
1135 linker_error(prog
, "declarations for %s `%s` have "
1136 "mismatching image format qualifiers\n",
1137 mode_string(var
), var
->name
);
1141 variables
.add_variable(var
);
1148 * Perform validation of uniforms used across multiple shader stages
1151 cross_validate_uniforms(struct gl_shader_program
*prog
)
1153 cross_validate_globals(prog
, prog
->_LinkedShaders
,
1154 MESA_SHADER_STAGES
, true);
1158 * Accumulates the array of buffer blocks and checks that all definitions of
1159 * blocks agree on their contents.
1162 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
,
1165 int *InterfaceBlockStageIndex
[MESA_SHADER_STAGES
];
1166 struct gl_uniform_block
*blks
= NULL
;
1167 unsigned *num_blks
= validate_ssbo
? &prog
->NumShaderStorageBlocks
:
1168 &prog
->NumUniformBlocks
;
1170 unsigned max_num_buffer_blocks
= 0;
1171 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1172 if (prog
->_LinkedShaders
[i
]) {
1173 if (validate_ssbo
) {
1174 max_num_buffer_blocks
+=
1175 prog
->_LinkedShaders
[i
]->NumShaderStorageBlocks
;
1177 max_num_buffer_blocks
+=
1178 prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
1183 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1184 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1186 InterfaceBlockStageIndex
[i
] = new int[max_num_buffer_blocks
];
1187 for (unsigned int j
= 0; j
< max_num_buffer_blocks
; j
++)
1188 InterfaceBlockStageIndex
[i
][j
] = -1;
1193 unsigned sh_num_blocks
;
1194 struct gl_uniform_block
**sh_blks
;
1195 if (validate_ssbo
) {
1196 sh_num_blocks
= prog
->_LinkedShaders
[i
]->NumShaderStorageBlocks
;
1197 sh_blks
= sh
->ShaderStorageBlocks
;
1199 sh_num_blocks
= prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
1200 sh_blks
= sh
->UniformBlocks
;
1203 for (unsigned int j
= 0; j
< sh_num_blocks
; j
++) {
1204 int index
= link_cross_validate_uniform_block(prog
, &blks
, num_blks
,
1208 linker_error(prog
, "buffer block `%s' has mismatching "
1209 "definitions\n", sh_blks
[j
]->Name
);
1211 for (unsigned k
= 0; k
<= i
; k
++) {
1212 delete[] InterfaceBlockStageIndex
[k
];
1217 InterfaceBlockStageIndex
[i
][index
] = j
;
1221 /* Update per stage block pointers to point to the program list.
1222 * FIXME: We should be able to free the per stage blocks here.
1224 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1225 for (unsigned j
= 0; j
< *num_blks
; j
++) {
1226 int stage_index
= InterfaceBlockStageIndex
[i
][j
];
1228 if (stage_index
!= -1) {
1229 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1231 blks
[j
].stageref
|= (1 << i
);
1233 struct gl_uniform_block
**sh_blks
= validate_ssbo
?
1234 sh
->ShaderStorageBlocks
: sh
->UniformBlocks
;
1236 sh_blks
[stage_index
] = &blks
[j
];
1241 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1242 delete[] InterfaceBlockStageIndex
[i
];
1246 prog
->ShaderStorageBlocks
= blks
;
1248 prog
->UniformBlocks
= blks
;
1255 * Populates a shaders symbol table with all global declarations
1258 populate_symbol_table(gl_shader
*sh
)
1260 sh
->symbols
= new(sh
) glsl_symbol_table
;
1262 foreach_in_list(ir_instruction
, inst
, sh
->ir
) {
1266 if ((func
= inst
->as_function()) != NULL
) {
1267 sh
->symbols
->add_function(func
);
1268 } else if ((var
= inst
->as_variable()) != NULL
) {
1269 if (var
->data
.mode
!= ir_var_temporary
)
1270 sh
->symbols
->add_variable(var
);
1277 * Remap variables referenced in an instruction tree
1279 * This is used when instruction trees are cloned from one shader and placed in
1280 * another. These trees will contain references to \c ir_variable nodes that
1281 * do not exist in the target shader. This function finds these \c ir_variable
1282 * references and replaces the references with matching variables in the target
1285 * If there is no matching variable in the target shader, a clone of the
1286 * \c ir_variable is made and added to the target shader. The new variable is
1287 * added to \b both the instruction stream and the symbol table.
1289 * \param inst IR tree that is to be processed.
1290 * \param symbols Symbol table containing global scope symbols in the
1292 * \param instructions Instruction stream where new variable declarations
1296 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
1299 class remap_visitor
: public ir_hierarchical_visitor
{
1301 remap_visitor(struct gl_shader
*target
,
1304 this->target
= target
;
1305 this->symbols
= target
->symbols
;
1306 this->instructions
= target
->ir
;
1307 this->temps
= temps
;
1310 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1312 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1313 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
1315 assert(var
!= NULL
);
1317 return visit_continue
;
1320 ir_variable
*const existing
=
1321 this->symbols
->get_variable(ir
->var
->name
);
1322 if (existing
!= NULL
)
1325 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1327 this->symbols
->add_variable(copy
);
1328 this->instructions
->push_head(copy
);
1332 return visit_continue
;
1336 struct gl_shader
*target
;
1337 glsl_symbol_table
*symbols
;
1338 exec_list
*instructions
;
1342 remap_visitor
v(target
, temps
);
1349 * Move non-declarations from one instruction stream to another
1351 * The intended usage pattern of this function is to pass the pointer to the
1352 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1353 * pointer) for \c last and \c false for \c make_copies on the first
1354 * call. Successive calls pass the return value of the previous call for
1355 * \c last and \c true for \c make_copies.
1357 * \param instructions Source instruction stream
1358 * \param last Instruction after which new instructions should be
1359 * inserted in the target instruction stream
1360 * \param make_copies Flag selecting whether instructions in \c instructions
1361 * should be copied (via \c ir_instruction::clone) into the
1362 * target list or moved.
1365 * The new "last" instruction in the target instruction stream. This pointer
1366 * is suitable for use as the \c last parameter of a later call to this
1370 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1371 bool make_copies
, gl_shader
*target
)
1373 hash_table
*temps
= NULL
;
1376 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
1377 hash_table_pointer_compare
);
1379 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1380 if (inst
->as_function())
1383 ir_variable
*var
= inst
->as_variable();
1384 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1387 assert(inst
->as_assignment()
1389 || inst
->as_if() /* for initializers with the ?: operator */
1390 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1393 inst
= inst
->clone(target
, NULL
);
1396 hash_table_insert(temps
, inst
, var
);
1398 remap_variables(inst
, target
, temps
);
1403 last
->insert_after(inst
);
1408 hash_table_dtor(temps
);
1415 * This class is only used in link_intrastage_shaders() below but declaring
1416 * it inside that function leads to compiler warnings with some versions of
1419 class array_sizing_visitor
: public ir_hierarchical_visitor
{
1421 array_sizing_visitor()
1422 : mem_ctx(ralloc_context(NULL
)),
1423 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash
,
1424 hash_table_pointer_compare
))
1428 ~array_sizing_visitor()
1430 hash_table_dtor(this->unnamed_interfaces
);
1431 ralloc_free(this->mem_ctx
);
1434 virtual ir_visitor_status
visit(ir_variable
*var
)
1436 const glsl_type
*type_without_array
;
1437 fixup_type(&var
->type
, var
->data
.max_array_access
,
1438 var
->data
.from_ssbo_unsized_array
);
1439 type_without_array
= var
->type
->without_array();
1440 if (var
->type
->is_interface()) {
1441 if (interface_contains_unsized_arrays(var
->type
)) {
1442 const glsl_type
*new_type
=
1443 resize_interface_members(var
->type
,
1444 var
->get_max_ifc_array_access(),
1445 var
->is_in_shader_storage_block());
1446 var
->type
= new_type
;
1447 var
->change_interface_type(new_type
);
1449 } else if (type_without_array
->is_interface()) {
1450 if (interface_contains_unsized_arrays(type_without_array
)) {
1451 const glsl_type
*new_type
=
1452 resize_interface_members(type_without_array
,
1453 var
->get_max_ifc_array_access(),
1454 var
->is_in_shader_storage_block());
1455 var
->change_interface_type(new_type
);
1456 var
->type
= update_interface_members_array(var
->type
, new_type
);
1458 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1459 /* Store a pointer to the variable in the unnamed_interfaces
1462 ir_variable
**interface_vars
= (ir_variable
**)
1463 hash_table_find(this->unnamed_interfaces
, ifc_type
);
1464 if (interface_vars
== NULL
) {
1465 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1467 hash_table_insert(this->unnamed_interfaces
, interface_vars
,
1470 unsigned index
= ifc_type
->field_index(var
->name
);
1471 assert(index
< ifc_type
->length
);
1472 assert(interface_vars
[index
] == NULL
);
1473 interface_vars
[index
] = var
;
1475 return visit_continue
;
1479 * For each unnamed interface block that was discovered while running the
1480 * visitor, adjust the interface type to reflect the newly assigned array
1481 * sizes, and fix up the ir_variable nodes to point to the new interface
1484 void fixup_unnamed_interface_types()
1486 hash_table_call_foreach(this->unnamed_interfaces
,
1487 fixup_unnamed_interface_type
, NULL
);
1492 * If the type pointed to by \c type represents an unsized array, replace
1493 * it with a sized array whose size is determined by max_array_access.
1495 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1496 bool from_ssbo_unsized_array
)
1498 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1499 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1500 max_array_access
+ 1);
1501 assert(*type
!= NULL
);
1505 static const glsl_type
*
1506 update_interface_members_array(const glsl_type
*type
,
1507 const glsl_type
*new_interface_type
)
1509 const glsl_type
*element_type
= type
->fields
.array
;
1510 if (element_type
->is_array()) {
1511 const glsl_type
*new_array_type
=
1512 update_interface_members_array(element_type
, new_interface_type
);
1513 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1515 return glsl_type::get_array_instance(new_interface_type
,
1521 * Determine whether the given interface type contains unsized arrays (if
1522 * it doesn't, array_sizing_visitor doesn't need to process it).
1524 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1526 for (unsigned i
= 0; i
< type
->length
; i
++) {
1527 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1528 if (elem_type
->is_unsized_array())
1535 * Create a new interface type based on the given type, with unsized arrays
1536 * replaced by sized arrays whose size is determined by
1537 * max_ifc_array_access.
1539 static const glsl_type
*
1540 resize_interface_members(const glsl_type
*type
,
1541 const unsigned *max_ifc_array_access
,
1544 unsigned num_fields
= type
->length
;
1545 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1546 memcpy(fields
, type
->fields
.structure
,
1547 num_fields
* sizeof(*fields
));
1548 for (unsigned i
= 0; i
< num_fields
; i
++) {
1549 /* If SSBO last member is unsized array, we don't replace it by a sized
1552 if (is_ssbo
&& i
== (num_fields
- 1))
1553 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1556 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1559 glsl_interface_packing packing
=
1560 (glsl_interface_packing
) type
->interface_packing
;
1561 const glsl_type
*new_ifc_type
=
1562 glsl_type::get_interface_instance(fields
, num_fields
,
1563 packing
, type
->name
);
1565 return new_ifc_type
;
1568 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1571 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1572 ir_variable
**interface_vars
= (ir_variable
**) data
;
1573 unsigned num_fields
= ifc_type
->length
;
1574 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1575 memcpy(fields
, ifc_type
->fields
.structure
,
1576 num_fields
* sizeof(*fields
));
1577 bool interface_type_changed
= false;
1578 for (unsigned i
= 0; i
< num_fields
; i
++) {
1579 if (interface_vars
[i
] != NULL
&&
1580 fields
[i
].type
!= interface_vars
[i
]->type
) {
1581 fields
[i
].type
= interface_vars
[i
]->type
;
1582 interface_type_changed
= true;
1585 if (!interface_type_changed
) {
1589 glsl_interface_packing packing
=
1590 (glsl_interface_packing
) ifc_type
->interface_packing
;
1591 const glsl_type
*new_ifc_type
=
1592 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1595 for (unsigned i
= 0; i
< num_fields
; i
++) {
1596 if (interface_vars
[i
] != NULL
)
1597 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1602 * Memory context used to allocate the data in \c unnamed_interfaces.
1607 * Hash table from const glsl_type * to an array of ir_variable *'s
1608 * pointing to the ir_variables constituting each unnamed interface block.
1610 hash_table
*unnamed_interfaces
;
1614 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1618 link_xfb_stride_layout_qualifiers(struct gl_context
*ctx
,
1619 struct gl_shader_program
*prog
,
1620 struct gl_shader
*linked_shader
,
1621 struct gl_shader
**shader_list
,
1622 unsigned num_shaders
)
1624 for (unsigned i
= 0; i
< MAX_FEEDBACK_BUFFERS
; i
++) {
1625 linked_shader
->TransformFeedback
.BufferStride
[i
] = 0;
1628 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1629 struct gl_shader
*shader
= shader_list
[i
];
1631 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1632 if (shader
->TransformFeedback
.BufferStride
[j
]) {
1633 if (linked_shader
->TransformFeedback
.BufferStride
[j
] != 0 &&
1634 shader
->TransformFeedback
.BufferStride
[j
] != 0 &&
1635 linked_shader
->TransformFeedback
.BufferStride
[j
] !=
1636 shader
->TransformFeedback
.BufferStride
[j
]) {
1638 "intrastage shaders defined with conflicting "
1639 "xfb_stride for buffer %d (%d and %d)\n", j
,
1640 linked_shader
->TransformFeedback
.BufferStride
[j
],
1641 shader
->TransformFeedback
.BufferStride
[j
]);
1645 if (shader
->TransformFeedback
.BufferStride
[j
])
1646 linked_shader
->TransformFeedback
.BufferStride
[j
] =
1647 shader
->TransformFeedback
.BufferStride
[j
];
1652 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1653 if (linked_shader
->TransformFeedback
.BufferStride
[j
]) {
1654 prog
->TransformFeedback
.BufferStride
[j
] =
1655 linked_shader
->TransformFeedback
.BufferStride
[j
];
1657 /* We will validate doubles at a later stage */
1658 if (prog
->TransformFeedback
.BufferStride
[j
] % 4) {
1659 linker_error(prog
, "invalid qualifier xfb_stride=%d must be a "
1660 "multiple of 4 or if its applied to a type that is "
1661 "or contains a double a multiple of 8.",
1662 prog
->TransformFeedback
.BufferStride
[j
]);
1666 if (prog
->TransformFeedback
.BufferStride
[j
] / 4 >
1667 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1669 "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1670 "limit has been exceeded.");
1678 * Performs the cross-validation of tessellation control shader vertices and
1679 * layout qualifiers for the attached tessellation control shaders,
1680 * and propagates them to the linked TCS and linked shader program.
1683 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1684 struct gl_shader
*linked_shader
,
1685 struct gl_shader
**shader_list
,
1686 unsigned num_shaders
)
1688 linked_shader
->TessCtrl
.VerticesOut
= 0;
1690 if (linked_shader
->Stage
!= MESA_SHADER_TESS_CTRL
)
1693 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1695 * "All tessellation control shader layout declarations in a program
1696 * must specify the same output patch vertex count. There must be at
1697 * least one layout qualifier specifying an output patch vertex count
1698 * in any program containing tessellation control shaders; however,
1699 * such a declaration is not required in all tessellation control
1703 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1704 struct gl_shader
*shader
= shader_list
[i
];
1706 if (shader
->TessCtrl
.VerticesOut
!= 0) {
1707 if (linked_shader
->TessCtrl
.VerticesOut
!= 0 &&
1708 linked_shader
->TessCtrl
.VerticesOut
!= shader
->TessCtrl
.VerticesOut
) {
1709 linker_error(prog
, "tessellation control shader defined with "
1710 "conflicting output vertex count (%d and %d)\n",
1711 linked_shader
->TessCtrl
.VerticesOut
,
1712 shader
->TessCtrl
.VerticesOut
);
1715 linked_shader
->TessCtrl
.VerticesOut
= shader
->TessCtrl
.VerticesOut
;
1719 /* Just do the intrastage -> interstage propagation right now,
1720 * since we already know we're in the right type of shader program
1723 if (linked_shader
->TessCtrl
.VerticesOut
== 0) {
1724 linker_error(prog
, "tessellation control shader didn't declare "
1725 "vertices out layout qualifier\n");
1728 prog
->TessCtrl
.VerticesOut
= linked_shader
->TessCtrl
.VerticesOut
;
1733 * Performs the cross-validation of tessellation evaluation shader
1734 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1735 * for the attached tessellation evaluation shaders, and propagates them
1736 * to the linked TES and linked shader program.
1739 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1740 struct gl_shader
*linked_shader
,
1741 struct gl_shader
**shader_list
,
1742 unsigned num_shaders
)
1744 linked_shader
->TessEval
.PrimitiveMode
= PRIM_UNKNOWN
;
1745 linked_shader
->TessEval
.Spacing
= 0;
1746 linked_shader
->TessEval
.VertexOrder
= 0;
1747 linked_shader
->TessEval
.PointMode
= -1;
1749 if (linked_shader
->Stage
!= MESA_SHADER_TESS_EVAL
)
1752 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1754 * "At least one tessellation evaluation shader (compilation unit) in
1755 * a program must declare a primitive mode in its input layout.
1756 * Declaration vertex spacing, ordering, and point mode identifiers is
1757 * optional. It is not required that all tessellation evaluation
1758 * shaders in a program declare a primitive mode. If spacing or
1759 * vertex ordering declarations are omitted, the tessellation
1760 * primitive generator will use equal spacing or counter-clockwise
1761 * vertex ordering, respectively. If a point mode declaration is
1762 * omitted, the tessellation primitive generator will produce lines or
1763 * triangles according to the primitive mode."
1766 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1767 struct gl_shader
*shader
= shader_list
[i
];
1769 if (shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1770 if (linked_shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
&&
1771 linked_shader
->TessEval
.PrimitiveMode
!= shader
->TessEval
.PrimitiveMode
) {
1772 linker_error(prog
, "tessellation evaluation shader defined with "
1773 "conflicting input primitive modes.\n");
1776 linked_shader
->TessEval
.PrimitiveMode
= shader
->TessEval
.PrimitiveMode
;
1779 if (shader
->TessEval
.Spacing
!= 0) {
1780 if (linked_shader
->TessEval
.Spacing
!= 0 &&
1781 linked_shader
->TessEval
.Spacing
!= shader
->TessEval
.Spacing
) {
1782 linker_error(prog
, "tessellation evaluation shader defined with "
1783 "conflicting vertex spacing.\n");
1786 linked_shader
->TessEval
.Spacing
= shader
->TessEval
.Spacing
;
1789 if (shader
->TessEval
.VertexOrder
!= 0) {
1790 if (linked_shader
->TessEval
.VertexOrder
!= 0 &&
1791 linked_shader
->TessEval
.VertexOrder
!= shader
->TessEval
.VertexOrder
) {
1792 linker_error(prog
, "tessellation evaluation shader defined with "
1793 "conflicting ordering.\n");
1796 linked_shader
->TessEval
.VertexOrder
= shader
->TessEval
.VertexOrder
;
1799 if (shader
->TessEval
.PointMode
!= -1) {
1800 if (linked_shader
->TessEval
.PointMode
!= -1 &&
1801 linked_shader
->TessEval
.PointMode
!= shader
->TessEval
.PointMode
) {
1802 linker_error(prog
, "tessellation evaluation shader defined with "
1803 "conflicting point modes.\n");
1806 linked_shader
->TessEval
.PointMode
= shader
->TessEval
.PointMode
;
1811 /* Just do the intrastage -> interstage propagation right now,
1812 * since we already know we're in the right type of shader program
1815 if (linked_shader
->TessEval
.PrimitiveMode
== PRIM_UNKNOWN
) {
1817 "tessellation evaluation shader didn't declare input "
1818 "primitive modes.\n");
1821 prog
->TessEval
.PrimitiveMode
= linked_shader
->TessEval
.PrimitiveMode
;
1823 if (linked_shader
->TessEval
.Spacing
== 0)
1824 linked_shader
->TessEval
.Spacing
= GL_EQUAL
;
1825 prog
->TessEval
.Spacing
= linked_shader
->TessEval
.Spacing
;
1827 if (linked_shader
->TessEval
.VertexOrder
== 0)
1828 linked_shader
->TessEval
.VertexOrder
= GL_CCW
;
1829 prog
->TessEval
.VertexOrder
= linked_shader
->TessEval
.VertexOrder
;
1831 if (linked_shader
->TessEval
.PointMode
== -1)
1832 linked_shader
->TessEval
.PointMode
= GL_FALSE
;
1833 prog
->TessEval
.PointMode
= linked_shader
->TessEval
.PointMode
;
1838 * Performs the cross-validation of layout qualifiers specified in
1839 * redeclaration of gl_FragCoord for the attached fragment shaders,
1840 * and propagates them to the linked FS and linked shader program.
1843 link_fs_input_layout_qualifiers(struct gl_shader_program
*prog
,
1844 struct gl_shader
*linked_shader
,
1845 struct gl_shader
**shader_list
,
1846 unsigned num_shaders
)
1848 linked_shader
->redeclares_gl_fragcoord
= false;
1849 linked_shader
->uses_gl_fragcoord
= false;
1850 linked_shader
->origin_upper_left
= false;
1851 linked_shader
->pixel_center_integer
= false;
1853 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1854 (prog
->Version
< 150 && !prog
->ARB_fragment_coord_conventions_enable
))
1857 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1858 struct gl_shader
*shader
= shader_list
[i
];
1859 /* From the GLSL 1.50 spec, page 39:
1861 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1862 * it must be redeclared in all the fragment shaders in that program
1863 * that have a static use gl_FragCoord."
1865 if ((linked_shader
->redeclares_gl_fragcoord
1866 && !shader
->redeclares_gl_fragcoord
1867 && shader
->uses_gl_fragcoord
)
1868 || (shader
->redeclares_gl_fragcoord
1869 && !linked_shader
->redeclares_gl_fragcoord
1870 && linked_shader
->uses_gl_fragcoord
)) {
1871 linker_error(prog
, "fragment shader defined with conflicting "
1872 "layout qualifiers for gl_FragCoord\n");
1875 /* From the GLSL 1.50 spec, page 39:
1877 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1878 * single program must have the same set of qualifiers."
1880 if (linked_shader
->redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
1881 && (shader
->origin_upper_left
!= linked_shader
->origin_upper_left
1882 || shader
->pixel_center_integer
!= linked_shader
->pixel_center_integer
)) {
1883 linker_error(prog
, "fragment shader defined with conflicting "
1884 "layout qualifiers for gl_FragCoord\n");
1887 /* Update the linked shader state. Note that uses_gl_fragcoord should
1888 * accumulate the results. The other values should replace. If there
1889 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1890 * are already known to be the same.
1892 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
1893 linked_shader
->redeclares_gl_fragcoord
=
1894 shader
->redeclares_gl_fragcoord
;
1895 linked_shader
->uses_gl_fragcoord
= linked_shader
->uses_gl_fragcoord
1896 || shader
->uses_gl_fragcoord
;
1897 linked_shader
->origin_upper_left
= shader
->origin_upper_left
;
1898 linked_shader
->pixel_center_integer
= shader
->pixel_center_integer
;
1901 linked_shader
->EarlyFragmentTests
|= shader
->EarlyFragmentTests
;
1906 * Performs the cross-validation of geometry shader max_vertices and
1907 * primitive type layout qualifiers for the attached geometry shaders,
1908 * and propagates them to the linked GS and linked shader program.
1911 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1912 struct gl_shader
*linked_shader
,
1913 struct gl_shader
**shader_list
,
1914 unsigned num_shaders
)
1916 linked_shader
->Geom
.VerticesOut
= 0;
1917 linked_shader
->Geom
.Invocations
= 0;
1918 linked_shader
->Geom
.InputType
= PRIM_UNKNOWN
;
1919 linked_shader
->Geom
.OutputType
= PRIM_UNKNOWN
;
1921 /* No in/out qualifiers defined for anything but GLSL 1.50+
1922 * geometry shaders so far.
1924 if (linked_shader
->Stage
!= MESA_SHADER_GEOMETRY
|| prog
->Version
< 150)
1927 /* From the GLSL 1.50 spec, page 46:
1929 * "All geometry shader output layout declarations in a program
1930 * must declare the same layout and same value for
1931 * max_vertices. There must be at least one geometry output
1932 * layout declaration somewhere in a program, but not all
1933 * geometry shaders (compilation units) are required to
1937 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1938 struct gl_shader
*shader
= shader_list
[i
];
1940 if (shader
->Geom
.InputType
!= PRIM_UNKNOWN
) {
1941 if (linked_shader
->Geom
.InputType
!= PRIM_UNKNOWN
&&
1942 linked_shader
->Geom
.InputType
!= shader
->Geom
.InputType
) {
1943 linker_error(prog
, "geometry shader defined with conflicting "
1947 linked_shader
->Geom
.InputType
= shader
->Geom
.InputType
;
1950 if (shader
->Geom
.OutputType
!= PRIM_UNKNOWN
) {
1951 if (linked_shader
->Geom
.OutputType
!= PRIM_UNKNOWN
&&
1952 linked_shader
->Geom
.OutputType
!= shader
->Geom
.OutputType
) {
1953 linker_error(prog
, "geometry shader defined with conflicting "
1957 linked_shader
->Geom
.OutputType
= shader
->Geom
.OutputType
;
1960 if (shader
->Geom
.VerticesOut
!= 0) {
1961 if (linked_shader
->Geom
.VerticesOut
!= 0 &&
1962 linked_shader
->Geom
.VerticesOut
!= shader
->Geom
.VerticesOut
) {
1963 linker_error(prog
, "geometry shader defined with conflicting "
1964 "output vertex count (%d and %d)\n",
1965 linked_shader
->Geom
.VerticesOut
,
1966 shader
->Geom
.VerticesOut
);
1969 linked_shader
->Geom
.VerticesOut
= shader
->Geom
.VerticesOut
;
1972 if (shader
->Geom
.Invocations
!= 0) {
1973 if (linked_shader
->Geom
.Invocations
!= 0 &&
1974 linked_shader
->Geom
.Invocations
!= shader
->Geom
.Invocations
) {
1975 linker_error(prog
, "geometry shader defined with conflicting "
1976 "invocation count (%d and %d)\n",
1977 linked_shader
->Geom
.Invocations
,
1978 shader
->Geom
.Invocations
);
1981 linked_shader
->Geom
.Invocations
= shader
->Geom
.Invocations
;
1985 /* Just do the intrastage -> interstage propagation right now,
1986 * since we already know we're in the right type of shader program
1989 if (linked_shader
->Geom
.InputType
== PRIM_UNKNOWN
) {
1991 "geometry shader didn't declare primitive input type\n");
1994 prog
->Geom
.InputType
= linked_shader
->Geom
.InputType
;
1996 if (linked_shader
->Geom
.OutputType
== PRIM_UNKNOWN
) {
1998 "geometry shader didn't declare primitive output type\n");
2001 prog
->Geom
.OutputType
= linked_shader
->Geom
.OutputType
;
2003 if (linked_shader
->Geom
.VerticesOut
== 0) {
2005 "geometry shader didn't declare max_vertices\n");
2008 prog
->Geom
.VerticesOut
= linked_shader
->Geom
.VerticesOut
;
2010 if (linked_shader
->Geom
.Invocations
== 0)
2011 linked_shader
->Geom
.Invocations
= 1;
2013 prog
->Geom
.Invocations
= linked_shader
->Geom
.Invocations
;
2018 * Perform cross-validation of compute shader local_size_{x,y,z} layout
2019 * qualifiers for the attached compute shaders, and propagate them to the
2020 * linked CS and linked shader program.
2023 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
2024 struct gl_shader
*linked_shader
,
2025 struct gl_shader
**shader_list
,
2026 unsigned num_shaders
)
2028 for (int i
= 0; i
< 3; i
++)
2029 linked_shader
->Comp
.LocalSize
[i
] = 0;
2031 /* This function is called for all shader stages, but it only has an effect
2032 * for compute shaders.
2034 if (linked_shader
->Stage
!= MESA_SHADER_COMPUTE
)
2037 /* From the ARB_compute_shader spec, in the section describing local size
2040 * If multiple compute shaders attached to a single program object
2041 * declare local work-group size, the declarations must be identical;
2042 * otherwise a link-time error results. Furthermore, if a program
2043 * object contains any compute shaders, at least one must contain an
2044 * input layout qualifier specifying the local work sizes of the
2045 * program, or a link-time error will occur.
2047 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
2048 struct gl_shader
*shader
= shader_list
[sh
];
2050 if (shader
->Comp
.LocalSize
[0] != 0) {
2051 if (linked_shader
->Comp
.LocalSize
[0] != 0) {
2052 for (int i
= 0; i
< 3; i
++) {
2053 if (linked_shader
->Comp
.LocalSize
[i
] !=
2054 shader
->Comp
.LocalSize
[i
]) {
2055 linker_error(prog
, "compute shader defined with conflicting "
2061 for (int i
= 0; i
< 3; i
++)
2062 linked_shader
->Comp
.LocalSize
[i
] = shader
->Comp
.LocalSize
[i
];
2066 /* Just do the intrastage -> interstage propagation right now,
2067 * since we already know we're in the right type of shader program
2070 if (linked_shader
->Comp
.LocalSize
[0] == 0) {
2071 linker_error(prog
, "compute shader didn't declare local size\n");
2074 for (int i
= 0; i
< 3; i
++)
2075 prog
->Comp
.LocalSize
[i
] = linked_shader
->Comp
.LocalSize
[i
];
2080 * Combine a group of shaders for a single stage to generate a linked shader
2083 * If this function is supplied a single shader, it is cloned, and the new
2084 * shader is returned.
2086 static struct gl_shader
*
2087 link_intrastage_shaders(void *mem_ctx
,
2088 struct gl_context
*ctx
,
2089 struct gl_shader_program
*prog
,
2090 struct gl_shader
**shader_list
,
2091 unsigned num_shaders
)
2093 struct gl_uniform_block
*ubo_blocks
= NULL
;
2094 struct gl_uniform_block
*ssbo_blocks
= NULL
;
2095 unsigned num_ubo_blocks
= 0;
2096 unsigned num_ssbo_blocks
= 0;
2098 /* Check that global variables defined in multiple shaders are consistent.
2100 cross_validate_globals(prog
, shader_list
, num_shaders
, false);
2101 if (!prog
->LinkStatus
)
2104 /* Check that interface blocks defined in multiple shaders are consistent.
2106 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
2108 if (!prog
->LinkStatus
)
2111 /* Link up uniform blocks defined within this stage. */
2112 link_uniform_blocks(mem_ctx
, ctx
, prog
, shader_list
, num_shaders
,
2113 &ubo_blocks
, &num_ubo_blocks
, &ssbo_blocks
,
2116 if (!prog
->LinkStatus
)
2119 /* Check that there is only a single definition of each function signature
2120 * across all shaders.
2122 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2123 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2124 ir_function
*const f
= node
->as_function();
2129 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2130 ir_function
*const other
=
2131 shader_list
[j
]->symbols
->get_function(f
->name
);
2133 /* If the other shader has no function (and therefore no function
2134 * signatures) with the same name, skip to the next shader.
2139 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2140 if (!sig
->is_defined
|| sig
->is_builtin())
2143 ir_function_signature
*other_sig
=
2144 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2146 if ((other_sig
!= NULL
) && other_sig
->is_defined
2147 && !other_sig
->is_builtin()) {
2148 linker_error(prog
, "function `%s' is multiply defined\n",
2157 /* Find the shader that defines main, and make a clone of it.
2159 * Starting with the clone, search for undefined references. If one is
2160 * found, find the shader that defines it. Clone the reference and add
2161 * it to the shader. Repeat until there are no undefined references or
2162 * until a reference cannot be resolved.
2164 gl_shader
*main
= NULL
;
2165 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2166 if (_mesa_get_main_function_signature(shader_list
[i
]) != NULL
) {
2167 main
= shader_list
[i
];
2173 linker_error(prog
, "%s shader lacks `main'\n",
2174 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2178 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
2179 linked
->ir
= new(linked
) exec_list
;
2180 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2182 /* Copy ubo blocks to linked shader list */
2183 linked
->UniformBlocks
=
2184 ralloc_array(linked
, gl_uniform_block
*, num_ubo_blocks
);
2185 ralloc_steal(linked
, ubo_blocks
);
2186 for (unsigned i
= 0; i
< num_ubo_blocks
; i
++) {
2187 linked
->UniformBlocks
[i
] = &ubo_blocks
[i
];
2189 linked
->NumUniformBlocks
= num_ubo_blocks
;
2191 /* Copy ssbo blocks to linked shader list */
2192 linked
->ShaderStorageBlocks
=
2193 ralloc_array(linked
, gl_uniform_block
*, num_ssbo_blocks
);
2194 ralloc_steal(linked
, ssbo_blocks
);
2195 for (unsigned i
= 0; i
< num_ssbo_blocks
; i
++) {
2196 linked
->ShaderStorageBlocks
[i
] = &ssbo_blocks
[i
];
2198 linked
->NumShaderStorageBlocks
= num_ssbo_blocks
;
2200 link_fs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2201 link_tcs_out_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2202 link_tes_in_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2203 link_gs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2204 link_cs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2205 link_xfb_stride_layout_qualifiers(ctx
, prog
, linked
, shader_list
,
2208 populate_symbol_table(linked
);
2210 /* The pointer to the main function in the final linked shader (i.e., the
2211 * copy of the original shader that contained the main function).
2213 ir_function_signature
*const main_sig
=
2214 _mesa_get_main_function_signature(linked
);
2216 /* Move any instructions other than variable declarations or function
2217 * declarations into main.
2219 exec_node
*insertion_point
=
2220 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2223 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2224 if (shader_list
[i
] == main
)
2227 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2228 insertion_point
, true, linked
);
2231 /* Check if any shader needs built-in functions. */
2232 bool need_builtins
= false;
2233 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2234 if (shader_list
[i
]->uses_builtin_functions
) {
2235 need_builtins
= true;
2241 if (need_builtins
) {
2242 /* Make a temporary array one larger than shader_list, which will hold
2243 * the built-in function shader as well.
2245 gl_shader
**linking_shaders
= (gl_shader
**)
2246 calloc(num_shaders
+ 1, sizeof(gl_shader
*));
2248 ok
= linking_shaders
!= NULL
;
2251 memcpy(linking_shaders
, shader_list
, num_shaders
* sizeof(gl_shader
*));
2252 _mesa_glsl_initialize_builtin_functions();
2253 linking_shaders
[num_shaders
] = _mesa_glsl_get_builtin_function_shader();
2255 ok
= link_function_calls(prog
, linked
, linking_shaders
, num_shaders
+ 1);
2257 free(linking_shaders
);
2259 _mesa_error_no_memory(__func__
);
2262 ok
= link_function_calls(prog
, linked
, shader_list
, num_shaders
);
2267 _mesa_delete_shader(ctx
, linked
);
2271 /* At this point linked should contain all of the linked IR, so
2272 * validate it to make sure nothing went wrong.
2274 validate_ir_tree(linked
->ir
);
2276 /* Set the size of geometry shader input arrays */
2277 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2278 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
2279 geom_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2280 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2281 ir
->accept(&input_resize_visitor
);
2285 if (ctx
->Const
.VertexID_is_zero_based
)
2286 lower_vertex_id(linked
);
2288 /* Validate correct usage of barrier() in the tess control shader */
2289 if (linked
->Stage
== MESA_SHADER_TESS_CTRL
) {
2290 barrier_use_visitor
visitor(prog
);
2291 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2292 ir
->accept(&visitor
);
2296 /* Make a pass over all variable declarations to ensure that arrays with
2297 * unspecified sizes have a size specified. The size is inferred from the
2298 * max_array_access field.
2300 array_sizing_visitor v
;
2302 v
.fixup_unnamed_interface_types();
2308 * Update the sizes of linked shader uniform arrays to the maximum
2311 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2313 * If one or more elements of an array are active,
2314 * GetActiveUniform will return the name of the array in name,
2315 * subject to the restrictions listed above. The type of the array
2316 * is returned in type. The size parameter contains the highest
2317 * array element index used, plus one. The compiler or linker
2318 * determines the highest index used. There will be only one
2319 * active uniform reported by the GL per uniform array.
2323 update_array_sizes(struct gl_shader_program
*prog
)
2325 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2326 if (prog
->_LinkedShaders
[i
] == NULL
)
2329 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2330 ir_variable
*const var
= node
->as_variable();
2332 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2333 !var
->type
->is_array())
2336 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2337 * will not be eliminated. Since we always do std140, just
2338 * don't resize arrays in UBOs.
2340 * Atomic counters are supposed to get deterministic
2341 * locations assigned based on the declaration ordering and
2342 * sizes, array compaction would mess that up.
2344 * Subroutine uniforms are not removed.
2346 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2347 var
->type
->contains_subroutine())
2350 unsigned int size
= var
->data
.max_array_access
;
2351 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2352 if (prog
->_LinkedShaders
[j
] == NULL
)
2355 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2356 ir_variable
*other_var
= node2
->as_variable();
2360 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2361 other_var
->data
.max_array_access
> size
) {
2362 size
= other_var
->data
.max_array_access
;
2367 if (size
+ 1 != var
->type
->length
) {
2368 /* If this is a built-in uniform (i.e., it's backed by some
2369 * fixed-function state), adjust the number of state slots to
2370 * match the new array size. The number of slots per array entry
2371 * is not known. It seems safe to assume that the total number of
2372 * slots is an integer multiple of the number of array elements.
2373 * Determine the number of slots per array element by dividing by
2374 * the old (total) size.
2376 const unsigned num_slots
= var
->get_num_state_slots();
2377 if (num_slots
> 0) {
2378 var
->set_num_state_slots((size
+ 1)
2379 * (num_slots
/ var
->type
->length
));
2382 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2384 /* FINISHME: We should update the types of array
2385 * dereferences of this variable now.
2393 * Resize tessellation evaluation per-vertex inputs to the size of
2394 * tessellation control per-vertex outputs.
2397 resize_tes_inputs(struct gl_context
*ctx
,
2398 struct gl_shader_program
*prog
)
2400 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2403 gl_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2404 gl_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2406 /* If no control shader is present, then the TES inputs are statically
2407 * sized to MaxPatchVertices; the actual size of the arrays won't be
2408 * known until draw time.
2410 const int num_vertices
= tcs
2411 ? tcs
->TessCtrl
.VerticesOut
2412 : ctx
->Const
.MaxPatchVertices
;
2414 tess_eval_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2415 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2416 ir
->accept(&input_resize_visitor
);
2420 /* Convert the gl_PatchVerticesIn system value into a constant, since
2421 * the value is known at this point.
2423 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2424 ir_variable
*var
= ir
->as_variable();
2425 if (var
&& var
->data
.mode
== ir_var_system_value
&&
2426 var
->data
.location
== SYSTEM_VALUE_VERTICES_IN
) {
2427 void *mem_ctx
= ralloc_parent(var
);
2428 var
->data
.mode
= ir_var_auto
;
2429 var
->data
.location
= 0;
2430 var
->constant_value
= new(mem_ctx
) ir_constant(num_vertices
);
2437 * Find a contiguous set of available bits in a bitmask.
2439 * \param used_mask Bits representing used (1) and unused (0) locations
2440 * \param needed_count Number of contiguous bits needed.
2443 * Base location of the available bits on success or -1 on failure.
2446 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2448 unsigned needed_mask
= (1 << needed_count
) - 1;
2449 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2451 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2452 * cannot optimize possibly infinite loops" for the loop below.
2454 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2457 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2458 if ((needed_mask
& ~used_mask
) == needed_mask
)
2469 * Assign locations for either VS inputs or FS outputs
2471 * \param prog Shader program whose variables need locations assigned
2472 * \param constants Driver specific constant values for the program.
2473 * \param target_index Selector for the program target to receive location
2474 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2475 * \c MESA_SHADER_FRAGMENT.
2478 * If locations are successfully assigned, true is returned. Otherwise an
2479 * error is emitted to the shader link log and false is returned.
2482 assign_attribute_or_color_locations(gl_shader_program
*prog
,
2483 struct gl_constants
*constants
,
2484 unsigned target_index
)
2486 /* Maximum number of generic locations. This corresponds to either the
2487 * maximum number of draw buffers or the maximum number of generic
2490 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2491 constants
->Program
[target_index
].MaxAttribs
:
2492 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2494 /* Mark invalid locations as being used.
2496 unsigned used_locations
= (max_index
>= 32)
2497 ? ~0 : ~((1 << max_index
) - 1);
2498 unsigned double_storage_locations
= 0;
2500 assert((target_index
== MESA_SHADER_VERTEX
)
2501 || (target_index
== MESA_SHADER_FRAGMENT
));
2503 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2507 /* Operate in a total of four passes.
2509 * 1. Invalidate the location assignments for all vertex shader inputs.
2511 * 2. Assign locations for inputs that have user-defined (via
2512 * glBindVertexAttribLocation) locations and outputs that have
2513 * user-defined locations (via glBindFragDataLocation).
2515 * 3. Sort the attributes without assigned locations by number of slots
2516 * required in decreasing order. Fragmentation caused by attribute
2517 * locations assigned by the application may prevent large attributes
2518 * from having enough contiguous space.
2520 * 4. Assign locations to any inputs without assigned locations.
2523 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2524 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2526 const enum ir_variable_mode direction
=
2527 (target_index
== MESA_SHADER_VERTEX
)
2528 ? ir_var_shader_in
: ir_var_shader_out
;
2531 /* Temporary storage for the set of attributes that need locations assigned.
2537 /* Used below in the call to qsort. */
2538 static int compare(const void *a
, const void *b
)
2540 const temp_attr
*const l
= (const temp_attr
*) a
;
2541 const temp_attr
*const r
= (const temp_attr
*) b
;
2543 /* Reversed because we want a descending order sort below. */
2544 return r
->slots
- l
->slots
;
2547 assert(max_index
<= 32);
2549 unsigned num_attr
= 0;
2551 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2552 ir_variable
*const var
= node
->as_variable();
2554 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2557 if (var
->data
.explicit_location
) {
2558 var
->data
.is_unmatched_generic_inout
= 0;
2559 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2560 || (var
->data
.location
< 0)) {
2562 "invalid explicit location %d specified for `%s'\n",
2563 (var
->data
.location
< 0)
2564 ? var
->data
.location
2565 : var
->data
.location
- generic_base
,
2569 } else if (target_index
== MESA_SHADER_VERTEX
) {
2572 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2573 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2574 var
->data
.location
= binding
;
2575 var
->data
.is_unmatched_generic_inout
= 0;
2577 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2581 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
2582 assert(binding
>= FRAG_RESULT_DATA0
);
2583 var
->data
.location
= binding
;
2584 var
->data
.is_unmatched_generic_inout
= 0;
2586 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
2587 var
->data
.index
= index
;
2592 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2594 * "Output binding assignments will cause LinkProgram to fail:
2596 * If the program has an active output assigned to a location greater
2597 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2598 * an active output assigned an index greater than or equal to one;"
2600 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2601 var
->data
.location
- generic_base
>=
2602 (int) constants
->MaxDualSourceDrawBuffers
) {
2604 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2605 "with index %u for %s\n",
2606 var
->data
.location
- generic_base
, var
->data
.index
,
2611 const unsigned slots
= var
->type
->count_attribute_slots(target_index
== MESA_SHADER_VERTEX
);
2613 /* If the variable is not a built-in and has a location statically
2614 * assigned in the shader (presumably via a layout qualifier), make sure
2615 * that it doesn't collide with other assigned locations. Otherwise,
2616 * add it to the list of variables that need linker-assigned locations.
2618 if (var
->data
.location
!= -1) {
2619 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2620 /* From page 61 of the OpenGL 4.0 spec:
2622 * "LinkProgram will fail if the attribute bindings assigned
2623 * by BindAttribLocation do not leave not enough space to
2624 * assign a location for an active matrix attribute or an
2625 * active attribute array, both of which require multiple
2626 * contiguous generic attributes."
2628 * I think above text prohibits the aliasing of explicit and
2629 * automatic assignments. But, aliasing is allowed in manual
2630 * assignments of attribute locations. See below comments for
2633 * From OpenGL 4.0 spec, page 61:
2635 * "It is possible for an application to bind more than one
2636 * attribute name to the same location. This is referred to as
2637 * aliasing. This will only work if only one of the aliased
2638 * attributes is active in the executable program, or if no
2639 * path through the shader consumes more than one attribute of
2640 * a set of attributes aliased to the same location. A link
2641 * error can occur if the linker determines that every path
2642 * through the shader consumes multiple aliased attributes,
2643 * but implementations are not required to generate an error
2646 * From GLSL 4.30 spec, page 54:
2648 * "A program will fail to link if any two non-vertex shader
2649 * input variables are assigned to the same location. For
2650 * vertex shaders, multiple input variables may be assigned
2651 * to the same location using either layout qualifiers or via
2652 * the OpenGL API. However, such aliasing is intended only to
2653 * support vertex shaders where each execution path accesses
2654 * at most one input per each location. Implementations are
2655 * permitted, but not required, to generate link-time errors
2656 * if they detect that every path through the vertex shader
2657 * executable accesses multiple inputs assigned to any single
2658 * location. For all shader types, a program will fail to link
2659 * if explicit location assignments leave the linker unable
2660 * to find space for other variables without explicit
2663 * From OpenGL ES 3.0 spec, page 56:
2665 * "Binding more than one attribute name to the same location
2666 * is referred to as aliasing, and is not permitted in OpenGL
2667 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2668 * fail when this condition exists. However, aliasing is
2669 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2670 * This will only work if only one of the aliased attributes
2671 * is active in the executable program, or if no path through
2672 * the shader consumes more than one attribute of a set of
2673 * attributes aliased to the same location. A link error can
2674 * occur if the linker determines that every path through the
2675 * shader consumes multiple aliased attributes, but implemen-
2676 * tations are not required to generate an error in this case."
2678 * After looking at above references from OpenGL, OpenGL ES and
2679 * GLSL specifications, we allow aliasing of vertex input variables
2680 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2682 * NOTE: This is not required by the spec but its worth mentioning
2683 * here that we're not doing anything to make sure that no path
2684 * through the vertex shader executable accesses multiple inputs
2685 * assigned to any single location.
2688 /* Mask representing the contiguous slots that will be used by
2691 const unsigned attr
= var
->data
.location
- generic_base
;
2692 const unsigned use_mask
= (1 << slots
) - 1;
2693 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2694 ? "vertex shader input" : "fragment shader output";
2696 /* Generate a link error if the requested locations for this
2697 * attribute exceed the maximum allowed attribute location.
2699 if (attr
+ slots
> max_index
) {
2701 "insufficient contiguous locations "
2702 "available for %s `%s' %d %d %d\n", string
,
2703 var
->name
, used_locations
, use_mask
, attr
);
2707 /* Generate a link error if the set of bits requested for this
2708 * attribute overlaps any previously allocated bits.
2710 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
2711 if (target_index
== MESA_SHADER_FRAGMENT
||
2712 (prog
->IsES
&& prog
->Version
>= 300)) {
2714 "overlapping location is assigned "
2715 "to %s `%s' %d %d %d\n", string
,
2716 var
->name
, used_locations
, use_mask
, attr
);
2719 linker_warning(prog
,
2720 "overlapping location is assigned "
2721 "to %s `%s' %d %d %d\n", string
,
2722 var
->name
, used_locations
, use_mask
, attr
);
2726 used_locations
|= (use_mask
<< attr
);
2728 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2730 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2731 * active attribute variables may fail to link, unless
2732 * device-dependent optimizations are able to make the program
2733 * fit within available hardware resources. For the purposes
2734 * of this test, attribute variables of the type dvec3, dvec4,
2735 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2736 * count as consuming twice as many attributes as equivalent
2737 * single-precision types. While these types use the same number
2738 * of generic attributes as their single-precision equivalents,
2739 * implementations are permitted to consume two single-precision
2740 * vectors of internal storage for each three- or four-component
2741 * double-precision vector."
2743 * Mark this attribute slot as taking up twice as much space
2744 * so we can count it properly against limits. According to
2745 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2746 * is optional behavior, but it seems preferable.
2748 if (var
->type
->without_array()->is_dual_slot_double())
2749 double_storage_locations
|= (use_mask
<< attr
);
2755 if (num_attr
>= max_index
) {
2756 linker_error(prog
, "too many %s (max %u)",
2757 target_index
== MESA_SHADER_VERTEX
?
2758 "vertex shader inputs" : "fragment shader outputs",
2762 to_assign
[num_attr
].slots
= slots
;
2763 to_assign
[num_attr
].var
= var
;
2767 if (target_index
== MESA_SHADER_VERTEX
) {
2768 unsigned total_attribs_size
=
2769 _mesa_bitcount(used_locations
& ((1 << max_index
) - 1)) +
2770 _mesa_bitcount(double_storage_locations
);
2771 if (total_attribs_size
> max_index
) {
2773 "attempt to use %d vertex attribute slots only %d available ",
2774 total_attribs_size
, max_index
);
2779 /* If all of the attributes were assigned locations by the application (or
2780 * are built-in attributes with fixed locations), return early. This should
2781 * be the common case.
2786 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
2788 if (target_index
== MESA_SHADER_VERTEX
) {
2789 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2790 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2791 * reserved to prevent it from being automatically allocated below.
2793 find_deref_visitor
find("gl_Vertex");
2795 if (find
.variable_found())
2796 used_locations
|= (1 << 0);
2799 for (unsigned i
= 0; i
< num_attr
; i
++) {
2800 /* Mask representing the contiguous slots that will be used by this
2803 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
2805 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
2808 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2809 ? "vertex shader input" : "fragment shader output";
2812 "insufficient contiguous locations "
2813 "available for %s `%s'\n",
2814 string
, to_assign
[i
].var
->name
);
2818 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
2819 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
2820 used_locations
|= (use_mask
<< location
);
2827 * Match explicit locations of outputs to inputs and deactivate the
2828 * unmatch flag if found so we don't optimise them away.
2831 match_explicit_outputs_to_inputs(struct gl_shader_program
*prog
,
2832 gl_shader
*producer
,
2833 gl_shader
*consumer
)
2835 glsl_symbol_table parameters
;
2836 ir_variable
*explicit_locations
[MAX_VARYING
][4] = { {NULL
, NULL
} };
2838 /* Find all shader outputs in the "producer" stage.
2840 foreach_in_list(ir_instruction
, node
, producer
->ir
) {
2841 ir_variable
*const var
= node
->as_variable();
2843 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_shader_out
))
2846 if (var
->data
.explicit_location
&&
2847 var
->data
.location
>= VARYING_SLOT_VAR0
) {
2848 const unsigned idx
= var
->data
.location
- VARYING_SLOT_VAR0
;
2849 if (explicit_locations
[idx
][var
->data
.location_frac
] == NULL
)
2850 explicit_locations
[idx
][var
->data
.location_frac
] = var
;
2854 /* Match inputs to outputs */
2855 foreach_in_list(ir_instruction
, node
, consumer
->ir
) {
2856 ir_variable
*const input
= node
->as_variable();
2858 if ((input
== NULL
) || (input
->data
.mode
!= ir_var_shader_in
))
2861 ir_variable
*output
= NULL
;
2862 if (input
->data
.explicit_location
2863 && input
->data
.location
>= VARYING_SLOT_VAR0
) {
2864 output
= explicit_locations
[input
->data
.location
- VARYING_SLOT_VAR0
]
2865 [input
->data
.location_frac
];
2867 if (output
!= NULL
){
2868 input
->data
.is_unmatched_generic_inout
= 0;
2869 output
->data
.is_unmatched_generic_inout
= 0;
2876 * Store the gl_FragDepth layout in the gl_shader_program struct.
2879 store_fragdepth_layout(struct gl_shader_program
*prog
)
2881 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
2885 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
2887 /* We don't look up the gl_FragDepth symbol directly because if
2888 * gl_FragDepth is not used in the shader, it's removed from the IR.
2889 * However, the symbol won't be removed from the symbol table.
2891 * We're only interested in the cases where the variable is NOT removed
2894 foreach_in_list(ir_instruction
, node
, ir
) {
2895 ir_variable
*const var
= node
->as_variable();
2897 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
2901 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
2902 switch (var
->data
.depth_layout
) {
2903 case ir_depth_layout_none
:
2904 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
2906 case ir_depth_layout_any
:
2907 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
2909 case ir_depth_layout_greater
:
2910 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
2912 case ir_depth_layout_less
:
2913 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
2915 case ir_depth_layout_unchanged
:
2916 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
2927 * Validate the resources used by a program versus the implementation limits
2930 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2932 unsigned total_uniform_blocks
= 0;
2933 unsigned total_shader_storage_blocks
= 0;
2935 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2936 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2941 if (sh
->num_samplers
> ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
2942 linker_error(prog
, "Too many %s shader texture samplers\n",
2943 _mesa_shader_stage_to_string(i
));
2946 if (sh
->num_uniform_components
>
2947 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
2948 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2949 linker_warning(prog
, "Too many %s shader default uniform block "
2950 "components, but the driver will try to optimize "
2951 "them out; this is non-portable out-of-spec "
2953 _mesa_shader_stage_to_string(i
));
2955 linker_error(prog
, "Too many %s shader default uniform block "
2957 _mesa_shader_stage_to_string(i
));
2961 if (sh
->num_combined_uniform_components
>
2962 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
2963 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2964 linker_warning(prog
, "Too many %s shader uniform components, "
2965 "but the driver will try to optimize them out; "
2966 "this is non-portable out-of-spec behavior\n",
2967 _mesa_shader_stage_to_string(i
));
2969 linker_error(prog
, "Too many %s shader uniform components\n",
2970 _mesa_shader_stage_to_string(i
));
2974 total_shader_storage_blocks
+= sh
->NumShaderStorageBlocks
;
2975 total_uniform_blocks
+= sh
->NumUniformBlocks
;
2977 const unsigned max_uniform_blocks
=
2978 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
2979 if (max_uniform_blocks
< sh
->NumUniformBlocks
) {
2980 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
2981 _mesa_shader_stage_to_string(i
), sh
->NumUniformBlocks
,
2982 max_uniform_blocks
);
2985 const unsigned max_shader_storage_blocks
=
2986 ctx
->Const
.Program
[i
].MaxShaderStorageBlocks
;
2987 if (max_shader_storage_blocks
< sh
->NumShaderStorageBlocks
) {
2988 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
2989 _mesa_shader_stage_to_string(i
),
2990 sh
->NumShaderStorageBlocks
, max_shader_storage_blocks
);
2994 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
2995 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
2996 total_uniform_blocks
, ctx
->Const
.MaxCombinedUniformBlocks
);
2999 if (total_shader_storage_blocks
> ctx
->Const
.MaxCombinedShaderStorageBlocks
) {
3000 linker_error(prog
, "Too many combined shader storage blocks (%d/%d)\n",
3001 total_shader_storage_blocks
,
3002 ctx
->Const
.MaxCombinedShaderStorageBlocks
);
3005 for (unsigned i
= 0; i
< prog
->NumUniformBlocks
; i
++) {
3006 if (prog
->UniformBlocks
[i
].UniformBufferSize
>
3007 ctx
->Const
.MaxUniformBlockSize
) {
3008 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
3009 prog
->UniformBlocks
[i
].Name
,
3010 prog
->UniformBlocks
[i
].UniformBufferSize
,
3011 ctx
->Const
.MaxUniformBlockSize
);
3015 for (unsigned i
= 0; i
< prog
->NumShaderStorageBlocks
; i
++) {
3016 if (prog
->ShaderStorageBlocks
[i
].UniformBufferSize
>
3017 ctx
->Const
.MaxShaderStorageBlockSize
) {
3018 linker_error(prog
, "Shader storage block %s too big (%d/%d)\n",
3019 prog
->ShaderStorageBlocks
[i
].Name
,
3020 prog
->ShaderStorageBlocks
[i
].UniformBufferSize
,
3021 ctx
->Const
.MaxShaderStorageBlockSize
);
3027 link_calculate_subroutine_compat(struct gl_shader_program
*prog
)
3029 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3030 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3035 for (unsigned j
= 0; j
< sh
->NumSubroutineUniformRemapTable
; j
++) {
3036 struct gl_uniform_storage
*uni
= sh
->SubroutineUniformRemapTable
[j
];
3042 for (unsigned f
= 0; f
< sh
->NumSubroutineFunctions
; f
++) {
3043 struct gl_subroutine_function
*fn
= &sh
->SubroutineFunctions
[f
];
3044 for (int k
= 0; k
< fn
->num_compat_types
; k
++) {
3045 if (fn
->types
[k
] == uni
->type
) {
3051 uni
->num_compatible_subroutines
= count
;
3057 check_subroutine_resources(struct gl_shader_program
*prog
)
3059 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3060 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3063 if (sh
->NumSubroutineUniformRemapTable
> MAX_SUBROUTINE_UNIFORM_LOCATIONS
)
3064 linker_error(prog
, "Too many %s shader subroutine uniforms\n",
3065 _mesa_shader_stage_to_string(i
));
3070 * Validate shader image resources.
3073 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3075 unsigned total_image_units
= 0;
3076 unsigned fragment_outputs
= 0;
3077 unsigned total_shader_storage_blocks
= 0;
3079 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
3082 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3083 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3086 if (sh
->NumImages
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
3087 linker_error(prog
, "Too many %s shader image uniforms (%u > %u)\n",
3088 _mesa_shader_stage_to_string(i
), sh
->NumImages
,
3089 ctx
->Const
.Program
[i
].MaxImageUniforms
);
3091 total_image_units
+= sh
->NumImages
;
3092 total_shader_storage_blocks
+= sh
->NumShaderStorageBlocks
;
3094 if (i
== MESA_SHADER_FRAGMENT
) {
3095 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3096 ir_variable
*var
= node
->as_variable();
3097 if (var
&& var
->data
.mode
== ir_var_shader_out
)
3098 /* since there are no double fs outputs - pass false */
3099 fragment_outputs
+= var
->type
->count_attribute_slots(false);
3105 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
3106 linker_error(prog
, "Too many combined image uniforms\n");
3108 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
3109 ctx
->Const
.MaxCombinedShaderOutputResources
)
3110 linker_error(prog
, "Too many combined image uniforms, shader storage "
3111 " buffers and fragment outputs\n");
3116 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3117 * for a variable, checks for overlaps between other uniforms using explicit
3121 reserve_explicit_locations(struct gl_shader_program
*prog
,
3122 string_to_uint_map
*map
, ir_variable
*var
)
3124 unsigned slots
= var
->type
->uniform_locations();
3125 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3126 unsigned return_value
= slots
;
3128 /* Resize remap table if locations do not fit in the current one. */
3129 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
3130 prog
->UniformRemapTable
=
3131 reralloc(prog
, prog
->UniformRemapTable
,
3132 gl_uniform_storage
*,
3135 if (!prog
->UniformRemapTable
) {
3136 linker_error(prog
, "Out of memory during linking.\n");
3140 /* Initialize allocated space. */
3141 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
3142 prog
->UniformRemapTable
[i
] = NULL
;
3144 prog
->NumUniformRemapTable
= max_loc
+ 1;
3147 for (unsigned i
= 0; i
< slots
; i
++) {
3148 unsigned loc
= var
->data
.location
+ i
;
3150 /* Check if location is already used. */
3151 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3153 /* Possibly same uniform from a different stage, this is ok. */
3155 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
) {
3160 /* ARB_explicit_uniform_location specification states:
3162 * "No two default-block uniform variables in the program can have
3163 * the same location, even if they are unused, otherwise a compiler
3164 * or linker error will be generated."
3167 "location qualifier for uniform %s overlaps "
3168 "previously used location\n",
3173 /* Initialize location as inactive before optimization
3174 * rounds and location assignment.
3176 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3179 /* Note, base location used for arrays. */
3180 map
->put(var
->data
.location
, var
->name
);
3182 return return_value
;
3186 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3187 struct gl_shader
*sh
,
3190 unsigned slots
= var
->type
->uniform_locations();
3191 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3193 /* Resize remap table if locations do not fit in the current one. */
3194 if (max_loc
+ 1 > sh
->NumSubroutineUniformRemapTable
) {
3195 sh
->SubroutineUniformRemapTable
=
3196 reralloc(sh
, sh
->SubroutineUniformRemapTable
,
3197 gl_uniform_storage
*,
3200 if (!sh
->SubroutineUniformRemapTable
) {
3201 linker_error(prog
, "Out of memory during linking.\n");
3205 /* Initialize allocated space. */
3206 for (unsigned i
= sh
->NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3207 sh
->SubroutineUniformRemapTable
[i
] = NULL
;
3209 sh
->NumSubroutineUniformRemapTable
= max_loc
+ 1;
3212 for (unsigned i
= 0; i
< slots
; i
++) {
3213 unsigned loc
= var
->data
.location
+ i
;
3215 /* Check if location is already used. */
3216 if (sh
->SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3218 /* ARB_explicit_uniform_location specification states:
3219 * "No two subroutine uniform variables can have the same location
3220 * in the same shader stage, otherwise a compiler or linker error
3221 * will be generated."
3224 "location qualifier for uniform %s overlaps "
3225 "previously used location\n",
3230 /* Initialize location as inactive before optimization
3231 * rounds and location assignment.
3233 sh
->SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3239 * Check and reserve all explicit uniform locations, called before
3240 * any optimizations happen to handle also inactive uniforms and
3241 * inactive array elements that may get trimmed away.
3244 check_explicit_uniform_locations(struct gl_context
*ctx
,
3245 struct gl_shader_program
*prog
)
3247 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3250 /* This map is used to detect if overlapping explicit locations
3251 * occur with the same uniform (from different stage) or a different one.
3253 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3256 linker_error(prog
, "Out of memory during linking.\n");
3260 unsigned entries_total
= 0;
3261 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3262 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3267 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3268 ir_variable
*var
= node
->as_variable();
3269 if (!var
|| var
->data
.mode
!= ir_var_uniform
)
3272 if (var
->data
.explicit_location
) {
3274 if (var
->type
->without_array()->is_subroutine())
3275 ret
= reserve_subroutine_explicit_locations(prog
, sh
, var
);
3277 int slots
= reserve_explicit_locations(prog
, uniform_map
,
3281 entries_total
+= slots
;
3292 struct empty_uniform_block
*current_block
= NULL
;
3294 for (unsigned i
= 0; i
< prog
->NumUniformRemapTable
; i
++) {
3295 /* We found empty space in UniformRemapTable. */
3296 if (prog
->UniformRemapTable
[i
] == NULL
) {
3297 /* We've found the beginning of a new continous block of empty slots */
3298 if (!current_block
|| current_block
->start
+ current_block
->slots
!= i
) {
3299 current_block
= rzalloc(prog
, struct empty_uniform_block
);
3300 current_block
->start
= i
;
3301 exec_list_push_tail(&prog
->EmptyUniformLocations
,
3302 ¤t_block
->link
);
3305 /* The current block continues, so we simply increment its slots */
3306 current_block
->slots
++;
3311 return entries_total
;
3315 should_add_buffer_variable(struct gl_shader_program
*shProg
,
3316 GLenum type
, const char *name
)
3318 bool found_interface
= false;
3319 unsigned block_name_len
= 0;
3320 const char *block_name_dot
= strchr(name
, '.');
3322 /* These rules only apply to buffer variables. So we return
3323 * true for the rest of types.
3325 if (type
!= GL_BUFFER_VARIABLE
)
3328 for (unsigned i
= 0; i
< shProg
->NumShaderStorageBlocks
; i
++) {
3329 const char *block_name
= shProg
->ShaderStorageBlocks
[i
].Name
;
3330 block_name_len
= strlen(block_name
);
3332 const char *block_square_bracket
= strchr(block_name
, '[');
3333 if (block_square_bracket
) {
3334 /* The block is part of an array of named interfaces,
3335 * for the name comparison we ignore the "[x]" part.
3337 block_name_len
-= strlen(block_square_bracket
);
3340 if (block_name_dot
) {
3341 /* Check if the variable name starts with the interface
3342 * name. The interface name (if present) should have the
3343 * length than the interface block name we are comparing to.
3345 unsigned len
= strlen(name
) - strlen(block_name_dot
);
3346 if (len
!= block_name_len
)
3350 if (strncmp(block_name
, name
, block_name_len
) == 0) {
3351 found_interface
= true;
3356 /* We remove the interface name from the buffer variable name,
3357 * including the dot that follows it.
3359 if (found_interface
)
3360 name
= name
+ block_name_len
+ 1;
3362 /* From: ARB_program_interface_query extension:
3364 * "For an active shader storage block member declared as an array, an
3365 * entry will be generated only for the first array element, regardless
3366 * of its type. For arrays of aggregate types, the enumeration rules are
3367 * applied recursively for the single enumerated array element.
3369 const char *struct_first_dot
= strchr(name
, '.');
3370 const char *first_square_bracket
= strchr(name
, '[');
3372 /* The buffer variable is on top level and it is not an array */
3373 if (!first_square_bracket
) {
3375 /* The shader storage block member is a struct, then generate the entry */
3376 } else if (struct_first_dot
&& struct_first_dot
< first_square_bracket
) {
3379 /* Shader storage block member is an array, only generate an entry for the
3380 * first array element.
3382 if (strncmp(first_square_bracket
, "[0]", 3) == 0)
3390 add_program_resource(struct gl_shader_program
*prog
, GLenum type
,
3391 const void *data
, uint8_t stages
)
3395 /* If resource already exists, do not add it again. */
3396 for (unsigned i
= 0; i
< prog
->NumProgramResourceList
; i
++)
3397 if (prog
->ProgramResourceList
[i
].Data
== data
)
3400 prog
->ProgramResourceList
=
3402 prog
->ProgramResourceList
,
3403 gl_program_resource
,
3404 prog
->NumProgramResourceList
+ 1);
3406 if (!prog
->ProgramResourceList
) {
3407 linker_error(prog
, "Out of memory during linking.\n");
3411 struct gl_program_resource
*res
=
3412 &prog
->ProgramResourceList
[prog
->NumProgramResourceList
];
3416 res
->StageReferences
= stages
;
3418 prog
->NumProgramResourceList
++;
3423 /* Function checks if a variable var is a packed varying and
3424 * if given name is part of packed varying's list.
3426 * If a variable is a packed varying, it has a name like
3427 * 'packed:a,b,c' where a, b and c are separate variables.
3430 included_in_packed_varying(ir_variable
*var
, const char *name
)
3432 if (strncmp(var
->name
, "packed:", 7) != 0)
3435 char *list
= strdup(var
->name
+ 7);
3440 char *token
= strtok_r(list
, ",", &saveptr
);
3442 if (strcmp(token
, name
) == 0) {
3446 token
= strtok_r(NULL
, ",", &saveptr
);
3453 * Function builds a stage reference bitmask from variable name.
3456 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3461 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3462 * used for reference mask in gl_program_resource will need to be changed.
3464 assert(MESA_SHADER_STAGES
< 8);
3466 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3467 struct gl_shader
*sh
= shProg
->_LinkedShaders
[i
];
3471 /* Shader symbol table may contain variables that have
3472 * been optimized away. Search IR for the variable instead.
3474 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3475 ir_variable
*var
= node
->as_variable();
3477 unsigned baselen
= strlen(var
->name
);
3479 if (included_in_packed_varying(var
, name
)) {
3484 /* Type needs to match if specified, otherwise we might
3485 * pick a variable with same name but different interface.
3487 if (var
->data
.mode
!= mode
)
3490 if (strncmp(var
->name
, name
, baselen
) == 0) {
3491 /* Check for exact name matches but also check for arrays and
3494 if (name
[baselen
] == '\0' ||
3495 name
[baselen
] == '[' ||
3496 name
[baselen
] == '.') {
3508 * Create gl_shader_variable from ir_variable class.
3510 static gl_shader_variable
*
3511 create_shader_variable(struct gl_shader_program
*shProg
,
3512 const ir_variable
*in
,
3513 const char *name
, const glsl_type
*type
,
3514 bool use_implicit_location
, int location
)
3516 gl_shader_variable
*out
= ralloc(shProg
, struct gl_shader_variable
);
3520 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3521 * expect to see gl_VertexID in the program resource list. Pretend.
3523 if (in
->data
.mode
== ir_var_system_value
&&
3524 in
->data
.location
== SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
) {
3525 out
->name
= ralloc_strdup(shProg
, "gl_VertexID");
3527 out
->name
= ralloc_strdup(shProg
, name
);
3533 /* From the ARB_program_interface_query specification:
3535 * "Not all active variables are assigned valid locations; the
3536 * following variables will have an effective location of -1:
3538 * * uniforms declared as atomic counters;
3540 * * members of a uniform block;
3542 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3544 * * inputs or outputs not declared with a "location" layout qualifier,
3545 * except for vertex shader inputs and fragment shader outputs."
3547 if (in
->type
->base_type
== GLSL_TYPE_ATOMIC_UINT
||
3548 is_gl_identifier(in
->name
) ||
3549 !(in
->data
.explicit_location
|| use_implicit_location
)) {
3552 out
->location
= location
;
3556 out
->component
= in
->data
.location_frac
;
3557 out
->index
= in
->data
.index
;
3558 out
->patch
= in
->data
.patch
;
3559 out
->mode
= in
->data
.mode
;
3565 add_shader_variable(struct gl_shader_program
*shProg
, unsigned stage_mask
,
3566 GLenum programInterface
, ir_variable
*var
,
3567 const char *name
, const glsl_type
*type
,
3568 bool use_implicit_location
, int location
)
3570 const bool is_vertex_input
=
3571 programInterface
== GL_PROGRAM_INPUT
&&
3572 stage_mask
== MESA_SHADER_VERTEX
;
3574 switch (type
->base_type
) {
3575 case GLSL_TYPE_STRUCT
: {
3576 /* From the ARB_program_interface_query specification:
3578 * "For an active variable declared as a structure, a separate entry
3579 * will be generated for each active structure member. The name of
3580 * each entry is formed by concatenating the name of the structure,
3581 * the "." character, and the name of the structure member. If a
3582 * structure member to enumerate is itself a structure or array, these
3583 * enumeration rules are applied recursively."
3585 unsigned field_location
= location
;
3586 for (unsigned i
= 0; i
< type
->length
; i
++) {
3587 const struct glsl_struct_field
*field
= &type
->fields
.structure
[i
];
3588 char *field_name
= ralloc_asprintf(shProg
, "%s.%s", name
, field
->name
);
3589 if (!add_shader_variable(shProg
, stage_mask
, programInterface
,
3590 var
, field_name
, field
->type
,
3591 use_implicit_location
, field_location
))
3595 field
->type
->count_attribute_slots(is_vertex_input
);
3601 /* From the ARB_program_interface_query specification:
3603 * "For an active variable declared as a single instance of a basic
3604 * type, a single entry will be generated, using the variable name
3605 * from the shader source."
3607 gl_shader_variable
*sha_v
=
3608 create_shader_variable(shProg
, var
, name
, type
,
3609 use_implicit_location
, location
);
3613 return add_program_resource(shProg
, programInterface
, sha_v
, stage_mask
);
3619 add_interface_variables(struct gl_shader_program
*shProg
,
3620 unsigned stage
, GLenum programInterface
)
3622 exec_list
*ir
= shProg
->_LinkedShaders
[stage
]->ir
;
3624 foreach_in_list(ir_instruction
, node
, ir
) {
3625 ir_variable
*var
= node
->as_variable();
3627 if (!var
|| var
->data
.how_declared
== ir_var_hidden
)
3632 switch (var
->data
.mode
) {
3633 case ir_var_system_value
:
3634 case ir_var_shader_in
:
3635 if (programInterface
!= GL_PROGRAM_INPUT
)
3637 loc_bias
= (stage
== MESA_SHADER_VERTEX
) ? int(VERT_ATTRIB_GENERIC0
)
3638 : int(VARYING_SLOT_VAR0
);
3640 case ir_var_shader_out
:
3641 if (programInterface
!= GL_PROGRAM_OUTPUT
)
3643 loc_bias
= (stage
== MESA_SHADER_FRAGMENT
) ? int(FRAG_RESULT_DATA0
)
3644 : int(VARYING_SLOT_VAR0
);
3650 /* Skip packed varyings, packed varyings are handled separately
3651 * by add_packed_varyings.
3653 if (strncmp(var
->name
, "packed:", 7) == 0)
3656 /* Skip fragdata arrays, these are handled separately
3657 * by add_fragdata_arrays.
3659 if (strncmp(var
->name
, "gl_out_FragData", 15) == 0)
3662 const bool vs_input_or_fs_output
=
3663 (stage
== MESA_SHADER_VERTEX
&& var
->data
.mode
== ir_var_shader_in
) ||
3664 (stage
== MESA_SHADER_FRAGMENT
&& var
->data
.mode
== ir_var_shader_out
);
3666 if (!add_shader_variable(shProg
, 1 << stage
, programInterface
,
3667 var
, var
->name
, var
->type
, vs_input_or_fs_output
,
3668 var
->data
.location
- loc_bias
))
3675 add_packed_varyings(struct gl_shader_program
*shProg
, int stage
, GLenum type
)
3677 struct gl_shader
*sh
= shProg
->_LinkedShaders
[stage
];
3680 if (!sh
|| !sh
->packed_varyings
)
3683 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
3684 ir_variable
*var
= node
->as_variable();
3686 switch (var
->data
.mode
) {
3687 case ir_var_shader_in
:
3688 iface
= GL_PROGRAM_INPUT
;
3690 case ir_var_shader_out
:
3691 iface
= GL_PROGRAM_OUTPUT
;
3694 unreachable("unexpected type");
3697 if (type
== iface
) {
3698 const int stage_mask
=
3699 build_stageref(shProg
, var
->name
, var
->data
.mode
);
3700 if (!add_shader_variable(shProg
, stage_mask
,
3701 iface
, var
, var
->name
, var
->type
, false,
3702 var
->data
.location
- VARYING_SLOT_VAR0
))
3711 add_fragdata_arrays(struct gl_shader_program
*shProg
)
3713 struct gl_shader
*sh
= shProg
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
3715 if (!sh
|| !sh
->fragdata_arrays
)
3718 foreach_in_list(ir_instruction
, node
, sh
->fragdata_arrays
) {
3719 ir_variable
*var
= node
->as_variable();
3721 assert(var
->data
.mode
== ir_var_shader_out
);
3723 if (!add_shader_variable(shProg
,
3724 1 << MESA_SHADER_FRAGMENT
,
3725 GL_PROGRAM_OUTPUT
, var
, var
->name
, var
->type
,
3726 true, var
->data
.location
- FRAG_RESULT_DATA0
))
3734 get_top_level_name(const char *name
)
3736 const char *first_dot
= strchr(name
, '.');
3737 const char *first_square_bracket
= strchr(name
, '[');
3739 /* From ARB_program_interface_query spec:
3741 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying the
3742 * number of active array elements of the top-level shader storage block
3743 * member containing to the active variable is written to <params>. If the
3744 * top-level block member is not declared as an array, the value one is
3745 * written to <params>. If the top-level block member is an array with no
3746 * declared size, the value zero is written to <params>.
3749 /* The buffer variable is on top level.*/
3750 if (!first_square_bracket
&& !first_dot
)
3751 name_size
= strlen(name
);
3752 else if ((!first_square_bracket
||
3753 (first_dot
&& first_dot
< first_square_bracket
)))
3754 name_size
= first_dot
- name
;
3756 name_size
= first_square_bracket
- name
;
3758 return strndup(name
, name_size
);
3762 get_var_name(const char *name
)
3764 const char *first_dot
= strchr(name
, '.');
3767 return strdup(name
);
3769 return strndup(first_dot
+1, strlen(first_dot
) - 1);
3773 is_top_level_shader_storage_block_member(const char* name
,
3774 const char* interface_name
,
3775 const char* field_name
)
3777 bool result
= false;
3779 /* If the given variable is already a top-level shader storage
3780 * block member, then return array_size = 1.
3781 * We could have two possibilities: if we have an instanced
3782 * shader storage block or not instanced.
3784 * For the first, we check create a name as it was in top level and
3785 * compare it with the real name. If they are the same, then
3786 * the variable is already at top-level.
3788 * Full instanced name is: interface name + '.' + var name +
3791 int name_length
= strlen(interface_name
) + 1 + strlen(field_name
) + 1;
3792 char *full_instanced_name
= (char *) calloc(name_length
, sizeof(char));
3793 if (!full_instanced_name
) {
3794 fprintf(stderr
, "%s: Cannot allocate space for name\n", __func__
);
3798 snprintf(full_instanced_name
, name_length
, "%s.%s",
3799 interface_name
, field_name
);
3801 /* Check if its top-level shader storage block member of an
3802 * instanced interface block, or of a unnamed interface block.
3804 if (strcmp(name
, full_instanced_name
) == 0 ||
3805 strcmp(name
, field_name
) == 0)
3808 free(full_instanced_name
);
3813 get_array_size(struct gl_uniform_storage
*uni
, const glsl_struct_field
*field
,
3814 char *interface_name
, char *var_name
)
3816 /* From GL_ARB_program_interface_query spec:
3818 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer
3819 * identifying the number of active array elements of the top-level
3820 * shader storage block member containing to the active variable is
3821 * written to <params>. If the top-level block member is not
3822 * declared as an array, the value one is written to <params>. If
3823 * the top-level block member is an array with no declared size,
3824 * the value zero is written to <params>.
3826 if (is_top_level_shader_storage_block_member(uni
->name
,
3830 else if (field
->type
->is_unsized_array())
3832 else if (field
->type
->is_array())
3833 return field
->type
->length
;
3839 get_array_stride(struct gl_uniform_storage
*uni
, const glsl_type
*interface
,
3840 const glsl_struct_field
*field
, char *interface_name
,
3843 /* From GL_ARB_program_interface_query:
3845 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
3846 * identifying the stride between array elements of the top-level
3847 * shader storage block member containing the active variable is
3848 * written to <params>. For top-level block members declared as
3849 * arrays, the value written is the difference, in basic machine
3850 * units, between the offsets of the active variable for
3851 * consecutive elements in the top-level array. For top-level
3852 * block members not declared as an array, zero is written to
3855 if (field
->type
->is_array()) {
3856 const enum glsl_matrix_layout matrix_layout
=
3857 glsl_matrix_layout(field
->matrix_layout
);
3858 bool row_major
= matrix_layout
== GLSL_MATRIX_LAYOUT_ROW_MAJOR
;
3859 const glsl_type
*array_type
= field
->type
->fields
.array
;
3861 if (is_top_level_shader_storage_block_member(uni
->name
,
3866 if (interface
->interface_packing
!= GLSL_INTERFACE_PACKING_STD430
) {
3867 if (array_type
->is_record() || array_type
->is_array())
3868 return glsl_align(array_type
->std140_size(row_major
), 16);
3870 return MAX2(array_type
->std140_base_alignment(row_major
), 16);
3872 return array_type
->std430_array_stride(row_major
);
3879 calculate_array_size_and_stride(struct gl_shader_program
*shProg
,
3880 struct gl_uniform_storage
*uni
)
3882 int block_index
= uni
->block_index
;
3883 int array_size
= -1;
3884 int array_stride
= -1;
3885 char *var_name
= get_top_level_name(uni
->name
);
3886 char *interface_name
=
3887 get_top_level_name(uni
->is_shader_storage
?
3888 shProg
->ShaderStorageBlocks
[block_index
].Name
:
3889 shProg
->UniformBlocks
[block_index
].Name
);
3891 if (strcmp(var_name
, interface_name
) == 0) {
3892 /* Deal with instanced array of SSBOs */
3893 char *temp_name
= get_var_name(uni
->name
);
3895 linker_error(shProg
, "Out of memory during linking.\n");
3896 goto write_top_level_array_size_and_stride
;
3899 var_name
= get_top_level_name(temp_name
);
3902 linker_error(shProg
, "Out of memory during linking.\n");
3903 goto write_top_level_array_size_and_stride
;
3907 for (unsigned i
= 0; i
< shProg
->NumShaders
; i
++) {
3908 if (shProg
->Shaders
[i
] == NULL
)
3911 const gl_shader
*stage
= shProg
->Shaders
[i
];
3912 foreach_in_list(ir_instruction
, node
, stage
->ir
) {
3913 ir_variable
*var
= node
->as_variable();
3914 if (!var
|| !var
->get_interface_type() ||
3915 var
->data
.mode
!= ir_var_shader_storage
)
3918 const glsl_type
*interface
= var
->get_interface_type();
3920 if (strcmp(interface_name
, interface
->name
) != 0)
3923 for (unsigned i
= 0; i
< interface
->length
; i
++) {
3924 const glsl_struct_field
*field
= &interface
->fields
.structure
[i
];
3925 if (strcmp(field
->name
, var_name
) != 0)
3928 array_stride
= get_array_stride(uni
, interface
, field
,
3929 interface_name
, var_name
);
3930 array_size
= get_array_size(uni
, field
, interface_name
, var_name
);
3931 goto write_top_level_array_size_and_stride
;
3935 write_top_level_array_size_and_stride
:
3936 free(interface_name
);
3938 uni
->top_level_array_stride
= array_stride
;
3939 uni
->top_level_array_size
= array_size
;
3943 * Builds up a list of program resources that point to existing
3947 build_program_resource_list(struct gl_context
*ctx
,
3948 struct gl_shader_program
*shProg
)
3950 /* Rebuild resource list. */
3951 if (shProg
->ProgramResourceList
) {
3952 ralloc_free(shProg
->ProgramResourceList
);
3953 shProg
->ProgramResourceList
= NULL
;
3954 shProg
->NumProgramResourceList
= 0;
3957 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
3959 /* Determine first input and final output stage. These are used to
3960 * detect which variables should be enumerated in the resource list
3961 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
3963 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3964 if (!shProg
->_LinkedShaders
[i
])
3966 if (input_stage
== MESA_SHADER_STAGES
)
3971 /* Empty shader, no resources. */
3972 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
3975 /* Program interface needs to expose varyings in case of SSO. */
3976 if (shProg
->SeparateShader
) {
3977 if (!add_packed_varyings(shProg
, input_stage
, GL_PROGRAM_INPUT
))
3980 if (!add_packed_varyings(shProg
, output_stage
, GL_PROGRAM_OUTPUT
))
3984 if (!add_fragdata_arrays(shProg
))
3987 /* Add inputs and outputs to the resource list. */
3988 if (!add_interface_variables(shProg
, input_stage
, GL_PROGRAM_INPUT
))
3991 if (!add_interface_variables(shProg
, output_stage
, GL_PROGRAM_OUTPUT
))
3994 /* Add transform feedback varyings. */
3995 if (shProg
->LinkedTransformFeedback
.NumVarying
> 0) {
3996 for (int i
= 0; i
< shProg
->LinkedTransformFeedback
.NumVarying
; i
++) {
3997 if (!add_program_resource(shProg
, GL_TRANSFORM_FEEDBACK_VARYING
,
3998 &shProg
->LinkedTransformFeedback
.Varyings
[i
],
4004 /* Add transform feedback buffers. */
4005 for (unsigned i
= 0; i
< ctx
->Const
.MaxTransformFeedbackBuffers
; i
++) {
4006 if ((shProg
->LinkedTransformFeedback
.ActiveBuffers
>> i
) & 1) {
4007 shProg
->LinkedTransformFeedback
.Buffers
[i
].Binding
= i
;
4008 if (!add_program_resource(shProg
, GL_TRANSFORM_FEEDBACK_BUFFER
,
4009 &shProg
->LinkedTransformFeedback
.Buffers
[i
],
4015 /* Add uniforms from uniform storage. */
4016 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
4017 /* Do not add uniforms internally used by Mesa. */
4018 if (shProg
->UniformStorage
[i
].hidden
)
4022 build_stageref(shProg
, shProg
->UniformStorage
[i
].name
,
4025 /* Add stagereferences for uniforms in a uniform block. */
4026 bool is_shader_storage
= shProg
->UniformStorage
[i
].is_shader_storage
;
4027 int block_index
= shProg
->UniformStorage
[i
].block_index
;
4028 if (block_index
!= -1) {
4029 stageref
|= is_shader_storage
?
4030 shProg
->ShaderStorageBlocks
[block_index
].stageref
:
4031 shProg
->UniformBlocks
[block_index
].stageref
;
4034 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
4035 if (!should_add_buffer_variable(shProg
, type
,
4036 shProg
->UniformStorage
[i
].name
))
4039 if (is_shader_storage
) {
4040 calculate_array_size_and_stride(shProg
, &shProg
->UniformStorage
[i
]);
4043 if (!add_program_resource(shProg
, type
,
4044 &shProg
->UniformStorage
[i
], stageref
))
4048 /* Add program uniform blocks. */
4049 for (unsigned i
= 0; i
< shProg
->NumUniformBlocks
; i
++) {
4050 if (!add_program_resource(shProg
, GL_UNIFORM_BLOCK
,
4051 &shProg
->UniformBlocks
[i
], 0))
4055 /* Add program shader storage blocks. */
4056 for (unsigned i
= 0; i
< shProg
->NumShaderStorageBlocks
; i
++) {
4057 if (!add_program_resource(shProg
, GL_SHADER_STORAGE_BLOCK
,
4058 &shProg
->ShaderStorageBlocks
[i
], 0))
4062 /* Add atomic counter buffers. */
4063 for (unsigned i
= 0; i
< shProg
->NumAtomicBuffers
; i
++) {
4064 if (!add_program_resource(shProg
, GL_ATOMIC_COUNTER_BUFFER
,
4065 &shProg
->AtomicBuffers
[i
], 0))
4069 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
4071 if (!shProg
->UniformStorage
[i
].hidden
)
4074 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
4075 if (!shProg
->UniformStorage
[i
].opaque
[j
].active
||
4076 !shProg
->UniformStorage
[i
].type
->is_subroutine())
4079 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
4080 /* add shader subroutines */
4081 if (!add_program_resource(shProg
, type
, &shProg
->UniformStorage
[i
], 0))
4086 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4087 struct gl_shader
*sh
= shProg
->_LinkedShaders
[i
];
4093 type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
4094 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
4095 if (!add_program_resource(shProg
, type
, &sh
->SubroutineFunctions
[j
], 0))
4102 * This check is done to make sure we allow only constant expression
4103 * indexing and "constant-index-expression" (indexing with an expression
4104 * that includes loop induction variable).
4107 validate_sampler_array_indexing(struct gl_context
*ctx
,
4108 struct gl_shader_program
*prog
)
4110 dynamic_sampler_array_indexing_visitor v
;
4111 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4112 if (prog
->_LinkedShaders
[i
] == NULL
)
4115 bool no_dynamic_indexing
=
4116 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
4118 /* Search for array derefs in shader. */
4119 v
.run(prog
->_LinkedShaders
[i
]->ir
);
4120 if (v
.uses_dynamic_sampler_array_indexing()) {
4121 const char *msg
= "sampler arrays indexed with non-constant "
4122 "expressions is forbidden in GLSL %s %u";
4123 /* Backend has indicated that it has no dynamic indexing support. */
4124 if (no_dynamic_indexing
) {
4125 linker_error(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
4128 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
4136 link_assign_subroutine_types(struct gl_shader_program
*prog
)
4138 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4139 gl_shader
*sh
= prog
->_LinkedShaders
[i
];
4144 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
4145 ir_function
*fn
= node
->as_function();
4149 if (fn
->is_subroutine
)
4150 sh
->NumSubroutineUniformTypes
++;
4152 if (!fn
->num_subroutine_types
)
4155 sh
->SubroutineFunctions
= reralloc(sh
, sh
->SubroutineFunctions
,
4156 struct gl_subroutine_function
,
4157 sh
->NumSubroutineFunctions
+ 1);
4158 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].name
= ralloc_strdup(sh
, fn
->name
);
4159 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
4160 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
=
4161 ralloc_array(sh
, const struct glsl_type
*,
4162 fn
->num_subroutine_types
);
4164 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4167 * "Each subroutine with an index qualifier in the shader must be
4168 * given a unique index, otherwise a compile or link error will be
4171 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
4172 if (sh
->SubroutineFunctions
[j
].index
!= -1 &&
4173 sh
->SubroutineFunctions
[j
].index
== fn
->subroutine_index
) {
4174 linker_error(prog
, "each subroutine index qualifier in the "
4175 "shader must be unique\n");
4179 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].index
=
4180 fn
->subroutine_index
;
4182 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
4183 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
4184 sh
->NumSubroutineFunctions
++;
4187 /* Assign index for subroutines without an explicit index*/
4189 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
4190 while (sh
->SubroutineFunctions
[j
].index
== -1) {
4191 for (unsigned k
= 0; k
< sh
->NumSubroutineFunctions
; k
++) {
4192 if (sh
->SubroutineFunctions
[k
].index
== index
)
4194 else if (k
== sh
->NumSubroutineFunctions
- 1)
4195 sh
->SubroutineFunctions
[j
].index
= index
;
4204 set_always_active_io(exec_list
*ir
, ir_variable_mode io_mode
)
4206 assert(io_mode
== ir_var_shader_in
|| io_mode
== ir_var_shader_out
);
4208 foreach_in_list(ir_instruction
, node
, ir
) {
4209 ir_variable
*const var
= node
->as_variable();
4211 if (var
== NULL
|| var
->data
.mode
!= io_mode
)
4214 /* Don't set always active on builtins that haven't been redeclared */
4215 if (var
->data
.how_declared
== ir_var_declared_implicitly
)
4218 var
->data
.always_active_io
= true;
4223 * When separate shader programs are enabled, only input/outputs between
4224 * the stages of a multi-stage separate program can be safely removed
4225 * from the shader interface. Other inputs/outputs must remain active.
4228 disable_varying_optimizations_for_sso(struct gl_shader_program
*prog
)
4230 unsigned first
, last
;
4231 assert(prog
->SeparateShader
);
4233 first
= MESA_SHADER_STAGES
;
4236 /* Determine first and last stage. Excluding the compute stage */
4237 for (unsigned i
= 0; i
< MESA_SHADER_COMPUTE
; i
++) {
4238 if (!prog
->_LinkedShaders
[i
])
4240 if (first
== MESA_SHADER_STAGES
)
4245 if (first
== MESA_SHADER_STAGES
)
4248 for (unsigned stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4249 gl_shader
*sh
= prog
->_LinkedShaders
[stage
];
4253 if (first
== last
) {
4254 /* For a single shader program only allow inputs to the vertex shader
4255 * and outputs from the fragment shader to be removed.
4257 if (stage
!= MESA_SHADER_VERTEX
)
4258 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4259 if (stage
!= MESA_SHADER_FRAGMENT
)
4260 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4262 /* For multi-stage separate shader programs only allow inputs and
4263 * outputs between the shader stages to be removed as well as inputs
4264 * to the vertex shader and outputs from the fragment shader.
4266 if (stage
== first
&& stage
!= MESA_SHADER_VERTEX
)
4267 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4268 else if (stage
== last
&& stage
!= MESA_SHADER_FRAGMENT
)
4269 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4275 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
4277 prog
->LinkStatus
= true; /* All error paths will set this to false */
4278 prog
->Validated
= false;
4279 prog
->_Used
= false;
4281 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4283 * "Linking can fail for a variety of reasons as specified in the
4284 * OpenGL Shading Language Specification, as well as any of the
4285 * following reasons:
4287 * - No shader objects are attached to program."
4289 * The Compatibility Profile specification does not list the error. In
4290 * Compatibility Profile missing shader stages are replaced by
4291 * fixed-function. This applies to the case where all stages are
4294 if (prog
->NumShaders
== 0) {
4295 if (ctx
->API
!= API_OPENGL_COMPAT
)
4296 linker_error(prog
, "no shaders attached to the program\n");
4300 unsigned num_tfeedback_decls
= 0;
4301 unsigned int num_explicit_uniform_locs
= 0;
4302 bool has_xfb_qualifiers
= false;
4303 char **varying_names
= NULL
;
4304 tfeedback_decl
*tfeedback_decls
= NULL
;
4306 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
4308 prog
->ARB_fragment_coord_conventions_enable
= false;
4310 /* Separate the shaders into groups based on their type.
4312 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
4313 unsigned num_shaders
[MESA_SHADER_STAGES
];
4315 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4316 shader_list
[i
] = (struct gl_shader
**)
4317 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
4321 unsigned min_version
= UINT_MAX
;
4322 unsigned max_version
= 0;
4323 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
4324 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
4325 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
4327 if (prog
->Shaders
[i
]->IsES
!= prog
->Shaders
[0]->IsES
) {
4328 linker_error(prog
, "all shaders must use same shading "
4329 "language version\n");
4333 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
4334 prog
->ARB_fragment_coord_conventions_enable
= true;
4337 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
4338 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
4339 num_shaders
[shader_type
]++;
4342 /* In desktop GLSL, different shader versions may be linked together. In
4343 * GLSL ES, all shader versions must be the same.
4345 if (prog
->Shaders
[0]->IsES
&& min_version
!= max_version
) {
4346 linker_error(prog
, "all shaders must use same shading "
4347 "language version\n");
4351 prog
->Version
= max_version
;
4352 prog
->IsES
= prog
->Shaders
[0]->IsES
;
4354 /* Some shaders have to be linked with some other shaders present.
4356 if (!prog
->SeparateShader
) {
4357 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
4358 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4359 linker_error(prog
, "Geometry shader must be linked with "
4363 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4364 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4365 linker_error(prog
, "Tessellation evaluation shader must be linked "
4366 "with vertex shader\n");
4369 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4370 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4371 linker_error(prog
, "Tessellation control shader must be linked with "
4376 /* The spec is self-contradictory here. It allows linking without a tess
4377 * eval shader, but that can only be used with transform feedback and
4378 * rasterization disabled. However, transform feedback isn't allowed
4379 * with GL_PATCHES, so it can't be used.
4381 * More investigation showed that the idea of transform feedback after
4382 * a tess control shader was dropped, because some hw vendors couldn't
4383 * support tessellation without a tess eval shader, but the linker
4384 * section wasn't updated to reflect that.
4386 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4389 * Do what's reasonable and always require a tess eval shader if a tess
4390 * control shader is present.
4392 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4393 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0) {
4394 linker_error(prog
, "Tessellation control shader must be linked with "
4395 "tessellation evaluation shader\n");
4400 /* Compute shaders have additional restrictions. */
4401 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
4402 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
4403 linker_error(prog
, "Compute shaders may not be linked with any other "
4404 "type of shader\n");
4407 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4408 if (prog
->_LinkedShaders
[i
] != NULL
)
4409 _mesa_delete_shader(ctx
, prog
->_LinkedShaders
[i
]);
4411 prog
->_LinkedShaders
[i
] = NULL
;
4414 /* Link all shaders for a particular stage and validate the result.
4416 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4417 if (num_shaders
[stage
] > 0) {
4418 gl_shader
*const sh
=
4419 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
4420 num_shaders
[stage
]);
4422 if (!prog
->LinkStatus
) {
4424 _mesa_delete_shader(ctx
, sh
);
4429 case MESA_SHADER_VERTEX
:
4430 validate_vertex_shader_executable(prog
, sh
);
4432 case MESA_SHADER_TESS_CTRL
:
4433 /* nothing to be done */
4435 case MESA_SHADER_TESS_EVAL
:
4436 validate_tess_eval_shader_executable(prog
, sh
);
4438 case MESA_SHADER_GEOMETRY
:
4439 validate_geometry_shader_executable(prog
, sh
);
4441 case MESA_SHADER_FRAGMENT
:
4442 validate_fragment_shader_executable(prog
, sh
);
4445 if (!prog
->LinkStatus
) {
4447 _mesa_delete_shader(ctx
, sh
);
4451 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[stage
], sh
);
4455 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0)
4456 prog
->LastClipDistanceArraySize
= prog
->Geom
.ClipDistanceArraySize
;
4457 else if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0)
4458 prog
->LastClipDistanceArraySize
= prog
->TessEval
.ClipDistanceArraySize
;
4459 else if (num_shaders
[MESA_SHADER_VERTEX
] > 0)
4460 prog
->LastClipDistanceArraySize
= prog
->Vert
.ClipDistanceArraySize
;
4462 prog
->LastClipDistanceArraySize
= 0; /* Not used */
4464 /* Here begins the inter-stage linking phase. Some initial validation is
4465 * performed, then locations are assigned for uniforms, attributes, and
4468 cross_validate_uniforms(prog
);
4469 if (!prog
->LinkStatus
)
4472 unsigned first
, last
, prev
;
4474 first
= MESA_SHADER_STAGES
;
4477 /* Determine first and last stage. */
4478 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4479 if (!prog
->_LinkedShaders
[i
])
4481 if (first
== MESA_SHADER_STAGES
)
4486 num_explicit_uniform_locs
= check_explicit_uniform_locations(ctx
, prog
);
4487 link_assign_subroutine_types(prog
);
4489 if (!prog
->LinkStatus
)
4492 resize_tes_inputs(ctx
, prog
);
4494 /* Validate the inputs of each stage with the output of the preceding
4498 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4499 if (prog
->_LinkedShaders
[i
] == NULL
)
4502 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
4503 prog
->_LinkedShaders
[i
]);
4504 if (!prog
->LinkStatus
)
4507 cross_validate_outputs_to_inputs(prog
,
4508 prog
->_LinkedShaders
[prev
],
4509 prog
->_LinkedShaders
[i
]);
4510 if (!prog
->LinkStatus
)
4516 /* Cross-validate uniform blocks between shader stages */
4517 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
,
4518 MESA_SHADER_STAGES
);
4519 if (!prog
->LinkStatus
)
4522 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4523 if (prog
->_LinkedShaders
[i
] != NULL
)
4524 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
4527 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4528 * it before optimization because we want most of the checks to get
4529 * dropped thanks to constant propagation.
4531 * This rule also applies to GLSL ES 3.00.
4533 if (max_version
>= (prog
->IsES
? 300 : 130)) {
4534 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4536 lower_discard_flow(sh
->ir
);
4540 if (prog
->SeparateShader
)
4541 disable_varying_optimizations_for_sso(prog
);
4544 if (!interstage_cross_validate_uniform_blocks(prog
, false))
4548 if (!interstage_cross_validate_uniform_blocks(prog
, true))
4551 /* Do common optimization before assigning storage for attributes,
4552 * uniforms, and varyings. Later optimization could possibly make
4553 * some of that unused.
4555 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4556 if (prog
->_LinkedShaders
[i
] == NULL
)
4559 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
4560 if (!prog
->LinkStatus
)
4563 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerCombinedClipCullDistance
) {
4564 lower_clip_distance(prog
->_LinkedShaders
[i
]);
4567 if (ctx
->Const
.LowerTessLevel
) {
4568 lower_tess_level(prog
->_LinkedShaders
[i
]);
4571 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false,
4572 &ctx
->Const
.ShaderCompilerOptions
[i
],
4573 ctx
->Const
.NativeIntegers
))
4576 lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
);
4579 /* Validation for special cases where we allow sampler array indexing
4580 * with loop induction variable. This check emits a warning or error
4581 * depending if backend can handle dynamic indexing.
4583 if ((!prog
->IsES
&& prog
->Version
< 130) ||
4584 (prog
->IsES
&& prog
->Version
< 300)) {
4585 if (!validate_sampler_array_indexing(ctx
, prog
))
4589 /* Check and validate stream emissions in geometry shaders */
4590 validate_geometry_shader_emissions(ctx
, prog
);
4592 /* Mark all generic shader inputs and outputs as unpaired. */
4593 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4594 if (prog
->_LinkedShaders
[i
] != NULL
) {
4595 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
4600 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4601 if (prog
->_LinkedShaders
[i
] == NULL
)
4604 match_explicit_outputs_to_inputs(prog
, prog
->_LinkedShaders
[prev
],
4605 prog
->_LinkedShaders
[i
]);
4609 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
4610 MESA_SHADER_VERTEX
)) {
4614 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
4615 MESA_SHADER_FRAGMENT
)) {
4619 /* From the ARB_enhanced_layouts spec:
4621 * "If the shader used to record output variables for transform feedback
4622 * varyings uses the "xfb_buffer", "xfb_offset", or "xfb_stride" layout
4623 * qualifiers, the values specified by TransformFeedbackVaryings are
4624 * ignored, and the set of variables captured for transform feedback is
4625 * instead derived from the specified layout qualifiers."
4627 for (int i
= MESA_SHADER_FRAGMENT
- 1; i
>= 0; i
--) {
4628 /* Find last stage before fragment shader */
4629 if (prog
->_LinkedShaders
[i
]) {
4630 has_xfb_qualifiers
=
4631 process_xfb_layout_qualifiers(mem_ctx
, prog
->_LinkedShaders
[i
],
4632 &num_tfeedback_decls
,
4638 if (!has_xfb_qualifiers
) {
4639 num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
4640 varying_names
= prog
->TransformFeedback
.VaryingNames
;
4643 if (num_tfeedback_decls
!= 0) {
4644 /* From GL_EXT_transform_feedback:
4645 * A program will fail to link if:
4647 * * the <count> specified by TransformFeedbackVaryingsEXT is
4648 * non-zero, but the program object has no vertex or geometry
4651 if (first
>= MESA_SHADER_FRAGMENT
) {
4652 linker_error(prog
, "Transform feedback varyings specified, but "
4653 "no vertex, tessellation, or geometry shader is "
4658 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
4659 num_tfeedback_decls
);
4660 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
4661 varying_names
, tfeedback_decls
))
4665 /* If there is no fragment shader we need to set transform feedback.
4667 * For SSO we need also need to assign output locations, we assign them
4668 * here because we need to do it for both single stage programs and multi
4671 if (last
< MESA_SHADER_FRAGMENT
&&
4672 (num_tfeedback_decls
!= 0 || prog
->SeparateShader
)) {
4673 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
4674 prog
->_LinkedShaders
[last
], NULL
,
4675 num_tfeedback_decls
, tfeedback_decls
))
4679 if (last
<= MESA_SHADER_FRAGMENT
) {
4680 /* Remove unused varyings from the first/last stage unless SSO */
4681 remove_unused_shader_inputs_and_outputs(prog
->SeparateShader
,
4682 prog
->_LinkedShaders
[first
],
4684 remove_unused_shader_inputs_and_outputs(prog
->SeparateShader
,
4685 prog
->_LinkedShaders
[last
],
4688 /* If the program is made up of only a single stage */
4689 if (first
== last
) {
4691 gl_shader
*const sh
= prog
->_LinkedShaders
[last
];
4692 if (prog
->SeparateShader
) {
4693 /* Assign input locations for SSO, output locations are already
4696 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
4697 NULL
/* producer */,
4699 0 /* num_tfeedback_decls */,
4700 NULL
/* tfeedback_decls */))
4704 do_dead_builtin_varyings(ctx
, NULL
, sh
, 0, NULL
);
4705 do_dead_builtin_varyings(ctx
, sh
, NULL
, num_tfeedback_decls
,
4708 /* Linking the stages in the opposite order (from fragment to vertex)
4709 * ensures that inter-shader outputs written to in an earlier stage
4710 * are eliminated if they are (transitively) not used in a later
4714 for (int i
= next
- 1; i
>= 0; i
--) {
4715 if (prog
->_LinkedShaders
[i
] == NULL
)
4718 gl_shader
*const sh_i
= prog
->_LinkedShaders
[i
];
4719 gl_shader
*const sh_next
= prog
->_LinkedShaders
[next
];
4721 if (!assign_varying_locations(ctx
, mem_ctx
, prog
, sh_i
, sh_next
,
4722 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
4726 do_dead_builtin_varyings(ctx
, sh_i
, sh_next
,
4727 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
4730 /* This must be done after all dead varyings are eliminated. */
4731 if (!check_against_output_limit(ctx
, prog
, sh_i
))
4733 if (!check_against_input_limit(ctx
, prog
, sh_next
))
4741 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
,
4742 has_xfb_qualifiers
))
4745 update_array_sizes(prog
);
4746 link_assign_uniform_locations(prog
, ctx
->Const
.UniformBooleanTrue
,
4747 num_explicit_uniform_locs
,
4748 ctx
->Const
.MaxUserAssignableUniformLocations
);
4749 link_assign_atomic_counter_resources(ctx
, prog
);
4750 store_fragdepth_layout(prog
);
4752 link_calculate_subroutine_compat(prog
);
4753 check_resources(ctx
, prog
);
4754 check_subroutine_resources(prog
);
4755 check_image_resources(ctx
, prog
);
4756 link_check_atomic_counter_resources(ctx
, prog
);
4758 if (!prog
->LinkStatus
)
4761 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
4762 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
4763 * anything about shader linking when one of the shaders (vertex or
4764 * fragment shader) is absent. So, the extension shouldn't change the
4765 * behavior specified in GLSL specification.
4767 * From OpenGL ES 3.1 specification (7.3 Program Objects):
4768 * "Linking can fail for a variety of reasons as specified in the
4769 * OpenGL ES Shading Language Specification, as well as any of the
4770 * following reasons:
4774 * * program contains objects to form either a vertex shader or
4775 * fragment shader, and program is not separable, and does not
4776 * contain objects to form both a vertex shader and fragment
4779 * However, the only scenario in 3.1+ where we don't require them both is
4780 * when we have a compute shader. For example:
4782 * - No shaders is a link error.
4783 * - Geom or Tess without a Vertex shader is a link error which means we
4784 * always require a Vertex shader and hence a Fragment shader.
4785 * - Finally a Compute shader linked with any other stage is a link error.
4787 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
&&
4788 num_shaders
[MESA_SHADER_COMPUTE
] == 0) {
4789 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
4790 linker_error(prog
, "program lacks a vertex shader\n");
4791 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
4792 linker_error(prog
, "program lacks a fragment shader\n");
4796 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4797 if (prog
->_LinkedShaders
[i
] == NULL
)
4800 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerBufferInterfaceBlocks
)
4801 lower_ubo_reference(prog
->_LinkedShaders
[i
]);
4803 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerShaderSharedVariables
)
4804 lower_shared_reference(prog
->_LinkedShaders
[i
],
4805 &prog
->Comp
.SharedSize
);
4807 lower_vector_derefs(prog
->_LinkedShaders
[i
]);
4808 do_vec_index_to_swizzle(prog
->_LinkedShaders
[i
]->ir
);
4812 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4813 free(shader_list
[i
]);
4814 if (prog
->_LinkedShaders
[i
] == NULL
)
4817 /* Do a final validation step to make sure that the IR wasn't
4818 * invalidated by any modifications performed after intrastage linking.
4820 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
4822 /* Retain any live IR, but trash the rest. */
4823 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
4825 /* The symbol table in the linked shaders may contain references to
4826 * variables that were removed (e.g., unused uniforms). Since it may
4827 * contain junk, there is no possible valid use. Delete it and set the
4830 delete prog
->_LinkedShaders
[i
]->symbols
;
4831 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
4834 ralloc_free(mem_ctx
);