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 existing
->data
.location
= var
->data
.location
;
992 existing
->data
.explicit_location
= true;
994 /* Check if uniform with implicit location was marked explicit
995 * by earlier shader stage. If so, mark it explicit in this stage
996 * too to make sure later processing does not treat it as
999 if (existing
->data
.explicit_location
) {
1000 var
->data
.location
= existing
->data
.location
;
1001 var
->data
.explicit_location
= true;
1005 /* From the GLSL 4.20 specification:
1006 * "A link error will result if two compilation units in a program
1007 * specify different integer-constant bindings for the same
1008 * opaque-uniform name. However, it is not an error to specify a
1009 * binding on some but not all declarations for the same name"
1011 if (var
->data
.explicit_binding
) {
1012 if (existing
->data
.explicit_binding
&&
1013 var
->data
.binding
!= existing
->data
.binding
) {
1014 linker_error(prog
, "explicit bindings for %s "
1015 "`%s' have differing values\n",
1016 mode_string(var
), var
->name
);
1020 existing
->data
.binding
= var
->data
.binding
;
1021 existing
->data
.explicit_binding
= true;
1024 if (var
->type
->contains_atomic() &&
1025 var
->data
.offset
!= existing
->data
.offset
) {
1026 linker_error(prog
, "offset specifications for %s "
1027 "`%s' have differing values\n",
1028 mode_string(var
), var
->name
);
1032 /* Validate layout qualifiers for gl_FragDepth.
1034 * From the AMD/ARB_conservative_depth specs:
1036 * "If gl_FragDepth is redeclared in any fragment shader in a
1037 * program, it must be redeclared in all fragment shaders in
1038 * that program that have static assignments to
1039 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1040 * fragment shaders in a single program must have the same set
1043 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1044 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1045 bool layout_differs
=
1046 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1048 if (layout_declared
&& layout_differs
) {
1050 "All redeclarations of gl_FragDepth in all "
1051 "fragment shaders in a single program must have "
1052 "the same set of qualifiers.\n");
1055 if (var
->data
.used
&& layout_differs
) {
1057 "If gl_FragDepth is redeclared with a layout "
1058 "qualifier in any fragment shader, it must be "
1059 "redeclared with the same layout qualifier in "
1060 "all fragment shaders that have assignments to "
1065 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1067 * "If a shared global has multiple initializers, the
1068 * initializers must all be constant expressions, and they
1069 * must all have the same value. Otherwise, a link error will
1070 * result. (A shared global having only one initializer does
1071 * not require that initializer to be a constant expression.)"
1073 * Previous to 4.20 the GLSL spec simply said that initializers
1074 * must have the same value. In this case of non-constant
1075 * initializers, this was impossible to determine. As a result,
1076 * no vendor actually implemented that behavior. The 4.20
1077 * behavior matches the implemented behavior of at least one other
1078 * vendor, so we'll implement that for all GLSL versions.
1080 if (var
->constant_initializer
!= NULL
) {
1081 if (existing
->constant_initializer
!= NULL
) {
1082 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1083 linker_error(prog
, "initializers for %s "
1084 "`%s' have differing values\n",
1085 mode_string(var
), var
->name
);
1089 /* If the first-seen instance of a particular uniform did not
1090 * have an initializer but a later instance does, copy the
1091 * initializer to the version stored in the symbol table.
1093 /* FINISHME: This is wrong. The constant_value field should
1094 * FINISHME: not be modified! Imagine a case where a shader
1095 * FINISHME: without an initializer is linked in two different
1096 * FINISHME: programs with shaders that have differing
1097 * FINISHME: initializers. Linking with the first will
1098 * FINISHME: modify the shader, and linking with the second
1099 * FINISHME: will fail.
1101 existing
->constant_initializer
=
1102 var
->constant_initializer
->clone(ralloc_parent(existing
),
1107 if (var
->data
.has_initializer
) {
1108 if (existing
->data
.has_initializer
1109 && (var
->constant_initializer
== NULL
1110 || existing
->constant_initializer
== NULL
)) {
1112 "shared global variable `%s' has multiple "
1113 "non-constant initializers.\n",
1118 /* Some instance had an initializer, so keep track of that. In
1119 * this location, all sorts of initializers (constant or
1120 * otherwise) will propagate the existence to the variable
1121 * stored in the symbol table.
1123 existing
->data
.has_initializer
= true;
1126 if (existing
->data
.invariant
!= var
->data
.invariant
) {
1127 linker_error(prog
, "declarations for %s `%s' have "
1128 "mismatching invariant qualifiers\n",
1129 mode_string(var
), var
->name
);
1132 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1133 linker_error(prog
, "declarations for %s `%s' have "
1134 "mismatching centroid qualifiers\n",
1135 mode_string(var
), var
->name
);
1138 if (existing
->data
.sample
!= var
->data
.sample
) {
1139 linker_error(prog
, "declarations for %s `%s` have "
1140 "mismatching sample qualifiers\n",
1141 mode_string(var
), var
->name
);
1144 if (existing
->data
.image_format
!= var
->data
.image_format
) {
1145 linker_error(prog
, "declarations for %s `%s` have "
1146 "mismatching image format qualifiers\n",
1147 mode_string(var
), var
->name
);
1151 variables
.add_variable(var
);
1158 * Perform validation of uniforms used across multiple shader stages
1161 cross_validate_uniforms(struct gl_shader_program
*prog
)
1163 cross_validate_globals(prog
, prog
->_LinkedShaders
,
1164 MESA_SHADER_STAGES
, true);
1168 * Accumulates the array of prog->BufferInterfaceBlocks and checks that all
1169 * definitons of blocks agree on their contents.
1172 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
)
1174 unsigned max_num_uniform_blocks
= 0;
1175 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1176 if (prog
->_LinkedShaders
[i
])
1177 max_num_uniform_blocks
+= prog
->_LinkedShaders
[i
]->NumBufferInterfaceBlocks
;
1180 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1181 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1183 prog
->InterfaceBlockStageIndex
[i
] = ralloc_array(prog
, int,
1184 max_num_uniform_blocks
);
1185 for (unsigned int j
= 0; j
< max_num_uniform_blocks
; j
++)
1186 prog
->InterfaceBlockStageIndex
[i
][j
] = -1;
1191 for (unsigned int j
= 0; j
< sh
->NumBufferInterfaceBlocks
; j
++) {
1192 int index
= link_cross_validate_uniform_block(prog
,
1193 &prog
->BufferInterfaceBlocks
,
1194 &prog
->NumBufferInterfaceBlocks
,
1195 sh
->BufferInterfaceBlocks
[j
]);
1198 linker_error(prog
, "uniform block `%s' has mismatching definitions\n",
1199 sh
->BufferInterfaceBlocks
[j
]->Name
);
1203 prog
->InterfaceBlockStageIndex
[i
][index
] = j
;
1207 /* Update per stage block pointers to point to the program list.
1208 * FIXME: We should be able to free the per stage blocks here.
1210 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1211 for (unsigned j
= 0; j
< prog
->NumBufferInterfaceBlocks
; j
++) {
1213 prog
->InterfaceBlockStageIndex
[i
][j
];
1215 if (stage_index
!= -1) {
1216 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1218 sh
->BufferInterfaceBlocks
[stage_index
] =
1219 &prog
->BufferInterfaceBlocks
[j
];
1229 * Populates a shaders symbol table with all global declarations
1232 populate_symbol_table(gl_shader
*sh
)
1234 sh
->symbols
= new(sh
) glsl_symbol_table
;
1236 foreach_in_list(ir_instruction
, inst
, sh
->ir
) {
1240 if ((func
= inst
->as_function()) != NULL
) {
1241 sh
->symbols
->add_function(func
);
1242 } else if ((var
= inst
->as_variable()) != NULL
) {
1243 if (var
->data
.mode
!= ir_var_temporary
)
1244 sh
->symbols
->add_variable(var
);
1251 * Remap variables referenced in an instruction tree
1253 * This is used when instruction trees are cloned from one shader and placed in
1254 * another. These trees will contain references to \c ir_variable nodes that
1255 * do not exist in the target shader. This function finds these \c ir_variable
1256 * references and replaces the references with matching variables in the target
1259 * If there is no matching variable in the target shader, a clone of the
1260 * \c ir_variable is made and added to the target shader. The new variable is
1261 * added to \b both the instruction stream and the symbol table.
1263 * \param inst IR tree that is to be processed.
1264 * \param symbols Symbol table containing global scope symbols in the
1266 * \param instructions Instruction stream where new variable declarations
1270 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
1273 class remap_visitor
: public ir_hierarchical_visitor
{
1275 remap_visitor(struct gl_shader
*target
,
1278 this->target
= target
;
1279 this->symbols
= target
->symbols
;
1280 this->instructions
= target
->ir
;
1281 this->temps
= temps
;
1284 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1286 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1287 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
1289 assert(var
!= NULL
);
1291 return visit_continue
;
1294 ir_variable
*const existing
=
1295 this->symbols
->get_variable(ir
->var
->name
);
1296 if (existing
!= NULL
)
1299 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1301 this->symbols
->add_variable(copy
);
1302 this->instructions
->push_head(copy
);
1306 return visit_continue
;
1310 struct gl_shader
*target
;
1311 glsl_symbol_table
*symbols
;
1312 exec_list
*instructions
;
1316 remap_visitor
v(target
, temps
);
1323 * Move non-declarations from one instruction stream to another
1325 * The intended usage pattern of this function is to pass the pointer to the
1326 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1327 * pointer) for \c last and \c false for \c make_copies on the first
1328 * call. Successive calls pass the return value of the previous call for
1329 * \c last and \c true for \c make_copies.
1331 * \param instructions Source instruction stream
1332 * \param last Instruction after which new instructions should be
1333 * inserted in the target instruction stream
1334 * \param make_copies Flag selecting whether instructions in \c instructions
1335 * should be copied (via \c ir_instruction::clone) into the
1336 * target list or moved.
1339 * The new "last" instruction in the target instruction stream. This pointer
1340 * is suitable for use as the \c last parameter of a later call to this
1344 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1345 bool make_copies
, gl_shader
*target
)
1347 hash_table
*temps
= NULL
;
1350 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
1351 hash_table_pointer_compare
);
1353 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1354 if (inst
->as_function())
1357 ir_variable
*var
= inst
->as_variable();
1358 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1361 assert(inst
->as_assignment()
1363 || inst
->as_if() /* for initializers with the ?: operator */
1364 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1367 inst
= inst
->clone(target
, NULL
);
1370 hash_table_insert(temps
, inst
, var
);
1372 remap_variables(inst
, target
, temps
);
1377 last
->insert_after(inst
);
1382 hash_table_dtor(temps
);
1389 * This class is only used in link_intrastage_shaders() below but declaring
1390 * it inside that function leads to compiler warnings with some versions of
1393 class array_sizing_visitor
: public ir_hierarchical_visitor
{
1395 array_sizing_visitor()
1396 : mem_ctx(ralloc_context(NULL
)),
1397 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash
,
1398 hash_table_pointer_compare
))
1402 ~array_sizing_visitor()
1404 hash_table_dtor(this->unnamed_interfaces
);
1405 ralloc_free(this->mem_ctx
);
1408 virtual ir_visitor_status
visit(ir_variable
*var
)
1410 const glsl_type
*type_without_array
;
1411 fixup_type(&var
->type
, var
->data
.max_array_access
,
1412 var
->data
.from_ssbo_unsized_array
);
1413 type_without_array
= var
->type
->without_array();
1414 if (var
->type
->is_interface()) {
1415 if (interface_contains_unsized_arrays(var
->type
)) {
1416 const glsl_type
*new_type
=
1417 resize_interface_members(var
->type
,
1418 var
->get_max_ifc_array_access(),
1419 var
->is_in_shader_storage_block());
1420 var
->type
= new_type
;
1421 var
->change_interface_type(new_type
);
1423 } else if (type_without_array
->is_interface()) {
1424 if (interface_contains_unsized_arrays(type_without_array
)) {
1425 const glsl_type
*new_type
=
1426 resize_interface_members(type_without_array
,
1427 var
->get_max_ifc_array_access(),
1428 var
->is_in_shader_storage_block());
1429 var
->change_interface_type(new_type
);
1430 var
->type
= update_interface_members_array(var
->type
, new_type
);
1432 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1433 /* Store a pointer to the variable in the unnamed_interfaces
1436 ir_variable
**interface_vars
= (ir_variable
**)
1437 hash_table_find(this->unnamed_interfaces
, ifc_type
);
1438 if (interface_vars
== NULL
) {
1439 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1441 hash_table_insert(this->unnamed_interfaces
, interface_vars
,
1444 unsigned index
= ifc_type
->field_index(var
->name
);
1445 assert(index
< ifc_type
->length
);
1446 assert(interface_vars
[index
] == NULL
);
1447 interface_vars
[index
] = var
;
1449 return visit_continue
;
1453 * For each unnamed interface block that was discovered while running the
1454 * visitor, adjust the interface type to reflect the newly assigned array
1455 * sizes, and fix up the ir_variable nodes to point to the new interface
1458 void fixup_unnamed_interface_types()
1460 hash_table_call_foreach(this->unnamed_interfaces
,
1461 fixup_unnamed_interface_type
, NULL
);
1466 * If the type pointed to by \c type represents an unsized array, replace
1467 * it with a sized array whose size is determined by max_array_access.
1469 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1470 bool from_ssbo_unsized_array
)
1472 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1473 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1474 max_array_access
+ 1);
1475 assert(*type
!= NULL
);
1479 static const glsl_type
*
1480 update_interface_members_array(const glsl_type
*type
,
1481 const glsl_type
*new_interface_type
)
1483 const glsl_type
*element_type
= type
->fields
.array
;
1484 if (element_type
->is_array()) {
1485 const glsl_type
*new_array_type
=
1486 update_interface_members_array(element_type
, new_interface_type
);
1487 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1489 return glsl_type::get_array_instance(new_interface_type
,
1495 * Determine whether the given interface type contains unsized arrays (if
1496 * it doesn't, array_sizing_visitor doesn't need to process it).
1498 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1500 for (unsigned i
= 0; i
< type
->length
; i
++) {
1501 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1502 if (elem_type
->is_unsized_array())
1509 * Create a new interface type based on the given type, with unsized arrays
1510 * replaced by sized arrays whose size is determined by
1511 * max_ifc_array_access.
1513 static const glsl_type
*
1514 resize_interface_members(const glsl_type
*type
,
1515 const unsigned *max_ifc_array_access
,
1518 unsigned num_fields
= type
->length
;
1519 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1520 memcpy(fields
, type
->fields
.structure
,
1521 num_fields
* sizeof(*fields
));
1522 for (unsigned i
= 0; i
< num_fields
; i
++) {
1523 /* If SSBO last member is unsized array, we don't replace it by a sized
1526 if (is_ssbo
&& i
== (num_fields
- 1))
1527 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1530 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1533 glsl_interface_packing packing
=
1534 (glsl_interface_packing
) type
->interface_packing
;
1535 const glsl_type
*new_ifc_type
=
1536 glsl_type::get_interface_instance(fields
, num_fields
,
1537 packing
, type
->name
);
1539 return new_ifc_type
;
1542 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1545 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1546 ir_variable
**interface_vars
= (ir_variable
**) data
;
1547 unsigned num_fields
= ifc_type
->length
;
1548 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1549 memcpy(fields
, ifc_type
->fields
.structure
,
1550 num_fields
* sizeof(*fields
));
1551 bool interface_type_changed
= false;
1552 for (unsigned i
= 0; i
< num_fields
; i
++) {
1553 if (interface_vars
[i
] != NULL
&&
1554 fields
[i
].type
!= interface_vars
[i
]->type
) {
1555 fields
[i
].type
= interface_vars
[i
]->type
;
1556 interface_type_changed
= true;
1559 if (!interface_type_changed
) {
1563 glsl_interface_packing packing
=
1564 (glsl_interface_packing
) ifc_type
->interface_packing
;
1565 const glsl_type
*new_ifc_type
=
1566 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1569 for (unsigned i
= 0; i
< num_fields
; i
++) {
1570 if (interface_vars
[i
] != NULL
)
1571 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1576 * Memory context used to allocate the data in \c unnamed_interfaces.
1581 * Hash table from const glsl_type * to an array of ir_variable *'s
1582 * pointing to the ir_variables constituting each unnamed interface block.
1584 hash_table
*unnamed_interfaces
;
1588 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1592 link_xfb_stride_layout_qualifiers(struct gl_context
*ctx
,
1593 struct gl_shader_program
*prog
,
1594 struct gl_shader
*linked_shader
,
1595 struct gl_shader
**shader_list
,
1596 unsigned num_shaders
)
1598 for (unsigned i
= 0; i
< MAX_FEEDBACK_BUFFERS
; i
++) {
1599 linked_shader
->TransformFeedback
.BufferStride
[i
] = 0;
1602 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1603 struct gl_shader
*shader
= shader_list
[i
];
1605 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1606 if (shader
->TransformFeedback
.BufferStride
[j
]) {
1607 if (linked_shader
->TransformFeedback
.BufferStride
[j
] != 0 &&
1608 shader
->TransformFeedback
.BufferStride
[j
] != 0 &&
1609 linked_shader
->TransformFeedback
.BufferStride
[j
] !=
1610 shader
->TransformFeedback
.BufferStride
[j
]) {
1612 "intrastage shaders defined with conflicting "
1613 "xfb_stride for buffer %d (%d and %d)\n", j
,
1614 linked_shader
->TransformFeedback
.BufferStride
[j
],
1615 shader
->TransformFeedback
.BufferStride
[j
]);
1619 if (shader
->TransformFeedback
.BufferStride
[j
])
1620 linked_shader
->TransformFeedback
.BufferStride
[j
] =
1621 shader
->TransformFeedback
.BufferStride
[j
];
1626 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1627 if (linked_shader
->TransformFeedback
.BufferStride
[j
]) {
1628 prog
->TransformFeedback
.BufferStride
[j
] =
1629 linked_shader
->TransformFeedback
.BufferStride
[j
];
1631 /* We will validate doubles at a later stage */
1632 if (prog
->TransformFeedback
.BufferStride
[j
] % 4) {
1633 linker_error(prog
, "invalid qualifier xfb_stride=%d must be a "
1634 "multiple of 4 or if its applied to a type that is "
1635 "or contains a double a multiple of 8.",
1636 prog
->TransformFeedback
.BufferStride
[j
]);
1640 if (prog
->TransformFeedback
.BufferStride
[j
] / 4 >
1641 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1643 "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1644 "limit has been exceeded.");
1652 * Performs the cross-validation of tessellation control shader vertices and
1653 * layout qualifiers for the attached tessellation control shaders,
1654 * and propagates them to the linked TCS and linked shader program.
1657 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1658 struct gl_shader
*linked_shader
,
1659 struct gl_shader
**shader_list
,
1660 unsigned num_shaders
)
1662 linked_shader
->TessCtrl
.VerticesOut
= 0;
1664 if (linked_shader
->Stage
!= MESA_SHADER_TESS_CTRL
)
1667 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1669 * "All tessellation control shader layout declarations in a program
1670 * must specify the same output patch vertex count. There must be at
1671 * least one layout qualifier specifying an output patch vertex count
1672 * in any program containing tessellation control shaders; however,
1673 * such a declaration is not required in all tessellation control
1677 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1678 struct gl_shader
*shader
= shader_list
[i
];
1680 if (shader
->TessCtrl
.VerticesOut
!= 0) {
1681 if (linked_shader
->TessCtrl
.VerticesOut
!= 0 &&
1682 linked_shader
->TessCtrl
.VerticesOut
!= shader
->TessCtrl
.VerticesOut
) {
1683 linker_error(prog
, "tessellation control shader defined with "
1684 "conflicting output vertex count (%d and %d)\n",
1685 linked_shader
->TessCtrl
.VerticesOut
,
1686 shader
->TessCtrl
.VerticesOut
);
1689 linked_shader
->TessCtrl
.VerticesOut
= shader
->TessCtrl
.VerticesOut
;
1693 /* Just do the intrastage -> interstage propagation right now,
1694 * since we already know we're in the right type of shader program
1697 if (linked_shader
->TessCtrl
.VerticesOut
== 0) {
1698 linker_error(prog
, "tessellation control shader didn't declare "
1699 "vertices out layout qualifier\n");
1702 prog
->TessCtrl
.VerticesOut
= linked_shader
->TessCtrl
.VerticesOut
;
1707 * Performs the cross-validation of tessellation evaluation shader
1708 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1709 * for the attached tessellation evaluation shaders, and propagates them
1710 * to the linked TES and linked shader program.
1713 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1714 struct gl_shader
*linked_shader
,
1715 struct gl_shader
**shader_list
,
1716 unsigned num_shaders
)
1718 linked_shader
->TessEval
.PrimitiveMode
= PRIM_UNKNOWN
;
1719 linked_shader
->TessEval
.Spacing
= 0;
1720 linked_shader
->TessEval
.VertexOrder
= 0;
1721 linked_shader
->TessEval
.PointMode
= -1;
1723 if (linked_shader
->Stage
!= MESA_SHADER_TESS_EVAL
)
1726 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1728 * "At least one tessellation evaluation shader (compilation unit) in
1729 * a program must declare a primitive mode in its input layout.
1730 * Declaration vertex spacing, ordering, and point mode identifiers is
1731 * optional. It is not required that all tessellation evaluation
1732 * shaders in a program declare a primitive mode. If spacing or
1733 * vertex ordering declarations are omitted, the tessellation
1734 * primitive generator will use equal spacing or counter-clockwise
1735 * vertex ordering, respectively. If a point mode declaration is
1736 * omitted, the tessellation primitive generator will produce lines or
1737 * triangles according to the primitive mode."
1740 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1741 struct gl_shader
*shader
= shader_list
[i
];
1743 if (shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1744 if (linked_shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
&&
1745 linked_shader
->TessEval
.PrimitiveMode
!= shader
->TessEval
.PrimitiveMode
) {
1746 linker_error(prog
, "tessellation evaluation shader defined with "
1747 "conflicting input primitive modes.\n");
1750 linked_shader
->TessEval
.PrimitiveMode
= shader
->TessEval
.PrimitiveMode
;
1753 if (shader
->TessEval
.Spacing
!= 0) {
1754 if (linked_shader
->TessEval
.Spacing
!= 0 &&
1755 linked_shader
->TessEval
.Spacing
!= shader
->TessEval
.Spacing
) {
1756 linker_error(prog
, "tessellation evaluation shader defined with "
1757 "conflicting vertex spacing.\n");
1760 linked_shader
->TessEval
.Spacing
= shader
->TessEval
.Spacing
;
1763 if (shader
->TessEval
.VertexOrder
!= 0) {
1764 if (linked_shader
->TessEval
.VertexOrder
!= 0 &&
1765 linked_shader
->TessEval
.VertexOrder
!= shader
->TessEval
.VertexOrder
) {
1766 linker_error(prog
, "tessellation evaluation shader defined with "
1767 "conflicting ordering.\n");
1770 linked_shader
->TessEval
.VertexOrder
= shader
->TessEval
.VertexOrder
;
1773 if (shader
->TessEval
.PointMode
!= -1) {
1774 if (linked_shader
->TessEval
.PointMode
!= -1 &&
1775 linked_shader
->TessEval
.PointMode
!= shader
->TessEval
.PointMode
) {
1776 linker_error(prog
, "tessellation evaluation shader defined with "
1777 "conflicting point modes.\n");
1780 linked_shader
->TessEval
.PointMode
= shader
->TessEval
.PointMode
;
1785 /* Just do the intrastage -> interstage propagation right now,
1786 * since we already know we're in the right type of shader program
1789 if (linked_shader
->TessEval
.PrimitiveMode
== PRIM_UNKNOWN
) {
1791 "tessellation evaluation shader didn't declare input "
1792 "primitive modes.\n");
1795 prog
->TessEval
.PrimitiveMode
= linked_shader
->TessEval
.PrimitiveMode
;
1797 if (linked_shader
->TessEval
.Spacing
== 0)
1798 linked_shader
->TessEval
.Spacing
= GL_EQUAL
;
1799 prog
->TessEval
.Spacing
= linked_shader
->TessEval
.Spacing
;
1801 if (linked_shader
->TessEval
.VertexOrder
== 0)
1802 linked_shader
->TessEval
.VertexOrder
= GL_CCW
;
1803 prog
->TessEval
.VertexOrder
= linked_shader
->TessEval
.VertexOrder
;
1805 if (linked_shader
->TessEval
.PointMode
== -1)
1806 linked_shader
->TessEval
.PointMode
= GL_FALSE
;
1807 prog
->TessEval
.PointMode
= linked_shader
->TessEval
.PointMode
;
1812 * Performs the cross-validation of layout qualifiers specified in
1813 * redeclaration of gl_FragCoord for the attached fragment shaders,
1814 * and propagates them to the linked FS and linked shader program.
1817 link_fs_input_layout_qualifiers(struct gl_shader_program
*prog
,
1818 struct gl_shader
*linked_shader
,
1819 struct gl_shader
**shader_list
,
1820 unsigned num_shaders
)
1822 linked_shader
->redeclares_gl_fragcoord
= false;
1823 linked_shader
->uses_gl_fragcoord
= false;
1824 linked_shader
->origin_upper_left
= false;
1825 linked_shader
->pixel_center_integer
= false;
1827 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1828 (prog
->Version
< 150 && !prog
->ARB_fragment_coord_conventions_enable
))
1831 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1832 struct gl_shader
*shader
= shader_list
[i
];
1833 /* From the GLSL 1.50 spec, page 39:
1835 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1836 * it must be redeclared in all the fragment shaders in that program
1837 * that have a static use gl_FragCoord."
1839 if ((linked_shader
->redeclares_gl_fragcoord
1840 && !shader
->redeclares_gl_fragcoord
1841 && shader
->uses_gl_fragcoord
)
1842 || (shader
->redeclares_gl_fragcoord
1843 && !linked_shader
->redeclares_gl_fragcoord
1844 && linked_shader
->uses_gl_fragcoord
)) {
1845 linker_error(prog
, "fragment shader defined with conflicting "
1846 "layout qualifiers for gl_FragCoord\n");
1849 /* From the GLSL 1.50 spec, page 39:
1851 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1852 * single program must have the same set of qualifiers."
1854 if (linked_shader
->redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
1855 && (shader
->origin_upper_left
!= linked_shader
->origin_upper_left
1856 || shader
->pixel_center_integer
!= linked_shader
->pixel_center_integer
)) {
1857 linker_error(prog
, "fragment shader defined with conflicting "
1858 "layout qualifiers for gl_FragCoord\n");
1861 /* Update the linked shader state. Note that uses_gl_fragcoord should
1862 * accumulate the results. The other values should replace. If there
1863 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1864 * are already known to be the same.
1866 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
1867 linked_shader
->redeclares_gl_fragcoord
=
1868 shader
->redeclares_gl_fragcoord
;
1869 linked_shader
->uses_gl_fragcoord
= linked_shader
->uses_gl_fragcoord
1870 || shader
->uses_gl_fragcoord
;
1871 linked_shader
->origin_upper_left
= shader
->origin_upper_left
;
1872 linked_shader
->pixel_center_integer
= shader
->pixel_center_integer
;
1875 linked_shader
->EarlyFragmentTests
|= shader
->EarlyFragmentTests
;
1880 * Performs the cross-validation of geometry shader max_vertices and
1881 * primitive type layout qualifiers for the attached geometry shaders,
1882 * and propagates them to the linked GS and linked shader program.
1885 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1886 struct gl_shader
*linked_shader
,
1887 struct gl_shader
**shader_list
,
1888 unsigned num_shaders
)
1890 linked_shader
->Geom
.VerticesOut
= 0;
1891 linked_shader
->Geom
.Invocations
= 0;
1892 linked_shader
->Geom
.InputType
= PRIM_UNKNOWN
;
1893 linked_shader
->Geom
.OutputType
= PRIM_UNKNOWN
;
1895 /* No in/out qualifiers defined for anything but GLSL 1.50+
1896 * geometry shaders so far.
1898 if (linked_shader
->Stage
!= MESA_SHADER_GEOMETRY
|| prog
->Version
< 150)
1901 /* From the GLSL 1.50 spec, page 46:
1903 * "All geometry shader output layout declarations in a program
1904 * must declare the same layout and same value for
1905 * max_vertices. There must be at least one geometry output
1906 * layout declaration somewhere in a program, but not all
1907 * geometry shaders (compilation units) are required to
1911 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1912 struct gl_shader
*shader
= shader_list
[i
];
1914 if (shader
->Geom
.InputType
!= PRIM_UNKNOWN
) {
1915 if (linked_shader
->Geom
.InputType
!= PRIM_UNKNOWN
&&
1916 linked_shader
->Geom
.InputType
!= shader
->Geom
.InputType
) {
1917 linker_error(prog
, "geometry shader defined with conflicting "
1921 linked_shader
->Geom
.InputType
= shader
->Geom
.InputType
;
1924 if (shader
->Geom
.OutputType
!= PRIM_UNKNOWN
) {
1925 if (linked_shader
->Geom
.OutputType
!= PRIM_UNKNOWN
&&
1926 linked_shader
->Geom
.OutputType
!= shader
->Geom
.OutputType
) {
1927 linker_error(prog
, "geometry shader defined with conflicting "
1931 linked_shader
->Geom
.OutputType
= shader
->Geom
.OutputType
;
1934 if (shader
->Geom
.VerticesOut
!= 0) {
1935 if (linked_shader
->Geom
.VerticesOut
!= 0 &&
1936 linked_shader
->Geom
.VerticesOut
!= shader
->Geom
.VerticesOut
) {
1937 linker_error(prog
, "geometry shader defined with conflicting "
1938 "output vertex count (%d and %d)\n",
1939 linked_shader
->Geom
.VerticesOut
,
1940 shader
->Geom
.VerticesOut
);
1943 linked_shader
->Geom
.VerticesOut
= shader
->Geom
.VerticesOut
;
1946 if (shader
->Geom
.Invocations
!= 0) {
1947 if (linked_shader
->Geom
.Invocations
!= 0 &&
1948 linked_shader
->Geom
.Invocations
!= shader
->Geom
.Invocations
) {
1949 linker_error(prog
, "geometry shader defined with conflicting "
1950 "invocation count (%d and %d)\n",
1951 linked_shader
->Geom
.Invocations
,
1952 shader
->Geom
.Invocations
);
1955 linked_shader
->Geom
.Invocations
= shader
->Geom
.Invocations
;
1959 /* Just do the intrastage -> interstage propagation right now,
1960 * since we already know we're in the right type of shader program
1963 if (linked_shader
->Geom
.InputType
== PRIM_UNKNOWN
) {
1965 "geometry shader didn't declare primitive input type\n");
1968 prog
->Geom
.InputType
= linked_shader
->Geom
.InputType
;
1970 if (linked_shader
->Geom
.OutputType
== PRIM_UNKNOWN
) {
1972 "geometry shader didn't declare primitive output type\n");
1975 prog
->Geom
.OutputType
= linked_shader
->Geom
.OutputType
;
1977 if (linked_shader
->Geom
.VerticesOut
== 0) {
1979 "geometry shader didn't declare max_vertices\n");
1982 prog
->Geom
.VerticesOut
= linked_shader
->Geom
.VerticesOut
;
1984 if (linked_shader
->Geom
.Invocations
== 0)
1985 linked_shader
->Geom
.Invocations
= 1;
1987 prog
->Geom
.Invocations
= linked_shader
->Geom
.Invocations
;
1992 * Perform cross-validation of compute shader local_size_{x,y,z} layout
1993 * qualifiers for the attached compute shaders, and propagate them to the
1994 * linked CS and linked shader program.
1997 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
1998 struct gl_shader
*linked_shader
,
1999 struct gl_shader
**shader_list
,
2000 unsigned num_shaders
)
2002 for (int i
= 0; i
< 3; i
++)
2003 linked_shader
->Comp
.LocalSize
[i
] = 0;
2005 /* This function is called for all shader stages, but it only has an effect
2006 * for compute shaders.
2008 if (linked_shader
->Stage
!= MESA_SHADER_COMPUTE
)
2011 /* From the ARB_compute_shader spec, in the section describing local size
2014 * If multiple compute shaders attached to a single program object
2015 * declare local work-group size, the declarations must be identical;
2016 * otherwise a link-time error results. Furthermore, if a program
2017 * object contains any compute shaders, at least one must contain an
2018 * input layout qualifier specifying the local work sizes of the
2019 * program, or a link-time error will occur.
2021 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
2022 struct gl_shader
*shader
= shader_list
[sh
];
2024 if (shader
->Comp
.LocalSize
[0] != 0) {
2025 if (linked_shader
->Comp
.LocalSize
[0] != 0) {
2026 for (int i
= 0; i
< 3; i
++) {
2027 if (linked_shader
->Comp
.LocalSize
[i
] !=
2028 shader
->Comp
.LocalSize
[i
]) {
2029 linker_error(prog
, "compute shader defined with conflicting "
2035 for (int i
= 0; i
< 3; i
++)
2036 linked_shader
->Comp
.LocalSize
[i
] = shader
->Comp
.LocalSize
[i
];
2040 /* Just do the intrastage -> interstage propagation right now,
2041 * since we already know we're in the right type of shader program
2044 if (linked_shader
->Comp
.LocalSize
[0] == 0) {
2045 linker_error(prog
, "compute shader didn't declare local size\n");
2048 for (int i
= 0; i
< 3; i
++)
2049 prog
->Comp
.LocalSize
[i
] = linked_shader
->Comp
.LocalSize
[i
];
2054 * Combine a group of shaders for a single stage to generate a linked shader
2057 * If this function is supplied a single shader, it is cloned, and the new
2058 * shader is returned.
2060 static struct gl_shader
*
2061 link_intrastage_shaders(void *mem_ctx
,
2062 struct gl_context
*ctx
,
2063 struct gl_shader_program
*prog
,
2064 struct gl_shader
**shader_list
,
2065 unsigned num_shaders
)
2067 struct gl_uniform_block
*uniform_blocks
= NULL
;
2069 /* Check that global variables defined in multiple shaders are consistent.
2071 cross_validate_globals(prog
, shader_list
, num_shaders
, false);
2072 if (!prog
->LinkStatus
)
2075 /* Check that interface blocks defined in multiple shaders are consistent.
2077 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
2079 if (!prog
->LinkStatus
)
2082 /* Link up uniform blocks defined within this stage. */
2083 const unsigned num_uniform_blocks
=
2084 link_uniform_blocks(mem_ctx
, ctx
, prog
, shader_list
, num_shaders
,
2086 if (!prog
->LinkStatus
)
2089 /* Check that there is only a single definition of each function signature
2090 * across all shaders.
2092 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2093 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2094 ir_function
*const f
= node
->as_function();
2099 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2100 ir_function
*const other
=
2101 shader_list
[j
]->symbols
->get_function(f
->name
);
2103 /* If the other shader has no function (and therefore no function
2104 * signatures) with the same name, skip to the next shader.
2109 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2110 if (!sig
->is_defined
|| sig
->is_builtin())
2113 ir_function_signature
*other_sig
=
2114 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2116 if ((other_sig
!= NULL
) && other_sig
->is_defined
2117 && !other_sig
->is_builtin()) {
2118 linker_error(prog
, "function `%s' is multiply defined\n",
2127 /* Find the shader that defines main, and make a clone of it.
2129 * Starting with the clone, search for undefined references. If one is
2130 * found, find the shader that defines it. Clone the reference and add
2131 * it to the shader. Repeat until there are no undefined references or
2132 * until a reference cannot be resolved.
2134 gl_shader
*main
= NULL
;
2135 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2136 if (_mesa_get_main_function_signature(shader_list
[i
]) != NULL
) {
2137 main
= shader_list
[i
];
2143 linker_error(prog
, "%s shader lacks `main'\n",
2144 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2148 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
2149 linked
->ir
= new(linked
) exec_list
;
2150 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2152 linked
->BufferInterfaceBlocks
=
2153 ralloc_array(linked
, gl_uniform_block
*, num_uniform_blocks
);
2155 ralloc_steal(linked
, uniform_blocks
);
2156 for (unsigned i
= 0; i
< num_uniform_blocks
; i
++) {
2157 linked
->BufferInterfaceBlocks
[i
] = &uniform_blocks
[i
];
2160 linked
->NumBufferInterfaceBlocks
= num_uniform_blocks
;
2162 link_fs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2163 link_tcs_out_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2164 link_tes_in_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2165 link_gs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2166 link_cs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2167 link_xfb_stride_layout_qualifiers(ctx
, prog
, linked
, shader_list
,
2170 populate_symbol_table(linked
);
2172 /* The pointer to the main function in the final linked shader (i.e., the
2173 * copy of the original shader that contained the main function).
2175 ir_function_signature
*const main_sig
=
2176 _mesa_get_main_function_signature(linked
);
2178 /* Move any instructions other than variable declarations or function
2179 * declarations into main.
2181 exec_node
*insertion_point
=
2182 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2185 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2186 if (shader_list
[i
] == main
)
2189 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2190 insertion_point
, true, linked
);
2193 /* Check if any shader needs built-in functions. */
2194 bool need_builtins
= false;
2195 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2196 if (shader_list
[i
]->uses_builtin_functions
) {
2197 need_builtins
= true;
2203 if (need_builtins
) {
2204 /* Make a temporary array one larger than shader_list, which will hold
2205 * the built-in function shader as well.
2207 gl_shader
**linking_shaders
= (gl_shader
**)
2208 calloc(num_shaders
+ 1, sizeof(gl_shader
*));
2210 ok
= linking_shaders
!= NULL
;
2213 memcpy(linking_shaders
, shader_list
, num_shaders
* sizeof(gl_shader
*));
2214 _mesa_glsl_initialize_builtin_functions();
2215 linking_shaders
[num_shaders
] = _mesa_glsl_get_builtin_function_shader();
2217 ok
= link_function_calls(prog
, linked
, linking_shaders
, num_shaders
+ 1);
2219 free(linking_shaders
);
2221 _mesa_error_no_memory(__func__
);
2224 ok
= link_function_calls(prog
, linked
, shader_list
, num_shaders
);
2229 _mesa_delete_shader(ctx
, linked
);
2233 /* At this point linked should contain all of the linked IR, so
2234 * validate it to make sure nothing went wrong.
2236 validate_ir_tree(linked
->ir
);
2238 /* Set the size of geometry shader input arrays */
2239 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2240 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
2241 geom_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2242 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2243 ir
->accept(&input_resize_visitor
);
2247 if (ctx
->Const
.VertexID_is_zero_based
)
2248 lower_vertex_id(linked
);
2250 /* Validate correct usage of barrier() in the tess control shader */
2251 if (linked
->Stage
== MESA_SHADER_TESS_CTRL
) {
2252 barrier_use_visitor
visitor(prog
);
2253 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2254 ir
->accept(&visitor
);
2258 /* Make a pass over all variable declarations to ensure that arrays with
2259 * unspecified sizes have a size specified. The size is inferred from the
2260 * max_array_access field.
2262 array_sizing_visitor v
;
2264 v
.fixup_unnamed_interface_types();
2270 * Update the sizes of linked shader uniform arrays to the maximum
2273 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2275 * If one or more elements of an array are active,
2276 * GetActiveUniform will return the name of the array in name,
2277 * subject to the restrictions listed above. The type of the array
2278 * is returned in type. The size parameter contains the highest
2279 * array element index used, plus one. The compiler or linker
2280 * determines the highest index used. There will be only one
2281 * active uniform reported by the GL per uniform array.
2285 update_array_sizes(struct gl_shader_program
*prog
)
2287 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2288 if (prog
->_LinkedShaders
[i
] == NULL
)
2291 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2292 ir_variable
*const var
= node
->as_variable();
2294 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2295 !var
->type
->is_array())
2298 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2299 * will not be eliminated. Since we always do std140, just
2300 * don't resize arrays in UBOs.
2302 * Atomic counters are supposed to get deterministic
2303 * locations assigned based on the declaration ordering and
2304 * sizes, array compaction would mess that up.
2306 * Subroutine uniforms are not removed.
2308 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2309 var
->type
->contains_subroutine())
2312 unsigned int size
= var
->data
.max_array_access
;
2313 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2314 if (prog
->_LinkedShaders
[j
] == NULL
)
2317 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2318 ir_variable
*other_var
= node2
->as_variable();
2322 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2323 other_var
->data
.max_array_access
> size
) {
2324 size
= other_var
->data
.max_array_access
;
2329 if (size
+ 1 != var
->type
->length
) {
2330 /* If this is a built-in uniform (i.e., it's backed by some
2331 * fixed-function state), adjust the number of state slots to
2332 * match the new array size. The number of slots per array entry
2333 * is not known. It seems safe to assume that the total number of
2334 * slots is an integer multiple of the number of array elements.
2335 * Determine the number of slots per array element by dividing by
2336 * the old (total) size.
2338 const unsigned num_slots
= var
->get_num_state_slots();
2339 if (num_slots
> 0) {
2340 var
->set_num_state_slots((size
+ 1)
2341 * (num_slots
/ var
->type
->length
));
2344 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2346 /* FINISHME: We should update the types of array
2347 * dereferences of this variable now.
2355 * Resize tessellation evaluation per-vertex inputs to the size of
2356 * tessellation control per-vertex outputs.
2359 resize_tes_inputs(struct gl_context
*ctx
,
2360 struct gl_shader_program
*prog
)
2362 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2365 gl_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2366 gl_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2368 /* If no control shader is present, then the TES inputs are statically
2369 * sized to MaxPatchVertices; the actual size of the arrays won't be
2370 * known until draw time.
2372 const int num_vertices
= tcs
2373 ? tcs
->TessCtrl
.VerticesOut
2374 : ctx
->Const
.MaxPatchVertices
;
2376 tess_eval_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2377 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2378 ir
->accept(&input_resize_visitor
);
2382 /* Convert the gl_PatchVerticesIn system value into a constant, since
2383 * the value is known at this point.
2385 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2386 ir_variable
*var
= ir
->as_variable();
2387 if (var
&& var
->data
.mode
== ir_var_system_value
&&
2388 var
->data
.location
== SYSTEM_VALUE_VERTICES_IN
) {
2389 void *mem_ctx
= ralloc_parent(var
);
2390 var
->data
.mode
= ir_var_auto
;
2391 var
->data
.location
= 0;
2392 var
->constant_value
= new(mem_ctx
) ir_constant(num_vertices
);
2399 * Find a contiguous set of available bits in a bitmask.
2401 * \param used_mask Bits representing used (1) and unused (0) locations
2402 * \param needed_count Number of contiguous bits needed.
2405 * Base location of the available bits on success or -1 on failure.
2408 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2410 unsigned needed_mask
= (1 << needed_count
) - 1;
2411 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2413 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2414 * cannot optimize possibly infinite loops" for the loop below.
2416 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2419 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2420 if ((needed_mask
& ~used_mask
) == needed_mask
)
2431 * Assign locations for either VS inputs or FS outputs
2433 * \param prog Shader program whose variables need locations assigned
2434 * \param constants Driver specific constant values for the program.
2435 * \param target_index Selector for the program target to receive location
2436 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2437 * \c MESA_SHADER_FRAGMENT.
2440 * If locations are successfully assigned, true is returned. Otherwise an
2441 * error is emitted to the shader link log and false is returned.
2444 assign_attribute_or_color_locations(gl_shader_program
*prog
,
2445 struct gl_constants
*constants
,
2446 unsigned target_index
)
2448 /* Maximum number of generic locations. This corresponds to either the
2449 * maximum number of draw buffers or the maximum number of generic
2452 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2453 constants
->Program
[target_index
].MaxAttribs
:
2454 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2456 /* Mark invalid locations as being used.
2458 unsigned used_locations
= (max_index
>= 32)
2459 ? ~0 : ~((1 << max_index
) - 1);
2460 unsigned double_storage_locations
= 0;
2462 assert((target_index
== MESA_SHADER_VERTEX
)
2463 || (target_index
== MESA_SHADER_FRAGMENT
));
2465 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2469 /* Operate in a total of four passes.
2471 * 1. Invalidate the location assignments for all vertex shader inputs.
2473 * 2. Assign locations for inputs that have user-defined (via
2474 * glBindVertexAttribLocation) locations and outputs that have
2475 * user-defined locations (via glBindFragDataLocation).
2477 * 3. Sort the attributes without assigned locations by number of slots
2478 * required in decreasing order. Fragmentation caused by attribute
2479 * locations assigned by the application may prevent large attributes
2480 * from having enough contiguous space.
2482 * 4. Assign locations to any inputs without assigned locations.
2485 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2486 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2488 const enum ir_variable_mode direction
=
2489 (target_index
== MESA_SHADER_VERTEX
)
2490 ? ir_var_shader_in
: ir_var_shader_out
;
2493 /* Temporary storage for the set of attributes that need locations assigned.
2499 /* Used below in the call to qsort. */
2500 static int compare(const void *a
, const void *b
)
2502 const temp_attr
*const l
= (const temp_attr
*) a
;
2503 const temp_attr
*const r
= (const temp_attr
*) b
;
2505 /* Reversed because we want a descending order sort below. */
2506 return r
->slots
- l
->slots
;
2509 assert(max_index
<= 32);
2511 unsigned num_attr
= 0;
2513 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2514 ir_variable
*const var
= node
->as_variable();
2516 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2519 if (var
->data
.explicit_location
) {
2520 var
->data
.is_unmatched_generic_inout
= 0;
2521 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2522 || (var
->data
.location
< 0)) {
2524 "invalid explicit location %d specified for `%s'\n",
2525 (var
->data
.location
< 0)
2526 ? var
->data
.location
2527 : var
->data
.location
- generic_base
,
2531 } else if (target_index
== MESA_SHADER_VERTEX
) {
2534 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2535 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2536 var
->data
.location
= binding
;
2537 var
->data
.is_unmatched_generic_inout
= 0;
2539 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2543 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
2544 assert(binding
>= FRAG_RESULT_DATA0
);
2545 var
->data
.location
= binding
;
2546 var
->data
.is_unmatched_generic_inout
= 0;
2548 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
2549 var
->data
.index
= index
;
2554 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2556 * "Output binding assignments will cause LinkProgram to fail:
2558 * If the program has an active output assigned to a location greater
2559 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2560 * an active output assigned an index greater than or equal to one;"
2562 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2563 var
->data
.location
- generic_base
>=
2564 (int) constants
->MaxDualSourceDrawBuffers
) {
2566 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2567 "with index %u for %s\n",
2568 var
->data
.location
- generic_base
, var
->data
.index
,
2573 const unsigned slots
= var
->type
->count_attribute_slots(target_index
== MESA_SHADER_VERTEX
? true : false);
2575 /* If the variable is not a built-in and has a location statically
2576 * assigned in the shader (presumably via a layout qualifier), make sure
2577 * that it doesn't collide with other assigned locations. Otherwise,
2578 * add it to the list of variables that need linker-assigned locations.
2580 if (var
->data
.location
!= -1) {
2581 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2582 /* From page 61 of the OpenGL 4.0 spec:
2584 * "LinkProgram will fail if the attribute bindings assigned
2585 * by BindAttribLocation do not leave not enough space to
2586 * assign a location for an active matrix attribute or an
2587 * active attribute array, both of which require multiple
2588 * contiguous generic attributes."
2590 * I think above text prohibits the aliasing of explicit and
2591 * automatic assignments. But, aliasing is allowed in manual
2592 * assignments of attribute locations. See below comments for
2595 * From OpenGL 4.0 spec, page 61:
2597 * "It is possible for an application to bind more than one
2598 * attribute name to the same location. This is referred to as
2599 * aliasing. This will only work if only one of the aliased
2600 * attributes is active in the executable program, or if no
2601 * path through the shader consumes more than one attribute of
2602 * a set of attributes aliased to the same location. A link
2603 * error can occur if the linker determines that every path
2604 * through the shader consumes multiple aliased attributes,
2605 * but implementations are not required to generate an error
2608 * From GLSL 4.30 spec, page 54:
2610 * "A program will fail to link if any two non-vertex shader
2611 * input variables are assigned to the same location. For
2612 * vertex shaders, multiple input variables may be assigned
2613 * to the same location using either layout qualifiers or via
2614 * the OpenGL API. However, such aliasing is intended only to
2615 * support vertex shaders where each execution path accesses
2616 * at most one input per each location. Implementations are
2617 * permitted, but not required, to generate link-time errors
2618 * if they detect that every path through the vertex shader
2619 * executable accesses multiple inputs assigned to any single
2620 * location. For all shader types, a program will fail to link
2621 * if explicit location assignments leave the linker unable
2622 * to find space for other variables without explicit
2625 * From OpenGL ES 3.0 spec, page 56:
2627 * "Binding more than one attribute name to the same location
2628 * is referred to as aliasing, and is not permitted in OpenGL
2629 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2630 * fail when this condition exists. However, aliasing is
2631 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2632 * This will only work if only one of the aliased attributes
2633 * is active in the executable program, or if no path through
2634 * the shader consumes more than one attribute of a set of
2635 * attributes aliased to the same location. A link error can
2636 * occur if the linker determines that every path through the
2637 * shader consumes multiple aliased attributes, but implemen-
2638 * tations are not required to generate an error in this case."
2640 * After looking at above references from OpenGL, OpenGL ES and
2641 * GLSL specifications, we allow aliasing of vertex input variables
2642 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2644 * NOTE: This is not required by the spec but its worth mentioning
2645 * here that we're not doing anything to make sure that no path
2646 * through the vertex shader executable accesses multiple inputs
2647 * assigned to any single location.
2650 /* Mask representing the contiguous slots that will be used by
2653 const unsigned attr
= var
->data
.location
- generic_base
;
2654 const unsigned use_mask
= (1 << slots
) - 1;
2655 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2656 ? "vertex shader input" : "fragment shader output";
2658 /* Generate a link error if the requested locations for this
2659 * attribute exceed the maximum allowed attribute location.
2661 if (attr
+ slots
> max_index
) {
2663 "insufficient contiguous locations "
2664 "available for %s `%s' %d %d %d\n", string
,
2665 var
->name
, used_locations
, use_mask
, attr
);
2669 /* Generate a link error if the set of bits requested for this
2670 * attribute overlaps any previously allocated bits.
2672 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
2673 if (target_index
== MESA_SHADER_FRAGMENT
||
2674 (prog
->IsES
&& prog
->Version
>= 300)) {
2676 "overlapping location is assigned "
2677 "to %s `%s' %d %d %d\n", string
,
2678 var
->name
, used_locations
, use_mask
, attr
);
2681 linker_warning(prog
,
2682 "overlapping location is assigned "
2683 "to %s `%s' %d %d %d\n", string
,
2684 var
->name
, used_locations
, use_mask
, attr
);
2688 used_locations
|= (use_mask
<< attr
);
2690 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2692 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2693 * active attribute variables may fail to link, unless
2694 * device-dependent optimizations are able to make the program
2695 * fit within available hardware resources. For the purposes
2696 * of this test, attribute variables of the type dvec3, dvec4,
2697 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2698 * count as consuming twice as many attributes as equivalent
2699 * single-precision types. While these types use the same number
2700 * of generic attributes as their single-precision equivalents,
2701 * implementations are permitted to consume two single-precision
2702 * vectors of internal storage for each three- or four-component
2703 * double-precision vector."
2705 * Mark this attribute slot as taking up twice as much space
2706 * so we can count it properly against limits. According to
2707 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2708 * is optional behavior, but it seems preferable.
2710 if (var
->type
->without_array()->is_dual_slot_double())
2711 double_storage_locations
|= (use_mask
<< attr
);
2717 if (num_attr
>= max_index
) {
2718 linker_error(prog
, "too many %s (max %u)",
2719 target_index
== MESA_SHADER_VERTEX
?
2720 "vertex shader inputs" : "fragment shader outputs",
2724 to_assign
[num_attr
].slots
= slots
;
2725 to_assign
[num_attr
].var
= var
;
2729 if (target_index
== MESA_SHADER_VERTEX
) {
2730 unsigned total_attribs_size
=
2731 _mesa_bitcount(used_locations
& ((1 << max_index
) - 1)) +
2732 _mesa_bitcount(double_storage_locations
);
2733 if (total_attribs_size
> max_index
) {
2735 "attempt to use %d vertex attribute slots only %d available ",
2736 total_attribs_size
, max_index
);
2741 /* If all of the attributes were assigned locations by the application (or
2742 * are built-in attributes with fixed locations), return early. This should
2743 * be the common case.
2748 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
2750 if (target_index
== MESA_SHADER_VERTEX
) {
2751 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2752 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2753 * reserved to prevent it from being automatically allocated below.
2755 find_deref_visitor
find("gl_Vertex");
2757 if (find
.variable_found())
2758 used_locations
|= (1 << 0);
2761 for (unsigned i
= 0; i
< num_attr
; i
++) {
2762 /* Mask representing the contiguous slots that will be used by this
2765 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
2767 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
2770 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2771 ? "vertex shader input" : "fragment shader output";
2774 "insufficient contiguous locations "
2775 "available for %s `%s'\n",
2776 string
, to_assign
[i
].var
->name
);
2780 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
2781 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
2782 used_locations
|= (use_mask
<< location
);
2789 * Match explicit locations of outputs to inputs and deactivate the
2790 * unmatch flag if found so we don't optimise them away.
2793 match_explicit_outputs_to_inputs(struct gl_shader_program
*prog
,
2794 gl_shader
*producer
,
2795 gl_shader
*consumer
)
2797 glsl_symbol_table parameters
;
2798 ir_variable
*explicit_locations
[MAX_VARYING
] = { NULL
};
2800 /* Find all shader outputs in the "producer" stage.
2802 foreach_in_list(ir_instruction
, node
, producer
->ir
) {
2803 ir_variable
*const var
= node
->as_variable();
2805 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_shader_out
))
2808 if (var
->data
.explicit_location
&&
2809 var
->data
.location
>= VARYING_SLOT_VAR0
) {
2810 const unsigned idx
= var
->data
.location
- VARYING_SLOT_VAR0
;
2811 if (explicit_locations
[idx
] == NULL
)
2812 explicit_locations
[idx
] = var
;
2816 /* Match inputs to outputs */
2817 foreach_in_list(ir_instruction
, node
, consumer
->ir
) {
2818 ir_variable
*const input
= node
->as_variable();
2820 if ((input
== NULL
) || (input
->data
.mode
!= ir_var_shader_in
))
2823 ir_variable
*output
= NULL
;
2824 if (input
->data
.explicit_location
2825 && input
->data
.location
>= VARYING_SLOT_VAR0
) {
2826 output
= explicit_locations
[input
->data
.location
- VARYING_SLOT_VAR0
];
2828 if (output
!= NULL
){
2829 input
->data
.is_unmatched_generic_inout
= 0;
2830 output
->data
.is_unmatched_generic_inout
= 0;
2837 * Store the gl_FragDepth layout in the gl_shader_program struct.
2840 store_fragdepth_layout(struct gl_shader_program
*prog
)
2842 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
2846 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
2848 /* We don't look up the gl_FragDepth symbol directly because if
2849 * gl_FragDepth is not used in the shader, it's removed from the IR.
2850 * However, the symbol won't be removed from the symbol table.
2852 * We're only interested in the cases where the variable is NOT removed
2855 foreach_in_list(ir_instruction
, node
, ir
) {
2856 ir_variable
*const var
= node
->as_variable();
2858 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
2862 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
2863 switch (var
->data
.depth_layout
) {
2864 case ir_depth_layout_none
:
2865 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
2867 case ir_depth_layout_any
:
2868 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
2870 case ir_depth_layout_greater
:
2871 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
2873 case ir_depth_layout_less
:
2874 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
2876 case ir_depth_layout_unchanged
:
2877 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
2888 * Validate the resources used by a program versus the implementation limits
2891 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2893 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2894 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2899 if (sh
->num_samplers
> ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
2900 linker_error(prog
, "Too many %s shader texture samplers\n",
2901 _mesa_shader_stage_to_string(i
));
2904 if (sh
->num_uniform_components
>
2905 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
2906 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2907 linker_warning(prog
, "Too many %s shader default uniform block "
2908 "components, but the driver will try to optimize "
2909 "them out; this is non-portable out-of-spec "
2911 _mesa_shader_stage_to_string(i
));
2913 linker_error(prog
, "Too many %s shader default uniform block "
2915 _mesa_shader_stage_to_string(i
));
2919 if (sh
->num_combined_uniform_components
>
2920 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
2921 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2922 linker_warning(prog
, "Too many %s shader uniform components, "
2923 "but the driver will try to optimize them out; "
2924 "this is non-portable out-of-spec behavior\n",
2925 _mesa_shader_stage_to_string(i
));
2927 linker_error(prog
, "Too many %s shader uniform components\n",
2928 _mesa_shader_stage_to_string(i
));
2933 unsigned blocks
[MESA_SHADER_STAGES
] = {0};
2934 unsigned total_uniform_blocks
= 0;
2935 unsigned shader_blocks
[MESA_SHADER_STAGES
] = {0};
2936 unsigned total_shader_storage_blocks
= 0;
2938 for (unsigned i
= 0; i
< prog
->NumBufferInterfaceBlocks
; i
++) {
2939 /* Don't check SSBOs for Uniform Block Size */
2940 if (!prog
->BufferInterfaceBlocks
[i
].IsShaderStorage
&&
2941 prog
->BufferInterfaceBlocks
[i
].UniformBufferSize
> ctx
->Const
.MaxUniformBlockSize
) {
2942 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
2943 prog
->BufferInterfaceBlocks
[i
].Name
,
2944 prog
->BufferInterfaceBlocks
[i
].UniformBufferSize
,
2945 ctx
->Const
.MaxUniformBlockSize
);
2948 if (prog
->BufferInterfaceBlocks
[i
].IsShaderStorage
&&
2949 prog
->BufferInterfaceBlocks
[i
].UniformBufferSize
> ctx
->Const
.MaxShaderStorageBlockSize
) {
2950 linker_error(prog
, "Shader storage block %s too big (%d/%d)\n",
2951 prog
->BufferInterfaceBlocks
[i
].Name
,
2952 prog
->BufferInterfaceBlocks
[i
].UniformBufferSize
,
2953 ctx
->Const
.MaxShaderStorageBlockSize
);
2956 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2957 if (prog
->InterfaceBlockStageIndex
[j
][i
] != -1) {
2958 struct gl_shader
*sh
= prog
->_LinkedShaders
[j
];
2959 int stage_index
= prog
->InterfaceBlockStageIndex
[j
][i
];
2961 sh
->BufferInterfaceBlocks
[stage_index
]->IsShaderStorage
) {
2963 total_shader_storage_blocks
++;
2966 total_uniform_blocks
++;
2971 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
2972 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
2973 total_uniform_blocks
,
2974 ctx
->Const
.MaxCombinedUniformBlocks
);
2976 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2977 const unsigned max_uniform_blocks
=
2978 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
2979 if (blocks
[i
] > max_uniform_blocks
) {
2980 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
2981 _mesa_shader_stage_to_string(i
),
2983 max_uniform_blocks
);
2989 if (total_shader_storage_blocks
> ctx
->Const
.MaxCombinedShaderStorageBlocks
) {
2990 linker_error(prog
, "Too many combined shader storage blocks (%d/%d)\n",
2991 total_shader_storage_blocks
,
2992 ctx
->Const
.MaxCombinedShaderStorageBlocks
);
2994 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2995 const unsigned max_shader_storage_blocks
=
2996 ctx
->Const
.Program
[i
].MaxShaderStorageBlocks
;
2997 if (shader_blocks
[i
] > max_shader_storage_blocks
) {
2998 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
2999 _mesa_shader_stage_to_string(i
),
3001 max_shader_storage_blocks
);
3010 link_calculate_subroutine_compat(struct gl_shader_program
*prog
)
3012 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3013 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3018 for (unsigned j
= 0; j
< sh
->NumSubroutineUniformRemapTable
; j
++) {
3019 struct gl_uniform_storage
*uni
= sh
->SubroutineUniformRemapTable
[j
];
3025 for (unsigned f
= 0; f
< sh
->NumSubroutineFunctions
; f
++) {
3026 struct gl_subroutine_function
*fn
= &sh
->SubroutineFunctions
[f
];
3027 for (int k
= 0; k
< fn
->num_compat_types
; k
++) {
3028 if (fn
->types
[k
] == uni
->type
) {
3034 uni
->num_compatible_subroutines
= count
;
3040 check_subroutine_resources(struct gl_shader_program
*prog
)
3042 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3043 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3046 if (sh
->NumSubroutineUniformRemapTable
> MAX_SUBROUTINE_UNIFORM_LOCATIONS
)
3047 linker_error(prog
, "Too many %s shader subroutine uniforms\n",
3048 _mesa_shader_stage_to_string(i
));
3053 * Validate shader image resources.
3056 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3058 unsigned total_image_units
= 0;
3059 unsigned fragment_outputs
= 0;
3060 unsigned total_shader_storage_blocks
= 0;
3062 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
3065 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3066 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3069 if (sh
->NumImages
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
3070 linker_error(prog
, "Too many %s shader image uniforms (%u > %u)\n",
3071 _mesa_shader_stage_to_string(i
), sh
->NumImages
,
3072 ctx
->Const
.Program
[i
].MaxImageUniforms
);
3074 total_image_units
+= sh
->NumImages
;
3076 for (unsigned j
= 0; j
< prog
->NumBufferInterfaceBlocks
; j
++) {
3077 int stage_index
= prog
->InterfaceBlockStageIndex
[i
][j
];
3078 if (stage_index
!= -1 &&
3079 sh
->BufferInterfaceBlocks
[stage_index
]->IsShaderStorage
)
3080 total_shader_storage_blocks
++;
3083 if (i
== MESA_SHADER_FRAGMENT
) {
3084 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3085 ir_variable
*var
= node
->as_variable();
3086 if (var
&& var
->data
.mode
== ir_var_shader_out
)
3087 /* since there are no double fs outputs - pass false */
3088 fragment_outputs
+= var
->type
->count_attribute_slots(false);
3094 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
3095 linker_error(prog
, "Too many combined image uniforms\n");
3097 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
3098 ctx
->Const
.MaxCombinedShaderOutputResources
)
3099 linker_error(prog
, "Too many combined image uniforms, shader storage "
3100 " buffers and fragment outputs\n");
3105 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3106 * for a variable, checks for overlaps between other uniforms using explicit
3110 reserve_explicit_locations(struct gl_shader_program
*prog
,
3111 string_to_uint_map
*map
, ir_variable
*var
)
3113 unsigned slots
= var
->type
->uniform_locations();
3114 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3115 unsigned return_value
= slots
;
3117 /* Resize remap table if locations do not fit in the current one. */
3118 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
3119 prog
->UniformRemapTable
=
3120 reralloc(prog
, prog
->UniformRemapTable
,
3121 gl_uniform_storage
*,
3124 if (!prog
->UniformRemapTable
) {
3125 linker_error(prog
, "Out of memory during linking.\n");
3129 /* Initialize allocated space. */
3130 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
3131 prog
->UniformRemapTable
[i
] = NULL
;
3133 prog
->NumUniformRemapTable
= max_loc
+ 1;
3136 for (unsigned i
= 0; i
< slots
; i
++) {
3137 unsigned loc
= var
->data
.location
+ i
;
3139 /* Check if location is already used. */
3140 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3142 /* Possibly same uniform from a different stage, this is ok. */
3144 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
) {
3149 /* ARB_explicit_uniform_location specification states:
3151 * "No two default-block uniform variables in the program can have
3152 * the same location, even if they are unused, otherwise a compiler
3153 * or linker error will be generated."
3156 "location qualifier for uniform %s overlaps "
3157 "previously used location\n",
3162 /* Initialize location as inactive before optimization
3163 * rounds and location assignment.
3165 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3168 /* Note, base location used for arrays. */
3169 map
->put(var
->data
.location
, var
->name
);
3171 return return_value
;
3175 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3176 struct gl_shader
*sh
,
3179 unsigned slots
= var
->type
->uniform_locations();
3180 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3182 /* Resize remap table if locations do not fit in the current one. */
3183 if (max_loc
+ 1 > sh
->NumSubroutineUniformRemapTable
) {
3184 sh
->SubroutineUniformRemapTable
=
3185 reralloc(sh
, sh
->SubroutineUniformRemapTable
,
3186 gl_uniform_storage
*,
3189 if (!sh
->SubroutineUniformRemapTable
) {
3190 linker_error(prog
, "Out of memory during linking.\n");
3194 /* Initialize allocated space. */
3195 for (unsigned i
= sh
->NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3196 sh
->SubroutineUniformRemapTable
[i
] = NULL
;
3198 sh
->NumSubroutineUniformRemapTable
= max_loc
+ 1;
3201 for (unsigned i
= 0; i
< slots
; i
++) {
3202 unsigned loc
= var
->data
.location
+ i
;
3204 /* Check if location is already used. */
3205 if (sh
->SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3207 /* ARB_explicit_uniform_location specification states:
3208 * "No two subroutine uniform variables can have the same location
3209 * in the same shader stage, otherwise a compiler or linker error
3210 * will be generated."
3213 "location qualifier for uniform %s overlaps "
3214 "previously used location\n",
3219 /* Initialize location as inactive before optimization
3220 * rounds and location assignment.
3222 sh
->SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3228 * Check and reserve all explicit uniform locations, called before
3229 * any optimizations happen to handle also inactive uniforms and
3230 * inactive array elements that may get trimmed away.
3233 check_explicit_uniform_locations(struct gl_context
*ctx
,
3234 struct gl_shader_program
*prog
)
3236 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3239 /* This map is used to detect if overlapping explicit locations
3240 * occur with the same uniform (from different stage) or a different one.
3242 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3245 linker_error(prog
, "Out of memory during linking.\n");
3249 unsigned entries_total
= 0;
3250 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3251 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3256 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3257 ir_variable
*var
= node
->as_variable();
3258 if (!var
|| var
->data
.mode
!= ir_var_uniform
)
3261 if (var
->data
.explicit_location
) {
3263 if (var
->type
->without_array()->is_subroutine())
3264 ret
= reserve_subroutine_explicit_locations(prog
, sh
, var
);
3266 int slots
= reserve_explicit_locations(prog
, uniform_map
,
3270 entries_total
+= slots
;
3281 struct empty_uniform_block
*current_block
= NULL
;
3283 for (unsigned i
= 0; i
< prog
->NumUniformRemapTable
; i
++) {
3284 /* We found empty space in UniformRemapTable. */
3285 if (prog
->UniformRemapTable
[i
] == NULL
) {
3286 /* We've found the beginning of a new continous block of empty slots */
3287 if (!current_block
|| current_block
->start
+ current_block
->slots
!= i
) {
3288 current_block
= rzalloc(prog
, struct empty_uniform_block
);
3289 current_block
->start
= i
;
3290 exec_list_push_tail(&prog
->EmptyUniformLocations
,
3291 ¤t_block
->link
);
3294 /* The current block continues, so we simply increment its slots */
3295 current_block
->slots
++;
3300 return entries_total
;
3304 should_add_buffer_variable(struct gl_shader_program
*shProg
,
3305 GLenum type
, const char *name
)
3307 bool found_interface
= false;
3308 unsigned block_name_len
= 0;
3309 const char *block_name_dot
= strchr(name
, '.');
3311 /* These rules only apply to buffer variables. So we return
3312 * true for the rest of types.
3314 if (type
!= GL_BUFFER_VARIABLE
)
3317 for (unsigned i
= 0; i
< shProg
->NumBufferInterfaceBlocks
; i
++) {
3318 const char *block_name
= shProg
->BufferInterfaceBlocks
[i
].Name
;
3319 block_name_len
= strlen(block_name
);
3321 const char *block_square_bracket
= strchr(block_name
, '[');
3322 if (block_square_bracket
) {
3323 /* The block is part of an array of named interfaces,
3324 * for the name comparison we ignore the "[x]" part.
3326 block_name_len
-= strlen(block_square_bracket
);
3329 if (block_name_dot
) {
3330 /* Check if the variable name starts with the interface
3331 * name. The interface name (if present) should have the
3332 * length than the interface block name we are comparing to.
3334 unsigned len
= strlen(name
) - strlen(block_name_dot
);
3335 if (len
!= block_name_len
)
3339 if (strncmp(block_name
, name
, block_name_len
) == 0) {
3340 found_interface
= true;
3345 /* We remove the interface name from the buffer variable name,
3346 * including the dot that follows it.
3348 if (found_interface
)
3349 name
= name
+ block_name_len
+ 1;
3351 /* From: ARB_program_interface_query extension:
3353 * "For an active shader storage block member declared as an array, an
3354 * entry will be generated only for the first array element, regardless
3355 * of its type. For arrays of aggregate types, the enumeration rules are
3356 * applied recursively for the single enumerated array element.
3358 const char *struct_first_dot
= strchr(name
, '.');
3359 const char *first_square_bracket
= strchr(name
, '[');
3361 /* The buffer variable is on top level and it is not an array */
3362 if (!first_square_bracket
) {
3364 /* The shader storage block member is a struct, then generate the entry */
3365 } else if (struct_first_dot
&& struct_first_dot
< first_square_bracket
) {
3368 /* Shader storage block member is an array, only generate an entry for the
3369 * first array element.
3371 if (strncmp(first_square_bracket
, "[0]", 3) == 0)
3379 add_program_resource(struct gl_shader_program
*prog
, GLenum type
,
3380 const void *data
, uint8_t stages
)
3384 /* If resource already exists, do not add it again. */
3385 for (unsigned i
= 0; i
< prog
->NumProgramResourceList
; i
++)
3386 if (prog
->ProgramResourceList
[i
].Data
== data
)
3389 prog
->ProgramResourceList
=
3391 prog
->ProgramResourceList
,
3392 gl_program_resource
,
3393 prog
->NumProgramResourceList
+ 1);
3395 if (!prog
->ProgramResourceList
) {
3396 linker_error(prog
, "Out of memory during linking.\n");
3400 struct gl_program_resource
*res
=
3401 &prog
->ProgramResourceList
[prog
->NumProgramResourceList
];
3405 res
->StageReferences
= stages
;
3407 prog
->NumProgramResourceList
++;
3412 /* Function checks if a variable var is a packed varying and
3413 * if given name is part of packed varying's list.
3415 * If a variable is a packed varying, it has a name like
3416 * 'packed:a,b,c' where a, b and c are separate variables.
3419 included_in_packed_varying(ir_variable
*var
, const char *name
)
3421 if (strncmp(var
->name
, "packed:", 7) != 0)
3424 char *list
= strdup(var
->name
+ 7);
3429 char *token
= strtok_r(list
, ",", &saveptr
);
3431 if (strcmp(token
, name
) == 0) {
3435 token
= strtok_r(NULL
, ",", &saveptr
);
3442 * Function builds a stage reference bitmask from variable name.
3445 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3450 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3451 * used for reference mask in gl_program_resource will need to be changed.
3453 assert(MESA_SHADER_STAGES
< 8);
3455 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3456 struct gl_shader
*sh
= shProg
->_LinkedShaders
[i
];
3460 /* Shader symbol table may contain variables that have
3461 * been optimized away. Search IR for the variable instead.
3463 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3464 ir_variable
*var
= node
->as_variable();
3466 unsigned baselen
= strlen(var
->name
);
3468 if (included_in_packed_varying(var
, name
)) {
3473 /* Type needs to match if specified, otherwise we might
3474 * pick a variable with same name but different interface.
3476 if (var
->data
.mode
!= mode
)
3479 if (strncmp(var
->name
, name
, baselen
) == 0) {
3480 /* Check for exact name matches but also check for arrays and
3483 if (name
[baselen
] == '\0' ||
3484 name
[baselen
] == '[' ||
3485 name
[baselen
] == '.') {
3497 * Create gl_shader_variable from ir_variable class.
3499 static gl_shader_variable
*
3500 create_shader_variable(struct gl_shader_program
*shProg
,
3501 const ir_variable
*in
, bool use_implicit_location
,
3504 gl_shader_variable
*out
= ralloc(shProg
, struct gl_shader_variable
);
3508 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3509 * expect to see gl_VertexID in the program resource list. Pretend.
3511 if (in
->data
.mode
== ir_var_system_value
&&
3512 in
->data
.location
== SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
) {
3513 out
->name
= ralloc_strdup(shProg
, "gl_VertexID");
3515 out
->name
= ralloc_strdup(shProg
, in
->name
);
3521 /* From the ARB_program_interface_query specification:
3523 * "Not all active variables are assigned valid locations; the
3524 * following variables will have an effective location of -1:
3526 * * uniforms declared as atomic counters;
3528 * * members of a uniform block;
3530 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3532 * * inputs or outputs not declared with a "location" layout qualifier,
3533 * except for vertex shader inputs and fragment shader outputs."
3535 if (in
->type
->base_type
== GLSL_TYPE_ATOMIC_UINT
||
3536 is_gl_identifier(in
->name
) ||
3537 !(in
->data
.explicit_location
|| use_implicit_location
)) {
3540 out
->location
= in
->data
.location
- location_bias
;
3543 out
->type
= in
->type
;
3544 out
->index
= in
->data
.index
;
3545 out
->patch
= in
->data
.patch
;
3546 out
->mode
= in
->data
.mode
;
3552 add_interface_variables(struct gl_shader_program
*shProg
,
3553 unsigned stage
, GLenum programInterface
)
3555 exec_list
*ir
= shProg
->_LinkedShaders
[stage
]->ir
;
3557 foreach_in_list(ir_instruction
, node
, ir
) {
3558 ir_variable
*var
= node
->as_variable();
3560 if (!var
|| var
->data
.how_declared
== ir_var_hidden
)
3565 switch (var
->data
.mode
) {
3566 case ir_var_system_value
:
3567 case ir_var_shader_in
:
3568 if (programInterface
!= GL_PROGRAM_INPUT
)
3570 loc_bias
= (stage
== MESA_SHADER_VERTEX
) ? int(VERT_ATTRIB_GENERIC0
)
3571 : int(VARYING_SLOT_VAR0
);
3573 case ir_var_shader_out
:
3574 if (programInterface
!= GL_PROGRAM_OUTPUT
)
3576 loc_bias
= (stage
== MESA_SHADER_FRAGMENT
) ? int(FRAG_RESULT_DATA0
)
3577 : int(VARYING_SLOT_VAR0
);
3583 /* Skip packed varyings, packed varyings are handled separately
3584 * by add_packed_varyings.
3586 if (strncmp(var
->name
, "packed:", 7) == 0)
3589 /* Skip fragdata arrays, these are handled separately
3590 * by add_fragdata_arrays.
3592 if (strncmp(var
->name
, "gl_out_FragData", 15) == 0)
3595 const bool vs_input_or_fs_output
=
3596 (stage
== MESA_SHADER_VERTEX
&& var
->data
.mode
== ir_var_shader_in
) ||
3597 (stage
== MESA_SHADER_FRAGMENT
&& var
->data
.mode
== ir_var_shader_out
);
3599 gl_shader_variable
*sha_v
=
3600 create_shader_variable(shProg
, var
, vs_input_or_fs_output
, loc_bias
);
3604 if (!add_program_resource(shProg
, programInterface
, sha_v
, 1 << stage
))
3611 add_packed_varyings(struct gl_shader_program
*shProg
, int stage
, GLenum type
)
3613 struct gl_shader
*sh
= shProg
->_LinkedShaders
[stage
];
3616 if (!sh
|| !sh
->packed_varyings
)
3619 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
3620 ir_variable
*var
= node
->as_variable();
3622 switch (var
->data
.mode
) {
3623 case ir_var_shader_in
:
3624 iface
= GL_PROGRAM_INPUT
;
3626 case ir_var_shader_out
:
3627 iface
= GL_PROGRAM_OUTPUT
;
3630 unreachable("unexpected type");
3633 if (type
== iface
) {
3634 gl_shader_variable
*sha_v
=
3635 create_shader_variable(shProg
, var
, false, VARYING_SLOT_VAR0
);
3638 if (!add_program_resource(shProg
, iface
, sha_v
,
3639 build_stageref(shProg
, sha_v
->name
,
3649 add_fragdata_arrays(struct gl_shader_program
*shProg
)
3651 struct gl_shader
*sh
= shProg
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
3653 if (!sh
|| !sh
->fragdata_arrays
)
3656 foreach_in_list(ir_instruction
, node
, sh
->fragdata_arrays
) {
3657 ir_variable
*var
= node
->as_variable();
3659 assert(var
->data
.mode
== ir_var_shader_out
);
3660 gl_shader_variable
*sha_v
=
3661 create_shader_variable(shProg
, var
, true, FRAG_RESULT_DATA0
);
3664 if (!add_program_resource(shProg
, GL_PROGRAM_OUTPUT
, sha_v
,
3665 1 << MESA_SHADER_FRAGMENT
))
3673 get_top_level_name(const char *name
)
3675 const char *first_dot
= strchr(name
, '.');
3676 const char *first_square_bracket
= strchr(name
, '[');
3678 /* From ARB_program_interface_query spec:
3680 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying the
3681 * number of active array elements of the top-level shader storage block
3682 * member containing to the active variable is written to <params>. If the
3683 * top-level block member is not declared as an array, the value one is
3684 * written to <params>. If the top-level block member is an array with no
3685 * declared size, the value zero is written to <params>.
3688 /* The buffer variable is on top level.*/
3689 if (!first_square_bracket
&& !first_dot
)
3690 name_size
= strlen(name
);
3691 else if ((!first_square_bracket
||
3692 (first_dot
&& first_dot
< first_square_bracket
)))
3693 name_size
= first_dot
- name
;
3695 name_size
= first_square_bracket
- name
;
3697 return strndup(name
, name_size
);
3701 get_var_name(const char *name
)
3703 const char *first_dot
= strchr(name
, '.');
3706 return strdup(name
);
3708 return strndup(first_dot
+1, strlen(first_dot
) - 1);
3712 is_top_level_shader_storage_block_member(const char* name
,
3713 const char* interface_name
,
3714 const char* field_name
)
3716 bool result
= false;
3718 /* If the given variable is already a top-level shader storage
3719 * block member, then return array_size = 1.
3720 * We could have two possibilities: if we have an instanced
3721 * shader storage block or not instanced.
3723 * For the first, we check create a name as it was in top level and
3724 * compare it with the real name. If they are the same, then
3725 * the variable is already at top-level.
3727 * Full instanced name is: interface name + '.' + var name +
3730 int name_length
= strlen(interface_name
) + 1 + strlen(field_name
) + 1;
3731 char *full_instanced_name
= (char *) calloc(name_length
, sizeof(char));
3732 if (!full_instanced_name
) {
3733 fprintf(stderr
, "%s: Cannot allocate space for name\n", __func__
);
3737 snprintf(full_instanced_name
, name_length
, "%s.%s",
3738 interface_name
, field_name
);
3740 /* Check if its top-level shader storage block member of an
3741 * instanced interface block, or of a unnamed interface block.
3743 if (strcmp(name
, full_instanced_name
) == 0 ||
3744 strcmp(name
, field_name
) == 0)
3747 free(full_instanced_name
);
3752 get_array_size(struct gl_uniform_storage
*uni
, const glsl_struct_field
*field
,
3753 char *interface_name
, char *var_name
)
3755 /* From GL_ARB_program_interface_query spec:
3757 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer
3758 * identifying the number of active array elements of the top-level
3759 * shader storage block member containing to the active variable is
3760 * written to <params>. If the top-level block member is not
3761 * declared as an array, the value one is written to <params>. If
3762 * the top-level block member is an array with no declared size,
3763 * the value zero is written to <params>.
3765 if (is_top_level_shader_storage_block_member(uni
->name
,
3769 else if (field
->type
->is_unsized_array())
3771 else if (field
->type
->is_array())
3772 return field
->type
->length
;
3778 get_array_stride(struct gl_uniform_storage
*uni
, const glsl_type
*interface
,
3779 const glsl_struct_field
*field
, char *interface_name
,
3782 /* From GL_ARB_program_interface_query:
3784 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
3785 * identifying the stride between array elements of the top-level
3786 * shader storage block member containing the active variable is
3787 * written to <params>. For top-level block members declared as
3788 * arrays, the value written is the difference, in basic machine
3789 * units, between the offsets of the active variable for
3790 * consecutive elements in the top-level array. For top-level
3791 * block members not declared as an array, zero is written to
3794 if (field
->type
->is_array()) {
3795 const enum glsl_matrix_layout matrix_layout
=
3796 glsl_matrix_layout(field
->matrix_layout
);
3797 bool row_major
= matrix_layout
== GLSL_MATRIX_LAYOUT_ROW_MAJOR
;
3798 const glsl_type
*array_type
= field
->type
->fields
.array
;
3800 if (is_top_level_shader_storage_block_member(uni
->name
,
3805 if (interface
->interface_packing
!= GLSL_INTERFACE_PACKING_STD430
) {
3806 if (array_type
->is_record() || array_type
->is_array())
3807 return glsl_align(array_type
->std140_size(row_major
), 16);
3809 return MAX2(array_type
->std140_base_alignment(row_major
), 16);
3811 return array_type
->std430_array_stride(row_major
);
3818 calculate_array_size_and_stride(struct gl_shader_program
*shProg
,
3819 struct gl_uniform_storage
*uni
)
3821 int block_index
= uni
->block_index
;
3822 int array_size
= -1;
3823 int array_stride
= -1;
3824 char *var_name
= get_top_level_name(uni
->name
);
3825 char *interface_name
=
3826 get_top_level_name(shProg
->BufferInterfaceBlocks
[block_index
].Name
);
3828 if (strcmp(var_name
, interface_name
) == 0) {
3829 /* Deal with instanced array of SSBOs */
3830 char *temp_name
= get_var_name(uni
->name
);
3832 linker_error(shProg
, "Out of memory during linking.\n");
3833 goto write_top_level_array_size_and_stride
;
3836 var_name
= get_top_level_name(temp_name
);
3839 linker_error(shProg
, "Out of memory during linking.\n");
3840 goto write_top_level_array_size_and_stride
;
3844 for (unsigned i
= 0; i
< shProg
->NumShaders
; i
++) {
3845 if (shProg
->Shaders
[i
] == NULL
)
3848 const gl_shader
*stage
= shProg
->Shaders
[i
];
3849 foreach_in_list(ir_instruction
, node
, stage
->ir
) {
3850 ir_variable
*var
= node
->as_variable();
3851 if (!var
|| !var
->get_interface_type() ||
3852 var
->data
.mode
!= ir_var_shader_storage
)
3855 const glsl_type
*interface
= var
->get_interface_type();
3857 if (strcmp(interface_name
, interface
->name
) != 0)
3860 for (unsigned i
= 0; i
< interface
->length
; i
++) {
3861 const glsl_struct_field
*field
= &interface
->fields
.structure
[i
];
3862 if (strcmp(field
->name
, var_name
) != 0)
3865 array_stride
= get_array_stride(uni
, interface
, field
,
3866 interface_name
, var_name
);
3867 array_size
= get_array_size(uni
, field
, interface_name
, var_name
);
3868 goto write_top_level_array_size_and_stride
;
3872 write_top_level_array_size_and_stride
:
3873 free(interface_name
);
3875 uni
->top_level_array_stride
= array_stride
;
3876 uni
->top_level_array_size
= array_size
;
3880 * Builds up a list of program resources that point to existing
3884 build_program_resource_list(struct gl_context
*ctx
,
3885 struct gl_shader_program
*shProg
)
3887 /* Rebuild resource list. */
3888 if (shProg
->ProgramResourceList
) {
3889 ralloc_free(shProg
->ProgramResourceList
);
3890 shProg
->ProgramResourceList
= NULL
;
3891 shProg
->NumProgramResourceList
= 0;
3894 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
3896 /* Determine first input and final output stage. These are used to
3897 * detect which variables should be enumerated in the resource list
3898 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
3900 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3901 if (!shProg
->_LinkedShaders
[i
])
3903 if (input_stage
== MESA_SHADER_STAGES
)
3908 /* Empty shader, no resources. */
3909 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
3912 /* Program interface needs to expose varyings in case of SSO. */
3913 if (shProg
->SeparateShader
) {
3914 if (!add_packed_varyings(shProg
, input_stage
, GL_PROGRAM_INPUT
))
3917 if (!add_packed_varyings(shProg
, output_stage
, GL_PROGRAM_OUTPUT
))
3921 if (!add_fragdata_arrays(shProg
))
3924 /* Add inputs and outputs to the resource list. */
3925 if (!add_interface_variables(shProg
, input_stage
, GL_PROGRAM_INPUT
))
3928 if (!add_interface_variables(shProg
, output_stage
, GL_PROGRAM_OUTPUT
))
3931 /* Add transform feedback varyings. */
3932 if (shProg
->LinkedTransformFeedback
.NumVarying
> 0) {
3933 for (int i
= 0; i
< shProg
->LinkedTransformFeedback
.NumVarying
; i
++) {
3934 if (!add_program_resource(shProg
, GL_TRANSFORM_FEEDBACK_VARYING
,
3935 &shProg
->LinkedTransformFeedback
.Varyings
[i
],
3941 /* Add transform feedback buffers. */
3942 for (unsigned i
= 0; i
< ctx
->Const
.MaxTransformFeedbackBuffers
; i
++) {
3943 if ((shProg
->LinkedTransformFeedback
.ActiveBuffers
>> i
) & 1) {
3944 shProg
->LinkedTransformFeedback
.Buffers
[i
].Binding
= i
;
3945 if (!add_program_resource(shProg
, GL_TRANSFORM_FEEDBACK_BUFFER
,
3946 &shProg
->LinkedTransformFeedback
.Buffers
[i
],
3952 /* Add uniforms from uniform storage. */
3953 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
3954 /* Do not add uniforms internally used by Mesa. */
3955 if (shProg
->UniformStorage
[i
].hidden
)
3959 build_stageref(shProg
, shProg
->UniformStorage
[i
].name
,
3962 /* Add stagereferences for uniforms in a uniform block. */
3963 int block_index
= shProg
->UniformStorage
[i
].block_index
;
3964 if (block_index
!= -1) {
3965 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
3966 if (shProg
->InterfaceBlockStageIndex
[j
][block_index
] != -1)
3967 stageref
|= (1 << j
);
3971 bool is_shader_storage
= shProg
->UniformStorage
[i
].is_shader_storage
;
3972 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
3973 if (!should_add_buffer_variable(shProg
, type
,
3974 shProg
->UniformStorage
[i
].name
))
3977 if (is_shader_storage
) {
3978 calculate_array_size_and_stride(shProg
, &shProg
->UniformStorage
[i
]);
3981 if (!add_program_resource(shProg
, type
,
3982 &shProg
->UniformStorage
[i
], stageref
))
3986 /* Add program uniform blocks and shader storage blocks. */
3987 for (unsigned i
= 0; i
< shProg
->NumBufferInterfaceBlocks
; i
++) {
3988 bool is_shader_storage
= shProg
->BufferInterfaceBlocks
[i
].IsShaderStorage
;
3989 GLenum type
= is_shader_storage
? GL_SHADER_STORAGE_BLOCK
: GL_UNIFORM_BLOCK
;
3990 if (!add_program_resource(shProg
, type
,
3991 &shProg
->BufferInterfaceBlocks
[i
], 0))
3995 /* Add atomic counter buffers. */
3996 for (unsigned i
= 0; i
< shProg
->NumAtomicBuffers
; i
++) {
3997 if (!add_program_resource(shProg
, GL_ATOMIC_COUNTER_BUFFER
,
3998 &shProg
->AtomicBuffers
[i
], 0))
4002 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
4004 if (!shProg
->UniformStorage
[i
].hidden
)
4007 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
4008 if (!shProg
->UniformStorage
[i
].opaque
[j
].active
||
4009 !shProg
->UniformStorage
[i
].type
->is_subroutine())
4012 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
4013 /* add shader subroutines */
4014 if (!add_program_resource(shProg
, type
, &shProg
->UniformStorage
[i
], 0))
4019 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4020 struct gl_shader
*sh
= shProg
->_LinkedShaders
[i
];
4026 type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
4027 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
4028 if (!add_program_resource(shProg
, type
, &sh
->SubroutineFunctions
[j
], 0))
4035 * This check is done to make sure we allow only constant expression
4036 * indexing and "constant-index-expression" (indexing with an expression
4037 * that includes loop induction variable).
4040 validate_sampler_array_indexing(struct gl_context
*ctx
,
4041 struct gl_shader_program
*prog
)
4043 dynamic_sampler_array_indexing_visitor v
;
4044 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4045 if (prog
->_LinkedShaders
[i
] == NULL
)
4048 bool no_dynamic_indexing
=
4049 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
4051 /* Search for array derefs in shader. */
4052 v
.run(prog
->_LinkedShaders
[i
]->ir
);
4053 if (v
.uses_dynamic_sampler_array_indexing()) {
4054 const char *msg
= "sampler arrays indexed with non-constant "
4055 "expressions is forbidden in GLSL %s %u";
4056 /* Backend has indicated that it has no dynamic indexing support. */
4057 if (no_dynamic_indexing
) {
4058 linker_error(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
4061 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
4069 link_assign_subroutine_types(struct gl_shader_program
*prog
)
4071 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4072 gl_shader
*sh
= prog
->_LinkedShaders
[i
];
4077 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
4078 ir_function
*fn
= node
->as_function();
4082 if (fn
->is_subroutine
)
4083 sh
->NumSubroutineUniformTypes
++;
4085 if (!fn
->num_subroutine_types
)
4088 sh
->SubroutineFunctions
= reralloc(sh
, sh
->SubroutineFunctions
,
4089 struct gl_subroutine_function
,
4090 sh
->NumSubroutineFunctions
+ 1);
4091 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].name
= ralloc_strdup(sh
, fn
->name
);
4092 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
4093 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
=
4094 ralloc_array(sh
, const struct glsl_type
*,
4095 fn
->num_subroutine_types
);
4097 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4100 * "Each subroutine with an index qualifier in the shader must be
4101 * given a unique index, otherwise a compile or link error will be
4104 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
4105 if (sh
->SubroutineFunctions
[j
].index
!= -1 &&
4106 sh
->SubroutineFunctions
[j
].index
== fn
->subroutine_index
) {
4107 linker_error(prog
, "each subroutine index qualifier in the "
4108 "shader must be unique\n");
4112 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].index
=
4113 fn
->subroutine_index
;
4115 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
4116 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
4117 sh
->NumSubroutineFunctions
++;
4120 /* Assign index for subroutines without an explicit index*/
4122 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
4123 while (sh
->SubroutineFunctions
[j
].index
== -1) {
4124 for (unsigned k
= 0; k
< sh
->NumSubroutineFunctions
; k
++) {
4125 if (sh
->SubroutineFunctions
[k
].index
== index
)
4127 else if (k
== sh
->NumSubroutineFunctions
- 1)
4128 sh
->SubroutineFunctions
[j
].index
= index
;
4137 split_ubos_and_ssbos(void *mem_ctx
,
4138 struct gl_uniform_block
**s_blks
,
4139 struct gl_uniform_block
*p_blks
,
4140 unsigned num_blocks
,
4141 struct gl_uniform_block
***ubos
,
4143 struct gl_uniform_block
***ssbos
,
4144 unsigned *num_ssbos
)
4146 unsigned num_ubo_blocks
= 0;
4147 unsigned num_ssbo_blocks
= 0;
4149 /* Are we spliting the list of blocks for the shader or the program */
4150 bool is_shader
= p_blks
== NULL
;
4152 for (unsigned i
= 0; i
< num_blocks
; i
++) {
4153 if (is_shader
? s_blks
[i
]->IsShaderStorage
: p_blks
[i
].IsShaderStorage
)
4159 *ubos
= ralloc_array(mem_ctx
, gl_uniform_block
*, num_ubo_blocks
);
4162 *ssbos
= ralloc_array(mem_ctx
, gl_uniform_block
*, num_ssbo_blocks
);
4165 for (unsigned i
= 0; i
< num_blocks
; i
++) {
4166 struct gl_uniform_block
*blk
= is_shader
? s_blks
[i
] : &p_blks
[i
];
4167 if (blk
->IsShaderStorage
) {
4168 (*ssbos
)[*num_ssbos
] = blk
;
4171 (*ubos
)[*num_ubos
] = blk
;
4176 assert(*num_ubos
+ *num_ssbos
== num_blocks
);
4180 set_always_active_io(exec_list
*ir
, ir_variable_mode io_mode
)
4182 assert(io_mode
== ir_var_shader_in
|| io_mode
== ir_var_shader_out
);
4184 foreach_in_list(ir_instruction
, node
, ir
) {
4185 ir_variable
*const var
= node
->as_variable();
4187 if (var
== NULL
|| var
->data
.mode
!= io_mode
)
4190 /* Don't set always active on builtins that haven't been redeclared */
4191 if (var
->data
.how_declared
== ir_var_declared_implicitly
)
4194 var
->data
.always_active_io
= true;
4199 * When separate shader programs are enabled, only input/outputs between
4200 * the stages of a multi-stage separate program can be safely removed
4201 * from the shader interface. Other inputs/outputs must remain active.
4204 disable_varying_optimizations_for_sso(struct gl_shader_program
*prog
)
4206 unsigned first
, last
;
4207 assert(prog
->SeparateShader
);
4209 first
= MESA_SHADER_STAGES
;
4212 /* Determine first and last stage. Excluding the compute stage */
4213 for (unsigned i
= 0; i
< MESA_SHADER_COMPUTE
; i
++) {
4214 if (!prog
->_LinkedShaders
[i
])
4216 if (first
== MESA_SHADER_STAGES
)
4221 if (first
== MESA_SHADER_STAGES
)
4224 for (unsigned stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4225 gl_shader
*sh
= prog
->_LinkedShaders
[stage
];
4229 if (first
== last
) {
4230 /* For a single shader program only allow inputs to the vertex shader
4231 * and outputs from the fragment shader to be removed.
4233 if (stage
!= MESA_SHADER_VERTEX
)
4234 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4235 if (stage
!= MESA_SHADER_FRAGMENT
)
4236 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4238 /* For multi-stage separate shader programs only allow inputs and
4239 * outputs between the shader stages to be removed as well as inputs
4240 * to the vertex shader and outputs from the fragment shader.
4242 if (stage
== first
&& stage
!= MESA_SHADER_VERTEX
)
4243 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4244 else if (stage
== last
&& stage
!= MESA_SHADER_FRAGMENT
)
4245 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4251 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
4253 prog
->LinkStatus
= true; /* All error paths will set this to false */
4254 prog
->Validated
= false;
4255 prog
->_Used
= false;
4257 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4259 * "Linking can fail for a variety of reasons as specified in the
4260 * OpenGL Shading Language Specification, as well as any of the
4261 * following reasons:
4263 * - No shader objects are attached to program."
4265 * The Compatibility Profile specification does not list the error. In
4266 * Compatibility Profile missing shader stages are replaced by
4267 * fixed-function. This applies to the case where all stages are
4270 if (prog
->NumShaders
== 0) {
4271 if (ctx
->API
!= API_OPENGL_COMPAT
)
4272 linker_error(prog
, "no shaders attached to the program\n");
4276 unsigned num_tfeedback_decls
= 0;
4277 unsigned int num_explicit_uniform_locs
= 0;
4278 bool has_xfb_qualifiers
= false;
4279 char **varying_names
= NULL
;
4280 tfeedback_decl
*tfeedback_decls
= NULL
;
4282 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
4284 prog
->ARB_fragment_coord_conventions_enable
= false;
4286 /* Separate the shaders into groups based on their type.
4288 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
4289 unsigned num_shaders
[MESA_SHADER_STAGES
];
4291 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4292 shader_list
[i
] = (struct gl_shader
**)
4293 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
4297 unsigned min_version
= UINT_MAX
;
4298 unsigned max_version
= 0;
4299 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
4300 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
4301 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
4303 if (prog
->Shaders
[i
]->IsES
!= prog
->Shaders
[0]->IsES
) {
4304 linker_error(prog
, "all shaders must use same shading "
4305 "language version\n");
4309 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
4310 prog
->ARB_fragment_coord_conventions_enable
= true;
4313 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
4314 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
4315 num_shaders
[shader_type
]++;
4318 /* In desktop GLSL, different shader versions may be linked together. In
4319 * GLSL ES, all shader versions must be the same.
4321 if (prog
->Shaders
[0]->IsES
&& min_version
!= max_version
) {
4322 linker_error(prog
, "all shaders must use same shading "
4323 "language version\n");
4327 prog
->Version
= max_version
;
4328 prog
->IsES
= prog
->Shaders
[0]->IsES
;
4330 /* Some shaders have to be linked with some other shaders present.
4332 if (!prog
->SeparateShader
) {
4333 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
4334 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4335 linker_error(prog
, "Geometry shader must be linked with "
4339 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4340 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4341 linker_error(prog
, "Tessellation evaluation shader must be linked "
4342 "with vertex shader\n");
4345 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4346 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4347 linker_error(prog
, "Tessellation control shader must be linked with "
4352 /* The spec is self-contradictory here. It allows linking without a tess
4353 * eval shader, but that can only be used with transform feedback and
4354 * rasterization disabled. However, transform feedback isn't allowed
4355 * with GL_PATCHES, so it can't be used.
4357 * More investigation showed that the idea of transform feedback after
4358 * a tess control shader was dropped, because some hw vendors couldn't
4359 * support tessellation without a tess eval shader, but the linker
4360 * section wasn't updated to reflect that.
4362 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4365 * Do what's reasonable and always require a tess eval shader if a tess
4366 * control shader is present.
4368 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4369 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0) {
4370 linker_error(prog
, "Tessellation control shader must be linked with "
4371 "tessellation evaluation shader\n");
4376 /* Compute shaders have additional restrictions. */
4377 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
4378 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
4379 linker_error(prog
, "Compute shaders may not be linked with any other "
4380 "type of shader\n");
4383 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4384 if (prog
->_LinkedShaders
[i
] != NULL
)
4385 _mesa_delete_shader(ctx
, prog
->_LinkedShaders
[i
]);
4387 prog
->_LinkedShaders
[i
] = NULL
;
4390 /* Link all shaders for a particular stage and validate the result.
4392 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4393 if (num_shaders
[stage
] > 0) {
4394 gl_shader
*const sh
=
4395 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
4396 num_shaders
[stage
]);
4398 if (!prog
->LinkStatus
) {
4400 _mesa_delete_shader(ctx
, sh
);
4405 case MESA_SHADER_VERTEX
:
4406 validate_vertex_shader_executable(prog
, sh
);
4408 case MESA_SHADER_TESS_CTRL
:
4409 /* nothing to be done */
4411 case MESA_SHADER_TESS_EVAL
:
4412 validate_tess_eval_shader_executable(prog
, sh
);
4414 case MESA_SHADER_GEOMETRY
:
4415 validate_geometry_shader_executable(prog
, sh
);
4417 case MESA_SHADER_FRAGMENT
:
4418 validate_fragment_shader_executable(prog
, sh
);
4421 if (!prog
->LinkStatus
) {
4423 _mesa_delete_shader(ctx
, sh
);
4427 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[stage
], sh
);
4431 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0)
4432 prog
->LastClipDistanceArraySize
= prog
->Geom
.ClipDistanceArraySize
;
4433 else if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0)
4434 prog
->LastClipDistanceArraySize
= prog
->TessEval
.ClipDistanceArraySize
;
4435 else if (num_shaders
[MESA_SHADER_VERTEX
] > 0)
4436 prog
->LastClipDistanceArraySize
= prog
->Vert
.ClipDistanceArraySize
;
4438 prog
->LastClipDistanceArraySize
= 0; /* Not used */
4440 /* Here begins the inter-stage linking phase. Some initial validation is
4441 * performed, then locations are assigned for uniforms, attributes, and
4444 cross_validate_uniforms(prog
);
4445 if (!prog
->LinkStatus
)
4448 unsigned first
, last
, prev
;
4450 first
= MESA_SHADER_STAGES
;
4453 /* Determine first and last stage. */
4454 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4455 if (!prog
->_LinkedShaders
[i
])
4457 if (first
== MESA_SHADER_STAGES
)
4462 num_explicit_uniform_locs
= check_explicit_uniform_locations(ctx
, prog
);
4463 link_assign_subroutine_types(prog
);
4465 if (!prog
->LinkStatus
)
4468 resize_tes_inputs(ctx
, prog
);
4470 /* Validate the inputs of each stage with the output of the preceding
4474 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4475 if (prog
->_LinkedShaders
[i
] == NULL
)
4478 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
4479 prog
->_LinkedShaders
[i
]);
4480 if (!prog
->LinkStatus
)
4483 cross_validate_outputs_to_inputs(prog
,
4484 prog
->_LinkedShaders
[prev
],
4485 prog
->_LinkedShaders
[i
]);
4486 if (!prog
->LinkStatus
)
4492 /* Cross-validate uniform blocks between shader stages */
4493 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
,
4494 MESA_SHADER_STAGES
);
4495 if (!prog
->LinkStatus
)
4498 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4499 if (prog
->_LinkedShaders
[i
] != NULL
)
4500 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
4503 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4504 * it before optimization because we want most of the checks to get
4505 * dropped thanks to constant propagation.
4507 * This rule also applies to GLSL ES 3.00.
4509 if (max_version
>= (prog
->IsES
? 300 : 130)) {
4510 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4512 lower_discard_flow(sh
->ir
);
4516 if (prog
->SeparateShader
)
4517 disable_varying_optimizations_for_sso(prog
);
4519 if (!interstage_cross_validate_uniform_blocks(prog
))
4522 /* Do common optimization before assigning storage for attributes,
4523 * uniforms, and varyings. Later optimization could possibly make
4524 * some of that unused.
4526 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4527 if (prog
->_LinkedShaders
[i
] == NULL
)
4530 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
4531 if (!prog
->LinkStatus
)
4534 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerClipDistance
) {
4535 lower_clip_distance(prog
->_LinkedShaders
[i
]);
4538 if (ctx
->Const
.LowerTessLevel
) {
4539 lower_tess_level(prog
->_LinkedShaders
[i
]);
4542 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false,
4543 &ctx
->Const
.ShaderCompilerOptions
[i
],
4544 ctx
->Const
.NativeIntegers
))
4547 lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
);
4550 /* Validation for special cases where we allow sampler array indexing
4551 * with loop induction variable. This check emits a warning or error
4552 * depending if backend can handle dynamic indexing.
4554 if ((!prog
->IsES
&& prog
->Version
< 130) ||
4555 (prog
->IsES
&& prog
->Version
< 300)) {
4556 if (!validate_sampler_array_indexing(ctx
, prog
))
4560 /* Check and validate stream emissions in geometry shaders */
4561 validate_geometry_shader_emissions(ctx
, prog
);
4563 /* Mark all generic shader inputs and outputs as unpaired. */
4564 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4565 if (prog
->_LinkedShaders
[i
] != NULL
) {
4566 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
4571 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4572 if (prog
->_LinkedShaders
[i
] == NULL
)
4575 match_explicit_outputs_to_inputs(prog
, prog
->_LinkedShaders
[prev
],
4576 prog
->_LinkedShaders
[i
]);
4580 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
4581 MESA_SHADER_VERTEX
)) {
4585 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
4586 MESA_SHADER_FRAGMENT
)) {
4590 /* From the ARB_enhanced_layouts spec:
4592 * "If the shader used to record output variables for transform feedback
4593 * varyings uses the "xfb_buffer", "xfb_offset", or "xfb_stride" layout
4594 * qualifiers, the values specified by TransformFeedbackVaryings are
4595 * ignored, and the set of variables captured for transform feedback is
4596 * instead derived from the specified layout qualifiers."
4598 for (int i
= MESA_SHADER_FRAGMENT
- 1; i
>= 0; i
--) {
4599 /* Find last stage before fragment shader */
4600 if (prog
->_LinkedShaders
[i
]) {
4601 has_xfb_qualifiers
=
4602 process_xfb_layout_qualifiers(mem_ctx
, prog
->_LinkedShaders
[i
],
4603 &num_tfeedback_decls
,
4609 if (!has_xfb_qualifiers
) {
4610 num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
4611 varying_names
= prog
->TransformFeedback
.VaryingNames
;
4614 if (num_tfeedback_decls
!= 0) {
4615 /* From GL_EXT_transform_feedback:
4616 * A program will fail to link if:
4618 * * the <count> specified by TransformFeedbackVaryingsEXT is
4619 * non-zero, but the program object has no vertex or geometry
4622 if (first
>= MESA_SHADER_FRAGMENT
) {
4623 linker_error(prog
, "Transform feedback varyings specified, but "
4624 "no vertex, tessellation, or geometry shader is "
4629 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
4630 num_tfeedback_decls
);
4631 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
4632 varying_names
, tfeedback_decls
))
4636 /* If there is no fragment shader we need to set transform feedback.
4638 * For SSO we need also need to assign output locations, we assign them
4639 * here because we need to do it for both single stage programs and multi
4642 if (last
< MESA_SHADER_FRAGMENT
&&
4643 (num_tfeedback_decls
!= 0 || prog
->SeparateShader
)) {
4644 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
4645 prog
->_LinkedShaders
[last
], NULL
,
4646 num_tfeedback_decls
, tfeedback_decls
))
4650 if (last
<= MESA_SHADER_FRAGMENT
) {
4651 /* Remove unused varyings from the first/last stage unless SSO */
4652 remove_unused_shader_inputs_and_outputs(prog
->SeparateShader
,
4653 prog
->_LinkedShaders
[first
],
4655 remove_unused_shader_inputs_and_outputs(prog
->SeparateShader
,
4656 prog
->_LinkedShaders
[last
],
4659 /* If the program is made up of only a single stage */
4660 if (first
== last
) {
4662 gl_shader
*const sh
= prog
->_LinkedShaders
[last
];
4663 if (prog
->SeparateShader
) {
4664 /* Assign input locations for SSO, output locations are already
4667 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
4668 NULL
/* producer */,
4670 0 /* num_tfeedback_decls */,
4671 NULL
/* tfeedback_decls */))
4675 do_dead_builtin_varyings(ctx
, NULL
, sh
, 0, NULL
);
4676 do_dead_builtin_varyings(ctx
, sh
, NULL
, num_tfeedback_decls
,
4679 /* Linking the stages in the opposite order (from fragment to vertex)
4680 * ensures that inter-shader outputs written to in an earlier stage
4681 * are eliminated if they are (transitively) not used in a later
4685 for (int i
= next
- 1; i
>= 0; i
--) {
4686 if (prog
->_LinkedShaders
[i
] == NULL
)
4689 gl_shader
*const sh_i
= prog
->_LinkedShaders
[i
];
4690 gl_shader
*const sh_next
= prog
->_LinkedShaders
[next
];
4692 if (!assign_varying_locations(ctx
, mem_ctx
, prog
, sh_i
, sh_next
,
4693 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
4697 do_dead_builtin_varyings(ctx
, sh_i
, sh_next
,
4698 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
4701 /* This must be done after all dead varyings are eliminated. */
4702 if (!check_against_output_limit(ctx
, prog
, sh_i
))
4704 if (!check_against_input_limit(ctx
, prog
, sh_next
))
4712 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
,
4713 has_xfb_qualifiers
))
4716 update_array_sizes(prog
);
4717 link_assign_uniform_locations(prog
, ctx
->Const
.UniformBooleanTrue
,
4718 num_explicit_uniform_locs
,
4719 ctx
->Const
.MaxUserAssignableUniformLocations
);
4720 link_assign_atomic_counter_resources(ctx
, prog
);
4721 store_fragdepth_layout(prog
);
4723 link_calculate_subroutine_compat(prog
);
4724 check_resources(ctx
, prog
);
4725 check_subroutine_resources(prog
);
4726 check_image_resources(ctx
, prog
);
4727 link_check_atomic_counter_resources(ctx
, prog
);
4729 if (!prog
->LinkStatus
)
4732 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
4733 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
4734 * anything about shader linking when one of the shaders (vertex or
4735 * fragment shader) is absent. So, the extension shouldn't change the
4736 * behavior specified in GLSL specification.
4738 * From OpenGL ES 3.1 specification (7.3 Program Objects):
4739 * "Linking can fail for a variety of reasons as specified in the
4740 * OpenGL ES Shading Language Specification, as well as any of the
4741 * following reasons:
4745 * * program contains objects to form either a vertex shader or
4746 * fragment shader, and program is not separable, and does not
4747 * contain objects to form both a vertex shader and fragment
4750 * However, the only scenario in 3.1+ where we don't require them both is
4751 * when we have a compute shader. For example:
4753 * - No shaders is a link error.
4754 * - Geom or Tess without a Vertex shader is a link error which means we
4755 * always require a Vertex shader and hence a Fragment shader.
4756 * - Finally a Compute shader linked with any other stage is a link error.
4758 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
&&
4759 num_shaders
[MESA_SHADER_COMPUTE
] == 0) {
4760 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
4761 linker_error(prog
, "program lacks a vertex shader\n");
4762 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
4763 linker_error(prog
, "program lacks a fragment shader\n");
4767 /* Split BufferInterfaceBlocks into UniformBlocks and ShaderStorageBlocks
4768 * for gl_shader_program and gl_shader, so that drivers that need separate
4769 * index spaces for each set can have that.
4771 for (unsigned i
= MESA_SHADER_VERTEX
; i
< MESA_SHADER_STAGES
; i
++) {
4772 if (prog
->_LinkedShaders
[i
] != NULL
) {
4773 gl_shader
*sh
= prog
->_LinkedShaders
[i
];
4774 split_ubos_and_ssbos(sh
,
4775 sh
->BufferInterfaceBlocks
,
4777 sh
->NumBufferInterfaceBlocks
,
4779 &sh
->NumUniformBlocks
,
4780 &sh
->ShaderStorageBlocks
,
4781 &sh
->NumShaderStorageBlocks
);
4785 split_ubos_and_ssbos(prog
,
4787 prog
->BufferInterfaceBlocks
,
4788 prog
->NumBufferInterfaceBlocks
,
4789 &prog
->UniformBlocks
,
4790 &prog
->NumUniformBlocks
,
4791 &prog
->ShaderStorageBlocks
,
4792 &prog
->NumShaderStorageBlocks
);
4794 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4795 if (prog
->_LinkedShaders
[i
] == NULL
)
4798 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerBufferInterfaceBlocks
)
4799 lower_ubo_reference(prog
->_LinkedShaders
[i
]);
4801 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerShaderSharedVariables
)
4802 lower_shared_reference(prog
->_LinkedShaders
[i
],
4803 &prog
->Comp
.SharedSize
);
4805 lower_vector_derefs(prog
->_LinkedShaders
[i
]);
4809 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4810 free(shader_list
[i
]);
4811 if (prog
->_LinkedShaders
[i
] == NULL
)
4814 /* Do a final validation step to make sure that the IR wasn't
4815 * invalidated by any modifications performed after intrastage linking.
4817 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
4819 /* Retain any live IR, but trash the rest. */
4820 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
4822 /* The symbol table in the linked shaders may contain references to
4823 * variables that were removed (e.g., unused uniforms). Since it may
4824 * contain junk, there is no possible valid use. Delete it and set the
4827 delete prog
->_LinkedShaders
[i
]->symbols
;
4828 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
4831 ralloc_free(mem_ctx
);