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
,
858 bool match_precision
)
860 /* Consider the types to be "the same" if both types are arrays
861 * of the same type and one of the arrays is implicitly sized.
862 * In addition, set the type of the linked variable to the
863 * explicitly sized array.
865 if (var
->type
->is_array() && existing
->type
->is_array()) {
866 const glsl_type
*no_array_var
= var
->type
->fields
.array
;
867 const glsl_type
*no_array_existing
= existing
->type
->fields
.array
;
870 type_matches
= (match_precision
?
871 no_array_var
== no_array_existing
:
872 no_array_var
->compare_no_precision(no_array_existing
));
875 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
876 if (var
->type
->length
!= 0) {
877 if ((int)var
->type
->length
<= existing
->data
.max_array_access
) {
878 linker_error(prog
, "%s `%s' declared as type "
879 "`%s' but outermost dimension has an index"
882 var
->name
, var
->type
->name
,
883 existing
->data
.max_array_access
);
885 existing
->type
= var
->type
;
887 } else if (existing
->type
->length
!= 0) {
888 if((int)existing
->type
->length
<= var
->data
.max_array_access
&&
889 !existing
->data
.from_ssbo_unsized_array
) {
890 linker_error(prog
, "%s `%s' declared as type "
891 "`%s' but outermost dimension has an index"
894 var
->name
, existing
->type
->name
,
895 var
->data
.max_array_access
);
906 * Perform validation of global variables used across multiple shaders
909 cross_validate_globals(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
910 struct exec_list
*ir
, glsl_symbol_table
*variables
,
913 foreach_in_list(ir_instruction
, node
, ir
) {
914 ir_variable
*const var
= node
->as_variable();
919 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
922 /* don't cross validate subroutine uniforms */
923 if (var
->type
->contains_subroutine())
926 /* Don't cross validate interface instances. These are only relevant
927 * inside a shader. The cross validation is done at the Interface Block
930 if (var
->is_interface_instance())
933 /* Don't cross validate temporaries that are at global scope. These
934 * will eventually get pulled into the shaders 'main'.
936 if (var
->data
.mode
== ir_var_temporary
)
939 /* If a global with this name has already been seen, verify that the
940 * new instance has the same type. In addition, if the globals have
941 * initializers, the values of the initializers must be the same.
943 ir_variable
*const existing
= variables
->get_variable(var
->name
);
944 if (existing
!= NULL
) {
945 /* Check if types match. */
946 if (var
->type
!= existing
->type
) {
947 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
948 /* If it is an unsized array in a Shader Storage Block,
949 * two different shaders can access to different elements.
950 * Because of that, they might be converted to different
951 * sized arrays, then check that they are compatible but
952 * ignore the array size.
954 if (!(var
->data
.mode
== ir_var_shader_storage
&&
955 var
->data
.from_ssbo_unsized_array
&&
956 existing
->data
.mode
== ir_var_shader_storage
&&
957 existing
->data
.from_ssbo_unsized_array
&&
958 var
->type
->gl_type
== existing
->type
->gl_type
)) {
959 linker_error(prog
, "%s `%s' declared as type "
960 "`%s' and type `%s'\n",
962 var
->name
, var
->type
->name
,
963 existing
->type
->name
);
969 if (var
->data
.explicit_location
) {
970 if (existing
->data
.explicit_location
971 && (var
->data
.location
!= existing
->data
.location
)) {
972 linker_error(prog
, "explicit locations for %s "
973 "`%s' have differing values\n",
974 mode_string(var
), var
->name
);
978 if (var
->data
.location_frac
!= existing
->data
.location_frac
) {
979 linker_error(prog
, "explicit components for %s `%s' have "
980 "differing values\n", mode_string(var
), var
->name
);
984 existing
->data
.location
= var
->data
.location
;
985 existing
->data
.explicit_location
= true;
987 /* Check if uniform with implicit location was marked explicit
988 * by earlier shader stage. If so, mark it explicit in this stage
989 * too to make sure later processing does not treat it as
992 if (existing
->data
.explicit_location
) {
993 var
->data
.location
= existing
->data
.location
;
994 var
->data
.explicit_location
= true;
998 /* From the GLSL 4.20 specification:
999 * "A link error will result if two compilation units in a program
1000 * specify different integer-constant bindings for the same
1001 * opaque-uniform name. However, it is not an error to specify a
1002 * binding on some but not all declarations for the same name"
1004 if (var
->data
.explicit_binding
) {
1005 if (existing
->data
.explicit_binding
&&
1006 var
->data
.binding
!= existing
->data
.binding
) {
1007 linker_error(prog
, "explicit bindings for %s "
1008 "`%s' have differing values\n",
1009 mode_string(var
), var
->name
);
1013 existing
->data
.binding
= var
->data
.binding
;
1014 existing
->data
.explicit_binding
= true;
1017 if (var
->type
->contains_atomic() &&
1018 var
->data
.offset
!= existing
->data
.offset
) {
1019 linker_error(prog
, "offset specifications for %s "
1020 "`%s' have differing values\n",
1021 mode_string(var
), var
->name
);
1025 /* Validate layout qualifiers for gl_FragDepth.
1027 * From the AMD/ARB_conservative_depth specs:
1029 * "If gl_FragDepth is redeclared in any fragment shader in a
1030 * program, it must be redeclared in all fragment shaders in
1031 * that program that have static assignments to
1032 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1033 * fragment shaders in a single program must have the same set
1036 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1037 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1038 bool layout_differs
=
1039 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1041 if (layout_declared
&& layout_differs
) {
1043 "All redeclarations of gl_FragDepth in all "
1044 "fragment shaders in a single program must have "
1045 "the same set of qualifiers.\n");
1048 if (var
->data
.used
&& layout_differs
) {
1050 "If gl_FragDepth is redeclared with a layout "
1051 "qualifier in any fragment shader, it must be "
1052 "redeclared with the same layout qualifier in "
1053 "all fragment shaders that have assignments to "
1058 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1060 * "If a shared global has multiple initializers, the
1061 * initializers must all be constant expressions, and they
1062 * must all have the same value. Otherwise, a link error will
1063 * result. (A shared global having only one initializer does
1064 * not require that initializer to be a constant expression.)"
1066 * Previous to 4.20 the GLSL spec simply said that initializers
1067 * must have the same value. In this case of non-constant
1068 * initializers, this was impossible to determine. As a result,
1069 * no vendor actually implemented that behavior. The 4.20
1070 * behavior matches the implemented behavior of at least one other
1071 * vendor, so we'll implement that for all GLSL versions.
1073 if (var
->constant_initializer
!= NULL
) {
1074 if (existing
->constant_initializer
!= NULL
) {
1075 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1076 linker_error(prog
, "initializers for %s "
1077 "`%s' have differing values\n",
1078 mode_string(var
), var
->name
);
1082 /* If the first-seen instance of a particular uniform did
1083 * not have an initializer but a later instance does,
1084 * replace the former with the later.
1086 variables
->replace_variable(existing
->name
, var
);
1090 if (var
->data
.has_initializer
) {
1091 if (existing
->data
.has_initializer
1092 && (var
->constant_initializer
== NULL
1093 || existing
->constant_initializer
== NULL
)) {
1095 "shared global variable `%s' has multiple "
1096 "non-constant initializers.\n",
1102 if (existing
->data
.explicit_invariant
!= var
->data
.explicit_invariant
) {
1103 linker_error(prog
, "declarations for %s `%s' have "
1104 "mismatching invariant qualifiers\n",
1105 mode_string(var
), var
->name
);
1108 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1109 linker_error(prog
, "declarations for %s `%s' have "
1110 "mismatching centroid qualifiers\n",
1111 mode_string(var
), var
->name
);
1114 if (existing
->data
.sample
!= var
->data
.sample
) {
1115 linker_error(prog
, "declarations for %s `%s` have "
1116 "mismatching sample qualifiers\n",
1117 mode_string(var
), var
->name
);
1120 if (existing
->data
.image_format
!= var
->data
.image_format
) {
1121 linker_error(prog
, "declarations for %s `%s` have "
1122 "mismatching image format qualifiers\n",
1123 mode_string(var
), var
->name
);
1127 /* Check the precision qualifier matches for uniform variables on
1130 if (!ctx
->Const
.AllowGLSLRelaxedES
&&
1131 prog
->IsES
&& !var
->get_interface_type() &&
1132 existing
->data
.precision
!= var
->data
.precision
) {
1133 if ((existing
->data
.used
&& var
->data
.used
) || prog
->data
->Version
>= 300) {
1134 linker_error(prog
, "declarations for %s `%s` have "
1135 "mismatching precision qualifiers\n",
1136 mode_string(var
), var
->name
);
1139 linker_warning(prog
, "declarations for %s `%s` have "
1140 "mismatching precision qualifiers\n",
1141 mode_string(var
), var
->name
);
1145 /* In OpenGL GLSL 3.20 spec, section 4.3.9:
1147 * "It is a link-time error if any particular shader interface
1150 * - two different blocks, each having no instance name, and each
1151 * having a member of the same name, or
1153 * - a variable outside a block, and a block with no instance name,
1154 * where the variable has the same name as a member in the block."
1156 const glsl_type
*var_itype
= var
->get_interface_type();
1157 const glsl_type
*existing_itype
= existing
->get_interface_type();
1158 if (var_itype
!= existing_itype
) {
1159 if (!var_itype
|| !existing_itype
) {
1160 linker_error(prog
, "declarations for %s `%s` are inside block "
1161 "`%s` and outside a block",
1162 mode_string(var
), var
->name
,
1163 var_itype
? var_itype
->name
: existing_itype
->name
);
1165 } else if (strcmp(var_itype
->name
, existing_itype
->name
) != 0) {
1166 linker_error(prog
, "declarations for %s `%s` are inside blocks "
1168 mode_string(var
), var
->name
,
1169 existing_itype
->name
,
1175 variables
->add_variable(var
);
1181 * Perform validation of uniforms used across multiple shader stages
1184 cross_validate_uniforms(struct gl_context
*ctx
,
1185 struct gl_shader_program
*prog
)
1187 glsl_symbol_table variables
;
1188 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1189 if (prog
->_LinkedShaders
[i
] == NULL
)
1192 cross_validate_globals(ctx
, prog
, prog
->_LinkedShaders
[i
]->ir
,
1198 * Accumulates the array of buffer blocks and checks that all definitions of
1199 * blocks agree on their contents.
1202 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
,
1205 int *InterfaceBlockStageIndex
[MESA_SHADER_STAGES
];
1206 struct gl_uniform_block
*blks
= NULL
;
1207 unsigned *num_blks
= validate_ssbo
? &prog
->data
->NumShaderStorageBlocks
:
1208 &prog
->data
->NumUniformBlocks
;
1210 unsigned max_num_buffer_blocks
= 0;
1211 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1212 if (prog
->_LinkedShaders
[i
]) {
1213 if (validate_ssbo
) {
1214 max_num_buffer_blocks
+=
1215 prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1217 max_num_buffer_blocks
+=
1218 prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1223 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1224 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1226 InterfaceBlockStageIndex
[i
] = new int[max_num_buffer_blocks
];
1227 for (unsigned int j
= 0; j
< max_num_buffer_blocks
; j
++)
1228 InterfaceBlockStageIndex
[i
][j
] = -1;
1233 unsigned sh_num_blocks
;
1234 struct gl_uniform_block
**sh_blks
;
1235 if (validate_ssbo
) {
1236 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1237 sh_blks
= sh
->Program
->sh
.ShaderStorageBlocks
;
1239 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1240 sh_blks
= sh
->Program
->sh
.UniformBlocks
;
1243 for (unsigned int j
= 0; j
< sh_num_blocks
; j
++) {
1244 int index
= link_cross_validate_uniform_block(prog
->data
, &blks
,
1245 num_blks
, sh_blks
[j
]);
1248 linker_error(prog
, "buffer block `%s' has mismatching "
1249 "definitions\n", sh_blks
[j
]->Name
);
1251 for (unsigned k
= 0; k
<= i
; k
++) {
1252 delete[] InterfaceBlockStageIndex
[k
];
1255 /* Reset the block count. This will help avoid various segfaults
1256 * from api calls that assume the array exists due to the count
1263 InterfaceBlockStageIndex
[i
][index
] = j
;
1267 /* Update per stage block pointers to point to the program list.
1268 * FIXME: We should be able to free the per stage blocks here.
1270 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1271 for (unsigned j
= 0; j
< *num_blks
; j
++) {
1272 int stage_index
= InterfaceBlockStageIndex
[i
][j
];
1274 if (stage_index
!= -1) {
1275 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1277 struct gl_uniform_block
**sh_blks
= validate_ssbo
?
1278 sh
->Program
->sh
.ShaderStorageBlocks
:
1279 sh
->Program
->sh
.UniformBlocks
;
1281 blks
[j
].stageref
|= sh_blks
[stage_index
]->stageref
;
1282 sh_blks
[stage_index
] = &blks
[j
];
1287 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1288 delete[] InterfaceBlockStageIndex
[i
];
1292 prog
->data
->ShaderStorageBlocks
= blks
;
1294 prog
->data
->UniformBlocks
= blks
;
1300 * Verifies the invariance of built-in special variables.
1303 validate_invariant_builtins(struct gl_shader_program
*prog
,
1304 const gl_linked_shader
*vert
,
1305 const gl_linked_shader
*frag
)
1307 const ir_variable
*var_vert
;
1308 const ir_variable
*var_frag
;
1314 * From OpenGL ES Shading Language 1.0 specification
1315 * (4.6.4 Invariance and Linkage):
1316 * "The invariance of varyings that are declared in both the vertex and
1317 * fragment shaders must match. For the built-in special variables,
1318 * gl_FragCoord can only be declared invariant if and only if
1319 * gl_Position is declared invariant. Similarly gl_PointCoord can only
1320 * be declared invariant if and only if gl_PointSize is declared
1321 * invariant. It is an error to declare gl_FrontFacing as invariant.
1322 * The invariance of gl_FrontFacing is the same as the invariance of
1325 var_frag
= frag
->symbols
->get_variable("gl_FragCoord");
1326 if (var_frag
&& var_frag
->data
.invariant
) {
1327 var_vert
= vert
->symbols
->get_variable("gl_Position");
1328 if (var_vert
&& !var_vert
->data
.invariant
) {
1330 "fragment shader built-in `%s' has invariant qualifier, "
1331 "but vertex shader built-in `%s' lacks invariant qualifier\n",
1332 var_frag
->name
, var_vert
->name
);
1337 var_frag
= frag
->symbols
->get_variable("gl_PointCoord");
1338 if (var_frag
&& var_frag
->data
.invariant
) {
1339 var_vert
= vert
->symbols
->get_variable("gl_PointSize");
1340 if (var_vert
&& !var_vert
->data
.invariant
) {
1342 "fragment shader built-in `%s' has invariant qualifier, "
1343 "but vertex shader built-in `%s' lacks invariant qualifier\n",
1344 var_frag
->name
, var_vert
->name
);
1349 var_frag
= frag
->symbols
->get_variable("gl_FrontFacing");
1350 if (var_frag
&& var_frag
->data
.invariant
) {
1352 "fragment shader built-in `%s' can not be declared as invariant\n",
1361 * Populates a shaders symbol table with all global declarations
1364 populate_symbol_table(gl_linked_shader
*sh
, glsl_symbol_table
*symbols
)
1366 sh
->symbols
= new(sh
) glsl_symbol_table
;
1368 _mesa_glsl_copy_symbols_from_table(sh
->ir
, symbols
, sh
->symbols
);
1373 * Remap variables referenced in an instruction tree
1375 * This is used when instruction trees are cloned from one shader and placed in
1376 * another. These trees will contain references to \c ir_variable nodes that
1377 * do not exist in the target shader. This function finds these \c ir_variable
1378 * references and replaces the references with matching variables in the target
1381 * If there is no matching variable in the target shader, a clone of the
1382 * \c ir_variable is made and added to the target shader. The new variable is
1383 * added to \b both the instruction stream and the symbol table.
1385 * \param inst IR tree that is to be processed.
1386 * \param symbols Symbol table containing global scope symbols in the
1388 * \param instructions Instruction stream where new variable declarations
1392 remap_variables(ir_instruction
*inst
, struct gl_linked_shader
*target
,
1395 class remap_visitor
: public ir_hierarchical_visitor
{
1397 remap_visitor(struct gl_linked_shader
*target
, hash_table
*temps
)
1399 this->target
= target
;
1400 this->symbols
= target
->symbols
;
1401 this->instructions
= target
->ir
;
1402 this->temps
= temps
;
1405 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1407 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1408 hash_entry
*entry
= _mesa_hash_table_search(temps
, ir
->var
);
1409 ir_variable
*var
= entry
? (ir_variable
*) entry
->data
: NULL
;
1411 assert(var
!= NULL
);
1413 return visit_continue
;
1416 ir_variable
*const existing
=
1417 this->symbols
->get_variable(ir
->var
->name
);
1418 if (existing
!= NULL
)
1421 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1423 this->symbols
->add_variable(copy
);
1424 this->instructions
->push_head(copy
);
1428 return visit_continue
;
1432 struct gl_linked_shader
*target
;
1433 glsl_symbol_table
*symbols
;
1434 exec_list
*instructions
;
1438 remap_visitor
v(target
, temps
);
1445 * Move non-declarations from one instruction stream to another
1447 * The intended usage pattern of this function is to pass the pointer to the
1448 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1449 * pointer) for \c last and \c false for \c make_copies on the first
1450 * call. Successive calls pass the return value of the previous call for
1451 * \c last and \c true for \c make_copies.
1453 * \param instructions Source instruction stream
1454 * \param last Instruction after which new instructions should be
1455 * inserted in the target instruction stream
1456 * \param make_copies Flag selecting whether instructions in \c instructions
1457 * should be copied (via \c ir_instruction::clone) into the
1458 * target list or moved.
1461 * The new "last" instruction in the target instruction stream. This pointer
1462 * is suitable for use as the \c last parameter of a later call to this
1466 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1467 bool make_copies
, gl_linked_shader
*target
)
1469 hash_table
*temps
= NULL
;
1472 temps
= _mesa_pointer_hash_table_create(NULL
);
1474 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1475 if (inst
->as_function())
1478 ir_variable
*var
= inst
->as_variable();
1479 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1482 assert(inst
->as_assignment()
1484 || inst
->as_if() /* for initializers with the ?: operator */
1485 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1488 inst
= inst
->clone(target
, NULL
);
1491 _mesa_hash_table_insert(temps
, var
, inst
);
1493 remap_variables(inst
, target
, temps
);
1498 last
->insert_after(inst
);
1503 _mesa_hash_table_destroy(temps
, NULL
);
1510 * This class is only used in link_intrastage_shaders() below but declaring
1511 * it inside that function leads to compiler warnings with some versions of
1514 class array_sizing_visitor
: public deref_type_updater
{
1516 array_sizing_visitor()
1517 : mem_ctx(ralloc_context(NULL
)),
1518 unnamed_interfaces(_mesa_pointer_hash_table_create(NULL
))
1522 ~array_sizing_visitor()
1524 _mesa_hash_table_destroy(this->unnamed_interfaces
, NULL
);
1525 ralloc_free(this->mem_ctx
);
1528 virtual ir_visitor_status
visit(ir_variable
*var
)
1530 const glsl_type
*type_without_array
;
1531 bool implicit_sized_array
= var
->data
.implicit_sized_array
;
1532 fixup_type(&var
->type
, var
->data
.max_array_access
,
1533 var
->data
.from_ssbo_unsized_array
,
1534 &implicit_sized_array
);
1535 var
->data
.implicit_sized_array
= implicit_sized_array
;
1536 type_without_array
= var
->type
->without_array();
1537 if (var
->type
->is_interface()) {
1538 if (interface_contains_unsized_arrays(var
->type
)) {
1539 const glsl_type
*new_type
=
1540 resize_interface_members(var
->type
,
1541 var
->get_max_ifc_array_access(),
1542 var
->is_in_shader_storage_block());
1543 var
->type
= new_type
;
1544 var
->change_interface_type(new_type
);
1546 } else if (type_without_array
->is_interface()) {
1547 if (interface_contains_unsized_arrays(type_without_array
)) {
1548 const glsl_type
*new_type
=
1549 resize_interface_members(type_without_array
,
1550 var
->get_max_ifc_array_access(),
1551 var
->is_in_shader_storage_block());
1552 var
->change_interface_type(new_type
);
1553 var
->type
= update_interface_members_array(var
->type
, new_type
);
1555 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1556 /* Store a pointer to the variable in the unnamed_interfaces
1560 _mesa_hash_table_search(this->unnamed_interfaces
,
1563 ir_variable
**interface_vars
= entry
? (ir_variable
**) entry
->data
: NULL
;
1565 if (interface_vars
== NULL
) {
1566 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1568 _mesa_hash_table_insert(this->unnamed_interfaces
, ifc_type
,
1571 unsigned index
= ifc_type
->field_index(var
->name
);
1572 assert(index
< ifc_type
->length
);
1573 assert(interface_vars
[index
] == NULL
);
1574 interface_vars
[index
] = var
;
1576 return visit_continue
;
1580 * For each unnamed interface block that was discovered while running the
1581 * visitor, adjust the interface type to reflect the newly assigned array
1582 * sizes, and fix up the ir_variable nodes to point to the new interface
1585 void fixup_unnamed_interface_types()
1587 hash_table_call_foreach(this->unnamed_interfaces
,
1588 fixup_unnamed_interface_type
, NULL
);
1593 * If the type pointed to by \c type represents an unsized array, replace
1594 * it with a sized array whose size is determined by max_array_access.
1596 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1597 bool from_ssbo_unsized_array
, bool *implicit_sized
)
1599 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1600 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1601 max_array_access
+ 1);
1602 *implicit_sized
= true;
1603 assert(*type
!= NULL
);
1607 static const glsl_type
*
1608 update_interface_members_array(const glsl_type
*type
,
1609 const glsl_type
*new_interface_type
)
1611 const glsl_type
*element_type
= type
->fields
.array
;
1612 if (element_type
->is_array()) {
1613 const glsl_type
*new_array_type
=
1614 update_interface_members_array(element_type
, new_interface_type
);
1615 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1617 return glsl_type::get_array_instance(new_interface_type
,
1623 * Determine whether the given interface type contains unsized arrays (if
1624 * it doesn't, array_sizing_visitor doesn't need to process it).
1626 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1628 for (unsigned i
= 0; i
< type
->length
; i
++) {
1629 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1630 if (elem_type
->is_unsized_array())
1637 * Create a new interface type based on the given type, with unsized arrays
1638 * replaced by sized arrays whose size is determined by
1639 * max_ifc_array_access.
1641 static const glsl_type
*
1642 resize_interface_members(const glsl_type
*type
,
1643 const int *max_ifc_array_access
,
1646 unsigned num_fields
= type
->length
;
1647 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1648 memcpy(fields
, type
->fields
.structure
,
1649 num_fields
* sizeof(*fields
));
1650 for (unsigned i
= 0; i
< num_fields
; i
++) {
1651 bool implicit_sized_array
= fields
[i
].implicit_sized_array
;
1652 /* If SSBO last member is unsized array, we don't replace it by a sized
1655 if (is_ssbo
&& i
== (num_fields
- 1))
1656 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1657 true, &implicit_sized_array
);
1659 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1660 false, &implicit_sized_array
);
1661 fields
[i
].implicit_sized_array
= implicit_sized_array
;
1663 glsl_interface_packing packing
=
1664 (glsl_interface_packing
) type
->interface_packing
;
1665 bool row_major
= (bool) type
->interface_row_major
;
1666 const glsl_type
*new_ifc_type
=
1667 glsl_type::get_interface_instance(fields
, num_fields
,
1668 packing
, row_major
, type
->name
);
1670 return new_ifc_type
;
1673 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1676 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1677 ir_variable
**interface_vars
= (ir_variable
**) data
;
1678 unsigned num_fields
= ifc_type
->length
;
1679 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1680 memcpy(fields
, ifc_type
->fields
.structure
,
1681 num_fields
* sizeof(*fields
));
1682 bool interface_type_changed
= false;
1683 for (unsigned i
= 0; i
< num_fields
; i
++) {
1684 if (interface_vars
[i
] != NULL
&&
1685 fields
[i
].type
!= interface_vars
[i
]->type
) {
1686 fields
[i
].type
= interface_vars
[i
]->type
;
1687 interface_type_changed
= true;
1690 if (!interface_type_changed
) {
1694 glsl_interface_packing packing
=
1695 (glsl_interface_packing
) ifc_type
->interface_packing
;
1696 bool row_major
= (bool) ifc_type
->interface_row_major
;
1697 const glsl_type
*new_ifc_type
=
1698 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1699 row_major
, ifc_type
->name
);
1701 for (unsigned i
= 0; i
< num_fields
; i
++) {
1702 if (interface_vars
[i
] != NULL
)
1703 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1708 * Memory context used to allocate the data in \c unnamed_interfaces.
1713 * Hash table from const glsl_type * to an array of ir_variable *'s
1714 * pointing to the ir_variables constituting each unnamed interface block.
1716 hash_table
*unnamed_interfaces
;
1720 validate_xfb_buffer_stride(struct gl_context
*ctx
, unsigned idx
,
1721 struct gl_shader_program
*prog
)
1723 /* We will validate doubles at a later stage */
1724 if (prog
->TransformFeedback
.BufferStride
[idx
] % 4) {
1725 linker_error(prog
, "invalid qualifier xfb_stride=%d must be a "
1726 "multiple of 4 or if its applied to a type that is "
1727 "or contains a double a multiple of 8.",
1728 prog
->TransformFeedback
.BufferStride
[idx
]);
1732 if (prog
->TransformFeedback
.BufferStride
[idx
] / 4 >
1733 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1734 linker_error(prog
, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1735 "limit has been exceeded.");
1743 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1747 link_xfb_stride_layout_qualifiers(struct gl_context
*ctx
,
1748 struct gl_shader_program
*prog
,
1749 struct gl_shader
**shader_list
,
1750 unsigned num_shaders
)
1752 for (unsigned i
= 0; i
< MAX_FEEDBACK_BUFFERS
; i
++) {
1753 prog
->TransformFeedback
.BufferStride
[i
] = 0;
1756 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1757 struct gl_shader
*shader
= shader_list
[i
];
1759 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1760 if (shader
->TransformFeedbackBufferStride
[j
]) {
1761 if (prog
->TransformFeedback
.BufferStride
[j
] == 0) {
1762 prog
->TransformFeedback
.BufferStride
[j
] =
1763 shader
->TransformFeedbackBufferStride
[j
];
1764 if (!validate_xfb_buffer_stride(ctx
, j
, prog
))
1766 } else if (prog
->TransformFeedback
.BufferStride
[j
] !=
1767 shader
->TransformFeedbackBufferStride
[j
]){
1769 "intrastage shaders defined with conflicting "
1770 "xfb_stride for buffer %d (%d and %d)\n", j
,
1771 prog
->TransformFeedback
.BufferStride
[j
],
1772 shader
->TransformFeedbackBufferStride
[j
]);
1781 * Check for conflicting bindless/bound sampler/image layout qualifiers at
1785 link_bindless_layout_qualifiers(struct gl_shader_program
*prog
,
1786 struct gl_shader
**shader_list
,
1787 unsigned num_shaders
)
1789 bool bindless_sampler
, bindless_image
;
1790 bool bound_sampler
, bound_image
;
1792 bindless_sampler
= bindless_image
= false;
1793 bound_sampler
= bound_image
= false;
1795 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1796 struct gl_shader
*shader
= shader_list
[i
];
1798 if (shader
->bindless_sampler
)
1799 bindless_sampler
= true;
1800 if (shader
->bindless_image
)
1801 bindless_image
= true;
1802 if (shader
->bound_sampler
)
1803 bound_sampler
= true;
1804 if (shader
->bound_image
)
1807 if ((bindless_sampler
&& bound_sampler
) ||
1808 (bindless_image
&& bound_image
)) {
1809 /* From section 4.4.6 of the ARB_bindless_texture spec:
1811 * "If both bindless_sampler and bound_sampler, or bindless_image
1812 * and bound_image, are declared at global scope in any
1813 * compilation unit, a link- time error will be generated."
1815 linker_error(prog
, "both bindless_sampler and bound_sampler, or "
1816 "bindless_image and bound_image, can't be declared at "
1823 * Performs the cross-validation of tessellation control shader vertices and
1824 * layout qualifiers for the attached tessellation control shaders,
1825 * and propagates them to the linked TCS and linked shader program.
1828 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1829 struct gl_program
*gl_prog
,
1830 struct gl_shader
**shader_list
,
1831 unsigned num_shaders
)
1833 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_CTRL
)
1836 gl_prog
->info
.tess
.tcs_vertices_out
= 0;
1838 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1840 * "All tessellation control shader layout declarations in a program
1841 * must specify the same output patch vertex count. There must be at
1842 * least one layout qualifier specifying an output patch vertex count
1843 * in any program containing tessellation control shaders; however,
1844 * such a declaration is not required in all tessellation control
1848 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1849 struct gl_shader
*shader
= shader_list
[i
];
1851 if (shader
->info
.TessCtrl
.VerticesOut
!= 0) {
1852 if (gl_prog
->info
.tess
.tcs_vertices_out
!= 0 &&
1853 gl_prog
->info
.tess
.tcs_vertices_out
!=
1854 (unsigned) shader
->info
.TessCtrl
.VerticesOut
) {
1855 linker_error(prog
, "tessellation control shader defined with "
1856 "conflicting output vertex count (%d and %d)\n",
1857 gl_prog
->info
.tess
.tcs_vertices_out
,
1858 shader
->info
.TessCtrl
.VerticesOut
);
1861 gl_prog
->info
.tess
.tcs_vertices_out
=
1862 shader
->info
.TessCtrl
.VerticesOut
;
1866 /* Just do the intrastage -> interstage propagation right now,
1867 * since we already know we're in the right type of shader program
1870 if (gl_prog
->info
.tess
.tcs_vertices_out
== 0) {
1871 linker_error(prog
, "tessellation control shader didn't declare "
1872 "vertices out layout qualifier\n");
1879 * Performs the cross-validation of tessellation evaluation shader
1880 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1881 * for the attached tessellation evaluation shaders, and propagates them
1882 * to the linked TES and linked shader program.
1885 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1886 struct gl_program
*gl_prog
,
1887 struct gl_shader
**shader_list
,
1888 unsigned num_shaders
)
1890 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_EVAL
)
1893 int point_mode
= -1;
1894 unsigned vertex_order
= 0;
1896 gl_prog
->info
.tess
.primitive_mode
= PRIM_UNKNOWN
;
1897 gl_prog
->info
.tess
.spacing
= TESS_SPACING_UNSPECIFIED
;
1899 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1901 * "At least one tessellation evaluation shader (compilation unit) in
1902 * a program must declare a primitive mode in its input layout.
1903 * Declaration vertex spacing, ordering, and point mode identifiers is
1904 * optional. It is not required that all tessellation evaluation
1905 * shaders in a program declare a primitive mode. If spacing or
1906 * vertex ordering declarations are omitted, the tessellation
1907 * primitive generator will use equal spacing or counter-clockwise
1908 * vertex ordering, respectively. If a point mode declaration is
1909 * omitted, the tessellation primitive generator will produce lines or
1910 * triangles according to the primitive mode."
1913 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1914 struct gl_shader
*shader
= shader_list
[i
];
1916 if (shader
->info
.TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1917 if (gl_prog
->info
.tess
.primitive_mode
!= PRIM_UNKNOWN
&&
1918 gl_prog
->info
.tess
.primitive_mode
!=
1919 shader
->info
.TessEval
.PrimitiveMode
) {
1920 linker_error(prog
, "tessellation evaluation shader defined with "
1921 "conflicting input primitive modes.\n");
1924 gl_prog
->info
.tess
.primitive_mode
=
1925 shader
->info
.TessEval
.PrimitiveMode
;
1928 if (shader
->info
.TessEval
.Spacing
!= 0) {
1929 if (gl_prog
->info
.tess
.spacing
!= 0 && gl_prog
->info
.tess
.spacing
!=
1930 shader
->info
.TessEval
.Spacing
) {
1931 linker_error(prog
, "tessellation evaluation shader defined with "
1932 "conflicting vertex spacing.\n");
1935 gl_prog
->info
.tess
.spacing
= shader
->info
.TessEval
.Spacing
;
1938 if (shader
->info
.TessEval
.VertexOrder
!= 0) {
1939 if (vertex_order
!= 0 &&
1940 vertex_order
!= shader
->info
.TessEval
.VertexOrder
) {
1941 linker_error(prog
, "tessellation evaluation shader defined with "
1942 "conflicting ordering.\n");
1945 vertex_order
= shader
->info
.TessEval
.VertexOrder
;
1948 if (shader
->info
.TessEval
.PointMode
!= -1) {
1949 if (point_mode
!= -1 &&
1950 point_mode
!= shader
->info
.TessEval
.PointMode
) {
1951 linker_error(prog
, "tessellation evaluation shader defined with "
1952 "conflicting point modes.\n");
1955 point_mode
= shader
->info
.TessEval
.PointMode
;
1960 /* Just do the intrastage -> interstage propagation right now,
1961 * since we already know we're in the right type of shader program
1964 if (gl_prog
->info
.tess
.primitive_mode
== PRIM_UNKNOWN
) {
1966 "tessellation evaluation shader didn't declare input "
1967 "primitive modes.\n");
1971 if (gl_prog
->info
.tess
.spacing
== TESS_SPACING_UNSPECIFIED
)
1972 gl_prog
->info
.tess
.spacing
= TESS_SPACING_EQUAL
;
1974 if (vertex_order
== 0 || vertex_order
== GL_CCW
)
1975 gl_prog
->info
.tess
.ccw
= true;
1977 gl_prog
->info
.tess
.ccw
= false;
1980 if (point_mode
== -1 || point_mode
== GL_FALSE
)
1981 gl_prog
->info
.tess
.point_mode
= false;
1983 gl_prog
->info
.tess
.point_mode
= true;
1988 * Performs the cross-validation of layout qualifiers specified in
1989 * redeclaration of gl_FragCoord for the attached fragment shaders,
1990 * and propagates them to the linked FS and linked shader program.
1993 link_fs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1994 struct gl_linked_shader
*linked_shader
,
1995 struct gl_shader
**shader_list
,
1996 unsigned num_shaders
)
1998 bool redeclares_gl_fragcoord
= false;
1999 bool uses_gl_fragcoord
= false;
2000 bool origin_upper_left
= false;
2001 bool pixel_center_integer
= false;
2003 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
2004 (prog
->data
->Version
< 150 &&
2005 !prog
->ARB_fragment_coord_conventions_enable
))
2008 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2009 struct gl_shader
*shader
= shader_list
[i
];
2010 /* From the GLSL 1.50 spec, page 39:
2012 * "If gl_FragCoord is redeclared in any fragment shader in a program,
2013 * it must be redeclared in all the fragment shaders in that program
2014 * that have a static use gl_FragCoord."
2016 if ((redeclares_gl_fragcoord
&& !shader
->redeclares_gl_fragcoord
&&
2017 shader
->uses_gl_fragcoord
)
2018 || (shader
->redeclares_gl_fragcoord
&& !redeclares_gl_fragcoord
&&
2019 uses_gl_fragcoord
)) {
2020 linker_error(prog
, "fragment shader defined with conflicting "
2021 "layout qualifiers for gl_FragCoord\n");
2024 /* From the GLSL 1.50 spec, page 39:
2026 * "All redeclarations of gl_FragCoord in all fragment shaders in a
2027 * single program must have the same set of qualifiers."
2029 if (redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
&&
2030 (shader
->origin_upper_left
!= origin_upper_left
||
2031 shader
->pixel_center_integer
!= pixel_center_integer
)) {
2032 linker_error(prog
, "fragment shader defined with conflicting "
2033 "layout qualifiers for gl_FragCoord\n");
2036 /* Update the linked shader state. Note that uses_gl_fragcoord should
2037 * accumulate the results. The other values should replace. If there
2038 * are multiple redeclarations, all the fields except uses_gl_fragcoord
2039 * are already known to be the same.
2041 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
2042 redeclares_gl_fragcoord
= shader
->redeclares_gl_fragcoord
;
2043 uses_gl_fragcoord
|= shader
->uses_gl_fragcoord
;
2044 origin_upper_left
= shader
->origin_upper_left
;
2045 pixel_center_integer
= shader
->pixel_center_integer
;
2048 linked_shader
->Program
->info
.fs
.early_fragment_tests
|=
2049 shader
->EarlyFragmentTests
|| shader
->PostDepthCoverage
;
2050 linked_shader
->Program
->info
.fs
.inner_coverage
|= shader
->InnerCoverage
;
2051 linked_shader
->Program
->info
.fs
.post_depth_coverage
|=
2052 shader
->PostDepthCoverage
;
2053 linked_shader
->Program
->info
.fs
.pixel_interlock_ordered
|=
2054 shader
->PixelInterlockOrdered
;
2055 linked_shader
->Program
->info
.fs
.pixel_interlock_unordered
|=
2056 shader
->PixelInterlockUnordered
;
2057 linked_shader
->Program
->info
.fs
.sample_interlock_ordered
|=
2058 shader
->SampleInterlockOrdered
;
2059 linked_shader
->Program
->info
.fs
.sample_interlock_unordered
|=
2060 shader
->SampleInterlockUnordered
;
2061 linked_shader
->Program
->sh
.fs
.BlendSupport
|= shader
->BlendSupport
;
2064 linked_shader
->Program
->info
.fs
.pixel_center_integer
= pixel_center_integer
;
2065 linked_shader
->Program
->info
.fs
.origin_upper_left
= origin_upper_left
;
2069 * Performs the cross-validation of geometry shader max_vertices and
2070 * primitive type layout qualifiers for the attached geometry shaders,
2071 * and propagates them to the linked GS and linked shader program.
2074 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
2075 struct gl_program
*gl_prog
,
2076 struct gl_shader
**shader_list
,
2077 unsigned num_shaders
)
2079 /* No in/out qualifiers defined for anything but GLSL 1.50+
2080 * geometry shaders so far.
2082 if (gl_prog
->info
.stage
!= MESA_SHADER_GEOMETRY
||
2083 prog
->data
->Version
< 150)
2086 int vertices_out
= -1;
2088 gl_prog
->info
.gs
.invocations
= 0;
2089 gl_prog
->info
.gs
.input_primitive
= PRIM_UNKNOWN
;
2090 gl_prog
->info
.gs
.output_primitive
= PRIM_UNKNOWN
;
2092 /* From the GLSL 1.50 spec, page 46:
2094 * "All geometry shader output layout declarations in a program
2095 * must declare the same layout and same value for
2096 * max_vertices. There must be at least one geometry output
2097 * layout declaration somewhere in a program, but not all
2098 * geometry shaders (compilation units) are required to
2102 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2103 struct gl_shader
*shader
= shader_list
[i
];
2105 if (shader
->info
.Geom
.InputType
!= PRIM_UNKNOWN
) {
2106 if (gl_prog
->info
.gs
.input_primitive
!= PRIM_UNKNOWN
&&
2107 gl_prog
->info
.gs
.input_primitive
!=
2108 shader
->info
.Geom
.InputType
) {
2109 linker_error(prog
, "geometry shader defined with conflicting "
2113 gl_prog
->info
.gs
.input_primitive
= shader
->info
.Geom
.InputType
;
2116 if (shader
->info
.Geom
.OutputType
!= PRIM_UNKNOWN
) {
2117 if (gl_prog
->info
.gs
.output_primitive
!= PRIM_UNKNOWN
&&
2118 gl_prog
->info
.gs
.output_primitive
!=
2119 shader
->info
.Geom
.OutputType
) {
2120 linker_error(prog
, "geometry shader defined with conflicting "
2124 gl_prog
->info
.gs
.output_primitive
= shader
->info
.Geom
.OutputType
;
2127 if (shader
->info
.Geom
.VerticesOut
!= -1) {
2128 if (vertices_out
!= -1 &&
2129 vertices_out
!= shader
->info
.Geom
.VerticesOut
) {
2130 linker_error(prog
, "geometry shader defined with conflicting "
2131 "output vertex count (%d and %d)\n",
2132 vertices_out
, shader
->info
.Geom
.VerticesOut
);
2135 vertices_out
= shader
->info
.Geom
.VerticesOut
;
2138 if (shader
->info
.Geom
.Invocations
!= 0) {
2139 if (gl_prog
->info
.gs
.invocations
!= 0 &&
2140 gl_prog
->info
.gs
.invocations
!=
2141 (unsigned) shader
->info
.Geom
.Invocations
) {
2142 linker_error(prog
, "geometry shader defined with conflicting "
2143 "invocation count (%d and %d)\n",
2144 gl_prog
->info
.gs
.invocations
,
2145 shader
->info
.Geom
.Invocations
);
2148 gl_prog
->info
.gs
.invocations
= shader
->info
.Geom
.Invocations
;
2152 /* Just do the intrastage -> interstage propagation right now,
2153 * since we already know we're in the right type of shader program
2156 if (gl_prog
->info
.gs
.input_primitive
== PRIM_UNKNOWN
) {
2158 "geometry shader didn't declare primitive input type\n");
2162 if (gl_prog
->info
.gs
.output_primitive
== PRIM_UNKNOWN
) {
2164 "geometry shader didn't declare primitive output type\n");
2168 if (vertices_out
== -1) {
2170 "geometry shader didn't declare max_vertices\n");
2173 gl_prog
->info
.gs
.vertices_out
= vertices_out
;
2176 if (gl_prog
->info
.gs
.invocations
== 0)
2177 gl_prog
->info
.gs
.invocations
= 1;
2182 * Perform cross-validation of compute shader local_size_{x,y,z} layout and
2183 * derivative arrangement qualifiers for the attached compute shaders, and
2184 * propagate them to the linked CS and linked shader program.
2187 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
2188 struct gl_program
*gl_prog
,
2189 struct gl_shader
**shader_list
,
2190 unsigned num_shaders
)
2192 /* This function is called for all shader stages, but it only has an effect
2193 * for compute shaders.
2195 if (gl_prog
->info
.stage
!= MESA_SHADER_COMPUTE
)
2198 for (int i
= 0; i
< 3; i
++)
2199 gl_prog
->info
.cs
.local_size
[i
] = 0;
2201 gl_prog
->info
.cs
.local_size_variable
= false;
2203 gl_prog
->info
.cs
.derivative_group
= DERIVATIVE_GROUP_NONE
;
2205 /* From the ARB_compute_shader spec, in the section describing local size
2208 * If multiple compute shaders attached to a single program object
2209 * declare local work-group size, the declarations must be identical;
2210 * otherwise a link-time error results. Furthermore, if a program
2211 * object contains any compute shaders, at least one must contain an
2212 * input layout qualifier specifying the local work sizes of the
2213 * program, or a link-time error will occur.
2215 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
2216 struct gl_shader
*shader
= shader_list
[sh
];
2218 if (shader
->info
.Comp
.LocalSize
[0] != 0) {
2219 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2220 for (int i
= 0; i
< 3; i
++) {
2221 if (gl_prog
->info
.cs
.local_size
[i
] !=
2222 shader
->info
.Comp
.LocalSize
[i
]) {
2223 linker_error(prog
, "compute shader defined with conflicting "
2229 for (int i
= 0; i
< 3; i
++) {
2230 gl_prog
->info
.cs
.local_size
[i
] =
2231 shader
->info
.Comp
.LocalSize
[i
];
2233 } else if (shader
->info
.Comp
.LocalSizeVariable
) {
2234 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2235 /* The ARB_compute_variable_group_size spec says:
2237 * If one compute shader attached to a program declares a
2238 * variable local group size and a second compute shader
2239 * attached to the same program declares a fixed local group
2240 * size, a link-time error results.
2242 linker_error(prog
, "compute shader defined with both fixed and "
2243 "variable local group size\n");
2246 gl_prog
->info
.cs
.local_size_variable
= true;
2249 enum gl_derivative_group group
= shader
->info
.Comp
.DerivativeGroup
;
2250 if (group
!= DERIVATIVE_GROUP_NONE
) {
2251 if (gl_prog
->info
.cs
.derivative_group
!= DERIVATIVE_GROUP_NONE
&&
2252 gl_prog
->info
.cs
.derivative_group
!= group
) {
2253 linker_error(prog
, "compute shader defined with conflicting "
2254 "derivative groups\n");
2257 gl_prog
->info
.cs
.derivative_group
= group
;
2261 /* Just do the intrastage -> interstage propagation right now,
2262 * since we already know we're in the right type of shader program
2265 if (gl_prog
->info
.cs
.local_size
[0] == 0 &&
2266 !gl_prog
->info
.cs
.local_size_variable
) {
2267 linker_error(prog
, "compute shader must contain a fixed or a variable "
2268 "local group size\n");
2272 if (gl_prog
->info
.cs
.derivative_group
== DERIVATIVE_GROUP_QUADS
) {
2273 if (gl_prog
->info
.cs
.local_size
[0] % 2 != 0) {
2274 linker_error(prog
, "derivative_group_quadsNV must be used with a "
2275 "local group size whose first dimension "
2276 "is a multiple of 2\n");
2279 if (gl_prog
->info
.cs
.local_size
[1] % 2 != 0) {
2280 linker_error(prog
, "derivative_group_quadsNV must be used with a local"
2281 "group size whose second dimension "
2282 "is a multiple of 2\n");
2285 } else if (gl_prog
->info
.cs
.derivative_group
== DERIVATIVE_GROUP_LINEAR
) {
2286 if ((gl_prog
->info
.cs
.local_size
[0] *
2287 gl_prog
->info
.cs
.local_size
[1] *
2288 gl_prog
->info
.cs
.local_size
[2]) % 4 != 0) {
2289 linker_error(prog
, "derivative_group_linearNV must be used with a "
2290 "local group size whose total number of invocations "
2291 "is a multiple of 4\n");
2298 * Link all out variables on a single stage which are not
2299 * directly used in a shader with the main function.
2302 link_output_variables(struct gl_linked_shader
*linked_shader
,
2303 struct gl_shader
**shader_list
,
2304 unsigned num_shaders
)
2306 struct glsl_symbol_table
*symbols
= linked_shader
->symbols
;
2308 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2310 /* Skip shader object with main function */
2311 if (shader_list
[i
]->symbols
->get_function("main"))
2314 foreach_in_list(ir_instruction
, ir
, shader_list
[i
]->ir
) {
2315 if (ir
->ir_type
!= ir_type_variable
)
2318 ir_variable
*var
= (ir_variable
*) ir
;
2320 if (var
->data
.mode
== ir_var_shader_out
&&
2321 !symbols
->get_variable(var
->name
)) {
2322 var
= var
->clone(linked_shader
, NULL
);
2323 symbols
->add_variable(var
);
2324 linked_shader
->ir
->push_head(var
);
2334 * Combine a group of shaders for a single stage to generate a linked shader
2337 * If this function is supplied a single shader, it is cloned, and the new
2338 * shader is returned.
2340 struct gl_linked_shader
*
2341 link_intrastage_shaders(void *mem_ctx
,
2342 struct gl_context
*ctx
,
2343 struct gl_shader_program
*prog
,
2344 struct gl_shader
**shader_list
,
2345 unsigned num_shaders
,
2346 bool allow_missing_main
)
2348 struct gl_uniform_block
*ubo_blocks
= NULL
;
2349 struct gl_uniform_block
*ssbo_blocks
= NULL
;
2350 unsigned num_ubo_blocks
= 0;
2351 unsigned num_ssbo_blocks
= 0;
2353 /* Check that global variables defined in multiple shaders are consistent.
2355 glsl_symbol_table variables
;
2356 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2357 if (shader_list
[i
] == NULL
)
2359 cross_validate_globals(ctx
, prog
, shader_list
[i
]->ir
, &variables
,
2363 if (!prog
->data
->LinkStatus
)
2366 /* Check that interface blocks defined in multiple shaders are consistent.
2368 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
2370 if (!prog
->data
->LinkStatus
)
2373 /* Check that there is only a single definition of each function signature
2374 * across all shaders.
2376 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2377 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2378 ir_function
*const f
= node
->as_function();
2383 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2384 ir_function
*const other
=
2385 shader_list
[j
]->symbols
->get_function(f
->name
);
2387 /* If the other shader has no function (and therefore no function
2388 * signatures) with the same name, skip to the next shader.
2393 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2394 if (!sig
->is_defined
)
2397 ir_function_signature
*other_sig
=
2398 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2400 if (other_sig
!= NULL
&& other_sig
->is_defined
) {
2401 linker_error(prog
, "function `%s' is multiply defined\n",
2410 /* Find the shader that defines main, and make a clone of it.
2412 * Starting with the clone, search for undefined references. If one is
2413 * found, find the shader that defines it. Clone the reference and add
2414 * it to the shader. Repeat until there are no undefined references or
2415 * until a reference cannot be resolved.
2417 gl_shader
*main
= NULL
;
2418 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2419 if (_mesa_get_main_function_signature(shader_list
[i
]->symbols
)) {
2420 main
= shader_list
[i
];
2425 if (main
== NULL
&& allow_missing_main
)
2426 main
= shader_list
[0];
2429 linker_error(prog
, "%s shader lacks `main'\n",
2430 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2434 gl_linked_shader
*linked
= rzalloc(NULL
, struct gl_linked_shader
);
2435 linked
->Stage
= shader_list
[0]->Stage
;
2437 /* Create program and attach it to the linked shader */
2438 struct gl_program
*gl_prog
=
2439 ctx
->Driver
.NewProgram(ctx
,
2440 _mesa_shader_stage_to_program(shader_list
[0]->Stage
),
2443 prog
->data
->LinkStatus
= LINKING_FAILURE
;
2444 _mesa_delete_linked_shader(ctx
, linked
);
2448 _mesa_reference_shader_program_data(ctx
, &gl_prog
->sh
.data
, prog
->data
);
2450 /* Don't use _mesa_reference_program() just take ownership */
2451 linked
->Program
= gl_prog
;
2453 linked
->ir
= new(linked
) exec_list
;
2454 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2456 link_fs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2457 link_tcs_out_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2458 link_tes_in_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2459 link_gs_inout_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2460 link_cs_input_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2462 if (linked
->Stage
!= MESA_SHADER_FRAGMENT
)
2463 link_xfb_stride_layout_qualifiers(ctx
, prog
, shader_list
, num_shaders
);
2465 link_bindless_layout_qualifiers(prog
, shader_list
, num_shaders
);
2467 populate_symbol_table(linked
, shader_list
[0]->symbols
);
2469 /* The pointer to the main function in the final linked shader (i.e., the
2470 * copy of the original shader that contained the main function).
2472 ir_function_signature
*const main_sig
=
2473 _mesa_get_main_function_signature(linked
->symbols
);
2475 /* Move any instructions other than variable declarations or function
2476 * declarations into main.
2478 if (main_sig
!= NULL
) {
2479 exec_node
*insertion_point
=
2480 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2483 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2484 if (shader_list
[i
] == main
)
2487 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2488 insertion_point
, true, linked
);
2492 if (!link_function_calls(prog
, linked
, shader_list
, num_shaders
)) {
2493 _mesa_delete_linked_shader(ctx
, linked
);
2497 if (linked
->Stage
!= MESA_SHADER_FRAGMENT
)
2498 link_output_variables(linked
, shader_list
, num_shaders
);
2500 /* Make a pass over all variable declarations to ensure that arrays with
2501 * unspecified sizes have a size specified. The size is inferred from the
2502 * max_array_access field.
2504 array_sizing_visitor v
;
2506 v
.fixup_unnamed_interface_types();
2508 /* Link up uniform blocks defined within this stage. */
2509 link_uniform_blocks(mem_ctx
, ctx
, prog
, linked
, &ubo_blocks
,
2510 &num_ubo_blocks
, &ssbo_blocks
, &num_ssbo_blocks
);
2512 if (!prog
->data
->LinkStatus
) {
2513 _mesa_delete_linked_shader(ctx
, linked
);
2517 /* Copy ubo blocks to linked shader list */
2518 linked
->Program
->sh
.UniformBlocks
=
2519 ralloc_array(linked
, gl_uniform_block
*, num_ubo_blocks
);
2520 ralloc_steal(linked
, ubo_blocks
);
2521 for (unsigned i
= 0; i
< num_ubo_blocks
; i
++) {
2522 linked
->Program
->sh
.UniformBlocks
[i
] = &ubo_blocks
[i
];
2524 linked
->Program
->info
.num_ubos
= num_ubo_blocks
;
2526 /* Copy ssbo blocks to linked shader list */
2527 linked
->Program
->sh
.ShaderStorageBlocks
=
2528 ralloc_array(linked
, gl_uniform_block
*, num_ssbo_blocks
);
2529 ralloc_steal(linked
, ssbo_blocks
);
2530 for (unsigned i
= 0; i
< num_ssbo_blocks
; i
++) {
2531 linked
->Program
->sh
.ShaderStorageBlocks
[i
] = &ssbo_blocks
[i
];
2533 linked
->Program
->info
.num_ssbos
= num_ssbo_blocks
;
2535 /* At this point linked should contain all of the linked IR, so
2536 * validate it to make sure nothing went wrong.
2538 validate_ir_tree(linked
->ir
);
2540 /* Set the size of geometry shader input arrays */
2541 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2542 unsigned num_vertices
=
2543 vertices_per_prim(gl_prog
->info
.gs
.input_primitive
);
2544 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2545 MESA_SHADER_GEOMETRY
);
2546 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2547 ir
->accept(&input_resize_visitor
);
2551 if (ctx
->Const
.VertexID_is_zero_based
)
2552 lower_vertex_id(linked
);
2554 if (ctx
->Const
.LowerCsDerivedVariables
)
2555 lower_cs_derived(linked
);
2558 /* Compute the source checksum. */
2559 linked
->SourceChecksum
= 0;
2560 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2561 if (shader_list
[i
] == NULL
)
2563 linked
->SourceChecksum
^= shader_list
[i
]->SourceChecksum
;
2571 * Update the sizes of linked shader uniform arrays to the maximum
2574 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2576 * If one or more elements of an array are active,
2577 * GetActiveUniform will return the name of the array in name,
2578 * subject to the restrictions listed above. The type of the array
2579 * is returned in type. The size parameter contains the highest
2580 * array element index used, plus one. The compiler or linker
2581 * determines the highest index used. There will be only one
2582 * active uniform reported by the GL per uniform array.
2586 update_array_sizes(struct gl_shader_program
*prog
)
2588 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2589 if (prog
->_LinkedShaders
[i
] == NULL
)
2592 bool types_were_updated
= false;
2594 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2595 ir_variable
*const var
= node
->as_variable();
2597 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2598 !var
->type
->is_array())
2601 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2602 * will not be eliminated. Since we always do std140, just
2603 * don't resize arrays in UBOs.
2605 * Atomic counters are supposed to get deterministic
2606 * locations assigned based on the declaration ordering and
2607 * sizes, array compaction would mess that up.
2609 * Subroutine uniforms are not removed.
2611 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2612 var
->type
->contains_subroutine() || var
->constant_initializer
)
2615 int size
= var
->data
.max_array_access
;
2616 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2617 if (prog
->_LinkedShaders
[j
] == NULL
)
2620 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2621 ir_variable
*other_var
= node2
->as_variable();
2625 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2626 other_var
->data
.max_array_access
> size
) {
2627 size
= other_var
->data
.max_array_access
;
2632 if (size
+ 1 != (int)var
->type
->length
) {
2633 /* If this is a built-in uniform (i.e., it's backed by some
2634 * fixed-function state), adjust the number of state slots to
2635 * match the new array size. The number of slots per array entry
2636 * is not known. It seems safe to assume that the total number of
2637 * slots is an integer multiple of the number of array elements.
2638 * Determine the number of slots per array element by dividing by
2639 * the old (total) size.
2641 const unsigned num_slots
= var
->get_num_state_slots();
2642 if (num_slots
> 0) {
2643 var
->set_num_state_slots((size
+ 1)
2644 * (num_slots
/ var
->type
->length
));
2647 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2649 types_were_updated
= true;
2653 /* Update the types of dereferences in case we changed any. */
2654 if (types_were_updated
) {
2655 deref_type_updater v
;
2656 v
.run(prog
->_LinkedShaders
[i
]->ir
);
2662 * Resize tessellation evaluation per-vertex inputs to the size of
2663 * tessellation control per-vertex outputs.
2666 resize_tes_inputs(struct gl_context
*ctx
,
2667 struct gl_shader_program
*prog
)
2669 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2672 gl_linked_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2673 gl_linked_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2675 /* If no control shader is present, then the TES inputs are statically
2676 * sized to MaxPatchVertices; the actual size of the arrays won't be
2677 * known until draw time.
2679 const int num_vertices
= tcs
2680 ? tcs
->Program
->info
.tess
.tcs_vertices_out
2681 : ctx
->Const
.MaxPatchVertices
;
2683 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2684 MESA_SHADER_TESS_EVAL
);
2685 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2686 ir
->accept(&input_resize_visitor
);
2690 /* Convert the gl_PatchVerticesIn system value into a constant, since
2691 * the value is known at this point.
2693 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2694 ir_variable
*var
= ir
->as_variable();
2695 if (var
&& var
->data
.mode
== ir_var_system_value
&&
2696 var
->data
.location
== SYSTEM_VALUE_VERTICES_IN
) {
2697 void *mem_ctx
= ralloc_parent(var
);
2698 var
->data
.location
= 0;
2699 var
->data
.explicit_location
= false;
2700 var
->data
.mode
= ir_var_auto
;
2701 var
->constant_value
= new(mem_ctx
) ir_constant(num_vertices
);
2708 * Find a contiguous set of available bits in a bitmask.
2710 * \param used_mask Bits representing used (1) and unused (0) locations
2711 * \param needed_count Number of contiguous bits needed.
2714 * Base location of the available bits on success or -1 on failure.
2717 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2719 unsigned needed_mask
= (1 << needed_count
) - 1;
2720 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2722 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2723 * cannot optimize possibly infinite loops" for the loop below.
2725 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2728 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2729 if ((needed_mask
& ~used_mask
) == needed_mask
)
2739 #define SAFE_MASK_FROM_INDEX(i) (((i) >= 32) ? ~0 : ((1 << (i)) - 1))
2742 * Assign locations for either VS inputs or FS outputs.
2744 * \param mem_ctx Temporary ralloc context used for linking.
2745 * \param prog Shader program whose variables need locations
2747 * \param constants Driver specific constant values for the program.
2748 * \param target_index Selector for the program target to receive location
2749 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2750 * \c MESA_SHADER_FRAGMENT.
2751 * \param do_assignment Whether we are actually marking the assignment or we
2752 * are just doing a dry-run checking.
2755 * If locations are (or can be, in case of dry-running) successfully assigned,
2756 * true is returned. Otherwise an error is emitted to the shader link log and
2757 * false is returned.
2760 assign_attribute_or_color_locations(void *mem_ctx
,
2761 gl_shader_program
*prog
,
2762 struct gl_constants
*constants
,
2763 unsigned target_index
,
2766 /* Maximum number of generic locations. This corresponds to either the
2767 * maximum number of draw buffers or the maximum number of generic
2770 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2771 constants
->Program
[target_index
].MaxAttribs
:
2772 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2774 /* Mark invalid locations as being used.
2776 unsigned used_locations
= ~SAFE_MASK_FROM_INDEX(max_index
);
2777 unsigned double_storage_locations
= 0;
2779 assert((target_index
== MESA_SHADER_VERTEX
)
2780 || (target_index
== MESA_SHADER_FRAGMENT
));
2782 gl_linked_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2786 /* Operate in a total of four passes.
2788 * 1. Invalidate the location assignments for all vertex shader inputs.
2790 * 2. Assign locations for inputs that have user-defined (via
2791 * glBindVertexAttribLocation) locations and outputs that have
2792 * user-defined locations (via glBindFragDataLocation).
2794 * 3. Sort the attributes without assigned locations by number of slots
2795 * required in decreasing order. Fragmentation caused by attribute
2796 * locations assigned by the application may prevent large attributes
2797 * from having enough contiguous space.
2799 * 4. Assign locations to any inputs without assigned locations.
2802 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2803 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2805 const enum ir_variable_mode direction
=
2806 (target_index
== MESA_SHADER_VERTEX
)
2807 ? ir_var_shader_in
: ir_var_shader_out
;
2810 /* Temporary storage for the set of attributes that need locations assigned.
2816 /* Used below in the call to qsort. */
2817 static int compare(const void *a
, const void *b
)
2819 const temp_attr
*const l
= (const temp_attr
*) a
;
2820 const temp_attr
*const r
= (const temp_attr
*) b
;
2822 /* Reversed because we want a descending order sort below. */
2823 return r
->slots
- l
->slots
;
2826 assert(max_index
<= 32);
2828 /* Temporary array for the set of attributes that have locations assigned,
2829 * for the purpose of checking overlapping slots/components of (non-ES)
2830 * fragment shader outputs.
2832 ir_variable
*assigned
[12 * 4]; /* (max # of FS outputs) * # components */
2833 unsigned assigned_attr
= 0;
2835 unsigned num_attr
= 0;
2837 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2838 ir_variable
*const var
= node
->as_variable();
2840 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2843 if (var
->data
.explicit_location
) {
2844 var
->data
.is_unmatched_generic_inout
= 0;
2845 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2846 || (var
->data
.location
< 0)) {
2848 "invalid explicit location %d specified for `%s'\n",
2849 (var
->data
.location
< 0)
2850 ? var
->data
.location
2851 : var
->data
.location
- generic_base
,
2855 } else if (target_index
== MESA_SHADER_VERTEX
) {
2858 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2859 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2860 var
->data
.location
= binding
;
2861 var
->data
.is_unmatched_generic_inout
= 0;
2863 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2866 const char *name
= var
->name
;
2867 const glsl_type
*type
= var
->type
;
2870 /* Check if there's a binding for the variable name */
2871 if (prog
->FragDataBindings
->get(binding
, name
)) {
2872 assert(binding
>= FRAG_RESULT_DATA0
);
2873 var
->data
.location
= binding
;
2874 var
->data
.is_unmatched_generic_inout
= 0;
2876 if (prog
->FragDataIndexBindings
->get(index
, name
)) {
2877 var
->data
.index
= index
;
2882 /* If not, but it's an array type, look for name[0] */
2883 if (type
->is_array()) {
2884 name
= ralloc_asprintf(mem_ctx
, "%s[0]", name
);
2885 type
= type
->fields
.array
;
2893 if (strcmp(var
->name
, "gl_LastFragData") == 0)
2896 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2898 * "Output binding assignments will cause LinkProgram to fail:
2900 * If the program has an active output assigned to a location greater
2901 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2902 * an active output assigned an index greater than or equal to one;"
2904 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2905 var
->data
.location
- generic_base
>=
2906 (int) constants
->MaxDualSourceDrawBuffers
) {
2908 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2909 "with index %u for %s\n",
2910 var
->data
.location
- generic_base
, var
->data
.index
,
2915 const unsigned slots
= var
->type
->count_attribute_slots(target_index
== MESA_SHADER_VERTEX
);
2917 /* If the variable is not a built-in and has a location statically
2918 * assigned in the shader (presumably via a layout qualifier), make sure
2919 * that it doesn't collide with other assigned locations. Otherwise,
2920 * add it to the list of variables that need linker-assigned locations.
2922 if (var
->data
.location
!= -1) {
2923 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2924 /* From page 61 of the OpenGL 4.0 spec:
2926 * "LinkProgram will fail if the attribute bindings assigned
2927 * by BindAttribLocation do not leave not enough space to
2928 * assign a location for an active matrix attribute or an
2929 * active attribute array, both of which require multiple
2930 * contiguous generic attributes."
2932 * I think above text prohibits the aliasing of explicit and
2933 * automatic assignments. But, aliasing is allowed in manual
2934 * assignments of attribute locations. See below comments for
2937 * From OpenGL 4.0 spec, page 61:
2939 * "It is possible for an application to bind more than one
2940 * attribute name to the same location. This is referred to as
2941 * aliasing. This will only work if only one of the aliased
2942 * attributes is active in the executable program, or if no
2943 * path through the shader consumes more than one attribute of
2944 * a set of attributes aliased to the same location. A link
2945 * error can occur if the linker determines that every path
2946 * through the shader consumes multiple aliased attributes,
2947 * but implementations are not required to generate an error
2950 * From GLSL 4.30 spec, page 54:
2952 * "A program will fail to link if any two non-vertex shader
2953 * input variables are assigned to the same location. For
2954 * vertex shaders, multiple input variables may be assigned
2955 * to the same location using either layout qualifiers or via
2956 * the OpenGL API. However, such aliasing is intended only to
2957 * support vertex shaders where each execution path accesses
2958 * at most one input per each location. Implementations are
2959 * permitted, but not required, to generate link-time errors
2960 * if they detect that every path through the vertex shader
2961 * executable accesses multiple inputs assigned to any single
2962 * location. For all shader types, a program will fail to link
2963 * if explicit location assignments leave the linker unable
2964 * to find space for other variables without explicit
2967 * From OpenGL ES 3.0 spec, page 56:
2969 * "Binding more than one attribute name to the same location
2970 * is referred to as aliasing, and is not permitted in OpenGL
2971 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2972 * fail when this condition exists. However, aliasing is
2973 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2974 * This will only work if only one of the aliased attributes
2975 * is active in the executable program, or if no path through
2976 * the shader consumes more than one attribute of a set of
2977 * attributes aliased to the same location. A link error can
2978 * occur if the linker determines that every path through the
2979 * shader consumes multiple aliased attributes, but implemen-
2980 * tations are not required to generate an error in this case."
2982 * After looking at above references from OpenGL, OpenGL ES and
2983 * GLSL specifications, we allow aliasing of vertex input variables
2984 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2986 * NOTE: This is not required by the spec but its worth mentioning
2987 * here that we're not doing anything to make sure that no path
2988 * through the vertex shader executable accesses multiple inputs
2989 * assigned to any single location.
2992 /* Mask representing the contiguous slots that will be used by
2995 const unsigned attr
= var
->data
.location
- generic_base
;
2996 const unsigned use_mask
= (1 << slots
) - 1;
2997 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2998 ? "vertex shader input" : "fragment shader output";
3000 /* Generate a link error if the requested locations for this
3001 * attribute exceed the maximum allowed attribute location.
3003 if (attr
+ slots
> max_index
) {
3005 "insufficient contiguous locations "
3006 "available for %s `%s' %d %d %d\n", string
,
3007 var
->name
, used_locations
, use_mask
, attr
);
3011 /* Generate a link error if the set of bits requested for this
3012 * attribute overlaps any previously allocated bits.
3014 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
3015 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
3016 /* From section 4.4.2 (Output Layout Qualifiers) of the GLSL
3019 * "Additionally, for fragment shader outputs, if two
3020 * variables are placed within the same location, they
3021 * must have the same underlying type (floating-point or
3022 * integer). No component aliasing of output variables or
3023 * members is allowed.
3025 for (unsigned i
= 0; i
< assigned_attr
; i
++) {
3026 unsigned assigned_slots
=
3027 assigned
[i
]->type
->count_attribute_slots(false);
3028 unsigned assig_attr
=
3029 assigned
[i
]->data
.location
- generic_base
;
3030 unsigned assigned_use_mask
= (1 << assigned_slots
) - 1;
3032 if ((assigned_use_mask
<< assig_attr
) &
3033 (use_mask
<< attr
)) {
3035 const glsl_type
*assigned_type
=
3036 assigned
[i
]->type
->without_array();
3037 const glsl_type
*type
= var
->type
->without_array();
3038 if (assigned_type
->base_type
!= type
->base_type
) {
3039 linker_error(prog
, "types do not match for aliased"
3040 " %ss %s and %s\n", string
,
3041 assigned
[i
]->name
, var
->name
);
3045 unsigned assigned_component_mask
=
3046 ((1 << assigned_type
->vector_elements
) - 1) <<
3047 assigned
[i
]->data
.location_frac
;
3048 unsigned component_mask
=
3049 ((1 << type
->vector_elements
) - 1) <<
3050 var
->data
.location_frac
;
3051 if (assigned_component_mask
& component_mask
) {
3052 linker_error(prog
, "overlapping component is "
3053 "assigned to %ss %s and %s "
3055 string
, assigned
[i
]->name
, var
->name
,
3056 var
->data
.location_frac
);
3061 } else if (target_index
== MESA_SHADER_FRAGMENT
||
3062 (prog
->IsES
&& prog
->data
->Version
>= 300)) {
3063 linker_error(prog
, "overlapping location is assigned "
3064 "to %s `%s' %d %d %d\n", string
, var
->name
,
3065 used_locations
, use_mask
, attr
);
3068 linker_warning(prog
, "overlapping location is assigned "
3069 "to %s `%s' %d %d %d\n", string
, var
->name
,
3070 used_locations
, use_mask
, attr
);
3074 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
3075 /* Only track assigned variables for non-ES fragment shaders
3076 * to avoid overflowing the array.
3078 * At most one variable per fragment output component should
3081 assert(assigned_attr
< ARRAY_SIZE(assigned
));
3082 assigned
[assigned_attr
] = var
;
3086 used_locations
|= (use_mask
<< attr
);
3088 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
3090 * "A program with more than the value of MAX_VERTEX_ATTRIBS
3091 * active attribute variables may fail to link, unless
3092 * device-dependent optimizations are able to make the program
3093 * fit within available hardware resources. For the purposes
3094 * of this test, attribute variables of the type dvec3, dvec4,
3095 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
3096 * count as consuming twice as many attributes as equivalent
3097 * single-precision types. While these types use the same number
3098 * of generic attributes as their single-precision equivalents,
3099 * implementations are permitted to consume two single-precision
3100 * vectors of internal storage for each three- or four-component
3101 * double-precision vector."
3103 * Mark this attribute slot as taking up twice as much space
3104 * so we can count it properly against limits. According to
3105 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
3106 * is optional behavior, but it seems preferable.
3108 if (var
->type
->without_array()->is_dual_slot())
3109 double_storage_locations
|= (use_mask
<< attr
);
3115 if (num_attr
>= max_index
) {
3116 linker_error(prog
, "too many %s (max %u)",
3117 target_index
== MESA_SHADER_VERTEX
?
3118 "vertex shader inputs" : "fragment shader outputs",
3122 to_assign
[num_attr
].slots
= slots
;
3123 to_assign
[num_attr
].var
= var
;
3130 if (target_index
== MESA_SHADER_VERTEX
) {
3131 unsigned total_attribs_size
=
3132 util_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
3133 util_bitcount(double_storage_locations
);
3134 if (total_attribs_size
> max_index
) {
3136 "attempt to use %d vertex attribute slots only %d available ",
3137 total_attribs_size
, max_index
);
3142 /* If all of the attributes were assigned locations by the application (or
3143 * are built-in attributes with fixed locations), return early. This should
3144 * be the common case.
3149 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
3151 if (target_index
== MESA_SHADER_VERTEX
) {
3152 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
3153 * only be explicitly assigned by via glBindAttribLocation. Mark it as
3154 * reserved to prevent it from being automatically allocated below.
3156 find_deref_visitor
find("gl_Vertex");
3158 if (find
.variable_found())
3159 used_locations
|= (1 << 0);
3162 for (unsigned i
= 0; i
< num_attr
; i
++) {
3163 /* Mask representing the contiguous slots that will be used by this
3166 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
3168 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
3171 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
3172 ? "vertex shader input" : "fragment shader output";
3175 "insufficient contiguous locations "
3176 "available for %s `%s'\n",
3177 string
, to_assign
[i
].var
->name
);
3181 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
3182 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
3183 used_locations
|= (use_mask
<< location
);
3185 if (to_assign
[i
].var
->type
->without_array()->is_dual_slot())
3186 double_storage_locations
|= (use_mask
<< location
);
3189 /* Now that we have all the locations, from the GL 4.5 core spec, section
3190 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
3191 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
3192 * as equivalent single-precision types.
3194 if (target_index
== MESA_SHADER_VERTEX
) {
3195 unsigned total_attribs_size
=
3196 util_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
3197 util_bitcount(double_storage_locations
);
3198 if (total_attribs_size
> max_index
) {
3200 "attempt to use %d vertex attribute slots only %d available ",
3201 total_attribs_size
, max_index
);
3210 * Match explicit locations of outputs to inputs and deactivate the
3211 * unmatch flag if found so we don't optimise them away.
3214 match_explicit_outputs_to_inputs(gl_linked_shader
*producer
,
3215 gl_linked_shader
*consumer
)
3217 glsl_symbol_table parameters
;
3218 ir_variable
*explicit_locations
[MAX_VARYINGS_INCL_PATCH
][4] =
3221 /* Find all shader outputs in the "producer" stage.
3223 foreach_in_list(ir_instruction
, node
, producer
->ir
) {
3224 ir_variable
*const var
= node
->as_variable();
3226 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_shader_out
))
3229 if (var
->data
.explicit_location
&&
3230 var
->data
.location
>= VARYING_SLOT_VAR0
) {
3231 const unsigned idx
= var
->data
.location
- VARYING_SLOT_VAR0
;
3232 if (explicit_locations
[idx
][var
->data
.location_frac
] == NULL
)
3233 explicit_locations
[idx
][var
->data
.location_frac
] = var
;
3235 /* Always match TCS outputs. They are shared by all invocations
3236 * within a patch and can be used as shared memory.
3238 if (producer
->Stage
== MESA_SHADER_TESS_CTRL
)
3239 var
->data
.is_unmatched_generic_inout
= 0;
3243 /* Match inputs to outputs */
3244 foreach_in_list(ir_instruction
, node
, consumer
->ir
) {
3245 ir_variable
*const input
= node
->as_variable();
3247 if ((input
== NULL
) || (input
->data
.mode
!= ir_var_shader_in
))
3250 ir_variable
*output
= NULL
;
3251 if (input
->data
.explicit_location
3252 && input
->data
.location
>= VARYING_SLOT_VAR0
) {
3253 output
= explicit_locations
[input
->data
.location
- VARYING_SLOT_VAR0
]
3254 [input
->data
.location_frac
];
3256 if (output
!= NULL
){
3257 input
->data
.is_unmatched_generic_inout
= 0;
3258 output
->data
.is_unmatched_generic_inout
= 0;
3265 * Store the gl_FragDepth layout in the gl_shader_program struct.
3268 store_fragdepth_layout(struct gl_shader_program
*prog
)
3270 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
3274 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
3276 /* We don't look up the gl_FragDepth symbol directly because if
3277 * gl_FragDepth is not used in the shader, it's removed from the IR.
3278 * However, the symbol won't be removed from the symbol table.
3280 * We're only interested in the cases where the variable is NOT removed
3283 foreach_in_list(ir_instruction
, node
, ir
) {
3284 ir_variable
*const var
= node
->as_variable();
3286 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
3290 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
3291 switch (var
->data
.depth_layout
) {
3292 case ir_depth_layout_none
:
3293 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
3295 case ir_depth_layout_any
:
3296 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
3298 case ir_depth_layout_greater
:
3299 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
3301 case ir_depth_layout_less
:
3302 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
3304 case ir_depth_layout_unchanged
:
3305 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
3316 * Validate the resources used by a program versus the implementation limits
3319 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3321 unsigned total_uniform_blocks
= 0;
3322 unsigned total_shader_storage_blocks
= 0;
3324 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3325 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3330 if (sh
->Program
->info
.num_textures
>
3331 ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
3332 linker_error(prog
, "Too many %s shader texture samplers\n",
3333 _mesa_shader_stage_to_string(i
));
3336 if (sh
->num_uniform_components
>
3337 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
3338 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3339 linker_warning(prog
, "Too many %s shader default uniform block "
3340 "components, but the driver will try to optimize "
3341 "them out; this is non-portable out-of-spec "
3343 _mesa_shader_stage_to_string(i
));
3345 linker_error(prog
, "Too many %s shader default uniform block "
3347 _mesa_shader_stage_to_string(i
));
3351 if (sh
->num_combined_uniform_components
>
3352 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
3353 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3354 linker_warning(prog
, "Too many %s shader uniform components, "
3355 "but the driver will try to optimize them out; "
3356 "this is non-portable out-of-spec behavior\n",
3357 _mesa_shader_stage_to_string(i
));
3359 linker_error(prog
, "Too many %s shader uniform components\n",
3360 _mesa_shader_stage_to_string(i
));
3364 total_shader_storage_blocks
+= sh
->Program
->info
.num_ssbos
;
3365 total_uniform_blocks
+= sh
->Program
->info
.num_ubos
;
3367 const unsigned max_uniform_blocks
=
3368 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
3369 if (max_uniform_blocks
< sh
->Program
->info
.num_ubos
) {
3370 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
3371 _mesa_shader_stage_to_string(i
),
3372 sh
->Program
->info
.num_ubos
, max_uniform_blocks
);
3375 const unsigned max_shader_storage_blocks
=
3376 ctx
->Const
.Program
[i
].MaxShaderStorageBlocks
;
3377 if (max_shader_storage_blocks
< sh
->Program
->info
.num_ssbos
) {
3378 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
3379 _mesa_shader_stage_to_string(i
),
3380 sh
->Program
->info
.num_ssbos
, max_shader_storage_blocks
);
3384 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
3385 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
3386 total_uniform_blocks
, ctx
->Const
.MaxCombinedUniformBlocks
);
3389 if (total_shader_storage_blocks
> ctx
->Const
.MaxCombinedShaderStorageBlocks
) {
3390 linker_error(prog
, "Too many combined shader storage blocks (%d/%d)\n",
3391 total_shader_storage_blocks
,
3392 ctx
->Const
.MaxCombinedShaderStorageBlocks
);
3395 for (unsigned i
= 0; i
< prog
->data
->NumUniformBlocks
; i
++) {
3396 if (prog
->data
->UniformBlocks
[i
].UniformBufferSize
>
3397 ctx
->Const
.MaxUniformBlockSize
) {
3398 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
3399 prog
->data
->UniformBlocks
[i
].Name
,
3400 prog
->data
->UniformBlocks
[i
].UniformBufferSize
,
3401 ctx
->Const
.MaxUniformBlockSize
);
3405 for (unsigned i
= 0; i
< prog
->data
->NumShaderStorageBlocks
; i
++) {
3406 if (prog
->data
->ShaderStorageBlocks
[i
].UniformBufferSize
>
3407 ctx
->Const
.MaxShaderStorageBlockSize
) {
3408 linker_error(prog
, "Shader storage block %s too big (%d/%d)\n",
3409 prog
->data
->ShaderStorageBlocks
[i
].Name
,
3410 prog
->data
->ShaderStorageBlocks
[i
].UniformBufferSize
,
3411 ctx
->Const
.MaxShaderStorageBlockSize
);
3417 link_calculate_subroutine_compat(struct gl_shader_program
*prog
)
3419 unsigned mask
= prog
->data
->linked_stages
;
3421 const int i
= u_bit_scan(&mask
);
3422 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3424 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineUniformRemapTable
; j
++) {
3425 if (p
->sh
.SubroutineUniformRemapTable
[j
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
)
3428 struct gl_uniform_storage
*uni
= p
->sh
.SubroutineUniformRemapTable
[j
];
3434 if (p
->sh
.NumSubroutineFunctions
== 0) {
3435 linker_error(prog
, "subroutine uniform %s defined but no valid functions found\n", uni
->type
->name
);
3438 for (unsigned f
= 0; f
< p
->sh
.NumSubroutineFunctions
; f
++) {
3439 struct gl_subroutine_function
*fn
= &p
->sh
.SubroutineFunctions
[f
];
3440 for (int k
= 0; k
< fn
->num_compat_types
; k
++) {
3441 if (fn
->types
[k
] == uni
->type
) {
3447 uni
->num_compatible_subroutines
= count
;
3453 check_subroutine_resources(struct gl_shader_program
*prog
)
3455 unsigned mask
= prog
->data
->linked_stages
;
3457 const int i
= u_bit_scan(&mask
);
3458 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3460 if (p
->sh
.NumSubroutineUniformRemapTable
> MAX_SUBROUTINE_UNIFORM_LOCATIONS
) {
3461 linker_error(prog
, "Too many %s shader subroutine uniforms\n",
3462 _mesa_shader_stage_to_string(i
));
3467 * Validate shader image resources.
3470 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3472 unsigned total_image_units
= 0;
3473 unsigned fragment_outputs
= 0;
3474 unsigned total_shader_storage_blocks
= 0;
3476 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
3479 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3480 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3483 if (sh
->Program
->info
.num_images
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
3484 linker_error(prog
, "Too many %s shader image uniforms (%u > %u)\n",
3485 _mesa_shader_stage_to_string(i
),
3486 sh
->Program
->info
.num_images
,
3487 ctx
->Const
.Program
[i
].MaxImageUniforms
);
3489 total_image_units
+= sh
->Program
->info
.num_images
;
3490 total_shader_storage_blocks
+= sh
->Program
->info
.num_ssbos
;
3492 if (i
== MESA_SHADER_FRAGMENT
) {
3493 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3494 ir_variable
*var
= node
->as_variable();
3495 if (var
&& var
->data
.mode
== ir_var_shader_out
)
3496 /* since there are no double fs outputs - pass false */
3497 fragment_outputs
+= var
->type
->count_attribute_slots(false);
3503 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
3504 linker_error(prog
, "Too many combined image uniforms\n");
3506 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
3507 ctx
->Const
.MaxCombinedShaderOutputResources
)
3508 linker_error(prog
, "Too many combined image uniforms, shader storage "
3509 " buffers and fragment outputs\n");
3514 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3515 * for a variable, checks for overlaps between other uniforms using explicit
3519 reserve_explicit_locations(struct gl_shader_program
*prog
,
3520 string_to_uint_map
*map
, ir_variable
*var
)
3522 unsigned slots
= var
->type
->uniform_locations();
3523 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3524 unsigned return_value
= slots
;
3526 /* Resize remap table if locations do not fit in the current one. */
3527 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
3528 prog
->UniformRemapTable
=
3529 reralloc(prog
, prog
->UniformRemapTable
,
3530 gl_uniform_storage
*,
3533 if (!prog
->UniformRemapTable
) {
3534 linker_error(prog
, "Out of memory during linking.\n");
3538 /* Initialize allocated space. */
3539 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
3540 prog
->UniformRemapTable
[i
] = NULL
;
3542 prog
->NumUniformRemapTable
= max_loc
+ 1;
3545 for (unsigned i
= 0; i
< slots
; i
++) {
3546 unsigned loc
= var
->data
.location
+ i
;
3548 /* Check if location is already used. */
3549 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3551 /* Possibly same uniform from a different stage, this is ok. */
3553 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
) {
3558 /* ARB_explicit_uniform_location specification states:
3560 * "No two default-block uniform variables in the program can have
3561 * the same location, even if they are unused, otherwise a compiler
3562 * or linker error will be generated."
3565 "location qualifier for uniform %s overlaps "
3566 "previously used location\n",
3571 /* Initialize location as inactive before optimization
3572 * rounds and location assignment.
3574 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3577 /* Note, base location used for arrays. */
3578 map
->put(var
->data
.location
, var
->name
);
3580 return return_value
;
3584 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3585 struct gl_program
*p
,
3588 unsigned slots
= var
->type
->uniform_locations();
3589 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3591 /* Resize remap table if locations do not fit in the current one. */
3592 if (max_loc
+ 1 > p
->sh
.NumSubroutineUniformRemapTable
) {
3593 p
->sh
.SubroutineUniformRemapTable
=
3594 reralloc(p
, p
->sh
.SubroutineUniformRemapTable
,
3595 gl_uniform_storage
*,
3598 if (!p
->sh
.SubroutineUniformRemapTable
) {
3599 linker_error(prog
, "Out of memory during linking.\n");
3603 /* Initialize allocated space. */
3604 for (unsigned i
= p
->sh
.NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3605 p
->sh
.SubroutineUniformRemapTable
[i
] = NULL
;
3607 p
->sh
.NumSubroutineUniformRemapTable
= max_loc
+ 1;
3610 for (unsigned i
= 0; i
< slots
; i
++) {
3611 unsigned loc
= var
->data
.location
+ i
;
3613 /* Check if location is already used. */
3614 if (p
->sh
.SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3616 /* ARB_explicit_uniform_location specification states:
3617 * "No two subroutine uniform variables can have the same location
3618 * in the same shader stage, otherwise a compiler or linker error
3619 * will be generated."
3622 "location qualifier for uniform %s overlaps "
3623 "previously used location\n",
3628 /* Initialize location as inactive before optimization
3629 * rounds and location assignment.
3631 p
->sh
.SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3637 * Check and reserve all explicit uniform locations, called before
3638 * any optimizations happen to handle also inactive uniforms and
3639 * inactive array elements that may get trimmed away.
3642 check_explicit_uniform_locations(struct gl_context
*ctx
,
3643 struct gl_shader_program
*prog
)
3645 prog
->NumExplicitUniformLocations
= 0;
3647 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3650 /* This map is used to detect if overlapping explicit locations
3651 * occur with the same uniform (from different stage) or a different one.
3653 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3656 linker_error(prog
, "Out of memory during linking.\n");
3660 unsigned entries_total
= 0;
3661 unsigned mask
= prog
->data
->linked_stages
;
3663 const int i
= u_bit_scan(&mask
);
3664 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3666 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
3667 ir_variable
*var
= node
->as_variable();
3668 if (!var
|| var
->data
.mode
!= ir_var_uniform
)
3671 if (var
->data
.explicit_location
) {
3673 if (var
->type
->without_array()->is_subroutine())
3674 ret
= reserve_subroutine_explicit_locations(prog
, p
, var
);
3676 int slots
= reserve_explicit_locations(prog
, uniform_map
,
3680 entries_total
+= slots
;
3691 link_util_update_empty_uniform_locations(prog
);
3694 prog
->NumExplicitUniformLocations
= entries_total
;
3697 /* Function checks if a variable var is a packed varying and
3698 * if given name is part of packed varying's list.
3700 * If a variable is a packed varying, it has a name like
3701 * 'packed:a,b,c' where a, b and c are separate variables.
3704 included_in_packed_varying(ir_variable
*var
, const char *name
)
3706 if (strncmp(var
->name
, "packed:", 7) != 0)
3709 char *list
= strdup(var
->name
+ 7);
3714 char *token
= strtok_r(list
, ",", &saveptr
);
3716 if (strcmp(token
, name
) == 0) {
3720 token
= strtok_r(NULL
, ",", &saveptr
);
3727 * Function builds a stage reference bitmask from variable name.
3730 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3735 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3736 * used for reference mask in gl_program_resource will need to be changed.
3738 assert(MESA_SHADER_STAGES
< 8);
3740 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3741 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
3745 /* Shader symbol table may contain variables that have
3746 * been optimized away. Search IR for the variable instead.
3748 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3749 ir_variable
*var
= node
->as_variable();
3751 unsigned baselen
= strlen(var
->name
);
3753 if (included_in_packed_varying(var
, name
)) {
3758 /* Type needs to match if specified, otherwise we might
3759 * pick a variable with same name but different interface.
3761 if (var
->data
.mode
!= mode
)
3764 if (strncmp(var
->name
, name
, baselen
) == 0) {
3765 /* Check for exact name matches but also check for arrays and
3768 if (name
[baselen
] == '\0' ||
3769 name
[baselen
] == '[' ||
3770 name
[baselen
] == '.') {
3782 * Create gl_shader_variable from ir_variable class.
3784 static gl_shader_variable
*
3785 create_shader_variable(struct gl_shader_program
*shProg
,
3786 const ir_variable
*in
,
3787 const char *name
, const glsl_type
*type
,
3788 const glsl_type
*interface_type
,
3789 bool use_implicit_location
, int location
,
3790 const glsl_type
*outermost_struct_type
)
3792 /* Allocate zero-initialized memory to ensure that bitfield padding
3795 gl_shader_variable
*out
= rzalloc(shProg
, struct gl_shader_variable
);
3799 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3800 * expect to see gl_VertexID in the program resource list. Pretend.
3802 if (in
->data
.mode
== ir_var_system_value
&&
3803 in
->data
.location
== SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
) {
3804 out
->name
= ralloc_strdup(shProg
, "gl_VertexID");
3805 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3806 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_OUTER
) ||
3807 (in
->data
.mode
== ir_var_system_value
&&
3808 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_OUTER
)) {
3809 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelOuter");
3810 type
= glsl_type::get_array_instance(glsl_type::float_type
, 4);
3811 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3812 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_INNER
) ||
3813 (in
->data
.mode
== ir_var_system_value
&&
3814 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_INNER
)) {
3815 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelInner");
3816 type
= glsl_type::get_array_instance(glsl_type::float_type
, 2);
3818 out
->name
= ralloc_strdup(shProg
, name
);
3824 /* The ARB_program_interface_query spec says:
3826 * "Not all active variables are assigned valid locations; the
3827 * following variables will have an effective location of -1:
3829 * * uniforms declared as atomic counters;
3831 * * members of a uniform block;
3833 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3835 * * inputs or outputs not declared with a "location" layout
3836 * qualifier, except for vertex shader inputs and fragment shader
3839 if (in
->type
->is_atomic_uint() || is_gl_identifier(in
->name
) ||
3840 !(in
->data
.explicit_location
|| use_implicit_location
)) {
3843 out
->location
= location
;
3847 out
->outermost_struct_type
= outermost_struct_type
;
3848 out
->interface_type
= interface_type
;
3849 out
->component
= in
->data
.location_frac
;
3850 out
->index
= in
->data
.index
;
3851 out
->patch
= in
->data
.patch
;
3852 out
->mode
= in
->data
.mode
;
3853 out
->interpolation
= in
->data
.interpolation
;
3854 out
->explicit_location
= in
->data
.explicit_location
;
3855 out
->precision
= in
->data
.precision
;
3861 add_shader_variable(const struct gl_context
*ctx
,
3862 struct gl_shader_program
*shProg
,
3863 struct set
*resource_set
,
3864 unsigned stage_mask
,
3865 GLenum programInterface
, ir_variable
*var
,
3866 const char *name
, const glsl_type
*type
,
3867 bool use_implicit_location
, int location
,
3868 bool inouts_share_location
,
3869 const glsl_type
*outermost_struct_type
= NULL
)
3871 const glsl_type
*interface_type
= var
->get_interface_type();
3873 if (outermost_struct_type
== NULL
) {
3874 if (var
->data
.from_named_ifc_block
) {
3875 const char *interface_name
= interface_type
->name
;
3877 if (interface_type
->is_array()) {
3878 /* Issue #16 of the ARB_program_interface_query spec says:
3880 * "* If a variable is a member of an interface block without an
3881 * instance name, it is enumerated using just the variable name.
3883 * * If a variable is a member of an interface block with an
3884 * instance name, it is enumerated as "BlockName.Member", where
3885 * "BlockName" is the name of the interface block (not the
3886 * instance name) and "Member" is the name of the variable."
3888 * In particular, it indicates that it should be "BlockName",
3889 * not "BlockName[array length]". The conformance suite and
3890 * dEQP both require this behavior.
3892 * Here, we unwrap the extra array level added by named interface
3893 * block array lowering so we have the correct variable type. We
3894 * also unwrap the interface type when constructing the name.
3896 * We leave interface_type the same so that ES 3.x SSO pipeline
3897 * validation can enforce the rules requiring array length to
3898 * match on interface blocks.
3900 type
= type
->fields
.array
;
3902 interface_name
= interface_type
->fields
.array
->name
;
3905 name
= ralloc_asprintf(shProg
, "%s.%s", interface_name
, name
);
3909 switch (type
->base_type
) {
3910 case GLSL_TYPE_STRUCT
: {
3911 /* The ARB_program_interface_query spec says:
3913 * "For an active variable declared as a structure, a separate entry
3914 * will be generated for each active structure member. The name of
3915 * each entry is formed by concatenating the name of the structure,
3916 * the "." character, and the name of the structure member. If a
3917 * structure member to enumerate is itself a structure or array,
3918 * these enumeration rules are applied recursively."
3920 if (outermost_struct_type
== NULL
)
3921 outermost_struct_type
= type
;
3923 unsigned field_location
= location
;
3924 for (unsigned i
= 0; i
< type
->length
; i
++) {
3925 const struct glsl_struct_field
*field
= &type
->fields
.structure
[i
];
3926 char *field_name
= ralloc_asprintf(shProg
, "%s.%s", name
, field
->name
);
3927 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3928 stage_mask
, programInterface
,
3929 var
, field_name
, field
->type
,
3930 use_implicit_location
, field_location
,
3931 false, outermost_struct_type
))
3934 field_location
+= field
->type
->count_attribute_slots(false);
3939 case GLSL_TYPE_ARRAY
: {
3940 /* The ARB_program_interface_query spec says:
3942 * "For an active variable declared as an array of basic types, a
3943 * single entry will be generated, with its name string formed by
3944 * concatenating the name of the array and the string "[0]"."
3946 * "For an active variable declared as an array of an aggregate data
3947 * type (structures or arrays), a separate entry will be generated
3948 * for each active array element, unless noted immediately below.
3949 * The name of each entry is formed by concatenating the name of
3950 * the array, the "[" character, an integer identifying the element
3951 * number, and the "]" character. These enumeration rules are
3952 * applied recursively, treating each enumerated array element as a
3953 * separate active variable."
3955 const struct glsl_type
*array_type
= type
->fields
.array
;
3956 if (array_type
->base_type
== GLSL_TYPE_STRUCT
||
3957 array_type
->base_type
== GLSL_TYPE_ARRAY
) {
3958 unsigned elem_location
= location
;
3959 unsigned stride
= inouts_share_location
? 0 :
3960 array_type
->count_attribute_slots(false);
3961 for (unsigned i
= 0; i
< type
->length
; i
++) {
3962 char *elem
= ralloc_asprintf(shProg
, "%s[%d]", name
, i
);
3963 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3964 stage_mask
, programInterface
,
3965 var
, elem
, array_type
,
3966 use_implicit_location
, elem_location
,
3967 false, outermost_struct_type
))
3969 elem_location
+= stride
;
3977 /* The ARB_program_interface_query spec says:
3979 * "For an active variable declared as a single instance of a basic
3980 * type, a single entry will be generated, using the variable name
3981 * from the shader source."
3983 gl_shader_variable
*sha_v
=
3984 create_shader_variable(shProg
, var
, name
, type
, interface_type
,
3985 use_implicit_location
, location
,
3986 outermost_struct_type
);
3990 return link_util_add_program_resource(shProg
, resource_set
,
3991 programInterface
, sha_v
, stage_mask
);
3997 inout_has_same_location(const ir_variable
*var
, unsigned stage
)
3999 if (!var
->data
.patch
&&
4000 ((var
->data
.mode
== ir_var_shader_out
&&
4001 stage
== MESA_SHADER_TESS_CTRL
) ||
4002 (var
->data
.mode
== ir_var_shader_in
&&
4003 (stage
== MESA_SHADER_TESS_CTRL
|| stage
== MESA_SHADER_TESS_EVAL
||
4004 stage
== MESA_SHADER_GEOMETRY
))))
4011 add_interface_variables(const struct gl_context
*ctx
,
4012 struct gl_shader_program
*shProg
,
4013 struct set
*resource_set
,
4014 unsigned stage
, GLenum programInterface
)
4016 exec_list
*ir
= shProg
->_LinkedShaders
[stage
]->ir
;
4018 foreach_in_list(ir_instruction
, node
, ir
) {
4019 ir_variable
*var
= node
->as_variable();
4021 if (!var
|| var
->data
.how_declared
== ir_var_hidden
)
4026 switch (var
->data
.mode
) {
4027 case ir_var_system_value
:
4028 case ir_var_shader_in
:
4029 if (programInterface
!= GL_PROGRAM_INPUT
)
4031 loc_bias
= (stage
== MESA_SHADER_VERTEX
) ? int(VERT_ATTRIB_GENERIC0
)
4032 : int(VARYING_SLOT_VAR0
);
4034 case ir_var_shader_out
:
4035 if (programInterface
!= GL_PROGRAM_OUTPUT
)
4037 loc_bias
= (stage
== MESA_SHADER_FRAGMENT
) ? int(FRAG_RESULT_DATA0
)
4038 : int(VARYING_SLOT_VAR0
);
4044 if (var
->data
.patch
)
4045 loc_bias
= int(VARYING_SLOT_PATCH0
);
4047 /* Skip packed varyings, packed varyings are handled separately
4048 * by add_packed_varyings.
4050 if (strncmp(var
->name
, "packed:", 7) == 0)
4053 /* Skip fragdata arrays, these are handled separately
4054 * by add_fragdata_arrays.
4056 if (strncmp(var
->name
, "gl_out_FragData", 15) == 0)
4059 const bool vs_input_or_fs_output
=
4060 (stage
== MESA_SHADER_VERTEX
&& var
->data
.mode
== ir_var_shader_in
) ||
4061 (stage
== MESA_SHADER_FRAGMENT
&& var
->data
.mode
== ir_var_shader_out
);
4063 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4064 1 << stage
, programInterface
,
4065 var
, var
->name
, var
->type
, vs_input_or_fs_output
,
4066 var
->data
.location
- loc_bias
,
4067 inout_has_same_location(var
, stage
)))
4074 add_packed_varyings(const struct gl_context
*ctx
,
4075 struct gl_shader_program
*shProg
,
4076 struct set
*resource_set
,
4077 int stage
, GLenum type
)
4079 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[stage
];
4082 if (!sh
|| !sh
->packed_varyings
)
4085 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
4086 ir_variable
*var
= node
->as_variable();
4088 switch (var
->data
.mode
) {
4089 case ir_var_shader_in
:
4090 iface
= GL_PROGRAM_INPUT
;
4092 case ir_var_shader_out
:
4093 iface
= GL_PROGRAM_OUTPUT
;
4096 unreachable("unexpected type");
4099 if (type
== iface
) {
4100 const int stage_mask
=
4101 build_stageref(shProg
, var
->name
, var
->data
.mode
);
4102 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4104 iface
, var
, var
->name
, var
->type
, false,
4105 var
->data
.location
- VARYING_SLOT_VAR0
,
4106 inout_has_same_location(var
, stage
)))
4115 add_fragdata_arrays(const struct gl_context
*ctx
,
4116 struct gl_shader_program
*shProg
,
4117 struct set
*resource_set
)
4119 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4121 if (!sh
|| !sh
->fragdata_arrays
)
4124 foreach_in_list(ir_instruction
, node
, sh
->fragdata_arrays
) {
4125 ir_variable
*var
= node
->as_variable();
4127 assert(var
->data
.mode
== ir_var_shader_out
);
4129 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4130 1 << MESA_SHADER_FRAGMENT
,
4131 GL_PROGRAM_OUTPUT
, var
, var
->name
, var
->type
,
4132 true, var
->data
.location
- FRAG_RESULT_DATA0
,
4141 get_top_level_name(const char *name
)
4143 const char *first_dot
= strchr(name
, '.');
4144 const char *first_square_bracket
= strchr(name
, '[');
4147 /* The ARB_program_interface_query spec says:
4149 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4150 * the number of active array elements of the top-level shader storage
4151 * block member containing to the active variable is written to
4152 * <params>. If the top-level block member is not declared as an
4153 * array, the value one is written to <params>. If the top-level block
4154 * member is an array with no declared size, the value zero is written
4158 /* The buffer variable is on top level.*/
4159 if (!first_square_bracket
&& !first_dot
)
4160 name_size
= strlen(name
);
4161 else if ((!first_square_bracket
||
4162 (first_dot
&& first_dot
< first_square_bracket
)))
4163 name_size
= first_dot
- name
;
4165 name_size
= first_square_bracket
- name
;
4167 return strndup(name
, name_size
);
4171 get_var_name(const char *name
)
4173 const char *first_dot
= strchr(name
, '.');
4176 return strdup(name
);
4178 return strndup(first_dot
+1, strlen(first_dot
) - 1);
4182 is_top_level_shader_storage_block_member(const char* name
,
4183 const char* interface_name
,
4184 const char* field_name
)
4186 bool result
= false;
4188 /* If the given variable is already a top-level shader storage
4189 * block member, then return array_size = 1.
4190 * We could have two possibilities: if we have an instanced
4191 * shader storage block or not instanced.
4193 * For the first, we check create a name as it was in top level and
4194 * compare it with the real name. If they are the same, then
4195 * the variable is already at top-level.
4197 * Full instanced name is: interface name + '.' + var name +
4200 int name_length
= strlen(interface_name
) + 1 + strlen(field_name
) + 1;
4201 char *full_instanced_name
= (char *) calloc(name_length
, sizeof(char));
4202 if (!full_instanced_name
) {
4203 fprintf(stderr
, "%s: Cannot allocate space for name\n", __func__
);
4207 snprintf(full_instanced_name
, name_length
, "%s.%s",
4208 interface_name
, field_name
);
4210 /* Check if its top-level shader storage block member of an
4211 * instanced interface block, or of a unnamed interface block.
4213 if (strcmp(name
, full_instanced_name
) == 0 ||
4214 strcmp(name
, field_name
) == 0)
4217 free(full_instanced_name
);
4222 get_array_size(struct gl_uniform_storage
*uni
, const glsl_struct_field
*field
,
4223 char *interface_name
, char *var_name
)
4225 /* The ARB_program_interface_query spec says:
4227 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4228 * the number of active array elements of the top-level shader storage
4229 * block member containing to the active variable is written to
4230 * <params>. If the top-level block member is not declared as an
4231 * array, the value one is written to <params>. If the top-level block
4232 * member is an array with no declared size, the value zero is written
4235 if (is_top_level_shader_storage_block_member(uni
->name
,
4239 else if (field
->type
->is_unsized_array())
4241 else if (field
->type
->is_array())
4242 return field
->type
->length
;
4248 get_array_stride(struct gl_context
*ctx
, struct gl_uniform_storage
*uni
,
4249 const glsl_type
*iface
, const glsl_struct_field
*field
,
4250 char *interface_name
, char *var_name
)
4252 /* The ARB_program_interface_query spec says:
4254 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
4255 * identifying the stride between array elements of the top-level
4256 * shader storage block member containing the active variable is
4257 * written to <params>. For top-level block members declared as
4258 * arrays, the value written is the difference, in basic machine units,
4259 * between the offsets of the active variable for consecutive elements
4260 * in the top-level array. For top-level block members not declared as
4261 * an array, zero is written to <params>."
4263 if (field
->type
->is_array()) {
4264 const enum glsl_matrix_layout matrix_layout
=
4265 glsl_matrix_layout(field
->matrix_layout
);
4266 bool row_major
= matrix_layout
== GLSL_MATRIX_LAYOUT_ROW_MAJOR
;
4267 const glsl_type
*array_type
= field
->type
->fields
.array
;
4269 if (is_top_level_shader_storage_block_member(uni
->name
,
4274 if (GLSL_INTERFACE_PACKING_STD140
==
4276 get_internal_ifc_packing(ctx
->Const
.UseSTD430AsDefaultPacking
)) {
4277 if (array_type
->is_struct() || array_type
->is_array())
4278 return glsl_align(array_type
->std140_size(row_major
), 16);
4280 return MAX2(array_type
->std140_base_alignment(row_major
), 16);
4282 return array_type
->std430_array_stride(row_major
);
4289 calculate_array_size_and_stride(struct gl_context
*ctx
,
4290 struct gl_shader_program
*shProg
,
4291 struct gl_uniform_storage
*uni
)
4293 int block_index
= uni
->block_index
;
4294 int array_size
= -1;
4295 int array_stride
= -1;
4296 char *var_name
= get_top_level_name(uni
->name
);
4297 char *interface_name
=
4298 get_top_level_name(uni
->is_shader_storage
?
4299 shProg
->data
->ShaderStorageBlocks
[block_index
].Name
:
4300 shProg
->data
->UniformBlocks
[block_index
].Name
);
4302 if (strcmp(var_name
, interface_name
) == 0) {
4303 /* Deal with instanced array of SSBOs */
4304 char *temp_name
= get_var_name(uni
->name
);
4306 linker_error(shProg
, "Out of memory during linking.\n");
4307 goto write_top_level_array_size_and_stride
;
4310 var_name
= get_top_level_name(temp_name
);
4313 linker_error(shProg
, "Out of memory during linking.\n");
4314 goto write_top_level_array_size_and_stride
;
4318 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4319 const gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
4323 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
4324 ir_variable
*var
= node
->as_variable();
4325 if (!var
|| !var
->get_interface_type() ||
4326 var
->data
.mode
!= ir_var_shader_storage
)
4329 const glsl_type
*iface
= var
->get_interface_type();
4331 if (strcmp(interface_name
, iface
->name
) != 0)
4334 for (unsigned i
= 0; i
< iface
->length
; i
++) {
4335 const glsl_struct_field
*field
= &iface
->fields
.structure
[i
];
4336 if (strcmp(field
->name
, var_name
) != 0)
4339 array_stride
= get_array_stride(ctx
, uni
, iface
, field
,
4340 interface_name
, var_name
);
4341 array_size
= get_array_size(uni
, field
, interface_name
, var_name
);
4342 goto write_top_level_array_size_and_stride
;
4346 write_top_level_array_size_and_stride
:
4347 free(interface_name
);
4349 uni
->top_level_array_stride
= array_stride
;
4350 uni
->top_level_array_size
= array_size
;
4354 * Builds up a list of program resources that point to existing
4358 build_program_resource_list(struct gl_context
*ctx
,
4359 struct gl_shader_program
*shProg
)
4361 /* Rebuild resource list. */
4362 if (shProg
->data
->ProgramResourceList
) {
4363 ralloc_free(shProg
->data
->ProgramResourceList
);
4364 shProg
->data
->ProgramResourceList
= NULL
;
4365 shProg
->data
->NumProgramResourceList
= 0;
4368 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
4370 /* Determine first input and final output stage. These are used to
4371 * detect which variables should be enumerated in the resource list
4372 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4374 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4375 if (!shProg
->_LinkedShaders
[i
])
4377 if (input_stage
== MESA_SHADER_STAGES
)
4382 /* Empty shader, no resources. */
4383 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
4386 struct set
*resource_set
= _mesa_pointer_set_create(NULL
);
4388 /* Program interface needs to expose varyings in case of SSO. */
4389 if (shProg
->SeparateShader
) {
4390 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4391 input_stage
, GL_PROGRAM_INPUT
))
4394 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4395 output_stage
, GL_PROGRAM_OUTPUT
))
4399 if (!add_fragdata_arrays(ctx
, shProg
, resource_set
))
4402 /* Add inputs and outputs to the resource list. */
4403 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4404 input_stage
, GL_PROGRAM_INPUT
))
4407 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4408 output_stage
, GL_PROGRAM_OUTPUT
))
4411 if (shProg
->last_vert_prog
) {
4412 struct gl_transform_feedback_info
*linked_xfb
=
4413 shProg
->last_vert_prog
->sh
.LinkedTransformFeedback
;
4415 /* Add transform feedback varyings. */
4416 if (linked_xfb
->NumVarying
> 0) {
4417 for (int i
= 0; i
< linked_xfb
->NumVarying
; i
++) {
4418 if (!link_util_add_program_resource(shProg
, resource_set
,
4419 GL_TRANSFORM_FEEDBACK_VARYING
,
4420 &linked_xfb
->Varyings
[i
], 0))
4425 /* Add transform feedback buffers. */
4426 for (unsigned i
= 0; i
< ctx
->Const
.MaxTransformFeedbackBuffers
; i
++) {
4427 if ((linked_xfb
->ActiveBuffers
>> i
) & 1) {
4428 linked_xfb
->Buffers
[i
].Binding
= i
;
4429 if (!link_util_add_program_resource(shProg
, resource_set
,
4430 GL_TRANSFORM_FEEDBACK_BUFFER
,
4431 &linked_xfb
->Buffers
[i
], 0))
4437 int top_level_array_base_offset
= -1;
4438 int top_level_array_size_in_bytes
= -1;
4439 int second_element_offset
= -1;
4440 int buffer_block_index
= -1;
4442 /* Add uniforms from uniform storage. */
4443 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4444 /* Do not add uniforms internally used by Mesa. */
4445 if (shProg
->data
->UniformStorage
[i
].hidden
)
4449 build_stageref(shProg
, shProg
->data
->UniformStorage
[i
].name
,
4452 /* Add stagereferences for uniforms in a uniform block. */
4453 bool is_shader_storage
=
4454 shProg
->data
->UniformStorage
[i
].is_shader_storage
;
4455 int block_index
= shProg
->data
->UniformStorage
[i
].block_index
;
4456 if (block_index
!= -1) {
4457 stageref
|= is_shader_storage
?
4458 shProg
->data
->ShaderStorageBlocks
[block_index
].stageref
:
4459 shProg
->data
->UniformBlocks
[block_index
].stageref
;
4462 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
4463 if (!link_util_should_add_buffer_variable(shProg
,
4464 &shProg
->data
->UniformStorage
[i
],
4465 top_level_array_base_offset
,
4466 top_level_array_size_in_bytes
,
4467 second_element_offset
,
4468 buffer_block_index
))
4471 if (is_shader_storage
) {
4472 calculate_array_size_and_stride(ctx
, shProg
,
4473 &shProg
->data
->UniformStorage
[i
]);
4475 /* From the OpenGL 4.6 specification, 7.3.1.1 Naming Active Resources:
4477 * "For an active shader storage block member declared as an array
4478 * of an aggregate type, an entry will be generated only for the
4479 * first array element, regardless of its type. Such block members
4480 * are referred to as top-level arrays. If the block member is an
4481 * aggregate type, the enumeration rules are then applied
4484 * Below we update our tracking values used by
4485 * link_util_should_add_buffer_variable(). We only want to reset the
4486 * offsets once we have moved past the first element.
4488 if (shProg
->data
->UniformStorage
[i
].offset
>= second_element_offset
) {
4489 top_level_array_base_offset
=
4490 shProg
->data
->UniformStorage
[i
].offset
;
4492 top_level_array_size_in_bytes
=
4493 shProg
->data
->UniformStorage
[i
].top_level_array_size
*
4494 shProg
->data
->UniformStorage
[i
].top_level_array_stride
;
4496 /* Set or reset the second element offset. For non arrays this
4497 * will be set to -1.
4499 second_element_offset
= top_level_array_size_in_bytes
?
4500 top_level_array_base_offset
+
4501 shProg
->data
->UniformStorage
[i
].top_level_array_stride
: -1;
4504 buffer_block_index
= shProg
->data
->UniformStorage
[i
].block_index
;
4507 if (!link_util_add_program_resource(shProg
, resource_set
, type
,
4508 &shProg
->data
->UniformStorage
[i
], stageref
))
4512 /* Add program uniform blocks. */
4513 for (unsigned i
= 0; i
< shProg
->data
->NumUniformBlocks
; i
++) {
4514 if (!link_util_add_program_resource(shProg
, resource_set
, GL_UNIFORM_BLOCK
,
4515 &shProg
->data
->UniformBlocks
[i
], 0))
4519 /* Add program shader storage blocks. */
4520 for (unsigned i
= 0; i
< shProg
->data
->NumShaderStorageBlocks
; i
++) {
4521 if (!link_util_add_program_resource(shProg
, resource_set
, GL_SHADER_STORAGE_BLOCK
,
4522 &shProg
->data
->ShaderStorageBlocks
[i
], 0))
4526 /* Add atomic counter buffers. */
4527 for (unsigned i
= 0; i
< shProg
->data
->NumAtomicBuffers
; i
++) {
4528 if (!link_util_add_program_resource(shProg
, resource_set
, GL_ATOMIC_COUNTER_BUFFER
,
4529 &shProg
->data
->AtomicBuffers
[i
], 0))
4533 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4535 if (!shProg
->data
->UniformStorage
[i
].hidden
)
4538 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
4539 if (!shProg
->data
->UniformStorage
[i
].opaque
[j
].active
||
4540 !shProg
->data
->UniformStorage
[i
].type
->is_subroutine())
4543 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
4544 /* add shader subroutines */
4545 if (!link_util_add_program_resource(shProg
, resource_set
,
4546 type
, &shProg
->data
->UniformStorage
[i
], 0))
4551 unsigned mask
= shProg
->data
->linked_stages
;
4553 const int i
= u_bit_scan(&mask
);
4554 struct gl_program
*p
= shProg
->_LinkedShaders
[i
]->Program
;
4556 GLuint type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
4557 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4558 if (!link_util_add_program_resource(shProg
, resource_set
,
4559 type
, &p
->sh
.SubroutineFunctions
[j
], 0))
4564 _mesa_set_destroy(resource_set
, NULL
);
4568 * This check is done to make sure we allow only constant expression
4569 * indexing and "constant-index-expression" (indexing with an expression
4570 * that includes loop induction variable).
4573 validate_sampler_array_indexing(struct gl_context
*ctx
,
4574 struct gl_shader_program
*prog
)
4576 dynamic_sampler_array_indexing_visitor v
;
4577 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4578 if (prog
->_LinkedShaders
[i
] == NULL
)
4581 bool no_dynamic_indexing
=
4582 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
4584 /* Search for array derefs in shader. */
4585 v
.run(prog
->_LinkedShaders
[i
]->ir
);
4586 if (v
.uses_dynamic_sampler_array_indexing()) {
4587 const char *msg
= "sampler arrays indexed with non-constant "
4588 "expressions is forbidden in GLSL %s %u";
4589 /* Backend has indicated that it has no dynamic indexing support. */
4590 if (no_dynamic_indexing
) {
4591 linker_error(prog
, msg
, prog
->IsES
? "ES" : "",
4592 prog
->data
->Version
);
4595 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "",
4596 prog
->data
->Version
);
4604 link_assign_subroutine_types(struct gl_shader_program
*prog
)
4606 unsigned mask
= prog
->data
->linked_stages
;
4608 const int i
= u_bit_scan(&mask
);
4609 gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
4611 p
->sh
.MaxSubroutineFunctionIndex
= 0;
4612 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
4613 ir_function
*fn
= node
->as_function();
4617 if (fn
->is_subroutine
)
4618 p
->sh
.NumSubroutineUniformTypes
++;
4620 if (!fn
->num_subroutine_types
)
4623 /* these should have been calculated earlier. */
4624 assert(fn
->subroutine_index
!= -1);
4625 if (p
->sh
.NumSubroutineFunctions
+ 1 > MAX_SUBROUTINES
) {
4626 linker_error(prog
, "Too many subroutine functions declared.\n");
4629 p
->sh
.SubroutineFunctions
= reralloc(p
, p
->sh
.SubroutineFunctions
,
4630 struct gl_subroutine_function
,
4631 p
->sh
.NumSubroutineFunctions
+ 1);
4632 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].name
= ralloc_strdup(p
, fn
->name
);
4633 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
4634 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
=
4635 ralloc_array(p
, const struct glsl_type
*,
4636 fn
->num_subroutine_types
);
4638 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4641 * "Each subroutine with an index qualifier in the shader must be
4642 * given a unique index, otherwise a compile or link error will be
4645 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4646 if (p
->sh
.SubroutineFunctions
[j
].index
!= -1 &&
4647 p
->sh
.SubroutineFunctions
[j
].index
== fn
->subroutine_index
) {
4648 linker_error(prog
, "each subroutine index qualifier in the "
4649 "shader must be unique\n");
4653 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].index
=
4654 fn
->subroutine_index
;
4656 if (fn
->subroutine_index
> (int)p
->sh
.MaxSubroutineFunctionIndex
)
4657 p
->sh
.MaxSubroutineFunctionIndex
= fn
->subroutine_index
;
4659 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
4660 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
4661 p
->sh
.NumSubroutineFunctions
++;
4667 verify_subroutine_associated_funcs(struct gl_shader_program
*prog
)
4669 unsigned mask
= prog
->data
->linked_stages
;
4671 const int i
= u_bit_scan(&mask
);
4672 gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
4673 glsl_symbol_table
*symbols
= prog
->_LinkedShaders
[i
]->symbols
;
4675 /* Section 6.1.2 (Subroutines) of the GLSL 4.00 spec says:
4677 * "A program will fail to compile or link if any shader
4678 * or stage contains two or more functions with the same
4679 * name if the name is associated with a subroutine type."
4681 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4682 unsigned definitions
= 0;
4683 char *name
= p
->sh
.SubroutineFunctions
[j
].name
;
4684 ir_function
*fn
= symbols
->get_function(name
);
4686 /* Calculate number of function definitions with the same name */
4687 foreach_in_list(ir_function_signature
, sig
, &fn
->signatures
) {
4688 if (sig
->is_defined
) {
4689 if (++definitions
> 1) {
4690 linker_error(prog
, "%s shader contains two or more function "
4691 "definitions with name `%s', which is "
4692 "associated with a subroutine type.\n",
4693 _mesa_shader_stage_to_string(i
),
4705 set_always_active_io(exec_list
*ir
, ir_variable_mode io_mode
)
4707 assert(io_mode
== ir_var_shader_in
|| io_mode
== ir_var_shader_out
);
4709 foreach_in_list(ir_instruction
, node
, ir
) {
4710 ir_variable
*const var
= node
->as_variable();
4712 if (var
== NULL
|| var
->data
.mode
!= io_mode
)
4715 /* Don't set always active on builtins that haven't been redeclared */
4716 if (var
->data
.how_declared
== ir_var_declared_implicitly
)
4719 var
->data
.always_active_io
= true;
4724 * When separate shader programs are enabled, only input/outputs between
4725 * the stages of a multi-stage separate program can be safely removed
4726 * from the shader interface. Other inputs/outputs must remain active.
4729 disable_varying_optimizations_for_sso(struct gl_shader_program
*prog
)
4731 unsigned first
, last
;
4732 assert(prog
->SeparateShader
);
4734 first
= MESA_SHADER_STAGES
;
4737 /* Determine first and last stage. Excluding the compute stage */
4738 for (unsigned i
= 0; i
< MESA_SHADER_COMPUTE
; i
++) {
4739 if (!prog
->_LinkedShaders
[i
])
4741 if (first
== MESA_SHADER_STAGES
)
4746 if (first
== MESA_SHADER_STAGES
)
4749 for (unsigned stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4750 gl_linked_shader
*sh
= prog
->_LinkedShaders
[stage
];
4754 /* Prevent the removal of inputs to the first and outputs from the last
4755 * stage, unless they are the initial pipeline inputs or final pipeline
4756 * outputs, respectively.
4758 * The removal of IO between shaders in the same program is always
4761 if (stage
== first
&& stage
!= MESA_SHADER_VERTEX
)
4762 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4763 if (stage
== last
&& stage
!= MESA_SHADER_FRAGMENT
)
4764 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4769 link_and_validate_uniforms(struct gl_context
*ctx
,
4770 struct gl_shader_program
*prog
)
4772 update_array_sizes(prog
);
4773 link_assign_uniform_locations(prog
, ctx
);
4775 link_assign_atomic_counter_resources(ctx
, prog
);
4776 link_calculate_subroutine_compat(prog
);
4777 check_resources(ctx
, prog
);
4778 check_subroutine_resources(prog
);
4779 check_image_resources(ctx
, prog
);
4780 link_check_atomic_counter_resources(ctx
, prog
);
4784 link_varyings_and_uniforms(unsigned first
, unsigned last
,
4785 struct gl_context
*ctx
,
4786 struct gl_shader_program
*prog
, void *mem_ctx
)
4788 /* Mark all generic shader inputs and outputs as unpaired. */
4789 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4790 if (prog
->_LinkedShaders
[i
] != NULL
) {
4791 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
4795 unsigned prev
= first
;
4796 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4797 if (prog
->_LinkedShaders
[i
] == NULL
)
4800 match_explicit_outputs_to_inputs(prog
->_LinkedShaders
[prev
],
4801 prog
->_LinkedShaders
[i
]);
4805 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4806 MESA_SHADER_VERTEX
, true)) {
4810 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4811 MESA_SHADER_FRAGMENT
, true)) {
4815 prog
->last_vert_prog
= NULL
;
4816 for (int i
= MESA_SHADER_GEOMETRY
; i
>= MESA_SHADER_VERTEX
; i
--) {
4817 if (prog
->_LinkedShaders
[i
] == NULL
)
4820 prog
->last_vert_prog
= prog
->_LinkedShaders
[i
]->Program
;
4824 if (!link_varyings(prog
, first
, last
, ctx
, mem_ctx
))
4827 link_and_validate_uniforms(ctx
, prog
);
4829 if (!prog
->data
->LinkStatus
)
4832 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4833 if (prog
->_LinkedShaders
[i
] == NULL
)
4836 const struct gl_shader_compiler_options
*options
=
4837 &ctx
->Const
.ShaderCompilerOptions
[i
];
4839 if (options
->LowerBufferInterfaceBlocks
)
4840 lower_ubo_reference(prog
->_LinkedShaders
[i
],
4841 options
->ClampBlockIndicesToArrayBounds
,
4842 ctx
->Const
.UseSTD430AsDefaultPacking
);
4844 if (i
== MESA_SHADER_COMPUTE
)
4845 lower_shared_reference(ctx
, prog
, prog
->_LinkedShaders
[i
]);
4847 lower_vector_derefs(prog
->_LinkedShaders
[i
]);
4848 do_vec_index_to_swizzle(prog
->_LinkedShaders
[i
]->ir
);
4855 linker_optimisation_loop(struct gl_context
*ctx
, exec_list
*ir
,
4858 if (ctx
->Const
.GLSLOptimizeConservatively
) {
4859 /* Run it just once. */
4860 do_common_optimization(ir
, true, false,
4861 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4862 ctx
->Const
.NativeIntegers
);
4864 /* Repeat it until it stops making changes. */
4865 while (do_common_optimization(ir
, true, false,
4866 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4867 ctx
->Const
.NativeIntegers
))
4873 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
4875 prog
->data
->LinkStatus
= LINKING_SUCCESS
; /* All error paths will set this to false */
4876 prog
->data
->Validated
= false;
4878 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4880 * "Linking can fail for a variety of reasons as specified in the
4881 * OpenGL Shading Language Specification, as well as any of the
4882 * following reasons:
4884 * - No shader objects are attached to program."
4886 * The Compatibility Profile specification does not list the error. In
4887 * Compatibility Profile missing shader stages are replaced by
4888 * fixed-function. This applies to the case where all stages are
4891 if (prog
->NumShaders
== 0) {
4892 if (ctx
->API
!= API_OPENGL_COMPAT
)
4893 linker_error(prog
, "no shaders attached to the program\n");
4897 #ifdef ENABLE_SHADER_CACHE
4898 if (shader_cache_read_program_metadata(ctx
, prog
))
4902 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
4904 prog
->ARB_fragment_coord_conventions_enable
= false;
4906 /* Separate the shaders into groups based on their type.
4908 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
4909 unsigned num_shaders
[MESA_SHADER_STAGES
];
4911 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4912 shader_list
[i
] = (struct gl_shader
**)
4913 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
4917 unsigned min_version
= UINT_MAX
;
4918 unsigned max_version
= 0;
4919 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
4920 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
4921 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
4923 if (!ctx
->Const
.AllowGLSLRelaxedES
&&
4924 prog
->Shaders
[i
]->IsES
!= prog
->Shaders
[0]->IsES
) {
4925 linker_error(prog
, "all shaders must use same shading "
4926 "language version\n");
4930 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
4931 prog
->ARB_fragment_coord_conventions_enable
= true;
4934 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
4935 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
4936 num_shaders
[shader_type
]++;
4939 /* In desktop GLSL, different shader versions may be linked together. In
4940 * GLSL ES, all shader versions must be the same.
4942 if (!ctx
->Const
.AllowGLSLRelaxedES
&& prog
->Shaders
[0]->IsES
&&
4943 min_version
!= max_version
) {
4944 linker_error(prog
, "all shaders must use same shading "
4945 "language version\n");
4949 prog
->data
->Version
= max_version
;
4950 prog
->IsES
= prog
->Shaders
[0]->IsES
;
4952 /* Some shaders have to be linked with some other shaders present.
4954 if (!prog
->SeparateShader
) {
4955 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
4956 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4957 linker_error(prog
, "Geometry shader must be linked with "
4961 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4962 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4963 linker_error(prog
, "Tessellation evaluation shader must be linked "
4964 "with vertex shader\n");
4967 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4968 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4969 linker_error(prog
, "Tessellation control shader must be linked with "
4974 /* Section 7.3 of the OpenGL ES 3.2 specification says:
4976 * "Linking can fail for [...] any of the following reasons:
4978 * * program contains an object to form a tessellation control
4979 * shader [...] and [...] the program is not separable and
4980 * contains no object to form a tessellation evaluation shader"
4982 * The OpenGL spec is contradictory. It allows linking without a tess
4983 * eval shader, but that can only be used with transform feedback and
4984 * rasterization disabled. However, transform feedback isn't allowed
4985 * with GL_PATCHES, so it can't be used.
4987 * More investigation showed that the idea of transform feedback after
4988 * a tess control shader was dropped, because some hw vendors couldn't
4989 * support tessellation without a tess eval shader, but the linker
4990 * section wasn't updated to reflect that.
4992 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4995 * Do what's reasonable and always require a tess eval shader if a tess
4996 * control shader is present.
4998 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4999 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0) {
5000 linker_error(prog
, "Tessellation control shader must be linked with "
5001 "tessellation evaluation shader\n");
5006 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
5007 num_shaders
[MESA_SHADER_TESS_CTRL
] == 0) {
5008 linker_error(prog
, "GLSL ES requires non-separable programs "
5009 "containing a tessellation evaluation shader to also "
5010 "be linked with a tessellation control shader\n");
5016 /* Compute shaders have additional restrictions. */
5017 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
5018 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
5019 linker_error(prog
, "Compute shaders may not be linked with any other "
5020 "type of shader\n");
5023 /* Link all shaders for a particular stage and validate the result.
5025 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
5026 if (num_shaders
[stage
] > 0) {
5027 gl_linked_shader
*const sh
=
5028 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
5029 num_shaders
[stage
], false);
5031 if (!prog
->data
->LinkStatus
) {
5033 _mesa_delete_linked_shader(ctx
, sh
);
5038 case MESA_SHADER_VERTEX
:
5039 validate_vertex_shader_executable(prog
, sh
, ctx
);
5041 case MESA_SHADER_TESS_CTRL
:
5042 /* nothing to be done */
5044 case MESA_SHADER_TESS_EVAL
:
5045 validate_tess_eval_shader_executable(prog
, sh
, ctx
);
5047 case MESA_SHADER_GEOMETRY
:
5048 validate_geometry_shader_executable(prog
, sh
, ctx
);
5050 case MESA_SHADER_FRAGMENT
:
5051 validate_fragment_shader_executable(prog
, sh
);
5054 if (!prog
->data
->LinkStatus
) {
5056 _mesa_delete_linked_shader(ctx
, sh
);
5060 prog
->_LinkedShaders
[stage
] = sh
;
5061 prog
->data
->linked_stages
|= 1 << stage
;
5065 /* Here begins the inter-stage linking phase. Some initial validation is
5066 * performed, then locations are assigned for uniforms, attributes, and
5069 cross_validate_uniforms(ctx
, prog
);
5070 if (!prog
->data
->LinkStatus
)
5073 unsigned first
, last
, prev
;
5075 first
= MESA_SHADER_STAGES
;
5078 /* Determine first and last stage. */
5079 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5080 if (!prog
->_LinkedShaders
[i
])
5082 if (first
== MESA_SHADER_STAGES
)
5087 check_explicit_uniform_locations(ctx
, prog
);
5088 link_assign_subroutine_types(prog
);
5089 verify_subroutine_associated_funcs(prog
);
5091 if (!prog
->data
->LinkStatus
)
5094 resize_tes_inputs(ctx
, prog
);
5096 /* Validate the inputs of each stage with the output of the preceding
5100 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
5101 if (prog
->_LinkedShaders
[i
] == NULL
)
5104 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
5105 prog
->_LinkedShaders
[i
]);
5106 if (!prog
->data
->LinkStatus
)
5109 cross_validate_outputs_to_inputs(ctx
, prog
,
5110 prog
->_LinkedShaders
[prev
],
5111 prog
->_LinkedShaders
[i
]);
5112 if (!prog
->data
->LinkStatus
)
5118 /* The cross validation of outputs/inputs above validates interstage
5119 * explicit locations. We need to do this also for the inputs in the first
5120 * stage and outputs of the last stage included in the program, since there
5121 * is no cross validation for these.
5123 validate_first_and_last_interface_explicit_locations(ctx
, prog
,
5124 (gl_shader_stage
) first
,
5125 (gl_shader_stage
) last
);
5127 /* Cross-validate uniform blocks between shader stages */
5128 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
);
5129 if (!prog
->data
->LinkStatus
)
5132 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5133 if (prog
->_LinkedShaders
[i
] != NULL
)
5134 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
5137 if (prog
->IsES
&& prog
->data
->Version
== 100)
5138 if (!validate_invariant_builtins(prog
,
5139 prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
5140 prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]))
5143 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
5144 * it before optimization because we want most of the checks to get
5145 * dropped thanks to constant propagation.
5147 * This rule also applies to GLSL ES 3.00.
5149 if (max_version
>= (prog
->IsES
? 300 : 130)) {
5150 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
5152 lower_discard_flow(sh
->ir
);
5156 if (prog
->SeparateShader
)
5157 disable_varying_optimizations_for_sso(prog
);
5160 if (!interstage_cross_validate_uniform_blocks(prog
, false))
5164 if (!interstage_cross_validate_uniform_blocks(prog
, true))
5167 /* Do common optimization before assigning storage for attributes,
5168 * uniforms, and varyings. Later optimization could possibly make
5169 * some of that unused.
5171 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5172 if (prog
->_LinkedShaders
[i
] == NULL
)
5175 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
5176 if (!prog
->data
->LinkStatus
)
5179 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerCombinedClipCullDistance
) {
5180 lower_clip_cull_distance(prog
, prog
->_LinkedShaders
[i
]);
5183 if (ctx
->Const
.LowerTessLevel
) {
5184 lower_tess_level(prog
->_LinkedShaders
[i
]);
5187 /* Section 13.46 (Vertex Attribute Aliasing) of the OpenGL ES 3.2
5188 * specification says:
5190 * "In general, the behavior of GLSL ES should not depend on compiler
5191 * optimizations which might be implementation-dependent. Name matching
5192 * rules in most languages, including C++ from which GLSL ES is derived,
5193 * are based on declarations rather than use.
5195 * RESOLUTION: The existence of aliasing is determined by declarations
5196 * present after preprocessing."
5198 * Because of this rule, we do a 'dry-run' of attribute assignment for
5199 * vertex shader inputs here.
5201 if (prog
->IsES
&& i
== MESA_SHADER_VERTEX
) {
5202 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
5203 MESA_SHADER_VERTEX
, false)) {
5208 /* Call opts before lowering const arrays to uniforms so we can const
5209 * propagate any elements accessed directly.
5211 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
5213 /* Call opts after lowering const arrays to copy propagate things. */
5214 if (lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
, i
))
5215 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
5217 propagate_invariance(prog
->_LinkedShaders
[i
]->ir
);
5220 /* Validation for special cases where we allow sampler array indexing
5221 * with loop induction variable. This check emits a warning or error
5222 * depending if backend can handle dynamic indexing.
5224 if ((!prog
->IsES
&& prog
->data
->Version
< 130) ||
5225 (prog
->IsES
&& prog
->data
->Version
< 300)) {
5226 if (!validate_sampler_array_indexing(ctx
, prog
))
5230 /* Check and validate stream emissions in geometry shaders */
5231 validate_geometry_shader_emissions(ctx
, prog
);
5233 store_fragdepth_layout(prog
);
5235 if(!link_varyings_and_uniforms(first
, last
, ctx
, prog
, mem_ctx
))
5238 /* Linking varyings can cause some extra, useless swizzles to be generated
5239 * due to packing and unpacking.
5241 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5242 if (prog
->_LinkedShaders
[i
] == NULL
)
5245 optimize_swizzles(prog
->_LinkedShaders
[i
]->ir
);
5248 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
5249 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
5250 * anything about shader linking when one of the shaders (vertex or
5251 * fragment shader) is absent. So, the extension shouldn't change the
5252 * behavior specified in GLSL specification.
5254 * From OpenGL ES 3.1 specification (7.3 Program Objects):
5255 * "Linking can fail for a variety of reasons as specified in the
5256 * OpenGL ES Shading Language Specification, as well as any of the
5257 * following reasons:
5261 * * program contains objects to form either a vertex shader or
5262 * fragment shader, and program is not separable, and does not
5263 * contain objects to form both a vertex shader and fragment
5266 * However, the only scenario in 3.1+ where we don't require them both is
5267 * when we have a compute shader. For example:
5269 * - No shaders is a link error.
5270 * - Geom or Tess without a Vertex shader is a link error which means we
5271 * always require a Vertex shader and hence a Fragment shader.
5272 * - Finally a Compute shader linked with any other stage is a link error.
5274 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
&&
5275 num_shaders
[MESA_SHADER_COMPUTE
] == 0) {
5276 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
5277 linker_error(prog
, "program lacks a vertex shader\n");
5278 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
5279 linker_error(prog
, "program lacks a fragment shader\n");
5284 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5285 free(shader_list
[i
]);
5286 if (prog
->_LinkedShaders
[i
] == NULL
)
5289 /* Do a final validation step to make sure that the IR wasn't
5290 * invalidated by any modifications performed after intrastage linking.
5292 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
5294 /* Retain any live IR, but trash the rest. */
5295 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
5297 /* The symbol table in the linked shaders may contain references to
5298 * variables that were removed (e.g., unused uniforms). Since it may
5299 * contain junk, there is no possible valid use. Delete it and set the
5302 delete prog
->_LinkedShaders
[i
]->symbols
;
5303 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
5306 ralloc_free(mem_ctx
);