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 "glsl_symbol_table.h"
70 #include "glsl_parser_extras.h"
73 #include "program/prog_instruction.h"
74 #include "program/program.h"
75 #include "util/mesa-sha1.h"
77 #include "string_to_uint_map.h"
79 #include "linker_util.h"
80 #include "link_varyings.h"
81 #include "ir_optimization.h"
82 #include "ir_rvalue_visitor.h"
83 #include "ir_uniform.h"
84 #include "builtin_functions.h"
85 #include "shader_cache.h"
86 #include "util/u_string.h"
87 #include "util/u_math.h"
89 #include "main/imports.h"
90 #include "main/shaderobj.h"
91 #include "main/enums.h"
92 #include "main/mtypes.h"
97 struct find_variable
{
101 find_variable(const char *name
) : name(name
), found(false) {}
105 * Visitor that determines whether or not a variable is ever written.
107 * Use \ref find_assignments for convenience.
109 class find_assignment_visitor
: public ir_hierarchical_visitor
{
111 find_assignment_visitor(unsigned num_vars
,
112 find_variable
* const *vars
)
113 : num_variables(num_vars
), num_found(0), variables(vars
)
117 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
119 ir_variable
*const var
= ir
->lhs
->variable_referenced();
121 return check_variable_name(var
->name
);
124 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
126 foreach_two_lists(formal_node
, &ir
->callee
->parameters
,
127 actual_node
, &ir
->actual_parameters
) {
128 ir_rvalue
*param_rval
= (ir_rvalue
*) actual_node
;
129 ir_variable
*sig_param
= (ir_variable
*) formal_node
;
131 if (sig_param
->data
.mode
== ir_var_function_out
||
132 sig_param
->data
.mode
== ir_var_function_inout
) {
133 ir_variable
*var
= param_rval
->variable_referenced();
134 if (var
&& check_variable_name(var
->name
) == visit_stop
)
139 if (ir
->return_deref
!= NULL
) {
140 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
142 if (check_variable_name(var
->name
) == visit_stop
)
146 return visit_continue_with_parent
;
150 ir_visitor_status
check_variable_name(const char *name
)
152 for (unsigned i
= 0; i
< num_variables
; ++i
) {
153 if (strcmp(variables
[i
]->name
, name
) == 0) {
154 if (!variables
[i
]->found
) {
155 variables
[i
]->found
= true;
157 assert(num_found
< num_variables
);
158 if (++num_found
== num_variables
)
165 return visit_continue_with_parent
;
169 unsigned num_variables
; /**< Number of variables to find */
170 unsigned num_found
; /**< Number of variables already found */
171 find_variable
* const *variables
; /**< Variables to find */
175 * Determine whether or not any of NULL-terminated list of variables is ever
179 find_assignments(exec_list
*ir
, find_variable
* const *vars
)
181 unsigned num_variables
= 0;
183 for (find_variable
* const *v
= vars
; *v
; ++v
)
186 find_assignment_visitor
visitor(num_variables
, vars
);
191 * Determine whether or not the given variable is ever written to.
194 find_assignments(exec_list
*ir
, find_variable
*var
)
196 find_assignment_visitor
visitor(1, &var
);
201 * Visitor that determines whether or not a variable is ever read.
203 class find_deref_visitor
: public ir_hierarchical_visitor
{
205 find_deref_visitor(const char *name
)
206 : name(name
), found(false)
211 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
213 if (strcmp(this->name
, ir
->var
->name
) == 0) {
218 return visit_continue
;
221 bool variable_found() const
227 const char *name
; /**< Find writes to a variable with this name. */
228 bool found
; /**< Was a write to the variable found? */
233 * A visitor helper that provides methods for updating the types of
234 * ir_dereferences. Classes that update variable types (say, updating
235 * array sizes) will want to use this so that dereference types stay in sync.
237 class deref_type_updater
: public ir_hierarchical_visitor
{
239 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
241 ir
->type
= ir
->var
->type
;
242 return visit_continue
;
245 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
247 const glsl_type
*const vt
= ir
->array
->type
;
249 ir
->type
= vt
->fields
.array
;
250 return visit_continue
;
253 virtual ir_visitor_status
visit_leave(ir_dereference_record
*ir
)
255 ir
->type
= ir
->record
->type
->fields
.structure
[ir
->field_idx
].type
;
256 return visit_continue
;
261 class array_resize_visitor
: public deref_type_updater
{
263 unsigned num_vertices
;
264 gl_shader_program
*prog
;
265 gl_shader_stage stage
;
267 array_resize_visitor(unsigned num_vertices
,
268 gl_shader_program
*prog
,
269 gl_shader_stage stage
)
271 this->num_vertices
= num_vertices
;
276 virtual ~array_resize_visitor()
281 virtual ir_visitor_status
visit(ir_variable
*var
)
283 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
||
285 return visit_continue
;
287 unsigned size
= var
->type
->length
;
289 if (stage
== MESA_SHADER_GEOMETRY
) {
290 /* Generate a link error if the shader has declared this array with
293 if (!var
->data
.implicit_sized_array
&&
294 size
&& size
!= this->num_vertices
) {
295 linker_error(this->prog
, "size of array %s declared as %u, "
296 "but number of input vertices is %u\n",
297 var
->name
, size
, this->num_vertices
);
298 return visit_continue
;
301 /* Generate a link error if the shader attempts to access an input
302 * array using an index too large for its actual size assigned at
305 if (var
->data
.max_array_access
>= (int)this->num_vertices
) {
306 linker_error(this->prog
, "%s shader accesses element %i of "
307 "%s, but only %i input vertices\n",
308 _mesa_shader_stage_to_string(this->stage
),
309 var
->data
.max_array_access
, var
->name
, this->num_vertices
);
310 return visit_continue
;
314 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
316 var
->data
.max_array_access
= this->num_vertices
- 1;
318 return visit_continue
;
323 * Visitor that determines the highest stream id to which a (geometry) shader
324 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
326 class find_emit_vertex_visitor
: public ir_hierarchical_visitor
{
328 find_emit_vertex_visitor(int max_allowed
)
329 : max_stream_allowed(max_allowed
),
330 invalid_stream_id(0),
331 invalid_stream_id_from_emit_vertex(false),
332 end_primitive_found(false),
333 uses_non_zero_stream(false)
338 virtual ir_visitor_status
visit_leave(ir_emit_vertex
*ir
)
340 int stream_id
= ir
->stream_id();
343 invalid_stream_id
= stream_id
;
344 invalid_stream_id_from_emit_vertex
= true;
348 if (stream_id
> max_stream_allowed
) {
349 invalid_stream_id
= stream_id
;
350 invalid_stream_id_from_emit_vertex
= true;
355 uses_non_zero_stream
= true;
357 return visit_continue
;
360 virtual ir_visitor_status
visit_leave(ir_end_primitive
*ir
)
362 end_primitive_found
= true;
364 int stream_id
= ir
->stream_id();
367 invalid_stream_id
= stream_id
;
368 invalid_stream_id_from_emit_vertex
= false;
372 if (stream_id
> max_stream_allowed
) {
373 invalid_stream_id
= stream_id
;
374 invalid_stream_id_from_emit_vertex
= false;
379 uses_non_zero_stream
= true;
381 return visit_continue
;
386 return invalid_stream_id
!= 0;
389 const char *error_func()
391 return invalid_stream_id_from_emit_vertex
?
392 "EmitStreamVertex" : "EndStreamPrimitive";
397 return invalid_stream_id
;
402 return uses_non_zero_stream
;
405 bool uses_end_primitive()
407 return end_primitive_found
;
411 int max_stream_allowed
;
412 int invalid_stream_id
;
413 bool invalid_stream_id_from_emit_vertex
;
414 bool end_primitive_found
;
415 bool uses_non_zero_stream
;
418 /* Class that finds array derefs and check if indexes are dynamic. */
419 class dynamic_sampler_array_indexing_visitor
: public ir_hierarchical_visitor
422 dynamic_sampler_array_indexing_visitor() :
423 dynamic_sampler_array_indexing(false)
427 ir_visitor_status
visit_enter(ir_dereference_array
*ir
)
429 if (!ir
->variable_referenced())
430 return visit_continue
;
432 if (!ir
->variable_referenced()->type
->contains_sampler())
433 return visit_continue
;
435 if (!ir
->array_index
->constant_expression_value(ralloc_parent(ir
))) {
436 dynamic_sampler_array_indexing
= true;
439 return visit_continue
;
442 bool uses_dynamic_sampler_array_indexing()
444 return dynamic_sampler_array_indexing
;
448 bool dynamic_sampler_array_indexing
;
451 } /* anonymous namespace */
454 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
458 ralloc_strcat(&prog
->data
->InfoLog
, "error: ");
460 ralloc_vasprintf_append(&prog
->data
->InfoLog
, fmt
, ap
);
463 prog
->data
->LinkStatus
= LINKING_FAILURE
;
468 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
472 ralloc_strcat(&prog
->data
->InfoLog
, "warning: ");
474 ralloc_vasprintf_append(&prog
->data
->InfoLog
, fmt
, ap
);
481 * Given a string identifying a program resource, break it into a base name
482 * and an optional array index in square brackets.
484 * If an array index is present, \c out_base_name_end is set to point to the
485 * "[" that precedes the array index, and the array index itself is returned
488 * If no array index is present (or if the array index is negative or
489 * mal-formed), \c out_base_name_end, is set to point to the null terminator
490 * at the end of the input string, and -1 is returned.
492 * Only the final array index is parsed; if the string contains other array
493 * indices (or structure field accesses), they are left in the base name.
495 * No attempt is made to check that the base name is properly formed;
496 * typically the caller will look up the base name in a hash table, so
497 * ill-formed base names simply turn into hash table lookup failures.
500 parse_program_resource_name(const GLchar
*name
,
501 const GLchar
**out_base_name_end
)
503 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
505 * "When an integer array element or block instance number is part of
506 * the name string, it will be specified in decimal form without a "+"
507 * or "-" sign or any extra leading zeroes. Additionally, the name
508 * string will not include white space anywhere in the string."
511 const size_t len
= strlen(name
);
512 *out_base_name_end
= name
+ len
;
514 if (len
== 0 || name
[len
-1] != ']')
517 /* Walk backwards over the string looking for a non-digit character. This
518 * had better be the opening bracket for an array index.
520 * Initially, i specifies the location of the ']'. Since the string may
521 * contain only the ']' charcater, walk backwards very carefully.
524 for (i
= len
- 1; (i
> 0) && isdigit(name
[i
-1]); --i
)
527 if ((i
== 0) || name
[i
-1] != '[')
530 long array_index
= strtol(&name
[i
], NULL
, 10);
534 /* Check for leading zero */
535 if (name
[i
] == '0' && name
[i
+1] != ']')
538 *out_base_name_end
= name
+ (i
- 1);
544 link_invalidate_variable_locations(exec_list
*ir
)
546 foreach_in_list(ir_instruction
, node
, ir
) {
547 ir_variable
*const var
= node
->as_variable();
552 /* Only assign locations for variables that lack an explicit location.
553 * Explicit locations are set for all built-in variables, generic vertex
554 * shader inputs (via layout(location=...)), and generic fragment shader
555 * outputs (also via layout(location=...)).
557 if (!var
->data
.explicit_location
) {
558 var
->data
.location
= -1;
559 var
->data
.location_frac
= 0;
562 /* ir_variable::is_unmatched_generic_inout is used by the linker while
563 * connecting outputs from one stage to inputs of the next stage.
565 if (var
->data
.explicit_location
&&
566 var
->data
.location
< VARYING_SLOT_VAR0
) {
567 var
->data
.is_unmatched_generic_inout
= 0;
569 var
->data
.is_unmatched_generic_inout
= 1;
576 * Set clip_distance_array_size based and cull_distance_array_size on the given
579 * Also check for errors based on incorrect usage of gl_ClipVertex and
580 * gl_ClipDistance and gl_CullDistance.
581 * Additionally test whether the arrays gl_ClipDistance and gl_CullDistance
582 * exceed the maximum size defined by gl_MaxCombinedClipAndCullDistances.
584 * Return false if an error was reported.
587 analyze_clip_cull_usage(struct gl_shader_program
*prog
,
588 struct gl_linked_shader
*shader
,
589 struct gl_context
*ctx
,
590 struct shader_info
*info
)
592 info
->clip_distance_array_size
= 0;
593 info
->cull_distance_array_size
= 0;
595 if (prog
->data
->Version
>= (prog
->IsES
? 300 : 130)) {
596 /* From section 7.1 (Vertex Shader Special Variables) of the
599 * "It is an error for a shader to statically write both
600 * gl_ClipVertex and gl_ClipDistance."
602 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
603 * gl_ClipVertex nor gl_ClipDistance. However with
604 * GL_EXT_clip_cull_distance, this functionality is exposed in ES 3.0.
606 find_variable
gl_ClipDistance("gl_ClipDistance");
607 find_variable
gl_CullDistance("gl_CullDistance");
608 find_variable
gl_ClipVertex("gl_ClipVertex");
609 find_variable
* const variables
[] = {
612 !prog
->IsES
? &gl_ClipVertex
: NULL
,
615 find_assignments(shader
->ir
, variables
);
617 /* From the ARB_cull_distance spec:
619 * It is a compile-time or link-time error for the set of shaders forming
620 * a program to statically read or write both gl_ClipVertex and either
621 * gl_ClipDistance or gl_CullDistance.
623 * This does not apply to GLSL ES shaders, since GLSL ES doesn't define
627 if (gl_ClipVertex
.found
&& gl_ClipDistance
.found
) {
628 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
629 "and `gl_ClipDistance'\n",
630 _mesa_shader_stage_to_string(shader
->Stage
));
633 if (gl_ClipVertex
.found
&& gl_CullDistance
.found
) {
634 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
635 "and `gl_CullDistance'\n",
636 _mesa_shader_stage_to_string(shader
->Stage
));
641 if (gl_ClipDistance
.found
) {
642 ir_variable
*clip_distance_var
=
643 shader
->symbols
->get_variable("gl_ClipDistance");
644 assert(clip_distance_var
);
645 info
->clip_distance_array_size
= clip_distance_var
->type
->length
;
647 if (gl_CullDistance
.found
) {
648 ir_variable
*cull_distance_var
=
649 shader
->symbols
->get_variable("gl_CullDistance");
650 assert(cull_distance_var
);
651 info
->cull_distance_array_size
= cull_distance_var
->type
->length
;
653 /* From the ARB_cull_distance spec:
655 * It is a compile-time or link-time error for the set of shaders forming
656 * a program to have the sum of the sizes of the gl_ClipDistance and
657 * gl_CullDistance arrays to be larger than
658 * gl_MaxCombinedClipAndCullDistances.
660 if ((uint32_t)(info
->clip_distance_array_size
+ info
->cull_distance_array_size
) >
661 ctx
->Const
.MaxClipPlanes
) {
662 linker_error(prog
, "%s shader: the combined size of "
663 "'gl_ClipDistance' and 'gl_CullDistance' size cannot "
665 "gl_MaxCombinedClipAndCullDistances (%u)",
666 _mesa_shader_stage_to_string(shader
->Stage
),
667 ctx
->Const
.MaxClipPlanes
);
674 * Verify that a vertex shader executable meets all semantic requirements.
676 * Also sets info.clip_distance_array_size and
677 * info.cull_distance_array_size as a side effect.
679 * \param shader Vertex shader executable to be verified
682 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
683 struct gl_linked_shader
*shader
,
684 struct gl_context
*ctx
)
689 /* From the GLSL 1.10 spec, page 48:
691 * "The variable gl_Position is available only in the vertex
692 * language and is intended for writing the homogeneous vertex
693 * position. All executions of a well-formed vertex shader
694 * executable must write a value into this variable. [...] The
695 * variable gl_Position is available only in the vertex
696 * language and is intended for writing the homogeneous vertex
697 * position. All executions of a well-formed vertex shader
698 * executable must write a value into this variable."
700 * while in GLSL 1.40 this text is changed to:
702 * "The variable gl_Position is available only in the vertex
703 * language and is intended for writing the homogeneous vertex
704 * position. It can be written at any time during shader
705 * execution. It may also be read back by a vertex shader
706 * after being written. This value will be used by primitive
707 * assembly, clipping, culling, and other fixed functionality
708 * operations, if present, that operate on primitives after
709 * vertex processing has occurred. Its value is undefined if
710 * the vertex shader executable does not write gl_Position."
712 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
713 * gl_Position is not an error.
715 if (prog
->data
->Version
< (prog
->IsES
? 300 : 140)) {
716 find_variable
gl_Position("gl_Position");
717 find_assignments(shader
->ir
, &gl_Position
);
718 if (!gl_Position
.found
) {
721 "vertex shader does not write to `gl_Position'. "
722 "Its value is undefined. \n");
725 "vertex shader does not write to `gl_Position'. \n");
731 analyze_clip_cull_usage(prog
, shader
, ctx
, &shader
->Program
->info
);
735 validate_tess_eval_shader_executable(struct gl_shader_program
*prog
,
736 struct gl_linked_shader
*shader
,
737 struct gl_context
*ctx
)
742 analyze_clip_cull_usage(prog
, shader
, ctx
, &shader
->Program
->info
);
747 * Verify that a fragment shader executable meets all semantic requirements
749 * \param shader Fragment shader executable to be verified
752 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
753 struct gl_linked_shader
*shader
)
758 find_variable
gl_FragColor("gl_FragColor");
759 find_variable
gl_FragData("gl_FragData");
760 find_variable
* const variables
[] = { &gl_FragColor
, &gl_FragData
, NULL
};
761 find_assignments(shader
->ir
, variables
);
763 if (gl_FragColor
.found
&& gl_FragData
.found
) {
764 linker_error(prog
, "fragment shader writes to both "
765 "`gl_FragColor' and `gl_FragData'\n");
770 * Verify that a geometry shader executable meets all semantic requirements
772 * Also sets prog->Geom.VerticesIn, and info.clip_distance_array_sizeand
773 * info.cull_distance_array_size as a side effect.
775 * \param shader Geometry shader executable to be verified
778 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
779 struct gl_linked_shader
*shader
,
780 struct gl_context
*ctx
)
785 unsigned num_vertices
=
786 vertices_per_prim(shader
->Program
->info
.gs
.input_primitive
);
787 prog
->Geom
.VerticesIn
= num_vertices
;
789 analyze_clip_cull_usage(prog
, shader
, ctx
, &shader
->Program
->info
);
793 * Check if geometry shaders emit to non-zero streams and do corresponding
797 validate_geometry_shader_emissions(struct gl_context
*ctx
,
798 struct gl_shader_program
*prog
)
800 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
];
803 find_emit_vertex_visitor
emit_vertex(ctx
->Const
.MaxVertexStreams
- 1);
804 emit_vertex
.run(sh
->ir
);
805 if (emit_vertex
.error()) {
806 linker_error(prog
, "Invalid call %s(%d). Accepted values for the "
807 "stream parameter are in the range [0, %d].\n",
808 emit_vertex
.error_func(),
809 emit_vertex
.error_stream(),
810 ctx
->Const
.MaxVertexStreams
- 1);
812 prog
->Geom
.UsesStreams
= emit_vertex
.uses_streams();
813 prog
->Geom
.UsesEndPrimitive
= emit_vertex
.uses_end_primitive();
815 /* From the ARB_gpu_shader5 spec:
817 * "Multiple vertex streams are supported only if the output primitive
818 * type is declared to be "points". A program will fail to link if it
819 * contains a geometry shader calling EmitStreamVertex() or
820 * EndStreamPrimitive() if its output primitive type is not "points".
822 * However, in the same spec:
824 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
825 * with <stream> set to zero."
829 * "The function EndPrimitive() is equivalent to calling
830 * EndStreamPrimitive() with <stream> set to zero."
832 * Since we can call EmitVertex() and EndPrimitive() when we output
833 * primitives other than points, calling EmitStreamVertex(0) or
834 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
835 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
836 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
839 if (prog
->Geom
.UsesStreams
&&
840 sh
->Program
->info
.gs
.output_primitive
!= GL_POINTS
) {
841 linker_error(prog
, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
842 "with n>0 requires point output\n");
848 validate_intrastage_arrays(struct gl_shader_program
*prog
,
849 ir_variable
*const var
,
850 ir_variable
*const existing
,
851 bool match_precision
)
853 /* Consider the types to be "the same" if both types are arrays
854 * of the same type and one of the arrays is implicitly sized.
855 * In addition, set the type of the linked variable to the
856 * explicitly sized array.
858 if (var
->type
->is_array() && existing
->type
->is_array()) {
859 const glsl_type
*no_array_var
= var
->type
->fields
.array
;
860 const glsl_type
*no_array_existing
= existing
->type
->fields
.array
;
863 type_matches
= (match_precision
?
864 no_array_var
== no_array_existing
:
865 no_array_var
->compare_no_precision(no_array_existing
));
868 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
869 if (var
->type
->length
!= 0) {
870 if ((int)var
->type
->length
<= existing
->data
.max_array_access
) {
871 linker_error(prog
, "%s `%s' declared as type "
872 "`%s' but outermost dimension has an index"
875 var
->name
, var
->type
->name
,
876 existing
->data
.max_array_access
);
878 existing
->type
= var
->type
;
880 } else if (existing
->type
->length
!= 0) {
881 if((int)existing
->type
->length
<= var
->data
.max_array_access
&&
882 !existing
->data
.from_ssbo_unsized_array
) {
883 linker_error(prog
, "%s `%s' declared as type "
884 "`%s' but outermost dimension has an index"
887 var
->name
, existing
->type
->name
,
888 var
->data
.max_array_access
);
899 * Perform validation of global variables used across multiple shaders
902 cross_validate_globals(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
903 struct exec_list
*ir
, glsl_symbol_table
*variables
,
906 foreach_in_list(ir_instruction
, node
, ir
) {
907 ir_variable
*const var
= node
->as_variable();
912 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
915 /* don't cross validate subroutine uniforms */
916 if (var
->type
->contains_subroutine())
919 /* Don't cross validate interface instances. These are only relevant
920 * inside a shader. The cross validation is done at the Interface Block
923 if (var
->is_interface_instance())
926 /* Don't cross validate temporaries that are at global scope. These
927 * will eventually get pulled into the shaders 'main'.
929 if (var
->data
.mode
== ir_var_temporary
)
932 /* If a global with this name has already been seen, verify that the
933 * new instance has the same type. In addition, if the globals have
934 * initializers, the values of the initializers must be the same.
936 ir_variable
*const existing
= variables
->get_variable(var
->name
);
937 if (existing
!= NULL
) {
938 /* Check if types match. */
939 if (var
->type
!= existing
->type
) {
940 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
941 /* If it is an unsized array in a Shader Storage Block,
942 * two different shaders can access to different elements.
943 * Because of that, they might be converted to different
944 * sized arrays, then check that they are compatible but
945 * ignore the array size.
947 if (!(var
->data
.mode
== ir_var_shader_storage
&&
948 var
->data
.from_ssbo_unsized_array
&&
949 existing
->data
.mode
== ir_var_shader_storage
&&
950 existing
->data
.from_ssbo_unsized_array
&&
951 var
->type
->gl_type
== existing
->type
->gl_type
)) {
952 linker_error(prog
, "%s `%s' declared as type "
953 "`%s' and type `%s'\n",
955 var
->name
, var
->type
->name
,
956 existing
->type
->name
);
962 if (var
->data
.explicit_location
) {
963 if (existing
->data
.explicit_location
964 && (var
->data
.location
!= existing
->data
.location
)) {
965 linker_error(prog
, "explicit locations for %s "
966 "`%s' have differing values\n",
967 mode_string(var
), var
->name
);
971 if (var
->data
.location_frac
!= existing
->data
.location_frac
) {
972 linker_error(prog
, "explicit components for %s `%s' have "
973 "differing values\n", mode_string(var
), var
->name
);
977 existing
->data
.location
= var
->data
.location
;
978 existing
->data
.explicit_location
= true;
980 /* Check if uniform with implicit location was marked explicit
981 * by earlier shader stage. If so, mark it explicit in this stage
982 * too to make sure later processing does not treat it as
985 if (existing
->data
.explicit_location
) {
986 var
->data
.location
= existing
->data
.location
;
987 var
->data
.explicit_location
= true;
991 /* From the GLSL 4.20 specification:
992 * "A link error will result if two compilation units in a program
993 * specify different integer-constant bindings for the same
994 * opaque-uniform name. However, it is not an error to specify a
995 * binding on some but not all declarations for the same name"
997 if (var
->data
.explicit_binding
) {
998 if (existing
->data
.explicit_binding
&&
999 var
->data
.binding
!= existing
->data
.binding
) {
1000 linker_error(prog
, "explicit bindings for %s "
1001 "`%s' have differing values\n",
1002 mode_string(var
), var
->name
);
1006 existing
->data
.binding
= var
->data
.binding
;
1007 existing
->data
.explicit_binding
= true;
1010 if (var
->type
->contains_atomic() &&
1011 var
->data
.offset
!= existing
->data
.offset
) {
1012 linker_error(prog
, "offset specifications for %s "
1013 "`%s' have differing values\n",
1014 mode_string(var
), var
->name
);
1018 /* Validate layout qualifiers for gl_FragDepth.
1020 * From the AMD/ARB_conservative_depth specs:
1022 * "If gl_FragDepth is redeclared in any fragment shader in a
1023 * program, it must be redeclared in all fragment shaders in
1024 * that program that have static assignments to
1025 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1026 * fragment shaders in a single program must have the same set
1029 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1030 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1031 bool layout_differs
=
1032 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1034 if (layout_declared
&& layout_differs
) {
1036 "All redeclarations of gl_FragDepth in all "
1037 "fragment shaders in a single program must have "
1038 "the same set of qualifiers.\n");
1041 if (var
->data
.used
&& layout_differs
) {
1043 "If gl_FragDepth is redeclared with a layout "
1044 "qualifier in any fragment shader, it must be "
1045 "redeclared with the same layout qualifier in "
1046 "all fragment shaders that have assignments to "
1051 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1053 * "If a shared global has multiple initializers, the
1054 * initializers must all be constant expressions, and they
1055 * must all have the same value. Otherwise, a link error will
1056 * result. (A shared global having only one initializer does
1057 * not require that initializer to be a constant expression.)"
1059 * Previous to 4.20 the GLSL spec simply said that initializers
1060 * must have the same value. In this case of non-constant
1061 * initializers, this was impossible to determine. As a result,
1062 * no vendor actually implemented that behavior. The 4.20
1063 * behavior matches the implemented behavior of at least one other
1064 * vendor, so we'll implement that for all GLSL versions.
1066 if (var
->constant_initializer
!= NULL
) {
1067 if (existing
->constant_initializer
!= NULL
) {
1068 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1069 linker_error(prog
, "initializers for %s "
1070 "`%s' have differing values\n",
1071 mode_string(var
), var
->name
);
1075 /* If the first-seen instance of a particular uniform did
1076 * not have an initializer but a later instance does,
1077 * replace the former with the later.
1079 variables
->replace_variable(existing
->name
, var
);
1083 if (var
->data
.has_initializer
) {
1084 if (existing
->data
.has_initializer
1085 && (var
->constant_initializer
== NULL
1086 || existing
->constant_initializer
== NULL
)) {
1088 "shared global variable `%s' has multiple "
1089 "non-constant initializers.\n",
1095 if (existing
->data
.explicit_invariant
!= var
->data
.explicit_invariant
) {
1096 linker_error(prog
, "declarations for %s `%s' have "
1097 "mismatching invariant qualifiers\n",
1098 mode_string(var
), var
->name
);
1101 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1102 linker_error(prog
, "declarations for %s `%s' have "
1103 "mismatching centroid qualifiers\n",
1104 mode_string(var
), var
->name
);
1107 if (existing
->data
.sample
!= var
->data
.sample
) {
1108 linker_error(prog
, "declarations for %s `%s` have "
1109 "mismatching sample qualifiers\n",
1110 mode_string(var
), var
->name
);
1113 if (existing
->data
.image_format
!= var
->data
.image_format
) {
1114 linker_error(prog
, "declarations for %s `%s` have "
1115 "mismatching image format qualifiers\n",
1116 mode_string(var
), var
->name
);
1120 /* Check the precision qualifier matches for uniform variables on
1123 if (!ctx
->Const
.AllowGLSLRelaxedES
&&
1124 prog
->IsES
&& !var
->get_interface_type() &&
1125 existing
->data
.precision
!= var
->data
.precision
) {
1126 if ((existing
->data
.used
&& var
->data
.used
) || prog
->data
->Version
>= 300) {
1127 linker_error(prog
, "declarations for %s `%s` have "
1128 "mismatching precision qualifiers\n",
1129 mode_string(var
), var
->name
);
1132 linker_warning(prog
, "declarations for %s `%s` have "
1133 "mismatching precision qualifiers\n",
1134 mode_string(var
), var
->name
);
1138 /* In OpenGL GLSL 3.20 spec, section 4.3.9:
1140 * "It is a link-time error if any particular shader interface
1143 * - two different blocks, each having no instance name, and each
1144 * having a member of the same name, or
1146 * - a variable outside a block, and a block with no instance name,
1147 * where the variable has the same name as a member in the block."
1149 const glsl_type
*var_itype
= var
->get_interface_type();
1150 const glsl_type
*existing_itype
= existing
->get_interface_type();
1151 if (var_itype
!= existing_itype
) {
1152 if (!var_itype
|| !existing_itype
) {
1153 linker_error(prog
, "declarations for %s `%s` are inside block "
1154 "`%s` and outside a block",
1155 mode_string(var
), var
->name
,
1156 var_itype
? var_itype
->name
: existing_itype
->name
);
1158 } else if (strcmp(var_itype
->name
, existing_itype
->name
) != 0) {
1159 linker_error(prog
, "declarations for %s `%s` are inside blocks "
1161 mode_string(var
), var
->name
,
1162 existing_itype
->name
,
1168 variables
->add_variable(var
);
1174 * Perform validation of uniforms used across multiple shader stages
1177 cross_validate_uniforms(struct gl_context
*ctx
,
1178 struct gl_shader_program
*prog
)
1180 glsl_symbol_table variables
;
1181 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1182 if (prog
->_LinkedShaders
[i
] == NULL
)
1185 cross_validate_globals(ctx
, prog
, prog
->_LinkedShaders
[i
]->ir
,
1191 * Accumulates the array of buffer blocks and checks that all definitions of
1192 * blocks agree on their contents.
1195 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
,
1198 int *InterfaceBlockStageIndex
[MESA_SHADER_STAGES
];
1199 struct gl_uniform_block
*blks
= NULL
;
1200 unsigned *num_blks
= validate_ssbo
? &prog
->data
->NumShaderStorageBlocks
:
1201 &prog
->data
->NumUniformBlocks
;
1203 unsigned max_num_buffer_blocks
= 0;
1204 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1205 if (prog
->_LinkedShaders
[i
]) {
1206 if (validate_ssbo
) {
1207 max_num_buffer_blocks
+=
1208 prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1210 max_num_buffer_blocks
+=
1211 prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1216 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1217 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1219 InterfaceBlockStageIndex
[i
] = new int[max_num_buffer_blocks
];
1220 for (unsigned int j
= 0; j
< max_num_buffer_blocks
; j
++)
1221 InterfaceBlockStageIndex
[i
][j
] = -1;
1226 unsigned sh_num_blocks
;
1227 struct gl_uniform_block
**sh_blks
;
1228 if (validate_ssbo
) {
1229 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1230 sh_blks
= sh
->Program
->sh
.ShaderStorageBlocks
;
1232 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1233 sh_blks
= sh
->Program
->sh
.UniformBlocks
;
1236 for (unsigned int j
= 0; j
< sh_num_blocks
; j
++) {
1237 int index
= link_cross_validate_uniform_block(prog
->data
, &blks
,
1238 num_blks
, sh_blks
[j
]);
1241 linker_error(prog
, "buffer block `%s' has mismatching "
1242 "definitions\n", sh_blks
[j
]->Name
);
1244 for (unsigned k
= 0; k
<= i
; k
++) {
1245 delete[] InterfaceBlockStageIndex
[k
];
1248 /* Reset the block count. This will help avoid various segfaults
1249 * from api calls that assume the array exists due to the count
1256 InterfaceBlockStageIndex
[i
][index
] = j
;
1260 /* Update per stage block pointers to point to the program list.
1261 * FIXME: We should be able to free the per stage blocks here.
1263 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1264 for (unsigned j
= 0; j
< *num_blks
; j
++) {
1265 int stage_index
= InterfaceBlockStageIndex
[i
][j
];
1267 if (stage_index
!= -1) {
1268 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1270 struct gl_uniform_block
**sh_blks
= validate_ssbo
?
1271 sh
->Program
->sh
.ShaderStorageBlocks
:
1272 sh
->Program
->sh
.UniformBlocks
;
1274 blks
[j
].stageref
|= sh_blks
[stage_index
]->stageref
;
1275 sh_blks
[stage_index
] = &blks
[j
];
1280 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1281 delete[] InterfaceBlockStageIndex
[i
];
1285 prog
->data
->ShaderStorageBlocks
= blks
;
1287 prog
->data
->UniformBlocks
= blks
;
1293 * Verifies the invariance of built-in special variables.
1296 validate_invariant_builtins(struct gl_shader_program
*prog
,
1297 const gl_linked_shader
*vert
,
1298 const gl_linked_shader
*frag
)
1300 const ir_variable
*var_vert
;
1301 const ir_variable
*var_frag
;
1307 * From OpenGL ES Shading Language 1.0 specification
1308 * (4.6.4 Invariance and Linkage):
1309 * "The invariance of varyings that are declared in both the vertex and
1310 * fragment shaders must match. For the built-in special variables,
1311 * gl_FragCoord can only be declared invariant if and only if
1312 * gl_Position is declared invariant. Similarly gl_PointCoord can only
1313 * be declared invariant if and only if gl_PointSize is declared
1314 * invariant. It is an error to declare gl_FrontFacing as invariant.
1315 * The invariance of gl_FrontFacing is the same as the invariance of
1318 var_frag
= frag
->symbols
->get_variable("gl_FragCoord");
1319 if (var_frag
&& var_frag
->data
.invariant
) {
1320 var_vert
= vert
->symbols
->get_variable("gl_Position");
1321 if (var_vert
&& !var_vert
->data
.invariant
) {
1323 "fragment shader built-in `%s' has invariant qualifier, "
1324 "but vertex shader built-in `%s' lacks invariant qualifier\n",
1325 var_frag
->name
, var_vert
->name
);
1330 var_frag
= frag
->symbols
->get_variable("gl_PointCoord");
1331 if (var_frag
&& var_frag
->data
.invariant
) {
1332 var_vert
= vert
->symbols
->get_variable("gl_PointSize");
1333 if (var_vert
&& !var_vert
->data
.invariant
) {
1335 "fragment shader built-in `%s' has invariant qualifier, "
1336 "but vertex shader built-in `%s' lacks invariant qualifier\n",
1337 var_frag
->name
, var_vert
->name
);
1342 var_frag
= frag
->symbols
->get_variable("gl_FrontFacing");
1343 if (var_frag
&& var_frag
->data
.invariant
) {
1345 "fragment shader built-in `%s' can not be declared as invariant\n",
1354 * Populates a shaders symbol table with all global declarations
1357 populate_symbol_table(gl_linked_shader
*sh
, glsl_symbol_table
*symbols
)
1359 sh
->symbols
= new(sh
) glsl_symbol_table
;
1361 _mesa_glsl_copy_symbols_from_table(sh
->ir
, symbols
, sh
->symbols
);
1366 * Remap variables referenced in an instruction tree
1368 * This is used when instruction trees are cloned from one shader and placed in
1369 * another. These trees will contain references to \c ir_variable nodes that
1370 * do not exist in the target shader. This function finds these \c ir_variable
1371 * references and replaces the references with matching variables in the target
1374 * If there is no matching variable in the target shader, a clone of the
1375 * \c ir_variable is made and added to the target shader. The new variable is
1376 * added to \b both the instruction stream and the symbol table.
1378 * \param inst IR tree that is to be processed.
1379 * \param symbols Symbol table containing global scope symbols in the
1381 * \param instructions Instruction stream where new variable declarations
1385 remap_variables(ir_instruction
*inst
, struct gl_linked_shader
*target
,
1388 class remap_visitor
: public ir_hierarchical_visitor
{
1390 remap_visitor(struct gl_linked_shader
*target
, hash_table
*temps
)
1392 this->target
= target
;
1393 this->symbols
= target
->symbols
;
1394 this->instructions
= target
->ir
;
1395 this->temps
= temps
;
1398 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1400 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1401 hash_entry
*entry
= _mesa_hash_table_search(temps
, ir
->var
);
1402 ir_variable
*var
= entry
? (ir_variable
*) entry
->data
: NULL
;
1404 assert(var
!= NULL
);
1406 return visit_continue
;
1409 ir_variable
*const existing
=
1410 this->symbols
->get_variable(ir
->var
->name
);
1411 if (existing
!= NULL
)
1414 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1416 this->symbols
->add_variable(copy
);
1417 this->instructions
->push_head(copy
);
1421 return visit_continue
;
1425 struct gl_linked_shader
*target
;
1426 glsl_symbol_table
*symbols
;
1427 exec_list
*instructions
;
1431 remap_visitor
v(target
, temps
);
1438 * Move non-declarations from one instruction stream to another
1440 * The intended usage pattern of this function is to pass the pointer to the
1441 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1442 * pointer) for \c last and \c false for \c make_copies on the first
1443 * call. Successive calls pass the return value of the previous call for
1444 * \c last and \c true for \c make_copies.
1446 * \param instructions Source instruction stream
1447 * \param last Instruction after which new instructions should be
1448 * inserted in the target instruction stream
1449 * \param make_copies Flag selecting whether instructions in \c instructions
1450 * should be copied (via \c ir_instruction::clone) into the
1451 * target list or moved.
1454 * The new "last" instruction in the target instruction stream. This pointer
1455 * is suitable for use as the \c last parameter of a later call to this
1459 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1460 bool make_copies
, gl_linked_shader
*target
)
1462 hash_table
*temps
= NULL
;
1465 temps
= _mesa_pointer_hash_table_create(NULL
);
1467 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1468 if (inst
->as_function())
1471 ir_variable
*var
= inst
->as_variable();
1472 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1475 assert(inst
->as_assignment()
1477 || inst
->as_if() /* for initializers with the ?: operator */
1478 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1481 inst
= inst
->clone(target
, NULL
);
1484 _mesa_hash_table_insert(temps
, var
, inst
);
1486 remap_variables(inst
, target
, temps
);
1491 last
->insert_after(inst
);
1496 _mesa_hash_table_destroy(temps
, NULL
);
1503 * This class is only used in link_intrastage_shaders() below but declaring
1504 * it inside that function leads to compiler warnings with some versions of
1507 class array_sizing_visitor
: public deref_type_updater
{
1509 array_sizing_visitor()
1510 : mem_ctx(ralloc_context(NULL
)),
1511 unnamed_interfaces(_mesa_pointer_hash_table_create(NULL
))
1515 ~array_sizing_visitor()
1517 _mesa_hash_table_destroy(this->unnamed_interfaces
, NULL
);
1518 ralloc_free(this->mem_ctx
);
1521 virtual ir_visitor_status
visit(ir_variable
*var
)
1523 const glsl_type
*type_without_array
;
1524 bool implicit_sized_array
= var
->data
.implicit_sized_array
;
1525 fixup_type(&var
->type
, var
->data
.max_array_access
,
1526 var
->data
.from_ssbo_unsized_array
,
1527 &implicit_sized_array
);
1528 var
->data
.implicit_sized_array
= implicit_sized_array
;
1529 type_without_array
= var
->type
->without_array();
1530 if (var
->type
->is_interface()) {
1531 if (interface_contains_unsized_arrays(var
->type
)) {
1532 const glsl_type
*new_type
=
1533 resize_interface_members(var
->type
,
1534 var
->get_max_ifc_array_access(),
1535 var
->is_in_shader_storage_block());
1536 var
->type
= new_type
;
1537 var
->change_interface_type(new_type
);
1539 } else if (type_without_array
->is_interface()) {
1540 if (interface_contains_unsized_arrays(type_without_array
)) {
1541 const glsl_type
*new_type
=
1542 resize_interface_members(type_without_array
,
1543 var
->get_max_ifc_array_access(),
1544 var
->is_in_shader_storage_block());
1545 var
->change_interface_type(new_type
);
1546 var
->type
= update_interface_members_array(var
->type
, new_type
);
1548 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1549 /* Store a pointer to the variable in the unnamed_interfaces
1553 _mesa_hash_table_search(this->unnamed_interfaces
,
1556 ir_variable
**interface_vars
= entry
? (ir_variable
**) entry
->data
: NULL
;
1558 if (interface_vars
== NULL
) {
1559 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1561 _mesa_hash_table_insert(this->unnamed_interfaces
, ifc_type
,
1564 unsigned index
= ifc_type
->field_index(var
->name
);
1565 assert(index
< ifc_type
->length
);
1566 assert(interface_vars
[index
] == NULL
);
1567 interface_vars
[index
] = var
;
1569 return visit_continue
;
1573 * For each unnamed interface block that was discovered while running the
1574 * visitor, adjust the interface type to reflect the newly assigned array
1575 * sizes, and fix up the ir_variable nodes to point to the new interface
1578 void fixup_unnamed_interface_types()
1580 hash_table_call_foreach(this->unnamed_interfaces
,
1581 fixup_unnamed_interface_type
, NULL
);
1586 * If the type pointed to by \c type represents an unsized array, replace
1587 * it with a sized array whose size is determined by max_array_access.
1589 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1590 bool from_ssbo_unsized_array
, bool *implicit_sized
)
1592 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1593 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1594 max_array_access
+ 1);
1595 *implicit_sized
= true;
1596 assert(*type
!= NULL
);
1600 static const glsl_type
*
1601 update_interface_members_array(const glsl_type
*type
,
1602 const glsl_type
*new_interface_type
)
1604 const glsl_type
*element_type
= type
->fields
.array
;
1605 if (element_type
->is_array()) {
1606 const glsl_type
*new_array_type
=
1607 update_interface_members_array(element_type
, new_interface_type
);
1608 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1610 return glsl_type::get_array_instance(new_interface_type
,
1616 * Determine whether the given interface type contains unsized arrays (if
1617 * it doesn't, array_sizing_visitor doesn't need to process it).
1619 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1621 for (unsigned i
= 0; i
< type
->length
; i
++) {
1622 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1623 if (elem_type
->is_unsized_array())
1630 * Create a new interface type based on the given type, with unsized arrays
1631 * replaced by sized arrays whose size is determined by
1632 * max_ifc_array_access.
1634 static const glsl_type
*
1635 resize_interface_members(const glsl_type
*type
,
1636 const int *max_ifc_array_access
,
1639 unsigned num_fields
= type
->length
;
1640 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1641 memcpy(fields
, type
->fields
.structure
,
1642 num_fields
* sizeof(*fields
));
1643 for (unsigned i
= 0; i
< num_fields
; i
++) {
1644 bool implicit_sized_array
= fields
[i
].implicit_sized_array
;
1645 /* If SSBO last member is unsized array, we don't replace it by a sized
1648 if (is_ssbo
&& i
== (num_fields
- 1))
1649 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1650 true, &implicit_sized_array
);
1652 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1653 false, &implicit_sized_array
);
1654 fields
[i
].implicit_sized_array
= implicit_sized_array
;
1656 glsl_interface_packing packing
=
1657 (glsl_interface_packing
) type
->interface_packing
;
1658 bool row_major
= (bool) type
->interface_row_major
;
1659 const glsl_type
*new_ifc_type
=
1660 glsl_type::get_interface_instance(fields
, num_fields
,
1661 packing
, row_major
, type
->name
);
1663 return new_ifc_type
;
1666 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1669 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1670 ir_variable
**interface_vars
= (ir_variable
**) data
;
1671 unsigned num_fields
= ifc_type
->length
;
1672 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1673 memcpy(fields
, ifc_type
->fields
.structure
,
1674 num_fields
* sizeof(*fields
));
1675 bool interface_type_changed
= false;
1676 for (unsigned i
= 0; i
< num_fields
; i
++) {
1677 if (interface_vars
[i
] != NULL
&&
1678 fields
[i
].type
!= interface_vars
[i
]->type
) {
1679 fields
[i
].type
= interface_vars
[i
]->type
;
1680 interface_type_changed
= true;
1683 if (!interface_type_changed
) {
1687 glsl_interface_packing packing
=
1688 (glsl_interface_packing
) ifc_type
->interface_packing
;
1689 bool row_major
= (bool) ifc_type
->interface_row_major
;
1690 const glsl_type
*new_ifc_type
=
1691 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1692 row_major
, ifc_type
->name
);
1694 for (unsigned i
= 0; i
< num_fields
; i
++) {
1695 if (interface_vars
[i
] != NULL
)
1696 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1701 * Memory context used to allocate the data in \c unnamed_interfaces.
1706 * Hash table from const glsl_type * to an array of ir_variable *'s
1707 * pointing to the ir_variables constituting each unnamed interface block.
1709 hash_table
*unnamed_interfaces
;
1713 validate_xfb_buffer_stride(struct gl_context
*ctx
, unsigned idx
,
1714 struct gl_shader_program
*prog
)
1716 /* We will validate doubles at a later stage */
1717 if (prog
->TransformFeedback
.BufferStride
[idx
] % 4) {
1718 linker_error(prog
, "invalid qualifier xfb_stride=%d must be a "
1719 "multiple of 4 or if its applied to a type that is "
1720 "or contains a double a multiple of 8.",
1721 prog
->TransformFeedback
.BufferStride
[idx
]);
1725 if (prog
->TransformFeedback
.BufferStride
[idx
] / 4 >
1726 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1727 linker_error(prog
, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1728 "limit has been exceeded.");
1736 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1740 link_xfb_stride_layout_qualifiers(struct gl_context
*ctx
,
1741 struct gl_shader_program
*prog
,
1742 struct gl_shader
**shader_list
,
1743 unsigned num_shaders
)
1745 for (unsigned i
= 0; i
< MAX_FEEDBACK_BUFFERS
; i
++) {
1746 prog
->TransformFeedback
.BufferStride
[i
] = 0;
1749 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1750 struct gl_shader
*shader
= shader_list
[i
];
1752 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1753 if (shader
->TransformFeedbackBufferStride
[j
]) {
1754 if (prog
->TransformFeedback
.BufferStride
[j
] == 0) {
1755 prog
->TransformFeedback
.BufferStride
[j
] =
1756 shader
->TransformFeedbackBufferStride
[j
];
1757 if (!validate_xfb_buffer_stride(ctx
, j
, prog
))
1759 } else if (prog
->TransformFeedback
.BufferStride
[j
] !=
1760 shader
->TransformFeedbackBufferStride
[j
]){
1762 "intrastage shaders defined with conflicting "
1763 "xfb_stride for buffer %d (%d and %d)\n", j
,
1764 prog
->TransformFeedback
.BufferStride
[j
],
1765 shader
->TransformFeedbackBufferStride
[j
]);
1774 * Check for conflicting bindless/bound sampler/image layout qualifiers at
1778 link_bindless_layout_qualifiers(struct gl_shader_program
*prog
,
1779 struct gl_shader
**shader_list
,
1780 unsigned num_shaders
)
1782 bool bindless_sampler
, bindless_image
;
1783 bool bound_sampler
, bound_image
;
1785 bindless_sampler
= bindless_image
= false;
1786 bound_sampler
= bound_image
= false;
1788 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1789 struct gl_shader
*shader
= shader_list
[i
];
1791 if (shader
->bindless_sampler
)
1792 bindless_sampler
= true;
1793 if (shader
->bindless_image
)
1794 bindless_image
= true;
1795 if (shader
->bound_sampler
)
1796 bound_sampler
= true;
1797 if (shader
->bound_image
)
1800 if ((bindless_sampler
&& bound_sampler
) ||
1801 (bindless_image
&& bound_image
)) {
1802 /* From section 4.4.6 of the ARB_bindless_texture spec:
1804 * "If both bindless_sampler and bound_sampler, or bindless_image
1805 * and bound_image, are declared at global scope in any
1806 * compilation unit, a link- time error will be generated."
1808 linker_error(prog
, "both bindless_sampler and bound_sampler, or "
1809 "bindless_image and bound_image, can't be declared at "
1816 * Performs the cross-validation of tessellation control shader vertices and
1817 * layout qualifiers for the attached tessellation control shaders,
1818 * and propagates them to the linked TCS and linked shader program.
1821 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1822 struct gl_program
*gl_prog
,
1823 struct gl_shader
**shader_list
,
1824 unsigned num_shaders
)
1826 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_CTRL
)
1829 gl_prog
->info
.tess
.tcs_vertices_out
= 0;
1831 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1833 * "All tessellation control shader layout declarations in a program
1834 * must specify the same output patch vertex count. There must be at
1835 * least one layout qualifier specifying an output patch vertex count
1836 * in any program containing tessellation control shaders; however,
1837 * such a declaration is not required in all tessellation control
1841 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1842 struct gl_shader
*shader
= shader_list
[i
];
1844 if (shader
->info
.TessCtrl
.VerticesOut
!= 0) {
1845 if (gl_prog
->info
.tess
.tcs_vertices_out
!= 0 &&
1846 gl_prog
->info
.tess
.tcs_vertices_out
!=
1847 (unsigned) shader
->info
.TessCtrl
.VerticesOut
) {
1848 linker_error(prog
, "tessellation control shader defined with "
1849 "conflicting output vertex count (%d and %d)\n",
1850 gl_prog
->info
.tess
.tcs_vertices_out
,
1851 shader
->info
.TessCtrl
.VerticesOut
);
1854 gl_prog
->info
.tess
.tcs_vertices_out
=
1855 shader
->info
.TessCtrl
.VerticesOut
;
1859 /* Just do the intrastage -> interstage propagation right now,
1860 * since we already know we're in the right type of shader program
1863 if (gl_prog
->info
.tess
.tcs_vertices_out
== 0) {
1864 linker_error(prog
, "tessellation control shader didn't declare "
1865 "vertices out layout qualifier\n");
1872 * Performs the cross-validation of tessellation evaluation shader
1873 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1874 * for the attached tessellation evaluation shaders, and propagates them
1875 * to the linked TES and linked shader program.
1878 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1879 struct gl_program
*gl_prog
,
1880 struct gl_shader
**shader_list
,
1881 unsigned num_shaders
)
1883 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_EVAL
)
1886 int point_mode
= -1;
1887 unsigned vertex_order
= 0;
1889 gl_prog
->info
.tess
.primitive_mode
= PRIM_UNKNOWN
;
1890 gl_prog
->info
.tess
.spacing
= TESS_SPACING_UNSPECIFIED
;
1892 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1894 * "At least one tessellation evaluation shader (compilation unit) in
1895 * a program must declare a primitive mode in its input layout.
1896 * Declaration vertex spacing, ordering, and point mode identifiers is
1897 * optional. It is not required that all tessellation evaluation
1898 * shaders in a program declare a primitive mode. If spacing or
1899 * vertex ordering declarations are omitted, the tessellation
1900 * primitive generator will use equal spacing or counter-clockwise
1901 * vertex ordering, respectively. If a point mode declaration is
1902 * omitted, the tessellation primitive generator will produce lines or
1903 * triangles according to the primitive mode."
1906 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1907 struct gl_shader
*shader
= shader_list
[i
];
1909 if (shader
->info
.TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1910 if (gl_prog
->info
.tess
.primitive_mode
!= PRIM_UNKNOWN
&&
1911 gl_prog
->info
.tess
.primitive_mode
!=
1912 shader
->info
.TessEval
.PrimitiveMode
) {
1913 linker_error(prog
, "tessellation evaluation shader defined with "
1914 "conflicting input primitive modes.\n");
1917 gl_prog
->info
.tess
.primitive_mode
=
1918 shader
->info
.TessEval
.PrimitiveMode
;
1921 if (shader
->info
.TessEval
.Spacing
!= 0) {
1922 if (gl_prog
->info
.tess
.spacing
!= 0 && gl_prog
->info
.tess
.spacing
!=
1923 shader
->info
.TessEval
.Spacing
) {
1924 linker_error(prog
, "tessellation evaluation shader defined with "
1925 "conflicting vertex spacing.\n");
1928 gl_prog
->info
.tess
.spacing
= shader
->info
.TessEval
.Spacing
;
1931 if (shader
->info
.TessEval
.VertexOrder
!= 0) {
1932 if (vertex_order
!= 0 &&
1933 vertex_order
!= shader
->info
.TessEval
.VertexOrder
) {
1934 linker_error(prog
, "tessellation evaluation shader defined with "
1935 "conflicting ordering.\n");
1938 vertex_order
= shader
->info
.TessEval
.VertexOrder
;
1941 if (shader
->info
.TessEval
.PointMode
!= -1) {
1942 if (point_mode
!= -1 &&
1943 point_mode
!= shader
->info
.TessEval
.PointMode
) {
1944 linker_error(prog
, "tessellation evaluation shader defined with "
1945 "conflicting point modes.\n");
1948 point_mode
= shader
->info
.TessEval
.PointMode
;
1953 /* Just do the intrastage -> interstage propagation right now,
1954 * since we already know we're in the right type of shader program
1957 if (gl_prog
->info
.tess
.primitive_mode
== PRIM_UNKNOWN
) {
1959 "tessellation evaluation shader didn't declare input "
1960 "primitive modes.\n");
1964 if (gl_prog
->info
.tess
.spacing
== TESS_SPACING_UNSPECIFIED
)
1965 gl_prog
->info
.tess
.spacing
= TESS_SPACING_EQUAL
;
1967 if (vertex_order
== 0 || vertex_order
== GL_CCW
)
1968 gl_prog
->info
.tess
.ccw
= true;
1970 gl_prog
->info
.tess
.ccw
= false;
1973 if (point_mode
== -1 || point_mode
== GL_FALSE
)
1974 gl_prog
->info
.tess
.point_mode
= false;
1976 gl_prog
->info
.tess
.point_mode
= true;
1981 * Performs the cross-validation of layout qualifiers specified in
1982 * redeclaration of gl_FragCoord for the attached fragment shaders,
1983 * and propagates them to the linked FS and linked shader program.
1986 link_fs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1987 struct gl_linked_shader
*linked_shader
,
1988 struct gl_shader
**shader_list
,
1989 unsigned num_shaders
)
1991 bool redeclares_gl_fragcoord
= false;
1992 bool uses_gl_fragcoord
= false;
1993 bool origin_upper_left
= false;
1994 bool pixel_center_integer
= false;
1996 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1997 (prog
->data
->Version
< 150 &&
1998 !prog
->ARB_fragment_coord_conventions_enable
))
2001 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2002 struct gl_shader
*shader
= shader_list
[i
];
2003 /* From the GLSL 1.50 spec, page 39:
2005 * "If gl_FragCoord is redeclared in any fragment shader in a program,
2006 * it must be redeclared in all the fragment shaders in that program
2007 * that have a static use gl_FragCoord."
2009 if ((redeclares_gl_fragcoord
&& !shader
->redeclares_gl_fragcoord
&&
2010 shader
->uses_gl_fragcoord
)
2011 || (shader
->redeclares_gl_fragcoord
&& !redeclares_gl_fragcoord
&&
2012 uses_gl_fragcoord
)) {
2013 linker_error(prog
, "fragment shader defined with conflicting "
2014 "layout qualifiers for gl_FragCoord\n");
2017 /* From the GLSL 1.50 spec, page 39:
2019 * "All redeclarations of gl_FragCoord in all fragment shaders in a
2020 * single program must have the same set of qualifiers."
2022 if (redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
&&
2023 (shader
->origin_upper_left
!= origin_upper_left
||
2024 shader
->pixel_center_integer
!= pixel_center_integer
)) {
2025 linker_error(prog
, "fragment shader defined with conflicting "
2026 "layout qualifiers for gl_FragCoord\n");
2029 /* Update the linked shader state. Note that uses_gl_fragcoord should
2030 * accumulate the results. The other values should replace. If there
2031 * are multiple redeclarations, all the fields except uses_gl_fragcoord
2032 * are already known to be the same.
2034 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
2035 redeclares_gl_fragcoord
= shader
->redeclares_gl_fragcoord
;
2036 uses_gl_fragcoord
|= shader
->uses_gl_fragcoord
;
2037 origin_upper_left
= shader
->origin_upper_left
;
2038 pixel_center_integer
= shader
->pixel_center_integer
;
2041 linked_shader
->Program
->info
.fs
.early_fragment_tests
|=
2042 shader
->EarlyFragmentTests
|| shader
->PostDepthCoverage
;
2043 linked_shader
->Program
->info
.fs
.inner_coverage
|= shader
->InnerCoverage
;
2044 linked_shader
->Program
->info
.fs
.post_depth_coverage
|=
2045 shader
->PostDepthCoverage
;
2046 linked_shader
->Program
->info
.fs
.pixel_interlock_ordered
|=
2047 shader
->PixelInterlockOrdered
;
2048 linked_shader
->Program
->info
.fs
.pixel_interlock_unordered
|=
2049 shader
->PixelInterlockUnordered
;
2050 linked_shader
->Program
->info
.fs
.sample_interlock_ordered
|=
2051 shader
->SampleInterlockOrdered
;
2052 linked_shader
->Program
->info
.fs
.sample_interlock_unordered
|=
2053 shader
->SampleInterlockUnordered
;
2054 linked_shader
->Program
->sh
.fs
.BlendSupport
|= shader
->BlendSupport
;
2057 linked_shader
->Program
->info
.fs
.pixel_center_integer
= pixel_center_integer
;
2058 linked_shader
->Program
->info
.fs
.origin_upper_left
= origin_upper_left
;
2062 * Performs the cross-validation of geometry shader max_vertices and
2063 * primitive type layout qualifiers for the attached geometry shaders,
2064 * and propagates them to the linked GS and linked shader program.
2067 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
2068 struct gl_program
*gl_prog
,
2069 struct gl_shader
**shader_list
,
2070 unsigned num_shaders
)
2072 /* No in/out qualifiers defined for anything but GLSL 1.50+
2073 * geometry shaders so far.
2075 if (gl_prog
->info
.stage
!= MESA_SHADER_GEOMETRY
||
2076 prog
->data
->Version
< 150)
2079 int vertices_out
= -1;
2081 gl_prog
->info
.gs
.invocations
= 0;
2082 gl_prog
->info
.gs
.input_primitive
= PRIM_UNKNOWN
;
2083 gl_prog
->info
.gs
.output_primitive
= PRIM_UNKNOWN
;
2085 /* From the GLSL 1.50 spec, page 46:
2087 * "All geometry shader output layout declarations in a program
2088 * must declare the same layout and same value for
2089 * max_vertices. There must be at least one geometry output
2090 * layout declaration somewhere in a program, but not all
2091 * geometry shaders (compilation units) are required to
2095 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2096 struct gl_shader
*shader
= shader_list
[i
];
2098 if (shader
->info
.Geom
.InputType
!= PRIM_UNKNOWN
) {
2099 if (gl_prog
->info
.gs
.input_primitive
!= PRIM_UNKNOWN
&&
2100 gl_prog
->info
.gs
.input_primitive
!=
2101 shader
->info
.Geom
.InputType
) {
2102 linker_error(prog
, "geometry shader defined with conflicting "
2106 gl_prog
->info
.gs
.input_primitive
= shader
->info
.Geom
.InputType
;
2109 if (shader
->info
.Geom
.OutputType
!= PRIM_UNKNOWN
) {
2110 if (gl_prog
->info
.gs
.output_primitive
!= PRIM_UNKNOWN
&&
2111 gl_prog
->info
.gs
.output_primitive
!=
2112 shader
->info
.Geom
.OutputType
) {
2113 linker_error(prog
, "geometry shader defined with conflicting "
2117 gl_prog
->info
.gs
.output_primitive
= shader
->info
.Geom
.OutputType
;
2120 if (shader
->info
.Geom
.VerticesOut
!= -1) {
2121 if (vertices_out
!= -1 &&
2122 vertices_out
!= shader
->info
.Geom
.VerticesOut
) {
2123 linker_error(prog
, "geometry shader defined with conflicting "
2124 "output vertex count (%d and %d)\n",
2125 vertices_out
, shader
->info
.Geom
.VerticesOut
);
2128 vertices_out
= shader
->info
.Geom
.VerticesOut
;
2131 if (shader
->info
.Geom
.Invocations
!= 0) {
2132 if (gl_prog
->info
.gs
.invocations
!= 0 &&
2133 gl_prog
->info
.gs
.invocations
!=
2134 (unsigned) shader
->info
.Geom
.Invocations
) {
2135 linker_error(prog
, "geometry shader defined with conflicting "
2136 "invocation count (%d and %d)\n",
2137 gl_prog
->info
.gs
.invocations
,
2138 shader
->info
.Geom
.Invocations
);
2141 gl_prog
->info
.gs
.invocations
= shader
->info
.Geom
.Invocations
;
2145 /* Just do the intrastage -> interstage propagation right now,
2146 * since we already know we're in the right type of shader program
2149 if (gl_prog
->info
.gs
.input_primitive
== PRIM_UNKNOWN
) {
2151 "geometry shader didn't declare primitive input type\n");
2155 if (gl_prog
->info
.gs
.output_primitive
== PRIM_UNKNOWN
) {
2157 "geometry shader didn't declare primitive output type\n");
2161 if (vertices_out
== -1) {
2163 "geometry shader didn't declare max_vertices\n");
2166 gl_prog
->info
.gs
.vertices_out
= vertices_out
;
2169 if (gl_prog
->info
.gs
.invocations
== 0)
2170 gl_prog
->info
.gs
.invocations
= 1;
2175 * Perform cross-validation of compute shader local_size_{x,y,z} layout and
2176 * derivative arrangement qualifiers for the attached compute shaders, and
2177 * propagate them to the linked CS and linked shader program.
2180 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
2181 struct gl_program
*gl_prog
,
2182 struct gl_shader
**shader_list
,
2183 unsigned num_shaders
)
2185 /* This function is called for all shader stages, but it only has an effect
2186 * for compute shaders.
2188 if (gl_prog
->info
.stage
!= MESA_SHADER_COMPUTE
)
2191 for (int i
= 0; i
< 3; i
++)
2192 gl_prog
->info
.cs
.local_size
[i
] = 0;
2194 gl_prog
->info
.cs
.local_size_variable
= false;
2196 gl_prog
->info
.cs
.derivative_group
= DERIVATIVE_GROUP_NONE
;
2198 /* From the ARB_compute_shader spec, in the section describing local size
2201 * If multiple compute shaders attached to a single program object
2202 * declare local work-group size, the declarations must be identical;
2203 * otherwise a link-time error results. Furthermore, if a program
2204 * object contains any compute shaders, at least one must contain an
2205 * input layout qualifier specifying the local work sizes of the
2206 * program, or a link-time error will occur.
2208 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
2209 struct gl_shader
*shader
= shader_list
[sh
];
2211 if (shader
->info
.Comp
.LocalSize
[0] != 0) {
2212 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2213 for (int i
= 0; i
< 3; i
++) {
2214 if (gl_prog
->info
.cs
.local_size
[i
] !=
2215 shader
->info
.Comp
.LocalSize
[i
]) {
2216 linker_error(prog
, "compute shader defined with conflicting "
2222 for (int i
= 0; i
< 3; i
++) {
2223 gl_prog
->info
.cs
.local_size
[i
] =
2224 shader
->info
.Comp
.LocalSize
[i
];
2226 } else if (shader
->info
.Comp
.LocalSizeVariable
) {
2227 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2228 /* The ARB_compute_variable_group_size spec says:
2230 * If one compute shader attached to a program declares a
2231 * variable local group size and a second compute shader
2232 * attached to the same program declares a fixed local group
2233 * size, a link-time error results.
2235 linker_error(prog
, "compute shader defined with both fixed and "
2236 "variable local group size\n");
2239 gl_prog
->info
.cs
.local_size_variable
= true;
2242 enum gl_derivative_group group
= shader
->info
.Comp
.DerivativeGroup
;
2243 if (group
!= DERIVATIVE_GROUP_NONE
) {
2244 if (gl_prog
->info
.cs
.derivative_group
!= DERIVATIVE_GROUP_NONE
&&
2245 gl_prog
->info
.cs
.derivative_group
!= group
) {
2246 linker_error(prog
, "compute shader defined with conflicting "
2247 "derivative groups\n");
2250 gl_prog
->info
.cs
.derivative_group
= group
;
2254 /* Just do the intrastage -> interstage propagation right now,
2255 * since we already know we're in the right type of shader program
2258 if (gl_prog
->info
.cs
.local_size
[0] == 0 &&
2259 !gl_prog
->info
.cs
.local_size_variable
) {
2260 linker_error(prog
, "compute shader must contain a fixed or a variable "
2261 "local group size\n");
2265 if (gl_prog
->info
.cs
.derivative_group
== DERIVATIVE_GROUP_QUADS
) {
2266 if (gl_prog
->info
.cs
.local_size
[0] % 2 != 0) {
2267 linker_error(prog
, "derivative_group_quadsNV must be used with a "
2268 "local group size whose first dimension "
2269 "is a multiple of 2\n");
2272 if (gl_prog
->info
.cs
.local_size
[1] % 2 != 0) {
2273 linker_error(prog
, "derivative_group_quadsNV must be used with a local"
2274 "group size whose second dimension "
2275 "is a multiple of 2\n");
2278 } else if (gl_prog
->info
.cs
.derivative_group
== DERIVATIVE_GROUP_LINEAR
) {
2279 if ((gl_prog
->info
.cs
.local_size
[0] *
2280 gl_prog
->info
.cs
.local_size
[1] *
2281 gl_prog
->info
.cs
.local_size
[2]) % 4 != 0) {
2282 linker_error(prog
, "derivative_group_linearNV must be used with a "
2283 "local group size whose total number of invocations "
2284 "is a multiple of 4\n");
2291 * Link all out variables on a single stage which are not
2292 * directly used in a shader with the main function.
2295 link_output_variables(struct gl_linked_shader
*linked_shader
,
2296 struct gl_shader
**shader_list
,
2297 unsigned num_shaders
)
2299 struct glsl_symbol_table
*symbols
= linked_shader
->symbols
;
2301 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2303 /* Skip shader object with main function */
2304 if (shader_list
[i
]->symbols
->get_function("main"))
2307 foreach_in_list(ir_instruction
, ir
, shader_list
[i
]->ir
) {
2308 if (ir
->ir_type
!= ir_type_variable
)
2311 ir_variable
*var
= (ir_variable
*) ir
;
2313 if (var
->data
.mode
== ir_var_shader_out
&&
2314 !symbols
->get_variable(var
->name
)) {
2315 var
= var
->clone(linked_shader
, NULL
);
2316 symbols
->add_variable(var
);
2317 linked_shader
->ir
->push_head(var
);
2327 * Combine a group of shaders for a single stage to generate a linked shader
2330 * If this function is supplied a single shader, it is cloned, and the new
2331 * shader is returned.
2333 struct gl_linked_shader
*
2334 link_intrastage_shaders(void *mem_ctx
,
2335 struct gl_context
*ctx
,
2336 struct gl_shader_program
*prog
,
2337 struct gl_shader
**shader_list
,
2338 unsigned num_shaders
,
2339 bool allow_missing_main
)
2341 struct gl_uniform_block
*ubo_blocks
= NULL
;
2342 struct gl_uniform_block
*ssbo_blocks
= NULL
;
2343 unsigned num_ubo_blocks
= 0;
2344 unsigned num_ssbo_blocks
= 0;
2346 /* Check that global variables defined in multiple shaders are consistent.
2348 glsl_symbol_table variables
;
2349 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2350 if (shader_list
[i
] == NULL
)
2352 cross_validate_globals(ctx
, prog
, shader_list
[i
]->ir
, &variables
,
2356 if (!prog
->data
->LinkStatus
)
2359 /* Check that interface blocks defined in multiple shaders are consistent.
2361 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
2363 if (!prog
->data
->LinkStatus
)
2366 /* Check that there is only a single definition of each function signature
2367 * across all shaders.
2369 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2370 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2371 ir_function
*const f
= node
->as_function();
2376 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2377 ir_function
*const other
=
2378 shader_list
[j
]->symbols
->get_function(f
->name
);
2380 /* If the other shader has no function (and therefore no function
2381 * signatures) with the same name, skip to the next shader.
2386 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2387 if (!sig
->is_defined
)
2390 ir_function_signature
*other_sig
=
2391 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2393 if (other_sig
!= NULL
&& other_sig
->is_defined
) {
2394 linker_error(prog
, "function `%s' is multiply defined\n",
2403 /* Find the shader that defines main, and make a clone of it.
2405 * Starting with the clone, search for undefined references. If one is
2406 * found, find the shader that defines it. Clone the reference and add
2407 * it to the shader. Repeat until there are no undefined references or
2408 * until a reference cannot be resolved.
2410 gl_shader
*main
= NULL
;
2411 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2412 if (_mesa_get_main_function_signature(shader_list
[i
]->symbols
)) {
2413 main
= shader_list
[i
];
2418 if (main
== NULL
&& allow_missing_main
)
2419 main
= shader_list
[0];
2422 linker_error(prog
, "%s shader lacks `main'\n",
2423 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2427 gl_linked_shader
*linked
= rzalloc(NULL
, struct gl_linked_shader
);
2428 linked
->Stage
= shader_list
[0]->Stage
;
2430 /* Create program and attach it to the linked shader */
2431 struct gl_program
*gl_prog
=
2432 ctx
->Driver
.NewProgram(ctx
,
2433 _mesa_shader_stage_to_program(shader_list
[0]->Stage
),
2436 prog
->data
->LinkStatus
= LINKING_FAILURE
;
2437 _mesa_delete_linked_shader(ctx
, linked
);
2441 _mesa_reference_shader_program_data(ctx
, &gl_prog
->sh
.data
, prog
->data
);
2443 /* Don't use _mesa_reference_program() just take ownership */
2444 linked
->Program
= gl_prog
;
2446 linked
->ir
= new(linked
) exec_list
;
2447 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2449 link_fs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2450 link_tcs_out_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2451 link_tes_in_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2452 link_gs_inout_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2453 link_cs_input_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2455 if (linked
->Stage
!= MESA_SHADER_FRAGMENT
)
2456 link_xfb_stride_layout_qualifiers(ctx
, prog
, shader_list
, num_shaders
);
2458 link_bindless_layout_qualifiers(prog
, shader_list
, num_shaders
);
2460 populate_symbol_table(linked
, shader_list
[0]->symbols
);
2462 /* The pointer to the main function in the final linked shader (i.e., the
2463 * copy of the original shader that contained the main function).
2465 ir_function_signature
*const main_sig
=
2466 _mesa_get_main_function_signature(linked
->symbols
);
2468 /* Move any instructions other than variable declarations or function
2469 * declarations into main.
2471 if (main_sig
!= NULL
) {
2472 exec_node
*insertion_point
=
2473 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2476 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2477 if (shader_list
[i
] == main
)
2480 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2481 insertion_point
, true, linked
);
2485 if (!link_function_calls(prog
, linked
, shader_list
, num_shaders
)) {
2486 _mesa_delete_linked_shader(ctx
, linked
);
2490 if (linked
->Stage
!= MESA_SHADER_FRAGMENT
)
2491 link_output_variables(linked
, shader_list
, num_shaders
);
2493 /* Make a pass over all variable declarations to ensure that arrays with
2494 * unspecified sizes have a size specified. The size is inferred from the
2495 * max_array_access field.
2497 array_sizing_visitor v
;
2499 v
.fixup_unnamed_interface_types();
2501 /* Link up uniform blocks defined within this stage. */
2502 link_uniform_blocks(mem_ctx
, ctx
, prog
, linked
, &ubo_blocks
,
2503 &num_ubo_blocks
, &ssbo_blocks
, &num_ssbo_blocks
);
2505 const unsigned max_uniform_blocks
=
2506 ctx
->Const
.Program
[linked
->Stage
].MaxUniformBlocks
;
2507 if (num_ubo_blocks
> max_uniform_blocks
) {
2508 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
2509 _mesa_shader_stage_to_string(linked
->Stage
),
2510 num_ubo_blocks
, max_uniform_blocks
);
2513 const unsigned max_shader_storage_blocks
=
2514 ctx
->Const
.Program
[linked
->Stage
].MaxShaderStorageBlocks
;
2515 if (num_ssbo_blocks
> max_shader_storage_blocks
) {
2516 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
2517 _mesa_shader_stage_to_string(linked
->Stage
),
2518 num_ssbo_blocks
, max_shader_storage_blocks
);
2521 if (!prog
->data
->LinkStatus
) {
2522 _mesa_delete_linked_shader(ctx
, linked
);
2526 /* Copy ubo blocks to linked shader list */
2527 linked
->Program
->sh
.UniformBlocks
=
2528 ralloc_array(linked
, gl_uniform_block
*, num_ubo_blocks
);
2529 ralloc_steal(linked
, ubo_blocks
);
2530 for (unsigned i
= 0; i
< num_ubo_blocks
; i
++) {
2531 linked
->Program
->sh
.UniformBlocks
[i
] = &ubo_blocks
[i
];
2533 linked
->Program
->info
.num_ubos
= num_ubo_blocks
;
2535 /* Copy ssbo blocks to linked shader list */
2536 linked
->Program
->sh
.ShaderStorageBlocks
=
2537 ralloc_array(linked
, gl_uniform_block
*, num_ssbo_blocks
);
2538 ralloc_steal(linked
, ssbo_blocks
);
2539 for (unsigned i
= 0; i
< num_ssbo_blocks
; i
++) {
2540 linked
->Program
->sh
.ShaderStorageBlocks
[i
] = &ssbo_blocks
[i
];
2542 linked
->Program
->info
.num_ssbos
= num_ssbo_blocks
;
2544 /* At this point linked should contain all of the linked IR, so
2545 * validate it to make sure nothing went wrong.
2547 validate_ir_tree(linked
->ir
);
2549 /* Set the size of geometry shader input arrays */
2550 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2551 unsigned num_vertices
=
2552 vertices_per_prim(gl_prog
->info
.gs
.input_primitive
);
2553 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2554 MESA_SHADER_GEOMETRY
);
2555 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2556 ir
->accept(&input_resize_visitor
);
2560 if (ctx
->Const
.VertexID_is_zero_based
)
2561 lower_vertex_id(linked
);
2563 if (ctx
->Const
.LowerCsDerivedVariables
)
2564 lower_cs_derived(linked
);
2567 /* Compute the source checksum. */
2568 linked
->SourceChecksum
= 0;
2569 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2570 if (shader_list
[i
] == NULL
)
2572 linked
->SourceChecksum
^= shader_list
[i
]->SourceChecksum
;
2580 * Update the sizes of linked shader uniform arrays to the maximum
2583 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2585 * If one or more elements of an array are active,
2586 * GetActiveUniform will return the name of the array in name,
2587 * subject to the restrictions listed above. The type of the array
2588 * is returned in type. The size parameter contains the highest
2589 * array element index used, plus one. The compiler or linker
2590 * determines the highest index used. There will be only one
2591 * active uniform reported by the GL per uniform array.
2595 update_array_sizes(struct gl_shader_program
*prog
)
2597 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2598 if (prog
->_LinkedShaders
[i
] == NULL
)
2601 bool types_were_updated
= false;
2603 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2604 ir_variable
*const var
= node
->as_variable();
2606 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2607 !var
->type
->is_array())
2610 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2611 * will not be eliminated. Since we always do std140, just
2612 * don't resize arrays in UBOs.
2614 * Atomic counters are supposed to get deterministic
2615 * locations assigned based on the declaration ordering and
2616 * sizes, array compaction would mess that up.
2618 * Subroutine uniforms are not removed.
2620 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2621 var
->type
->contains_subroutine() || var
->constant_initializer
)
2624 int size
= var
->data
.max_array_access
;
2625 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2626 if (prog
->_LinkedShaders
[j
] == NULL
)
2629 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2630 ir_variable
*other_var
= node2
->as_variable();
2634 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2635 other_var
->data
.max_array_access
> size
) {
2636 size
= other_var
->data
.max_array_access
;
2641 if (size
+ 1 != (int)var
->type
->length
) {
2642 /* If this is a built-in uniform (i.e., it's backed by some
2643 * fixed-function state), adjust the number of state slots to
2644 * match the new array size. The number of slots per array entry
2645 * is not known. It seems safe to assume that the total number of
2646 * slots is an integer multiple of the number of array elements.
2647 * Determine the number of slots per array element by dividing by
2648 * the old (total) size.
2650 const unsigned num_slots
= var
->get_num_state_slots();
2651 if (num_slots
> 0) {
2652 var
->set_num_state_slots((size
+ 1)
2653 * (num_slots
/ var
->type
->length
));
2656 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2658 types_were_updated
= true;
2662 /* Update the types of dereferences in case we changed any. */
2663 if (types_were_updated
) {
2664 deref_type_updater v
;
2665 v
.run(prog
->_LinkedShaders
[i
]->ir
);
2671 * Resize tessellation evaluation per-vertex inputs to the size of
2672 * tessellation control per-vertex outputs.
2675 resize_tes_inputs(struct gl_context
*ctx
,
2676 struct gl_shader_program
*prog
)
2678 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2681 gl_linked_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2682 gl_linked_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2684 /* If no control shader is present, then the TES inputs are statically
2685 * sized to MaxPatchVertices; the actual size of the arrays won't be
2686 * known until draw time.
2688 const int num_vertices
= tcs
2689 ? tcs
->Program
->info
.tess
.tcs_vertices_out
2690 : ctx
->Const
.MaxPatchVertices
;
2692 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2693 MESA_SHADER_TESS_EVAL
);
2694 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2695 ir
->accept(&input_resize_visitor
);
2699 /* Convert the gl_PatchVerticesIn system value into a constant, since
2700 * the value is known at this point.
2702 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2703 ir_variable
*var
= ir
->as_variable();
2704 if (var
&& var
->data
.mode
== ir_var_system_value
&&
2705 var
->data
.location
== SYSTEM_VALUE_VERTICES_IN
) {
2706 void *mem_ctx
= ralloc_parent(var
);
2707 var
->data
.location
= 0;
2708 var
->data
.explicit_location
= false;
2709 var
->data
.mode
= ir_var_auto
;
2710 var
->constant_value
= new(mem_ctx
) ir_constant(num_vertices
);
2717 * Find a contiguous set of available bits in a bitmask.
2719 * \param used_mask Bits representing used (1) and unused (0) locations
2720 * \param needed_count Number of contiguous bits needed.
2723 * Base location of the available bits on success or -1 on failure.
2726 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2728 unsigned needed_mask
= (1 << needed_count
) - 1;
2729 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2731 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2732 * cannot optimize possibly infinite loops" for the loop below.
2734 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2737 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2738 if ((needed_mask
& ~used_mask
) == needed_mask
)
2748 #define SAFE_MASK_FROM_INDEX(i) (((i) >= 32) ? ~0 : ((1 << (i)) - 1))
2751 * Assign locations for either VS inputs or FS outputs.
2753 * \param mem_ctx Temporary ralloc context used for linking.
2754 * \param prog Shader program whose variables need locations
2756 * \param constants Driver specific constant values for the program.
2757 * \param target_index Selector for the program target to receive location
2758 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2759 * \c MESA_SHADER_FRAGMENT.
2760 * \param do_assignment Whether we are actually marking the assignment or we
2761 * are just doing a dry-run checking.
2764 * If locations are (or can be, in case of dry-running) successfully assigned,
2765 * true is returned. Otherwise an error is emitted to the shader link log and
2766 * false is returned.
2769 assign_attribute_or_color_locations(void *mem_ctx
,
2770 gl_shader_program
*prog
,
2771 struct gl_constants
*constants
,
2772 unsigned target_index
,
2775 /* Maximum number of generic locations. This corresponds to either the
2776 * maximum number of draw buffers or the maximum number of generic
2779 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2780 constants
->Program
[target_index
].MaxAttribs
:
2781 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2783 /* Mark invalid locations as being used.
2785 unsigned used_locations
= ~SAFE_MASK_FROM_INDEX(max_index
);
2786 unsigned double_storage_locations
= 0;
2788 assert((target_index
== MESA_SHADER_VERTEX
)
2789 || (target_index
== MESA_SHADER_FRAGMENT
));
2791 gl_linked_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2795 /* Operate in a total of four passes.
2797 * 1. Invalidate the location assignments for all vertex shader inputs.
2799 * 2. Assign locations for inputs that have user-defined (via
2800 * glBindVertexAttribLocation) locations and outputs that have
2801 * user-defined locations (via glBindFragDataLocation).
2803 * 3. Sort the attributes without assigned locations by number of slots
2804 * required in decreasing order. Fragmentation caused by attribute
2805 * locations assigned by the application may prevent large attributes
2806 * from having enough contiguous space.
2808 * 4. Assign locations to any inputs without assigned locations.
2811 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2812 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2814 const enum ir_variable_mode direction
=
2815 (target_index
== MESA_SHADER_VERTEX
)
2816 ? ir_var_shader_in
: ir_var_shader_out
;
2819 /* Temporary storage for the set of attributes that need locations assigned.
2825 /* Used below in the call to qsort. */
2826 static int compare(const void *a
, const void *b
)
2828 const temp_attr
*const l
= (const temp_attr
*) a
;
2829 const temp_attr
*const r
= (const temp_attr
*) b
;
2831 /* Reversed because we want a descending order sort below. */
2832 return r
->slots
- l
->slots
;
2835 assert(max_index
<= 32);
2837 /* Temporary array for the set of attributes that have locations assigned,
2838 * for the purpose of checking overlapping slots/components of (non-ES)
2839 * fragment shader outputs.
2841 ir_variable
*assigned
[12 * 4]; /* (max # of FS outputs) * # components */
2842 unsigned assigned_attr
= 0;
2844 unsigned num_attr
= 0;
2846 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2847 ir_variable
*const var
= node
->as_variable();
2849 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2852 if (var
->data
.explicit_location
) {
2853 var
->data
.is_unmatched_generic_inout
= 0;
2854 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2855 || (var
->data
.location
< 0)) {
2857 "invalid explicit location %d specified for `%s'\n",
2858 (var
->data
.location
< 0)
2859 ? var
->data
.location
2860 : var
->data
.location
- generic_base
,
2864 } else if (target_index
== MESA_SHADER_VERTEX
) {
2867 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2868 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2869 var
->data
.location
= binding
;
2870 var
->data
.is_unmatched_generic_inout
= 0;
2872 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2875 const char *name
= var
->name
;
2876 const glsl_type
*type
= var
->type
;
2879 /* Check if there's a binding for the variable name */
2880 if (prog
->FragDataBindings
->get(binding
, name
)) {
2881 assert(binding
>= FRAG_RESULT_DATA0
);
2882 var
->data
.location
= binding
;
2883 var
->data
.is_unmatched_generic_inout
= 0;
2885 if (prog
->FragDataIndexBindings
->get(index
, name
)) {
2886 var
->data
.index
= index
;
2891 /* If not, but it's an array type, look for name[0] */
2892 if (type
->is_array()) {
2893 name
= ralloc_asprintf(mem_ctx
, "%s[0]", name
);
2894 type
= type
->fields
.array
;
2902 if (strcmp(var
->name
, "gl_LastFragData") == 0)
2905 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2907 * "Output binding assignments will cause LinkProgram to fail:
2909 * If the program has an active output assigned to a location greater
2910 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2911 * an active output assigned an index greater than or equal to one;"
2913 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2914 var
->data
.location
- generic_base
>=
2915 (int) constants
->MaxDualSourceDrawBuffers
) {
2917 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2918 "with index %u for %s\n",
2919 var
->data
.location
- generic_base
, var
->data
.index
,
2924 const unsigned slots
= var
->type
->count_attribute_slots(target_index
== MESA_SHADER_VERTEX
);
2926 /* If the variable is not a built-in and has a location statically
2927 * assigned in the shader (presumably via a layout qualifier), make sure
2928 * that it doesn't collide with other assigned locations. Otherwise,
2929 * add it to the list of variables that need linker-assigned locations.
2931 if (var
->data
.location
!= -1) {
2932 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2933 /* From page 61 of the OpenGL 4.0 spec:
2935 * "LinkProgram will fail if the attribute bindings assigned
2936 * by BindAttribLocation do not leave not enough space to
2937 * assign a location for an active matrix attribute or an
2938 * active attribute array, both of which require multiple
2939 * contiguous generic attributes."
2941 * I think above text prohibits the aliasing of explicit and
2942 * automatic assignments. But, aliasing is allowed in manual
2943 * assignments of attribute locations. See below comments for
2946 * From OpenGL 4.0 spec, page 61:
2948 * "It is possible for an application to bind more than one
2949 * attribute name to the same location. This is referred to as
2950 * aliasing. This will only work if only one of the aliased
2951 * attributes is active in the executable program, or if no
2952 * path through the shader consumes more than one attribute of
2953 * a set of attributes aliased to the same location. A link
2954 * error can occur if the linker determines that every path
2955 * through the shader consumes multiple aliased attributes,
2956 * but implementations are not required to generate an error
2959 * From GLSL 4.30 spec, page 54:
2961 * "A program will fail to link if any two non-vertex shader
2962 * input variables are assigned to the same location. For
2963 * vertex shaders, multiple input variables may be assigned
2964 * to the same location using either layout qualifiers or via
2965 * the OpenGL API. However, such aliasing is intended only to
2966 * support vertex shaders where each execution path accesses
2967 * at most one input per each location. Implementations are
2968 * permitted, but not required, to generate link-time errors
2969 * if they detect that every path through the vertex shader
2970 * executable accesses multiple inputs assigned to any single
2971 * location. For all shader types, a program will fail to link
2972 * if explicit location assignments leave the linker unable
2973 * to find space for other variables without explicit
2976 * From OpenGL ES 3.0 spec, page 56:
2978 * "Binding more than one attribute name to the same location
2979 * is referred to as aliasing, and is not permitted in OpenGL
2980 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2981 * fail when this condition exists. However, aliasing is
2982 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2983 * This will only work if only one of the aliased attributes
2984 * is active in the executable program, or if no path through
2985 * the shader consumes more than one attribute of a set of
2986 * attributes aliased to the same location. A link error can
2987 * occur if the linker determines that every path through the
2988 * shader consumes multiple aliased attributes, but implemen-
2989 * tations are not required to generate an error in this case."
2991 * After looking at above references from OpenGL, OpenGL ES and
2992 * GLSL specifications, we allow aliasing of vertex input variables
2993 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2995 * NOTE: This is not required by the spec but its worth mentioning
2996 * here that we're not doing anything to make sure that no path
2997 * through the vertex shader executable accesses multiple inputs
2998 * assigned to any single location.
3001 /* Mask representing the contiguous slots that will be used by
3004 const unsigned attr
= var
->data
.location
- generic_base
;
3005 const unsigned use_mask
= (1 << slots
) - 1;
3006 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
3007 ? "vertex shader input" : "fragment shader output";
3009 /* Generate a link error if the requested locations for this
3010 * attribute exceed the maximum allowed attribute location.
3012 if (attr
+ slots
> max_index
) {
3014 "insufficient contiguous locations "
3015 "available for %s `%s' %d %d %d\n", string
,
3016 var
->name
, used_locations
, use_mask
, attr
);
3020 /* Generate a link error if the set of bits requested for this
3021 * attribute overlaps any previously allocated bits.
3023 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
3024 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
3025 /* From section 4.4.2 (Output Layout Qualifiers) of the GLSL
3028 * "Additionally, for fragment shader outputs, if two
3029 * variables are placed within the same location, they
3030 * must have the same underlying type (floating-point or
3031 * integer). No component aliasing of output variables or
3032 * members is allowed.
3034 for (unsigned i
= 0; i
< assigned_attr
; i
++) {
3035 unsigned assigned_slots
=
3036 assigned
[i
]->type
->count_attribute_slots(false);
3037 unsigned assig_attr
=
3038 assigned
[i
]->data
.location
- generic_base
;
3039 unsigned assigned_use_mask
= (1 << assigned_slots
) - 1;
3041 if ((assigned_use_mask
<< assig_attr
) &
3042 (use_mask
<< attr
)) {
3044 const glsl_type
*assigned_type
=
3045 assigned
[i
]->type
->without_array();
3046 const glsl_type
*type
= var
->type
->without_array();
3047 if (assigned_type
->base_type
!= type
->base_type
) {
3048 linker_error(prog
, "types do not match for aliased"
3049 " %ss %s and %s\n", string
,
3050 assigned
[i
]->name
, var
->name
);
3054 unsigned assigned_component_mask
=
3055 ((1 << assigned_type
->vector_elements
) - 1) <<
3056 assigned
[i
]->data
.location_frac
;
3057 unsigned component_mask
=
3058 ((1 << type
->vector_elements
) - 1) <<
3059 var
->data
.location_frac
;
3060 if (assigned_component_mask
& component_mask
) {
3061 linker_error(prog
, "overlapping component is "
3062 "assigned to %ss %s and %s "
3064 string
, assigned
[i
]->name
, var
->name
,
3065 var
->data
.location_frac
);
3070 } else if (target_index
== MESA_SHADER_FRAGMENT
||
3071 (prog
->IsES
&& prog
->data
->Version
>= 300)) {
3072 linker_error(prog
, "overlapping location is assigned "
3073 "to %s `%s' %d %d %d\n", string
, var
->name
,
3074 used_locations
, use_mask
, attr
);
3077 linker_warning(prog
, "overlapping location is assigned "
3078 "to %s `%s' %d %d %d\n", string
, var
->name
,
3079 used_locations
, use_mask
, attr
);
3083 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
3084 /* Only track assigned variables for non-ES fragment shaders
3085 * to avoid overflowing the array.
3087 * At most one variable per fragment output component should
3090 assert(assigned_attr
< ARRAY_SIZE(assigned
));
3091 assigned
[assigned_attr
] = var
;
3095 used_locations
|= (use_mask
<< attr
);
3097 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
3099 * "A program with more than the value of MAX_VERTEX_ATTRIBS
3100 * active attribute variables may fail to link, unless
3101 * device-dependent optimizations are able to make the program
3102 * fit within available hardware resources. For the purposes
3103 * of this test, attribute variables of the type dvec3, dvec4,
3104 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
3105 * count as consuming twice as many attributes as equivalent
3106 * single-precision types. While these types use the same number
3107 * of generic attributes as their single-precision equivalents,
3108 * implementations are permitted to consume two single-precision
3109 * vectors of internal storage for each three- or four-component
3110 * double-precision vector."
3112 * Mark this attribute slot as taking up twice as much space
3113 * so we can count it properly against limits. According to
3114 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
3115 * is optional behavior, but it seems preferable.
3117 if (var
->type
->without_array()->is_dual_slot())
3118 double_storage_locations
|= (use_mask
<< attr
);
3124 if (num_attr
>= max_index
) {
3125 linker_error(prog
, "too many %s (max %u)",
3126 target_index
== MESA_SHADER_VERTEX
?
3127 "vertex shader inputs" : "fragment shader outputs",
3131 to_assign
[num_attr
].slots
= slots
;
3132 to_assign
[num_attr
].var
= var
;
3139 if (target_index
== MESA_SHADER_VERTEX
) {
3140 unsigned total_attribs_size
=
3141 util_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
3142 util_bitcount(double_storage_locations
);
3143 if (total_attribs_size
> max_index
) {
3145 "attempt to use %d vertex attribute slots only %d available ",
3146 total_attribs_size
, max_index
);
3151 /* If all of the attributes were assigned locations by the application (or
3152 * are built-in attributes with fixed locations), return early. This should
3153 * be the common case.
3158 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
3160 if (target_index
== MESA_SHADER_VERTEX
) {
3161 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
3162 * only be explicitly assigned by via glBindAttribLocation. Mark it as
3163 * reserved to prevent it from being automatically allocated below.
3165 find_deref_visitor
find("gl_Vertex");
3167 if (find
.variable_found())
3168 used_locations
|= (1 << 0);
3171 for (unsigned i
= 0; i
< num_attr
; i
++) {
3172 /* Mask representing the contiguous slots that will be used by this
3175 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
3177 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
3180 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
3181 ? "vertex shader input" : "fragment shader output";
3184 "insufficient contiguous locations "
3185 "available for %s `%s'\n",
3186 string
, to_assign
[i
].var
->name
);
3190 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
3191 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
3192 used_locations
|= (use_mask
<< location
);
3194 if (to_assign
[i
].var
->type
->without_array()->is_dual_slot())
3195 double_storage_locations
|= (use_mask
<< location
);
3198 /* Now that we have all the locations, from the GL 4.5 core spec, section
3199 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
3200 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
3201 * as equivalent single-precision types.
3203 if (target_index
== MESA_SHADER_VERTEX
) {
3204 unsigned total_attribs_size
=
3205 util_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
3206 util_bitcount(double_storage_locations
);
3207 if (total_attribs_size
> max_index
) {
3209 "attempt to use %d vertex attribute slots only %d available ",
3210 total_attribs_size
, max_index
);
3219 * Match explicit locations of outputs to inputs and deactivate the
3220 * unmatch flag if found so we don't optimise them away.
3223 match_explicit_outputs_to_inputs(gl_linked_shader
*producer
,
3224 gl_linked_shader
*consumer
)
3226 glsl_symbol_table parameters
;
3227 ir_variable
*explicit_locations
[MAX_VARYINGS_INCL_PATCH
][4] =
3230 /* Find all shader outputs in the "producer" stage.
3232 foreach_in_list(ir_instruction
, node
, producer
->ir
) {
3233 ir_variable
*const var
= node
->as_variable();
3235 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_shader_out
))
3238 if (var
->data
.explicit_location
&&
3239 var
->data
.location
>= VARYING_SLOT_VAR0
) {
3240 const unsigned idx
= var
->data
.location
- VARYING_SLOT_VAR0
;
3241 if (explicit_locations
[idx
][var
->data
.location_frac
] == NULL
)
3242 explicit_locations
[idx
][var
->data
.location_frac
] = var
;
3244 /* Always match TCS outputs. They are shared by all invocations
3245 * within a patch and can be used as shared memory.
3247 if (producer
->Stage
== MESA_SHADER_TESS_CTRL
)
3248 var
->data
.is_unmatched_generic_inout
= 0;
3252 /* Match inputs to outputs */
3253 foreach_in_list(ir_instruction
, node
, consumer
->ir
) {
3254 ir_variable
*const input
= node
->as_variable();
3256 if ((input
== NULL
) || (input
->data
.mode
!= ir_var_shader_in
))
3259 ir_variable
*output
= NULL
;
3260 if (input
->data
.explicit_location
3261 && input
->data
.location
>= VARYING_SLOT_VAR0
) {
3262 output
= explicit_locations
[input
->data
.location
- VARYING_SLOT_VAR0
]
3263 [input
->data
.location_frac
];
3265 if (output
!= NULL
){
3266 input
->data
.is_unmatched_generic_inout
= 0;
3267 output
->data
.is_unmatched_generic_inout
= 0;
3274 * Store the gl_FragDepth layout in the gl_shader_program struct.
3277 store_fragdepth_layout(struct gl_shader_program
*prog
)
3279 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
3283 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
3285 /* We don't look up the gl_FragDepth symbol directly because if
3286 * gl_FragDepth is not used in the shader, it's removed from the IR.
3287 * However, the symbol won't be removed from the symbol table.
3289 * We're only interested in the cases where the variable is NOT removed
3292 foreach_in_list(ir_instruction
, node
, ir
) {
3293 ir_variable
*const var
= node
->as_variable();
3295 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
3299 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
3300 switch (var
->data
.depth_layout
) {
3301 case ir_depth_layout_none
:
3302 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
3304 case ir_depth_layout_any
:
3305 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
3307 case ir_depth_layout_greater
:
3308 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
3310 case ir_depth_layout_less
:
3311 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
3313 case ir_depth_layout_unchanged
:
3314 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
3325 * Validate the resources used by a program versus the implementation limits
3328 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3330 unsigned total_uniform_blocks
= 0;
3331 unsigned total_shader_storage_blocks
= 0;
3333 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3334 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3339 if (sh
->num_uniform_components
>
3340 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
3341 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3342 linker_warning(prog
, "Too many %s shader default uniform block "
3343 "components, but the driver will try to optimize "
3344 "them out; this is non-portable out-of-spec "
3346 _mesa_shader_stage_to_string(i
));
3348 linker_error(prog
, "Too many %s shader default uniform block "
3350 _mesa_shader_stage_to_string(i
));
3354 if (sh
->num_combined_uniform_components
>
3355 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
3356 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3357 linker_warning(prog
, "Too many %s shader uniform components, "
3358 "but the driver will try to optimize them out; "
3359 "this is non-portable out-of-spec behavior\n",
3360 _mesa_shader_stage_to_string(i
));
3362 linker_error(prog
, "Too many %s shader uniform components\n",
3363 _mesa_shader_stage_to_string(i
));
3367 total_shader_storage_blocks
+= sh
->Program
->info
.num_ssbos
;
3368 total_uniform_blocks
+= sh
->Program
->info
.num_ubos
;
3371 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
3372 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
3373 total_uniform_blocks
, ctx
->Const
.MaxCombinedUniformBlocks
);
3376 if (total_shader_storage_blocks
> ctx
->Const
.MaxCombinedShaderStorageBlocks
) {
3377 linker_error(prog
, "Too many combined shader storage blocks (%d/%d)\n",
3378 total_shader_storage_blocks
,
3379 ctx
->Const
.MaxCombinedShaderStorageBlocks
);
3382 for (unsigned i
= 0; i
< prog
->data
->NumUniformBlocks
; i
++) {
3383 if (prog
->data
->UniformBlocks
[i
].UniformBufferSize
>
3384 ctx
->Const
.MaxUniformBlockSize
) {
3385 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
3386 prog
->data
->UniformBlocks
[i
].Name
,
3387 prog
->data
->UniformBlocks
[i
].UniformBufferSize
,
3388 ctx
->Const
.MaxUniformBlockSize
);
3392 for (unsigned i
= 0; i
< prog
->data
->NumShaderStorageBlocks
; i
++) {
3393 if (prog
->data
->ShaderStorageBlocks
[i
].UniformBufferSize
>
3394 ctx
->Const
.MaxShaderStorageBlockSize
) {
3395 linker_error(prog
, "Shader storage block %s too big (%d/%d)\n",
3396 prog
->data
->ShaderStorageBlocks
[i
].Name
,
3397 prog
->data
->ShaderStorageBlocks
[i
].UniformBufferSize
,
3398 ctx
->Const
.MaxShaderStorageBlockSize
);
3404 link_calculate_subroutine_compat(struct gl_shader_program
*prog
)
3406 unsigned mask
= prog
->data
->linked_stages
;
3408 const int i
= u_bit_scan(&mask
);
3409 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3411 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineUniformRemapTable
; j
++) {
3412 if (p
->sh
.SubroutineUniformRemapTable
[j
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
)
3415 struct gl_uniform_storage
*uni
= p
->sh
.SubroutineUniformRemapTable
[j
];
3421 if (p
->sh
.NumSubroutineFunctions
== 0) {
3422 linker_error(prog
, "subroutine uniform %s defined but no valid functions found\n", uni
->type
->name
);
3425 for (unsigned f
= 0; f
< p
->sh
.NumSubroutineFunctions
; f
++) {
3426 struct gl_subroutine_function
*fn
= &p
->sh
.SubroutineFunctions
[f
];
3427 for (int k
= 0; k
< fn
->num_compat_types
; k
++) {
3428 if (fn
->types
[k
] == uni
->type
) {
3434 uni
->num_compatible_subroutines
= count
;
3440 check_subroutine_resources(struct gl_shader_program
*prog
)
3442 unsigned mask
= prog
->data
->linked_stages
;
3444 const int i
= u_bit_scan(&mask
);
3445 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3447 if (p
->sh
.NumSubroutineUniformRemapTable
> MAX_SUBROUTINE_UNIFORM_LOCATIONS
) {
3448 linker_error(prog
, "Too many %s shader subroutine uniforms\n",
3449 _mesa_shader_stage_to_string(i
));
3454 * Validate shader image resources.
3457 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3459 unsigned total_image_units
= 0;
3460 unsigned fragment_outputs
= 0;
3461 unsigned total_shader_storage_blocks
= 0;
3463 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
3466 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3467 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3470 total_image_units
+= sh
->Program
->info
.num_images
;
3471 total_shader_storage_blocks
+= sh
->Program
->info
.num_ssbos
;
3473 if (i
== MESA_SHADER_FRAGMENT
) {
3474 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3475 ir_variable
*var
= node
->as_variable();
3476 if (var
&& var
->data
.mode
== ir_var_shader_out
)
3477 /* since there are no double fs outputs - pass false */
3478 fragment_outputs
+= var
->type
->count_attribute_slots(false);
3484 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
3485 linker_error(prog
, "Too many combined image uniforms\n");
3487 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
3488 ctx
->Const
.MaxCombinedShaderOutputResources
)
3489 linker_error(prog
, "Too many combined image uniforms, shader storage "
3490 " buffers and fragment outputs\n");
3495 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3496 * for a variable, checks for overlaps between other uniforms using explicit
3500 reserve_explicit_locations(struct gl_shader_program
*prog
,
3501 string_to_uint_map
*map
, ir_variable
*var
)
3503 unsigned slots
= var
->type
->uniform_locations();
3504 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3505 unsigned return_value
= slots
;
3507 /* Resize remap table if locations do not fit in the current one. */
3508 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
3509 prog
->UniformRemapTable
=
3510 reralloc(prog
, prog
->UniformRemapTable
,
3511 gl_uniform_storage
*,
3514 if (!prog
->UniformRemapTable
) {
3515 linker_error(prog
, "Out of memory during linking.\n");
3519 /* Initialize allocated space. */
3520 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
3521 prog
->UniformRemapTable
[i
] = NULL
;
3523 prog
->NumUniformRemapTable
= max_loc
+ 1;
3526 for (unsigned i
= 0; i
< slots
; i
++) {
3527 unsigned loc
= var
->data
.location
+ i
;
3529 /* Check if location is already used. */
3530 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3532 /* Possibly same uniform from a different stage, this is ok. */
3534 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
) {
3539 /* ARB_explicit_uniform_location specification states:
3541 * "No two default-block uniform variables in the program can have
3542 * the same location, even if they are unused, otherwise a compiler
3543 * or linker error will be generated."
3546 "location qualifier for uniform %s overlaps "
3547 "previously used location\n",
3552 /* Initialize location as inactive before optimization
3553 * rounds and location assignment.
3555 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3558 /* Note, base location used for arrays. */
3559 map
->put(var
->data
.location
, var
->name
);
3561 return return_value
;
3565 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3566 struct gl_program
*p
,
3569 unsigned slots
= var
->type
->uniform_locations();
3570 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3572 /* Resize remap table if locations do not fit in the current one. */
3573 if (max_loc
+ 1 > p
->sh
.NumSubroutineUniformRemapTable
) {
3574 p
->sh
.SubroutineUniformRemapTable
=
3575 reralloc(p
, p
->sh
.SubroutineUniformRemapTable
,
3576 gl_uniform_storage
*,
3579 if (!p
->sh
.SubroutineUniformRemapTable
) {
3580 linker_error(prog
, "Out of memory during linking.\n");
3584 /* Initialize allocated space. */
3585 for (unsigned i
= p
->sh
.NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3586 p
->sh
.SubroutineUniformRemapTable
[i
] = NULL
;
3588 p
->sh
.NumSubroutineUniformRemapTable
= max_loc
+ 1;
3591 for (unsigned i
= 0; i
< slots
; i
++) {
3592 unsigned loc
= var
->data
.location
+ i
;
3594 /* Check if location is already used. */
3595 if (p
->sh
.SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3597 /* ARB_explicit_uniform_location specification states:
3598 * "No two subroutine uniform variables can have the same location
3599 * in the same shader stage, otherwise a compiler or linker error
3600 * will be generated."
3603 "location qualifier for uniform %s overlaps "
3604 "previously used location\n",
3609 /* Initialize location as inactive before optimization
3610 * rounds and location assignment.
3612 p
->sh
.SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3618 * Check and reserve all explicit uniform locations, called before
3619 * any optimizations happen to handle also inactive uniforms and
3620 * inactive array elements that may get trimmed away.
3623 check_explicit_uniform_locations(struct gl_context
*ctx
,
3624 struct gl_shader_program
*prog
)
3626 prog
->NumExplicitUniformLocations
= 0;
3628 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3631 /* This map is used to detect if overlapping explicit locations
3632 * occur with the same uniform (from different stage) or a different one.
3634 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3637 linker_error(prog
, "Out of memory during linking.\n");
3641 unsigned entries_total
= 0;
3642 unsigned mask
= prog
->data
->linked_stages
;
3644 const int i
= u_bit_scan(&mask
);
3645 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3647 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
3648 ir_variable
*var
= node
->as_variable();
3649 if (!var
|| var
->data
.mode
!= ir_var_uniform
)
3652 if (var
->data
.explicit_location
) {
3654 if (var
->type
->without_array()->is_subroutine())
3655 ret
= reserve_subroutine_explicit_locations(prog
, p
, var
);
3657 int slots
= reserve_explicit_locations(prog
, uniform_map
,
3661 entries_total
+= slots
;
3672 link_util_update_empty_uniform_locations(prog
);
3675 prog
->NumExplicitUniformLocations
= entries_total
;
3678 /* Function checks if a variable var is a packed varying and
3679 * if given name is part of packed varying's list.
3681 * If a variable is a packed varying, it has a name like
3682 * 'packed:a,b,c' where a, b and c are separate variables.
3685 included_in_packed_varying(ir_variable
*var
, const char *name
)
3687 if (strncmp(var
->name
, "packed:", 7) != 0)
3690 char *list
= strdup(var
->name
+ 7);
3695 char *token
= strtok_r(list
, ",", &saveptr
);
3697 if (strcmp(token
, name
) == 0) {
3701 token
= strtok_r(NULL
, ",", &saveptr
);
3708 * Function builds a stage reference bitmask from variable name.
3711 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3716 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3717 * used for reference mask in gl_program_resource will need to be changed.
3719 assert(MESA_SHADER_STAGES
< 8);
3721 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3722 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
3726 /* Shader symbol table may contain variables that have
3727 * been optimized away. Search IR for the variable instead.
3729 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3730 ir_variable
*var
= node
->as_variable();
3732 unsigned baselen
= strlen(var
->name
);
3734 if (included_in_packed_varying(var
, name
)) {
3739 /* Type needs to match if specified, otherwise we might
3740 * pick a variable with same name but different interface.
3742 if (var
->data
.mode
!= mode
)
3745 if (strncmp(var
->name
, name
, baselen
) == 0) {
3746 /* Check for exact name matches but also check for arrays and
3749 if (name
[baselen
] == '\0' ||
3750 name
[baselen
] == '[' ||
3751 name
[baselen
] == '.') {
3763 * Create gl_shader_variable from ir_variable class.
3765 static gl_shader_variable
*
3766 create_shader_variable(struct gl_shader_program
*shProg
,
3767 const ir_variable
*in
,
3768 const char *name
, const glsl_type
*type
,
3769 const glsl_type
*interface_type
,
3770 bool use_implicit_location
, int location
,
3771 const glsl_type
*outermost_struct_type
)
3773 /* Allocate zero-initialized memory to ensure that bitfield padding
3776 gl_shader_variable
*out
= rzalloc(shProg
, struct gl_shader_variable
);
3780 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3781 * expect to see gl_VertexID in the program resource list. Pretend.
3783 if (in
->data
.mode
== ir_var_system_value
&&
3784 in
->data
.location
== SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
) {
3785 out
->name
= ralloc_strdup(shProg
, "gl_VertexID");
3786 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3787 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_OUTER
) ||
3788 (in
->data
.mode
== ir_var_system_value
&&
3789 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_OUTER
)) {
3790 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelOuter");
3791 type
= glsl_type::get_array_instance(glsl_type::float_type
, 4);
3792 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3793 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_INNER
) ||
3794 (in
->data
.mode
== ir_var_system_value
&&
3795 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_INNER
)) {
3796 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelInner");
3797 type
= glsl_type::get_array_instance(glsl_type::float_type
, 2);
3799 out
->name
= ralloc_strdup(shProg
, name
);
3805 /* The ARB_program_interface_query spec says:
3807 * "Not all active variables are assigned valid locations; the
3808 * following variables will have an effective location of -1:
3810 * * uniforms declared as atomic counters;
3812 * * members of a uniform block;
3814 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3816 * * inputs or outputs not declared with a "location" layout
3817 * qualifier, except for vertex shader inputs and fragment shader
3820 if (in
->type
->is_atomic_uint() || is_gl_identifier(in
->name
) ||
3821 !(in
->data
.explicit_location
|| use_implicit_location
)) {
3824 out
->location
= location
;
3828 out
->outermost_struct_type
= outermost_struct_type
;
3829 out
->interface_type
= interface_type
;
3830 out
->component
= in
->data
.location_frac
;
3831 out
->index
= in
->data
.index
;
3832 out
->patch
= in
->data
.patch
;
3833 out
->mode
= in
->data
.mode
;
3834 out
->interpolation
= in
->data
.interpolation
;
3835 out
->explicit_location
= in
->data
.explicit_location
;
3836 out
->precision
= in
->data
.precision
;
3842 add_shader_variable(const struct gl_context
*ctx
,
3843 struct gl_shader_program
*shProg
,
3844 struct set
*resource_set
,
3845 unsigned stage_mask
,
3846 GLenum programInterface
, ir_variable
*var
,
3847 const char *name
, const glsl_type
*type
,
3848 bool use_implicit_location
, int location
,
3849 bool inouts_share_location
,
3850 const glsl_type
*outermost_struct_type
= NULL
)
3852 const glsl_type
*interface_type
= var
->get_interface_type();
3854 if (outermost_struct_type
== NULL
) {
3855 if (var
->data
.from_named_ifc_block
) {
3856 const char *interface_name
= interface_type
->name
;
3858 if (interface_type
->is_array()) {
3859 /* Issue #16 of the ARB_program_interface_query spec says:
3861 * "* If a variable is a member of an interface block without an
3862 * instance name, it is enumerated using just the variable name.
3864 * * If a variable is a member of an interface block with an
3865 * instance name, it is enumerated as "BlockName.Member", where
3866 * "BlockName" is the name of the interface block (not the
3867 * instance name) and "Member" is the name of the variable."
3869 * In particular, it indicates that it should be "BlockName",
3870 * not "BlockName[array length]". The conformance suite and
3871 * dEQP both require this behavior.
3873 * Here, we unwrap the extra array level added by named interface
3874 * block array lowering so we have the correct variable type. We
3875 * also unwrap the interface type when constructing the name.
3877 * We leave interface_type the same so that ES 3.x SSO pipeline
3878 * validation can enforce the rules requiring array length to
3879 * match on interface blocks.
3881 type
= type
->fields
.array
;
3883 interface_name
= interface_type
->fields
.array
->name
;
3886 name
= ralloc_asprintf(shProg
, "%s.%s", interface_name
, name
);
3890 switch (type
->base_type
) {
3891 case GLSL_TYPE_STRUCT
: {
3892 /* The ARB_program_interface_query spec says:
3894 * "For an active variable declared as a structure, a separate entry
3895 * will be generated for each active structure member. The name of
3896 * each entry is formed by concatenating the name of the structure,
3897 * the "." character, and the name of the structure member. If a
3898 * structure member to enumerate is itself a structure or array,
3899 * these enumeration rules are applied recursively."
3901 if (outermost_struct_type
== NULL
)
3902 outermost_struct_type
= type
;
3904 unsigned field_location
= location
;
3905 for (unsigned i
= 0; i
< type
->length
; i
++) {
3906 const struct glsl_struct_field
*field
= &type
->fields
.structure
[i
];
3907 char *field_name
= ralloc_asprintf(shProg
, "%s.%s", name
, field
->name
);
3908 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3909 stage_mask
, programInterface
,
3910 var
, field_name
, field
->type
,
3911 use_implicit_location
, field_location
,
3912 false, outermost_struct_type
))
3915 field_location
+= field
->type
->count_attribute_slots(false);
3920 case GLSL_TYPE_ARRAY
: {
3921 /* The ARB_program_interface_query spec says:
3923 * "For an active variable declared as an array of basic types, a
3924 * single entry will be generated, with its name string formed by
3925 * concatenating the name of the array and the string "[0]"."
3927 * "For an active variable declared as an array of an aggregate data
3928 * type (structures or arrays), a separate entry will be generated
3929 * for each active array element, unless noted immediately below.
3930 * The name of each entry is formed by concatenating the name of
3931 * the array, the "[" character, an integer identifying the element
3932 * number, and the "]" character. These enumeration rules are
3933 * applied recursively, treating each enumerated array element as a
3934 * separate active variable."
3936 const struct glsl_type
*array_type
= type
->fields
.array
;
3937 if (array_type
->base_type
== GLSL_TYPE_STRUCT
||
3938 array_type
->base_type
== GLSL_TYPE_ARRAY
) {
3939 unsigned elem_location
= location
;
3940 unsigned stride
= inouts_share_location
? 0 :
3941 array_type
->count_attribute_slots(false);
3942 for (unsigned i
= 0; i
< type
->length
; i
++) {
3943 char *elem
= ralloc_asprintf(shProg
, "%s[%d]", name
, i
);
3944 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3945 stage_mask
, programInterface
,
3946 var
, elem
, array_type
,
3947 use_implicit_location
, elem_location
,
3948 false, outermost_struct_type
))
3950 elem_location
+= stride
;
3958 /* The ARB_program_interface_query spec says:
3960 * "For an active variable declared as a single instance of a basic
3961 * type, a single entry will be generated, using the variable name
3962 * from the shader source."
3964 gl_shader_variable
*sha_v
=
3965 create_shader_variable(shProg
, var
, name
, type
, interface_type
,
3966 use_implicit_location
, location
,
3967 outermost_struct_type
);
3971 return link_util_add_program_resource(shProg
, resource_set
,
3972 programInterface
, sha_v
, stage_mask
);
3978 inout_has_same_location(const ir_variable
*var
, unsigned stage
)
3980 if (!var
->data
.patch
&&
3981 ((var
->data
.mode
== ir_var_shader_out
&&
3982 stage
== MESA_SHADER_TESS_CTRL
) ||
3983 (var
->data
.mode
== ir_var_shader_in
&&
3984 (stage
== MESA_SHADER_TESS_CTRL
|| stage
== MESA_SHADER_TESS_EVAL
||
3985 stage
== MESA_SHADER_GEOMETRY
))))
3992 add_interface_variables(const struct gl_context
*ctx
,
3993 struct gl_shader_program
*shProg
,
3994 struct set
*resource_set
,
3995 unsigned stage
, GLenum programInterface
)
3997 exec_list
*ir
= shProg
->_LinkedShaders
[stage
]->ir
;
3999 foreach_in_list(ir_instruction
, node
, ir
) {
4000 ir_variable
*var
= node
->as_variable();
4002 if (!var
|| var
->data
.how_declared
== ir_var_hidden
)
4007 switch (var
->data
.mode
) {
4008 case ir_var_system_value
:
4009 case ir_var_shader_in
:
4010 if (programInterface
!= GL_PROGRAM_INPUT
)
4012 loc_bias
= (stage
== MESA_SHADER_VERTEX
) ? int(VERT_ATTRIB_GENERIC0
)
4013 : int(VARYING_SLOT_VAR0
);
4015 case ir_var_shader_out
:
4016 if (programInterface
!= GL_PROGRAM_OUTPUT
)
4018 loc_bias
= (stage
== MESA_SHADER_FRAGMENT
) ? int(FRAG_RESULT_DATA0
)
4019 : int(VARYING_SLOT_VAR0
);
4025 if (var
->data
.patch
)
4026 loc_bias
= int(VARYING_SLOT_PATCH0
);
4028 /* Skip packed varyings, packed varyings are handled separately
4029 * by add_packed_varyings.
4031 if (strncmp(var
->name
, "packed:", 7) == 0)
4034 /* Skip fragdata arrays, these are handled separately
4035 * by add_fragdata_arrays.
4037 if (strncmp(var
->name
, "gl_out_FragData", 15) == 0)
4040 const bool vs_input_or_fs_output
=
4041 (stage
== MESA_SHADER_VERTEX
&& var
->data
.mode
== ir_var_shader_in
) ||
4042 (stage
== MESA_SHADER_FRAGMENT
&& var
->data
.mode
== ir_var_shader_out
);
4044 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4045 1 << stage
, programInterface
,
4046 var
, var
->name
, var
->type
, vs_input_or_fs_output
,
4047 var
->data
.location
- loc_bias
,
4048 inout_has_same_location(var
, stage
)))
4055 add_packed_varyings(const struct gl_context
*ctx
,
4056 struct gl_shader_program
*shProg
,
4057 struct set
*resource_set
,
4058 int stage
, GLenum type
)
4060 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[stage
];
4063 if (!sh
|| !sh
->packed_varyings
)
4066 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
4067 ir_variable
*var
= node
->as_variable();
4069 switch (var
->data
.mode
) {
4070 case ir_var_shader_in
:
4071 iface
= GL_PROGRAM_INPUT
;
4073 case ir_var_shader_out
:
4074 iface
= GL_PROGRAM_OUTPUT
;
4077 unreachable("unexpected type");
4080 if (type
== iface
) {
4081 const int stage_mask
=
4082 build_stageref(shProg
, var
->name
, var
->data
.mode
);
4083 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4085 iface
, var
, var
->name
, var
->type
, false,
4086 var
->data
.location
- VARYING_SLOT_VAR0
,
4087 inout_has_same_location(var
, stage
)))
4096 add_fragdata_arrays(const struct gl_context
*ctx
,
4097 struct gl_shader_program
*shProg
,
4098 struct set
*resource_set
)
4100 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4102 if (!sh
|| !sh
->fragdata_arrays
)
4105 foreach_in_list(ir_instruction
, node
, sh
->fragdata_arrays
) {
4106 ir_variable
*var
= node
->as_variable();
4108 assert(var
->data
.mode
== ir_var_shader_out
);
4110 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4111 1 << MESA_SHADER_FRAGMENT
,
4112 GL_PROGRAM_OUTPUT
, var
, var
->name
, var
->type
,
4113 true, var
->data
.location
- FRAG_RESULT_DATA0
,
4122 * Builds up a list of program resources that point to existing
4126 build_program_resource_list(struct gl_context
*ctx
,
4127 struct gl_shader_program
*shProg
,
4128 bool add_packed_varyings_only
)
4130 /* Rebuild resource list. */
4131 if (shProg
->data
->ProgramResourceList
) {
4132 ralloc_free(shProg
->data
->ProgramResourceList
);
4133 shProg
->data
->ProgramResourceList
= NULL
;
4134 shProg
->data
->NumProgramResourceList
= 0;
4137 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
4139 /* Determine first input and final output stage. These are used to
4140 * detect which variables should be enumerated in the resource list
4141 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4143 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4144 if (!shProg
->_LinkedShaders
[i
])
4146 if (input_stage
== MESA_SHADER_STAGES
)
4151 /* Empty shader, no resources. */
4152 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
4155 struct set
*resource_set
= _mesa_pointer_set_create(NULL
);
4157 /* Program interface needs to expose varyings in case of SSO. */
4158 if (shProg
->SeparateShader
) {
4159 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4160 input_stage
, GL_PROGRAM_INPUT
))
4163 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4164 output_stage
, GL_PROGRAM_OUTPUT
))
4168 if (add_packed_varyings_only
)
4171 if (!add_fragdata_arrays(ctx
, shProg
, resource_set
))
4174 /* Add inputs and outputs to the resource list. */
4175 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4176 input_stage
, GL_PROGRAM_INPUT
))
4179 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4180 output_stage
, GL_PROGRAM_OUTPUT
))
4183 if (shProg
->last_vert_prog
) {
4184 struct gl_transform_feedback_info
*linked_xfb
=
4185 shProg
->last_vert_prog
->sh
.LinkedTransformFeedback
;
4187 /* Add transform feedback varyings. */
4188 if (linked_xfb
->NumVarying
> 0) {
4189 for (int i
= 0; i
< linked_xfb
->NumVarying
; i
++) {
4190 if (!link_util_add_program_resource(shProg
, resource_set
,
4191 GL_TRANSFORM_FEEDBACK_VARYING
,
4192 &linked_xfb
->Varyings
[i
], 0))
4197 /* Add transform feedback buffers. */
4198 for (unsigned i
= 0; i
< ctx
->Const
.MaxTransformFeedbackBuffers
; i
++) {
4199 if ((linked_xfb
->ActiveBuffers
>> i
) & 1) {
4200 linked_xfb
->Buffers
[i
].Binding
= i
;
4201 if (!link_util_add_program_resource(shProg
, resource_set
,
4202 GL_TRANSFORM_FEEDBACK_BUFFER
,
4203 &linked_xfb
->Buffers
[i
], 0))
4209 int top_level_array_base_offset
= -1;
4210 int top_level_array_size_in_bytes
= -1;
4211 int second_element_offset
= -1;
4212 int buffer_block_index
= -1;
4214 /* Add uniforms from uniform storage. */
4215 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4216 /* Do not add uniforms internally used by Mesa. */
4217 if (shProg
->data
->UniformStorage
[i
].hidden
)
4220 bool is_shader_storage
=
4221 shProg
->data
->UniformStorage
[i
].is_shader_storage
;
4222 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
4223 if (!link_util_should_add_buffer_variable(shProg
,
4224 &shProg
->data
->UniformStorage
[i
],
4225 top_level_array_base_offset
,
4226 top_level_array_size_in_bytes
,
4227 second_element_offset
,
4228 buffer_block_index
))
4231 if (is_shader_storage
) {
4232 /* From the OpenGL 4.6 specification, 7.3.1.1 Naming Active Resources:
4234 * "For an active shader storage block member declared as an array
4235 * of an aggregate type, an entry will be generated only for the
4236 * first array element, regardless of its type. Such block members
4237 * are referred to as top-level arrays. If the block member is an
4238 * aggregate type, the enumeration rules are then applied
4241 * Below we update our tracking values used by
4242 * link_util_should_add_buffer_variable(). We only want to reset the
4243 * offsets once we have moved past the first element.
4245 if (shProg
->data
->UniformStorage
[i
].offset
>= second_element_offset
) {
4246 top_level_array_base_offset
=
4247 shProg
->data
->UniformStorage
[i
].offset
;
4249 top_level_array_size_in_bytes
=
4250 shProg
->data
->UniformStorage
[i
].top_level_array_size
*
4251 shProg
->data
->UniformStorage
[i
].top_level_array_stride
;
4253 /* Set or reset the second element offset. For non arrays this
4254 * will be set to -1.
4256 second_element_offset
= top_level_array_size_in_bytes
?
4257 top_level_array_base_offset
+
4258 shProg
->data
->UniformStorage
[i
].top_level_array_stride
: -1;
4261 buffer_block_index
= shProg
->data
->UniformStorage
[i
].block_index
;
4264 uint8_t stageref
= shProg
->data
->UniformStorage
[i
].active_shader_mask
;
4265 if (!link_util_add_program_resource(shProg
, resource_set
, type
,
4266 &shProg
->data
->UniformStorage
[i
], stageref
))
4270 /* Add program uniform blocks. */
4271 for (unsigned i
= 0; i
< shProg
->data
->NumUniformBlocks
; i
++) {
4272 if (!link_util_add_program_resource(shProg
, resource_set
, GL_UNIFORM_BLOCK
,
4273 &shProg
->data
->UniformBlocks
[i
], 0))
4277 /* Add program shader storage blocks. */
4278 for (unsigned i
= 0; i
< shProg
->data
->NumShaderStorageBlocks
; i
++) {
4279 if (!link_util_add_program_resource(shProg
, resource_set
, GL_SHADER_STORAGE_BLOCK
,
4280 &shProg
->data
->ShaderStorageBlocks
[i
], 0))
4284 /* Add atomic counter buffers. */
4285 for (unsigned i
= 0; i
< shProg
->data
->NumAtomicBuffers
; i
++) {
4286 if (!link_util_add_program_resource(shProg
, resource_set
, GL_ATOMIC_COUNTER_BUFFER
,
4287 &shProg
->data
->AtomicBuffers
[i
], 0))
4291 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4293 if (!shProg
->data
->UniformStorage
[i
].hidden
)
4296 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
4297 if (!shProg
->data
->UniformStorage
[i
].opaque
[j
].active
||
4298 !shProg
->data
->UniformStorage
[i
].type
->is_subroutine())
4301 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
4302 /* add shader subroutines */
4303 if (!link_util_add_program_resource(shProg
, resource_set
,
4304 type
, &shProg
->data
->UniformStorage
[i
], 0))
4309 unsigned mask
= shProg
->data
->linked_stages
;
4311 const int i
= u_bit_scan(&mask
);
4312 struct gl_program
*p
= shProg
->_LinkedShaders
[i
]->Program
;
4314 GLuint type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
4315 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4316 if (!link_util_add_program_resource(shProg
, resource_set
,
4317 type
, &p
->sh
.SubroutineFunctions
[j
], 0))
4322 _mesa_set_destroy(resource_set
, NULL
);
4326 * This check is done to make sure we allow only constant expression
4327 * indexing and "constant-index-expression" (indexing with an expression
4328 * that includes loop induction variable).
4331 validate_sampler_array_indexing(struct gl_context
*ctx
,
4332 struct gl_shader_program
*prog
)
4334 dynamic_sampler_array_indexing_visitor v
;
4335 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4336 if (prog
->_LinkedShaders
[i
] == NULL
)
4339 bool no_dynamic_indexing
=
4340 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
4342 /* Search for array derefs in shader. */
4343 v
.run(prog
->_LinkedShaders
[i
]->ir
);
4344 if (v
.uses_dynamic_sampler_array_indexing()) {
4345 const char *msg
= "sampler arrays indexed with non-constant "
4346 "expressions is forbidden in GLSL %s %u";
4347 /* Backend has indicated that it has no dynamic indexing support. */
4348 if (no_dynamic_indexing
) {
4349 linker_error(prog
, msg
, prog
->IsES
? "ES" : "",
4350 prog
->data
->Version
);
4353 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "",
4354 prog
->data
->Version
);
4362 link_assign_subroutine_types(struct gl_shader_program
*prog
)
4364 unsigned mask
= prog
->data
->linked_stages
;
4366 const int i
= u_bit_scan(&mask
);
4367 gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
4369 p
->sh
.MaxSubroutineFunctionIndex
= 0;
4370 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
4371 ir_function
*fn
= node
->as_function();
4375 if (fn
->is_subroutine
)
4376 p
->sh
.NumSubroutineUniformTypes
++;
4378 if (!fn
->num_subroutine_types
)
4381 /* these should have been calculated earlier. */
4382 assert(fn
->subroutine_index
!= -1);
4383 if (p
->sh
.NumSubroutineFunctions
+ 1 > MAX_SUBROUTINES
) {
4384 linker_error(prog
, "Too many subroutine functions declared.\n");
4387 p
->sh
.SubroutineFunctions
= reralloc(p
, p
->sh
.SubroutineFunctions
,
4388 struct gl_subroutine_function
,
4389 p
->sh
.NumSubroutineFunctions
+ 1);
4390 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].name
= ralloc_strdup(p
, fn
->name
);
4391 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
4392 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
=
4393 ralloc_array(p
, const struct glsl_type
*,
4394 fn
->num_subroutine_types
);
4396 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4399 * "Each subroutine with an index qualifier in the shader must be
4400 * given a unique index, otherwise a compile or link error will be
4403 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4404 if (p
->sh
.SubroutineFunctions
[j
].index
!= -1 &&
4405 p
->sh
.SubroutineFunctions
[j
].index
== fn
->subroutine_index
) {
4406 linker_error(prog
, "each subroutine index qualifier in the "
4407 "shader must be unique\n");
4411 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].index
=
4412 fn
->subroutine_index
;
4414 if (fn
->subroutine_index
> (int)p
->sh
.MaxSubroutineFunctionIndex
)
4415 p
->sh
.MaxSubroutineFunctionIndex
= fn
->subroutine_index
;
4417 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
4418 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
4419 p
->sh
.NumSubroutineFunctions
++;
4425 verify_subroutine_associated_funcs(struct gl_shader_program
*prog
)
4427 unsigned mask
= prog
->data
->linked_stages
;
4429 const int i
= u_bit_scan(&mask
);
4430 gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
4431 glsl_symbol_table
*symbols
= prog
->_LinkedShaders
[i
]->symbols
;
4433 /* Section 6.1.2 (Subroutines) of the GLSL 4.00 spec says:
4435 * "A program will fail to compile or link if any shader
4436 * or stage contains two or more functions with the same
4437 * name if the name is associated with a subroutine type."
4439 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4440 unsigned definitions
= 0;
4441 char *name
= p
->sh
.SubroutineFunctions
[j
].name
;
4442 ir_function
*fn
= symbols
->get_function(name
);
4444 /* Calculate number of function definitions with the same name */
4445 foreach_in_list(ir_function_signature
, sig
, &fn
->signatures
) {
4446 if (sig
->is_defined
) {
4447 if (++definitions
> 1) {
4448 linker_error(prog
, "%s shader contains two or more function "
4449 "definitions with name `%s', which is "
4450 "associated with a subroutine type.\n",
4451 _mesa_shader_stage_to_string(i
),
4463 set_always_active_io(exec_list
*ir
, ir_variable_mode io_mode
)
4465 assert(io_mode
== ir_var_shader_in
|| io_mode
== ir_var_shader_out
);
4467 foreach_in_list(ir_instruction
, node
, ir
) {
4468 ir_variable
*const var
= node
->as_variable();
4470 if (var
== NULL
|| var
->data
.mode
!= io_mode
)
4473 /* Don't set always active on builtins that haven't been redeclared */
4474 if (var
->data
.how_declared
== ir_var_declared_implicitly
)
4477 var
->data
.always_active_io
= true;
4482 * When separate shader programs are enabled, only input/outputs between
4483 * the stages of a multi-stage separate program can be safely removed
4484 * from the shader interface. Other inputs/outputs must remain active.
4487 disable_varying_optimizations_for_sso(struct gl_shader_program
*prog
)
4489 unsigned first
, last
;
4490 assert(prog
->SeparateShader
);
4492 first
= MESA_SHADER_STAGES
;
4495 /* Determine first and last stage. Excluding the compute stage */
4496 for (unsigned i
= 0; i
< MESA_SHADER_COMPUTE
; i
++) {
4497 if (!prog
->_LinkedShaders
[i
])
4499 if (first
== MESA_SHADER_STAGES
)
4504 if (first
== MESA_SHADER_STAGES
)
4507 for (unsigned stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4508 gl_linked_shader
*sh
= prog
->_LinkedShaders
[stage
];
4512 /* Prevent the removal of inputs to the first and outputs from the last
4513 * stage, unless they are the initial pipeline inputs or final pipeline
4514 * outputs, respectively.
4516 * The removal of IO between shaders in the same program is always
4519 if (stage
== first
&& stage
!= MESA_SHADER_VERTEX
)
4520 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4521 if (stage
== last
&& stage
!= MESA_SHADER_FRAGMENT
)
4522 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4527 link_and_validate_uniforms(struct gl_context
*ctx
,
4528 struct gl_shader_program
*prog
)
4530 update_array_sizes(prog
);
4531 link_assign_uniform_locations(prog
, ctx
);
4533 if (prog
->data
->LinkStatus
== LINKING_FAILURE
)
4536 link_calculate_subroutine_compat(prog
);
4537 check_resources(ctx
, prog
);
4538 check_subroutine_resources(prog
);
4540 if (!ctx
->Const
.UseNIRGLSLLinker
) {
4541 check_image_resources(ctx
, prog
);
4542 link_assign_atomic_counter_resources(ctx
, prog
);
4543 link_check_atomic_counter_resources(ctx
, prog
);
4548 link_varyings_and_uniforms(unsigned first
, unsigned last
,
4549 struct gl_context
*ctx
,
4550 struct gl_shader_program
*prog
, void *mem_ctx
)
4552 /* Mark all generic shader inputs and outputs as unpaired. */
4553 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4554 if (prog
->_LinkedShaders
[i
] != NULL
) {
4555 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
4559 unsigned prev
= first
;
4560 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4561 if (prog
->_LinkedShaders
[i
] == NULL
)
4564 match_explicit_outputs_to_inputs(prog
->_LinkedShaders
[prev
],
4565 prog
->_LinkedShaders
[i
]);
4569 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4570 MESA_SHADER_VERTEX
, true)) {
4574 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4575 MESA_SHADER_FRAGMENT
, true)) {
4579 prog
->last_vert_prog
= NULL
;
4580 for (int i
= MESA_SHADER_GEOMETRY
; i
>= MESA_SHADER_VERTEX
; i
--) {
4581 if (prog
->_LinkedShaders
[i
] == NULL
)
4584 prog
->last_vert_prog
= prog
->_LinkedShaders
[i
]->Program
;
4588 if (!link_varyings(prog
, first
, last
, ctx
, mem_ctx
))
4591 link_and_validate_uniforms(ctx
, prog
);
4593 if (!prog
->data
->LinkStatus
)
4596 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4597 if (prog
->_LinkedShaders
[i
] == NULL
)
4600 const struct gl_shader_compiler_options
*options
=
4601 &ctx
->Const
.ShaderCompilerOptions
[i
];
4603 if (options
->LowerBufferInterfaceBlocks
)
4604 lower_ubo_reference(prog
->_LinkedShaders
[i
],
4605 options
->ClampBlockIndicesToArrayBounds
,
4606 ctx
->Const
.UseSTD430AsDefaultPacking
);
4608 if (i
== MESA_SHADER_COMPUTE
)
4609 lower_shared_reference(ctx
, prog
, prog
->_LinkedShaders
[i
]);
4611 lower_vector_derefs(prog
->_LinkedShaders
[i
]);
4612 do_vec_index_to_swizzle(prog
->_LinkedShaders
[i
]->ir
);
4619 linker_optimisation_loop(struct gl_context
*ctx
, exec_list
*ir
,
4622 if (ctx
->Const
.GLSLOptimizeConservatively
) {
4623 /* Run it just once. */
4624 do_common_optimization(ir
, true, false,
4625 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4626 ctx
->Const
.NativeIntegers
);
4628 /* Repeat it until it stops making changes. */
4629 while (do_common_optimization(ir
, true, false,
4630 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4631 ctx
->Const
.NativeIntegers
))
4637 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
4639 prog
->data
->LinkStatus
= LINKING_SUCCESS
; /* All error paths will set this to false */
4640 prog
->data
->Validated
= false;
4642 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4644 * "Linking can fail for a variety of reasons as specified in the
4645 * OpenGL Shading Language Specification, as well as any of the
4646 * following reasons:
4648 * - No shader objects are attached to program."
4650 * The Compatibility Profile specification does not list the error. In
4651 * Compatibility Profile missing shader stages are replaced by
4652 * fixed-function. This applies to the case where all stages are
4655 if (prog
->NumShaders
== 0) {
4656 if (ctx
->API
!= API_OPENGL_COMPAT
)
4657 linker_error(prog
, "no shaders attached to the program\n");
4661 #ifdef ENABLE_SHADER_CACHE
4662 if (shader_cache_read_program_metadata(ctx
, prog
))
4666 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
4668 prog
->ARB_fragment_coord_conventions_enable
= false;
4670 /* Separate the shaders into groups based on their type.
4672 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
4673 unsigned num_shaders
[MESA_SHADER_STAGES
];
4675 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4676 shader_list
[i
] = (struct gl_shader
**)
4677 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
4681 unsigned min_version
= UINT_MAX
;
4682 unsigned max_version
= 0;
4683 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
4684 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
4685 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
4687 if (!ctx
->Const
.AllowGLSLRelaxedES
&&
4688 prog
->Shaders
[i
]->IsES
!= prog
->Shaders
[0]->IsES
) {
4689 linker_error(prog
, "all shaders must use same shading "
4690 "language version\n");
4694 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
4695 prog
->ARB_fragment_coord_conventions_enable
= true;
4698 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
4699 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
4700 num_shaders
[shader_type
]++;
4703 /* In desktop GLSL, different shader versions may be linked together. In
4704 * GLSL ES, all shader versions must be the same.
4706 if (!ctx
->Const
.AllowGLSLRelaxedES
&& prog
->Shaders
[0]->IsES
&&
4707 min_version
!= max_version
) {
4708 linker_error(prog
, "all shaders must use same shading "
4709 "language version\n");
4713 prog
->data
->Version
= max_version
;
4714 prog
->IsES
= prog
->Shaders
[0]->IsES
;
4716 /* Some shaders have to be linked with some other shaders present.
4718 if (!prog
->SeparateShader
) {
4719 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
4720 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4721 linker_error(prog
, "Geometry shader must be linked with "
4725 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4726 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4727 linker_error(prog
, "Tessellation evaluation shader must be linked "
4728 "with vertex shader\n");
4731 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4732 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4733 linker_error(prog
, "Tessellation control shader must be linked with "
4738 /* Section 7.3 of the OpenGL ES 3.2 specification says:
4740 * "Linking can fail for [...] any of the following reasons:
4742 * * program contains an object to form a tessellation control
4743 * shader [...] and [...] the program is not separable and
4744 * contains no object to form a tessellation evaluation shader"
4746 * The OpenGL spec is contradictory. It allows linking without a tess
4747 * eval shader, but that can only be used with transform feedback and
4748 * rasterization disabled. However, transform feedback isn't allowed
4749 * with GL_PATCHES, so it can't be used.
4751 * More investigation showed that the idea of transform feedback after
4752 * a tess control shader was dropped, because some hw vendors couldn't
4753 * support tessellation without a tess eval shader, but the linker
4754 * section wasn't updated to reflect that.
4756 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4759 * Do what's reasonable and always require a tess eval shader if a tess
4760 * control shader is present.
4762 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4763 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0) {
4764 linker_error(prog
, "Tessellation control shader must be linked with "
4765 "tessellation evaluation shader\n");
4770 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4771 num_shaders
[MESA_SHADER_TESS_CTRL
] == 0) {
4772 linker_error(prog
, "GLSL ES requires non-separable programs "
4773 "containing a tessellation evaluation shader to also "
4774 "be linked with a tessellation control shader\n");
4780 /* Compute shaders have additional restrictions. */
4781 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
4782 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
4783 linker_error(prog
, "Compute shaders may not be linked with any other "
4784 "type of shader\n");
4787 /* Link all shaders for a particular stage and validate the result.
4789 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4790 if (num_shaders
[stage
] > 0) {
4791 gl_linked_shader
*const sh
=
4792 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
4793 num_shaders
[stage
], false);
4795 if (!prog
->data
->LinkStatus
) {
4797 _mesa_delete_linked_shader(ctx
, sh
);
4802 case MESA_SHADER_VERTEX
:
4803 validate_vertex_shader_executable(prog
, sh
, ctx
);
4805 case MESA_SHADER_TESS_CTRL
:
4806 /* nothing to be done */
4808 case MESA_SHADER_TESS_EVAL
:
4809 validate_tess_eval_shader_executable(prog
, sh
, ctx
);
4811 case MESA_SHADER_GEOMETRY
:
4812 validate_geometry_shader_executable(prog
, sh
, ctx
);
4814 case MESA_SHADER_FRAGMENT
:
4815 validate_fragment_shader_executable(prog
, sh
);
4818 if (!prog
->data
->LinkStatus
) {
4820 _mesa_delete_linked_shader(ctx
, sh
);
4824 prog
->_LinkedShaders
[stage
] = sh
;
4825 prog
->data
->linked_stages
|= 1 << stage
;
4829 /* Here begins the inter-stage linking phase. Some initial validation is
4830 * performed, then locations are assigned for uniforms, attributes, and
4833 cross_validate_uniforms(ctx
, prog
);
4834 if (!prog
->data
->LinkStatus
)
4837 unsigned first
, last
, prev
;
4839 first
= MESA_SHADER_STAGES
;
4842 /* Determine first and last stage. */
4843 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4844 if (!prog
->_LinkedShaders
[i
])
4846 if (first
== MESA_SHADER_STAGES
)
4851 check_explicit_uniform_locations(ctx
, prog
);
4852 link_assign_subroutine_types(prog
);
4853 verify_subroutine_associated_funcs(prog
);
4855 if (!prog
->data
->LinkStatus
)
4858 resize_tes_inputs(ctx
, prog
);
4860 /* Validate the inputs of each stage with the output of the preceding
4864 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4865 if (prog
->_LinkedShaders
[i
] == NULL
)
4868 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
4869 prog
->_LinkedShaders
[i
]);
4870 if (!prog
->data
->LinkStatus
)
4873 cross_validate_outputs_to_inputs(ctx
, prog
,
4874 prog
->_LinkedShaders
[prev
],
4875 prog
->_LinkedShaders
[i
]);
4876 if (!prog
->data
->LinkStatus
)
4882 /* The cross validation of outputs/inputs above validates interstage
4883 * explicit locations. We need to do this also for the inputs in the first
4884 * stage and outputs of the last stage included in the program, since there
4885 * is no cross validation for these.
4887 validate_first_and_last_interface_explicit_locations(ctx
, prog
,
4888 (gl_shader_stage
) first
,
4889 (gl_shader_stage
) last
);
4891 /* Cross-validate uniform blocks between shader stages */
4892 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
);
4893 if (!prog
->data
->LinkStatus
)
4896 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4897 if (prog
->_LinkedShaders
[i
] != NULL
)
4898 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
4901 if (prog
->IsES
&& prog
->data
->Version
== 100)
4902 if (!validate_invariant_builtins(prog
,
4903 prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
4904 prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]))
4907 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4908 * it before optimization because we want most of the checks to get
4909 * dropped thanks to constant propagation.
4911 * This rule also applies to GLSL ES 3.00.
4913 if (max_version
>= (prog
->IsES
? 300 : 130)) {
4914 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4916 lower_discard_flow(sh
->ir
);
4920 if (prog
->SeparateShader
)
4921 disable_varying_optimizations_for_sso(prog
);
4924 if (!interstage_cross_validate_uniform_blocks(prog
, false))
4928 if (!interstage_cross_validate_uniform_blocks(prog
, true))
4931 /* Do common optimization before assigning storage for attributes,
4932 * uniforms, and varyings. Later optimization could possibly make
4933 * some of that unused.
4935 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4936 if (prog
->_LinkedShaders
[i
] == NULL
)
4939 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
4940 if (!prog
->data
->LinkStatus
)
4943 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerCombinedClipCullDistance
) {
4944 lower_clip_cull_distance(prog
, prog
->_LinkedShaders
[i
]);
4947 if (ctx
->Const
.LowerTessLevel
) {
4948 lower_tess_level(prog
->_LinkedShaders
[i
]);
4951 /* Section 13.46 (Vertex Attribute Aliasing) of the OpenGL ES 3.2
4952 * specification says:
4954 * "In general, the behavior of GLSL ES should not depend on compiler
4955 * optimizations which might be implementation-dependent. Name matching
4956 * rules in most languages, including C++ from which GLSL ES is derived,
4957 * are based on declarations rather than use.
4959 * RESOLUTION: The existence of aliasing is determined by declarations
4960 * present after preprocessing."
4962 * Because of this rule, we do a 'dry-run' of attribute assignment for
4963 * vertex shader inputs here.
4965 if (prog
->IsES
&& i
== MESA_SHADER_VERTEX
) {
4966 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4967 MESA_SHADER_VERTEX
, false)) {
4972 /* Call opts before lowering const arrays to uniforms so we can const
4973 * propagate any elements accessed directly.
4975 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
4977 /* Call opts after lowering const arrays to copy propagate things. */
4978 if (ctx
->Const
.GLSLLowerConstArrays
&&
4979 lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
, i
,
4980 ctx
->Const
.Program
[i
].MaxUniformComponents
))
4981 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
4985 /* Validation for special cases where we allow sampler array indexing
4986 * with loop induction variable. This check emits a warning or error
4987 * depending if backend can handle dynamic indexing.
4989 if ((!prog
->IsES
&& prog
->data
->Version
< 130) ||
4990 (prog
->IsES
&& prog
->data
->Version
< 300)) {
4991 if (!validate_sampler_array_indexing(ctx
, prog
))
4995 /* Check and validate stream emissions in geometry shaders */
4996 validate_geometry_shader_emissions(ctx
, prog
);
4998 store_fragdepth_layout(prog
);
5000 if(!link_varyings_and_uniforms(first
, last
, ctx
, prog
, mem_ctx
))
5003 /* Linking varyings can cause some extra, useless swizzles to be generated
5004 * due to packing and unpacking.
5006 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5007 if (prog
->_LinkedShaders
[i
] == NULL
)
5010 optimize_swizzles(prog
->_LinkedShaders
[i
]->ir
);
5013 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
5014 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
5015 * anything about shader linking when one of the shaders (vertex or
5016 * fragment shader) is absent. So, the extension shouldn't change the
5017 * behavior specified in GLSL specification.
5019 * From OpenGL ES 3.1 specification (7.3 Program Objects):
5020 * "Linking can fail for a variety of reasons as specified in the
5021 * OpenGL ES Shading Language Specification, as well as any of the
5022 * following reasons:
5026 * * program contains objects to form either a vertex shader or
5027 * fragment shader, and program is not separable, and does not
5028 * contain objects to form both a vertex shader and fragment
5031 * However, the only scenario in 3.1+ where we don't require them both is
5032 * when we have a compute shader. For example:
5034 * - No shaders is a link error.
5035 * - Geom or Tess without a Vertex shader is a link error which means we
5036 * always require a Vertex shader and hence a Fragment shader.
5037 * - Finally a Compute shader linked with any other stage is a link error.
5039 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
&&
5040 num_shaders
[MESA_SHADER_COMPUTE
] == 0) {
5041 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
5042 linker_error(prog
, "program lacks a vertex shader\n");
5043 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
5044 linker_error(prog
, "program lacks a fragment shader\n");
5049 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5050 free(shader_list
[i
]);
5051 if (prog
->_LinkedShaders
[i
] == NULL
)
5054 /* Do a final validation step to make sure that the IR wasn't
5055 * invalidated by any modifications performed after intrastage linking.
5057 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
5059 /* Retain any live IR, but trash the rest. */
5060 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
5062 /* The symbol table in the linked shaders may contain references to
5063 * variables that were removed (e.g., unused uniforms). Since it may
5064 * contain junk, there is no possible valid use. Delete it and set the
5067 delete prog
->_LinkedShaders
[i
]->symbols
;
5068 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
5071 ralloc_free(mem_ctx
);