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
>= (int)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 and cull_distance_array_size on the given
647 * Also check for errors based on incorrect usage of gl_ClipVertex and
648 * gl_ClipDistance and gl_CullDistance.
649 * Additionally test whether the arrays gl_ClipDistance and gl_CullDistance
650 * exceed the maximum size defined by gl_MaxCombinedClipAndCullDistances.
652 * Return false if an error was reported.
655 analyze_clip_cull_usage(struct gl_shader_program
*prog
,
656 struct gl_shader
*shader
,
657 struct gl_context
*ctx
,
658 GLuint
*clip_distance_array_size
,
659 GLuint
*cull_distance_array_size
)
661 *clip_distance_array_size
= 0;
662 *cull_distance_array_size
= 0;
664 if (prog
->Version
>= (prog
->IsES
? 300 : 130)) {
665 /* From section 7.1 (Vertex Shader Special Variables) of the
668 * "It is an error for a shader to statically write both
669 * gl_ClipVertex and gl_ClipDistance."
671 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
672 * gl_ClipVertex nor gl_ClipDistance. However with
673 * GL_EXT_clip_cull_distance, this functionality is exposed in ES 3.0.
675 find_assignment_visitor
clip_distance("gl_ClipDistance");
676 find_assignment_visitor
cull_distance("gl_CullDistance");
678 clip_distance
.run(shader
->ir
);
679 cull_distance
.run(shader
->ir
);
681 /* From the ARB_cull_distance spec:
683 * It is a compile-time or link-time error for the set of shaders forming
684 * a program to statically read or write both gl_ClipVertex and either
685 * gl_ClipDistance or gl_CullDistance.
687 * This does not apply to GLSL ES shaders, since GLSL ES doesn't define
691 find_assignment_visitor
clip_vertex("gl_ClipVertex");
693 clip_vertex
.run(shader
->ir
);
695 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
696 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
697 "and `gl_ClipDistance'\n",
698 _mesa_shader_stage_to_string(shader
->Stage
));
701 if (clip_vertex
.variable_found() && cull_distance
.variable_found()) {
702 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
703 "and `gl_CullDistance'\n",
704 _mesa_shader_stage_to_string(shader
->Stage
));
709 if (clip_distance
.variable_found()) {
710 ir_variable
*clip_distance_var
=
711 shader
->symbols
->get_variable("gl_ClipDistance");
712 assert(clip_distance_var
);
713 *clip_distance_array_size
= clip_distance_var
->type
->length
;
715 if (cull_distance
.variable_found()) {
716 ir_variable
*cull_distance_var
=
717 shader
->symbols
->get_variable("gl_CullDistance");
718 assert(cull_distance_var
);
719 *cull_distance_array_size
= cull_distance_var
->type
->length
;
721 /* From the ARB_cull_distance spec:
723 * It is a compile-time or link-time error for the set of shaders forming
724 * a program to have the sum of the sizes of the gl_ClipDistance and
725 * gl_CullDistance arrays to be larger than
726 * gl_MaxCombinedClipAndCullDistances.
728 if ((*clip_distance_array_size
+ *cull_distance_array_size
) >
729 ctx
->Const
.MaxClipPlanes
) {
730 linker_error(prog
, "%s shader: the combined size of "
731 "'gl_ClipDistance' and 'gl_CullDistance' size cannot "
733 "gl_MaxCombinedClipAndCullDistances (%u)",
734 _mesa_shader_stage_to_string(shader
->Stage
),
735 ctx
->Const
.MaxClipPlanes
);
742 * Verify that a vertex shader executable meets all semantic requirements.
744 * Also sets prog->Vert.ClipDistanceArraySize and
745 * prog->Vert.CullDistanceArraySize as a side effect.
747 * \param shader Vertex shader executable to be verified
750 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
751 struct gl_shader
*shader
,
752 struct gl_context
*ctx
)
757 /* From the GLSL 1.10 spec, page 48:
759 * "The variable gl_Position is available only in the vertex
760 * language and is intended for writing the homogeneous vertex
761 * position. All executions of a well-formed vertex shader
762 * executable must write a value into this variable. [...] The
763 * variable gl_Position is available only in the vertex
764 * language and is intended for writing the homogeneous vertex
765 * position. All executions of a well-formed vertex shader
766 * executable must write a value into this variable."
768 * while in GLSL 1.40 this text is changed to:
770 * "The variable gl_Position is available only in the vertex
771 * language and is intended for writing the homogeneous vertex
772 * position. It can be written at any time during shader
773 * execution. It may also be read back by a vertex shader
774 * after being written. This value will be used by primitive
775 * assembly, clipping, culling, and other fixed functionality
776 * operations, if present, that operate on primitives after
777 * vertex processing has occurred. Its value is undefined if
778 * the vertex shader executable does not write gl_Position."
780 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
781 * gl_Position is not an error.
783 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
784 find_assignment_visitor
find("gl_Position");
785 find
.run(shader
->ir
);
786 if (!find
.variable_found()) {
789 "vertex shader does not write to `gl_Position'."
790 "It's value is undefined. \n");
793 "vertex shader does not write to `gl_Position'. \n");
799 analyze_clip_cull_usage(prog
, shader
, ctx
,
800 &prog
->Vert
.ClipDistanceArraySize
,
801 &prog
->Vert
.CullDistanceArraySize
);
805 validate_tess_eval_shader_executable(struct gl_shader_program
*prog
,
806 struct gl_shader
*shader
,
807 struct gl_context
*ctx
)
812 analyze_clip_cull_usage(prog
, shader
, ctx
,
813 &prog
->TessEval
.ClipDistanceArraySize
,
814 &prog
->TessEval
.CullDistanceArraySize
);
819 * Verify that a fragment shader executable meets all semantic requirements
821 * \param shader Fragment shader executable to be verified
824 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
825 struct gl_shader
*shader
)
830 find_assignment_visitor
frag_color("gl_FragColor");
831 find_assignment_visitor
frag_data("gl_FragData");
833 frag_color
.run(shader
->ir
);
834 frag_data
.run(shader
->ir
);
836 if (frag_color
.variable_found() && frag_data
.variable_found()) {
837 linker_error(prog
, "fragment shader writes to both "
838 "`gl_FragColor' and `gl_FragData'\n");
843 * Verify that a geometry shader executable meets all semantic requirements
845 * Also sets prog->Geom.VerticesIn, and prog->Geom.ClipDistanceArraySize and
846 * prog->Geom.CullDistanceArraySize as a side effect.
848 * \param shader Geometry shader executable to be verified
851 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
852 struct gl_shader
*shader
,
853 struct gl_context
*ctx
)
858 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
859 prog
->Geom
.VerticesIn
= num_vertices
;
861 analyze_clip_cull_usage(prog
, shader
, ctx
,
862 &prog
->Geom
.ClipDistanceArraySize
,
863 &prog
->Geom
.CullDistanceArraySize
);
867 * Check if geometry shaders emit to non-zero streams and do corresponding
871 validate_geometry_shader_emissions(struct gl_context
*ctx
,
872 struct gl_shader_program
*prog
)
874 if (prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
] != NULL
) {
875 find_emit_vertex_visitor
emit_vertex(ctx
->Const
.MaxVertexStreams
- 1);
876 emit_vertex
.run(prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
]->ir
);
877 if (emit_vertex
.error()) {
878 linker_error(prog
, "Invalid call %s(%d). Accepted values for the "
879 "stream parameter are in the range [0, %d].\n",
880 emit_vertex
.error_func(),
881 emit_vertex
.error_stream(),
882 ctx
->Const
.MaxVertexStreams
- 1);
884 prog
->Geom
.UsesStreams
= emit_vertex
.uses_streams();
885 prog
->Geom
.UsesEndPrimitive
= emit_vertex
.uses_end_primitive();
887 /* From the ARB_gpu_shader5 spec:
889 * "Multiple vertex streams are supported only if the output primitive
890 * type is declared to be "points". A program will fail to link if it
891 * contains a geometry shader calling EmitStreamVertex() or
892 * EndStreamPrimitive() if its output primitive type is not "points".
894 * However, in the same spec:
896 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
897 * with <stream> set to zero."
901 * "The function EndPrimitive() is equivalent to calling
902 * EndStreamPrimitive() with <stream> set to zero."
904 * Since we can call EmitVertex() and EndPrimitive() when we output
905 * primitives other than points, calling EmitStreamVertex(0) or
906 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
907 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
908 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
911 if (prog
->Geom
.UsesStreams
&& prog
->Geom
.OutputType
!= GL_POINTS
) {
912 linker_error(prog
, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
913 "with n>0 requires point output\n");
919 validate_intrastage_arrays(struct gl_shader_program
*prog
,
920 ir_variable
*const var
,
921 ir_variable
*const existing
)
923 /* Consider the types to be "the same" if both types are arrays
924 * of the same type and one of the arrays is implicitly sized.
925 * In addition, set the type of the linked variable to the
926 * explicitly sized array.
928 if (var
->type
->is_array() && existing
->type
->is_array()) {
929 if ((var
->type
->fields
.array
== existing
->type
->fields
.array
) &&
930 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
931 if (var
->type
->length
!= 0) {
932 if ((int)var
->type
->length
<= existing
->data
.max_array_access
) {
933 linker_error(prog
, "%s `%s' declared as type "
934 "`%s' but outermost dimension has an index"
937 var
->name
, var
->type
->name
,
938 existing
->data
.max_array_access
);
940 existing
->type
= var
->type
;
942 } else if (existing
->type
->length
!= 0) {
943 if((int)existing
->type
->length
<= var
->data
.max_array_access
&&
944 !existing
->data
.from_ssbo_unsized_array
) {
945 linker_error(prog
, "%s `%s' declared as type "
946 "`%s' but outermost dimension has an index"
949 var
->name
, existing
->type
->name
,
950 var
->data
.max_array_access
);
955 /* The arrays of structs could have different glsl_type pointers but
956 * they are actually the same type. Use record_compare() to check that.
958 if (existing
->type
->fields
.array
->is_record() &&
959 var
->type
->fields
.array
->is_record() &&
960 existing
->type
->fields
.array
->record_compare(var
->type
->fields
.array
))
969 * Perform validation of global variables used across multiple shaders
972 cross_validate_globals(struct gl_shader_program
*prog
,
973 struct gl_shader
**shader_list
,
974 unsigned num_shaders
,
977 /* Examine all of the uniforms in all of the shaders and cross validate
980 glsl_symbol_table variables
;
981 for (unsigned i
= 0; i
< num_shaders
; i
++) {
982 if (shader_list
[i
] == NULL
)
985 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
986 ir_variable
*const var
= node
->as_variable();
991 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
994 /* don't cross validate subroutine uniforms */
995 if (var
->type
->contains_subroutine())
998 /* Don't cross validate temporaries that are at global scope. These
999 * will eventually get pulled into the shaders 'main'.
1001 if (var
->data
.mode
== ir_var_temporary
)
1004 /* If a global with this name has already been seen, verify that the
1005 * new instance has the same type. In addition, if the globals have
1006 * initializers, the values of the initializers must be the same.
1008 ir_variable
*const existing
= variables
.get_variable(var
->name
);
1009 if (existing
!= NULL
) {
1010 /* Check if types match. Interface blocks have some special
1011 * rules so we handle those elsewhere.
1013 if (var
->type
!= existing
->type
&&
1014 !var
->is_interface_instance()) {
1015 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
1016 if (var
->type
->is_record() && existing
->type
->is_record()
1017 && existing
->type
->record_compare(var
->type
)) {
1018 existing
->type
= var
->type
;
1020 /* If it is an unsized array in a Shader Storage Block,
1021 * two different shaders can access to different elements.
1022 * Because of that, they might be converted to different
1023 * sized arrays, then check that they are compatible but
1024 * ignore the array size.
1026 if (!(var
->data
.mode
== ir_var_shader_storage
&&
1027 var
->data
.from_ssbo_unsized_array
&&
1028 existing
->data
.mode
== ir_var_shader_storage
&&
1029 existing
->data
.from_ssbo_unsized_array
&&
1030 var
->type
->gl_type
== existing
->type
->gl_type
)) {
1031 linker_error(prog
, "%s `%s' declared as type "
1032 "`%s' and type `%s'\n",
1034 var
->name
, var
->type
->name
,
1035 existing
->type
->name
);
1042 if (var
->data
.explicit_location
) {
1043 if (existing
->data
.explicit_location
1044 && (var
->data
.location
!= existing
->data
.location
)) {
1045 linker_error(prog
, "explicit locations for %s "
1046 "`%s' have differing values\n",
1047 mode_string(var
), var
->name
);
1051 if (var
->data
.location_frac
!= existing
->data
.location_frac
) {
1052 linker_error(prog
, "explicit components for %s "
1053 "`%s' have differing values\n",
1054 mode_string(var
), var
->name
);
1058 existing
->data
.location
= var
->data
.location
;
1059 existing
->data
.explicit_location
= true;
1061 /* Check if uniform with implicit location was marked explicit
1062 * by earlier shader stage. If so, mark it explicit in this stage
1063 * too to make sure later processing does not treat it as
1066 if (existing
->data
.explicit_location
) {
1067 var
->data
.location
= existing
->data
.location
;
1068 var
->data
.explicit_location
= true;
1072 /* From the GLSL 4.20 specification:
1073 * "A link error will result if two compilation units in a program
1074 * specify different integer-constant bindings for the same
1075 * opaque-uniform name. However, it is not an error to specify a
1076 * binding on some but not all declarations for the same name"
1078 if (var
->data
.explicit_binding
) {
1079 if (existing
->data
.explicit_binding
&&
1080 var
->data
.binding
!= existing
->data
.binding
) {
1081 linker_error(prog
, "explicit bindings for %s "
1082 "`%s' have differing values\n",
1083 mode_string(var
), var
->name
);
1087 existing
->data
.binding
= var
->data
.binding
;
1088 existing
->data
.explicit_binding
= true;
1091 if (var
->type
->contains_atomic() &&
1092 var
->data
.offset
!= existing
->data
.offset
) {
1093 linker_error(prog
, "offset specifications for %s "
1094 "`%s' have differing values\n",
1095 mode_string(var
), var
->name
);
1099 /* Validate layout qualifiers for gl_FragDepth.
1101 * From the AMD/ARB_conservative_depth specs:
1103 * "If gl_FragDepth is redeclared in any fragment shader in a
1104 * program, it must be redeclared in all fragment shaders in
1105 * that program that have static assignments to
1106 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1107 * fragment shaders in a single program must have the same set
1110 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1111 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1112 bool layout_differs
=
1113 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1115 if (layout_declared
&& layout_differs
) {
1117 "All redeclarations of gl_FragDepth in all "
1118 "fragment shaders in a single program must have "
1119 "the same set of qualifiers.\n");
1122 if (var
->data
.used
&& layout_differs
) {
1124 "If gl_FragDepth is redeclared with a layout "
1125 "qualifier in any fragment shader, it must be "
1126 "redeclared with the same layout qualifier in "
1127 "all fragment shaders that have assignments to "
1132 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1134 * "If a shared global has multiple initializers, the
1135 * initializers must all be constant expressions, and they
1136 * must all have the same value. Otherwise, a link error will
1137 * result. (A shared global having only one initializer does
1138 * not require that initializer to be a constant expression.)"
1140 * Previous to 4.20 the GLSL spec simply said that initializers
1141 * must have the same value. In this case of non-constant
1142 * initializers, this was impossible to determine. As a result,
1143 * no vendor actually implemented that behavior. The 4.20
1144 * behavior matches the implemented behavior of at least one other
1145 * vendor, so we'll implement that for all GLSL versions.
1147 if (var
->constant_initializer
!= NULL
) {
1148 if (existing
->constant_initializer
!= NULL
) {
1149 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1150 linker_error(prog
, "initializers for %s "
1151 "`%s' have differing values\n",
1152 mode_string(var
), var
->name
);
1156 /* If the first-seen instance of a particular uniform did
1157 * not have an initializer but a later instance does,
1158 * replace the former with the later.
1160 variables
.replace_variable(existing
->name
, var
);
1164 if (var
->data
.has_initializer
) {
1165 if (existing
->data
.has_initializer
1166 && (var
->constant_initializer
== NULL
1167 || existing
->constant_initializer
== NULL
)) {
1169 "shared global variable `%s' has multiple "
1170 "non-constant initializers.\n",
1176 if (existing
->data
.invariant
!= var
->data
.invariant
) {
1177 linker_error(prog
, "declarations for %s `%s' have "
1178 "mismatching invariant qualifiers\n",
1179 mode_string(var
), var
->name
);
1182 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1183 linker_error(prog
, "declarations for %s `%s' have "
1184 "mismatching centroid qualifiers\n",
1185 mode_string(var
), var
->name
);
1188 if (existing
->data
.sample
!= var
->data
.sample
) {
1189 linker_error(prog
, "declarations for %s `%s` have "
1190 "mismatching sample qualifiers\n",
1191 mode_string(var
), var
->name
);
1194 if (existing
->data
.image_format
!= var
->data
.image_format
) {
1195 linker_error(prog
, "declarations for %s `%s` have "
1196 "mismatching image format qualifiers\n",
1197 mode_string(var
), var
->name
);
1201 variables
.add_variable(var
);
1208 * Perform validation of uniforms used across multiple shader stages
1211 cross_validate_uniforms(struct gl_shader_program
*prog
)
1213 cross_validate_globals(prog
, prog
->_LinkedShaders
,
1214 MESA_SHADER_STAGES
, true);
1218 * Accumulates the array of buffer blocks and checks that all definitions of
1219 * blocks agree on their contents.
1222 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
,
1225 int *InterfaceBlockStageIndex
[MESA_SHADER_STAGES
];
1226 struct gl_uniform_block
*blks
= NULL
;
1227 unsigned *num_blks
= validate_ssbo
? &prog
->NumShaderStorageBlocks
:
1228 &prog
->NumUniformBlocks
;
1230 unsigned max_num_buffer_blocks
= 0;
1231 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1232 if (prog
->_LinkedShaders
[i
]) {
1233 if (validate_ssbo
) {
1234 max_num_buffer_blocks
+=
1235 prog
->_LinkedShaders
[i
]->NumShaderStorageBlocks
;
1237 max_num_buffer_blocks
+=
1238 prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
1243 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1244 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1246 InterfaceBlockStageIndex
[i
] = new int[max_num_buffer_blocks
];
1247 for (unsigned int j
= 0; j
< max_num_buffer_blocks
; j
++)
1248 InterfaceBlockStageIndex
[i
][j
] = -1;
1253 unsigned sh_num_blocks
;
1254 struct gl_uniform_block
**sh_blks
;
1255 if (validate_ssbo
) {
1256 sh_num_blocks
= prog
->_LinkedShaders
[i
]->NumShaderStorageBlocks
;
1257 sh_blks
= sh
->ShaderStorageBlocks
;
1259 sh_num_blocks
= prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
1260 sh_blks
= sh
->UniformBlocks
;
1263 for (unsigned int j
= 0; j
< sh_num_blocks
; j
++) {
1264 int index
= link_cross_validate_uniform_block(prog
, &blks
, num_blks
,
1268 linker_error(prog
, "buffer block `%s' has mismatching "
1269 "definitions\n", sh_blks
[j
]->Name
);
1271 for (unsigned k
= 0; k
<= i
; k
++) {
1272 delete[] InterfaceBlockStageIndex
[k
];
1277 InterfaceBlockStageIndex
[i
][index
] = j
;
1281 /* Update per stage block pointers to point to the program list.
1282 * FIXME: We should be able to free the per stage blocks here.
1284 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1285 for (unsigned j
= 0; j
< *num_blks
; j
++) {
1286 int stage_index
= InterfaceBlockStageIndex
[i
][j
];
1288 if (stage_index
!= -1) {
1289 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1291 blks
[j
].stageref
|= (1 << i
);
1293 struct gl_uniform_block
**sh_blks
= validate_ssbo
?
1294 sh
->ShaderStorageBlocks
: sh
->UniformBlocks
;
1296 sh_blks
[stage_index
] = &blks
[j
];
1301 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1302 delete[] InterfaceBlockStageIndex
[i
];
1306 prog
->ShaderStorageBlocks
= blks
;
1308 prog
->UniformBlocks
= blks
;
1315 * Populates a shaders symbol table with all global declarations
1318 populate_symbol_table(gl_shader
*sh
)
1320 sh
->symbols
= new(sh
) glsl_symbol_table
;
1322 foreach_in_list(ir_instruction
, inst
, sh
->ir
) {
1326 if ((func
= inst
->as_function()) != NULL
) {
1327 sh
->symbols
->add_function(func
);
1328 } else if ((var
= inst
->as_variable()) != NULL
) {
1329 if (var
->data
.mode
!= ir_var_temporary
)
1330 sh
->symbols
->add_variable(var
);
1337 * Remap variables referenced in an instruction tree
1339 * This is used when instruction trees are cloned from one shader and placed in
1340 * another. These trees will contain references to \c ir_variable nodes that
1341 * do not exist in the target shader. This function finds these \c ir_variable
1342 * references and replaces the references with matching variables in the target
1345 * If there is no matching variable in the target shader, a clone of the
1346 * \c ir_variable is made and added to the target shader. The new variable is
1347 * added to \b both the instruction stream and the symbol table.
1349 * \param inst IR tree that is to be processed.
1350 * \param symbols Symbol table containing global scope symbols in the
1352 * \param instructions Instruction stream where new variable declarations
1356 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
1359 class remap_visitor
: public ir_hierarchical_visitor
{
1361 remap_visitor(struct gl_shader
*target
,
1364 this->target
= target
;
1365 this->symbols
= target
->symbols
;
1366 this->instructions
= target
->ir
;
1367 this->temps
= temps
;
1370 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1372 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1373 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
1375 assert(var
!= NULL
);
1377 return visit_continue
;
1380 ir_variable
*const existing
=
1381 this->symbols
->get_variable(ir
->var
->name
);
1382 if (existing
!= NULL
)
1385 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1387 this->symbols
->add_variable(copy
);
1388 this->instructions
->push_head(copy
);
1392 return visit_continue
;
1396 struct gl_shader
*target
;
1397 glsl_symbol_table
*symbols
;
1398 exec_list
*instructions
;
1402 remap_visitor
v(target
, temps
);
1409 * Move non-declarations from one instruction stream to another
1411 * The intended usage pattern of this function is to pass the pointer to the
1412 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1413 * pointer) for \c last and \c false for \c make_copies on the first
1414 * call. Successive calls pass the return value of the previous call for
1415 * \c last and \c true for \c make_copies.
1417 * \param instructions Source instruction stream
1418 * \param last Instruction after which new instructions should be
1419 * inserted in the target instruction stream
1420 * \param make_copies Flag selecting whether instructions in \c instructions
1421 * should be copied (via \c ir_instruction::clone) into the
1422 * target list or moved.
1425 * The new "last" instruction in the target instruction stream. This pointer
1426 * is suitable for use as the \c last parameter of a later call to this
1430 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1431 bool make_copies
, gl_shader
*target
)
1433 hash_table
*temps
= NULL
;
1436 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
1437 hash_table_pointer_compare
);
1439 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1440 if (inst
->as_function())
1443 ir_variable
*var
= inst
->as_variable();
1444 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1447 assert(inst
->as_assignment()
1449 || inst
->as_if() /* for initializers with the ?: operator */
1450 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1453 inst
= inst
->clone(target
, NULL
);
1456 hash_table_insert(temps
, inst
, var
);
1458 remap_variables(inst
, target
, temps
);
1463 last
->insert_after(inst
);
1468 hash_table_dtor(temps
);
1475 * This class is only used in link_intrastage_shaders() below but declaring
1476 * it inside that function leads to compiler warnings with some versions of
1479 class array_sizing_visitor
: public ir_hierarchical_visitor
{
1481 array_sizing_visitor()
1482 : mem_ctx(ralloc_context(NULL
)),
1483 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash
,
1484 hash_table_pointer_compare
))
1488 ~array_sizing_visitor()
1490 hash_table_dtor(this->unnamed_interfaces
);
1491 ralloc_free(this->mem_ctx
);
1494 virtual ir_visitor_status
visit(ir_variable
*var
)
1496 const glsl_type
*type_without_array
;
1497 fixup_type(&var
->type
, var
->data
.max_array_access
,
1498 var
->data
.from_ssbo_unsized_array
);
1499 type_without_array
= var
->type
->without_array();
1500 if (var
->type
->is_interface()) {
1501 if (interface_contains_unsized_arrays(var
->type
)) {
1502 const glsl_type
*new_type
=
1503 resize_interface_members(var
->type
,
1504 var
->get_max_ifc_array_access(),
1505 var
->is_in_shader_storage_block());
1506 var
->type
= new_type
;
1507 var
->change_interface_type(new_type
);
1509 } else if (type_without_array
->is_interface()) {
1510 if (interface_contains_unsized_arrays(type_without_array
)) {
1511 const glsl_type
*new_type
=
1512 resize_interface_members(type_without_array
,
1513 var
->get_max_ifc_array_access(),
1514 var
->is_in_shader_storage_block());
1515 var
->change_interface_type(new_type
);
1516 var
->type
= update_interface_members_array(var
->type
, new_type
);
1518 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1519 /* Store a pointer to the variable in the unnamed_interfaces
1522 ir_variable
**interface_vars
= (ir_variable
**)
1523 hash_table_find(this->unnamed_interfaces
, ifc_type
);
1524 if (interface_vars
== NULL
) {
1525 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1527 hash_table_insert(this->unnamed_interfaces
, interface_vars
,
1530 unsigned index
= ifc_type
->field_index(var
->name
);
1531 assert(index
< ifc_type
->length
);
1532 assert(interface_vars
[index
] == NULL
);
1533 interface_vars
[index
] = var
;
1535 return visit_continue
;
1539 * For each unnamed interface block that was discovered while running the
1540 * visitor, adjust the interface type to reflect the newly assigned array
1541 * sizes, and fix up the ir_variable nodes to point to the new interface
1544 void fixup_unnamed_interface_types()
1546 hash_table_call_foreach(this->unnamed_interfaces
,
1547 fixup_unnamed_interface_type
, NULL
);
1552 * If the type pointed to by \c type represents an unsized array, replace
1553 * it with a sized array whose size is determined by max_array_access.
1555 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1556 bool from_ssbo_unsized_array
)
1558 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1559 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1560 max_array_access
+ 1);
1561 assert(*type
!= NULL
);
1565 static const glsl_type
*
1566 update_interface_members_array(const glsl_type
*type
,
1567 const glsl_type
*new_interface_type
)
1569 const glsl_type
*element_type
= type
->fields
.array
;
1570 if (element_type
->is_array()) {
1571 const glsl_type
*new_array_type
=
1572 update_interface_members_array(element_type
, new_interface_type
);
1573 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1575 return glsl_type::get_array_instance(new_interface_type
,
1581 * Determine whether the given interface type contains unsized arrays (if
1582 * it doesn't, array_sizing_visitor doesn't need to process it).
1584 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1586 for (unsigned i
= 0; i
< type
->length
; i
++) {
1587 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1588 if (elem_type
->is_unsized_array())
1595 * Create a new interface type based on the given type, with unsized arrays
1596 * replaced by sized arrays whose size is determined by
1597 * max_ifc_array_access.
1599 static const glsl_type
*
1600 resize_interface_members(const glsl_type
*type
,
1601 const int *max_ifc_array_access
,
1604 unsigned num_fields
= type
->length
;
1605 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1606 memcpy(fields
, type
->fields
.structure
,
1607 num_fields
* sizeof(*fields
));
1608 for (unsigned i
= 0; i
< num_fields
; i
++) {
1609 /* If SSBO last member is unsized array, we don't replace it by a sized
1612 if (is_ssbo
&& i
== (num_fields
- 1))
1613 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1616 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1619 glsl_interface_packing packing
=
1620 (glsl_interface_packing
) type
->interface_packing
;
1621 const glsl_type
*new_ifc_type
=
1622 glsl_type::get_interface_instance(fields
, num_fields
,
1623 packing
, type
->name
);
1625 return new_ifc_type
;
1628 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1631 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1632 ir_variable
**interface_vars
= (ir_variable
**) data
;
1633 unsigned num_fields
= ifc_type
->length
;
1634 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1635 memcpy(fields
, ifc_type
->fields
.structure
,
1636 num_fields
* sizeof(*fields
));
1637 bool interface_type_changed
= false;
1638 for (unsigned i
= 0; i
< num_fields
; i
++) {
1639 if (interface_vars
[i
] != NULL
&&
1640 fields
[i
].type
!= interface_vars
[i
]->type
) {
1641 fields
[i
].type
= interface_vars
[i
]->type
;
1642 interface_type_changed
= true;
1645 if (!interface_type_changed
) {
1649 glsl_interface_packing packing
=
1650 (glsl_interface_packing
) ifc_type
->interface_packing
;
1651 const glsl_type
*new_ifc_type
=
1652 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1655 for (unsigned i
= 0; i
< num_fields
; i
++) {
1656 if (interface_vars
[i
] != NULL
)
1657 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1662 * Memory context used to allocate the data in \c unnamed_interfaces.
1667 * Hash table from const glsl_type * to an array of ir_variable *'s
1668 * pointing to the ir_variables constituting each unnamed interface block.
1670 hash_table
*unnamed_interfaces
;
1674 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1678 link_xfb_stride_layout_qualifiers(struct gl_context
*ctx
,
1679 struct gl_shader_program
*prog
,
1680 struct gl_shader
*linked_shader
,
1681 struct gl_shader
**shader_list
,
1682 unsigned num_shaders
)
1684 for (unsigned i
= 0; i
< MAX_FEEDBACK_BUFFERS
; i
++) {
1685 linked_shader
->TransformFeedback
.BufferStride
[i
] = 0;
1688 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1689 struct gl_shader
*shader
= shader_list
[i
];
1691 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1692 if (shader
->TransformFeedback
.BufferStride
[j
]) {
1693 if (linked_shader
->TransformFeedback
.BufferStride
[j
] != 0 &&
1694 shader
->TransformFeedback
.BufferStride
[j
] != 0 &&
1695 linked_shader
->TransformFeedback
.BufferStride
[j
] !=
1696 shader
->TransformFeedback
.BufferStride
[j
]) {
1698 "intrastage shaders defined with conflicting "
1699 "xfb_stride for buffer %d (%d and %d)\n", j
,
1700 linked_shader
->TransformFeedback
.BufferStride
[j
],
1701 shader
->TransformFeedback
.BufferStride
[j
]);
1705 if (shader
->TransformFeedback
.BufferStride
[j
])
1706 linked_shader
->TransformFeedback
.BufferStride
[j
] =
1707 shader
->TransformFeedback
.BufferStride
[j
];
1712 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1713 if (linked_shader
->TransformFeedback
.BufferStride
[j
]) {
1714 prog
->TransformFeedback
.BufferStride
[j
] =
1715 linked_shader
->TransformFeedback
.BufferStride
[j
];
1717 /* We will validate doubles at a later stage */
1718 if (prog
->TransformFeedback
.BufferStride
[j
] % 4) {
1719 linker_error(prog
, "invalid qualifier xfb_stride=%d must be a "
1720 "multiple of 4 or if its applied to a type that is "
1721 "or contains a double a multiple of 8.",
1722 prog
->TransformFeedback
.BufferStride
[j
]);
1726 if (prog
->TransformFeedback
.BufferStride
[j
] / 4 >
1727 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1729 "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1730 "limit has been exceeded.");
1738 * Performs the cross-validation of tessellation control shader vertices and
1739 * layout qualifiers for the attached tessellation control shaders,
1740 * and propagates them to the linked TCS and linked shader program.
1743 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1744 struct gl_shader
*linked_shader
,
1745 struct gl_shader
**shader_list
,
1746 unsigned num_shaders
)
1748 linked_shader
->TessCtrl
.VerticesOut
= 0;
1750 if (linked_shader
->Stage
!= MESA_SHADER_TESS_CTRL
)
1753 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1755 * "All tessellation control shader layout declarations in a program
1756 * must specify the same output patch vertex count. There must be at
1757 * least one layout qualifier specifying an output patch vertex count
1758 * in any program containing tessellation control shaders; however,
1759 * such a declaration is not required in all tessellation control
1763 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1764 struct gl_shader
*shader
= shader_list
[i
];
1766 if (shader
->TessCtrl
.VerticesOut
!= 0) {
1767 if (linked_shader
->TessCtrl
.VerticesOut
!= 0 &&
1768 linked_shader
->TessCtrl
.VerticesOut
!= shader
->TessCtrl
.VerticesOut
) {
1769 linker_error(prog
, "tessellation control shader defined with "
1770 "conflicting output vertex count (%d and %d)\n",
1771 linked_shader
->TessCtrl
.VerticesOut
,
1772 shader
->TessCtrl
.VerticesOut
);
1775 linked_shader
->TessCtrl
.VerticesOut
= shader
->TessCtrl
.VerticesOut
;
1779 /* Just do the intrastage -> interstage propagation right now,
1780 * since we already know we're in the right type of shader program
1783 if (linked_shader
->TessCtrl
.VerticesOut
== 0) {
1784 linker_error(prog
, "tessellation control shader didn't declare "
1785 "vertices out layout qualifier\n");
1788 prog
->TessCtrl
.VerticesOut
= linked_shader
->TessCtrl
.VerticesOut
;
1793 * Performs the cross-validation of tessellation evaluation shader
1794 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1795 * for the attached tessellation evaluation shaders, and propagates them
1796 * to the linked TES and linked shader program.
1799 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1800 struct gl_shader
*linked_shader
,
1801 struct gl_shader
**shader_list
,
1802 unsigned num_shaders
)
1804 linked_shader
->TessEval
.PrimitiveMode
= PRIM_UNKNOWN
;
1805 linked_shader
->TessEval
.Spacing
= 0;
1806 linked_shader
->TessEval
.VertexOrder
= 0;
1807 linked_shader
->TessEval
.PointMode
= -1;
1809 if (linked_shader
->Stage
!= MESA_SHADER_TESS_EVAL
)
1812 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1814 * "At least one tessellation evaluation shader (compilation unit) in
1815 * a program must declare a primitive mode in its input layout.
1816 * Declaration vertex spacing, ordering, and point mode identifiers is
1817 * optional. It is not required that all tessellation evaluation
1818 * shaders in a program declare a primitive mode. If spacing or
1819 * vertex ordering declarations are omitted, the tessellation
1820 * primitive generator will use equal spacing or counter-clockwise
1821 * vertex ordering, respectively. If a point mode declaration is
1822 * omitted, the tessellation primitive generator will produce lines or
1823 * triangles according to the primitive mode."
1826 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1827 struct gl_shader
*shader
= shader_list
[i
];
1829 if (shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1830 if (linked_shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
&&
1831 linked_shader
->TessEval
.PrimitiveMode
!= shader
->TessEval
.PrimitiveMode
) {
1832 linker_error(prog
, "tessellation evaluation shader defined with "
1833 "conflicting input primitive modes.\n");
1836 linked_shader
->TessEval
.PrimitiveMode
= shader
->TessEval
.PrimitiveMode
;
1839 if (shader
->TessEval
.Spacing
!= 0) {
1840 if (linked_shader
->TessEval
.Spacing
!= 0 &&
1841 linked_shader
->TessEval
.Spacing
!= shader
->TessEval
.Spacing
) {
1842 linker_error(prog
, "tessellation evaluation shader defined with "
1843 "conflicting vertex spacing.\n");
1846 linked_shader
->TessEval
.Spacing
= shader
->TessEval
.Spacing
;
1849 if (shader
->TessEval
.VertexOrder
!= 0) {
1850 if (linked_shader
->TessEval
.VertexOrder
!= 0 &&
1851 linked_shader
->TessEval
.VertexOrder
!= shader
->TessEval
.VertexOrder
) {
1852 linker_error(prog
, "tessellation evaluation shader defined with "
1853 "conflicting ordering.\n");
1856 linked_shader
->TessEval
.VertexOrder
= shader
->TessEval
.VertexOrder
;
1859 if (shader
->TessEval
.PointMode
!= -1) {
1860 if (linked_shader
->TessEval
.PointMode
!= -1 &&
1861 linked_shader
->TessEval
.PointMode
!= shader
->TessEval
.PointMode
) {
1862 linker_error(prog
, "tessellation evaluation shader defined with "
1863 "conflicting point modes.\n");
1866 linked_shader
->TessEval
.PointMode
= shader
->TessEval
.PointMode
;
1871 /* Just do the intrastage -> interstage propagation right now,
1872 * since we already know we're in the right type of shader program
1875 if (linked_shader
->TessEval
.PrimitiveMode
== PRIM_UNKNOWN
) {
1877 "tessellation evaluation shader didn't declare input "
1878 "primitive modes.\n");
1881 prog
->TessEval
.PrimitiveMode
= linked_shader
->TessEval
.PrimitiveMode
;
1883 if (linked_shader
->TessEval
.Spacing
== 0)
1884 linked_shader
->TessEval
.Spacing
= GL_EQUAL
;
1885 prog
->TessEval
.Spacing
= linked_shader
->TessEval
.Spacing
;
1887 if (linked_shader
->TessEval
.VertexOrder
== 0)
1888 linked_shader
->TessEval
.VertexOrder
= GL_CCW
;
1889 prog
->TessEval
.VertexOrder
= linked_shader
->TessEval
.VertexOrder
;
1891 if (linked_shader
->TessEval
.PointMode
== -1)
1892 linked_shader
->TessEval
.PointMode
= GL_FALSE
;
1893 prog
->TessEval
.PointMode
= linked_shader
->TessEval
.PointMode
;
1898 * Performs the cross-validation of layout qualifiers specified in
1899 * redeclaration of gl_FragCoord for the attached fragment shaders,
1900 * and propagates them to the linked FS and linked shader program.
1903 link_fs_input_layout_qualifiers(struct gl_shader_program
*prog
,
1904 struct gl_shader
*linked_shader
,
1905 struct gl_shader
**shader_list
,
1906 unsigned num_shaders
)
1908 linked_shader
->redeclares_gl_fragcoord
= false;
1909 linked_shader
->uses_gl_fragcoord
= false;
1910 linked_shader
->origin_upper_left
= false;
1911 linked_shader
->pixel_center_integer
= false;
1913 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1914 (prog
->Version
< 150 && !prog
->ARB_fragment_coord_conventions_enable
))
1917 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1918 struct gl_shader
*shader
= shader_list
[i
];
1919 /* From the GLSL 1.50 spec, page 39:
1921 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1922 * it must be redeclared in all the fragment shaders in that program
1923 * that have a static use gl_FragCoord."
1925 if ((linked_shader
->redeclares_gl_fragcoord
1926 && !shader
->redeclares_gl_fragcoord
1927 && shader
->uses_gl_fragcoord
)
1928 || (shader
->redeclares_gl_fragcoord
1929 && !linked_shader
->redeclares_gl_fragcoord
1930 && linked_shader
->uses_gl_fragcoord
)) {
1931 linker_error(prog
, "fragment shader defined with conflicting "
1932 "layout qualifiers for gl_FragCoord\n");
1935 /* From the GLSL 1.50 spec, page 39:
1937 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1938 * single program must have the same set of qualifiers."
1940 if (linked_shader
->redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
1941 && (shader
->origin_upper_left
!= linked_shader
->origin_upper_left
1942 || shader
->pixel_center_integer
!= linked_shader
->pixel_center_integer
)) {
1943 linker_error(prog
, "fragment shader defined with conflicting "
1944 "layout qualifiers for gl_FragCoord\n");
1947 /* Update the linked shader state. Note that uses_gl_fragcoord should
1948 * accumulate the results. The other values should replace. If there
1949 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1950 * are already known to be the same.
1952 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
1953 linked_shader
->redeclares_gl_fragcoord
=
1954 shader
->redeclares_gl_fragcoord
;
1955 linked_shader
->uses_gl_fragcoord
= linked_shader
->uses_gl_fragcoord
1956 || shader
->uses_gl_fragcoord
;
1957 linked_shader
->origin_upper_left
= shader
->origin_upper_left
;
1958 linked_shader
->pixel_center_integer
= shader
->pixel_center_integer
;
1961 linked_shader
->EarlyFragmentTests
|= shader
->EarlyFragmentTests
;
1966 * Performs the cross-validation of geometry shader max_vertices and
1967 * primitive type layout qualifiers for the attached geometry shaders,
1968 * and propagates them to the linked GS and linked shader program.
1971 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1972 struct gl_shader
*linked_shader
,
1973 struct gl_shader
**shader_list
,
1974 unsigned num_shaders
)
1976 linked_shader
->Geom
.VerticesOut
= 0;
1977 linked_shader
->Geom
.Invocations
= 0;
1978 linked_shader
->Geom
.InputType
= PRIM_UNKNOWN
;
1979 linked_shader
->Geom
.OutputType
= PRIM_UNKNOWN
;
1981 /* No in/out qualifiers defined for anything but GLSL 1.50+
1982 * geometry shaders so far.
1984 if (linked_shader
->Stage
!= MESA_SHADER_GEOMETRY
|| prog
->Version
< 150)
1987 /* From the GLSL 1.50 spec, page 46:
1989 * "All geometry shader output layout declarations in a program
1990 * must declare the same layout and same value for
1991 * max_vertices. There must be at least one geometry output
1992 * layout declaration somewhere in a program, but not all
1993 * geometry shaders (compilation units) are required to
1997 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1998 struct gl_shader
*shader
= shader_list
[i
];
2000 if (shader
->Geom
.InputType
!= PRIM_UNKNOWN
) {
2001 if (linked_shader
->Geom
.InputType
!= PRIM_UNKNOWN
&&
2002 linked_shader
->Geom
.InputType
!= shader
->Geom
.InputType
) {
2003 linker_error(prog
, "geometry shader defined with conflicting "
2007 linked_shader
->Geom
.InputType
= shader
->Geom
.InputType
;
2010 if (shader
->Geom
.OutputType
!= PRIM_UNKNOWN
) {
2011 if (linked_shader
->Geom
.OutputType
!= PRIM_UNKNOWN
&&
2012 linked_shader
->Geom
.OutputType
!= shader
->Geom
.OutputType
) {
2013 linker_error(prog
, "geometry shader defined with conflicting "
2017 linked_shader
->Geom
.OutputType
= shader
->Geom
.OutputType
;
2020 if (shader
->Geom
.VerticesOut
!= 0) {
2021 if (linked_shader
->Geom
.VerticesOut
!= 0 &&
2022 linked_shader
->Geom
.VerticesOut
!= shader
->Geom
.VerticesOut
) {
2023 linker_error(prog
, "geometry shader defined with conflicting "
2024 "output vertex count (%d and %d)\n",
2025 linked_shader
->Geom
.VerticesOut
,
2026 shader
->Geom
.VerticesOut
);
2029 linked_shader
->Geom
.VerticesOut
= shader
->Geom
.VerticesOut
;
2032 if (shader
->Geom
.Invocations
!= 0) {
2033 if (linked_shader
->Geom
.Invocations
!= 0 &&
2034 linked_shader
->Geom
.Invocations
!= shader
->Geom
.Invocations
) {
2035 linker_error(prog
, "geometry shader defined with conflicting "
2036 "invocation count (%d and %d)\n",
2037 linked_shader
->Geom
.Invocations
,
2038 shader
->Geom
.Invocations
);
2041 linked_shader
->Geom
.Invocations
= shader
->Geom
.Invocations
;
2045 /* Just do the intrastage -> interstage propagation right now,
2046 * since we already know we're in the right type of shader program
2049 if (linked_shader
->Geom
.InputType
== PRIM_UNKNOWN
) {
2051 "geometry shader didn't declare primitive input type\n");
2054 prog
->Geom
.InputType
= linked_shader
->Geom
.InputType
;
2056 if (linked_shader
->Geom
.OutputType
== PRIM_UNKNOWN
) {
2058 "geometry shader didn't declare primitive output type\n");
2061 prog
->Geom
.OutputType
= linked_shader
->Geom
.OutputType
;
2063 if (linked_shader
->Geom
.VerticesOut
== 0) {
2065 "geometry shader didn't declare max_vertices\n");
2068 prog
->Geom
.VerticesOut
= linked_shader
->Geom
.VerticesOut
;
2070 if (linked_shader
->Geom
.Invocations
== 0)
2071 linked_shader
->Geom
.Invocations
= 1;
2073 prog
->Geom
.Invocations
= linked_shader
->Geom
.Invocations
;
2078 * Perform cross-validation of compute shader local_size_{x,y,z} layout
2079 * qualifiers for the attached compute shaders, and propagate them to the
2080 * linked CS and linked shader program.
2083 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
2084 struct gl_shader
*linked_shader
,
2085 struct gl_shader
**shader_list
,
2086 unsigned num_shaders
)
2088 for (int i
= 0; i
< 3; i
++)
2089 linked_shader
->Comp
.LocalSize
[i
] = 0;
2091 /* This function is called for all shader stages, but it only has an effect
2092 * for compute shaders.
2094 if (linked_shader
->Stage
!= MESA_SHADER_COMPUTE
)
2097 /* From the ARB_compute_shader spec, in the section describing local size
2100 * If multiple compute shaders attached to a single program object
2101 * declare local work-group size, the declarations must be identical;
2102 * otherwise a link-time error results. Furthermore, if a program
2103 * object contains any compute shaders, at least one must contain an
2104 * input layout qualifier specifying the local work sizes of the
2105 * program, or a link-time error will occur.
2107 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
2108 struct gl_shader
*shader
= shader_list
[sh
];
2110 if (shader
->Comp
.LocalSize
[0] != 0) {
2111 if (linked_shader
->Comp
.LocalSize
[0] != 0) {
2112 for (int i
= 0; i
< 3; i
++) {
2113 if (linked_shader
->Comp
.LocalSize
[i
] !=
2114 shader
->Comp
.LocalSize
[i
]) {
2115 linker_error(prog
, "compute shader defined with conflicting "
2121 for (int i
= 0; i
< 3; i
++)
2122 linked_shader
->Comp
.LocalSize
[i
] = shader
->Comp
.LocalSize
[i
];
2126 /* Just do the intrastage -> interstage propagation right now,
2127 * since we already know we're in the right type of shader program
2130 if (linked_shader
->Comp
.LocalSize
[0] == 0) {
2131 linker_error(prog
, "compute shader didn't declare local size\n");
2134 for (int i
= 0; i
< 3; i
++)
2135 prog
->Comp
.LocalSize
[i
] = linked_shader
->Comp
.LocalSize
[i
];
2140 * Combine a group of shaders for a single stage to generate a linked shader
2143 * If this function is supplied a single shader, it is cloned, and the new
2144 * shader is returned.
2146 static struct gl_shader
*
2147 link_intrastage_shaders(void *mem_ctx
,
2148 struct gl_context
*ctx
,
2149 struct gl_shader_program
*prog
,
2150 struct gl_shader
**shader_list
,
2151 unsigned num_shaders
)
2153 struct gl_uniform_block
*ubo_blocks
= NULL
;
2154 struct gl_uniform_block
*ssbo_blocks
= NULL
;
2155 unsigned num_ubo_blocks
= 0;
2156 unsigned num_ssbo_blocks
= 0;
2158 /* Check that global variables defined in multiple shaders are consistent.
2160 cross_validate_globals(prog
, shader_list
, num_shaders
, false);
2161 if (!prog
->LinkStatus
)
2164 /* Check that interface blocks defined in multiple shaders are consistent.
2166 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
2168 if (!prog
->LinkStatus
)
2171 /* Link up uniform blocks defined within this stage. */
2172 link_uniform_blocks(mem_ctx
, ctx
, prog
, shader_list
, num_shaders
,
2173 &ubo_blocks
, &num_ubo_blocks
, &ssbo_blocks
,
2176 if (!prog
->LinkStatus
)
2179 /* Check that there is only a single definition of each function signature
2180 * across all shaders.
2182 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2183 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2184 ir_function
*const f
= node
->as_function();
2189 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2190 ir_function
*const other
=
2191 shader_list
[j
]->symbols
->get_function(f
->name
);
2193 /* If the other shader has no function (and therefore no function
2194 * signatures) with the same name, skip to the next shader.
2199 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2200 if (!sig
->is_defined
|| sig
->is_builtin())
2203 ir_function_signature
*other_sig
=
2204 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2206 if ((other_sig
!= NULL
) && other_sig
->is_defined
2207 && !other_sig
->is_builtin()) {
2208 linker_error(prog
, "function `%s' is multiply defined\n",
2217 /* Find the shader that defines main, and make a clone of it.
2219 * Starting with the clone, search for undefined references. If one is
2220 * found, find the shader that defines it. Clone the reference and add
2221 * it to the shader. Repeat until there are no undefined references or
2222 * until a reference cannot be resolved.
2224 gl_shader
*main
= NULL
;
2225 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2226 if (_mesa_get_main_function_signature(shader_list
[i
]) != NULL
) {
2227 main
= shader_list
[i
];
2233 linker_error(prog
, "%s shader lacks `main'\n",
2234 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2238 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
2239 linked
->ir
= new(linked
) exec_list
;
2240 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2242 /* Copy ubo blocks to linked shader list */
2243 linked
->UniformBlocks
=
2244 ralloc_array(linked
, gl_uniform_block
*, num_ubo_blocks
);
2245 ralloc_steal(linked
, ubo_blocks
);
2246 for (unsigned i
= 0; i
< num_ubo_blocks
; i
++) {
2247 linked
->UniformBlocks
[i
] = &ubo_blocks
[i
];
2249 linked
->NumUniformBlocks
= num_ubo_blocks
;
2251 /* Copy ssbo blocks to linked shader list */
2252 linked
->ShaderStorageBlocks
=
2253 ralloc_array(linked
, gl_uniform_block
*, num_ssbo_blocks
);
2254 ralloc_steal(linked
, ssbo_blocks
);
2255 for (unsigned i
= 0; i
< num_ssbo_blocks
; i
++) {
2256 linked
->ShaderStorageBlocks
[i
] = &ssbo_blocks
[i
];
2258 linked
->NumShaderStorageBlocks
= num_ssbo_blocks
;
2260 link_fs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2261 link_tcs_out_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2262 link_tes_in_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2263 link_gs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2264 link_cs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2265 link_xfb_stride_layout_qualifiers(ctx
, prog
, linked
, shader_list
,
2268 populate_symbol_table(linked
);
2270 /* The pointer to the main function in the final linked shader (i.e., the
2271 * copy of the original shader that contained the main function).
2273 ir_function_signature
*const main_sig
=
2274 _mesa_get_main_function_signature(linked
);
2276 /* Move any instructions other than variable declarations or function
2277 * declarations into main.
2279 exec_node
*insertion_point
=
2280 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2283 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2284 if (shader_list
[i
] == main
)
2287 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2288 insertion_point
, true, linked
);
2291 /* Check if any shader needs built-in functions. */
2292 bool need_builtins
= false;
2293 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2294 if (shader_list
[i
]->uses_builtin_functions
) {
2295 need_builtins
= true;
2301 if (need_builtins
) {
2302 /* Make a temporary array one larger than shader_list, which will hold
2303 * the built-in function shader as well.
2305 gl_shader
**linking_shaders
= (gl_shader
**)
2306 calloc(num_shaders
+ 1, sizeof(gl_shader
*));
2308 ok
= linking_shaders
!= NULL
;
2311 memcpy(linking_shaders
, shader_list
, num_shaders
* sizeof(gl_shader
*));
2312 _mesa_glsl_initialize_builtin_functions();
2313 linking_shaders
[num_shaders
] = _mesa_glsl_get_builtin_function_shader();
2315 ok
= link_function_calls(prog
, linked
, linking_shaders
, num_shaders
+ 1);
2317 free(linking_shaders
);
2319 _mesa_error_no_memory(__func__
);
2322 ok
= link_function_calls(prog
, linked
, shader_list
, num_shaders
);
2327 _mesa_delete_shader(ctx
, linked
);
2331 /* At this point linked should contain all of the linked IR, so
2332 * validate it to make sure nothing went wrong.
2334 validate_ir_tree(linked
->ir
);
2336 /* Set the size of geometry shader input arrays */
2337 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2338 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
2339 geom_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2340 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2341 ir
->accept(&input_resize_visitor
);
2345 if (ctx
->Const
.VertexID_is_zero_based
)
2346 lower_vertex_id(linked
);
2348 /* Validate correct usage of barrier() in the tess control shader */
2349 if (linked
->Stage
== MESA_SHADER_TESS_CTRL
) {
2350 barrier_use_visitor
visitor(prog
);
2351 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2352 ir
->accept(&visitor
);
2356 /* Make a pass over all variable declarations to ensure that arrays with
2357 * unspecified sizes have a size specified. The size is inferred from the
2358 * max_array_access field.
2360 array_sizing_visitor v
;
2362 v
.fixup_unnamed_interface_types();
2368 * Update the sizes of linked shader uniform arrays to the maximum
2371 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2373 * If one or more elements of an array are active,
2374 * GetActiveUniform will return the name of the array in name,
2375 * subject to the restrictions listed above. The type of the array
2376 * is returned in type. The size parameter contains the highest
2377 * array element index used, plus one. The compiler or linker
2378 * determines the highest index used. There will be only one
2379 * active uniform reported by the GL per uniform array.
2383 update_array_sizes(struct gl_shader_program
*prog
)
2385 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2386 if (prog
->_LinkedShaders
[i
] == NULL
)
2389 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2390 ir_variable
*const var
= node
->as_variable();
2392 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2393 !var
->type
->is_array())
2396 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2397 * will not be eliminated. Since we always do std140, just
2398 * don't resize arrays in UBOs.
2400 * Atomic counters are supposed to get deterministic
2401 * locations assigned based on the declaration ordering and
2402 * sizes, array compaction would mess that up.
2404 * Subroutine uniforms are not removed.
2406 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2407 var
->type
->contains_subroutine() || var
->constant_initializer
)
2410 int size
= var
->data
.max_array_access
;
2411 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2412 if (prog
->_LinkedShaders
[j
] == NULL
)
2415 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2416 ir_variable
*other_var
= node2
->as_variable();
2420 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2421 other_var
->data
.max_array_access
> size
) {
2422 size
= other_var
->data
.max_array_access
;
2427 if (size
+ 1 != (int)var
->type
->length
) {
2428 /* If this is a built-in uniform (i.e., it's backed by some
2429 * fixed-function state), adjust the number of state slots to
2430 * match the new array size. The number of slots per array entry
2431 * is not known. It seems safe to assume that the total number of
2432 * slots is an integer multiple of the number of array elements.
2433 * Determine the number of slots per array element by dividing by
2434 * the old (total) size.
2436 const unsigned num_slots
= var
->get_num_state_slots();
2437 if (num_slots
> 0) {
2438 var
->set_num_state_slots((size
+ 1)
2439 * (num_slots
/ var
->type
->length
));
2442 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2444 /* FINISHME: We should update the types of array
2445 * dereferences of this variable now.
2453 * Resize tessellation evaluation per-vertex inputs to the size of
2454 * tessellation control per-vertex outputs.
2457 resize_tes_inputs(struct gl_context
*ctx
,
2458 struct gl_shader_program
*prog
)
2460 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2463 gl_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2464 gl_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2466 /* If no control shader is present, then the TES inputs are statically
2467 * sized to MaxPatchVertices; the actual size of the arrays won't be
2468 * known until draw time.
2470 const int num_vertices
= tcs
2471 ? tcs
->TessCtrl
.VerticesOut
2472 : ctx
->Const
.MaxPatchVertices
;
2474 tess_eval_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2475 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2476 ir
->accept(&input_resize_visitor
);
2480 /* Convert the gl_PatchVerticesIn system value into a constant, since
2481 * the value is known at this point.
2483 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2484 ir_variable
*var
= ir
->as_variable();
2485 if (var
&& var
->data
.mode
== ir_var_system_value
&&
2486 var
->data
.location
== SYSTEM_VALUE_VERTICES_IN
) {
2487 void *mem_ctx
= ralloc_parent(var
);
2488 var
->data
.mode
= ir_var_auto
;
2489 var
->data
.location
= 0;
2490 var
->constant_value
= new(mem_ctx
) ir_constant(num_vertices
);
2497 * Find a contiguous set of available bits in a bitmask.
2499 * \param used_mask Bits representing used (1) and unused (0) locations
2500 * \param needed_count Number of contiguous bits needed.
2503 * Base location of the available bits on success or -1 on failure.
2506 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2508 unsigned needed_mask
= (1 << needed_count
) - 1;
2509 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2511 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2512 * cannot optimize possibly infinite loops" for the loop below.
2514 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2517 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2518 if ((needed_mask
& ~used_mask
) == needed_mask
)
2529 * Assign locations for either VS inputs or FS outputs
2531 * \param prog Shader program whose variables need locations assigned
2532 * \param constants Driver specific constant values for the program.
2533 * \param target_index Selector for the program target to receive location
2534 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2535 * \c MESA_SHADER_FRAGMENT.
2538 * If locations are successfully assigned, true is returned. Otherwise an
2539 * error is emitted to the shader link log and false is returned.
2542 assign_attribute_or_color_locations(gl_shader_program
*prog
,
2543 struct gl_constants
*constants
,
2544 unsigned target_index
)
2546 /* Maximum number of generic locations. This corresponds to either the
2547 * maximum number of draw buffers or the maximum number of generic
2550 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2551 constants
->Program
[target_index
].MaxAttribs
:
2552 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2554 /* Mark invalid locations as being used.
2556 unsigned used_locations
= (max_index
>= 32)
2557 ? ~0 : ~((1 << max_index
) - 1);
2558 unsigned double_storage_locations
= 0;
2560 assert((target_index
== MESA_SHADER_VERTEX
)
2561 || (target_index
== MESA_SHADER_FRAGMENT
));
2563 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2567 /* Operate in a total of four passes.
2569 * 1. Invalidate the location assignments for all vertex shader inputs.
2571 * 2. Assign locations for inputs that have user-defined (via
2572 * glBindVertexAttribLocation) locations and outputs that have
2573 * user-defined locations (via glBindFragDataLocation).
2575 * 3. Sort the attributes without assigned locations by number of slots
2576 * required in decreasing order. Fragmentation caused by attribute
2577 * locations assigned by the application may prevent large attributes
2578 * from having enough contiguous space.
2580 * 4. Assign locations to any inputs without assigned locations.
2583 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2584 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2586 const enum ir_variable_mode direction
=
2587 (target_index
== MESA_SHADER_VERTEX
)
2588 ? ir_var_shader_in
: ir_var_shader_out
;
2591 /* Temporary storage for the set of attributes that need locations assigned.
2597 /* Used below in the call to qsort. */
2598 static int compare(const void *a
, const void *b
)
2600 const temp_attr
*const l
= (const temp_attr
*) a
;
2601 const temp_attr
*const r
= (const temp_attr
*) b
;
2603 /* Reversed because we want a descending order sort below. */
2604 return r
->slots
- l
->slots
;
2607 assert(max_index
<= 32);
2609 unsigned num_attr
= 0;
2611 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2612 ir_variable
*const var
= node
->as_variable();
2614 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2617 if (var
->data
.explicit_location
) {
2618 var
->data
.is_unmatched_generic_inout
= 0;
2619 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2620 || (var
->data
.location
< 0)) {
2622 "invalid explicit location %d specified for `%s'\n",
2623 (var
->data
.location
< 0)
2624 ? var
->data
.location
2625 : var
->data
.location
- generic_base
,
2629 } else if (target_index
== MESA_SHADER_VERTEX
) {
2632 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2633 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2634 var
->data
.location
= binding
;
2635 var
->data
.is_unmatched_generic_inout
= 0;
2637 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2641 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
2642 assert(binding
>= FRAG_RESULT_DATA0
);
2643 var
->data
.location
= binding
;
2644 var
->data
.is_unmatched_generic_inout
= 0;
2646 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
2647 var
->data
.index
= index
;
2652 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2654 * "Output binding assignments will cause LinkProgram to fail:
2656 * If the program has an active output assigned to a location greater
2657 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2658 * an active output assigned an index greater than or equal to one;"
2660 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2661 var
->data
.location
- generic_base
>=
2662 (int) constants
->MaxDualSourceDrawBuffers
) {
2664 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2665 "with index %u for %s\n",
2666 var
->data
.location
- generic_base
, var
->data
.index
,
2671 const unsigned slots
= var
->type
->count_attribute_slots(target_index
== MESA_SHADER_VERTEX
);
2673 /* If the variable is not a built-in and has a location statically
2674 * assigned in the shader (presumably via a layout qualifier), make sure
2675 * that it doesn't collide with other assigned locations. Otherwise,
2676 * add it to the list of variables that need linker-assigned locations.
2678 if (var
->data
.location
!= -1) {
2679 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2680 /* From page 61 of the OpenGL 4.0 spec:
2682 * "LinkProgram will fail if the attribute bindings assigned
2683 * by BindAttribLocation do not leave not enough space to
2684 * assign a location for an active matrix attribute or an
2685 * active attribute array, both of which require multiple
2686 * contiguous generic attributes."
2688 * I think above text prohibits the aliasing of explicit and
2689 * automatic assignments. But, aliasing is allowed in manual
2690 * assignments of attribute locations. See below comments for
2693 * From OpenGL 4.0 spec, page 61:
2695 * "It is possible for an application to bind more than one
2696 * attribute name to the same location. This is referred to as
2697 * aliasing. This will only work if only one of the aliased
2698 * attributes is active in the executable program, or if no
2699 * path through the shader consumes more than one attribute of
2700 * a set of attributes aliased to the same location. A link
2701 * error can occur if the linker determines that every path
2702 * through the shader consumes multiple aliased attributes,
2703 * but implementations are not required to generate an error
2706 * From GLSL 4.30 spec, page 54:
2708 * "A program will fail to link if any two non-vertex shader
2709 * input variables are assigned to the same location. For
2710 * vertex shaders, multiple input variables may be assigned
2711 * to the same location using either layout qualifiers or via
2712 * the OpenGL API. However, such aliasing is intended only to
2713 * support vertex shaders where each execution path accesses
2714 * at most one input per each location. Implementations are
2715 * permitted, but not required, to generate link-time errors
2716 * if they detect that every path through the vertex shader
2717 * executable accesses multiple inputs assigned to any single
2718 * location. For all shader types, a program will fail to link
2719 * if explicit location assignments leave the linker unable
2720 * to find space for other variables without explicit
2723 * From OpenGL ES 3.0 spec, page 56:
2725 * "Binding more than one attribute name to the same location
2726 * is referred to as aliasing, and is not permitted in OpenGL
2727 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2728 * fail when this condition exists. However, aliasing is
2729 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2730 * This will only work if only one of the aliased attributes
2731 * is active in the executable program, or if no path through
2732 * the shader consumes more than one attribute of a set of
2733 * attributes aliased to the same location. A link error can
2734 * occur if the linker determines that every path through the
2735 * shader consumes multiple aliased attributes, but implemen-
2736 * tations are not required to generate an error in this case."
2738 * After looking at above references from OpenGL, OpenGL ES and
2739 * GLSL specifications, we allow aliasing of vertex input variables
2740 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2742 * NOTE: This is not required by the spec but its worth mentioning
2743 * here that we're not doing anything to make sure that no path
2744 * through the vertex shader executable accesses multiple inputs
2745 * assigned to any single location.
2748 /* Mask representing the contiguous slots that will be used by
2751 const unsigned attr
= var
->data
.location
- generic_base
;
2752 const unsigned use_mask
= (1 << slots
) - 1;
2753 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2754 ? "vertex shader input" : "fragment shader output";
2756 /* Generate a link error if the requested locations for this
2757 * attribute exceed the maximum allowed attribute location.
2759 if (attr
+ slots
> max_index
) {
2761 "insufficient contiguous locations "
2762 "available for %s `%s' %d %d %d\n", string
,
2763 var
->name
, used_locations
, use_mask
, attr
);
2767 /* Generate a link error if the set of bits requested for this
2768 * attribute overlaps any previously allocated bits.
2770 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
2771 if (target_index
== MESA_SHADER_FRAGMENT
||
2772 (prog
->IsES
&& prog
->Version
>= 300)) {
2774 "overlapping location is assigned "
2775 "to %s `%s' %d %d %d\n", string
,
2776 var
->name
, used_locations
, use_mask
, attr
);
2779 linker_warning(prog
,
2780 "overlapping location is assigned "
2781 "to %s `%s' %d %d %d\n", string
,
2782 var
->name
, used_locations
, use_mask
, attr
);
2786 used_locations
|= (use_mask
<< attr
);
2788 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2790 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2791 * active attribute variables may fail to link, unless
2792 * device-dependent optimizations are able to make the program
2793 * fit within available hardware resources. For the purposes
2794 * of this test, attribute variables of the type dvec3, dvec4,
2795 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2796 * count as consuming twice as many attributes as equivalent
2797 * single-precision types. While these types use the same number
2798 * of generic attributes as their single-precision equivalents,
2799 * implementations are permitted to consume two single-precision
2800 * vectors of internal storage for each three- or four-component
2801 * double-precision vector."
2803 * Mark this attribute slot as taking up twice as much space
2804 * so we can count it properly against limits. According to
2805 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2806 * is optional behavior, but it seems preferable.
2808 if (var
->type
->without_array()->is_dual_slot_double())
2809 double_storage_locations
|= (use_mask
<< attr
);
2815 if (num_attr
>= max_index
) {
2816 linker_error(prog
, "too many %s (max %u)",
2817 target_index
== MESA_SHADER_VERTEX
?
2818 "vertex shader inputs" : "fragment shader outputs",
2822 to_assign
[num_attr
].slots
= slots
;
2823 to_assign
[num_attr
].var
= var
;
2827 if (target_index
== MESA_SHADER_VERTEX
) {
2828 unsigned total_attribs_size
=
2829 _mesa_bitcount(used_locations
& ((1 << max_index
) - 1)) +
2830 _mesa_bitcount(double_storage_locations
);
2831 if (total_attribs_size
> max_index
) {
2833 "attempt to use %d vertex attribute slots only %d available ",
2834 total_attribs_size
, max_index
);
2839 /* If all of the attributes were assigned locations by the application (or
2840 * are built-in attributes with fixed locations), return early. This should
2841 * be the common case.
2846 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
2848 if (target_index
== MESA_SHADER_VERTEX
) {
2849 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2850 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2851 * reserved to prevent it from being automatically allocated below.
2853 find_deref_visitor
find("gl_Vertex");
2855 if (find
.variable_found())
2856 used_locations
|= (1 << 0);
2859 for (unsigned i
= 0; i
< num_attr
; i
++) {
2860 /* Mask representing the contiguous slots that will be used by this
2863 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
2865 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
2868 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2869 ? "vertex shader input" : "fragment shader output";
2872 "insufficient contiguous locations "
2873 "available for %s `%s'\n",
2874 string
, to_assign
[i
].var
->name
);
2878 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
2879 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
2880 used_locations
|= (use_mask
<< location
);
2882 if (to_assign
[i
].var
->type
->without_array()->is_dual_slot_double())
2883 double_storage_locations
|= (use_mask
<< location
);
2886 /* Now that we have all the locations, from the GL 4.5 core spec, section
2887 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
2888 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
2889 * as equivalent single-precision types.
2891 if (target_index
== MESA_SHADER_VERTEX
) {
2892 unsigned total_attribs_size
=
2893 _mesa_bitcount(used_locations
& ((1 << max_index
) - 1)) +
2894 _mesa_bitcount(double_storage_locations
);
2895 if (total_attribs_size
> max_index
) {
2897 "attempt to use %d vertex attribute slots only %d available ",
2898 total_attribs_size
, max_index
);
2907 * Match explicit locations of outputs to inputs and deactivate the
2908 * unmatch flag if found so we don't optimise them away.
2911 match_explicit_outputs_to_inputs(gl_shader
*producer
,
2912 gl_shader
*consumer
)
2914 glsl_symbol_table parameters
;
2915 ir_variable
*explicit_locations
[MAX_VARYINGS_INCL_PATCH
][4] =
2918 /* Find all shader outputs in the "producer" stage.
2920 foreach_in_list(ir_instruction
, node
, producer
->ir
) {
2921 ir_variable
*const var
= node
->as_variable();
2923 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_shader_out
))
2926 if (var
->data
.explicit_location
&&
2927 var
->data
.location
>= VARYING_SLOT_VAR0
) {
2928 const unsigned idx
= var
->data
.location
- VARYING_SLOT_VAR0
;
2929 if (explicit_locations
[idx
][var
->data
.location_frac
] == NULL
)
2930 explicit_locations
[idx
][var
->data
.location_frac
] = var
;
2934 /* Match inputs to outputs */
2935 foreach_in_list(ir_instruction
, node
, consumer
->ir
) {
2936 ir_variable
*const input
= node
->as_variable();
2938 if ((input
== NULL
) || (input
->data
.mode
!= ir_var_shader_in
))
2941 ir_variable
*output
= NULL
;
2942 if (input
->data
.explicit_location
2943 && input
->data
.location
>= VARYING_SLOT_VAR0
) {
2944 output
= explicit_locations
[input
->data
.location
- VARYING_SLOT_VAR0
]
2945 [input
->data
.location_frac
];
2947 if (output
!= NULL
){
2948 input
->data
.is_unmatched_generic_inout
= 0;
2949 output
->data
.is_unmatched_generic_inout
= 0;
2956 * Store the gl_FragDepth layout in the gl_shader_program struct.
2959 store_fragdepth_layout(struct gl_shader_program
*prog
)
2961 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
2965 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
2967 /* We don't look up the gl_FragDepth symbol directly because if
2968 * gl_FragDepth is not used in the shader, it's removed from the IR.
2969 * However, the symbol won't be removed from the symbol table.
2971 * We're only interested in the cases where the variable is NOT removed
2974 foreach_in_list(ir_instruction
, node
, ir
) {
2975 ir_variable
*const var
= node
->as_variable();
2977 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
2981 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
2982 switch (var
->data
.depth_layout
) {
2983 case ir_depth_layout_none
:
2984 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
2986 case ir_depth_layout_any
:
2987 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
2989 case ir_depth_layout_greater
:
2990 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
2992 case ir_depth_layout_less
:
2993 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
2995 case ir_depth_layout_unchanged
:
2996 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
3007 * Validate the resources used by a program versus the implementation limits
3010 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3012 unsigned total_uniform_blocks
= 0;
3013 unsigned total_shader_storage_blocks
= 0;
3015 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3016 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3021 if (sh
->num_samplers
> ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
3022 linker_error(prog
, "Too many %s shader texture samplers\n",
3023 _mesa_shader_stage_to_string(i
));
3026 if (sh
->num_uniform_components
>
3027 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
3028 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3029 linker_warning(prog
, "Too many %s shader default uniform block "
3030 "components, but the driver will try to optimize "
3031 "them out; this is non-portable out-of-spec "
3033 _mesa_shader_stage_to_string(i
));
3035 linker_error(prog
, "Too many %s shader default uniform block "
3037 _mesa_shader_stage_to_string(i
));
3041 if (sh
->num_combined_uniform_components
>
3042 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
3043 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3044 linker_warning(prog
, "Too many %s shader uniform components, "
3045 "but the driver will try to optimize them out; "
3046 "this is non-portable out-of-spec behavior\n",
3047 _mesa_shader_stage_to_string(i
));
3049 linker_error(prog
, "Too many %s shader uniform components\n",
3050 _mesa_shader_stage_to_string(i
));
3054 total_shader_storage_blocks
+= sh
->NumShaderStorageBlocks
;
3055 total_uniform_blocks
+= sh
->NumUniformBlocks
;
3057 const unsigned max_uniform_blocks
=
3058 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
3059 if (max_uniform_blocks
< sh
->NumUniformBlocks
) {
3060 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
3061 _mesa_shader_stage_to_string(i
), sh
->NumUniformBlocks
,
3062 max_uniform_blocks
);
3065 const unsigned max_shader_storage_blocks
=
3066 ctx
->Const
.Program
[i
].MaxShaderStorageBlocks
;
3067 if (max_shader_storage_blocks
< sh
->NumShaderStorageBlocks
) {
3068 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
3069 _mesa_shader_stage_to_string(i
),
3070 sh
->NumShaderStorageBlocks
, max_shader_storage_blocks
);
3074 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
3075 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
3076 total_uniform_blocks
, ctx
->Const
.MaxCombinedUniformBlocks
);
3079 if (total_shader_storage_blocks
> ctx
->Const
.MaxCombinedShaderStorageBlocks
) {
3080 linker_error(prog
, "Too many combined shader storage blocks (%d/%d)\n",
3081 total_shader_storage_blocks
,
3082 ctx
->Const
.MaxCombinedShaderStorageBlocks
);
3085 for (unsigned i
= 0; i
< prog
->NumUniformBlocks
; i
++) {
3086 if (prog
->UniformBlocks
[i
].UniformBufferSize
>
3087 ctx
->Const
.MaxUniformBlockSize
) {
3088 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
3089 prog
->UniformBlocks
[i
].Name
,
3090 prog
->UniformBlocks
[i
].UniformBufferSize
,
3091 ctx
->Const
.MaxUniformBlockSize
);
3095 for (unsigned i
= 0; i
< prog
->NumShaderStorageBlocks
; i
++) {
3096 if (prog
->ShaderStorageBlocks
[i
].UniformBufferSize
>
3097 ctx
->Const
.MaxShaderStorageBlockSize
) {
3098 linker_error(prog
, "Shader storage block %s too big (%d/%d)\n",
3099 prog
->ShaderStorageBlocks
[i
].Name
,
3100 prog
->ShaderStorageBlocks
[i
].UniformBufferSize
,
3101 ctx
->Const
.MaxShaderStorageBlockSize
);
3107 link_calculate_subroutine_compat(struct gl_shader_program
*prog
)
3109 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3110 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3115 for (unsigned j
= 0; j
< sh
->NumSubroutineUniformRemapTable
; j
++) {
3116 if (sh
->SubroutineUniformRemapTable
[j
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
)
3119 struct gl_uniform_storage
*uni
= sh
->SubroutineUniformRemapTable
[j
];
3124 sh
->NumSubroutineUniforms
++;
3126 if (sh
->NumSubroutineFunctions
== 0) {
3127 linker_error(prog
, "subroutine uniform %s defined but no valid functions found\n", uni
->type
->name
);
3130 for (unsigned f
= 0; f
< sh
->NumSubroutineFunctions
; f
++) {
3131 struct gl_subroutine_function
*fn
= &sh
->SubroutineFunctions
[f
];
3132 for (int k
= 0; k
< fn
->num_compat_types
; k
++) {
3133 if (fn
->types
[k
] == uni
->type
) {
3139 uni
->num_compatible_subroutines
= count
;
3145 check_subroutine_resources(struct gl_shader_program
*prog
)
3147 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3148 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3151 if (sh
->NumSubroutineUniformRemapTable
> MAX_SUBROUTINE_UNIFORM_LOCATIONS
)
3152 linker_error(prog
, "Too many %s shader subroutine uniforms\n",
3153 _mesa_shader_stage_to_string(i
));
3158 * Validate shader image resources.
3161 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3163 unsigned total_image_units
= 0;
3164 unsigned fragment_outputs
= 0;
3165 unsigned total_shader_storage_blocks
= 0;
3167 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
3170 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3171 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3174 if (sh
->NumImages
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
3175 linker_error(prog
, "Too many %s shader image uniforms (%u > %u)\n",
3176 _mesa_shader_stage_to_string(i
), sh
->NumImages
,
3177 ctx
->Const
.Program
[i
].MaxImageUniforms
);
3179 total_image_units
+= sh
->NumImages
;
3180 total_shader_storage_blocks
+= sh
->NumShaderStorageBlocks
;
3182 if (i
== MESA_SHADER_FRAGMENT
) {
3183 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3184 ir_variable
*var
= node
->as_variable();
3185 if (var
&& var
->data
.mode
== ir_var_shader_out
)
3186 /* since there are no double fs outputs - pass false */
3187 fragment_outputs
+= var
->type
->count_attribute_slots(false);
3193 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
3194 linker_error(prog
, "Too many combined image uniforms\n");
3196 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
3197 ctx
->Const
.MaxCombinedShaderOutputResources
)
3198 linker_error(prog
, "Too many combined image uniforms, shader storage "
3199 " buffers and fragment outputs\n");
3204 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3205 * for a variable, checks for overlaps between other uniforms using explicit
3209 reserve_explicit_locations(struct gl_shader_program
*prog
,
3210 string_to_uint_map
*map
, ir_variable
*var
)
3212 unsigned slots
= var
->type
->uniform_locations();
3213 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3214 unsigned return_value
= slots
;
3216 /* Resize remap table if locations do not fit in the current one. */
3217 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
3218 prog
->UniformRemapTable
=
3219 reralloc(prog
, prog
->UniformRemapTable
,
3220 gl_uniform_storage
*,
3223 if (!prog
->UniformRemapTable
) {
3224 linker_error(prog
, "Out of memory during linking.\n");
3228 /* Initialize allocated space. */
3229 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
3230 prog
->UniformRemapTable
[i
] = NULL
;
3232 prog
->NumUniformRemapTable
= max_loc
+ 1;
3235 for (unsigned i
= 0; i
< slots
; i
++) {
3236 unsigned loc
= var
->data
.location
+ i
;
3238 /* Check if location is already used. */
3239 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3241 /* Possibly same uniform from a different stage, this is ok. */
3243 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
) {
3248 /* ARB_explicit_uniform_location specification states:
3250 * "No two default-block uniform variables in the program can have
3251 * the same location, even if they are unused, otherwise a compiler
3252 * or linker error will be generated."
3255 "location qualifier for uniform %s overlaps "
3256 "previously used location\n",
3261 /* Initialize location as inactive before optimization
3262 * rounds and location assignment.
3264 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3267 /* Note, base location used for arrays. */
3268 map
->put(var
->data
.location
, var
->name
);
3270 return return_value
;
3274 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3275 struct gl_shader
*sh
,
3278 unsigned slots
= var
->type
->uniform_locations();
3279 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3281 /* Resize remap table if locations do not fit in the current one. */
3282 if (max_loc
+ 1 > sh
->NumSubroutineUniformRemapTable
) {
3283 sh
->SubroutineUniformRemapTable
=
3284 reralloc(sh
, sh
->SubroutineUniformRemapTable
,
3285 gl_uniform_storage
*,
3288 if (!sh
->SubroutineUniformRemapTable
) {
3289 linker_error(prog
, "Out of memory during linking.\n");
3293 /* Initialize allocated space. */
3294 for (unsigned i
= sh
->NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3295 sh
->SubroutineUniformRemapTable
[i
] = NULL
;
3297 sh
->NumSubroutineUniformRemapTable
= max_loc
+ 1;
3300 for (unsigned i
= 0; i
< slots
; i
++) {
3301 unsigned loc
= var
->data
.location
+ i
;
3303 /* Check if location is already used. */
3304 if (sh
->SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3306 /* ARB_explicit_uniform_location specification states:
3307 * "No two subroutine uniform variables can have the same location
3308 * in the same shader stage, otherwise a compiler or linker error
3309 * will be generated."
3312 "location qualifier for uniform %s overlaps "
3313 "previously used location\n",
3318 /* Initialize location as inactive before optimization
3319 * rounds and location assignment.
3321 sh
->SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3327 * Check and reserve all explicit uniform locations, called before
3328 * any optimizations happen to handle also inactive uniforms and
3329 * inactive array elements that may get trimmed away.
3332 check_explicit_uniform_locations(struct gl_context
*ctx
,
3333 struct gl_shader_program
*prog
)
3335 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3338 /* This map is used to detect if overlapping explicit locations
3339 * occur with the same uniform (from different stage) or a different one.
3341 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3344 linker_error(prog
, "Out of memory during linking.\n");
3348 unsigned entries_total
= 0;
3349 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3350 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3355 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3356 ir_variable
*var
= node
->as_variable();
3357 if (!var
|| var
->data
.mode
!= ir_var_uniform
)
3360 if (var
->data
.explicit_location
) {
3362 if (var
->type
->without_array()->is_subroutine())
3363 ret
= reserve_subroutine_explicit_locations(prog
, sh
, var
);
3365 int slots
= reserve_explicit_locations(prog
, uniform_map
,
3369 entries_total
+= slots
;
3380 struct empty_uniform_block
*current_block
= NULL
;
3382 for (unsigned i
= 0; i
< prog
->NumUniformRemapTable
; i
++) {
3383 /* We found empty space in UniformRemapTable. */
3384 if (prog
->UniformRemapTable
[i
] == NULL
) {
3385 /* We've found the beginning of a new continous block of empty slots */
3386 if (!current_block
|| current_block
->start
+ current_block
->slots
!= i
) {
3387 current_block
= rzalloc(prog
, struct empty_uniform_block
);
3388 current_block
->start
= i
;
3389 exec_list_push_tail(&prog
->EmptyUniformLocations
,
3390 ¤t_block
->link
);
3393 /* The current block continues, so we simply increment its slots */
3394 current_block
->slots
++;
3399 return entries_total
;
3403 should_add_buffer_variable(struct gl_shader_program
*shProg
,
3404 GLenum type
, const char *name
)
3406 bool found_interface
= false;
3407 unsigned block_name_len
= 0;
3408 const char *block_name_dot
= strchr(name
, '.');
3410 /* These rules only apply to buffer variables. So we return
3411 * true for the rest of types.
3413 if (type
!= GL_BUFFER_VARIABLE
)
3416 for (unsigned i
= 0; i
< shProg
->NumShaderStorageBlocks
; i
++) {
3417 const char *block_name
= shProg
->ShaderStorageBlocks
[i
].Name
;
3418 block_name_len
= strlen(block_name
);
3420 const char *block_square_bracket
= strchr(block_name
, '[');
3421 if (block_square_bracket
) {
3422 /* The block is part of an array of named interfaces,
3423 * for the name comparison we ignore the "[x]" part.
3425 block_name_len
-= strlen(block_square_bracket
);
3428 if (block_name_dot
) {
3429 /* Check if the variable name starts with the interface
3430 * name. The interface name (if present) should have the
3431 * length than the interface block name we are comparing to.
3433 unsigned len
= strlen(name
) - strlen(block_name_dot
);
3434 if (len
!= block_name_len
)
3438 if (strncmp(block_name
, name
, block_name_len
) == 0) {
3439 found_interface
= true;
3444 /* We remove the interface name from the buffer variable name,
3445 * including the dot that follows it.
3447 if (found_interface
)
3448 name
= name
+ block_name_len
+ 1;
3450 /* The ARB_program_interface_query spec says:
3452 * "For an active shader storage block member declared as an array, an
3453 * entry will be generated only for the first array element, regardless
3454 * of its type. For arrays of aggregate types, the enumeration rules
3455 * are applied recursively for the single enumerated array element."
3457 const char *struct_first_dot
= strchr(name
, '.');
3458 const char *first_square_bracket
= strchr(name
, '[');
3460 /* The buffer variable is on top level and it is not an array */
3461 if (!first_square_bracket
) {
3463 /* The shader storage block member is a struct, then generate the entry */
3464 } else if (struct_first_dot
&& struct_first_dot
< first_square_bracket
) {
3467 /* Shader storage block member is an array, only generate an entry for the
3468 * first array element.
3470 if (strncmp(first_square_bracket
, "[0]", 3) == 0)
3478 add_program_resource(struct gl_shader_program
*prog
, GLenum type
,
3479 const void *data
, uint8_t stages
)
3483 /* If resource already exists, do not add it again. */
3484 for (unsigned i
= 0; i
< prog
->NumProgramResourceList
; i
++)
3485 if (prog
->ProgramResourceList
[i
].Data
== data
)
3488 prog
->ProgramResourceList
=
3490 prog
->ProgramResourceList
,
3491 gl_program_resource
,
3492 prog
->NumProgramResourceList
+ 1);
3494 if (!prog
->ProgramResourceList
) {
3495 linker_error(prog
, "Out of memory during linking.\n");
3499 struct gl_program_resource
*res
=
3500 &prog
->ProgramResourceList
[prog
->NumProgramResourceList
];
3504 res
->StageReferences
= stages
;
3506 prog
->NumProgramResourceList
++;
3511 /* Function checks if a variable var is a packed varying and
3512 * if given name is part of packed varying's list.
3514 * If a variable is a packed varying, it has a name like
3515 * 'packed:a,b,c' where a, b and c are separate variables.
3518 included_in_packed_varying(ir_variable
*var
, const char *name
)
3520 if (strncmp(var
->name
, "packed:", 7) != 0)
3523 char *list
= strdup(var
->name
+ 7);
3528 char *token
= strtok_r(list
, ",", &saveptr
);
3530 if (strcmp(token
, name
) == 0) {
3534 token
= strtok_r(NULL
, ",", &saveptr
);
3541 * Function builds a stage reference bitmask from variable name.
3544 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3549 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3550 * used for reference mask in gl_program_resource will need to be changed.
3552 assert(MESA_SHADER_STAGES
< 8);
3554 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3555 struct gl_shader
*sh
= shProg
->_LinkedShaders
[i
];
3559 /* Shader symbol table may contain variables that have
3560 * been optimized away. Search IR for the variable instead.
3562 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3563 ir_variable
*var
= node
->as_variable();
3565 unsigned baselen
= strlen(var
->name
);
3567 if (included_in_packed_varying(var
, name
)) {
3572 /* Type needs to match if specified, otherwise we might
3573 * pick a variable with same name but different interface.
3575 if (var
->data
.mode
!= mode
)
3578 if (strncmp(var
->name
, name
, baselen
) == 0) {
3579 /* Check for exact name matches but also check for arrays and
3582 if (name
[baselen
] == '\0' ||
3583 name
[baselen
] == '[' ||
3584 name
[baselen
] == '.') {
3596 * Create gl_shader_variable from ir_variable class.
3598 static gl_shader_variable
*
3599 create_shader_variable(struct gl_shader_program
*shProg
,
3600 const ir_variable
*in
,
3601 const char *name
, const glsl_type
*type
,
3602 bool use_implicit_location
, int location
)
3604 gl_shader_variable
*out
= ralloc(shProg
, struct gl_shader_variable
);
3608 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3609 * expect to see gl_VertexID in the program resource list. Pretend.
3611 if (in
->data
.mode
== ir_var_system_value
&&
3612 in
->data
.location
== SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
) {
3613 out
->name
= ralloc_strdup(shProg
, "gl_VertexID");
3615 out
->name
= ralloc_strdup(shProg
, name
);
3621 /* The ARB_program_interface_query spec says:
3623 * "Not all active variables are assigned valid locations; the
3624 * following variables will have an effective location of -1:
3626 * * uniforms declared as atomic counters;
3628 * * members of a uniform block;
3630 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3632 * * inputs or outputs not declared with a "location" layout
3633 * qualifier, except for vertex shader inputs and fragment shader
3636 if (in
->type
->base_type
== GLSL_TYPE_ATOMIC_UINT
||
3637 is_gl_identifier(in
->name
) ||
3638 !(in
->data
.explicit_location
|| use_implicit_location
)) {
3641 out
->location
= location
;
3645 out
->component
= in
->data
.location_frac
;
3646 out
->index
= in
->data
.index
;
3647 out
->patch
= in
->data
.patch
;
3648 out
->mode
= in
->data
.mode
;
3654 add_shader_variable(struct gl_shader_program
*shProg
, unsigned stage_mask
,
3655 GLenum programInterface
, ir_variable
*var
,
3656 const char *name
, const glsl_type
*type
,
3657 bool use_implicit_location
, int location
)
3659 const bool is_vertex_input
=
3660 programInterface
== GL_PROGRAM_INPUT
&&
3661 stage_mask
== MESA_SHADER_VERTEX
;
3663 switch (type
->base_type
) {
3664 case GLSL_TYPE_STRUCT
: {
3665 /* The ARB_program_interface_query spec says:
3667 * "For an active variable declared as a structure, a separate entry
3668 * will be generated for each active structure member. The name of
3669 * each entry is formed by concatenating the name of the structure,
3670 * the "." character, and the name of the structure member. If a
3671 * structure member to enumerate is itself a structure or array,
3672 * these enumeration rules are applied recursively."
3674 unsigned field_location
= location
;
3675 for (unsigned i
= 0; i
< type
->length
; i
++) {
3676 const struct glsl_struct_field
*field
= &type
->fields
.structure
[i
];
3677 char *field_name
= ralloc_asprintf(shProg
, "%s.%s", name
, field
->name
);
3678 if (!add_shader_variable(shProg
, stage_mask
, programInterface
,
3679 var
, field_name
, field
->type
,
3680 use_implicit_location
, field_location
))
3684 field
->type
->count_attribute_slots(is_vertex_input
);
3690 /* Issue #16 of the ARB_program_interface_query spec says:
3692 * "* If a variable is a member of an interface block without an
3693 * instance name, it is enumerated using just the variable name.
3695 * * If a variable is a member of an interface block with an instance
3696 * name, it is enumerated as "BlockName.Member", where "BlockName" is
3697 * the name of the interface block (not the instance name) and
3698 * "Member" is the name of the variable."
3700 const char *prefixed_name
= (var
->data
.from_named_ifc_block
&&
3701 !is_gl_identifier(var
->name
))
3702 ? ralloc_asprintf(shProg
, "%s.%s", var
->get_interface_type()->name
,
3706 /* The ARB_program_interface_query spec says:
3708 * "For an active variable declared as a single instance of a basic
3709 * type, a single entry will be generated, using the variable name
3710 * from the shader source."
3712 gl_shader_variable
*sha_v
=
3713 create_shader_variable(shProg
, var
, prefixed_name
, type
,
3714 use_implicit_location
, location
);
3718 return add_program_resource(shProg
, programInterface
, sha_v
, stage_mask
);
3724 add_interface_variables(struct gl_shader_program
*shProg
,
3725 unsigned stage
, GLenum programInterface
)
3727 exec_list
*ir
= shProg
->_LinkedShaders
[stage
]->ir
;
3729 foreach_in_list(ir_instruction
, node
, ir
) {
3730 ir_variable
*var
= node
->as_variable();
3732 if (!var
|| var
->data
.how_declared
== ir_var_hidden
)
3737 switch (var
->data
.mode
) {
3738 case ir_var_system_value
:
3739 case ir_var_shader_in
:
3740 if (programInterface
!= GL_PROGRAM_INPUT
)
3742 loc_bias
= (stage
== MESA_SHADER_VERTEX
) ? int(VERT_ATTRIB_GENERIC0
)
3743 : int(VARYING_SLOT_VAR0
);
3745 case ir_var_shader_out
:
3746 if (programInterface
!= GL_PROGRAM_OUTPUT
)
3748 loc_bias
= (stage
== MESA_SHADER_FRAGMENT
) ? int(FRAG_RESULT_DATA0
)
3749 : int(VARYING_SLOT_VAR0
);
3755 /* Skip packed varyings, packed varyings are handled separately
3756 * by add_packed_varyings.
3758 if (strncmp(var
->name
, "packed:", 7) == 0)
3761 /* Skip fragdata arrays, these are handled separately
3762 * by add_fragdata_arrays.
3764 if (strncmp(var
->name
, "gl_out_FragData", 15) == 0)
3767 const bool vs_input_or_fs_output
=
3768 (stage
== MESA_SHADER_VERTEX
&& var
->data
.mode
== ir_var_shader_in
) ||
3769 (stage
== MESA_SHADER_FRAGMENT
&& var
->data
.mode
== ir_var_shader_out
);
3771 if (!add_shader_variable(shProg
, 1 << stage
, programInterface
,
3772 var
, var
->name
, var
->type
, vs_input_or_fs_output
,
3773 var
->data
.location
- loc_bias
))
3780 add_packed_varyings(struct gl_shader_program
*shProg
, int stage
, GLenum type
)
3782 struct gl_shader
*sh
= shProg
->_LinkedShaders
[stage
];
3785 if (!sh
|| !sh
->packed_varyings
)
3788 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
3789 ir_variable
*var
= node
->as_variable();
3791 switch (var
->data
.mode
) {
3792 case ir_var_shader_in
:
3793 iface
= GL_PROGRAM_INPUT
;
3795 case ir_var_shader_out
:
3796 iface
= GL_PROGRAM_OUTPUT
;
3799 unreachable("unexpected type");
3802 if (type
== iface
) {
3803 const int stage_mask
=
3804 build_stageref(shProg
, var
->name
, var
->data
.mode
);
3805 if (!add_shader_variable(shProg
, stage_mask
,
3806 iface
, var
, var
->name
, var
->type
, false,
3807 var
->data
.location
- VARYING_SLOT_VAR0
))
3816 add_fragdata_arrays(struct gl_shader_program
*shProg
)
3818 struct gl_shader
*sh
= shProg
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
3820 if (!sh
|| !sh
->fragdata_arrays
)
3823 foreach_in_list(ir_instruction
, node
, sh
->fragdata_arrays
) {
3824 ir_variable
*var
= node
->as_variable();
3826 assert(var
->data
.mode
== ir_var_shader_out
);
3828 if (!add_shader_variable(shProg
,
3829 1 << MESA_SHADER_FRAGMENT
,
3830 GL_PROGRAM_OUTPUT
, var
, var
->name
, var
->type
,
3831 true, var
->data
.location
- FRAG_RESULT_DATA0
))
3839 get_top_level_name(const char *name
)
3841 const char *first_dot
= strchr(name
, '.');
3842 const char *first_square_bracket
= strchr(name
, '[');
3845 /* The ARB_program_interface_query spec says:
3847 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
3848 * the number of active array elements of the top-level shader storage
3849 * block member containing to the active variable is written to
3850 * <params>. If the top-level block member is not declared as an
3851 * array, the value one is written to <params>. If the top-level block
3852 * member is an array with no declared size, the value zero is written
3856 /* The buffer variable is on top level.*/
3857 if (!first_square_bracket
&& !first_dot
)
3858 name_size
= strlen(name
);
3859 else if ((!first_square_bracket
||
3860 (first_dot
&& first_dot
< first_square_bracket
)))
3861 name_size
= first_dot
- name
;
3863 name_size
= first_square_bracket
- name
;
3865 return strndup(name
, name_size
);
3869 get_var_name(const char *name
)
3871 const char *first_dot
= strchr(name
, '.');
3874 return strdup(name
);
3876 return strndup(first_dot
+1, strlen(first_dot
) - 1);
3880 is_top_level_shader_storage_block_member(const char* name
,
3881 const char* interface_name
,
3882 const char* field_name
)
3884 bool result
= false;
3886 /* If the given variable is already a top-level shader storage
3887 * block member, then return array_size = 1.
3888 * We could have two possibilities: if we have an instanced
3889 * shader storage block or not instanced.
3891 * For the first, we check create a name as it was in top level and
3892 * compare it with the real name. If they are the same, then
3893 * the variable is already at top-level.
3895 * Full instanced name is: interface name + '.' + var name +
3898 int name_length
= strlen(interface_name
) + 1 + strlen(field_name
) + 1;
3899 char *full_instanced_name
= (char *) calloc(name_length
, sizeof(char));
3900 if (!full_instanced_name
) {
3901 fprintf(stderr
, "%s: Cannot allocate space for name\n", __func__
);
3905 snprintf(full_instanced_name
, name_length
, "%s.%s",
3906 interface_name
, field_name
);
3908 /* Check if its top-level shader storage block member of an
3909 * instanced interface block, or of a unnamed interface block.
3911 if (strcmp(name
, full_instanced_name
) == 0 ||
3912 strcmp(name
, field_name
) == 0)
3915 free(full_instanced_name
);
3920 get_array_size(struct gl_uniform_storage
*uni
, const glsl_struct_field
*field
,
3921 char *interface_name
, char *var_name
)
3923 /* The ARB_program_interface_query spec says:
3925 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
3926 * the number of active array elements of the top-level shader storage
3927 * block member containing to the active variable is written to
3928 * <params>. If the top-level block member is not declared as an
3929 * array, the value one is written to <params>. If the top-level block
3930 * member is an array with no declared size, the value zero is written
3933 if (is_top_level_shader_storage_block_member(uni
->name
,
3937 else if (field
->type
->is_unsized_array())
3939 else if (field
->type
->is_array())
3940 return field
->type
->length
;
3946 get_array_stride(struct gl_uniform_storage
*uni
, const glsl_type
*interface
,
3947 const glsl_struct_field
*field
, char *interface_name
,
3950 /* The ARB_program_interface_query spec says:
3952 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
3953 * identifying the stride between array elements of the top-level
3954 * shader storage block member containing the active variable is
3955 * written to <params>. For top-level block members declared as
3956 * arrays, the value written is the difference, in basic machine units,
3957 * between the offsets of the active variable for consecutive elements
3958 * in the top-level array. For top-level block members not declared as
3959 * an array, zero is written to <params>."
3961 if (field
->type
->is_array()) {
3962 const enum glsl_matrix_layout matrix_layout
=
3963 glsl_matrix_layout(field
->matrix_layout
);
3964 bool row_major
= matrix_layout
== GLSL_MATRIX_LAYOUT_ROW_MAJOR
;
3965 const glsl_type
*array_type
= field
->type
->fields
.array
;
3967 if (is_top_level_shader_storage_block_member(uni
->name
,
3972 if (interface
->interface_packing
!= GLSL_INTERFACE_PACKING_STD430
) {
3973 if (array_type
->is_record() || array_type
->is_array())
3974 return glsl_align(array_type
->std140_size(row_major
), 16);
3976 return MAX2(array_type
->std140_base_alignment(row_major
), 16);
3978 return array_type
->std430_array_stride(row_major
);
3985 calculate_array_size_and_stride(struct gl_shader_program
*shProg
,
3986 struct gl_uniform_storage
*uni
)
3988 int block_index
= uni
->block_index
;
3989 int array_size
= -1;
3990 int array_stride
= -1;
3991 char *var_name
= get_top_level_name(uni
->name
);
3992 char *interface_name
=
3993 get_top_level_name(uni
->is_shader_storage
?
3994 shProg
->ShaderStorageBlocks
[block_index
].Name
:
3995 shProg
->UniformBlocks
[block_index
].Name
);
3997 if (strcmp(var_name
, interface_name
) == 0) {
3998 /* Deal with instanced array of SSBOs */
3999 char *temp_name
= get_var_name(uni
->name
);
4001 linker_error(shProg
, "Out of memory during linking.\n");
4002 goto write_top_level_array_size_and_stride
;
4005 var_name
= get_top_level_name(temp_name
);
4008 linker_error(shProg
, "Out of memory during linking.\n");
4009 goto write_top_level_array_size_and_stride
;
4013 for (unsigned i
= 0; i
< shProg
->NumShaders
; i
++) {
4014 if (shProg
->Shaders
[i
] == NULL
)
4017 const gl_shader
*stage
= shProg
->Shaders
[i
];
4018 foreach_in_list(ir_instruction
, node
, stage
->ir
) {
4019 ir_variable
*var
= node
->as_variable();
4020 if (!var
|| !var
->get_interface_type() ||
4021 var
->data
.mode
!= ir_var_shader_storage
)
4024 const glsl_type
*interface
= var
->get_interface_type();
4026 if (strcmp(interface_name
, interface
->name
) != 0)
4029 for (unsigned i
= 0; i
< interface
->length
; i
++) {
4030 const glsl_struct_field
*field
= &interface
->fields
.structure
[i
];
4031 if (strcmp(field
->name
, var_name
) != 0)
4034 array_stride
= get_array_stride(uni
, interface
, field
,
4035 interface_name
, var_name
);
4036 array_size
= get_array_size(uni
, field
, interface_name
, var_name
);
4037 goto write_top_level_array_size_and_stride
;
4041 write_top_level_array_size_and_stride
:
4042 free(interface_name
);
4044 uni
->top_level_array_stride
= array_stride
;
4045 uni
->top_level_array_size
= array_size
;
4049 * Builds up a list of program resources that point to existing
4053 build_program_resource_list(struct gl_context
*ctx
,
4054 struct gl_shader_program
*shProg
)
4056 /* Rebuild resource list. */
4057 if (shProg
->ProgramResourceList
) {
4058 ralloc_free(shProg
->ProgramResourceList
);
4059 shProg
->ProgramResourceList
= NULL
;
4060 shProg
->NumProgramResourceList
= 0;
4063 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
4065 /* Determine first input and final output stage. These are used to
4066 * detect which variables should be enumerated in the resource list
4067 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4069 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4070 if (!shProg
->_LinkedShaders
[i
])
4072 if (input_stage
== MESA_SHADER_STAGES
)
4077 /* Empty shader, no resources. */
4078 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
4081 /* Program interface needs to expose varyings in case of SSO. */
4082 if (shProg
->SeparateShader
) {
4083 if (!add_packed_varyings(shProg
, input_stage
, GL_PROGRAM_INPUT
))
4086 if (!add_packed_varyings(shProg
, output_stage
, GL_PROGRAM_OUTPUT
))
4090 if (!add_fragdata_arrays(shProg
))
4093 /* Add inputs and outputs to the resource list. */
4094 if (!add_interface_variables(shProg
, input_stage
, GL_PROGRAM_INPUT
))
4097 if (!add_interface_variables(shProg
, output_stage
, GL_PROGRAM_OUTPUT
))
4100 /* Add transform feedback varyings. */
4101 if (shProg
->LinkedTransformFeedback
.NumVarying
> 0) {
4102 for (int i
= 0; i
< shProg
->LinkedTransformFeedback
.NumVarying
; i
++) {
4103 if (!add_program_resource(shProg
, GL_TRANSFORM_FEEDBACK_VARYING
,
4104 &shProg
->LinkedTransformFeedback
.Varyings
[i
],
4110 /* Add transform feedback buffers. */
4111 for (unsigned i
= 0; i
< ctx
->Const
.MaxTransformFeedbackBuffers
; i
++) {
4112 if ((shProg
->LinkedTransformFeedback
.ActiveBuffers
>> i
) & 1) {
4113 shProg
->LinkedTransformFeedback
.Buffers
[i
].Binding
= i
;
4114 if (!add_program_resource(shProg
, GL_TRANSFORM_FEEDBACK_BUFFER
,
4115 &shProg
->LinkedTransformFeedback
.Buffers
[i
],
4121 /* Add uniforms from uniform storage. */
4122 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
4123 /* Do not add uniforms internally used by Mesa. */
4124 if (shProg
->UniformStorage
[i
].hidden
)
4128 build_stageref(shProg
, shProg
->UniformStorage
[i
].name
,
4131 /* Add stagereferences for uniforms in a uniform block. */
4132 bool is_shader_storage
= shProg
->UniformStorage
[i
].is_shader_storage
;
4133 int block_index
= shProg
->UniformStorage
[i
].block_index
;
4134 if (block_index
!= -1) {
4135 stageref
|= is_shader_storage
?
4136 shProg
->ShaderStorageBlocks
[block_index
].stageref
:
4137 shProg
->UniformBlocks
[block_index
].stageref
;
4140 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
4141 if (!should_add_buffer_variable(shProg
, type
,
4142 shProg
->UniformStorage
[i
].name
))
4145 if (is_shader_storage
) {
4146 calculate_array_size_and_stride(shProg
, &shProg
->UniformStorage
[i
]);
4149 if (!add_program_resource(shProg
, type
,
4150 &shProg
->UniformStorage
[i
], stageref
))
4154 /* Add program uniform blocks. */
4155 for (unsigned i
= 0; i
< shProg
->NumUniformBlocks
; i
++) {
4156 if (!add_program_resource(shProg
, GL_UNIFORM_BLOCK
,
4157 &shProg
->UniformBlocks
[i
], 0))
4161 /* Add program shader storage blocks. */
4162 for (unsigned i
= 0; i
< shProg
->NumShaderStorageBlocks
; i
++) {
4163 if (!add_program_resource(shProg
, GL_SHADER_STORAGE_BLOCK
,
4164 &shProg
->ShaderStorageBlocks
[i
], 0))
4168 /* Add atomic counter buffers. */
4169 for (unsigned i
= 0; i
< shProg
->NumAtomicBuffers
; i
++) {
4170 if (!add_program_resource(shProg
, GL_ATOMIC_COUNTER_BUFFER
,
4171 &shProg
->AtomicBuffers
[i
], 0))
4175 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
4177 if (!shProg
->UniformStorage
[i
].hidden
)
4180 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
4181 if (!shProg
->UniformStorage
[i
].opaque
[j
].active
||
4182 !shProg
->UniformStorage
[i
].type
->is_subroutine())
4185 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
4186 /* add shader subroutines */
4187 if (!add_program_resource(shProg
, type
, &shProg
->UniformStorage
[i
], 0))
4192 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4193 struct gl_shader
*sh
= shProg
->_LinkedShaders
[i
];
4199 type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
4200 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
4201 if (!add_program_resource(shProg
, type
, &sh
->SubroutineFunctions
[j
], 0))
4208 * This check is done to make sure we allow only constant expression
4209 * indexing and "constant-index-expression" (indexing with an expression
4210 * that includes loop induction variable).
4213 validate_sampler_array_indexing(struct gl_context
*ctx
,
4214 struct gl_shader_program
*prog
)
4216 dynamic_sampler_array_indexing_visitor v
;
4217 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4218 if (prog
->_LinkedShaders
[i
] == NULL
)
4221 bool no_dynamic_indexing
=
4222 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
4224 /* Search for array derefs in shader. */
4225 v
.run(prog
->_LinkedShaders
[i
]->ir
);
4226 if (v
.uses_dynamic_sampler_array_indexing()) {
4227 const char *msg
= "sampler arrays indexed with non-constant "
4228 "expressions is forbidden in GLSL %s %u";
4229 /* Backend has indicated that it has no dynamic indexing support. */
4230 if (no_dynamic_indexing
) {
4231 linker_error(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
4234 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
4242 link_assign_subroutine_types(struct gl_shader_program
*prog
)
4244 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4245 gl_shader
*sh
= prog
->_LinkedShaders
[i
];
4250 sh
->MaxSubroutineFunctionIndex
= 0;
4251 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
4252 ir_function
*fn
= node
->as_function();
4256 if (fn
->is_subroutine
)
4257 sh
->NumSubroutineUniformTypes
++;
4259 if (!fn
->num_subroutine_types
)
4262 /* these should have been calculated earlier. */
4263 assert(fn
->subroutine_index
!= -1);
4264 if (sh
->NumSubroutineFunctions
+ 1 > MAX_SUBROUTINES
) {
4265 linker_error(prog
, "Too many subroutine functions declared.\n");
4268 sh
->SubroutineFunctions
= reralloc(sh
, sh
->SubroutineFunctions
,
4269 struct gl_subroutine_function
,
4270 sh
->NumSubroutineFunctions
+ 1);
4271 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].name
= ralloc_strdup(sh
, fn
->name
);
4272 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
4273 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
=
4274 ralloc_array(sh
, const struct glsl_type
*,
4275 fn
->num_subroutine_types
);
4277 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4280 * "Each subroutine with an index qualifier in the shader must be
4281 * given a unique index, otherwise a compile or link error will be
4284 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
4285 if (sh
->SubroutineFunctions
[j
].index
!= -1 &&
4286 sh
->SubroutineFunctions
[j
].index
== fn
->subroutine_index
) {
4287 linker_error(prog
, "each subroutine index qualifier in the "
4288 "shader must be unique\n");
4292 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].index
=
4293 fn
->subroutine_index
;
4295 if (fn
->subroutine_index
> (int)sh
->MaxSubroutineFunctionIndex
)
4296 sh
->MaxSubroutineFunctionIndex
= fn
->subroutine_index
;
4298 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
4299 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
4300 sh
->NumSubroutineFunctions
++;
4306 set_always_active_io(exec_list
*ir
, ir_variable_mode io_mode
)
4308 assert(io_mode
== ir_var_shader_in
|| io_mode
== ir_var_shader_out
);
4310 foreach_in_list(ir_instruction
, node
, ir
) {
4311 ir_variable
*const var
= node
->as_variable();
4313 if (var
== NULL
|| var
->data
.mode
!= io_mode
)
4316 /* Don't set always active on builtins that haven't been redeclared */
4317 if (var
->data
.how_declared
== ir_var_declared_implicitly
)
4320 var
->data
.always_active_io
= true;
4325 * When separate shader programs are enabled, only input/outputs between
4326 * the stages of a multi-stage separate program can be safely removed
4327 * from the shader interface. Other inputs/outputs must remain active.
4330 disable_varying_optimizations_for_sso(struct gl_shader_program
*prog
)
4332 unsigned first
, last
;
4333 assert(prog
->SeparateShader
);
4335 first
= MESA_SHADER_STAGES
;
4338 /* Determine first and last stage. Excluding the compute stage */
4339 for (unsigned i
= 0; i
< MESA_SHADER_COMPUTE
; i
++) {
4340 if (!prog
->_LinkedShaders
[i
])
4342 if (first
== MESA_SHADER_STAGES
)
4347 if (first
== MESA_SHADER_STAGES
)
4350 for (unsigned stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4351 gl_shader
*sh
= prog
->_LinkedShaders
[stage
];
4355 if (first
== last
) {
4356 /* For a single shader program only allow inputs to the vertex shader
4357 * and outputs from the fragment shader to be removed.
4359 if (stage
!= MESA_SHADER_VERTEX
)
4360 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4361 if (stage
!= MESA_SHADER_FRAGMENT
)
4362 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4364 /* For multi-stage separate shader programs only allow inputs and
4365 * outputs between the shader stages to be removed as well as inputs
4366 * to the vertex shader and outputs from the fragment shader.
4368 if (stage
== first
&& stage
!= MESA_SHADER_VERTEX
)
4369 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4370 else if (stage
== last
&& stage
!= MESA_SHADER_FRAGMENT
)
4371 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4377 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
4379 prog
->LinkStatus
= true; /* All error paths will set this to false */
4380 prog
->Validated
= false;
4381 prog
->_Used
= false;
4383 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4385 * "Linking can fail for a variety of reasons as specified in the
4386 * OpenGL Shading Language Specification, as well as any of the
4387 * following reasons:
4389 * - No shader objects are attached to program."
4391 * The Compatibility Profile specification does not list the error. In
4392 * Compatibility Profile missing shader stages are replaced by
4393 * fixed-function. This applies to the case where all stages are
4396 if (prog
->NumShaders
== 0) {
4397 if (ctx
->API
!= API_OPENGL_COMPAT
)
4398 linker_error(prog
, "no shaders attached to the program\n");
4402 unsigned num_tfeedback_decls
= 0;
4403 unsigned int num_explicit_uniform_locs
= 0;
4404 bool has_xfb_qualifiers
= false;
4405 char **varying_names
= NULL
;
4406 tfeedback_decl
*tfeedback_decls
= NULL
;
4408 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
4410 prog
->ARB_fragment_coord_conventions_enable
= false;
4412 /* Separate the shaders into groups based on their type.
4414 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
4415 unsigned num_shaders
[MESA_SHADER_STAGES
];
4417 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4418 shader_list
[i
] = (struct gl_shader
**)
4419 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
4423 unsigned min_version
= UINT_MAX
;
4424 unsigned max_version
= 0;
4425 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
4426 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
4427 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
4429 if (prog
->Shaders
[i
]->IsES
!= prog
->Shaders
[0]->IsES
) {
4430 linker_error(prog
, "all shaders must use same shading "
4431 "language version\n");
4435 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
4436 prog
->ARB_fragment_coord_conventions_enable
= true;
4439 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
4440 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
4441 num_shaders
[shader_type
]++;
4444 /* In desktop GLSL, different shader versions may be linked together. In
4445 * GLSL ES, all shader versions must be the same.
4447 if (prog
->Shaders
[0]->IsES
&& min_version
!= max_version
) {
4448 linker_error(prog
, "all shaders must use same shading "
4449 "language version\n");
4453 prog
->Version
= max_version
;
4454 prog
->IsES
= prog
->Shaders
[0]->IsES
;
4456 /* Some shaders have to be linked with some other shaders present.
4458 if (!prog
->SeparateShader
) {
4459 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
4460 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4461 linker_error(prog
, "Geometry shader must be linked with "
4465 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4466 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4467 linker_error(prog
, "Tessellation evaluation shader must be linked "
4468 "with vertex shader\n");
4471 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4472 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4473 linker_error(prog
, "Tessellation control shader must be linked with "
4478 /* The spec is self-contradictory here. It allows linking without a tess
4479 * eval shader, but that can only be used with transform feedback and
4480 * rasterization disabled. However, transform feedback isn't allowed
4481 * with GL_PATCHES, so it can't be used.
4483 * More investigation showed that the idea of transform feedback after
4484 * a tess control shader was dropped, because some hw vendors couldn't
4485 * support tessellation without a tess eval shader, but the linker
4486 * section wasn't updated to reflect that.
4488 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4491 * Do what's reasonable and always require a tess eval shader if a tess
4492 * control shader is present.
4494 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4495 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0) {
4496 linker_error(prog
, "Tessellation control shader must be linked with "
4497 "tessellation evaluation shader\n");
4502 /* Compute shaders have additional restrictions. */
4503 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
4504 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
4505 linker_error(prog
, "Compute shaders may not be linked with any other "
4506 "type of shader\n");
4509 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4510 if (prog
->_LinkedShaders
[i
] != NULL
)
4511 _mesa_delete_shader(ctx
, prog
->_LinkedShaders
[i
]);
4513 prog
->_LinkedShaders
[i
] = NULL
;
4516 /* Link all shaders for a particular stage and validate the result.
4518 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4519 if (num_shaders
[stage
] > 0) {
4520 gl_shader
*const sh
=
4521 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
4522 num_shaders
[stage
]);
4524 if (!prog
->LinkStatus
) {
4526 _mesa_delete_shader(ctx
, sh
);
4531 case MESA_SHADER_VERTEX
:
4532 validate_vertex_shader_executable(prog
, sh
, ctx
);
4534 case MESA_SHADER_TESS_CTRL
:
4535 /* nothing to be done */
4537 case MESA_SHADER_TESS_EVAL
:
4538 validate_tess_eval_shader_executable(prog
, sh
, ctx
);
4540 case MESA_SHADER_GEOMETRY
:
4541 validate_geometry_shader_executable(prog
, sh
, ctx
);
4543 case MESA_SHADER_FRAGMENT
:
4544 validate_fragment_shader_executable(prog
, sh
);
4547 if (!prog
->LinkStatus
) {
4549 _mesa_delete_shader(ctx
, sh
);
4553 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[stage
], sh
);
4557 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0) {
4558 prog
->LastClipDistanceArraySize
= prog
->Geom
.ClipDistanceArraySize
;
4559 prog
->LastCullDistanceArraySize
= prog
->Geom
.CullDistanceArraySize
;
4560 } else if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0) {
4561 prog
->LastClipDistanceArraySize
= prog
->TessEval
.ClipDistanceArraySize
;
4562 prog
->LastCullDistanceArraySize
= prog
->TessEval
.CullDistanceArraySize
;
4563 } else if (num_shaders
[MESA_SHADER_VERTEX
] > 0) {
4564 prog
->LastClipDistanceArraySize
= prog
->Vert
.ClipDistanceArraySize
;
4565 prog
->LastCullDistanceArraySize
= prog
->Vert
.CullDistanceArraySize
;
4567 prog
->LastClipDistanceArraySize
= 0; /* Not used */
4568 prog
->LastCullDistanceArraySize
= 0; /* Not used */
4571 /* Here begins the inter-stage linking phase. Some initial validation is
4572 * performed, then locations are assigned for uniforms, attributes, and
4575 cross_validate_uniforms(prog
);
4576 if (!prog
->LinkStatus
)
4579 unsigned first
, last
, prev
;
4581 first
= MESA_SHADER_STAGES
;
4584 /* Determine first and last stage. */
4585 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4586 if (!prog
->_LinkedShaders
[i
])
4588 if (first
== MESA_SHADER_STAGES
)
4593 num_explicit_uniform_locs
= check_explicit_uniform_locations(ctx
, prog
);
4594 link_assign_subroutine_types(prog
);
4596 if (!prog
->LinkStatus
)
4599 resize_tes_inputs(ctx
, prog
);
4601 /* Validate the inputs of each stage with the output of the preceding
4605 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4606 if (prog
->_LinkedShaders
[i
] == NULL
)
4609 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
4610 prog
->_LinkedShaders
[i
]);
4611 if (!prog
->LinkStatus
)
4614 cross_validate_outputs_to_inputs(prog
,
4615 prog
->_LinkedShaders
[prev
],
4616 prog
->_LinkedShaders
[i
]);
4617 if (!prog
->LinkStatus
)
4623 /* Cross-validate uniform blocks between shader stages */
4624 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
,
4625 MESA_SHADER_STAGES
);
4626 if (!prog
->LinkStatus
)
4629 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4630 if (prog
->_LinkedShaders
[i
] != NULL
)
4631 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
4634 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4635 * it before optimization because we want most of the checks to get
4636 * dropped thanks to constant propagation.
4638 * This rule also applies to GLSL ES 3.00.
4640 if (max_version
>= (prog
->IsES
? 300 : 130)) {
4641 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4643 lower_discard_flow(sh
->ir
);
4647 if (prog
->SeparateShader
)
4648 disable_varying_optimizations_for_sso(prog
);
4651 if (!interstage_cross_validate_uniform_blocks(prog
, false))
4655 if (!interstage_cross_validate_uniform_blocks(prog
, true))
4658 /* Do common optimization before assigning storage for attributes,
4659 * uniforms, and varyings. Later optimization could possibly make
4660 * some of that unused.
4662 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4663 if (prog
->_LinkedShaders
[i
] == NULL
)
4666 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
4667 if (!prog
->LinkStatus
)
4670 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerCombinedClipCullDistance
) {
4671 lower_clip_cull_distance(prog
, prog
->_LinkedShaders
[i
]);
4674 if (ctx
->Const
.LowerTessLevel
) {
4675 lower_tess_level(prog
->_LinkedShaders
[i
]);
4678 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false,
4679 &ctx
->Const
.ShaderCompilerOptions
[i
],
4680 ctx
->Const
.NativeIntegers
))
4683 lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
);
4686 /* Validation for special cases where we allow sampler array indexing
4687 * with loop induction variable. This check emits a warning or error
4688 * depending if backend can handle dynamic indexing.
4690 if ((!prog
->IsES
&& prog
->Version
< 130) ||
4691 (prog
->IsES
&& prog
->Version
< 300)) {
4692 if (!validate_sampler_array_indexing(ctx
, prog
))
4696 /* Check and validate stream emissions in geometry shaders */
4697 validate_geometry_shader_emissions(ctx
, prog
);
4699 /* Mark all generic shader inputs and outputs as unpaired. */
4700 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4701 if (prog
->_LinkedShaders
[i
] != NULL
) {
4702 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
4707 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4708 if (prog
->_LinkedShaders
[i
] == NULL
)
4711 match_explicit_outputs_to_inputs(prog
->_LinkedShaders
[prev
],
4712 prog
->_LinkedShaders
[i
]);
4716 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
4717 MESA_SHADER_VERTEX
)) {
4721 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
4722 MESA_SHADER_FRAGMENT
)) {
4726 /* From the ARB_enhanced_layouts spec:
4728 * "If the shader used to record output variables for transform feedback
4729 * varyings uses the "xfb_buffer", "xfb_offset", or "xfb_stride" layout
4730 * qualifiers, the values specified by TransformFeedbackVaryings are
4731 * ignored, and the set of variables captured for transform feedback is
4732 * instead derived from the specified layout qualifiers."
4734 for (int i
= MESA_SHADER_FRAGMENT
- 1; i
>= 0; i
--) {
4735 /* Find last stage before fragment shader */
4736 if (prog
->_LinkedShaders
[i
]) {
4737 has_xfb_qualifiers
=
4738 process_xfb_layout_qualifiers(mem_ctx
, prog
->_LinkedShaders
[i
],
4739 &num_tfeedback_decls
,
4745 if (!has_xfb_qualifiers
) {
4746 num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
4747 varying_names
= prog
->TransformFeedback
.VaryingNames
;
4750 if (num_tfeedback_decls
!= 0) {
4751 /* From GL_EXT_transform_feedback:
4752 * A program will fail to link if:
4754 * * the <count> specified by TransformFeedbackVaryingsEXT is
4755 * non-zero, but the program object has no vertex or geometry
4758 if (first
>= MESA_SHADER_FRAGMENT
) {
4759 linker_error(prog
, "Transform feedback varyings specified, but "
4760 "no vertex, tessellation, or geometry shader is "
4765 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
4766 num_tfeedback_decls
);
4767 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
4768 varying_names
, tfeedback_decls
))
4772 /* If there is no fragment shader we need to set transform feedback.
4774 * For SSO we also need to assign output locations. We assign them here
4775 * because we need to do it for both single stage programs and multi stage
4778 if (last
< MESA_SHADER_FRAGMENT
&&
4779 (num_tfeedback_decls
!= 0 || prog
->SeparateShader
)) {
4780 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
4781 prog
->_LinkedShaders
[last
], NULL
,
4782 num_tfeedback_decls
, tfeedback_decls
))
4786 if (last
<= MESA_SHADER_FRAGMENT
) {
4787 /* Remove unused varyings from the first/last stage unless SSO */
4788 remove_unused_shader_inputs_and_outputs(prog
->SeparateShader
,
4789 prog
->_LinkedShaders
[first
],
4791 remove_unused_shader_inputs_and_outputs(prog
->SeparateShader
,
4792 prog
->_LinkedShaders
[last
],
4795 /* If the program is made up of only a single stage */
4796 if (first
== last
) {
4798 gl_shader
*const sh
= prog
->_LinkedShaders
[last
];
4799 if (prog
->SeparateShader
) {
4800 /* Assign input locations for SSO, output locations are already
4803 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
4804 NULL
/* producer */,
4806 0 /* num_tfeedback_decls */,
4807 NULL
/* tfeedback_decls */))
4811 do_dead_builtin_varyings(ctx
, NULL
, sh
, 0, NULL
);
4812 do_dead_builtin_varyings(ctx
, sh
, NULL
, num_tfeedback_decls
,
4815 /* Linking the stages in the opposite order (from fragment to vertex)
4816 * ensures that inter-shader outputs written to in an earlier stage
4817 * are eliminated if they are (transitively) not used in a later
4821 for (int i
= next
- 1; i
>= 0; i
--) {
4822 if (prog
->_LinkedShaders
[i
] == NULL
&& i
!= 0)
4825 gl_shader
*const sh_i
= prog
->_LinkedShaders
[i
];
4826 gl_shader
*const sh_next
= prog
->_LinkedShaders
[next
];
4828 if (!assign_varying_locations(ctx
, mem_ctx
, prog
, sh_i
, sh_next
,
4829 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
4833 do_dead_builtin_varyings(ctx
, sh_i
, sh_next
,
4834 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
4837 /* This must be done after all dead varyings are eliminated. */
4839 if (!check_against_output_limit(ctx
, prog
, sh_i
)) {
4843 if (!check_against_input_limit(ctx
, prog
, sh_next
))
4851 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
,
4852 has_xfb_qualifiers
))
4855 update_array_sizes(prog
);
4856 link_assign_uniform_locations(prog
, ctx
->Const
.UniformBooleanTrue
,
4857 num_explicit_uniform_locs
,
4858 ctx
->Const
.MaxUserAssignableUniformLocations
);
4859 link_assign_atomic_counter_resources(ctx
, prog
);
4860 store_fragdepth_layout(prog
);
4862 link_calculate_subroutine_compat(prog
);
4863 check_resources(ctx
, prog
);
4864 check_subroutine_resources(prog
);
4865 check_image_resources(ctx
, prog
);
4866 link_check_atomic_counter_resources(ctx
, prog
);
4868 if (!prog
->LinkStatus
)
4871 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
4872 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
4873 * anything about shader linking when one of the shaders (vertex or
4874 * fragment shader) is absent. So, the extension shouldn't change the
4875 * behavior specified in GLSL specification.
4877 * From OpenGL ES 3.1 specification (7.3 Program Objects):
4878 * "Linking can fail for a variety of reasons as specified in the
4879 * OpenGL ES Shading Language Specification, as well as any of the
4880 * following reasons:
4884 * * program contains objects to form either a vertex shader or
4885 * fragment shader, and program is not separable, and does not
4886 * contain objects to form both a vertex shader and fragment
4889 * However, the only scenario in 3.1+ where we don't require them both is
4890 * when we have a compute shader. For example:
4892 * - No shaders is a link error.
4893 * - Geom or Tess without a Vertex shader is a link error which means we
4894 * always require a Vertex shader and hence a Fragment shader.
4895 * - Finally a Compute shader linked with any other stage is a link error.
4897 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
&&
4898 num_shaders
[MESA_SHADER_COMPUTE
] == 0) {
4899 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
4900 linker_error(prog
, "program lacks a vertex shader\n");
4901 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
4902 linker_error(prog
, "program lacks a fragment shader\n");
4906 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4907 if (prog
->_LinkedShaders
[i
] == NULL
)
4910 const struct gl_shader_compiler_options
*options
=
4911 &ctx
->Const
.ShaderCompilerOptions
[i
];
4913 if (options
->LowerBufferInterfaceBlocks
)
4914 lower_ubo_reference(prog
->_LinkedShaders
[i
],
4915 options
->ClampBlockIndicesToArrayBounds
);
4917 if (options
->LowerShaderSharedVariables
)
4918 lower_shared_reference(prog
->_LinkedShaders
[i
],
4919 &prog
->Comp
.SharedSize
);
4921 lower_vector_derefs(prog
->_LinkedShaders
[i
]);
4922 do_vec_index_to_swizzle(prog
->_LinkedShaders
[i
]->ir
);
4926 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4927 free(shader_list
[i
]);
4928 if (prog
->_LinkedShaders
[i
] == NULL
)
4931 /* Do a final validation step to make sure that the IR wasn't
4932 * invalidated by any modifications performed after intrastage linking.
4934 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
4936 /* Retain any live IR, but trash the rest. */
4937 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
4939 /* The symbol table in the linked shaders may contain references to
4940 * variables that were removed (e.g., unused uniforms). Since it may
4941 * contain junk, there is no possible valid use. Delete it and set the
4944 delete prog
->_LinkedShaders
[i
]->symbols
;
4945 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
4948 ralloc_free(mem_ctx
);