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"
87 #include "main/imports.h"
88 #include "main/shaderobj.h"
89 #include "main/enums.h"
90 #include "main/mtypes.h"
95 struct find_variable
{
99 find_variable(const char *name
) : name(name
), found(false) {}
103 * Visitor that determines whether or not a variable is ever written.
105 * Use \ref find_assignments for convenience.
107 class find_assignment_visitor
: public ir_hierarchical_visitor
{
109 find_assignment_visitor(unsigned num_vars
,
110 find_variable
* const *vars
)
111 : num_variables(num_vars
), num_found(0), variables(vars
)
115 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
117 ir_variable
*const var
= ir
->lhs
->variable_referenced();
119 return check_variable_name(var
->name
);
122 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
124 foreach_two_lists(formal_node
, &ir
->callee
->parameters
,
125 actual_node
, &ir
->actual_parameters
) {
126 ir_rvalue
*param_rval
= (ir_rvalue
*) actual_node
;
127 ir_variable
*sig_param
= (ir_variable
*) formal_node
;
129 if (sig_param
->data
.mode
== ir_var_function_out
||
130 sig_param
->data
.mode
== ir_var_function_inout
) {
131 ir_variable
*var
= param_rval
->variable_referenced();
132 if (var
&& check_variable_name(var
->name
) == visit_stop
)
137 if (ir
->return_deref
!= NULL
) {
138 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
140 if (check_variable_name(var
->name
) == visit_stop
)
144 return visit_continue_with_parent
;
148 ir_visitor_status
check_variable_name(const char *name
)
150 for (unsigned i
= 0; i
< num_variables
; ++i
) {
151 if (strcmp(variables
[i
]->name
, name
) == 0) {
152 if (!variables
[i
]->found
) {
153 variables
[i
]->found
= true;
155 assert(num_found
< num_variables
);
156 if (++num_found
== num_variables
)
163 return visit_continue_with_parent
;
167 unsigned num_variables
; /**< Number of variables to find */
168 unsigned num_found
; /**< Number of variables already found */
169 find_variable
* const *variables
; /**< Variables to find */
173 * Determine whether or not any of NULL-terminated list of variables is ever
177 find_assignments(exec_list
*ir
, find_variable
* const *vars
)
179 unsigned num_variables
= 0;
181 for (find_variable
* const *v
= vars
; *v
; ++v
)
184 find_assignment_visitor
visitor(num_variables
, vars
);
189 * Determine whether or not the given variable is ever written to.
192 find_assignments(exec_list
*ir
, find_variable
*var
)
194 find_assignment_visitor
visitor(1, &var
);
199 * Visitor that determines whether or not a variable is ever read.
201 class find_deref_visitor
: public ir_hierarchical_visitor
{
203 find_deref_visitor(const char *name
)
204 : name(name
), found(false)
209 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
211 if (strcmp(this->name
, ir
->var
->name
) == 0) {
216 return visit_continue
;
219 bool variable_found() const
225 const char *name
; /**< Find writes to a variable with this name. */
226 bool found
; /**< Was a write to the variable found? */
231 * A visitor helper that provides methods for updating the types of
232 * ir_dereferences. Classes that update variable types (say, updating
233 * array sizes) will want to use this so that dereference types stay in sync.
235 class deref_type_updater
: public ir_hierarchical_visitor
{
237 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
239 ir
->type
= ir
->var
->type
;
240 return visit_continue
;
243 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
245 const glsl_type
*const vt
= ir
->array
->type
;
247 ir
->type
= vt
->fields
.array
;
248 return visit_continue
;
251 virtual ir_visitor_status
visit_leave(ir_dereference_record
*ir
)
253 ir
->type
= ir
->record
->type
->fields
.structure
[ir
->field_idx
].type
;
254 return visit_continue
;
259 class array_resize_visitor
: public deref_type_updater
{
261 unsigned num_vertices
;
262 gl_shader_program
*prog
;
263 gl_shader_stage stage
;
265 array_resize_visitor(unsigned num_vertices
,
266 gl_shader_program
*prog
,
267 gl_shader_stage stage
)
269 this->num_vertices
= num_vertices
;
274 virtual ~array_resize_visitor()
279 virtual ir_visitor_status
visit(ir_variable
*var
)
281 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
||
283 return visit_continue
;
285 unsigned size
= var
->type
->length
;
287 if (stage
== MESA_SHADER_GEOMETRY
) {
288 /* Generate a link error if the shader has declared this array with
291 if (!var
->data
.implicit_sized_array
&&
292 size
&& size
!= this->num_vertices
) {
293 linker_error(this->prog
, "size of array %s declared as %u, "
294 "but number of input vertices is %u\n",
295 var
->name
, size
, this->num_vertices
);
296 return visit_continue
;
299 /* Generate a link error if the shader attempts to access an input
300 * array using an index too large for its actual size assigned at
303 if (var
->data
.max_array_access
>= (int)this->num_vertices
) {
304 linker_error(this->prog
, "%s shader accesses element %i of "
305 "%s, but only %i input vertices\n",
306 _mesa_shader_stage_to_string(this->stage
),
307 var
->data
.max_array_access
, var
->name
, this->num_vertices
);
308 return visit_continue
;
312 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
314 var
->data
.max_array_access
= this->num_vertices
- 1;
316 return visit_continue
;
321 * Visitor that determines the highest stream id to which a (geometry) shader
322 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
324 class find_emit_vertex_visitor
: public ir_hierarchical_visitor
{
326 find_emit_vertex_visitor(int max_allowed
)
327 : max_stream_allowed(max_allowed
),
328 invalid_stream_id(0),
329 invalid_stream_id_from_emit_vertex(false),
330 end_primitive_found(false),
331 uses_non_zero_stream(false)
336 virtual ir_visitor_status
visit_leave(ir_emit_vertex
*ir
)
338 int stream_id
= ir
->stream_id();
341 invalid_stream_id
= stream_id
;
342 invalid_stream_id_from_emit_vertex
= true;
346 if (stream_id
> max_stream_allowed
) {
347 invalid_stream_id
= stream_id
;
348 invalid_stream_id_from_emit_vertex
= true;
353 uses_non_zero_stream
= true;
355 return visit_continue
;
358 virtual ir_visitor_status
visit_leave(ir_end_primitive
*ir
)
360 end_primitive_found
= true;
362 int stream_id
= ir
->stream_id();
365 invalid_stream_id
= stream_id
;
366 invalid_stream_id_from_emit_vertex
= false;
370 if (stream_id
> max_stream_allowed
) {
371 invalid_stream_id
= stream_id
;
372 invalid_stream_id_from_emit_vertex
= false;
377 uses_non_zero_stream
= true;
379 return visit_continue
;
384 return invalid_stream_id
!= 0;
387 const char *error_func()
389 return invalid_stream_id_from_emit_vertex
?
390 "EmitStreamVertex" : "EndStreamPrimitive";
395 return invalid_stream_id
;
400 return uses_non_zero_stream
;
403 bool uses_end_primitive()
405 return end_primitive_found
;
409 int max_stream_allowed
;
410 int invalid_stream_id
;
411 bool invalid_stream_id_from_emit_vertex
;
412 bool end_primitive_found
;
413 bool uses_non_zero_stream
;
416 /* Class that finds array derefs and check if indexes are dynamic. */
417 class dynamic_sampler_array_indexing_visitor
: public ir_hierarchical_visitor
420 dynamic_sampler_array_indexing_visitor() :
421 dynamic_sampler_array_indexing(false)
425 ir_visitor_status
visit_enter(ir_dereference_array
*ir
)
427 if (!ir
->variable_referenced())
428 return visit_continue
;
430 if (!ir
->variable_referenced()->type
->contains_sampler())
431 return visit_continue
;
433 if (!ir
->array_index
->constant_expression_value(ralloc_parent(ir
))) {
434 dynamic_sampler_array_indexing
= true;
437 return visit_continue
;
440 bool uses_dynamic_sampler_array_indexing()
442 return dynamic_sampler_array_indexing
;
446 bool dynamic_sampler_array_indexing
;
449 } /* anonymous namespace */
452 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
456 ralloc_strcat(&prog
->data
->InfoLog
, "error: ");
458 ralloc_vasprintf_append(&prog
->data
->InfoLog
, fmt
, ap
);
461 prog
->data
->LinkStatus
= LINKING_FAILURE
;
466 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
470 ralloc_strcat(&prog
->data
->InfoLog
, "warning: ");
472 ralloc_vasprintf_append(&prog
->data
->InfoLog
, fmt
, ap
);
479 * Given a string identifying a program resource, break it into a base name
480 * and an optional array index in square brackets.
482 * If an array index is present, \c out_base_name_end is set to point to the
483 * "[" that precedes the array index, and the array index itself is returned
486 * If no array index is present (or if the array index is negative or
487 * mal-formed), \c out_base_name_end, is set to point to the null terminator
488 * at the end of the input string, and -1 is returned.
490 * Only the final array index is parsed; if the string contains other array
491 * indices (or structure field accesses), they are left in the base name.
493 * No attempt is made to check that the base name is properly formed;
494 * typically the caller will look up the base name in a hash table, so
495 * ill-formed base names simply turn into hash table lookup failures.
498 parse_program_resource_name(const GLchar
*name
,
499 const GLchar
**out_base_name_end
)
501 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
503 * "When an integer array element or block instance number is part of
504 * the name string, it will be specified in decimal form without a "+"
505 * or "-" sign or any extra leading zeroes. Additionally, the name
506 * string will not include white space anywhere in the string."
509 const size_t len
= strlen(name
);
510 *out_base_name_end
= name
+ len
;
512 if (len
== 0 || name
[len
-1] != ']')
515 /* Walk backwards over the string looking for a non-digit character. This
516 * had better be the opening bracket for an array index.
518 * Initially, i specifies the location of the ']'. Since the string may
519 * contain only the ']' charcater, walk backwards very carefully.
522 for (i
= len
- 1; (i
> 0) && isdigit(name
[i
-1]); --i
)
525 if ((i
== 0) || name
[i
-1] != '[')
528 long array_index
= strtol(&name
[i
], NULL
, 10);
532 /* Check for leading zero */
533 if (name
[i
] == '0' && name
[i
+1] != ']')
536 *out_base_name_end
= name
+ (i
- 1);
542 link_invalidate_variable_locations(exec_list
*ir
)
544 foreach_in_list(ir_instruction
, node
, ir
) {
545 ir_variable
*const var
= node
->as_variable();
550 /* Only assign locations for variables that lack an explicit location.
551 * Explicit locations are set for all built-in variables, generic vertex
552 * shader inputs (via layout(location=...)), and generic fragment shader
553 * outputs (also via layout(location=...)).
555 if (!var
->data
.explicit_location
) {
556 var
->data
.location
= -1;
557 var
->data
.location_frac
= 0;
560 /* ir_variable::is_unmatched_generic_inout is used by the linker while
561 * connecting outputs from one stage to inputs of the next stage.
563 if (var
->data
.explicit_location
&&
564 var
->data
.location
< VARYING_SLOT_VAR0
) {
565 var
->data
.is_unmatched_generic_inout
= 0;
567 var
->data
.is_unmatched_generic_inout
= 1;
574 * Set clip_distance_array_size based and cull_distance_array_size on the given
577 * Also check for errors based on incorrect usage of gl_ClipVertex and
578 * gl_ClipDistance and gl_CullDistance.
579 * Additionally test whether the arrays gl_ClipDistance and gl_CullDistance
580 * exceed the maximum size defined by gl_MaxCombinedClipAndCullDistances.
582 * Return false if an error was reported.
585 analyze_clip_cull_usage(struct gl_shader_program
*prog
,
586 struct gl_linked_shader
*shader
,
587 struct gl_context
*ctx
,
588 GLuint
*clip_distance_array_size
,
589 GLuint
*cull_distance_array_size
)
591 *clip_distance_array_size
= 0;
592 *cull_distance_array_size
= 0;
594 if (prog
->data
->Version
>= (prog
->IsES
? 300 : 130)) {
595 /* From section 7.1 (Vertex Shader Special Variables) of the
598 * "It is an error for a shader to statically write both
599 * gl_ClipVertex and gl_ClipDistance."
601 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
602 * gl_ClipVertex nor gl_ClipDistance. However with
603 * GL_EXT_clip_cull_distance, this functionality is exposed in ES 3.0.
605 find_variable
gl_ClipDistance("gl_ClipDistance");
606 find_variable
gl_CullDistance("gl_CullDistance");
607 find_variable
gl_ClipVertex("gl_ClipVertex");
608 find_variable
* const variables
[] = {
611 !prog
->IsES
? &gl_ClipVertex
: NULL
,
614 find_assignments(shader
->ir
, variables
);
616 /* From the ARB_cull_distance spec:
618 * It is a compile-time or link-time error for the set of shaders forming
619 * a program to statically read or write both gl_ClipVertex and either
620 * gl_ClipDistance or gl_CullDistance.
622 * This does not apply to GLSL ES shaders, since GLSL ES doesn't define
626 if (gl_ClipVertex
.found
&& gl_ClipDistance
.found
) {
627 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
628 "and `gl_ClipDistance'\n",
629 _mesa_shader_stage_to_string(shader
->Stage
));
632 if (gl_ClipVertex
.found
&& gl_CullDistance
.found
) {
633 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
634 "and `gl_CullDistance'\n",
635 _mesa_shader_stage_to_string(shader
->Stage
));
640 if (gl_ClipDistance
.found
) {
641 ir_variable
*clip_distance_var
=
642 shader
->symbols
->get_variable("gl_ClipDistance");
643 assert(clip_distance_var
);
644 *clip_distance_array_size
= clip_distance_var
->type
->length
;
646 if (gl_CullDistance
.found
) {
647 ir_variable
*cull_distance_var
=
648 shader
->symbols
->get_variable("gl_CullDistance");
649 assert(cull_distance_var
);
650 *cull_distance_array_size
= cull_distance_var
->type
->length
;
652 /* From the ARB_cull_distance spec:
654 * It is a compile-time or link-time error for the set of shaders forming
655 * a program to have the sum of the sizes of the gl_ClipDistance and
656 * gl_CullDistance arrays to be larger than
657 * gl_MaxCombinedClipAndCullDistances.
659 if ((*clip_distance_array_size
+ *cull_distance_array_size
) >
660 ctx
->Const
.MaxClipPlanes
) {
661 linker_error(prog
, "%s shader: the combined size of "
662 "'gl_ClipDistance' and 'gl_CullDistance' size cannot "
664 "gl_MaxCombinedClipAndCullDistances (%u)",
665 _mesa_shader_stage_to_string(shader
->Stage
),
666 ctx
->Const
.MaxClipPlanes
);
673 * Verify that a vertex shader executable meets all semantic requirements.
675 * Also sets info.clip_distance_array_size and
676 * info.cull_distance_array_size as a side effect.
678 * \param shader Vertex shader executable to be verified
681 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
682 struct gl_linked_shader
*shader
,
683 struct gl_context
*ctx
)
688 /* From the GLSL 1.10 spec, page 48:
690 * "The variable gl_Position is available only in the vertex
691 * language and is intended for writing the homogeneous vertex
692 * position. All executions of a well-formed vertex shader
693 * executable must write a value into this variable. [...] The
694 * variable gl_Position is available only in the vertex
695 * language and is intended for writing the homogeneous vertex
696 * position. All executions of a well-formed vertex shader
697 * executable must write a value into this variable."
699 * while in GLSL 1.40 this text is changed to:
701 * "The variable gl_Position is available only in the vertex
702 * language and is intended for writing the homogeneous vertex
703 * position. It can be written at any time during shader
704 * execution. It may also be read back by a vertex shader
705 * after being written. This value will be used by primitive
706 * assembly, clipping, culling, and other fixed functionality
707 * operations, if present, that operate on primitives after
708 * vertex processing has occurred. Its value is undefined if
709 * the vertex shader executable does not write gl_Position."
711 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
712 * gl_Position is not an error.
714 if (prog
->data
->Version
< (prog
->IsES
? 300 : 140)) {
715 find_variable
gl_Position("gl_Position");
716 find_assignments(shader
->ir
, &gl_Position
);
717 if (!gl_Position
.found
) {
720 "vertex shader does not write to `gl_Position'. "
721 "Its value is undefined. \n");
724 "vertex shader does not write to `gl_Position'. \n");
730 analyze_clip_cull_usage(prog
, shader
, ctx
,
731 &shader
->Program
->info
.clip_distance_array_size
,
732 &shader
->Program
->info
.cull_distance_array_size
);
736 validate_tess_eval_shader_executable(struct gl_shader_program
*prog
,
737 struct gl_linked_shader
*shader
,
738 struct gl_context
*ctx
)
743 analyze_clip_cull_usage(prog
, shader
, ctx
,
744 &shader
->Program
->info
.clip_distance_array_size
,
745 &shader
->Program
->info
.cull_distance_array_size
);
750 * Verify that a fragment shader executable meets all semantic requirements
752 * \param shader Fragment shader executable to be verified
755 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
756 struct gl_linked_shader
*shader
)
761 find_variable
gl_FragColor("gl_FragColor");
762 find_variable
gl_FragData("gl_FragData");
763 find_variable
* const variables
[] = { &gl_FragColor
, &gl_FragData
, NULL
};
764 find_assignments(shader
->ir
, variables
);
766 if (gl_FragColor
.found
&& gl_FragData
.found
) {
767 linker_error(prog
, "fragment shader writes to both "
768 "`gl_FragColor' and `gl_FragData'\n");
773 * Verify that a geometry shader executable meets all semantic requirements
775 * Also sets prog->Geom.VerticesIn, and info.clip_distance_array_sizeand
776 * info.cull_distance_array_size as a side effect.
778 * \param shader Geometry shader executable to be verified
781 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
782 struct gl_linked_shader
*shader
,
783 struct gl_context
*ctx
)
788 unsigned num_vertices
=
789 vertices_per_prim(shader
->Program
->info
.gs
.input_primitive
);
790 prog
->Geom
.VerticesIn
= num_vertices
;
792 analyze_clip_cull_usage(prog
, shader
, ctx
,
793 &shader
->Program
->info
.clip_distance_array_size
,
794 &shader
->Program
->info
.cull_distance_array_size
);
798 * Check if geometry shaders emit to non-zero streams and do corresponding
802 validate_geometry_shader_emissions(struct gl_context
*ctx
,
803 struct gl_shader_program
*prog
)
805 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
];
808 find_emit_vertex_visitor
emit_vertex(ctx
->Const
.MaxVertexStreams
- 1);
809 emit_vertex
.run(sh
->ir
);
810 if (emit_vertex
.error()) {
811 linker_error(prog
, "Invalid call %s(%d). Accepted values for the "
812 "stream parameter are in the range [0, %d].\n",
813 emit_vertex
.error_func(),
814 emit_vertex
.error_stream(),
815 ctx
->Const
.MaxVertexStreams
- 1);
817 prog
->Geom
.UsesStreams
= emit_vertex
.uses_streams();
818 prog
->Geom
.UsesEndPrimitive
= emit_vertex
.uses_end_primitive();
820 /* From the ARB_gpu_shader5 spec:
822 * "Multiple vertex streams are supported only if the output primitive
823 * type is declared to be "points". A program will fail to link if it
824 * contains a geometry shader calling EmitStreamVertex() or
825 * EndStreamPrimitive() if its output primitive type is not "points".
827 * However, in the same spec:
829 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
830 * with <stream> set to zero."
834 * "The function EndPrimitive() is equivalent to calling
835 * EndStreamPrimitive() with <stream> set to zero."
837 * Since we can call EmitVertex() and EndPrimitive() when we output
838 * primitives other than points, calling EmitStreamVertex(0) or
839 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
840 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
841 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
844 if (prog
->Geom
.UsesStreams
&&
845 sh
->Program
->info
.gs
.output_primitive
!= GL_POINTS
) {
846 linker_error(prog
, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
847 "with n>0 requires point output\n");
853 validate_intrastage_arrays(struct gl_shader_program
*prog
,
854 ir_variable
*const var
,
855 ir_variable
*const existing
)
857 /* Consider the types to be "the same" if both types are arrays
858 * of the same type and one of the arrays is implicitly sized.
859 * In addition, set the type of the linked variable to the
860 * explicitly sized array.
862 if (var
->type
->is_array() && existing
->type
->is_array()) {
863 if ((var
->type
->fields
.array
== existing
->type
->fields
.array
) &&
864 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
865 if (var
->type
->length
!= 0) {
866 if ((int)var
->type
->length
<= existing
->data
.max_array_access
) {
867 linker_error(prog
, "%s `%s' declared as type "
868 "`%s' but outermost dimension has an index"
871 var
->name
, var
->type
->name
,
872 existing
->data
.max_array_access
);
874 existing
->type
= var
->type
;
876 } else if (existing
->type
->length
!= 0) {
877 if((int)existing
->type
->length
<= var
->data
.max_array_access
&&
878 !existing
->data
.from_ssbo_unsized_array
) {
879 linker_error(prog
, "%s `%s' declared as type "
880 "`%s' but outermost dimension has an index"
883 var
->name
, existing
->type
->name
,
884 var
->data
.max_array_access
);
895 * Perform validation of global variables used across multiple shaders
898 cross_validate_globals(struct gl_context
*ctx
, struct gl_shader_program
*prog
,
899 struct exec_list
*ir
, glsl_symbol_table
*variables
,
902 foreach_in_list(ir_instruction
, node
, ir
) {
903 ir_variable
*const var
= node
->as_variable();
908 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
911 /* don't cross validate subroutine uniforms */
912 if (var
->type
->contains_subroutine())
915 /* Don't cross validate interface instances. These are only relevant
916 * inside a shader. The cross validation is done at the Interface Block
919 if (var
->is_interface_instance())
922 /* Don't cross validate temporaries that are at global scope. These
923 * will eventually get pulled into the shaders 'main'.
925 if (var
->data
.mode
== ir_var_temporary
)
928 /* If a global with this name has already been seen, verify that the
929 * new instance has the same type. In addition, if the globals have
930 * initializers, the values of the initializers must be the same.
932 ir_variable
*const existing
= variables
->get_variable(var
->name
);
933 if (existing
!= NULL
) {
934 /* Check if types match. */
935 if (var
->type
!= existing
->type
) {
936 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
937 /* If it is an unsized array in a Shader Storage Block,
938 * two different shaders can access to different elements.
939 * Because of that, they might be converted to different
940 * sized arrays, then check that they are compatible but
941 * ignore the array size.
943 if (!(var
->data
.mode
== ir_var_shader_storage
&&
944 var
->data
.from_ssbo_unsized_array
&&
945 existing
->data
.mode
== ir_var_shader_storage
&&
946 existing
->data
.from_ssbo_unsized_array
&&
947 var
->type
->gl_type
== existing
->type
->gl_type
)) {
948 linker_error(prog
, "%s `%s' declared as type "
949 "`%s' and type `%s'\n",
951 var
->name
, var
->type
->name
,
952 existing
->type
->name
);
958 if (var
->data
.explicit_location
) {
959 if (existing
->data
.explicit_location
960 && (var
->data
.location
!= existing
->data
.location
)) {
961 linker_error(prog
, "explicit locations for %s "
962 "`%s' have differing values\n",
963 mode_string(var
), var
->name
);
967 if (var
->data
.location_frac
!= existing
->data
.location_frac
) {
968 linker_error(prog
, "explicit components for %s `%s' have "
969 "differing values\n", mode_string(var
), var
->name
);
973 existing
->data
.location
= var
->data
.location
;
974 existing
->data
.explicit_location
= true;
976 /* Check if uniform with implicit location was marked explicit
977 * by earlier shader stage. If so, mark it explicit in this stage
978 * too to make sure later processing does not treat it as
981 if (existing
->data
.explicit_location
) {
982 var
->data
.location
= existing
->data
.location
;
983 var
->data
.explicit_location
= true;
987 /* From the GLSL 4.20 specification:
988 * "A link error will result if two compilation units in a program
989 * specify different integer-constant bindings for the same
990 * opaque-uniform name. However, it is not an error to specify a
991 * binding on some but not all declarations for the same name"
993 if (var
->data
.explicit_binding
) {
994 if (existing
->data
.explicit_binding
&&
995 var
->data
.binding
!= existing
->data
.binding
) {
996 linker_error(prog
, "explicit bindings for %s "
997 "`%s' have differing values\n",
998 mode_string(var
), var
->name
);
1002 existing
->data
.binding
= var
->data
.binding
;
1003 existing
->data
.explicit_binding
= true;
1006 if (var
->type
->contains_atomic() &&
1007 var
->data
.offset
!= existing
->data
.offset
) {
1008 linker_error(prog
, "offset specifications for %s "
1009 "`%s' have differing values\n",
1010 mode_string(var
), var
->name
);
1014 /* Validate layout qualifiers for gl_FragDepth.
1016 * From the AMD/ARB_conservative_depth specs:
1018 * "If gl_FragDepth is redeclared in any fragment shader in a
1019 * program, it must be redeclared in all fragment shaders in
1020 * that program that have static assignments to
1021 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1022 * fragment shaders in a single program must have the same set
1025 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1026 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1027 bool layout_differs
=
1028 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1030 if (layout_declared
&& layout_differs
) {
1032 "All redeclarations of gl_FragDepth in all "
1033 "fragment shaders in a single program must have "
1034 "the same set of qualifiers.\n");
1037 if (var
->data
.used
&& layout_differs
) {
1039 "If gl_FragDepth is redeclared with a layout "
1040 "qualifier in any fragment shader, it must be "
1041 "redeclared with the same layout qualifier in "
1042 "all fragment shaders that have assignments to "
1047 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1049 * "If a shared global has multiple initializers, the
1050 * initializers must all be constant expressions, and they
1051 * must all have the same value. Otherwise, a link error will
1052 * result. (A shared global having only one initializer does
1053 * not require that initializer to be a constant expression.)"
1055 * Previous to 4.20 the GLSL spec simply said that initializers
1056 * must have the same value. In this case of non-constant
1057 * initializers, this was impossible to determine. As a result,
1058 * no vendor actually implemented that behavior. The 4.20
1059 * behavior matches the implemented behavior of at least one other
1060 * vendor, so we'll implement that for all GLSL versions.
1062 if (var
->constant_initializer
!= NULL
) {
1063 if (existing
->constant_initializer
!= NULL
) {
1064 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1065 linker_error(prog
, "initializers for %s "
1066 "`%s' have differing values\n",
1067 mode_string(var
), var
->name
);
1071 /* If the first-seen instance of a particular uniform did
1072 * not have an initializer but a later instance does,
1073 * replace the former with the later.
1075 variables
->replace_variable(existing
->name
, var
);
1079 if (var
->data
.has_initializer
) {
1080 if (existing
->data
.has_initializer
1081 && (var
->constant_initializer
== NULL
1082 || existing
->constant_initializer
== NULL
)) {
1084 "shared global variable `%s' has multiple "
1085 "non-constant initializers.\n",
1091 if (existing
->data
.invariant
!= var
->data
.invariant
) {
1092 linker_error(prog
, "declarations for %s `%s' have "
1093 "mismatching invariant qualifiers\n",
1094 mode_string(var
), var
->name
);
1097 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1098 linker_error(prog
, "declarations for %s `%s' have "
1099 "mismatching centroid qualifiers\n",
1100 mode_string(var
), var
->name
);
1103 if (existing
->data
.sample
!= var
->data
.sample
) {
1104 linker_error(prog
, "declarations for %s `%s` have "
1105 "mismatching sample qualifiers\n",
1106 mode_string(var
), var
->name
);
1109 if (existing
->data
.image_format
!= var
->data
.image_format
) {
1110 linker_error(prog
, "declarations for %s `%s` have "
1111 "mismatching image format qualifiers\n",
1112 mode_string(var
), var
->name
);
1116 /* Check the precision qualifier matches for uniform variables on
1119 if (!ctx
->Const
.AllowGLSLRelaxedES
&&
1120 prog
->IsES
&& !var
->get_interface_type() &&
1121 existing
->data
.precision
!= var
->data
.precision
) {
1122 if ((existing
->data
.used
&& var
->data
.used
) || prog
->data
->Version
>= 300) {
1123 linker_error(prog
, "declarations for %s `%s` have "
1124 "mismatching precision qualifiers\n",
1125 mode_string(var
), var
->name
);
1128 linker_warning(prog
, "declarations for %s `%s` have "
1129 "mismatching precision qualifiers\n",
1130 mode_string(var
), var
->name
);
1134 /* In OpenGL GLSL 3.20 spec, section 4.3.9:
1136 * "It is a link-time error if any particular shader interface
1139 * - two different blocks, each having no instance name, and each
1140 * having a member of the same name, or
1142 * - a variable outside a block, and a block with no instance name,
1143 * where the variable has the same name as a member in the block."
1145 const glsl_type
*var_itype
= var
->get_interface_type();
1146 const glsl_type
*existing_itype
= existing
->get_interface_type();
1147 if (var_itype
!= existing_itype
) {
1148 if (!var_itype
|| !existing_itype
) {
1149 linker_error(prog
, "declarations for %s `%s` are inside block "
1150 "`%s` and outside a block",
1151 mode_string(var
), var
->name
,
1152 var_itype
? var_itype
->name
: existing_itype
->name
);
1154 } else if (strcmp(var_itype
->name
, existing_itype
->name
) != 0) {
1155 linker_error(prog
, "declarations for %s `%s` are inside blocks "
1157 mode_string(var
), var
->name
,
1158 existing_itype
->name
,
1164 variables
->add_variable(var
);
1170 * Perform validation of uniforms used across multiple shader stages
1173 cross_validate_uniforms(struct gl_context
*ctx
,
1174 struct gl_shader_program
*prog
)
1176 glsl_symbol_table variables
;
1177 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1178 if (prog
->_LinkedShaders
[i
] == NULL
)
1181 cross_validate_globals(ctx
, prog
, prog
->_LinkedShaders
[i
]->ir
,
1187 * Accumulates the array of buffer blocks and checks that all definitions of
1188 * blocks agree on their contents.
1191 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
,
1194 int *InterfaceBlockStageIndex
[MESA_SHADER_STAGES
];
1195 struct gl_uniform_block
*blks
= NULL
;
1196 unsigned *num_blks
= validate_ssbo
? &prog
->data
->NumShaderStorageBlocks
:
1197 &prog
->data
->NumUniformBlocks
;
1199 unsigned max_num_buffer_blocks
= 0;
1200 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1201 if (prog
->_LinkedShaders
[i
]) {
1202 if (validate_ssbo
) {
1203 max_num_buffer_blocks
+=
1204 prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1206 max_num_buffer_blocks
+=
1207 prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1212 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1213 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1215 InterfaceBlockStageIndex
[i
] = new int[max_num_buffer_blocks
];
1216 for (unsigned int j
= 0; j
< max_num_buffer_blocks
; j
++)
1217 InterfaceBlockStageIndex
[i
][j
] = -1;
1222 unsigned sh_num_blocks
;
1223 struct gl_uniform_block
**sh_blks
;
1224 if (validate_ssbo
) {
1225 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1226 sh_blks
= sh
->Program
->sh
.ShaderStorageBlocks
;
1228 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1229 sh_blks
= sh
->Program
->sh
.UniformBlocks
;
1232 for (unsigned int j
= 0; j
< sh_num_blocks
; j
++) {
1233 int index
= link_cross_validate_uniform_block(prog
->data
, &blks
,
1234 num_blks
, sh_blks
[j
]);
1237 linker_error(prog
, "buffer block `%s' has mismatching "
1238 "definitions\n", sh_blks
[j
]->Name
);
1240 for (unsigned k
= 0; k
<= i
; k
++) {
1241 delete[] InterfaceBlockStageIndex
[k
];
1244 /* Reset the block count. This will help avoid various segfaults
1245 * from api calls that assume the array exists due to the count
1252 InterfaceBlockStageIndex
[i
][index
] = j
;
1256 /* Update per stage block pointers to point to the program list.
1257 * FIXME: We should be able to free the per stage blocks here.
1259 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1260 for (unsigned j
= 0; j
< *num_blks
; j
++) {
1261 int stage_index
= InterfaceBlockStageIndex
[i
][j
];
1263 if (stage_index
!= -1) {
1264 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1266 struct gl_uniform_block
**sh_blks
= validate_ssbo
?
1267 sh
->Program
->sh
.ShaderStorageBlocks
:
1268 sh
->Program
->sh
.UniformBlocks
;
1270 blks
[j
].stageref
|= sh_blks
[stage_index
]->stageref
;
1271 sh_blks
[stage_index
] = &blks
[j
];
1276 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1277 delete[] InterfaceBlockStageIndex
[i
];
1281 prog
->data
->ShaderStorageBlocks
= blks
;
1283 prog
->data
->UniformBlocks
= blks
;
1290 * Populates a shaders symbol table with all global declarations
1293 populate_symbol_table(gl_linked_shader
*sh
, glsl_symbol_table
*symbols
)
1295 sh
->symbols
= new(sh
) glsl_symbol_table
;
1297 _mesa_glsl_copy_symbols_from_table(sh
->ir
, symbols
, sh
->symbols
);
1302 * Remap variables referenced in an instruction tree
1304 * This is used when instruction trees are cloned from one shader and placed in
1305 * another. These trees will contain references to \c ir_variable nodes that
1306 * do not exist in the target shader. This function finds these \c ir_variable
1307 * references and replaces the references with matching variables in the target
1310 * If there is no matching variable in the target shader, a clone of the
1311 * \c ir_variable is made and added to the target shader. The new variable is
1312 * added to \b both the instruction stream and the symbol table.
1314 * \param inst IR tree that is to be processed.
1315 * \param symbols Symbol table containing global scope symbols in the
1317 * \param instructions Instruction stream where new variable declarations
1321 remap_variables(ir_instruction
*inst
, struct gl_linked_shader
*target
,
1324 class remap_visitor
: public ir_hierarchical_visitor
{
1326 remap_visitor(struct gl_linked_shader
*target
, hash_table
*temps
)
1328 this->target
= target
;
1329 this->symbols
= target
->symbols
;
1330 this->instructions
= target
->ir
;
1331 this->temps
= temps
;
1334 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1336 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1337 hash_entry
*entry
= _mesa_hash_table_search(temps
, ir
->var
);
1338 ir_variable
*var
= entry
? (ir_variable
*) entry
->data
: NULL
;
1340 assert(var
!= NULL
);
1342 return visit_continue
;
1345 ir_variable
*const existing
=
1346 this->symbols
->get_variable(ir
->var
->name
);
1347 if (existing
!= NULL
)
1350 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1352 this->symbols
->add_variable(copy
);
1353 this->instructions
->push_head(copy
);
1357 return visit_continue
;
1361 struct gl_linked_shader
*target
;
1362 glsl_symbol_table
*symbols
;
1363 exec_list
*instructions
;
1367 remap_visitor
v(target
, temps
);
1374 * Move non-declarations from one instruction stream to another
1376 * The intended usage pattern of this function is to pass the pointer to the
1377 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1378 * pointer) for \c last and \c false for \c make_copies on the first
1379 * call. Successive calls pass the return value of the previous call for
1380 * \c last and \c true for \c make_copies.
1382 * \param instructions Source instruction stream
1383 * \param last Instruction after which new instructions should be
1384 * inserted in the target instruction stream
1385 * \param make_copies Flag selecting whether instructions in \c instructions
1386 * should be copied (via \c ir_instruction::clone) into the
1387 * target list or moved.
1390 * The new "last" instruction in the target instruction stream. This pointer
1391 * is suitable for use as the \c last parameter of a later call to this
1395 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1396 bool make_copies
, gl_linked_shader
*target
)
1398 hash_table
*temps
= NULL
;
1401 temps
= _mesa_hash_table_create(NULL
, _mesa_hash_pointer
,
1402 _mesa_key_pointer_equal
);
1404 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1405 if (inst
->as_function())
1408 ir_variable
*var
= inst
->as_variable();
1409 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1412 assert(inst
->as_assignment()
1414 || inst
->as_if() /* for initializers with the ?: operator */
1415 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1418 inst
= inst
->clone(target
, NULL
);
1421 _mesa_hash_table_insert(temps
, var
, inst
);
1423 remap_variables(inst
, target
, temps
);
1428 last
->insert_after(inst
);
1433 _mesa_hash_table_destroy(temps
, NULL
);
1440 * This class is only used in link_intrastage_shaders() below but declaring
1441 * it inside that function leads to compiler warnings with some versions of
1444 class array_sizing_visitor
: public deref_type_updater
{
1446 array_sizing_visitor()
1447 : mem_ctx(ralloc_context(NULL
)),
1448 unnamed_interfaces(_mesa_hash_table_create(NULL
, _mesa_hash_pointer
,
1449 _mesa_key_pointer_equal
))
1453 ~array_sizing_visitor()
1455 _mesa_hash_table_destroy(this->unnamed_interfaces
, NULL
);
1456 ralloc_free(this->mem_ctx
);
1459 virtual ir_visitor_status
visit(ir_variable
*var
)
1461 const glsl_type
*type_without_array
;
1462 bool implicit_sized_array
= var
->data
.implicit_sized_array
;
1463 fixup_type(&var
->type
, var
->data
.max_array_access
,
1464 var
->data
.from_ssbo_unsized_array
,
1465 &implicit_sized_array
);
1466 var
->data
.implicit_sized_array
= implicit_sized_array
;
1467 type_without_array
= var
->type
->without_array();
1468 if (var
->type
->is_interface()) {
1469 if (interface_contains_unsized_arrays(var
->type
)) {
1470 const glsl_type
*new_type
=
1471 resize_interface_members(var
->type
,
1472 var
->get_max_ifc_array_access(),
1473 var
->is_in_shader_storage_block());
1474 var
->type
= new_type
;
1475 var
->change_interface_type(new_type
);
1477 } else if (type_without_array
->is_interface()) {
1478 if (interface_contains_unsized_arrays(type_without_array
)) {
1479 const glsl_type
*new_type
=
1480 resize_interface_members(type_without_array
,
1481 var
->get_max_ifc_array_access(),
1482 var
->is_in_shader_storage_block());
1483 var
->change_interface_type(new_type
);
1484 var
->type
= update_interface_members_array(var
->type
, new_type
);
1486 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1487 /* Store a pointer to the variable in the unnamed_interfaces
1491 _mesa_hash_table_search(this->unnamed_interfaces
,
1494 ir_variable
**interface_vars
= entry
? (ir_variable
**) entry
->data
: NULL
;
1496 if (interface_vars
== NULL
) {
1497 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1499 _mesa_hash_table_insert(this->unnamed_interfaces
, ifc_type
,
1502 unsigned index
= ifc_type
->field_index(var
->name
);
1503 assert(index
< ifc_type
->length
);
1504 assert(interface_vars
[index
] == NULL
);
1505 interface_vars
[index
] = var
;
1507 return visit_continue
;
1511 * For each unnamed interface block that was discovered while running the
1512 * visitor, adjust the interface type to reflect the newly assigned array
1513 * sizes, and fix up the ir_variable nodes to point to the new interface
1516 void fixup_unnamed_interface_types()
1518 hash_table_call_foreach(this->unnamed_interfaces
,
1519 fixup_unnamed_interface_type
, NULL
);
1524 * If the type pointed to by \c type represents an unsized array, replace
1525 * it with a sized array whose size is determined by max_array_access.
1527 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1528 bool from_ssbo_unsized_array
, bool *implicit_sized
)
1530 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1531 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1532 max_array_access
+ 1);
1533 *implicit_sized
= true;
1534 assert(*type
!= NULL
);
1538 static const glsl_type
*
1539 update_interface_members_array(const glsl_type
*type
,
1540 const glsl_type
*new_interface_type
)
1542 const glsl_type
*element_type
= type
->fields
.array
;
1543 if (element_type
->is_array()) {
1544 const glsl_type
*new_array_type
=
1545 update_interface_members_array(element_type
, new_interface_type
);
1546 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1548 return glsl_type::get_array_instance(new_interface_type
,
1554 * Determine whether the given interface type contains unsized arrays (if
1555 * it doesn't, array_sizing_visitor doesn't need to process it).
1557 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1559 for (unsigned i
= 0; i
< type
->length
; i
++) {
1560 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1561 if (elem_type
->is_unsized_array())
1568 * Create a new interface type based on the given type, with unsized arrays
1569 * replaced by sized arrays whose size is determined by
1570 * max_ifc_array_access.
1572 static const glsl_type
*
1573 resize_interface_members(const glsl_type
*type
,
1574 const int *max_ifc_array_access
,
1577 unsigned num_fields
= type
->length
;
1578 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1579 memcpy(fields
, type
->fields
.structure
,
1580 num_fields
* sizeof(*fields
));
1581 for (unsigned i
= 0; i
< num_fields
; i
++) {
1582 bool implicit_sized_array
= fields
[i
].implicit_sized_array
;
1583 /* If SSBO last member is unsized array, we don't replace it by a sized
1586 if (is_ssbo
&& i
== (num_fields
- 1))
1587 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1588 true, &implicit_sized_array
);
1590 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1591 false, &implicit_sized_array
);
1592 fields
[i
].implicit_sized_array
= implicit_sized_array
;
1594 glsl_interface_packing packing
=
1595 (glsl_interface_packing
) type
->interface_packing
;
1596 bool row_major
= (bool) type
->interface_row_major
;
1597 const glsl_type
*new_ifc_type
=
1598 glsl_type::get_interface_instance(fields
, num_fields
,
1599 packing
, row_major
, type
->name
);
1601 return new_ifc_type
;
1604 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1607 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1608 ir_variable
**interface_vars
= (ir_variable
**) data
;
1609 unsigned num_fields
= ifc_type
->length
;
1610 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1611 memcpy(fields
, ifc_type
->fields
.structure
,
1612 num_fields
* sizeof(*fields
));
1613 bool interface_type_changed
= false;
1614 for (unsigned i
= 0; i
< num_fields
; i
++) {
1615 if (interface_vars
[i
] != NULL
&&
1616 fields
[i
].type
!= interface_vars
[i
]->type
) {
1617 fields
[i
].type
= interface_vars
[i
]->type
;
1618 interface_type_changed
= true;
1621 if (!interface_type_changed
) {
1625 glsl_interface_packing packing
=
1626 (glsl_interface_packing
) ifc_type
->interface_packing
;
1627 bool row_major
= (bool) ifc_type
->interface_row_major
;
1628 const glsl_type
*new_ifc_type
=
1629 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1630 row_major
, ifc_type
->name
);
1632 for (unsigned i
= 0; i
< num_fields
; i
++) {
1633 if (interface_vars
[i
] != NULL
)
1634 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1639 * Memory context used to allocate the data in \c unnamed_interfaces.
1644 * Hash table from const glsl_type * to an array of ir_variable *'s
1645 * pointing to the ir_variables constituting each unnamed interface block.
1647 hash_table
*unnamed_interfaces
;
1651 validate_xfb_buffer_stride(struct gl_context
*ctx
, unsigned idx
,
1652 struct gl_shader_program
*prog
)
1654 /* We will validate doubles at a later stage */
1655 if (prog
->TransformFeedback
.BufferStride
[idx
] % 4) {
1656 linker_error(prog
, "invalid qualifier xfb_stride=%d must be a "
1657 "multiple of 4 or if its applied to a type that is "
1658 "or contains a double a multiple of 8.",
1659 prog
->TransformFeedback
.BufferStride
[idx
]);
1663 if (prog
->TransformFeedback
.BufferStride
[idx
] / 4 >
1664 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1665 linker_error(prog
, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1666 "limit has been exceeded.");
1674 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1678 link_xfb_stride_layout_qualifiers(struct gl_context
*ctx
,
1679 struct gl_shader_program
*prog
,
1680 struct gl_shader
**shader_list
,
1681 unsigned num_shaders
)
1683 for (unsigned i
= 0; i
< MAX_FEEDBACK_BUFFERS
; i
++) {
1684 prog
->TransformFeedback
.BufferStride
[i
] = 0;
1687 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1688 struct gl_shader
*shader
= shader_list
[i
];
1690 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1691 if (shader
->TransformFeedbackBufferStride
[j
]) {
1692 if (prog
->TransformFeedback
.BufferStride
[j
] == 0) {
1693 prog
->TransformFeedback
.BufferStride
[j
] =
1694 shader
->TransformFeedbackBufferStride
[j
];
1695 if (!validate_xfb_buffer_stride(ctx
, j
, prog
))
1697 } else if (prog
->TransformFeedback
.BufferStride
[j
] !=
1698 shader
->TransformFeedbackBufferStride
[j
]){
1700 "intrastage shaders defined with conflicting "
1701 "xfb_stride for buffer %d (%d and %d)\n", j
,
1702 prog
->TransformFeedback
.BufferStride
[j
],
1703 shader
->TransformFeedbackBufferStride
[j
]);
1712 * Check for conflicting bindless/bound sampler/image layout qualifiers at
1716 link_bindless_layout_qualifiers(struct gl_shader_program
*prog
,
1717 struct gl_shader
**shader_list
,
1718 unsigned num_shaders
)
1720 bool bindless_sampler
, bindless_image
;
1721 bool bound_sampler
, bound_image
;
1723 bindless_sampler
= bindless_image
= false;
1724 bound_sampler
= bound_image
= false;
1726 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1727 struct gl_shader
*shader
= shader_list
[i
];
1729 if (shader
->bindless_sampler
)
1730 bindless_sampler
= true;
1731 if (shader
->bindless_image
)
1732 bindless_image
= true;
1733 if (shader
->bound_sampler
)
1734 bound_sampler
= true;
1735 if (shader
->bound_image
)
1738 if ((bindless_sampler
&& bound_sampler
) ||
1739 (bindless_image
&& bound_image
)) {
1740 /* From section 4.4.6 of the ARB_bindless_texture spec:
1742 * "If both bindless_sampler and bound_sampler, or bindless_image
1743 * and bound_image, are declared at global scope in any
1744 * compilation unit, a link- time error will be generated."
1746 linker_error(prog
, "both bindless_sampler and bound_sampler, or "
1747 "bindless_image and bound_image, can't be declared at "
1754 * Performs the cross-validation of tessellation control shader vertices and
1755 * layout qualifiers for the attached tessellation control shaders,
1756 * and propagates them to the linked TCS and linked shader program.
1759 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1760 struct gl_program
*gl_prog
,
1761 struct gl_shader
**shader_list
,
1762 unsigned num_shaders
)
1764 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_CTRL
)
1767 gl_prog
->info
.tess
.tcs_vertices_out
= 0;
1769 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1771 * "All tessellation control shader layout declarations in a program
1772 * must specify the same output patch vertex count. There must be at
1773 * least one layout qualifier specifying an output patch vertex count
1774 * in any program containing tessellation control shaders; however,
1775 * such a declaration is not required in all tessellation control
1779 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1780 struct gl_shader
*shader
= shader_list
[i
];
1782 if (shader
->info
.TessCtrl
.VerticesOut
!= 0) {
1783 if (gl_prog
->info
.tess
.tcs_vertices_out
!= 0 &&
1784 gl_prog
->info
.tess
.tcs_vertices_out
!=
1785 (unsigned) shader
->info
.TessCtrl
.VerticesOut
) {
1786 linker_error(prog
, "tessellation control shader defined with "
1787 "conflicting output vertex count (%d and %d)\n",
1788 gl_prog
->info
.tess
.tcs_vertices_out
,
1789 shader
->info
.TessCtrl
.VerticesOut
);
1792 gl_prog
->info
.tess
.tcs_vertices_out
=
1793 shader
->info
.TessCtrl
.VerticesOut
;
1797 /* Just do the intrastage -> interstage propagation right now,
1798 * since we already know we're in the right type of shader program
1801 if (gl_prog
->info
.tess
.tcs_vertices_out
== 0) {
1802 linker_error(prog
, "tessellation control shader didn't declare "
1803 "vertices out layout qualifier\n");
1810 * Performs the cross-validation of tessellation evaluation shader
1811 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1812 * for the attached tessellation evaluation shaders, and propagates them
1813 * to the linked TES and linked shader program.
1816 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1817 struct gl_program
*gl_prog
,
1818 struct gl_shader
**shader_list
,
1819 unsigned num_shaders
)
1821 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_EVAL
)
1824 int point_mode
= -1;
1825 unsigned vertex_order
= 0;
1827 gl_prog
->info
.tess
.primitive_mode
= PRIM_UNKNOWN
;
1828 gl_prog
->info
.tess
.spacing
= TESS_SPACING_UNSPECIFIED
;
1830 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1832 * "At least one tessellation evaluation shader (compilation unit) in
1833 * a program must declare a primitive mode in its input layout.
1834 * Declaration vertex spacing, ordering, and point mode identifiers is
1835 * optional. It is not required that all tessellation evaluation
1836 * shaders in a program declare a primitive mode. If spacing or
1837 * vertex ordering declarations are omitted, the tessellation
1838 * primitive generator will use equal spacing or counter-clockwise
1839 * vertex ordering, respectively. If a point mode declaration is
1840 * omitted, the tessellation primitive generator will produce lines or
1841 * triangles according to the primitive mode."
1844 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1845 struct gl_shader
*shader
= shader_list
[i
];
1847 if (shader
->info
.TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1848 if (gl_prog
->info
.tess
.primitive_mode
!= PRIM_UNKNOWN
&&
1849 gl_prog
->info
.tess
.primitive_mode
!=
1850 shader
->info
.TessEval
.PrimitiveMode
) {
1851 linker_error(prog
, "tessellation evaluation shader defined with "
1852 "conflicting input primitive modes.\n");
1855 gl_prog
->info
.tess
.primitive_mode
=
1856 shader
->info
.TessEval
.PrimitiveMode
;
1859 if (shader
->info
.TessEval
.Spacing
!= 0) {
1860 if (gl_prog
->info
.tess
.spacing
!= 0 && gl_prog
->info
.tess
.spacing
!=
1861 shader
->info
.TessEval
.Spacing
) {
1862 linker_error(prog
, "tessellation evaluation shader defined with "
1863 "conflicting vertex spacing.\n");
1866 gl_prog
->info
.tess
.spacing
= shader
->info
.TessEval
.Spacing
;
1869 if (shader
->info
.TessEval
.VertexOrder
!= 0) {
1870 if (vertex_order
!= 0 &&
1871 vertex_order
!= shader
->info
.TessEval
.VertexOrder
) {
1872 linker_error(prog
, "tessellation evaluation shader defined with "
1873 "conflicting ordering.\n");
1876 vertex_order
= shader
->info
.TessEval
.VertexOrder
;
1879 if (shader
->info
.TessEval
.PointMode
!= -1) {
1880 if (point_mode
!= -1 &&
1881 point_mode
!= shader
->info
.TessEval
.PointMode
) {
1882 linker_error(prog
, "tessellation evaluation shader defined with "
1883 "conflicting point modes.\n");
1886 point_mode
= shader
->info
.TessEval
.PointMode
;
1891 /* Just do the intrastage -> interstage propagation right now,
1892 * since we already know we're in the right type of shader program
1895 if (gl_prog
->info
.tess
.primitive_mode
== PRIM_UNKNOWN
) {
1897 "tessellation evaluation shader didn't declare input "
1898 "primitive modes.\n");
1902 if (gl_prog
->info
.tess
.spacing
== TESS_SPACING_UNSPECIFIED
)
1903 gl_prog
->info
.tess
.spacing
= TESS_SPACING_EQUAL
;
1905 if (vertex_order
== 0 || vertex_order
== GL_CCW
)
1906 gl_prog
->info
.tess
.ccw
= true;
1908 gl_prog
->info
.tess
.ccw
= false;
1911 if (point_mode
== -1 || point_mode
== GL_FALSE
)
1912 gl_prog
->info
.tess
.point_mode
= false;
1914 gl_prog
->info
.tess
.point_mode
= true;
1919 * Performs the cross-validation of layout qualifiers specified in
1920 * redeclaration of gl_FragCoord for the attached fragment shaders,
1921 * and propagates them to the linked FS and linked shader program.
1924 link_fs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1925 struct gl_linked_shader
*linked_shader
,
1926 struct gl_shader
**shader_list
,
1927 unsigned num_shaders
)
1929 bool redeclares_gl_fragcoord
= false;
1930 bool uses_gl_fragcoord
= false;
1931 bool origin_upper_left
= false;
1932 bool pixel_center_integer
= false;
1934 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1935 (prog
->data
->Version
< 150 &&
1936 !prog
->ARB_fragment_coord_conventions_enable
))
1939 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1940 struct gl_shader
*shader
= shader_list
[i
];
1941 /* From the GLSL 1.50 spec, page 39:
1943 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1944 * it must be redeclared in all the fragment shaders in that program
1945 * that have a static use gl_FragCoord."
1947 if ((redeclares_gl_fragcoord
&& !shader
->redeclares_gl_fragcoord
&&
1948 shader
->uses_gl_fragcoord
)
1949 || (shader
->redeclares_gl_fragcoord
&& !redeclares_gl_fragcoord
&&
1950 uses_gl_fragcoord
)) {
1951 linker_error(prog
, "fragment shader defined with conflicting "
1952 "layout qualifiers for gl_FragCoord\n");
1955 /* From the GLSL 1.50 spec, page 39:
1957 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1958 * single program must have the same set of qualifiers."
1960 if (redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
&&
1961 (shader
->origin_upper_left
!= origin_upper_left
||
1962 shader
->pixel_center_integer
!= pixel_center_integer
)) {
1963 linker_error(prog
, "fragment shader defined with conflicting "
1964 "layout qualifiers for gl_FragCoord\n");
1967 /* Update the linked shader state. Note that uses_gl_fragcoord should
1968 * accumulate the results. The other values should replace. If there
1969 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1970 * are already known to be the same.
1972 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
1973 redeclares_gl_fragcoord
= shader
->redeclares_gl_fragcoord
;
1974 uses_gl_fragcoord
|= shader
->uses_gl_fragcoord
;
1975 origin_upper_left
= shader
->origin_upper_left
;
1976 pixel_center_integer
= shader
->pixel_center_integer
;
1979 linked_shader
->Program
->info
.fs
.early_fragment_tests
|=
1980 shader
->EarlyFragmentTests
|| shader
->PostDepthCoverage
;
1981 linked_shader
->Program
->info
.fs
.inner_coverage
|= shader
->InnerCoverage
;
1982 linked_shader
->Program
->info
.fs
.post_depth_coverage
|=
1983 shader
->PostDepthCoverage
;
1984 linked_shader
->Program
->info
.fs
.pixel_interlock_ordered
|=
1985 shader
->PixelInterlockOrdered
;
1986 linked_shader
->Program
->info
.fs
.pixel_interlock_unordered
|=
1987 shader
->PixelInterlockUnordered
;
1988 linked_shader
->Program
->info
.fs
.sample_interlock_ordered
|=
1989 shader
->SampleInterlockOrdered
;
1990 linked_shader
->Program
->info
.fs
.sample_interlock_unordered
|=
1991 shader
->SampleInterlockUnordered
;
1993 linked_shader
->Program
->sh
.fs
.BlendSupport
|= shader
->BlendSupport
;
1998 * Performs the cross-validation of geometry shader max_vertices and
1999 * primitive type layout qualifiers for the attached geometry shaders,
2000 * and propagates them to the linked GS and linked shader program.
2003 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
2004 struct gl_program
*gl_prog
,
2005 struct gl_shader
**shader_list
,
2006 unsigned num_shaders
)
2008 /* No in/out qualifiers defined for anything but GLSL 1.50+
2009 * geometry shaders so far.
2011 if (gl_prog
->info
.stage
!= MESA_SHADER_GEOMETRY
||
2012 prog
->data
->Version
< 150)
2015 int vertices_out
= -1;
2017 gl_prog
->info
.gs
.invocations
= 0;
2018 gl_prog
->info
.gs
.input_primitive
= PRIM_UNKNOWN
;
2019 gl_prog
->info
.gs
.output_primitive
= PRIM_UNKNOWN
;
2021 /* From the GLSL 1.50 spec, page 46:
2023 * "All geometry shader output layout declarations in a program
2024 * must declare the same layout and same value for
2025 * max_vertices. There must be at least one geometry output
2026 * layout declaration somewhere in a program, but not all
2027 * geometry shaders (compilation units) are required to
2031 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2032 struct gl_shader
*shader
= shader_list
[i
];
2034 if (shader
->info
.Geom
.InputType
!= PRIM_UNKNOWN
) {
2035 if (gl_prog
->info
.gs
.input_primitive
!= PRIM_UNKNOWN
&&
2036 gl_prog
->info
.gs
.input_primitive
!=
2037 shader
->info
.Geom
.InputType
) {
2038 linker_error(prog
, "geometry shader defined with conflicting "
2042 gl_prog
->info
.gs
.input_primitive
= shader
->info
.Geom
.InputType
;
2045 if (shader
->info
.Geom
.OutputType
!= PRIM_UNKNOWN
) {
2046 if (gl_prog
->info
.gs
.output_primitive
!= PRIM_UNKNOWN
&&
2047 gl_prog
->info
.gs
.output_primitive
!=
2048 shader
->info
.Geom
.OutputType
) {
2049 linker_error(prog
, "geometry shader defined with conflicting "
2053 gl_prog
->info
.gs
.output_primitive
= shader
->info
.Geom
.OutputType
;
2056 if (shader
->info
.Geom
.VerticesOut
!= -1) {
2057 if (vertices_out
!= -1 &&
2058 vertices_out
!= shader
->info
.Geom
.VerticesOut
) {
2059 linker_error(prog
, "geometry shader defined with conflicting "
2060 "output vertex count (%d and %d)\n",
2061 vertices_out
, shader
->info
.Geom
.VerticesOut
);
2064 vertices_out
= shader
->info
.Geom
.VerticesOut
;
2067 if (shader
->info
.Geom
.Invocations
!= 0) {
2068 if (gl_prog
->info
.gs
.invocations
!= 0 &&
2069 gl_prog
->info
.gs
.invocations
!=
2070 (unsigned) shader
->info
.Geom
.Invocations
) {
2071 linker_error(prog
, "geometry shader defined with conflicting "
2072 "invocation count (%d and %d)\n",
2073 gl_prog
->info
.gs
.invocations
,
2074 shader
->info
.Geom
.Invocations
);
2077 gl_prog
->info
.gs
.invocations
= shader
->info
.Geom
.Invocations
;
2081 /* Just do the intrastage -> interstage propagation right now,
2082 * since we already know we're in the right type of shader program
2085 if (gl_prog
->info
.gs
.input_primitive
== PRIM_UNKNOWN
) {
2087 "geometry shader didn't declare primitive input type\n");
2091 if (gl_prog
->info
.gs
.output_primitive
== PRIM_UNKNOWN
) {
2093 "geometry shader didn't declare primitive output type\n");
2097 if (vertices_out
== -1) {
2099 "geometry shader didn't declare max_vertices\n");
2102 gl_prog
->info
.gs
.vertices_out
= vertices_out
;
2105 if (gl_prog
->info
.gs
.invocations
== 0)
2106 gl_prog
->info
.gs
.invocations
= 1;
2111 * Perform cross-validation of compute shader local_size_{x,y,z} layout
2112 * qualifiers for the attached compute shaders, and propagate them to the
2113 * linked CS and linked shader program.
2116 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
2117 struct gl_program
*gl_prog
,
2118 struct gl_shader
**shader_list
,
2119 unsigned num_shaders
)
2121 /* This function is called for all shader stages, but it only has an effect
2122 * for compute shaders.
2124 if (gl_prog
->info
.stage
!= MESA_SHADER_COMPUTE
)
2127 for (int i
= 0; i
< 3; i
++)
2128 gl_prog
->info
.cs
.local_size
[i
] = 0;
2130 gl_prog
->info
.cs
.local_size_variable
= false;
2132 /* From the ARB_compute_shader spec, in the section describing local size
2135 * If multiple compute shaders attached to a single program object
2136 * declare local work-group size, the declarations must be identical;
2137 * otherwise a link-time error results. Furthermore, if a program
2138 * object contains any compute shaders, at least one must contain an
2139 * input layout qualifier specifying the local work sizes of the
2140 * program, or a link-time error will occur.
2142 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
2143 struct gl_shader
*shader
= shader_list
[sh
];
2145 if (shader
->info
.Comp
.LocalSize
[0] != 0) {
2146 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2147 for (int i
= 0; i
< 3; i
++) {
2148 if (gl_prog
->info
.cs
.local_size
[i
] !=
2149 shader
->info
.Comp
.LocalSize
[i
]) {
2150 linker_error(prog
, "compute shader defined with conflicting "
2156 for (int i
= 0; i
< 3; i
++) {
2157 gl_prog
->info
.cs
.local_size
[i
] =
2158 shader
->info
.Comp
.LocalSize
[i
];
2160 } else if (shader
->info
.Comp
.LocalSizeVariable
) {
2161 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2162 /* The ARB_compute_variable_group_size spec says:
2164 * If one compute shader attached to a program declares a
2165 * variable local group size and a second compute shader
2166 * attached to the same program declares a fixed local group
2167 * size, a link-time error results.
2169 linker_error(prog
, "compute shader defined with both fixed and "
2170 "variable local group size\n");
2173 gl_prog
->info
.cs
.local_size_variable
= true;
2177 /* Just do the intrastage -> interstage propagation right now,
2178 * since we already know we're in the right type of shader program
2181 if (gl_prog
->info
.cs
.local_size
[0] == 0 &&
2182 !gl_prog
->info
.cs
.local_size_variable
) {
2183 linker_error(prog
, "compute shader must contain a fixed or a variable "
2184 "local group size\n");
2191 * Combine a group of shaders for a single stage to generate a linked shader
2194 * If this function is supplied a single shader, it is cloned, and the new
2195 * shader is returned.
2197 struct gl_linked_shader
*
2198 link_intrastage_shaders(void *mem_ctx
,
2199 struct gl_context
*ctx
,
2200 struct gl_shader_program
*prog
,
2201 struct gl_shader
**shader_list
,
2202 unsigned num_shaders
,
2203 bool allow_missing_main
)
2205 struct gl_uniform_block
*ubo_blocks
= NULL
;
2206 struct gl_uniform_block
*ssbo_blocks
= NULL
;
2207 unsigned num_ubo_blocks
= 0;
2208 unsigned num_ssbo_blocks
= 0;
2210 /* Check that global variables defined in multiple shaders are consistent.
2212 glsl_symbol_table variables
;
2213 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2214 if (shader_list
[i
] == NULL
)
2216 cross_validate_globals(ctx
, prog
, shader_list
[i
]->ir
, &variables
,
2220 if (!prog
->data
->LinkStatus
)
2223 /* Check that interface blocks defined in multiple shaders are consistent.
2225 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
2227 if (!prog
->data
->LinkStatus
)
2230 /* Check that there is only a single definition of each function signature
2231 * across all shaders.
2233 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2234 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2235 ir_function
*const f
= node
->as_function();
2240 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2241 ir_function
*const other
=
2242 shader_list
[j
]->symbols
->get_function(f
->name
);
2244 /* If the other shader has no function (and therefore no function
2245 * signatures) with the same name, skip to the next shader.
2250 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2251 if (!sig
->is_defined
)
2254 ir_function_signature
*other_sig
=
2255 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2257 if (other_sig
!= NULL
&& other_sig
->is_defined
) {
2258 linker_error(prog
, "function `%s' is multiply defined\n",
2267 /* Find the shader that defines main, and make a clone of it.
2269 * Starting with the clone, search for undefined references. If one is
2270 * found, find the shader that defines it. Clone the reference and add
2271 * it to the shader. Repeat until there are no undefined references or
2272 * until a reference cannot be resolved.
2274 gl_shader
*main
= NULL
;
2275 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2276 if (_mesa_get_main_function_signature(shader_list
[i
]->symbols
)) {
2277 main
= shader_list
[i
];
2282 if (main
== NULL
&& allow_missing_main
)
2283 main
= shader_list
[0];
2286 linker_error(prog
, "%s shader lacks `main'\n",
2287 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2291 gl_linked_shader
*linked
= rzalloc(NULL
, struct gl_linked_shader
);
2292 linked
->Stage
= shader_list
[0]->Stage
;
2294 /* Create program and attach it to the linked shader */
2295 struct gl_program
*gl_prog
=
2296 ctx
->Driver
.NewProgram(ctx
,
2297 _mesa_shader_stage_to_program(shader_list
[0]->Stage
),
2300 prog
->data
->LinkStatus
= LINKING_FAILURE
;
2301 _mesa_delete_linked_shader(ctx
, linked
);
2305 _mesa_reference_shader_program_data(ctx
, &gl_prog
->sh
.data
, prog
->data
);
2307 /* Don't use _mesa_reference_program() just take ownership */
2308 linked
->Program
= gl_prog
;
2310 linked
->ir
= new(linked
) exec_list
;
2311 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2313 link_fs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2314 link_tcs_out_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2315 link_tes_in_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2316 link_gs_inout_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2317 link_cs_input_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2319 if (linked
->Stage
!= MESA_SHADER_FRAGMENT
)
2320 link_xfb_stride_layout_qualifiers(ctx
, prog
, shader_list
, num_shaders
);
2322 link_bindless_layout_qualifiers(prog
, shader_list
, num_shaders
);
2324 populate_symbol_table(linked
, shader_list
[0]->symbols
);
2326 /* The pointer to the main function in the final linked shader (i.e., the
2327 * copy of the original shader that contained the main function).
2329 ir_function_signature
*const main_sig
=
2330 _mesa_get_main_function_signature(linked
->symbols
);
2332 /* Move any instructions other than variable declarations or function
2333 * declarations into main.
2335 if (main_sig
!= NULL
) {
2336 exec_node
*insertion_point
=
2337 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2340 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2341 if (shader_list
[i
] == main
)
2344 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2345 insertion_point
, true, linked
);
2349 if (!link_function_calls(prog
, linked
, shader_list
, num_shaders
)) {
2350 _mesa_delete_linked_shader(ctx
, linked
);
2354 /* Make a pass over all variable declarations to ensure that arrays with
2355 * unspecified sizes have a size specified. The size is inferred from the
2356 * max_array_access field.
2358 array_sizing_visitor v
;
2360 v
.fixup_unnamed_interface_types();
2362 /* Link up uniform blocks defined within this stage. */
2363 link_uniform_blocks(mem_ctx
, ctx
, prog
, linked
, &ubo_blocks
,
2364 &num_ubo_blocks
, &ssbo_blocks
, &num_ssbo_blocks
);
2366 if (!prog
->data
->LinkStatus
) {
2367 _mesa_delete_linked_shader(ctx
, linked
);
2371 /* Copy ubo blocks to linked shader list */
2372 linked
->Program
->sh
.UniformBlocks
=
2373 ralloc_array(linked
, gl_uniform_block
*, num_ubo_blocks
);
2374 ralloc_steal(linked
, ubo_blocks
);
2375 for (unsigned i
= 0; i
< num_ubo_blocks
; i
++) {
2376 linked
->Program
->sh
.UniformBlocks
[i
] = &ubo_blocks
[i
];
2378 linked
->Program
->info
.num_ubos
= num_ubo_blocks
;
2380 /* Copy ssbo blocks to linked shader list */
2381 linked
->Program
->sh
.ShaderStorageBlocks
=
2382 ralloc_array(linked
, gl_uniform_block
*, num_ssbo_blocks
);
2383 ralloc_steal(linked
, ssbo_blocks
);
2384 for (unsigned i
= 0; i
< num_ssbo_blocks
; i
++) {
2385 linked
->Program
->sh
.ShaderStorageBlocks
[i
] = &ssbo_blocks
[i
];
2387 linked
->Program
->info
.num_ssbos
= num_ssbo_blocks
;
2389 /* At this point linked should contain all of the linked IR, so
2390 * validate it to make sure nothing went wrong.
2392 validate_ir_tree(linked
->ir
);
2394 /* Set the size of geometry shader input arrays */
2395 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2396 unsigned num_vertices
=
2397 vertices_per_prim(gl_prog
->info
.gs
.input_primitive
);
2398 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2399 MESA_SHADER_GEOMETRY
);
2400 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2401 ir
->accept(&input_resize_visitor
);
2405 if (ctx
->Const
.VertexID_is_zero_based
)
2406 lower_vertex_id(linked
);
2408 if (ctx
->Const
.LowerCsDerivedVariables
)
2409 lower_cs_derived(linked
);
2412 /* Compute the source checksum. */
2413 linked
->SourceChecksum
= 0;
2414 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2415 if (shader_list
[i
] == NULL
)
2417 linked
->SourceChecksum
^= shader_list
[i
]->SourceChecksum
;
2425 * Update the sizes of linked shader uniform arrays to the maximum
2428 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2430 * If one or more elements of an array are active,
2431 * GetActiveUniform will return the name of the array in name,
2432 * subject to the restrictions listed above. The type of the array
2433 * is returned in type. The size parameter contains the highest
2434 * array element index used, plus one. The compiler or linker
2435 * determines the highest index used. There will be only one
2436 * active uniform reported by the GL per uniform array.
2440 update_array_sizes(struct gl_shader_program
*prog
)
2442 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2443 if (prog
->_LinkedShaders
[i
] == NULL
)
2446 bool types_were_updated
= false;
2448 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2449 ir_variable
*const var
= node
->as_variable();
2451 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2452 !var
->type
->is_array())
2455 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2456 * will not be eliminated. Since we always do std140, just
2457 * don't resize arrays in UBOs.
2459 * Atomic counters are supposed to get deterministic
2460 * locations assigned based on the declaration ordering and
2461 * sizes, array compaction would mess that up.
2463 * Subroutine uniforms are not removed.
2465 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2466 var
->type
->contains_subroutine() || var
->constant_initializer
)
2469 int size
= var
->data
.max_array_access
;
2470 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2471 if (prog
->_LinkedShaders
[j
] == NULL
)
2474 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2475 ir_variable
*other_var
= node2
->as_variable();
2479 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2480 other_var
->data
.max_array_access
> size
) {
2481 size
= other_var
->data
.max_array_access
;
2486 if (size
+ 1 != (int)var
->type
->length
) {
2487 /* If this is a built-in uniform (i.e., it's backed by some
2488 * fixed-function state), adjust the number of state slots to
2489 * match the new array size. The number of slots per array entry
2490 * is not known. It seems safe to assume that the total number of
2491 * slots is an integer multiple of the number of array elements.
2492 * Determine the number of slots per array element by dividing by
2493 * the old (total) size.
2495 const unsigned num_slots
= var
->get_num_state_slots();
2496 if (num_slots
> 0) {
2497 var
->set_num_state_slots((size
+ 1)
2498 * (num_slots
/ var
->type
->length
));
2501 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2503 types_were_updated
= true;
2507 /* Update the types of dereferences in case we changed any. */
2508 if (types_were_updated
) {
2509 deref_type_updater v
;
2510 v
.run(prog
->_LinkedShaders
[i
]->ir
);
2516 * Resize tessellation evaluation per-vertex inputs to the size of
2517 * tessellation control per-vertex outputs.
2520 resize_tes_inputs(struct gl_context
*ctx
,
2521 struct gl_shader_program
*prog
)
2523 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2526 gl_linked_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2527 gl_linked_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2529 /* If no control shader is present, then the TES inputs are statically
2530 * sized to MaxPatchVertices; the actual size of the arrays won't be
2531 * known until draw time.
2533 const int num_vertices
= tcs
2534 ? tcs
->Program
->info
.tess
.tcs_vertices_out
2535 : ctx
->Const
.MaxPatchVertices
;
2537 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2538 MESA_SHADER_TESS_EVAL
);
2539 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2540 ir
->accept(&input_resize_visitor
);
2544 /* Convert the gl_PatchVerticesIn system value into a constant, since
2545 * the value is known at this point.
2547 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2548 ir_variable
*var
= ir
->as_variable();
2549 if (var
&& var
->data
.mode
== ir_var_system_value
&&
2550 var
->data
.location
== SYSTEM_VALUE_VERTICES_IN
) {
2551 void *mem_ctx
= ralloc_parent(var
);
2552 var
->data
.location
= 0;
2553 var
->data
.explicit_location
= false;
2554 var
->data
.mode
= ir_var_auto
;
2555 var
->constant_value
= new(mem_ctx
) ir_constant(num_vertices
);
2562 * Find a contiguous set of available bits in a bitmask.
2564 * \param used_mask Bits representing used (1) and unused (0) locations
2565 * \param needed_count Number of contiguous bits needed.
2568 * Base location of the available bits on success or -1 on failure.
2571 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2573 unsigned needed_mask
= (1 << needed_count
) - 1;
2574 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2576 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2577 * cannot optimize possibly infinite loops" for the loop below.
2579 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2582 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2583 if ((needed_mask
& ~used_mask
) == needed_mask
)
2593 #define SAFE_MASK_FROM_INDEX(i) (((i) >= 32) ? ~0 : ((1 << (i)) - 1))
2596 * Assign locations for either VS inputs or FS outputs
2598 * \param mem_ctx Temporary ralloc context used for linking
2599 * \param prog Shader program whose variables need locations assigned
2600 * \param constants Driver specific constant values for the program.
2601 * \param target_index Selector for the program target to receive location
2602 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2603 * \c MESA_SHADER_FRAGMENT.
2606 * If locations are successfully assigned, true is returned. Otherwise an
2607 * error is emitted to the shader link log and false is returned.
2610 assign_attribute_or_color_locations(void *mem_ctx
,
2611 gl_shader_program
*prog
,
2612 struct gl_constants
*constants
,
2613 unsigned target_index
)
2615 /* Maximum number of generic locations. This corresponds to either the
2616 * maximum number of draw buffers or the maximum number of generic
2619 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2620 constants
->Program
[target_index
].MaxAttribs
:
2621 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2623 /* Mark invalid locations as being used.
2625 unsigned used_locations
= ~SAFE_MASK_FROM_INDEX(max_index
);
2626 unsigned double_storage_locations
= 0;
2628 assert((target_index
== MESA_SHADER_VERTEX
)
2629 || (target_index
== MESA_SHADER_FRAGMENT
));
2631 gl_linked_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2635 /* Operate in a total of four passes.
2637 * 1. Invalidate the location assignments for all vertex shader inputs.
2639 * 2. Assign locations for inputs that have user-defined (via
2640 * glBindVertexAttribLocation) locations and outputs that have
2641 * user-defined locations (via glBindFragDataLocation).
2643 * 3. Sort the attributes without assigned locations by number of slots
2644 * required in decreasing order. Fragmentation caused by attribute
2645 * locations assigned by the application may prevent large attributes
2646 * from having enough contiguous space.
2648 * 4. Assign locations to any inputs without assigned locations.
2651 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2652 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2654 const enum ir_variable_mode direction
=
2655 (target_index
== MESA_SHADER_VERTEX
)
2656 ? ir_var_shader_in
: ir_var_shader_out
;
2659 /* Temporary storage for the set of attributes that need locations assigned.
2665 /* Used below in the call to qsort. */
2666 static int compare(const void *a
, const void *b
)
2668 const temp_attr
*const l
= (const temp_attr
*) a
;
2669 const temp_attr
*const r
= (const temp_attr
*) b
;
2671 /* Reversed because we want a descending order sort below. */
2672 return r
->slots
- l
->slots
;
2675 assert(max_index
<= 32);
2677 /* Temporary array for the set of attributes that have locations assigned,
2678 * for the purpose of checking overlapping slots/components of (non-ES)
2679 * fragment shader outputs.
2681 ir_variable
*assigned
[12 * 4]; /* (max # of FS outputs) * # components */
2682 unsigned assigned_attr
= 0;
2684 unsigned num_attr
= 0;
2686 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2687 ir_variable
*const var
= node
->as_variable();
2689 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2692 if (var
->data
.explicit_location
) {
2693 var
->data
.is_unmatched_generic_inout
= 0;
2694 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2695 || (var
->data
.location
< 0)) {
2697 "invalid explicit location %d specified for `%s'\n",
2698 (var
->data
.location
< 0)
2699 ? var
->data
.location
2700 : var
->data
.location
- generic_base
,
2704 } else if (target_index
== MESA_SHADER_VERTEX
) {
2707 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2708 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2709 var
->data
.location
= binding
;
2710 var
->data
.is_unmatched_generic_inout
= 0;
2712 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2715 const char *name
= var
->name
;
2716 const glsl_type
*type
= var
->type
;
2719 /* Check if there's a binding for the variable name */
2720 if (prog
->FragDataBindings
->get(binding
, name
)) {
2721 assert(binding
>= FRAG_RESULT_DATA0
);
2722 var
->data
.location
= binding
;
2723 var
->data
.is_unmatched_generic_inout
= 0;
2725 if (prog
->FragDataIndexBindings
->get(index
, name
)) {
2726 var
->data
.index
= index
;
2731 /* If not, but it's an array type, look for name[0] */
2732 if (type
->is_array()) {
2733 name
= ralloc_asprintf(mem_ctx
, "%s[0]", name
);
2734 type
= type
->fields
.array
;
2742 if (strcmp(var
->name
, "gl_LastFragData") == 0)
2745 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2747 * "Output binding assignments will cause LinkProgram to fail:
2749 * If the program has an active output assigned to a location greater
2750 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2751 * an active output assigned an index greater than or equal to one;"
2753 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2754 var
->data
.location
- generic_base
>=
2755 (int) constants
->MaxDualSourceDrawBuffers
) {
2757 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2758 "with index %u for %s\n",
2759 var
->data
.location
- generic_base
, var
->data
.index
,
2764 const unsigned slots
= var
->type
->count_attribute_slots(target_index
== MESA_SHADER_VERTEX
);
2766 /* If the variable is not a built-in and has a location statically
2767 * assigned in the shader (presumably via a layout qualifier), make sure
2768 * that it doesn't collide with other assigned locations. Otherwise,
2769 * add it to the list of variables that need linker-assigned locations.
2771 if (var
->data
.location
!= -1) {
2772 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2773 /* From page 61 of the OpenGL 4.0 spec:
2775 * "LinkProgram will fail if the attribute bindings assigned
2776 * by BindAttribLocation do not leave not enough space to
2777 * assign a location for an active matrix attribute or an
2778 * active attribute array, both of which require multiple
2779 * contiguous generic attributes."
2781 * I think above text prohibits the aliasing of explicit and
2782 * automatic assignments. But, aliasing is allowed in manual
2783 * assignments of attribute locations. See below comments for
2786 * From OpenGL 4.0 spec, page 61:
2788 * "It is possible for an application to bind more than one
2789 * attribute name to the same location. This is referred to as
2790 * aliasing. This will only work if only one of the aliased
2791 * attributes is active in the executable program, or if no
2792 * path through the shader consumes more than one attribute of
2793 * a set of attributes aliased to the same location. A link
2794 * error can occur if the linker determines that every path
2795 * through the shader consumes multiple aliased attributes,
2796 * but implementations are not required to generate an error
2799 * From GLSL 4.30 spec, page 54:
2801 * "A program will fail to link if any two non-vertex shader
2802 * input variables are assigned to the same location. For
2803 * vertex shaders, multiple input variables may be assigned
2804 * to the same location using either layout qualifiers or via
2805 * the OpenGL API. However, such aliasing is intended only to
2806 * support vertex shaders where each execution path accesses
2807 * at most one input per each location. Implementations are
2808 * permitted, but not required, to generate link-time errors
2809 * if they detect that every path through the vertex shader
2810 * executable accesses multiple inputs assigned to any single
2811 * location. For all shader types, a program will fail to link
2812 * if explicit location assignments leave the linker unable
2813 * to find space for other variables without explicit
2816 * From OpenGL ES 3.0 spec, page 56:
2818 * "Binding more than one attribute name to the same location
2819 * is referred to as aliasing, and is not permitted in OpenGL
2820 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2821 * fail when this condition exists. However, aliasing is
2822 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2823 * This will only work if only one of the aliased attributes
2824 * is active in the executable program, or if no path through
2825 * the shader consumes more than one attribute of a set of
2826 * attributes aliased to the same location. A link error can
2827 * occur if the linker determines that every path through the
2828 * shader consumes multiple aliased attributes, but implemen-
2829 * tations are not required to generate an error in this case."
2831 * After looking at above references from OpenGL, OpenGL ES and
2832 * GLSL specifications, we allow aliasing of vertex input variables
2833 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2835 * NOTE: This is not required by the spec but its worth mentioning
2836 * here that we're not doing anything to make sure that no path
2837 * through the vertex shader executable accesses multiple inputs
2838 * assigned to any single location.
2841 /* Mask representing the contiguous slots that will be used by
2844 const unsigned attr
= var
->data
.location
- generic_base
;
2845 const unsigned use_mask
= (1 << slots
) - 1;
2846 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2847 ? "vertex shader input" : "fragment shader output";
2849 /* Generate a link error if the requested locations for this
2850 * attribute exceed the maximum allowed attribute location.
2852 if (attr
+ slots
> max_index
) {
2854 "insufficient contiguous locations "
2855 "available for %s `%s' %d %d %d\n", string
,
2856 var
->name
, used_locations
, use_mask
, attr
);
2860 /* Generate a link error if the set of bits requested for this
2861 * attribute overlaps any previously allocated bits.
2863 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
2864 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
2865 /* From section 4.4.2 (Output Layout Qualifiers) of the GLSL
2868 * "Additionally, for fragment shader outputs, if two
2869 * variables are placed within the same location, they
2870 * must have the same underlying type (floating-point or
2871 * integer). No component aliasing of output variables or
2872 * members is allowed.
2874 for (unsigned i
= 0; i
< assigned_attr
; i
++) {
2875 unsigned assigned_slots
=
2876 assigned
[i
]->type
->count_attribute_slots(false);
2877 unsigned assig_attr
=
2878 assigned
[i
]->data
.location
- generic_base
;
2879 unsigned assigned_use_mask
= (1 << assigned_slots
) - 1;
2881 if ((assigned_use_mask
<< assig_attr
) &
2882 (use_mask
<< attr
)) {
2884 const glsl_type
*assigned_type
=
2885 assigned
[i
]->type
->without_array();
2886 const glsl_type
*type
= var
->type
->without_array();
2887 if (assigned_type
->base_type
!= type
->base_type
) {
2888 linker_error(prog
, "types do not match for aliased"
2889 " %ss %s and %s\n", string
,
2890 assigned
[i
]->name
, var
->name
);
2894 unsigned assigned_component_mask
=
2895 ((1 << assigned_type
->vector_elements
) - 1) <<
2896 assigned
[i
]->data
.location_frac
;
2897 unsigned component_mask
=
2898 ((1 << type
->vector_elements
) - 1) <<
2899 var
->data
.location_frac
;
2900 if (assigned_component_mask
& component_mask
) {
2901 linker_error(prog
, "overlapping component is "
2902 "assigned to %ss %s and %s "
2904 string
, assigned
[i
]->name
, var
->name
,
2905 var
->data
.location_frac
);
2910 } else if (target_index
== MESA_SHADER_FRAGMENT
||
2911 (prog
->IsES
&& prog
->data
->Version
>= 300)) {
2912 linker_error(prog
, "overlapping location is assigned "
2913 "to %s `%s' %d %d %d\n", string
, var
->name
,
2914 used_locations
, use_mask
, attr
);
2917 linker_warning(prog
, "overlapping location is assigned "
2918 "to %s `%s' %d %d %d\n", string
, var
->name
,
2919 used_locations
, use_mask
, attr
);
2923 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
2924 /* Only track assigned variables for non-ES fragment shaders
2925 * to avoid overflowing the array.
2927 * At most one variable per fragment output component should
2930 assert(assigned_attr
< ARRAY_SIZE(assigned
));
2931 assigned
[assigned_attr
] = var
;
2935 used_locations
|= (use_mask
<< attr
);
2937 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2939 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2940 * active attribute variables may fail to link, unless
2941 * device-dependent optimizations are able to make the program
2942 * fit within available hardware resources. For the purposes
2943 * of this test, attribute variables of the type dvec3, dvec4,
2944 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2945 * count as consuming twice as many attributes as equivalent
2946 * single-precision types. While these types use the same number
2947 * of generic attributes as their single-precision equivalents,
2948 * implementations are permitted to consume two single-precision
2949 * vectors of internal storage for each three- or four-component
2950 * double-precision vector."
2952 * Mark this attribute slot as taking up twice as much space
2953 * so we can count it properly against limits. According to
2954 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2955 * is optional behavior, but it seems preferable.
2957 if (var
->type
->without_array()->is_dual_slot())
2958 double_storage_locations
|= (use_mask
<< attr
);
2964 if (num_attr
>= max_index
) {
2965 linker_error(prog
, "too many %s (max %u)",
2966 target_index
== MESA_SHADER_VERTEX
?
2967 "vertex shader inputs" : "fragment shader outputs",
2971 to_assign
[num_attr
].slots
= slots
;
2972 to_assign
[num_attr
].var
= var
;
2976 if (target_index
== MESA_SHADER_VERTEX
) {
2977 unsigned total_attribs_size
=
2978 _mesa_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
2979 _mesa_bitcount(double_storage_locations
);
2980 if (total_attribs_size
> max_index
) {
2982 "attempt to use %d vertex attribute slots only %d available ",
2983 total_attribs_size
, max_index
);
2988 /* If all of the attributes were assigned locations by the application (or
2989 * are built-in attributes with fixed locations), return early. This should
2990 * be the common case.
2995 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
2997 if (target_index
== MESA_SHADER_VERTEX
) {
2998 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2999 * only be explicitly assigned by via glBindAttribLocation. Mark it as
3000 * reserved to prevent it from being automatically allocated below.
3002 find_deref_visitor
find("gl_Vertex");
3004 if (find
.variable_found())
3005 used_locations
|= (1 << 0);
3008 for (unsigned i
= 0; i
< num_attr
; i
++) {
3009 /* Mask representing the contiguous slots that will be used by this
3012 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
3014 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
3017 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
3018 ? "vertex shader input" : "fragment shader output";
3021 "insufficient contiguous locations "
3022 "available for %s `%s'\n",
3023 string
, to_assign
[i
].var
->name
);
3027 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
3028 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
3029 used_locations
|= (use_mask
<< location
);
3031 if (to_assign
[i
].var
->type
->without_array()->is_dual_slot())
3032 double_storage_locations
|= (use_mask
<< location
);
3035 /* Now that we have all the locations, from the GL 4.5 core spec, section
3036 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
3037 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
3038 * as equivalent single-precision types.
3040 if (target_index
== MESA_SHADER_VERTEX
) {
3041 unsigned total_attribs_size
=
3042 _mesa_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
3043 _mesa_bitcount(double_storage_locations
);
3044 if (total_attribs_size
> max_index
) {
3046 "attempt to use %d vertex attribute slots only %d available ",
3047 total_attribs_size
, max_index
);
3056 * Match explicit locations of outputs to inputs and deactivate the
3057 * unmatch flag if found so we don't optimise them away.
3060 match_explicit_outputs_to_inputs(gl_linked_shader
*producer
,
3061 gl_linked_shader
*consumer
)
3063 glsl_symbol_table parameters
;
3064 ir_variable
*explicit_locations
[MAX_VARYINGS_INCL_PATCH
][4] =
3067 /* Find all shader outputs in the "producer" stage.
3069 foreach_in_list(ir_instruction
, node
, producer
->ir
) {
3070 ir_variable
*const var
= node
->as_variable();
3072 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_shader_out
))
3075 if (var
->data
.explicit_location
&&
3076 var
->data
.location
>= VARYING_SLOT_VAR0
) {
3077 const unsigned idx
= var
->data
.location
- VARYING_SLOT_VAR0
;
3078 if (explicit_locations
[idx
][var
->data
.location_frac
] == NULL
)
3079 explicit_locations
[idx
][var
->data
.location_frac
] = var
;
3083 /* Match inputs to outputs */
3084 foreach_in_list(ir_instruction
, node
, consumer
->ir
) {
3085 ir_variable
*const input
= node
->as_variable();
3087 if ((input
== NULL
) || (input
->data
.mode
!= ir_var_shader_in
))
3090 ir_variable
*output
= NULL
;
3091 if (input
->data
.explicit_location
3092 && input
->data
.location
>= VARYING_SLOT_VAR0
) {
3093 output
= explicit_locations
[input
->data
.location
- VARYING_SLOT_VAR0
]
3094 [input
->data
.location_frac
];
3096 if (output
!= NULL
){
3097 input
->data
.is_unmatched_generic_inout
= 0;
3098 output
->data
.is_unmatched_generic_inout
= 0;
3105 * Store the gl_FragDepth layout in the gl_shader_program struct.
3108 store_fragdepth_layout(struct gl_shader_program
*prog
)
3110 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
3114 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
3116 /* We don't look up the gl_FragDepth symbol directly because if
3117 * gl_FragDepth is not used in the shader, it's removed from the IR.
3118 * However, the symbol won't be removed from the symbol table.
3120 * We're only interested in the cases where the variable is NOT removed
3123 foreach_in_list(ir_instruction
, node
, ir
) {
3124 ir_variable
*const var
= node
->as_variable();
3126 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
3130 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
3131 switch (var
->data
.depth_layout
) {
3132 case ir_depth_layout_none
:
3133 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
3135 case ir_depth_layout_any
:
3136 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
3138 case ir_depth_layout_greater
:
3139 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
3141 case ir_depth_layout_less
:
3142 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
3144 case ir_depth_layout_unchanged
:
3145 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
3156 * Validate the resources used by a program versus the implementation limits
3159 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3161 unsigned total_uniform_blocks
= 0;
3162 unsigned total_shader_storage_blocks
= 0;
3164 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3165 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3170 if (sh
->Program
->info
.num_textures
>
3171 ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
3172 linker_error(prog
, "Too many %s shader texture samplers\n",
3173 _mesa_shader_stage_to_string(i
));
3176 if (sh
->num_uniform_components
>
3177 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
3178 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3179 linker_warning(prog
, "Too many %s shader default uniform block "
3180 "components, but the driver will try to optimize "
3181 "them out; this is non-portable out-of-spec "
3183 _mesa_shader_stage_to_string(i
));
3185 linker_error(prog
, "Too many %s shader default uniform block "
3187 _mesa_shader_stage_to_string(i
));
3191 if (sh
->num_combined_uniform_components
>
3192 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
3193 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3194 linker_warning(prog
, "Too many %s shader uniform components, "
3195 "but the driver will try to optimize them out; "
3196 "this is non-portable out-of-spec behavior\n",
3197 _mesa_shader_stage_to_string(i
));
3199 linker_error(prog
, "Too many %s shader uniform components\n",
3200 _mesa_shader_stage_to_string(i
));
3204 total_shader_storage_blocks
+= sh
->Program
->info
.num_ssbos
;
3205 total_uniform_blocks
+= sh
->Program
->info
.num_ubos
;
3207 const unsigned max_uniform_blocks
=
3208 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
3209 if (max_uniform_blocks
< sh
->Program
->info
.num_ubos
) {
3210 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
3211 _mesa_shader_stage_to_string(i
),
3212 sh
->Program
->info
.num_ubos
, max_uniform_blocks
);
3215 const unsigned max_shader_storage_blocks
=
3216 ctx
->Const
.Program
[i
].MaxShaderStorageBlocks
;
3217 if (max_shader_storage_blocks
< sh
->Program
->info
.num_ssbos
) {
3218 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
3219 _mesa_shader_stage_to_string(i
),
3220 sh
->Program
->info
.num_ssbos
, max_shader_storage_blocks
);
3224 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
3225 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
3226 total_uniform_blocks
, ctx
->Const
.MaxCombinedUniformBlocks
);
3229 if (total_shader_storage_blocks
> ctx
->Const
.MaxCombinedShaderStorageBlocks
) {
3230 linker_error(prog
, "Too many combined shader storage blocks (%d/%d)\n",
3231 total_shader_storage_blocks
,
3232 ctx
->Const
.MaxCombinedShaderStorageBlocks
);
3235 for (unsigned i
= 0; i
< prog
->data
->NumUniformBlocks
; i
++) {
3236 if (prog
->data
->UniformBlocks
[i
].UniformBufferSize
>
3237 ctx
->Const
.MaxUniformBlockSize
) {
3238 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
3239 prog
->data
->UniformBlocks
[i
].Name
,
3240 prog
->data
->UniformBlocks
[i
].UniformBufferSize
,
3241 ctx
->Const
.MaxUniformBlockSize
);
3245 for (unsigned i
= 0; i
< prog
->data
->NumShaderStorageBlocks
; i
++) {
3246 if (prog
->data
->ShaderStorageBlocks
[i
].UniformBufferSize
>
3247 ctx
->Const
.MaxShaderStorageBlockSize
) {
3248 linker_error(prog
, "Shader storage block %s too big (%d/%d)\n",
3249 prog
->data
->ShaderStorageBlocks
[i
].Name
,
3250 prog
->data
->ShaderStorageBlocks
[i
].UniformBufferSize
,
3251 ctx
->Const
.MaxShaderStorageBlockSize
);
3257 link_calculate_subroutine_compat(struct gl_shader_program
*prog
)
3259 unsigned mask
= prog
->data
->linked_stages
;
3261 const int i
= u_bit_scan(&mask
);
3262 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3264 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineUniformRemapTable
; j
++) {
3265 if (p
->sh
.SubroutineUniformRemapTable
[j
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
)
3268 struct gl_uniform_storage
*uni
= p
->sh
.SubroutineUniformRemapTable
[j
];
3274 if (p
->sh
.NumSubroutineFunctions
== 0) {
3275 linker_error(prog
, "subroutine uniform %s defined but no valid functions found\n", uni
->type
->name
);
3278 for (unsigned f
= 0; f
< p
->sh
.NumSubroutineFunctions
; f
++) {
3279 struct gl_subroutine_function
*fn
= &p
->sh
.SubroutineFunctions
[f
];
3280 for (int k
= 0; k
< fn
->num_compat_types
; k
++) {
3281 if (fn
->types
[k
] == uni
->type
) {
3287 uni
->num_compatible_subroutines
= count
;
3293 check_subroutine_resources(struct gl_shader_program
*prog
)
3295 unsigned mask
= prog
->data
->linked_stages
;
3297 const int i
= u_bit_scan(&mask
);
3298 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3300 if (p
->sh
.NumSubroutineUniformRemapTable
> MAX_SUBROUTINE_UNIFORM_LOCATIONS
) {
3301 linker_error(prog
, "Too many %s shader subroutine uniforms\n",
3302 _mesa_shader_stage_to_string(i
));
3307 * Validate shader image resources.
3310 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3312 unsigned total_image_units
= 0;
3313 unsigned fragment_outputs
= 0;
3314 unsigned total_shader_storage_blocks
= 0;
3316 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
3319 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3320 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3323 if (sh
->Program
->info
.num_images
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
3324 linker_error(prog
, "Too many %s shader image uniforms (%u > %u)\n",
3325 _mesa_shader_stage_to_string(i
),
3326 sh
->Program
->info
.num_images
,
3327 ctx
->Const
.Program
[i
].MaxImageUniforms
);
3329 total_image_units
+= sh
->Program
->info
.num_images
;
3330 total_shader_storage_blocks
+= sh
->Program
->info
.num_ssbos
;
3332 if (i
== MESA_SHADER_FRAGMENT
) {
3333 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3334 ir_variable
*var
= node
->as_variable();
3335 if (var
&& var
->data
.mode
== ir_var_shader_out
)
3336 /* since there are no double fs outputs - pass false */
3337 fragment_outputs
+= var
->type
->count_attribute_slots(false);
3343 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
3344 linker_error(prog
, "Too many combined image uniforms\n");
3346 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
3347 ctx
->Const
.MaxCombinedShaderOutputResources
)
3348 linker_error(prog
, "Too many combined image uniforms, shader storage "
3349 " buffers and fragment outputs\n");
3354 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3355 * for a variable, checks for overlaps between other uniforms using explicit
3359 reserve_explicit_locations(struct gl_shader_program
*prog
,
3360 string_to_uint_map
*map
, ir_variable
*var
)
3362 unsigned slots
= var
->type
->uniform_locations();
3363 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3364 unsigned return_value
= slots
;
3366 /* Resize remap table if locations do not fit in the current one. */
3367 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
3368 prog
->UniformRemapTable
=
3369 reralloc(prog
, prog
->UniformRemapTable
,
3370 gl_uniform_storage
*,
3373 if (!prog
->UniformRemapTable
) {
3374 linker_error(prog
, "Out of memory during linking.\n");
3378 /* Initialize allocated space. */
3379 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
3380 prog
->UniformRemapTable
[i
] = NULL
;
3382 prog
->NumUniformRemapTable
= max_loc
+ 1;
3385 for (unsigned i
= 0; i
< slots
; i
++) {
3386 unsigned loc
= var
->data
.location
+ i
;
3388 /* Check if location is already used. */
3389 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3391 /* Possibly same uniform from a different stage, this is ok. */
3393 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
) {
3398 /* ARB_explicit_uniform_location specification states:
3400 * "No two default-block uniform variables in the program can have
3401 * the same location, even if they are unused, otherwise a compiler
3402 * or linker error will be generated."
3405 "location qualifier for uniform %s overlaps "
3406 "previously used location\n",
3411 /* Initialize location as inactive before optimization
3412 * rounds and location assignment.
3414 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3417 /* Note, base location used for arrays. */
3418 map
->put(var
->data
.location
, var
->name
);
3420 return return_value
;
3424 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3425 struct gl_program
*p
,
3428 unsigned slots
= var
->type
->uniform_locations();
3429 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3431 /* Resize remap table if locations do not fit in the current one. */
3432 if (max_loc
+ 1 > p
->sh
.NumSubroutineUniformRemapTable
) {
3433 p
->sh
.SubroutineUniformRemapTable
=
3434 reralloc(p
, p
->sh
.SubroutineUniformRemapTable
,
3435 gl_uniform_storage
*,
3438 if (!p
->sh
.SubroutineUniformRemapTable
) {
3439 linker_error(prog
, "Out of memory during linking.\n");
3443 /* Initialize allocated space. */
3444 for (unsigned i
= p
->sh
.NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3445 p
->sh
.SubroutineUniformRemapTable
[i
] = NULL
;
3447 p
->sh
.NumSubroutineUniformRemapTable
= max_loc
+ 1;
3450 for (unsigned i
= 0; i
< slots
; i
++) {
3451 unsigned loc
= var
->data
.location
+ i
;
3453 /* Check if location is already used. */
3454 if (p
->sh
.SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3456 /* ARB_explicit_uniform_location specification states:
3457 * "No two subroutine uniform variables can have the same location
3458 * in the same shader stage, otherwise a compiler or linker error
3459 * will be generated."
3462 "location qualifier for uniform %s overlaps "
3463 "previously used location\n",
3468 /* Initialize location as inactive before optimization
3469 * rounds and location assignment.
3471 p
->sh
.SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3477 * Check and reserve all explicit uniform locations, called before
3478 * any optimizations happen to handle also inactive uniforms and
3479 * inactive array elements that may get trimmed away.
3482 check_explicit_uniform_locations(struct gl_context
*ctx
,
3483 struct gl_shader_program
*prog
)
3485 prog
->NumExplicitUniformLocations
= 0;
3487 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3490 /* This map is used to detect if overlapping explicit locations
3491 * occur with the same uniform (from different stage) or a different one.
3493 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3496 linker_error(prog
, "Out of memory during linking.\n");
3500 unsigned entries_total
= 0;
3501 unsigned mask
= prog
->data
->linked_stages
;
3503 const int i
= u_bit_scan(&mask
);
3504 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3506 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
3507 ir_variable
*var
= node
->as_variable();
3508 if (!var
|| var
->data
.mode
!= ir_var_uniform
)
3511 if (var
->data
.explicit_location
) {
3513 if (var
->type
->without_array()->is_subroutine())
3514 ret
= reserve_subroutine_explicit_locations(prog
, p
, var
);
3516 int slots
= reserve_explicit_locations(prog
, uniform_map
,
3520 entries_total
+= slots
;
3531 link_util_update_empty_uniform_locations(prog
);
3534 prog
->NumExplicitUniformLocations
= entries_total
;
3538 should_add_buffer_variable(struct gl_shader_program
*shProg
,
3539 GLenum type
, const char *name
)
3541 bool found_interface
= false;
3542 unsigned block_name_len
= 0;
3543 const char *block_name_dot
= strchr(name
, '.');
3545 /* These rules only apply to buffer variables. So we return
3546 * true for the rest of types.
3548 if (type
!= GL_BUFFER_VARIABLE
)
3551 for (unsigned i
= 0; i
< shProg
->data
->NumShaderStorageBlocks
; i
++) {
3552 const char *block_name
= shProg
->data
->ShaderStorageBlocks
[i
].Name
;
3553 block_name_len
= strlen(block_name
);
3555 const char *block_square_bracket
= strchr(block_name
, '[');
3556 if (block_square_bracket
) {
3557 /* The block is part of an array of named interfaces,
3558 * for the name comparison we ignore the "[x]" part.
3560 block_name_len
-= strlen(block_square_bracket
);
3563 if (block_name_dot
) {
3564 /* Check if the variable name starts with the interface
3565 * name. The interface name (if present) should have the
3566 * length than the interface block name we are comparing to.
3568 unsigned len
= strlen(name
) - strlen(block_name_dot
);
3569 if (len
!= block_name_len
)
3573 if (strncmp(block_name
, name
, block_name_len
) == 0) {
3574 found_interface
= true;
3579 /* We remove the interface name from the buffer variable name,
3580 * including the dot that follows it.
3582 if (found_interface
)
3583 name
= name
+ block_name_len
+ 1;
3585 /* The ARB_program_interface_query spec says:
3587 * "For an active shader storage block member declared as an array, an
3588 * entry will be generated only for the first array element, regardless
3589 * of its type. For arrays of aggregate types, the enumeration rules
3590 * are applied recursively for the single enumerated array element."
3592 const char *struct_first_dot
= strchr(name
, '.');
3593 const char *first_square_bracket
= strchr(name
, '[');
3595 /* The buffer variable is on top level and it is not an array */
3596 if (!first_square_bracket
) {
3598 /* The shader storage block member is a struct, then generate the entry */
3599 } else if (struct_first_dot
&& struct_first_dot
< first_square_bracket
) {
3602 /* Shader storage block member is an array, only generate an entry for the
3603 * first array element.
3605 if (strncmp(first_square_bracket
, "[0]", 3) == 0)
3612 /* Function checks if a variable var is a packed varying and
3613 * if given name is part of packed varying's list.
3615 * If a variable is a packed varying, it has a name like
3616 * 'packed:a,b,c' where a, b and c are separate variables.
3619 included_in_packed_varying(ir_variable
*var
, const char *name
)
3621 if (strncmp(var
->name
, "packed:", 7) != 0)
3624 char *list
= strdup(var
->name
+ 7);
3629 char *token
= strtok_r(list
, ",", &saveptr
);
3631 if (strcmp(token
, name
) == 0) {
3635 token
= strtok_r(NULL
, ",", &saveptr
);
3642 * Function builds a stage reference bitmask from variable name.
3645 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3650 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3651 * used for reference mask in gl_program_resource will need to be changed.
3653 assert(MESA_SHADER_STAGES
< 8);
3655 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3656 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
3660 /* Shader symbol table may contain variables that have
3661 * been optimized away. Search IR for the variable instead.
3663 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3664 ir_variable
*var
= node
->as_variable();
3666 unsigned baselen
= strlen(var
->name
);
3668 if (included_in_packed_varying(var
, name
)) {
3673 /* Type needs to match if specified, otherwise we might
3674 * pick a variable with same name but different interface.
3676 if (var
->data
.mode
!= mode
)
3679 if (strncmp(var
->name
, name
, baselen
) == 0) {
3680 /* Check for exact name matches but also check for arrays and
3683 if (name
[baselen
] == '\0' ||
3684 name
[baselen
] == '[' ||
3685 name
[baselen
] == '.') {
3697 * Create gl_shader_variable from ir_variable class.
3699 static gl_shader_variable
*
3700 create_shader_variable(struct gl_shader_program
*shProg
,
3701 const ir_variable
*in
,
3702 const char *name
, const glsl_type
*type
,
3703 const glsl_type
*interface_type
,
3704 bool use_implicit_location
, int location
,
3705 const glsl_type
*outermost_struct_type
)
3707 /* Allocate zero-initialized memory to ensure that bitfield padding
3710 gl_shader_variable
*out
= rzalloc(shProg
, struct gl_shader_variable
);
3714 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3715 * expect to see gl_VertexID in the program resource list. Pretend.
3717 if (in
->data
.mode
== ir_var_system_value
&&
3718 in
->data
.location
== SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
) {
3719 out
->name
= ralloc_strdup(shProg
, "gl_VertexID");
3720 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3721 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_OUTER
) ||
3722 (in
->data
.mode
== ir_var_system_value
&&
3723 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_OUTER
)) {
3724 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelOuter");
3725 type
= glsl_type::get_array_instance(glsl_type::float_type
, 4);
3726 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3727 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_INNER
) ||
3728 (in
->data
.mode
== ir_var_system_value
&&
3729 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_INNER
)) {
3730 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelInner");
3731 type
= glsl_type::get_array_instance(glsl_type::float_type
, 2);
3733 out
->name
= ralloc_strdup(shProg
, name
);
3739 /* The ARB_program_interface_query spec says:
3741 * "Not all active variables are assigned valid locations; the
3742 * following variables will have an effective location of -1:
3744 * * uniforms declared as atomic counters;
3746 * * members of a uniform block;
3748 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3750 * * inputs or outputs not declared with a "location" layout
3751 * qualifier, except for vertex shader inputs and fragment shader
3754 if (in
->type
->is_atomic_uint() || is_gl_identifier(in
->name
) ||
3755 !(in
->data
.explicit_location
|| use_implicit_location
)) {
3758 out
->location
= location
;
3762 out
->outermost_struct_type
= outermost_struct_type
;
3763 out
->interface_type
= interface_type
;
3764 out
->component
= in
->data
.location_frac
;
3765 out
->index
= in
->data
.index
;
3766 out
->patch
= in
->data
.patch
;
3767 out
->mode
= in
->data
.mode
;
3768 out
->interpolation
= in
->data
.interpolation
;
3769 out
->explicit_location
= in
->data
.explicit_location
;
3770 out
->precision
= in
->data
.precision
;
3776 add_shader_variable(const struct gl_context
*ctx
,
3777 struct gl_shader_program
*shProg
,
3778 struct set
*resource_set
,
3779 unsigned stage_mask
,
3780 GLenum programInterface
, ir_variable
*var
,
3781 const char *name
, const glsl_type
*type
,
3782 bool use_implicit_location
, int location
,
3783 bool inouts_share_location
,
3784 const glsl_type
*outermost_struct_type
= NULL
)
3786 const glsl_type
*interface_type
= var
->get_interface_type();
3788 if (outermost_struct_type
== NULL
) {
3789 if (var
->data
.from_named_ifc_block
) {
3790 const char *interface_name
= interface_type
->name
;
3792 if (interface_type
->is_array()) {
3793 /* Issue #16 of the ARB_program_interface_query spec says:
3795 * "* If a variable is a member of an interface block without an
3796 * instance name, it is enumerated using just the variable name.
3798 * * If a variable is a member of an interface block with an
3799 * instance name, it is enumerated as "BlockName.Member", where
3800 * "BlockName" is the name of the interface block (not the
3801 * instance name) and "Member" is the name of the variable."
3803 * In particular, it indicates that it should be "BlockName",
3804 * not "BlockName[array length]". The conformance suite and
3805 * dEQP both require this behavior.
3807 * Here, we unwrap the extra array level added by named interface
3808 * block array lowering so we have the correct variable type. We
3809 * also unwrap the interface type when constructing the name.
3811 * We leave interface_type the same so that ES 3.x SSO pipeline
3812 * validation can enforce the rules requiring array length to
3813 * match on interface blocks.
3815 type
= type
->fields
.array
;
3817 interface_name
= interface_type
->fields
.array
->name
;
3820 name
= ralloc_asprintf(shProg
, "%s.%s", interface_name
, name
);
3824 switch (type
->base_type
) {
3825 case GLSL_TYPE_STRUCT
: {
3826 /* The ARB_program_interface_query spec says:
3828 * "For an active variable declared as a structure, a separate entry
3829 * will be generated for each active structure member. The name of
3830 * each entry is formed by concatenating the name of the structure,
3831 * the "." character, and the name of the structure member. If a
3832 * structure member to enumerate is itself a structure or array,
3833 * these enumeration rules are applied recursively."
3835 if (outermost_struct_type
== NULL
)
3836 outermost_struct_type
= type
;
3838 unsigned field_location
= location
;
3839 for (unsigned i
= 0; i
< type
->length
; i
++) {
3840 const struct glsl_struct_field
*field
= &type
->fields
.structure
[i
];
3841 char *field_name
= ralloc_asprintf(shProg
, "%s.%s", name
, field
->name
);
3842 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3843 stage_mask
, programInterface
,
3844 var
, field_name
, field
->type
,
3845 use_implicit_location
, field_location
,
3846 false, outermost_struct_type
))
3849 field_location
+= field
->type
->count_attribute_slots(false);
3854 case GLSL_TYPE_ARRAY
: {
3855 /* The ARB_program_interface_query spec says:
3857 * "For an active variable declared as an array of basic types, a
3858 * single entry will be generated, with its name string formed by
3859 * concatenating the name of the array and the string "[0]"."
3861 * "For an active variable declared as an array of an aggregate data
3862 * type (structures or arrays), a separate entry will be generated
3863 * for each active array element, unless noted immediately below.
3864 * The name of each entry is formed by concatenating the name of
3865 * the array, the "[" character, an integer identifying the element
3866 * number, and the "]" character. These enumeration rules are
3867 * applied recursively, treating each enumerated array element as a
3868 * separate active variable."
3870 const struct glsl_type
*array_type
= type
->fields
.array
;
3871 if (array_type
->base_type
== GLSL_TYPE_STRUCT
||
3872 array_type
->base_type
== GLSL_TYPE_ARRAY
) {
3873 unsigned elem_location
= location
;
3874 unsigned stride
= inouts_share_location
? 0 :
3875 array_type
->count_attribute_slots(false);
3876 for (unsigned i
= 0; i
< type
->length
; i
++) {
3877 char *elem
= ralloc_asprintf(shProg
, "%s[%d]", name
, i
);
3878 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3879 stage_mask
, programInterface
,
3880 var
, elem
, array_type
,
3881 use_implicit_location
, elem_location
,
3882 false, outermost_struct_type
))
3884 elem_location
+= stride
;
3892 /* The ARB_program_interface_query spec says:
3894 * "For an active variable declared as a single instance of a basic
3895 * type, a single entry will be generated, using the variable name
3896 * from the shader source."
3898 gl_shader_variable
*sha_v
=
3899 create_shader_variable(shProg
, var
, name
, type
, interface_type
,
3900 use_implicit_location
, location
,
3901 outermost_struct_type
);
3905 return link_util_add_program_resource(shProg
, resource_set
,
3906 programInterface
, sha_v
, stage_mask
);
3912 inout_has_same_location(const ir_variable
*var
, unsigned stage
)
3914 if (!var
->data
.patch
&&
3915 ((var
->data
.mode
== ir_var_shader_out
&&
3916 stage
== MESA_SHADER_TESS_CTRL
) ||
3917 (var
->data
.mode
== ir_var_shader_in
&&
3918 (stage
== MESA_SHADER_TESS_CTRL
|| stage
== MESA_SHADER_TESS_EVAL
||
3919 stage
== MESA_SHADER_GEOMETRY
))))
3926 add_interface_variables(const struct gl_context
*ctx
,
3927 struct gl_shader_program
*shProg
,
3928 struct set
*resource_set
,
3929 unsigned stage
, GLenum programInterface
)
3931 exec_list
*ir
= shProg
->_LinkedShaders
[stage
]->ir
;
3933 foreach_in_list(ir_instruction
, node
, ir
) {
3934 ir_variable
*var
= node
->as_variable();
3936 if (!var
|| var
->data
.how_declared
== ir_var_hidden
)
3941 switch (var
->data
.mode
) {
3942 case ir_var_system_value
:
3943 case ir_var_shader_in
:
3944 if (programInterface
!= GL_PROGRAM_INPUT
)
3946 loc_bias
= (stage
== MESA_SHADER_VERTEX
) ? int(VERT_ATTRIB_GENERIC0
)
3947 : int(VARYING_SLOT_VAR0
);
3949 case ir_var_shader_out
:
3950 if (programInterface
!= GL_PROGRAM_OUTPUT
)
3952 loc_bias
= (stage
== MESA_SHADER_FRAGMENT
) ? int(FRAG_RESULT_DATA0
)
3953 : int(VARYING_SLOT_VAR0
);
3959 if (var
->data
.patch
)
3960 loc_bias
= int(VARYING_SLOT_PATCH0
);
3962 /* Skip packed varyings, packed varyings are handled separately
3963 * by add_packed_varyings.
3965 if (strncmp(var
->name
, "packed:", 7) == 0)
3968 /* Skip fragdata arrays, these are handled separately
3969 * by add_fragdata_arrays.
3971 if (strncmp(var
->name
, "gl_out_FragData", 15) == 0)
3974 const bool vs_input_or_fs_output
=
3975 (stage
== MESA_SHADER_VERTEX
&& var
->data
.mode
== ir_var_shader_in
) ||
3976 (stage
== MESA_SHADER_FRAGMENT
&& var
->data
.mode
== ir_var_shader_out
);
3978 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3979 1 << stage
, programInterface
,
3980 var
, var
->name
, var
->type
, vs_input_or_fs_output
,
3981 var
->data
.location
- loc_bias
,
3982 inout_has_same_location(var
, stage
)))
3989 add_packed_varyings(const struct gl_context
*ctx
,
3990 struct gl_shader_program
*shProg
,
3991 struct set
*resource_set
,
3992 int stage
, GLenum type
)
3994 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[stage
];
3997 if (!sh
|| !sh
->packed_varyings
)
4000 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
4001 ir_variable
*var
= node
->as_variable();
4003 switch (var
->data
.mode
) {
4004 case ir_var_shader_in
:
4005 iface
= GL_PROGRAM_INPUT
;
4007 case ir_var_shader_out
:
4008 iface
= GL_PROGRAM_OUTPUT
;
4011 unreachable("unexpected type");
4014 if (type
== iface
) {
4015 const int stage_mask
=
4016 build_stageref(shProg
, var
->name
, var
->data
.mode
);
4017 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4019 iface
, var
, var
->name
, var
->type
, false,
4020 var
->data
.location
- VARYING_SLOT_VAR0
,
4021 inout_has_same_location(var
, stage
)))
4030 add_fragdata_arrays(const struct gl_context
*ctx
,
4031 struct gl_shader_program
*shProg
,
4032 struct set
*resource_set
)
4034 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4036 if (!sh
|| !sh
->fragdata_arrays
)
4039 foreach_in_list(ir_instruction
, node
, sh
->fragdata_arrays
) {
4040 ir_variable
*var
= node
->as_variable();
4042 assert(var
->data
.mode
== ir_var_shader_out
);
4044 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4045 1 << MESA_SHADER_FRAGMENT
,
4046 GL_PROGRAM_OUTPUT
, var
, var
->name
, var
->type
,
4047 true, var
->data
.location
- FRAG_RESULT_DATA0
,
4056 get_top_level_name(const char *name
)
4058 const char *first_dot
= strchr(name
, '.');
4059 const char *first_square_bracket
= strchr(name
, '[');
4062 /* The ARB_program_interface_query spec says:
4064 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4065 * the number of active array elements of the top-level shader storage
4066 * block member containing to the active variable is written to
4067 * <params>. If the top-level block member is not declared as an
4068 * array, the value one is written to <params>. If the top-level block
4069 * member is an array with no declared size, the value zero is written
4073 /* The buffer variable is on top level.*/
4074 if (!first_square_bracket
&& !first_dot
)
4075 name_size
= strlen(name
);
4076 else if ((!first_square_bracket
||
4077 (first_dot
&& first_dot
< first_square_bracket
)))
4078 name_size
= first_dot
- name
;
4080 name_size
= first_square_bracket
- name
;
4082 return strndup(name
, name_size
);
4086 get_var_name(const char *name
)
4088 const char *first_dot
= strchr(name
, '.');
4091 return strdup(name
);
4093 return strndup(first_dot
+1, strlen(first_dot
) - 1);
4097 is_top_level_shader_storage_block_member(const char* name
,
4098 const char* interface_name
,
4099 const char* field_name
)
4101 bool result
= false;
4103 /* If the given variable is already a top-level shader storage
4104 * block member, then return array_size = 1.
4105 * We could have two possibilities: if we have an instanced
4106 * shader storage block or not instanced.
4108 * For the first, we check create a name as it was in top level and
4109 * compare it with the real name. If they are the same, then
4110 * the variable is already at top-level.
4112 * Full instanced name is: interface name + '.' + var name +
4115 int name_length
= strlen(interface_name
) + 1 + strlen(field_name
) + 1;
4116 char *full_instanced_name
= (char *) calloc(name_length
, sizeof(char));
4117 if (!full_instanced_name
) {
4118 fprintf(stderr
, "%s: Cannot allocate space for name\n", __func__
);
4122 snprintf(full_instanced_name
, name_length
, "%s.%s",
4123 interface_name
, field_name
);
4125 /* Check if its top-level shader storage block member of an
4126 * instanced interface block, or of a unnamed interface block.
4128 if (strcmp(name
, full_instanced_name
) == 0 ||
4129 strcmp(name
, field_name
) == 0)
4132 free(full_instanced_name
);
4137 get_array_size(struct gl_uniform_storage
*uni
, const glsl_struct_field
*field
,
4138 char *interface_name
, char *var_name
)
4140 /* The ARB_program_interface_query spec says:
4142 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4143 * the number of active array elements of the top-level shader storage
4144 * block member containing to the active variable is written to
4145 * <params>. If the top-level block member is not declared as an
4146 * array, the value one is written to <params>. If the top-level block
4147 * member is an array with no declared size, the value zero is written
4150 if (is_top_level_shader_storage_block_member(uni
->name
,
4154 else if (field
->type
->is_unsized_array())
4156 else if (field
->type
->is_array())
4157 return field
->type
->length
;
4163 get_array_stride(struct gl_context
*ctx
, struct gl_uniform_storage
*uni
,
4164 const glsl_type
*iface
, const glsl_struct_field
*field
,
4165 char *interface_name
, char *var_name
)
4167 /* The ARB_program_interface_query spec says:
4169 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
4170 * identifying the stride between array elements of the top-level
4171 * shader storage block member containing the active variable is
4172 * written to <params>. For top-level block members declared as
4173 * arrays, the value written is the difference, in basic machine units,
4174 * between the offsets of the active variable for consecutive elements
4175 * in the top-level array. For top-level block members not declared as
4176 * an array, zero is written to <params>."
4178 if (field
->type
->is_array()) {
4179 const enum glsl_matrix_layout matrix_layout
=
4180 glsl_matrix_layout(field
->matrix_layout
);
4181 bool row_major
= matrix_layout
== GLSL_MATRIX_LAYOUT_ROW_MAJOR
;
4182 const glsl_type
*array_type
= field
->type
->fields
.array
;
4184 if (is_top_level_shader_storage_block_member(uni
->name
,
4189 if (GLSL_INTERFACE_PACKING_STD140
==
4191 get_internal_ifc_packing(ctx
->Const
.UseSTD430AsDefaultPacking
)) {
4192 if (array_type
->is_record() || array_type
->is_array())
4193 return glsl_align(array_type
->std140_size(row_major
), 16);
4195 return MAX2(array_type
->std140_base_alignment(row_major
), 16);
4197 return array_type
->std430_array_stride(row_major
);
4204 calculate_array_size_and_stride(struct gl_context
*ctx
,
4205 struct gl_shader_program
*shProg
,
4206 struct gl_uniform_storage
*uni
)
4208 int block_index
= uni
->block_index
;
4209 int array_size
= -1;
4210 int array_stride
= -1;
4211 char *var_name
= get_top_level_name(uni
->name
);
4212 char *interface_name
=
4213 get_top_level_name(uni
->is_shader_storage
?
4214 shProg
->data
->ShaderStorageBlocks
[block_index
].Name
:
4215 shProg
->data
->UniformBlocks
[block_index
].Name
);
4217 if (strcmp(var_name
, interface_name
) == 0) {
4218 /* Deal with instanced array of SSBOs */
4219 char *temp_name
= get_var_name(uni
->name
);
4221 linker_error(shProg
, "Out of memory during linking.\n");
4222 goto write_top_level_array_size_and_stride
;
4225 var_name
= get_top_level_name(temp_name
);
4228 linker_error(shProg
, "Out of memory during linking.\n");
4229 goto write_top_level_array_size_and_stride
;
4233 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4234 const gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
4238 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
4239 ir_variable
*var
= node
->as_variable();
4240 if (!var
|| !var
->get_interface_type() ||
4241 var
->data
.mode
!= ir_var_shader_storage
)
4244 const glsl_type
*iface
= var
->get_interface_type();
4246 if (strcmp(interface_name
, iface
->name
) != 0)
4249 for (unsigned i
= 0; i
< iface
->length
; i
++) {
4250 const glsl_struct_field
*field
= &iface
->fields
.structure
[i
];
4251 if (strcmp(field
->name
, var_name
) != 0)
4254 array_stride
= get_array_stride(ctx
, uni
, iface
, field
,
4255 interface_name
, var_name
);
4256 array_size
= get_array_size(uni
, field
, interface_name
, var_name
);
4257 goto write_top_level_array_size_and_stride
;
4261 write_top_level_array_size_and_stride
:
4262 free(interface_name
);
4264 uni
->top_level_array_stride
= array_stride
;
4265 uni
->top_level_array_size
= array_size
;
4269 * Builds up a list of program resources that point to existing
4273 build_program_resource_list(struct gl_context
*ctx
,
4274 struct gl_shader_program
*shProg
)
4276 /* Rebuild resource list. */
4277 if (shProg
->data
->ProgramResourceList
) {
4278 ralloc_free(shProg
->data
->ProgramResourceList
);
4279 shProg
->data
->ProgramResourceList
= NULL
;
4280 shProg
->data
->NumProgramResourceList
= 0;
4283 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
4285 /* Determine first input and final output stage. These are used to
4286 * detect which variables should be enumerated in the resource list
4287 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4289 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4290 if (!shProg
->_LinkedShaders
[i
])
4292 if (input_stage
== MESA_SHADER_STAGES
)
4297 /* Empty shader, no resources. */
4298 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
4301 struct set
*resource_set
= _mesa_set_create(NULL
,
4303 _mesa_key_pointer_equal
);
4305 /* Program interface needs to expose varyings in case of SSO. */
4306 if (shProg
->SeparateShader
) {
4307 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4308 input_stage
, GL_PROGRAM_INPUT
))
4311 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4312 output_stage
, GL_PROGRAM_OUTPUT
))
4316 if (!add_fragdata_arrays(ctx
, shProg
, resource_set
))
4319 /* Add inputs and outputs to the resource list. */
4320 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4321 input_stage
, GL_PROGRAM_INPUT
))
4324 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4325 output_stage
, GL_PROGRAM_OUTPUT
))
4328 if (shProg
->last_vert_prog
) {
4329 struct gl_transform_feedback_info
*linked_xfb
=
4330 shProg
->last_vert_prog
->sh
.LinkedTransformFeedback
;
4332 /* Add transform feedback varyings. */
4333 if (linked_xfb
->NumVarying
> 0) {
4334 for (int i
= 0; i
< linked_xfb
->NumVarying
; i
++) {
4335 if (!link_util_add_program_resource(shProg
, resource_set
,
4336 GL_TRANSFORM_FEEDBACK_VARYING
,
4337 &linked_xfb
->Varyings
[i
], 0))
4342 /* Add transform feedback buffers. */
4343 for (unsigned i
= 0; i
< ctx
->Const
.MaxTransformFeedbackBuffers
; i
++) {
4344 if ((linked_xfb
->ActiveBuffers
>> i
) & 1) {
4345 linked_xfb
->Buffers
[i
].Binding
= i
;
4346 if (!link_util_add_program_resource(shProg
, resource_set
,
4347 GL_TRANSFORM_FEEDBACK_BUFFER
,
4348 &linked_xfb
->Buffers
[i
], 0))
4354 /* Add uniforms from uniform storage. */
4355 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4356 /* Do not add uniforms internally used by Mesa. */
4357 if (shProg
->data
->UniformStorage
[i
].hidden
)
4361 build_stageref(shProg
, shProg
->data
->UniformStorage
[i
].name
,
4364 /* Add stagereferences for uniforms in a uniform block. */
4365 bool is_shader_storage
=
4366 shProg
->data
->UniformStorage
[i
].is_shader_storage
;
4367 int block_index
= shProg
->data
->UniformStorage
[i
].block_index
;
4368 if (block_index
!= -1) {
4369 stageref
|= is_shader_storage
?
4370 shProg
->data
->ShaderStorageBlocks
[block_index
].stageref
:
4371 shProg
->data
->UniformBlocks
[block_index
].stageref
;
4374 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
4375 if (!should_add_buffer_variable(shProg
, type
,
4376 shProg
->data
->UniformStorage
[i
].name
))
4379 if (is_shader_storage
) {
4380 calculate_array_size_and_stride(ctx
, shProg
,
4381 &shProg
->data
->UniformStorage
[i
]);
4384 if (!link_util_add_program_resource(shProg
, resource_set
, type
,
4385 &shProg
->data
->UniformStorage
[i
], stageref
))
4389 /* Add program uniform blocks. */
4390 for (unsigned i
= 0; i
< shProg
->data
->NumUniformBlocks
; i
++) {
4391 if (!link_util_add_program_resource(shProg
, resource_set
, GL_UNIFORM_BLOCK
,
4392 &shProg
->data
->UniformBlocks
[i
], 0))
4396 /* Add program shader storage blocks. */
4397 for (unsigned i
= 0; i
< shProg
->data
->NumShaderStorageBlocks
; i
++) {
4398 if (!link_util_add_program_resource(shProg
, resource_set
, GL_SHADER_STORAGE_BLOCK
,
4399 &shProg
->data
->ShaderStorageBlocks
[i
], 0))
4403 /* Add atomic counter buffers. */
4404 for (unsigned i
= 0; i
< shProg
->data
->NumAtomicBuffers
; i
++) {
4405 if (!link_util_add_program_resource(shProg
, resource_set
, GL_ATOMIC_COUNTER_BUFFER
,
4406 &shProg
->data
->AtomicBuffers
[i
], 0))
4410 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4412 if (!shProg
->data
->UniformStorage
[i
].hidden
)
4415 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
4416 if (!shProg
->data
->UniformStorage
[i
].opaque
[j
].active
||
4417 !shProg
->data
->UniformStorage
[i
].type
->is_subroutine())
4420 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
4421 /* add shader subroutines */
4422 if (!link_util_add_program_resource(shProg
, resource_set
,
4423 type
, &shProg
->data
->UniformStorage
[i
], 0))
4428 unsigned mask
= shProg
->data
->linked_stages
;
4430 const int i
= u_bit_scan(&mask
);
4431 struct gl_program
*p
= shProg
->_LinkedShaders
[i
]->Program
;
4433 GLuint type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
4434 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4435 if (!link_util_add_program_resource(shProg
, resource_set
,
4436 type
, &p
->sh
.SubroutineFunctions
[j
], 0))
4441 _mesa_set_destroy(resource_set
, NULL
);
4445 * This check is done to make sure we allow only constant expression
4446 * indexing and "constant-index-expression" (indexing with an expression
4447 * that includes loop induction variable).
4450 validate_sampler_array_indexing(struct gl_context
*ctx
,
4451 struct gl_shader_program
*prog
)
4453 dynamic_sampler_array_indexing_visitor v
;
4454 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4455 if (prog
->_LinkedShaders
[i
] == NULL
)
4458 bool no_dynamic_indexing
=
4459 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
4461 /* Search for array derefs in shader. */
4462 v
.run(prog
->_LinkedShaders
[i
]->ir
);
4463 if (v
.uses_dynamic_sampler_array_indexing()) {
4464 const char *msg
= "sampler arrays indexed with non-constant "
4465 "expressions is forbidden in GLSL %s %u";
4466 /* Backend has indicated that it has no dynamic indexing support. */
4467 if (no_dynamic_indexing
) {
4468 linker_error(prog
, msg
, prog
->IsES
? "ES" : "",
4469 prog
->data
->Version
);
4472 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "",
4473 prog
->data
->Version
);
4481 link_assign_subroutine_types(struct gl_shader_program
*prog
)
4483 unsigned mask
= prog
->data
->linked_stages
;
4485 const int i
= u_bit_scan(&mask
);
4486 gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
4488 p
->sh
.MaxSubroutineFunctionIndex
= 0;
4489 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
4490 ir_function
*fn
= node
->as_function();
4494 if (fn
->is_subroutine
)
4495 p
->sh
.NumSubroutineUniformTypes
++;
4497 if (!fn
->num_subroutine_types
)
4500 /* these should have been calculated earlier. */
4501 assert(fn
->subroutine_index
!= -1);
4502 if (p
->sh
.NumSubroutineFunctions
+ 1 > MAX_SUBROUTINES
) {
4503 linker_error(prog
, "Too many subroutine functions declared.\n");
4506 p
->sh
.SubroutineFunctions
= reralloc(p
, p
->sh
.SubroutineFunctions
,
4507 struct gl_subroutine_function
,
4508 p
->sh
.NumSubroutineFunctions
+ 1);
4509 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].name
= ralloc_strdup(p
, fn
->name
);
4510 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
4511 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
=
4512 ralloc_array(p
, const struct glsl_type
*,
4513 fn
->num_subroutine_types
);
4515 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4518 * "Each subroutine with an index qualifier in the shader must be
4519 * given a unique index, otherwise a compile or link error will be
4522 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4523 if (p
->sh
.SubroutineFunctions
[j
].index
!= -1 &&
4524 p
->sh
.SubroutineFunctions
[j
].index
== fn
->subroutine_index
) {
4525 linker_error(prog
, "each subroutine index qualifier in the "
4526 "shader must be unique\n");
4530 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].index
=
4531 fn
->subroutine_index
;
4533 if (fn
->subroutine_index
> (int)p
->sh
.MaxSubroutineFunctionIndex
)
4534 p
->sh
.MaxSubroutineFunctionIndex
= fn
->subroutine_index
;
4536 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
4537 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
4538 p
->sh
.NumSubroutineFunctions
++;
4544 set_always_active_io(exec_list
*ir
, ir_variable_mode io_mode
)
4546 assert(io_mode
== ir_var_shader_in
|| io_mode
== ir_var_shader_out
);
4548 foreach_in_list(ir_instruction
, node
, ir
) {
4549 ir_variable
*const var
= node
->as_variable();
4551 if (var
== NULL
|| var
->data
.mode
!= io_mode
)
4554 /* Don't set always active on builtins that haven't been redeclared */
4555 if (var
->data
.how_declared
== ir_var_declared_implicitly
)
4558 var
->data
.always_active_io
= true;
4563 * When separate shader programs are enabled, only input/outputs between
4564 * the stages of a multi-stage separate program can be safely removed
4565 * from the shader interface. Other inputs/outputs must remain active.
4568 disable_varying_optimizations_for_sso(struct gl_shader_program
*prog
)
4570 unsigned first
, last
;
4571 assert(prog
->SeparateShader
);
4573 first
= MESA_SHADER_STAGES
;
4576 /* Determine first and last stage. Excluding the compute stage */
4577 for (unsigned i
= 0; i
< MESA_SHADER_COMPUTE
; i
++) {
4578 if (!prog
->_LinkedShaders
[i
])
4580 if (first
== MESA_SHADER_STAGES
)
4585 if (first
== MESA_SHADER_STAGES
)
4588 for (unsigned stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4589 gl_linked_shader
*sh
= prog
->_LinkedShaders
[stage
];
4593 /* Prevent the removal of inputs to the first and outputs from the last
4594 * stage, unless they are the initial pipeline inputs or final pipeline
4595 * outputs, respectively.
4597 * The removal of IO between shaders in the same program is always
4600 if (stage
== first
&& stage
!= MESA_SHADER_VERTEX
)
4601 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4602 if (stage
== last
&& stage
!= MESA_SHADER_FRAGMENT
)
4603 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4608 link_and_validate_uniforms(struct gl_context
*ctx
,
4609 struct gl_shader_program
*prog
)
4611 update_array_sizes(prog
);
4612 link_assign_uniform_locations(prog
, ctx
);
4614 link_assign_atomic_counter_resources(ctx
, prog
);
4615 link_calculate_subroutine_compat(prog
);
4616 check_resources(ctx
, prog
);
4617 check_subroutine_resources(prog
);
4618 check_image_resources(ctx
, prog
);
4619 link_check_atomic_counter_resources(ctx
, prog
);
4623 link_varyings_and_uniforms(unsigned first
, unsigned last
,
4624 struct gl_context
*ctx
,
4625 struct gl_shader_program
*prog
, void *mem_ctx
)
4627 /* Mark all generic shader inputs and outputs as unpaired. */
4628 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4629 if (prog
->_LinkedShaders
[i
] != NULL
) {
4630 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
4634 unsigned prev
= first
;
4635 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4636 if (prog
->_LinkedShaders
[i
] == NULL
)
4639 match_explicit_outputs_to_inputs(prog
->_LinkedShaders
[prev
],
4640 prog
->_LinkedShaders
[i
]);
4644 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4645 MESA_SHADER_VERTEX
)) {
4649 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4650 MESA_SHADER_FRAGMENT
)) {
4654 prog
->last_vert_prog
= NULL
;
4655 for (int i
= MESA_SHADER_GEOMETRY
; i
>= MESA_SHADER_VERTEX
; i
--) {
4656 if (prog
->_LinkedShaders
[i
] == NULL
)
4659 prog
->last_vert_prog
= prog
->_LinkedShaders
[i
]->Program
;
4663 if (!link_varyings(prog
, first
, last
, ctx
, mem_ctx
))
4666 link_and_validate_uniforms(ctx
, prog
);
4668 if (!prog
->data
->LinkStatus
)
4671 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4672 if (prog
->_LinkedShaders
[i
] == NULL
)
4675 const struct gl_shader_compiler_options
*options
=
4676 &ctx
->Const
.ShaderCompilerOptions
[i
];
4678 if (options
->LowerBufferInterfaceBlocks
)
4679 lower_ubo_reference(prog
->_LinkedShaders
[i
],
4680 options
->ClampBlockIndicesToArrayBounds
,
4681 ctx
->Const
.UseSTD430AsDefaultPacking
);
4683 if (i
== MESA_SHADER_COMPUTE
)
4684 lower_shared_reference(ctx
, prog
, prog
->_LinkedShaders
[i
]);
4686 lower_vector_derefs(prog
->_LinkedShaders
[i
]);
4687 do_vec_index_to_swizzle(prog
->_LinkedShaders
[i
]->ir
);
4694 linker_optimisation_loop(struct gl_context
*ctx
, exec_list
*ir
,
4697 if (ctx
->Const
.GLSLOptimizeConservatively
) {
4698 /* Run it just once. */
4699 do_common_optimization(ir
, true, false,
4700 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4701 ctx
->Const
.NativeIntegers
);
4703 /* Repeat it until it stops making changes. */
4704 while (do_common_optimization(ir
, true, false,
4705 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4706 ctx
->Const
.NativeIntegers
))
4712 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
4714 prog
->data
->LinkStatus
= LINKING_SUCCESS
; /* All error paths will set this to false */
4715 prog
->data
->Validated
= false;
4717 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4719 * "Linking can fail for a variety of reasons as specified in the
4720 * OpenGL Shading Language Specification, as well as any of the
4721 * following reasons:
4723 * - No shader objects are attached to program."
4725 * The Compatibility Profile specification does not list the error. In
4726 * Compatibility Profile missing shader stages are replaced by
4727 * fixed-function. This applies to the case where all stages are
4730 if (prog
->NumShaders
== 0) {
4731 if (ctx
->API
!= API_OPENGL_COMPAT
)
4732 linker_error(prog
, "no shaders attached to the program\n");
4736 #ifdef ENABLE_SHADER_CACHE
4737 if (shader_cache_read_program_metadata(ctx
, prog
))
4741 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
4743 prog
->ARB_fragment_coord_conventions_enable
= false;
4745 /* Separate the shaders into groups based on their type.
4747 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
4748 unsigned num_shaders
[MESA_SHADER_STAGES
];
4750 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4751 shader_list
[i
] = (struct gl_shader
**)
4752 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
4756 unsigned min_version
= UINT_MAX
;
4757 unsigned max_version
= 0;
4758 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
4759 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
4760 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
4762 if (!ctx
->Const
.AllowGLSLRelaxedES
&&
4763 prog
->Shaders
[i
]->IsES
!= prog
->Shaders
[0]->IsES
) {
4764 linker_error(prog
, "all shaders must use same shading "
4765 "language version\n");
4769 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
4770 prog
->ARB_fragment_coord_conventions_enable
= true;
4773 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
4774 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
4775 num_shaders
[shader_type
]++;
4778 /* In desktop GLSL, different shader versions may be linked together. In
4779 * GLSL ES, all shader versions must be the same.
4781 if (!ctx
->Const
.AllowGLSLRelaxedES
&& prog
->Shaders
[0]->IsES
&&
4782 min_version
!= max_version
) {
4783 linker_error(prog
, "all shaders must use same shading "
4784 "language version\n");
4788 prog
->data
->Version
= max_version
;
4789 prog
->IsES
= prog
->Shaders
[0]->IsES
;
4791 /* Some shaders have to be linked with some other shaders present.
4793 if (!prog
->SeparateShader
) {
4794 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
4795 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4796 linker_error(prog
, "Geometry shader must be linked with "
4800 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4801 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4802 linker_error(prog
, "Tessellation evaluation shader must be linked "
4803 "with vertex shader\n");
4806 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4807 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4808 linker_error(prog
, "Tessellation control shader must be linked with "
4813 /* Section 7.3 of the OpenGL ES 3.2 specification says:
4815 * "Linking can fail for [...] any of the following reasons:
4817 * * program contains an object to form a tessellation control
4818 * shader [...] and [...] the program is not separable and
4819 * contains no object to form a tessellation evaluation shader"
4821 * The OpenGL spec is contradictory. It allows linking without a tess
4822 * eval shader, but that can only be used with transform feedback and
4823 * rasterization disabled. However, transform feedback isn't allowed
4824 * with GL_PATCHES, so it can't be used.
4826 * More investigation showed that the idea of transform feedback after
4827 * a tess control shader was dropped, because some hw vendors couldn't
4828 * support tessellation without a tess eval shader, but the linker
4829 * section wasn't updated to reflect that.
4831 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4834 * Do what's reasonable and always require a tess eval shader if a tess
4835 * control shader is present.
4837 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4838 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0) {
4839 linker_error(prog
, "Tessellation control shader must be linked with "
4840 "tessellation evaluation shader\n");
4845 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4846 num_shaders
[MESA_SHADER_TESS_CTRL
] == 0) {
4847 linker_error(prog
, "GLSL ES requires non-separable programs "
4848 "containing a tessellation evaluation shader to also "
4849 "be linked with a tessellation control shader\n");
4855 /* Compute shaders have additional restrictions. */
4856 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
4857 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
4858 linker_error(prog
, "Compute shaders may not be linked with any other "
4859 "type of shader\n");
4862 /* Link all shaders for a particular stage and validate the result.
4864 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4865 if (num_shaders
[stage
] > 0) {
4866 gl_linked_shader
*const sh
=
4867 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
4868 num_shaders
[stage
], false);
4870 if (!prog
->data
->LinkStatus
) {
4872 _mesa_delete_linked_shader(ctx
, sh
);
4877 case MESA_SHADER_VERTEX
:
4878 validate_vertex_shader_executable(prog
, sh
, ctx
);
4880 case MESA_SHADER_TESS_CTRL
:
4881 /* nothing to be done */
4883 case MESA_SHADER_TESS_EVAL
:
4884 validate_tess_eval_shader_executable(prog
, sh
, ctx
);
4886 case MESA_SHADER_GEOMETRY
:
4887 validate_geometry_shader_executable(prog
, sh
, ctx
);
4889 case MESA_SHADER_FRAGMENT
:
4890 validate_fragment_shader_executable(prog
, sh
);
4893 if (!prog
->data
->LinkStatus
) {
4895 _mesa_delete_linked_shader(ctx
, sh
);
4899 prog
->_LinkedShaders
[stage
] = sh
;
4900 prog
->data
->linked_stages
|= 1 << stage
;
4904 /* Here begins the inter-stage linking phase. Some initial validation is
4905 * performed, then locations are assigned for uniforms, attributes, and
4908 cross_validate_uniforms(ctx
, prog
);
4909 if (!prog
->data
->LinkStatus
)
4912 unsigned first
, last
, prev
;
4914 first
= MESA_SHADER_STAGES
;
4917 /* Determine first and last stage. */
4918 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4919 if (!prog
->_LinkedShaders
[i
])
4921 if (first
== MESA_SHADER_STAGES
)
4926 check_explicit_uniform_locations(ctx
, prog
);
4927 link_assign_subroutine_types(prog
);
4929 if (!prog
->data
->LinkStatus
)
4932 resize_tes_inputs(ctx
, prog
);
4934 /* Validate the inputs of each stage with the output of the preceding
4938 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4939 if (prog
->_LinkedShaders
[i
] == NULL
)
4942 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
4943 prog
->_LinkedShaders
[i
]);
4944 if (!prog
->data
->LinkStatus
)
4947 cross_validate_outputs_to_inputs(ctx
, prog
,
4948 prog
->_LinkedShaders
[prev
],
4949 prog
->_LinkedShaders
[i
]);
4950 if (!prog
->data
->LinkStatus
)
4956 /* The cross validation of outputs/inputs above validates explicit locations
4957 * but for SSO programs we need to do this also for the inputs in the
4958 * first stage and outputs of the last stage included in the program, since
4959 * there is no cross validation for these.
4961 if (prog
->SeparateShader
)
4962 validate_sso_explicit_locations(ctx
, prog
,
4963 (gl_shader_stage
) first
,
4964 (gl_shader_stage
) last
);
4966 /* Cross-validate uniform blocks between shader stages */
4967 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
);
4968 if (!prog
->data
->LinkStatus
)
4971 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4972 if (prog
->_LinkedShaders
[i
] != NULL
)
4973 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
4976 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4977 * it before optimization because we want most of the checks to get
4978 * dropped thanks to constant propagation.
4980 * This rule also applies to GLSL ES 3.00.
4982 if (max_version
>= (prog
->IsES
? 300 : 130)) {
4983 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4985 lower_discard_flow(sh
->ir
);
4989 if (prog
->SeparateShader
)
4990 disable_varying_optimizations_for_sso(prog
);
4993 if (!interstage_cross_validate_uniform_blocks(prog
, false))
4997 if (!interstage_cross_validate_uniform_blocks(prog
, true))
5000 /* Do common optimization before assigning storage for attributes,
5001 * uniforms, and varyings. Later optimization could possibly make
5002 * some of that unused.
5004 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5005 if (prog
->_LinkedShaders
[i
] == NULL
)
5008 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
5009 if (!prog
->data
->LinkStatus
)
5012 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerCombinedClipCullDistance
) {
5013 lower_clip_cull_distance(prog
, prog
->_LinkedShaders
[i
]);
5016 if (ctx
->Const
.LowerTessLevel
) {
5017 lower_tess_level(prog
->_LinkedShaders
[i
]);
5020 /* Call opts before lowering const arrays to uniforms so we can const
5021 * propagate any elements accessed directly.
5023 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
5025 /* Call opts after lowering const arrays to copy propagate things. */
5026 if (lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
, i
))
5027 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
5029 propagate_invariance(prog
->_LinkedShaders
[i
]->ir
);
5032 /* Validation for special cases where we allow sampler array indexing
5033 * with loop induction variable. This check emits a warning or error
5034 * depending if backend can handle dynamic indexing.
5036 if ((!prog
->IsES
&& prog
->data
->Version
< 130) ||
5037 (prog
->IsES
&& prog
->data
->Version
< 300)) {
5038 if (!validate_sampler_array_indexing(ctx
, prog
))
5042 /* Check and validate stream emissions in geometry shaders */
5043 validate_geometry_shader_emissions(ctx
, prog
);
5045 store_fragdepth_layout(prog
);
5047 if(!link_varyings_and_uniforms(first
, last
, ctx
, prog
, mem_ctx
))
5050 /* Linking varyings can cause some extra, useless swizzles to be generated
5051 * due to packing and unpacking.
5053 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5054 if (prog
->_LinkedShaders
[i
] == NULL
)
5057 optimize_swizzles(prog
->_LinkedShaders
[i
]->ir
);
5060 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
5061 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
5062 * anything about shader linking when one of the shaders (vertex or
5063 * fragment shader) is absent. So, the extension shouldn't change the
5064 * behavior specified in GLSL specification.
5066 * From OpenGL ES 3.1 specification (7.3 Program Objects):
5067 * "Linking can fail for a variety of reasons as specified in the
5068 * OpenGL ES Shading Language Specification, as well as any of the
5069 * following reasons:
5073 * * program contains objects to form either a vertex shader or
5074 * fragment shader, and program is not separable, and does not
5075 * contain objects to form both a vertex shader and fragment
5078 * However, the only scenario in 3.1+ where we don't require them both is
5079 * when we have a compute shader. For example:
5081 * - No shaders is a link error.
5082 * - Geom or Tess without a Vertex shader is a link error which means we
5083 * always require a Vertex shader and hence a Fragment shader.
5084 * - Finally a Compute shader linked with any other stage is a link error.
5086 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
&&
5087 num_shaders
[MESA_SHADER_COMPUTE
] == 0) {
5088 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
5089 linker_error(prog
, "program lacks a vertex shader\n");
5090 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
5091 linker_error(prog
, "program lacks a fragment shader\n");
5096 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5097 free(shader_list
[i
]);
5098 if (prog
->_LinkedShaders
[i
] == NULL
)
5101 /* Do a final validation step to make sure that the IR wasn't
5102 * invalidated by any modifications performed after intrastage linking.
5104 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
5106 /* Retain any live IR, but trash the rest. */
5107 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
5109 /* The symbol table in the linked shaders may contain references to
5110 * variables that were removed (e.g., unused uniforms). Since it may
5111 * contain junk, there is no possible valid use. Delete it and set the
5114 delete prog
->_LinkedShaders
[i
]->symbols
;
5115 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
5118 ralloc_free(mem_ctx
);