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 GLuint
*clip_distance_array_size
,
591 GLuint
*cull_distance_array_size
)
593 *clip_distance_array_size
= 0;
594 *cull_distance_array_size
= 0;
596 if (prog
->data
->Version
>= (prog
->IsES
? 300 : 130)) {
597 /* From section 7.1 (Vertex Shader Special Variables) of the
600 * "It is an error for a shader to statically write both
601 * gl_ClipVertex and gl_ClipDistance."
603 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
604 * gl_ClipVertex nor gl_ClipDistance. However with
605 * GL_EXT_clip_cull_distance, this functionality is exposed in ES 3.0.
607 find_variable
gl_ClipDistance("gl_ClipDistance");
608 find_variable
gl_CullDistance("gl_CullDistance");
609 find_variable
gl_ClipVertex("gl_ClipVertex");
610 find_variable
* const variables
[] = {
613 !prog
->IsES
? &gl_ClipVertex
: NULL
,
616 find_assignments(shader
->ir
, variables
);
618 /* From the ARB_cull_distance spec:
620 * It is a compile-time or link-time error for the set of shaders forming
621 * a program to statically read or write both gl_ClipVertex and either
622 * gl_ClipDistance or gl_CullDistance.
624 * This does not apply to GLSL ES shaders, since GLSL ES doesn't define
628 if (gl_ClipVertex
.found
&& gl_ClipDistance
.found
) {
629 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
630 "and `gl_ClipDistance'\n",
631 _mesa_shader_stage_to_string(shader
->Stage
));
634 if (gl_ClipVertex
.found
&& gl_CullDistance
.found
) {
635 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
636 "and `gl_CullDistance'\n",
637 _mesa_shader_stage_to_string(shader
->Stage
));
642 if (gl_ClipDistance
.found
) {
643 ir_variable
*clip_distance_var
=
644 shader
->symbols
->get_variable("gl_ClipDistance");
645 assert(clip_distance_var
);
646 *clip_distance_array_size
= clip_distance_var
->type
->length
;
648 if (gl_CullDistance
.found
) {
649 ir_variable
*cull_distance_var
=
650 shader
->symbols
->get_variable("gl_CullDistance");
651 assert(cull_distance_var
);
652 *cull_distance_array_size
= cull_distance_var
->type
->length
;
654 /* From the ARB_cull_distance spec:
656 * It is a compile-time or link-time error for the set of shaders forming
657 * a program to have the sum of the sizes of the gl_ClipDistance and
658 * gl_CullDistance arrays to be larger than
659 * gl_MaxCombinedClipAndCullDistances.
661 if ((*clip_distance_array_size
+ *cull_distance_array_size
) >
662 ctx
->Const
.MaxClipPlanes
) {
663 linker_error(prog
, "%s shader: the combined size of "
664 "'gl_ClipDistance' and 'gl_CullDistance' size cannot "
666 "gl_MaxCombinedClipAndCullDistances (%u)",
667 _mesa_shader_stage_to_string(shader
->Stage
),
668 ctx
->Const
.MaxClipPlanes
);
675 * Verify that a vertex shader executable meets all semantic requirements.
677 * Also sets info.clip_distance_array_size and
678 * info.cull_distance_array_size as a side effect.
680 * \param shader Vertex shader executable to be verified
683 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
684 struct gl_linked_shader
*shader
,
685 struct gl_context
*ctx
)
690 /* From the GLSL 1.10 spec, page 48:
692 * "The variable gl_Position is available only in the vertex
693 * language and is intended for writing the homogeneous vertex
694 * position. All executions of a well-formed vertex shader
695 * executable must write a value into this variable. [...] The
696 * variable gl_Position is available only in the vertex
697 * language and is intended for writing the homogeneous vertex
698 * position. All executions of a well-formed vertex shader
699 * executable must write a value into this variable."
701 * while in GLSL 1.40 this text is changed to:
703 * "The variable gl_Position is available only in the vertex
704 * language and is intended for writing the homogeneous vertex
705 * position. It can be written at any time during shader
706 * execution. It may also be read back by a vertex shader
707 * after being written. This value will be used by primitive
708 * assembly, clipping, culling, and other fixed functionality
709 * operations, if present, that operate on primitives after
710 * vertex processing has occurred. Its value is undefined if
711 * the vertex shader executable does not write gl_Position."
713 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
714 * gl_Position is not an error.
716 if (prog
->data
->Version
< (prog
->IsES
? 300 : 140)) {
717 find_variable
gl_Position("gl_Position");
718 find_assignments(shader
->ir
, &gl_Position
);
719 if (!gl_Position
.found
) {
722 "vertex shader does not write to `gl_Position'. "
723 "Its value is undefined. \n");
726 "vertex shader does not write to `gl_Position'. \n");
732 analyze_clip_cull_usage(prog
, shader
, ctx
,
733 &shader
->Program
->info
.clip_distance_array_size
,
734 &shader
->Program
->info
.cull_distance_array_size
);
738 validate_tess_eval_shader_executable(struct gl_shader_program
*prog
,
739 struct gl_linked_shader
*shader
,
740 struct gl_context
*ctx
)
745 analyze_clip_cull_usage(prog
, shader
, ctx
,
746 &shader
->Program
->info
.clip_distance_array_size
,
747 &shader
->Program
->info
.cull_distance_array_size
);
752 * Verify that a fragment shader executable meets all semantic requirements
754 * \param shader Fragment shader executable to be verified
757 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
758 struct gl_linked_shader
*shader
)
763 find_variable
gl_FragColor("gl_FragColor");
764 find_variable
gl_FragData("gl_FragData");
765 find_variable
* const variables
[] = { &gl_FragColor
, &gl_FragData
, NULL
};
766 find_assignments(shader
->ir
, variables
);
768 if (gl_FragColor
.found
&& gl_FragData
.found
) {
769 linker_error(prog
, "fragment shader writes to both "
770 "`gl_FragColor' and `gl_FragData'\n");
775 * Verify that a geometry shader executable meets all semantic requirements
777 * Also sets prog->Geom.VerticesIn, and info.clip_distance_array_sizeand
778 * info.cull_distance_array_size as a side effect.
780 * \param shader Geometry shader executable to be verified
783 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
784 struct gl_linked_shader
*shader
,
785 struct gl_context
*ctx
)
790 unsigned num_vertices
=
791 vertices_per_prim(shader
->Program
->info
.gs
.input_primitive
);
792 prog
->Geom
.VerticesIn
= num_vertices
;
794 analyze_clip_cull_usage(prog
, shader
, ctx
,
795 &shader
->Program
->info
.clip_distance_array_size
,
796 &shader
->Program
->info
.cull_distance_array_size
);
800 * Check if geometry shaders emit to non-zero streams and do corresponding
804 validate_geometry_shader_emissions(struct gl_context
*ctx
,
805 struct gl_shader_program
*prog
)
807 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
];
810 find_emit_vertex_visitor
emit_vertex(ctx
->Const
.MaxVertexStreams
- 1);
811 emit_vertex
.run(sh
->ir
);
812 if (emit_vertex
.error()) {
813 linker_error(prog
, "Invalid call %s(%d). Accepted values for the "
814 "stream parameter are in the range [0, %d].\n",
815 emit_vertex
.error_func(),
816 emit_vertex
.error_stream(),
817 ctx
->Const
.MaxVertexStreams
- 1);
819 prog
->Geom
.UsesStreams
= emit_vertex
.uses_streams();
820 prog
->Geom
.UsesEndPrimitive
= emit_vertex
.uses_end_primitive();
822 /* From the ARB_gpu_shader5 spec:
824 * "Multiple vertex streams are supported only if the output primitive
825 * type is declared to be "points". A program will fail to link if it
826 * contains a geometry shader calling EmitStreamVertex() or
827 * EndStreamPrimitive() if its output primitive type is not "points".
829 * However, in the same spec:
831 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
832 * with <stream> set to zero."
836 * "The function EndPrimitive() is equivalent to calling
837 * EndStreamPrimitive() with <stream> set to zero."
839 * Since we can call EmitVertex() and EndPrimitive() when we output
840 * primitives other than points, calling EmitStreamVertex(0) or
841 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
842 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
843 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
846 if (prog
->Geom
.UsesStreams
&&
847 sh
->Program
->info
.gs
.output_primitive
!= GL_POINTS
) {
848 linker_error(prog
, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
849 "with n>0 requires point output\n");
855 validate_intrastage_arrays(struct gl_shader_program
*prog
,
856 ir_variable
*const var
,
857 ir_variable
*const existing
)
859 /* Consider the types to be "the same" if both types are arrays
860 * of the same type and one of the arrays is implicitly sized.
861 * In addition, set the type of the linked variable to the
862 * explicitly sized array.
864 if (var
->type
->is_array() && existing
->type
->is_array()) {
865 if ((var
->type
->fields
.array
== existing
->type
->fields
.array
) &&
866 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
867 if (var
->type
->length
!= 0) {
868 if ((int)var
->type
->length
<= existing
->data
.max_array_access
) {
869 linker_error(prog
, "%s `%s' declared as type "
870 "`%s' but outermost dimension has an index"
873 var
->name
, var
->type
->name
,
874 existing
->data
.max_array_access
);
876 existing
->type
= var
->type
;
878 } else if (existing
->type
->length
!= 0) {
879 if((int)existing
->type
->length
<= var
->data
.max_array_access
&&
880 !existing
->data
.from_ssbo_unsized_array
) {
881 linker_error(prog
, "%s `%s' declared as type "
882 "`%s' but outermost dimension has an index"
885 var
->name
, existing
->type
->name
,
886 var
->data
.max_array_access
);
897 * Perform validation of global variables used across multiple shaders
900 cross_validate_globals(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
901 struct exec_list
*ir
, glsl_symbol_table
*variables
,
904 foreach_in_list(ir_instruction
, node
, ir
) {
905 ir_variable
*const var
= node
->as_variable();
910 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
913 /* don't cross validate subroutine uniforms */
914 if (var
->type
->contains_subroutine())
917 /* Don't cross validate interface instances. These are only relevant
918 * inside a shader. The cross validation is done at the Interface Block
921 if (var
->is_interface_instance())
924 /* Don't cross validate temporaries that are at global scope. These
925 * will eventually get pulled into the shaders 'main'.
927 if (var
->data
.mode
== ir_var_temporary
)
930 /* If a global with this name has already been seen, verify that the
931 * new instance has the same type. In addition, if the globals have
932 * initializers, the values of the initializers must be the same.
934 ir_variable
*const existing
= variables
->get_variable(var
->name
);
935 if (existing
!= NULL
) {
936 /* Check if types match. */
937 if (var
->type
!= existing
->type
) {
938 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
939 /* If it is an unsized array in a Shader Storage Block,
940 * two different shaders can access to different elements.
941 * Because of that, they might be converted to different
942 * sized arrays, then check that they are compatible but
943 * ignore the array size.
945 if (!(var
->data
.mode
== ir_var_shader_storage
&&
946 var
->data
.from_ssbo_unsized_array
&&
947 existing
->data
.mode
== ir_var_shader_storage
&&
948 existing
->data
.from_ssbo_unsized_array
&&
949 var
->type
->gl_type
== existing
->type
->gl_type
)) {
950 linker_error(prog
, "%s `%s' declared as type "
951 "`%s' and type `%s'\n",
953 var
->name
, var
->type
->name
,
954 existing
->type
->name
);
960 if (var
->data
.explicit_location
) {
961 if (existing
->data
.explicit_location
962 && (var
->data
.location
!= existing
->data
.location
)) {
963 linker_error(prog
, "explicit locations for %s "
964 "`%s' have differing values\n",
965 mode_string(var
), var
->name
);
969 if (var
->data
.location_frac
!= existing
->data
.location_frac
) {
970 linker_error(prog
, "explicit components for %s `%s' have "
971 "differing values\n", mode_string(var
), var
->name
);
975 existing
->data
.location
= var
->data
.location
;
976 existing
->data
.explicit_location
= true;
978 /* Check if uniform with implicit location was marked explicit
979 * by earlier shader stage. If so, mark it explicit in this stage
980 * too to make sure later processing does not treat it as
983 if (existing
->data
.explicit_location
) {
984 var
->data
.location
= existing
->data
.location
;
985 var
->data
.explicit_location
= true;
989 /* From the GLSL 4.20 specification:
990 * "A link error will result if two compilation units in a program
991 * specify different integer-constant bindings for the same
992 * opaque-uniform name. However, it is not an error to specify a
993 * binding on some but not all declarations for the same name"
995 if (var
->data
.explicit_binding
) {
996 if (existing
->data
.explicit_binding
&&
997 var
->data
.binding
!= existing
->data
.binding
) {
998 linker_error(prog
, "explicit bindings for %s "
999 "`%s' have differing values\n",
1000 mode_string(var
), var
->name
);
1004 existing
->data
.binding
= var
->data
.binding
;
1005 existing
->data
.explicit_binding
= true;
1008 if (var
->type
->contains_atomic() &&
1009 var
->data
.offset
!= existing
->data
.offset
) {
1010 linker_error(prog
, "offset specifications for %s "
1011 "`%s' have differing values\n",
1012 mode_string(var
), var
->name
);
1016 /* Validate layout qualifiers for gl_FragDepth.
1018 * From the AMD/ARB_conservative_depth specs:
1020 * "If gl_FragDepth is redeclared in any fragment shader in a
1021 * program, it must be redeclared in all fragment shaders in
1022 * that program that have static assignments to
1023 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1024 * fragment shaders in a single program must have the same set
1027 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1028 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1029 bool layout_differs
=
1030 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1032 if (layout_declared
&& layout_differs
) {
1034 "All redeclarations of gl_FragDepth in all "
1035 "fragment shaders in a single program must have "
1036 "the same set of qualifiers.\n");
1039 if (var
->data
.used
&& layout_differs
) {
1041 "If gl_FragDepth is redeclared with a layout "
1042 "qualifier in any fragment shader, it must be "
1043 "redeclared with the same layout qualifier in "
1044 "all fragment shaders that have assignments to "
1049 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1051 * "If a shared global has multiple initializers, the
1052 * initializers must all be constant expressions, and they
1053 * must all have the same value. Otherwise, a link error will
1054 * result. (A shared global having only one initializer does
1055 * not require that initializer to be a constant expression.)"
1057 * Previous to 4.20 the GLSL spec simply said that initializers
1058 * must have the same value. In this case of non-constant
1059 * initializers, this was impossible to determine. As a result,
1060 * no vendor actually implemented that behavior. The 4.20
1061 * behavior matches the implemented behavior of at least one other
1062 * vendor, so we'll implement that for all GLSL versions.
1064 if (var
->constant_initializer
!= NULL
) {
1065 if (existing
->constant_initializer
!= NULL
) {
1066 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1067 linker_error(prog
, "initializers for %s "
1068 "`%s' have differing values\n",
1069 mode_string(var
), var
->name
);
1073 /* If the first-seen instance of a particular uniform did
1074 * not have an initializer but a later instance does,
1075 * replace the former with the later.
1077 variables
->replace_variable(existing
->name
, var
);
1081 if (var
->data
.has_initializer
) {
1082 if (existing
->data
.has_initializer
1083 && (var
->constant_initializer
== NULL
1084 || existing
->constant_initializer
== NULL
)) {
1086 "shared global variable `%s' has multiple "
1087 "non-constant initializers.\n",
1093 if (existing
->data
.explicit_invariant
!= var
->data
.explicit_invariant
) {
1094 linker_error(prog
, "declarations for %s `%s' have "
1095 "mismatching invariant qualifiers\n",
1096 mode_string(var
), var
->name
);
1099 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1100 linker_error(prog
, "declarations for %s `%s' have "
1101 "mismatching centroid qualifiers\n",
1102 mode_string(var
), var
->name
);
1105 if (existing
->data
.sample
!= var
->data
.sample
) {
1106 linker_error(prog
, "declarations for %s `%s` have "
1107 "mismatching sample qualifiers\n",
1108 mode_string(var
), var
->name
);
1111 if (existing
->data
.image_format
!= var
->data
.image_format
) {
1112 linker_error(prog
, "declarations for %s `%s` have "
1113 "mismatching image format qualifiers\n",
1114 mode_string(var
), var
->name
);
1118 /* Check the precision qualifier matches for uniform variables on
1121 if (!ctx
->Const
.AllowGLSLRelaxedES
&&
1122 prog
->IsES
&& !var
->get_interface_type() &&
1123 existing
->data
.precision
!= var
->data
.precision
) {
1124 if ((existing
->data
.used
&& var
->data
.used
) || prog
->data
->Version
>= 300) {
1125 linker_error(prog
, "declarations for %s `%s` have "
1126 "mismatching precision qualifiers\n",
1127 mode_string(var
), var
->name
);
1130 linker_warning(prog
, "declarations for %s `%s` have "
1131 "mismatching precision qualifiers\n",
1132 mode_string(var
), var
->name
);
1136 /* In OpenGL GLSL 3.20 spec, section 4.3.9:
1138 * "It is a link-time error if any particular shader interface
1141 * - two different blocks, each having no instance name, and each
1142 * having a member of the same name, or
1144 * - a variable outside a block, and a block with no instance name,
1145 * where the variable has the same name as a member in the block."
1147 const glsl_type
*var_itype
= var
->get_interface_type();
1148 const glsl_type
*existing_itype
= existing
->get_interface_type();
1149 if (var_itype
!= existing_itype
) {
1150 if (!var_itype
|| !existing_itype
) {
1151 linker_error(prog
, "declarations for %s `%s` are inside block "
1152 "`%s` and outside a block",
1153 mode_string(var
), var
->name
,
1154 var_itype
? var_itype
->name
: existing_itype
->name
);
1156 } else if (strcmp(var_itype
->name
, existing_itype
->name
) != 0) {
1157 linker_error(prog
, "declarations for %s `%s` are inside blocks "
1159 mode_string(var
), var
->name
,
1160 existing_itype
->name
,
1166 variables
->add_variable(var
);
1172 * Perform validation of uniforms used across multiple shader stages
1175 cross_validate_uniforms(struct gl_context
*ctx
,
1176 struct gl_shader_program
*prog
)
1178 glsl_symbol_table variables
;
1179 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1180 if (prog
->_LinkedShaders
[i
] == NULL
)
1183 cross_validate_globals(ctx
, prog
, prog
->_LinkedShaders
[i
]->ir
,
1189 * Accumulates the array of buffer blocks and checks that all definitions of
1190 * blocks agree on their contents.
1193 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
,
1196 int *InterfaceBlockStageIndex
[MESA_SHADER_STAGES
];
1197 struct gl_uniform_block
*blks
= NULL
;
1198 unsigned *num_blks
= validate_ssbo
? &prog
->data
->NumShaderStorageBlocks
:
1199 &prog
->data
->NumUniformBlocks
;
1201 unsigned max_num_buffer_blocks
= 0;
1202 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1203 if (prog
->_LinkedShaders
[i
]) {
1204 if (validate_ssbo
) {
1205 max_num_buffer_blocks
+=
1206 prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1208 max_num_buffer_blocks
+=
1209 prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1214 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1215 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1217 InterfaceBlockStageIndex
[i
] = new int[max_num_buffer_blocks
];
1218 for (unsigned int j
= 0; j
< max_num_buffer_blocks
; j
++)
1219 InterfaceBlockStageIndex
[i
][j
] = -1;
1224 unsigned sh_num_blocks
;
1225 struct gl_uniform_block
**sh_blks
;
1226 if (validate_ssbo
) {
1227 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1228 sh_blks
= sh
->Program
->sh
.ShaderStorageBlocks
;
1230 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1231 sh_blks
= sh
->Program
->sh
.UniformBlocks
;
1234 for (unsigned int j
= 0; j
< sh_num_blocks
; j
++) {
1235 int index
= link_cross_validate_uniform_block(prog
->data
, &blks
,
1236 num_blks
, sh_blks
[j
]);
1239 linker_error(prog
, "buffer block `%s' has mismatching "
1240 "definitions\n", sh_blks
[j
]->Name
);
1242 for (unsigned k
= 0; k
<= i
; k
++) {
1243 delete[] InterfaceBlockStageIndex
[k
];
1246 /* Reset the block count. This will help avoid various segfaults
1247 * from api calls that assume the array exists due to the count
1254 InterfaceBlockStageIndex
[i
][index
] = j
;
1258 /* Update per stage block pointers to point to the program list.
1259 * FIXME: We should be able to free the per stage blocks here.
1261 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1262 for (unsigned j
= 0; j
< *num_blks
; j
++) {
1263 int stage_index
= InterfaceBlockStageIndex
[i
][j
];
1265 if (stage_index
!= -1) {
1266 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1268 struct gl_uniform_block
**sh_blks
= validate_ssbo
?
1269 sh
->Program
->sh
.ShaderStorageBlocks
:
1270 sh
->Program
->sh
.UniformBlocks
;
1272 blks
[j
].stageref
|= sh_blks
[stage_index
]->stageref
;
1273 sh_blks
[stage_index
] = &blks
[j
];
1278 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1279 delete[] InterfaceBlockStageIndex
[i
];
1283 prog
->data
->ShaderStorageBlocks
= blks
;
1285 prog
->data
->UniformBlocks
= blks
;
1291 * Verifies the invariance of built-in special variables.
1294 validate_invariant_builtins(struct gl_shader_program
*prog
,
1295 const gl_linked_shader
*vert
,
1296 const gl_linked_shader
*frag
)
1298 const ir_variable
*var_vert
;
1299 const ir_variable
*var_frag
;
1305 * From OpenGL ES Shading Language 1.0 specification
1306 * (4.6.4 Invariance and Linkage):
1307 * "The invariance of varyings that are declared in both the vertex and
1308 * fragment shaders must match. For the built-in special variables,
1309 * gl_FragCoord can only be declared invariant if and only if
1310 * gl_Position is declared invariant. Similarly gl_PointCoord can only
1311 * be declared invariant if and only if gl_PointSize is declared
1312 * invariant. It is an error to declare gl_FrontFacing as invariant.
1313 * The invariance of gl_FrontFacing is the same as the invariance of
1316 var_frag
= frag
->symbols
->get_variable("gl_FragCoord");
1317 if (var_frag
&& var_frag
->data
.invariant
) {
1318 var_vert
= vert
->symbols
->get_variable("gl_Position");
1319 if (var_vert
&& !var_vert
->data
.invariant
) {
1321 "fragment shader built-in `%s' has invariant qualifier, "
1322 "but vertex shader built-in `%s' lacks invariant qualifier\n",
1323 var_frag
->name
, var_vert
->name
);
1328 var_frag
= frag
->symbols
->get_variable("gl_PointCoord");
1329 if (var_frag
&& var_frag
->data
.invariant
) {
1330 var_vert
= vert
->symbols
->get_variable("gl_PointSize");
1331 if (var_vert
&& !var_vert
->data
.invariant
) {
1333 "fragment shader built-in `%s' has invariant qualifier, "
1334 "but vertex shader built-in `%s' lacks invariant qualifier\n",
1335 var_frag
->name
, var_vert
->name
);
1340 var_frag
= frag
->symbols
->get_variable("gl_FrontFacing");
1341 if (var_frag
&& var_frag
->data
.invariant
) {
1343 "fragment shader built-in `%s' can not be declared as invariant\n",
1352 * Populates a shaders symbol table with all global declarations
1355 populate_symbol_table(gl_linked_shader
*sh
, glsl_symbol_table
*symbols
)
1357 sh
->symbols
= new(sh
) glsl_symbol_table
;
1359 _mesa_glsl_copy_symbols_from_table(sh
->ir
, symbols
, sh
->symbols
);
1364 * Remap variables referenced in an instruction tree
1366 * This is used when instruction trees are cloned from one shader and placed in
1367 * another. These trees will contain references to \c ir_variable nodes that
1368 * do not exist in the target shader. This function finds these \c ir_variable
1369 * references and replaces the references with matching variables in the target
1372 * If there is no matching variable in the target shader, a clone of the
1373 * \c ir_variable is made and added to the target shader. The new variable is
1374 * added to \b both the instruction stream and the symbol table.
1376 * \param inst IR tree that is to be processed.
1377 * \param symbols Symbol table containing global scope symbols in the
1379 * \param instructions Instruction stream where new variable declarations
1383 remap_variables(ir_instruction
*inst
, struct gl_linked_shader
*target
,
1386 class remap_visitor
: public ir_hierarchical_visitor
{
1388 remap_visitor(struct gl_linked_shader
*target
, hash_table
*temps
)
1390 this->target
= target
;
1391 this->symbols
= target
->symbols
;
1392 this->instructions
= target
->ir
;
1393 this->temps
= temps
;
1396 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1398 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1399 hash_entry
*entry
= _mesa_hash_table_search(temps
, ir
->var
);
1400 ir_variable
*var
= entry
? (ir_variable
*) entry
->data
: NULL
;
1402 assert(var
!= NULL
);
1404 return visit_continue
;
1407 ir_variable
*const existing
=
1408 this->symbols
->get_variable(ir
->var
->name
);
1409 if (existing
!= NULL
)
1412 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1414 this->symbols
->add_variable(copy
);
1415 this->instructions
->push_head(copy
);
1419 return visit_continue
;
1423 struct gl_linked_shader
*target
;
1424 glsl_symbol_table
*symbols
;
1425 exec_list
*instructions
;
1429 remap_visitor
v(target
, temps
);
1436 * Move non-declarations from one instruction stream to another
1438 * The intended usage pattern of this function is to pass the pointer to the
1439 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1440 * pointer) for \c last and \c false for \c make_copies on the first
1441 * call. Successive calls pass the return value of the previous call for
1442 * \c last and \c true for \c make_copies.
1444 * \param instructions Source instruction stream
1445 * \param last Instruction after which new instructions should be
1446 * inserted in the target instruction stream
1447 * \param make_copies Flag selecting whether instructions in \c instructions
1448 * should be copied (via \c ir_instruction::clone) into the
1449 * target list or moved.
1452 * The new "last" instruction in the target instruction stream. This pointer
1453 * is suitable for use as the \c last parameter of a later call to this
1457 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1458 bool make_copies
, gl_linked_shader
*target
)
1460 hash_table
*temps
= NULL
;
1463 temps
= _mesa_pointer_hash_table_create(NULL
);
1465 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1466 if (inst
->as_function())
1469 ir_variable
*var
= inst
->as_variable();
1470 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1473 assert(inst
->as_assignment()
1475 || inst
->as_if() /* for initializers with the ?: operator */
1476 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1479 inst
= inst
->clone(target
, NULL
);
1482 _mesa_hash_table_insert(temps
, var
, inst
);
1484 remap_variables(inst
, target
, temps
);
1489 last
->insert_after(inst
);
1494 _mesa_hash_table_destroy(temps
, NULL
);
1501 * This class is only used in link_intrastage_shaders() below but declaring
1502 * it inside that function leads to compiler warnings with some versions of
1505 class array_sizing_visitor
: public deref_type_updater
{
1507 array_sizing_visitor()
1508 : mem_ctx(ralloc_context(NULL
)),
1509 unnamed_interfaces(_mesa_pointer_hash_table_create(NULL
))
1513 ~array_sizing_visitor()
1515 _mesa_hash_table_destroy(this->unnamed_interfaces
, NULL
);
1516 ralloc_free(this->mem_ctx
);
1519 virtual ir_visitor_status
visit(ir_variable
*var
)
1521 const glsl_type
*type_without_array
;
1522 bool implicit_sized_array
= var
->data
.implicit_sized_array
;
1523 fixup_type(&var
->type
, var
->data
.max_array_access
,
1524 var
->data
.from_ssbo_unsized_array
,
1525 &implicit_sized_array
);
1526 var
->data
.implicit_sized_array
= implicit_sized_array
;
1527 type_without_array
= var
->type
->without_array();
1528 if (var
->type
->is_interface()) {
1529 if (interface_contains_unsized_arrays(var
->type
)) {
1530 const glsl_type
*new_type
=
1531 resize_interface_members(var
->type
,
1532 var
->get_max_ifc_array_access(),
1533 var
->is_in_shader_storage_block());
1534 var
->type
= new_type
;
1535 var
->change_interface_type(new_type
);
1537 } else if (type_without_array
->is_interface()) {
1538 if (interface_contains_unsized_arrays(type_without_array
)) {
1539 const glsl_type
*new_type
=
1540 resize_interface_members(type_without_array
,
1541 var
->get_max_ifc_array_access(),
1542 var
->is_in_shader_storage_block());
1543 var
->change_interface_type(new_type
);
1544 var
->type
= update_interface_members_array(var
->type
, new_type
);
1546 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1547 /* Store a pointer to the variable in the unnamed_interfaces
1551 _mesa_hash_table_search(this->unnamed_interfaces
,
1554 ir_variable
**interface_vars
= entry
? (ir_variable
**) entry
->data
: NULL
;
1556 if (interface_vars
== NULL
) {
1557 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1559 _mesa_hash_table_insert(this->unnamed_interfaces
, ifc_type
,
1562 unsigned index
= ifc_type
->field_index(var
->name
);
1563 assert(index
< ifc_type
->length
);
1564 assert(interface_vars
[index
] == NULL
);
1565 interface_vars
[index
] = var
;
1567 return visit_continue
;
1571 * For each unnamed interface block that was discovered while running the
1572 * visitor, adjust the interface type to reflect the newly assigned array
1573 * sizes, and fix up the ir_variable nodes to point to the new interface
1576 void fixup_unnamed_interface_types()
1578 hash_table_call_foreach(this->unnamed_interfaces
,
1579 fixup_unnamed_interface_type
, NULL
);
1584 * If the type pointed to by \c type represents an unsized array, replace
1585 * it with a sized array whose size is determined by max_array_access.
1587 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1588 bool from_ssbo_unsized_array
, bool *implicit_sized
)
1590 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1591 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1592 max_array_access
+ 1);
1593 *implicit_sized
= true;
1594 assert(*type
!= NULL
);
1598 static const glsl_type
*
1599 update_interface_members_array(const glsl_type
*type
,
1600 const glsl_type
*new_interface_type
)
1602 const glsl_type
*element_type
= type
->fields
.array
;
1603 if (element_type
->is_array()) {
1604 const glsl_type
*new_array_type
=
1605 update_interface_members_array(element_type
, new_interface_type
);
1606 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1608 return glsl_type::get_array_instance(new_interface_type
,
1614 * Determine whether the given interface type contains unsized arrays (if
1615 * it doesn't, array_sizing_visitor doesn't need to process it).
1617 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1619 for (unsigned i
= 0; i
< type
->length
; i
++) {
1620 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1621 if (elem_type
->is_unsized_array())
1628 * Create a new interface type based on the given type, with unsized arrays
1629 * replaced by sized arrays whose size is determined by
1630 * max_ifc_array_access.
1632 static const glsl_type
*
1633 resize_interface_members(const glsl_type
*type
,
1634 const int *max_ifc_array_access
,
1637 unsigned num_fields
= type
->length
;
1638 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1639 memcpy(fields
, type
->fields
.structure
,
1640 num_fields
* sizeof(*fields
));
1641 for (unsigned i
= 0; i
< num_fields
; i
++) {
1642 bool implicit_sized_array
= fields
[i
].implicit_sized_array
;
1643 /* If SSBO last member is unsized array, we don't replace it by a sized
1646 if (is_ssbo
&& i
== (num_fields
- 1))
1647 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1648 true, &implicit_sized_array
);
1650 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1651 false, &implicit_sized_array
);
1652 fields
[i
].implicit_sized_array
= implicit_sized_array
;
1654 glsl_interface_packing packing
=
1655 (glsl_interface_packing
) type
->interface_packing
;
1656 bool row_major
= (bool) type
->interface_row_major
;
1657 const glsl_type
*new_ifc_type
=
1658 glsl_type::get_interface_instance(fields
, num_fields
,
1659 packing
, row_major
, type
->name
);
1661 return new_ifc_type
;
1664 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1667 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1668 ir_variable
**interface_vars
= (ir_variable
**) data
;
1669 unsigned num_fields
= ifc_type
->length
;
1670 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1671 memcpy(fields
, ifc_type
->fields
.structure
,
1672 num_fields
* sizeof(*fields
));
1673 bool interface_type_changed
= false;
1674 for (unsigned i
= 0; i
< num_fields
; i
++) {
1675 if (interface_vars
[i
] != NULL
&&
1676 fields
[i
].type
!= interface_vars
[i
]->type
) {
1677 fields
[i
].type
= interface_vars
[i
]->type
;
1678 interface_type_changed
= true;
1681 if (!interface_type_changed
) {
1685 glsl_interface_packing packing
=
1686 (glsl_interface_packing
) ifc_type
->interface_packing
;
1687 bool row_major
= (bool) ifc_type
->interface_row_major
;
1688 const glsl_type
*new_ifc_type
=
1689 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1690 row_major
, ifc_type
->name
);
1692 for (unsigned i
= 0; i
< num_fields
; i
++) {
1693 if (interface_vars
[i
] != NULL
)
1694 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1699 * Memory context used to allocate the data in \c unnamed_interfaces.
1704 * Hash table from const glsl_type * to an array of ir_variable *'s
1705 * pointing to the ir_variables constituting each unnamed interface block.
1707 hash_table
*unnamed_interfaces
;
1711 validate_xfb_buffer_stride(struct gl_context
*ctx
, unsigned idx
,
1712 struct gl_shader_program
*prog
)
1714 /* We will validate doubles at a later stage */
1715 if (prog
->TransformFeedback
.BufferStride
[idx
] % 4) {
1716 linker_error(prog
, "invalid qualifier xfb_stride=%d must be a "
1717 "multiple of 4 or if its applied to a type that is "
1718 "or contains a double a multiple of 8.",
1719 prog
->TransformFeedback
.BufferStride
[idx
]);
1723 if (prog
->TransformFeedback
.BufferStride
[idx
] / 4 >
1724 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1725 linker_error(prog
, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1726 "limit has been exceeded.");
1734 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1738 link_xfb_stride_layout_qualifiers(struct gl_context
*ctx
,
1739 struct gl_shader_program
*prog
,
1740 struct gl_shader
**shader_list
,
1741 unsigned num_shaders
)
1743 for (unsigned i
= 0; i
< MAX_FEEDBACK_BUFFERS
; i
++) {
1744 prog
->TransformFeedback
.BufferStride
[i
] = 0;
1747 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1748 struct gl_shader
*shader
= shader_list
[i
];
1750 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1751 if (shader
->TransformFeedbackBufferStride
[j
]) {
1752 if (prog
->TransformFeedback
.BufferStride
[j
] == 0) {
1753 prog
->TransformFeedback
.BufferStride
[j
] =
1754 shader
->TransformFeedbackBufferStride
[j
];
1755 if (!validate_xfb_buffer_stride(ctx
, j
, prog
))
1757 } else if (prog
->TransformFeedback
.BufferStride
[j
] !=
1758 shader
->TransformFeedbackBufferStride
[j
]){
1760 "intrastage shaders defined with conflicting "
1761 "xfb_stride for buffer %d (%d and %d)\n", j
,
1762 prog
->TransformFeedback
.BufferStride
[j
],
1763 shader
->TransformFeedbackBufferStride
[j
]);
1772 * Check for conflicting bindless/bound sampler/image layout qualifiers at
1776 link_bindless_layout_qualifiers(struct gl_shader_program
*prog
,
1777 struct gl_shader
**shader_list
,
1778 unsigned num_shaders
)
1780 bool bindless_sampler
, bindless_image
;
1781 bool bound_sampler
, bound_image
;
1783 bindless_sampler
= bindless_image
= false;
1784 bound_sampler
= bound_image
= false;
1786 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1787 struct gl_shader
*shader
= shader_list
[i
];
1789 if (shader
->bindless_sampler
)
1790 bindless_sampler
= true;
1791 if (shader
->bindless_image
)
1792 bindless_image
= true;
1793 if (shader
->bound_sampler
)
1794 bound_sampler
= true;
1795 if (shader
->bound_image
)
1798 if ((bindless_sampler
&& bound_sampler
) ||
1799 (bindless_image
&& bound_image
)) {
1800 /* From section 4.4.6 of the ARB_bindless_texture spec:
1802 * "If both bindless_sampler and bound_sampler, or bindless_image
1803 * and bound_image, are declared at global scope in any
1804 * compilation unit, a link- time error will be generated."
1806 linker_error(prog
, "both bindless_sampler and bound_sampler, or "
1807 "bindless_image and bound_image, can't be declared at "
1814 * Performs the cross-validation of tessellation control shader vertices and
1815 * layout qualifiers for the attached tessellation control shaders,
1816 * and propagates them to the linked TCS and linked shader program.
1819 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1820 struct gl_program
*gl_prog
,
1821 struct gl_shader
**shader_list
,
1822 unsigned num_shaders
)
1824 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_CTRL
)
1827 gl_prog
->info
.tess
.tcs_vertices_out
= 0;
1829 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1831 * "All tessellation control shader layout declarations in a program
1832 * must specify the same output patch vertex count. There must be at
1833 * least one layout qualifier specifying an output patch vertex count
1834 * in any program containing tessellation control shaders; however,
1835 * such a declaration is not required in all tessellation control
1839 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1840 struct gl_shader
*shader
= shader_list
[i
];
1842 if (shader
->info
.TessCtrl
.VerticesOut
!= 0) {
1843 if (gl_prog
->info
.tess
.tcs_vertices_out
!= 0 &&
1844 gl_prog
->info
.tess
.tcs_vertices_out
!=
1845 (unsigned) shader
->info
.TessCtrl
.VerticesOut
) {
1846 linker_error(prog
, "tessellation control shader defined with "
1847 "conflicting output vertex count (%d and %d)\n",
1848 gl_prog
->info
.tess
.tcs_vertices_out
,
1849 shader
->info
.TessCtrl
.VerticesOut
);
1852 gl_prog
->info
.tess
.tcs_vertices_out
=
1853 shader
->info
.TessCtrl
.VerticesOut
;
1857 /* Just do the intrastage -> interstage propagation right now,
1858 * since we already know we're in the right type of shader program
1861 if (gl_prog
->info
.tess
.tcs_vertices_out
== 0) {
1862 linker_error(prog
, "tessellation control shader didn't declare "
1863 "vertices out layout qualifier\n");
1870 * Performs the cross-validation of tessellation evaluation shader
1871 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1872 * for the attached tessellation evaluation shaders, and propagates them
1873 * to the linked TES and linked shader program.
1876 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1877 struct gl_program
*gl_prog
,
1878 struct gl_shader
**shader_list
,
1879 unsigned num_shaders
)
1881 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_EVAL
)
1884 int point_mode
= -1;
1885 unsigned vertex_order
= 0;
1887 gl_prog
->info
.tess
.primitive_mode
= PRIM_UNKNOWN
;
1888 gl_prog
->info
.tess
.spacing
= TESS_SPACING_UNSPECIFIED
;
1890 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1892 * "At least one tessellation evaluation shader (compilation unit) in
1893 * a program must declare a primitive mode in its input layout.
1894 * Declaration vertex spacing, ordering, and point mode identifiers is
1895 * optional. It is not required that all tessellation evaluation
1896 * shaders in a program declare a primitive mode. If spacing or
1897 * vertex ordering declarations are omitted, the tessellation
1898 * primitive generator will use equal spacing or counter-clockwise
1899 * vertex ordering, respectively. If a point mode declaration is
1900 * omitted, the tessellation primitive generator will produce lines or
1901 * triangles according to the primitive mode."
1904 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1905 struct gl_shader
*shader
= shader_list
[i
];
1907 if (shader
->info
.TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1908 if (gl_prog
->info
.tess
.primitive_mode
!= PRIM_UNKNOWN
&&
1909 gl_prog
->info
.tess
.primitive_mode
!=
1910 shader
->info
.TessEval
.PrimitiveMode
) {
1911 linker_error(prog
, "tessellation evaluation shader defined with "
1912 "conflicting input primitive modes.\n");
1915 gl_prog
->info
.tess
.primitive_mode
=
1916 shader
->info
.TessEval
.PrimitiveMode
;
1919 if (shader
->info
.TessEval
.Spacing
!= 0) {
1920 if (gl_prog
->info
.tess
.spacing
!= 0 && gl_prog
->info
.tess
.spacing
!=
1921 shader
->info
.TessEval
.Spacing
) {
1922 linker_error(prog
, "tessellation evaluation shader defined with "
1923 "conflicting vertex spacing.\n");
1926 gl_prog
->info
.tess
.spacing
= shader
->info
.TessEval
.Spacing
;
1929 if (shader
->info
.TessEval
.VertexOrder
!= 0) {
1930 if (vertex_order
!= 0 &&
1931 vertex_order
!= shader
->info
.TessEval
.VertexOrder
) {
1932 linker_error(prog
, "tessellation evaluation shader defined with "
1933 "conflicting ordering.\n");
1936 vertex_order
= shader
->info
.TessEval
.VertexOrder
;
1939 if (shader
->info
.TessEval
.PointMode
!= -1) {
1940 if (point_mode
!= -1 &&
1941 point_mode
!= shader
->info
.TessEval
.PointMode
) {
1942 linker_error(prog
, "tessellation evaluation shader defined with "
1943 "conflicting point modes.\n");
1946 point_mode
= shader
->info
.TessEval
.PointMode
;
1951 /* Just do the intrastage -> interstage propagation right now,
1952 * since we already know we're in the right type of shader program
1955 if (gl_prog
->info
.tess
.primitive_mode
== PRIM_UNKNOWN
) {
1957 "tessellation evaluation shader didn't declare input "
1958 "primitive modes.\n");
1962 if (gl_prog
->info
.tess
.spacing
== TESS_SPACING_UNSPECIFIED
)
1963 gl_prog
->info
.tess
.spacing
= TESS_SPACING_EQUAL
;
1965 if (vertex_order
== 0 || vertex_order
== GL_CCW
)
1966 gl_prog
->info
.tess
.ccw
= true;
1968 gl_prog
->info
.tess
.ccw
= false;
1971 if (point_mode
== -1 || point_mode
== GL_FALSE
)
1972 gl_prog
->info
.tess
.point_mode
= false;
1974 gl_prog
->info
.tess
.point_mode
= true;
1979 * Performs the cross-validation of layout qualifiers specified in
1980 * redeclaration of gl_FragCoord for the attached fragment shaders,
1981 * and propagates them to the linked FS and linked shader program.
1984 link_fs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1985 struct gl_linked_shader
*linked_shader
,
1986 struct gl_shader
**shader_list
,
1987 unsigned num_shaders
)
1989 bool redeclares_gl_fragcoord
= false;
1990 bool uses_gl_fragcoord
= false;
1991 bool origin_upper_left
= false;
1992 bool pixel_center_integer
= false;
1994 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1995 (prog
->data
->Version
< 150 &&
1996 !prog
->ARB_fragment_coord_conventions_enable
))
1999 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2000 struct gl_shader
*shader
= shader_list
[i
];
2001 /* From the GLSL 1.50 spec, page 39:
2003 * "If gl_FragCoord is redeclared in any fragment shader in a program,
2004 * it must be redeclared in all the fragment shaders in that program
2005 * that have a static use gl_FragCoord."
2007 if ((redeclares_gl_fragcoord
&& !shader
->redeclares_gl_fragcoord
&&
2008 shader
->uses_gl_fragcoord
)
2009 || (shader
->redeclares_gl_fragcoord
&& !redeclares_gl_fragcoord
&&
2010 uses_gl_fragcoord
)) {
2011 linker_error(prog
, "fragment shader defined with conflicting "
2012 "layout qualifiers for gl_FragCoord\n");
2015 /* From the GLSL 1.50 spec, page 39:
2017 * "All redeclarations of gl_FragCoord in all fragment shaders in a
2018 * single program must have the same set of qualifiers."
2020 if (redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
&&
2021 (shader
->origin_upper_left
!= origin_upper_left
||
2022 shader
->pixel_center_integer
!= pixel_center_integer
)) {
2023 linker_error(prog
, "fragment shader defined with conflicting "
2024 "layout qualifiers for gl_FragCoord\n");
2027 /* Update the linked shader state. Note that uses_gl_fragcoord should
2028 * accumulate the results. The other values should replace. If there
2029 * are multiple redeclarations, all the fields except uses_gl_fragcoord
2030 * are already known to be the same.
2032 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
2033 redeclares_gl_fragcoord
= shader
->redeclares_gl_fragcoord
;
2034 uses_gl_fragcoord
|= shader
->uses_gl_fragcoord
;
2035 origin_upper_left
= shader
->origin_upper_left
;
2036 pixel_center_integer
= shader
->pixel_center_integer
;
2039 linked_shader
->Program
->info
.fs
.early_fragment_tests
|=
2040 shader
->EarlyFragmentTests
|| shader
->PostDepthCoverage
;
2041 linked_shader
->Program
->info
.fs
.inner_coverage
|= shader
->InnerCoverage
;
2042 linked_shader
->Program
->info
.fs
.post_depth_coverage
|=
2043 shader
->PostDepthCoverage
;
2044 linked_shader
->Program
->info
.fs
.pixel_interlock_ordered
|=
2045 shader
->PixelInterlockOrdered
;
2046 linked_shader
->Program
->info
.fs
.pixel_interlock_unordered
|=
2047 shader
->PixelInterlockUnordered
;
2048 linked_shader
->Program
->info
.fs
.sample_interlock_ordered
|=
2049 shader
->SampleInterlockOrdered
;
2050 linked_shader
->Program
->info
.fs
.sample_interlock_unordered
|=
2051 shader
->SampleInterlockUnordered
;
2052 linked_shader
->Program
->sh
.fs
.BlendSupport
|= shader
->BlendSupport
;
2055 linked_shader
->Program
->info
.fs
.pixel_center_integer
= pixel_center_integer
;
2056 linked_shader
->Program
->info
.fs
.origin_upper_left
= origin_upper_left
;
2060 * Performs the cross-validation of geometry shader max_vertices and
2061 * primitive type layout qualifiers for the attached geometry shaders,
2062 * and propagates them to the linked GS and linked shader program.
2065 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
2066 struct gl_program
*gl_prog
,
2067 struct gl_shader
**shader_list
,
2068 unsigned num_shaders
)
2070 /* No in/out qualifiers defined for anything but GLSL 1.50+
2071 * geometry shaders so far.
2073 if (gl_prog
->info
.stage
!= MESA_SHADER_GEOMETRY
||
2074 prog
->data
->Version
< 150)
2077 int vertices_out
= -1;
2079 gl_prog
->info
.gs
.invocations
= 0;
2080 gl_prog
->info
.gs
.input_primitive
= PRIM_UNKNOWN
;
2081 gl_prog
->info
.gs
.output_primitive
= PRIM_UNKNOWN
;
2083 /* From the GLSL 1.50 spec, page 46:
2085 * "All geometry shader output layout declarations in a program
2086 * must declare the same layout and same value for
2087 * max_vertices. There must be at least one geometry output
2088 * layout declaration somewhere in a program, but not all
2089 * geometry shaders (compilation units) are required to
2093 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2094 struct gl_shader
*shader
= shader_list
[i
];
2096 if (shader
->info
.Geom
.InputType
!= PRIM_UNKNOWN
) {
2097 if (gl_prog
->info
.gs
.input_primitive
!= PRIM_UNKNOWN
&&
2098 gl_prog
->info
.gs
.input_primitive
!=
2099 shader
->info
.Geom
.InputType
) {
2100 linker_error(prog
, "geometry shader defined with conflicting "
2104 gl_prog
->info
.gs
.input_primitive
= shader
->info
.Geom
.InputType
;
2107 if (shader
->info
.Geom
.OutputType
!= PRIM_UNKNOWN
) {
2108 if (gl_prog
->info
.gs
.output_primitive
!= PRIM_UNKNOWN
&&
2109 gl_prog
->info
.gs
.output_primitive
!=
2110 shader
->info
.Geom
.OutputType
) {
2111 linker_error(prog
, "geometry shader defined with conflicting "
2115 gl_prog
->info
.gs
.output_primitive
= shader
->info
.Geom
.OutputType
;
2118 if (shader
->info
.Geom
.VerticesOut
!= -1) {
2119 if (vertices_out
!= -1 &&
2120 vertices_out
!= shader
->info
.Geom
.VerticesOut
) {
2121 linker_error(prog
, "geometry shader defined with conflicting "
2122 "output vertex count (%d and %d)\n",
2123 vertices_out
, shader
->info
.Geom
.VerticesOut
);
2126 vertices_out
= shader
->info
.Geom
.VerticesOut
;
2129 if (shader
->info
.Geom
.Invocations
!= 0) {
2130 if (gl_prog
->info
.gs
.invocations
!= 0 &&
2131 gl_prog
->info
.gs
.invocations
!=
2132 (unsigned) shader
->info
.Geom
.Invocations
) {
2133 linker_error(prog
, "geometry shader defined with conflicting "
2134 "invocation count (%d and %d)\n",
2135 gl_prog
->info
.gs
.invocations
,
2136 shader
->info
.Geom
.Invocations
);
2139 gl_prog
->info
.gs
.invocations
= shader
->info
.Geom
.Invocations
;
2143 /* Just do the intrastage -> interstage propagation right now,
2144 * since we already know we're in the right type of shader program
2147 if (gl_prog
->info
.gs
.input_primitive
== PRIM_UNKNOWN
) {
2149 "geometry shader didn't declare primitive input type\n");
2153 if (gl_prog
->info
.gs
.output_primitive
== PRIM_UNKNOWN
) {
2155 "geometry shader didn't declare primitive output type\n");
2159 if (vertices_out
== -1) {
2161 "geometry shader didn't declare max_vertices\n");
2164 gl_prog
->info
.gs
.vertices_out
= vertices_out
;
2167 if (gl_prog
->info
.gs
.invocations
== 0)
2168 gl_prog
->info
.gs
.invocations
= 1;
2173 * Perform cross-validation of compute shader local_size_{x,y,z} layout and
2174 * derivative arrangement qualifiers for the attached compute shaders, and
2175 * propagate them to the linked CS and linked shader program.
2178 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
2179 struct gl_program
*gl_prog
,
2180 struct gl_shader
**shader_list
,
2181 unsigned num_shaders
)
2183 /* This function is called for all shader stages, but it only has an effect
2184 * for compute shaders.
2186 if (gl_prog
->info
.stage
!= MESA_SHADER_COMPUTE
)
2189 for (int i
= 0; i
< 3; i
++)
2190 gl_prog
->info
.cs
.local_size
[i
] = 0;
2192 gl_prog
->info
.cs
.local_size_variable
= false;
2194 gl_prog
->info
.cs
.derivative_group
= DERIVATIVE_GROUP_NONE
;
2196 /* From the ARB_compute_shader spec, in the section describing local size
2199 * If multiple compute shaders attached to a single program object
2200 * declare local work-group size, the declarations must be identical;
2201 * otherwise a link-time error results. Furthermore, if a program
2202 * object contains any compute shaders, at least one must contain an
2203 * input layout qualifier specifying the local work sizes of the
2204 * program, or a link-time error will occur.
2206 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
2207 struct gl_shader
*shader
= shader_list
[sh
];
2209 if (shader
->info
.Comp
.LocalSize
[0] != 0) {
2210 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2211 for (int i
= 0; i
< 3; i
++) {
2212 if (gl_prog
->info
.cs
.local_size
[i
] !=
2213 shader
->info
.Comp
.LocalSize
[i
]) {
2214 linker_error(prog
, "compute shader defined with conflicting "
2220 for (int i
= 0; i
< 3; i
++) {
2221 gl_prog
->info
.cs
.local_size
[i
] =
2222 shader
->info
.Comp
.LocalSize
[i
];
2224 } else if (shader
->info
.Comp
.LocalSizeVariable
) {
2225 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2226 /* The ARB_compute_variable_group_size spec says:
2228 * If one compute shader attached to a program declares a
2229 * variable local group size and a second compute shader
2230 * attached to the same program declares a fixed local group
2231 * size, a link-time error results.
2233 linker_error(prog
, "compute shader defined with both fixed and "
2234 "variable local group size\n");
2237 gl_prog
->info
.cs
.local_size_variable
= true;
2240 enum gl_derivative_group group
= shader
->info
.Comp
.DerivativeGroup
;
2241 if (group
!= DERIVATIVE_GROUP_NONE
) {
2242 if (gl_prog
->info
.cs
.derivative_group
!= DERIVATIVE_GROUP_NONE
&&
2243 gl_prog
->info
.cs
.derivative_group
!= group
) {
2244 linker_error(prog
, "compute shader defined with conflicting "
2245 "derivative groups\n");
2248 gl_prog
->info
.cs
.derivative_group
= group
;
2252 /* Just do the intrastage -> interstage propagation right now,
2253 * since we already know we're in the right type of shader program
2256 if (gl_prog
->info
.cs
.local_size
[0] == 0 &&
2257 !gl_prog
->info
.cs
.local_size_variable
) {
2258 linker_error(prog
, "compute shader must contain a fixed or a variable "
2259 "local group size\n");
2263 if (gl_prog
->info
.cs
.derivative_group
== DERIVATIVE_GROUP_QUADS
) {
2264 if (gl_prog
->info
.cs
.local_size
[0] % 2 != 0) {
2265 linker_error(prog
, "derivative_group_quadsNV must be used with a "
2266 "local group size whose first dimension "
2267 "is a multiple of 2\n");
2270 if (gl_prog
->info
.cs
.local_size
[1] % 2 != 0) {
2271 linker_error(prog
, "derivative_group_quadsNV must be used with a local"
2272 "group size whose second dimension "
2273 "is a multiple of 2\n");
2276 } else if (gl_prog
->info
.cs
.derivative_group
== DERIVATIVE_GROUP_LINEAR
) {
2277 if ((gl_prog
->info
.cs
.local_size
[0] *
2278 gl_prog
->info
.cs
.local_size
[1] *
2279 gl_prog
->info
.cs
.local_size
[2]) % 4 != 0) {
2280 linker_error(prog
, "derivative_group_linearNV must be used with a "
2281 "local group size whose total number of invocations "
2282 "is a multiple of 4\n");
2289 * Link all out variables on a single stage which are not
2290 * directly used in a shader with the main function.
2293 link_output_variables(struct gl_linked_shader
*linked_shader
,
2294 struct gl_shader
**shader_list
,
2295 unsigned num_shaders
)
2297 struct glsl_symbol_table
*symbols
= linked_shader
->symbols
;
2299 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2301 /* Skip shader object with main function */
2302 if (shader_list
[i
]->symbols
->get_function("main"))
2305 foreach_in_list(ir_instruction
, ir
, shader_list
[i
]->ir
) {
2306 if (ir
->ir_type
!= ir_type_variable
)
2309 ir_variable
*var
= (ir_variable
*) ir
;
2311 if (var
->data
.mode
== ir_var_shader_out
&&
2312 !symbols
->get_variable(var
->name
)) {
2313 var
= var
->clone(linked_shader
, NULL
);
2314 symbols
->add_variable(var
);
2315 linked_shader
->ir
->push_head(var
);
2325 * Combine a group of shaders for a single stage to generate a linked shader
2328 * If this function is supplied a single shader, it is cloned, and the new
2329 * shader is returned.
2331 struct gl_linked_shader
*
2332 link_intrastage_shaders(void *mem_ctx
,
2333 struct gl_context
*ctx
,
2334 struct gl_shader_program
*prog
,
2335 struct gl_shader
**shader_list
,
2336 unsigned num_shaders
,
2337 bool allow_missing_main
)
2339 struct gl_uniform_block
*ubo_blocks
= NULL
;
2340 struct gl_uniform_block
*ssbo_blocks
= NULL
;
2341 unsigned num_ubo_blocks
= 0;
2342 unsigned num_ssbo_blocks
= 0;
2344 /* Check that global variables defined in multiple shaders are consistent.
2346 glsl_symbol_table variables
;
2347 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2348 if (shader_list
[i
] == NULL
)
2350 cross_validate_globals(ctx
, prog
, shader_list
[i
]->ir
, &variables
,
2354 if (!prog
->data
->LinkStatus
)
2357 /* Check that interface blocks defined in multiple shaders are consistent.
2359 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
2361 if (!prog
->data
->LinkStatus
)
2364 /* Check that there is only a single definition of each function signature
2365 * across all shaders.
2367 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2368 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2369 ir_function
*const f
= node
->as_function();
2374 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2375 ir_function
*const other
=
2376 shader_list
[j
]->symbols
->get_function(f
->name
);
2378 /* If the other shader has no function (and therefore no function
2379 * signatures) with the same name, skip to the next shader.
2384 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2385 if (!sig
->is_defined
)
2388 ir_function_signature
*other_sig
=
2389 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2391 if (other_sig
!= NULL
&& other_sig
->is_defined
) {
2392 linker_error(prog
, "function `%s' is multiply defined\n",
2401 /* Find the shader that defines main, and make a clone of it.
2403 * Starting with the clone, search for undefined references. If one is
2404 * found, find the shader that defines it. Clone the reference and add
2405 * it to the shader. Repeat until there are no undefined references or
2406 * until a reference cannot be resolved.
2408 gl_shader
*main
= NULL
;
2409 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2410 if (_mesa_get_main_function_signature(shader_list
[i
]->symbols
)) {
2411 main
= shader_list
[i
];
2416 if (main
== NULL
&& allow_missing_main
)
2417 main
= shader_list
[0];
2420 linker_error(prog
, "%s shader lacks `main'\n",
2421 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2425 gl_linked_shader
*linked
= rzalloc(NULL
, struct gl_linked_shader
);
2426 linked
->Stage
= shader_list
[0]->Stage
;
2428 /* Create program and attach it to the linked shader */
2429 struct gl_program
*gl_prog
=
2430 ctx
->Driver
.NewProgram(ctx
,
2431 _mesa_shader_stage_to_program(shader_list
[0]->Stage
),
2434 prog
->data
->LinkStatus
= LINKING_FAILURE
;
2435 _mesa_delete_linked_shader(ctx
, linked
);
2439 _mesa_reference_shader_program_data(ctx
, &gl_prog
->sh
.data
, prog
->data
);
2441 /* Don't use _mesa_reference_program() just take ownership */
2442 linked
->Program
= gl_prog
;
2444 linked
->ir
= new(linked
) exec_list
;
2445 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2447 link_fs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2448 link_tcs_out_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2449 link_tes_in_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2450 link_gs_inout_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2451 link_cs_input_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2453 if (linked
->Stage
!= MESA_SHADER_FRAGMENT
)
2454 link_xfb_stride_layout_qualifiers(ctx
, prog
, shader_list
, num_shaders
);
2456 link_bindless_layout_qualifiers(prog
, shader_list
, num_shaders
);
2458 populate_symbol_table(linked
, shader_list
[0]->symbols
);
2460 /* The pointer to the main function in the final linked shader (i.e., the
2461 * copy of the original shader that contained the main function).
2463 ir_function_signature
*const main_sig
=
2464 _mesa_get_main_function_signature(linked
->symbols
);
2466 /* Move any instructions other than variable declarations or function
2467 * declarations into main.
2469 if (main_sig
!= NULL
) {
2470 exec_node
*insertion_point
=
2471 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2474 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2475 if (shader_list
[i
] == main
)
2478 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2479 insertion_point
, true, linked
);
2483 if (!link_function_calls(prog
, linked
, shader_list
, num_shaders
)) {
2484 _mesa_delete_linked_shader(ctx
, linked
);
2488 if (linked
->Stage
!= MESA_SHADER_FRAGMENT
)
2489 link_output_variables(linked
, shader_list
, num_shaders
);
2491 /* Make a pass over all variable declarations to ensure that arrays with
2492 * unspecified sizes have a size specified. The size is inferred from the
2493 * max_array_access field.
2495 array_sizing_visitor v
;
2497 v
.fixup_unnamed_interface_types();
2499 /* Link up uniform blocks defined within this stage. */
2500 link_uniform_blocks(mem_ctx
, ctx
, prog
, linked
, &ubo_blocks
,
2501 &num_ubo_blocks
, &ssbo_blocks
, &num_ssbo_blocks
);
2503 if (!prog
->data
->LinkStatus
) {
2504 _mesa_delete_linked_shader(ctx
, linked
);
2508 /* Copy ubo blocks to linked shader list */
2509 linked
->Program
->sh
.UniformBlocks
=
2510 ralloc_array(linked
, gl_uniform_block
*, num_ubo_blocks
);
2511 ralloc_steal(linked
, ubo_blocks
);
2512 for (unsigned i
= 0; i
< num_ubo_blocks
; i
++) {
2513 linked
->Program
->sh
.UniformBlocks
[i
] = &ubo_blocks
[i
];
2515 linked
->Program
->info
.num_ubos
= num_ubo_blocks
;
2517 /* Copy ssbo blocks to linked shader list */
2518 linked
->Program
->sh
.ShaderStorageBlocks
=
2519 ralloc_array(linked
, gl_uniform_block
*, num_ssbo_blocks
);
2520 ralloc_steal(linked
, ssbo_blocks
);
2521 for (unsigned i
= 0; i
< num_ssbo_blocks
; i
++) {
2522 linked
->Program
->sh
.ShaderStorageBlocks
[i
] = &ssbo_blocks
[i
];
2524 linked
->Program
->info
.num_ssbos
= num_ssbo_blocks
;
2526 /* At this point linked should contain all of the linked IR, so
2527 * validate it to make sure nothing went wrong.
2529 validate_ir_tree(linked
->ir
);
2531 /* Set the size of geometry shader input arrays */
2532 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2533 unsigned num_vertices
=
2534 vertices_per_prim(gl_prog
->info
.gs
.input_primitive
);
2535 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2536 MESA_SHADER_GEOMETRY
);
2537 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2538 ir
->accept(&input_resize_visitor
);
2542 if (ctx
->Const
.VertexID_is_zero_based
)
2543 lower_vertex_id(linked
);
2545 if (ctx
->Const
.LowerCsDerivedVariables
)
2546 lower_cs_derived(linked
);
2549 /* Compute the source checksum. */
2550 linked
->SourceChecksum
= 0;
2551 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2552 if (shader_list
[i
] == NULL
)
2554 linked
->SourceChecksum
^= shader_list
[i
]->SourceChecksum
;
2562 * Update the sizes of linked shader uniform arrays to the maximum
2565 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2567 * If one or more elements of an array are active,
2568 * GetActiveUniform will return the name of the array in name,
2569 * subject to the restrictions listed above. The type of the array
2570 * is returned in type. The size parameter contains the highest
2571 * array element index used, plus one. The compiler or linker
2572 * determines the highest index used. There will be only one
2573 * active uniform reported by the GL per uniform array.
2577 update_array_sizes(struct gl_shader_program
*prog
)
2579 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2580 if (prog
->_LinkedShaders
[i
] == NULL
)
2583 bool types_were_updated
= false;
2585 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2586 ir_variable
*const var
= node
->as_variable();
2588 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2589 !var
->type
->is_array())
2592 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2593 * will not be eliminated. Since we always do std140, just
2594 * don't resize arrays in UBOs.
2596 * Atomic counters are supposed to get deterministic
2597 * locations assigned based on the declaration ordering and
2598 * sizes, array compaction would mess that up.
2600 * Subroutine uniforms are not removed.
2602 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2603 var
->type
->contains_subroutine() || var
->constant_initializer
)
2606 int size
= var
->data
.max_array_access
;
2607 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2608 if (prog
->_LinkedShaders
[j
] == NULL
)
2611 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2612 ir_variable
*other_var
= node2
->as_variable();
2616 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2617 other_var
->data
.max_array_access
> size
) {
2618 size
= other_var
->data
.max_array_access
;
2623 if (size
+ 1 != (int)var
->type
->length
) {
2624 /* If this is a built-in uniform (i.e., it's backed by some
2625 * fixed-function state), adjust the number of state slots to
2626 * match the new array size. The number of slots per array entry
2627 * is not known. It seems safe to assume that the total number of
2628 * slots is an integer multiple of the number of array elements.
2629 * Determine the number of slots per array element by dividing by
2630 * the old (total) size.
2632 const unsigned num_slots
= var
->get_num_state_slots();
2633 if (num_slots
> 0) {
2634 var
->set_num_state_slots((size
+ 1)
2635 * (num_slots
/ var
->type
->length
));
2638 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2640 types_were_updated
= true;
2644 /* Update the types of dereferences in case we changed any. */
2645 if (types_were_updated
) {
2646 deref_type_updater v
;
2647 v
.run(prog
->_LinkedShaders
[i
]->ir
);
2653 * Resize tessellation evaluation per-vertex inputs to the size of
2654 * tessellation control per-vertex outputs.
2657 resize_tes_inputs(struct gl_context
*ctx
,
2658 struct gl_shader_program
*prog
)
2660 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2663 gl_linked_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2664 gl_linked_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2666 /* If no control shader is present, then the TES inputs are statically
2667 * sized to MaxPatchVertices; the actual size of the arrays won't be
2668 * known until draw time.
2670 const int num_vertices
= tcs
2671 ? tcs
->Program
->info
.tess
.tcs_vertices_out
2672 : ctx
->Const
.MaxPatchVertices
;
2674 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2675 MESA_SHADER_TESS_EVAL
);
2676 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2677 ir
->accept(&input_resize_visitor
);
2681 /* Convert the gl_PatchVerticesIn system value into a constant, since
2682 * the value is known at this point.
2684 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2685 ir_variable
*var
= ir
->as_variable();
2686 if (var
&& var
->data
.mode
== ir_var_system_value
&&
2687 var
->data
.location
== SYSTEM_VALUE_VERTICES_IN
) {
2688 void *mem_ctx
= ralloc_parent(var
);
2689 var
->data
.location
= 0;
2690 var
->data
.explicit_location
= false;
2691 var
->data
.mode
= ir_var_auto
;
2692 var
->constant_value
= new(mem_ctx
) ir_constant(num_vertices
);
2699 * Find a contiguous set of available bits in a bitmask.
2701 * \param used_mask Bits representing used (1) and unused (0) locations
2702 * \param needed_count Number of contiguous bits needed.
2705 * Base location of the available bits on success or -1 on failure.
2708 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2710 unsigned needed_mask
= (1 << needed_count
) - 1;
2711 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2713 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2714 * cannot optimize possibly infinite loops" for the loop below.
2716 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2719 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2720 if ((needed_mask
& ~used_mask
) == needed_mask
)
2730 #define SAFE_MASK_FROM_INDEX(i) (((i) >= 32) ? ~0 : ((1 << (i)) - 1))
2733 * Assign locations for either VS inputs or FS outputs.
2735 * \param mem_ctx Temporary ralloc context used for linking.
2736 * \param prog Shader program whose variables need locations
2738 * \param constants Driver specific constant values for the program.
2739 * \param target_index Selector for the program target to receive location
2740 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2741 * \c MESA_SHADER_FRAGMENT.
2742 * \param do_assignment Whether we are actually marking the assignment or we
2743 * are just doing a dry-run checking.
2746 * If locations are (or can be, in case of dry-running) successfully assigned,
2747 * true is returned. Otherwise an error is emitted to the shader link log and
2748 * false is returned.
2751 assign_attribute_or_color_locations(void *mem_ctx
,
2752 gl_shader_program
*prog
,
2753 struct gl_constants
*constants
,
2754 unsigned target_index
,
2757 /* Maximum number of generic locations. This corresponds to either the
2758 * maximum number of draw buffers or the maximum number of generic
2761 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2762 constants
->Program
[target_index
].MaxAttribs
:
2763 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2765 /* Mark invalid locations as being used.
2767 unsigned used_locations
= ~SAFE_MASK_FROM_INDEX(max_index
);
2768 unsigned double_storage_locations
= 0;
2770 assert((target_index
== MESA_SHADER_VERTEX
)
2771 || (target_index
== MESA_SHADER_FRAGMENT
));
2773 gl_linked_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2777 /* Operate in a total of four passes.
2779 * 1. Invalidate the location assignments for all vertex shader inputs.
2781 * 2. Assign locations for inputs that have user-defined (via
2782 * glBindVertexAttribLocation) locations and outputs that have
2783 * user-defined locations (via glBindFragDataLocation).
2785 * 3. Sort the attributes without assigned locations by number of slots
2786 * required in decreasing order. Fragmentation caused by attribute
2787 * locations assigned by the application may prevent large attributes
2788 * from having enough contiguous space.
2790 * 4. Assign locations to any inputs without assigned locations.
2793 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2794 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2796 const enum ir_variable_mode direction
=
2797 (target_index
== MESA_SHADER_VERTEX
)
2798 ? ir_var_shader_in
: ir_var_shader_out
;
2801 /* Temporary storage for the set of attributes that need locations assigned.
2807 /* Used below in the call to qsort. */
2808 static int compare(const void *a
, const void *b
)
2810 const temp_attr
*const l
= (const temp_attr
*) a
;
2811 const temp_attr
*const r
= (const temp_attr
*) b
;
2813 /* Reversed because we want a descending order sort below. */
2814 return r
->slots
- l
->slots
;
2817 assert(max_index
<= 32);
2819 /* Temporary array for the set of attributes that have locations assigned,
2820 * for the purpose of checking overlapping slots/components of (non-ES)
2821 * fragment shader outputs.
2823 ir_variable
*assigned
[12 * 4]; /* (max # of FS outputs) * # components */
2824 unsigned assigned_attr
= 0;
2826 unsigned num_attr
= 0;
2828 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2829 ir_variable
*const var
= node
->as_variable();
2831 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2834 if (var
->data
.explicit_location
) {
2835 var
->data
.is_unmatched_generic_inout
= 0;
2836 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2837 || (var
->data
.location
< 0)) {
2839 "invalid explicit location %d specified for `%s'\n",
2840 (var
->data
.location
< 0)
2841 ? var
->data
.location
2842 : var
->data
.location
- generic_base
,
2846 } else if (target_index
== MESA_SHADER_VERTEX
) {
2849 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2850 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2851 var
->data
.location
= binding
;
2852 var
->data
.is_unmatched_generic_inout
= 0;
2854 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2857 const char *name
= var
->name
;
2858 const glsl_type
*type
= var
->type
;
2861 /* Check if there's a binding for the variable name */
2862 if (prog
->FragDataBindings
->get(binding
, name
)) {
2863 assert(binding
>= FRAG_RESULT_DATA0
);
2864 var
->data
.location
= binding
;
2865 var
->data
.is_unmatched_generic_inout
= 0;
2867 if (prog
->FragDataIndexBindings
->get(index
, name
)) {
2868 var
->data
.index
= index
;
2873 /* If not, but it's an array type, look for name[0] */
2874 if (type
->is_array()) {
2875 name
= ralloc_asprintf(mem_ctx
, "%s[0]", name
);
2876 type
= type
->fields
.array
;
2884 if (strcmp(var
->name
, "gl_LastFragData") == 0)
2887 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2889 * "Output binding assignments will cause LinkProgram to fail:
2891 * If the program has an active output assigned to a location greater
2892 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2893 * an active output assigned an index greater than or equal to one;"
2895 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2896 var
->data
.location
- generic_base
>=
2897 (int) constants
->MaxDualSourceDrawBuffers
) {
2899 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2900 "with index %u for %s\n",
2901 var
->data
.location
- generic_base
, var
->data
.index
,
2906 const unsigned slots
= var
->type
->count_attribute_slots(target_index
== MESA_SHADER_VERTEX
);
2908 /* If the variable is not a built-in and has a location statically
2909 * assigned in the shader (presumably via a layout qualifier), make sure
2910 * that it doesn't collide with other assigned locations. Otherwise,
2911 * add it to the list of variables that need linker-assigned locations.
2913 if (var
->data
.location
!= -1) {
2914 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2915 /* From page 61 of the OpenGL 4.0 spec:
2917 * "LinkProgram will fail if the attribute bindings assigned
2918 * by BindAttribLocation do not leave not enough space to
2919 * assign a location for an active matrix attribute or an
2920 * active attribute array, both of which require multiple
2921 * contiguous generic attributes."
2923 * I think above text prohibits the aliasing of explicit and
2924 * automatic assignments. But, aliasing is allowed in manual
2925 * assignments of attribute locations. See below comments for
2928 * From OpenGL 4.0 spec, page 61:
2930 * "It is possible for an application to bind more than one
2931 * attribute name to the same location. This is referred to as
2932 * aliasing. This will only work if only one of the aliased
2933 * attributes is active in the executable program, or if no
2934 * path through the shader consumes more than one attribute of
2935 * a set of attributes aliased to the same location. A link
2936 * error can occur if the linker determines that every path
2937 * through the shader consumes multiple aliased attributes,
2938 * but implementations are not required to generate an error
2941 * From GLSL 4.30 spec, page 54:
2943 * "A program will fail to link if any two non-vertex shader
2944 * input variables are assigned to the same location. For
2945 * vertex shaders, multiple input variables may be assigned
2946 * to the same location using either layout qualifiers or via
2947 * the OpenGL API. However, such aliasing is intended only to
2948 * support vertex shaders where each execution path accesses
2949 * at most one input per each location. Implementations are
2950 * permitted, but not required, to generate link-time errors
2951 * if they detect that every path through the vertex shader
2952 * executable accesses multiple inputs assigned to any single
2953 * location. For all shader types, a program will fail to link
2954 * if explicit location assignments leave the linker unable
2955 * to find space for other variables without explicit
2958 * From OpenGL ES 3.0 spec, page 56:
2960 * "Binding more than one attribute name to the same location
2961 * is referred to as aliasing, and is not permitted in OpenGL
2962 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2963 * fail when this condition exists. However, aliasing is
2964 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2965 * This will only work if only one of the aliased attributes
2966 * is active in the executable program, or if no path through
2967 * the shader consumes more than one attribute of a set of
2968 * attributes aliased to the same location. A link error can
2969 * occur if the linker determines that every path through the
2970 * shader consumes multiple aliased attributes, but implemen-
2971 * tations are not required to generate an error in this case."
2973 * After looking at above references from OpenGL, OpenGL ES and
2974 * GLSL specifications, we allow aliasing of vertex input variables
2975 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2977 * NOTE: This is not required by the spec but its worth mentioning
2978 * here that we're not doing anything to make sure that no path
2979 * through the vertex shader executable accesses multiple inputs
2980 * assigned to any single location.
2983 /* Mask representing the contiguous slots that will be used by
2986 const unsigned attr
= var
->data
.location
- generic_base
;
2987 const unsigned use_mask
= (1 << slots
) - 1;
2988 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2989 ? "vertex shader input" : "fragment shader output";
2991 /* Generate a link error if the requested locations for this
2992 * attribute exceed the maximum allowed attribute location.
2994 if (attr
+ slots
> max_index
) {
2996 "insufficient contiguous locations "
2997 "available for %s `%s' %d %d %d\n", string
,
2998 var
->name
, used_locations
, use_mask
, attr
);
3002 /* Generate a link error if the set of bits requested for this
3003 * attribute overlaps any previously allocated bits.
3005 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
3006 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
3007 /* From section 4.4.2 (Output Layout Qualifiers) of the GLSL
3010 * "Additionally, for fragment shader outputs, if two
3011 * variables are placed within the same location, they
3012 * must have the same underlying type (floating-point or
3013 * integer). No component aliasing of output variables or
3014 * members is allowed.
3016 for (unsigned i
= 0; i
< assigned_attr
; i
++) {
3017 unsigned assigned_slots
=
3018 assigned
[i
]->type
->count_attribute_slots(false);
3019 unsigned assig_attr
=
3020 assigned
[i
]->data
.location
- generic_base
;
3021 unsigned assigned_use_mask
= (1 << assigned_slots
) - 1;
3023 if ((assigned_use_mask
<< assig_attr
) &
3024 (use_mask
<< attr
)) {
3026 const glsl_type
*assigned_type
=
3027 assigned
[i
]->type
->without_array();
3028 const glsl_type
*type
= var
->type
->without_array();
3029 if (assigned_type
->base_type
!= type
->base_type
) {
3030 linker_error(prog
, "types do not match for aliased"
3031 " %ss %s and %s\n", string
,
3032 assigned
[i
]->name
, var
->name
);
3036 unsigned assigned_component_mask
=
3037 ((1 << assigned_type
->vector_elements
) - 1) <<
3038 assigned
[i
]->data
.location_frac
;
3039 unsigned component_mask
=
3040 ((1 << type
->vector_elements
) - 1) <<
3041 var
->data
.location_frac
;
3042 if (assigned_component_mask
& component_mask
) {
3043 linker_error(prog
, "overlapping component is "
3044 "assigned to %ss %s and %s "
3046 string
, assigned
[i
]->name
, var
->name
,
3047 var
->data
.location_frac
);
3052 } else if (target_index
== MESA_SHADER_FRAGMENT
||
3053 (prog
->IsES
&& prog
->data
->Version
>= 300)) {
3054 linker_error(prog
, "overlapping location is assigned "
3055 "to %s `%s' %d %d %d\n", string
, var
->name
,
3056 used_locations
, use_mask
, attr
);
3059 linker_warning(prog
, "overlapping location is assigned "
3060 "to %s `%s' %d %d %d\n", string
, var
->name
,
3061 used_locations
, use_mask
, attr
);
3065 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
3066 /* Only track assigned variables for non-ES fragment shaders
3067 * to avoid overflowing the array.
3069 * At most one variable per fragment output component should
3072 assert(assigned_attr
< ARRAY_SIZE(assigned
));
3073 assigned
[assigned_attr
] = var
;
3077 used_locations
|= (use_mask
<< attr
);
3079 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
3081 * "A program with more than the value of MAX_VERTEX_ATTRIBS
3082 * active attribute variables may fail to link, unless
3083 * device-dependent optimizations are able to make the program
3084 * fit within available hardware resources. For the purposes
3085 * of this test, attribute variables of the type dvec3, dvec4,
3086 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
3087 * count as consuming twice as many attributes as equivalent
3088 * single-precision types. While these types use the same number
3089 * of generic attributes as their single-precision equivalents,
3090 * implementations are permitted to consume two single-precision
3091 * vectors of internal storage for each three- or four-component
3092 * double-precision vector."
3094 * Mark this attribute slot as taking up twice as much space
3095 * so we can count it properly against limits. According to
3096 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
3097 * is optional behavior, but it seems preferable.
3099 if (var
->type
->without_array()->is_dual_slot())
3100 double_storage_locations
|= (use_mask
<< attr
);
3106 if (num_attr
>= max_index
) {
3107 linker_error(prog
, "too many %s (max %u)",
3108 target_index
== MESA_SHADER_VERTEX
?
3109 "vertex shader inputs" : "fragment shader outputs",
3113 to_assign
[num_attr
].slots
= slots
;
3114 to_assign
[num_attr
].var
= var
;
3121 if (target_index
== MESA_SHADER_VERTEX
) {
3122 unsigned total_attribs_size
=
3123 util_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
3124 util_bitcount(double_storage_locations
);
3125 if (total_attribs_size
> max_index
) {
3127 "attempt to use %d vertex attribute slots only %d available ",
3128 total_attribs_size
, max_index
);
3133 /* If all of the attributes were assigned locations by the application (or
3134 * are built-in attributes with fixed locations), return early. This should
3135 * be the common case.
3140 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
3142 if (target_index
== MESA_SHADER_VERTEX
) {
3143 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
3144 * only be explicitly assigned by via glBindAttribLocation. Mark it as
3145 * reserved to prevent it from being automatically allocated below.
3147 find_deref_visitor
find("gl_Vertex");
3149 if (find
.variable_found())
3150 used_locations
|= (1 << 0);
3153 for (unsigned i
= 0; i
< num_attr
; i
++) {
3154 /* Mask representing the contiguous slots that will be used by this
3157 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
3159 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
3162 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
3163 ? "vertex shader input" : "fragment shader output";
3166 "insufficient contiguous locations "
3167 "available for %s `%s'\n",
3168 string
, to_assign
[i
].var
->name
);
3172 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
3173 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
3174 used_locations
|= (use_mask
<< location
);
3176 if (to_assign
[i
].var
->type
->without_array()->is_dual_slot())
3177 double_storage_locations
|= (use_mask
<< location
);
3180 /* Now that we have all the locations, from the GL 4.5 core spec, section
3181 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
3182 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
3183 * as equivalent single-precision types.
3185 if (target_index
== MESA_SHADER_VERTEX
) {
3186 unsigned total_attribs_size
=
3187 util_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
3188 util_bitcount(double_storage_locations
);
3189 if (total_attribs_size
> max_index
) {
3191 "attempt to use %d vertex attribute slots only %d available ",
3192 total_attribs_size
, max_index
);
3201 * Match explicit locations of outputs to inputs and deactivate the
3202 * unmatch flag if found so we don't optimise them away.
3205 match_explicit_outputs_to_inputs(gl_linked_shader
*producer
,
3206 gl_linked_shader
*consumer
)
3208 glsl_symbol_table parameters
;
3209 ir_variable
*explicit_locations
[MAX_VARYINGS_INCL_PATCH
][4] =
3212 /* Find all shader outputs in the "producer" stage.
3214 foreach_in_list(ir_instruction
, node
, producer
->ir
) {
3215 ir_variable
*const var
= node
->as_variable();
3217 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_shader_out
))
3220 if (var
->data
.explicit_location
&&
3221 var
->data
.location
>= VARYING_SLOT_VAR0
) {
3222 const unsigned idx
= var
->data
.location
- VARYING_SLOT_VAR0
;
3223 if (explicit_locations
[idx
][var
->data
.location_frac
] == NULL
)
3224 explicit_locations
[idx
][var
->data
.location_frac
] = var
;
3226 /* Always match TCS outputs. They are shared by all invocations
3227 * within a patch and can be used as shared memory.
3229 if (producer
->Stage
== MESA_SHADER_TESS_CTRL
)
3230 var
->data
.is_unmatched_generic_inout
= 0;
3234 /* Match inputs to outputs */
3235 foreach_in_list(ir_instruction
, node
, consumer
->ir
) {
3236 ir_variable
*const input
= node
->as_variable();
3238 if ((input
== NULL
) || (input
->data
.mode
!= ir_var_shader_in
))
3241 ir_variable
*output
= NULL
;
3242 if (input
->data
.explicit_location
3243 && input
->data
.location
>= VARYING_SLOT_VAR0
) {
3244 output
= explicit_locations
[input
->data
.location
- VARYING_SLOT_VAR0
]
3245 [input
->data
.location_frac
];
3247 if (output
!= NULL
){
3248 input
->data
.is_unmatched_generic_inout
= 0;
3249 output
->data
.is_unmatched_generic_inout
= 0;
3256 * Store the gl_FragDepth layout in the gl_shader_program struct.
3259 store_fragdepth_layout(struct gl_shader_program
*prog
)
3261 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
3265 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
3267 /* We don't look up the gl_FragDepth symbol directly because if
3268 * gl_FragDepth is not used in the shader, it's removed from the IR.
3269 * However, the symbol won't be removed from the symbol table.
3271 * We're only interested in the cases where the variable is NOT removed
3274 foreach_in_list(ir_instruction
, node
, ir
) {
3275 ir_variable
*const var
= node
->as_variable();
3277 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
3281 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
3282 switch (var
->data
.depth_layout
) {
3283 case ir_depth_layout_none
:
3284 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
3286 case ir_depth_layout_any
:
3287 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
3289 case ir_depth_layout_greater
:
3290 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
3292 case ir_depth_layout_less
:
3293 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
3295 case ir_depth_layout_unchanged
:
3296 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
3307 * Validate the resources used by a program versus the implementation limits
3310 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3312 unsigned total_uniform_blocks
= 0;
3313 unsigned total_shader_storage_blocks
= 0;
3315 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3316 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3321 if (sh
->Program
->info
.num_textures
>
3322 ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
3323 linker_error(prog
, "Too many %s shader texture samplers\n",
3324 _mesa_shader_stage_to_string(i
));
3327 if (sh
->num_uniform_components
>
3328 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
3329 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3330 linker_warning(prog
, "Too many %s shader default uniform block "
3331 "components, but the driver will try to optimize "
3332 "them out; this is non-portable out-of-spec "
3334 _mesa_shader_stage_to_string(i
));
3336 linker_error(prog
, "Too many %s shader default uniform block "
3338 _mesa_shader_stage_to_string(i
));
3342 if (sh
->num_combined_uniform_components
>
3343 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
3344 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3345 linker_warning(prog
, "Too many %s shader uniform components, "
3346 "but the driver will try to optimize them out; "
3347 "this is non-portable out-of-spec behavior\n",
3348 _mesa_shader_stage_to_string(i
));
3350 linker_error(prog
, "Too many %s shader uniform components\n",
3351 _mesa_shader_stage_to_string(i
));
3355 total_shader_storage_blocks
+= sh
->Program
->info
.num_ssbos
;
3356 total_uniform_blocks
+= sh
->Program
->info
.num_ubos
;
3358 const unsigned max_uniform_blocks
=
3359 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
3360 if (max_uniform_blocks
< sh
->Program
->info
.num_ubos
) {
3361 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
3362 _mesa_shader_stage_to_string(i
),
3363 sh
->Program
->info
.num_ubos
, max_uniform_blocks
);
3366 const unsigned max_shader_storage_blocks
=
3367 ctx
->Const
.Program
[i
].MaxShaderStorageBlocks
;
3368 if (max_shader_storage_blocks
< sh
->Program
->info
.num_ssbos
) {
3369 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
3370 _mesa_shader_stage_to_string(i
),
3371 sh
->Program
->info
.num_ssbos
, max_shader_storage_blocks
);
3375 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
3376 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
3377 total_uniform_blocks
, ctx
->Const
.MaxCombinedUniformBlocks
);
3380 if (total_shader_storage_blocks
> ctx
->Const
.MaxCombinedShaderStorageBlocks
) {
3381 linker_error(prog
, "Too many combined shader storage blocks (%d/%d)\n",
3382 total_shader_storage_blocks
,
3383 ctx
->Const
.MaxCombinedShaderStorageBlocks
);
3386 for (unsigned i
= 0; i
< prog
->data
->NumUniformBlocks
; i
++) {
3387 if (prog
->data
->UniformBlocks
[i
].UniformBufferSize
>
3388 ctx
->Const
.MaxUniformBlockSize
) {
3389 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
3390 prog
->data
->UniformBlocks
[i
].Name
,
3391 prog
->data
->UniformBlocks
[i
].UniformBufferSize
,
3392 ctx
->Const
.MaxUniformBlockSize
);
3396 for (unsigned i
= 0; i
< prog
->data
->NumShaderStorageBlocks
; i
++) {
3397 if (prog
->data
->ShaderStorageBlocks
[i
].UniformBufferSize
>
3398 ctx
->Const
.MaxShaderStorageBlockSize
) {
3399 linker_error(prog
, "Shader storage block %s too big (%d/%d)\n",
3400 prog
->data
->ShaderStorageBlocks
[i
].Name
,
3401 prog
->data
->ShaderStorageBlocks
[i
].UniformBufferSize
,
3402 ctx
->Const
.MaxShaderStorageBlockSize
);
3408 link_calculate_subroutine_compat(struct gl_shader_program
*prog
)
3410 unsigned mask
= prog
->data
->linked_stages
;
3412 const int i
= u_bit_scan(&mask
);
3413 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3415 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineUniformRemapTable
; j
++) {
3416 if (p
->sh
.SubroutineUniformRemapTable
[j
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
)
3419 struct gl_uniform_storage
*uni
= p
->sh
.SubroutineUniformRemapTable
[j
];
3425 if (p
->sh
.NumSubroutineFunctions
== 0) {
3426 linker_error(prog
, "subroutine uniform %s defined but no valid functions found\n", uni
->type
->name
);
3429 for (unsigned f
= 0; f
< p
->sh
.NumSubroutineFunctions
; f
++) {
3430 struct gl_subroutine_function
*fn
= &p
->sh
.SubroutineFunctions
[f
];
3431 for (int k
= 0; k
< fn
->num_compat_types
; k
++) {
3432 if (fn
->types
[k
] == uni
->type
) {
3438 uni
->num_compatible_subroutines
= count
;
3444 check_subroutine_resources(struct gl_shader_program
*prog
)
3446 unsigned mask
= prog
->data
->linked_stages
;
3448 const int i
= u_bit_scan(&mask
);
3449 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3451 if (p
->sh
.NumSubroutineUniformRemapTable
> MAX_SUBROUTINE_UNIFORM_LOCATIONS
) {
3452 linker_error(prog
, "Too many %s shader subroutine uniforms\n",
3453 _mesa_shader_stage_to_string(i
));
3458 * Validate shader image resources.
3461 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3463 unsigned total_image_units
= 0;
3464 unsigned fragment_outputs
= 0;
3465 unsigned total_shader_storage_blocks
= 0;
3467 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
3470 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3471 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3474 if (sh
->Program
->info
.num_images
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
3475 linker_error(prog
, "Too many %s shader image uniforms (%u > %u)\n",
3476 _mesa_shader_stage_to_string(i
),
3477 sh
->Program
->info
.num_images
,
3478 ctx
->Const
.Program
[i
].MaxImageUniforms
);
3480 total_image_units
+= sh
->Program
->info
.num_images
;
3481 total_shader_storage_blocks
+= sh
->Program
->info
.num_ssbos
;
3483 if (i
== MESA_SHADER_FRAGMENT
) {
3484 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3485 ir_variable
*var
= node
->as_variable();
3486 if (var
&& var
->data
.mode
== ir_var_shader_out
)
3487 /* since there are no double fs outputs - pass false */
3488 fragment_outputs
+= var
->type
->count_attribute_slots(false);
3494 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
3495 linker_error(prog
, "Too many combined image uniforms\n");
3497 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
3498 ctx
->Const
.MaxCombinedShaderOutputResources
)
3499 linker_error(prog
, "Too many combined image uniforms, shader storage "
3500 " buffers and fragment outputs\n");
3505 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3506 * for a variable, checks for overlaps between other uniforms using explicit
3510 reserve_explicit_locations(struct gl_shader_program
*prog
,
3511 string_to_uint_map
*map
, ir_variable
*var
)
3513 unsigned slots
= var
->type
->uniform_locations();
3514 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3515 unsigned return_value
= slots
;
3517 /* Resize remap table if locations do not fit in the current one. */
3518 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
3519 prog
->UniformRemapTable
=
3520 reralloc(prog
, prog
->UniformRemapTable
,
3521 gl_uniform_storage
*,
3524 if (!prog
->UniformRemapTable
) {
3525 linker_error(prog
, "Out of memory during linking.\n");
3529 /* Initialize allocated space. */
3530 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
3531 prog
->UniformRemapTable
[i
] = NULL
;
3533 prog
->NumUniformRemapTable
= max_loc
+ 1;
3536 for (unsigned i
= 0; i
< slots
; i
++) {
3537 unsigned loc
= var
->data
.location
+ i
;
3539 /* Check if location is already used. */
3540 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3542 /* Possibly same uniform from a different stage, this is ok. */
3544 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
) {
3549 /* ARB_explicit_uniform_location specification states:
3551 * "No two default-block uniform variables in the program can have
3552 * the same location, even if they are unused, otherwise a compiler
3553 * or linker error will be generated."
3556 "location qualifier for uniform %s overlaps "
3557 "previously used location\n",
3562 /* Initialize location as inactive before optimization
3563 * rounds and location assignment.
3565 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3568 /* Note, base location used for arrays. */
3569 map
->put(var
->data
.location
, var
->name
);
3571 return return_value
;
3575 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3576 struct gl_program
*p
,
3579 unsigned slots
= var
->type
->uniform_locations();
3580 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3582 /* Resize remap table if locations do not fit in the current one. */
3583 if (max_loc
+ 1 > p
->sh
.NumSubroutineUniformRemapTable
) {
3584 p
->sh
.SubroutineUniformRemapTable
=
3585 reralloc(p
, p
->sh
.SubroutineUniformRemapTable
,
3586 gl_uniform_storage
*,
3589 if (!p
->sh
.SubroutineUniformRemapTable
) {
3590 linker_error(prog
, "Out of memory during linking.\n");
3594 /* Initialize allocated space. */
3595 for (unsigned i
= p
->sh
.NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3596 p
->sh
.SubroutineUniformRemapTable
[i
] = NULL
;
3598 p
->sh
.NumSubroutineUniformRemapTable
= max_loc
+ 1;
3601 for (unsigned i
= 0; i
< slots
; i
++) {
3602 unsigned loc
= var
->data
.location
+ i
;
3604 /* Check if location is already used. */
3605 if (p
->sh
.SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3607 /* ARB_explicit_uniform_location specification states:
3608 * "No two subroutine uniform variables can have the same location
3609 * in the same shader stage, otherwise a compiler or linker error
3610 * will be generated."
3613 "location qualifier for uniform %s overlaps "
3614 "previously used location\n",
3619 /* Initialize location as inactive before optimization
3620 * rounds and location assignment.
3622 p
->sh
.SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3628 * Check and reserve all explicit uniform locations, called before
3629 * any optimizations happen to handle also inactive uniforms and
3630 * inactive array elements that may get trimmed away.
3633 check_explicit_uniform_locations(struct gl_context
*ctx
,
3634 struct gl_shader_program
*prog
)
3636 prog
->NumExplicitUniformLocations
= 0;
3638 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3641 /* This map is used to detect if overlapping explicit locations
3642 * occur with the same uniform (from different stage) or a different one.
3644 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3647 linker_error(prog
, "Out of memory during linking.\n");
3651 unsigned entries_total
= 0;
3652 unsigned mask
= prog
->data
->linked_stages
;
3654 const int i
= u_bit_scan(&mask
);
3655 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3657 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
3658 ir_variable
*var
= node
->as_variable();
3659 if (!var
|| var
->data
.mode
!= ir_var_uniform
)
3662 if (var
->data
.explicit_location
) {
3664 if (var
->type
->without_array()->is_subroutine())
3665 ret
= reserve_subroutine_explicit_locations(prog
, p
, var
);
3667 int slots
= reserve_explicit_locations(prog
, uniform_map
,
3671 entries_total
+= slots
;
3682 link_util_update_empty_uniform_locations(prog
);
3685 prog
->NumExplicitUniformLocations
= entries_total
;
3689 should_add_buffer_variable(struct gl_shader_program
*shProg
,
3690 GLenum type
, const char *name
)
3692 bool found_interface
= false;
3693 unsigned block_name_len
= 0;
3694 const char *block_name_dot
= strchr(name
, '.');
3696 /* These rules only apply to buffer variables. So we return
3697 * true for the rest of types.
3699 if (type
!= GL_BUFFER_VARIABLE
)
3702 for (unsigned i
= 0; i
< shProg
->data
->NumShaderStorageBlocks
; i
++) {
3703 const char *block_name
= shProg
->data
->ShaderStorageBlocks
[i
].Name
;
3704 block_name_len
= strlen(block_name
);
3706 const char *block_square_bracket
= strchr(block_name
, '[');
3707 if (block_square_bracket
) {
3708 /* The block is part of an array of named interfaces,
3709 * for the name comparison we ignore the "[x]" part.
3711 block_name_len
-= strlen(block_square_bracket
);
3714 if (block_name_dot
) {
3715 /* Check if the variable name starts with the interface
3716 * name. The interface name (if present) should have the
3717 * length than the interface block name we are comparing to.
3719 unsigned len
= strlen(name
) - strlen(block_name_dot
);
3720 if (len
!= block_name_len
)
3724 if (strncmp(block_name
, name
, block_name_len
) == 0) {
3725 found_interface
= true;
3730 /* We remove the interface name from the buffer variable name,
3731 * including the dot that follows it.
3733 if (found_interface
)
3734 name
= name
+ block_name_len
+ 1;
3736 /* The ARB_program_interface_query spec says:
3738 * "For an active shader storage block member declared as an array, an
3739 * entry will be generated only for the first array element, regardless
3740 * of its type. For arrays of aggregate types, the enumeration rules
3741 * are applied recursively for the single enumerated array element."
3743 const char *struct_first_dot
= strchr(name
, '.');
3744 const char *first_square_bracket
= strchr(name
, '[');
3746 /* The buffer variable is on top level and it is not an array */
3747 if (!first_square_bracket
) {
3749 /* The shader storage block member is a struct, then generate the entry */
3750 } else if (struct_first_dot
&& struct_first_dot
< first_square_bracket
) {
3753 /* Shader storage block member is an array, only generate an entry for the
3754 * first array element.
3756 if (strncmp(first_square_bracket
, "[0]", 3) == 0)
3763 /* Function checks if a variable var is a packed varying and
3764 * if given name is part of packed varying's list.
3766 * If a variable is a packed varying, it has a name like
3767 * 'packed:a,b,c' where a, b and c are separate variables.
3770 included_in_packed_varying(ir_variable
*var
, const char *name
)
3772 if (strncmp(var
->name
, "packed:", 7) != 0)
3775 char *list
= strdup(var
->name
+ 7);
3780 char *token
= strtok_r(list
, ",", &saveptr
);
3782 if (strcmp(token
, name
) == 0) {
3786 token
= strtok_r(NULL
, ",", &saveptr
);
3793 * Function builds a stage reference bitmask from variable name.
3796 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3801 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3802 * used for reference mask in gl_program_resource will need to be changed.
3804 assert(MESA_SHADER_STAGES
< 8);
3806 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3807 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
3811 /* Shader symbol table may contain variables that have
3812 * been optimized away. Search IR for the variable instead.
3814 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3815 ir_variable
*var
= node
->as_variable();
3817 unsigned baselen
= strlen(var
->name
);
3819 if (included_in_packed_varying(var
, name
)) {
3824 /* Type needs to match if specified, otherwise we might
3825 * pick a variable with same name but different interface.
3827 if (var
->data
.mode
!= mode
)
3830 if (strncmp(var
->name
, name
, baselen
) == 0) {
3831 /* Check for exact name matches but also check for arrays and
3834 if (name
[baselen
] == '\0' ||
3835 name
[baselen
] == '[' ||
3836 name
[baselen
] == '.') {
3848 * Create gl_shader_variable from ir_variable class.
3850 static gl_shader_variable
*
3851 create_shader_variable(struct gl_shader_program
*shProg
,
3852 const ir_variable
*in
,
3853 const char *name
, const glsl_type
*type
,
3854 const glsl_type
*interface_type
,
3855 bool use_implicit_location
, int location
,
3856 const glsl_type
*outermost_struct_type
)
3858 /* Allocate zero-initialized memory to ensure that bitfield padding
3861 gl_shader_variable
*out
= rzalloc(shProg
, struct gl_shader_variable
);
3865 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3866 * expect to see gl_VertexID in the program resource list. Pretend.
3868 if (in
->data
.mode
== ir_var_system_value
&&
3869 in
->data
.location
== SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
) {
3870 out
->name
= ralloc_strdup(shProg
, "gl_VertexID");
3871 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3872 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_OUTER
) ||
3873 (in
->data
.mode
== ir_var_system_value
&&
3874 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_OUTER
)) {
3875 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelOuter");
3876 type
= glsl_type::get_array_instance(glsl_type::float_type
, 4);
3877 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3878 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_INNER
) ||
3879 (in
->data
.mode
== ir_var_system_value
&&
3880 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_INNER
)) {
3881 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelInner");
3882 type
= glsl_type::get_array_instance(glsl_type::float_type
, 2);
3884 out
->name
= ralloc_strdup(shProg
, name
);
3890 /* The ARB_program_interface_query spec says:
3892 * "Not all active variables are assigned valid locations; the
3893 * following variables will have an effective location of -1:
3895 * * uniforms declared as atomic counters;
3897 * * members of a uniform block;
3899 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3901 * * inputs or outputs not declared with a "location" layout
3902 * qualifier, except for vertex shader inputs and fragment shader
3905 if (in
->type
->is_atomic_uint() || is_gl_identifier(in
->name
) ||
3906 !(in
->data
.explicit_location
|| use_implicit_location
)) {
3909 out
->location
= location
;
3913 out
->outermost_struct_type
= outermost_struct_type
;
3914 out
->interface_type
= interface_type
;
3915 out
->component
= in
->data
.location_frac
;
3916 out
->index
= in
->data
.index
;
3917 out
->patch
= in
->data
.patch
;
3918 out
->mode
= in
->data
.mode
;
3919 out
->interpolation
= in
->data
.interpolation
;
3920 out
->explicit_location
= in
->data
.explicit_location
;
3921 out
->precision
= in
->data
.precision
;
3927 add_shader_variable(const struct gl_context
*ctx
,
3928 struct gl_shader_program
*shProg
,
3929 struct set
*resource_set
,
3930 unsigned stage_mask
,
3931 GLenum programInterface
, ir_variable
*var
,
3932 const char *name
, const glsl_type
*type
,
3933 bool use_implicit_location
, int location
,
3934 bool inouts_share_location
,
3935 const glsl_type
*outermost_struct_type
= NULL
)
3937 const glsl_type
*interface_type
= var
->get_interface_type();
3939 if (outermost_struct_type
== NULL
) {
3940 if (var
->data
.from_named_ifc_block
) {
3941 const char *interface_name
= interface_type
->name
;
3943 if (interface_type
->is_array()) {
3944 /* Issue #16 of the ARB_program_interface_query spec says:
3946 * "* If a variable is a member of an interface block without an
3947 * instance name, it is enumerated using just the variable name.
3949 * * If a variable is a member of an interface block with an
3950 * instance name, it is enumerated as "BlockName.Member", where
3951 * "BlockName" is the name of the interface block (not the
3952 * instance name) and "Member" is the name of the variable."
3954 * In particular, it indicates that it should be "BlockName",
3955 * not "BlockName[array length]". The conformance suite and
3956 * dEQP both require this behavior.
3958 * Here, we unwrap the extra array level added by named interface
3959 * block array lowering so we have the correct variable type. We
3960 * also unwrap the interface type when constructing the name.
3962 * We leave interface_type the same so that ES 3.x SSO pipeline
3963 * validation can enforce the rules requiring array length to
3964 * match on interface blocks.
3966 type
= type
->fields
.array
;
3968 interface_name
= interface_type
->fields
.array
->name
;
3971 name
= ralloc_asprintf(shProg
, "%s.%s", interface_name
, name
);
3975 switch (type
->base_type
) {
3976 case GLSL_TYPE_STRUCT
: {
3977 /* The ARB_program_interface_query spec says:
3979 * "For an active variable declared as a structure, a separate entry
3980 * will be generated for each active structure member. The name of
3981 * each entry is formed by concatenating the name of the structure,
3982 * the "." character, and the name of the structure member. If a
3983 * structure member to enumerate is itself a structure or array,
3984 * these enumeration rules are applied recursively."
3986 if (outermost_struct_type
== NULL
)
3987 outermost_struct_type
= type
;
3989 unsigned field_location
= location
;
3990 for (unsigned i
= 0; i
< type
->length
; i
++) {
3991 const struct glsl_struct_field
*field
= &type
->fields
.structure
[i
];
3992 char *field_name
= ralloc_asprintf(shProg
, "%s.%s", name
, field
->name
);
3993 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3994 stage_mask
, programInterface
,
3995 var
, field_name
, field
->type
,
3996 use_implicit_location
, field_location
,
3997 false, outermost_struct_type
))
4000 field_location
+= field
->type
->count_attribute_slots(false);
4005 case GLSL_TYPE_ARRAY
: {
4006 /* The ARB_program_interface_query spec says:
4008 * "For an active variable declared as an array of basic types, a
4009 * single entry will be generated, with its name string formed by
4010 * concatenating the name of the array and the string "[0]"."
4012 * "For an active variable declared as an array of an aggregate data
4013 * type (structures or arrays), a separate entry will be generated
4014 * for each active array element, unless noted immediately below.
4015 * The name of each entry is formed by concatenating the name of
4016 * the array, the "[" character, an integer identifying the element
4017 * number, and the "]" character. These enumeration rules are
4018 * applied recursively, treating each enumerated array element as a
4019 * separate active variable."
4021 const struct glsl_type
*array_type
= type
->fields
.array
;
4022 if (array_type
->base_type
== GLSL_TYPE_STRUCT
||
4023 array_type
->base_type
== GLSL_TYPE_ARRAY
) {
4024 unsigned elem_location
= location
;
4025 unsigned stride
= inouts_share_location
? 0 :
4026 array_type
->count_attribute_slots(false);
4027 for (unsigned i
= 0; i
< type
->length
; i
++) {
4028 char *elem
= ralloc_asprintf(shProg
, "%s[%d]", name
, i
);
4029 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4030 stage_mask
, programInterface
,
4031 var
, elem
, array_type
,
4032 use_implicit_location
, elem_location
,
4033 false, outermost_struct_type
))
4035 elem_location
+= stride
;
4043 /* The ARB_program_interface_query spec says:
4045 * "For an active variable declared as a single instance of a basic
4046 * type, a single entry will be generated, using the variable name
4047 * from the shader source."
4049 gl_shader_variable
*sha_v
=
4050 create_shader_variable(shProg
, var
, name
, type
, interface_type
,
4051 use_implicit_location
, location
,
4052 outermost_struct_type
);
4056 return link_util_add_program_resource(shProg
, resource_set
,
4057 programInterface
, sha_v
, stage_mask
);
4063 inout_has_same_location(const ir_variable
*var
, unsigned stage
)
4065 if (!var
->data
.patch
&&
4066 ((var
->data
.mode
== ir_var_shader_out
&&
4067 stage
== MESA_SHADER_TESS_CTRL
) ||
4068 (var
->data
.mode
== ir_var_shader_in
&&
4069 (stage
== MESA_SHADER_TESS_CTRL
|| stage
== MESA_SHADER_TESS_EVAL
||
4070 stage
== MESA_SHADER_GEOMETRY
))))
4077 add_interface_variables(const struct gl_context
*ctx
,
4078 struct gl_shader_program
*shProg
,
4079 struct set
*resource_set
,
4080 unsigned stage
, GLenum programInterface
)
4082 exec_list
*ir
= shProg
->_LinkedShaders
[stage
]->ir
;
4084 foreach_in_list(ir_instruction
, node
, ir
) {
4085 ir_variable
*var
= node
->as_variable();
4087 if (!var
|| var
->data
.how_declared
== ir_var_hidden
)
4092 switch (var
->data
.mode
) {
4093 case ir_var_system_value
:
4094 case ir_var_shader_in
:
4095 if (programInterface
!= GL_PROGRAM_INPUT
)
4097 loc_bias
= (stage
== MESA_SHADER_VERTEX
) ? int(VERT_ATTRIB_GENERIC0
)
4098 : int(VARYING_SLOT_VAR0
);
4100 case ir_var_shader_out
:
4101 if (programInterface
!= GL_PROGRAM_OUTPUT
)
4103 loc_bias
= (stage
== MESA_SHADER_FRAGMENT
) ? int(FRAG_RESULT_DATA0
)
4104 : int(VARYING_SLOT_VAR0
);
4110 if (var
->data
.patch
)
4111 loc_bias
= int(VARYING_SLOT_PATCH0
);
4113 /* Skip packed varyings, packed varyings are handled separately
4114 * by add_packed_varyings.
4116 if (strncmp(var
->name
, "packed:", 7) == 0)
4119 /* Skip fragdata arrays, these are handled separately
4120 * by add_fragdata_arrays.
4122 if (strncmp(var
->name
, "gl_out_FragData", 15) == 0)
4125 const bool vs_input_or_fs_output
=
4126 (stage
== MESA_SHADER_VERTEX
&& var
->data
.mode
== ir_var_shader_in
) ||
4127 (stage
== MESA_SHADER_FRAGMENT
&& var
->data
.mode
== ir_var_shader_out
);
4129 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4130 1 << stage
, programInterface
,
4131 var
, var
->name
, var
->type
, vs_input_or_fs_output
,
4132 var
->data
.location
- loc_bias
,
4133 inout_has_same_location(var
, stage
)))
4140 add_packed_varyings(const struct gl_context
*ctx
,
4141 struct gl_shader_program
*shProg
,
4142 struct set
*resource_set
,
4143 int stage
, GLenum type
)
4145 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[stage
];
4148 if (!sh
|| !sh
->packed_varyings
)
4151 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
4152 ir_variable
*var
= node
->as_variable();
4154 switch (var
->data
.mode
) {
4155 case ir_var_shader_in
:
4156 iface
= GL_PROGRAM_INPUT
;
4158 case ir_var_shader_out
:
4159 iface
= GL_PROGRAM_OUTPUT
;
4162 unreachable("unexpected type");
4165 if (type
== iface
) {
4166 const int stage_mask
=
4167 build_stageref(shProg
, var
->name
, var
->data
.mode
);
4168 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4170 iface
, var
, var
->name
, var
->type
, false,
4171 var
->data
.location
- VARYING_SLOT_VAR0
,
4172 inout_has_same_location(var
, stage
)))
4181 add_fragdata_arrays(const struct gl_context
*ctx
,
4182 struct gl_shader_program
*shProg
,
4183 struct set
*resource_set
)
4185 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4187 if (!sh
|| !sh
->fragdata_arrays
)
4190 foreach_in_list(ir_instruction
, node
, sh
->fragdata_arrays
) {
4191 ir_variable
*var
= node
->as_variable();
4193 assert(var
->data
.mode
== ir_var_shader_out
);
4195 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4196 1 << MESA_SHADER_FRAGMENT
,
4197 GL_PROGRAM_OUTPUT
, var
, var
->name
, var
->type
,
4198 true, var
->data
.location
- FRAG_RESULT_DATA0
,
4207 get_top_level_name(const char *name
)
4209 const char *first_dot
= strchr(name
, '.');
4210 const char *first_square_bracket
= strchr(name
, '[');
4213 /* The ARB_program_interface_query spec says:
4215 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4216 * the number of active array elements of the top-level shader storage
4217 * block member containing to the active variable is written to
4218 * <params>. If the top-level block member is not declared as an
4219 * array, the value one is written to <params>. If the top-level block
4220 * member is an array with no declared size, the value zero is written
4224 /* The buffer variable is on top level.*/
4225 if (!first_square_bracket
&& !first_dot
)
4226 name_size
= strlen(name
);
4227 else if ((!first_square_bracket
||
4228 (first_dot
&& first_dot
< first_square_bracket
)))
4229 name_size
= first_dot
- name
;
4231 name_size
= first_square_bracket
- name
;
4233 return strndup(name
, name_size
);
4237 get_var_name(const char *name
)
4239 const char *first_dot
= strchr(name
, '.');
4242 return strdup(name
);
4244 return strndup(first_dot
+1, strlen(first_dot
) - 1);
4248 is_top_level_shader_storage_block_member(const char* name
,
4249 const char* interface_name
,
4250 const char* field_name
)
4252 bool result
= false;
4254 /* If the given variable is already a top-level shader storage
4255 * block member, then return array_size = 1.
4256 * We could have two possibilities: if we have an instanced
4257 * shader storage block or not instanced.
4259 * For the first, we check create a name as it was in top level and
4260 * compare it with the real name. If they are the same, then
4261 * the variable is already at top-level.
4263 * Full instanced name is: interface name + '.' + var name +
4266 int name_length
= strlen(interface_name
) + 1 + strlen(field_name
) + 1;
4267 char *full_instanced_name
= (char *) calloc(name_length
, sizeof(char));
4268 if (!full_instanced_name
) {
4269 fprintf(stderr
, "%s: Cannot allocate space for name\n", __func__
);
4273 util_snprintf(full_instanced_name
, name_length
, "%s.%s",
4274 interface_name
, field_name
);
4276 /* Check if its top-level shader storage block member of an
4277 * instanced interface block, or of a unnamed interface block.
4279 if (strcmp(name
, full_instanced_name
) == 0 ||
4280 strcmp(name
, field_name
) == 0)
4283 free(full_instanced_name
);
4288 get_array_size(struct gl_uniform_storage
*uni
, const glsl_struct_field
*field
,
4289 char *interface_name
, char *var_name
)
4291 /* The ARB_program_interface_query spec says:
4293 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4294 * the number of active array elements of the top-level shader storage
4295 * block member containing to the active variable is written to
4296 * <params>. If the top-level block member is not declared as an
4297 * array, the value one is written to <params>. If the top-level block
4298 * member is an array with no declared size, the value zero is written
4301 if (is_top_level_shader_storage_block_member(uni
->name
,
4305 else if (field
->type
->is_unsized_array())
4307 else if (field
->type
->is_array())
4308 return field
->type
->length
;
4314 get_array_stride(struct gl_context
*ctx
, struct gl_uniform_storage
*uni
,
4315 const glsl_type
*iface
, const glsl_struct_field
*field
,
4316 char *interface_name
, char *var_name
)
4318 /* The ARB_program_interface_query spec says:
4320 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
4321 * identifying the stride between array elements of the top-level
4322 * shader storage block member containing the active variable is
4323 * written to <params>. For top-level block members declared as
4324 * arrays, the value written is the difference, in basic machine units,
4325 * between the offsets of the active variable for consecutive elements
4326 * in the top-level array. For top-level block members not declared as
4327 * an array, zero is written to <params>."
4329 if (field
->type
->is_array()) {
4330 const enum glsl_matrix_layout matrix_layout
=
4331 glsl_matrix_layout(field
->matrix_layout
);
4332 bool row_major
= matrix_layout
== GLSL_MATRIX_LAYOUT_ROW_MAJOR
;
4333 const glsl_type
*array_type
= field
->type
->fields
.array
;
4335 if (is_top_level_shader_storage_block_member(uni
->name
,
4340 if (GLSL_INTERFACE_PACKING_STD140
==
4342 get_internal_ifc_packing(ctx
->Const
.UseSTD430AsDefaultPacking
)) {
4343 if (array_type
->is_struct() || array_type
->is_array())
4344 return glsl_align(array_type
->std140_size(row_major
), 16);
4346 return MAX2(array_type
->std140_base_alignment(row_major
), 16);
4348 return array_type
->std430_array_stride(row_major
);
4355 calculate_array_size_and_stride(struct gl_context
*ctx
,
4356 struct gl_shader_program
*shProg
,
4357 struct gl_uniform_storage
*uni
)
4359 int block_index
= uni
->block_index
;
4360 int array_size
= -1;
4361 int array_stride
= -1;
4362 char *var_name
= get_top_level_name(uni
->name
);
4363 char *interface_name
=
4364 get_top_level_name(uni
->is_shader_storage
?
4365 shProg
->data
->ShaderStorageBlocks
[block_index
].Name
:
4366 shProg
->data
->UniformBlocks
[block_index
].Name
);
4368 if (strcmp(var_name
, interface_name
) == 0) {
4369 /* Deal with instanced array of SSBOs */
4370 char *temp_name
= get_var_name(uni
->name
);
4372 linker_error(shProg
, "Out of memory during linking.\n");
4373 goto write_top_level_array_size_and_stride
;
4376 var_name
= get_top_level_name(temp_name
);
4379 linker_error(shProg
, "Out of memory during linking.\n");
4380 goto write_top_level_array_size_and_stride
;
4384 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4385 const gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
4389 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
4390 ir_variable
*var
= node
->as_variable();
4391 if (!var
|| !var
->get_interface_type() ||
4392 var
->data
.mode
!= ir_var_shader_storage
)
4395 const glsl_type
*iface
= var
->get_interface_type();
4397 if (strcmp(interface_name
, iface
->name
) != 0)
4400 for (unsigned i
= 0; i
< iface
->length
; i
++) {
4401 const glsl_struct_field
*field
= &iface
->fields
.structure
[i
];
4402 if (strcmp(field
->name
, var_name
) != 0)
4405 array_stride
= get_array_stride(ctx
, uni
, iface
, field
,
4406 interface_name
, var_name
);
4407 array_size
= get_array_size(uni
, field
, interface_name
, var_name
);
4408 goto write_top_level_array_size_and_stride
;
4412 write_top_level_array_size_and_stride
:
4413 free(interface_name
);
4415 uni
->top_level_array_stride
= array_stride
;
4416 uni
->top_level_array_size
= array_size
;
4420 * Builds up a list of program resources that point to existing
4424 build_program_resource_list(struct gl_context
*ctx
,
4425 struct gl_shader_program
*shProg
)
4427 /* Rebuild resource list. */
4428 if (shProg
->data
->ProgramResourceList
) {
4429 ralloc_free(shProg
->data
->ProgramResourceList
);
4430 shProg
->data
->ProgramResourceList
= NULL
;
4431 shProg
->data
->NumProgramResourceList
= 0;
4434 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
4436 /* Determine first input and final output stage. These are used to
4437 * detect which variables should be enumerated in the resource list
4438 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4440 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4441 if (!shProg
->_LinkedShaders
[i
])
4443 if (input_stage
== MESA_SHADER_STAGES
)
4448 /* Empty shader, no resources. */
4449 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
4452 struct set
*resource_set
= _mesa_pointer_set_create(NULL
);
4454 /* Program interface needs to expose varyings in case of SSO. */
4455 if (shProg
->SeparateShader
) {
4456 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4457 input_stage
, GL_PROGRAM_INPUT
))
4460 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4461 output_stage
, GL_PROGRAM_OUTPUT
))
4465 if (!add_fragdata_arrays(ctx
, shProg
, resource_set
))
4468 /* Add inputs and outputs to the resource list. */
4469 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4470 input_stage
, GL_PROGRAM_INPUT
))
4473 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4474 output_stage
, GL_PROGRAM_OUTPUT
))
4477 if (shProg
->last_vert_prog
) {
4478 struct gl_transform_feedback_info
*linked_xfb
=
4479 shProg
->last_vert_prog
->sh
.LinkedTransformFeedback
;
4481 /* Add transform feedback varyings. */
4482 if (linked_xfb
->NumVarying
> 0) {
4483 for (int i
= 0; i
< linked_xfb
->NumVarying
; i
++) {
4484 if (!link_util_add_program_resource(shProg
, resource_set
,
4485 GL_TRANSFORM_FEEDBACK_VARYING
,
4486 &linked_xfb
->Varyings
[i
], 0))
4491 /* Add transform feedback buffers. */
4492 for (unsigned i
= 0; i
< ctx
->Const
.MaxTransformFeedbackBuffers
; i
++) {
4493 if ((linked_xfb
->ActiveBuffers
>> i
) & 1) {
4494 linked_xfb
->Buffers
[i
].Binding
= i
;
4495 if (!link_util_add_program_resource(shProg
, resource_set
,
4496 GL_TRANSFORM_FEEDBACK_BUFFER
,
4497 &linked_xfb
->Buffers
[i
], 0))
4503 /* Add uniforms from uniform storage. */
4504 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4505 /* Do not add uniforms internally used by Mesa. */
4506 if (shProg
->data
->UniformStorage
[i
].hidden
)
4510 build_stageref(shProg
, shProg
->data
->UniformStorage
[i
].name
,
4513 /* Add stagereferences for uniforms in a uniform block. */
4514 bool is_shader_storage
=
4515 shProg
->data
->UniformStorage
[i
].is_shader_storage
;
4516 int block_index
= shProg
->data
->UniformStorage
[i
].block_index
;
4517 if (block_index
!= -1) {
4518 stageref
|= is_shader_storage
?
4519 shProg
->data
->ShaderStorageBlocks
[block_index
].stageref
:
4520 shProg
->data
->UniformBlocks
[block_index
].stageref
;
4523 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
4524 if (!should_add_buffer_variable(shProg
, type
,
4525 shProg
->data
->UniformStorage
[i
].name
))
4528 if (is_shader_storage
) {
4529 calculate_array_size_and_stride(ctx
, shProg
,
4530 &shProg
->data
->UniformStorage
[i
]);
4533 if (!link_util_add_program_resource(shProg
, resource_set
, type
,
4534 &shProg
->data
->UniformStorage
[i
], stageref
))
4538 /* Add program uniform blocks. */
4539 for (unsigned i
= 0; i
< shProg
->data
->NumUniformBlocks
; i
++) {
4540 if (!link_util_add_program_resource(shProg
, resource_set
, GL_UNIFORM_BLOCK
,
4541 &shProg
->data
->UniformBlocks
[i
], 0))
4545 /* Add program shader storage blocks. */
4546 for (unsigned i
= 0; i
< shProg
->data
->NumShaderStorageBlocks
; i
++) {
4547 if (!link_util_add_program_resource(shProg
, resource_set
, GL_SHADER_STORAGE_BLOCK
,
4548 &shProg
->data
->ShaderStorageBlocks
[i
], 0))
4552 /* Add atomic counter buffers. */
4553 for (unsigned i
= 0; i
< shProg
->data
->NumAtomicBuffers
; i
++) {
4554 if (!link_util_add_program_resource(shProg
, resource_set
, GL_ATOMIC_COUNTER_BUFFER
,
4555 &shProg
->data
->AtomicBuffers
[i
], 0))
4559 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4561 if (!shProg
->data
->UniformStorage
[i
].hidden
)
4564 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
4565 if (!shProg
->data
->UniformStorage
[i
].opaque
[j
].active
||
4566 !shProg
->data
->UniformStorage
[i
].type
->is_subroutine())
4569 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
4570 /* add shader subroutines */
4571 if (!link_util_add_program_resource(shProg
, resource_set
,
4572 type
, &shProg
->data
->UniformStorage
[i
], 0))
4577 unsigned mask
= shProg
->data
->linked_stages
;
4579 const int i
= u_bit_scan(&mask
);
4580 struct gl_program
*p
= shProg
->_LinkedShaders
[i
]->Program
;
4582 GLuint type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
4583 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4584 if (!link_util_add_program_resource(shProg
, resource_set
,
4585 type
, &p
->sh
.SubroutineFunctions
[j
], 0))
4590 _mesa_set_destroy(resource_set
, NULL
);
4594 * This check is done to make sure we allow only constant expression
4595 * indexing and "constant-index-expression" (indexing with an expression
4596 * that includes loop induction variable).
4599 validate_sampler_array_indexing(struct gl_context
*ctx
,
4600 struct gl_shader_program
*prog
)
4602 dynamic_sampler_array_indexing_visitor v
;
4603 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4604 if (prog
->_LinkedShaders
[i
] == NULL
)
4607 bool no_dynamic_indexing
=
4608 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
4610 /* Search for array derefs in shader. */
4611 v
.run(prog
->_LinkedShaders
[i
]->ir
);
4612 if (v
.uses_dynamic_sampler_array_indexing()) {
4613 const char *msg
= "sampler arrays indexed with non-constant "
4614 "expressions is forbidden in GLSL %s %u";
4615 /* Backend has indicated that it has no dynamic indexing support. */
4616 if (no_dynamic_indexing
) {
4617 linker_error(prog
, msg
, prog
->IsES
? "ES" : "",
4618 prog
->data
->Version
);
4621 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "",
4622 prog
->data
->Version
);
4630 link_assign_subroutine_types(struct gl_shader_program
*prog
)
4632 unsigned mask
= prog
->data
->linked_stages
;
4634 const int i
= u_bit_scan(&mask
);
4635 gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
4637 p
->sh
.MaxSubroutineFunctionIndex
= 0;
4638 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
4639 ir_function
*fn
= node
->as_function();
4643 if (fn
->is_subroutine
)
4644 p
->sh
.NumSubroutineUniformTypes
++;
4646 if (!fn
->num_subroutine_types
)
4649 /* these should have been calculated earlier. */
4650 assert(fn
->subroutine_index
!= -1);
4651 if (p
->sh
.NumSubroutineFunctions
+ 1 > MAX_SUBROUTINES
) {
4652 linker_error(prog
, "Too many subroutine functions declared.\n");
4655 p
->sh
.SubroutineFunctions
= reralloc(p
, p
->sh
.SubroutineFunctions
,
4656 struct gl_subroutine_function
,
4657 p
->sh
.NumSubroutineFunctions
+ 1);
4658 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].name
= ralloc_strdup(p
, fn
->name
);
4659 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
4660 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
=
4661 ralloc_array(p
, const struct glsl_type
*,
4662 fn
->num_subroutine_types
);
4664 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4667 * "Each subroutine with an index qualifier in the shader must be
4668 * given a unique index, otherwise a compile or link error will be
4671 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4672 if (p
->sh
.SubroutineFunctions
[j
].index
!= -1 &&
4673 p
->sh
.SubroutineFunctions
[j
].index
== fn
->subroutine_index
) {
4674 linker_error(prog
, "each subroutine index qualifier in the "
4675 "shader must be unique\n");
4679 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].index
=
4680 fn
->subroutine_index
;
4682 if (fn
->subroutine_index
> (int)p
->sh
.MaxSubroutineFunctionIndex
)
4683 p
->sh
.MaxSubroutineFunctionIndex
= fn
->subroutine_index
;
4685 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
4686 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
4687 p
->sh
.NumSubroutineFunctions
++;
4693 verify_subroutine_associated_funcs(struct gl_shader_program
*prog
)
4695 unsigned mask
= prog
->data
->linked_stages
;
4697 const int i
= u_bit_scan(&mask
);
4698 gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
4699 glsl_symbol_table
*symbols
= prog
->_LinkedShaders
[i
]->symbols
;
4701 /* Section 6.1.2 (Subroutines) of the GLSL 4.00 spec says:
4703 * "A program will fail to compile or link if any shader
4704 * or stage contains two or more functions with the same
4705 * name if the name is associated with a subroutine type."
4707 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4708 unsigned definitions
= 0;
4709 char *name
= p
->sh
.SubroutineFunctions
[j
].name
;
4710 ir_function
*fn
= symbols
->get_function(name
);
4712 /* Calculate number of function definitions with the same name */
4713 foreach_in_list(ir_function_signature
, sig
, &fn
->signatures
) {
4714 if (sig
->is_defined
) {
4715 if (++definitions
> 1) {
4716 linker_error(prog
, "%s shader contains two or more function "
4717 "definitions with name `%s', which is "
4718 "associated with a subroutine type.\n",
4719 _mesa_shader_stage_to_string(i
),
4731 set_always_active_io(exec_list
*ir
, ir_variable_mode io_mode
)
4733 assert(io_mode
== ir_var_shader_in
|| io_mode
== ir_var_shader_out
);
4735 foreach_in_list(ir_instruction
, node
, ir
) {
4736 ir_variable
*const var
= node
->as_variable();
4738 if (var
== NULL
|| var
->data
.mode
!= io_mode
)
4741 /* Don't set always active on builtins that haven't been redeclared */
4742 if (var
->data
.how_declared
== ir_var_declared_implicitly
)
4745 var
->data
.always_active_io
= true;
4750 * When separate shader programs are enabled, only input/outputs between
4751 * the stages of a multi-stage separate program can be safely removed
4752 * from the shader interface. Other inputs/outputs must remain active.
4755 disable_varying_optimizations_for_sso(struct gl_shader_program
*prog
)
4757 unsigned first
, last
;
4758 assert(prog
->SeparateShader
);
4760 first
= MESA_SHADER_STAGES
;
4763 /* Determine first and last stage. Excluding the compute stage */
4764 for (unsigned i
= 0; i
< MESA_SHADER_COMPUTE
; i
++) {
4765 if (!prog
->_LinkedShaders
[i
])
4767 if (first
== MESA_SHADER_STAGES
)
4772 if (first
== MESA_SHADER_STAGES
)
4775 for (unsigned stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4776 gl_linked_shader
*sh
= prog
->_LinkedShaders
[stage
];
4780 /* Prevent the removal of inputs to the first and outputs from the last
4781 * stage, unless they are the initial pipeline inputs or final pipeline
4782 * outputs, respectively.
4784 * The removal of IO between shaders in the same program is always
4787 if (stage
== first
&& stage
!= MESA_SHADER_VERTEX
)
4788 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4789 if (stage
== last
&& stage
!= MESA_SHADER_FRAGMENT
)
4790 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4795 link_and_validate_uniforms(struct gl_context
*ctx
,
4796 struct gl_shader_program
*prog
)
4798 update_array_sizes(prog
);
4799 link_assign_uniform_locations(prog
, ctx
);
4801 link_assign_atomic_counter_resources(ctx
, prog
);
4802 link_calculate_subroutine_compat(prog
);
4803 check_resources(ctx
, prog
);
4804 check_subroutine_resources(prog
);
4805 check_image_resources(ctx
, prog
);
4806 link_check_atomic_counter_resources(ctx
, prog
);
4810 link_varyings_and_uniforms(unsigned first
, unsigned last
,
4811 struct gl_context
*ctx
,
4812 struct gl_shader_program
*prog
, void *mem_ctx
)
4814 /* Mark all generic shader inputs and outputs as unpaired. */
4815 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4816 if (prog
->_LinkedShaders
[i
] != NULL
) {
4817 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
4821 unsigned prev
= first
;
4822 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4823 if (prog
->_LinkedShaders
[i
] == NULL
)
4826 match_explicit_outputs_to_inputs(prog
->_LinkedShaders
[prev
],
4827 prog
->_LinkedShaders
[i
]);
4831 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4832 MESA_SHADER_VERTEX
, true)) {
4836 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4837 MESA_SHADER_FRAGMENT
, true)) {
4841 prog
->last_vert_prog
= NULL
;
4842 for (int i
= MESA_SHADER_GEOMETRY
; i
>= MESA_SHADER_VERTEX
; i
--) {
4843 if (prog
->_LinkedShaders
[i
] == NULL
)
4846 prog
->last_vert_prog
= prog
->_LinkedShaders
[i
]->Program
;
4850 if (!link_varyings(prog
, first
, last
, ctx
, mem_ctx
))
4853 link_and_validate_uniforms(ctx
, prog
);
4855 if (!prog
->data
->LinkStatus
)
4858 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4859 if (prog
->_LinkedShaders
[i
] == NULL
)
4862 const struct gl_shader_compiler_options
*options
=
4863 &ctx
->Const
.ShaderCompilerOptions
[i
];
4865 if (options
->LowerBufferInterfaceBlocks
)
4866 lower_ubo_reference(prog
->_LinkedShaders
[i
],
4867 options
->ClampBlockIndicesToArrayBounds
,
4868 ctx
->Const
.UseSTD430AsDefaultPacking
);
4870 if (i
== MESA_SHADER_COMPUTE
)
4871 lower_shared_reference(ctx
, prog
, prog
->_LinkedShaders
[i
]);
4873 lower_vector_derefs(prog
->_LinkedShaders
[i
]);
4874 do_vec_index_to_swizzle(prog
->_LinkedShaders
[i
]->ir
);
4881 linker_optimisation_loop(struct gl_context
*ctx
, exec_list
*ir
,
4884 if (ctx
->Const
.GLSLOptimizeConservatively
) {
4885 /* Run it just once. */
4886 do_common_optimization(ir
, true, false,
4887 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4888 ctx
->Const
.NativeIntegers
);
4890 /* Repeat it until it stops making changes. */
4891 while (do_common_optimization(ir
, true, false,
4892 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4893 ctx
->Const
.NativeIntegers
))
4899 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
4901 prog
->data
->LinkStatus
= LINKING_SUCCESS
; /* All error paths will set this to false */
4902 prog
->data
->Validated
= false;
4904 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4906 * "Linking can fail for a variety of reasons as specified in the
4907 * OpenGL Shading Language Specification, as well as any of the
4908 * following reasons:
4910 * - No shader objects are attached to program."
4912 * The Compatibility Profile specification does not list the error. In
4913 * Compatibility Profile missing shader stages are replaced by
4914 * fixed-function. This applies to the case where all stages are
4917 if (prog
->NumShaders
== 0) {
4918 if (ctx
->API
!= API_OPENGL_COMPAT
)
4919 linker_error(prog
, "no shaders attached to the program\n");
4923 #ifdef ENABLE_SHADER_CACHE
4924 if (shader_cache_read_program_metadata(ctx
, prog
))
4928 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
4930 prog
->ARB_fragment_coord_conventions_enable
= false;
4932 /* Separate the shaders into groups based on their type.
4934 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
4935 unsigned num_shaders
[MESA_SHADER_STAGES
];
4937 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4938 shader_list
[i
] = (struct gl_shader
**)
4939 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
4943 unsigned min_version
= UINT_MAX
;
4944 unsigned max_version
= 0;
4945 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
4946 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
4947 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
4949 if (!ctx
->Const
.AllowGLSLRelaxedES
&&
4950 prog
->Shaders
[i
]->IsES
!= prog
->Shaders
[0]->IsES
) {
4951 linker_error(prog
, "all shaders must use same shading "
4952 "language version\n");
4956 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
4957 prog
->ARB_fragment_coord_conventions_enable
= true;
4960 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
4961 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
4962 num_shaders
[shader_type
]++;
4965 /* In desktop GLSL, different shader versions may be linked together. In
4966 * GLSL ES, all shader versions must be the same.
4968 if (!ctx
->Const
.AllowGLSLRelaxedES
&& prog
->Shaders
[0]->IsES
&&
4969 min_version
!= max_version
) {
4970 linker_error(prog
, "all shaders must use same shading "
4971 "language version\n");
4975 prog
->data
->Version
= max_version
;
4976 prog
->IsES
= prog
->Shaders
[0]->IsES
;
4978 /* Some shaders have to be linked with some other shaders present.
4980 if (!prog
->SeparateShader
) {
4981 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
4982 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4983 linker_error(prog
, "Geometry shader must be linked with "
4987 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4988 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4989 linker_error(prog
, "Tessellation evaluation shader must be linked "
4990 "with vertex shader\n");
4993 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4994 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4995 linker_error(prog
, "Tessellation control shader must be linked with "
5000 /* Section 7.3 of the OpenGL ES 3.2 specification says:
5002 * "Linking can fail for [...] any of the following reasons:
5004 * * program contains an object to form a tessellation control
5005 * shader [...] and [...] the program is not separable and
5006 * contains no object to form a tessellation evaluation shader"
5008 * The OpenGL spec is contradictory. It allows linking without a tess
5009 * eval shader, but that can only be used with transform feedback and
5010 * rasterization disabled. However, transform feedback isn't allowed
5011 * with GL_PATCHES, so it can't be used.
5013 * More investigation showed that the idea of transform feedback after
5014 * a tess control shader was dropped, because some hw vendors couldn't
5015 * support tessellation without a tess eval shader, but the linker
5016 * section wasn't updated to reflect that.
5018 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
5021 * Do what's reasonable and always require a tess eval shader if a tess
5022 * control shader is present.
5024 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
5025 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0) {
5026 linker_error(prog
, "Tessellation control shader must be linked with "
5027 "tessellation evaluation shader\n");
5032 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
5033 num_shaders
[MESA_SHADER_TESS_CTRL
] == 0) {
5034 linker_error(prog
, "GLSL ES requires non-separable programs "
5035 "containing a tessellation evaluation shader to also "
5036 "be linked with a tessellation control shader\n");
5042 /* Compute shaders have additional restrictions. */
5043 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
5044 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
5045 linker_error(prog
, "Compute shaders may not be linked with any other "
5046 "type of shader\n");
5049 /* Link all shaders for a particular stage and validate the result.
5051 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
5052 if (num_shaders
[stage
] > 0) {
5053 gl_linked_shader
*const sh
=
5054 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
5055 num_shaders
[stage
], false);
5057 if (!prog
->data
->LinkStatus
) {
5059 _mesa_delete_linked_shader(ctx
, sh
);
5064 case MESA_SHADER_VERTEX
:
5065 validate_vertex_shader_executable(prog
, sh
, ctx
);
5067 case MESA_SHADER_TESS_CTRL
:
5068 /* nothing to be done */
5070 case MESA_SHADER_TESS_EVAL
:
5071 validate_tess_eval_shader_executable(prog
, sh
, ctx
);
5073 case MESA_SHADER_GEOMETRY
:
5074 validate_geometry_shader_executable(prog
, sh
, ctx
);
5076 case MESA_SHADER_FRAGMENT
:
5077 validate_fragment_shader_executable(prog
, sh
);
5080 if (!prog
->data
->LinkStatus
) {
5082 _mesa_delete_linked_shader(ctx
, sh
);
5086 prog
->_LinkedShaders
[stage
] = sh
;
5087 prog
->data
->linked_stages
|= 1 << stage
;
5091 /* Here begins the inter-stage linking phase. Some initial validation is
5092 * performed, then locations are assigned for uniforms, attributes, and
5095 cross_validate_uniforms(ctx
, prog
);
5096 if (!prog
->data
->LinkStatus
)
5099 unsigned first
, last
, prev
;
5101 first
= MESA_SHADER_STAGES
;
5104 /* Determine first and last stage. */
5105 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5106 if (!prog
->_LinkedShaders
[i
])
5108 if (first
== MESA_SHADER_STAGES
)
5113 check_explicit_uniform_locations(ctx
, prog
);
5114 link_assign_subroutine_types(prog
);
5115 verify_subroutine_associated_funcs(prog
);
5117 if (!prog
->data
->LinkStatus
)
5120 resize_tes_inputs(ctx
, prog
);
5122 /* Validate the inputs of each stage with the output of the preceding
5126 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
5127 if (prog
->_LinkedShaders
[i
] == NULL
)
5130 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
5131 prog
->_LinkedShaders
[i
]);
5132 if (!prog
->data
->LinkStatus
)
5135 cross_validate_outputs_to_inputs(ctx
, prog
,
5136 prog
->_LinkedShaders
[prev
],
5137 prog
->_LinkedShaders
[i
]);
5138 if (!prog
->data
->LinkStatus
)
5144 /* The cross validation of outputs/inputs above validates interstage
5145 * explicit locations. We need to do this also for the inputs in the first
5146 * stage and outputs of the last stage included in the program, since there
5147 * is no cross validation for these.
5149 validate_first_and_last_interface_explicit_locations(ctx
, prog
,
5150 (gl_shader_stage
) first
,
5151 (gl_shader_stage
) last
);
5153 /* Cross-validate uniform blocks between shader stages */
5154 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
);
5155 if (!prog
->data
->LinkStatus
)
5158 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5159 if (prog
->_LinkedShaders
[i
] != NULL
)
5160 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
5163 if (prog
->IsES
&& prog
->data
->Version
== 100)
5164 if (!validate_invariant_builtins(prog
,
5165 prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
5166 prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]))
5169 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
5170 * it before optimization because we want most of the checks to get
5171 * dropped thanks to constant propagation.
5173 * This rule also applies to GLSL ES 3.00.
5175 if (max_version
>= (prog
->IsES
? 300 : 130)) {
5176 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
5178 lower_discard_flow(sh
->ir
);
5182 if (prog
->SeparateShader
)
5183 disable_varying_optimizations_for_sso(prog
);
5186 if (!interstage_cross_validate_uniform_blocks(prog
, false))
5190 if (!interstage_cross_validate_uniform_blocks(prog
, true))
5193 /* Do common optimization before assigning storage for attributes,
5194 * uniforms, and varyings. Later optimization could possibly make
5195 * some of that unused.
5197 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5198 if (prog
->_LinkedShaders
[i
] == NULL
)
5201 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
5202 if (!prog
->data
->LinkStatus
)
5205 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerCombinedClipCullDistance
) {
5206 lower_clip_cull_distance(prog
, prog
->_LinkedShaders
[i
]);
5209 if (ctx
->Const
.LowerTessLevel
) {
5210 lower_tess_level(prog
->_LinkedShaders
[i
]);
5213 /* Section 13.46 (Vertex Attribute Aliasing) of the OpenGL ES 3.2
5214 * specification says:
5216 * "In general, the behavior of GLSL ES should not depend on compiler
5217 * optimizations which might be implementation-dependent. Name matching
5218 * rules in most languages, including C++ from which GLSL ES is derived,
5219 * are based on declarations rather than use.
5221 * RESOLUTION: The existence of aliasing is determined by declarations
5222 * present after preprocessing."
5224 * Because of this rule, we do a 'dry-run' of attribute assignment for
5225 * vertex shader inputs here.
5227 if (prog
->IsES
&& i
== MESA_SHADER_VERTEX
) {
5228 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
5229 MESA_SHADER_VERTEX
, false)) {
5234 /* Call opts before lowering const arrays to uniforms so we can const
5235 * propagate any elements accessed directly.
5237 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
5239 /* Call opts after lowering const arrays to copy propagate things. */
5240 if (lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
, i
))
5241 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
5243 propagate_invariance(prog
->_LinkedShaders
[i
]->ir
);
5246 /* Validation for special cases where we allow sampler array indexing
5247 * with loop induction variable. This check emits a warning or error
5248 * depending if backend can handle dynamic indexing.
5250 if ((!prog
->IsES
&& prog
->data
->Version
< 130) ||
5251 (prog
->IsES
&& prog
->data
->Version
< 300)) {
5252 if (!validate_sampler_array_indexing(ctx
, prog
))
5256 /* Check and validate stream emissions in geometry shaders */
5257 validate_geometry_shader_emissions(ctx
, prog
);
5259 store_fragdepth_layout(prog
);
5261 if(!link_varyings_and_uniforms(first
, last
, ctx
, prog
, mem_ctx
))
5264 /* Linking varyings can cause some extra, useless swizzles to be generated
5265 * due to packing and unpacking.
5267 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5268 if (prog
->_LinkedShaders
[i
] == NULL
)
5271 optimize_swizzles(prog
->_LinkedShaders
[i
]->ir
);
5274 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
5275 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
5276 * anything about shader linking when one of the shaders (vertex or
5277 * fragment shader) is absent. So, the extension shouldn't change the
5278 * behavior specified in GLSL specification.
5280 * From OpenGL ES 3.1 specification (7.3 Program Objects):
5281 * "Linking can fail for a variety of reasons as specified in the
5282 * OpenGL ES Shading Language Specification, as well as any of the
5283 * following reasons:
5287 * * program contains objects to form either a vertex shader or
5288 * fragment shader, and program is not separable, and does not
5289 * contain objects to form both a vertex shader and fragment
5292 * However, the only scenario in 3.1+ where we don't require them both is
5293 * when we have a compute shader. For example:
5295 * - No shaders is a link error.
5296 * - Geom or Tess without a Vertex shader is a link error which means we
5297 * always require a Vertex shader and hence a Fragment shader.
5298 * - Finally a Compute shader linked with any other stage is a link error.
5300 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
&&
5301 num_shaders
[MESA_SHADER_COMPUTE
] == 0) {
5302 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
5303 linker_error(prog
, "program lacks a vertex shader\n");
5304 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
5305 linker_error(prog
, "program lacks a fragment shader\n");
5310 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5311 free(shader_list
[i
]);
5312 if (prog
->_LinkedShaders
[i
] == NULL
)
5315 /* Do a final validation step to make sure that the IR wasn't
5316 * invalidated by any modifications performed after intrastage linking.
5318 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
5320 /* Retain any live IR, but trash the rest. */
5321 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
5323 /* The symbol table in the linked shaders may contain references to
5324 * variables that were removed (e.g., unused uniforms). Since it may
5325 * contain junk, there is no possible valid use. Delete it and set the
5328 delete prog
->_LinkedShaders
[i
]->symbols
;
5329 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
5332 ralloc_free(mem_ctx
);