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"
85 void linker_error(gl_shader_program
*, const char *, ...);
90 * Visitor that determines whether or not a variable is ever written.
92 class find_assignment_visitor
: public ir_hierarchical_visitor
{
94 find_assignment_visitor(const char *name
)
95 : name(name
), found(false)
100 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
102 ir_variable
*const var
= ir
->lhs
->variable_referenced();
104 if (strcmp(name
, var
->name
) == 0) {
109 return visit_continue_with_parent
;
112 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
114 foreach_two_lists(formal_node
, &ir
->callee
->parameters
,
115 actual_node
, &ir
->actual_parameters
) {
116 ir_rvalue
*param_rval
= (ir_rvalue
*) actual_node
;
117 ir_variable
*sig_param
= (ir_variable
*) formal_node
;
119 if (sig_param
->data
.mode
== ir_var_function_out
||
120 sig_param
->data
.mode
== ir_var_function_inout
) {
121 ir_variable
*var
= param_rval
->variable_referenced();
122 if (var
&& strcmp(name
, var
->name
) == 0) {
129 if (ir
->return_deref
!= NULL
) {
130 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
132 if (strcmp(name
, var
->name
) == 0) {
138 return visit_continue_with_parent
;
141 bool variable_found()
147 const char *name
; /**< Find writes to a variable with this name. */
148 bool found
; /**< Was a write to the variable found? */
153 * Visitor that determines whether or not a variable is ever read.
155 class find_deref_visitor
: public ir_hierarchical_visitor
{
157 find_deref_visitor(const char *name
)
158 : name(name
), found(false)
163 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
165 if (strcmp(this->name
, ir
->var
->name
) == 0) {
170 return visit_continue
;
173 bool variable_found() const
179 const char *name
; /**< Find writes to a variable with this name. */
180 bool found
; /**< Was a write to the variable found? */
184 class geom_array_resize_visitor
: public ir_hierarchical_visitor
{
186 unsigned num_vertices
;
187 gl_shader_program
*prog
;
189 geom_array_resize_visitor(unsigned num_vertices
, gl_shader_program
*prog
)
191 this->num_vertices
= num_vertices
;
195 virtual ~geom_array_resize_visitor()
200 virtual ir_visitor_status
visit(ir_variable
*var
)
202 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
)
203 return visit_continue
;
205 unsigned size
= var
->type
->length
;
207 /* Generate a link error if the shader has declared this array with an
210 if (size
&& size
!= this->num_vertices
) {
211 linker_error(this->prog
, "size of array %s declared as %u, "
212 "but number of input vertices is %u\n",
213 var
->name
, size
, this->num_vertices
);
214 return visit_continue
;
217 /* Generate a link error if the shader attempts to access an input
218 * array using an index too large for its actual size assigned at link
221 if (var
->data
.max_array_access
>= this->num_vertices
) {
222 linker_error(this->prog
, "geometry shader accesses element %i of "
223 "%s, but only %i input vertices\n",
224 var
->data
.max_array_access
, var
->name
, this->num_vertices
);
225 return visit_continue
;
228 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
230 var
->data
.max_array_access
= this->num_vertices
- 1;
232 return visit_continue
;
235 /* Dereferences of input variables need to be updated so that their type
236 * matches the newly assigned type of the variable they are accessing. */
237 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
239 ir
->type
= ir
->var
->type
;
240 return visit_continue
;
243 /* Dereferences of 2D input arrays need to be updated so that their type
244 * matches the newly assigned type of the array they are accessing. */
245 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
247 const glsl_type
*const vt
= ir
->array
->type
;
249 ir
->type
= vt
->fields
.array
;
250 return visit_continue
;
254 class tess_eval_array_resize_visitor
: public ir_hierarchical_visitor
{
256 unsigned num_vertices
;
257 gl_shader_program
*prog
;
259 tess_eval_array_resize_visitor(unsigned num_vertices
, gl_shader_program
*prog
)
261 this->num_vertices
= num_vertices
;
265 virtual ~tess_eval_array_resize_visitor()
270 virtual ir_visitor_status
visit(ir_variable
*var
)
272 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
|| var
->data
.patch
)
273 return visit_continue
;
275 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
277 var
->data
.max_array_access
= this->num_vertices
- 1;
279 return visit_continue
;
282 /* Dereferences of input variables need to be updated so that their type
283 * matches the newly assigned type of the variable they are accessing. */
284 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
286 ir
->type
= ir
->var
->type
;
287 return visit_continue
;
290 /* Dereferences of 2D input arrays need to be updated so that their type
291 * matches the newly assigned type of the array they are accessing. */
292 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
294 const glsl_type
*const vt
= ir
->array
->type
;
296 ir
->type
= vt
->fields
.array
;
297 return visit_continue
;
301 class barrier_use_visitor
: public ir_hierarchical_visitor
{
303 barrier_use_visitor(gl_shader_program
*prog
)
304 : prog(prog
), in_main(false), after_return(false), control_flow(0)
308 virtual ~barrier_use_visitor()
313 virtual ir_visitor_status
visit_enter(ir_function
*ir
)
315 if (strcmp(ir
->name
, "main") == 0)
318 return visit_continue
;
321 virtual ir_visitor_status
visit_leave(ir_function
*)
324 after_return
= false;
325 return visit_continue
;
328 virtual ir_visitor_status
visit_leave(ir_return
*)
331 return visit_continue
;
334 virtual ir_visitor_status
visit_enter(ir_if
*)
337 return visit_continue
;
340 virtual ir_visitor_status
visit_leave(ir_if
*)
343 return visit_continue
;
346 virtual ir_visitor_status
visit_enter(ir_loop
*)
349 return visit_continue
;
352 virtual ir_visitor_status
visit_leave(ir_loop
*)
355 return visit_continue
;
358 /* FINISHME: `switch` is not expressed at the IR level -- it's already
359 * been lowered to a mess of `if`s. We'll correctly disallow any use of
360 * barrier() in a conditional path within the switch, but not in a path
361 * which is always hit.
364 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
366 if (ir
->use_builtin
&& strcmp(ir
->callee_name(), "barrier") == 0) {
367 /* Use of barrier(); determine if it is legal: */
369 linker_error(prog
, "Builtin barrier() may only be used in main");
374 linker_error(prog
, "Builtin barrier() may not be used after return");
378 if (control_flow
!= 0) {
379 linker_error(prog
, "Builtin barrier() may not be used inside control flow");
383 return visit_continue
;
387 gl_shader_program
*prog
;
388 bool in_main
, after_return
;
393 * Visitor that determines the highest stream id to which a (geometry) shader
394 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
396 class find_emit_vertex_visitor
: public ir_hierarchical_visitor
{
398 find_emit_vertex_visitor(int max_allowed
)
399 : max_stream_allowed(max_allowed
),
400 invalid_stream_id(0),
401 invalid_stream_id_from_emit_vertex(false),
402 end_primitive_found(false),
403 uses_non_zero_stream(false)
408 virtual ir_visitor_status
visit_leave(ir_emit_vertex
*ir
)
410 int stream_id
= ir
->stream_id();
413 invalid_stream_id
= stream_id
;
414 invalid_stream_id_from_emit_vertex
= true;
418 if (stream_id
> max_stream_allowed
) {
419 invalid_stream_id
= stream_id
;
420 invalid_stream_id_from_emit_vertex
= true;
425 uses_non_zero_stream
= true;
427 return visit_continue
;
430 virtual ir_visitor_status
visit_leave(ir_end_primitive
*ir
)
432 end_primitive_found
= true;
434 int stream_id
= ir
->stream_id();
437 invalid_stream_id
= stream_id
;
438 invalid_stream_id_from_emit_vertex
= false;
442 if (stream_id
> max_stream_allowed
) {
443 invalid_stream_id
= stream_id
;
444 invalid_stream_id_from_emit_vertex
= false;
449 uses_non_zero_stream
= true;
451 return visit_continue
;
456 return invalid_stream_id
!= 0;
459 const char *error_func()
461 return invalid_stream_id_from_emit_vertex
?
462 "EmitStreamVertex" : "EndStreamPrimitive";
467 return invalid_stream_id
;
472 return uses_non_zero_stream
;
475 bool uses_end_primitive()
477 return end_primitive_found
;
481 int max_stream_allowed
;
482 int invalid_stream_id
;
483 bool invalid_stream_id_from_emit_vertex
;
484 bool end_primitive_found
;
485 bool uses_non_zero_stream
;
488 /* Class that finds array derefs and check if indexes are dynamic. */
489 class dynamic_sampler_array_indexing_visitor
: public ir_hierarchical_visitor
492 dynamic_sampler_array_indexing_visitor() :
493 dynamic_sampler_array_indexing(false)
497 ir_visitor_status
visit_enter(ir_dereference_array
*ir
)
499 if (!ir
->variable_referenced())
500 return visit_continue
;
502 if (!ir
->variable_referenced()->type
->contains_sampler())
503 return visit_continue
;
505 if (!ir
->array_index
->constant_expression_value()) {
506 dynamic_sampler_array_indexing
= true;
509 return visit_continue
;
512 bool uses_dynamic_sampler_array_indexing()
514 return dynamic_sampler_array_indexing
;
518 bool dynamic_sampler_array_indexing
;
521 } /* anonymous namespace */
524 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
528 ralloc_strcat(&prog
->InfoLog
, "error: ");
530 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
533 prog
->LinkStatus
= false;
538 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
542 ralloc_strcat(&prog
->InfoLog
, "warning: ");
544 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
551 * Given a string identifying a program resource, break it into a base name
552 * and an optional array index in square brackets.
554 * If an array index is present, \c out_base_name_end is set to point to the
555 * "[" that precedes the array index, and the array index itself is returned
558 * If no array index is present (or if the array index is negative or
559 * mal-formed), \c out_base_name_end, is set to point to the null terminator
560 * at the end of the input string, and -1 is returned.
562 * Only the final array index is parsed; if the string contains other array
563 * indices (or structure field accesses), they are left in the base name.
565 * No attempt is made to check that the base name is properly formed;
566 * typically the caller will look up the base name in a hash table, so
567 * ill-formed base names simply turn into hash table lookup failures.
570 parse_program_resource_name(const GLchar
*name
,
571 const GLchar
**out_base_name_end
)
573 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
575 * "When an integer array element or block instance number is part of
576 * the name string, it will be specified in decimal form without a "+"
577 * or "-" sign or any extra leading zeroes. Additionally, the name
578 * string will not include white space anywhere in the string."
581 const size_t len
= strlen(name
);
582 *out_base_name_end
= name
+ len
;
584 if (len
== 0 || name
[len
-1] != ']')
587 /* Walk backwards over the string looking for a non-digit character. This
588 * had better be the opening bracket for an array index.
590 * Initially, i specifies the location of the ']'. Since the string may
591 * contain only the ']' charcater, walk backwards very carefully.
594 for (i
= len
- 1; (i
> 0) && isdigit(name
[i
-1]); --i
)
597 if ((i
== 0) || name
[i
-1] != '[')
600 long array_index
= strtol(&name
[i
], NULL
, 10);
604 /* Check for leading zero */
605 if (name
[i
] == '0' && name
[i
+1] != ']')
608 *out_base_name_end
= name
+ (i
- 1);
614 link_invalidate_variable_locations(exec_list
*ir
)
616 foreach_in_list(ir_instruction
, node
, ir
) {
617 ir_variable
*const var
= node
->as_variable();
622 /* Only assign locations for variables that lack an explicit location.
623 * Explicit locations are set for all built-in variables, generic vertex
624 * shader inputs (via layout(location=...)), and generic fragment shader
625 * outputs (also via layout(location=...)).
627 if (!var
->data
.explicit_location
) {
628 var
->data
.location
= -1;
629 var
->data
.location_frac
= 0;
632 /* ir_variable::is_unmatched_generic_inout is used by the linker while
633 * connecting outputs from one stage to inputs of the next stage.
635 if (var
->data
.explicit_location
&&
636 var
->data
.location
< VARYING_SLOT_VAR0
) {
637 var
->data
.is_unmatched_generic_inout
= 0;
639 var
->data
.is_unmatched_generic_inout
= 1;
646 * Set clip_distance_array_size based on the given shader.
648 * Also check for errors based on incorrect usage of gl_ClipVertex and
651 * Return false if an error was reported.
654 analyze_clip_usage(struct gl_shader_program
*prog
,
655 struct gl_shader
*shader
,
656 GLuint
*clip_distance_array_size
)
658 *clip_distance_array_size
= 0;
660 if (!prog
->IsES
&& prog
->Version
>= 130) {
661 /* From section 7.1 (Vertex Shader Special Variables) of the
664 * "It is an error for a shader to statically write both
665 * gl_ClipVertex and gl_ClipDistance."
667 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
668 * gl_ClipVertex nor gl_ClipDistance.
670 find_assignment_visitor
clip_vertex("gl_ClipVertex");
671 find_assignment_visitor
clip_distance("gl_ClipDistance");
673 clip_vertex
.run(shader
->ir
);
674 clip_distance
.run(shader
->ir
);
675 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
676 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
677 "and `gl_ClipDistance'\n",
678 _mesa_shader_stage_to_string(shader
->Stage
));
682 if (clip_distance
.variable_found()) {
683 ir_variable
*clip_distance_var
=
684 shader
->symbols
->get_variable("gl_ClipDistance");
686 assert(clip_distance_var
);
687 *clip_distance_array_size
= clip_distance_var
->type
->length
;
694 * Verify that a vertex shader executable meets all semantic requirements.
696 * Also sets prog->Vert.ClipDistanceArraySize as a side effect.
698 * \param shader Vertex shader executable to be verified
701 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
702 struct gl_shader
*shader
)
707 /* From the GLSL 1.10 spec, page 48:
709 * "The variable gl_Position is available only in the vertex
710 * language and is intended for writing the homogeneous vertex
711 * position. All executions of a well-formed vertex shader
712 * executable must write a value into this variable. [...] The
713 * variable gl_Position is available only in the vertex
714 * language and is intended for writing the homogeneous vertex
715 * position. All executions of a well-formed vertex shader
716 * executable must write a value into this variable."
718 * while in GLSL 1.40 this text is changed to:
720 * "The variable gl_Position is available only in the vertex
721 * language and is intended for writing the homogeneous vertex
722 * position. It can be written at any time during shader
723 * execution. It may also be read back by a vertex shader
724 * after being written. This value will be used by primitive
725 * assembly, clipping, culling, and other fixed functionality
726 * operations, if present, that operate on primitives after
727 * vertex processing has occurred. Its value is undefined if
728 * the vertex shader executable does not write gl_Position."
730 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
731 * gl_Position is not an error.
733 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
734 find_assignment_visitor
find("gl_Position");
735 find
.run(shader
->ir
);
736 if (!find
.variable_found()) {
739 "vertex shader does not write to `gl_Position'."
740 "It's value is undefined. \n");
743 "vertex shader does not write to `gl_Position'. \n");
749 analyze_clip_usage(prog
, shader
, &prog
->Vert
.ClipDistanceArraySize
);
753 validate_tess_eval_shader_executable(struct gl_shader_program
*prog
,
754 struct gl_shader
*shader
)
759 analyze_clip_usage(prog
, shader
, &prog
->TessEval
.ClipDistanceArraySize
);
764 * Verify that a fragment shader executable meets all semantic requirements
766 * \param shader Fragment shader executable to be verified
769 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
770 struct gl_shader
*shader
)
775 find_assignment_visitor
frag_color("gl_FragColor");
776 find_assignment_visitor
frag_data("gl_FragData");
778 frag_color
.run(shader
->ir
);
779 frag_data
.run(shader
->ir
);
781 if (frag_color
.variable_found() && frag_data
.variable_found()) {
782 linker_error(prog
, "fragment shader writes to both "
783 "`gl_FragColor' and `gl_FragData'\n");
788 * Verify that a geometry shader executable meets all semantic requirements
790 * Also sets prog->Geom.VerticesIn, and prog->Geom.ClipDistanceArraySize as
793 * \param shader Geometry shader executable to be verified
796 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
797 struct gl_shader
*shader
)
802 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
803 prog
->Geom
.VerticesIn
= num_vertices
;
805 analyze_clip_usage(prog
, shader
, &prog
->Geom
.ClipDistanceArraySize
);
809 * Check if geometry shaders emit to non-zero streams and do corresponding
813 validate_geometry_shader_emissions(struct gl_context
*ctx
,
814 struct gl_shader_program
*prog
)
816 if (prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
] != NULL
) {
817 find_emit_vertex_visitor
emit_vertex(ctx
->Const
.MaxVertexStreams
- 1);
818 emit_vertex
.run(prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
]->ir
);
819 if (emit_vertex
.error()) {
820 linker_error(prog
, "Invalid call %s(%d). Accepted values for the "
821 "stream parameter are in the range [0, %d].\n",
822 emit_vertex
.error_func(),
823 emit_vertex
.error_stream(),
824 ctx
->Const
.MaxVertexStreams
- 1);
826 prog
->Geom
.UsesStreams
= emit_vertex
.uses_streams();
827 prog
->Geom
.UsesEndPrimitive
= emit_vertex
.uses_end_primitive();
829 /* From the ARB_gpu_shader5 spec:
831 * "Multiple vertex streams are supported only if the output primitive
832 * type is declared to be "points". A program will fail to link if it
833 * contains a geometry shader calling EmitStreamVertex() or
834 * EndStreamPrimitive() if its output primitive type is not "points".
836 * However, in the same spec:
838 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
839 * with <stream> set to zero."
843 * "The function EndPrimitive() is equivalent to calling
844 * EndStreamPrimitive() with <stream> set to zero."
846 * Since we can call EmitVertex() and EndPrimitive() when we output
847 * primitives other than points, calling EmitStreamVertex(0) or
848 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
849 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
850 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
853 if (prog
->Geom
.UsesStreams
&& prog
->Geom
.OutputType
!= GL_POINTS
) {
854 linker_error(prog
, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
855 "with n>0 requires point output\n");
861 validate_intrastage_arrays(struct gl_shader_program
*prog
,
862 ir_variable
*const var
,
863 ir_variable
*const existing
)
865 /* Consider the types to be "the same" if both types are arrays
866 * of the same type and one of the arrays is implicitly sized.
867 * In addition, set the type of the linked variable to the
868 * explicitly sized array.
870 if (var
->type
->is_array() && existing
->type
->is_array()) {
871 if ((var
->type
->fields
.array
== existing
->type
->fields
.array
) &&
872 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
873 if (var
->type
->length
!= 0) {
874 if (var
->type
->length
<= existing
->data
.max_array_access
) {
875 linker_error(prog
, "%s `%s' declared as type "
876 "`%s' but outermost dimension has an index"
879 var
->name
, var
->type
->name
,
880 existing
->data
.max_array_access
);
882 existing
->type
= var
->type
;
884 } else if (existing
->type
->length
!= 0) {
885 if(existing
->type
->length
<= var
->data
.max_array_access
&&
886 !existing
->data
.from_ssbo_unsized_array
) {
887 linker_error(prog
, "%s `%s' declared as type "
888 "`%s' but outermost dimension has an index"
891 var
->name
, existing
->type
->name
,
892 var
->data
.max_array_access
);
897 /* The arrays of structs could have different glsl_type pointers but
898 * they are actually the same type. Use record_compare() to check that.
900 if (existing
->type
->fields
.array
->is_record() &&
901 var
->type
->fields
.array
->is_record() &&
902 existing
->type
->fields
.array
->record_compare(var
->type
->fields
.array
))
911 * Perform validation of global variables used across multiple shaders
914 cross_validate_globals(struct gl_shader_program
*prog
,
915 struct gl_shader
**shader_list
,
916 unsigned num_shaders
,
919 /* Examine all of the uniforms in all of the shaders and cross validate
922 glsl_symbol_table variables
;
923 for (unsigned i
= 0; i
< num_shaders
; i
++) {
924 if (shader_list
[i
] == NULL
)
927 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
928 ir_variable
*const var
= node
->as_variable();
933 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
936 /* don't cross validate subroutine uniforms */
937 if (var
->type
->contains_subroutine())
940 /* Don't cross validate temporaries that are at global scope. These
941 * will eventually get pulled into the shaders 'main'.
943 if (var
->data
.mode
== ir_var_temporary
)
946 /* If a global with this name has already been seen, verify that the
947 * new instance has the same type. In addition, if the globals have
948 * initializers, the values of the initializers must be the same.
950 ir_variable
*const existing
= variables
.get_variable(var
->name
);
951 if (existing
!= NULL
) {
952 /* Check if types match. Interface blocks have some special
953 * rules so we handle those elsewhere.
955 if (var
->type
!= existing
->type
&&
956 !var
->is_interface_instance()) {
957 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
958 if (var
->type
->is_record() && existing
->type
->is_record()
959 && existing
->type
->record_compare(var
->type
)) {
960 existing
->type
= var
->type
;
962 /* If it is an unsized array in a Shader Storage Block,
963 * two different shaders can access to different elements.
964 * Because of that, they might be converted to different
965 * sized arrays, then check that they are compatible but
966 * ignore the array size.
968 if (!(var
->data
.mode
== ir_var_shader_storage
&&
969 var
->data
.from_ssbo_unsized_array
&&
970 existing
->data
.mode
== ir_var_shader_storage
&&
971 existing
->data
.from_ssbo_unsized_array
&&
972 var
->type
->gl_type
== existing
->type
->gl_type
)) {
973 linker_error(prog
, "%s `%s' declared as type "
974 "`%s' and type `%s'\n",
976 var
->name
, var
->type
->name
,
977 existing
->type
->name
);
984 if (var
->data
.explicit_location
) {
985 if (existing
->data
.explicit_location
986 && (var
->data
.location
!= existing
->data
.location
)) {
987 linker_error(prog
, "explicit locations for %s "
988 "`%s' have differing values\n",
989 mode_string(var
), var
->name
);
993 existing
->data
.location
= var
->data
.location
;
994 existing
->data
.explicit_location
= true;
997 /* From the GLSL 4.20 specification:
998 * "A link error will result if two compilation units in a program
999 * specify different integer-constant bindings for the same
1000 * opaque-uniform name. However, it is not an error to specify a
1001 * binding on some but not all declarations for the same name"
1003 if (var
->data
.explicit_binding
) {
1004 if (existing
->data
.explicit_binding
&&
1005 var
->data
.binding
!= existing
->data
.binding
) {
1006 linker_error(prog
, "explicit bindings for %s "
1007 "`%s' have differing values\n",
1008 mode_string(var
), var
->name
);
1012 existing
->data
.binding
= var
->data
.binding
;
1013 existing
->data
.explicit_binding
= true;
1016 if (var
->type
->contains_atomic() &&
1017 var
->data
.atomic
.offset
!= existing
->data
.atomic
.offset
) {
1018 linker_error(prog
, "offset specifications for %s "
1019 "`%s' have differing values\n",
1020 mode_string(var
), var
->name
);
1024 /* Validate layout qualifiers for gl_FragDepth.
1026 * From the AMD/ARB_conservative_depth specs:
1028 * "If gl_FragDepth is redeclared in any fragment shader in a
1029 * program, it must be redeclared in all fragment shaders in
1030 * that program that have static assignments to
1031 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1032 * fragment shaders in a single program must have the same set
1035 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1036 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1037 bool layout_differs
=
1038 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1040 if (layout_declared
&& layout_differs
) {
1042 "All redeclarations of gl_FragDepth in all "
1043 "fragment shaders in a single program must have "
1044 "the same set of qualifiers.\n");
1047 if (var
->data
.used
&& layout_differs
) {
1049 "If gl_FragDepth is redeclared with a layout "
1050 "qualifier in any fragment shader, it must be "
1051 "redeclared with the same layout qualifier in "
1052 "all fragment shaders that have assignments to "
1057 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1059 * "If a shared global has multiple initializers, the
1060 * initializers must all be constant expressions, and they
1061 * must all have the same value. Otherwise, a link error will
1062 * result. (A shared global having only one initializer does
1063 * not require that initializer to be a constant expression.)"
1065 * Previous to 4.20 the GLSL spec simply said that initializers
1066 * must have the same value. In this case of non-constant
1067 * initializers, this was impossible to determine. As a result,
1068 * no vendor actually implemented that behavior. The 4.20
1069 * behavior matches the implemented behavior of at least one other
1070 * vendor, so we'll implement that for all GLSL versions.
1072 if (var
->constant_initializer
!= NULL
) {
1073 if (existing
->constant_initializer
!= NULL
) {
1074 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1075 linker_error(prog
, "initializers for %s "
1076 "`%s' have differing values\n",
1077 mode_string(var
), var
->name
);
1081 /* If the first-seen instance of a particular uniform did not
1082 * have an initializer but a later instance does, copy the
1083 * initializer to the version stored in the symbol table.
1085 /* FINISHME: This is wrong. The constant_value field should
1086 * FINISHME: not be modified! Imagine a case where a shader
1087 * FINISHME: without an initializer is linked in two different
1088 * FINISHME: programs with shaders that have differing
1089 * FINISHME: initializers. Linking with the first will
1090 * FINISHME: modify the shader, and linking with the second
1091 * FINISHME: will fail.
1093 existing
->constant_initializer
=
1094 var
->constant_initializer
->clone(ralloc_parent(existing
),
1099 if (var
->data
.has_initializer
) {
1100 if (existing
->data
.has_initializer
1101 && (var
->constant_initializer
== NULL
1102 || existing
->constant_initializer
== NULL
)) {
1104 "shared global variable `%s' has multiple "
1105 "non-constant initializers.\n",
1110 /* Some instance had an initializer, so keep track of that. In
1111 * this location, all sorts of initializers (constant or
1112 * otherwise) will propagate the existence to the variable
1113 * stored in the symbol table.
1115 existing
->data
.has_initializer
= true;
1118 if (existing
->data
.invariant
!= var
->data
.invariant
) {
1119 linker_error(prog
, "declarations for %s `%s' have "
1120 "mismatching invariant qualifiers\n",
1121 mode_string(var
), var
->name
);
1124 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1125 linker_error(prog
, "declarations for %s `%s' have "
1126 "mismatching centroid qualifiers\n",
1127 mode_string(var
), var
->name
);
1130 if (existing
->data
.sample
!= var
->data
.sample
) {
1131 linker_error(prog
, "declarations for %s `%s` have "
1132 "mismatching sample qualifiers\n",
1133 mode_string(var
), var
->name
);
1137 variables
.add_variable(var
);
1144 * Perform validation of uniforms used across multiple shader stages
1147 cross_validate_uniforms(struct gl_shader_program
*prog
)
1149 cross_validate_globals(prog
, prog
->_LinkedShaders
,
1150 MESA_SHADER_STAGES
, true);
1154 * Accumulates the array of prog->BufferInterfaceBlocks and checks that all
1155 * definitons of blocks agree on their contents.
1158 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
)
1160 unsigned max_num_uniform_blocks
= 0;
1161 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1162 if (prog
->_LinkedShaders
[i
])
1163 max_num_uniform_blocks
+= prog
->_LinkedShaders
[i
]->NumBufferInterfaceBlocks
;
1166 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1167 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
1169 prog
->InterfaceBlockStageIndex
[i
] = ralloc_array(prog
, int,
1170 max_num_uniform_blocks
);
1171 for (unsigned int j
= 0; j
< max_num_uniform_blocks
; j
++)
1172 prog
->InterfaceBlockStageIndex
[i
][j
] = -1;
1177 for (unsigned int j
= 0; j
< sh
->NumBufferInterfaceBlocks
; j
++) {
1178 int index
= link_cross_validate_uniform_block(prog
,
1179 &prog
->BufferInterfaceBlocks
,
1180 &prog
->NumBufferInterfaceBlocks
,
1181 &sh
->BufferInterfaceBlocks
[j
]);
1184 linker_error(prog
, "uniform block `%s' has mismatching definitions\n",
1185 sh
->BufferInterfaceBlocks
[j
].Name
);
1189 prog
->InterfaceBlockStageIndex
[i
][index
] = j
;
1198 * Populates a shaders symbol table with all global declarations
1201 populate_symbol_table(gl_shader
*sh
)
1203 sh
->symbols
= new(sh
) glsl_symbol_table
;
1205 foreach_in_list(ir_instruction
, inst
, sh
->ir
) {
1209 if ((func
= inst
->as_function()) != NULL
) {
1210 sh
->symbols
->add_function(func
);
1211 } else if ((var
= inst
->as_variable()) != NULL
) {
1212 if (var
->data
.mode
!= ir_var_temporary
)
1213 sh
->symbols
->add_variable(var
);
1220 * Remap variables referenced in an instruction tree
1222 * This is used when instruction trees are cloned from one shader and placed in
1223 * another. These trees will contain references to \c ir_variable nodes that
1224 * do not exist in the target shader. This function finds these \c ir_variable
1225 * references and replaces the references with matching variables in the target
1228 * If there is no matching variable in the target shader, a clone of the
1229 * \c ir_variable is made and added to the target shader. The new variable is
1230 * added to \b both the instruction stream and the symbol table.
1232 * \param inst IR tree that is to be processed.
1233 * \param symbols Symbol table containing global scope symbols in the
1235 * \param instructions Instruction stream where new variable declarations
1239 remap_variables(ir_instruction
*inst
, struct gl_shader
*target
,
1242 class remap_visitor
: public ir_hierarchical_visitor
{
1244 remap_visitor(struct gl_shader
*target
,
1247 this->target
= target
;
1248 this->symbols
= target
->symbols
;
1249 this->instructions
= target
->ir
;
1250 this->temps
= temps
;
1253 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1255 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1256 ir_variable
*var
= (ir_variable
*) hash_table_find(temps
, ir
->var
);
1258 assert(var
!= NULL
);
1260 return visit_continue
;
1263 ir_variable
*const existing
=
1264 this->symbols
->get_variable(ir
->var
->name
);
1265 if (existing
!= NULL
)
1268 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1270 this->symbols
->add_variable(copy
);
1271 this->instructions
->push_head(copy
);
1275 return visit_continue
;
1279 struct gl_shader
*target
;
1280 glsl_symbol_table
*symbols
;
1281 exec_list
*instructions
;
1285 remap_visitor
v(target
, temps
);
1292 * Move non-declarations from one instruction stream to another
1294 * The intended usage pattern of this function is to pass the pointer to the
1295 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1296 * pointer) for \c last and \c false for \c make_copies on the first
1297 * call. Successive calls pass the return value of the previous call for
1298 * \c last and \c true for \c make_copies.
1300 * \param instructions Source instruction stream
1301 * \param last Instruction after which new instructions should be
1302 * inserted in the target instruction stream
1303 * \param make_copies Flag selecting whether instructions in \c instructions
1304 * should be copied (via \c ir_instruction::clone) into the
1305 * target list or moved.
1308 * The new "last" instruction in the target instruction stream. This pointer
1309 * is suitable for use as the \c last parameter of a later call to this
1313 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1314 bool make_copies
, gl_shader
*target
)
1316 hash_table
*temps
= NULL
;
1319 temps
= hash_table_ctor(0, hash_table_pointer_hash
,
1320 hash_table_pointer_compare
);
1322 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1323 if (inst
->as_function())
1326 ir_variable
*var
= inst
->as_variable();
1327 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1330 assert(inst
->as_assignment()
1332 || inst
->as_if() /* for initializers with the ?: operator */
1333 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1336 inst
= inst
->clone(target
, NULL
);
1339 hash_table_insert(temps
, inst
, var
);
1341 remap_variables(inst
, target
, temps
);
1346 last
->insert_after(inst
);
1351 hash_table_dtor(temps
);
1358 * This class is only used in link_intrastage_shaders() below but declaring
1359 * it inside that function leads to compiler warnings with some versions of
1362 class array_sizing_visitor
: public ir_hierarchical_visitor
{
1364 array_sizing_visitor()
1365 : mem_ctx(ralloc_context(NULL
)),
1366 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash
,
1367 hash_table_pointer_compare
))
1371 ~array_sizing_visitor()
1373 hash_table_dtor(this->unnamed_interfaces
);
1374 ralloc_free(this->mem_ctx
);
1377 virtual ir_visitor_status
visit(ir_variable
*var
)
1379 const glsl_type
*type_without_array
;
1380 fixup_type(&var
->type
, var
->data
.max_array_access
,
1381 var
->data
.from_ssbo_unsized_array
);
1382 type_without_array
= var
->type
->without_array();
1383 if (var
->type
->is_interface()) {
1384 if (interface_contains_unsized_arrays(var
->type
)) {
1385 const glsl_type
*new_type
=
1386 resize_interface_members(var
->type
,
1387 var
->get_max_ifc_array_access(),
1388 var
->is_in_shader_storage_block());
1389 var
->type
= new_type
;
1390 var
->change_interface_type(new_type
);
1392 } else if (type_without_array
->is_interface()) {
1393 if (interface_contains_unsized_arrays(type_without_array
)) {
1394 const glsl_type
*new_type
=
1395 resize_interface_members(type_without_array
,
1396 var
->get_max_ifc_array_access(),
1397 var
->is_in_shader_storage_block());
1398 var
->change_interface_type(new_type
);
1399 var
->type
= update_interface_members_array(var
->type
, new_type
);
1401 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1402 /* Store a pointer to the variable in the unnamed_interfaces
1405 ir_variable
**interface_vars
= (ir_variable
**)
1406 hash_table_find(this->unnamed_interfaces
, ifc_type
);
1407 if (interface_vars
== NULL
) {
1408 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1410 hash_table_insert(this->unnamed_interfaces
, interface_vars
,
1413 unsigned index
= ifc_type
->field_index(var
->name
);
1414 assert(index
< ifc_type
->length
);
1415 assert(interface_vars
[index
] == NULL
);
1416 interface_vars
[index
] = var
;
1418 return visit_continue
;
1422 * For each unnamed interface block that was discovered while running the
1423 * visitor, adjust the interface type to reflect the newly assigned array
1424 * sizes, and fix up the ir_variable nodes to point to the new interface
1427 void fixup_unnamed_interface_types()
1429 hash_table_call_foreach(this->unnamed_interfaces
,
1430 fixup_unnamed_interface_type
, NULL
);
1435 * If the type pointed to by \c type represents an unsized array, replace
1436 * it with a sized array whose size is determined by max_array_access.
1438 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1439 bool from_ssbo_unsized_array
)
1441 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1442 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1443 max_array_access
+ 1);
1444 assert(*type
!= NULL
);
1448 static const glsl_type
*
1449 update_interface_members_array(const glsl_type
*type
,
1450 const glsl_type
*new_interface_type
)
1452 const glsl_type
*element_type
= type
->fields
.array
;
1453 if (element_type
->is_array()) {
1454 const glsl_type
*new_array_type
=
1455 update_interface_members_array(element_type
, new_interface_type
);
1456 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1458 return glsl_type::get_array_instance(new_interface_type
,
1464 * Determine whether the given interface type contains unsized arrays (if
1465 * it doesn't, array_sizing_visitor doesn't need to process it).
1467 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1469 for (unsigned i
= 0; i
< type
->length
; i
++) {
1470 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1471 if (elem_type
->is_unsized_array())
1478 * Create a new interface type based on the given type, with unsized arrays
1479 * replaced by sized arrays whose size is determined by
1480 * max_ifc_array_access.
1482 static const glsl_type
*
1483 resize_interface_members(const glsl_type
*type
,
1484 const unsigned *max_ifc_array_access
,
1487 unsigned num_fields
= type
->length
;
1488 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1489 memcpy(fields
, type
->fields
.structure
,
1490 num_fields
* sizeof(*fields
));
1491 for (unsigned i
= 0; i
< num_fields
; i
++) {
1492 /* If SSBO last member is unsized array, we don't replace it by a sized
1495 if (is_ssbo
&& i
== (num_fields
- 1))
1496 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1499 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1502 glsl_interface_packing packing
=
1503 (glsl_interface_packing
) type
->interface_packing
;
1504 const glsl_type
*new_ifc_type
=
1505 glsl_type::get_interface_instance(fields
, num_fields
,
1506 packing
, type
->name
);
1508 return new_ifc_type
;
1511 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1514 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1515 ir_variable
**interface_vars
= (ir_variable
**) data
;
1516 unsigned num_fields
= ifc_type
->length
;
1517 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1518 memcpy(fields
, ifc_type
->fields
.structure
,
1519 num_fields
* sizeof(*fields
));
1520 bool interface_type_changed
= false;
1521 for (unsigned i
= 0; i
< num_fields
; i
++) {
1522 if (interface_vars
[i
] != NULL
&&
1523 fields
[i
].type
!= interface_vars
[i
]->type
) {
1524 fields
[i
].type
= interface_vars
[i
]->type
;
1525 interface_type_changed
= true;
1528 if (!interface_type_changed
) {
1532 glsl_interface_packing packing
=
1533 (glsl_interface_packing
) ifc_type
->interface_packing
;
1534 const glsl_type
*new_ifc_type
=
1535 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1538 for (unsigned i
= 0; i
< num_fields
; i
++) {
1539 if (interface_vars
[i
] != NULL
)
1540 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1545 * Memory context used to allocate the data in \c unnamed_interfaces.
1550 * Hash table from const glsl_type * to an array of ir_variable *'s
1551 * pointing to the ir_variables constituting each unnamed interface block.
1553 hash_table
*unnamed_interfaces
;
1558 * Performs the cross-validation of tessellation control shader vertices and
1559 * layout qualifiers for the attached tessellation control shaders,
1560 * and propagates them to the linked TCS and linked shader program.
1563 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1564 struct gl_shader
*linked_shader
,
1565 struct gl_shader
**shader_list
,
1566 unsigned num_shaders
)
1568 linked_shader
->TessCtrl
.VerticesOut
= 0;
1570 if (linked_shader
->Stage
!= MESA_SHADER_TESS_CTRL
)
1573 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1575 * "All tessellation control shader layout declarations in a program
1576 * must specify the same output patch vertex count. There must be at
1577 * least one layout qualifier specifying an output patch vertex count
1578 * in any program containing tessellation control shaders; however,
1579 * such a declaration is not required in all tessellation control
1583 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1584 struct gl_shader
*shader
= shader_list
[i
];
1586 if (shader
->TessCtrl
.VerticesOut
!= 0) {
1587 if (linked_shader
->TessCtrl
.VerticesOut
!= 0 &&
1588 linked_shader
->TessCtrl
.VerticesOut
!= shader
->TessCtrl
.VerticesOut
) {
1589 linker_error(prog
, "tessellation control shader defined with "
1590 "conflicting output vertex count (%d and %d)\n",
1591 linked_shader
->TessCtrl
.VerticesOut
,
1592 shader
->TessCtrl
.VerticesOut
);
1595 linked_shader
->TessCtrl
.VerticesOut
= shader
->TessCtrl
.VerticesOut
;
1599 /* Just do the intrastage -> interstage propagation right now,
1600 * since we already know we're in the right type of shader program
1603 if (linked_shader
->TessCtrl
.VerticesOut
== 0) {
1604 linker_error(prog
, "tessellation control shader didn't declare "
1605 "vertices out layout qualifier\n");
1608 prog
->TessCtrl
.VerticesOut
= linked_shader
->TessCtrl
.VerticesOut
;
1613 * Performs the cross-validation of tessellation evaluation shader
1614 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1615 * for the attached tessellation evaluation shaders, and propagates them
1616 * to the linked TES and linked shader program.
1619 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1620 struct gl_shader
*linked_shader
,
1621 struct gl_shader
**shader_list
,
1622 unsigned num_shaders
)
1624 linked_shader
->TessEval
.PrimitiveMode
= PRIM_UNKNOWN
;
1625 linked_shader
->TessEval
.Spacing
= 0;
1626 linked_shader
->TessEval
.VertexOrder
= 0;
1627 linked_shader
->TessEval
.PointMode
= -1;
1629 if (linked_shader
->Stage
!= MESA_SHADER_TESS_EVAL
)
1632 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1634 * "At least one tessellation evaluation shader (compilation unit) in
1635 * a program must declare a primitive mode in its input layout.
1636 * Declaration vertex spacing, ordering, and point mode identifiers is
1637 * optional. It is not required that all tessellation evaluation
1638 * shaders in a program declare a primitive mode. If spacing or
1639 * vertex ordering declarations are omitted, the tessellation
1640 * primitive generator will use equal spacing or counter-clockwise
1641 * vertex ordering, respectively. If a point mode declaration is
1642 * omitted, the tessellation primitive generator will produce lines or
1643 * triangles according to the primitive mode."
1646 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1647 struct gl_shader
*shader
= shader_list
[i
];
1649 if (shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1650 if (linked_shader
->TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
&&
1651 linked_shader
->TessEval
.PrimitiveMode
!= shader
->TessEval
.PrimitiveMode
) {
1652 linker_error(prog
, "tessellation evaluation shader defined with "
1653 "conflicting input primitive modes.\n");
1656 linked_shader
->TessEval
.PrimitiveMode
= shader
->TessEval
.PrimitiveMode
;
1659 if (shader
->TessEval
.Spacing
!= 0) {
1660 if (linked_shader
->TessEval
.Spacing
!= 0 &&
1661 linked_shader
->TessEval
.Spacing
!= shader
->TessEval
.Spacing
) {
1662 linker_error(prog
, "tessellation evaluation shader defined with "
1663 "conflicting vertex spacing.\n");
1666 linked_shader
->TessEval
.Spacing
= shader
->TessEval
.Spacing
;
1669 if (shader
->TessEval
.VertexOrder
!= 0) {
1670 if (linked_shader
->TessEval
.VertexOrder
!= 0 &&
1671 linked_shader
->TessEval
.VertexOrder
!= shader
->TessEval
.VertexOrder
) {
1672 linker_error(prog
, "tessellation evaluation shader defined with "
1673 "conflicting ordering.\n");
1676 linked_shader
->TessEval
.VertexOrder
= shader
->TessEval
.VertexOrder
;
1679 if (shader
->TessEval
.PointMode
!= -1) {
1680 if (linked_shader
->TessEval
.PointMode
!= -1 &&
1681 linked_shader
->TessEval
.PointMode
!= shader
->TessEval
.PointMode
) {
1682 linker_error(prog
, "tessellation evaluation shader defined with "
1683 "conflicting point modes.\n");
1686 linked_shader
->TessEval
.PointMode
= shader
->TessEval
.PointMode
;
1691 /* Just do the intrastage -> interstage propagation right now,
1692 * since we already know we're in the right type of shader program
1695 if (linked_shader
->TessEval
.PrimitiveMode
== PRIM_UNKNOWN
) {
1697 "tessellation evaluation shader didn't declare input "
1698 "primitive modes.\n");
1701 prog
->TessEval
.PrimitiveMode
= linked_shader
->TessEval
.PrimitiveMode
;
1703 if (linked_shader
->TessEval
.Spacing
== 0)
1704 linked_shader
->TessEval
.Spacing
= GL_EQUAL
;
1705 prog
->TessEval
.Spacing
= linked_shader
->TessEval
.Spacing
;
1707 if (linked_shader
->TessEval
.VertexOrder
== 0)
1708 linked_shader
->TessEval
.VertexOrder
= GL_CCW
;
1709 prog
->TessEval
.VertexOrder
= linked_shader
->TessEval
.VertexOrder
;
1711 if (linked_shader
->TessEval
.PointMode
== -1)
1712 linked_shader
->TessEval
.PointMode
= GL_FALSE
;
1713 prog
->TessEval
.PointMode
= linked_shader
->TessEval
.PointMode
;
1718 * Performs the cross-validation of layout qualifiers specified in
1719 * redeclaration of gl_FragCoord for the attached fragment shaders,
1720 * and propagates them to the linked FS and linked shader program.
1723 link_fs_input_layout_qualifiers(struct gl_shader_program
*prog
,
1724 struct gl_shader
*linked_shader
,
1725 struct gl_shader
**shader_list
,
1726 unsigned num_shaders
)
1728 linked_shader
->redeclares_gl_fragcoord
= false;
1729 linked_shader
->uses_gl_fragcoord
= false;
1730 linked_shader
->origin_upper_left
= false;
1731 linked_shader
->pixel_center_integer
= false;
1733 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1734 (prog
->Version
< 150 && !prog
->ARB_fragment_coord_conventions_enable
))
1737 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1738 struct gl_shader
*shader
= shader_list
[i
];
1739 /* From the GLSL 1.50 spec, page 39:
1741 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1742 * it must be redeclared in all the fragment shaders in that program
1743 * that have a static use gl_FragCoord."
1745 if ((linked_shader
->redeclares_gl_fragcoord
1746 && !shader
->redeclares_gl_fragcoord
1747 && shader
->uses_gl_fragcoord
)
1748 || (shader
->redeclares_gl_fragcoord
1749 && !linked_shader
->redeclares_gl_fragcoord
1750 && linked_shader
->uses_gl_fragcoord
)) {
1751 linker_error(prog
, "fragment shader defined with conflicting "
1752 "layout qualifiers for gl_FragCoord\n");
1755 /* From the GLSL 1.50 spec, page 39:
1757 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1758 * single program must have the same set of qualifiers."
1760 if (linked_shader
->redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
1761 && (shader
->origin_upper_left
!= linked_shader
->origin_upper_left
1762 || shader
->pixel_center_integer
!= linked_shader
->pixel_center_integer
)) {
1763 linker_error(prog
, "fragment shader defined with conflicting "
1764 "layout qualifiers for gl_FragCoord\n");
1767 /* Update the linked shader state. Note that uses_gl_fragcoord should
1768 * accumulate the results. The other values should replace. If there
1769 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1770 * are already known to be the same.
1772 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
1773 linked_shader
->redeclares_gl_fragcoord
=
1774 shader
->redeclares_gl_fragcoord
;
1775 linked_shader
->uses_gl_fragcoord
= linked_shader
->uses_gl_fragcoord
1776 || shader
->uses_gl_fragcoord
;
1777 linked_shader
->origin_upper_left
= shader
->origin_upper_left
;
1778 linked_shader
->pixel_center_integer
= shader
->pixel_center_integer
;
1781 linked_shader
->EarlyFragmentTests
|= shader
->EarlyFragmentTests
;
1786 * Performs the cross-validation of geometry shader max_vertices and
1787 * primitive type layout qualifiers for the attached geometry shaders,
1788 * and propagates them to the linked GS and linked shader program.
1791 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1792 struct gl_shader
*linked_shader
,
1793 struct gl_shader
**shader_list
,
1794 unsigned num_shaders
)
1796 linked_shader
->Geom
.VerticesOut
= 0;
1797 linked_shader
->Geom
.Invocations
= 0;
1798 linked_shader
->Geom
.InputType
= PRIM_UNKNOWN
;
1799 linked_shader
->Geom
.OutputType
= PRIM_UNKNOWN
;
1801 /* No in/out qualifiers defined for anything but GLSL 1.50+
1802 * geometry shaders so far.
1804 if (linked_shader
->Stage
!= MESA_SHADER_GEOMETRY
|| prog
->Version
< 150)
1807 /* From the GLSL 1.50 spec, page 46:
1809 * "All geometry shader output layout declarations in a program
1810 * must declare the same layout and same value for
1811 * max_vertices. There must be at least one geometry output
1812 * layout declaration somewhere in a program, but not all
1813 * geometry shaders (compilation units) are required to
1817 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1818 struct gl_shader
*shader
= shader_list
[i
];
1820 if (shader
->Geom
.InputType
!= PRIM_UNKNOWN
) {
1821 if (linked_shader
->Geom
.InputType
!= PRIM_UNKNOWN
&&
1822 linked_shader
->Geom
.InputType
!= shader
->Geom
.InputType
) {
1823 linker_error(prog
, "geometry shader defined with conflicting "
1827 linked_shader
->Geom
.InputType
= shader
->Geom
.InputType
;
1830 if (shader
->Geom
.OutputType
!= PRIM_UNKNOWN
) {
1831 if (linked_shader
->Geom
.OutputType
!= PRIM_UNKNOWN
&&
1832 linked_shader
->Geom
.OutputType
!= shader
->Geom
.OutputType
) {
1833 linker_error(prog
, "geometry shader defined with conflicting "
1837 linked_shader
->Geom
.OutputType
= shader
->Geom
.OutputType
;
1840 if (shader
->Geom
.VerticesOut
!= 0) {
1841 if (linked_shader
->Geom
.VerticesOut
!= 0 &&
1842 linked_shader
->Geom
.VerticesOut
!= shader
->Geom
.VerticesOut
) {
1843 linker_error(prog
, "geometry shader defined with conflicting "
1844 "output vertex count (%d and %d)\n",
1845 linked_shader
->Geom
.VerticesOut
,
1846 shader
->Geom
.VerticesOut
);
1849 linked_shader
->Geom
.VerticesOut
= shader
->Geom
.VerticesOut
;
1852 if (shader
->Geom
.Invocations
!= 0) {
1853 if (linked_shader
->Geom
.Invocations
!= 0 &&
1854 linked_shader
->Geom
.Invocations
!= shader
->Geom
.Invocations
) {
1855 linker_error(prog
, "geometry shader defined with conflicting "
1856 "invocation count (%d and %d)\n",
1857 linked_shader
->Geom
.Invocations
,
1858 shader
->Geom
.Invocations
);
1861 linked_shader
->Geom
.Invocations
= shader
->Geom
.Invocations
;
1865 /* Just do the intrastage -> interstage propagation right now,
1866 * since we already know we're in the right type of shader program
1869 if (linked_shader
->Geom
.InputType
== PRIM_UNKNOWN
) {
1871 "geometry shader didn't declare primitive input type\n");
1874 prog
->Geom
.InputType
= linked_shader
->Geom
.InputType
;
1876 if (linked_shader
->Geom
.OutputType
== PRIM_UNKNOWN
) {
1878 "geometry shader didn't declare primitive output type\n");
1881 prog
->Geom
.OutputType
= linked_shader
->Geom
.OutputType
;
1883 if (linked_shader
->Geom
.VerticesOut
== 0) {
1885 "geometry shader didn't declare max_vertices\n");
1888 prog
->Geom
.VerticesOut
= linked_shader
->Geom
.VerticesOut
;
1890 if (linked_shader
->Geom
.Invocations
== 0)
1891 linked_shader
->Geom
.Invocations
= 1;
1893 prog
->Geom
.Invocations
= linked_shader
->Geom
.Invocations
;
1898 * Perform cross-validation of compute shader local_size_{x,y,z} layout
1899 * qualifiers for the attached compute shaders, and propagate them to the
1900 * linked CS and linked shader program.
1903 link_cs_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 for (int i
= 0; i
< 3; i
++)
1909 linked_shader
->Comp
.LocalSize
[i
] = 0;
1911 /* This function is called for all shader stages, but it only has an effect
1912 * for compute shaders.
1914 if (linked_shader
->Stage
!= MESA_SHADER_COMPUTE
)
1917 /* From the ARB_compute_shader spec, in the section describing local size
1920 * If multiple compute shaders attached to a single program object
1921 * declare local work-group size, the declarations must be identical;
1922 * otherwise a link-time error results. Furthermore, if a program
1923 * object contains any compute shaders, at least one must contain an
1924 * input layout qualifier specifying the local work sizes of the
1925 * program, or a link-time error will occur.
1927 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
1928 struct gl_shader
*shader
= shader_list
[sh
];
1930 if (shader
->Comp
.LocalSize
[0] != 0) {
1931 if (linked_shader
->Comp
.LocalSize
[0] != 0) {
1932 for (int i
= 0; i
< 3; i
++) {
1933 if (linked_shader
->Comp
.LocalSize
[i
] !=
1934 shader
->Comp
.LocalSize
[i
]) {
1935 linker_error(prog
, "compute shader defined with conflicting "
1941 for (int i
= 0; i
< 3; i
++)
1942 linked_shader
->Comp
.LocalSize
[i
] = shader
->Comp
.LocalSize
[i
];
1946 /* Just do the intrastage -> interstage propagation right now,
1947 * since we already know we're in the right type of shader program
1950 if (linked_shader
->Comp
.LocalSize
[0] == 0) {
1951 linker_error(prog
, "compute shader didn't declare local size\n");
1954 for (int i
= 0; i
< 3; i
++)
1955 prog
->Comp
.LocalSize
[i
] = linked_shader
->Comp
.LocalSize
[i
];
1960 * Combine a group of shaders for a single stage to generate a linked shader
1963 * If this function is supplied a single shader, it is cloned, and the new
1964 * shader is returned.
1966 static struct gl_shader
*
1967 link_intrastage_shaders(void *mem_ctx
,
1968 struct gl_context
*ctx
,
1969 struct gl_shader_program
*prog
,
1970 struct gl_shader
**shader_list
,
1971 unsigned num_shaders
)
1973 struct gl_uniform_block
*uniform_blocks
= NULL
;
1975 /* Check that global variables defined in multiple shaders are consistent.
1977 cross_validate_globals(prog
, shader_list
, num_shaders
, false);
1978 if (!prog
->LinkStatus
)
1981 /* Check that interface blocks defined in multiple shaders are consistent.
1983 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
1985 if (!prog
->LinkStatus
)
1988 /* Link up uniform blocks defined within this stage. */
1989 const unsigned num_uniform_blocks
=
1990 link_uniform_blocks(mem_ctx
, ctx
, prog
, shader_list
, num_shaders
,
1992 if (!prog
->LinkStatus
)
1995 /* Check that there is only a single definition of each function signature
1996 * across all shaders.
1998 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
1999 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2000 ir_function
*const f
= node
->as_function();
2005 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2006 ir_function
*const other
=
2007 shader_list
[j
]->symbols
->get_function(f
->name
);
2009 /* If the other shader has no function (and therefore no function
2010 * signatures) with the same name, skip to the next shader.
2015 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2016 if (!sig
->is_defined
|| sig
->is_builtin())
2019 ir_function_signature
*other_sig
=
2020 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2022 if ((other_sig
!= NULL
) && other_sig
->is_defined
2023 && !other_sig
->is_builtin()) {
2024 linker_error(prog
, "function `%s' is multiply defined\n",
2033 /* Find the shader that defines main, and make a clone of it.
2035 * Starting with the clone, search for undefined references. If one is
2036 * found, find the shader that defines it. Clone the reference and add
2037 * it to the shader. Repeat until there are no undefined references or
2038 * until a reference cannot be resolved.
2040 gl_shader
*main
= NULL
;
2041 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2042 if (_mesa_get_main_function_signature(shader_list
[i
]) != NULL
) {
2043 main
= shader_list
[i
];
2049 linker_error(prog
, "%s shader lacks `main'\n",
2050 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2054 gl_shader
*linked
= ctx
->Driver
.NewShader(NULL
, 0, main
->Type
);
2055 linked
->ir
= new(linked
) exec_list
;
2056 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2058 linked
->BufferInterfaceBlocks
= uniform_blocks
;
2059 linked
->NumBufferInterfaceBlocks
= num_uniform_blocks
;
2060 ralloc_steal(linked
, linked
->BufferInterfaceBlocks
);
2062 link_fs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2063 link_tcs_out_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2064 link_tes_in_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2065 link_gs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2066 link_cs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2068 populate_symbol_table(linked
);
2070 /* The pointer to the main function in the final linked shader (i.e., the
2071 * copy of the original shader that contained the main function).
2073 ir_function_signature
*const main_sig
=
2074 _mesa_get_main_function_signature(linked
);
2076 /* Move any instructions other than variable declarations or function
2077 * declarations into main.
2079 exec_node
*insertion_point
=
2080 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2083 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2084 if (shader_list
[i
] == main
)
2087 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2088 insertion_point
, true, linked
);
2091 /* Check if any shader needs built-in functions. */
2092 bool need_builtins
= false;
2093 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2094 if (shader_list
[i
]->uses_builtin_functions
) {
2095 need_builtins
= true;
2101 if (need_builtins
) {
2102 /* Make a temporary array one larger than shader_list, which will hold
2103 * the built-in function shader as well.
2105 gl_shader
**linking_shaders
= (gl_shader
**)
2106 calloc(num_shaders
+ 1, sizeof(gl_shader
*));
2108 ok
= linking_shaders
!= NULL
;
2111 memcpy(linking_shaders
, shader_list
, num_shaders
* sizeof(gl_shader
*));
2112 linking_shaders
[num_shaders
] = _mesa_glsl_get_builtin_function_shader();
2114 ok
= link_function_calls(prog
, linked
, linking_shaders
, num_shaders
+ 1);
2116 free(linking_shaders
);
2118 _mesa_error_no_memory(__func__
);
2121 ok
= link_function_calls(prog
, linked
, shader_list
, num_shaders
);
2126 _mesa_delete_shader(ctx
, linked
);
2130 /* At this point linked should contain all of the linked IR, so
2131 * validate it to make sure nothing went wrong.
2133 validate_ir_tree(linked
->ir
);
2135 /* Set the size of geometry shader input arrays */
2136 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2137 unsigned num_vertices
= vertices_per_prim(prog
->Geom
.InputType
);
2138 geom_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2139 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2140 ir
->accept(&input_resize_visitor
);
2144 if (ctx
->Const
.VertexID_is_zero_based
)
2145 lower_vertex_id(linked
);
2147 /* Validate correct usage of barrier() in the tess control shader */
2148 if (linked
->Stage
== MESA_SHADER_TESS_CTRL
) {
2149 barrier_use_visitor
visitor(prog
);
2150 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2151 ir
->accept(&visitor
);
2155 /* Make a pass over all variable declarations to ensure that arrays with
2156 * unspecified sizes have a size specified. The size is inferred from the
2157 * max_array_access field.
2159 array_sizing_visitor v
;
2161 v
.fixup_unnamed_interface_types();
2167 * Update the sizes of linked shader uniform arrays to the maximum
2170 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2172 * If one or more elements of an array are active,
2173 * GetActiveUniform will return the name of the array in name,
2174 * subject to the restrictions listed above. The type of the array
2175 * is returned in type. The size parameter contains the highest
2176 * array element index used, plus one. The compiler or linker
2177 * determines the highest index used. There will be only one
2178 * active uniform reported by the GL per uniform array.
2182 update_array_sizes(struct gl_shader_program
*prog
)
2184 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2185 if (prog
->_LinkedShaders
[i
] == NULL
)
2188 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2189 ir_variable
*const var
= node
->as_variable();
2191 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2192 !var
->type
->is_array())
2195 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2196 * will not be eliminated. Since we always do std140, just
2197 * don't resize arrays in UBOs.
2199 * Atomic counters are supposed to get deterministic
2200 * locations assigned based on the declaration ordering and
2201 * sizes, array compaction would mess that up.
2203 * Subroutine uniforms are not removed.
2205 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2206 var
->type
->contains_subroutine())
2209 unsigned int size
= var
->data
.max_array_access
;
2210 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2211 if (prog
->_LinkedShaders
[j
] == NULL
)
2214 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2215 ir_variable
*other_var
= node2
->as_variable();
2219 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2220 other_var
->data
.max_array_access
> size
) {
2221 size
= other_var
->data
.max_array_access
;
2226 if (size
+ 1 != var
->type
->length
) {
2227 /* If this is a built-in uniform (i.e., it's backed by some
2228 * fixed-function state), adjust the number of state slots to
2229 * match the new array size. The number of slots per array entry
2230 * is not known. It seems safe to assume that the total number of
2231 * slots is an integer multiple of the number of array elements.
2232 * Determine the number of slots per array element by dividing by
2233 * the old (total) size.
2235 const unsigned num_slots
= var
->get_num_state_slots();
2236 if (num_slots
> 0) {
2237 var
->set_num_state_slots((size
+ 1)
2238 * (num_slots
/ var
->type
->length
));
2241 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2243 /* FINISHME: We should update the types of array
2244 * dereferences of this variable now.
2252 * Resize tessellation evaluation per-vertex inputs to the size of
2253 * tessellation control per-vertex outputs.
2256 resize_tes_inputs(struct gl_context
*ctx
,
2257 struct gl_shader_program
*prog
)
2259 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2262 gl_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2263 gl_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2265 /* If no control shader is present, then the TES inputs are statically
2266 * sized to MaxPatchVertices; the actual size of the arrays won't be
2267 * known until draw time.
2269 const int num_vertices
= tcs
2270 ? tcs
->TessCtrl
.VerticesOut
2271 : ctx
->Const
.MaxPatchVertices
;
2273 tess_eval_array_resize_visitor
input_resize_visitor(num_vertices
, prog
);
2274 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2275 ir
->accept(&input_resize_visitor
);
2279 /* Convert the gl_PatchVerticesIn system value into a constant, since
2280 * the value is known at this point.
2282 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2283 ir_variable
*var
= ir
->as_variable();
2284 if (var
&& var
->data
.mode
== ir_var_system_value
&&
2285 var
->data
.location
== SYSTEM_VALUE_VERTICES_IN
) {
2286 void *mem_ctx
= ralloc_parent(var
);
2287 var
->data
.mode
= ir_var_auto
;
2288 var
->data
.location
= 0;
2289 var
->constant_value
= new(mem_ctx
) ir_constant(num_vertices
);
2296 * Find a contiguous set of available bits in a bitmask.
2298 * \param used_mask Bits representing used (1) and unused (0) locations
2299 * \param needed_count Number of contiguous bits needed.
2302 * Base location of the available bits on success or -1 on failure.
2305 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2307 unsigned needed_mask
= (1 << needed_count
) - 1;
2308 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2310 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2311 * cannot optimize possibly infinite loops" for the loop below.
2313 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2316 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2317 if ((needed_mask
& ~used_mask
) == needed_mask
)
2328 * Assign locations for either VS inputs or FS outputs
2330 * \param prog Shader program whose variables need locations assigned
2331 * \param constants Driver specific constant values for the program.
2332 * \param target_index Selector for the program target to receive location
2333 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2334 * \c MESA_SHADER_FRAGMENT.
2337 * If locations are successfully assigned, true is returned. Otherwise an
2338 * error is emitted to the shader link log and false is returned.
2341 assign_attribute_or_color_locations(gl_shader_program
*prog
,
2342 struct gl_constants
*constants
,
2343 unsigned target_index
)
2345 /* Maximum number of generic locations. This corresponds to either the
2346 * maximum number of draw buffers or the maximum number of generic
2349 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2350 constants
->Program
[target_index
].MaxAttribs
:
2351 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2353 /* Mark invalid locations as being used.
2355 unsigned used_locations
= (max_index
>= 32)
2356 ? ~0 : ~((1 << max_index
) - 1);
2357 unsigned double_storage_locations
= 0;
2359 assert((target_index
== MESA_SHADER_VERTEX
)
2360 || (target_index
== MESA_SHADER_FRAGMENT
));
2362 gl_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2366 /* Operate in a total of four passes.
2368 * 1. Invalidate the location assignments for all vertex shader inputs.
2370 * 2. Assign locations for inputs that have user-defined (via
2371 * glBindVertexAttribLocation) locations and outputs that have
2372 * user-defined locations (via glBindFragDataLocation).
2374 * 3. Sort the attributes without assigned locations by number of slots
2375 * required in decreasing order. Fragmentation caused by attribute
2376 * locations assigned by the application may prevent large attributes
2377 * from having enough contiguous space.
2379 * 4. Assign locations to any inputs without assigned locations.
2382 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2383 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2385 const enum ir_variable_mode direction
=
2386 (target_index
== MESA_SHADER_VERTEX
)
2387 ? ir_var_shader_in
: ir_var_shader_out
;
2390 /* Temporary storage for the set of attributes that need locations assigned.
2396 /* Used below in the call to qsort. */
2397 static int compare(const void *a
, const void *b
)
2399 const temp_attr
*const l
= (const temp_attr
*) a
;
2400 const temp_attr
*const r
= (const temp_attr
*) b
;
2402 /* Reversed because we want a descending order sort below. */
2403 return r
->slots
- l
->slots
;
2407 unsigned num_attr
= 0;
2409 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2410 ir_variable
*const var
= node
->as_variable();
2412 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2415 if (var
->data
.explicit_location
) {
2416 var
->data
.is_unmatched_generic_inout
= 0;
2417 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2418 || (var
->data
.location
< 0)) {
2420 "invalid explicit location %d specified for `%s'\n",
2421 (var
->data
.location
< 0)
2422 ? var
->data
.location
2423 : var
->data
.location
- generic_base
,
2427 } else if (target_index
== MESA_SHADER_VERTEX
) {
2430 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2431 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2432 var
->data
.location
= binding
;
2433 var
->data
.is_unmatched_generic_inout
= 0;
2435 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2439 if (prog
->FragDataBindings
->get(binding
, var
->name
)) {
2440 assert(binding
>= FRAG_RESULT_DATA0
);
2441 var
->data
.location
= binding
;
2442 var
->data
.is_unmatched_generic_inout
= 0;
2444 if (prog
->FragDataIndexBindings
->get(index
, var
->name
)) {
2445 var
->data
.index
= index
;
2450 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2452 * "Output binding assignments will cause LinkProgram to fail:
2454 * If the program has an active output assigned to a location greater
2455 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2456 * an active output assigned an index greater than or equal to one;"
2458 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2459 var
->data
.location
- generic_base
>=
2460 (int) constants
->MaxDualSourceDrawBuffers
) {
2462 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2463 "with index %u for %s\n",
2464 var
->data
.location
- generic_base
, var
->data
.index
,
2469 const unsigned slots
= var
->type
->count_attribute_slots();
2471 /* If the variable is not a built-in and has a location statically
2472 * assigned in the shader (presumably via a layout qualifier), make sure
2473 * that it doesn't collide with other assigned locations. Otherwise,
2474 * add it to the list of variables that need linker-assigned locations.
2476 if (var
->data
.location
!= -1) {
2477 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2478 /* From page 61 of the OpenGL 4.0 spec:
2480 * "LinkProgram will fail if the attribute bindings assigned
2481 * by BindAttribLocation do not leave not enough space to
2482 * assign a location for an active matrix attribute or an
2483 * active attribute array, both of which require multiple
2484 * contiguous generic attributes."
2486 * I think above text prohibits the aliasing of explicit and
2487 * automatic assignments. But, aliasing is allowed in manual
2488 * assignments of attribute locations. See below comments for
2491 * From OpenGL 4.0 spec, page 61:
2493 * "It is possible for an application to bind more than one
2494 * attribute name to the same location. This is referred to as
2495 * aliasing. This will only work if only one of the aliased
2496 * attributes is active in the executable program, or if no
2497 * path through the shader consumes more than one attribute of
2498 * a set of attributes aliased to the same location. A link
2499 * error can occur if the linker determines that every path
2500 * through the shader consumes multiple aliased attributes,
2501 * but implementations are not required to generate an error
2504 * From GLSL 4.30 spec, page 54:
2506 * "A program will fail to link if any two non-vertex shader
2507 * input variables are assigned to the same location. For
2508 * vertex shaders, multiple input variables may be assigned
2509 * to the same location using either layout qualifiers or via
2510 * the OpenGL API. However, such aliasing is intended only to
2511 * support vertex shaders where each execution path accesses
2512 * at most one input per each location. Implementations are
2513 * permitted, but not required, to generate link-time errors
2514 * if they detect that every path through the vertex shader
2515 * executable accesses multiple inputs assigned to any single
2516 * location. For all shader types, a program will fail to link
2517 * if explicit location assignments leave the linker unable
2518 * to find space for other variables without explicit
2521 * From OpenGL ES 3.0 spec, page 56:
2523 * "Binding more than one attribute name to the same location
2524 * is referred to as aliasing, and is not permitted in OpenGL
2525 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2526 * fail when this condition exists. However, aliasing is
2527 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2528 * This will only work if only one of the aliased attributes
2529 * is active in the executable program, or if no path through
2530 * the shader consumes more than one attribute of a set of
2531 * attributes aliased to the same location. A link error can
2532 * occur if the linker determines that every path through the
2533 * shader consumes multiple aliased attributes, but implemen-
2534 * tations are not required to generate an error in this case."
2536 * After looking at above references from OpenGL, OpenGL ES and
2537 * GLSL specifications, we allow aliasing of vertex input variables
2538 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2540 * NOTE: This is not required by the spec but its worth mentioning
2541 * here that we're not doing anything to make sure that no path
2542 * through the vertex shader executable accesses multiple inputs
2543 * assigned to any single location.
2546 /* Mask representing the contiguous slots that will be used by
2549 const unsigned attr
= var
->data
.location
- generic_base
;
2550 const unsigned use_mask
= (1 << slots
) - 1;
2551 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2552 ? "vertex shader input" : "fragment shader output";
2554 /* Generate a link error if the requested locations for this
2555 * attribute exceed the maximum allowed attribute location.
2557 if (attr
+ slots
> max_index
) {
2559 "insufficient contiguous locations "
2560 "available for %s `%s' %d %d %d\n", string
,
2561 var
->name
, used_locations
, use_mask
, attr
);
2565 /* Generate a link error if the set of bits requested for this
2566 * attribute overlaps any previously allocated bits.
2568 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
2569 if (target_index
== MESA_SHADER_FRAGMENT
||
2570 (prog
->IsES
&& prog
->Version
>= 300)) {
2572 "overlapping location is assigned "
2573 "to %s `%s' %d %d %d\n", string
,
2574 var
->name
, used_locations
, use_mask
, attr
);
2577 linker_warning(prog
,
2578 "overlapping location is assigned "
2579 "to %s `%s' %d %d %d\n", string
,
2580 var
->name
, used_locations
, use_mask
, attr
);
2584 used_locations
|= (use_mask
<< attr
);
2586 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2588 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2589 * active attribute variables may fail to link, unless
2590 * device-dependent optimizations are able to make the program
2591 * fit within available hardware resources. For the purposes
2592 * of this test, attribute variables of the type dvec3, dvec4,
2593 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2594 * count as consuming twice as many attributes as equivalent
2595 * single-precision types. While these types use the same number
2596 * of generic attributes as their single-precision equivalents,
2597 * implementations are permitted to consume two single-precision
2598 * vectors of internal storage for each three- or four-component
2599 * double-precision vector."
2601 * Mark this attribute slot as taking up twice as much space
2602 * so we can count it properly against limits. According to
2603 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2604 * is optional behavior, but it seems preferable.
2606 const glsl_type
*type
= var
->type
->without_array();
2607 if (type
== glsl_type::dvec3_type
||
2608 type
== glsl_type::dvec4_type
||
2609 type
== glsl_type::dmat2x3_type
||
2610 type
== glsl_type::dmat2x4_type
||
2611 type
== glsl_type::dmat3_type
||
2612 type
== glsl_type::dmat3x4_type
||
2613 type
== glsl_type::dmat4x3_type
||
2614 type
== glsl_type::dmat4_type
) {
2615 double_storage_locations
|= (use_mask
<< attr
);
2622 to_assign
[num_attr
].slots
= slots
;
2623 to_assign
[num_attr
].var
= var
;
2627 if (target_index
== MESA_SHADER_VERTEX
) {
2628 unsigned total_attribs_size
=
2629 _mesa_bitcount(used_locations
& ((1 << max_index
) - 1)) +
2630 _mesa_bitcount(double_storage_locations
);
2631 if (total_attribs_size
> max_index
) {
2633 "attempt to use %d vertex attribute slots only %d available ",
2634 total_attribs_size
, max_index
);
2639 /* If all of the attributes were assigned locations by the application (or
2640 * are built-in attributes with fixed locations), return early. This should
2641 * be the common case.
2646 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
2648 if (target_index
== MESA_SHADER_VERTEX
) {
2649 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2650 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2651 * reserved to prevent it from being automatically allocated below.
2653 find_deref_visitor
find("gl_Vertex");
2655 if (find
.variable_found())
2656 used_locations
|= (1 << 0);
2659 for (unsigned i
= 0; i
< num_attr
; i
++) {
2660 /* Mask representing the contiguous slots that will be used by this
2663 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
2665 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
2668 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2669 ? "vertex shader input" : "fragment shader output";
2672 "insufficient contiguous locations "
2673 "available for %s `%s'\n",
2674 string
, to_assign
[i
].var
->name
);
2678 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
2679 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
2680 used_locations
|= (use_mask
<< location
);
2687 * Match explicit locations of outputs to inputs and deactivate the
2688 * unmatch flag if found so we don't optimise them away.
2691 match_explicit_outputs_to_inputs(struct gl_shader_program
*prog
,
2692 gl_shader
*producer
,
2693 gl_shader
*consumer
)
2695 glsl_symbol_table parameters
;
2696 ir_variable
*explicit_locations
[MAX_VARYING
] = { NULL
};
2698 /* Find all shader outputs in the "producer" stage.
2700 foreach_in_list(ir_instruction
, node
, producer
->ir
) {
2701 ir_variable
*const var
= node
->as_variable();
2703 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_shader_out
))
2706 if (var
->data
.explicit_location
&&
2707 var
->data
.location
>= VARYING_SLOT_VAR0
) {
2708 const unsigned idx
= var
->data
.location
- VARYING_SLOT_VAR0
;
2709 if (explicit_locations
[idx
] == NULL
)
2710 explicit_locations
[idx
] = var
;
2714 /* Match inputs to outputs */
2715 foreach_in_list(ir_instruction
, node
, consumer
->ir
) {
2716 ir_variable
*const input
= node
->as_variable();
2718 if ((input
== NULL
) || (input
->data
.mode
!= ir_var_shader_in
))
2721 ir_variable
*output
= NULL
;
2722 if (input
->data
.explicit_location
2723 && input
->data
.location
>= VARYING_SLOT_VAR0
) {
2724 output
= explicit_locations
[input
->data
.location
- VARYING_SLOT_VAR0
];
2726 if (output
!= NULL
){
2727 input
->data
.is_unmatched_generic_inout
= 0;
2728 output
->data
.is_unmatched_generic_inout
= 0;
2735 * Demote shader inputs and outputs that are not used in other stages
2738 demote_shader_inputs_and_outputs(gl_shader
*sh
, enum ir_variable_mode mode
)
2740 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2741 ir_variable
*const var
= node
->as_variable();
2743 if ((var
== NULL
) || (var
->data
.mode
!= int(mode
)))
2746 /* A shader 'in' or 'out' variable is only really an input or output if
2747 * its value is used by other shader stages. This will cause the variable
2748 * to have a location assigned.
2750 if (var
->data
.is_unmatched_generic_inout
) {
2751 assert(var
->data
.mode
!= ir_var_temporary
);
2752 var
->data
.mode
= ir_var_auto
;
2759 * Store the gl_FragDepth layout in the gl_shader_program struct.
2762 store_fragdepth_layout(struct gl_shader_program
*prog
)
2764 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
2768 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
2770 /* We don't look up the gl_FragDepth symbol directly because if
2771 * gl_FragDepth is not used in the shader, it's removed from the IR.
2772 * However, the symbol won't be removed from the symbol table.
2774 * We're only interested in the cases where the variable is NOT removed
2777 foreach_in_list(ir_instruction
, node
, ir
) {
2778 ir_variable
*const var
= node
->as_variable();
2780 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
2784 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
2785 switch (var
->data
.depth_layout
) {
2786 case ir_depth_layout_none
:
2787 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
2789 case ir_depth_layout_any
:
2790 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
2792 case ir_depth_layout_greater
:
2793 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
2795 case ir_depth_layout_less
:
2796 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
2798 case ir_depth_layout_unchanged
:
2799 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
2810 * Validate the resources used by a program versus the implementation limits
2813 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2815 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2816 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2821 if (sh
->num_samplers
> ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
2822 linker_error(prog
, "Too many %s shader texture samplers\n",
2823 _mesa_shader_stage_to_string(i
));
2826 if (sh
->num_uniform_components
>
2827 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
2828 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2829 linker_warning(prog
, "Too many %s shader default uniform block "
2830 "components, but the driver will try to optimize "
2831 "them out; this is non-portable out-of-spec "
2833 _mesa_shader_stage_to_string(i
));
2835 linker_error(prog
, "Too many %s shader default uniform block "
2837 _mesa_shader_stage_to_string(i
));
2841 if (sh
->num_combined_uniform_components
>
2842 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
2843 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
2844 linker_warning(prog
, "Too many %s shader uniform components, "
2845 "but the driver will try to optimize them out; "
2846 "this is non-portable out-of-spec behavior\n",
2847 _mesa_shader_stage_to_string(i
));
2849 linker_error(prog
, "Too many %s shader uniform components\n",
2850 _mesa_shader_stage_to_string(i
));
2855 unsigned blocks
[MESA_SHADER_STAGES
] = {0};
2856 unsigned total_uniform_blocks
= 0;
2857 unsigned shader_blocks
[MESA_SHADER_STAGES
] = {0};
2858 unsigned total_shader_storage_blocks
= 0;
2860 for (unsigned i
= 0; i
< prog
->NumBufferInterfaceBlocks
; i
++) {
2861 /* Don't check SSBOs for Uniform Block Size */
2862 if (!prog
->BufferInterfaceBlocks
[i
].IsShaderStorage
&&
2863 prog
->BufferInterfaceBlocks
[i
].UniformBufferSize
> ctx
->Const
.MaxUniformBlockSize
) {
2864 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
2865 prog
->BufferInterfaceBlocks
[i
].Name
,
2866 prog
->BufferInterfaceBlocks
[i
].UniformBufferSize
,
2867 ctx
->Const
.MaxUniformBlockSize
);
2870 if (prog
->BufferInterfaceBlocks
[i
].IsShaderStorage
&&
2871 prog
->BufferInterfaceBlocks
[i
].UniformBufferSize
> ctx
->Const
.MaxShaderStorageBlockSize
) {
2872 linker_error(prog
, "Shader storage block %s too big (%d/%d)\n",
2873 prog
->BufferInterfaceBlocks
[i
].Name
,
2874 prog
->BufferInterfaceBlocks
[i
].UniformBufferSize
,
2875 ctx
->Const
.MaxShaderStorageBlockSize
);
2878 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2879 if (prog
->InterfaceBlockStageIndex
[j
][i
] != -1) {
2880 struct gl_shader
*sh
= prog
->_LinkedShaders
[j
];
2881 int stage_index
= prog
->InterfaceBlockStageIndex
[j
][i
];
2882 if (sh
&& sh
->BufferInterfaceBlocks
[stage_index
].IsShaderStorage
) {
2884 total_shader_storage_blocks
++;
2887 total_uniform_blocks
++;
2892 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
2893 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
2894 total_uniform_blocks
,
2895 ctx
->Const
.MaxCombinedUniformBlocks
);
2897 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2898 const unsigned max_uniform_blocks
=
2899 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
2900 if (blocks
[i
] > max_uniform_blocks
) {
2901 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
2902 _mesa_shader_stage_to_string(i
),
2904 max_uniform_blocks
);
2910 if (total_shader_storage_blocks
> ctx
->Const
.MaxCombinedShaderStorageBlocks
) {
2911 linker_error(prog
, "Too many combined shader storage blocks (%d/%d)\n",
2912 total_shader_storage_blocks
,
2913 ctx
->Const
.MaxCombinedShaderStorageBlocks
);
2915 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2916 const unsigned max_shader_storage_blocks
=
2917 ctx
->Const
.Program
[i
].MaxShaderStorageBlocks
;
2918 if (shader_blocks
[i
] > max_shader_storage_blocks
) {
2919 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
2920 _mesa_shader_stage_to_string(i
),
2922 max_shader_storage_blocks
);
2931 link_calculate_subroutine_compat(struct gl_shader_program
*prog
)
2933 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2934 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2939 for (unsigned j
= 0; j
< sh
->NumSubroutineUniformRemapTable
; j
++) {
2940 struct gl_uniform_storage
*uni
= sh
->SubroutineUniformRemapTable
[j
];
2946 for (unsigned f
= 0; f
< sh
->NumSubroutineFunctions
; f
++) {
2947 struct gl_subroutine_function
*fn
= &sh
->SubroutineFunctions
[f
];
2948 for (int k
= 0; k
< fn
->num_compat_types
; k
++) {
2949 if (fn
->types
[k
] == uni
->type
) {
2955 uni
->num_compatible_subroutines
= count
;
2961 check_subroutine_resources(struct gl_shader_program
*prog
)
2963 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2964 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2967 if (sh
->NumSubroutineUniformRemapTable
> MAX_SUBROUTINE_UNIFORM_LOCATIONS
)
2968 linker_error(prog
, "Too many %s shader subroutine uniforms\n",
2969 _mesa_shader_stage_to_string(i
));
2974 * Validate shader image resources.
2977 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
2979 unsigned total_image_units
= 0;
2980 unsigned fragment_outputs
= 0;
2981 unsigned total_shader_storage_blocks
= 0;
2983 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
2986 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2987 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
2990 if (sh
->NumImages
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
2991 linker_error(prog
, "Too many %s shader image uniforms (%u > %u)\n",
2992 _mesa_shader_stage_to_string(i
), sh
->NumImages
,
2993 ctx
->Const
.Program
[i
].MaxImageUniforms
);
2995 total_image_units
+= sh
->NumImages
;
2997 for (unsigned j
= 0; j
< prog
->NumBufferInterfaceBlocks
; j
++) {
2998 int stage_index
= prog
->InterfaceBlockStageIndex
[i
][j
];
2999 if (stage_index
!= -1 && sh
->BufferInterfaceBlocks
[stage_index
].IsShaderStorage
)
3000 total_shader_storage_blocks
++;
3003 if (i
== MESA_SHADER_FRAGMENT
) {
3004 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3005 ir_variable
*var
= node
->as_variable();
3006 if (var
&& var
->data
.mode
== ir_var_shader_out
)
3007 fragment_outputs
+= var
->type
->count_attribute_slots();
3013 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
3014 linker_error(prog
, "Too many combined image uniforms\n");
3016 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
3017 ctx
->Const
.MaxCombinedShaderOutputResources
)
3018 linker_error(prog
, "Too many combined image uniforms, shader storage "
3019 " buffers and fragment outputs\n");
3024 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3025 * for a variable, checks for overlaps between other uniforms using explicit
3029 reserve_explicit_locations(struct gl_shader_program
*prog
,
3030 string_to_uint_map
*map
, ir_variable
*var
)
3032 unsigned slots
= var
->type
->uniform_locations();
3033 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3035 /* Resize remap table if locations do not fit in the current one. */
3036 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
3037 prog
->UniformRemapTable
=
3038 reralloc(prog
, prog
->UniformRemapTable
,
3039 gl_uniform_storage
*,
3042 if (!prog
->UniformRemapTable
) {
3043 linker_error(prog
, "Out of memory during linking.\n");
3047 /* Initialize allocated space. */
3048 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
3049 prog
->UniformRemapTable
[i
] = NULL
;
3051 prog
->NumUniformRemapTable
= max_loc
+ 1;
3054 for (unsigned i
= 0; i
< slots
; i
++) {
3055 unsigned loc
= var
->data
.location
+ i
;
3057 /* Check if location is already used. */
3058 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3060 /* Possibly same uniform from a different stage, this is ok. */
3062 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
)
3065 /* ARB_explicit_uniform_location specification states:
3067 * "No two default-block uniform variables in the program can have
3068 * the same location, even if they are unused, otherwise a compiler
3069 * or linker error will be generated."
3072 "location qualifier for uniform %s overlaps "
3073 "previously used location\n",
3078 /* Initialize location as inactive before optimization
3079 * rounds and location assignment.
3081 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3084 /* Note, base location used for arrays. */
3085 map
->put(var
->data
.location
, var
->name
);
3091 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3092 struct gl_shader
*sh
,
3095 unsigned slots
= var
->type
->uniform_locations();
3096 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3098 /* Resize remap table if locations do not fit in the current one. */
3099 if (max_loc
+ 1 > sh
->NumSubroutineUniformRemapTable
) {
3100 sh
->SubroutineUniformRemapTable
=
3101 reralloc(sh
, sh
->SubroutineUniformRemapTable
,
3102 gl_uniform_storage
*,
3105 if (!sh
->SubroutineUniformRemapTable
) {
3106 linker_error(prog
, "Out of memory during linking.\n");
3110 /* Initialize allocated space. */
3111 for (unsigned i
= sh
->NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3112 sh
->SubroutineUniformRemapTable
[i
] = NULL
;
3114 sh
->NumSubroutineUniformRemapTable
= max_loc
+ 1;
3117 for (unsigned i
= 0; i
< slots
; i
++) {
3118 unsigned loc
= var
->data
.location
+ i
;
3120 /* Check if location is already used. */
3121 if (sh
->SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3123 /* ARB_explicit_uniform_location specification states:
3124 * "No two subroutine uniform variables can have the same location
3125 * in the same shader stage, otherwise a compiler or linker error
3126 * will be generated."
3129 "location qualifier for uniform %s overlaps "
3130 "previously used location\n",
3135 /* Initialize location as inactive before optimization
3136 * rounds and location assignment.
3138 sh
->SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3144 * Check and reserve all explicit uniform locations, called before
3145 * any optimizations happen to handle also inactive uniforms and
3146 * inactive array elements that may get trimmed away.
3149 check_explicit_uniform_locations(struct gl_context
*ctx
,
3150 struct gl_shader_program
*prog
)
3152 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3155 /* This map is used to detect if overlapping explicit locations
3156 * occur with the same uniform (from different stage) or a different one.
3158 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3161 linker_error(prog
, "Out of memory during linking.\n");
3165 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3166 struct gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3171 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3172 ir_variable
*var
= node
->as_variable();
3173 if (var
&& (var
->data
.mode
== ir_var_uniform
&&
3174 var
->data
.explicit_location
)) {
3176 if (var
->type
->is_subroutine())
3177 ret
= reserve_subroutine_explicit_locations(prog
, sh
, var
);
3179 ret
= reserve_explicit_locations(prog
, uniform_map
, var
);
3192 should_add_buffer_variable(struct gl_shader_program
*shProg
,
3193 GLenum type
, const char *name
)
3195 bool found_interface
= false;
3196 unsigned block_name_len
= 0;
3197 const char *block_name_dot
= strchr(name
, '.');
3199 /* These rules only apply to buffer variables. So we return
3200 * true for the rest of types.
3202 if (type
!= GL_BUFFER_VARIABLE
)
3205 for (unsigned i
= 0; i
< shProg
->NumBufferInterfaceBlocks
; i
++) {
3206 const char *block_name
= shProg
->BufferInterfaceBlocks
[i
].Name
;
3207 block_name_len
= strlen(block_name
);
3209 const char *block_square_bracket
= strchr(block_name
, '[');
3210 if (block_square_bracket
) {
3211 /* The block is part of an array of named interfaces,
3212 * for the name comparison we ignore the "[x]" part.
3214 block_name_len
-= strlen(block_square_bracket
);
3217 if (block_name_dot
) {
3218 /* Check if the variable name starts with the interface
3219 * name. The interface name (if present) should have the
3220 * length than the interface block name we are comparing to.
3222 unsigned len
= strlen(name
) - strlen(block_name_dot
);
3223 if (len
!= block_name_len
)
3227 if (strncmp(block_name
, name
, block_name_len
) == 0) {
3228 found_interface
= true;
3233 /* We remove the interface name from the buffer variable name,
3234 * including the dot that follows it.
3236 if (found_interface
)
3237 name
= name
+ block_name_len
+ 1;
3239 /* From: ARB_program_interface_query extension:
3241 * "For an active shader storage block member declared as an array, an
3242 * entry will be generated only for the first array element, regardless
3243 * of its type. For arrays of aggregate types, the enumeration rules are
3244 * applied recursively for the single enumerated array element.
3246 const char *struct_first_dot
= strchr(name
, '.');
3247 const char *first_square_bracket
= strchr(name
, '[');
3249 /* The buffer variable is on top level and it is not an array */
3250 if (!first_square_bracket
) {
3252 /* The shader storage block member is a struct, then generate the entry */
3253 } else if (struct_first_dot
&& struct_first_dot
< first_square_bracket
) {
3256 /* Shader storage block member is an array, only generate an entry for the
3257 * first array element.
3259 if (strncmp(first_square_bracket
, "[0]", 3) == 0)
3267 add_program_resource(struct gl_shader_program
*prog
, GLenum type
,
3268 const void *data
, uint8_t stages
)
3272 /* If resource already exists, do not add it again. */
3273 for (unsigned i
= 0; i
< prog
->NumProgramResourceList
; i
++)
3274 if (prog
->ProgramResourceList
[i
].Data
== data
)
3277 prog
->ProgramResourceList
=
3279 prog
->ProgramResourceList
,
3280 gl_program_resource
,
3281 prog
->NumProgramResourceList
+ 1);
3283 if (!prog
->ProgramResourceList
) {
3284 linker_error(prog
, "Out of memory during linking.\n");
3288 struct gl_program_resource
*res
=
3289 &prog
->ProgramResourceList
[prog
->NumProgramResourceList
];
3293 res
->StageReferences
= stages
;
3295 prog
->NumProgramResourceList
++;
3300 /* Function checks if a variable var is a packed varying and
3301 * if given name is part of packed varying's list.
3303 * If a variable is a packed varying, it has a name like
3304 * 'packed:a,b,c' where a, b and c are separate variables.
3307 included_in_packed_varying(ir_variable
*var
, const char *name
)
3309 if (strncmp(var
->name
, "packed:", 7) != 0)
3312 char *list
= strdup(var
->name
+ 7);
3317 char *token
= strtok_r(list
, ",", &saveptr
);
3319 if (strcmp(token
, name
) == 0) {
3323 token
= strtok_r(NULL
, ",", &saveptr
);
3330 * Function builds a stage reference bitmask from variable name.
3333 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3338 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3339 * used for reference mask in gl_program_resource will need to be changed.
3341 assert(MESA_SHADER_STAGES
< 8);
3343 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3344 struct gl_shader
*sh
= shProg
->_LinkedShaders
[i
];
3348 /* Shader symbol table may contain variables that have
3349 * been optimized away. Search IR for the variable instead.
3351 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3352 ir_variable
*var
= node
->as_variable();
3354 unsigned baselen
= strlen(var
->name
);
3356 if (included_in_packed_varying(var
, name
)) {
3361 /* Type needs to match if specified, otherwise we might
3362 * pick a variable with same name but different interface.
3364 if (var
->data
.mode
!= mode
)
3367 if (strncmp(var
->name
, name
, baselen
) == 0) {
3368 /* Check for exact name matches but also check for arrays and
3371 if (name
[baselen
] == '\0' ||
3372 name
[baselen
] == '[' ||
3373 name
[baselen
] == '.') {
3385 add_interface_variables(struct gl_shader_program
*shProg
,
3386 exec_list
*ir
, GLenum programInterface
)
3388 foreach_in_list(ir_instruction
, node
, ir
) {
3389 ir_variable
*var
= node
->as_variable();
3395 switch (var
->data
.mode
) {
3396 /* From GL 4.3 core spec, section 11.1.1 (Vertex Attributes):
3397 * "For GetActiveAttrib, all active vertex shader input variables
3398 * are enumerated, including the special built-in inputs gl_VertexID
3399 * and gl_InstanceID."
3401 case ir_var_system_value
:
3402 if (var
->data
.location
!= SYSTEM_VALUE_VERTEX_ID
&&
3403 var
->data
.location
!= SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
&&
3404 var
->data
.location
!= SYSTEM_VALUE_INSTANCE_ID
)
3406 /* Mark special built-in inputs referenced by the vertex stage so
3407 * that they are considered active by the shader queries.
3409 mask
= (1 << (MESA_SHADER_VERTEX
));
3411 case ir_var_shader_in
:
3412 if (programInterface
!= GL_PROGRAM_INPUT
)
3415 case ir_var_shader_out
:
3416 if (programInterface
!= GL_PROGRAM_OUTPUT
)
3423 /* Skip packed varyings, packed varyings are handled separately
3424 * by add_packed_varyings.
3426 if (strncmp(var
->name
, "packed:", 7) == 0)
3429 /* Skip fragdata arrays, these are handled separately
3430 * by add_fragdata_arrays.
3432 if (strncmp(var
->name
, "gl_out_FragData", 15) == 0)
3435 if (!add_program_resource(shProg
, programInterface
, var
,
3436 build_stageref(shProg
, var
->name
,
3437 var
->data
.mode
) | mask
))
3444 add_packed_varyings(struct gl_shader_program
*shProg
, int stage
)
3446 struct gl_shader
*sh
= shProg
->_LinkedShaders
[stage
];
3449 if (!sh
|| !sh
->packed_varyings
)
3452 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
3453 ir_variable
*var
= node
->as_variable();
3455 switch (var
->data
.mode
) {
3456 case ir_var_shader_in
:
3457 iface
= GL_PROGRAM_INPUT
;
3459 case ir_var_shader_out
:
3460 iface
= GL_PROGRAM_OUTPUT
;
3463 unreachable("unexpected type");
3465 if (!add_program_resource(shProg
, iface
, var
,
3466 build_stageref(shProg
, var
->name
,
3475 add_fragdata_arrays(struct gl_shader_program
*shProg
)
3477 struct gl_shader
*sh
= shProg
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
3479 if (!sh
|| !sh
->fragdata_arrays
)
3482 foreach_in_list(ir_instruction
, node
, sh
->fragdata_arrays
) {
3483 ir_variable
*var
= node
->as_variable();
3485 assert(var
->data
.mode
== ir_var_shader_out
);
3486 if (!add_program_resource(shProg
, GL_PROGRAM_OUTPUT
, var
,
3487 1 << MESA_SHADER_FRAGMENT
))
3495 get_top_level_name(const char *name
)
3497 const char *first_dot
= strchr(name
, '.');
3498 const char *first_square_bracket
= strchr(name
, '[');
3500 /* From ARB_program_interface_query spec:
3502 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying the
3503 * number of active array elements of the top-level shader storage block
3504 * member containing to the active variable is written to <params>. If the
3505 * top-level block member is not declared as an array, the value one is
3506 * written to <params>. If the top-level block member is an array with no
3507 * declared size, the value zero is written to <params>.
3510 /* The buffer variable is on top level.*/
3511 if (!first_square_bracket
&& !first_dot
)
3512 name_size
= strlen(name
);
3513 else if ((!first_square_bracket
||
3514 (first_dot
&& first_dot
< first_square_bracket
)))
3515 name_size
= first_dot
- name
;
3517 name_size
= first_square_bracket
- name
;
3519 return strndup(name
, name_size
);
3523 get_var_name(const char *name
)
3525 const char *first_dot
= strchr(name
, '.');
3528 return strdup(name
);
3530 return strndup(first_dot
+1, strlen(first_dot
) - 1);
3534 is_top_level_shader_storage_block_member(const char* name
,
3535 const char* interface_name
,
3536 const char* field_name
)
3538 bool result
= false;
3540 /* If the given variable is already a top-level shader storage
3541 * block member, then return array_size = 1.
3542 * We could have two possibilities: if we have an instanced
3543 * shader storage block or not instanced.
3545 * For the first, we check create a name as it was in top level and
3546 * compare it with the real name. If they are the same, then
3547 * the variable is already at top-level.
3549 * Full instanced name is: interface name + '.' + var name +
3552 int name_length
= strlen(interface_name
) + 1 + strlen(field_name
) + 1;
3553 char *full_instanced_name
= (char *) calloc(name_length
, sizeof(char));
3554 if (!full_instanced_name
) {
3555 fprintf(stderr
, "%s: Cannot allocate space for name\n", __func__
);
3559 snprintf(full_instanced_name
, name_length
, "%s.%s",
3560 interface_name
, field_name
);
3562 /* Check if its top-level shader storage block member of an
3563 * instanced interface block, or of a unnamed interface block.
3565 if (strcmp(name
, full_instanced_name
) == 0 ||
3566 strcmp(name
, field_name
) == 0)
3569 free(full_instanced_name
);
3574 get_array_size(struct gl_uniform_storage
*uni
, const glsl_struct_field
*field
,
3575 char *interface_name
, char *var_name
)
3577 /* From GL_ARB_program_interface_query spec:
3579 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer
3580 * identifying the number of active array elements of the top-level
3581 * shader storage block member containing to the active variable is
3582 * written to <params>. If the top-level block member is not
3583 * declared as an array, the value one is written to <params>. If
3584 * the top-level block member is an array with no declared size,
3585 * the value zero is written to <params>.
3587 if (is_top_level_shader_storage_block_member(uni
->name
,
3591 else if (field
->type
->is_unsized_array())
3593 else if (field
->type
->is_array())
3594 return field
->type
->length
;
3600 get_array_stride(struct gl_uniform_storage
*uni
, const glsl_type
*interface
,
3601 const glsl_struct_field
*field
, char *interface_name
,
3604 /* From GL_ARB_program_interface_query:
3606 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
3607 * identifying the stride between array elements of the top-level
3608 * shader storage block member containing the active variable is
3609 * written to <params>. For top-level block members declared as
3610 * arrays, the value written is the difference, in basic machine
3611 * units, between the offsets of the active variable for
3612 * consecutive elements in the top-level array. For top-level
3613 * block members not declared as an array, zero is written to
3616 if (field
->type
->is_array()) {
3617 const enum glsl_matrix_layout matrix_layout
=
3618 glsl_matrix_layout(field
->matrix_layout
);
3619 bool row_major
= matrix_layout
== GLSL_MATRIX_LAYOUT_ROW_MAJOR
;
3620 const glsl_type
*array_type
= field
->type
->fields
.array
;
3622 if (is_top_level_shader_storage_block_member(uni
->name
,
3627 if (interface
->interface_packing
!= GLSL_INTERFACE_PACKING_STD430
) {
3628 if (array_type
->is_record() || array_type
->is_array())
3629 return glsl_align(array_type
->std140_size(row_major
), 16);
3631 return MAX2(array_type
->std140_base_alignment(row_major
), 16);
3633 return array_type
->std430_array_stride(row_major
);
3640 calculate_array_size_and_stride(struct gl_shader_program
*shProg
,
3641 struct gl_uniform_storage
*uni
)
3643 int block_index
= uni
->block_index
;
3644 int array_size
= -1;
3645 int array_stride
= -1;
3646 char *var_name
= get_top_level_name(uni
->name
);
3647 char *interface_name
=
3648 get_top_level_name(shProg
->BufferInterfaceBlocks
[block_index
].Name
);
3650 if (strcmp(var_name
, interface_name
) == 0) {
3651 /* Deal with instanced array of SSBOs */
3652 char *temp_name
= get_var_name(uni
->name
);
3654 linker_error(shProg
, "Out of memory during linking.\n");
3655 goto write_top_level_array_size_and_stride
;
3658 var_name
= get_top_level_name(temp_name
);
3661 linker_error(shProg
, "Out of memory during linking.\n");
3662 goto write_top_level_array_size_and_stride
;
3666 for (unsigned i
= 0; i
< shProg
->NumShaders
; i
++) {
3667 if (shProg
->Shaders
[i
] == NULL
)
3670 const gl_shader
*stage
= shProg
->Shaders
[i
];
3671 foreach_in_list(ir_instruction
, node
, stage
->ir
) {
3672 ir_variable
*var
= node
->as_variable();
3673 if (!var
|| !var
->get_interface_type() ||
3674 var
->data
.mode
!= ir_var_shader_storage
)
3677 const glsl_type
*interface
= var
->get_interface_type();
3679 if (strcmp(interface_name
, interface
->name
) != 0)
3682 for (unsigned i
= 0; i
< interface
->length
; i
++) {
3683 const glsl_struct_field
*field
= &interface
->fields
.structure
[i
];
3684 if (strcmp(field
->name
, var_name
) != 0)
3687 array_stride
= get_array_stride(uni
, interface
, field
,
3688 interface_name
, var_name
);
3689 array_size
= get_array_size(uni
, field
, interface_name
, var_name
);
3690 goto write_top_level_array_size_and_stride
;
3694 write_top_level_array_size_and_stride
:
3695 free(interface_name
);
3697 uni
->top_level_array_stride
= array_stride
;
3698 uni
->top_level_array_size
= array_size
;
3702 * Builds up a list of program resources that point to existing
3706 build_program_resource_list(struct gl_shader_program
*shProg
)
3708 /* Rebuild resource list. */
3709 if (shProg
->ProgramResourceList
) {
3710 ralloc_free(shProg
->ProgramResourceList
);
3711 shProg
->ProgramResourceList
= NULL
;
3712 shProg
->NumProgramResourceList
= 0;
3715 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
3717 /* Determine first input and final output stage. These are used to
3718 * detect which variables should be enumerated in the resource list
3719 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
3721 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3722 if (!shProg
->_LinkedShaders
[i
])
3724 if (input_stage
== MESA_SHADER_STAGES
)
3729 /* Empty shader, no resources. */
3730 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
3733 /* Program interface needs to expose varyings in case of SSO. */
3734 if (shProg
->SeparateShader
) {
3735 if (!add_packed_varyings(shProg
, input_stage
))
3737 if (!add_packed_varyings(shProg
, output_stage
))
3741 if (!add_fragdata_arrays(shProg
))
3744 /* Add inputs and outputs to the resource list. */
3745 if (!add_interface_variables(shProg
, shProg
->_LinkedShaders
[input_stage
]->ir
,
3749 if (!add_interface_variables(shProg
, shProg
->_LinkedShaders
[output_stage
]->ir
,
3753 /* Add transform feedback varyings. */
3754 if (shProg
->LinkedTransformFeedback
.NumVarying
> 0) {
3755 for (int i
= 0; i
< shProg
->LinkedTransformFeedback
.NumVarying
; i
++) {
3756 if (!add_program_resource(shProg
, GL_TRANSFORM_FEEDBACK_VARYING
,
3757 &shProg
->LinkedTransformFeedback
.Varyings
[i
],
3763 /* Add uniforms from uniform storage. */
3764 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
3765 /* Do not add uniforms internally used by Mesa. */
3766 if (shProg
->UniformStorage
[i
].hidden
)
3770 build_stageref(shProg
, shProg
->UniformStorage
[i
].name
,
3773 /* Add stagereferences for uniforms in a uniform block. */
3774 int block_index
= shProg
->UniformStorage
[i
].block_index
;
3775 if (block_index
!= -1) {
3776 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
3777 if (shProg
->InterfaceBlockStageIndex
[j
][block_index
] != -1)
3778 stageref
|= (1 << j
);
3782 bool is_shader_storage
= shProg
->UniformStorage
[i
].is_shader_storage
;
3783 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
3784 if (!should_add_buffer_variable(shProg
, type
,
3785 shProg
->UniformStorage
[i
].name
))
3788 if (is_shader_storage
) {
3789 calculate_array_size_and_stride(shProg
, &shProg
->UniformStorage
[i
]);
3792 if (!add_program_resource(shProg
, type
,
3793 &shProg
->UniformStorage
[i
], stageref
))
3797 /* Add program uniform blocks and shader storage blocks. */
3798 for (unsigned i
= 0; i
< shProg
->NumBufferInterfaceBlocks
; i
++) {
3799 bool is_shader_storage
= shProg
->BufferInterfaceBlocks
[i
].IsShaderStorage
;
3800 GLenum type
= is_shader_storage
? GL_SHADER_STORAGE_BLOCK
: GL_UNIFORM_BLOCK
;
3801 if (!add_program_resource(shProg
, type
,
3802 &shProg
->BufferInterfaceBlocks
[i
], 0))
3806 /* Add atomic counter buffers. */
3807 for (unsigned i
= 0; i
< shProg
->NumAtomicBuffers
; i
++) {
3808 if (!add_program_resource(shProg
, GL_ATOMIC_COUNTER_BUFFER
,
3809 &shProg
->AtomicBuffers
[i
], 0))
3813 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
3815 if (!shProg
->UniformStorage
[i
].hidden
)
3818 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
3819 if (!shProg
->UniformStorage
[i
].opaque
[j
].active
||
3820 !shProg
->UniformStorage
[i
].type
->is_subroutine())
3823 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
3824 /* add shader subroutines */
3825 if (!add_program_resource(shProg
, type
, &shProg
->UniformStorage
[i
], 0))
3830 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3831 struct gl_shader
*sh
= shProg
->_LinkedShaders
[i
];
3837 type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
3838 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
3839 if (!add_program_resource(shProg
, type
, &sh
->SubroutineFunctions
[j
], 0))
3846 * This check is done to make sure we allow only constant expression
3847 * indexing and "constant-index-expression" (indexing with an expression
3848 * that includes loop induction variable).
3851 validate_sampler_array_indexing(struct gl_context
*ctx
,
3852 struct gl_shader_program
*prog
)
3854 dynamic_sampler_array_indexing_visitor v
;
3855 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3856 if (prog
->_LinkedShaders
[i
] == NULL
)
3859 bool no_dynamic_indexing
=
3860 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
3862 /* Search for array derefs in shader. */
3863 v
.run(prog
->_LinkedShaders
[i
]->ir
);
3864 if (v
.uses_dynamic_sampler_array_indexing()) {
3865 const char *msg
= "sampler arrays indexed with non-constant "
3866 "expressions is forbidden in GLSL %s %u";
3867 /* Backend has indicated that it has no dynamic indexing support. */
3868 if (no_dynamic_indexing
) {
3869 linker_error(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
3872 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
3880 link_assign_subroutine_types(struct gl_shader_program
*prog
)
3882 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3883 gl_shader
*sh
= prog
->_LinkedShaders
[i
];
3888 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3889 ir_function
*fn
= node
->as_function();
3893 if (fn
->is_subroutine
)
3894 sh
->NumSubroutineUniformTypes
++;
3896 if (!fn
->num_subroutine_types
)
3899 sh
->SubroutineFunctions
= reralloc(sh
, sh
->SubroutineFunctions
,
3900 struct gl_subroutine_function
,
3901 sh
->NumSubroutineFunctions
+ 1);
3902 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].name
= ralloc_strdup(sh
, fn
->name
);
3903 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
3904 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
=
3905 ralloc_array(sh
, const struct glsl_type
*,
3906 fn
->num_subroutine_types
);
3908 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
3911 * "Each subroutine with an index qualifier in the shader must be
3912 * given a unique index, otherwise a compile or link error will be
3915 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
3916 if (sh
->SubroutineFunctions
[j
].index
!= -1 &&
3917 sh
->SubroutineFunctions
[j
].index
== fn
->subroutine_index
) {
3918 linker_error(prog
, "each subroutine index qualifier in the "
3919 "shader must be unique\n");
3923 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].index
=
3924 fn
->subroutine_index
;
3926 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
3927 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
3928 sh
->NumSubroutineFunctions
++;
3931 /* Assign index for subroutines without an explicit index*/
3933 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
3934 while (sh
->SubroutineFunctions
[j
].index
== -1) {
3935 for (unsigned k
= 0; k
< sh
->NumSubroutineFunctions
; k
++) {
3936 if (sh
->SubroutineFunctions
[k
].index
== index
)
3938 else if (k
== sh
->NumSubroutineFunctions
- 1)
3939 sh
->SubroutineFunctions
[j
].index
= index
;
3948 split_ubos_and_ssbos(void *mem_ctx
,
3949 struct gl_uniform_block
*blocks
,
3950 unsigned num_blocks
,
3951 struct gl_uniform_block
***ubos
,
3953 struct gl_uniform_block
***ssbos
,
3954 unsigned *num_ssbos
)
3956 unsigned num_ubo_blocks
= 0;
3957 unsigned num_ssbo_blocks
= 0;
3959 for (unsigned i
= 0; i
< num_blocks
; i
++) {
3960 if (blocks
[i
].IsShaderStorage
)
3966 *ubos
= ralloc_array(mem_ctx
, gl_uniform_block
*, num_ubo_blocks
);
3969 *ssbos
= ralloc_array(mem_ctx
, gl_uniform_block
*, num_ssbo_blocks
);
3972 for (unsigned i
= 0; i
< num_blocks
; i
++) {
3973 if (blocks
[i
].IsShaderStorage
) {
3974 (*ssbos
)[(*num_ssbos
)++] = &blocks
[i
];
3976 (*ubos
)[(*num_ubos
)++] = &blocks
[i
];
3980 assert(*num_ubos
+ *num_ssbos
== num_blocks
);
3984 set_always_active_io(exec_list
*ir
, ir_variable_mode io_mode
)
3986 assert(io_mode
== ir_var_shader_in
|| io_mode
== ir_var_shader_out
);
3988 foreach_in_list(ir_instruction
, node
, ir
) {
3989 ir_variable
*const var
= node
->as_variable();
3991 if (var
== NULL
|| var
->data
.mode
!= io_mode
)
3994 /* Don't set always active on builtins that haven't been redeclared */
3995 if (var
->data
.how_declared
== ir_var_declared_implicitly
)
3998 var
->data
.always_active_io
= true;
4003 * When separate shader programs are enabled, only input/outputs between
4004 * the stages of a multi-stage separate program can be safely removed
4005 * from the shader interface. Other inputs/outputs must remain active.
4008 disable_varying_optimizations_for_sso(struct gl_shader_program
*prog
)
4010 unsigned first
, last
;
4011 assert(prog
->SeparateShader
);
4013 first
= MESA_SHADER_STAGES
;
4016 /* Determine first and last stage. Excluding the compute stage */
4017 for (unsigned i
= 0; i
< MESA_SHADER_COMPUTE
; i
++) {
4018 if (!prog
->_LinkedShaders
[i
])
4020 if (first
== MESA_SHADER_STAGES
)
4025 if (first
== MESA_SHADER_STAGES
)
4028 for (unsigned stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4029 gl_shader
*sh
= prog
->_LinkedShaders
[stage
];
4033 if (first
== last
) {
4034 /* For a single shader program only allow inputs to the vertex shader
4035 * and outputs from the fragment shader to be removed.
4037 if (stage
!= MESA_SHADER_VERTEX
)
4038 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4039 if (stage
!= MESA_SHADER_FRAGMENT
)
4040 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4042 /* For multi-stage separate shader programs only allow inputs and
4043 * outputs between the shader stages to be removed as well as inputs
4044 * to the vertex shader and outputs from the fragment shader.
4046 if (stage
== first
&& stage
!= MESA_SHADER_VERTEX
)
4047 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4048 else if (stage
== last
&& stage
!= MESA_SHADER_FRAGMENT
)
4049 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4055 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
4057 tfeedback_decl
*tfeedback_decls
= NULL
;
4058 unsigned num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
4060 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
4062 prog
->LinkStatus
= true; /* All error paths will set this to false */
4063 prog
->Validated
= false;
4064 prog
->_Used
= false;
4066 prog
->ARB_fragment_coord_conventions_enable
= false;
4068 /* Separate the shaders into groups based on their type.
4070 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
4071 unsigned num_shaders
[MESA_SHADER_STAGES
];
4073 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4074 shader_list
[i
] = (struct gl_shader
**)
4075 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
4079 unsigned min_version
= UINT_MAX
;
4080 unsigned max_version
= 0;
4081 const bool is_es_prog
=
4082 (prog
->NumShaders
> 0 && prog
->Shaders
[0]->IsES
) ? true : false;
4083 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
4084 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
4085 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
4087 if (prog
->Shaders
[i
]->IsES
!= is_es_prog
) {
4088 linker_error(prog
, "all shaders must use same shading "
4089 "language version\n");
4093 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
4094 prog
->ARB_fragment_coord_conventions_enable
= true;
4097 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
4098 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
4099 num_shaders
[shader_type
]++;
4102 /* In desktop GLSL, different shader versions may be linked together. In
4103 * GLSL ES, all shader versions must be the same.
4105 if (is_es_prog
&& min_version
!= max_version
) {
4106 linker_error(prog
, "all shaders must use same shading "
4107 "language version\n");
4111 prog
->Version
= max_version
;
4112 prog
->IsES
= is_es_prog
;
4114 /* From OpenGL 4.5 Core specification (7.3 Program Objects):
4115 * "Linking can fail for a variety of reasons as specified in the OpenGL
4116 * Shading Language Specification, as well as any of the following
4119 * * No shader objects are attached to program.
4123 * Same rule applies for OpenGL ES >= 3.1.
4126 if (prog
->NumShaders
== 0 &&
4127 ((ctx
->API
== API_OPENGL_CORE
&& ctx
->Version
>= 45) ||
4128 (ctx
->API
== API_OPENGLES2
&& ctx
->Version
>= 31))) {
4129 linker_error(prog
, "No shader objects are attached to program.\n");
4133 /* Some shaders have to be linked with some other shaders present.
4135 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
4136 num_shaders
[MESA_SHADER_VERTEX
] == 0 &&
4137 !prog
->SeparateShader
) {
4138 linker_error(prog
, "Geometry shader must be linked with "
4142 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4143 num_shaders
[MESA_SHADER_VERTEX
] == 0 &&
4144 !prog
->SeparateShader
) {
4145 linker_error(prog
, "Tessellation evaluation shader must be linked with "
4149 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4150 num_shaders
[MESA_SHADER_VERTEX
] == 0 &&
4151 !prog
->SeparateShader
) {
4152 linker_error(prog
, "Tessellation control shader must be linked with "
4157 /* The spec is self-contradictory here. It allows linking without a tess
4158 * eval shader, but that can only be used with transform feedback and
4159 * rasterization disabled. However, transform feedback isn't allowed
4160 * with GL_PATCHES, so it can't be used.
4162 * More investigation showed that the idea of transform feedback after
4163 * a tess control shader was dropped, because some hw vendors couldn't
4164 * support tessellation without a tess eval shader, but the linker section
4165 * wasn't updated to reflect that.
4167 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4170 * Do what's reasonable and always require a tess eval shader if a tess
4171 * control shader is present.
4173 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4174 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0 &&
4175 !prog
->SeparateShader
) {
4176 linker_error(prog
, "Tessellation control shader must be linked with "
4177 "tessellation evaluation shader\n");
4181 /* Compute shaders have additional restrictions. */
4182 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
4183 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
4184 linker_error(prog
, "Compute shaders may not be linked with any other "
4185 "type of shader\n");
4188 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4189 if (prog
->_LinkedShaders
[i
] != NULL
)
4190 _mesa_delete_shader(ctx
, prog
->_LinkedShaders
[i
]);
4192 prog
->_LinkedShaders
[i
] = NULL
;
4195 /* Link all shaders for a particular stage and validate the result.
4197 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4198 if (num_shaders
[stage
] > 0) {
4199 gl_shader
*const sh
=
4200 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
4201 num_shaders
[stage
]);
4203 if (!prog
->LinkStatus
) {
4205 _mesa_delete_shader(ctx
, sh
);
4210 case MESA_SHADER_VERTEX
:
4211 validate_vertex_shader_executable(prog
, sh
);
4213 case MESA_SHADER_TESS_CTRL
:
4214 /* nothing to be done */
4216 case MESA_SHADER_TESS_EVAL
:
4217 validate_tess_eval_shader_executable(prog
, sh
);
4219 case MESA_SHADER_GEOMETRY
:
4220 validate_geometry_shader_executable(prog
, sh
);
4222 case MESA_SHADER_FRAGMENT
:
4223 validate_fragment_shader_executable(prog
, sh
);
4226 if (!prog
->LinkStatus
) {
4228 _mesa_delete_shader(ctx
, sh
);
4232 _mesa_reference_shader(ctx
, &prog
->_LinkedShaders
[stage
], sh
);
4236 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0)
4237 prog
->LastClipDistanceArraySize
= prog
->Geom
.ClipDistanceArraySize
;
4238 else if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0)
4239 prog
->LastClipDistanceArraySize
= prog
->TessEval
.ClipDistanceArraySize
;
4240 else if (num_shaders
[MESA_SHADER_VERTEX
] > 0)
4241 prog
->LastClipDistanceArraySize
= prog
->Vert
.ClipDistanceArraySize
;
4243 prog
->LastClipDistanceArraySize
= 0; /* Not used */
4245 /* Here begins the inter-stage linking phase. Some initial validation is
4246 * performed, then locations are assigned for uniforms, attributes, and
4249 cross_validate_uniforms(prog
);
4250 if (!prog
->LinkStatus
)
4253 unsigned first
, last
, prev
;
4255 first
= MESA_SHADER_STAGES
;
4258 /* Determine first and last stage. */
4259 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4260 if (!prog
->_LinkedShaders
[i
])
4262 if (first
== MESA_SHADER_STAGES
)
4267 check_explicit_uniform_locations(ctx
, prog
);
4268 link_assign_subroutine_types(prog
);
4270 if (!prog
->LinkStatus
)
4273 resize_tes_inputs(ctx
, prog
);
4275 /* Validate the inputs of each stage with the output of the preceding
4279 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4280 if (prog
->_LinkedShaders
[i
] == NULL
)
4283 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
4284 prog
->_LinkedShaders
[i
]);
4285 if (!prog
->LinkStatus
)
4288 cross_validate_outputs_to_inputs(prog
,
4289 prog
->_LinkedShaders
[prev
],
4290 prog
->_LinkedShaders
[i
]);
4291 if (!prog
->LinkStatus
)
4297 /* Cross-validate uniform blocks between shader stages */
4298 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
,
4299 MESA_SHADER_STAGES
);
4300 if (!prog
->LinkStatus
)
4303 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4304 if (prog
->_LinkedShaders
[i
] != NULL
)
4305 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
4308 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4309 * it before optimization because we want most of the checks to get
4310 * dropped thanks to constant propagation.
4312 * This rule also applies to GLSL ES 3.00.
4314 if (max_version
>= (is_es_prog
? 300 : 130)) {
4315 struct gl_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4317 lower_discard_flow(sh
->ir
);
4321 if (prog
->SeparateShader
)
4322 disable_varying_optimizations_for_sso(prog
);
4324 if (!interstage_cross_validate_uniform_blocks(prog
))
4327 /* Do common optimization before assigning storage for attributes,
4328 * uniforms, and varyings. Later optimization could possibly make
4329 * some of that unused.
4331 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4332 if (prog
->_LinkedShaders
[i
] == NULL
)
4335 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
4336 if (!prog
->LinkStatus
)
4339 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerClipDistance
) {
4340 lower_clip_distance(prog
->_LinkedShaders
[i
]);
4343 if (ctx
->Const
.LowerTessLevel
) {
4344 lower_tess_level(prog
->_LinkedShaders
[i
]);
4347 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false,
4348 &ctx
->Const
.ShaderCompilerOptions
[i
],
4349 ctx
->Const
.NativeIntegers
))
4352 lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
);
4355 /* Validation for special cases where we allow sampler array indexing
4356 * with loop induction variable. This check emits a warning or error
4357 * depending if backend can handle dynamic indexing.
4359 if ((!prog
->IsES
&& prog
->Version
< 130) ||
4360 (prog
->IsES
&& prog
->Version
< 300)) {
4361 if (!validate_sampler_array_indexing(ctx
, prog
))
4365 /* Check and validate stream emissions in geometry shaders */
4366 validate_geometry_shader_emissions(ctx
, prog
);
4368 /* Mark all generic shader inputs and outputs as unpaired. */
4369 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4370 if (prog
->_LinkedShaders
[i
] != NULL
) {
4371 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
4376 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4377 if (prog
->_LinkedShaders
[i
] == NULL
)
4380 match_explicit_outputs_to_inputs(prog
, prog
->_LinkedShaders
[prev
],
4381 prog
->_LinkedShaders
[i
]);
4385 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
4386 MESA_SHADER_VERTEX
)) {
4390 if (!assign_attribute_or_color_locations(prog
, &ctx
->Const
,
4391 MESA_SHADER_FRAGMENT
)) {
4395 if (num_tfeedback_decls
!= 0) {
4396 /* From GL_EXT_transform_feedback:
4397 * A program will fail to link if:
4399 * * the <count> specified by TransformFeedbackVaryingsEXT is
4400 * non-zero, but the program object has no vertex or geometry
4403 if (first
== MESA_SHADER_FRAGMENT
) {
4404 linker_error(prog
, "Transform feedback varyings specified, but "
4405 "no vertex or geometry shader is present.\n");
4409 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
4410 prog
->TransformFeedback
.NumVarying
);
4411 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
4412 prog
->TransformFeedback
.VaryingNames
,
4417 /* Linking the stages in the opposite order (from fragment to vertex)
4418 * ensures that inter-shader outputs written to in an earlier stage are
4419 * eliminated if they are (transitively) not used in a later stage.
4423 if (first
< MESA_SHADER_FRAGMENT
) {
4424 gl_shader
*const sh
= prog
->_LinkedShaders
[last
];
4426 if (first
!= MESA_SHADER_VERTEX
) {
4427 /* There was no vertex shader, but we still have to assign varying
4428 * locations for use by tessellation/geometry shader inputs in SSO.
4430 * If the shader is not separable (i.e., prog->SeparateShader is
4431 * false), linking will have already failed when first is not
4432 * MESA_SHADER_VERTEX.
4434 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
4435 NULL
, prog
->_LinkedShaders
[first
],
4436 num_tfeedback_decls
, tfeedback_decls
))
4440 if (last
!= MESA_SHADER_FRAGMENT
&&
4441 (num_tfeedback_decls
!= 0 || prog
->SeparateShader
)) {
4442 /* There was no fragment shader, but we still have to assign varying
4443 * locations for use by transform feedback.
4445 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
4447 num_tfeedback_decls
, tfeedback_decls
))
4451 do_dead_builtin_varyings(ctx
, sh
, NULL
,
4452 num_tfeedback_decls
, tfeedback_decls
);
4454 if (!prog
->SeparateShader
) {
4455 demote_shader_inputs_and_outputs(sh
, ir_var_shader_out
);
4456 /* Eliminate code that is now dead due to unused outputs being
4459 while (do_dead_code(sh
->ir
, false))
4463 else if (first
== MESA_SHADER_FRAGMENT
) {
4464 /* If the program only contains a fragment shader...
4466 gl_shader
*const sh
= prog
->_LinkedShaders
[first
];
4468 do_dead_builtin_varyings(ctx
, NULL
, sh
,
4469 num_tfeedback_decls
, tfeedback_decls
);
4471 if (prog
->SeparateShader
) {
4472 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
4473 NULL
/* producer */,
4475 0 /* num_tfeedback_decls */,
4476 NULL
/* tfeedback_decls */))
4479 demote_shader_inputs_and_outputs(sh
, ir_var_shader_in
);
4480 /* Eliminate code that is now dead due to unused inputs being
4483 while (do_dead_code(sh
->ir
, false))
4489 for (int i
= next
- 1; i
>= 0; i
--) {
4490 if (prog
->_LinkedShaders
[i
] == NULL
)
4493 gl_shader
*const sh_i
= prog
->_LinkedShaders
[i
];
4494 gl_shader
*const sh_next
= prog
->_LinkedShaders
[next
];
4496 if (!assign_varying_locations(ctx
, mem_ctx
, prog
, sh_i
, sh_next
,
4497 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
4501 do_dead_builtin_varyings(ctx
, sh_i
, sh_next
,
4502 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
4505 demote_shader_inputs_and_outputs(sh_i
, ir_var_shader_out
);
4506 demote_shader_inputs_and_outputs(sh_next
, ir_var_shader_in
);
4508 /* Eliminate code that is now dead due to unused outputs being demoted.
4510 while (do_dead_code(sh_i
->ir
, false))
4512 while (do_dead_code(sh_next
->ir
, false))
4515 /* This must be done after all dead varyings are eliminated. */
4516 if (!check_against_output_limit(ctx
, prog
, sh_i
))
4518 if (!check_against_input_limit(ctx
, prog
, sh_next
))
4524 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
))
4527 update_array_sizes(prog
);
4528 link_assign_uniform_locations(prog
, ctx
->Const
.UniformBooleanTrue
);
4529 link_assign_atomic_counter_resources(ctx
, prog
);
4530 store_fragdepth_layout(prog
);
4532 link_calculate_subroutine_compat(prog
);
4533 check_resources(ctx
, prog
);
4534 check_subroutine_resources(prog
);
4535 check_image_resources(ctx
, prog
);
4536 link_check_atomic_counter_resources(ctx
, prog
);
4538 if (!prog
->LinkStatus
)
4541 /* OpenGL ES requires that a vertex shader and a fragment shader both be
4542 * present in a linked program. GL_ARB_ES2_compatibility doesn't say
4543 * anything about shader linking when one of the shaders (vertex or
4544 * fragment shader) is absent. So, the extension shouldn't change the
4545 * behavior specified in GLSL specification.
4547 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
) {
4548 /* With ES < 3.1 one needs to have always vertex + fragment shader. */
4549 if (ctx
->Version
< 31) {
4550 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
4551 linker_error(prog
, "program lacks a vertex shader\n");
4552 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
4553 linker_error(prog
, "program lacks a fragment shader\n");
4556 /* From OpenGL ES 3.1 specification (7.3 Program Objects):
4557 * "Linking can fail for a variety of reasons as specified in the
4558 * OpenGL ES Shading Language Specification, as well as any of the
4559 * following reasons:
4563 * * program contains objects to form either a vertex shader or
4564 * fragment shader, and program is not separable, and does not
4565 * contain objects to form both a vertex shader and fragment
4568 if (!!prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] ^
4569 !!prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]) {
4570 linker_error(prog
, "Program needs to contain both vertex and "
4571 "fragment shaders.\n");
4576 /* Split BufferInterfaceBlocks into UniformBlocks and ShaderStorageBlocks
4577 * for gl_shader_program and gl_shader, so that drivers that need separate
4578 * index spaces for each set can have that.
4580 for (unsigned i
= MESA_SHADER_VERTEX
; i
< MESA_SHADER_STAGES
; i
++) {
4581 if (prog
->_LinkedShaders
[i
] != NULL
) {
4582 gl_shader
*sh
= prog
->_LinkedShaders
[i
];
4583 split_ubos_and_ssbos(sh
,
4584 sh
->BufferInterfaceBlocks
,
4585 sh
->NumBufferInterfaceBlocks
,
4587 &sh
->NumUniformBlocks
,
4588 &sh
->ShaderStorageBlocks
,
4589 &sh
->NumShaderStorageBlocks
);
4593 split_ubos_and_ssbos(prog
,
4594 prog
->BufferInterfaceBlocks
,
4595 prog
->NumBufferInterfaceBlocks
,
4596 &prog
->UniformBlocks
,
4597 &prog
->NumUniformBlocks
,
4598 &prog
->ShaderStorageBlocks
,
4599 &prog
->NumShaderStorageBlocks
);
4601 /* FINISHME: Assign fragment shader output locations. */
4603 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4604 if (prog
->_LinkedShaders
[i
] == NULL
)
4607 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerBufferInterfaceBlocks
)
4608 lower_ubo_reference(prog
->_LinkedShaders
[i
]);
4610 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerShaderSharedVariables
)
4611 lower_shared_reference(prog
->_LinkedShaders
[i
],
4612 &prog
->Comp
.SharedSize
);
4614 lower_vector_derefs(prog
->_LinkedShaders
[i
]);
4618 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4619 free(shader_list
[i
]);
4620 if (prog
->_LinkedShaders
[i
] == NULL
)
4623 /* Do a final validation step to make sure that the IR wasn't
4624 * invalidated by any modifications performed after intrastage linking.
4626 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
4628 /* Retain any live IR, but trash the rest. */
4629 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
4631 /* The symbol table in the linked shaders may contain references to
4632 * variables that were removed (e.g., unused uniforms). Since it may
4633 * contain junk, there is no possible valid use. Delete it and set the
4636 delete prog
->_LinkedShaders
[i
]->symbols
;
4637 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
4640 ralloc_free(mem_ctx
);