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 using deref_type_updater::visit
;
265 unsigned num_vertices
;
266 gl_shader_program
*prog
;
267 gl_shader_stage stage
;
269 array_resize_visitor(unsigned num_vertices
,
270 gl_shader_program
*prog
,
271 gl_shader_stage stage
)
273 this->num_vertices
= num_vertices
;
278 virtual ~array_resize_visitor()
283 virtual ir_visitor_status
visit(ir_variable
*var
)
285 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
||
287 return visit_continue
;
289 unsigned size
= var
->type
->length
;
291 if (stage
== MESA_SHADER_GEOMETRY
) {
292 /* Generate a link error if the shader has declared this array with
295 if (!var
->data
.implicit_sized_array
&&
296 size
&& size
!= this->num_vertices
) {
297 linker_error(this->prog
, "size of array %s declared as %u, "
298 "but number of input vertices is %u\n",
299 var
->name
, size
, this->num_vertices
);
300 return visit_continue
;
303 /* Generate a link error if the shader attempts to access an input
304 * array using an index too large for its actual size assigned at
307 if (var
->data
.max_array_access
>= (int)this->num_vertices
) {
308 linker_error(this->prog
, "%s shader accesses element %i of "
309 "%s, but only %i input vertices\n",
310 _mesa_shader_stage_to_string(this->stage
),
311 var
->data
.max_array_access
, var
->name
, this->num_vertices
);
312 return visit_continue
;
316 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
318 var
->data
.max_array_access
= this->num_vertices
- 1;
320 return visit_continue
;
325 * Visitor that determines the highest stream id to which a (geometry) shader
326 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
328 class find_emit_vertex_visitor
: public ir_hierarchical_visitor
{
330 find_emit_vertex_visitor(int max_allowed
)
331 : max_stream_allowed(max_allowed
),
332 invalid_stream_id(0),
333 invalid_stream_id_from_emit_vertex(false),
334 end_primitive_found(false),
335 uses_non_zero_stream(false)
340 virtual ir_visitor_status
visit_leave(ir_emit_vertex
*ir
)
342 int stream_id
= ir
->stream_id();
345 invalid_stream_id
= stream_id
;
346 invalid_stream_id_from_emit_vertex
= true;
350 if (stream_id
> max_stream_allowed
) {
351 invalid_stream_id
= stream_id
;
352 invalid_stream_id_from_emit_vertex
= true;
357 uses_non_zero_stream
= true;
359 return visit_continue
;
362 virtual ir_visitor_status
visit_leave(ir_end_primitive
*ir
)
364 end_primitive_found
= true;
366 int stream_id
= ir
->stream_id();
369 invalid_stream_id
= stream_id
;
370 invalid_stream_id_from_emit_vertex
= false;
374 if (stream_id
> max_stream_allowed
) {
375 invalid_stream_id
= stream_id
;
376 invalid_stream_id_from_emit_vertex
= false;
381 uses_non_zero_stream
= true;
383 return visit_continue
;
388 return invalid_stream_id
!= 0;
391 const char *error_func()
393 return invalid_stream_id_from_emit_vertex
?
394 "EmitStreamVertex" : "EndStreamPrimitive";
399 return invalid_stream_id
;
404 return uses_non_zero_stream
;
407 bool uses_end_primitive()
409 return end_primitive_found
;
413 int max_stream_allowed
;
414 int invalid_stream_id
;
415 bool invalid_stream_id_from_emit_vertex
;
416 bool end_primitive_found
;
417 bool uses_non_zero_stream
;
420 /* Class that finds array derefs and check if indexes are dynamic. */
421 class dynamic_sampler_array_indexing_visitor
: public ir_hierarchical_visitor
424 dynamic_sampler_array_indexing_visitor() :
425 dynamic_sampler_array_indexing(false)
429 ir_visitor_status
visit_enter(ir_dereference_array
*ir
)
431 if (!ir
->variable_referenced())
432 return visit_continue
;
434 if (!ir
->variable_referenced()->type
->contains_sampler())
435 return visit_continue
;
437 if (!ir
->array_index
->constant_expression_value(ralloc_parent(ir
))) {
438 dynamic_sampler_array_indexing
= true;
441 return visit_continue
;
444 bool uses_dynamic_sampler_array_indexing()
446 return dynamic_sampler_array_indexing
;
450 bool dynamic_sampler_array_indexing
;
453 } /* anonymous namespace */
456 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
460 ralloc_strcat(&prog
->data
->InfoLog
, "error: ");
462 ralloc_vasprintf_append(&prog
->data
->InfoLog
, fmt
, ap
);
465 prog
->data
->LinkStatus
= LINKING_FAILURE
;
470 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
474 ralloc_strcat(&prog
->data
->InfoLog
, "warning: ");
476 ralloc_vasprintf_append(&prog
->data
->InfoLog
, fmt
, ap
);
483 * Given a string identifying a program resource, break it into a base name
484 * and an optional array index in square brackets.
486 * If an array index is present, \c out_base_name_end is set to point to the
487 * "[" that precedes the array index, and the array index itself is returned
490 * If no array index is present (or if the array index is negative or
491 * mal-formed), \c out_base_name_end, is set to point to the null terminator
492 * at the end of the input string, and -1 is returned.
494 * Only the final array index is parsed; if the string contains other array
495 * indices (or structure field accesses), they are left in the base name.
497 * No attempt is made to check that the base name is properly formed;
498 * typically the caller will look up the base name in a hash table, so
499 * ill-formed base names simply turn into hash table lookup failures.
502 parse_program_resource_name(const GLchar
*name
,
503 const GLchar
**out_base_name_end
)
505 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
507 * "When an integer array element or block instance number is part of
508 * the name string, it will be specified in decimal form without a "+"
509 * or "-" sign or any extra leading zeroes. Additionally, the name
510 * string will not include white space anywhere in the string."
513 const size_t len
= strlen(name
);
514 *out_base_name_end
= name
+ len
;
516 if (len
== 0 || name
[len
-1] != ']')
519 /* Walk backwards over the string looking for a non-digit character. This
520 * had better be the opening bracket for an array index.
522 * Initially, i specifies the location of the ']'. Since the string may
523 * contain only the ']' charcater, walk backwards very carefully.
526 for (i
= len
- 1; (i
> 0) && isdigit(name
[i
-1]); --i
)
529 if ((i
== 0) || name
[i
-1] != '[')
532 long array_index
= strtol(&name
[i
], NULL
, 10);
536 /* Check for leading zero */
537 if (name
[i
] == '0' && name
[i
+1] != ']')
540 *out_base_name_end
= name
+ (i
- 1);
546 link_invalidate_variable_locations(exec_list
*ir
)
548 foreach_in_list(ir_instruction
, node
, ir
) {
549 ir_variable
*const var
= node
->as_variable();
554 /* Only assign locations for variables that lack an explicit location.
555 * Explicit locations are set for all built-in variables, generic vertex
556 * shader inputs (via layout(location=...)), and generic fragment shader
557 * outputs (also via layout(location=...)).
559 if (!var
->data
.explicit_location
) {
560 var
->data
.location
= -1;
561 var
->data
.location_frac
= 0;
564 /* ir_variable::is_unmatched_generic_inout is used by the linker while
565 * connecting outputs from one stage to inputs of the next stage.
567 if (var
->data
.explicit_location
&&
568 var
->data
.location
< VARYING_SLOT_VAR0
) {
569 var
->data
.is_unmatched_generic_inout
= 0;
571 var
->data
.is_unmatched_generic_inout
= 1;
578 * Set clip_distance_array_size based and cull_distance_array_size on the given
581 * Also check for errors based on incorrect usage of gl_ClipVertex and
582 * gl_ClipDistance and gl_CullDistance.
583 * Additionally test whether the arrays gl_ClipDistance and gl_CullDistance
584 * exceed the maximum size defined by gl_MaxCombinedClipAndCullDistances.
586 * Return false if an error was reported.
589 analyze_clip_cull_usage(struct gl_shader_program
*prog
,
590 struct gl_linked_shader
*shader
,
591 struct gl_context
*ctx
,
592 struct shader_info
*info
)
594 info
->clip_distance_array_size
= 0;
595 info
->cull_distance_array_size
= 0;
597 if (prog
->data
->Version
>= (prog
->IsES
? 300 : 130)) {
598 /* From section 7.1 (Vertex Shader Special Variables) of the
601 * "It is an error for a shader to statically write both
602 * gl_ClipVertex and gl_ClipDistance."
604 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
605 * gl_ClipVertex nor gl_ClipDistance. However with
606 * GL_EXT_clip_cull_distance, this functionality is exposed in ES 3.0.
608 find_variable
gl_ClipDistance("gl_ClipDistance");
609 find_variable
gl_CullDistance("gl_CullDistance");
610 find_variable
gl_ClipVertex("gl_ClipVertex");
611 find_variable
* const variables
[] = {
614 !prog
->IsES
? &gl_ClipVertex
: NULL
,
617 find_assignments(shader
->ir
, variables
);
619 /* From the ARB_cull_distance spec:
621 * It is a compile-time or link-time error for the set of shaders forming
622 * a program to statically read or write both gl_ClipVertex and either
623 * gl_ClipDistance or gl_CullDistance.
625 * This does not apply to GLSL ES shaders, since GLSL ES doesn't define
629 if (gl_ClipVertex
.found
&& gl_ClipDistance
.found
) {
630 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
631 "and `gl_ClipDistance'\n",
632 _mesa_shader_stage_to_string(shader
->Stage
));
635 if (gl_ClipVertex
.found
&& gl_CullDistance
.found
) {
636 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
637 "and `gl_CullDistance'\n",
638 _mesa_shader_stage_to_string(shader
->Stage
));
643 if (gl_ClipDistance
.found
) {
644 ir_variable
*clip_distance_var
=
645 shader
->symbols
->get_variable("gl_ClipDistance");
646 assert(clip_distance_var
);
647 info
->clip_distance_array_size
= clip_distance_var
->type
->length
;
649 if (gl_CullDistance
.found
) {
650 ir_variable
*cull_distance_var
=
651 shader
->symbols
->get_variable("gl_CullDistance");
652 assert(cull_distance_var
);
653 info
->cull_distance_array_size
= cull_distance_var
->type
->length
;
655 /* From the ARB_cull_distance spec:
657 * It is a compile-time or link-time error for the set of shaders forming
658 * a program to have the sum of the sizes of the gl_ClipDistance and
659 * gl_CullDistance arrays to be larger than
660 * gl_MaxCombinedClipAndCullDistances.
662 if ((uint32_t)(info
->clip_distance_array_size
+ info
->cull_distance_array_size
) >
663 ctx
->Const
.MaxClipPlanes
) {
664 linker_error(prog
, "%s shader: the combined size of "
665 "'gl_ClipDistance' and 'gl_CullDistance' size cannot "
667 "gl_MaxCombinedClipAndCullDistances (%u)",
668 _mesa_shader_stage_to_string(shader
->Stage
),
669 ctx
->Const
.MaxClipPlanes
);
676 * Verify that a vertex shader executable meets all semantic requirements.
678 * Also sets info.clip_distance_array_size and
679 * info.cull_distance_array_size as a side effect.
681 * \param shader Vertex shader executable to be verified
684 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
685 struct gl_linked_shader
*shader
,
686 struct gl_context
*ctx
)
691 /* From the GLSL 1.10 spec, page 48:
693 * "The variable gl_Position is available only in the vertex
694 * language and is intended for writing the homogeneous vertex
695 * position. All executions of a well-formed vertex shader
696 * executable must write a value into this variable. [...] The
697 * variable gl_Position is available only in the vertex
698 * language and is intended for writing the homogeneous vertex
699 * position. All executions of a well-formed vertex shader
700 * executable must write a value into this variable."
702 * while in GLSL 1.40 this text is changed to:
704 * "The variable gl_Position is available only in the vertex
705 * language and is intended for writing the homogeneous vertex
706 * position. It can be written at any time during shader
707 * execution. It may also be read back by a vertex shader
708 * after being written. This value will be used by primitive
709 * assembly, clipping, culling, and other fixed functionality
710 * operations, if present, that operate on primitives after
711 * vertex processing has occurred. Its value is undefined if
712 * the vertex shader executable does not write gl_Position."
714 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
715 * gl_Position is not an error.
717 if (prog
->data
->Version
< (prog
->IsES
? 300 : 140)) {
718 find_variable
gl_Position("gl_Position");
719 find_assignments(shader
->ir
, &gl_Position
);
720 if (!gl_Position
.found
) {
723 "vertex shader does not write to `gl_Position'. "
724 "Its value is undefined. \n");
727 "vertex shader does not write to `gl_Position'. \n");
733 analyze_clip_cull_usage(prog
, shader
, ctx
, &shader
->Program
->info
);
737 validate_tess_eval_shader_executable(struct gl_shader_program
*prog
,
738 struct gl_linked_shader
*shader
,
739 struct gl_context
*ctx
)
744 analyze_clip_cull_usage(prog
, shader
, ctx
, &shader
->Program
->info
);
749 * Verify that a fragment shader executable meets all semantic requirements
751 * \param shader Fragment shader executable to be verified
754 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
755 struct gl_linked_shader
*shader
)
760 find_variable
gl_FragColor("gl_FragColor");
761 find_variable
gl_FragData("gl_FragData");
762 find_variable
* const variables
[] = { &gl_FragColor
, &gl_FragData
, NULL
};
763 find_assignments(shader
->ir
, variables
);
765 if (gl_FragColor
.found
&& gl_FragData
.found
) {
766 linker_error(prog
, "fragment shader writes to both "
767 "`gl_FragColor' and `gl_FragData'\n");
772 * Verify that a geometry shader executable meets all semantic requirements
774 * Also sets prog->Geom.VerticesIn, and info.clip_distance_array_sizeand
775 * info.cull_distance_array_size as a side effect.
777 * \param shader Geometry shader executable to be verified
780 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
781 struct gl_linked_shader
*shader
,
782 struct gl_context
*ctx
)
787 unsigned num_vertices
=
788 vertices_per_prim(shader
->Program
->info
.gs
.input_primitive
);
789 prog
->Geom
.VerticesIn
= num_vertices
;
791 analyze_clip_cull_usage(prog
, shader
, ctx
, &shader
->Program
->info
);
795 * Check if geometry shaders emit to non-zero streams and do corresponding
799 validate_geometry_shader_emissions(struct gl_context
*ctx
,
800 struct gl_shader_program
*prog
)
802 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
];
805 find_emit_vertex_visitor
emit_vertex(ctx
->Const
.MaxVertexStreams
- 1);
806 emit_vertex
.run(sh
->ir
);
807 if (emit_vertex
.error()) {
808 linker_error(prog
, "Invalid call %s(%d). Accepted values for the "
809 "stream parameter are in the range [0, %d].\n",
810 emit_vertex
.error_func(),
811 emit_vertex
.error_stream(),
812 ctx
->Const
.MaxVertexStreams
- 1);
814 prog
->Geom
.UsesStreams
= emit_vertex
.uses_streams();
815 prog
->Geom
.UsesEndPrimitive
= emit_vertex
.uses_end_primitive();
817 /* From the ARB_gpu_shader5 spec:
819 * "Multiple vertex streams are supported only if the output primitive
820 * type is declared to be "points". A program will fail to link if it
821 * contains a geometry shader calling EmitStreamVertex() or
822 * EndStreamPrimitive() if its output primitive type is not "points".
824 * However, in the same spec:
826 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
827 * with <stream> set to zero."
831 * "The function EndPrimitive() is equivalent to calling
832 * EndStreamPrimitive() with <stream> set to zero."
834 * Since we can call EmitVertex() and EndPrimitive() when we output
835 * primitives other than points, calling EmitStreamVertex(0) or
836 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
837 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
838 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
841 if (prog
->Geom
.UsesStreams
&&
842 sh
->Program
->info
.gs
.output_primitive
!= GL_POINTS
) {
843 linker_error(prog
, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
844 "with n>0 requires point output\n");
850 validate_intrastage_arrays(struct gl_shader_program
*prog
,
851 ir_variable
*const var
,
852 ir_variable
*const existing
,
853 bool match_precision
)
855 /* Consider the types to be "the same" if both types are arrays
856 * of the same type and one of the arrays is implicitly sized.
857 * In addition, set the type of the linked variable to the
858 * explicitly sized array.
860 if (var
->type
->is_array() && existing
->type
->is_array()) {
861 const glsl_type
*no_array_var
= var
->type
->fields
.array
;
862 const glsl_type
*no_array_existing
= existing
->type
->fields
.array
;
865 type_matches
= (match_precision
?
866 no_array_var
== no_array_existing
:
867 no_array_var
->compare_no_precision(no_array_existing
));
870 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
871 if (var
->type
->length
!= 0) {
872 if ((int)var
->type
->length
<= existing
->data
.max_array_access
) {
873 linker_error(prog
, "%s `%s' declared as type "
874 "`%s' but outermost dimension has an index"
877 var
->name
, var
->type
->name
,
878 existing
->data
.max_array_access
);
880 existing
->type
= var
->type
;
882 } else if (existing
->type
->length
!= 0) {
883 if((int)existing
->type
->length
<= var
->data
.max_array_access
&&
884 !existing
->data
.from_ssbo_unsized_array
) {
885 linker_error(prog
, "%s `%s' declared as type "
886 "`%s' but outermost dimension has an index"
889 var
->name
, existing
->type
->name
,
890 var
->data
.max_array_access
);
901 * Perform validation of global variables used across multiple shaders
904 cross_validate_globals(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
905 struct exec_list
*ir
, glsl_symbol_table
*variables
,
908 foreach_in_list(ir_instruction
, node
, ir
) {
909 ir_variable
*const var
= node
->as_variable();
914 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
917 /* don't cross validate subroutine uniforms */
918 if (var
->type
->contains_subroutine())
921 /* Don't cross validate interface instances. These are only relevant
922 * inside a shader. The cross validation is done at the Interface Block
925 if (var
->is_interface_instance())
928 /* Don't cross validate temporaries that are at global scope. These
929 * will eventually get pulled into the shaders 'main'.
931 if (var
->data
.mode
== ir_var_temporary
)
934 /* If a global with this name has already been seen, verify that the
935 * new instance has the same type. In addition, if the globals have
936 * initializers, the values of the initializers must be the same.
938 ir_variable
*const existing
= variables
->get_variable(var
->name
);
939 if (existing
!= NULL
) {
940 /* Check if types match. */
941 if (var
->type
!= existing
->type
) {
942 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
943 /* If it is an unsized array in a Shader Storage Block,
944 * two different shaders can access to different elements.
945 * Because of that, they might be converted to different
946 * sized arrays, then check that they are compatible but
947 * ignore the array size.
949 if (!(var
->data
.mode
== ir_var_shader_storage
&&
950 var
->data
.from_ssbo_unsized_array
&&
951 existing
->data
.mode
== ir_var_shader_storage
&&
952 existing
->data
.from_ssbo_unsized_array
&&
953 var
->type
->gl_type
== existing
->type
->gl_type
)) {
954 linker_error(prog
, "%s `%s' declared as type "
955 "`%s' and type `%s'\n",
957 var
->name
, var
->type
->name
,
958 existing
->type
->name
);
964 if (var
->data
.explicit_location
) {
965 if (existing
->data
.explicit_location
966 && (var
->data
.location
!= existing
->data
.location
)) {
967 linker_error(prog
, "explicit locations for %s "
968 "`%s' have differing values\n",
969 mode_string(var
), var
->name
);
973 if (var
->data
.location_frac
!= existing
->data
.location_frac
) {
974 linker_error(prog
, "explicit components for %s `%s' have "
975 "differing values\n", mode_string(var
), var
->name
);
979 existing
->data
.location
= var
->data
.location
;
980 existing
->data
.explicit_location
= true;
982 /* Check if uniform with implicit location was marked explicit
983 * by earlier shader stage. If so, mark it explicit in this stage
984 * too to make sure later processing does not treat it as
987 if (existing
->data
.explicit_location
) {
988 var
->data
.location
= existing
->data
.location
;
989 var
->data
.explicit_location
= true;
993 /* From the GLSL 4.20 specification:
994 * "A link error will result if two compilation units in a program
995 * specify different integer-constant bindings for the same
996 * opaque-uniform name. However, it is not an error to specify a
997 * binding on some but not all declarations for the same name"
999 if (var
->data
.explicit_binding
) {
1000 if (existing
->data
.explicit_binding
&&
1001 var
->data
.binding
!= existing
->data
.binding
) {
1002 linker_error(prog
, "explicit bindings for %s "
1003 "`%s' have differing values\n",
1004 mode_string(var
), var
->name
);
1008 existing
->data
.binding
= var
->data
.binding
;
1009 existing
->data
.explicit_binding
= true;
1012 if (var
->type
->contains_atomic() &&
1013 var
->data
.offset
!= existing
->data
.offset
) {
1014 linker_error(prog
, "offset specifications for %s "
1015 "`%s' have differing values\n",
1016 mode_string(var
), var
->name
);
1020 /* Validate layout qualifiers for gl_FragDepth.
1022 * From the AMD/ARB_conservative_depth specs:
1024 * "If gl_FragDepth is redeclared in any fragment shader in a
1025 * program, it must be redeclared in all fragment shaders in
1026 * that program that have static assignments to
1027 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1028 * fragment shaders in a single program must have the same set
1031 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1032 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1033 bool layout_differs
=
1034 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1036 if (layout_declared
&& layout_differs
) {
1038 "All redeclarations of gl_FragDepth in all "
1039 "fragment shaders in a single program must have "
1040 "the same set of qualifiers.\n");
1043 if (var
->data
.used
&& layout_differs
) {
1045 "If gl_FragDepth is redeclared with a layout "
1046 "qualifier in any fragment shader, it must be "
1047 "redeclared with the same layout qualifier in "
1048 "all fragment shaders that have assignments to "
1053 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1055 * "If a shared global has multiple initializers, the
1056 * initializers must all be constant expressions, and they
1057 * must all have the same value. Otherwise, a link error will
1058 * result. (A shared global having only one initializer does
1059 * not require that initializer to be a constant expression.)"
1061 * Previous to 4.20 the GLSL spec simply said that initializers
1062 * must have the same value. In this case of non-constant
1063 * initializers, this was impossible to determine. As a result,
1064 * no vendor actually implemented that behavior. The 4.20
1065 * behavior matches the implemented behavior of at least one other
1066 * vendor, so we'll implement that for all GLSL versions.
1068 if (var
->constant_initializer
!= NULL
) {
1069 if (existing
->constant_initializer
!= NULL
) {
1070 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1071 linker_error(prog
, "initializers for %s "
1072 "`%s' have differing values\n",
1073 mode_string(var
), var
->name
);
1077 /* If the first-seen instance of a particular uniform did
1078 * not have an initializer but a later instance does,
1079 * replace the former with the later.
1081 variables
->replace_variable(existing
->name
, var
);
1085 if (var
->data
.has_initializer
) {
1086 if (existing
->data
.has_initializer
1087 && (var
->constant_initializer
== NULL
1088 || existing
->constant_initializer
== NULL
)) {
1090 "shared global variable `%s' has multiple "
1091 "non-constant initializers.\n",
1097 if (existing
->data
.explicit_invariant
!= var
->data
.explicit_invariant
) {
1098 linker_error(prog
, "declarations for %s `%s' have "
1099 "mismatching invariant qualifiers\n",
1100 mode_string(var
), var
->name
);
1103 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1104 linker_error(prog
, "declarations for %s `%s' have "
1105 "mismatching centroid qualifiers\n",
1106 mode_string(var
), var
->name
);
1109 if (existing
->data
.sample
!= var
->data
.sample
) {
1110 linker_error(prog
, "declarations for %s `%s` have "
1111 "mismatching sample qualifiers\n",
1112 mode_string(var
), var
->name
);
1115 if (existing
->data
.image_format
!= var
->data
.image_format
) {
1116 linker_error(prog
, "declarations for %s `%s` have "
1117 "mismatching image format qualifiers\n",
1118 mode_string(var
), var
->name
);
1122 /* Check the precision qualifier matches for uniform variables on
1125 if (!ctx
->Const
.AllowGLSLRelaxedES
&&
1126 prog
->IsES
&& !var
->get_interface_type() &&
1127 existing
->data
.precision
!= var
->data
.precision
) {
1128 if ((existing
->data
.used
&& var
->data
.used
) || prog
->data
->Version
>= 300) {
1129 linker_error(prog
, "declarations for %s `%s` have "
1130 "mismatching precision qualifiers\n",
1131 mode_string(var
), var
->name
);
1134 linker_warning(prog
, "declarations for %s `%s` have "
1135 "mismatching precision qualifiers\n",
1136 mode_string(var
), var
->name
);
1140 /* In OpenGL GLSL 3.20 spec, section 4.3.9:
1142 * "It is a link-time error if any particular shader interface
1145 * - two different blocks, each having no instance name, and each
1146 * having a member of the same name, or
1148 * - a variable outside a block, and a block with no instance name,
1149 * where the variable has the same name as a member in the block."
1151 const glsl_type
*var_itype
= var
->get_interface_type();
1152 const glsl_type
*existing_itype
= existing
->get_interface_type();
1153 if (var_itype
!= existing_itype
) {
1154 if (!var_itype
|| !existing_itype
) {
1155 linker_error(prog
, "declarations for %s `%s` are inside block "
1156 "`%s` and outside a block",
1157 mode_string(var
), var
->name
,
1158 var_itype
? var_itype
->name
: existing_itype
->name
);
1160 } else if (strcmp(var_itype
->name
, existing_itype
->name
) != 0) {
1161 linker_error(prog
, "declarations for %s `%s` are inside blocks "
1163 mode_string(var
), var
->name
,
1164 existing_itype
->name
,
1170 variables
->add_variable(var
);
1176 * Perform validation of uniforms used across multiple shader stages
1179 cross_validate_uniforms(struct gl_context
*ctx
,
1180 struct gl_shader_program
*prog
)
1182 glsl_symbol_table variables
;
1183 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1184 if (prog
->_LinkedShaders
[i
] == NULL
)
1187 cross_validate_globals(ctx
, prog
, prog
->_LinkedShaders
[i
]->ir
,
1193 * Accumulates the array of buffer blocks and checks that all definitions of
1194 * blocks agree on their contents.
1197 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
,
1200 int *InterfaceBlockStageIndex
[MESA_SHADER_STAGES
];
1201 struct gl_uniform_block
*blks
= NULL
;
1202 unsigned *num_blks
= validate_ssbo
? &prog
->data
->NumShaderStorageBlocks
:
1203 &prog
->data
->NumUniformBlocks
;
1205 unsigned max_num_buffer_blocks
= 0;
1206 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1207 if (prog
->_LinkedShaders
[i
]) {
1208 if (validate_ssbo
) {
1209 max_num_buffer_blocks
+=
1210 prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1212 max_num_buffer_blocks
+=
1213 prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1218 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1219 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1221 InterfaceBlockStageIndex
[i
] = new int[max_num_buffer_blocks
];
1222 for (unsigned int j
= 0; j
< max_num_buffer_blocks
; j
++)
1223 InterfaceBlockStageIndex
[i
][j
] = -1;
1228 unsigned sh_num_blocks
;
1229 struct gl_uniform_block
**sh_blks
;
1230 if (validate_ssbo
) {
1231 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1232 sh_blks
= sh
->Program
->sh
.ShaderStorageBlocks
;
1234 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1235 sh_blks
= sh
->Program
->sh
.UniformBlocks
;
1238 for (unsigned int j
= 0; j
< sh_num_blocks
; j
++) {
1239 int index
= link_cross_validate_uniform_block(prog
->data
, &blks
,
1240 num_blks
, sh_blks
[j
]);
1243 linker_error(prog
, "buffer block `%s' has mismatching "
1244 "definitions\n", sh_blks
[j
]->Name
);
1246 for (unsigned k
= 0; k
<= i
; k
++) {
1247 delete[] InterfaceBlockStageIndex
[k
];
1250 /* Reset the block count. This will help avoid various segfaults
1251 * from api calls that assume the array exists due to the count
1258 InterfaceBlockStageIndex
[i
][index
] = j
;
1262 /* Update per stage block pointers to point to the program list.
1263 * FIXME: We should be able to free the per stage blocks here.
1265 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1266 for (unsigned j
= 0; j
< *num_blks
; j
++) {
1267 int stage_index
= InterfaceBlockStageIndex
[i
][j
];
1269 if (stage_index
!= -1) {
1270 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1272 struct gl_uniform_block
**sh_blks
= validate_ssbo
?
1273 sh
->Program
->sh
.ShaderStorageBlocks
:
1274 sh
->Program
->sh
.UniformBlocks
;
1276 blks
[j
].stageref
|= sh_blks
[stage_index
]->stageref
;
1277 sh_blks
[stage_index
] = &blks
[j
];
1282 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1283 delete[] InterfaceBlockStageIndex
[i
];
1287 prog
->data
->ShaderStorageBlocks
= blks
;
1289 prog
->data
->UniformBlocks
= blks
;
1295 * Verifies the invariance of built-in special variables.
1298 validate_invariant_builtins(struct gl_shader_program
*prog
,
1299 const gl_linked_shader
*vert
,
1300 const gl_linked_shader
*frag
)
1302 const ir_variable
*var_vert
;
1303 const ir_variable
*var_frag
;
1309 * From OpenGL ES Shading Language 1.0 specification
1310 * (4.6.4 Invariance and Linkage):
1311 * "The invariance of varyings that are declared in both the vertex and
1312 * fragment shaders must match. For the built-in special variables,
1313 * gl_FragCoord can only be declared invariant if and only if
1314 * gl_Position is declared invariant. Similarly gl_PointCoord can only
1315 * be declared invariant if and only if gl_PointSize is declared
1316 * invariant. It is an error to declare gl_FrontFacing as invariant.
1317 * The invariance of gl_FrontFacing is the same as the invariance of
1320 var_frag
= frag
->symbols
->get_variable("gl_FragCoord");
1321 if (var_frag
&& var_frag
->data
.invariant
) {
1322 var_vert
= vert
->symbols
->get_variable("gl_Position");
1323 if (var_vert
&& !var_vert
->data
.invariant
) {
1325 "fragment shader built-in `%s' has invariant qualifier, "
1326 "but vertex shader built-in `%s' lacks invariant qualifier\n",
1327 var_frag
->name
, var_vert
->name
);
1332 var_frag
= frag
->symbols
->get_variable("gl_PointCoord");
1333 if (var_frag
&& var_frag
->data
.invariant
) {
1334 var_vert
= vert
->symbols
->get_variable("gl_PointSize");
1335 if (var_vert
&& !var_vert
->data
.invariant
) {
1337 "fragment shader built-in `%s' has invariant qualifier, "
1338 "but vertex shader built-in `%s' lacks invariant qualifier\n",
1339 var_frag
->name
, var_vert
->name
);
1344 var_frag
= frag
->symbols
->get_variable("gl_FrontFacing");
1345 if (var_frag
&& var_frag
->data
.invariant
) {
1347 "fragment shader built-in `%s' can not be declared as invariant\n",
1356 * Populates a shaders symbol table with all global declarations
1359 populate_symbol_table(gl_linked_shader
*sh
, glsl_symbol_table
*symbols
)
1361 sh
->symbols
= new(sh
) glsl_symbol_table
;
1363 _mesa_glsl_copy_symbols_from_table(sh
->ir
, symbols
, sh
->symbols
);
1368 * Remap variables referenced in an instruction tree
1370 * This is used when instruction trees are cloned from one shader and placed in
1371 * another. These trees will contain references to \c ir_variable nodes that
1372 * do not exist in the target shader. This function finds these \c ir_variable
1373 * references and replaces the references with matching variables in the target
1376 * If there is no matching variable in the target shader, a clone of the
1377 * \c ir_variable is made and added to the target shader. The new variable is
1378 * added to \b both the instruction stream and the symbol table.
1380 * \param inst IR tree that is to be processed.
1381 * \param symbols Symbol table containing global scope symbols in the
1383 * \param instructions Instruction stream where new variable declarations
1387 remap_variables(ir_instruction
*inst
, struct gl_linked_shader
*target
,
1390 class remap_visitor
: public ir_hierarchical_visitor
{
1392 remap_visitor(struct gl_linked_shader
*target
, hash_table
*temps
)
1394 this->target
= target
;
1395 this->symbols
= target
->symbols
;
1396 this->instructions
= target
->ir
;
1397 this->temps
= temps
;
1400 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1402 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1403 hash_entry
*entry
= _mesa_hash_table_search(temps
, ir
->var
);
1404 ir_variable
*var
= entry
? (ir_variable
*) entry
->data
: NULL
;
1406 assert(var
!= NULL
);
1408 return visit_continue
;
1411 ir_variable
*const existing
=
1412 this->symbols
->get_variable(ir
->var
->name
);
1413 if (existing
!= NULL
)
1416 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1418 this->symbols
->add_variable(copy
);
1419 this->instructions
->push_head(copy
);
1423 return visit_continue
;
1427 struct gl_linked_shader
*target
;
1428 glsl_symbol_table
*symbols
;
1429 exec_list
*instructions
;
1433 remap_visitor
v(target
, temps
);
1440 * Move non-declarations from one instruction stream to another
1442 * The intended usage pattern of this function is to pass the pointer to the
1443 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1444 * pointer) for \c last and \c false for \c make_copies on the first
1445 * call. Successive calls pass the return value of the previous call for
1446 * \c last and \c true for \c make_copies.
1448 * \param instructions Source instruction stream
1449 * \param last Instruction after which new instructions should be
1450 * inserted in the target instruction stream
1451 * \param make_copies Flag selecting whether instructions in \c instructions
1452 * should be copied (via \c ir_instruction::clone) into the
1453 * target list or moved.
1456 * The new "last" instruction in the target instruction stream. This pointer
1457 * is suitable for use as the \c last parameter of a later call to this
1461 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1462 bool make_copies
, gl_linked_shader
*target
)
1464 hash_table
*temps
= NULL
;
1467 temps
= _mesa_pointer_hash_table_create(NULL
);
1469 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1470 if (inst
->as_function())
1473 ir_variable
*var
= inst
->as_variable();
1474 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1477 assert(inst
->as_assignment()
1479 || inst
->as_if() /* for initializers with the ?: operator */
1480 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1483 inst
= inst
->clone(target
, NULL
);
1486 _mesa_hash_table_insert(temps
, var
, inst
);
1488 remap_variables(inst
, target
, temps
);
1493 last
->insert_after(inst
);
1498 _mesa_hash_table_destroy(temps
, NULL
);
1505 * This class is only used in link_intrastage_shaders() below but declaring
1506 * it inside that function leads to compiler warnings with some versions of
1509 class array_sizing_visitor
: public deref_type_updater
{
1511 using deref_type_updater::visit
;
1513 array_sizing_visitor()
1514 : mem_ctx(ralloc_context(NULL
)),
1515 unnamed_interfaces(_mesa_pointer_hash_table_create(NULL
))
1519 ~array_sizing_visitor()
1521 _mesa_hash_table_destroy(this->unnamed_interfaces
, NULL
);
1522 ralloc_free(this->mem_ctx
);
1525 virtual ir_visitor_status
visit(ir_variable
*var
)
1527 const glsl_type
*type_without_array
;
1528 bool implicit_sized_array
= var
->data
.implicit_sized_array
;
1529 fixup_type(&var
->type
, var
->data
.max_array_access
,
1530 var
->data
.from_ssbo_unsized_array
,
1531 &implicit_sized_array
);
1532 var
->data
.implicit_sized_array
= implicit_sized_array
;
1533 type_without_array
= var
->type
->without_array();
1534 if (var
->type
->is_interface()) {
1535 if (interface_contains_unsized_arrays(var
->type
)) {
1536 const glsl_type
*new_type
=
1537 resize_interface_members(var
->type
,
1538 var
->get_max_ifc_array_access(),
1539 var
->is_in_shader_storage_block());
1540 var
->type
= new_type
;
1541 var
->change_interface_type(new_type
);
1543 } else if (type_without_array
->is_interface()) {
1544 if (interface_contains_unsized_arrays(type_without_array
)) {
1545 const glsl_type
*new_type
=
1546 resize_interface_members(type_without_array
,
1547 var
->get_max_ifc_array_access(),
1548 var
->is_in_shader_storage_block());
1549 var
->change_interface_type(new_type
);
1550 var
->type
= update_interface_members_array(var
->type
, new_type
);
1552 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1553 /* Store a pointer to the variable in the unnamed_interfaces
1557 _mesa_hash_table_search(this->unnamed_interfaces
,
1560 ir_variable
**interface_vars
= entry
? (ir_variable
**) entry
->data
: NULL
;
1562 if (interface_vars
== NULL
) {
1563 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1565 _mesa_hash_table_insert(this->unnamed_interfaces
, ifc_type
,
1568 unsigned index
= ifc_type
->field_index(var
->name
);
1569 assert(index
< ifc_type
->length
);
1570 assert(interface_vars
[index
] == NULL
);
1571 interface_vars
[index
] = var
;
1573 return visit_continue
;
1577 * For each unnamed interface block that was discovered while running the
1578 * visitor, adjust the interface type to reflect the newly assigned array
1579 * sizes, and fix up the ir_variable nodes to point to the new interface
1582 void fixup_unnamed_interface_types()
1584 hash_table_call_foreach(this->unnamed_interfaces
,
1585 fixup_unnamed_interface_type
, NULL
);
1590 * If the type pointed to by \c type represents an unsized array, replace
1591 * it with a sized array whose size is determined by max_array_access.
1593 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1594 bool from_ssbo_unsized_array
, bool *implicit_sized
)
1596 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1597 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1598 max_array_access
+ 1);
1599 *implicit_sized
= true;
1600 assert(*type
!= NULL
);
1604 static const glsl_type
*
1605 update_interface_members_array(const glsl_type
*type
,
1606 const glsl_type
*new_interface_type
)
1608 const glsl_type
*element_type
= type
->fields
.array
;
1609 if (element_type
->is_array()) {
1610 const glsl_type
*new_array_type
=
1611 update_interface_members_array(element_type
, new_interface_type
);
1612 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1614 return glsl_type::get_array_instance(new_interface_type
,
1620 * Determine whether the given interface type contains unsized arrays (if
1621 * it doesn't, array_sizing_visitor doesn't need to process it).
1623 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1625 for (unsigned i
= 0; i
< type
->length
; i
++) {
1626 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1627 if (elem_type
->is_unsized_array())
1634 * Create a new interface type based on the given type, with unsized arrays
1635 * replaced by sized arrays whose size is determined by
1636 * max_ifc_array_access.
1638 static const glsl_type
*
1639 resize_interface_members(const glsl_type
*type
,
1640 const int *max_ifc_array_access
,
1643 unsigned num_fields
= type
->length
;
1644 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1645 memcpy(fields
, type
->fields
.structure
,
1646 num_fields
* sizeof(*fields
));
1647 for (unsigned i
= 0; i
< num_fields
; i
++) {
1648 bool implicit_sized_array
= fields
[i
].implicit_sized_array
;
1649 /* If SSBO last member is unsized array, we don't replace it by a sized
1652 if (is_ssbo
&& i
== (num_fields
- 1))
1653 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1654 true, &implicit_sized_array
);
1656 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1657 false, &implicit_sized_array
);
1658 fields
[i
].implicit_sized_array
= implicit_sized_array
;
1660 glsl_interface_packing packing
=
1661 (glsl_interface_packing
) type
->interface_packing
;
1662 bool row_major
= (bool) type
->interface_row_major
;
1663 const glsl_type
*new_ifc_type
=
1664 glsl_type::get_interface_instance(fields
, num_fields
,
1665 packing
, row_major
, type
->name
);
1667 return new_ifc_type
;
1670 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1673 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1674 ir_variable
**interface_vars
= (ir_variable
**) data
;
1675 unsigned num_fields
= ifc_type
->length
;
1676 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1677 memcpy(fields
, ifc_type
->fields
.structure
,
1678 num_fields
* sizeof(*fields
));
1679 bool interface_type_changed
= false;
1680 for (unsigned i
= 0; i
< num_fields
; i
++) {
1681 if (interface_vars
[i
] != NULL
&&
1682 fields
[i
].type
!= interface_vars
[i
]->type
) {
1683 fields
[i
].type
= interface_vars
[i
]->type
;
1684 interface_type_changed
= true;
1687 if (!interface_type_changed
) {
1691 glsl_interface_packing packing
=
1692 (glsl_interface_packing
) ifc_type
->interface_packing
;
1693 bool row_major
= (bool) ifc_type
->interface_row_major
;
1694 const glsl_type
*new_ifc_type
=
1695 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1696 row_major
, ifc_type
->name
);
1698 for (unsigned i
= 0; i
< num_fields
; i
++) {
1699 if (interface_vars
[i
] != NULL
)
1700 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1705 * Memory context used to allocate the data in \c unnamed_interfaces.
1710 * Hash table from const glsl_type * to an array of ir_variable *'s
1711 * pointing to the ir_variables constituting each unnamed interface block.
1713 hash_table
*unnamed_interfaces
;
1717 validate_xfb_buffer_stride(struct gl_context
*ctx
, unsigned idx
,
1718 struct gl_shader_program
*prog
)
1720 /* We will validate doubles at a later stage */
1721 if (prog
->TransformFeedback
.BufferStride
[idx
] % 4) {
1722 linker_error(prog
, "invalid qualifier xfb_stride=%d must be a "
1723 "multiple of 4 or if its applied to a type that is "
1724 "or contains a double a multiple of 8.",
1725 prog
->TransformFeedback
.BufferStride
[idx
]);
1729 if (prog
->TransformFeedback
.BufferStride
[idx
] / 4 >
1730 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1731 linker_error(prog
, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1732 "limit has been exceeded.");
1740 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1744 link_xfb_stride_layout_qualifiers(struct gl_context
*ctx
,
1745 struct gl_shader_program
*prog
,
1746 struct gl_shader
**shader_list
,
1747 unsigned num_shaders
)
1749 for (unsigned i
= 0; i
< MAX_FEEDBACK_BUFFERS
; i
++) {
1750 prog
->TransformFeedback
.BufferStride
[i
] = 0;
1753 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1754 struct gl_shader
*shader
= shader_list
[i
];
1756 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1757 if (shader
->TransformFeedbackBufferStride
[j
]) {
1758 if (prog
->TransformFeedback
.BufferStride
[j
] == 0) {
1759 prog
->TransformFeedback
.BufferStride
[j
] =
1760 shader
->TransformFeedbackBufferStride
[j
];
1761 if (!validate_xfb_buffer_stride(ctx
, j
, prog
))
1763 } else if (prog
->TransformFeedback
.BufferStride
[j
] !=
1764 shader
->TransformFeedbackBufferStride
[j
]){
1766 "intrastage shaders defined with conflicting "
1767 "xfb_stride for buffer %d (%d and %d)\n", j
,
1768 prog
->TransformFeedback
.BufferStride
[j
],
1769 shader
->TransformFeedbackBufferStride
[j
]);
1778 * Check for conflicting bindless/bound sampler/image layout qualifiers at
1782 link_bindless_layout_qualifiers(struct gl_shader_program
*prog
,
1783 struct gl_shader
**shader_list
,
1784 unsigned num_shaders
)
1786 bool bindless_sampler
, bindless_image
;
1787 bool bound_sampler
, bound_image
;
1789 bindless_sampler
= bindless_image
= false;
1790 bound_sampler
= bound_image
= false;
1792 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1793 struct gl_shader
*shader
= shader_list
[i
];
1795 if (shader
->bindless_sampler
)
1796 bindless_sampler
= true;
1797 if (shader
->bindless_image
)
1798 bindless_image
= true;
1799 if (shader
->bound_sampler
)
1800 bound_sampler
= true;
1801 if (shader
->bound_image
)
1804 if ((bindless_sampler
&& bound_sampler
) ||
1805 (bindless_image
&& bound_image
)) {
1806 /* From section 4.4.6 of the ARB_bindless_texture spec:
1808 * "If both bindless_sampler and bound_sampler, or bindless_image
1809 * and bound_image, are declared at global scope in any
1810 * compilation unit, a link- time error will be generated."
1812 linker_error(prog
, "both bindless_sampler and bound_sampler, or "
1813 "bindless_image and bound_image, can't be declared at "
1820 * Performs the cross-validation of tessellation control shader vertices and
1821 * layout qualifiers for the attached tessellation control shaders,
1822 * and propagates them to the linked TCS and linked shader program.
1825 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1826 struct gl_program
*gl_prog
,
1827 struct gl_shader
**shader_list
,
1828 unsigned num_shaders
)
1830 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_CTRL
)
1833 gl_prog
->info
.tess
.tcs_vertices_out
= 0;
1835 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1837 * "All tessellation control shader layout declarations in a program
1838 * must specify the same output patch vertex count. There must be at
1839 * least one layout qualifier specifying an output patch vertex count
1840 * in any program containing tessellation control shaders; however,
1841 * such a declaration is not required in all tessellation control
1845 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1846 struct gl_shader
*shader
= shader_list
[i
];
1848 if (shader
->info
.TessCtrl
.VerticesOut
!= 0) {
1849 if (gl_prog
->info
.tess
.tcs_vertices_out
!= 0 &&
1850 gl_prog
->info
.tess
.tcs_vertices_out
!=
1851 (unsigned) shader
->info
.TessCtrl
.VerticesOut
) {
1852 linker_error(prog
, "tessellation control shader defined with "
1853 "conflicting output vertex count (%d and %d)\n",
1854 gl_prog
->info
.tess
.tcs_vertices_out
,
1855 shader
->info
.TessCtrl
.VerticesOut
);
1858 gl_prog
->info
.tess
.tcs_vertices_out
=
1859 shader
->info
.TessCtrl
.VerticesOut
;
1863 /* Just do the intrastage -> interstage propagation right now,
1864 * since we already know we're in the right type of shader program
1867 if (gl_prog
->info
.tess
.tcs_vertices_out
== 0) {
1868 linker_error(prog
, "tessellation control shader didn't declare "
1869 "vertices out layout qualifier\n");
1876 * Performs the cross-validation of tessellation evaluation shader
1877 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1878 * for the attached tessellation evaluation shaders, and propagates them
1879 * to the linked TES and linked shader program.
1882 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1883 struct gl_program
*gl_prog
,
1884 struct gl_shader
**shader_list
,
1885 unsigned num_shaders
)
1887 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_EVAL
)
1890 int point_mode
= -1;
1891 unsigned vertex_order
= 0;
1893 gl_prog
->info
.tess
.primitive_mode
= PRIM_UNKNOWN
;
1894 gl_prog
->info
.tess
.spacing
= TESS_SPACING_UNSPECIFIED
;
1896 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1898 * "At least one tessellation evaluation shader (compilation unit) in
1899 * a program must declare a primitive mode in its input layout.
1900 * Declaration vertex spacing, ordering, and point mode identifiers is
1901 * optional. It is not required that all tessellation evaluation
1902 * shaders in a program declare a primitive mode. If spacing or
1903 * vertex ordering declarations are omitted, the tessellation
1904 * primitive generator will use equal spacing or counter-clockwise
1905 * vertex ordering, respectively. If a point mode declaration is
1906 * omitted, the tessellation primitive generator will produce lines or
1907 * triangles according to the primitive mode."
1910 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1911 struct gl_shader
*shader
= shader_list
[i
];
1913 if (shader
->info
.TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1914 if (gl_prog
->info
.tess
.primitive_mode
!= PRIM_UNKNOWN
&&
1915 gl_prog
->info
.tess
.primitive_mode
!=
1916 shader
->info
.TessEval
.PrimitiveMode
) {
1917 linker_error(prog
, "tessellation evaluation shader defined with "
1918 "conflicting input primitive modes.\n");
1921 gl_prog
->info
.tess
.primitive_mode
=
1922 shader
->info
.TessEval
.PrimitiveMode
;
1925 if (shader
->info
.TessEval
.Spacing
!= 0) {
1926 if (gl_prog
->info
.tess
.spacing
!= 0 && gl_prog
->info
.tess
.spacing
!=
1927 shader
->info
.TessEval
.Spacing
) {
1928 linker_error(prog
, "tessellation evaluation shader defined with "
1929 "conflicting vertex spacing.\n");
1932 gl_prog
->info
.tess
.spacing
= shader
->info
.TessEval
.Spacing
;
1935 if (shader
->info
.TessEval
.VertexOrder
!= 0) {
1936 if (vertex_order
!= 0 &&
1937 vertex_order
!= shader
->info
.TessEval
.VertexOrder
) {
1938 linker_error(prog
, "tessellation evaluation shader defined with "
1939 "conflicting ordering.\n");
1942 vertex_order
= shader
->info
.TessEval
.VertexOrder
;
1945 if (shader
->info
.TessEval
.PointMode
!= -1) {
1946 if (point_mode
!= -1 &&
1947 point_mode
!= shader
->info
.TessEval
.PointMode
) {
1948 linker_error(prog
, "tessellation evaluation shader defined with "
1949 "conflicting point modes.\n");
1952 point_mode
= shader
->info
.TessEval
.PointMode
;
1957 /* Just do the intrastage -> interstage propagation right now,
1958 * since we already know we're in the right type of shader program
1961 if (gl_prog
->info
.tess
.primitive_mode
== PRIM_UNKNOWN
) {
1963 "tessellation evaluation shader didn't declare input "
1964 "primitive modes.\n");
1968 if (gl_prog
->info
.tess
.spacing
== TESS_SPACING_UNSPECIFIED
)
1969 gl_prog
->info
.tess
.spacing
= TESS_SPACING_EQUAL
;
1971 if (vertex_order
== 0 || vertex_order
== GL_CCW
)
1972 gl_prog
->info
.tess
.ccw
= true;
1974 gl_prog
->info
.tess
.ccw
= false;
1977 if (point_mode
== -1 || point_mode
== GL_FALSE
)
1978 gl_prog
->info
.tess
.point_mode
= false;
1980 gl_prog
->info
.tess
.point_mode
= true;
1985 * Performs the cross-validation of layout qualifiers specified in
1986 * redeclaration of gl_FragCoord for the attached fragment shaders,
1987 * and propagates them to the linked FS and linked shader program.
1990 link_fs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1991 struct gl_linked_shader
*linked_shader
,
1992 struct gl_shader
**shader_list
,
1993 unsigned num_shaders
)
1995 bool redeclares_gl_fragcoord
= false;
1996 bool uses_gl_fragcoord
= false;
1997 bool origin_upper_left
= false;
1998 bool pixel_center_integer
= false;
2000 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
2001 (prog
->data
->Version
< 150 &&
2002 !prog
->ARB_fragment_coord_conventions_enable
))
2005 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2006 struct gl_shader
*shader
= shader_list
[i
];
2007 /* From the GLSL 1.50 spec, page 39:
2009 * "If gl_FragCoord is redeclared in any fragment shader in a program,
2010 * it must be redeclared in all the fragment shaders in that program
2011 * that have a static use gl_FragCoord."
2013 if ((redeclares_gl_fragcoord
&& !shader
->redeclares_gl_fragcoord
&&
2014 shader
->uses_gl_fragcoord
)
2015 || (shader
->redeclares_gl_fragcoord
&& !redeclares_gl_fragcoord
&&
2016 uses_gl_fragcoord
)) {
2017 linker_error(prog
, "fragment shader defined with conflicting "
2018 "layout qualifiers for gl_FragCoord\n");
2021 /* From the GLSL 1.50 spec, page 39:
2023 * "All redeclarations of gl_FragCoord in all fragment shaders in a
2024 * single program must have the same set of qualifiers."
2026 if (redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
&&
2027 (shader
->origin_upper_left
!= origin_upper_left
||
2028 shader
->pixel_center_integer
!= pixel_center_integer
)) {
2029 linker_error(prog
, "fragment shader defined with conflicting "
2030 "layout qualifiers for gl_FragCoord\n");
2033 /* Update the linked shader state. Note that uses_gl_fragcoord should
2034 * accumulate the results. The other values should replace. If there
2035 * are multiple redeclarations, all the fields except uses_gl_fragcoord
2036 * are already known to be the same.
2038 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
2039 redeclares_gl_fragcoord
= shader
->redeclares_gl_fragcoord
;
2040 uses_gl_fragcoord
|= shader
->uses_gl_fragcoord
;
2041 origin_upper_left
= shader
->origin_upper_left
;
2042 pixel_center_integer
= shader
->pixel_center_integer
;
2045 linked_shader
->Program
->info
.fs
.early_fragment_tests
|=
2046 shader
->EarlyFragmentTests
|| shader
->PostDepthCoverage
;
2047 linked_shader
->Program
->info
.fs
.inner_coverage
|= shader
->InnerCoverage
;
2048 linked_shader
->Program
->info
.fs
.post_depth_coverage
|=
2049 shader
->PostDepthCoverage
;
2050 linked_shader
->Program
->info
.fs
.pixel_interlock_ordered
|=
2051 shader
->PixelInterlockOrdered
;
2052 linked_shader
->Program
->info
.fs
.pixel_interlock_unordered
|=
2053 shader
->PixelInterlockUnordered
;
2054 linked_shader
->Program
->info
.fs
.sample_interlock_ordered
|=
2055 shader
->SampleInterlockOrdered
;
2056 linked_shader
->Program
->info
.fs
.sample_interlock_unordered
|=
2057 shader
->SampleInterlockUnordered
;
2058 linked_shader
->Program
->sh
.fs
.BlendSupport
|= shader
->BlendSupport
;
2061 linked_shader
->Program
->info
.fs
.pixel_center_integer
= pixel_center_integer
;
2062 linked_shader
->Program
->info
.fs
.origin_upper_left
= origin_upper_left
;
2066 * Performs the cross-validation of geometry shader max_vertices and
2067 * primitive type layout qualifiers for the attached geometry shaders,
2068 * and propagates them to the linked GS and linked shader program.
2071 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
2072 struct gl_program
*gl_prog
,
2073 struct gl_shader
**shader_list
,
2074 unsigned num_shaders
)
2076 /* No in/out qualifiers defined for anything but GLSL 1.50+
2077 * geometry shaders so far.
2079 if (gl_prog
->info
.stage
!= MESA_SHADER_GEOMETRY
||
2080 prog
->data
->Version
< 150)
2083 int vertices_out
= -1;
2085 gl_prog
->info
.gs
.invocations
= 0;
2086 gl_prog
->info
.gs
.input_primitive
= PRIM_UNKNOWN
;
2087 gl_prog
->info
.gs
.output_primitive
= PRIM_UNKNOWN
;
2089 /* From the GLSL 1.50 spec, page 46:
2091 * "All geometry shader output layout declarations in a program
2092 * must declare the same layout and same value for
2093 * max_vertices. There must be at least one geometry output
2094 * layout declaration somewhere in a program, but not all
2095 * geometry shaders (compilation units) are required to
2099 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2100 struct gl_shader
*shader
= shader_list
[i
];
2102 if (shader
->info
.Geom
.InputType
!= PRIM_UNKNOWN
) {
2103 if (gl_prog
->info
.gs
.input_primitive
!= PRIM_UNKNOWN
&&
2104 gl_prog
->info
.gs
.input_primitive
!=
2105 shader
->info
.Geom
.InputType
) {
2106 linker_error(prog
, "geometry shader defined with conflicting "
2110 gl_prog
->info
.gs
.input_primitive
= shader
->info
.Geom
.InputType
;
2113 if (shader
->info
.Geom
.OutputType
!= PRIM_UNKNOWN
) {
2114 if (gl_prog
->info
.gs
.output_primitive
!= PRIM_UNKNOWN
&&
2115 gl_prog
->info
.gs
.output_primitive
!=
2116 shader
->info
.Geom
.OutputType
) {
2117 linker_error(prog
, "geometry shader defined with conflicting "
2121 gl_prog
->info
.gs
.output_primitive
= shader
->info
.Geom
.OutputType
;
2124 if (shader
->info
.Geom
.VerticesOut
!= -1) {
2125 if (vertices_out
!= -1 &&
2126 vertices_out
!= shader
->info
.Geom
.VerticesOut
) {
2127 linker_error(prog
, "geometry shader defined with conflicting "
2128 "output vertex count (%d and %d)\n",
2129 vertices_out
, shader
->info
.Geom
.VerticesOut
);
2132 vertices_out
= shader
->info
.Geom
.VerticesOut
;
2135 if (shader
->info
.Geom
.Invocations
!= 0) {
2136 if (gl_prog
->info
.gs
.invocations
!= 0 &&
2137 gl_prog
->info
.gs
.invocations
!=
2138 (unsigned) shader
->info
.Geom
.Invocations
) {
2139 linker_error(prog
, "geometry shader defined with conflicting "
2140 "invocation count (%d and %d)\n",
2141 gl_prog
->info
.gs
.invocations
,
2142 shader
->info
.Geom
.Invocations
);
2145 gl_prog
->info
.gs
.invocations
= shader
->info
.Geom
.Invocations
;
2149 /* Just do the intrastage -> interstage propagation right now,
2150 * since we already know we're in the right type of shader program
2153 if (gl_prog
->info
.gs
.input_primitive
== PRIM_UNKNOWN
) {
2155 "geometry shader didn't declare primitive input type\n");
2159 if (gl_prog
->info
.gs
.output_primitive
== PRIM_UNKNOWN
) {
2161 "geometry shader didn't declare primitive output type\n");
2165 if (vertices_out
== -1) {
2167 "geometry shader didn't declare max_vertices\n");
2170 gl_prog
->info
.gs
.vertices_out
= vertices_out
;
2173 if (gl_prog
->info
.gs
.invocations
== 0)
2174 gl_prog
->info
.gs
.invocations
= 1;
2179 * Perform cross-validation of compute shader local_size_{x,y,z} layout and
2180 * derivative arrangement qualifiers for the attached compute shaders, and
2181 * propagate them to the linked CS and linked shader program.
2184 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
2185 struct gl_program
*gl_prog
,
2186 struct gl_shader
**shader_list
,
2187 unsigned num_shaders
)
2189 /* This function is called for all shader stages, but it only has an effect
2190 * for compute shaders.
2192 if (gl_prog
->info
.stage
!= MESA_SHADER_COMPUTE
)
2195 for (int i
= 0; i
< 3; i
++)
2196 gl_prog
->info
.cs
.local_size
[i
] = 0;
2198 gl_prog
->info
.cs
.local_size_variable
= false;
2200 gl_prog
->info
.cs
.derivative_group
= DERIVATIVE_GROUP_NONE
;
2202 /* From the ARB_compute_shader spec, in the section describing local size
2205 * If multiple compute shaders attached to a single program object
2206 * declare local work-group size, the declarations must be identical;
2207 * otherwise a link-time error results. Furthermore, if a program
2208 * object contains any compute shaders, at least one must contain an
2209 * input layout qualifier specifying the local work sizes of the
2210 * program, or a link-time error will occur.
2212 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
2213 struct gl_shader
*shader
= shader_list
[sh
];
2215 if (shader
->info
.Comp
.LocalSize
[0] != 0) {
2216 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2217 for (int i
= 0; i
< 3; i
++) {
2218 if (gl_prog
->info
.cs
.local_size
[i
] !=
2219 shader
->info
.Comp
.LocalSize
[i
]) {
2220 linker_error(prog
, "compute shader defined with conflicting "
2226 for (int i
= 0; i
< 3; i
++) {
2227 gl_prog
->info
.cs
.local_size
[i
] =
2228 shader
->info
.Comp
.LocalSize
[i
];
2230 } else if (shader
->info
.Comp
.LocalSizeVariable
) {
2231 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2232 /* The ARB_compute_variable_group_size spec says:
2234 * If one compute shader attached to a program declares a
2235 * variable local group size and a second compute shader
2236 * attached to the same program declares a fixed local group
2237 * size, a link-time error results.
2239 linker_error(prog
, "compute shader defined with both fixed and "
2240 "variable local group size\n");
2243 gl_prog
->info
.cs
.local_size_variable
= true;
2246 enum gl_derivative_group group
= shader
->info
.Comp
.DerivativeGroup
;
2247 if (group
!= DERIVATIVE_GROUP_NONE
) {
2248 if (gl_prog
->info
.cs
.derivative_group
!= DERIVATIVE_GROUP_NONE
&&
2249 gl_prog
->info
.cs
.derivative_group
!= group
) {
2250 linker_error(prog
, "compute shader defined with conflicting "
2251 "derivative groups\n");
2254 gl_prog
->info
.cs
.derivative_group
= group
;
2258 /* Just do the intrastage -> interstage propagation right now,
2259 * since we already know we're in the right type of shader program
2262 if (gl_prog
->info
.cs
.local_size
[0] == 0 &&
2263 !gl_prog
->info
.cs
.local_size_variable
) {
2264 linker_error(prog
, "compute shader must contain a fixed or a variable "
2265 "local group size\n");
2269 if (gl_prog
->info
.cs
.derivative_group
== DERIVATIVE_GROUP_QUADS
) {
2270 if (gl_prog
->info
.cs
.local_size
[0] % 2 != 0) {
2271 linker_error(prog
, "derivative_group_quadsNV must be used with a "
2272 "local group size whose first dimension "
2273 "is a multiple of 2\n");
2276 if (gl_prog
->info
.cs
.local_size
[1] % 2 != 0) {
2277 linker_error(prog
, "derivative_group_quadsNV must be used with a local"
2278 "group size whose second dimension "
2279 "is a multiple of 2\n");
2282 } else if (gl_prog
->info
.cs
.derivative_group
== DERIVATIVE_GROUP_LINEAR
) {
2283 if ((gl_prog
->info
.cs
.local_size
[0] *
2284 gl_prog
->info
.cs
.local_size
[1] *
2285 gl_prog
->info
.cs
.local_size
[2]) % 4 != 0) {
2286 linker_error(prog
, "derivative_group_linearNV must be used with a "
2287 "local group size whose total number of invocations "
2288 "is a multiple of 4\n");
2295 * Link all out variables on a single stage which are not
2296 * directly used in a shader with the main function.
2299 link_output_variables(struct gl_linked_shader
*linked_shader
,
2300 struct gl_shader
**shader_list
,
2301 unsigned num_shaders
)
2303 struct glsl_symbol_table
*symbols
= linked_shader
->symbols
;
2305 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2307 /* Skip shader object with main function */
2308 if (shader_list
[i
]->symbols
->get_function("main"))
2311 foreach_in_list(ir_instruction
, ir
, shader_list
[i
]->ir
) {
2312 if (ir
->ir_type
!= ir_type_variable
)
2315 ir_variable
*var
= (ir_variable
*) ir
;
2317 if (var
->data
.mode
== ir_var_shader_out
&&
2318 !symbols
->get_variable(var
->name
)) {
2319 var
= var
->clone(linked_shader
, NULL
);
2320 symbols
->add_variable(var
);
2321 linked_shader
->ir
->push_head(var
);
2331 * Combine a group of shaders for a single stage to generate a linked shader
2334 * If this function is supplied a single shader, it is cloned, and the new
2335 * shader is returned.
2337 struct gl_linked_shader
*
2338 link_intrastage_shaders(void *mem_ctx
,
2339 struct gl_context
*ctx
,
2340 struct gl_shader_program
*prog
,
2341 struct gl_shader
**shader_list
,
2342 unsigned num_shaders
,
2343 bool allow_missing_main
)
2345 struct gl_uniform_block
*ubo_blocks
= NULL
;
2346 struct gl_uniform_block
*ssbo_blocks
= NULL
;
2347 unsigned num_ubo_blocks
= 0;
2348 unsigned num_ssbo_blocks
= 0;
2350 /* Check that global variables defined in multiple shaders are consistent.
2352 glsl_symbol_table variables
;
2353 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2354 if (shader_list
[i
] == NULL
)
2356 cross_validate_globals(ctx
, prog
, shader_list
[i
]->ir
, &variables
,
2360 if (!prog
->data
->LinkStatus
)
2363 /* Check that interface blocks defined in multiple shaders are consistent.
2365 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
2367 if (!prog
->data
->LinkStatus
)
2370 /* Check that there is only a single definition of each function signature
2371 * across all shaders.
2373 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2374 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2375 ir_function
*const f
= node
->as_function();
2380 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2381 ir_function
*const other
=
2382 shader_list
[j
]->symbols
->get_function(f
->name
);
2384 /* If the other shader has no function (and therefore no function
2385 * signatures) with the same name, skip to the next shader.
2390 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2391 if (!sig
->is_defined
)
2394 ir_function_signature
*other_sig
=
2395 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2397 if (other_sig
!= NULL
&& other_sig
->is_defined
) {
2398 linker_error(prog
, "function `%s' is multiply defined\n",
2407 /* Find the shader that defines main, and make a clone of it.
2409 * Starting with the clone, search for undefined references. If one is
2410 * found, find the shader that defines it. Clone the reference and add
2411 * it to the shader. Repeat until there are no undefined references or
2412 * until a reference cannot be resolved.
2414 gl_shader
*main
= NULL
;
2415 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2416 if (_mesa_get_main_function_signature(shader_list
[i
]->symbols
)) {
2417 main
= shader_list
[i
];
2422 if (main
== NULL
&& allow_missing_main
)
2423 main
= shader_list
[0];
2426 linker_error(prog
, "%s shader lacks `main'\n",
2427 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2431 gl_linked_shader
*linked
= rzalloc(NULL
, struct gl_linked_shader
);
2432 linked
->Stage
= shader_list
[0]->Stage
;
2434 /* Create program and attach it to the linked shader */
2435 struct gl_program
*gl_prog
=
2436 ctx
->Driver
.NewProgram(ctx
,
2437 _mesa_shader_stage_to_program(shader_list
[0]->Stage
),
2440 prog
->data
->LinkStatus
= LINKING_FAILURE
;
2441 _mesa_delete_linked_shader(ctx
, linked
);
2445 _mesa_reference_shader_program_data(ctx
, &gl_prog
->sh
.data
, prog
->data
);
2447 /* Don't use _mesa_reference_program() just take ownership */
2448 linked
->Program
= gl_prog
;
2450 linked
->ir
= new(linked
) exec_list
;
2451 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2453 link_fs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2454 link_tcs_out_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2455 link_tes_in_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2456 link_gs_inout_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2457 link_cs_input_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2459 if (linked
->Stage
!= MESA_SHADER_FRAGMENT
)
2460 link_xfb_stride_layout_qualifiers(ctx
, prog
, shader_list
, num_shaders
);
2462 link_bindless_layout_qualifiers(prog
, shader_list
, num_shaders
);
2464 populate_symbol_table(linked
, shader_list
[0]->symbols
);
2466 /* The pointer to the main function in the final linked shader (i.e., the
2467 * copy of the original shader that contained the main function).
2469 ir_function_signature
*const main_sig
=
2470 _mesa_get_main_function_signature(linked
->symbols
);
2472 /* Move any instructions other than variable declarations or function
2473 * declarations into main.
2475 if (main_sig
!= NULL
) {
2476 exec_node
*insertion_point
=
2477 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2480 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2481 if (shader_list
[i
] == main
)
2484 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2485 insertion_point
, true, linked
);
2489 if (!link_function_calls(prog
, linked
, shader_list
, num_shaders
)) {
2490 _mesa_delete_linked_shader(ctx
, linked
);
2494 if (linked
->Stage
!= MESA_SHADER_FRAGMENT
)
2495 link_output_variables(linked
, shader_list
, num_shaders
);
2497 /* Make a pass over all variable declarations to ensure that arrays with
2498 * unspecified sizes have a size specified. The size is inferred from the
2499 * max_array_access field.
2501 array_sizing_visitor v
;
2503 v
.fixup_unnamed_interface_types();
2505 /* Link up uniform blocks defined within this stage. */
2506 link_uniform_blocks(mem_ctx
, ctx
, prog
, linked
, &ubo_blocks
,
2507 &num_ubo_blocks
, &ssbo_blocks
, &num_ssbo_blocks
);
2509 const unsigned max_uniform_blocks
=
2510 ctx
->Const
.Program
[linked
->Stage
].MaxUniformBlocks
;
2511 if (num_ubo_blocks
> max_uniform_blocks
) {
2512 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
2513 _mesa_shader_stage_to_string(linked
->Stage
),
2514 num_ubo_blocks
, max_uniform_blocks
);
2517 const unsigned max_shader_storage_blocks
=
2518 ctx
->Const
.Program
[linked
->Stage
].MaxShaderStorageBlocks
;
2519 if (num_ssbo_blocks
> max_shader_storage_blocks
) {
2520 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
2521 _mesa_shader_stage_to_string(linked
->Stage
),
2522 num_ssbo_blocks
, max_shader_storage_blocks
);
2525 if (!prog
->data
->LinkStatus
) {
2526 _mesa_delete_linked_shader(ctx
, linked
);
2530 /* Copy ubo blocks to linked shader list */
2531 linked
->Program
->sh
.UniformBlocks
=
2532 ralloc_array(linked
, gl_uniform_block
*, num_ubo_blocks
);
2533 ralloc_steal(linked
, ubo_blocks
);
2534 for (unsigned i
= 0; i
< num_ubo_blocks
; i
++) {
2535 linked
->Program
->sh
.UniformBlocks
[i
] = &ubo_blocks
[i
];
2537 linked
->Program
->info
.num_ubos
= num_ubo_blocks
;
2539 /* Copy ssbo blocks to linked shader list */
2540 linked
->Program
->sh
.ShaderStorageBlocks
=
2541 ralloc_array(linked
, gl_uniform_block
*, num_ssbo_blocks
);
2542 ralloc_steal(linked
, ssbo_blocks
);
2543 for (unsigned i
= 0; i
< num_ssbo_blocks
; i
++) {
2544 linked
->Program
->sh
.ShaderStorageBlocks
[i
] = &ssbo_blocks
[i
];
2546 linked
->Program
->info
.num_ssbos
= num_ssbo_blocks
;
2548 /* At this point linked should contain all of the linked IR, so
2549 * validate it to make sure nothing went wrong.
2551 validate_ir_tree(linked
->ir
);
2553 /* Set the size of geometry shader input arrays */
2554 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2555 unsigned num_vertices
=
2556 vertices_per_prim(gl_prog
->info
.gs
.input_primitive
);
2557 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2558 MESA_SHADER_GEOMETRY
);
2559 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2560 ir
->accept(&input_resize_visitor
);
2564 if (ctx
->Const
.VertexID_is_zero_based
)
2565 lower_vertex_id(linked
);
2567 if (ctx
->Const
.LowerCsDerivedVariables
)
2568 lower_cs_derived(linked
);
2571 /* Compute the source checksum. */
2572 linked
->SourceChecksum
= 0;
2573 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2574 if (shader_list
[i
] == NULL
)
2576 linked
->SourceChecksum
^= shader_list
[i
]->SourceChecksum
;
2584 * Update the sizes of linked shader uniform arrays to the maximum
2587 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2589 * If one or more elements of an array are active,
2590 * GetActiveUniform will return the name of the array in name,
2591 * subject to the restrictions listed above. The type of the array
2592 * is returned in type. The size parameter contains the highest
2593 * array element index used, plus one. The compiler or linker
2594 * determines the highest index used. There will be only one
2595 * active uniform reported by the GL per uniform array.
2599 update_array_sizes(struct gl_shader_program
*prog
)
2601 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2602 if (prog
->_LinkedShaders
[i
] == NULL
)
2605 bool types_were_updated
= false;
2607 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2608 ir_variable
*const var
= node
->as_variable();
2610 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2611 !var
->type
->is_array())
2614 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2615 * will not be eliminated. Since we always do std140, just
2616 * don't resize arrays in UBOs.
2618 * Atomic counters are supposed to get deterministic
2619 * locations assigned based on the declaration ordering and
2620 * sizes, array compaction would mess that up.
2622 * Subroutine uniforms are not removed.
2624 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2625 var
->type
->contains_subroutine() || var
->constant_initializer
)
2628 int size
= var
->data
.max_array_access
;
2629 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2630 if (prog
->_LinkedShaders
[j
] == NULL
)
2633 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2634 ir_variable
*other_var
= node2
->as_variable();
2638 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2639 other_var
->data
.max_array_access
> size
) {
2640 size
= other_var
->data
.max_array_access
;
2645 if (size
+ 1 != (int)var
->type
->length
) {
2646 /* If this is a built-in uniform (i.e., it's backed by some
2647 * fixed-function state), adjust the number of state slots to
2648 * match the new array size. The number of slots per array entry
2649 * is not known. It seems safe to assume that the total number of
2650 * slots is an integer multiple of the number of array elements.
2651 * Determine the number of slots per array element by dividing by
2652 * the old (total) size.
2654 const unsigned num_slots
= var
->get_num_state_slots();
2655 if (num_slots
> 0) {
2656 var
->set_num_state_slots((size
+ 1)
2657 * (num_slots
/ var
->type
->length
));
2660 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2662 types_were_updated
= true;
2666 /* Update the types of dereferences in case we changed any. */
2667 if (types_were_updated
) {
2668 deref_type_updater v
;
2669 v
.run(prog
->_LinkedShaders
[i
]->ir
);
2675 * Resize tessellation evaluation per-vertex inputs to the size of
2676 * tessellation control per-vertex outputs.
2679 resize_tes_inputs(struct gl_context
*ctx
,
2680 struct gl_shader_program
*prog
)
2682 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2685 gl_linked_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2686 gl_linked_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2688 /* If no control shader is present, then the TES inputs are statically
2689 * sized to MaxPatchVertices; the actual size of the arrays won't be
2690 * known until draw time.
2692 const int num_vertices
= tcs
2693 ? tcs
->Program
->info
.tess
.tcs_vertices_out
2694 : ctx
->Const
.MaxPatchVertices
;
2696 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2697 MESA_SHADER_TESS_EVAL
);
2698 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2699 ir
->accept(&input_resize_visitor
);
2703 /* Convert the gl_PatchVerticesIn system value into a constant, since
2704 * the value is known at this point.
2706 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2707 ir_variable
*var
= ir
->as_variable();
2708 if (var
&& var
->data
.mode
== ir_var_system_value
&&
2709 var
->data
.location
== SYSTEM_VALUE_VERTICES_IN
) {
2710 void *mem_ctx
= ralloc_parent(var
);
2711 var
->data
.location
= 0;
2712 var
->data
.explicit_location
= false;
2713 var
->data
.mode
= ir_var_auto
;
2714 var
->constant_value
= new(mem_ctx
) ir_constant(num_vertices
);
2721 * Find a contiguous set of available bits in a bitmask.
2723 * \param used_mask Bits representing used (1) and unused (0) locations
2724 * \param needed_count Number of contiguous bits needed.
2727 * Base location of the available bits on success or -1 on failure.
2730 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2732 unsigned needed_mask
= (1 << needed_count
) - 1;
2733 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2735 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2736 * cannot optimize possibly infinite loops" for the loop below.
2738 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2741 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2742 if ((needed_mask
& ~used_mask
) == needed_mask
)
2752 #define SAFE_MASK_FROM_INDEX(i) (((i) >= 32) ? ~0 : ((1 << (i)) - 1))
2755 * Assign locations for either VS inputs or FS outputs.
2757 * \param mem_ctx Temporary ralloc context used for linking.
2758 * \param prog Shader program whose variables need locations
2760 * \param constants Driver specific constant values for the program.
2761 * \param target_index Selector for the program target to receive location
2762 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2763 * \c MESA_SHADER_FRAGMENT.
2764 * \param do_assignment Whether we are actually marking the assignment or we
2765 * are just doing a dry-run checking.
2768 * If locations are (or can be, in case of dry-running) successfully assigned,
2769 * true is returned. Otherwise an error is emitted to the shader link log and
2770 * false is returned.
2773 assign_attribute_or_color_locations(void *mem_ctx
,
2774 gl_shader_program
*prog
,
2775 struct gl_constants
*constants
,
2776 unsigned target_index
,
2779 /* Maximum number of generic locations. This corresponds to either the
2780 * maximum number of draw buffers or the maximum number of generic
2783 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2784 constants
->Program
[target_index
].MaxAttribs
:
2785 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2787 /* Mark invalid locations as being used.
2789 unsigned used_locations
= ~SAFE_MASK_FROM_INDEX(max_index
);
2790 unsigned double_storage_locations
= 0;
2792 assert((target_index
== MESA_SHADER_VERTEX
)
2793 || (target_index
== MESA_SHADER_FRAGMENT
));
2795 gl_linked_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2799 /* Operate in a total of four passes.
2801 * 1. Invalidate the location assignments for all vertex shader inputs.
2803 * 2. Assign locations for inputs that have user-defined (via
2804 * glBindVertexAttribLocation) locations and outputs that have
2805 * user-defined locations (via glBindFragDataLocation).
2807 * 3. Sort the attributes without assigned locations by number of slots
2808 * required in decreasing order. Fragmentation caused by attribute
2809 * locations assigned by the application may prevent large attributes
2810 * from having enough contiguous space.
2812 * 4. Assign locations to any inputs without assigned locations.
2815 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2816 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2818 const enum ir_variable_mode direction
=
2819 (target_index
== MESA_SHADER_VERTEX
)
2820 ? ir_var_shader_in
: ir_var_shader_out
;
2823 /* Temporary storage for the set of attributes that need locations assigned.
2829 /* Used below in the call to qsort. */
2830 static int compare(const void *a
, const void *b
)
2832 const temp_attr
*const l
= (const temp_attr
*) a
;
2833 const temp_attr
*const r
= (const temp_attr
*) b
;
2835 /* Reversed because we want a descending order sort below. */
2836 return r
->slots
- l
->slots
;
2839 assert(max_index
<= 32);
2841 /* Temporary array for the set of attributes that have locations assigned,
2842 * for the purpose of checking overlapping slots/components of (non-ES)
2843 * fragment shader outputs.
2845 ir_variable
*assigned
[12 * 4]; /* (max # of FS outputs) * # components */
2846 unsigned assigned_attr
= 0;
2848 unsigned num_attr
= 0;
2850 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2851 ir_variable
*const var
= node
->as_variable();
2853 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2856 if (var
->data
.explicit_location
) {
2857 var
->data
.is_unmatched_generic_inout
= 0;
2858 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2859 || (var
->data
.location
< 0)) {
2861 "invalid explicit location %d specified for `%s'\n",
2862 (var
->data
.location
< 0)
2863 ? var
->data
.location
2864 : var
->data
.location
- generic_base
,
2868 } else if (target_index
== MESA_SHADER_VERTEX
) {
2871 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2872 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2873 var
->data
.location
= binding
;
2874 var
->data
.is_unmatched_generic_inout
= 0;
2876 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2879 const char *name
= var
->name
;
2880 const glsl_type
*type
= var
->type
;
2883 /* Check if there's a binding for the variable name */
2884 if (prog
->FragDataBindings
->get(binding
, name
)) {
2885 assert(binding
>= FRAG_RESULT_DATA0
);
2886 var
->data
.location
= binding
;
2887 var
->data
.is_unmatched_generic_inout
= 0;
2889 if (prog
->FragDataIndexBindings
->get(index
, name
)) {
2890 var
->data
.index
= index
;
2895 /* If not, but it's an array type, look for name[0] */
2896 if (type
->is_array()) {
2897 name
= ralloc_asprintf(mem_ctx
, "%s[0]", name
);
2898 type
= type
->fields
.array
;
2906 if (strcmp(var
->name
, "gl_LastFragData") == 0)
2909 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2911 * "Output binding assignments will cause LinkProgram to fail:
2913 * If the program has an active output assigned to a location greater
2914 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2915 * an active output assigned an index greater than or equal to one;"
2917 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2918 var
->data
.location
- generic_base
>=
2919 (int) constants
->MaxDualSourceDrawBuffers
) {
2921 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2922 "with index %u for %s\n",
2923 var
->data
.location
- generic_base
, var
->data
.index
,
2928 const unsigned slots
= var
->type
->count_attribute_slots(target_index
== MESA_SHADER_VERTEX
);
2930 /* If the variable is not a built-in and has a location statically
2931 * assigned in the shader (presumably via a layout qualifier), make sure
2932 * that it doesn't collide with other assigned locations. Otherwise,
2933 * add it to the list of variables that need linker-assigned locations.
2935 if (var
->data
.location
!= -1) {
2936 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2937 /* From page 61 of the OpenGL 4.0 spec:
2939 * "LinkProgram will fail if the attribute bindings assigned
2940 * by BindAttribLocation do not leave not enough space to
2941 * assign a location for an active matrix attribute or an
2942 * active attribute array, both of which require multiple
2943 * contiguous generic attributes."
2945 * I think above text prohibits the aliasing of explicit and
2946 * automatic assignments. But, aliasing is allowed in manual
2947 * assignments of attribute locations. See below comments for
2950 * From OpenGL 4.0 spec, page 61:
2952 * "It is possible for an application to bind more than one
2953 * attribute name to the same location. This is referred to as
2954 * aliasing. This will only work if only one of the aliased
2955 * attributes is active in the executable program, or if no
2956 * path through the shader consumes more than one attribute of
2957 * a set of attributes aliased to the same location. A link
2958 * error can occur if the linker determines that every path
2959 * through the shader consumes multiple aliased attributes,
2960 * but implementations are not required to generate an error
2963 * From GLSL 4.30 spec, page 54:
2965 * "A program will fail to link if any two non-vertex shader
2966 * input variables are assigned to the same location. For
2967 * vertex shaders, multiple input variables may be assigned
2968 * to the same location using either layout qualifiers or via
2969 * the OpenGL API. However, such aliasing is intended only to
2970 * support vertex shaders where each execution path accesses
2971 * at most one input per each location. Implementations are
2972 * permitted, but not required, to generate link-time errors
2973 * if they detect that every path through the vertex shader
2974 * executable accesses multiple inputs assigned to any single
2975 * location. For all shader types, a program will fail to link
2976 * if explicit location assignments leave the linker unable
2977 * to find space for other variables without explicit
2980 * From OpenGL ES 3.0 spec, page 56:
2982 * "Binding more than one attribute name to the same location
2983 * is referred to as aliasing, and is not permitted in OpenGL
2984 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2985 * fail when this condition exists. However, aliasing is
2986 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2987 * This will only work if only one of the aliased attributes
2988 * is active in the executable program, or if no path through
2989 * the shader consumes more than one attribute of a set of
2990 * attributes aliased to the same location. A link error can
2991 * occur if the linker determines that every path through the
2992 * shader consumes multiple aliased attributes, but implemen-
2993 * tations are not required to generate an error in this case."
2995 * After looking at above references from OpenGL, OpenGL ES and
2996 * GLSL specifications, we allow aliasing of vertex input variables
2997 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2999 * NOTE: This is not required by the spec but its worth mentioning
3000 * here that we're not doing anything to make sure that no path
3001 * through the vertex shader executable accesses multiple inputs
3002 * assigned to any single location.
3005 /* Mask representing the contiguous slots that will be used by
3008 const unsigned attr
= var
->data
.location
- generic_base
;
3009 const unsigned use_mask
= (1 << slots
) - 1;
3010 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
3011 ? "vertex shader input" : "fragment shader output";
3013 /* Generate a link error if the requested locations for this
3014 * attribute exceed the maximum allowed attribute location.
3016 if (attr
+ slots
> max_index
) {
3018 "insufficient contiguous locations "
3019 "available for %s `%s' %d %d %d\n", string
,
3020 var
->name
, used_locations
, use_mask
, attr
);
3024 /* Generate a link error if the set of bits requested for this
3025 * attribute overlaps any previously allocated bits.
3027 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
3028 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
3029 /* From section 4.4.2 (Output Layout Qualifiers) of the GLSL
3032 * "Additionally, for fragment shader outputs, if two
3033 * variables are placed within the same location, they
3034 * must have the same underlying type (floating-point or
3035 * integer). No component aliasing of output variables or
3036 * members is allowed.
3038 for (unsigned i
= 0; i
< assigned_attr
; i
++) {
3039 unsigned assigned_slots
=
3040 assigned
[i
]->type
->count_attribute_slots(false);
3041 unsigned assig_attr
=
3042 assigned
[i
]->data
.location
- generic_base
;
3043 unsigned assigned_use_mask
= (1 << assigned_slots
) - 1;
3045 if ((assigned_use_mask
<< assig_attr
) &
3046 (use_mask
<< attr
)) {
3048 const glsl_type
*assigned_type
=
3049 assigned
[i
]->type
->without_array();
3050 const glsl_type
*type
= var
->type
->without_array();
3051 if (assigned_type
->base_type
!= type
->base_type
) {
3052 linker_error(prog
, "types do not match for aliased"
3053 " %ss %s and %s\n", string
,
3054 assigned
[i
]->name
, var
->name
);
3058 unsigned assigned_component_mask
=
3059 ((1 << assigned_type
->vector_elements
) - 1) <<
3060 assigned
[i
]->data
.location_frac
;
3061 unsigned component_mask
=
3062 ((1 << type
->vector_elements
) - 1) <<
3063 var
->data
.location_frac
;
3064 if (assigned_component_mask
& component_mask
) {
3065 linker_error(prog
, "overlapping component is "
3066 "assigned to %ss %s and %s "
3068 string
, assigned
[i
]->name
, var
->name
,
3069 var
->data
.location_frac
);
3074 } else if (target_index
== MESA_SHADER_FRAGMENT
||
3075 (prog
->IsES
&& prog
->data
->Version
>= 300)) {
3076 linker_error(prog
, "overlapping location is assigned "
3077 "to %s `%s' %d %d %d\n", string
, var
->name
,
3078 used_locations
, use_mask
, attr
);
3081 linker_warning(prog
, "overlapping location is assigned "
3082 "to %s `%s' %d %d %d\n", string
, var
->name
,
3083 used_locations
, use_mask
, attr
);
3087 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
3088 /* Only track assigned variables for non-ES fragment shaders
3089 * to avoid overflowing the array.
3091 * At most one variable per fragment output component should
3094 assert(assigned_attr
< ARRAY_SIZE(assigned
));
3095 assigned
[assigned_attr
] = var
;
3099 used_locations
|= (use_mask
<< attr
);
3101 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
3103 * "A program with more than the value of MAX_VERTEX_ATTRIBS
3104 * active attribute variables may fail to link, unless
3105 * device-dependent optimizations are able to make the program
3106 * fit within available hardware resources. For the purposes
3107 * of this test, attribute variables of the type dvec3, dvec4,
3108 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
3109 * count as consuming twice as many attributes as equivalent
3110 * single-precision types. While these types use the same number
3111 * of generic attributes as their single-precision equivalents,
3112 * implementations are permitted to consume two single-precision
3113 * vectors of internal storage for each three- or four-component
3114 * double-precision vector."
3116 * Mark this attribute slot as taking up twice as much space
3117 * so we can count it properly against limits. According to
3118 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
3119 * is optional behavior, but it seems preferable.
3121 if (var
->type
->without_array()->is_dual_slot())
3122 double_storage_locations
|= (use_mask
<< attr
);
3128 if (num_attr
>= max_index
) {
3129 linker_error(prog
, "too many %s (max %u)",
3130 target_index
== MESA_SHADER_VERTEX
?
3131 "vertex shader inputs" : "fragment shader outputs",
3135 to_assign
[num_attr
].slots
= slots
;
3136 to_assign
[num_attr
].var
= var
;
3143 if (target_index
== MESA_SHADER_VERTEX
) {
3144 unsigned total_attribs_size
=
3145 util_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
3146 util_bitcount(double_storage_locations
);
3147 if (total_attribs_size
> max_index
) {
3149 "attempt to use %d vertex attribute slots only %d available ",
3150 total_attribs_size
, max_index
);
3155 /* If all of the attributes were assigned locations by the application (or
3156 * are built-in attributes with fixed locations), return early. This should
3157 * be the common case.
3162 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
3164 if (target_index
== MESA_SHADER_VERTEX
) {
3165 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
3166 * only be explicitly assigned by via glBindAttribLocation. Mark it as
3167 * reserved to prevent it from being automatically allocated below.
3169 find_deref_visitor
find("gl_Vertex");
3171 if (find
.variable_found())
3172 used_locations
|= (1 << 0);
3175 for (unsigned i
= 0; i
< num_attr
; i
++) {
3176 /* Mask representing the contiguous slots that will be used by this
3179 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
3181 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
3184 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
3185 ? "vertex shader input" : "fragment shader output";
3188 "insufficient contiguous locations "
3189 "available for %s `%s'\n",
3190 string
, to_assign
[i
].var
->name
);
3194 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
3195 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
3196 used_locations
|= (use_mask
<< location
);
3198 if (to_assign
[i
].var
->type
->without_array()->is_dual_slot())
3199 double_storage_locations
|= (use_mask
<< location
);
3202 /* Now that we have all the locations, from the GL 4.5 core spec, section
3203 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
3204 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
3205 * as equivalent single-precision types.
3207 if (target_index
== MESA_SHADER_VERTEX
) {
3208 unsigned total_attribs_size
=
3209 util_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
3210 util_bitcount(double_storage_locations
);
3211 if (total_attribs_size
> max_index
) {
3213 "attempt to use %d vertex attribute slots only %d available ",
3214 total_attribs_size
, max_index
);
3223 * Match explicit locations of outputs to inputs and deactivate the
3224 * unmatch flag if found so we don't optimise them away.
3227 match_explicit_outputs_to_inputs(gl_linked_shader
*producer
,
3228 gl_linked_shader
*consumer
)
3230 glsl_symbol_table parameters
;
3231 ir_variable
*explicit_locations
[MAX_VARYINGS_INCL_PATCH
][4] =
3234 /* Find all shader outputs in the "producer" stage.
3236 foreach_in_list(ir_instruction
, node
, producer
->ir
) {
3237 ir_variable
*const var
= node
->as_variable();
3239 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_shader_out
))
3242 if (var
->data
.explicit_location
&&
3243 var
->data
.location
>= VARYING_SLOT_VAR0
) {
3244 const unsigned idx
= var
->data
.location
- VARYING_SLOT_VAR0
;
3245 if (explicit_locations
[idx
][var
->data
.location_frac
] == NULL
)
3246 explicit_locations
[idx
][var
->data
.location_frac
] = var
;
3248 /* Always match TCS outputs. They are shared by all invocations
3249 * within a patch and can be used as shared memory.
3251 if (producer
->Stage
== MESA_SHADER_TESS_CTRL
)
3252 var
->data
.is_unmatched_generic_inout
= 0;
3256 /* Match inputs to outputs */
3257 foreach_in_list(ir_instruction
, node
, consumer
->ir
) {
3258 ir_variable
*const input
= node
->as_variable();
3260 if ((input
== NULL
) || (input
->data
.mode
!= ir_var_shader_in
))
3263 ir_variable
*output
= NULL
;
3264 if (input
->data
.explicit_location
3265 && input
->data
.location
>= VARYING_SLOT_VAR0
) {
3266 output
= explicit_locations
[input
->data
.location
- VARYING_SLOT_VAR0
]
3267 [input
->data
.location_frac
];
3269 if (output
!= NULL
){
3270 input
->data
.is_unmatched_generic_inout
= 0;
3271 output
->data
.is_unmatched_generic_inout
= 0;
3278 * Store the gl_FragDepth layout in the gl_shader_program struct.
3281 store_fragdepth_layout(struct gl_shader_program
*prog
)
3283 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
3287 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
3289 /* We don't look up the gl_FragDepth symbol directly because if
3290 * gl_FragDepth is not used in the shader, it's removed from the IR.
3291 * However, the symbol won't be removed from the symbol table.
3293 * We're only interested in the cases where the variable is NOT removed
3296 foreach_in_list(ir_instruction
, node
, ir
) {
3297 ir_variable
*const var
= node
->as_variable();
3299 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
3303 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
3304 switch (var
->data
.depth_layout
) {
3305 case ir_depth_layout_none
:
3306 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
3308 case ir_depth_layout_any
:
3309 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
3311 case ir_depth_layout_greater
:
3312 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
3314 case ir_depth_layout_less
:
3315 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
3317 case ir_depth_layout_unchanged
:
3318 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
3329 * Validate shader image resources.
3332 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3334 unsigned total_image_units
= 0;
3335 unsigned fragment_outputs
= 0;
3336 unsigned total_shader_storage_blocks
= 0;
3338 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
3341 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3342 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3345 total_image_units
+= sh
->Program
->info
.num_images
;
3346 total_shader_storage_blocks
+= sh
->Program
->info
.num_ssbos
;
3348 if (i
== MESA_SHADER_FRAGMENT
) {
3349 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3350 ir_variable
*var
= node
->as_variable();
3351 if (var
&& var
->data
.mode
== ir_var_shader_out
)
3352 /* since there are no double fs outputs - pass false */
3353 fragment_outputs
+= var
->type
->count_attribute_slots(false);
3359 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
3360 linker_error(prog
, "Too many combined image uniforms\n");
3362 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
3363 ctx
->Const
.MaxCombinedShaderOutputResources
)
3364 linker_error(prog
, "Too many combined image uniforms, shader storage "
3365 " buffers and fragment outputs\n");
3370 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3371 * for a variable, checks for overlaps between other uniforms using explicit
3375 reserve_explicit_locations(struct gl_shader_program
*prog
,
3376 string_to_uint_map
*map
, ir_variable
*var
)
3378 unsigned slots
= var
->type
->uniform_locations();
3379 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3380 unsigned return_value
= slots
;
3382 /* Resize remap table if locations do not fit in the current one. */
3383 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
3384 prog
->UniformRemapTable
=
3385 reralloc(prog
, prog
->UniformRemapTable
,
3386 gl_uniform_storage
*,
3389 if (!prog
->UniformRemapTable
) {
3390 linker_error(prog
, "Out of memory during linking.\n");
3394 /* Initialize allocated space. */
3395 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
3396 prog
->UniformRemapTable
[i
] = NULL
;
3398 prog
->NumUniformRemapTable
= max_loc
+ 1;
3401 for (unsigned i
= 0; i
< slots
; i
++) {
3402 unsigned loc
= var
->data
.location
+ i
;
3404 /* Check if location is already used. */
3405 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3407 /* Possibly same uniform from a different stage, this is ok. */
3409 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
) {
3414 /* ARB_explicit_uniform_location specification states:
3416 * "No two default-block uniform variables in the program can have
3417 * the same location, even if they are unused, otherwise a compiler
3418 * or linker error will be generated."
3421 "location qualifier for uniform %s overlaps "
3422 "previously used location\n",
3427 /* Initialize location as inactive before optimization
3428 * rounds and location assignment.
3430 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3433 /* Note, base location used for arrays. */
3434 map
->put(var
->data
.location
, var
->name
);
3436 return return_value
;
3440 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3441 struct gl_program
*p
,
3444 unsigned slots
= var
->type
->uniform_locations();
3445 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3447 /* Resize remap table if locations do not fit in the current one. */
3448 if (max_loc
+ 1 > p
->sh
.NumSubroutineUniformRemapTable
) {
3449 p
->sh
.SubroutineUniformRemapTable
=
3450 reralloc(p
, p
->sh
.SubroutineUniformRemapTable
,
3451 gl_uniform_storage
*,
3454 if (!p
->sh
.SubroutineUniformRemapTable
) {
3455 linker_error(prog
, "Out of memory during linking.\n");
3459 /* Initialize allocated space. */
3460 for (unsigned i
= p
->sh
.NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3461 p
->sh
.SubroutineUniformRemapTable
[i
] = NULL
;
3463 p
->sh
.NumSubroutineUniformRemapTable
= max_loc
+ 1;
3466 for (unsigned i
= 0; i
< slots
; i
++) {
3467 unsigned loc
= var
->data
.location
+ i
;
3469 /* Check if location is already used. */
3470 if (p
->sh
.SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3472 /* ARB_explicit_uniform_location specification states:
3473 * "No two subroutine uniform variables can have the same location
3474 * in the same shader stage, otherwise a compiler or linker error
3475 * will be generated."
3478 "location qualifier for uniform %s overlaps "
3479 "previously used location\n",
3484 /* Initialize location as inactive before optimization
3485 * rounds and location assignment.
3487 p
->sh
.SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3493 * Check and reserve all explicit uniform locations, called before
3494 * any optimizations happen to handle also inactive uniforms and
3495 * inactive array elements that may get trimmed away.
3498 check_explicit_uniform_locations(struct gl_context
*ctx
,
3499 struct gl_shader_program
*prog
)
3501 prog
->NumExplicitUniformLocations
= 0;
3503 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3506 /* This map is used to detect if overlapping explicit locations
3507 * occur with the same uniform (from different stage) or a different one.
3509 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3512 linker_error(prog
, "Out of memory during linking.\n");
3516 unsigned entries_total
= 0;
3517 unsigned mask
= prog
->data
->linked_stages
;
3519 const int i
= u_bit_scan(&mask
);
3520 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3522 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
3523 ir_variable
*var
= node
->as_variable();
3524 if (!var
|| var
->data
.mode
!= ir_var_uniform
)
3527 if (var
->data
.explicit_location
) {
3529 if (var
->type
->without_array()->is_subroutine())
3530 ret
= reserve_subroutine_explicit_locations(prog
, p
, var
);
3532 int slots
= reserve_explicit_locations(prog
, uniform_map
,
3536 entries_total
+= slots
;
3547 link_util_update_empty_uniform_locations(prog
);
3550 prog
->NumExplicitUniformLocations
= entries_total
;
3553 /* Function checks if a variable var is a packed varying and
3554 * if given name is part of packed varying's list.
3556 * If a variable is a packed varying, it has a name like
3557 * 'packed:a,b,c' where a, b and c are separate variables.
3560 included_in_packed_varying(ir_variable
*var
, const char *name
)
3562 if (strncmp(var
->name
, "packed:", 7) != 0)
3565 char *list
= strdup(var
->name
+ 7);
3570 char *token
= strtok_r(list
, ",", &saveptr
);
3572 if (strcmp(token
, name
) == 0) {
3576 token
= strtok_r(NULL
, ",", &saveptr
);
3583 * Function builds a stage reference bitmask from variable name.
3586 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3591 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3592 * used for reference mask in gl_program_resource will need to be changed.
3594 assert(MESA_SHADER_STAGES
< 8);
3596 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3597 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
3601 /* Shader symbol table may contain variables that have
3602 * been optimized away. Search IR for the variable instead.
3604 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3605 ir_variable
*var
= node
->as_variable();
3607 unsigned baselen
= strlen(var
->name
);
3609 if (included_in_packed_varying(var
, name
)) {
3614 /* Type needs to match if specified, otherwise we might
3615 * pick a variable with same name but different interface.
3617 if (var
->data
.mode
!= mode
)
3620 if (strncmp(var
->name
, name
, baselen
) == 0) {
3621 /* Check for exact name matches but also check for arrays and
3624 if (name
[baselen
] == '\0' ||
3625 name
[baselen
] == '[' ||
3626 name
[baselen
] == '.') {
3638 * Create gl_shader_variable from ir_variable class.
3640 static gl_shader_variable
*
3641 create_shader_variable(struct gl_shader_program
*shProg
,
3642 const ir_variable
*in
,
3643 const char *name
, const glsl_type
*type
,
3644 const glsl_type
*interface_type
,
3645 bool use_implicit_location
, int location
,
3646 const glsl_type
*outermost_struct_type
)
3648 /* Allocate zero-initialized memory to ensure that bitfield padding
3651 gl_shader_variable
*out
= rzalloc(shProg
, struct gl_shader_variable
);
3655 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3656 * expect to see gl_VertexID in the program resource list. Pretend.
3658 if (in
->data
.mode
== ir_var_system_value
&&
3659 in
->data
.location
== SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
) {
3660 out
->name
= ralloc_strdup(shProg
, "gl_VertexID");
3661 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3662 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_OUTER
) ||
3663 (in
->data
.mode
== ir_var_system_value
&&
3664 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_OUTER
)) {
3665 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelOuter");
3666 type
= glsl_type::get_array_instance(glsl_type::float_type
, 4);
3667 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3668 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_INNER
) ||
3669 (in
->data
.mode
== ir_var_system_value
&&
3670 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_INNER
)) {
3671 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelInner");
3672 type
= glsl_type::get_array_instance(glsl_type::float_type
, 2);
3674 out
->name
= ralloc_strdup(shProg
, name
);
3680 /* The ARB_program_interface_query spec says:
3682 * "Not all active variables are assigned valid locations; the
3683 * following variables will have an effective location of -1:
3685 * * uniforms declared as atomic counters;
3687 * * members of a uniform block;
3689 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3691 * * inputs or outputs not declared with a "location" layout
3692 * qualifier, except for vertex shader inputs and fragment shader
3695 if (in
->type
->is_atomic_uint() || is_gl_identifier(in
->name
) ||
3696 !(in
->data
.explicit_location
|| use_implicit_location
)) {
3699 out
->location
= location
;
3703 out
->outermost_struct_type
= outermost_struct_type
;
3704 out
->interface_type
= interface_type
;
3705 out
->component
= in
->data
.location_frac
;
3706 out
->index
= in
->data
.index
;
3707 out
->patch
= in
->data
.patch
;
3708 out
->mode
= in
->data
.mode
;
3709 out
->interpolation
= in
->data
.interpolation
;
3710 out
->explicit_location
= in
->data
.explicit_location
;
3711 out
->precision
= in
->data
.precision
;
3717 add_shader_variable(const struct gl_context
*ctx
,
3718 struct gl_shader_program
*shProg
,
3719 struct set
*resource_set
,
3720 unsigned stage_mask
,
3721 GLenum programInterface
, ir_variable
*var
,
3722 const char *name
, const glsl_type
*type
,
3723 bool use_implicit_location
, int location
,
3724 bool inouts_share_location
,
3725 const glsl_type
*outermost_struct_type
= NULL
)
3727 const glsl_type
*interface_type
= var
->get_interface_type();
3729 if (outermost_struct_type
== NULL
) {
3730 if (var
->data
.from_named_ifc_block
) {
3731 const char *interface_name
= interface_type
->name
;
3733 if (interface_type
->is_array()) {
3734 /* Issue #16 of the ARB_program_interface_query spec says:
3736 * "* If a variable is a member of an interface block without an
3737 * instance name, it is enumerated using just the variable name.
3739 * * If a variable is a member of an interface block with an
3740 * instance name, it is enumerated as "BlockName.Member", where
3741 * "BlockName" is the name of the interface block (not the
3742 * instance name) and "Member" is the name of the variable."
3744 * In particular, it indicates that it should be "BlockName",
3745 * not "BlockName[array length]". The conformance suite and
3746 * dEQP both require this behavior.
3748 * Here, we unwrap the extra array level added by named interface
3749 * block array lowering so we have the correct variable type. We
3750 * also unwrap the interface type when constructing the name.
3752 * We leave interface_type the same so that ES 3.x SSO pipeline
3753 * validation can enforce the rules requiring array length to
3754 * match on interface blocks.
3756 type
= type
->fields
.array
;
3758 interface_name
= interface_type
->fields
.array
->name
;
3761 name
= ralloc_asprintf(shProg
, "%s.%s", interface_name
, name
);
3765 switch (type
->base_type
) {
3766 case GLSL_TYPE_STRUCT
: {
3767 /* The ARB_program_interface_query spec says:
3769 * "For an active variable declared as a structure, a separate entry
3770 * will be generated for each active structure member. The name of
3771 * each entry is formed by concatenating the name of the structure,
3772 * the "." character, and the name of the structure member. If a
3773 * structure member to enumerate is itself a structure or array,
3774 * these enumeration rules are applied recursively."
3776 if (outermost_struct_type
== NULL
)
3777 outermost_struct_type
= type
;
3779 unsigned field_location
= location
;
3780 for (unsigned i
= 0; i
< type
->length
; i
++) {
3781 const struct glsl_struct_field
*field
= &type
->fields
.structure
[i
];
3782 char *field_name
= ralloc_asprintf(shProg
, "%s.%s", name
, field
->name
);
3783 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3784 stage_mask
, programInterface
,
3785 var
, field_name
, field
->type
,
3786 use_implicit_location
, field_location
,
3787 false, outermost_struct_type
))
3790 field_location
+= field
->type
->count_attribute_slots(false);
3795 case GLSL_TYPE_ARRAY
: {
3796 /* The ARB_program_interface_query spec says:
3798 * "For an active variable declared as an array of basic types, a
3799 * single entry will be generated, with its name string formed by
3800 * concatenating the name of the array and the string "[0]"."
3802 * "For an active variable declared as an array of an aggregate data
3803 * type (structures or arrays), a separate entry will be generated
3804 * for each active array element, unless noted immediately below.
3805 * The name of each entry is formed by concatenating the name of
3806 * the array, the "[" character, an integer identifying the element
3807 * number, and the "]" character. These enumeration rules are
3808 * applied recursively, treating each enumerated array element as a
3809 * separate active variable."
3811 const struct glsl_type
*array_type
= type
->fields
.array
;
3812 if (array_type
->base_type
== GLSL_TYPE_STRUCT
||
3813 array_type
->base_type
== GLSL_TYPE_ARRAY
) {
3814 unsigned elem_location
= location
;
3815 unsigned stride
= inouts_share_location
? 0 :
3816 array_type
->count_attribute_slots(false);
3817 for (unsigned i
= 0; i
< type
->length
; i
++) {
3818 char *elem
= ralloc_asprintf(shProg
, "%s[%d]", name
, i
);
3819 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3820 stage_mask
, programInterface
,
3821 var
, elem
, array_type
,
3822 use_implicit_location
, elem_location
,
3823 false, outermost_struct_type
))
3825 elem_location
+= stride
;
3833 /* The ARB_program_interface_query spec says:
3835 * "For an active variable declared as a single instance of a basic
3836 * type, a single entry will be generated, using the variable name
3837 * from the shader source."
3839 gl_shader_variable
*sha_v
=
3840 create_shader_variable(shProg
, var
, name
, type
, interface_type
,
3841 use_implicit_location
, location
,
3842 outermost_struct_type
);
3846 return link_util_add_program_resource(shProg
, resource_set
,
3847 programInterface
, sha_v
, stage_mask
);
3853 inout_has_same_location(const ir_variable
*var
, unsigned stage
)
3855 if (!var
->data
.patch
&&
3856 ((var
->data
.mode
== ir_var_shader_out
&&
3857 stage
== MESA_SHADER_TESS_CTRL
) ||
3858 (var
->data
.mode
== ir_var_shader_in
&&
3859 (stage
== MESA_SHADER_TESS_CTRL
|| stage
== MESA_SHADER_TESS_EVAL
||
3860 stage
== MESA_SHADER_GEOMETRY
))))
3867 add_interface_variables(const struct gl_context
*ctx
,
3868 struct gl_shader_program
*shProg
,
3869 struct set
*resource_set
,
3870 unsigned stage
, GLenum programInterface
)
3872 exec_list
*ir
= shProg
->_LinkedShaders
[stage
]->ir
;
3874 foreach_in_list(ir_instruction
, node
, ir
) {
3875 ir_variable
*var
= node
->as_variable();
3877 if (!var
|| var
->data
.how_declared
== ir_var_hidden
)
3882 switch (var
->data
.mode
) {
3883 case ir_var_system_value
:
3884 case ir_var_shader_in
:
3885 if (programInterface
!= GL_PROGRAM_INPUT
)
3887 loc_bias
= (stage
== MESA_SHADER_VERTEX
) ? int(VERT_ATTRIB_GENERIC0
)
3888 : int(VARYING_SLOT_VAR0
);
3890 case ir_var_shader_out
:
3891 if (programInterface
!= GL_PROGRAM_OUTPUT
)
3893 loc_bias
= (stage
== MESA_SHADER_FRAGMENT
) ? int(FRAG_RESULT_DATA0
)
3894 : int(VARYING_SLOT_VAR0
);
3900 if (var
->data
.patch
)
3901 loc_bias
= int(VARYING_SLOT_PATCH0
);
3903 /* Skip packed varyings, packed varyings are handled separately
3904 * by add_packed_varyings.
3906 if (strncmp(var
->name
, "packed:", 7) == 0)
3909 /* Skip fragdata arrays, these are handled separately
3910 * by add_fragdata_arrays.
3912 if (strncmp(var
->name
, "gl_out_FragData", 15) == 0)
3915 const bool vs_input_or_fs_output
=
3916 (stage
== MESA_SHADER_VERTEX
&& var
->data
.mode
== ir_var_shader_in
) ||
3917 (stage
== MESA_SHADER_FRAGMENT
&& var
->data
.mode
== ir_var_shader_out
);
3919 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3920 1 << stage
, programInterface
,
3921 var
, var
->name
, var
->type
, vs_input_or_fs_output
,
3922 var
->data
.location
- loc_bias
,
3923 inout_has_same_location(var
, stage
)))
3930 add_packed_varyings(const struct gl_context
*ctx
,
3931 struct gl_shader_program
*shProg
,
3932 struct set
*resource_set
,
3933 int stage
, GLenum type
)
3935 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[stage
];
3938 if (!sh
|| !sh
->packed_varyings
)
3941 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
3942 ir_variable
*var
= node
->as_variable();
3944 switch (var
->data
.mode
) {
3945 case ir_var_shader_in
:
3946 iface
= GL_PROGRAM_INPUT
;
3948 case ir_var_shader_out
:
3949 iface
= GL_PROGRAM_OUTPUT
;
3952 unreachable("unexpected type");
3955 if (type
== iface
) {
3956 const int stage_mask
=
3957 build_stageref(shProg
, var
->name
, var
->data
.mode
);
3958 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3960 iface
, var
, var
->name
, var
->type
, false,
3961 var
->data
.location
- VARYING_SLOT_VAR0
,
3962 inout_has_same_location(var
, stage
)))
3971 add_fragdata_arrays(const struct gl_context
*ctx
,
3972 struct gl_shader_program
*shProg
,
3973 struct set
*resource_set
)
3975 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
3977 if (!sh
|| !sh
->fragdata_arrays
)
3980 foreach_in_list(ir_instruction
, node
, sh
->fragdata_arrays
) {
3981 ir_variable
*var
= node
->as_variable();
3983 assert(var
->data
.mode
== ir_var_shader_out
);
3985 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3986 1 << MESA_SHADER_FRAGMENT
,
3987 GL_PROGRAM_OUTPUT
, var
, var
->name
, var
->type
,
3988 true, var
->data
.location
- FRAG_RESULT_DATA0
,
3997 * Builds up a list of program resources that point to existing
4001 build_program_resource_list(struct gl_context
*ctx
,
4002 struct gl_shader_program
*shProg
,
4003 bool add_packed_varyings_only
)
4005 /* Rebuild resource list. */
4006 if (shProg
->data
->ProgramResourceList
) {
4007 ralloc_free(shProg
->data
->ProgramResourceList
);
4008 shProg
->data
->ProgramResourceList
= NULL
;
4009 shProg
->data
->NumProgramResourceList
= 0;
4012 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
4014 /* Determine first input and final output stage. These are used to
4015 * detect which variables should be enumerated in the resource list
4016 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4018 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4019 if (!shProg
->_LinkedShaders
[i
])
4021 if (input_stage
== MESA_SHADER_STAGES
)
4026 /* Empty shader, no resources. */
4027 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
4030 struct set
*resource_set
= _mesa_pointer_set_create(NULL
);
4032 /* Program interface needs to expose varyings in case of SSO. */
4033 if (shProg
->SeparateShader
) {
4034 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4035 input_stage
, GL_PROGRAM_INPUT
))
4038 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4039 output_stage
, GL_PROGRAM_OUTPUT
))
4043 if (add_packed_varyings_only
) {
4044 _mesa_set_destroy(resource_set
, NULL
);
4048 if (!add_fragdata_arrays(ctx
, shProg
, resource_set
))
4051 /* Add inputs and outputs to the resource list. */
4052 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4053 input_stage
, GL_PROGRAM_INPUT
))
4056 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4057 output_stage
, GL_PROGRAM_OUTPUT
))
4060 if (shProg
->last_vert_prog
) {
4061 struct gl_transform_feedback_info
*linked_xfb
=
4062 shProg
->last_vert_prog
->sh
.LinkedTransformFeedback
;
4064 /* Add transform feedback varyings. */
4065 if (linked_xfb
->NumVarying
> 0) {
4066 for (int i
= 0; i
< linked_xfb
->NumVarying
; i
++) {
4067 if (!link_util_add_program_resource(shProg
, resource_set
,
4068 GL_TRANSFORM_FEEDBACK_VARYING
,
4069 &linked_xfb
->Varyings
[i
], 0))
4074 /* Add transform feedback buffers. */
4075 for (unsigned i
= 0; i
< ctx
->Const
.MaxTransformFeedbackBuffers
; i
++) {
4076 if ((linked_xfb
->ActiveBuffers
>> i
) & 1) {
4077 linked_xfb
->Buffers
[i
].Binding
= i
;
4078 if (!link_util_add_program_resource(shProg
, resource_set
,
4079 GL_TRANSFORM_FEEDBACK_BUFFER
,
4080 &linked_xfb
->Buffers
[i
], 0))
4086 int top_level_array_base_offset
= -1;
4087 int top_level_array_size_in_bytes
= -1;
4088 int second_element_offset
= -1;
4089 int buffer_block_index
= -1;
4091 /* Add uniforms from uniform storage. */
4092 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4093 /* Do not add uniforms internally used by Mesa. */
4094 if (shProg
->data
->UniformStorage
[i
].hidden
)
4097 bool is_shader_storage
=
4098 shProg
->data
->UniformStorage
[i
].is_shader_storage
;
4099 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
4100 if (!link_util_should_add_buffer_variable(shProg
,
4101 &shProg
->data
->UniformStorage
[i
],
4102 top_level_array_base_offset
,
4103 top_level_array_size_in_bytes
,
4104 second_element_offset
,
4105 buffer_block_index
))
4108 if (is_shader_storage
) {
4109 /* From the OpenGL 4.6 specification, 7.3.1.1 Naming Active Resources:
4111 * "For an active shader storage block member declared as an array
4112 * of an aggregate type, an entry will be generated only for the
4113 * first array element, regardless of its type. Such block members
4114 * are referred to as top-level arrays. If the block member is an
4115 * aggregate type, the enumeration rules are then applied
4118 * Below we update our tracking values used by
4119 * link_util_should_add_buffer_variable(). We only want to reset the
4120 * offsets once we have moved past the first element.
4122 if (shProg
->data
->UniformStorage
[i
].offset
>= second_element_offset
) {
4123 top_level_array_base_offset
=
4124 shProg
->data
->UniformStorage
[i
].offset
;
4126 top_level_array_size_in_bytes
=
4127 shProg
->data
->UniformStorage
[i
].top_level_array_size
*
4128 shProg
->data
->UniformStorage
[i
].top_level_array_stride
;
4130 /* Set or reset the second element offset. For non arrays this
4131 * will be set to -1.
4133 second_element_offset
= top_level_array_size_in_bytes
?
4134 top_level_array_base_offset
+
4135 shProg
->data
->UniformStorage
[i
].top_level_array_stride
: -1;
4138 buffer_block_index
= shProg
->data
->UniformStorage
[i
].block_index
;
4141 uint8_t stageref
= shProg
->data
->UniformStorage
[i
].active_shader_mask
;
4142 if (!link_util_add_program_resource(shProg
, resource_set
, type
,
4143 &shProg
->data
->UniformStorage
[i
], stageref
))
4147 /* Add program uniform blocks. */
4148 for (unsigned i
= 0; i
< shProg
->data
->NumUniformBlocks
; i
++) {
4149 if (!link_util_add_program_resource(shProg
, resource_set
, GL_UNIFORM_BLOCK
,
4150 &shProg
->data
->UniformBlocks
[i
], 0))
4154 /* Add program shader storage blocks. */
4155 for (unsigned i
= 0; i
< shProg
->data
->NumShaderStorageBlocks
; i
++) {
4156 if (!link_util_add_program_resource(shProg
, resource_set
, GL_SHADER_STORAGE_BLOCK
,
4157 &shProg
->data
->ShaderStorageBlocks
[i
], 0))
4161 /* Add atomic counter buffers. */
4162 for (unsigned i
= 0; i
< shProg
->data
->NumAtomicBuffers
; i
++) {
4163 if (!link_util_add_program_resource(shProg
, resource_set
, GL_ATOMIC_COUNTER_BUFFER
,
4164 &shProg
->data
->AtomicBuffers
[i
], 0))
4168 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4170 if (!shProg
->data
->UniformStorage
[i
].hidden
)
4173 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
4174 if (!shProg
->data
->UniformStorage
[i
].opaque
[j
].active
||
4175 !shProg
->data
->UniformStorage
[i
].type
->is_subroutine())
4178 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
4179 /* add shader subroutines */
4180 if (!link_util_add_program_resource(shProg
, resource_set
,
4181 type
, &shProg
->data
->UniformStorage
[i
], 0))
4186 unsigned mask
= shProg
->data
->linked_stages
;
4188 const int i
= u_bit_scan(&mask
);
4189 struct gl_program
*p
= shProg
->_LinkedShaders
[i
]->Program
;
4191 GLuint type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
4192 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4193 if (!link_util_add_program_resource(shProg
, resource_set
,
4194 type
, &p
->sh
.SubroutineFunctions
[j
], 0))
4199 _mesa_set_destroy(resource_set
, NULL
);
4203 * This check is done to make sure we allow only constant expression
4204 * indexing and "constant-index-expression" (indexing with an expression
4205 * that includes loop induction variable).
4208 validate_sampler_array_indexing(struct gl_context
*ctx
,
4209 struct gl_shader_program
*prog
)
4211 dynamic_sampler_array_indexing_visitor v
;
4212 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4213 if (prog
->_LinkedShaders
[i
] == NULL
)
4216 bool no_dynamic_indexing
=
4217 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
4219 /* Search for array derefs in shader. */
4220 v
.run(prog
->_LinkedShaders
[i
]->ir
);
4221 if (v
.uses_dynamic_sampler_array_indexing()) {
4222 const char *msg
= "sampler arrays indexed with non-constant "
4223 "expressions is forbidden in GLSL %s %u";
4224 /* Backend has indicated that it has no dynamic indexing support. */
4225 if (no_dynamic_indexing
) {
4226 linker_error(prog
, msg
, prog
->IsES
? "ES" : "",
4227 prog
->data
->Version
);
4230 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "",
4231 prog
->data
->Version
);
4239 link_assign_subroutine_types(struct gl_shader_program
*prog
)
4241 unsigned mask
= prog
->data
->linked_stages
;
4243 const int i
= u_bit_scan(&mask
);
4244 gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
4246 p
->sh
.MaxSubroutineFunctionIndex
= 0;
4247 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
4248 ir_function
*fn
= node
->as_function();
4252 if (fn
->is_subroutine
)
4253 p
->sh
.NumSubroutineUniformTypes
++;
4255 if (!fn
->num_subroutine_types
)
4258 /* these should have been calculated earlier. */
4259 assert(fn
->subroutine_index
!= -1);
4260 if (p
->sh
.NumSubroutineFunctions
+ 1 > MAX_SUBROUTINES
) {
4261 linker_error(prog
, "Too many subroutine functions declared.\n");
4264 p
->sh
.SubroutineFunctions
= reralloc(p
, p
->sh
.SubroutineFunctions
,
4265 struct gl_subroutine_function
,
4266 p
->sh
.NumSubroutineFunctions
+ 1);
4267 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].name
= ralloc_strdup(p
, fn
->name
);
4268 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
4269 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
=
4270 ralloc_array(p
, const struct glsl_type
*,
4271 fn
->num_subroutine_types
);
4273 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4276 * "Each subroutine with an index qualifier in the shader must be
4277 * given a unique index, otherwise a compile or link error will be
4280 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4281 if (p
->sh
.SubroutineFunctions
[j
].index
!= -1 &&
4282 p
->sh
.SubroutineFunctions
[j
].index
== fn
->subroutine_index
) {
4283 linker_error(prog
, "each subroutine index qualifier in the "
4284 "shader must be unique\n");
4288 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].index
=
4289 fn
->subroutine_index
;
4291 if (fn
->subroutine_index
> (int)p
->sh
.MaxSubroutineFunctionIndex
)
4292 p
->sh
.MaxSubroutineFunctionIndex
= fn
->subroutine_index
;
4294 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
4295 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
4296 p
->sh
.NumSubroutineFunctions
++;
4302 verify_subroutine_associated_funcs(struct gl_shader_program
*prog
)
4304 unsigned mask
= prog
->data
->linked_stages
;
4306 const int i
= u_bit_scan(&mask
);
4307 gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
4308 glsl_symbol_table
*symbols
= prog
->_LinkedShaders
[i
]->symbols
;
4310 /* Section 6.1.2 (Subroutines) of the GLSL 4.00 spec says:
4312 * "A program will fail to compile or link if any shader
4313 * or stage contains two or more functions with the same
4314 * name if the name is associated with a subroutine type."
4316 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4317 unsigned definitions
= 0;
4318 char *name
= p
->sh
.SubroutineFunctions
[j
].name
;
4319 ir_function
*fn
= symbols
->get_function(name
);
4321 /* Calculate number of function definitions with the same name */
4322 foreach_in_list(ir_function_signature
, sig
, &fn
->signatures
) {
4323 if (sig
->is_defined
) {
4324 if (++definitions
> 1) {
4325 linker_error(prog
, "%s shader contains two or more function "
4326 "definitions with name `%s', which is "
4327 "associated with a subroutine type.\n",
4328 _mesa_shader_stage_to_string(i
),
4340 set_always_active_io(exec_list
*ir
, ir_variable_mode io_mode
)
4342 assert(io_mode
== ir_var_shader_in
|| io_mode
== ir_var_shader_out
);
4344 foreach_in_list(ir_instruction
, node
, ir
) {
4345 ir_variable
*const var
= node
->as_variable();
4347 if (var
== NULL
|| var
->data
.mode
!= io_mode
)
4350 /* Don't set always active on builtins that haven't been redeclared */
4351 if (var
->data
.how_declared
== ir_var_declared_implicitly
)
4354 var
->data
.always_active_io
= true;
4359 * When separate shader programs are enabled, only input/outputs between
4360 * the stages of a multi-stage separate program can be safely removed
4361 * from the shader interface. Other inputs/outputs must remain active.
4364 disable_varying_optimizations_for_sso(struct gl_shader_program
*prog
)
4366 unsigned first
, last
;
4367 assert(prog
->SeparateShader
);
4369 first
= MESA_SHADER_STAGES
;
4372 /* Determine first and last stage. Excluding the compute stage */
4373 for (unsigned i
= 0; i
< MESA_SHADER_COMPUTE
; i
++) {
4374 if (!prog
->_LinkedShaders
[i
])
4376 if (first
== MESA_SHADER_STAGES
)
4381 if (first
== MESA_SHADER_STAGES
)
4384 for (unsigned stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4385 gl_linked_shader
*sh
= prog
->_LinkedShaders
[stage
];
4389 /* Prevent the removal of inputs to the first and outputs from the last
4390 * stage, unless they are the initial pipeline inputs or final pipeline
4391 * outputs, respectively.
4393 * The removal of IO between shaders in the same program is always
4396 if (stage
== first
&& stage
!= MESA_SHADER_VERTEX
)
4397 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4398 if (stage
== last
&& stage
!= MESA_SHADER_FRAGMENT
)
4399 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4404 link_and_validate_uniforms(struct gl_context
*ctx
,
4405 struct gl_shader_program
*prog
)
4407 update_array_sizes(prog
);
4408 link_assign_uniform_locations(prog
, ctx
);
4410 if (prog
->data
->LinkStatus
== LINKING_FAILURE
)
4413 if (!ctx
->Const
.UseNIRGLSLLinker
) {
4414 link_util_calculate_subroutine_compat(prog
);
4415 link_util_check_uniform_resources(ctx
, prog
);
4416 link_util_check_subroutine_resources(prog
);
4417 check_image_resources(ctx
, prog
);
4418 link_assign_atomic_counter_resources(ctx
, prog
);
4419 link_check_atomic_counter_resources(ctx
, prog
);
4424 link_varyings_and_uniforms(unsigned first
, unsigned last
,
4425 struct gl_context
*ctx
,
4426 struct gl_shader_program
*prog
, void *mem_ctx
)
4428 /* Mark all generic shader inputs and outputs as unpaired. */
4429 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4430 if (prog
->_LinkedShaders
[i
] != NULL
) {
4431 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
4435 unsigned prev
= first
;
4436 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4437 if (prog
->_LinkedShaders
[i
] == NULL
)
4440 match_explicit_outputs_to_inputs(prog
->_LinkedShaders
[prev
],
4441 prog
->_LinkedShaders
[i
]);
4445 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4446 MESA_SHADER_VERTEX
, true)) {
4450 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4451 MESA_SHADER_FRAGMENT
, true)) {
4455 prog
->last_vert_prog
= NULL
;
4456 for (int i
= MESA_SHADER_GEOMETRY
; i
>= MESA_SHADER_VERTEX
; i
--) {
4457 if (prog
->_LinkedShaders
[i
] == NULL
)
4460 prog
->last_vert_prog
= prog
->_LinkedShaders
[i
]->Program
;
4464 if (!link_varyings(prog
, first
, last
, ctx
, mem_ctx
))
4467 link_and_validate_uniforms(ctx
, prog
);
4469 if (!prog
->data
->LinkStatus
)
4472 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4473 if (prog
->_LinkedShaders
[i
] == NULL
)
4476 const struct gl_shader_compiler_options
*options
=
4477 &ctx
->Const
.ShaderCompilerOptions
[i
];
4479 if (options
->LowerBufferInterfaceBlocks
)
4480 lower_ubo_reference(prog
->_LinkedShaders
[i
],
4481 options
->ClampBlockIndicesToArrayBounds
,
4482 ctx
->Const
.UseSTD430AsDefaultPacking
);
4484 if (i
== MESA_SHADER_COMPUTE
)
4485 lower_shared_reference(ctx
, prog
, prog
->_LinkedShaders
[i
]);
4487 lower_vector_derefs(prog
->_LinkedShaders
[i
]);
4488 do_vec_index_to_swizzle(prog
->_LinkedShaders
[i
]->ir
);
4495 linker_optimisation_loop(struct gl_context
*ctx
, exec_list
*ir
,
4498 if (ctx
->Const
.GLSLOptimizeConservatively
) {
4499 /* Run it just once. */
4500 do_common_optimization(ir
, true, false,
4501 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4502 ctx
->Const
.NativeIntegers
);
4504 /* Repeat it until it stops making changes. */
4505 while (do_common_optimization(ir
, true, false,
4506 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4507 ctx
->Const
.NativeIntegers
))
4513 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
4515 prog
->data
->LinkStatus
= LINKING_SUCCESS
; /* All error paths will set this to false */
4516 prog
->data
->Validated
= false;
4518 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4520 * "Linking can fail for a variety of reasons as specified in the
4521 * OpenGL Shading Language Specification, as well as any of the
4522 * following reasons:
4524 * - No shader objects are attached to program."
4526 * The Compatibility Profile specification does not list the error. In
4527 * Compatibility Profile missing shader stages are replaced by
4528 * fixed-function. This applies to the case where all stages are
4531 if (prog
->NumShaders
== 0) {
4532 if (ctx
->API
!= API_OPENGL_COMPAT
)
4533 linker_error(prog
, "no shaders attached to the program\n");
4537 #ifdef ENABLE_SHADER_CACHE
4538 if (shader_cache_read_program_metadata(ctx
, prog
))
4542 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
4544 prog
->ARB_fragment_coord_conventions_enable
= false;
4546 /* Separate the shaders into groups based on their type.
4548 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
4549 unsigned num_shaders
[MESA_SHADER_STAGES
];
4551 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4552 shader_list
[i
] = (struct gl_shader
**)
4553 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
4557 unsigned min_version
= UINT_MAX
;
4558 unsigned max_version
= 0;
4559 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
4560 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
4561 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
4563 if (!ctx
->Const
.AllowGLSLRelaxedES
&&
4564 prog
->Shaders
[i
]->IsES
!= prog
->Shaders
[0]->IsES
) {
4565 linker_error(prog
, "all shaders must use same shading "
4566 "language version\n");
4570 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
4571 prog
->ARB_fragment_coord_conventions_enable
= true;
4574 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
4575 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
4576 num_shaders
[shader_type
]++;
4579 /* In desktop GLSL, different shader versions may be linked together. In
4580 * GLSL ES, all shader versions must be the same.
4582 if (!ctx
->Const
.AllowGLSLRelaxedES
&& prog
->Shaders
[0]->IsES
&&
4583 min_version
!= max_version
) {
4584 linker_error(prog
, "all shaders must use same shading "
4585 "language version\n");
4589 prog
->data
->Version
= max_version
;
4590 prog
->IsES
= prog
->Shaders
[0]->IsES
;
4592 /* Some shaders have to be linked with some other shaders present.
4594 if (!prog
->SeparateShader
) {
4595 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
4596 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4597 linker_error(prog
, "Geometry shader must be linked with "
4601 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4602 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4603 linker_error(prog
, "Tessellation evaluation shader must be linked "
4604 "with vertex shader\n");
4607 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4608 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4609 linker_error(prog
, "Tessellation control shader must be linked with "
4614 /* Section 7.3 of the OpenGL ES 3.2 specification says:
4616 * "Linking can fail for [...] any of the following reasons:
4618 * * program contains an object to form a tessellation control
4619 * shader [...] and [...] the program is not separable and
4620 * contains no object to form a tessellation evaluation shader"
4622 * The OpenGL spec is contradictory. It allows linking without a tess
4623 * eval shader, but that can only be used with transform feedback and
4624 * rasterization disabled. However, transform feedback isn't allowed
4625 * with GL_PATCHES, so it can't be used.
4627 * More investigation showed that the idea of transform feedback after
4628 * a tess control shader was dropped, because some hw vendors couldn't
4629 * support tessellation without a tess eval shader, but the linker
4630 * section wasn't updated to reflect that.
4632 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4635 * Do what's reasonable and always require a tess eval shader if a tess
4636 * control shader is present.
4638 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4639 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0) {
4640 linker_error(prog
, "Tessellation control shader must be linked with "
4641 "tessellation evaluation shader\n");
4646 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4647 num_shaders
[MESA_SHADER_TESS_CTRL
] == 0) {
4648 linker_error(prog
, "GLSL ES requires non-separable programs "
4649 "containing a tessellation evaluation shader to also "
4650 "be linked with a tessellation control shader\n");
4656 /* Compute shaders have additional restrictions. */
4657 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
4658 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
4659 linker_error(prog
, "Compute shaders may not be linked with any other "
4660 "type of shader\n");
4663 /* Link all shaders for a particular stage and validate the result.
4665 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4666 if (num_shaders
[stage
] > 0) {
4667 gl_linked_shader
*const sh
=
4668 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
4669 num_shaders
[stage
], false);
4671 if (!prog
->data
->LinkStatus
) {
4673 _mesa_delete_linked_shader(ctx
, sh
);
4678 case MESA_SHADER_VERTEX
:
4679 validate_vertex_shader_executable(prog
, sh
, ctx
);
4681 case MESA_SHADER_TESS_CTRL
:
4682 /* nothing to be done */
4684 case MESA_SHADER_TESS_EVAL
:
4685 validate_tess_eval_shader_executable(prog
, sh
, ctx
);
4687 case MESA_SHADER_GEOMETRY
:
4688 validate_geometry_shader_executable(prog
, sh
, ctx
);
4690 case MESA_SHADER_FRAGMENT
:
4691 validate_fragment_shader_executable(prog
, sh
);
4694 if (!prog
->data
->LinkStatus
) {
4696 _mesa_delete_linked_shader(ctx
, sh
);
4700 prog
->_LinkedShaders
[stage
] = sh
;
4701 prog
->data
->linked_stages
|= 1 << stage
;
4705 /* Here begins the inter-stage linking phase. Some initial validation is
4706 * performed, then locations are assigned for uniforms, attributes, and
4709 cross_validate_uniforms(ctx
, prog
);
4710 if (!prog
->data
->LinkStatus
)
4713 unsigned first
, last
, prev
;
4715 first
= MESA_SHADER_STAGES
;
4718 /* Determine first and last stage. */
4719 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4720 if (!prog
->_LinkedShaders
[i
])
4722 if (first
== MESA_SHADER_STAGES
)
4727 check_explicit_uniform_locations(ctx
, prog
);
4728 link_assign_subroutine_types(prog
);
4729 verify_subroutine_associated_funcs(prog
);
4731 if (!prog
->data
->LinkStatus
)
4734 resize_tes_inputs(ctx
, prog
);
4736 /* Validate the inputs of each stage with the output of the preceding
4740 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4741 if (prog
->_LinkedShaders
[i
] == NULL
)
4744 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
4745 prog
->_LinkedShaders
[i
]);
4746 if (!prog
->data
->LinkStatus
)
4749 cross_validate_outputs_to_inputs(ctx
, prog
,
4750 prog
->_LinkedShaders
[prev
],
4751 prog
->_LinkedShaders
[i
]);
4752 if (!prog
->data
->LinkStatus
)
4758 /* The cross validation of outputs/inputs above validates interstage
4759 * explicit locations. We need to do this also for the inputs in the first
4760 * stage and outputs of the last stage included in the program, since there
4761 * is no cross validation for these.
4763 validate_first_and_last_interface_explicit_locations(ctx
, prog
,
4764 (gl_shader_stage
) first
,
4765 (gl_shader_stage
) last
);
4767 /* Cross-validate uniform blocks between shader stages */
4768 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
);
4769 if (!prog
->data
->LinkStatus
)
4772 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4773 if (prog
->_LinkedShaders
[i
] != NULL
)
4774 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
4777 if (prog
->IsES
&& prog
->data
->Version
== 100)
4778 if (!validate_invariant_builtins(prog
,
4779 prog
->_LinkedShaders
[MESA_SHADER_VERTEX
],
4780 prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]))
4783 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4784 * it before optimization because we want most of the checks to get
4785 * dropped thanks to constant propagation.
4787 * This rule also applies to GLSL ES 3.00.
4789 if (max_version
>= (prog
->IsES
? 300 : 130)) {
4790 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4792 lower_discard_flow(sh
->ir
);
4796 if (prog
->SeparateShader
)
4797 disable_varying_optimizations_for_sso(prog
);
4800 if (!interstage_cross_validate_uniform_blocks(prog
, false))
4804 if (!interstage_cross_validate_uniform_blocks(prog
, true))
4807 /* Do common optimization before assigning storage for attributes,
4808 * uniforms, and varyings. Later optimization could possibly make
4809 * some of that unused.
4811 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4812 if (prog
->_LinkedShaders
[i
] == NULL
)
4815 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
4816 if (!prog
->data
->LinkStatus
)
4819 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerCombinedClipCullDistance
) {
4820 lower_clip_cull_distance(prog
, prog
->_LinkedShaders
[i
]);
4823 if (ctx
->Const
.LowerTessLevel
) {
4824 lower_tess_level(prog
->_LinkedShaders
[i
]);
4827 /* Section 13.46 (Vertex Attribute Aliasing) of the OpenGL ES 3.2
4828 * specification says:
4830 * "In general, the behavior of GLSL ES should not depend on compiler
4831 * optimizations which might be implementation-dependent. Name matching
4832 * rules in most languages, including C++ from which GLSL ES is derived,
4833 * are based on declarations rather than use.
4835 * RESOLUTION: The existence of aliasing is determined by declarations
4836 * present after preprocessing."
4838 * Because of this rule, we do a 'dry-run' of attribute assignment for
4839 * vertex shader inputs here.
4841 if (prog
->IsES
&& i
== MESA_SHADER_VERTEX
) {
4842 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4843 MESA_SHADER_VERTEX
, false)) {
4848 /* Call opts before lowering const arrays to uniforms so we can const
4849 * propagate any elements accessed directly.
4851 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
4853 /* Call opts after lowering const arrays to copy propagate things. */
4854 if (ctx
->Const
.GLSLLowerConstArrays
&&
4855 lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
, i
,
4856 ctx
->Const
.Program
[i
].MaxUniformComponents
))
4857 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
4861 /* Validation for special cases where we allow sampler array indexing
4862 * with loop induction variable. This check emits a warning or error
4863 * depending if backend can handle dynamic indexing.
4865 if ((!prog
->IsES
&& prog
->data
->Version
< 130) ||
4866 (prog
->IsES
&& prog
->data
->Version
< 300)) {
4867 if (!validate_sampler_array_indexing(ctx
, prog
))
4871 /* Check and validate stream emissions in geometry shaders */
4872 validate_geometry_shader_emissions(ctx
, prog
);
4874 store_fragdepth_layout(prog
);
4876 if(!link_varyings_and_uniforms(first
, last
, ctx
, prog
, mem_ctx
))
4879 /* Linking varyings can cause some extra, useless swizzles to be generated
4880 * due to packing and unpacking.
4882 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4883 if (prog
->_LinkedShaders
[i
] == NULL
)
4886 optimize_swizzles(prog
->_LinkedShaders
[i
]->ir
);
4889 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
4890 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
4891 * anything about shader linking when one of the shaders (vertex or
4892 * fragment shader) is absent. So, the extension shouldn't change the
4893 * behavior specified in GLSL specification.
4895 * From OpenGL ES 3.1 specification (7.3 Program Objects):
4896 * "Linking can fail for a variety of reasons as specified in the
4897 * OpenGL ES Shading Language Specification, as well as any of the
4898 * following reasons:
4902 * * program contains objects to form either a vertex shader or
4903 * fragment shader, and program is not separable, and does not
4904 * contain objects to form both a vertex shader and fragment
4907 * However, the only scenario in 3.1+ where we don't require them both is
4908 * when we have a compute shader. For example:
4910 * - No shaders is a link error.
4911 * - Geom or Tess without a Vertex shader is a link error which means we
4912 * always require a Vertex shader and hence a Fragment shader.
4913 * - Finally a Compute shader linked with any other stage is a link error.
4915 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
&&
4916 num_shaders
[MESA_SHADER_COMPUTE
] == 0) {
4917 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
4918 linker_error(prog
, "program lacks a vertex shader\n");
4919 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
4920 linker_error(prog
, "program lacks a fragment shader\n");
4925 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4926 free(shader_list
[i
]);
4927 if (prog
->_LinkedShaders
[i
] == NULL
)
4930 /* Do a final validation step to make sure that the IR wasn't
4931 * invalidated by any modifications performed after intrastage linking.
4933 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
4935 /* Retain any live IR, but trash the rest. */
4936 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
4938 /* The symbol table in the linked shaders may contain references to
4939 * variables that were removed (e.g., unused uniforms). Since it may
4940 * contain junk, there is no possible valid use. Delete it and set the
4943 delete prog
->_LinkedShaders
[i
]->symbols
;
4944 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
4947 ralloc_free(mem_ctx
);