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/prog_instruction.h"
76 #include "util/string_to_uint_map.h"
78 #include "link_varyings.h"
79 #include "ir_optimization.h"
80 #include "ir_rvalue_visitor.h"
81 #include "ir_uniform.h"
83 #include "main/shaderobj.h"
84 #include "main/enums.h"
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 array_resize_visitor
: public ir_hierarchical_visitor
{
186 unsigned num_vertices
;
187 gl_shader_program
*prog
;
188 gl_shader_stage stage
;
190 array_resize_visitor(unsigned num_vertices
,
191 gl_shader_program
*prog
,
192 gl_shader_stage stage
)
194 this->num_vertices
= num_vertices
;
199 virtual ~array_resize_visitor()
204 virtual ir_visitor_status
visit(ir_variable
*var
)
206 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
||
208 return visit_continue
;
210 unsigned size
= var
->type
->length
;
212 if (stage
== MESA_SHADER_GEOMETRY
) {
213 /* Generate a link error if the shader has declared this array with
216 if (!var
->data
.implicit_sized_array
&&
217 size
&& size
!= this->num_vertices
) {
218 linker_error(this->prog
, "size of array %s declared as %u, "
219 "but number of input vertices is %u\n",
220 var
->name
, size
, this->num_vertices
);
221 return visit_continue
;
224 /* Generate a link error if the shader attempts to access an input
225 * array using an index too large for its actual size assigned at
228 if (var
->data
.max_array_access
>= (int)this->num_vertices
) {
229 linker_error(this->prog
, "%s shader accesses element %i of "
230 "%s, but only %i input vertices\n",
231 _mesa_shader_stage_to_string(this->stage
),
232 var
->data
.max_array_access
, var
->name
, this->num_vertices
);
233 return visit_continue
;
237 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
239 var
->data
.max_array_access
= this->num_vertices
- 1;
241 return visit_continue
;
244 /* Dereferences of input variables need to be updated so that their type
245 * matches the newly assigned type of the variable they are accessing. */
246 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
248 ir
->type
= ir
->var
->type
;
249 return visit_continue
;
252 /* Dereferences of 2D input arrays need to be updated so that their type
253 * matches the newly assigned type of the array they are accessing. */
254 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
256 const glsl_type
*const vt
= ir
->array
->type
;
258 ir
->type
= vt
->fields
.array
;
259 return visit_continue
;
263 class barrier_use_visitor
: public ir_hierarchical_visitor
{
265 barrier_use_visitor(gl_shader_program
*prog
)
266 : prog(prog
), in_main(false), after_return(false), control_flow(0)
270 virtual ~barrier_use_visitor()
275 virtual ir_visitor_status
visit_enter(ir_function
*ir
)
277 if (strcmp(ir
->name
, "main") == 0)
280 return visit_continue
;
283 virtual ir_visitor_status
visit_leave(ir_function
*)
286 after_return
= false;
287 return visit_continue
;
290 virtual ir_visitor_status
visit_leave(ir_return
*)
293 return visit_continue
;
296 virtual ir_visitor_status
visit_enter(ir_if
*)
299 return visit_continue
;
302 virtual ir_visitor_status
visit_leave(ir_if
*)
305 return visit_continue
;
308 virtual ir_visitor_status
visit_enter(ir_loop
*)
311 return visit_continue
;
314 virtual ir_visitor_status
visit_leave(ir_loop
*)
317 return visit_continue
;
320 /* FINISHME: `switch` is not expressed at the IR level -- it's already
321 * been lowered to a mess of `if`s. We'll correctly disallow any use of
322 * barrier() in a conditional path within the switch, but not in a path
323 * which is always hit.
326 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
328 if (ir
->use_builtin
&& strcmp(ir
->callee_name(), "barrier") == 0) {
329 /* Use of barrier(); determine if it is legal: */
331 linker_error(prog
, "Builtin barrier() may only be used in main");
336 linker_error(prog
, "Builtin barrier() may not be used after return");
340 if (control_flow
!= 0) {
341 linker_error(prog
, "Builtin barrier() may not be used inside control flow");
345 return visit_continue
;
349 gl_shader_program
*prog
;
350 bool in_main
, after_return
;
355 * Visitor that determines the highest stream id to which a (geometry) shader
356 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
358 class find_emit_vertex_visitor
: public ir_hierarchical_visitor
{
360 find_emit_vertex_visitor(int max_allowed
)
361 : max_stream_allowed(max_allowed
),
362 invalid_stream_id(0),
363 invalid_stream_id_from_emit_vertex(false),
364 end_primitive_found(false),
365 uses_non_zero_stream(false)
370 virtual ir_visitor_status
visit_leave(ir_emit_vertex
*ir
)
372 int stream_id
= ir
->stream_id();
375 invalid_stream_id
= stream_id
;
376 invalid_stream_id_from_emit_vertex
= true;
380 if (stream_id
> max_stream_allowed
) {
381 invalid_stream_id
= stream_id
;
382 invalid_stream_id_from_emit_vertex
= true;
387 uses_non_zero_stream
= true;
389 return visit_continue
;
392 virtual ir_visitor_status
visit_leave(ir_end_primitive
*ir
)
394 end_primitive_found
= true;
396 int stream_id
= ir
->stream_id();
399 invalid_stream_id
= stream_id
;
400 invalid_stream_id_from_emit_vertex
= false;
404 if (stream_id
> max_stream_allowed
) {
405 invalid_stream_id
= stream_id
;
406 invalid_stream_id_from_emit_vertex
= false;
411 uses_non_zero_stream
= true;
413 return visit_continue
;
418 return invalid_stream_id
!= 0;
421 const char *error_func()
423 return invalid_stream_id_from_emit_vertex
?
424 "EmitStreamVertex" : "EndStreamPrimitive";
429 return invalid_stream_id
;
434 return uses_non_zero_stream
;
437 bool uses_end_primitive()
439 return end_primitive_found
;
443 int max_stream_allowed
;
444 int invalid_stream_id
;
445 bool invalid_stream_id_from_emit_vertex
;
446 bool end_primitive_found
;
447 bool uses_non_zero_stream
;
450 /* Class that finds array derefs and check if indexes are dynamic. */
451 class dynamic_sampler_array_indexing_visitor
: public ir_hierarchical_visitor
454 dynamic_sampler_array_indexing_visitor() :
455 dynamic_sampler_array_indexing(false)
459 ir_visitor_status
visit_enter(ir_dereference_array
*ir
)
461 if (!ir
->variable_referenced())
462 return visit_continue
;
464 if (!ir
->variable_referenced()->type
->contains_sampler())
465 return visit_continue
;
467 if (!ir
->array_index
->constant_expression_value()) {
468 dynamic_sampler_array_indexing
= true;
471 return visit_continue
;
474 bool uses_dynamic_sampler_array_indexing()
476 return dynamic_sampler_array_indexing
;
480 bool dynamic_sampler_array_indexing
;
483 } /* anonymous namespace */
486 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
490 ralloc_strcat(&prog
->InfoLog
, "error: ");
492 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
495 prog
->LinkStatus
= false;
500 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
504 ralloc_strcat(&prog
->InfoLog
, "warning: ");
506 ralloc_vasprintf_append(&prog
->InfoLog
, fmt
, ap
);
513 * Given a string identifying a program resource, break it into a base name
514 * and an optional array index in square brackets.
516 * If an array index is present, \c out_base_name_end is set to point to the
517 * "[" that precedes the array index, and the array index itself is returned
520 * If no array index is present (or if the array index is negative or
521 * mal-formed), \c out_base_name_end, is set to point to the null terminator
522 * at the end of the input string, and -1 is returned.
524 * Only the final array index is parsed; if the string contains other array
525 * indices (or structure field accesses), they are left in the base name.
527 * No attempt is made to check that the base name is properly formed;
528 * typically the caller will look up the base name in a hash table, so
529 * ill-formed base names simply turn into hash table lookup failures.
532 parse_program_resource_name(const GLchar
*name
,
533 const GLchar
**out_base_name_end
)
535 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
537 * "When an integer array element or block instance number is part of
538 * the name string, it will be specified in decimal form without a "+"
539 * or "-" sign or any extra leading zeroes. Additionally, the name
540 * string will not include white space anywhere in the string."
543 const size_t len
= strlen(name
);
544 *out_base_name_end
= name
+ len
;
546 if (len
== 0 || name
[len
-1] != ']')
549 /* Walk backwards over the string looking for a non-digit character. This
550 * had better be the opening bracket for an array index.
552 * Initially, i specifies the location of the ']'. Since the string may
553 * contain only the ']' charcater, walk backwards very carefully.
556 for (i
= len
- 1; (i
> 0) && isdigit(name
[i
-1]); --i
)
559 if ((i
== 0) || name
[i
-1] != '[')
562 long array_index
= strtol(&name
[i
], NULL
, 10);
566 /* Check for leading zero */
567 if (name
[i
] == '0' && name
[i
+1] != ']')
570 *out_base_name_end
= name
+ (i
- 1);
576 link_invalidate_variable_locations(exec_list
*ir
)
578 foreach_in_list(ir_instruction
, node
, ir
) {
579 ir_variable
*const var
= node
->as_variable();
584 /* Only assign locations for variables that lack an explicit location.
585 * Explicit locations are set for all built-in variables, generic vertex
586 * shader inputs (via layout(location=...)), and generic fragment shader
587 * outputs (also via layout(location=...)).
589 if (!var
->data
.explicit_location
) {
590 var
->data
.location
= -1;
591 var
->data
.location_frac
= 0;
594 /* ir_variable::is_unmatched_generic_inout is used by the linker while
595 * connecting outputs from one stage to inputs of the next stage.
597 if (var
->data
.explicit_location
&&
598 var
->data
.location
< VARYING_SLOT_VAR0
) {
599 var
->data
.is_unmatched_generic_inout
= 0;
601 var
->data
.is_unmatched_generic_inout
= 1;
608 * Set clip_distance_array_size based and cull_distance_array_size on the given
611 * Also check for errors based on incorrect usage of gl_ClipVertex and
612 * gl_ClipDistance and gl_CullDistance.
613 * Additionally test whether the arrays gl_ClipDistance and gl_CullDistance
614 * exceed the maximum size defined by gl_MaxCombinedClipAndCullDistances.
616 * Return false if an error was reported.
619 analyze_clip_cull_usage(struct gl_shader_program
*prog
,
620 struct gl_linked_shader
*shader
,
621 struct gl_context
*ctx
,
622 GLuint
*clip_distance_array_size
,
623 GLuint
*cull_distance_array_size
)
625 *clip_distance_array_size
= 0;
626 *cull_distance_array_size
= 0;
628 if (prog
->Version
>= (prog
->IsES
? 300 : 130)) {
629 /* From section 7.1 (Vertex Shader Special Variables) of the
632 * "It is an error for a shader to statically write both
633 * gl_ClipVertex and gl_ClipDistance."
635 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
636 * gl_ClipVertex nor gl_ClipDistance. However with
637 * GL_EXT_clip_cull_distance, this functionality is exposed in ES 3.0.
639 find_assignment_visitor
clip_distance("gl_ClipDistance");
640 find_assignment_visitor
cull_distance("gl_CullDistance");
642 clip_distance
.run(shader
->ir
);
643 cull_distance
.run(shader
->ir
);
645 /* From the ARB_cull_distance spec:
647 * It is a compile-time or link-time error for the set of shaders forming
648 * a program to statically read or write both gl_ClipVertex and either
649 * gl_ClipDistance or gl_CullDistance.
651 * This does not apply to GLSL ES shaders, since GLSL ES doesn't define
655 find_assignment_visitor
clip_vertex("gl_ClipVertex");
657 clip_vertex
.run(shader
->ir
);
659 if (clip_vertex
.variable_found() && clip_distance
.variable_found()) {
660 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
661 "and `gl_ClipDistance'\n",
662 _mesa_shader_stage_to_string(shader
->Stage
));
665 if (clip_vertex
.variable_found() && cull_distance
.variable_found()) {
666 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
667 "and `gl_CullDistance'\n",
668 _mesa_shader_stage_to_string(shader
->Stage
));
673 if (clip_distance
.variable_found()) {
674 ir_variable
*clip_distance_var
=
675 shader
->symbols
->get_variable("gl_ClipDistance");
676 assert(clip_distance_var
);
677 *clip_distance_array_size
= clip_distance_var
->type
->length
;
679 if (cull_distance
.variable_found()) {
680 ir_variable
*cull_distance_var
=
681 shader
->symbols
->get_variable("gl_CullDistance");
682 assert(cull_distance_var
);
683 *cull_distance_array_size
= cull_distance_var
->type
->length
;
685 /* From the ARB_cull_distance spec:
687 * It is a compile-time or link-time error for the set of shaders forming
688 * a program to have the sum of the sizes of the gl_ClipDistance and
689 * gl_CullDistance arrays to be larger than
690 * gl_MaxCombinedClipAndCullDistances.
692 if ((*clip_distance_array_size
+ *cull_distance_array_size
) >
693 ctx
->Const
.MaxClipPlanes
) {
694 linker_error(prog
, "%s shader: the combined size of "
695 "'gl_ClipDistance' and 'gl_CullDistance' size cannot "
697 "gl_MaxCombinedClipAndCullDistances (%u)",
698 _mesa_shader_stage_to_string(shader
->Stage
),
699 ctx
->Const
.MaxClipPlanes
);
706 * Verify that a vertex shader executable meets all semantic requirements.
708 * Also sets prog->Vert.ClipDistanceArraySize and
709 * prog->Vert.CullDistanceArraySize as a side effect.
711 * \param shader Vertex shader executable to be verified
714 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
715 struct gl_linked_shader
*shader
,
716 struct gl_context
*ctx
)
721 /* From the GLSL 1.10 spec, page 48:
723 * "The variable gl_Position is available only in the vertex
724 * language and is intended for writing the homogeneous vertex
725 * position. All executions of a well-formed vertex shader
726 * executable must write a value into this variable. [...] The
727 * variable gl_Position is available only in the vertex
728 * language and is intended for writing the homogeneous vertex
729 * position. All executions of a well-formed vertex shader
730 * executable must write a value into this variable."
732 * while in GLSL 1.40 this text is changed to:
734 * "The variable gl_Position is available only in the vertex
735 * language and is intended for writing the homogeneous vertex
736 * position. It can be written at any time during shader
737 * execution. It may also be read back by a vertex shader
738 * after being written. This value will be used by primitive
739 * assembly, clipping, culling, and other fixed functionality
740 * operations, if present, that operate on primitives after
741 * vertex processing has occurred. Its value is undefined if
742 * the vertex shader executable does not write gl_Position."
744 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
745 * gl_Position is not an error.
747 if (prog
->Version
< (prog
->IsES
? 300 : 140)) {
748 find_assignment_visitor
find("gl_Position");
749 find
.run(shader
->ir
);
750 if (!find
.variable_found()) {
753 "vertex shader does not write to `gl_Position'."
754 "It's value is undefined. \n");
757 "vertex shader does not write to `gl_Position'. \n");
763 analyze_clip_cull_usage(prog
, shader
, ctx
,
764 &prog
->Vert
.ClipDistanceArraySize
,
765 &prog
->Vert
.CullDistanceArraySize
);
769 validate_tess_eval_shader_executable(struct gl_shader_program
*prog
,
770 struct gl_linked_shader
*shader
,
771 struct gl_context
*ctx
)
776 analyze_clip_cull_usage(prog
, shader
, ctx
,
777 &prog
->TessEval
.ClipDistanceArraySize
,
778 &prog
->TessEval
.CullDistanceArraySize
);
783 * Verify that a fragment shader executable meets all semantic requirements
785 * \param shader Fragment shader executable to be verified
788 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
789 struct gl_linked_shader
*shader
)
794 find_assignment_visitor
frag_color("gl_FragColor");
795 find_assignment_visitor
frag_data("gl_FragData");
797 frag_color
.run(shader
->ir
);
798 frag_data
.run(shader
->ir
);
800 if (frag_color
.variable_found() && frag_data
.variable_found()) {
801 linker_error(prog
, "fragment shader writes to both "
802 "`gl_FragColor' and `gl_FragData'\n");
807 * Verify that a geometry shader executable meets all semantic requirements
809 * Also sets prog->Geom.VerticesIn, and prog->Geom.ClipDistanceArraySize and
810 * prog->Geom.CullDistanceArraySize as a side effect.
812 * \param shader Geometry shader executable to be verified
815 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
816 struct gl_linked_shader
*shader
,
817 struct gl_context
*ctx
)
822 unsigned num_vertices
= vertices_per_prim(shader
->info
.Geom
.InputType
);
823 prog
->Geom
.VerticesIn
= num_vertices
;
825 analyze_clip_cull_usage(prog
, shader
, ctx
,
826 &prog
->Geom
.ClipDistanceArraySize
,
827 &prog
->Geom
.CullDistanceArraySize
);
831 * Check if geometry shaders emit to non-zero streams and do corresponding
835 validate_geometry_shader_emissions(struct gl_context
*ctx
,
836 struct gl_shader_program
*prog
)
838 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
];
841 find_emit_vertex_visitor
emit_vertex(ctx
->Const
.MaxVertexStreams
- 1);
842 emit_vertex
.run(sh
->ir
);
843 if (emit_vertex
.error()) {
844 linker_error(prog
, "Invalid call %s(%d). Accepted values for the "
845 "stream parameter are in the range [0, %d].\n",
846 emit_vertex
.error_func(),
847 emit_vertex
.error_stream(),
848 ctx
->Const
.MaxVertexStreams
- 1);
850 prog
->Geom
.UsesStreams
= emit_vertex
.uses_streams();
851 prog
->Geom
.UsesEndPrimitive
= emit_vertex
.uses_end_primitive();
853 /* From the ARB_gpu_shader5 spec:
855 * "Multiple vertex streams are supported only if the output primitive
856 * type is declared to be "points". A program will fail to link if it
857 * contains a geometry shader calling EmitStreamVertex() or
858 * EndStreamPrimitive() if its output primitive type is not "points".
860 * However, in the same spec:
862 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
863 * with <stream> set to zero."
867 * "The function EndPrimitive() is equivalent to calling
868 * EndStreamPrimitive() with <stream> set to zero."
870 * Since we can call EmitVertex() and EndPrimitive() when we output
871 * primitives other than points, calling EmitStreamVertex(0) or
872 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
873 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
874 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
877 if (prog
->Geom
.UsesStreams
&& sh
->info
.Geom
.OutputType
!= GL_POINTS
) {
878 linker_error(prog
, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
879 "with n>0 requires point output\n");
885 validate_intrastage_arrays(struct gl_shader_program
*prog
,
886 ir_variable
*const var
,
887 ir_variable
*const existing
)
889 /* Consider the types to be "the same" if both types are arrays
890 * of the same type and one of the arrays is implicitly sized.
891 * In addition, set the type of the linked variable to the
892 * explicitly sized array.
894 if (var
->type
->is_array() && existing
->type
->is_array()) {
895 if ((var
->type
->fields
.array
== existing
->type
->fields
.array
) &&
896 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
897 if (var
->type
->length
!= 0) {
898 if ((int)var
->type
->length
<= existing
->data
.max_array_access
) {
899 linker_error(prog
, "%s `%s' declared as type "
900 "`%s' but outermost dimension has an index"
903 var
->name
, var
->type
->name
,
904 existing
->data
.max_array_access
);
906 existing
->type
= var
->type
;
908 } else if (existing
->type
->length
!= 0) {
909 if((int)existing
->type
->length
<= var
->data
.max_array_access
&&
910 !existing
->data
.from_ssbo_unsized_array
) {
911 linker_error(prog
, "%s `%s' declared as type "
912 "`%s' but outermost dimension has an index"
915 var
->name
, existing
->type
->name
,
916 var
->data
.max_array_access
);
921 /* The arrays of structs could have different glsl_type pointers but
922 * they are actually the same type. Use record_compare() to check that.
924 if (existing
->type
->fields
.array
->is_record() &&
925 var
->type
->fields
.array
->is_record() &&
926 existing
->type
->fields
.array
->record_compare(var
->type
->fields
.array
))
935 * Perform validation of global variables used across multiple shaders
938 cross_validate_globals(struct gl_shader_program
*prog
,
939 struct exec_list
*ir
, glsl_symbol_table
*variables
,
942 foreach_in_list(ir_instruction
, node
, ir
) {
943 ir_variable
*const var
= node
->as_variable();
948 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
951 /* don't cross validate subroutine uniforms */
952 if (var
->type
->contains_subroutine())
955 /* Don't cross validate temporaries that are at global scope. These
956 * will eventually get pulled into the shaders 'main'.
958 if (var
->data
.mode
== ir_var_temporary
)
961 /* If a global with this name has already been seen, verify that the
962 * new instance has the same type. In addition, if the globals have
963 * initializers, the values of the initializers must be the same.
965 ir_variable
*const existing
= variables
->get_variable(var
->name
);
966 if (existing
!= NULL
) {
967 /* Check if types match. Interface blocks have some special
968 * rules so we handle those elsewhere.
970 if (var
->type
!= existing
->type
&&
971 !var
->is_interface_instance()) {
972 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
973 if (var
->type
->is_record() && existing
->type
->is_record()
974 && existing
->type
->record_compare(var
->type
)) {
975 existing
->type
= var
->type
;
977 /* If it is an unsized array in a Shader Storage Block,
978 * two different shaders can access to different elements.
979 * Because of that, they might be converted to different
980 * sized arrays, then check that they are compatible but
981 * ignore the array size.
983 if (!(var
->data
.mode
== ir_var_shader_storage
&&
984 var
->data
.from_ssbo_unsized_array
&&
985 existing
->data
.mode
== ir_var_shader_storage
&&
986 existing
->data
.from_ssbo_unsized_array
&&
987 var
->type
->gl_type
== existing
->type
->gl_type
)) {
988 linker_error(prog
, "%s `%s' declared as type "
989 "`%s' and type `%s'\n",
991 var
->name
, var
->type
->name
,
992 existing
->type
->name
);
999 if (var
->data
.explicit_location
) {
1000 if (existing
->data
.explicit_location
1001 && (var
->data
.location
!= existing
->data
.location
)) {
1002 linker_error(prog
, "explicit locations for %s "
1003 "`%s' have differing values\n",
1004 mode_string(var
), var
->name
);
1008 if (var
->data
.location_frac
!= existing
->data
.location_frac
) {
1009 linker_error(prog
, "explicit components for %s `%s' have "
1010 "differing values\n", mode_string(var
), var
->name
);
1014 existing
->data
.location
= var
->data
.location
;
1015 existing
->data
.explicit_location
= true;
1017 /* Check if uniform with implicit location was marked explicit
1018 * by earlier shader stage. If so, mark it explicit in this stage
1019 * too to make sure later processing does not treat it as
1022 if (existing
->data
.explicit_location
) {
1023 var
->data
.location
= existing
->data
.location
;
1024 var
->data
.explicit_location
= true;
1028 /* From the GLSL 4.20 specification:
1029 * "A link error will result if two compilation units in a program
1030 * specify different integer-constant bindings for the same
1031 * opaque-uniform name. However, it is not an error to specify a
1032 * binding on some but not all declarations for the same name"
1034 if (var
->data
.explicit_binding
) {
1035 if (existing
->data
.explicit_binding
&&
1036 var
->data
.binding
!= existing
->data
.binding
) {
1037 linker_error(prog
, "explicit bindings for %s "
1038 "`%s' have differing values\n",
1039 mode_string(var
), var
->name
);
1043 existing
->data
.binding
= var
->data
.binding
;
1044 existing
->data
.explicit_binding
= true;
1047 if (var
->type
->contains_atomic() &&
1048 var
->data
.offset
!= existing
->data
.offset
) {
1049 linker_error(prog
, "offset specifications for %s "
1050 "`%s' have differing values\n",
1051 mode_string(var
), var
->name
);
1055 /* Validate layout qualifiers for gl_FragDepth.
1057 * From the AMD/ARB_conservative_depth specs:
1059 * "If gl_FragDepth is redeclared in any fragment shader in a
1060 * program, it must be redeclared in all fragment shaders in
1061 * that program that have static assignments to
1062 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1063 * fragment shaders in a single program must have the same set
1066 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1067 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1068 bool layout_differs
=
1069 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1071 if (layout_declared
&& layout_differs
) {
1073 "All redeclarations of gl_FragDepth in all "
1074 "fragment shaders in a single program must have "
1075 "the same set of qualifiers.\n");
1078 if (var
->data
.used
&& layout_differs
) {
1080 "If gl_FragDepth is redeclared with a layout "
1081 "qualifier in any fragment shader, it must be "
1082 "redeclared with the same layout qualifier in "
1083 "all fragment shaders that have assignments to "
1088 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1090 * "If a shared global has multiple initializers, the
1091 * initializers must all be constant expressions, and they
1092 * must all have the same value. Otherwise, a link error will
1093 * result. (A shared global having only one initializer does
1094 * not require that initializer to be a constant expression.)"
1096 * Previous to 4.20 the GLSL spec simply said that initializers
1097 * must have the same value. In this case of non-constant
1098 * initializers, this was impossible to determine. As a result,
1099 * no vendor actually implemented that behavior. The 4.20
1100 * behavior matches the implemented behavior of at least one other
1101 * vendor, so we'll implement that for all GLSL versions.
1103 if (var
->constant_initializer
!= NULL
) {
1104 if (existing
->constant_initializer
!= NULL
) {
1105 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1106 linker_error(prog
, "initializers for %s "
1107 "`%s' have differing values\n",
1108 mode_string(var
), var
->name
);
1112 /* If the first-seen instance of a particular uniform did
1113 * not have an initializer but a later instance does,
1114 * replace the former with the later.
1116 variables
->replace_variable(existing
->name
, var
);
1120 if (var
->data
.has_initializer
) {
1121 if (existing
->data
.has_initializer
1122 && (var
->constant_initializer
== NULL
1123 || existing
->constant_initializer
== NULL
)) {
1125 "shared global variable `%s' has multiple "
1126 "non-constant initializers.\n",
1132 if (existing
->data
.invariant
!= var
->data
.invariant
) {
1133 linker_error(prog
, "declarations for %s `%s' have "
1134 "mismatching invariant qualifiers\n",
1135 mode_string(var
), var
->name
);
1138 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1139 linker_error(prog
, "declarations for %s `%s' have "
1140 "mismatching centroid qualifiers\n",
1141 mode_string(var
), var
->name
);
1144 if (existing
->data
.sample
!= var
->data
.sample
) {
1145 linker_error(prog
, "declarations for %s `%s` have "
1146 "mismatching sample qualifiers\n",
1147 mode_string(var
), var
->name
);
1150 if (existing
->data
.image_format
!= var
->data
.image_format
) {
1151 linker_error(prog
, "declarations for %s `%s` have "
1152 "mismatching image format qualifiers\n",
1153 mode_string(var
), var
->name
);
1157 if (prog
->IsES
&& existing
->data
.precision
!= var
->data
.precision
) {
1158 linker_error(prog
, "declarations for %s `%s` have "
1159 "mismatching precision qualifiers\n",
1160 mode_string(var
), var
->name
);
1164 variables
->add_variable(var
);
1170 * Perform validation of uniforms used across multiple shader stages
1173 cross_validate_uniforms(struct gl_shader_program
*prog
)
1175 glsl_symbol_table variables
;
1176 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1177 if (prog
->_LinkedShaders
[i
] == NULL
)
1180 cross_validate_globals(prog
, prog
->_LinkedShaders
[i
]->ir
, &variables
,
1186 * Accumulates the array of buffer blocks and checks that all definitions of
1187 * blocks agree on their contents.
1190 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
,
1193 int *InterfaceBlockStageIndex
[MESA_SHADER_STAGES
];
1194 struct gl_uniform_block
*blks
= NULL
;
1195 unsigned *num_blks
= validate_ssbo
? &prog
->NumShaderStorageBlocks
:
1196 &prog
->NumUniformBlocks
;
1198 unsigned max_num_buffer_blocks
= 0;
1199 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1200 if (prog
->_LinkedShaders
[i
]) {
1201 if (validate_ssbo
) {
1202 max_num_buffer_blocks
+=
1203 prog
->_LinkedShaders
[i
]->NumShaderStorageBlocks
;
1205 max_num_buffer_blocks
+=
1206 prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
1211 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1212 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1214 InterfaceBlockStageIndex
[i
] = new int[max_num_buffer_blocks
];
1215 for (unsigned int j
= 0; j
< max_num_buffer_blocks
; j
++)
1216 InterfaceBlockStageIndex
[i
][j
] = -1;
1221 unsigned sh_num_blocks
;
1222 struct gl_uniform_block
**sh_blks
;
1223 if (validate_ssbo
) {
1224 sh_num_blocks
= prog
->_LinkedShaders
[i
]->NumShaderStorageBlocks
;
1225 sh_blks
= sh
->ShaderStorageBlocks
;
1227 sh_num_blocks
= prog
->_LinkedShaders
[i
]->NumUniformBlocks
;
1228 sh_blks
= sh
->UniformBlocks
;
1231 for (unsigned int j
= 0; j
< sh_num_blocks
; j
++) {
1232 int index
= link_cross_validate_uniform_block(prog
, &blks
, num_blks
,
1236 linker_error(prog
, "buffer block `%s' has mismatching "
1237 "definitions\n", sh_blks
[j
]->Name
);
1239 for (unsigned k
= 0; k
<= i
; k
++) {
1240 delete[] InterfaceBlockStageIndex
[k
];
1245 InterfaceBlockStageIndex
[i
][index
] = j
;
1249 /* Update per stage block pointers to point to the program list.
1250 * FIXME: We should be able to free the per stage blocks here.
1252 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1253 for (unsigned j
= 0; j
< *num_blks
; j
++) {
1254 int stage_index
= InterfaceBlockStageIndex
[i
][j
];
1256 if (stage_index
!= -1) {
1257 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1259 blks
[j
].stageref
|= (1 << i
);
1261 struct gl_uniform_block
**sh_blks
= validate_ssbo
?
1262 sh
->ShaderStorageBlocks
: sh
->UniformBlocks
;
1264 sh_blks
[stage_index
] = &blks
[j
];
1269 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1270 delete[] InterfaceBlockStageIndex
[i
];
1274 prog
->ShaderStorageBlocks
= blks
;
1276 prog
->UniformBlocks
= blks
;
1283 * Populates a shaders symbol table with all global declarations
1286 populate_symbol_table(gl_linked_shader
*sh
)
1288 sh
->symbols
= new(sh
) glsl_symbol_table
;
1290 foreach_in_list(ir_instruction
, inst
, sh
->ir
) {
1294 if ((func
= inst
->as_function()) != NULL
) {
1295 sh
->symbols
->add_function(func
);
1296 } else if ((var
= inst
->as_variable()) != NULL
) {
1297 if (var
->data
.mode
!= ir_var_temporary
)
1298 sh
->symbols
->add_variable(var
);
1305 * Remap variables referenced in an instruction tree
1307 * This is used when instruction trees are cloned from one shader and placed in
1308 * another. These trees will contain references to \c ir_variable nodes that
1309 * do not exist in the target shader. This function finds these \c ir_variable
1310 * references and replaces the references with matching variables in the target
1313 * If there is no matching variable in the target shader, a clone of the
1314 * \c ir_variable is made and added to the target shader. The new variable is
1315 * added to \b both the instruction stream and the symbol table.
1317 * \param inst IR tree that is to be processed.
1318 * \param symbols Symbol table containing global scope symbols in the
1320 * \param instructions Instruction stream where new variable declarations
1324 remap_variables(ir_instruction
*inst
, struct gl_linked_shader
*target
,
1327 class remap_visitor
: public ir_hierarchical_visitor
{
1329 remap_visitor(struct gl_linked_shader
*target
,
1332 this->target
= target
;
1333 this->symbols
= target
->symbols
;
1334 this->instructions
= target
->ir
;
1335 this->temps
= temps
;
1338 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1340 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1341 hash_entry
*entry
= _mesa_hash_table_search(temps
, ir
->var
);
1342 ir_variable
*var
= entry
? (ir_variable
*) entry
->data
: NULL
;
1344 assert(var
!= NULL
);
1346 return visit_continue
;
1349 ir_variable
*const existing
=
1350 this->symbols
->get_variable(ir
->var
->name
);
1351 if (existing
!= NULL
)
1354 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1356 this->symbols
->add_variable(copy
);
1357 this->instructions
->push_head(copy
);
1361 return visit_continue
;
1365 struct gl_linked_shader
*target
;
1366 glsl_symbol_table
*symbols
;
1367 exec_list
*instructions
;
1371 remap_visitor
v(target
, temps
);
1378 * Move non-declarations from one instruction stream to another
1380 * The intended usage pattern of this function is to pass the pointer to the
1381 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1382 * pointer) for \c last and \c false for \c make_copies on the first
1383 * call. Successive calls pass the return value of the previous call for
1384 * \c last and \c true for \c make_copies.
1386 * \param instructions Source instruction stream
1387 * \param last Instruction after which new instructions should be
1388 * inserted in the target instruction stream
1389 * \param make_copies Flag selecting whether instructions in \c instructions
1390 * should be copied (via \c ir_instruction::clone) into the
1391 * target list or moved.
1394 * The new "last" instruction in the target instruction stream. This pointer
1395 * is suitable for use as the \c last parameter of a later call to this
1399 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1400 bool make_copies
, gl_linked_shader
*target
)
1402 hash_table
*temps
= NULL
;
1405 temps
= _mesa_hash_table_create(NULL
, _mesa_hash_pointer
,
1406 _mesa_key_pointer_equal
);
1408 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1409 if (inst
->as_function())
1412 ir_variable
*var
= inst
->as_variable();
1413 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1416 assert(inst
->as_assignment()
1418 || inst
->as_if() /* for initializers with the ?: operator */
1419 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1422 inst
= inst
->clone(target
, NULL
);
1425 _mesa_hash_table_insert(temps
, var
, inst
);
1427 remap_variables(inst
, target
, temps
);
1432 last
->insert_after(inst
);
1437 _mesa_hash_table_destroy(temps
, NULL
);
1444 * This class is only used in link_intrastage_shaders() below but declaring
1445 * it inside that function leads to compiler warnings with some versions of
1448 class array_sizing_visitor
: public ir_hierarchical_visitor
{
1450 array_sizing_visitor()
1451 : mem_ctx(ralloc_context(NULL
)),
1452 unnamed_interfaces(_mesa_hash_table_create(NULL
, _mesa_hash_pointer
,
1453 _mesa_key_pointer_equal
))
1457 ~array_sizing_visitor()
1459 _mesa_hash_table_destroy(this->unnamed_interfaces
, NULL
);
1460 ralloc_free(this->mem_ctx
);
1463 virtual ir_visitor_status
visit(ir_variable
*var
)
1465 const glsl_type
*type_without_array
;
1466 bool implicit_sized_array
= var
->data
.implicit_sized_array
;
1467 fixup_type(&var
->type
, var
->data
.max_array_access
,
1468 var
->data
.from_ssbo_unsized_array
,
1469 &implicit_sized_array
);
1470 var
->data
.implicit_sized_array
= implicit_sized_array
;
1471 type_without_array
= var
->type
->without_array();
1472 if (var
->type
->is_interface()) {
1473 if (interface_contains_unsized_arrays(var
->type
)) {
1474 const glsl_type
*new_type
=
1475 resize_interface_members(var
->type
,
1476 var
->get_max_ifc_array_access(),
1477 var
->is_in_shader_storage_block());
1478 var
->type
= new_type
;
1479 var
->change_interface_type(new_type
);
1481 } else if (type_without_array
->is_interface()) {
1482 if (interface_contains_unsized_arrays(type_without_array
)) {
1483 const glsl_type
*new_type
=
1484 resize_interface_members(type_without_array
,
1485 var
->get_max_ifc_array_access(),
1486 var
->is_in_shader_storage_block());
1487 var
->change_interface_type(new_type
);
1488 var
->type
= update_interface_members_array(var
->type
, new_type
);
1490 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1491 /* Store a pointer to the variable in the unnamed_interfaces
1495 _mesa_hash_table_search(this->unnamed_interfaces
,
1498 ir_variable
**interface_vars
= entry
? (ir_variable
**) entry
->data
: NULL
;
1500 if (interface_vars
== NULL
) {
1501 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1503 _mesa_hash_table_insert(this->unnamed_interfaces
, ifc_type
,
1506 unsigned index
= ifc_type
->field_index(var
->name
);
1507 assert(index
< ifc_type
->length
);
1508 assert(interface_vars
[index
] == NULL
);
1509 interface_vars
[index
] = var
;
1511 return visit_continue
;
1515 * For each unnamed interface block that was discovered while running the
1516 * visitor, adjust the interface type to reflect the newly assigned array
1517 * sizes, and fix up the ir_variable nodes to point to the new interface
1520 void fixup_unnamed_interface_types()
1522 hash_table_call_foreach(this->unnamed_interfaces
,
1523 fixup_unnamed_interface_type
, NULL
);
1528 * If the type pointed to by \c type represents an unsized array, replace
1529 * it with a sized array whose size is determined by max_array_access.
1531 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1532 bool from_ssbo_unsized_array
, bool *implicit_sized
)
1534 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1535 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1536 max_array_access
+ 1);
1537 *implicit_sized
= true;
1538 assert(*type
!= NULL
);
1542 static const glsl_type
*
1543 update_interface_members_array(const glsl_type
*type
,
1544 const glsl_type
*new_interface_type
)
1546 const glsl_type
*element_type
= type
->fields
.array
;
1547 if (element_type
->is_array()) {
1548 const glsl_type
*new_array_type
=
1549 update_interface_members_array(element_type
, new_interface_type
);
1550 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1552 return glsl_type::get_array_instance(new_interface_type
,
1558 * Determine whether the given interface type contains unsized arrays (if
1559 * it doesn't, array_sizing_visitor doesn't need to process it).
1561 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1563 for (unsigned i
= 0; i
< type
->length
; i
++) {
1564 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1565 if (elem_type
->is_unsized_array())
1572 * Create a new interface type based on the given type, with unsized arrays
1573 * replaced by sized arrays whose size is determined by
1574 * max_ifc_array_access.
1576 static const glsl_type
*
1577 resize_interface_members(const glsl_type
*type
,
1578 const int *max_ifc_array_access
,
1581 unsigned num_fields
= type
->length
;
1582 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1583 memcpy(fields
, type
->fields
.structure
,
1584 num_fields
* sizeof(*fields
));
1585 for (unsigned i
= 0; i
< num_fields
; i
++) {
1586 bool implicit_sized_array
= fields
[i
].implicit_sized_array
;
1587 /* If SSBO last member is unsized array, we don't replace it by a sized
1590 if (is_ssbo
&& i
== (num_fields
- 1))
1591 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1592 true, &implicit_sized_array
);
1594 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1595 false, &implicit_sized_array
);
1596 fields
[i
].implicit_sized_array
= implicit_sized_array
;
1598 glsl_interface_packing packing
=
1599 (glsl_interface_packing
) type
->interface_packing
;
1600 const glsl_type
*new_ifc_type
=
1601 glsl_type::get_interface_instance(fields
, num_fields
,
1602 packing
, type
->name
);
1604 return new_ifc_type
;
1607 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1610 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1611 ir_variable
**interface_vars
= (ir_variable
**) data
;
1612 unsigned num_fields
= ifc_type
->length
;
1613 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1614 memcpy(fields
, ifc_type
->fields
.structure
,
1615 num_fields
* sizeof(*fields
));
1616 bool interface_type_changed
= false;
1617 for (unsigned i
= 0; i
< num_fields
; i
++) {
1618 if (interface_vars
[i
] != NULL
&&
1619 fields
[i
].type
!= interface_vars
[i
]->type
) {
1620 fields
[i
].type
= interface_vars
[i
]->type
;
1621 interface_type_changed
= true;
1624 if (!interface_type_changed
) {
1628 glsl_interface_packing packing
=
1629 (glsl_interface_packing
) ifc_type
->interface_packing
;
1630 const glsl_type
*new_ifc_type
=
1631 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1634 for (unsigned i
= 0; i
< num_fields
; i
++) {
1635 if (interface_vars
[i
] != NULL
)
1636 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1641 * Memory context used to allocate the data in \c unnamed_interfaces.
1646 * Hash table from const glsl_type * to an array of ir_variable *'s
1647 * pointing to the ir_variables constituting each unnamed interface block.
1649 hash_table
*unnamed_interfaces
;
1653 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1657 link_xfb_stride_layout_qualifiers(struct gl_context
*ctx
,
1658 struct gl_shader_program
*prog
,
1659 struct gl_linked_shader
*linked_shader
,
1660 struct gl_shader
**shader_list
,
1661 unsigned num_shaders
)
1663 for (unsigned i
= 0; i
< MAX_FEEDBACK_BUFFERS
; i
++) {
1664 linked_shader
->info
.TransformFeedback
.BufferStride
[i
] = 0;
1667 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1668 struct gl_shader
*shader
= shader_list
[i
];
1670 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1671 if (shader
->info
.TransformFeedback
.BufferStride
[j
]) {
1672 if (linked_shader
->info
.TransformFeedback
.BufferStride
[j
] != 0 &&
1673 shader
->info
.TransformFeedback
.BufferStride
[j
] != 0 &&
1674 linked_shader
->info
.TransformFeedback
.BufferStride
[j
] !=
1675 shader
->info
.TransformFeedback
.BufferStride
[j
]) {
1677 "intrastage shaders defined with conflicting "
1678 "xfb_stride for buffer %d (%d and %d)\n", j
,
1680 info
.TransformFeedback
.BufferStride
[j
],
1681 shader
->info
.TransformFeedback
.BufferStride
[j
]);
1685 if (shader
->info
.TransformFeedback
.BufferStride
[j
])
1686 linked_shader
->info
.TransformFeedback
.BufferStride
[j
] =
1687 shader
->info
.TransformFeedback
.BufferStride
[j
];
1692 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1693 if (linked_shader
->info
.TransformFeedback
.BufferStride
[j
]) {
1694 prog
->TransformFeedback
.BufferStride
[j
] =
1695 linked_shader
->info
.TransformFeedback
.BufferStride
[j
];
1697 /* We will validate doubles at a later stage */
1698 if (prog
->TransformFeedback
.BufferStride
[j
] % 4) {
1699 linker_error(prog
, "invalid qualifier xfb_stride=%d must be a "
1700 "multiple of 4 or if its applied to a type that is "
1701 "or contains a double a multiple of 8.",
1702 prog
->TransformFeedback
.BufferStride
[j
]);
1706 if (prog
->TransformFeedback
.BufferStride
[j
] / 4 >
1707 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1709 "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1710 "limit has been exceeded.");
1718 * Performs the cross-validation of tessellation control shader vertices and
1719 * layout qualifiers for the attached tessellation control shaders,
1720 * and propagates them to the linked TCS and linked shader program.
1723 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1724 struct gl_linked_shader
*linked_shader
,
1725 struct gl_shader
**shader_list
,
1726 unsigned num_shaders
)
1728 linked_shader
->info
.TessCtrl
.VerticesOut
= 0;
1730 if (linked_shader
->Stage
!= MESA_SHADER_TESS_CTRL
)
1733 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1735 * "All tessellation control shader layout declarations in a program
1736 * must specify the same output patch vertex count. There must be at
1737 * least one layout qualifier specifying an output patch vertex count
1738 * in any program containing tessellation control shaders; however,
1739 * such a declaration is not required in all tessellation control
1743 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1744 struct gl_shader
*shader
= shader_list
[i
];
1746 if (shader
->info
.TessCtrl
.VerticesOut
!= 0) {
1747 if (linked_shader
->info
.TessCtrl
.VerticesOut
!= 0 &&
1748 linked_shader
->info
.TessCtrl
.VerticesOut
!=
1749 shader
->info
.TessCtrl
.VerticesOut
) {
1750 linker_error(prog
, "tessellation control shader defined with "
1751 "conflicting output vertex count (%d and %d)\n",
1752 linked_shader
->info
.TessCtrl
.VerticesOut
,
1753 shader
->info
.TessCtrl
.VerticesOut
);
1756 linked_shader
->info
.TessCtrl
.VerticesOut
=
1757 shader
->info
.TessCtrl
.VerticesOut
;
1761 /* Just do the intrastage -> interstage propagation right now,
1762 * since we already know we're in the right type of shader program
1765 if (linked_shader
->info
.TessCtrl
.VerticesOut
== 0) {
1766 linker_error(prog
, "tessellation control shader didn't declare "
1767 "vertices out layout qualifier\n");
1774 * Performs the cross-validation of tessellation evaluation shader
1775 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1776 * for the attached tessellation evaluation shaders, and propagates them
1777 * to the linked TES and linked shader program.
1780 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1781 struct gl_linked_shader
*linked_shader
,
1782 struct gl_shader
**shader_list
,
1783 unsigned num_shaders
)
1785 linked_shader
->info
.TessEval
.PrimitiveMode
= PRIM_UNKNOWN
;
1786 linked_shader
->info
.TessEval
.Spacing
= 0;
1787 linked_shader
->info
.TessEval
.VertexOrder
= 0;
1788 linked_shader
->info
.TessEval
.PointMode
= -1;
1790 if (linked_shader
->Stage
!= MESA_SHADER_TESS_EVAL
)
1793 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1795 * "At least one tessellation evaluation shader (compilation unit) in
1796 * a program must declare a primitive mode in its input layout.
1797 * Declaration vertex spacing, ordering, and point mode identifiers is
1798 * optional. It is not required that all tessellation evaluation
1799 * shaders in a program declare a primitive mode. If spacing or
1800 * vertex ordering declarations are omitted, the tessellation
1801 * primitive generator will use equal spacing or counter-clockwise
1802 * vertex ordering, respectively. If a point mode declaration is
1803 * omitted, the tessellation primitive generator will produce lines or
1804 * triangles according to the primitive mode."
1807 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1808 struct gl_shader
*shader
= shader_list
[i
];
1810 if (shader
->info
.TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1811 if (linked_shader
->info
.TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
&&
1812 linked_shader
->info
.TessEval
.PrimitiveMode
!=
1813 shader
->info
.TessEval
.PrimitiveMode
) {
1814 linker_error(prog
, "tessellation evaluation shader defined with "
1815 "conflicting input primitive modes.\n");
1818 linked_shader
->info
.TessEval
.PrimitiveMode
= shader
->info
.TessEval
.PrimitiveMode
;
1821 if (shader
->info
.TessEval
.Spacing
!= 0) {
1822 if (linked_shader
->info
.TessEval
.Spacing
!= 0 &&
1823 linked_shader
->info
.TessEval
.Spacing
!=
1824 shader
->info
.TessEval
.Spacing
) {
1825 linker_error(prog
, "tessellation evaluation shader defined with "
1826 "conflicting vertex spacing.\n");
1829 linked_shader
->info
.TessEval
.Spacing
= shader
->info
.TessEval
.Spacing
;
1832 if (shader
->info
.TessEval
.VertexOrder
!= 0) {
1833 if (linked_shader
->info
.TessEval
.VertexOrder
!= 0 &&
1834 linked_shader
->info
.TessEval
.VertexOrder
!=
1835 shader
->info
.TessEval
.VertexOrder
) {
1836 linker_error(prog
, "tessellation evaluation shader defined with "
1837 "conflicting ordering.\n");
1840 linked_shader
->info
.TessEval
.VertexOrder
=
1841 shader
->info
.TessEval
.VertexOrder
;
1844 if (shader
->info
.TessEval
.PointMode
!= -1) {
1845 if (linked_shader
->info
.TessEval
.PointMode
!= -1 &&
1846 linked_shader
->info
.TessEval
.PointMode
!=
1847 shader
->info
.TessEval
.PointMode
) {
1848 linker_error(prog
, "tessellation evaluation shader defined with "
1849 "conflicting point modes.\n");
1852 linked_shader
->info
.TessEval
.PointMode
=
1853 shader
->info
.TessEval
.PointMode
;
1858 /* Just do the intrastage -> interstage propagation right now,
1859 * since we already know we're in the right type of shader program
1862 if (linked_shader
->info
.TessEval
.PrimitiveMode
== PRIM_UNKNOWN
) {
1864 "tessellation evaluation shader didn't declare input "
1865 "primitive modes.\n");
1869 if (linked_shader
->info
.TessEval
.Spacing
== 0)
1870 linked_shader
->info
.TessEval
.Spacing
= GL_EQUAL
;
1872 if (linked_shader
->info
.TessEval
.VertexOrder
== 0)
1873 linked_shader
->info
.TessEval
.VertexOrder
= GL_CCW
;
1875 if (linked_shader
->info
.TessEval
.PointMode
== -1)
1876 linked_shader
->info
.TessEval
.PointMode
= GL_FALSE
;
1881 * Performs the cross-validation of layout qualifiers specified in
1882 * redeclaration of gl_FragCoord for the attached fragment shaders,
1883 * and propagates them to the linked FS and linked shader program.
1886 link_fs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1887 struct gl_linked_shader
*linked_shader
,
1888 struct gl_shader
**shader_list
,
1889 unsigned num_shaders
)
1891 linked_shader
->info
.redeclares_gl_fragcoord
= false;
1892 linked_shader
->info
.uses_gl_fragcoord
= false;
1893 linked_shader
->info
.origin_upper_left
= false;
1894 linked_shader
->info
.pixel_center_integer
= false;
1895 linked_shader
->info
.BlendSupport
= 0;
1897 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1898 (prog
->Version
< 150 && !prog
->ARB_fragment_coord_conventions_enable
))
1901 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1902 struct gl_shader
*shader
= shader_list
[i
];
1903 /* From the GLSL 1.50 spec, page 39:
1905 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1906 * it must be redeclared in all the fragment shaders in that program
1907 * that have a static use gl_FragCoord."
1909 if ((linked_shader
->info
.redeclares_gl_fragcoord
1910 && !shader
->info
.redeclares_gl_fragcoord
1911 && shader
->info
.uses_gl_fragcoord
)
1912 || (shader
->info
.redeclares_gl_fragcoord
1913 && !linked_shader
->info
.redeclares_gl_fragcoord
1914 && linked_shader
->info
.uses_gl_fragcoord
)) {
1915 linker_error(prog
, "fragment shader defined with conflicting "
1916 "layout qualifiers for gl_FragCoord\n");
1919 /* From the GLSL 1.50 spec, page 39:
1921 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1922 * single program must have the same set of qualifiers."
1924 if (linked_shader
->info
.redeclares_gl_fragcoord
&&
1925 shader
->info
.redeclares_gl_fragcoord
&&
1926 (shader
->info
.origin_upper_left
!=
1927 linked_shader
->info
.origin_upper_left
||
1928 shader
->info
.pixel_center_integer
!=
1929 linked_shader
->info
.pixel_center_integer
)) {
1930 linker_error(prog
, "fragment shader defined with conflicting "
1931 "layout qualifiers for gl_FragCoord\n");
1934 /* Update the linked shader state. Note that uses_gl_fragcoord should
1935 * accumulate the results. The other values should replace. If there
1936 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1937 * are already known to be the same.
1939 if (shader
->info
.redeclares_gl_fragcoord
||
1940 shader
->info
.uses_gl_fragcoord
) {
1941 linked_shader
->info
.redeclares_gl_fragcoord
=
1942 shader
->info
.redeclares_gl_fragcoord
;
1943 linked_shader
->info
.uses_gl_fragcoord
=
1944 linked_shader
->info
.uses_gl_fragcoord
||
1945 shader
->info
.uses_gl_fragcoord
;
1946 linked_shader
->info
.origin_upper_left
=
1947 shader
->info
.origin_upper_left
;
1948 linked_shader
->info
.pixel_center_integer
=
1949 shader
->info
.pixel_center_integer
;
1952 linked_shader
->info
.EarlyFragmentTests
|=
1953 shader
->info
.EarlyFragmentTests
;
1954 linked_shader
->info
.BlendSupport
|= shader
->info
.BlendSupport
;
1959 * Performs the cross-validation of geometry shader max_vertices and
1960 * primitive type layout qualifiers for the attached geometry shaders,
1961 * and propagates them to the linked GS and linked shader program.
1964 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1965 struct gl_linked_shader
*linked_shader
,
1966 struct gl_shader
**shader_list
,
1967 unsigned num_shaders
)
1969 linked_shader
->info
.Geom
.VerticesOut
= -1;
1970 linked_shader
->info
.Geom
.Invocations
= 0;
1971 linked_shader
->info
.Geom
.InputType
= PRIM_UNKNOWN
;
1972 linked_shader
->info
.Geom
.OutputType
= PRIM_UNKNOWN
;
1974 /* No in/out qualifiers defined for anything but GLSL 1.50+
1975 * geometry shaders so far.
1977 if (linked_shader
->Stage
!= MESA_SHADER_GEOMETRY
|| prog
->Version
< 150)
1980 /* From the GLSL 1.50 spec, page 46:
1982 * "All geometry shader output layout declarations in a program
1983 * must declare the same layout and same value for
1984 * max_vertices. There must be at least one geometry output
1985 * layout declaration somewhere in a program, but not all
1986 * geometry shaders (compilation units) are required to
1990 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1991 struct gl_shader
*shader
= shader_list
[i
];
1993 if (shader
->info
.Geom
.InputType
!= PRIM_UNKNOWN
) {
1994 if (linked_shader
->info
.Geom
.InputType
!= PRIM_UNKNOWN
&&
1995 linked_shader
->info
.Geom
.InputType
!=
1996 shader
->info
.Geom
.InputType
) {
1997 linker_error(prog
, "geometry shader defined with conflicting "
2001 linked_shader
->info
.Geom
.InputType
= shader
->info
.Geom
.InputType
;
2004 if (shader
->info
.Geom
.OutputType
!= PRIM_UNKNOWN
) {
2005 if (linked_shader
->info
.Geom
.OutputType
!= PRIM_UNKNOWN
&&
2006 linked_shader
->info
.Geom
.OutputType
!=
2007 shader
->info
.Geom
.OutputType
) {
2008 linker_error(prog
, "geometry shader defined with conflicting "
2012 linked_shader
->info
.Geom
.OutputType
= shader
->info
.Geom
.OutputType
;
2015 if (shader
->info
.Geom
.VerticesOut
!= -1) {
2016 if (linked_shader
->info
.Geom
.VerticesOut
!= -1 &&
2017 linked_shader
->info
.Geom
.VerticesOut
!=
2018 shader
->info
.Geom
.VerticesOut
) {
2019 linker_error(prog
, "geometry shader defined with conflicting "
2020 "output vertex count (%d and %d)\n",
2021 linked_shader
->info
.Geom
.VerticesOut
,
2022 shader
->info
.Geom
.VerticesOut
);
2025 linked_shader
->info
.Geom
.VerticesOut
= shader
->info
.Geom
.VerticesOut
;
2028 if (shader
->info
.Geom
.Invocations
!= 0) {
2029 if (linked_shader
->info
.Geom
.Invocations
!= 0 &&
2030 linked_shader
->info
.Geom
.Invocations
!=
2031 shader
->info
.Geom
.Invocations
) {
2032 linker_error(prog
, "geometry shader defined with conflicting "
2033 "invocation count (%d and %d)\n",
2034 linked_shader
->info
.Geom
.Invocations
,
2035 shader
->info
.Geom
.Invocations
);
2038 linked_shader
->info
.Geom
.Invocations
= shader
->info
.Geom
.Invocations
;
2042 /* Just do the intrastage -> interstage propagation right now,
2043 * since we already know we're in the right type of shader program
2046 if (linked_shader
->info
.Geom
.InputType
== PRIM_UNKNOWN
) {
2048 "geometry shader didn't declare primitive input type\n");
2052 if (linked_shader
->info
.Geom
.OutputType
== PRIM_UNKNOWN
) {
2054 "geometry shader didn't declare primitive output type\n");
2058 if (linked_shader
->info
.Geom
.VerticesOut
== -1) {
2060 "geometry shader didn't declare max_vertices\n");
2064 if (linked_shader
->info
.Geom
.Invocations
== 0)
2065 linked_shader
->info
.Geom
.Invocations
= 1;
2070 * Perform cross-validation of compute shader local_size_{x,y,z} layout
2071 * qualifiers for the attached compute shaders, and propagate them to the
2072 * linked CS and linked shader program.
2075 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
2076 struct gl_linked_shader
*linked_shader
,
2077 struct gl_shader
**shader_list
,
2078 unsigned num_shaders
)
2080 for (int i
= 0; i
< 3; i
++)
2081 linked_shader
->info
.Comp
.LocalSize
[i
] = 0;
2083 /* This function is called for all shader stages, but it only has an effect
2084 * for compute shaders.
2086 if (linked_shader
->Stage
!= MESA_SHADER_COMPUTE
)
2089 /* From the ARB_compute_shader spec, in the section describing local size
2092 * If multiple compute shaders attached to a single program object
2093 * declare local work-group size, the declarations must be identical;
2094 * otherwise a link-time error results. Furthermore, if a program
2095 * object contains any compute shaders, at least one must contain an
2096 * input layout qualifier specifying the local work sizes of the
2097 * program, or a link-time error will occur.
2099 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
2100 struct gl_shader
*shader
= shader_list
[sh
];
2102 if (shader
->info
.Comp
.LocalSize
[0] != 0) {
2103 if (linked_shader
->info
.Comp
.LocalSize
[0] != 0) {
2104 for (int i
= 0; i
< 3; i
++) {
2105 if (linked_shader
->info
.Comp
.LocalSize
[i
] !=
2106 shader
->info
.Comp
.LocalSize
[i
]) {
2107 linker_error(prog
, "compute shader defined with conflicting "
2113 for (int i
= 0; i
< 3; i
++) {
2114 linked_shader
->info
.Comp
.LocalSize
[i
] =
2115 shader
->info
.Comp
.LocalSize
[i
];
2120 /* Just do the intrastage -> interstage propagation right now,
2121 * since we already know we're in the right type of shader program
2124 if (linked_shader
->info
.Comp
.LocalSize
[0] == 0) {
2125 linker_error(prog
, "compute shader didn't declare local size\n");
2128 for (int i
= 0; i
< 3; i
++)
2129 prog
->Comp
.LocalSize
[i
] = linked_shader
->info
.Comp
.LocalSize
[i
];
2134 * Combine a group of shaders for a single stage to generate a linked shader
2137 * If this function is supplied a single shader, it is cloned, and the new
2138 * shader is returned.
2140 static struct gl_linked_shader
*
2141 link_intrastage_shaders(void *mem_ctx
,
2142 struct gl_context
*ctx
,
2143 struct gl_shader_program
*prog
,
2144 struct gl_shader
**shader_list
,
2145 unsigned num_shaders
)
2147 struct gl_uniform_block
*ubo_blocks
= NULL
;
2148 struct gl_uniform_block
*ssbo_blocks
= NULL
;
2149 unsigned num_ubo_blocks
= 0;
2150 unsigned num_ssbo_blocks
= 0;
2152 /* Check that global variables defined in multiple shaders are consistent.
2154 glsl_symbol_table variables
;
2155 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2156 if (shader_list
[i
] == NULL
)
2158 cross_validate_globals(prog
, shader_list
[i
]->ir
, &variables
, false);
2161 if (!prog
->LinkStatus
)
2164 /* Check that interface blocks defined in multiple shaders are consistent.
2166 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
2168 if (!prog
->LinkStatus
)
2171 /* Check that there is only a single definition of each function signature
2172 * across all shaders.
2174 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2175 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2176 ir_function
*const f
= node
->as_function();
2181 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2182 ir_function
*const other
=
2183 shader_list
[j
]->symbols
->get_function(f
->name
);
2185 /* If the other shader has no function (and therefore no function
2186 * signatures) with the same name, skip to the next shader.
2191 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2192 if (!sig
->is_defined
|| sig
->is_builtin())
2195 ir_function_signature
*other_sig
=
2196 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2198 if ((other_sig
!= NULL
) && other_sig
->is_defined
2199 && !other_sig
->is_builtin()) {
2200 linker_error(prog
, "function `%s' is multiply defined\n",
2209 /* Find the shader that defines main, and make a clone of it.
2211 * Starting with the clone, search for undefined references. If one is
2212 * found, find the shader that defines it. Clone the reference and add
2213 * it to the shader. Repeat until there are no undefined references or
2214 * until a reference cannot be resolved.
2216 gl_shader
*main
= NULL
;
2217 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2218 if (_mesa_get_main_function_signature(shader_list
[i
]->symbols
)) {
2219 main
= shader_list
[i
];
2225 linker_error(prog
, "%s shader lacks `main'\n",
2226 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2230 gl_linked_shader
*linked
= ctx
->Driver
.NewShader(shader_list
[0]->Stage
);
2231 linked
->ir
= new(linked
) exec_list
;
2232 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2234 link_fs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2235 link_tcs_out_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2236 link_tes_in_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2237 link_gs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2238 link_cs_input_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2239 link_xfb_stride_layout_qualifiers(ctx
, prog
, linked
, shader_list
,
2242 populate_symbol_table(linked
);
2244 /* The pointer to the main function in the final linked shader (i.e., the
2245 * copy of the original shader that contained the main function).
2247 ir_function_signature
*const main_sig
=
2248 _mesa_get_main_function_signature(linked
->symbols
);
2250 /* Move any instructions other than variable declarations or function
2251 * declarations into main.
2253 exec_node
*insertion_point
=
2254 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2257 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2258 if (shader_list
[i
] == main
)
2261 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2262 insertion_point
, true, linked
);
2265 /* Check if any shader needs built-in functions. */
2266 bool need_builtins
= false;
2267 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2268 if (shader_list
[i
]->info
.uses_builtin_functions
) {
2269 need_builtins
= true;
2275 if (need_builtins
) {
2276 /* Make a temporary array one larger than shader_list, which will hold
2277 * the built-in function shader as well.
2279 gl_shader
**linking_shaders
= (gl_shader
**)
2280 calloc(num_shaders
+ 1, sizeof(gl_shader
*));
2282 ok
= linking_shaders
!= NULL
;
2285 memcpy(linking_shaders
, shader_list
, num_shaders
* sizeof(gl_shader
*));
2286 _mesa_glsl_initialize_builtin_functions();
2287 linking_shaders
[num_shaders
] = _mesa_glsl_get_builtin_function_shader();
2289 ok
= link_function_calls(prog
, linked
, linking_shaders
, num_shaders
+ 1);
2291 free(linking_shaders
);
2293 _mesa_error_no_memory(__func__
);
2296 ok
= link_function_calls(prog
, linked
, shader_list
, num_shaders
);
2301 _mesa_delete_linked_shader(ctx
, linked
);
2305 /* Make a pass over all variable declarations to ensure that arrays with
2306 * unspecified sizes have a size specified. The size is inferred from the
2307 * max_array_access field.
2309 array_sizing_visitor v
;
2311 v
.fixup_unnamed_interface_types();
2313 /* Link up uniform blocks defined within this stage. */
2314 link_uniform_blocks(mem_ctx
, ctx
, prog
, linked
, &ubo_blocks
,
2315 &num_ubo_blocks
, &ssbo_blocks
, &num_ssbo_blocks
);
2317 if (!prog
->LinkStatus
) {
2318 _mesa_delete_linked_shader(ctx
, linked
);
2322 /* Copy ubo blocks to linked shader list */
2323 linked
->UniformBlocks
=
2324 ralloc_array(linked
, gl_uniform_block
*, num_ubo_blocks
);
2325 ralloc_steal(linked
, ubo_blocks
);
2326 for (unsigned i
= 0; i
< num_ubo_blocks
; i
++) {
2327 linked
->UniformBlocks
[i
] = &ubo_blocks
[i
];
2329 linked
->NumUniformBlocks
= num_ubo_blocks
;
2331 /* Copy ssbo blocks to linked shader list */
2332 linked
->ShaderStorageBlocks
=
2333 ralloc_array(linked
, gl_uniform_block
*, num_ssbo_blocks
);
2334 ralloc_steal(linked
, ssbo_blocks
);
2335 for (unsigned i
= 0; i
< num_ssbo_blocks
; i
++) {
2336 linked
->ShaderStorageBlocks
[i
] = &ssbo_blocks
[i
];
2338 linked
->NumShaderStorageBlocks
= num_ssbo_blocks
;
2340 /* At this point linked should contain all of the linked IR, so
2341 * validate it to make sure nothing went wrong.
2343 validate_ir_tree(linked
->ir
);
2345 /* Set the size of geometry shader input arrays */
2346 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2347 unsigned num_vertices
= vertices_per_prim(linked
->info
.Geom
.InputType
);
2348 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2349 MESA_SHADER_GEOMETRY
);
2350 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2351 ir
->accept(&input_resize_visitor
);
2355 if (ctx
->Const
.VertexID_is_zero_based
)
2356 lower_vertex_id(linked
);
2358 /* Validate correct usage of barrier() in the tess control shader */
2359 if (linked
->Stage
== MESA_SHADER_TESS_CTRL
) {
2360 barrier_use_visitor
visitor(prog
);
2361 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2362 ir
->accept(&visitor
);
2370 * Update the sizes of linked shader uniform arrays to the maximum
2373 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2375 * If one or more elements of an array are active,
2376 * GetActiveUniform will return the name of the array in name,
2377 * subject to the restrictions listed above. The type of the array
2378 * is returned in type. The size parameter contains the highest
2379 * array element index used, plus one. The compiler or linker
2380 * determines the highest index used. There will be only one
2381 * active uniform reported by the GL per uniform array.
2385 update_array_sizes(struct gl_shader_program
*prog
)
2387 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2388 if (prog
->_LinkedShaders
[i
] == NULL
)
2391 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2392 ir_variable
*const var
= node
->as_variable();
2394 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2395 !var
->type
->is_array())
2398 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2399 * will not be eliminated. Since we always do std140, just
2400 * don't resize arrays in UBOs.
2402 * Atomic counters are supposed to get deterministic
2403 * locations assigned based on the declaration ordering and
2404 * sizes, array compaction would mess that up.
2406 * Subroutine uniforms are not removed.
2408 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2409 var
->type
->contains_subroutine() || var
->constant_initializer
)
2412 int size
= var
->data
.max_array_access
;
2413 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2414 if (prog
->_LinkedShaders
[j
] == NULL
)
2417 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2418 ir_variable
*other_var
= node2
->as_variable();
2422 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2423 other_var
->data
.max_array_access
> size
) {
2424 size
= other_var
->data
.max_array_access
;
2429 if (size
+ 1 != (int)var
->type
->length
) {
2430 /* If this is a built-in uniform (i.e., it's backed by some
2431 * fixed-function state), adjust the number of state slots to
2432 * match the new array size. The number of slots per array entry
2433 * is not known. It seems safe to assume that the total number of
2434 * slots is an integer multiple of the number of array elements.
2435 * Determine the number of slots per array element by dividing by
2436 * the old (total) size.
2438 const unsigned num_slots
= var
->get_num_state_slots();
2439 if (num_slots
> 0) {
2440 var
->set_num_state_slots((size
+ 1)
2441 * (num_slots
/ var
->type
->length
));
2444 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2446 /* FINISHME: We should update the types of array
2447 * dereferences of this variable now.
2455 * Resize tessellation evaluation per-vertex inputs to the size of
2456 * tessellation control per-vertex outputs.
2459 resize_tes_inputs(struct gl_context
*ctx
,
2460 struct gl_shader_program
*prog
)
2462 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2465 gl_linked_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2466 gl_linked_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2468 /* If no control shader is present, then the TES inputs are statically
2469 * sized to MaxPatchVertices; the actual size of the arrays won't be
2470 * known until draw time.
2472 const int num_vertices
= tcs
2473 ? tcs
->info
.TessCtrl
.VerticesOut
2474 : ctx
->Const
.MaxPatchVertices
;
2476 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2477 MESA_SHADER_TESS_EVAL
);
2478 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2479 ir
->accept(&input_resize_visitor
);
2482 if (tcs
|| ctx
->Const
.LowerTESPatchVerticesIn
) {
2483 /* Convert the gl_PatchVerticesIn system value into a constant, since
2484 * the value is known at this point.
2486 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2487 ir_variable
*var
= ir
->as_variable();
2488 if (var
&& var
->data
.mode
== ir_var_system_value
&&
2489 var
->data
.location
== SYSTEM_VALUE_VERTICES_IN
) {
2490 void *mem_ctx
= ralloc_parent(var
);
2491 var
->data
.location
= 0;
2492 var
->data
.explicit_location
= false;
2494 var
->data
.mode
= ir_var_auto
;
2495 var
->constant_value
= new(mem_ctx
) ir_constant(num_vertices
);
2497 var
->data
.mode
= ir_var_uniform
;
2498 var
->data
.how_declared
= ir_var_hidden
;
2499 var
->allocate_state_slots(1);
2500 ir_state_slot
*slot0
= &var
->get_state_slots()[0];
2501 slot0
->swizzle
= SWIZZLE_XXXX
;
2502 slot0
->tokens
[0] = STATE_INTERNAL
;
2503 slot0
->tokens
[1] = STATE_TES_PATCH_VERTICES_IN
;
2504 for (int i
= 2; i
< STATE_LENGTH
; i
++)
2505 slot0
->tokens
[i
] = 0;
2513 * Find a contiguous set of available bits in a bitmask.
2515 * \param used_mask Bits representing used (1) and unused (0) locations
2516 * \param needed_count Number of contiguous bits needed.
2519 * Base location of the available bits on success or -1 on failure.
2522 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2524 unsigned needed_mask
= (1 << needed_count
) - 1;
2525 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2527 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2528 * cannot optimize possibly infinite loops" for the loop below.
2530 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2533 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2534 if ((needed_mask
& ~used_mask
) == needed_mask
)
2545 * Assign locations for either VS inputs or FS outputs
2547 * \param mem_ctx Temporary ralloc context used for linking
2548 * \param prog Shader program whose variables need locations assigned
2549 * \param constants Driver specific constant values for the program.
2550 * \param target_index Selector for the program target to receive location
2551 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2552 * \c MESA_SHADER_FRAGMENT.
2555 * If locations are successfully assigned, true is returned. Otherwise an
2556 * error is emitted to the shader link log and false is returned.
2559 assign_attribute_or_color_locations(void *mem_ctx
,
2560 gl_shader_program
*prog
,
2561 struct gl_constants
*constants
,
2562 unsigned target_index
)
2564 /* Maximum number of generic locations. This corresponds to either the
2565 * maximum number of draw buffers or the maximum number of generic
2568 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2569 constants
->Program
[target_index
].MaxAttribs
:
2570 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2572 /* Mark invalid locations as being used.
2574 unsigned used_locations
= (max_index
>= 32)
2575 ? ~0 : ~((1 << max_index
) - 1);
2576 unsigned double_storage_locations
= 0;
2578 assert((target_index
== MESA_SHADER_VERTEX
)
2579 || (target_index
== MESA_SHADER_FRAGMENT
));
2581 gl_linked_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2585 /* Operate in a total of four passes.
2587 * 1. Invalidate the location assignments for all vertex shader inputs.
2589 * 2. Assign locations for inputs that have user-defined (via
2590 * glBindVertexAttribLocation) locations and outputs that have
2591 * user-defined locations (via glBindFragDataLocation).
2593 * 3. Sort the attributes without assigned locations by number of slots
2594 * required in decreasing order. Fragmentation caused by attribute
2595 * locations assigned by the application may prevent large attributes
2596 * from having enough contiguous space.
2598 * 4. Assign locations to any inputs without assigned locations.
2601 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2602 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2604 const enum ir_variable_mode direction
=
2605 (target_index
== MESA_SHADER_VERTEX
)
2606 ? ir_var_shader_in
: ir_var_shader_out
;
2609 /* Temporary storage for the set of attributes that need locations assigned.
2615 /* Used below in the call to qsort. */
2616 static int compare(const void *a
, const void *b
)
2618 const temp_attr
*const l
= (const temp_attr
*) a
;
2619 const temp_attr
*const r
= (const temp_attr
*) b
;
2621 /* Reversed because we want a descending order sort below. */
2622 return r
->slots
- l
->slots
;
2625 assert(max_index
<= 32);
2627 /* Temporary array for the set of attributes that have locations assigned.
2629 ir_variable
*assigned
[16];
2631 unsigned num_attr
= 0;
2632 unsigned assigned_attr
= 0;
2634 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2635 ir_variable
*const var
= node
->as_variable();
2637 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2640 if (var
->data
.explicit_location
) {
2641 var
->data
.is_unmatched_generic_inout
= 0;
2642 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2643 || (var
->data
.location
< 0)) {
2645 "invalid explicit location %d specified for `%s'\n",
2646 (var
->data
.location
< 0)
2647 ? var
->data
.location
2648 : var
->data
.location
- generic_base
,
2652 } else if (target_index
== MESA_SHADER_VERTEX
) {
2655 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2656 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2657 var
->data
.location
= binding
;
2658 var
->data
.is_unmatched_generic_inout
= 0;
2660 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2663 const char *name
= var
->name
;
2664 const glsl_type
*type
= var
->type
;
2667 /* Check if there's a binding for the variable name */
2668 if (prog
->FragDataBindings
->get(binding
, name
)) {
2669 assert(binding
>= FRAG_RESULT_DATA0
);
2670 var
->data
.location
= binding
;
2671 var
->data
.is_unmatched_generic_inout
= 0;
2673 if (prog
->FragDataIndexBindings
->get(index
, name
)) {
2674 var
->data
.index
= index
;
2679 /* If not, but it's an array type, look for name[0] */
2680 if (type
->is_array()) {
2681 name
= ralloc_asprintf(mem_ctx
, "%s[0]", name
);
2682 type
= type
->fields
.array
;
2690 if (strcmp(var
->name
, "gl_LastFragData") == 0)
2693 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2695 * "Output binding assignments will cause LinkProgram to fail:
2697 * If the program has an active output assigned to a location greater
2698 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2699 * an active output assigned an index greater than or equal to one;"
2701 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2702 var
->data
.location
- generic_base
>=
2703 (int) constants
->MaxDualSourceDrawBuffers
) {
2705 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2706 "with index %u for %s\n",
2707 var
->data
.location
- generic_base
, var
->data
.index
,
2712 const unsigned slots
= var
->type
->count_attribute_slots(target_index
== MESA_SHADER_VERTEX
);
2714 /* If the variable is not a built-in and has a location statically
2715 * assigned in the shader (presumably via a layout qualifier), make sure
2716 * that it doesn't collide with other assigned locations. Otherwise,
2717 * add it to the list of variables that need linker-assigned locations.
2719 if (var
->data
.location
!= -1) {
2720 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2721 /* From page 61 of the OpenGL 4.0 spec:
2723 * "LinkProgram will fail if the attribute bindings assigned
2724 * by BindAttribLocation do not leave not enough space to
2725 * assign a location for an active matrix attribute or an
2726 * active attribute array, both of which require multiple
2727 * contiguous generic attributes."
2729 * I think above text prohibits the aliasing of explicit and
2730 * automatic assignments. But, aliasing is allowed in manual
2731 * assignments of attribute locations. See below comments for
2734 * From OpenGL 4.0 spec, page 61:
2736 * "It is possible for an application to bind more than one
2737 * attribute name to the same location. This is referred to as
2738 * aliasing. This will only work if only one of the aliased
2739 * attributes is active in the executable program, or if no
2740 * path through the shader consumes more than one attribute of
2741 * a set of attributes aliased to the same location. A link
2742 * error can occur if the linker determines that every path
2743 * through the shader consumes multiple aliased attributes,
2744 * but implementations are not required to generate an error
2747 * From GLSL 4.30 spec, page 54:
2749 * "A program will fail to link if any two non-vertex shader
2750 * input variables are assigned to the same location. For
2751 * vertex shaders, multiple input variables may be assigned
2752 * to the same location using either layout qualifiers or via
2753 * the OpenGL API. However, such aliasing is intended only to
2754 * support vertex shaders where each execution path accesses
2755 * at most one input per each location. Implementations are
2756 * permitted, but not required, to generate link-time errors
2757 * if they detect that every path through the vertex shader
2758 * executable accesses multiple inputs assigned to any single
2759 * location. For all shader types, a program will fail to link
2760 * if explicit location assignments leave the linker unable
2761 * to find space for other variables without explicit
2764 * From OpenGL ES 3.0 spec, page 56:
2766 * "Binding more than one attribute name to the same location
2767 * is referred to as aliasing, and is not permitted in OpenGL
2768 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2769 * fail when this condition exists. However, aliasing is
2770 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2771 * This will only work if only one of the aliased attributes
2772 * is active in the executable program, or if no path through
2773 * the shader consumes more than one attribute of a set of
2774 * attributes aliased to the same location. A link error can
2775 * occur if the linker determines that every path through the
2776 * shader consumes multiple aliased attributes, but implemen-
2777 * tations are not required to generate an error in this case."
2779 * After looking at above references from OpenGL, OpenGL ES and
2780 * GLSL specifications, we allow aliasing of vertex input variables
2781 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2783 * NOTE: This is not required by the spec but its worth mentioning
2784 * here that we're not doing anything to make sure that no path
2785 * through the vertex shader executable accesses multiple inputs
2786 * assigned to any single location.
2789 /* Mask representing the contiguous slots that will be used by
2792 const unsigned attr
= var
->data
.location
- generic_base
;
2793 const unsigned use_mask
= (1 << slots
) - 1;
2794 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2795 ? "vertex shader input" : "fragment shader output";
2797 /* Generate a link error if the requested locations for this
2798 * attribute exceed the maximum allowed attribute location.
2800 if (attr
+ slots
> max_index
) {
2802 "insufficient contiguous locations "
2803 "available for %s `%s' %d %d %d\n", string
,
2804 var
->name
, used_locations
, use_mask
, attr
);
2808 /* Generate a link error if the set of bits requested for this
2809 * attribute overlaps any previously allocated bits.
2811 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
2812 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
2813 /* From section 4.4.2 (Output Layout Qualifiers) of the GLSL
2816 * "Additionally, for fragment shader outputs, if two
2817 * variables are placed within the same location, they
2818 * must have the same underlying type (floating-point or
2819 * integer). No component aliasing of output variables or
2820 * members is allowed.
2822 for (unsigned i
= 0; i
< assigned_attr
; i
++) {
2823 unsigned assigned_slots
=
2824 assigned
[i
]->type
->count_attribute_slots(false);
2825 unsigned assig_attr
=
2826 assigned
[i
]->data
.location
- generic_base
;
2827 unsigned assigned_use_mask
= (1 << assigned_slots
) - 1;
2829 if ((assigned_use_mask
<< assig_attr
) &
2830 (use_mask
<< attr
)) {
2832 const glsl_type
*assigned_type
=
2833 assigned
[i
]->type
->without_array();
2834 const glsl_type
*type
= var
->type
->without_array();
2835 if (assigned_type
->base_type
!= type
->base_type
) {
2836 linker_error(prog
, "types do not match for aliased"
2837 " %ss %s and %s\n", string
,
2838 assigned
[i
]->name
, var
->name
);
2842 unsigned assigned_component_mask
=
2843 ((1 << assigned_type
->vector_elements
) - 1) <<
2844 assigned
[i
]->data
.location_frac
;
2845 unsigned component_mask
=
2846 ((1 << type
->vector_elements
) - 1) <<
2847 var
->data
.location_frac
;
2848 if (assigned_component_mask
& component_mask
) {
2849 linker_error(prog
, "overlapping component is "
2850 "assigned to %ss %s and %s "
2852 string
, assigned
[i
]->name
, var
->name
,
2853 var
->data
.location_frac
);
2858 } else if (target_index
== MESA_SHADER_FRAGMENT
||
2859 (prog
->IsES
&& prog
->Version
>= 300)) {
2860 linker_error(prog
, "overlapping location is assigned "
2861 "to %s `%s' %d %d %d\n", string
, var
->name
,
2862 used_locations
, use_mask
, attr
);
2865 linker_warning(prog
, "overlapping location is assigned "
2866 "to %s `%s' %d %d %d\n", string
, var
->name
,
2867 used_locations
, use_mask
, attr
);
2871 used_locations
|= (use_mask
<< attr
);
2873 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2875 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2876 * active attribute variables may fail to link, unless
2877 * device-dependent optimizations are able to make the program
2878 * fit within available hardware resources. For the purposes
2879 * of this test, attribute variables of the type dvec3, dvec4,
2880 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2881 * count as consuming twice as many attributes as equivalent
2882 * single-precision types. While these types use the same number
2883 * of generic attributes as their single-precision equivalents,
2884 * implementations are permitted to consume two single-precision
2885 * vectors of internal storage for each three- or four-component
2886 * double-precision vector."
2888 * Mark this attribute slot as taking up twice as much space
2889 * so we can count it properly against limits. According to
2890 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2891 * is optional behavior, but it seems preferable.
2893 if (var
->type
->without_array()->is_dual_slot())
2894 double_storage_locations
|= (use_mask
<< attr
);
2897 assigned
[assigned_attr
] = var
;
2903 if (num_attr
>= max_index
) {
2904 linker_error(prog
, "too many %s (max %u)",
2905 target_index
== MESA_SHADER_VERTEX
?
2906 "vertex shader inputs" : "fragment shader outputs",
2910 to_assign
[num_attr
].slots
= slots
;
2911 to_assign
[num_attr
].var
= var
;
2915 if (target_index
== MESA_SHADER_VERTEX
) {
2916 unsigned total_attribs_size
=
2917 _mesa_bitcount(used_locations
& ((1 << max_index
) - 1)) +
2918 _mesa_bitcount(double_storage_locations
);
2919 if (total_attribs_size
> max_index
) {
2921 "attempt to use %d vertex attribute slots only %d available ",
2922 total_attribs_size
, max_index
);
2927 /* If all of the attributes were assigned locations by the application (or
2928 * are built-in attributes with fixed locations), return early. This should
2929 * be the common case.
2934 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
2936 if (target_index
== MESA_SHADER_VERTEX
) {
2937 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2938 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2939 * reserved to prevent it from being automatically allocated below.
2941 find_deref_visitor
find("gl_Vertex");
2943 if (find
.variable_found())
2944 used_locations
|= (1 << 0);
2947 for (unsigned i
= 0; i
< num_attr
; i
++) {
2948 /* Mask representing the contiguous slots that will be used by this
2951 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
2953 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
2956 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2957 ? "vertex shader input" : "fragment shader output";
2960 "insufficient contiguous locations "
2961 "available for %s `%s'\n",
2962 string
, to_assign
[i
].var
->name
);
2966 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
2967 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
2968 used_locations
|= (use_mask
<< location
);
2970 if (to_assign
[i
].var
->type
->without_array()->is_dual_slot())
2971 double_storage_locations
|= (use_mask
<< location
);
2974 /* Now that we have all the locations, from the GL 4.5 core spec, section
2975 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
2976 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
2977 * as equivalent single-precision types.
2979 if (target_index
== MESA_SHADER_VERTEX
) {
2980 unsigned total_attribs_size
=
2981 _mesa_bitcount(used_locations
& ((1 << max_index
) - 1)) +
2982 _mesa_bitcount(double_storage_locations
);
2983 if (total_attribs_size
> max_index
) {
2985 "attempt to use %d vertex attribute slots only %d available ",
2986 total_attribs_size
, max_index
);
2995 * Match explicit locations of outputs to inputs and deactivate the
2996 * unmatch flag if found so we don't optimise them away.
2999 match_explicit_outputs_to_inputs(gl_linked_shader
*producer
,
3000 gl_linked_shader
*consumer
)
3002 glsl_symbol_table parameters
;
3003 ir_variable
*explicit_locations
[MAX_VARYINGS_INCL_PATCH
][4] =
3006 /* Find all shader outputs in the "producer" stage.
3008 foreach_in_list(ir_instruction
, node
, producer
->ir
) {
3009 ir_variable
*const var
= node
->as_variable();
3011 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_shader_out
))
3014 if (var
->data
.explicit_location
&&
3015 var
->data
.location
>= VARYING_SLOT_VAR0
) {
3016 const unsigned idx
= var
->data
.location
- VARYING_SLOT_VAR0
;
3017 if (explicit_locations
[idx
][var
->data
.location_frac
] == NULL
)
3018 explicit_locations
[idx
][var
->data
.location_frac
] = var
;
3022 /* Match inputs to outputs */
3023 foreach_in_list(ir_instruction
, node
, consumer
->ir
) {
3024 ir_variable
*const input
= node
->as_variable();
3026 if ((input
== NULL
) || (input
->data
.mode
!= ir_var_shader_in
))
3029 ir_variable
*output
= NULL
;
3030 if (input
->data
.explicit_location
3031 && input
->data
.location
>= VARYING_SLOT_VAR0
) {
3032 output
= explicit_locations
[input
->data
.location
- VARYING_SLOT_VAR0
]
3033 [input
->data
.location_frac
];
3035 if (output
!= NULL
){
3036 input
->data
.is_unmatched_generic_inout
= 0;
3037 output
->data
.is_unmatched_generic_inout
= 0;
3044 * Store the gl_FragDepth layout in the gl_shader_program struct.
3047 store_fragdepth_layout(struct gl_shader_program
*prog
)
3049 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
3053 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
3055 /* We don't look up the gl_FragDepth symbol directly because if
3056 * gl_FragDepth is not used in the shader, it's removed from the IR.
3057 * However, the symbol won't be removed from the symbol table.
3059 * We're only interested in the cases where the variable is NOT removed
3062 foreach_in_list(ir_instruction
, node
, ir
) {
3063 ir_variable
*const var
= node
->as_variable();
3065 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
3069 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
3070 switch (var
->data
.depth_layout
) {
3071 case ir_depth_layout_none
:
3072 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
3074 case ir_depth_layout_any
:
3075 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
3077 case ir_depth_layout_greater
:
3078 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
3080 case ir_depth_layout_less
:
3081 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
3083 case ir_depth_layout_unchanged
:
3084 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
3095 * Validate the resources used by a program versus the implementation limits
3098 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3100 unsigned total_uniform_blocks
= 0;
3101 unsigned total_shader_storage_blocks
= 0;
3103 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3104 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3109 if (sh
->num_samplers
> ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
3110 linker_error(prog
, "Too many %s shader texture samplers\n",
3111 _mesa_shader_stage_to_string(i
));
3114 if (sh
->num_uniform_components
>
3115 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
3116 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3117 linker_warning(prog
, "Too many %s shader default uniform block "
3118 "components, but the driver will try to optimize "
3119 "them out; this is non-portable out-of-spec "
3121 _mesa_shader_stage_to_string(i
));
3123 linker_error(prog
, "Too many %s shader default uniform block "
3125 _mesa_shader_stage_to_string(i
));
3129 if (sh
->num_combined_uniform_components
>
3130 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
3131 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3132 linker_warning(prog
, "Too many %s shader uniform components, "
3133 "but the driver will try to optimize them out; "
3134 "this is non-portable out-of-spec behavior\n",
3135 _mesa_shader_stage_to_string(i
));
3137 linker_error(prog
, "Too many %s shader uniform components\n",
3138 _mesa_shader_stage_to_string(i
));
3142 total_shader_storage_blocks
+= sh
->NumShaderStorageBlocks
;
3143 total_uniform_blocks
+= sh
->NumUniformBlocks
;
3145 const unsigned max_uniform_blocks
=
3146 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
3147 if (max_uniform_blocks
< sh
->NumUniformBlocks
) {
3148 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
3149 _mesa_shader_stage_to_string(i
), sh
->NumUniformBlocks
,
3150 max_uniform_blocks
);
3153 const unsigned max_shader_storage_blocks
=
3154 ctx
->Const
.Program
[i
].MaxShaderStorageBlocks
;
3155 if (max_shader_storage_blocks
< sh
->NumShaderStorageBlocks
) {
3156 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
3157 _mesa_shader_stage_to_string(i
),
3158 sh
->NumShaderStorageBlocks
, max_shader_storage_blocks
);
3162 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
3163 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
3164 total_uniform_blocks
, ctx
->Const
.MaxCombinedUniformBlocks
);
3167 if (total_shader_storage_blocks
> ctx
->Const
.MaxCombinedShaderStorageBlocks
) {
3168 linker_error(prog
, "Too many combined shader storage blocks (%d/%d)\n",
3169 total_shader_storage_blocks
,
3170 ctx
->Const
.MaxCombinedShaderStorageBlocks
);
3173 for (unsigned i
= 0; i
< prog
->NumUniformBlocks
; i
++) {
3174 if (prog
->UniformBlocks
[i
].UniformBufferSize
>
3175 ctx
->Const
.MaxUniformBlockSize
) {
3176 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
3177 prog
->UniformBlocks
[i
].Name
,
3178 prog
->UniformBlocks
[i
].UniformBufferSize
,
3179 ctx
->Const
.MaxUniformBlockSize
);
3183 for (unsigned i
= 0; i
< prog
->NumShaderStorageBlocks
; i
++) {
3184 if (prog
->ShaderStorageBlocks
[i
].UniformBufferSize
>
3185 ctx
->Const
.MaxShaderStorageBlockSize
) {
3186 linker_error(prog
, "Shader storage block %s too big (%d/%d)\n",
3187 prog
->ShaderStorageBlocks
[i
].Name
,
3188 prog
->ShaderStorageBlocks
[i
].UniformBufferSize
,
3189 ctx
->Const
.MaxShaderStorageBlockSize
);
3195 link_calculate_subroutine_compat(struct gl_shader_program
*prog
)
3197 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3198 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3203 for (unsigned j
= 0; j
< sh
->NumSubroutineUniformRemapTable
; j
++) {
3204 if (sh
->SubroutineUniformRemapTable
[j
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
)
3207 struct gl_uniform_storage
*uni
= sh
->SubroutineUniformRemapTable
[j
];
3212 sh
->NumSubroutineUniforms
++;
3214 if (sh
->NumSubroutineFunctions
== 0) {
3215 linker_error(prog
, "subroutine uniform %s defined but no valid functions found\n", uni
->type
->name
);
3218 for (unsigned f
= 0; f
< sh
->NumSubroutineFunctions
; f
++) {
3219 struct gl_subroutine_function
*fn
= &sh
->SubroutineFunctions
[f
];
3220 for (int k
= 0; k
< fn
->num_compat_types
; k
++) {
3221 if (fn
->types
[k
] == uni
->type
) {
3227 uni
->num_compatible_subroutines
= count
;
3233 check_subroutine_resources(struct gl_shader_program
*prog
)
3235 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3236 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3239 if (sh
->NumSubroutineUniformRemapTable
> MAX_SUBROUTINE_UNIFORM_LOCATIONS
)
3240 linker_error(prog
, "Too many %s shader subroutine uniforms\n",
3241 _mesa_shader_stage_to_string(i
));
3246 * Validate shader image resources.
3249 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3251 unsigned total_image_units
= 0;
3252 unsigned fragment_outputs
= 0;
3253 unsigned total_shader_storage_blocks
= 0;
3255 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
3258 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3259 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3262 if (sh
->NumImages
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
3263 linker_error(prog
, "Too many %s shader image uniforms (%u > %u)\n",
3264 _mesa_shader_stage_to_string(i
), sh
->NumImages
,
3265 ctx
->Const
.Program
[i
].MaxImageUniforms
);
3267 total_image_units
+= sh
->NumImages
;
3268 total_shader_storage_blocks
+= sh
->NumShaderStorageBlocks
;
3270 if (i
== MESA_SHADER_FRAGMENT
) {
3271 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3272 ir_variable
*var
= node
->as_variable();
3273 if (var
&& var
->data
.mode
== ir_var_shader_out
)
3274 /* since there are no double fs outputs - pass false */
3275 fragment_outputs
+= var
->type
->count_attribute_slots(false);
3281 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
3282 linker_error(prog
, "Too many combined image uniforms\n");
3284 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
3285 ctx
->Const
.MaxCombinedShaderOutputResources
)
3286 linker_error(prog
, "Too many combined image uniforms, shader storage "
3287 " buffers and fragment outputs\n");
3292 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3293 * for a variable, checks for overlaps between other uniforms using explicit
3297 reserve_explicit_locations(struct gl_shader_program
*prog
,
3298 string_to_uint_map
*map
, ir_variable
*var
)
3300 unsigned slots
= var
->type
->uniform_locations();
3301 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3302 unsigned return_value
= slots
;
3304 /* Resize remap table if locations do not fit in the current one. */
3305 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
3306 prog
->UniformRemapTable
=
3307 reralloc(prog
, prog
->UniformRemapTable
,
3308 gl_uniform_storage
*,
3311 if (!prog
->UniformRemapTable
) {
3312 linker_error(prog
, "Out of memory during linking.\n");
3316 /* Initialize allocated space. */
3317 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
3318 prog
->UniformRemapTable
[i
] = NULL
;
3320 prog
->NumUniformRemapTable
= max_loc
+ 1;
3323 for (unsigned i
= 0; i
< slots
; i
++) {
3324 unsigned loc
= var
->data
.location
+ i
;
3326 /* Check if location is already used. */
3327 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3329 /* Possibly same uniform from a different stage, this is ok. */
3331 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
) {
3336 /* ARB_explicit_uniform_location specification states:
3338 * "No two default-block uniform variables in the program can have
3339 * the same location, even if they are unused, otherwise a compiler
3340 * or linker error will be generated."
3343 "location qualifier for uniform %s overlaps "
3344 "previously used location\n",
3349 /* Initialize location as inactive before optimization
3350 * rounds and location assignment.
3352 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3355 /* Note, base location used for arrays. */
3356 map
->put(var
->data
.location
, var
->name
);
3358 return return_value
;
3362 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3363 struct gl_linked_shader
*sh
,
3366 unsigned slots
= var
->type
->uniform_locations();
3367 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3369 /* Resize remap table if locations do not fit in the current one. */
3370 if (max_loc
+ 1 > sh
->NumSubroutineUniformRemapTable
) {
3371 sh
->SubroutineUniformRemapTable
=
3372 reralloc(sh
, sh
->SubroutineUniformRemapTable
,
3373 gl_uniform_storage
*,
3376 if (!sh
->SubroutineUniformRemapTable
) {
3377 linker_error(prog
, "Out of memory during linking.\n");
3381 /* Initialize allocated space. */
3382 for (unsigned i
= sh
->NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3383 sh
->SubroutineUniformRemapTable
[i
] = NULL
;
3385 sh
->NumSubroutineUniformRemapTable
= max_loc
+ 1;
3388 for (unsigned i
= 0; i
< slots
; i
++) {
3389 unsigned loc
= var
->data
.location
+ i
;
3391 /* Check if location is already used. */
3392 if (sh
->SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3394 /* ARB_explicit_uniform_location specification states:
3395 * "No two subroutine uniform variables can have the same location
3396 * in the same shader stage, otherwise a compiler or linker error
3397 * will be generated."
3400 "location qualifier for uniform %s overlaps "
3401 "previously used location\n",
3406 /* Initialize location as inactive before optimization
3407 * rounds and location assignment.
3409 sh
->SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3415 * Check and reserve all explicit uniform locations, called before
3416 * any optimizations happen to handle also inactive uniforms and
3417 * inactive array elements that may get trimmed away.
3420 check_explicit_uniform_locations(struct gl_context
*ctx
,
3421 struct gl_shader_program
*prog
)
3423 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3426 /* This map is used to detect if overlapping explicit locations
3427 * occur with the same uniform (from different stage) or a different one.
3429 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3432 linker_error(prog
, "Out of memory during linking.\n");
3436 unsigned entries_total
= 0;
3437 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3438 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3443 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3444 ir_variable
*var
= node
->as_variable();
3445 if (!var
|| var
->data
.mode
!= ir_var_uniform
)
3448 if (var
->data
.explicit_location
) {
3450 if (var
->type
->without_array()->is_subroutine())
3451 ret
= reserve_subroutine_explicit_locations(prog
, sh
, var
);
3453 int slots
= reserve_explicit_locations(prog
, uniform_map
,
3457 entries_total
+= slots
;
3468 struct empty_uniform_block
*current_block
= NULL
;
3470 for (unsigned i
= 0; i
< prog
->NumUniformRemapTable
; i
++) {
3471 /* We found empty space in UniformRemapTable. */
3472 if (prog
->UniformRemapTable
[i
] == NULL
) {
3473 /* We've found the beginning of a new continous block of empty slots */
3474 if (!current_block
|| current_block
->start
+ current_block
->slots
!= i
) {
3475 current_block
= rzalloc(prog
, struct empty_uniform_block
);
3476 current_block
->start
= i
;
3477 exec_list_push_tail(&prog
->EmptyUniformLocations
,
3478 ¤t_block
->link
);
3481 /* The current block continues, so we simply increment its slots */
3482 current_block
->slots
++;
3487 return entries_total
;
3491 should_add_buffer_variable(struct gl_shader_program
*shProg
,
3492 GLenum type
, const char *name
)
3494 bool found_interface
= false;
3495 unsigned block_name_len
= 0;
3496 const char *block_name_dot
= strchr(name
, '.');
3498 /* These rules only apply to buffer variables. So we return
3499 * true for the rest of types.
3501 if (type
!= GL_BUFFER_VARIABLE
)
3504 for (unsigned i
= 0; i
< shProg
->NumShaderStorageBlocks
; i
++) {
3505 const char *block_name
= shProg
->ShaderStorageBlocks
[i
].Name
;
3506 block_name_len
= strlen(block_name
);
3508 const char *block_square_bracket
= strchr(block_name
, '[');
3509 if (block_square_bracket
) {
3510 /* The block is part of an array of named interfaces,
3511 * for the name comparison we ignore the "[x]" part.
3513 block_name_len
-= strlen(block_square_bracket
);
3516 if (block_name_dot
) {
3517 /* Check if the variable name starts with the interface
3518 * name. The interface name (if present) should have the
3519 * length than the interface block name we are comparing to.
3521 unsigned len
= strlen(name
) - strlen(block_name_dot
);
3522 if (len
!= block_name_len
)
3526 if (strncmp(block_name
, name
, block_name_len
) == 0) {
3527 found_interface
= true;
3532 /* We remove the interface name from the buffer variable name,
3533 * including the dot that follows it.
3535 if (found_interface
)
3536 name
= name
+ block_name_len
+ 1;
3538 /* The ARB_program_interface_query spec says:
3540 * "For an active shader storage block member declared as an array, an
3541 * entry will be generated only for the first array element, regardless
3542 * of its type. For arrays of aggregate types, the enumeration rules
3543 * are applied recursively for the single enumerated array element."
3545 const char *struct_first_dot
= strchr(name
, '.');
3546 const char *first_square_bracket
= strchr(name
, '[');
3548 /* The buffer variable is on top level and it is not an array */
3549 if (!first_square_bracket
) {
3551 /* The shader storage block member is a struct, then generate the entry */
3552 } else if (struct_first_dot
&& struct_first_dot
< first_square_bracket
) {
3555 /* Shader storage block member is an array, only generate an entry for the
3556 * first array element.
3558 if (strncmp(first_square_bracket
, "[0]", 3) == 0)
3566 add_program_resource(struct gl_shader_program
*prog
,
3567 struct set
*resource_set
,
3568 GLenum type
, const void *data
, uint8_t stages
)
3572 /* If resource already exists, do not add it again. */
3573 if (_mesa_set_search(resource_set
, data
))
3576 prog
->ProgramResourceList
=
3578 prog
->ProgramResourceList
,
3579 gl_program_resource
,
3580 prog
->NumProgramResourceList
+ 1);
3582 if (!prog
->ProgramResourceList
) {
3583 linker_error(prog
, "Out of memory during linking.\n");
3587 struct gl_program_resource
*res
=
3588 &prog
->ProgramResourceList
[prog
->NumProgramResourceList
];
3592 res
->StageReferences
= stages
;
3594 prog
->NumProgramResourceList
++;
3596 _mesa_set_add(resource_set
, data
);
3601 /* Function checks if a variable var is a packed varying and
3602 * if given name is part of packed varying's list.
3604 * If a variable is a packed varying, it has a name like
3605 * 'packed:a,b,c' where a, b and c are separate variables.
3608 included_in_packed_varying(ir_variable
*var
, const char *name
)
3610 if (strncmp(var
->name
, "packed:", 7) != 0)
3613 char *list
= strdup(var
->name
+ 7);
3618 char *token
= strtok_r(list
, ",", &saveptr
);
3620 if (strcmp(token
, name
) == 0) {
3624 token
= strtok_r(NULL
, ",", &saveptr
);
3631 * Function builds a stage reference bitmask from variable name.
3634 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3639 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3640 * used for reference mask in gl_program_resource will need to be changed.
3642 assert(MESA_SHADER_STAGES
< 8);
3644 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3645 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
3649 /* Shader symbol table may contain variables that have
3650 * been optimized away. Search IR for the variable instead.
3652 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3653 ir_variable
*var
= node
->as_variable();
3655 unsigned baselen
= strlen(var
->name
);
3657 if (included_in_packed_varying(var
, name
)) {
3662 /* Type needs to match if specified, otherwise we might
3663 * pick a variable with same name but different interface.
3665 if (var
->data
.mode
!= mode
)
3668 if (strncmp(var
->name
, name
, baselen
) == 0) {
3669 /* Check for exact name matches but also check for arrays and
3672 if (name
[baselen
] == '\0' ||
3673 name
[baselen
] == '[' ||
3674 name
[baselen
] == '.') {
3686 * Create gl_shader_variable from ir_variable class.
3688 static gl_shader_variable
*
3689 create_shader_variable(struct gl_shader_program
*shProg
,
3690 const ir_variable
*in
,
3691 const char *name
, const glsl_type
*type
,
3692 bool use_implicit_location
, int location
,
3693 const glsl_type
*outermost_struct_type
)
3695 gl_shader_variable
*out
= ralloc(shProg
, struct gl_shader_variable
);
3699 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3700 * expect to see gl_VertexID in the program resource list. Pretend.
3702 if (in
->data
.mode
== ir_var_system_value
&&
3703 in
->data
.location
== SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
) {
3704 out
->name
= ralloc_strdup(shProg
, "gl_VertexID");
3705 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3706 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_OUTER
) ||
3707 (in
->data
.mode
== ir_var_system_value
&&
3708 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_OUTER
)) {
3709 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelOuter");
3710 type
= glsl_type::get_array_instance(glsl_type::float_type
, 4);
3711 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3712 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_INNER
) ||
3713 (in
->data
.mode
== ir_var_system_value
&&
3714 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_INNER
)) {
3715 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelInner");
3716 type
= glsl_type::get_array_instance(glsl_type::float_type
, 2);
3718 out
->name
= ralloc_strdup(shProg
, name
);
3724 /* The ARB_program_interface_query spec says:
3726 * "Not all active variables are assigned valid locations; the
3727 * following variables will have an effective location of -1:
3729 * * uniforms declared as atomic counters;
3731 * * members of a uniform block;
3733 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3735 * * inputs or outputs not declared with a "location" layout
3736 * qualifier, except for vertex shader inputs and fragment shader
3739 if (in
->type
->base_type
== GLSL_TYPE_ATOMIC_UINT
||
3740 is_gl_identifier(in
->name
) ||
3741 !(in
->data
.explicit_location
|| use_implicit_location
)) {
3744 out
->location
= location
;
3748 out
->outermost_struct_type
= outermost_struct_type
;
3749 out
->interface_type
= in
->get_interface_type();
3750 out
->component
= in
->data
.location_frac
;
3751 out
->index
= in
->data
.index
;
3752 out
->patch
= in
->data
.patch
;
3753 out
->mode
= in
->data
.mode
;
3754 out
->interpolation
= in
->data
.interpolation
;
3755 out
->explicit_location
= in
->data
.explicit_location
;
3756 out
->precision
= in
->data
.precision
;
3762 add_shader_variable(struct gl_shader_program
*shProg
, struct set
*resource_set
,
3763 unsigned stage_mask
,
3764 GLenum programInterface
, ir_variable
*var
,
3765 const char *name
, const glsl_type
*type
,
3766 bool use_implicit_location
, int location
,
3767 const glsl_type
*outermost_struct_type
= NULL
)
3769 const bool is_vertex_input
=
3770 programInterface
== GL_PROGRAM_INPUT
&&
3771 stage_mask
== MESA_SHADER_VERTEX
;
3773 switch (type
->base_type
) {
3774 case GLSL_TYPE_STRUCT
: {
3775 /* The ARB_program_interface_query spec says:
3777 * "For an active variable declared as a structure, a separate entry
3778 * will be generated for each active structure member. The name of
3779 * each entry is formed by concatenating the name of the structure,
3780 * the "." character, and the name of the structure member. If a
3781 * structure member to enumerate is itself a structure or array,
3782 * these enumeration rules are applied recursively."
3784 if (outermost_struct_type
== NULL
)
3785 outermost_struct_type
= type
;
3787 unsigned field_location
= location
;
3788 for (unsigned i
= 0; i
< type
->length
; i
++) {
3789 const struct glsl_struct_field
*field
= &type
->fields
.structure
[i
];
3790 char *field_name
= ralloc_asprintf(shProg
, "%s.%s", name
, field
->name
);
3791 if (!add_shader_variable(shProg
, resource_set
,
3792 stage_mask
, programInterface
,
3793 var
, field_name
, field
->type
,
3794 use_implicit_location
, field_location
,
3795 outermost_struct_type
))
3799 field
->type
->count_attribute_slots(is_vertex_input
);
3805 /* Issue #16 of the ARB_program_interface_query spec says:
3807 * "* If a variable is a member of an interface block without an
3808 * instance name, it is enumerated using just the variable name.
3810 * * If a variable is a member of an interface block with an instance
3811 * name, it is enumerated as "BlockName.Member", where "BlockName" is
3812 * the name of the interface block (not the instance name) and
3813 * "Member" is the name of the variable."
3815 const char *prefixed_name
= (var
->data
.from_named_ifc_block
&&
3816 !is_gl_identifier(var
->name
))
3817 ? ralloc_asprintf(shProg
, "%s.%s", var
->get_interface_type()->name
,
3821 /* The ARB_program_interface_query spec says:
3823 * "For an active variable declared as a single instance of a basic
3824 * type, a single entry will be generated, using the variable name
3825 * from the shader source."
3827 gl_shader_variable
*sha_v
=
3828 create_shader_variable(shProg
, var
, prefixed_name
, type
,
3829 use_implicit_location
, location
,
3830 outermost_struct_type
);
3834 return add_program_resource(shProg
, resource_set
,
3835 programInterface
, sha_v
, stage_mask
);
3841 add_interface_variables(struct gl_shader_program
*shProg
,
3842 struct set
*resource_set
,
3843 unsigned stage
, GLenum programInterface
)
3845 exec_list
*ir
= shProg
->_LinkedShaders
[stage
]->ir
;
3847 foreach_in_list(ir_instruction
, node
, ir
) {
3848 ir_variable
*var
= node
->as_variable();
3850 if (!var
|| var
->data
.how_declared
== ir_var_hidden
)
3855 switch (var
->data
.mode
) {
3856 case ir_var_system_value
:
3857 case ir_var_shader_in
:
3858 if (programInterface
!= GL_PROGRAM_INPUT
)
3860 loc_bias
= (stage
== MESA_SHADER_VERTEX
) ? int(VERT_ATTRIB_GENERIC0
)
3861 : int(VARYING_SLOT_VAR0
);
3863 case ir_var_shader_out
:
3864 if (programInterface
!= GL_PROGRAM_OUTPUT
)
3866 loc_bias
= (stage
== MESA_SHADER_FRAGMENT
) ? int(FRAG_RESULT_DATA0
)
3867 : int(VARYING_SLOT_VAR0
);
3873 if (var
->data
.patch
)
3874 loc_bias
= int(VARYING_SLOT_PATCH0
);
3876 /* Skip packed varyings, packed varyings are handled separately
3877 * by add_packed_varyings.
3879 if (strncmp(var
->name
, "packed:", 7) == 0)
3882 /* Skip fragdata arrays, these are handled separately
3883 * by add_fragdata_arrays.
3885 if (strncmp(var
->name
, "gl_out_FragData", 15) == 0)
3888 const bool vs_input_or_fs_output
=
3889 (stage
== MESA_SHADER_VERTEX
&& var
->data
.mode
== ir_var_shader_in
) ||
3890 (stage
== MESA_SHADER_FRAGMENT
&& var
->data
.mode
== ir_var_shader_out
);
3892 if (!add_shader_variable(shProg
, resource_set
,
3893 1 << stage
, programInterface
,
3894 var
, var
->name
, var
->type
, vs_input_or_fs_output
,
3895 var
->data
.location
- loc_bias
))
3902 add_packed_varyings(struct gl_shader_program
*shProg
, struct set
*resource_set
,
3903 int stage
, GLenum type
)
3905 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[stage
];
3908 if (!sh
|| !sh
->packed_varyings
)
3911 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
3912 ir_variable
*var
= node
->as_variable();
3914 switch (var
->data
.mode
) {
3915 case ir_var_shader_in
:
3916 iface
= GL_PROGRAM_INPUT
;
3918 case ir_var_shader_out
:
3919 iface
= GL_PROGRAM_OUTPUT
;
3922 unreachable("unexpected type");
3925 if (type
== iface
) {
3926 const int stage_mask
=
3927 build_stageref(shProg
, var
->name
, var
->data
.mode
);
3928 if (!add_shader_variable(shProg
, resource_set
,
3930 iface
, var
, var
->name
, var
->type
, false,
3931 var
->data
.location
- VARYING_SLOT_VAR0
))
3940 add_fragdata_arrays(struct gl_shader_program
*shProg
, struct set
*resource_set
)
3942 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
3944 if (!sh
|| !sh
->fragdata_arrays
)
3947 foreach_in_list(ir_instruction
, node
, sh
->fragdata_arrays
) {
3948 ir_variable
*var
= node
->as_variable();
3950 assert(var
->data
.mode
== ir_var_shader_out
);
3952 if (!add_shader_variable(shProg
, resource_set
,
3953 1 << MESA_SHADER_FRAGMENT
,
3954 GL_PROGRAM_OUTPUT
, var
, var
->name
, var
->type
,
3955 true, var
->data
.location
- FRAG_RESULT_DATA0
))
3963 get_top_level_name(const char *name
)
3965 const char *first_dot
= strchr(name
, '.');
3966 const char *first_square_bracket
= strchr(name
, '[');
3969 /* The ARB_program_interface_query spec says:
3971 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
3972 * the number of active array elements of the top-level shader storage
3973 * block member containing to the active variable is written to
3974 * <params>. If the top-level block member is not declared as an
3975 * array, the value one is written to <params>. If the top-level block
3976 * member is an array with no declared size, the value zero is written
3980 /* The buffer variable is on top level.*/
3981 if (!first_square_bracket
&& !first_dot
)
3982 name_size
= strlen(name
);
3983 else if ((!first_square_bracket
||
3984 (first_dot
&& first_dot
< first_square_bracket
)))
3985 name_size
= first_dot
- name
;
3987 name_size
= first_square_bracket
- name
;
3989 return strndup(name
, name_size
);
3993 get_var_name(const char *name
)
3995 const char *first_dot
= strchr(name
, '.');
3998 return strdup(name
);
4000 return strndup(first_dot
+1, strlen(first_dot
) - 1);
4004 is_top_level_shader_storage_block_member(const char* name
,
4005 const char* interface_name
,
4006 const char* field_name
)
4008 bool result
= false;
4010 /* If the given variable is already a top-level shader storage
4011 * block member, then return array_size = 1.
4012 * We could have two possibilities: if we have an instanced
4013 * shader storage block or not instanced.
4015 * For the first, we check create a name as it was in top level and
4016 * compare it with the real name. If they are the same, then
4017 * the variable is already at top-level.
4019 * Full instanced name is: interface name + '.' + var name +
4022 int name_length
= strlen(interface_name
) + 1 + strlen(field_name
) + 1;
4023 char *full_instanced_name
= (char *) calloc(name_length
, sizeof(char));
4024 if (!full_instanced_name
) {
4025 fprintf(stderr
, "%s: Cannot allocate space for name\n", __func__
);
4029 snprintf(full_instanced_name
, name_length
, "%s.%s",
4030 interface_name
, field_name
);
4032 /* Check if its top-level shader storage block member of an
4033 * instanced interface block, or of a unnamed interface block.
4035 if (strcmp(name
, full_instanced_name
) == 0 ||
4036 strcmp(name
, field_name
) == 0)
4039 free(full_instanced_name
);
4044 get_array_size(struct gl_uniform_storage
*uni
, const glsl_struct_field
*field
,
4045 char *interface_name
, char *var_name
)
4047 /* The ARB_program_interface_query spec says:
4049 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4050 * the number of active array elements of the top-level shader storage
4051 * block member containing to the active variable is written to
4052 * <params>. If the top-level block member is not declared as an
4053 * array, the value one is written to <params>. If the top-level block
4054 * member is an array with no declared size, the value zero is written
4057 if (is_top_level_shader_storage_block_member(uni
->name
,
4061 else if (field
->type
->is_unsized_array())
4063 else if (field
->type
->is_array())
4064 return field
->type
->length
;
4070 get_array_stride(struct gl_uniform_storage
*uni
, const glsl_type
*interface
,
4071 const glsl_struct_field
*field
, char *interface_name
,
4074 /* The ARB_program_interface_query spec says:
4076 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
4077 * identifying the stride between array elements of the top-level
4078 * shader storage block member containing the active variable is
4079 * written to <params>. For top-level block members declared as
4080 * arrays, the value written is the difference, in basic machine units,
4081 * between the offsets of the active variable for consecutive elements
4082 * in the top-level array. For top-level block members not declared as
4083 * an array, zero is written to <params>."
4085 if (field
->type
->is_array()) {
4086 const enum glsl_matrix_layout matrix_layout
=
4087 glsl_matrix_layout(field
->matrix_layout
);
4088 bool row_major
= matrix_layout
== GLSL_MATRIX_LAYOUT_ROW_MAJOR
;
4089 const glsl_type
*array_type
= field
->type
->fields
.array
;
4091 if (is_top_level_shader_storage_block_member(uni
->name
,
4096 if (interface
->interface_packing
!= GLSL_INTERFACE_PACKING_STD430
) {
4097 if (array_type
->is_record() || array_type
->is_array())
4098 return glsl_align(array_type
->std140_size(row_major
), 16);
4100 return MAX2(array_type
->std140_base_alignment(row_major
), 16);
4102 return array_type
->std430_array_stride(row_major
);
4109 calculate_array_size_and_stride(struct gl_shader_program
*shProg
,
4110 struct gl_uniform_storage
*uni
)
4112 int block_index
= uni
->block_index
;
4113 int array_size
= -1;
4114 int array_stride
= -1;
4115 char *var_name
= get_top_level_name(uni
->name
);
4116 char *interface_name
=
4117 get_top_level_name(uni
->is_shader_storage
?
4118 shProg
->ShaderStorageBlocks
[block_index
].Name
:
4119 shProg
->UniformBlocks
[block_index
].Name
);
4121 if (strcmp(var_name
, interface_name
) == 0) {
4122 /* Deal with instanced array of SSBOs */
4123 char *temp_name
= get_var_name(uni
->name
);
4125 linker_error(shProg
, "Out of memory during linking.\n");
4126 goto write_top_level_array_size_and_stride
;
4129 var_name
= get_top_level_name(temp_name
);
4132 linker_error(shProg
, "Out of memory during linking.\n");
4133 goto write_top_level_array_size_and_stride
;
4137 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4138 const gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
4142 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
4143 ir_variable
*var
= node
->as_variable();
4144 if (!var
|| !var
->get_interface_type() ||
4145 var
->data
.mode
!= ir_var_shader_storage
)
4148 const glsl_type
*interface
= var
->get_interface_type();
4150 if (strcmp(interface_name
, interface
->name
) != 0)
4153 for (unsigned i
= 0; i
< interface
->length
; i
++) {
4154 const glsl_struct_field
*field
= &interface
->fields
.structure
[i
];
4155 if (strcmp(field
->name
, var_name
) != 0)
4158 array_stride
= get_array_stride(uni
, interface
, field
,
4159 interface_name
, var_name
);
4160 array_size
= get_array_size(uni
, field
, interface_name
, var_name
);
4161 goto write_top_level_array_size_and_stride
;
4165 write_top_level_array_size_and_stride
:
4166 free(interface_name
);
4168 uni
->top_level_array_stride
= array_stride
;
4169 uni
->top_level_array_size
= array_size
;
4173 * Builds up a list of program resources that point to existing
4177 build_program_resource_list(struct gl_context
*ctx
,
4178 struct gl_shader_program
*shProg
)
4180 /* Rebuild resource list. */
4181 if (shProg
->ProgramResourceList
) {
4182 ralloc_free(shProg
->ProgramResourceList
);
4183 shProg
->ProgramResourceList
= NULL
;
4184 shProg
->NumProgramResourceList
= 0;
4187 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
4189 /* Determine first input and final output stage. These are used to
4190 * detect which variables should be enumerated in the resource list
4191 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4193 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4194 if (!shProg
->_LinkedShaders
[i
])
4196 if (input_stage
== MESA_SHADER_STAGES
)
4201 /* Empty shader, no resources. */
4202 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
4205 struct set
*resource_set
= _mesa_set_create(NULL
,
4207 _mesa_key_pointer_equal
);
4209 /* Program interface needs to expose varyings in case of SSO. */
4210 if (shProg
->SeparateShader
) {
4211 if (!add_packed_varyings(shProg
, resource_set
,
4212 input_stage
, GL_PROGRAM_INPUT
))
4215 if (!add_packed_varyings(shProg
, resource_set
,
4216 output_stage
, GL_PROGRAM_OUTPUT
))
4220 if (!add_fragdata_arrays(shProg
, resource_set
))
4223 /* Add inputs and outputs to the resource list. */
4224 if (!add_interface_variables(shProg
, resource_set
,
4225 input_stage
, GL_PROGRAM_INPUT
))
4228 if (!add_interface_variables(shProg
, resource_set
,
4229 output_stage
, GL_PROGRAM_OUTPUT
))
4232 /* Add transform feedback varyings. */
4233 if (shProg
->LinkedTransformFeedback
.NumVarying
> 0) {
4234 for (int i
= 0; i
< shProg
->LinkedTransformFeedback
.NumVarying
; i
++) {
4235 if (!add_program_resource(shProg
, resource_set
,
4236 GL_TRANSFORM_FEEDBACK_VARYING
,
4237 &shProg
->LinkedTransformFeedback
.Varyings
[i
],
4243 /* Add transform feedback buffers. */
4244 for (unsigned i
= 0; i
< ctx
->Const
.MaxTransformFeedbackBuffers
; i
++) {
4245 if ((shProg
->LinkedTransformFeedback
.ActiveBuffers
>> i
) & 1) {
4246 shProg
->LinkedTransformFeedback
.Buffers
[i
].Binding
= i
;
4247 if (!add_program_resource(shProg
, resource_set
,
4248 GL_TRANSFORM_FEEDBACK_BUFFER
,
4249 &shProg
->LinkedTransformFeedback
.Buffers
[i
],
4255 /* Add uniforms from uniform storage. */
4256 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
4257 /* Do not add uniforms internally used by Mesa. */
4258 if (shProg
->UniformStorage
[i
].hidden
)
4262 build_stageref(shProg
, shProg
->UniformStorage
[i
].name
,
4265 /* Add stagereferences for uniforms in a uniform block. */
4266 bool is_shader_storage
= shProg
->UniformStorage
[i
].is_shader_storage
;
4267 int block_index
= shProg
->UniformStorage
[i
].block_index
;
4268 if (block_index
!= -1) {
4269 stageref
|= is_shader_storage
?
4270 shProg
->ShaderStorageBlocks
[block_index
].stageref
:
4271 shProg
->UniformBlocks
[block_index
].stageref
;
4274 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
4275 if (!should_add_buffer_variable(shProg
, type
,
4276 shProg
->UniformStorage
[i
].name
))
4279 if (is_shader_storage
) {
4280 calculate_array_size_and_stride(shProg
, &shProg
->UniformStorage
[i
]);
4283 if (!add_program_resource(shProg
, resource_set
, type
,
4284 &shProg
->UniformStorage
[i
], stageref
))
4288 /* Add program uniform blocks. */
4289 for (unsigned i
= 0; i
< shProg
->NumUniformBlocks
; i
++) {
4290 if (!add_program_resource(shProg
, resource_set
, GL_UNIFORM_BLOCK
,
4291 &shProg
->UniformBlocks
[i
], 0))
4295 /* Add program shader storage blocks. */
4296 for (unsigned i
= 0; i
< shProg
->NumShaderStorageBlocks
; i
++) {
4297 if (!add_program_resource(shProg
, resource_set
, GL_SHADER_STORAGE_BLOCK
,
4298 &shProg
->ShaderStorageBlocks
[i
], 0))
4302 /* Add atomic counter buffers. */
4303 for (unsigned i
= 0; i
< shProg
->NumAtomicBuffers
; i
++) {
4304 if (!add_program_resource(shProg
, resource_set
, GL_ATOMIC_COUNTER_BUFFER
,
4305 &shProg
->AtomicBuffers
[i
], 0))
4309 for (unsigned i
= 0; i
< shProg
->NumUniformStorage
; i
++) {
4311 if (!shProg
->UniformStorage
[i
].hidden
)
4314 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
4315 if (!shProg
->UniformStorage
[i
].opaque
[j
].active
||
4316 !shProg
->UniformStorage
[i
].type
->is_subroutine())
4319 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
4320 /* add shader subroutines */
4321 if (!add_program_resource(shProg
, resource_set
,
4322 type
, &shProg
->UniformStorage
[i
], 0))
4327 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4328 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
4334 type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
4335 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
4336 if (!add_program_resource(shProg
, resource_set
,
4337 type
, &sh
->SubroutineFunctions
[j
], 0))
4342 _mesa_set_destroy(resource_set
, NULL
);
4346 * This check is done to make sure we allow only constant expression
4347 * indexing and "constant-index-expression" (indexing with an expression
4348 * that includes loop induction variable).
4351 validate_sampler_array_indexing(struct gl_context
*ctx
,
4352 struct gl_shader_program
*prog
)
4354 dynamic_sampler_array_indexing_visitor v
;
4355 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4356 if (prog
->_LinkedShaders
[i
] == NULL
)
4359 bool no_dynamic_indexing
=
4360 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
4362 /* Search for array derefs in shader. */
4363 v
.run(prog
->_LinkedShaders
[i
]->ir
);
4364 if (v
.uses_dynamic_sampler_array_indexing()) {
4365 const char *msg
= "sampler arrays indexed with non-constant "
4366 "expressions is forbidden in GLSL %s %u";
4367 /* Backend has indicated that it has no dynamic indexing support. */
4368 if (no_dynamic_indexing
) {
4369 linker_error(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
4372 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "", prog
->Version
);
4380 link_assign_subroutine_types(struct gl_shader_program
*prog
)
4382 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4383 gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
4388 sh
->MaxSubroutineFunctionIndex
= 0;
4389 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
4390 ir_function
*fn
= node
->as_function();
4394 if (fn
->is_subroutine
)
4395 sh
->NumSubroutineUniformTypes
++;
4397 if (!fn
->num_subroutine_types
)
4400 /* these should have been calculated earlier. */
4401 assert(fn
->subroutine_index
!= -1);
4402 if (sh
->NumSubroutineFunctions
+ 1 > MAX_SUBROUTINES
) {
4403 linker_error(prog
, "Too many subroutine functions declared.\n");
4406 sh
->SubroutineFunctions
= reralloc(sh
, sh
->SubroutineFunctions
,
4407 struct gl_subroutine_function
,
4408 sh
->NumSubroutineFunctions
+ 1);
4409 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].name
= ralloc_strdup(sh
, fn
->name
);
4410 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
4411 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
=
4412 ralloc_array(sh
, const struct glsl_type
*,
4413 fn
->num_subroutine_types
);
4415 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4418 * "Each subroutine with an index qualifier in the shader must be
4419 * given a unique index, otherwise a compile or link error will be
4422 for (unsigned j
= 0; j
< sh
->NumSubroutineFunctions
; j
++) {
4423 if (sh
->SubroutineFunctions
[j
].index
!= -1 &&
4424 sh
->SubroutineFunctions
[j
].index
== fn
->subroutine_index
) {
4425 linker_error(prog
, "each subroutine index qualifier in the "
4426 "shader must be unique\n");
4430 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].index
=
4431 fn
->subroutine_index
;
4433 if (fn
->subroutine_index
> (int)sh
->MaxSubroutineFunctionIndex
)
4434 sh
->MaxSubroutineFunctionIndex
= fn
->subroutine_index
;
4436 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
4437 sh
->SubroutineFunctions
[sh
->NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
4438 sh
->NumSubroutineFunctions
++;
4444 set_always_active_io(exec_list
*ir
, ir_variable_mode io_mode
)
4446 assert(io_mode
== ir_var_shader_in
|| io_mode
== ir_var_shader_out
);
4448 foreach_in_list(ir_instruction
, node
, ir
) {
4449 ir_variable
*const var
= node
->as_variable();
4451 if (var
== NULL
|| var
->data
.mode
!= io_mode
)
4454 /* Don't set always active on builtins that haven't been redeclared */
4455 if (var
->data
.how_declared
== ir_var_declared_implicitly
)
4458 var
->data
.always_active_io
= true;
4463 * When separate shader programs are enabled, only input/outputs between
4464 * the stages of a multi-stage separate program can be safely removed
4465 * from the shader interface. Other inputs/outputs must remain active.
4468 disable_varying_optimizations_for_sso(struct gl_shader_program
*prog
)
4470 unsigned first
, last
;
4471 assert(prog
->SeparateShader
);
4473 first
= MESA_SHADER_STAGES
;
4476 /* Determine first and last stage. Excluding the compute stage */
4477 for (unsigned i
= 0; i
< MESA_SHADER_COMPUTE
; i
++) {
4478 if (!prog
->_LinkedShaders
[i
])
4480 if (first
== MESA_SHADER_STAGES
)
4485 if (first
== MESA_SHADER_STAGES
)
4488 for (unsigned stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4489 gl_linked_shader
*sh
= prog
->_LinkedShaders
[stage
];
4493 if (first
== last
) {
4494 /* For a single shader program only allow inputs to the vertex shader
4495 * and outputs from the fragment shader to be removed.
4497 if (stage
!= MESA_SHADER_VERTEX
)
4498 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4499 if (stage
!= MESA_SHADER_FRAGMENT
)
4500 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4502 /* For multi-stage separate shader programs only allow inputs and
4503 * outputs between the shader stages to be removed as well as inputs
4504 * to the vertex shader and outputs from the fragment shader.
4506 if (stage
== first
&& stage
!= MESA_SHADER_VERTEX
)
4507 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4508 else if (stage
== last
&& stage
!= MESA_SHADER_FRAGMENT
)
4509 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4515 link_varyings_and_uniforms(unsigned first
, unsigned last
,
4516 unsigned num_explicit_uniform_locs
,
4517 struct gl_context
*ctx
,
4518 struct gl_shader_program
*prog
, void *mem_ctx
)
4520 bool has_xfb_qualifiers
= false;
4521 unsigned num_tfeedback_decls
= 0;
4522 char **varying_names
= NULL
;
4523 tfeedback_decl
*tfeedback_decls
= NULL
;
4525 /* Mark all generic shader inputs and outputs as unpaired. */
4526 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4527 if (prog
->_LinkedShaders
[i
] != NULL
) {
4528 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
4532 unsigned prev
= first
;
4533 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4534 if (prog
->_LinkedShaders
[i
] == NULL
)
4537 match_explicit_outputs_to_inputs(prog
->_LinkedShaders
[prev
],
4538 prog
->_LinkedShaders
[i
]);
4542 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4543 MESA_SHADER_VERTEX
)) {
4547 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4548 MESA_SHADER_FRAGMENT
)) {
4552 /* From the ARB_enhanced_layouts spec:
4554 * "If the shader used to record output variables for transform feedback
4555 * varyings uses the "xfb_buffer", "xfb_offset", or "xfb_stride" layout
4556 * qualifiers, the values specified by TransformFeedbackVaryings are
4557 * ignored, and the set of variables captured for transform feedback is
4558 * instead derived from the specified layout qualifiers."
4560 for (int i
= MESA_SHADER_FRAGMENT
- 1; i
>= 0; i
--) {
4561 /* Find last stage before fragment shader */
4562 if (prog
->_LinkedShaders
[i
]) {
4563 has_xfb_qualifiers
=
4564 process_xfb_layout_qualifiers(mem_ctx
, prog
->_LinkedShaders
[i
],
4565 &num_tfeedback_decls
,
4571 if (!has_xfb_qualifiers
) {
4572 num_tfeedback_decls
= prog
->TransformFeedback
.NumVarying
;
4573 varying_names
= prog
->TransformFeedback
.VaryingNames
;
4576 if (num_tfeedback_decls
!= 0) {
4577 /* From GL_EXT_transform_feedback:
4578 * A program will fail to link if:
4580 * * the <count> specified by TransformFeedbackVaryingsEXT is
4581 * non-zero, but the program object has no vertex or geometry
4584 if (first
>= MESA_SHADER_FRAGMENT
) {
4585 linker_error(prog
, "Transform feedback varyings specified, but "
4586 "no vertex, tessellation, or geometry shader is "
4591 tfeedback_decls
= ralloc_array(mem_ctx
, tfeedback_decl
,
4592 num_tfeedback_decls
);
4593 if (!parse_tfeedback_decls(ctx
, prog
, mem_ctx
, num_tfeedback_decls
,
4594 varying_names
, tfeedback_decls
))
4598 /* If there is no fragment shader we need to set transform feedback.
4600 * For SSO we also need to assign output locations. We assign them here
4601 * because we need to do it for both single stage programs and multi stage
4604 if (last
< MESA_SHADER_FRAGMENT
&&
4605 (num_tfeedback_decls
!= 0 || prog
->SeparateShader
)) {
4606 const uint64_t reserved_out_slots
=
4607 reserved_varying_slot(prog
->_LinkedShaders
[last
], ir_var_shader_out
);
4608 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
4609 prog
->_LinkedShaders
[last
], NULL
,
4610 num_tfeedback_decls
, tfeedback_decls
,
4611 reserved_out_slots
))
4615 if (last
<= MESA_SHADER_FRAGMENT
) {
4616 /* Remove unused varyings from the first/last stage unless SSO */
4617 remove_unused_shader_inputs_and_outputs(prog
->SeparateShader
,
4618 prog
->_LinkedShaders
[first
],
4620 remove_unused_shader_inputs_and_outputs(prog
->SeparateShader
,
4621 prog
->_LinkedShaders
[last
],
4624 /* If the program is made up of only a single stage */
4625 if (first
== last
) {
4626 gl_linked_shader
*const sh
= prog
->_LinkedShaders
[last
];
4628 do_dead_builtin_varyings(ctx
, NULL
, sh
, 0, NULL
);
4629 do_dead_builtin_varyings(ctx
, sh
, NULL
, num_tfeedback_decls
,
4632 if (prog
->SeparateShader
) {
4633 const uint64_t reserved_slots
=
4634 reserved_varying_slot(sh
, ir_var_shader_in
);
4636 /* Assign input locations for SSO, output locations are already
4639 if (!assign_varying_locations(ctx
, mem_ctx
, prog
,
4640 NULL
/* producer */,
4642 0 /* num_tfeedback_decls */,
4643 NULL
/* tfeedback_decls */,
4648 /* Linking the stages in the opposite order (from fragment to vertex)
4649 * ensures that inter-shader outputs written to in an earlier stage
4650 * are eliminated if they are (transitively) not used in a later
4654 for (int i
= next
- 1; i
>= 0; i
--) {
4655 if (prog
->_LinkedShaders
[i
] == NULL
&& i
!= 0)
4658 gl_linked_shader
*const sh_i
= prog
->_LinkedShaders
[i
];
4659 gl_linked_shader
*const sh_next
= prog
->_LinkedShaders
[next
];
4661 const uint64_t reserved_out_slots
=
4662 reserved_varying_slot(sh_i
, ir_var_shader_out
);
4663 const uint64_t reserved_in_slots
=
4664 reserved_varying_slot(sh_next
, ir_var_shader_in
);
4666 do_dead_builtin_varyings(ctx
, sh_i
, sh_next
,
4667 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
4670 if (!assign_varying_locations(ctx
, mem_ctx
, prog
, sh_i
, sh_next
,
4671 next
== MESA_SHADER_FRAGMENT
? num_tfeedback_decls
: 0,
4673 reserved_out_slots
| reserved_in_slots
))
4676 /* This must be done after all dead varyings are eliminated. */
4678 unsigned slots_used
= _mesa_bitcount_64(reserved_out_slots
);
4679 if (!check_against_output_limit(ctx
, prog
, sh_i
, slots_used
)) {
4684 unsigned slots_used
= _mesa_bitcount_64(reserved_in_slots
);
4685 if (!check_against_input_limit(ctx
, prog
, sh_next
, slots_used
))
4693 if (!store_tfeedback_info(ctx
, prog
, num_tfeedback_decls
, tfeedback_decls
,
4694 has_xfb_qualifiers
))
4697 update_array_sizes(prog
);
4698 link_assign_uniform_locations(prog
, ctx
->Const
.UniformBooleanTrue
,
4699 num_explicit_uniform_locs
,
4700 ctx
->Const
.MaxUserAssignableUniformLocations
);
4701 link_assign_atomic_counter_resources(ctx
, prog
);
4703 link_calculate_subroutine_compat(prog
);
4704 check_resources(ctx
, prog
);
4705 check_subroutine_resources(prog
);
4706 check_image_resources(ctx
, prog
);
4707 link_check_atomic_counter_resources(ctx
, prog
);
4709 if (!prog
->LinkStatus
)
4712 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4713 if (prog
->_LinkedShaders
[i
] == NULL
)
4716 const struct gl_shader_compiler_options
*options
=
4717 &ctx
->Const
.ShaderCompilerOptions
[i
];
4719 if (options
->LowerBufferInterfaceBlocks
)
4720 lower_ubo_reference(prog
->_LinkedShaders
[i
],
4721 options
->ClampBlockIndicesToArrayBounds
);
4723 if (options
->LowerShaderSharedVariables
)
4724 lower_shared_reference(prog
->_LinkedShaders
[i
],
4725 &prog
->Comp
.SharedSize
);
4727 lower_vector_derefs(prog
->_LinkedShaders
[i
]);
4728 do_vec_index_to_swizzle(prog
->_LinkedShaders
[i
]->ir
);
4735 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
4737 prog
->LinkStatus
= true; /* All error paths will set this to false */
4738 prog
->Validated
= false;
4739 prog
->_Used
= false;
4741 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4743 * "Linking can fail for a variety of reasons as specified in the
4744 * OpenGL Shading Language Specification, as well as any of the
4745 * following reasons:
4747 * - No shader objects are attached to program."
4749 * The Compatibility Profile specification does not list the error. In
4750 * Compatibility Profile missing shader stages are replaced by
4751 * fixed-function. This applies to the case where all stages are
4754 if (prog
->NumShaders
== 0) {
4755 if (ctx
->API
!= API_OPENGL_COMPAT
)
4756 linker_error(prog
, "no shaders attached to the program\n");
4760 unsigned int num_explicit_uniform_locs
= 0;
4762 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
4764 prog
->ARB_fragment_coord_conventions_enable
= false;
4766 /* Separate the shaders into groups based on their type.
4768 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
4769 unsigned num_shaders
[MESA_SHADER_STAGES
];
4771 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4772 shader_list
[i
] = (struct gl_shader
**)
4773 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
4777 unsigned min_version
= UINT_MAX
;
4778 unsigned max_version
= 0;
4779 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
4780 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
4781 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
4783 if (prog
->Shaders
[i
]->IsES
!= prog
->Shaders
[0]->IsES
) {
4784 linker_error(prog
, "all shaders must use same shading "
4785 "language version\n");
4789 if (prog
->Shaders
[i
]->info
.ARB_fragment_coord_conventions_enable
) {
4790 prog
->ARB_fragment_coord_conventions_enable
= true;
4793 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
4794 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
4795 num_shaders
[shader_type
]++;
4798 /* In desktop GLSL, different shader versions may be linked together. In
4799 * GLSL ES, all shader versions must be the same.
4801 if (prog
->Shaders
[0]->IsES
&& min_version
!= max_version
) {
4802 linker_error(prog
, "all shaders must use same shading "
4803 "language version\n");
4807 prog
->Version
= max_version
;
4808 prog
->IsES
= prog
->Shaders
[0]->IsES
;
4810 /* Some shaders have to be linked with some other shaders present.
4812 if (!prog
->SeparateShader
) {
4813 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
4814 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4815 linker_error(prog
, "Geometry shader must be linked with "
4819 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4820 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4821 linker_error(prog
, "Tessellation evaluation shader must be linked "
4822 "with vertex shader\n");
4825 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4826 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4827 linker_error(prog
, "Tessellation control shader must be linked with "
4832 /* The spec is self-contradictory here. It allows linking without a tess
4833 * eval shader, but that can only be used with transform feedback and
4834 * rasterization disabled. However, transform feedback isn't allowed
4835 * with GL_PATCHES, so it can't be used.
4837 * More investigation showed that the idea of transform feedback after
4838 * a tess control shader was dropped, because some hw vendors couldn't
4839 * support tessellation without a tess eval shader, but the linker
4840 * section wasn't updated to reflect that.
4842 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4845 * Do what's reasonable and always require a tess eval shader if a tess
4846 * control shader is present.
4848 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4849 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0) {
4850 linker_error(prog
, "Tessellation control shader must be linked with "
4851 "tessellation evaluation shader\n");
4856 /* Compute shaders have additional restrictions. */
4857 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
4858 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
4859 linker_error(prog
, "Compute shaders may not be linked with any other "
4860 "type of shader\n");
4863 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4864 if (prog
->_LinkedShaders
[i
] != NULL
) {
4865 _mesa_delete_linked_shader(ctx
, prog
->_LinkedShaders
[i
]);
4868 prog
->_LinkedShaders
[i
] = NULL
;
4871 /* Link all shaders for a particular stage and validate the result.
4873 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4874 if (num_shaders
[stage
] > 0) {
4875 gl_linked_shader
*const sh
=
4876 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
4877 num_shaders
[stage
]);
4879 if (!prog
->LinkStatus
) {
4881 _mesa_delete_linked_shader(ctx
, sh
);
4886 case MESA_SHADER_VERTEX
:
4887 validate_vertex_shader_executable(prog
, sh
, ctx
);
4889 case MESA_SHADER_TESS_CTRL
:
4890 /* nothing to be done */
4892 case MESA_SHADER_TESS_EVAL
:
4893 validate_tess_eval_shader_executable(prog
, sh
, ctx
);
4895 case MESA_SHADER_GEOMETRY
:
4896 validate_geometry_shader_executable(prog
, sh
, ctx
);
4898 case MESA_SHADER_FRAGMENT
:
4899 validate_fragment_shader_executable(prog
, sh
);
4902 if (!prog
->LinkStatus
) {
4904 _mesa_delete_linked_shader(ctx
, sh
);
4908 prog
->_LinkedShaders
[stage
] = sh
;
4912 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0) {
4913 prog
->LastClipDistanceArraySize
= prog
->Geom
.ClipDistanceArraySize
;
4914 prog
->LastCullDistanceArraySize
= prog
->Geom
.CullDistanceArraySize
;
4915 } else if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0) {
4916 prog
->LastClipDistanceArraySize
= prog
->TessEval
.ClipDistanceArraySize
;
4917 prog
->LastCullDistanceArraySize
= prog
->TessEval
.CullDistanceArraySize
;
4918 } else if (num_shaders
[MESA_SHADER_VERTEX
] > 0) {
4919 prog
->LastClipDistanceArraySize
= prog
->Vert
.ClipDistanceArraySize
;
4920 prog
->LastCullDistanceArraySize
= prog
->Vert
.CullDistanceArraySize
;
4922 prog
->LastClipDistanceArraySize
= 0; /* Not used */
4923 prog
->LastCullDistanceArraySize
= 0; /* Not used */
4926 /* Here begins the inter-stage linking phase. Some initial validation is
4927 * performed, then locations are assigned for uniforms, attributes, and
4930 cross_validate_uniforms(prog
);
4931 if (!prog
->LinkStatus
)
4934 unsigned first
, last
, prev
;
4936 first
= MESA_SHADER_STAGES
;
4939 /* Determine first and last stage. */
4940 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4941 if (!prog
->_LinkedShaders
[i
])
4943 if (first
== MESA_SHADER_STAGES
)
4948 num_explicit_uniform_locs
= check_explicit_uniform_locations(ctx
, prog
);
4949 link_assign_subroutine_types(prog
);
4951 if (!prog
->LinkStatus
)
4954 resize_tes_inputs(ctx
, prog
);
4956 /* Validate the inputs of each stage with the output of the preceding
4960 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4961 if (prog
->_LinkedShaders
[i
] == NULL
)
4964 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
4965 prog
->_LinkedShaders
[i
]);
4966 if (!prog
->LinkStatus
)
4969 cross_validate_outputs_to_inputs(prog
,
4970 prog
->_LinkedShaders
[prev
],
4971 prog
->_LinkedShaders
[i
]);
4972 if (!prog
->LinkStatus
)
4978 /* Cross-validate uniform blocks between shader stages */
4979 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
);
4980 if (!prog
->LinkStatus
)
4983 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4984 if (prog
->_LinkedShaders
[i
] != NULL
)
4985 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
4988 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4989 * it before optimization because we want most of the checks to get
4990 * dropped thanks to constant propagation.
4992 * This rule also applies to GLSL ES 3.00.
4994 if (max_version
>= (prog
->IsES
? 300 : 130)) {
4995 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4997 lower_discard_flow(sh
->ir
);
5001 if (prog
->SeparateShader
)
5002 disable_varying_optimizations_for_sso(prog
);
5005 if (!interstage_cross_validate_uniform_blocks(prog
, false))
5009 if (!interstage_cross_validate_uniform_blocks(prog
, true))
5012 /* Do common optimization before assigning storage for attributes,
5013 * uniforms, and varyings. Later optimization could possibly make
5014 * some of that unused.
5016 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5017 if (prog
->_LinkedShaders
[i
] == NULL
)
5020 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
5021 if (!prog
->LinkStatus
)
5024 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerCombinedClipCullDistance
) {
5025 lower_clip_cull_distance(prog
, prog
->_LinkedShaders
[i
]);
5028 if (ctx
->Const
.LowerTessLevel
) {
5029 lower_tess_level(prog
->_LinkedShaders
[i
]);
5032 while (do_common_optimization(prog
->_LinkedShaders
[i
]->ir
, true, false,
5033 &ctx
->Const
.ShaderCompilerOptions
[i
],
5034 ctx
->Const
.NativeIntegers
))
5037 lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
);
5038 propagate_invariance(prog
->_LinkedShaders
[i
]->ir
);
5041 /* Validation for special cases where we allow sampler array indexing
5042 * with loop induction variable. This check emits a warning or error
5043 * depending if backend can handle dynamic indexing.
5045 if ((!prog
->IsES
&& prog
->Version
< 130) ||
5046 (prog
->IsES
&& prog
->Version
< 300)) {
5047 if (!validate_sampler_array_indexing(ctx
, prog
))
5051 /* Check and validate stream emissions in geometry shaders */
5052 validate_geometry_shader_emissions(ctx
, prog
);
5054 store_fragdepth_layout(prog
);
5056 if(!link_varyings_and_uniforms(first
, last
, num_explicit_uniform_locs
, ctx
,
5060 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
5061 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
5062 * anything about shader linking when one of the shaders (vertex or
5063 * fragment shader) is absent. So, the extension shouldn't change the
5064 * behavior specified in GLSL specification.
5066 * From OpenGL ES 3.1 specification (7.3 Program Objects):
5067 * "Linking can fail for a variety of reasons as specified in the
5068 * OpenGL ES Shading Language Specification, as well as any of the
5069 * following reasons:
5073 * * program contains objects to form either a vertex shader or
5074 * fragment shader, and program is not separable, and does not
5075 * contain objects to form both a vertex shader and fragment
5078 * However, the only scenario in 3.1+ where we don't require them both is
5079 * when we have a compute shader. For example:
5081 * - No shaders is a link error.
5082 * - Geom or Tess without a Vertex shader is a link error which means we
5083 * always require a Vertex shader and hence a Fragment shader.
5084 * - Finally a Compute shader linked with any other stage is a link error.
5086 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
&&
5087 num_shaders
[MESA_SHADER_COMPUTE
] == 0) {
5088 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
5089 linker_error(prog
, "program lacks a vertex shader\n");
5090 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
5091 linker_error(prog
, "program lacks a fragment shader\n");
5096 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5097 free(shader_list
[i
]);
5098 if (prog
->_LinkedShaders
[i
] == NULL
)
5101 /* Do a final validation step to make sure that the IR wasn't
5102 * invalidated by any modifications performed after intrastage linking.
5104 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
5106 /* Retain any live IR, but trash the rest. */
5107 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
5109 /* The symbol table in the linked shaders may contain references to
5110 * variables that were removed (e.g., unused uniforms). Since it may
5111 * contain junk, there is no possible valid use. Delete it and set the
5114 delete prog
->_LinkedShaders
[i
]->symbols
;
5115 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
5118 ralloc_free(mem_ctx
);