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 "link_varyings.h"
80 #include "ir_optimization.h"
81 #include "ir_rvalue_visitor.h"
82 #include "ir_uniform.h"
83 #include "builtin_functions.h"
84 #include "shader_cache.h"
86 #include "main/imports.h"
87 #include "main/shaderobj.h"
88 #include "main/enums.h"
89 #include "main/mtypes.h"
94 struct find_variable
{
98 find_variable(const char *name
) : name(name
), found(false) {}
102 * Visitor that determines whether or not a variable is ever written.
104 * Use \ref find_assignments for convenience.
106 class find_assignment_visitor
: public ir_hierarchical_visitor
{
108 find_assignment_visitor(unsigned num_vars
,
109 find_variable
* const *vars
)
110 : num_variables(num_vars
), num_found(0), variables(vars
)
114 virtual ir_visitor_status
visit_enter(ir_assignment
*ir
)
116 ir_variable
*const var
= ir
->lhs
->variable_referenced();
118 return check_variable_name(var
->name
);
121 virtual ir_visitor_status
visit_enter(ir_call
*ir
)
123 foreach_two_lists(formal_node
, &ir
->callee
->parameters
,
124 actual_node
, &ir
->actual_parameters
) {
125 ir_rvalue
*param_rval
= (ir_rvalue
*) actual_node
;
126 ir_variable
*sig_param
= (ir_variable
*) formal_node
;
128 if (sig_param
->data
.mode
== ir_var_function_out
||
129 sig_param
->data
.mode
== ir_var_function_inout
) {
130 ir_variable
*var
= param_rval
->variable_referenced();
131 if (var
&& check_variable_name(var
->name
) == visit_stop
)
136 if (ir
->return_deref
!= NULL
) {
137 ir_variable
*const var
= ir
->return_deref
->variable_referenced();
139 if (check_variable_name(var
->name
) == visit_stop
)
143 return visit_continue_with_parent
;
147 ir_visitor_status
check_variable_name(const char *name
)
149 for (unsigned i
= 0; i
< num_variables
; ++i
) {
150 if (strcmp(variables
[i
]->name
, name
) == 0) {
151 if (!variables
[i
]->found
) {
152 variables
[i
]->found
= true;
154 assert(num_found
< num_variables
);
155 if (++num_found
== num_variables
)
162 return visit_continue_with_parent
;
166 unsigned num_variables
; /**< Number of variables to find */
167 unsigned num_found
; /**< Number of variables already found */
168 find_variable
* const *variables
; /**< Variables to find */
172 * Determine whether or not any of NULL-terminated list of variables is ever
176 find_assignments(exec_list
*ir
, find_variable
* const *vars
)
178 unsigned num_variables
= 0;
180 for (find_variable
* const *v
= vars
; *v
; ++v
)
183 find_assignment_visitor
visitor(num_variables
, vars
);
188 * Determine whether or not the given variable is ever written to.
191 find_assignments(exec_list
*ir
, find_variable
*var
)
193 find_assignment_visitor
visitor(1, &var
);
198 * Visitor that determines whether or not a variable is ever read.
200 class find_deref_visitor
: public ir_hierarchical_visitor
{
202 find_deref_visitor(const char *name
)
203 : name(name
), found(false)
208 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
210 if (strcmp(this->name
, ir
->var
->name
) == 0) {
215 return visit_continue
;
218 bool variable_found() const
224 const char *name
; /**< Find writes to a variable with this name. */
225 bool found
; /**< Was a write to the variable found? */
230 * A visitor helper that provides methods for updating the types of
231 * ir_dereferences. Classes that update variable types (say, updating
232 * array sizes) will want to use this so that dereference types stay in sync.
234 class deref_type_updater
: public ir_hierarchical_visitor
{
236 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
238 ir
->type
= ir
->var
->type
;
239 return visit_continue
;
242 virtual ir_visitor_status
visit_leave(ir_dereference_array
*ir
)
244 const glsl_type
*const vt
= ir
->array
->type
;
246 ir
->type
= vt
->fields
.array
;
247 return visit_continue
;
250 virtual ir_visitor_status
visit_leave(ir_dereference_record
*ir
)
252 ir
->type
= ir
->record
->type
->fields
.structure
[ir
->field_idx
].type
;
253 return visit_continue
;
258 class array_resize_visitor
: public deref_type_updater
{
260 unsigned num_vertices
;
261 gl_shader_program
*prog
;
262 gl_shader_stage stage
;
264 array_resize_visitor(unsigned num_vertices
,
265 gl_shader_program
*prog
,
266 gl_shader_stage stage
)
268 this->num_vertices
= num_vertices
;
273 virtual ~array_resize_visitor()
278 virtual ir_visitor_status
visit(ir_variable
*var
)
280 if (!var
->type
->is_array() || var
->data
.mode
!= ir_var_shader_in
||
282 return visit_continue
;
284 unsigned size
= var
->type
->length
;
286 if (stage
== MESA_SHADER_GEOMETRY
) {
287 /* Generate a link error if the shader has declared this array with
290 if (!var
->data
.implicit_sized_array
&&
291 size
&& size
!= this->num_vertices
) {
292 linker_error(this->prog
, "size of array %s declared as %u, "
293 "but number of input vertices is %u\n",
294 var
->name
, size
, this->num_vertices
);
295 return visit_continue
;
298 /* Generate a link error if the shader attempts to access an input
299 * array using an index too large for its actual size assigned at
302 if (var
->data
.max_array_access
>= (int)this->num_vertices
) {
303 linker_error(this->prog
, "%s shader accesses element %i of "
304 "%s, but only %i input vertices\n",
305 _mesa_shader_stage_to_string(this->stage
),
306 var
->data
.max_array_access
, var
->name
, this->num_vertices
);
307 return visit_continue
;
311 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
313 var
->data
.max_array_access
= this->num_vertices
- 1;
315 return visit_continue
;
320 * Visitor that determines the highest stream id to which a (geometry) shader
321 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
323 class find_emit_vertex_visitor
: public ir_hierarchical_visitor
{
325 find_emit_vertex_visitor(int max_allowed
)
326 : max_stream_allowed(max_allowed
),
327 invalid_stream_id(0),
328 invalid_stream_id_from_emit_vertex(false),
329 end_primitive_found(false),
330 uses_non_zero_stream(false)
335 virtual ir_visitor_status
visit_leave(ir_emit_vertex
*ir
)
337 int stream_id
= ir
->stream_id();
340 invalid_stream_id
= stream_id
;
341 invalid_stream_id_from_emit_vertex
= true;
345 if (stream_id
> max_stream_allowed
) {
346 invalid_stream_id
= stream_id
;
347 invalid_stream_id_from_emit_vertex
= true;
352 uses_non_zero_stream
= true;
354 return visit_continue
;
357 virtual ir_visitor_status
visit_leave(ir_end_primitive
*ir
)
359 end_primitive_found
= true;
361 int stream_id
= ir
->stream_id();
364 invalid_stream_id
= stream_id
;
365 invalid_stream_id_from_emit_vertex
= false;
369 if (stream_id
> max_stream_allowed
) {
370 invalid_stream_id
= stream_id
;
371 invalid_stream_id_from_emit_vertex
= false;
376 uses_non_zero_stream
= true;
378 return visit_continue
;
383 return invalid_stream_id
!= 0;
386 const char *error_func()
388 return invalid_stream_id_from_emit_vertex
?
389 "EmitStreamVertex" : "EndStreamPrimitive";
394 return invalid_stream_id
;
399 return uses_non_zero_stream
;
402 bool uses_end_primitive()
404 return end_primitive_found
;
408 int max_stream_allowed
;
409 int invalid_stream_id
;
410 bool invalid_stream_id_from_emit_vertex
;
411 bool end_primitive_found
;
412 bool uses_non_zero_stream
;
415 /* Class that finds array derefs and check if indexes are dynamic. */
416 class dynamic_sampler_array_indexing_visitor
: public ir_hierarchical_visitor
419 dynamic_sampler_array_indexing_visitor() :
420 dynamic_sampler_array_indexing(false)
424 ir_visitor_status
visit_enter(ir_dereference_array
*ir
)
426 if (!ir
->variable_referenced())
427 return visit_continue
;
429 if (!ir
->variable_referenced()->type
->contains_sampler())
430 return visit_continue
;
432 if (!ir
->array_index
->constant_expression_value(ralloc_parent(ir
))) {
433 dynamic_sampler_array_indexing
= true;
436 return visit_continue
;
439 bool uses_dynamic_sampler_array_indexing()
441 return dynamic_sampler_array_indexing
;
445 bool dynamic_sampler_array_indexing
;
448 } /* anonymous namespace */
451 linker_error(gl_shader_program
*prog
, const char *fmt
, ...)
455 ralloc_strcat(&prog
->data
->InfoLog
, "error: ");
457 ralloc_vasprintf_append(&prog
->data
->InfoLog
, fmt
, ap
);
460 prog
->data
->LinkStatus
= LINKING_FAILURE
;
465 linker_warning(gl_shader_program
*prog
, const char *fmt
, ...)
469 ralloc_strcat(&prog
->data
->InfoLog
, "warning: ");
471 ralloc_vasprintf_append(&prog
->data
->InfoLog
, fmt
, ap
);
478 * Given a string identifying a program resource, break it into a base name
479 * and an optional array index in square brackets.
481 * If an array index is present, \c out_base_name_end is set to point to the
482 * "[" that precedes the array index, and the array index itself is returned
485 * If no array index is present (or if the array index is negative or
486 * mal-formed), \c out_base_name_end, is set to point to the null terminator
487 * at the end of the input string, and -1 is returned.
489 * Only the final array index is parsed; if the string contains other array
490 * indices (or structure field accesses), they are left in the base name.
492 * No attempt is made to check that the base name is properly formed;
493 * typically the caller will look up the base name in a hash table, so
494 * ill-formed base names simply turn into hash table lookup failures.
497 parse_program_resource_name(const GLchar
*name
,
498 const GLchar
**out_base_name_end
)
500 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
502 * "When an integer array element or block instance number is part of
503 * the name string, it will be specified in decimal form without a "+"
504 * or "-" sign or any extra leading zeroes. Additionally, the name
505 * string will not include white space anywhere in the string."
508 const size_t len
= strlen(name
);
509 *out_base_name_end
= name
+ len
;
511 if (len
== 0 || name
[len
-1] != ']')
514 /* Walk backwards over the string looking for a non-digit character. This
515 * had better be the opening bracket for an array index.
517 * Initially, i specifies the location of the ']'. Since the string may
518 * contain only the ']' charcater, walk backwards very carefully.
521 for (i
= len
- 1; (i
> 0) && isdigit(name
[i
-1]); --i
)
524 if ((i
== 0) || name
[i
-1] != '[')
527 long array_index
= strtol(&name
[i
], NULL
, 10);
531 /* Check for leading zero */
532 if (name
[i
] == '0' && name
[i
+1] != ']')
535 *out_base_name_end
= name
+ (i
- 1);
541 link_invalidate_variable_locations(exec_list
*ir
)
543 foreach_in_list(ir_instruction
, node
, ir
) {
544 ir_variable
*const var
= node
->as_variable();
549 /* Only assign locations for variables that lack an explicit location.
550 * Explicit locations are set for all built-in variables, generic vertex
551 * shader inputs (via layout(location=...)), and generic fragment shader
552 * outputs (also via layout(location=...)).
554 if (!var
->data
.explicit_location
) {
555 var
->data
.location
= -1;
556 var
->data
.location_frac
= 0;
559 /* ir_variable::is_unmatched_generic_inout is used by the linker while
560 * connecting outputs from one stage to inputs of the next stage.
562 if (var
->data
.explicit_location
&&
563 var
->data
.location
< VARYING_SLOT_VAR0
) {
564 var
->data
.is_unmatched_generic_inout
= 0;
566 var
->data
.is_unmatched_generic_inout
= 1;
573 * Set clip_distance_array_size based and cull_distance_array_size on the given
576 * Also check for errors based on incorrect usage of gl_ClipVertex and
577 * gl_ClipDistance and gl_CullDistance.
578 * Additionally test whether the arrays gl_ClipDistance and gl_CullDistance
579 * exceed the maximum size defined by gl_MaxCombinedClipAndCullDistances.
581 * Return false if an error was reported.
584 analyze_clip_cull_usage(struct gl_shader_program
*prog
,
585 struct gl_linked_shader
*shader
,
586 struct gl_context
*ctx
,
587 GLuint
*clip_distance_array_size
,
588 GLuint
*cull_distance_array_size
)
590 *clip_distance_array_size
= 0;
591 *cull_distance_array_size
= 0;
593 if (prog
->data
->Version
>= (prog
->IsES
? 300 : 130)) {
594 /* From section 7.1 (Vertex Shader Special Variables) of the
597 * "It is an error for a shader to statically write both
598 * gl_ClipVertex and gl_ClipDistance."
600 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
601 * gl_ClipVertex nor gl_ClipDistance. However with
602 * GL_EXT_clip_cull_distance, this functionality is exposed in ES 3.0.
604 find_variable
gl_ClipDistance("gl_ClipDistance");
605 find_variable
gl_CullDistance("gl_CullDistance");
606 find_variable
gl_ClipVertex("gl_ClipVertex");
607 find_variable
* const variables
[] = {
610 !prog
->IsES
? &gl_ClipVertex
: NULL
,
613 find_assignments(shader
->ir
, variables
);
615 /* From the ARB_cull_distance spec:
617 * It is a compile-time or link-time error for the set of shaders forming
618 * a program to statically read or write both gl_ClipVertex and either
619 * gl_ClipDistance or gl_CullDistance.
621 * This does not apply to GLSL ES shaders, since GLSL ES doesn't define
625 if (gl_ClipVertex
.found
&& gl_ClipDistance
.found
) {
626 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
627 "and `gl_ClipDistance'\n",
628 _mesa_shader_stage_to_string(shader
->Stage
));
631 if (gl_ClipVertex
.found
&& gl_CullDistance
.found
) {
632 linker_error(prog
, "%s shader writes to both `gl_ClipVertex' "
633 "and `gl_CullDistance'\n",
634 _mesa_shader_stage_to_string(shader
->Stage
));
639 if (gl_ClipDistance
.found
) {
640 ir_variable
*clip_distance_var
=
641 shader
->symbols
->get_variable("gl_ClipDistance");
642 assert(clip_distance_var
);
643 *clip_distance_array_size
= clip_distance_var
->type
->length
;
645 if (gl_CullDistance
.found
) {
646 ir_variable
*cull_distance_var
=
647 shader
->symbols
->get_variable("gl_CullDistance");
648 assert(cull_distance_var
);
649 *cull_distance_array_size
= cull_distance_var
->type
->length
;
651 /* From the ARB_cull_distance spec:
653 * It is a compile-time or link-time error for the set of shaders forming
654 * a program to have the sum of the sizes of the gl_ClipDistance and
655 * gl_CullDistance arrays to be larger than
656 * gl_MaxCombinedClipAndCullDistances.
658 if ((*clip_distance_array_size
+ *cull_distance_array_size
) >
659 ctx
->Const
.MaxClipPlanes
) {
660 linker_error(prog
, "%s shader: the combined size of "
661 "'gl_ClipDistance' and 'gl_CullDistance' size cannot "
663 "gl_MaxCombinedClipAndCullDistances (%u)",
664 _mesa_shader_stage_to_string(shader
->Stage
),
665 ctx
->Const
.MaxClipPlanes
);
672 * Verify that a vertex shader executable meets all semantic requirements.
674 * Also sets info.clip_distance_array_size and
675 * info.cull_distance_array_size as a side effect.
677 * \param shader Vertex shader executable to be verified
680 validate_vertex_shader_executable(struct gl_shader_program
*prog
,
681 struct gl_linked_shader
*shader
,
682 struct gl_context
*ctx
)
687 /* From the GLSL 1.10 spec, page 48:
689 * "The variable gl_Position is available only in the vertex
690 * language and is intended for writing the homogeneous vertex
691 * position. All executions of a well-formed vertex shader
692 * executable must write a value into this variable. [...] The
693 * variable gl_Position is available only in the vertex
694 * language and is intended for writing the homogeneous vertex
695 * position. All executions of a well-formed vertex shader
696 * executable must write a value into this variable."
698 * while in GLSL 1.40 this text is changed to:
700 * "The variable gl_Position is available only in the vertex
701 * language and is intended for writing the homogeneous vertex
702 * position. It can be written at any time during shader
703 * execution. It may also be read back by a vertex shader
704 * after being written. This value will be used by primitive
705 * assembly, clipping, culling, and other fixed functionality
706 * operations, if present, that operate on primitives after
707 * vertex processing has occurred. Its value is undefined if
708 * the vertex shader executable does not write gl_Position."
710 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
711 * gl_Position is not an error.
713 if (prog
->data
->Version
< (prog
->IsES
? 300 : 140)) {
714 find_variable
gl_Position("gl_Position");
715 find_assignments(shader
->ir
, &gl_Position
);
716 if (!gl_Position
.found
) {
719 "vertex shader does not write to `gl_Position'. "
720 "Its value is undefined. \n");
723 "vertex shader does not write to `gl_Position'. \n");
729 analyze_clip_cull_usage(prog
, shader
, ctx
,
730 &shader
->Program
->info
.clip_distance_array_size
,
731 &shader
->Program
->info
.cull_distance_array_size
);
735 validate_tess_eval_shader_executable(struct gl_shader_program
*prog
,
736 struct gl_linked_shader
*shader
,
737 struct gl_context
*ctx
)
742 analyze_clip_cull_usage(prog
, shader
, ctx
,
743 &shader
->Program
->info
.clip_distance_array_size
,
744 &shader
->Program
->info
.cull_distance_array_size
);
749 * Verify that a fragment shader executable meets all semantic requirements
751 * \param shader Fragment shader executable to be verified
754 validate_fragment_shader_executable(struct gl_shader_program
*prog
,
755 struct gl_linked_shader
*shader
)
760 find_variable
gl_FragColor("gl_FragColor");
761 find_variable
gl_FragData("gl_FragData");
762 find_variable
* const variables
[] = { &gl_FragColor
, &gl_FragData
, NULL
};
763 find_assignments(shader
->ir
, variables
);
765 if (gl_FragColor
.found
&& gl_FragData
.found
) {
766 linker_error(prog
, "fragment shader writes to both "
767 "`gl_FragColor' and `gl_FragData'\n");
772 * Verify that a geometry shader executable meets all semantic requirements
774 * Also sets prog->Geom.VerticesIn, and info.clip_distance_array_sizeand
775 * info.cull_distance_array_size as a side effect.
777 * \param shader Geometry shader executable to be verified
780 validate_geometry_shader_executable(struct gl_shader_program
*prog
,
781 struct gl_linked_shader
*shader
,
782 struct gl_context
*ctx
)
787 unsigned num_vertices
=
788 vertices_per_prim(shader
->Program
->info
.gs
.input_primitive
);
789 prog
->Geom
.VerticesIn
= num_vertices
;
791 analyze_clip_cull_usage(prog
, shader
, ctx
,
792 &shader
->Program
->info
.clip_distance_array_size
,
793 &shader
->Program
->info
.cull_distance_array_size
);
797 * Check if geometry shaders emit to non-zero streams and do corresponding
801 validate_geometry_shader_emissions(struct gl_context
*ctx
,
802 struct gl_shader_program
*prog
)
804 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_GEOMETRY
];
807 find_emit_vertex_visitor
emit_vertex(ctx
->Const
.MaxVertexStreams
- 1);
808 emit_vertex
.run(sh
->ir
);
809 if (emit_vertex
.error()) {
810 linker_error(prog
, "Invalid call %s(%d). Accepted values for the "
811 "stream parameter are in the range [0, %d].\n",
812 emit_vertex
.error_func(),
813 emit_vertex
.error_stream(),
814 ctx
->Const
.MaxVertexStreams
- 1);
816 prog
->Geom
.UsesStreams
= emit_vertex
.uses_streams();
817 prog
->Geom
.UsesEndPrimitive
= emit_vertex
.uses_end_primitive();
819 /* From the ARB_gpu_shader5 spec:
821 * "Multiple vertex streams are supported only if the output primitive
822 * type is declared to be "points". A program will fail to link if it
823 * contains a geometry shader calling EmitStreamVertex() or
824 * EndStreamPrimitive() if its output primitive type is not "points".
826 * However, in the same spec:
828 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
829 * with <stream> set to zero."
833 * "The function EndPrimitive() is equivalent to calling
834 * EndStreamPrimitive() with <stream> set to zero."
836 * Since we can call EmitVertex() and EndPrimitive() when we output
837 * primitives other than points, calling EmitStreamVertex(0) or
838 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
839 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
840 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
843 if (prog
->Geom
.UsesStreams
&&
844 sh
->Program
->info
.gs
.output_primitive
!= GL_POINTS
) {
845 linker_error(prog
, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
846 "with n>0 requires point output\n");
852 validate_intrastage_arrays(struct gl_shader_program
*prog
,
853 ir_variable
*const var
,
854 ir_variable
*const existing
)
856 /* Consider the types to be "the same" if both types are arrays
857 * of the same type and one of the arrays is implicitly sized.
858 * In addition, set the type of the linked variable to the
859 * explicitly sized array.
861 if (var
->type
->is_array() && existing
->type
->is_array()) {
862 if ((var
->type
->fields
.array
== existing
->type
->fields
.array
) &&
863 ((var
->type
->length
== 0)|| (existing
->type
->length
== 0))) {
864 if (var
->type
->length
!= 0) {
865 if ((int)var
->type
->length
<= existing
->data
.max_array_access
) {
866 linker_error(prog
, "%s `%s' declared as type "
867 "`%s' but outermost dimension has an index"
870 var
->name
, var
->type
->name
,
871 existing
->data
.max_array_access
);
873 existing
->type
= var
->type
;
875 } else if (existing
->type
->length
!= 0) {
876 if((int)existing
->type
->length
<= var
->data
.max_array_access
&&
877 !existing
->data
.from_ssbo_unsized_array
) {
878 linker_error(prog
, "%s `%s' declared as type "
879 "`%s' but outermost dimension has an index"
882 var
->name
, existing
->type
->name
,
883 var
->data
.max_array_access
);
894 * Perform validation of global variables used across multiple shaders
897 cross_validate_globals(struct gl_shader_program
*prog
,
898 struct exec_list
*ir
, glsl_symbol_table
*variables
,
901 foreach_in_list(ir_instruction
, node
, ir
) {
902 ir_variable
*const var
= node
->as_variable();
907 if (uniforms_only
&& (var
->data
.mode
!= ir_var_uniform
&& var
->data
.mode
!= ir_var_shader_storage
))
910 /* don't cross validate subroutine uniforms */
911 if (var
->type
->contains_subroutine())
914 /* Don't cross validate interface instances. These are only relevant
915 * inside a shader. The cross validation is done at the Interface Block
918 if (var
->is_interface_instance())
921 /* Don't cross validate temporaries that are at global scope. These
922 * will eventually get pulled into the shaders 'main'.
924 if (var
->data
.mode
== ir_var_temporary
)
927 /* If a global with this name has already been seen, verify that the
928 * new instance has the same type. In addition, if the globals have
929 * initializers, the values of the initializers must be the same.
931 ir_variable
*const existing
= variables
->get_variable(var
->name
);
932 if (existing
!= NULL
) {
933 /* Check if types match. */
934 if (var
->type
!= existing
->type
) {
935 if (!validate_intrastage_arrays(prog
, var
, existing
)) {
936 /* If it is an unsized array in a Shader Storage Block,
937 * two different shaders can access to different elements.
938 * Because of that, they might be converted to different
939 * sized arrays, then check that they are compatible but
940 * ignore the array size.
942 if (!(var
->data
.mode
== ir_var_shader_storage
&&
943 var
->data
.from_ssbo_unsized_array
&&
944 existing
->data
.mode
== ir_var_shader_storage
&&
945 existing
->data
.from_ssbo_unsized_array
&&
946 var
->type
->gl_type
== existing
->type
->gl_type
)) {
947 linker_error(prog
, "%s `%s' declared as type "
948 "`%s' and type `%s'\n",
950 var
->name
, var
->type
->name
,
951 existing
->type
->name
);
957 if (var
->data
.explicit_location
) {
958 if (existing
->data
.explicit_location
959 && (var
->data
.location
!= existing
->data
.location
)) {
960 linker_error(prog
, "explicit locations for %s "
961 "`%s' have differing values\n",
962 mode_string(var
), var
->name
);
966 if (var
->data
.location_frac
!= existing
->data
.location_frac
) {
967 linker_error(prog
, "explicit components for %s `%s' have "
968 "differing values\n", mode_string(var
), var
->name
);
972 existing
->data
.location
= var
->data
.location
;
973 existing
->data
.explicit_location
= true;
975 /* Check if uniform with implicit location was marked explicit
976 * by earlier shader stage. If so, mark it explicit in this stage
977 * too to make sure later processing does not treat it as
980 if (existing
->data
.explicit_location
) {
981 var
->data
.location
= existing
->data
.location
;
982 var
->data
.explicit_location
= true;
986 /* From the GLSL 4.20 specification:
987 * "A link error will result if two compilation units in a program
988 * specify different integer-constant bindings for the same
989 * opaque-uniform name. However, it is not an error to specify a
990 * binding on some but not all declarations for the same name"
992 if (var
->data
.explicit_binding
) {
993 if (existing
->data
.explicit_binding
&&
994 var
->data
.binding
!= existing
->data
.binding
) {
995 linker_error(prog
, "explicit bindings for %s "
996 "`%s' have differing values\n",
997 mode_string(var
), var
->name
);
1001 existing
->data
.binding
= var
->data
.binding
;
1002 existing
->data
.explicit_binding
= true;
1005 if (var
->type
->contains_atomic() &&
1006 var
->data
.offset
!= existing
->data
.offset
) {
1007 linker_error(prog
, "offset specifications for %s "
1008 "`%s' have differing values\n",
1009 mode_string(var
), var
->name
);
1013 /* Validate layout qualifiers for gl_FragDepth.
1015 * From the AMD/ARB_conservative_depth specs:
1017 * "If gl_FragDepth is redeclared in any fragment shader in a
1018 * program, it must be redeclared in all fragment shaders in
1019 * that program that have static assignments to
1020 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1021 * fragment shaders in a single program must have the same set
1024 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
1025 bool layout_declared
= var
->data
.depth_layout
!= ir_depth_layout_none
;
1026 bool layout_differs
=
1027 var
->data
.depth_layout
!= existing
->data
.depth_layout
;
1029 if (layout_declared
&& layout_differs
) {
1031 "All redeclarations of gl_FragDepth in all "
1032 "fragment shaders in a single program must have "
1033 "the same set of qualifiers.\n");
1036 if (var
->data
.used
&& layout_differs
) {
1038 "If gl_FragDepth is redeclared with a layout "
1039 "qualifier in any fragment shader, it must be "
1040 "redeclared with the same layout qualifier in "
1041 "all fragment shaders that have assignments to "
1046 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1048 * "If a shared global has multiple initializers, the
1049 * initializers must all be constant expressions, and they
1050 * must all have the same value. Otherwise, a link error will
1051 * result. (A shared global having only one initializer does
1052 * not require that initializer to be a constant expression.)"
1054 * Previous to 4.20 the GLSL spec simply said that initializers
1055 * must have the same value. In this case of non-constant
1056 * initializers, this was impossible to determine. As a result,
1057 * no vendor actually implemented that behavior. The 4.20
1058 * behavior matches the implemented behavior of at least one other
1059 * vendor, so we'll implement that for all GLSL versions.
1061 if (var
->constant_initializer
!= NULL
) {
1062 if (existing
->constant_initializer
!= NULL
) {
1063 if (!var
->constant_initializer
->has_value(existing
->constant_initializer
)) {
1064 linker_error(prog
, "initializers for %s "
1065 "`%s' have differing values\n",
1066 mode_string(var
), var
->name
);
1070 /* If the first-seen instance of a particular uniform did
1071 * not have an initializer but a later instance does,
1072 * replace the former with the later.
1074 variables
->replace_variable(existing
->name
, var
);
1078 if (var
->data
.has_initializer
) {
1079 if (existing
->data
.has_initializer
1080 && (var
->constant_initializer
== NULL
1081 || existing
->constant_initializer
== NULL
)) {
1083 "shared global variable `%s' has multiple "
1084 "non-constant initializers.\n",
1090 if (existing
->data
.invariant
!= var
->data
.invariant
) {
1091 linker_error(prog
, "declarations for %s `%s' have "
1092 "mismatching invariant qualifiers\n",
1093 mode_string(var
), var
->name
);
1096 if (existing
->data
.centroid
!= var
->data
.centroid
) {
1097 linker_error(prog
, "declarations for %s `%s' have "
1098 "mismatching centroid qualifiers\n",
1099 mode_string(var
), var
->name
);
1102 if (existing
->data
.sample
!= var
->data
.sample
) {
1103 linker_error(prog
, "declarations for %s `%s` have "
1104 "mismatching sample qualifiers\n",
1105 mode_string(var
), var
->name
);
1108 if (existing
->data
.image_format
!= var
->data
.image_format
) {
1109 linker_error(prog
, "declarations for %s `%s` have "
1110 "mismatching image format qualifiers\n",
1111 mode_string(var
), var
->name
);
1115 /* Check the precision qualifier matches for uniform variables on
1118 if (prog
->IsES
&& !var
->get_interface_type() &&
1119 existing
->data
.precision
!= var
->data
.precision
) {
1120 if ((existing
->data
.used
&& var
->data
.used
) || prog
->data
->Version
>= 300) {
1121 linker_error(prog
, "declarations for %s `%s` have "
1122 "mismatching precision qualifiers\n",
1123 mode_string(var
), var
->name
);
1126 linker_warning(prog
, "declarations for %s `%s` have "
1127 "mismatching precision qualifiers\n",
1128 mode_string(var
), var
->name
);
1132 /* In OpenGL GLSL 3.20 spec, section 4.3.9:
1134 * "It is a link-time error if any particular shader interface
1137 * - two different blocks, each having no instance name, and each
1138 * having a member of the same name, or
1140 * - a variable outside a block, and a block with no instance name,
1141 * where the variable has the same name as a member in the block."
1143 const glsl_type
*var_itype
= var
->get_interface_type();
1144 const glsl_type
*existing_itype
= existing
->get_interface_type();
1145 if (var_itype
!= existing_itype
) {
1146 if (!var_itype
|| !existing_itype
) {
1147 linker_error(prog
, "declarations for %s `%s` are inside block "
1148 "`%s` and outside a block",
1149 mode_string(var
), var
->name
,
1150 var_itype
? var_itype
->name
: existing_itype
->name
);
1152 } else if (strcmp(var_itype
->name
, existing_itype
->name
) != 0) {
1153 linker_error(prog
, "declarations for %s `%s` are inside blocks "
1155 mode_string(var
), var
->name
,
1156 existing_itype
->name
,
1162 variables
->add_variable(var
);
1168 * Perform validation of uniforms used across multiple shader stages
1171 cross_validate_uniforms(struct gl_shader_program
*prog
)
1173 glsl_symbol_table variables
;
1174 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1175 if (prog
->_LinkedShaders
[i
] == NULL
)
1178 cross_validate_globals(prog
, prog
->_LinkedShaders
[i
]->ir
, &variables
,
1184 * Accumulates the array of buffer blocks and checks that all definitions of
1185 * blocks agree on their contents.
1188 interstage_cross_validate_uniform_blocks(struct gl_shader_program
*prog
,
1191 int *InterfaceBlockStageIndex
[MESA_SHADER_STAGES
];
1192 struct gl_uniform_block
*blks
= NULL
;
1193 unsigned *num_blks
= validate_ssbo
? &prog
->data
->NumShaderStorageBlocks
:
1194 &prog
->data
->NumUniformBlocks
;
1196 unsigned max_num_buffer_blocks
= 0;
1197 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1198 if (prog
->_LinkedShaders
[i
]) {
1199 if (validate_ssbo
) {
1200 max_num_buffer_blocks
+=
1201 prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1203 max_num_buffer_blocks
+=
1204 prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1209 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1210 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1212 InterfaceBlockStageIndex
[i
] = new int[max_num_buffer_blocks
];
1213 for (unsigned int j
= 0; j
< max_num_buffer_blocks
; j
++)
1214 InterfaceBlockStageIndex
[i
][j
] = -1;
1219 unsigned sh_num_blocks
;
1220 struct gl_uniform_block
**sh_blks
;
1221 if (validate_ssbo
) {
1222 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ssbos
;
1223 sh_blks
= sh
->Program
->sh
.ShaderStorageBlocks
;
1225 sh_num_blocks
= prog
->_LinkedShaders
[i
]->Program
->info
.num_ubos
;
1226 sh_blks
= sh
->Program
->sh
.UniformBlocks
;
1229 for (unsigned int j
= 0; j
< sh_num_blocks
; j
++) {
1230 int index
= link_cross_validate_uniform_block(prog
->data
, &blks
,
1231 num_blks
, sh_blks
[j
]);
1234 linker_error(prog
, "buffer block `%s' has mismatching "
1235 "definitions\n", sh_blks
[j
]->Name
);
1237 for (unsigned k
= 0; k
<= i
; k
++) {
1238 delete[] InterfaceBlockStageIndex
[k
];
1241 /* Reset the block count. This will help avoid various segfaults
1242 * from api calls that assume the array exists due to the count
1249 InterfaceBlockStageIndex
[i
][index
] = j
;
1253 /* Update per stage block pointers to point to the program list.
1254 * FIXME: We should be able to free the per stage blocks here.
1256 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1257 for (unsigned j
= 0; j
< *num_blks
; j
++) {
1258 int stage_index
= InterfaceBlockStageIndex
[i
][j
];
1260 if (stage_index
!= -1) {
1261 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
1263 struct gl_uniform_block
**sh_blks
= validate_ssbo
?
1264 sh
->Program
->sh
.ShaderStorageBlocks
:
1265 sh
->Program
->sh
.UniformBlocks
;
1267 blks
[j
].stageref
|= sh_blks
[stage_index
]->stageref
;
1268 sh_blks
[stage_index
] = &blks
[j
];
1273 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
1274 delete[] InterfaceBlockStageIndex
[i
];
1278 prog
->data
->ShaderStorageBlocks
= blks
;
1280 prog
->data
->UniformBlocks
= blks
;
1287 * Populates a shaders symbol table with all global declarations
1290 populate_symbol_table(gl_linked_shader
*sh
, glsl_symbol_table
*symbols
)
1292 sh
->symbols
= new(sh
) glsl_symbol_table
;
1294 _mesa_glsl_copy_symbols_from_table(sh
->ir
, symbols
, sh
->symbols
);
1299 * Remap variables referenced in an instruction tree
1301 * This is used when instruction trees are cloned from one shader and placed in
1302 * another. These trees will contain references to \c ir_variable nodes that
1303 * do not exist in the target shader. This function finds these \c ir_variable
1304 * references and replaces the references with matching variables in the target
1307 * If there is no matching variable in the target shader, a clone of the
1308 * \c ir_variable is made and added to the target shader. The new variable is
1309 * added to \b both the instruction stream and the symbol table.
1311 * \param inst IR tree that is to be processed.
1312 * \param symbols Symbol table containing global scope symbols in the
1314 * \param instructions Instruction stream where new variable declarations
1318 remap_variables(ir_instruction
*inst
, struct gl_linked_shader
*target
,
1321 class remap_visitor
: public ir_hierarchical_visitor
{
1323 remap_visitor(struct gl_linked_shader
*target
, hash_table
*temps
)
1325 this->target
= target
;
1326 this->symbols
= target
->symbols
;
1327 this->instructions
= target
->ir
;
1328 this->temps
= temps
;
1331 virtual ir_visitor_status
visit(ir_dereference_variable
*ir
)
1333 if (ir
->var
->data
.mode
== ir_var_temporary
) {
1334 hash_entry
*entry
= _mesa_hash_table_search(temps
, ir
->var
);
1335 ir_variable
*var
= entry
? (ir_variable
*) entry
->data
: NULL
;
1337 assert(var
!= NULL
);
1339 return visit_continue
;
1342 ir_variable
*const existing
=
1343 this->symbols
->get_variable(ir
->var
->name
);
1344 if (existing
!= NULL
)
1347 ir_variable
*copy
= ir
->var
->clone(this->target
, NULL
);
1349 this->symbols
->add_variable(copy
);
1350 this->instructions
->push_head(copy
);
1354 return visit_continue
;
1358 struct gl_linked_shader
*target
;
1359 glsl_symbol_table
*symbols
;
1360 exec_list
*instructions
;
1364 remap_visitor
v(target
, temps
);
1371 * Move non-declarations from one instruction stream to another
1373 * The intended usage pattern of this function is to pass the pointer to the
1374 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1375 * pointer) for \c last and \c false for \c make_copies on the first
1376 * call. Successive calls pass the return value of the previous call for
1377 * \c last and \c true for \c make_copies.
1379 * \param instructions Source instruction stream
1380 * \param last Instruction after which new instructions should be
1381 * inserted in the target instruction stream
1382 * \param make_copies Flag selecting whether instructions in \c instructions
1383 * should be copied (via \c ir_instruction::clone) into the
1384 * target list or moved.
1387 * The new "last" instruction in the target instruction stream. This pointer
1388 * is suitable for use as the \c last parameter of a later call to this
1392 move_non_declarations(exec_list
*instructions
, exec_node
*last
,
1393 bool make_copies
, gl_linked_shader
*target
)
1395 hash_table
*temps
= NULL
;
1398 temps
= _mesa_hash_table_create(NULL
, _mesa_hash_pointer
,
1399 _mesa_key_pointer_equal
);
1401 foreach_in_list_safe(ir_instruction
, inst
, instructions
) {
1402 if (inst
->as_function())
1405 ir_variable
*var
= inst
->as_variable();
1406 if ((var
!= NULL
) && (var
->data
.mode
!= ir_var_temporary
))
1409 assert(inst
->as_assignment()
1411 || inst
->as_if() /* for initializers with the ?: operator */
1412 || ((var
!= NULL
) && (var
->data
.mode
== ir_var_temporary
)));
1415 inst
= inst
->clone(target
, NULL
);
1418 _mesa_hash_table_insert(temps
, var
, inst
);
1420 remap_variables(inst
, target
, temps
);
1425 last
->insert_after(inst
);
1430 _mesa_hash_table_destroy(temps
, NULL
);
1437 * This class is only used in link_intrastage_shaders() below but declaring
1438 * it inside that function leads to compiler warnings with some versions of
1441 class array_sizing_visitor
: public deref_type_updater
{
1443 array_sizing_visitor()
1444 : mem_ctx(ralloc_context(NULL
)),
1445 unnamed_interfaces(_mesa_hash_table_create(NULL
, _mesa_hash_pointer
,
1446 _mesa_key_pointer_equal
))
1450 ~array_sizing_visitor()
1452 _mesa_hash_table_destroy(this->unnamed_interfaces
, NULL
);
1453 ralloc_free(this->mem_ctx
);
1456 virtual ir_visitor_status
visit(ir_variable
*var
)
1458 const glsl_type
*type_without_array
;
1459 bool implicit_sized_array
= var
->data
.implicit_sized_array
;
1460 fixup_type(&var
->type
, var
->data
.max_array_access
,
1461 var
->data
.from_ssbo_unsized_array
,
1462 &implicit_sized_array
);
1463 var
->data
.implicit_sized_array
= implicit_sized_array
;
1464 type_without_array
= var
->type
->without_array();
1465 if (var
->type
->is_interface()) {
1466 if (interface_contains_unsized_arrays(var
->type
)) {
1467 const glsl_type
*new_type
=
1468 resize_interface_members(var
->type
,
1469 var
->get_max_ifc_array_access(),
1470 var
->is_in_shader_storage_block());
1471 var
->type
= new_type
;
1472 var
->change_interface_type(new_type
);
1474 } else if (type_without_array
->is_interface()) {
1475 if (interface_contains_unsized_arrays(type_without_array
)) {
1476 const glsl_type
*new_type
=
1477 resize_interface_members(type_without_array
,
1478 var
->get_max_ifc_array_access(),
1479 var
->is_in_shader_storage_block());
1480 var
->change_interface_type(new_type
);
1481 var
->type
= update_interface_members_array(var
->type
, new_type
);
1483 } else if (const glsl_type
*ifc_type
= var
->get_interface_type()) {
1484 /* Store a pointer to the variable in the unnamed_interfaces
1488 _mesa_hash_table_search(this->unnamed_interfaces
,
1491 ir_variable
**interface_vars
= entry
? (ir_variable
**) entry
->data
: NULL
;
1493 if (interface_vars
== NULL
) {
1494 interface_vars
= rzalloc_array(mem_ctx
, ir_variable
*,
1496 _mesa_hash_table_insert(this->unnamed_interfaces
, ifc_type
,
1499 unsigned index
= ifc_type
->field_index(var
->name
);
1500 assert(index
< ifc_type
->length
);
1501 assert(interface_vars
[index
] == NULL
);
1502 interface_vars
[index
] = var
;
1504 return visit_continue
;
1508 * For each unnamed interface block that was discovered while running the
1509 * visitor, adjust the interface type to reflect the newly assigned array
1510 * sizes, and fix up the ir_variable nodes to point to the new interface
1513 void fixup_unnamed_interface_types()
1515 hash_table_call_foreach(this->unnamed_interfaces
,
1516 fixup_unnamed_interface_type
, NULL
);
1521 * If the type pointed to by \c type represents an unsized array, replace
1522 * it with a sized array whose size is determined by max_array_access.
1524 static void fixup_type(const glsl_type
**type
, unsigned max_array_access
,
1525 bool from_ssbo_unsized_array
, bool *implicit_sized
)
1527 if (!from_ssbo_unsized_array
&& (*type
)->is_unsized_array()) {
1528 *type
= glsl_type::get_array_instance((*type
)->fields
.array
,
1529 max_array_access
+ 1);
1530 *implicit_sized
= true;
1531 assert(*type
!= NULL
);
1535 static const glsl_type
*
1536 update_interface_members_array(const glsl_type
*type
,
1537 const glsl_type
*new_interface_type
)
1539 const glsl_type
*element_type
= type
->fields
.array
;
1540 if (element_type
->is_array()) {
1541 const glsl_type
*new_array_type
=
1542 update_interface_members_array(element_type
, new_interface_type
);
1543 return glsl_type::get_array_instance(new_array_type
, type
->length
);
1545 return glsl_type::get_array_instance(new_interface_type
,
1551 * Determine whether the given interface type contains unsized arrays (if
1552 * it doesn't, array_sizing_visitor doesn't need to process it).
1554 static bool interface_contains_unsized_arrays(const glsl_type
*type
)
1556 for (unsigned i
= 0; i
< type
->length
; i
++) {
1557 const glsl_type
*elem_type
= type
->fields
.structure
[i
].type
;
1558 if (elem_type
->is_unsized_array())
1565 * Create a new interface type based on the given type, with unsized arrays
1566 * replaced by sized arrays whose size is determined by
1567 * max_ifc_array_access.
1569 static const glsl_type
*
1570 resize_interface_members(const glsl_type
*type
,
1571 const int *max_ifc_array_access
,
1574 unsigned num_fields
= type
->length
;
1575 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1576 memcpy(fields
, type
->fields
.structure
,
1577 num_fields
* sizeof(*fields
));
1578 for (unsigned i
= 0; i
< num_fields
; i
++) {
1579 bool implicit_sized_array
= fields
[i
].implicit_sized_array
;
1580 /* If SSBO last member is unsized array, we don't replace it by a sized
1583 if (is_ssbo
&& i
== (num_fields
- 1))
1584 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1585 true, &implicit_sized_array
);
1587 fixup_type(&fields
[i
].type
, max_ifc_array_access
[i
],
1588 false, &implicit_sized_array
);
1589 fields
[i
].implicit_sized_array
= implicit_sized_array
;
1591 glsl_interface_packing packing
=
1592 (glsl_interface_packing
) type
->interface_packing
;
1593 bool row_major
= (bool) type
->interface_row_major
;
1594 const glsl_type
*new_ifc_type
=
1595 glsl_type::get_interface_instance(fields
, num_fields
,
1596 packing
, row_major
, type
->name
);
1598 return new_ifc_type
;
1601 static void fixup_unnamed_interface_type(const void *key
, void *data
,
1604 const glsl_type
*ifc_type
= (const glsl_type
*) key
;
1605 ir_variable
**interface_vars
= (ir_variable
**) data
;
1606 unsigned num_fields
= ifc_type
->length
;
1607 glsl_struct_field
*fields
= new glsl_struct_field
[num_fields
];
1608 memcpy(fields
, ifc_type
->fields
.structure
,
1609 num_fields
* sizeof(*fields
));
1610 bool interface_type_changed
= false;
1611 for (unsigned i
= 0; i
< num_fields
; i
++) {
1612 if (interface_vars
[i
] != NULL
&&
1613 fields
[i
].type
!= interface_vars
[i
]->type
) {
1614 fields
[i
].type
= interface_vars
[i
]->type
;
1615 interface_type_changed
= true;
1618 if (!interface_type_changed
) {
1622 glsl_interface_packing packing
=
1623 (glsl_interface_packing
) ifc_type
->interface_packing
;
1624 bool row_major
= (bool) ifc_type
->interface_row_major
;
1625 const glsl_type
*new_ifc_type
=
1626 glsl_type::get_interface_instance(fields
, num_fields
, packing
,
1627 row_major
, ifc_type
->name
);
1629 for (unsigned i
= 0; i
< num_fields
; i
++) {
1630 if (interface_vars
[i
] != NULL
)
1631 interface_vars
[i
]->change_interface_type(new_ifc_type
);
1636 * Memory context used to allocate the data in \c unnamed_interfaces.
1641 * Hash table from const glsl_type * to an array of ir_variable *'s
1642 * pointing to the ir_variables constituting each unnamed interface block.
1644 hash_table
*unnamed_interfaces
;
1648 validate_xfb_buffer_stride(struct gl_context
*ctx
, unsigned idx
,
1649 struct gl_shader_program
*prog
)
1651 /* We will validate doubles at a later stage */
1652 if (prog
->TransformFeedback
.BufferStride
[idx
] % 4) {
1653 linker_error(prog
, "invalid qualifier xfb_stride=%d must be a "
1654 "multiple of 4 or if its applied to a type that is "
1655 "or contains a double a multiple of 8.",
1656 prog
->TransformFeedback
.BufferStride
[idx
]);
1660 if (prog
->TransformFeedback
.BufferStride
[idx
] / 4 >
1661 ctx
->Const
.MaxTransformFeedbackInterleavedComponents
) {
1662 linker_error(prog
, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1663 "limit has been exceeded.");
1671 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1675 link_xfb_stride_layout_qualifiers(struct gl_context
*ctx
,
1676 struct gl_shader_program
*prog
,
1677 struct gl_shader
**shader_list
,
1678 unsigned num_shaders
)
1680 for (unsigned i
= 0; i
< MAX_FEEDBACK_BUFFERS
; i
++) {
1681 prog
->TransformFeedback
.BufferStride
[i
] = 0;
1684 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1685 struct gl_shader
*shader
= shader_list
[i
];
1687 for (unsigned j
= 0; j
< MAX_FEEDBACK_BUFFERS
; j
++) {
1688 if (shader
->TransformFeedbackBufferStride
[j
]) {
1689 if (prog
->TransformFeedback
.BufferStride
[j
] == 0) {
1690 prog
->TransformFeedback
.BufferStride
[j
] =
1691 shader
->TransformFeedbackBufferStride
[j
];
1692 if (!validate_xfb_buffer_stride(ctx
, j
, prog
))
1694 } else if (prog
->TransformFeedback
.BufferStride
[j
] !=
1695 shader
->TransformFeedbackBufferStride
[j
]){
1697 "intrastage shaders defined with conflicting "
1698 "xfb_stride for buffer %d (%d and %d)\n", j
,
1699 prog
->TransformFeedback
.BufferStride
[j
],
1700 shader
->TransformFeedbackBufferStride
[j
]);
1709 * Check for conflicting bindless/bound sampler/image layout qualifiers at
1713 link_bindless_layout_qualifiers(struct gl_shader_program
*prog
,
1714 struct gl_shader
**shader_list
,
1715 unsigned num_shaders
)
1717 bool bindless_sampler
, bindless_image
;
1718 bool bound_sampler
, bound_image
;
1720 bindless_sampler
= bindless_image
= false;
1721 bound_sampler
= bound_image
= false;
1723 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1724 struct gl_shader
*shader
= shader_list
[i
];
1726 if (shader
->bindless_sampler
)
1727 bindless_sampler
= true;
1728 if (shader
->bindless_image
)
1729 bindless_image
= true;
1730 if (shader
->bound_sampler
)
1731 bound_sampler
= true;
1732 if (shader
->bound_image
)
1735 if ((bindless_sampler
&& bound_sampler
) ||
1736 (bindless_image
&& bound_image
)) {
1737 /* From section 4.4.6 of the ARB_bindless_texture spec:
1739 * "If both bindless_sampler and bound_sampler, or bindless_image
1740 * and bound_image, are declared at global scope in any
1741 * compilation unit, a link- time error will be generated."
1743 linker_error(prog
, "both bindless_sampler and bound_sampler, or "
1744 "bindless_image and bound_image, can't be declared at "
1751 * Performs the cross-validation of tessellation control shader vertices and
1752 * layout qualifiers for the attached tessellation control shaders,
1753 * and propagates them to the linked TCS and linked shader program.
1756 link_tcs_out_layout_qualifiers(struct gl_shader_program
*prog
,
1757 struct gl_program
*gl_prog
,
1758 struct gl_shader
**shader_list
,
1759 unsigned num_shaders
)
1761 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_CTRL
)
1764 gl_prog
->info
.tess
.tcs_vertices_out
= 0;
1766 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1768 * "All tessellation control shader layout declarations in a program
1769 * must specify the same output patch vertex count. There must be at
1770 * least one layout qualifier specifying an output patch vertex count
1771 * in any program containing tessellation control shaders; however,
1772 * such a declaration is not required in all tessellation control
1776 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1777 struct gl_shader
*shader
= shader_list
[i
];
1779 if (shader
->info
.TessCtrl
.VerticesOut
!= 0) {
1780 if (gl_prog
->info
.tess
.tcs_vertices_out
!= 0 &&
1781 gl_prog
->info
.tess
.tcs_vertices_out
!=
1782 (unsigned) shader
->info
.TessCtrl
.VerticesOut
) {
1783 linker_error(prog
, "tessellation control shader defined with "
1784 "conflicting output vertex count (%d and %d)\n",
1785 gl_prog
->info
.tess
.tcs_vertices_out
,
1786 shader
->info
.TessCtrl
.VerticesOut
);
1789 gl_prog
->info
.tess
.tcs_vertices_out
=
1790 shader
->info
.TessCtrl
.VerticesOut
;
1794 /* Just do the intrastage -> interstage propagation right now,
1795 * since we already know we're in the right type of shader program
1798 if (gl_prog
->info
.tess
.tcs_vertices_out
== 0) {
1799 linker_error(prog
, "tessellation control shader didn't declare "
1800 "vertices out layout qualifier\n");
1807 * Performs the cross-validation of tessellation evaluation shader
1808 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1809 * for the attached tessellation evaluation shaders, and propagates them
1810 * to the linked TES and linked shader program.
1813 link_tes_in_layout_qualifiers(struct gl_shader_program
*prog
,
1814 struct gl_program
*gl_prog
,
1815 struct gl_shader
**shader_list
,
1816 unsigned num_shaders
)
1818 if (gl_prog
->info
.stage
!= MESA_SHADER_TESS_EVAL
)
1821 int point_mode
= -1;
1822 unsigned vertex_order
= 0;
1824 gl_prog
->info
.tess
.primitive_mode
= PRIM_UNKNOWN
;
1825 gl_prog
->info
.tess
.spacing
= TESS_SPACING_UNSPECIFIED
;
1827 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1829 * "At least one tessellation evaluation shader (compilation unit) in
1830 * a program must declare a primitive mode in its input layout.
1831 * Declaration vertex spacing, ordering, and point mode identifiers is
1832 * optional. It is not required that all tessellation evaluation
1833 * shaders in a program declare a primitive mode. If spacing or
1834 * vertex ordering declarations are omitted, the tessellation
1835 * primitive generator will use equal spacing or counter-clockwise
1836 * vertex ordering, respectively. If a point mode declaration is
1837 * omitted, the tessellation primitive generator will produce lines or
1838 * triangles according to the primitive mode."
1841 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1842 struct gl_shader
*shader
= shader_list
[i
];
1844 if (shader
->info
.TessEval
.PrimitiveMode
!= PRIM_UNKNOWN
) {
1845 if (gl_prog
->info
.tess
.primitive_mode
!= PRIM_UNKNOWN
&&
1846 gl_prog
->info
.tess
.primitive_mode
!=
1847 shader
->info
.TessEval
.PrimitiveMode
) {
1848 linker_error(prog
, "tessellation evaluation shader defined with "
1849 "conflicting input primitive modes.\n");
1852 gl_prog
->info
.tess
.primitive_mode
=
1853 shader
->info
.TessEval
.PrimitiveMode
;
1856 if (shader
->info
.TessEval
.Spacing
!= 0) {
1857 if (gl_prog
->info
.tess
.spacing
!= 0 && gl_prog
->info
.tess
.spacing
!=
1858 shader
->info
.TessEval
.Spacing
) {
1859 linker_error(prog
, "tessellation evaluation shader defined with "
1860 "conflicting vertex spacing.\n");
1863 gl_prog
->info
.tess
.spacing
= shader
->info
.TessEval
.Spacing
;
1866 if (shader
->info
.TessEval
.VertexOrder
!= 0) {
1867 if (vertex_order
!= 0 &&
1868 vertex_order
!= shader
->info
.TessEval
.VertexOrder
) {
1869 linker_error(prog
, "tessellation evaluation shader defined with "
1870 "conflicting ordering.\n");
1873 vertex_order
= shader
->info
.TessEval
.VertexOrder
;
1876 if (shader
->info
.TessEval
.PointMode
!= -1) {
1877 if (point_mode
!= -1 &&
1878 point_mode
!= shader
->info
.TessEval
.PointMode
) {
1879 linker_error(prog
, "tessellation evaluation shader defined with "
1880 "conflicting point modes.\n");
1883 point_mode
= shader
->info
.TessEval
.PointMode
;
1888 /* Just do the intrastage -> interstage propagation right now,
1889 * since we already know we're in the right type of shader program
1892 if (gl_prog
->info
.tess
.primitive_mode
== PRIM_UNKNOWN
) {
1894 "tessellation evaluation shader didn't declare input "
1895 "primitive modes.\n");
1899 if (gl_prog
->info
.tess
.spacing
== TESS_SPACING_UNSPECIFIED
)
1900 gl_prog
->info
.tess
.spacing
= TESS_SPACING_EQUAL
;
1902 if (vertex_order
== 0 || vertex_order
== GL_CCW
)
1903 gl_prog
->info
.tess
.ccw
= true;
1905 gl_prog
->info
.tess
.ccw
= false;
1908 if (point_mode
== -1 || point_mode
== GL_FALSE
)
1909 gl_prog
->info
.tess
.point_mode
= false;
1911 gl_prog
->info
.tess
.point_mode
= true;
1916 * Performs the cross-validation of layout qualifiers specified in
1917 * redeclaration of gl_FragCoord for the attached fragment shaders,
1918 * and propagates them to the linked FS and linked shader program.
1921 link_fs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
1922 struct gl_linked_shader
*linked_shader
,
1923 struct gl_shader
**shader_list
,
1924 unsigned num_shaders
)
1926 bool redeclares_gl_fragcoord
= false;
1927 bool uses_gl_fragcoord
= false;
1928 bool origin_upper_left
= false;
1929 bool pixel_center_integer
= false;
1931 if (linked_shader
->Stage
!= MESA_SHADER_FRAGMENT
||
1932 (prog
->data
->Version
< 150 &&
1933 !prog
->ARB_fragment_coord_conventions_enable
))
1936 for (unsigned i
= 0; i
< num_shaders
; i
++) {
1937 struct gl_shader
*shader
= shader_list
[i
];
1938 /* From the GLSL 1.50 spec, page 39:
1940 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1941 * it must be redeclared in all the fragment shaders in that program
1942 * that have a static use gl_FragCoord."
1944 if ((redeclares_gl_fragcoord
&& !shader
->redeclares_gl_fragcoord
&&
1945 shader
->uses_gl_fragcoord
)
1946 || (shader
->redeclares_gl_fragcoord
&& !redeclares_gl_fragcoord
&&
1947 uses_gl_fragcoord
)) {
1948 linker_error(prog
, "fragment shader defined with conflicting "
1949 "layout qualifiers for gl_FragCoord\n");
1952 /* From the GLSL 1.50 spec, page 39:
1954 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1955 * single program must have the same set of qualifiers."
1957 if (redeclares_gl_fragcoord
&& shader
->redeclares_gl_fragcoord
&&
1958 (shader
->origin_upper_left
!= origin_upper_left
||
1959 shader
->pixel_center_integer
!= pixel_center_integer
)) {
1960 linker_error(prog
, "fragment shader defined with conflicting "
1961 "layout qualifiers for gl_FragCoord\n");
1964 /* Update the linked shader state. Note that uses_gl_fragcoord should
1965 * accumulate the results. The other values should replace. If there
1966 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1967 * are already known to be the same.
1969 if (shader
->redeclares_gl_fragcoord
|| shader
->uses_gl_fragcoord
) {
1970 redeclares_gl_fragcoord
= shader
->redeclares_gl_fragcoord
;
1971 uses_gl_fragcoord
|= shader
->uses_gl_fragcoord
;
1972 origin_upper_left
= shader
->origin_upper_left
;
1973 pixel_center_integer
= shader
->pixel_center_integer
;
1976 linked_shader
->Program
->info
.fs
.early_fragment_tests
|=
1977 shader
->EarlyFragmentTests
|| shader
->PostDepthCoverage
;
1978 linked_shader
->Program
->info
.fs
.inner_coverage
|= shader
->InnerCoverage
;
1979 linked_shader
->Program
->info
.fs
.post_depth_coverage
|=
1980 shader
->PostDepthCoverage
;
1981 linked_shader
->Program
->info
.fs
.pixel_interlock_ordered
|=
1982 shader
->PixelInterlockOrdered
;
1983 linked_shader
->Program
->info
.fs
.pixel_interlock_unordered
|=
1984 shader
->PixelInterlockUnordered
;
1985 linked_shader
->Program
->info
.fs
.sample_interlock_ordered
|=
1986 shader
->SampleInterlockOrdered
;
1987 linked_shader
->Program
->info
.fs
.sample_interlock_unordered
|=
1988 shader
->SampleInterlockUnordered
;
1990 linked_shader
->Program
->sh
.fs
.BlendSupport
|= shader
->BlendSupport
;
1995 * Performs the cross-validation of geometry shader max_vertices and
1996 * primitive type layout qualifiers for the attached geometry shaders,
1997 * and propagates them to the linked GS and linked shader program.
2000 link_gs_inout_layout_qualifiers(struct gl_shader_program
*prog
,
2001 struct gl_program
*gl_prog
,
2002 struct gl_shader
**shader_list
,
2003 unsigned num_shaders
)
2005 /* No in/out qualifiers defined for anything but GLSL 1.50+
2006 * geometry shaders so far.
2008 if (gl_prog
->info
.stage
!= MESA_SHADER_GEOMETRY
||
2009 prog
->data
->Version
< 150)
2012 int vertices_out
= -1;
2014 gl_prog
->info
.gs
.invocations
= 0;
2015 gl_prog
->info
.gs
.input_primitive
= PRIM_UNKNOWN
;
2016 gl_prog
->info
.gs
.output_primitive
= PRIM_UNKNOWN
;
2018 /* From the GLSL 1.50 spec, page 46:
2020 * "All geometry shader output layout declarations in a program
2021 * must declare the same layout and same value for
2022 * max_vertices. There must be at least one geometry output
2023 * layout declaration somewhere in a program, but not all
2024 * geometry shaders (compilation units) are required to
2028 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2029 struct gl_shader
*shader
= shader_list
[i
];
2031 if (shader
->info
.Geom
.InputType
!= PRIM_UNKNOWN
) {
2032 if (gl_prog
->info
.gs
.input_primitive
!= PRIM_UNKNOWN
&&
2033 gl_prog
->info
.gs
.input_primitive
!=
2034 shader
->info
.Geom
.InputType
) {
2035 linker_error(prog
, "geometry shader defined with conflicting "
2039 gl_prog
->info
.gs
.input_primitive
= shader
->info
.Geom
.InputType
;
2042 if (shader
->info
.Geom
.OutputType
!= PRIM_UNKNOWN
) {
2043 if (gl_prog
->info
.gs
.output_primitive
!= PRIM_UNKNOWN
&&
2044 gl_prog
->info
.gs
.output_primitive
!=
2045 shader
->info
.Geom
.OutputType
) {
2046 linker_error(prog
, "geometry shader defined with conflicting "
2050 gl_prog
->info
.gs
.output_primitive
= shader
->info
.Geom
.OutputType
;
2053 if (shader
->info
.Geom
.VerticesOut
!= -1) {
2054 if (vertices_out
!= -1 &&
2055 vertices_out
!= shader
->info
.Geom
.VerticesOut
) {
2056 linker_error(prog
, "geometry shader defined with conflicting "
2057 "output vertex count (%d and %d)\n",
2058 vertices_out
, shader
->info
.Geom
.VerticesOut
);
2061 vertices_out
= shader
->info
.Geom
.VerticesOut
;
2064 if (shader
->info
.Geom
.Invocations
!= 0) {
2065 if (gl_prog
->info
.gs
.invocations
!= 0 &&
2066 gl_prog
->info
.gs
.invocations
!=
2067 (unsigned) shader
->info
.Geom
.Invocations
) {
2068 linker_error(prog
, "geometry shader defined with conflicting "
2069 "invocation count (%d and %d)\n",
2070 gl_prog
->info
.gs
.invocations
,
2071 shader
->info
.Geom
.Invocations
);
2074 gl_prog
->info
.gs
.invocations
= shader
->info
.Geom
.Invocations
;
2078 /* Just do the intrastage -> interstage propagation right now,
2079 * since we already know we're in the right type of shader program
2082 if (gl_prog
->info
.gs
.input_primitive
== PRIM_UNKNOWN
) {
2084 "geometry shader didn't declare primitive input type\n");
2088 if (gl_prog
->info
.gs
.output_primitive
== PRIM_UNKNOWN
) {
2090 "geometry shader didn't declare primitive output type\n");
2094 if (vertices_out
== -1) {
2096 "geometry shader didn't declare max_vertices\n");
2099 gl_prog
->info
.gs
.vertices_out
= vertices_out
;
2102 if (gl_prog
->info
.gs
.invocations
== 0)
2103 gl_prog
->info
.gs
.invocations
= 1;
2108 * Perform cross-validation of compute shader local_size_{x,y,z} layout
2109 * qualifiers for the attached compute shaders, and propagate them to the
2110 * linked CS and linked shader program.
2113 link_cs_input_layout_qualifiers(struct gl_shader_program
*prog
,
2114 struct gl_program
*gl_prog
,
2115 struct gl_shader
**shader_list
,
2116 unsigned num_shaders
)
2118 /* This function is called for all shader stages, but it only has an effect
2119 * for compute shaders.
2121 if (gl_prog
->info
.stage
!= MESA_SHADER_COMPUTE
)
2124 for (int i
= 0; i
< 3; i
++)
2125 gl_prog
->info
.cs
.local_size
[i
] = 0;
2127 gl_prog
->info
.cs
.local_size_variable
= false;
2129 /* From the ARB_compute_shader spec, in the section describing local size
2132 * If multiple compute shaders attached to a single program object
2133 * declare local work-group size, the declarations must be identical;
2134 * otherwise a link-time error results. Furthermore, if a program
2135 * object contains any compute shaders, at least one must contain an
2136 * input layout qualifier specifying the local work sizes of the
2137 * program, or a link-time error will occur.
2139 for (unsigned sh
= 0; sh
< num_shaders
; sh
++) {
2140 struct gl_shader
*shader
= shader_list
[sh
];
2142 if (shader
->info
.Comp
.LocalSize
[0] != 0) {
2143 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2144 for (int i
= 0; i
< 3; i
++) {
2145 if (gl_prog
->info
.cs
.local_size
[i
] !=
2146 shader
->info
.Comp
.LocalSize
[i
]) {
2147 linker_error(prog
, "compute shader defined with conflicting "
2153 for (int i
= 0; i
< 3; i
++) {
2154 gl_prog
->info
.cs
.local_size
[i
] =
2155 shader
->info
.Comp
.LocalSize
[i
];
2157 } else if (shader
->info
.Comp
.LocalSizeVariable
) {
2158 if (gl_prog
->info
.cs
.local_size
[0] != 0) {
2159 /* The ARB_compute_variable_group_size spec says:
2161 * If one compute shader attached to a program declares a
2162 * variable local group size and a second compute shader
2163 * attached to the same program declares a fixed local group
2164 * size, a link-time error results.
2166 linker_error(prog
, "compute shader defined with both fixed and "
2167 "variable local group size\n");
2170 gl_prog
->info
.cs
.local_size_variable
= true;
2174 /* Just do the intrastage -> interstage propagation right now,
2175 * since we already know we're in the right type of shader program
2178 if (gl_prog
->info
.cs
.local_size
[0] == 0 &&
2179 !gl_prog
->info
.cs
.local_size_variable
) {
2180 linker_error(prog
, "compute shader must contain a fixed or a variable "
2181 "local group size\n");
2188 * Combine a group of shaders for a single stage to generate a linked shader
2191 * If this function is supplied a single shader, it is cloned, and the new
2192 * shader is returned.
2194 struct gl_linked_shader
*
2195 link_intrastage_shaders(void *mem_ctx
,
2196 struct gl_context
*ctx
,
2197 struct gl_shader_program
*prog
,
2198 struct gl_shader
**shader_list
,
2199 unsigned num_shaders
,
2200 bool allow_missing_main
)
2202 struct gl_uniform_block
*ubo_blocks
= NULL
;
2203 struct gl_uniform_block
*ssbo_blocks
= NULL
;
2204 unsigned num_ubo_blocks
= 0;
2205 unsigned num_ssbo_blocks
= 0;
2207 /* Check that global variables defined in multiple shaders are consistent.
2209 glsl_symbol_table variables
;
2210 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2211 if (shader_list
[i
] == NULL
)
2213 cross_validate_globals(prog
, shader_list
[i
]->ir
, &variables
, false);
2216 if (!prog
->data
->LinkStatus
)
2219 /* Check that interface blocks defined in multiple shaders are consistent.
2221 validate_intrastage_interface_blocks(prog
, (const gl_shader
**)shader_list
,
2223 if (!prog
->data
->LinkStatus
)
2226 /* Check that there is only a single definition of each function signature
2227 * across all shaders.
2229 for (unsigned i
= 0; i
< (num_shaders
- 1); i
++) {
2230 foreach_in_list(ir_instruction
, node
, shader_list
[i
]->ir
) {
2231 ir_function
*const f
= node
->as_function();
2236 for (unsigned j
= i
+ 1; j
< num_shaders
; j
++) {
2237 ir_function
*const other
=
2238 shader_list
[j
]->symbols
->get_function(f
->name
);
2240 /* If the other shader has no function (and therefore no function
2241 * signatures) with the same name, skip to the next shader.
2246 foreach_in_list(ir_function_signature
, sig
, &f
->signatures
) {
2247 if (!sig
->is_defined
)
2250 ir_function_signature
*other_sig
=
2251 other
->exact_matching_signature(NULL
, &sig
->parameters
);
2253 if (other_sig
!= NULL
&& other_sig
->is_defined
) {
2254 linker_error(prog
, "function `%s' is multiply defined\n",
2263 /* Find the shader that defines main, and make a clone of it.
2265 * Starting with the clone, search for undefined references. If one is
2266 * found, find the shader that defines it. Clone the reference and add
2267 * it to the shader. Repeat until there are no undefined references or
2268 * until a reference cannot be resolved.
2270 gl_shader
*main
= NULL
;
2271 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2272 if (_mesa_get_main_function_signature(shader_list
[i
]->symbols
)) {
2273 main
= shader_list
[i
];
2278 if (main
== NULL
&& allow_missing_main
)
2279 main
= shader_list
[0];
2282 linker_error(prog
, "%s shader lacks `main'\n",
2283 _mesa_shader_stage_to_string(shader_list
[0]->Stage
));
2287 gl_linked_shader
*linked
= rzalloc(NULL
, struct gl_linked_shader
);
2288 linked
->Stage
= shader_list
[0]->Stage
;
2290 /* Create program and attach it to the linked shader */
2291 struct gl_program
*gl_prog
=
2292 ctx
->Driver
.NewProgram(ctx
,
2293 _mesa_shader_stage_to_program(shader_list
[0]->Stage
),
2296 prog
->data
->LinkStatus
= LINKING_FAILURE
;
2297 _mesa_delete_linked_shader(ctx
, linked
);
2301 _mesa_reference_shader_program_data(ctx
, &gl_prog
->sh
.data
, prog
->data
);
2303 /* Don't use _mesa_reference_program() just take ownership */
2304 linked
->Program
= gl_prog
;
2306 linked
->ir
= new(linked
) exec_list
;
2307 clone_ir_list(mem_ctx
, linked
->ir
, main
->ir
);
2309 link_fs_inout_layout_qualifiers(prog
, linked
, shader_list
, num_shaders
);
2310 link_tcs_out_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2311 link_tes_in_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2312 link_gs_inout_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2313 link_cs_input_layout_qualifiers(prog
, gl_prog
, shader_list
, num_shaders
);
2315 if (linked
->Stage
!= MESA_SHADER_FRAGMENT
)
2316 link_xfb_stride_layout_qualifiers(ctx
, prog
, shader_list
, num_shaders
);
2318 link_bindless_layout_qualifiers(prog
, shader_list
, num_shaders
);
2320 populate_symbol_table(linked
, shader_list
[0]->symbols
);
2322 /* The pointer to the main function in the final linked shader (i.e., the
2323 * copy of the original shader that contained the main function).
2325 ir_function_signature
*const main_sig
=
2326 _mesa_get_main_function_signature(linked
->symbols
);
2328 /* Move any instructions other than variable declarations or function
2329 * declarations into main.
2331 if (main_sig
!= NULL
) {
2332 exec_node
*insertion_point
=
2333 move_non_declarations(linked
->ir
, (exec_node
*) &main_sig
->body
, false,
2336 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2337 if (shader_list
[i
] == main
)
2340 insertion_point
= move_non_declarations(shader_list
[i
]->ir
,
2341 insertion_point
, true, linked
);
2345 if (!link_function_calls(prog
, linked
, shader_list
, num_shaders
)) {
2346 _mesa_delete_linked_shader(ctx
, linked
);
2350 /* Make a pass over all variable declarations to ensure that arrays with
2351 * unspecified sizes have a size specified. The size is inferred from the
2352 * max_array_access field.
2354 array_sizing_visitor v
;
2356 v
.fixup_unnamed_interface_types();
2358 /* Link up uniform blocks defined within this stage. */
2359 link_uniform_blocks(mem_ctx
, ctx
, prog
, linked
, &ubo_blocks
,
2360 &num_ubo_blocks
, &ssbo_blocks
, &num_ssbo_blocks
);
2362 if (!prog
->data
->LinkStatus
) {
2363 _mesa_delete_linked_shader(ctx
, linked
);
2367 /* Copy ubo blocks to linked shader list */
2368 linked
->Program
->sh
.UniformBlocks
=
2369 ralloc_array(linked
, gl_uniform_block
*, num_ubo_blocks
);
2370 ralloc_steal(linked
, ubo_blocks
);
2371 for (unsigned i
= 0; i
< num_ubo_blocks
; i
++) {
2372 linked
->Program
->sh
.UniformBlocks
[i
] = &ubo_blocks
[i
];
2374 linked
->Program
->info
.num_ubos
= num_ubo_blocks
;
2376 /* Copy ssbo blocks to linked shader list */
2377 linked
->Program
->sh
.ShaderStorageBlocks
=
2378 ralloc_array(linked
, gl_uniform_block
*, num_ssbo_blocks
);
2379 ralloc_steal(linked
, ssbo_blocks
);
2380 for (unsigned i
= 0; i
< num_ssbo_blocks
; i
++) {
2381 linked
->Program
->sh
.ShaderStorageBlocks
[i
] = &ssbo_blocks
[i
];
2383 linked
->Program
->info
.num_ssbos
= num_ssbo_blocks
;
2385 /* At this point linked should contain all of the linked IR, so
2386 * validate it to make sure nothing went wrong.
2388 validate_ir_tree(linked
->ir
);
2390 /* Set the size of geometry shader input arrays */
2391 if (linked
->Stage
== MESA_SHADER_GEOMETRY
) {
2392 unsigned num_vertices
=
2393 vertices_per_prim(gl_prog
->info
.gs
.input_primitive
);
2394 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2395 MESA_SHADER_GEOMETRY
);
2396 foreach_in_list(ir_instruction
, ir
, linked
->ir
) {
2397 ir
->accept(&input_resize_visitor
);
2401 if (ctx
->Const
.VertexID_is_zero_based
)
2402 lower_vertex_id(linked
);
2404 if (ctx
->Const
.LowerCsDerivedVariables
)
2405 lower_cs_derived(linked
);
2408 /* Compute the source checksum. */
2409 linked
->SourceChecksum
= 0;
2410 for (unsigned i
= 0; i
< num_shaders
; i
++) {
2411 if (shader_list
[i
] == NULL
)
2413 linked
->SourceChecksum
^= shader_list
[i
]->SourceChecksum
;
2421 * Update the sizes of linked shader uniform arrays to the maximum
2424 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2426 * If one or more elements of an array are active,
2427 * GetActiveUniform will return the name of the array in name,
2428 * subject to the restrictions listed above. The type of the array
2429 * is returned in type. The size parameter contains the highest
2430 * array element index used, plus one. The compiler or linker
2431 * determines the highest index used. There will be only one
2432 * active uniform reported by the GL per uniform array.
2436 update_array_sizes(struct gl_shader_program
*prog
)
2438 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
2439 if (prog
->_LinkedShaders
[i
] == NULL
)
2442 bool types_were_updated
= false;
2444 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
2445 ir_variable
*const var
= node
->as_variable();
2447 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_uniform
) ||
2448 !var
->type
->is_array())
2451 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2452 * will not be eliminated. Since we always do std140, just
2453 * don't resize arrays in UBOs.
2455 * Atomic counters are supposed to get deterministic
2456 * locations assigned based on the declaration ordering and
2457 * sizes, array compaction would mess that up.
2459 * Subroutine uniforms are not removed.
2461 if (var
->is_in_buffer_block() || var
->type
->contains_atomic() ||
2462 var
->type
->contains_subroutine() || var
->constant_initializer
)
2465 int size
= var
->data
.max_array_access
;
2466 for (unsigned j
= 0; j
< MESA_SHADER_STAGES
; j
++) {
2467 if (prog
->_LinkedShaders
[j
] == NULL
)
2470 foreach_in_list(ir_instruction
, node2
, prog
->_LinkedShaders
[j
]->ir
) {
2471 ir_variable
*other_var
= node2
->as_variable();
2475 if (strcmp(var
->name
, other_var
->name
) == 0 &&
2476 other_var
->data
.max_array_access
> size
) {
2477 size
= other_var
->data
.max_array_access
;
2482 if (size
+ 1 != (int)var
->type
->length
) {
2483 /* If this is a built-in uniform (i.e., it's backed by some
2484 * fixed-function state), adjust the number of state slots to
2485 * match the new array size. The number of slots per array entry
2486 * is not known. It seems safe to assume that the total number of
2487 * slots is an integer multiple of the number of array elements.
2488 * Determine the number of slots per array element by dividing by
2489 * the old (total) size.
2491 const unsigned num_slots
= var
->get_num_state_slots();
2492 if (num_slots
> 0) {
2493 var
->set_num_state_slots((size
+ 1)
2494 * (num_slots
/ var
->type
->length
));
2497 var
->type
= glsl_type::get_array_instance(var
->type
->fields
.array
,
2499 types_were_updated
= true;
2503 /* Update the types of dereferences in case we changed any. */
2504 if (types_were_updated
) {
2505 deref_type_updater v
;
2506 v
.run(prog
->_LinkedShaders
[i
]->ir
);
2512 * Resize tessellation evaluation per-vertex inputs to the size of
2513 * tessellation control per-vertex outputs.
2516 resize_tes_inputs(struct gl_context
*ctx
,
2517 struct gl_shader_program
*prog
)
2519 if (prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
] == NULL
)
2522 gl_linked_shader
*const tcs
= prog
->_LinkedShaders
[MESA_SHADER_TESS_CTRL
];
2523 gl_linked_shader
*const tes
= prog
->_LinkedShaders
[MESA_SHADER_TESS_EVAL
];
2525 /* If no control shader is present, then the TES inputs are statically
2526 * sized to MaxPatchVertices; the actual size of the arrays won't be
2527 * known until draw time.
2529 const int num_vertices
= tcs
2530 ? tcs
->Program
->info
.tess
.tcs_vertices_out
2531 : ctx
->Const
.MaxPatchVertices
;
2533 array_resize_visitor
input_resize_visitor(num_vertices
, prog
,
2534 MESA_SHADER_TESS_EVAL
);
2535 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2536 ir
->accept(&input_resize_visitor
);
2540 /* Convert the gl_PatchVerticesIn system value into a constant, since
2541 * the value is known at this point.
2543 foreach_in_list(ir_instruction
, ir
, tes
->ir
) {
2544 ir_variable
*var
= ir
->as_variable();
2545 if (var
&& var
->data
.mode
== ir_var_system_value
&&
2546 var
->data
.location
== SYSTEM_VALUE_VERTICES_IN
) {
2547 void *mem_ctx
= ralloc_parent(var
);
2548 var
->data
.location
= 0;
2549 var
->data
.explicit_location
= false;
2550 var
->data
.mode
= ir_var_auto
;
2551 var
->constant_value
= new(mem_ctx
) ir_constant(num_vertices
);
2558 * Find a contiguous set of available bits in a bitmask.
2560 * \param used_mask Bits representing used (1) and unused (0) locations
2561 * \param needed_count Number of contiguous bits needed.
2564 * Base location of the available bits on success or -1 on failure.
2567 find_available_slots(unsigned used_mask
, unsigned needed_count
)
2569 unsigned needed_mask
= (1 << needed_count
) - 1;
2570 const int max_bit_to_test
= (8 * sizeof(used_mask
)) - needed_count
;
2572 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2573 * cannot optimize possibly infinite loops" for the loop below.
2575 if ((needed_count
== 0) || (max_bit_to_test
< 0) || (max_bit_to_test
> 32))
2578 for (int i
= 0; i
<= max_bit_to_test
; i
++) {
2579 if ((needed_mask
& ~used_mask
) == needed_mask
)
2589 #define SAFE_MASK_FROM_INDEX(i) (((i) >= 32) ? ~0 : ((1 << (i)) - 1))
2592 * Assign locations for either VS inputs or FS outputs
2594 * \param mem_ctx Temporary ralloc context used for linking
2595 * \param prog Shader program whose variables need locations assigned
2596 * \param constants Driver specific constant values for the program.
2597 * \param target_index Selector for the program target to receive location
2598 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2599 * \c MESA_SHADER_FRAGMENT.
2602 * If locations are successfully assigned, true is returned. Otherwise an
2603 * error is emitted to the shader link log and false is returned.
2606 assign_attribute_or_color_locations(void *mem_ctx
,
2607 gl_shader_program
*prog
,
2608 struct gl_constants
*constants
,
2609 unsigned target_index
)
2611 /* Maximum number of generic locations. This corresponds to either the
2612 * maximum number of draw buffers or the maximum number of generic
2615 unsigned max_index
= (target_index
== MESA_SHADER_VERTEX
) ?
2616 constants
->Program
[target_index
].MaxAttribs
:
2617 MAX2(constants
->MaxDrawBuffers
, constants
->MaxDualSourceDrawBuffers
);
2619 /* Mark invalid locations as being used.
2621 unsigned used_locations
= ~SAFE_MASK_FROM_INDEX(max_index
);
2622 unsigned double_storage_locations
= 0;
2624 assert((target_index
== MESA_SHADER_VERTEX
)
2625 || (target_index
== MESA_SHADER_FRAGMENT
));
2627 gl_linked_shader
*const sh
= prog
->_LinkedShaders
[target_index
];
2631 /* Operate in a total of four passes.
2633 * 1. Invalidate the location assignments for all vertex shader inputs.
2635 * 2. Assign locations for inputs that have user-defined (via
2636 * glBindVertexAttribLocation) locations and outputs that have
2637 * user-defined locations (via glBindFragDataLocation).
2639 * 3. Sort the attributes without assigned locations by number of slots
2640 * required in decreasing order. Fragmentation caused by attribute
2641 * locations assigned by the application may prevent large attributes
2642 * from having enough contiguous space.
2644 * 4. Assign locations to any inputs without assigned locations.
2647 const int generic_base
= (target_index
== MESA_SHADER_VERTEX
)
2648 ? (int) VERT_ATTRIB_GENERIC0
: (int) FRAG_RESULT_DATA0
;
2650 const enum ir_variable_mode direction
=
2651 (target_index
== MESA_SHADER_VERTEX
)
2652 ? ir_var_shader_in
: ir_var_shader_out
;
2655 /* Temporary storage for the set of attributes that need locations assigned.
2661 /* Used below in the call to qsort. */
2662 static int compare(const void *a
, const void *b
)
2664 const temp_attr
*const l
= (const temp_attr
*) a
;
2665 const temp_attr
*const r
= (const temp_attr
*) b
;
2667 /* Reversed because we want a descending order sort below. */
2668 return r
->slots
- l
->slots
;
2671 assert(max_index
<= 32);
2673 /* Temporary array for the set of attributes that have locations assigned,
2674 * for the purpose of checking overlapping slots/components of (non-ES)
2675 * fragment shader outputs.
2677 ir_variable
*assigned
[12 * 4]; /* (max # of FS outputs) * # components */
2678 unsigned assigned_attr
= 0;
2680 unsigned num_attr
= 0;
2682 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
2683 ir_variable
*const var
= node
->as_variable();
2685 if ((var
== NULL
) || (var
->data
.mode
!= (unsigned) direction
))
2688 if (var
->data
.explicit_location
) {
2689 var
->data
.is_unmatched_generic_inout
= 0;
2690 if ((var
->data
.location
>= (int)(max_index
+ generic_base
))
2691 || (var
->data
.location
< 0)) {
2693 "invalid explicit location %d specified for `%s'\n",
2694 (var
->data
.location
< 0)
2695 ? var
->data
.location
2696 : var
->data
.location
- generic_base
,
2700 } else if (target_index
== MESA_SHADER_VERTEX
) {
2703 if (prog
->AttributeBindings
->get(binding
, var
->name
)) {
2704 assert(binding
>= VERT_ATTRIB_GENERIC0
);
2705 var
->data
.location
= binding
;
2706 var
->data
.is_unmatched_generic_inout
= 0;
2708 } else if (target_index
== MESA_SHADER_FRAGMENT
) {
2711 const char *name
= var
->name
;
2712 const glsl_type
*type
= var
->type
;
2715 /* Check if there's a binding for the variable name */
2716 if (prog
->FragDataBindings
->get(binding
, name
)) {
2717 assert(binding
>= FRAG_RESULT_DATA0
);
2718 var
->data
.location
= binding
;
2719 var
->data
.is_unmatched_generic_inout
= 0;
2721 if (prog
->FragDataIndexBindings
->get(index
, name
)) {
2722 var
->data
.index
= index
;
2727 /* If not, but it's an array type, look for name[0] */
2728 if (type
->is_array()) {
2729 name
= ralloc_asprintf(mem_ctx
, "%s[0]", name
);
2730 type
= type
->fields
.array
;
2738 if (strcmp(var
->name
, "gl_LastFragData") == 0)
2741 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2743 * "Output binding assignments will cause LinkProgram to fail:
2745 * If the program has an active output assigned to a location greater
2746 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2747 * an active output assigned an index greater than or equal to one;"
2749 if (target_index
== MESA_SHADER_FRAGMENT
&& var
->data
.index
>= 1 &&
2750 var
->data
.location
- generic_base
>=
2751 (int) constants
->MaxDualSourceDrawBuffers
) {
2753 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2754 "with index %u for %s\n",
2755 var
->data
.location
- generic_base
, var
->data
.index
,
2760 const unsigned slots
= var
->type
->count_attribute_slots(target_index
== MESA_SHADER_VERTEX
);
2762 /* If the variable is not a built-in and has a location statically
2763 * assigned in the shader (presumably via a layout qualifier), make sure
2764 * that it doesn't collide with other assigned locations. Otherwise,
2765 * add it to the list of variables that need linker-assigned locations.
2767 if (var
->data
.location
!= -1) {
2768 if (var
->data
.location
>= generic_base
&& var
->data
.index
< 1) {
2769 /* From page 61 of the OpenGL 4.0 spec:
2771 * "LinkProgram will fail if the attribute bindings assigned
2772 * by BindAttribLocation do not leave not enough space to
2773 * assign a location for an active matrix attribute or an
2774 * active attribute array, both of which require multiple
2775 * contiguous generic attributes."
2777 * I think above text prohibits the aliasing of explicit and
2778 * automatic assignments. But, aliasing is allowed in manual
2779 * assignments of attribute locations. See below comments for
2782 * From OpenGL 4.0 spec, page 61:
2784 * "It is possible for an application to bind more than one
2785 * attribute name to the same location. This is referred to as
2786 * aliasing. This will only work if only one of the aliased
2787 * attributes is active in the executable program, or if no
2788 * path through the shader consumes more than one attribute of
2789 * a set of attributes aliased to the same location. A link
2790 * error can occur if the linker determines that every path
2791 * through the shader consumes multiple aliased attributes,
2792 * but implementations are not required to generate an error
2795 * From GLSL 4.30 spec, page 54:
2797 * "A program will fail to link if any two non-vertex shader
2798 * input variables are assigned to the same location. For
2799 * vertex shaders, multiple input variables may be assigned
2800 * to the same location using either layout qualifiers or via
2801 * the OpenGL API. However, such aliasing is intended only to
2802 * support vertex shaders where each execution path accesses
2803 * at most one input per each location. Implementations are
2804 * permitted, but not required, to generate link-time errors
2805 * if they detect that every path through the vertex shader
2806 * executable accesses multiple inputs assigned to any single
2807 * location. For all shader types, a program will fail to link
2808 * if explicit location assignments leave the linker unable
2809 * to find space for other variables without explicit
2812 * From OpenGL ES 3.0 spec, page 56:
2814 * "Binding more than one attribute name to the same location
2815 * is referred to as aliasing, and is not permitted in OpenGL
2816 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2817 * fail when this condition exists. However, aliasing is
2818 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2819 * This will only work if only one of the aliased attributes
2820 * is active in the executable program, or if no path through
2821 * the shader consumes more than one attribute of a set of
2822 * attributes aliased to the same location. A link error can
2823 * occur if the linker determines that every path through the
2824 * shader consumes multiple aliased attributes, but implemen-
2825 * tations are not required to generate an error in this case."
2827 * After looking at above references from OpenGL, OpenGL ES and
2828 * GLSL specifications, we allow aliasing of vertex input variables
2829 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2831 * NOTE: This is not required by the spec but its worth mentioning
2832 * here that we're not doing anything to make sure that no path
2833 * through the vertex shader executable accesses multiple inputs
2834 * assigned to any single location.
2837 /* Mask representing the contiguous slots that will be used by
2840 const unsigned attr
= var
->data
.location
- generic_base
;
2841 const unsigned use_mask
= (1 << slots
) - 1;
2842 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
2843 ? "vertex shader input" : "fragment shader output";
2845 /* Generate a link error if the requested locations for this
2846 * attribute exceed the maximum allowed attribute location.
2848 if (attr
+ slots
> max_index
) {
2850 "insufficient contiguous locations "
2851 "available for %s `%s' %d %d %d\n", string
,
2852 var
->name
, used_locations
, use_mask
, attr
);
2856 /* Generate a link error if the set of bits requested for this
2857 * attribute overlaps any previously allocated bits.
2859 if ((~(use_mask
<< attr
) & used_locations
) != used_locations
) {
2860 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
2861 /* From section 4.4.2 (Output Layout Qualifiers) of the GLSL
2864 * "Additionally, for fragment shader outputs, if two
2865 * variables are placed within the same location, they
2866 * must have the same underlying type (floating-point or
2867 * integer). No component aliasing of output variables or
2868 * members is allowed.
2870 for (unsigned i
= 0; i
< assigned_attr
; i
++) {
2871 unsigned assigned_slots
=
2872 assigned
[i
]->type
->count_attribute_slots(false);
2873 unsigned assig_attr
=
2874 assigned
[i
]->data
.location
- generic_base
;
2875 unsigned assigned_use_mask
= (1 << assigned_slots
) - 1;
2877 if ((assigned_use_mask
<< assig_attr
) &
2878 (use_mask
<< attr
)) {
2880 const glsl_type
*assigned_type
=
2881 assigned
[i
]->type
->without_array();
2882 const glsl_type
*type
= var
->type
->without_array();
2883 if (assigned_type
->base_type
!= type
->base_type
) {
2884 linker_error(prog
, "types do not match for aliased"
2885 " %ss %s and %s\n", string
,
2886 assigned
[i
]->name
, var
->name
);
2890 unsigned assigned_component_mask
=
2891 ((1 << assigned_type
->vector_elements
) - 1) <<
2892 assigned
[i
]->data
.location_frac
;
2893 unsigned component_mask
=
2894 ((1 << type
->vector_elements
) - 1) <<
2895 var
->data
.location_frac
;
2896 if (assigned_component_mask
& component_mask
) {
2897 linker_error(prog
, "overlapping component is "
2898 "assigned to %ss %s and %s "
2900 string
, assigned
[i
]->name
, var
->name
,
2901 var
->data
.location_frac
);
2906 } else if (target_index
== MESA_SHADER_FRAGMENT
||
2907 (prog
->IsES
&& prog
->data
->Version
>= 300)) {
2908 linker_error(prog
, "overlapping location is assigned "
2909 "to %s `%s' %d %d %d\n", string
, var
->name
,
2910 used_locations
, use_mask
, attr
);
2913 linker_warning(prog
, "overlapping location is assigned "
2914 "to %s `%s' %d %d %d\n", string
, var
->name
,
2915 used_locations
, use_mask
, attr
);
2919 if (target_index
== MESA_SHADER_FRAGMENT
&& !prog
->IsES
) {
2920 /* Only track assigned variables for non-ES fragment shaders
2921 * to avoid overflowing the array.
2923 * At most one variable per fragment output component should
2926 assert(assigned_attr
< ARRAY_SIZE(assigned
));
2927 assigned
[assigned_attr
] = var
;
2931 used_locations
|= (use_mask
<< attr
);
2933 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2935 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2936 * active attribute variables may fail to link, unless
2937 * device-dependent optimizations are able to make the program
2938 * fit within available hardware resources. For the purposes
2939 * of this test, attribute variables of the type dvec3, dvec4,
2940 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2941 * count as consuming twice as many attributes as equivalent
2942 * single-precision types. While these types use the same number
2943 * of generic attributes as their single-precision equivalents,
2944 * implementations are permitted to consume two single-precision
2945 * vectors of internal storage for each three- or four-component
2946 * double-precision vector."
2948 * Mark this attribute slot as taking up twice as much space
2949 * so we can count it properly against limits. According to
2950 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2951 * is optional behavior, but it seems preferable.
2953 if (var
->type
->without_array()->is_dual_slot())
2954 double_storage_locations
|= (use_mask
<< attr
);
2960 if (num_attr
>= max_index
) {
2961 linker_error(prog
, "too many %s (max %u)",
2962 target_index
== MESA_SHADER_VERTEX
?
2963 "vertex shader inputs" : "fragment shader outputs",
2967 to_assign
[num_attr
].slots
= slots
;
2968 to_assign
[num_attr
].var
= var
;
2972 if (target_index
== MESA_SHADER_VERTEX
) {
2973 unsigned total_attribs_size
=
2974 _mesa_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
2975 _mesa_bitcount(double_storage_locations
);
2976 if (total_attribs_size
> max_index
) {
2978 "attempt to use %d vertex attribute slots only %d available ",
2979 total_attribs_size
, max_index
);
2984 /* If all of the attributes were assigned locations by the application (or
2985 * are built-in attributes with fixed locations), return early. This should
2986 * be the common case.
2991 qsort(to_assign
, num_attr
, sizeof(to_assign
[0]), temp_attr::compare
);
2993 if (target_index
== MESA_SHADER_VERTEX
) {
2994 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2995 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2996 * reserved to prevent it from being automatically allocated below.
2998 find_deref_visitor
find("gl_Vertex");
3000 if (find
.variable_found())
3001 used_locations
|= (1 << 0);
3004 for (unsigned i
= 0; i
< num_attr
; i
++) {
3005 /* Mask representing the contiguous slots that will be used by this
3008 const unsigned use_mask
= (1 << to_assign
[i
].slots
) - 1;
3010 int location
= find_available_slots(used_locations
, to_assign
[i
].slots
);
3013 const char *const string
= (target_index
== MESA_SHADER_VERTEX
)
3014 ? "vertex shader input" : "fragment shader output";
3017 "insufficient contiguous locations "
3018 "available for %s `%s'\n",
3019 string
, to_assign
[i
].var
->name
);
3023 to_assign
[i
].var
->data
.location
= generic_base
+ location
;
3024 to_assign
[i
].var
->data
.is_unmatched_generic_inout
= 0;
3025 used_locations
|= (use_mask
<< location
);
3027 if (to_assign
[i
].var
->type
->without_array()->is_dual_slot())
3028 double_storage_locations
|= (use_mask
<< location
);
3031 /* Now that we have all the locations, from the GL 4.5 core spec, section
3032 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
3033 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
3034 * as equivalent single-precision types.
3036 if (target_index
== MESA_SHADER_VERTEX
) {
3037 unsigned total_attribs_size
=
3038 _mesa_bitcount(used_locations
& SAFE_MASK_FROM_INDEX(max_index
)) +
3039 _mesa_bitcount(double_storage_locations
);
3040 if (total_attribs_size
> max_index
) {
3042 "attempt to use %d vertex attribute slots only %d available ",
3043 total_attribs_size
, max_index
);
3052 * Match explicit locations of outputs to inputs and deactivate the
3053 * unmatch flag if found so we don't optimise them away.
3056 match_explicit_outputs_to_inputs(gl_linked_shader
*producer
,
3057 gl_linked_shader
*consumer
)
3059 glsl_symbol_table parameters
;
3060 ir_variable
*explicit_locations
[MAX_VARYINGS_INCL_PATCH
][4] =
3063 /* Find all shader outputs in the "producer" stage.
3065 foreach_in_list(ir_instruction
, node
, producer
->ir
) {
3066 ir_variable
*const var
= node
->as_variable();
3068 if ((var
== NULL
) || (var
->data
.mode
!= ir_var_shader_out
))
3071 if (var
->data
.explicit_location
&&
3072 var
->data
.location
>= VARYING_SLOT_VAR0
) {
3073 const unsigned idx
= var
->data
.location
- VARYING_SLOT_VAR0
;
3074 if (explicit_locations
[idx
][var
->data
.location_frac
] == NULL
)
3075 explicit_locations
[idx
][var
->data
.location_frac
] = var
;
3079 /* Match inputs to outputs */
3080 foreach_in_list(ir_instruction
, node
, consumer
->ir
) {
3081 ir_variable
*const input
= node
->as_variable();
3083 if ((input
== NULL
) || (input
->data
.mode
!= ir_var_shader_in
))
3086 ir_variable
*output
= NULL
;
3087 if (input
->data
.explicit_location
3088 && input
->data
.location
>= VARYING_SLOT_VAR0
) {
3089 output
= explicit_locations
[input
->data
.location
- VARYING_SLOT_VAR0
]
3090 [input
->data
.location_frac
];
3092 if (output
!= NULL
){
3093 input
->data
.is_unmatched_generic_inout
= 0;
3094 output
->data
.is_unmatched_generic_inout
= 0;
3101 * Store the gl_FragDepth layout in the gl_shader_program struct.
3104 store_fragdepth_layout(struct gl_shader_program
*prog
)
3106 if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
3110 struct exec_list
*ir
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
]->ir
;
3112 /* We don't look up the gl_FragDepth symbol directly because if
3113 * gl_FragDepth is not used in the shader, it's removed from the IR.
3114 * However, the symbol won't be removed from the symbol table.
3116 * We're only interested in the cases where the variable is NOT removed
3119 foreach_in_list(ir_instruction
, node
, ir
) {
3120 ir_variable
*const var
= node
->as_variable();
3122 if (var
== NULL
|| var
->data
.mode
!= ir_var_shader_out
) {
3126 if (strcmp(var
->name
, "gl_FragDepth") == 0) {
3127 switch (var
->data
.depth_layout
) {
3128 case ir_depth_layout_none
:
3129 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_NONE
;
3131 case ir_depth_layout_any
:
3132 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_ANY
;
3134 case ir_depth_layout_greater
:
3135 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_GREATER
;
3137 case ir_depth_layout_less
:
3138 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_LESS
;
3140 case ir_depth_layout_unchanged
:
3141 prog
->FragDepthLayout
= FRAG_DEPTH_LAYOUT_UNCHANGED
;
3152 * Validate the resources used by a program versus the implementation limits
3155 check_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3157 unsigned total_uniform_blocks
= 0;
3158 unsigned total_shader_storage_blocks
= 0;
3160 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3161 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3166 if (sh
->Program
->info
.num_textures
>
3167 ctx
->Const
.Program
[i
].MaxTextureImageUnits
) {
3168 linker_error(prog
, "Too many %s shader texture samplers\n",
3169 _mesa_shader_stage_to_string(i
));
3172 if (sh
->num_uniform_components
>
3173 ctx
->Const
.Program
[i
].MaxUniformComponents
) {
3174 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3175 linker_warning(prog
, "Too many %s shader default uniform block "
3176 "components, but the driver will try to optimize "
3177 "them out; this is non-portable out-of-spec "
3179 _mesa_shader_stage_to_string(i
));
3181 linker_error(prog
, "Too many %s shader default uniform block "
3183 _mesa_shader_stage_to_string(i
));
3187 if (sh
->num_combined_uniform_components
>
3188 ctx
->Const
.Program
[i
].MaxCombinedUniformComponents
) {
3189 if (ctx
->Const
.GLSLSkipStrictMaxUniformLimitCheck
) {
3190 linker_warning(prog
, "Too many %s shader uniform components, "
3191 "but the driver will try to optimize them out; "
3192 "this is non-portable out-of-spec behavior\n",
3193 _mesa_shader_stage_to_string(i
));
3195 linker_error(prog
, "Too many %s shader uniform components\n",
3196 _mesa_shader_stage_to_string(i
));
3200 total_shader_storage_blocks
+= sh
->Program
->info
.num_ssbos
;
3201 total_uniform_blocks
+= sh
->Program
->info
.num_ubos
;
3203 const unsigned max_uniform_blocks
=
3204 ctx
->Const
.Program
[i
].MaxUniformBlocks
;
3205 if (max_uniform_blocks
< sh
->Program
->info
.num_ubos
) {
3206 linker_error(prog
, "Too many %s uniform blocks (%d/%d)\n",
3207 _mesa_shader_stage_to_string(i
),
3208 sh
->Program
->info
.num_ubos
, max_uniform_blocks
);
3211 const unsigned max_shader_storage_blocks
=
3212 ctx
->Const
.Program
[i
].MaxShaderStorageBlocks
;
3213 if (max_shader_storage_blocks
< sh
->Program
->info
.num_ssbos
) {
3214 linker_error(prog
, "Too many %s shader storage blocks (%d/%d)\n",
3215 _mesa_shader_stage_to_string(i
),
3216 sh
->Program
->info
.num_ssbos
, max_shader_storage_blocks
);
3220 if (total_uniform_blocks
> ctx
->Const
.MaxCombinedUniformBlocks
) {
3221 linker_error(prog
, "Too many combined uniform blocks (%d/%d)\n",
3222 total_uniform_blocks
, ctx
->Const
.MaxCombinedUniformBlocks
);
3225 if (total_shader_storage_blocks
> ctx
->Const
.MaxCombinedShaderStorageBlocks
) {
3226 linker_error(prog
, "Too many combined shader storage blocks (%d/%d)\n",
3227 total_shader_storage_blocks
,
3228 ctx
->Const
.MaxCombinedShaderStorageBlocks
);
3231 for (unsigned i
= 0; i
< prog
->data
->NumUniformBlocks
; i
++) {
3232 if (prog
->data
->UniformBlocks
[i
].UniformBufferSize
>
3233 ctx
->Const
.MaxUniformBlockSize
) {
3234 linker_error(prog
, "Uniform block %s too big (%d/%d)\n",
3235 prog
->data
->UniformBlocks
[i
].Name
,
3236 prog
->data
->UniformBlocks
[i
].UniformBufferSize
,
3237 ctx
->Const
.MaxUniformBlockSize
);
3241 for (unsigned i
= 0; i
< prog
->data
->NumShaderStorageBlocks
; i
++) {
3242 if (prog
->data
->ShaderStorageBlocks
[i
].UniformBufferSize
>
3243 ctx
->Const
.MaxShaderStorageBlockSize
) {
3244 linker_error(prog
, "Shader storage block %s too big (%d/%d)\n",
3245 prog
->data
->ShaderStorageBlocks
[i
].Name
,
3246 prog
->data
->ShaderStorageBlocks
[i
].UniformBufferSize
,
3247 ctx
->Const
.MaxShaderStorageBlockSize
);
3253 link_calculate_subroutine_compat(struct gl_shader_program
*prog
)
3255 unsigned mask
= prog
->data
->linked_stages
;
3257 const int i
= u_bit_scan(&mask
);
3258 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3260 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineUniformRemapTable
; j
++) {
3261 if (p
->sh
.SubroutineUniformRemapTable
[j
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
)
3264 struct gl_uniform_storage
*uni
= p
->sh
.SubroutineUniformRemapTable
[j
];
3270 if (p
->sh
.NumSubroutineFunctions
== 0) {
3271 linker_error(prog
, "subroutine uniform %s defined but no valid functions found\n", uni
->type
->name
);
3274 for (unsigned f
= 0; f
< p
->sh
.NumSubroutineFunctions
; f
++) {
3275 struct gl_subroutine_function
*fn
= &p
->sh
.SubroutineFunctions
[f
];
3276 for (int k
= 0; k
< fn
->num_compat_types
; k
++) {
3277 if (fn
->types
[k
] == uni
->type
) {
3283 uni
->num_compatible_subroutines
= count
;
3289 check_subroutine_resources(struct gl_shader_program
*prog
)
3291 unsigned mask
= prog
->data
->linked_stages
;
3293 const int i
= u_bit_scan(&mask
);
3294 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3296 if (p
->sh
.NumSubroutineUniformRemapTable
> MAX_SUBROUTINE_UNIFORM_LOCATIONS
) {
3297 linker_error(prog
, "Too many %s shader subroutine uniforms\n",
3298 _mesa_shader_stage_to_string(i
));
3303 * Validate shader image resources.
3306 check_image_resources(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
3308 unsigned total_image_units
= 0;
3309 unsigned fragment_outputs
= 0;
3310 unsigned total_shader_storage_blocks
= 0;
3312 if (!ctx
->Extensions
.ARB_shader_image_load_store
)
3315 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3316 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[i
];
3319 if (sh
->Program
->info
.num_images
> ctx
->Const
.Program
[i
].MaxImageUniforms
)
3320 linker_error(prog
, "Too many %s shader image uniforms (%u > %u)\n",
3321 _mesa_shader_stage_to_string(i
),
3322 sh
->Program
->info
.num_images
,
3323 ctx
->Const
.Program
[i
].MaxImageUniforms
);
3325 total_image_units
+= sh
->Program
->info
.num_images
;
3326 total_shader_storage_blocks
+= sh
->Program
->info
.num_ssbos
;
3328 if (i
== MESA_SHADER_FRAGMENT
) {
3329 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3330 ir_variable
*var
= node
->as_variable();
3331 if (var
&& var
->data
.mode
== ir_var_shader_out
)
3332 /* since there are no double fs outputs - pass false */
3333 fragment_outputs
+= var
->type
->count_attribute_slots(false);
3339 if (total_image_units
> ctx
->Const
.MaxCombinedImageUniforms
)
3340 linker_error(prog
, "Too many combined image uniforms\n");
3342 if (total_image_units
+ fragment_outputs
+ total_shader_storage_blocks
>
3343 ctx
->Const
.MaxCombinedShaderOutputResources
)
3344 linker_error(prog
, "Too many combined image uniforms, shader storage "
3345 " buffers and fragment outputs\n");
3350 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3351 * for a variable, checks for overlaps between other uniforms using explicit
3355 reserve_explicit_locations(struct gl_shader_program
*prog
,
3356 string_to_uint_map
*map
, ir_variable
*var
)
3358 unsigned slots
= var
->type
->uniform_locations();
3359 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3360 unsigned return_value
= slots
;
3362 /* Resize remap table if locations do not fit in the current one. */
3363 if (max_loc
+ 1 > prog
->NumUniformRemapTable
) {
3364 prog
->UniformRemapTable
=
3365 reralloc(prog
, prog
->UniformRemapTable
,
3366 gl_uniform_storage
*,
3369 if (!prog
->UniformRemapTable
) {
3370 linker_error(prog
, "Out of memory during linking.\n");
3374 /* Initialize allocated space. */
3375 for (unsigned i
= prog
->NumUniformRemapTable
; i
< max_loc
+ 1; i
++)
3376 prog
->UniformRemapTable
[i
] = NULL
;
3378 prog
->NumUniformRemapTable
= max_loc
+ 1;
3381 for (unsigned i
= 0; i
< slots
; i
++) {
3382 unsigned loc
= var
->data
.location
+ i
;
3384 /* Check if location is already used. */
3385 if (prog
->UniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3387 /* Possibly same uniform from a different stage, this is ok. */
3389 if (map
->get(hash_loc
, var
->name
) && hash_loc
== loc
- i
) {
3394 /* ARB_explicit_uniform_location specification states:
3396 * "No two default-block uniform variables in the program can have
3397 * the same location, even if they are unused, otherwise a compiler
3398 * or linker error will be generated."
3401 "location qualifier for uniform %s overlaps "
3402 "previously used location\n",
3407 /* Initialize location as inactive before optimization
3408 * rounds and location assignment.
3410 prog
->UniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3413 /* Note, base location used for arrays. */
3414 map
->put(var
->data
.location
, var
->name
);
3416 return return_value
;
3420 reserve_subroutine_explicit_locations(struct gl_shader_program
*prog
,
3421 struct gl_program
*p
,
3424 unsigned slots
= var
->type
->uniform_locations();
3425 unsigned max_loc
= var
->data
.location
+ slots
- 1;
3427 /* Resize remap table if locations do not fit in the current one. */
3428 if (max_loc
+ 1 > p
->sh
.NumSubroutineUniformRemapTable
) {
3429 p
->sh
.SubroutineUniformRemapTable
=
3430 reralloc(p
, p
->sh
.SubroutineUniformRemapTable
,
3431 gl_uniform_storage
*,
3434 if (!p
->sh
.SubroutineUniformRemapTable
) {
3435 linker_error(prog
, "Out of memory during linking.\n");
3439 /* Initialize allocated space. */
3440 for (unsigned i
= p
->sh
.NumSubroutineUniformRemapTable
; i
< max_loc
+ 1; i
++)
3441 p
->sh
.SubroutineUniformRemapTable
[i
] = NULL
;
3443 p
->sh
.NumSubroutineUniformRemapTable
= max_loc
+ 1;
3446 for (unsigned i
= 0; i
< slots
; i
++) {
3447 unsigned loc
= var
->data
.location
+ i
;
3449 /* Check if location is already used. */
3450 if (p
->sh
.SubroutineUniformRemapTable
[loc
] == INACTIVE_UNIFORM_EXPLICIT_LOCATION
) {
3452 /* ARB_explicit_uniform_location specification states:
3453 * "No two subroutine uniform variables can have the same location
3454 * in the same shader stage, otherwise a compiler or linker error
3455 * will be generated."
3458 "location qualifier for uniform %s overlaps "
3459 "previously used location\n",
3464 /* Initialize location as inactive before optimization
3465 * rounds and location assignment.
3467 p
->sh
.SubroutineUniformRemapTable
[loc
] = INACTIVE_UNIFORM_EXPLICIT_LOCATION
;
3473 * Check and reserve all explicit uniform locations, called before
3474 * any optimizations happen to handle also inactive uniforms and
3475 * inactive array elements that may get trimmed away.
3478 check_explicit_uniform_locations(struct gl_context
*ctx
,
3479 struct gl_shader_program
*prog
)
3481 prog
->NumExplicitUniformLocations
= 0;
3483 if (!ctx
->Extensions
.ARB_explicit_uniform_location
)
3486 /* This map is used to detect if overlapping explicit locations
3487 * occur with the same uniform (from different stage) or a different one.
3489 string_to_uint_map
*uniform_map
= new string_to_uint_map
;
3492 linker_error(prog
, "Out of memory during linking.\n");
3496 unsigned entries_total
= 0;
3497 unsigned mask
= prog
->data
->linked_stages
;
3499 const int i
= u_bit_scan(&mask
);
3500 struct gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
3502 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
3503 ir_variable
*var
= node
->as_variable();
3504 if (!var
|| var
->data
.mode
!= ir_var_uniform
)
3507 if (var
->data
.explicit_location
) {
3509 if (var
->type
->without_array()->is_subroutine())
3510 ret
= reserve_subroutine_explicit_locations(prog
, p
, var
);
3512 int slots
= reserve_explicit_locations(prog
, uniform_map
,
3516 entries_total
+= slots
;
3527 struct empty_uniform_block
*current_block
= NULL
;
3529 for (unsigned i
= 0; i
< prog
->NumUniformRemapTable
; i
++) {
3530 /* We found empty space in UniformRemapTable. */
3531 if (prog
->UniformRemapTable
[i
] == NULL
) {
3532 /* We've found the beginning of a new continous block of empty slots */
3533 if (!current_block
|| current_block
->start
+ current_block
->slots
!= i
) {
3534 current_block
= rzalloc(prog
, struct empty_uniform_block
);
3535 current_block
->start
= i
;
3536 exec_list_push_tail(&prog
->EmptyUniformLocations
,
3537 ¤t_block
->link
);
3540 /* The current block continues, so we simply increment its slots */
3541 current_block
->slots
++;
3546 prog
->NumExplicitUniformLocations
= entries_total
;
3550 should_add_buffer_variable(struct gl_shader_program
*shProg
,
3551 GLenum type
, const char *name
)
3553 bool found_interface
= false;
3554 unsigned block_name_len
= 0;
3555 const char *block_name_dot
= strchr(name
, '.');
3557 /* These rules only apply to buffer variables. So we return
3558 * true for the rest of types.
3560 if (type
!= GL_BUFFER_VARIABLE
)
3563 for (unsigned i
= 0; i
< shProg
->data
->NumShaderStorageBlocks
; i
++) {
3564 const char *block_name
= shProg
->data
->ShaderStorageBlocks
[i
].Name
;
3565 block_name_len
= strlen(block_name
);
3567 const char *block_square_bracket
= strchr(block_name
, '[');
3568 if (block_square_bracket
) {
3569 /* The block is part of an array of named interfaces,
3570 * for the name comparison we ignore the "[x]" part.
3572 block_name_len
-= strlen(block_square_bracket
);
3575 if (block_name_dot
) {
3576 /* Check if the variable name starts with the interface
3577 * name. The interface name (if present) should have the
3578 * length than the interface block name we are comparing to.
3580 unsigned len
= strlen(name
) - strlen(block_name_dot
);
3581 if (len
!= block_name_len
)
3585 if (strncmp(block_name
, name
, block_name_len
) == 0) {
3586 found_interface
= true;
3591 /* We remove the interface name from the buffer variable name,
3592 * including the dot that follows it.
3594 if (found_interface
)
3595 name
= name
+ block_name_len
+ 1;
3597 /* The ARB_program_interface_query spec says:
3599 * "For an active shader storage block member declared as an array, an
3600 * entry will be generated only for the first array element, regardless
3601 * of its type. For arrays of aggregate types, the enumeration rules
3602 * are applied recursively for the single enumerated array element."
3604 const char *struct_first_dot
= strchr(name
, '.');
3605 const char *first_square_bracket
= strchr(name
, '[');
3607 /* The buffer variable is on top level and it is not an array */
3608 if (!first_square_bracket
) {
3610 /* The shader storage block member is a struct, then generate the entry */
3611 } else if (struct_first_dot
&& struct_first_dot
< first_square_bracket
) {
3614 /* Shader storage block member is an array, only generate an entry for the
3615 * first array element.
3617 if (strncmp(first_square_bracket
, "[0]", 3) == 0)
3625 add_program_resource(struct gl_shader_program
*prog
,
3626 struct set
*resource_set
,
3627 GLenum type
, const void *data
, uint8_t stages
)
3631 /* If resource already exists, do not add it again. */
3632 if (_mesa_set_search(resource_set
, data
))
3635 prog
->data
->ProgramResourceList
=
3636 reralloc(prog
->data
,
3637 prog
->data
->ProgramResourceList
,
3638 gl_program_resource
,
3639 prog
->data
->NumProgramResourceList
+ 1);
3641 if (!prog
->data
->ProgramResourceList
) {
3642 linker_error(prog
, "Out of memory during linking.\n");
3646 struct gl_program_resource
*res
=
3647 &prog
->data
->ProgramResourceList
[prog
->data
->NumProgramResourceList
];
3651 res
->StageReferences
= stages
;
3653 prog
->data
->NumProgramResourceList
++;
3655 _mesa_set_add(resource_set
, data
);
3660 /* Function checks if a variable var is a packed varying and
3661 * if given name is part of packed varying's list.
3663 * If a variable is a packed varying, it has a name like
3664 * 'packed:a,b,c' where a, b and c are separate variables.
3667 included_in_packed_varying(ir_variable
*var
, const char *name
)
3669 if (strncmp(var
->name
, "packed:", 7) != 0)
3672 char *list
= strdup(var
->name
+ 7);
3677 char *token
= strtok_r(list
, ",", &saveptr
);
3679 if (strcmp(token
, name
) == 0) {
3683 token
= strtok_r(NULL
, ",", &saveptr
);
3690 * Function builds a stage reference bitmask from variable name.
3693 build_stageref(struct gl_shader_program
*shProg
, const char *name
,
3698 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3699 * used for reference mask in gl_program_resource will need to be changed.
3701 assert(MESA_SHADER_STAGES
< 8);
3703 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
3704 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
3708 /* Shader symbol table may contain variables that have
3709 * been optimized away. Search IR for the variable instead.
3711 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
3712 ir_variable
*var
= node
->as_variable();
3714 unsigned baselen
= strlen(var
->name
);
3716 if (included_in_packed_varying(var
, name
)) {
3721 /* Type needs to match if specified, otherwise we might
3722 * pick a variable with same name but different interface.
3724 if (var
->data
.mode
!= mode
)
3727 if (strncmp(var
->name
, name
, baselen
) == 0) {
3728 /* Check for exact name matches but also check for arrays and
3731 if (name
[baselen
] == '\0' ||
3732 name
[baselen
] == '[' ||
3733 name
[baselen
] == '.') {
3745 * Create gl_shader_variable from ir_variable class.
3747 static gl_shader_variable
*
3748 create_shader_variable(struct gl_shader_program
*shProg
,
3749 const ir_variable
*in
,
3750 const char *name
, const glsl_type
*type
,
3751 const glsl_type
*interface_type
,
3752 bool use_implicit_location
, int location
,
3753 const glsl_type
*outermost_struct_type
)
3755 /* Allocate zero-initialized memory to ensure that bitfield padding
3758 gl_shader_variable
*out
= rzalloc(shProg
, struct gl_shader_variable
);
3762 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3763 * expect to see gl_VertexID in the program resource list. Pretend.
3765 if (in
->data
.mode
== ir_var_system_value
&&
3766 in
->data
.location
== SYSTEM_VALUE_VERTEX_ID_ZERO_BASE
) {
3767 out
->name
= ralloc_strdup(shProg
, "gl_VertexID");
3768 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3769 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_OUTER
) ||
3770 (in
->data
.mode
== ir_var_system_value
&&
3771 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_OUTER
)) {
3772 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelOuter");
3773 type
= glsl_type::get_array_instance(glsl_type::float_type
, 4);
3774 } else if ((in
->data
.mode
== ir_var_shader_out
&&
3775 in
->data
.location
== VARYING_SLOT_TESS_LEVEL_INNER
) ||
3776 (in
->data
.mode
== ir_var_system_value
&&
3777 in
->data
.location
== SYSTEM_VALUE_TESS_LEVEL_INNER
)) {
3778 out
->name
= ralloc_strdup(shProg
, "gl_TessLevelInner");
3779 type
= glsl_type::get_array_instance(glsl_type::float_type
, 2);
3781 out
->name
= ralloc_strdup(shProg
, name
);
3787 /* The ARB_program_interface_query spec says:
3789 * "Not all active variables are assigned valid locations; the
3790 * following variables will have an effective location of -1:
3792 * * uniforms declared as atomic counters;
3794 * * members of a uniform block;
3796 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3798 * * inputs or outputs not declared with a "location" layout
3799 * qualifier, except for vertex shader inputs and fragment shader
3802 if (in
->type
->is_atomic_uint() || is_gl_identifier(in
->name
) ||
3803 !(in
->data
.explicit_location
|| use_implicit_location
)) {
3806 out
->location
= location
;
3810 out
->outermost_struct_type
= outermost_struct_type
;
3811 out
->interface_type
= interface_type
;
3812 out
->component
= in
->data
.location_frac
;
3813 out
->index
= in
->data
.index
;
3814 out
->patch
= in
->data
.patch
;
3815 out
->mode
= in
->data
.mode
;
3816 out
->interpolation
= in
->data
.interpolation
;
3817 out
->explicit_location
= in
->data
.explicit_location
;
3818 out
->precision
= in
->data
.precision
;
3824 add_shader_variable(const struct gl_context
*ctx
,
3825 struct gl_shader_program
*shProg
,
3826 struct set
*resource_set
,
3827 unsigned stage_mask
,
3828 GLenum programInterface
, ir_variable
*var
,
3829 const char *name
, const glsl_type
*type
,
3830 bool use_implicit_location
, int location
,
3831 bool inouts_share_location
,
3832 const glsl_type
*outermost_struct_type
= NULL
)
3834 const glsl_type
*interface_type
= var
->get_interface_type();
3836 if (outermost_struct_type
== NULL
) {
3837 if (var
->data
.from_named_ifc_block
) {
3838 const char *interface_name
= interface_type
->name
;
3840 if (interface_type
->is_array()) {
3841 /* Issue #16 of the ARB_program_interface_query spec says:
3843 * "* If a variable is a member of an interface block without an
3844 * instance name, it is enumerated using just the variable name.
3846 * * If a variable is a member of an interface block with an
3847 * instance name, it is enumerated as "BlockName.Member", where
3848 * "BlockName" is the name of the interface block (not the
3849 * instance name) and "Member" is the name of the variable."
3851 * In particular, it indicates that it should be "BlockName",
3852 * not "BlockName[array length]". The conformance suite and
3853 * dEQP both require this behavior.
3855 * Here, we unwrap the extra array level added by named interface
3856 * block array lowering so we have the correct variable type. We
3857 * also unwrap the interface type when constructing the name.
3859 * We leave interface_type the same so that ES 3.x SSO pipeline
3860 * validation can enforce the rules requiring array length to
3861 * match on interface blocks.
3863 type
= type
->fields
.array
;
3865 interface_name
= interface_type
->fields
.array
->name
;
3868 name
= ralloc_asprintf(shProg
, "%s.%s", interface_name
, name
);
3872 switch (type
->base_type
) {
3873 case GLSL_TYPE_STRUCT
: {
3874 /* The ARB_program_interface_query spec says:
3876 * "For an active variable declared as a structure, a separate entry
3877 * will be generated for each active structure member. The name of
3878 * each entry is formed by concatenating the name of the structure,
3879 * the "." character, and the name of the structure member. If a
3880 * structure member to enumerate is itself a structure or array,
3881 * these enumeration rules are applied recursively."
3883 if (outermost_struct_type
== NULL
)
3884 outermost_struct_type
= type
;
3886 unsigned field_location
= location
;
3887 for (unsigned i
= 0; i
< type
->length
; i
++) {
3888 const struct glsl_struct_field
*field
= &type
->fields
.structure
[i
];
3889 char *field_name
= ralloc_asprintf(shProg
, "%s.%s", name
, field
->name
);
3890 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3891 stage_mask
, programInterface
,
3892 var
, field_name
, field
->type
,
3893 use_implicit_location
, field_location
,
3894 false, outermost_struct_type
))
3897 field_location
+= field
->type
->count_attribute_slots(false);
3902 case GLSL_TYPE_ARRAY
: {
3903 /* The ARB_program_interface_query spec says:
3905 * "For an active variable declared as an array of basic types, a
3906 * single entry will be generated, with its name string formed by
3907 * concatenating the name of the array and the string "[0]"."
3909 * "For an active variable declared as an array of an aggregate data
3910 * type (structures or arrays), a separate entry will be generated
3911 * for each active array element, unless noted immediately below.
3912 * The name of each entry is formed by concatenating the name of
3913 * the array, the "[" character, an integer identifying the element
3914 * number, and the "]" character. These enumeration rules are
3915 * applied recursively, treating each enumerated array element as a
3916 * separate active variable."
3918 const struct glsl_type
*array_type
= type
->fields
.array
;
3919 if (array_type
->base_type
== GLSL_TYPE_STRUCT
||
3920 array_type
->base_type
== GLSL_TYPE_ARRAY
) {
3921 unsigned elem_location
= location
;
3922 unsigned stride
= inouts_share_location
? 0 :
3923 array_type
->count_attribute_slots(false);
3924 for (unsigned i
= 0; i
< type
->length
; i
++) {
3925 char *elem
= ralloc_asprintf(shProg
, "%s[%d]", name
, i
);
3926 if (!add_shader_variable(ctx
, shProg
, resource_set
,
3927 stage_mask
, programInterface
,
3928 var
, elem
, array_type
,
3929 use_implicit_location
, elem_location
,
3930 false, outermost_struct_type
))
3932 elem_location
+= stride
;
3940 /* The ARB_program_interface_query spec says:
3942 * "For an active variable declared as a single instance of a basic
3943 * type, a single entry will be generated, using the variable name
3944 * from the shader source."
3946 gl_shader_variable
*sha_v
=
3947 create_shader_variable(shProg
, var
, name
, type
, interface_type
,
3948 use_implicit_location
, location
,
3949 outermost_struct_type
);
3953 return add_program_resource(shProg
, resource_set
,
3954 programInterface
, sha_v
, stage_mask
);
3960 inout_has_same_location(const ir_variable
*var
, unsigned stage
)
3962 if (!var
->data
.patch
&&
3963 ((var
->data
.mode
== ir_var_shader_out
&&
3964 stage
== MESA_SHADER_TESS_CTRL
) ||
3965 (var
->data
.mode
== ir_var_shader_in
&&
3966 (stage
== MESA_SHADER_TESS_CTRL
|| stage
== MESA_SHADER_TESS_EVAL
||
3967 stage
== MESA_SHADER_GEOMETRY
))))
3974 add_interface_variables(const struct gl_context
*ctx
,
3975 struct gl_shader_program
*shProg
,
3976 struct set
*resource_set
,
3977 unsigned stage
, GLenum programInterface
)
3979 exec_list
*ir
= shProg
->_LinkedShaders
[stage
]->ir
;
3981 foreach_in_list(ir_instruction
, node
, ir
) {
3982 ir_variable
*var
= node
->as_variable();
3984 if (!var
|| var
->data
.how_declared
== ir_var_hidden
)
3989 switch (var
->data
.mode
) {
3990 case ir_var_system_value
:
3991 case ir_var_shader_in
:
3992 if (programInterface
!= GL_PROGRAM_INPUT
)
3994 loc_bias
= (stage
== MESA_SHADER_VERTEX
) ? int(VERT_ATTRIB_GENERIC0
)
3995 : int(VARYING_SLOT_VAR0
);
3997 case ir_var_shader_out
:
3998 if (programInterface
!= GL_PROGRAM_OUTPUT
)
4000 loc_bias
= (stage
== MESA_SHADER_FRAGMENT
) ? int(FRAG_RESULT_DATA0
)
4001 : int(VARYING_SLOT_VAR0
);
4007 if (var
->data
.patch
)
4008 loc_bias
= int(VARYING_SLOT_PATCH0
);
4010 /* Skip packed varyings, packed varyings are handled separately
4011 * by add_packed_varyings.
4013 if (strncmp(var
->name
, "packed:", 7) == 0)
4016 /* Skip fragdata arrays, these are handled separately
4017 * by add_fragdata_arrays.
4019 if (strncmp(var
->name
, "gl_out_FragData", 15) == 0)
4022 const bool vs_input_or_fs_output
=
4023 (stage
== MESA_SHADER_VERTEX
&& var
->data
.mode
== ir_var_shader_in
) ||
4024 (stage
== MESA_SHADER_FRAGMENT
&& var
->data
.mode
== ir_var_shader_out
);
4026 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4027 1 << stage
, programInterface
,
4028 var
, var
->name
, var
->type
, vs_input_or_fs_output
,
4029 var
->data
.location
- loc_bias
,
4030 inout_has_same_location(var
, stage
)))
4037 add_packed_varyings(const struct gl_context
*ctx
,
4038 struct gl_shader_program
*shProg
,
4039 struct set
*resource_set
,
4040 int stage
, GLenum type
)
4042 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[stage
];
4045 if (!sh
|| !sh
->packed_varyings
)
4048 foreach_in_list(ir_instruction
, node
, sh
->packed_varyings
) {
4049 ir_variable
*var
= node
->as_variable();
4051 switch (var
->data
.mode
) {
4052 case ir_var_shader_in
:
4053 iface
= GL_PROGRAM_INPUT
;
4055 case ir_var_shader_out
:
4056 iface
= GL_PROGRAM_OUTPUT
;
4059 unreachable("unexpected type");
4062 if (type
== iface
) {
4063 const int stage_mask
=
4064 build_stageref(shProg
, var
->name
, var
->data
.mode
);
4065 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4067 iface
, var
, var
->name
, var
->type
, false,
4068 var
->data
.location
- VARYING_SLOT_VAR0
,
4069 inout_has_same_location(var
, stage
)))
4078 add_fragdata_arrays(const struct gl_context
*ctx
,
4079 struct gl_shader_program
*shProg
,
4080 struct set
*resource_set
)
4082 struct gl_linked_shader
*sh
= shProg
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
4084 if (!sh
|| !sh
->fragdata_arrays
)
4087 foreach_in_list(ir_instruction
, node
, sh
->fragdata_arrays
) {
4088 ir_variable
*var
= node
->as_variable();
4090 assert(var
->data
.mode
== ir_var_shader_out
);
4092 if (!add_shader_variable(ctx
, shProg
, resource_set
,
4093 1 << MESA_SHADER_FRAGMENT
,
4094 GL_PROGRAM_OUTPUT
, var
, var
->name
, var
->type
,
4095 true, var
->data
.location
- FRAG_RESULT_DATA0
,
4104 get_top_level_name(const char *name
)
4106 const char *first_dot
= strchr(name
, '.');
4107 const char *first_square_bracket
= strchr(name
, '[');
4110 /* The ARB_program_interface_query spec says:
4112 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4113 * the number of active array elements of the top-level shader storage
4114 * block member containing to the active variable is written to
4115 * <params>. If the top-level block member is not declared as an
4116 * array, the value one is written to <params>. If the top-level block
4117 * member is an array with no declared size, the value zero is written
4121 /* The buffer variable is on top level.*/
4122 if (!first_square_bracket
&& !first_dot
)
4123 name_size
= strlen(name
);
4124 else if ((!first_square_bracket
||
4125 (first_dot
&& first_dot
< first_square_bracket
)))
4126 name_size
= first_dot
- name
;
4128 name_size
= first_square_bracket
- name
;
4130 return strndup(name
, name_size
);
4134 get_var_name(const char *name
)
4136 const char *first_dot
= strchr(name
, '.');
4139 return strdup(name
);
4141 return strndup(first_dot
+1, strlen(first_dot
) - 1);
4145 is_top_level_shader_storage_block_member(const char* name
,
4146 const char* interface_name
,
4147 const char* field_name
)
4149 bool result
= false;
4151 /* If the given variable is already a top-level shader storage
4152 * block member, then return array_size = 1.
4153 * We could have two possibilities: if we have an instanced
4154 * shader storage block or not instanced.
4156 * For the first, we check create a name as it was in top level and
4157 * compare it with the real name. If they are the same, then
4158 * the variable is already at top-level.
4160 * Full instanced name is: interface name + '.' + var name +
4163 int name_length
= strlen(interface_name
) + 1 + strlen(field_name
) + 1;
4164 char *full_instanced_name
= (char *) calloc(name_length
, sizeof(char));
4165 if (!full_instanced_name
) {
4166 fprintf(stderr
, "%s: Cannot allocate space for name\n", __func__
);
4170 snprintf(full_instanced_name
, name_length
, "%s.%s",
4171 interface_name
, field_name
);
4173 /* Check if its top-level shader storage block member of an
4174 * instanced interface block, or of a unnamed interface block.
4176 if (strcmp(name
, full_instanced_name
) == 0 ||
4177 strcmp(name
, field_name
) == 0)
4180 free(full_instanced_name
);
4185 get_array_size(struct gl_uniform_storage
*uni
, const glsl_struct_field
*field
,
4186 char *interface_name
, char *var_name
)
4188 /* The ARB_program_interface_query spec says:
4190 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4191 * the number of active array elements of the top-level shader storage
4192 * block member containing to the active variable is written to
4193 * <params>. If the top-level block member is not declared as an
4194 * array, the value one is written to <params>. If the top-level block
4195 * member is an array with no declared size, the value zero is written
4198 if (is_top_level_shader_storage_block_member(uni
->name
,
4202 else if (field
->type
->is_unsized_array())
4204 else if (field
->type
->is_array())
4205 return field
->type
->length
;
4211 get_array_stride(struct gl_context
*ctx
, struct gl_uniform_storage
*uni
,
4212 const glsl_type
*iface
, const glsl_struct_field
*field
,
4213 char *interface_name
, char *var_name
)
4215 /* The ARB_program_interface_query spec says:
4217 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
4218 * identifying the stride between array elements of the top-level
4219 * shader storage block member containing the active variable is
4220 * written to <params>. For top-level block members declared as
4221 * arrays, the value written is the difference, in basic machine units,
4222 * between the offsets of the active variable for consecutive elements
4223 * in the top-level array. For top-level block members not declared as
4224 * an array, zero is written to <params>."
4226 if (field
->type
->is_array()) {
4227 const enum glsl_matrix_layout matrix_layout
=
4228 glsl_matrix_layout(field
->matrix_layout
);
4229 bool row_major
= matrix_layout
== GLSL_MATRIX_LAYOUT_ROW_MAJOR
;
4230 const glsl_type
*array_type
= field
->type
->fields
.array
;
4232 if (is_top_level_shader_storage_block_member(uni
->name
,
4237 if (GLSL_INTERFACE_PACKING_STD140
==
4239 get_internal_ifc_packing(ctx
->Const
.UseSTD430AsDefaultPacking
)) {
4240 if (array_type
->is_record() || array_type
->is_array())
4241 return glsl_align(array_type
->std140_size(row_major
), 16);
4243 return MAX2(array_type
->std140_base_alignment(row_major
), 16);
4245 return array_type
->std430_array_stride(row_major
);
4252 calculate_array_size_and_stride(struct gl_context
*ctx
,
4253 struct gl_shader_program
*shProg
,
4254 struct gl_uniform_storage
*uni
)
4256 int block_index
= uni
->block_index
;
4257 int array_size
= -1;
4258 int array_stride
= -1;
4259 char *var_name
= get_top_level_name(uni
->name
);
4260 char *interface_name
=
4261 get_top_level_name(uni
->is_shader_storage
?
4262 shProg
->data
->ShaderStorageBlocks
[block_index
].Name
:
4263 shProg
->data
->UniformBlocks
[block_index
].Name
);
4265 if (strcmp(var_name
, interface_name
) == 0) {
4266 /* Deal with instanced array of SSBOs */
4267 char *temp_name
= get_var_name(uni
->name
);
4269 linker_error(shProg
, "Out of memory during linking.\n");
4270 goto write_top_level_array_size_and_stride
;
4273 var_name
= get_top_level_name(temp_name
);
4276 linker_error(shProg
, "Out of memory during linking.\n");
4277 goto write_top_level_array_size_and_stride
;
4281 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4282 const gl_linked_shader
*sh
= shProg
->_LinkedShaders
[i
];
4286 foreach_in_list(ir_instruction
, node
, sh
->ir
) {
4287 ir_variable
*var
= node
->as_variable();
4288 if (!var
|| !var
->get_interface_type() ||
4289 var
->data
.mode
!= ir_var_shader_storage
)
4292 const glsl_type
*iface
= var
->get_interface_type();
4294 if (strcmp(interface_name
, iface
->name
) != 0)
4297 for (unsigned i
= 0; i
< iface
->length
; i
++) {
4298 const glsl_struct_field
*field
= &iface
->fields
.structure
[i
];
4299 if (strcmp(field
->name
, var_name
) != 0)
4302 array_stride
= get_array_stride(ctx
, uni
, iface
, field
,
4303 interface_name
, var_name
);
4304 array_size
= get_array_size(uni
, field
, interface_name
, var_name
);
4305 goto write_top_level_array_size_and_stride
;
4309 write_top_level_array_size_and_stride
:
4310 free(interface_name
);
4312 uni
->top_level_array_stride
= array_stride
;
4313 uni
->top_level_array_size
= array_size
;
4317 * Builds up a list of program resources that point to existing
4321 build_program_resource_list(struct gl_context
*ctx
,
4322 struct gl_shader_program
*shProg
)
4324 /* Rebuild resource list. */
4325 if (shProg
->data
->ProgramResourceList
) {
4326 ralloc_free(shProg
->data
->ProgramResourceList
);
4327 shProg
->data
->ProgramResourceList
= NULL
;
4328 shProg
->data
->NumProgramResourceList
= 0;
4331 int input_stage
= MESA_SHADER_STAGES
, output_stage
= 0;
4333 /* Determine first input and final output stage. These are used to
4334 * detect which variables should be enumerated in the resource list
4335 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4337 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4338 if (!shProg
->_LinkedShaders
[i
])
4340 if (input_stage
== MESA_SHADER_STAGES
)
4345 /* Empty shader, no resources. */
4346 if (input_stage
== MESA_SHADER_STAGES
&& output_stage
== 0)
4349 struct set
*resource_set
= _mesa_set_create(NULL
,
4351 _mesa_key_pointer_equal
);
4353 /* Program interface needs to expose varyings in case of SSO. */
4354 if (shProg
->SeparateShader
) {
4355 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4356 input_stage
, GL_PROGRAM_INPUT
))
4359 if (!add_packed_varyings(ctx
, shProg
, resource_set
,
4360 output_stage
, GL_PROGRAM_OUTPUT
))
4364 if (!add_fragdata_arrays(ctx
, shProg
, resource_set
))
4367 /* Add inputs and outputs to the resource list. */
4368 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4369 input_stage
, GL_PROGRAM_INPUT
))
4372 if (!add_interface_variables(ctx
, shProg
, resource_set
,
4373 output_stage
, GL_PROGRAM_OUTPUT
))
4376 if (shProg
->last_vert_prog
) {
4377 struct gl_transform_feedback_info
*linked_xfb
=
4378 shProg
->last_vert_prog
->sh
.LinkedTransformFeedback
;
4380 /* Add transform feedback varyings. */
4381 if (linked_xfb
->NumVarying
> 0) {
4382 for (int i
= 0; i
< linked_xfb
->NumVarying
; i
++) {
4383 if (!add_program_resource(shProg
, resource_set
,
4384 GL_TRANSFORM_FEEDBACK_VARYING
,
4385 &linked_xfb
->Varyings
[i
], 0))
4390 /* Add transform feedback buffers. */
4391 for (unsigned i
= 0; i
< ctx
->Const
.MaxTransformFeedbackBuffers
; i
++) {
4392 if ((linked_xfb
->ActiveBuffers
>> i
) & 1) {
4393 linked_xfb
->Buffers
[i
].Binding
= i
;
4394 if (!add_program_resource(shProg
, resource_set
,
4395 GL_TRANSFORM_FEEDBACK_BUFFER
,
4396 &linked_xfb
->Buffers
[i
], 0))
4402 /* Add uniforms from uniform storage. */
4403 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4404 /* Do not add uniforms internally used by Mesa. */
4405 if (shProg
->data
->UniformStorage
[i
].hidden
)
4409 build_stageref(shProg
, shProg
->data
->UniformStorage
[i
].name
,
4412 /* Add stagereferences for uniforms in a uniform block. */
4413 bool is_shader_storage
=
4414 shProg
->data
->UniformStorage
[i
].is_shader_storage
;
4415 int block_index
= shProg
->data
->UniformStorage
[i
].block_index
;
4416 if (block_index
!= -1) {
4417 stageref
|= is_shader_storage
?
4418 shProg
->data
->ShaderStorageBlocks
[block_index
].stageref
:
4419 shProg
->data
->UniformBlocks
[block_index
].stageref
;
4422 GLenum type
= is_shader_storage
? GL_BUFFER_VARIABLE
: GL_UNIFORM
;
4423 if (!should_add_buffer_variable(shProg
, type
,
4424 shProg
->data
->UniformStorage
[i
].name
))
4427 if (is_shader_storage
) {
4428 calculate_array_size_and_stride(ctx
, shProg
,
4429 &shProg
->data
->UniformStorage
[i
]);
4432 if (!add_program_resource(shProg
, resource_set
, type
,
4433 &shProg
->data
->UniformStorage
[i
], stageref
))
4437 /* Add program uniform blocks. */
4438 for (unsigned i
= 0; i
< shProg
->data
->NumUniformBlocks
; i
++) {
4439 if (!add_program_resource(shProg
, resource_set
, GL_UNIFORM_BLOCK
,
4440 &shProg
->data
->UniformBlocks
[i
], 0))
4444 /* Add program shader storage blocks. */
4445 for (unsigned i
= 0; i
< shProg
->data
->NumShaderStorageBlocks
; i
++) {
4446 if (!add_program_resource(shProg
, resource_set
, GL_SHADER_STORAGE_BLOCK
,
4447 &shProg
->data
->ShaderStorageBlocks
[i
], 0))
4451 /* Add atomic counter buffers. */
4452 for (unsigned i
= 0; i
< shProg
->data
->NumAtomicBuffers
; i
++) {
4453 if (!add_program_resource(shProg
, resource_set
, GL_ATOMIC_COUNTER_BUFFER
,
4454 &shProg
->data
->AtomicBuffers
[i
], 0))
4458 for (unsigned i
= 0; i
< shProg
->data
->NumUniformStorage
; i
++) {
4460 if (!shProg
->data
->UniformStorage
[i
].hidden
)
4463 for (int j
= MESA_SHADER_VERTEX
; j
< MESA_SHADER_STAGES
; j
++) {
4464 if (!shProg
->data
->UniformStorage
[i
].opaque
[j
].active
||
4465 !shProg
->data
->UniformStorage
[i
].type
->is_subroutine())
4468 type
= _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage
)j
);
4469 /* add shader subroutines */
4470 if (!add_program_resource(shProg
, resource_set
,
4471 type
, &shProg
->data
->UniformStorage
[i
], 0))
4476 unsigned mask
= shProg
->data
->linked_stages
;
4478 const int i
= u_bit_scan(&mask
);
4479 struct gl_program
*p
= shProg
->_LinkedShaders
[i
]->Program
;
4481 GLuint type
= _mesa_shader_stage_to_subroutine((gl_shader_stage
)i
);
4482 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4483 if (!add_program_resource(shProg
, resource_set
,
4484 type
, &p
->sh
.SubroutineFunctions
[j
], 0))
4489 _mesa_set_destroy(resource_set
, NULL
);
4493 * This check is done to make sure we allow only constant expression
4494 * indexing and "constant-index-expression" (indexing with an expression
4495 * that includes loop induction variable).
4498 validate_sampler_array_indexing(struct gl_context
*ctx
,
4499 struct gl_shader_program
*prog
)
4501 dynamic_sampler_array_indexing_visitor v
;
4502 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4503 if (prog
->_LinkedShaders
[i
] == NULL
)
4506 bool no_dynamic_indexing
=
4507 ctx
->Const
.ShaderCompilerOptions
[i
].EmitNoIndirectSampler
;
4509 /* Search for array derefs in shader. */
4510 v
.run(prog
->_LinkedShaders
[i
]->ir
);
4511 if (v
.uses_dynamic_sampler_array_indexing()) {
4512 const char *msg
= "sampler arrays indexed with non-constant "
4513 "expressions is forbidden in GLSL %s %u";
4514 /* Backend has indicated that it has no dynamic indexing support. */
4515 if (no_dynamic_indexing
) {
4516 linker_error(prog
, msg
, prog
->IsES
? "ES" : "",
4517 prog
->data
->Version
);
4520 linker_warning(prog
, msg
, prog
->IsES
? "ES" : "",
4521 prog
->data
->Version
);
4529 link_assign_subroutine_types(struct gl_shader_program
*prog
)
4531 unsigned mask
= prog
->data
->linked_stages
;
4533 const int i
= u_bit_scan(&mask
);
4534 gl_program
*p
= prog
->_LinkedShaders
[i
]->Program
;
4536 p
->sh
.MaxSubroutineFunctionIndex
= 0;
4537 foreach_in_list(ir_instruction
, node
, prog
->_LinkedShaders
[i
]->ir
) {
4538 ir_function
*fn
= node
->as_function();
4542 if (fn
->is_subroutine
)
4543 p
->sh
.NumSubroutineUniformTypes
++;
4545 if (!fn
->num_subroutine_types
)
4548 /* these should have been calculated earlier. */
4549 assert(fn
->subroutine_index
!= -1);
4550 if (p
->sh
.NumSubroutineFunctions
+ 1 > MAX_SUBROUTINES
) {
4551 linker_error(prog
, "Too many subroutine functions declared.\n");
4554 p
->sh
.SubroutineFunctions
= reralloc(p
, p
->sh
.SubroutineFunctions
,
4555 struct gl_subroutine_function
,
4556 p
->sh
.NumSubroutineFunctions
+ 1);
4557 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].name
= ralloc_strdup(p
, fn
->name
);
4558 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].num_compat_types
= fn
->num_subroutine_types
;
4559 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
=
4560 ralloc_array(p
, const struct glsl_type
*,
4561 fn
->num_subroutine_types
);
4563 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4566 * "Each subroutine with an index qualifier in the shader must be
4567 * given a unique index, otherwise a compile or link error will be
4570 for (unsigned j
= 0; j
< p
->sh
.NumSubroutineFunctions
; j
++) {
4571 if (p
->sh
.SubroutineFunctions
[j
].index
!= -1 &&
4572 p
->sh
.SubroutineFunctions
[j
].index
== fn
->subroutine_index
) {
4573 linker_error(prog
, "each subroutine index qualifier in the "
4574 "shader must be unique\n");
4578 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].index
=
4579 fn
->subroutine_index
;
4581 if (fn
->subroutine_index
> (int)p
->sh
.MaxSubroutineFunctionIndex
)
4582 p
->sh
.MaxSubroutineFunctionIndex
= fn
->subroutine_index
;
4584 for (int j
= 0; j
< fn
->num_subroutine_types
; j
++)
4585 p
->sh
.SubroutineFunctions
[p
->sh
.NumSubroutineFunctions
].types
[j
] = fn
->subroutine_types
[j
];
4586 p
->sh
.NumSubroutineFunctions
++;
4592 set_always_active_io(exec_list
*ir
, ir_variable_mode io_mode
)
4594 assert(io_mode
== ir_var_shader_in
|| io_mode
== ir_var_shader_out
);
4596 foreach_in_list(ir_instruction
, node
, ir
) {
4597 ir_variable
*const var
= node
->as_variable();
4599 if (var
== NULL
|| var
->data
.mode
!= io_mode
)
4602 /* Don't set always active on builtins that haven't been redeclared */
4603 if (var
->data
.how_declared
== ir_var_declared_implicitly
)
4606 var
->data
.always_active_io
= true;
4611 * When separate shader programs are enabled, only input/outputs between
4612 * the stages of a multi-stage separate program can be safely removed
4613 * from the shader interface. Other inputs/outputs must remain active.
4616 disable_varying_optimizations_for_sso(struct gl_shader_program
*prog
)
4618 unsigned first
, last
;
4619 assert(prog
->SeparateShader
);
4621 first
= MESA_SHADER_STAGES
;
4624 /* Determine first and last stage. Excluding the compute stage */
4625 for (unsigned i
= 0; i
< MESA_SHADER_COMPUTE
; i
++) {
4626 if (!prog
->_LinkedShaders
[i
])
4628 if (first
== MESA_SHADER_STAGES
)
4633 if (first
== MESA_SHADER_STAGES
)
4636 for (unsigned stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4637 gl_linked_shader
*sh
= prog
->_LinkedShaders
[stage
];
4641 /* Prevent the removal of inputs to the first and outputs from the last
4642 * stage, unless they are the initial pipeline inputs or final pipeline
4643 * outputs, respectively.
4645 * The removal of IO between shaders in the same program is always
4648 if (stage
== first
&& stage
!= MESA_SHADER_VERTEX
)
4649 set_always_active_io(sh
->ir
, ir_var_shader_in
);
4650 if (stage
== last
&& stage
!= MESA_SHADER_FRAGMENT
)
4651 set_always_active_io(sh
->ir
, ir_var_shader_out
);
4656 link_and_validate_uniforms(struct gl_context
*ctx
,
4657 struct gl_shader_program
*prog
)
4659 update_array_sizes(prog
);
4660 link_assign_uniform_locations(prog
, ctx
);
4662 link_assign_atomic_counter_resources(ctx
, prog
);
4663 link_calculate_subroutine_compat(prog
);
4664 check_resources(ctx
, prog
);
4665 check_subroutine_resources(prog
);
4666 check_image_resources(ctx
, prog
);
4667 link_check_atomic_counter_resources(ctx
, prog
);
4671 link_varyings_and_uniforms(unsigned first
, unsigned last
,
4672 struct gl_context
*ctx
,
4673 struct gl_shader_program
*prog
, void *mem_ctx
)
4675 /* Mark all generic shader inputs and outputs as unpaired. */
4676 for (unsigned i
= MESA_SHADER_VERTEX
; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4677 if (prog
->_LinkedShaders
[i
] != NULL
) {
4678 link_invalidate_variable_locations(prog
->_LinkedShaders
[i
]->ir
);
4682 unsigned prev
= first
;
4683 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4684 if (prog
->_LinkedShaders
[i
] == NULL
)
4687 match_explicit_outputs_to_inputs(prog
->_LinkedShaders
[prev
],
4688 prog
->_LinkedShaders
[i
]);
4692 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4693 MESA_SHADER_VERTEX
)) {
4697 if (!assign_attribute_or_color_locations(mem_ctx
, prog
, &ctx
->Const
,
4698 MESA_SHADER_FRAGMENT
)) {
4702 prog
->last_vert_prog
= NULL
;
4703 for (int i
= MESA_SHADER_GEOMETRY
; i
>= MESA_SHADER_VERTEX
; i
--) {
4704 if (prog
->_LinkedShaders
[i
] == NULL
)
4707 prog
->last_vert_prog
= prog
->_LinkedShaders
[i
]->Program
;
4711 if (!link_varyings(prog
, first
, last
, ctx
, mem_ctx
))
4714 link_and_validate_uniforms(ctx
, prog
);
4716 if (!prog
->data
->LinkStatus
)
4719 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4720 if (prog
->_LinkedShaders
[i
] == NULL
)
4723 const struct gl_shader_compiler_options
*options
=
4724 &ctx
->Const
.ShaderCompilerOptions
[i
];
4726 if (options
->LowerBufferInterfaceBlocks
)
4727 lower_ubo_reference(prog
->_LinkedShaders
[i
],
4728 options
->ClampBlockIndicesToArrayBounds
,
4729 ctx
->Const
.UseSTD430AsDefaultPacking
);
4731 if (i
== MESA_SHADER_COMPUTE
)
4732 lower_shared_reference(ctx
, prog
, prog
->_LinkedShaders
[i
]);
4734 lower_vector_derefs(prog
->_LinkedShaders
[i
]);
4735 do_vec_index_to_swizzle(prog
->_LinkedShaders
[i
]->ir
);
4742 linker_optimisation_loop(struct gl_context
*ctx
, exec_list
*ir
,
4745 if (ctx
->Const
.GLSLOptimizeConservatively
) {
4746 /* Run it just once. */
4747 do_common_optimization(ir
, true, false,
4748 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4749 ctx
->Const
.NativeIntegers
);
4751 /* Repeat it until it stops making changes. */
4752 while (do_common_optimization(ir
, true, false,
4753 &ctx
->Const
.ShaderCompilerOptions
[stage
],
4754 ctx
->Const
.NativeIntegers
))
4760 link_shaders(struct gl_context
*ctx
, struct gl_shader_program
*prog
)
4762 prog
->data
->LinkStatus
= LINKING_SUCCESS
; /* All error paths will set this to false */
4763 prog
->data
->Validated
= false;
4765 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4767 * "Linking can fail for a variety of reasons as specified in the
4768 * OpenGL Shading Language Specification, as well as any of the
4769 * following reasons:
4771 * - No shader objects are attached to program."
4773 * The Compatibility Profile specification does not list the error. In
4774 * Compatibility Profile missing shader stages are replaced by
4775 * fixed-function. This applies to the case where all stages are
4778 if (prog
->NumShaders
== 0) {
4779 if (ctx
->API
!= API_OPENGL_COMPAT
)
4780 linker_error(prog
, "no shaders attached to the program\n");
4784 #ifdef ENABLE_SHADER_CACHE
4785 if (shader_cache_read_program_metadata(ctx
, prog
))
4789 void *mem_ctx
= ralloc_context(NULL
); // temporary linker context
4791 prog
->ARB_fragment_coord_conventions_enable
= false;
4793 /* Separate the shaders into groups based on their type.
4795 struct gl_shader
**shader_list
[MESA_SHADER_STAGES
];
4796 unsigned num_shaders
[MESA_SHADER_STAGES
];
4798 for (int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4799 shader_list
[i
] = (struct gl_shader
**)
4800 calloc(prog
->NumShaders
, sizeof(struct gl_shader
*));
4804 unsigned min_version
= UINT_MAX
;
4805 unsigned max_version
= 0;
4806 for (unsigned i
= 0; i
< prog
->NumShaders
; i
++) {
4807 min_version
= MIN2(min_version
, prog
->Shaders
[i
]->Version
);
4808 max_version
= MAX2(max_version
, prog
->Shaders
[i
]->Version
);
4810 if (prog
->Shaders
[i
]->IsES
!= prog
->Shaders
[0]->IsES
) {
4811 linker_error(prog
, "all shaders must use same shading "
4812 "language version\n");
4816 if (prog
->Shaders
[i
]->ARB_fragment_coord_conventions_enable
) {
4817 prog
->ARB_fragment_coord_conventions_enable
= true;
4820 gl_shader_stage shader_type
= prog
->Shaders
[i
]->Stage
;
4821 shader_list
[shader_type
][num_shaders
[shader_type
]] = prog
->Shaders
[i
];
4822 num_shaders
[shader_type
]++;
4825 /* In desktop GLSL, different shader versions may be linked together. In
4826 * GLSL ES, all shader versions must be the same.
4828 if (prog
->Shaders
[0]->IsES
&& min_version
!= max_version
) {
4829 linker_error(prog
, "all shaders must use same shading "
4830 "language version\n");
4834 prog
->data
->Version
= max_version
;
4835 prog
->IsES
= prog
->Shaders
[0]->IsES
;
4837 /* Some shaders have to be linked with some other shaders present.
4839 if (!prog
->SeparateShader
) {
4840 if (num_shaders
[MESA_SHADER_GEOMETRY
] > 0 &&
4841 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4842 linker_error(prog
, "Geometry shader must be linked with "
4846 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4847 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4848 linker_error(prog
, "Tessellation evaluation shader must be linked "
4849 "with vertex shader\n");
4852 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4853 num_shaders
[MESA_SHADER_VERTEX
] == 0) {
4854 linker_error(prog
, "Tessellation control shader must be linked with "
4859 /* Section 7.3 of the OpenGL ES 3.2 specification says:
4861 * "Linking can fail for [...] any of the following reasons:
4863 * * program contains an object to form a tessellation control
4864 * shader [...] and [...] the program is not separable and
4865 * contains no object to form a tessellation evaluation shader"
4867 * The OpenGL spec is contradictory. It allows linking without a tess
4868 * eval shader, but that can only be used with transform feedback and
4869 * rasterization disabled. However, transform feedback isn't allowed
4870 * with GL_PATCHES, so it can't be used.
4872 * More investigation showed that the idea of transform feedback after
4873 * a tess control shader was dropped, because some hw vendors couldn't
4874 * support tessellation without a tess eval shader, but the linker
4875 * section wasn't updated to reflect that.
4877 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4880 * Do what's reasonable and always require a tess eval shader if a tess
4881 * control shader is present.
4883 if (num_shaders
[MESA_SHADER_TESS_CTRL
] > 0 &&
4884 num_shaders
[MESA_SHADER_TESS_EVAL
] == 0) {
4885 linker_error(prog
, "Tessellation control shader must be linked with "
4886 "tessellation evaluation shader\n");
4891 if (num_shaders
[MESA_SHADER_TESS_EVAL
] > 0 &&
4892 num_shaders
[MESA_SHADER_TESS_CTRL
] == 0) {
4893 linker_error(prog
, "GLSL ES requires non-separable programs "
4894 "containing a tessellation evaluation shader to also "
4895 "be linked with a tessellation control shader\n");
4901 /* Compute shaders have additional restrictions. */
4902 if (num_shaders
[MESA_SHADER_COMPUTE
] > 0 &&
4903 num_shaders
[MESA_SHADER_COMPUTE
] != prog
->NumShaders
) {
4904 linker_error(prog
, "Compute shaders may not be linked with any other "
4905 "type of shader\n");
4908 /* Link all shaders for a particular stage and validate the result.
4910 for (int stage
= 0; stage
< MESA_SHADER_STAGES
; stage
++) {
4911 if (num_shaders
[stage
] > 0) {
4912 gl_linked_shader
*const sh
=
4913 link_intrastage_shaders(mem_ctx
, ctx
, prog
, shader_list
[stage
],
4914 num_shaders
[stage
], false);
4916 if (!prog
->data
->LinkStatus
) {
4918 _mesa_delete_linked_shader(ctx
, sh
);
4923 case MESA_SHADER_VERTEX
:
4924 validate_vertex_shader_executable(prog
, sh
, ctx
);
4926 case MESA_SHADER_TESS_CTRL
:
4927 /* nothing to be done */
4929 case MESA_SHADER_TESS_EVAL
:
4930 validate_tess_eval_shader_executable(prog
, sh
, ctx
);
4932 case MESA_SHADER_GEOMETRY
:
4933 validate_geometry_shader_executable(prog
, sh
, ctx
);
4935 case MESA_SHADER_FRAGMENT
:
4936 validate_fragment_shader_executable(prog
, sh
);
4939 if (!prog
->data
->LinkStatus
) {
4941 _mesa_delete_linked_shader(ctx
, sh
);
4945 prog
->_LinkedShaders
[stage
] = sh
;
4946 prog
->data
->linked_stages
|= 1 << stage
;
4950 /* Here begins the inter-stage linking phase. Some initial validation is
4951 * performed, then locations are assigned for uniforms, attributes, and
4954 cross_validate_uniforms(prog
);
4955 if (!prog
->data
->LinkStatus
)
4958 unsigned first
, last
, prev
;
4960 first
= MESA_SHADER_STAGES
;
4963 /* Determine first and last stage. */
4964 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
4965 if (!prog
->_LinkedShaders
[i
])
4967 if (first
== MESA_SHADER_STAGES
)
4972 check_explicit_uniform_locations(ctx
, prog
);
4973 link_assign_subroutine_types(prog
);
4975 if (!prog
->data
->LinkStatus
)
4978 resize_tes_inputs(ctx
, prog
);
4980 /* Validate the inputs of each stage with the output of the preceding
4984 for (unsigned i
= prev
+ 1; i
<= MESA_SHADER_FRAGMENT
; i
++) {
4985 if (prog
->_LinkedShaders
[i
] == NULL
)
4988 validate_interstage_inout_blocks(prog
, prog
->_LinkedShaders
[prev
],
4989 prog
->_LinkedShaders
[i
]);
4990 if (!prog
->data
->LinkStatus
)
4993 cross_validate_outputs_to_inputs(ctx
, prog
,
4994 prog
->_LinkedShaders
[prev
],
4995 prog
->_LinkedShaders
[i
]);
4996 if (!prog
->data
->LinkStatus
)
5002 /* The cross validation of outputs/inputs above validates explicit locations
5003 * but for SSO programs we need to do this also for the inputs in the
5004 * first stage and outputs of the last stage included in the program, since
5005 * there is no cross validation for these.
5007 if (prog
->SeparateShader
)
5008 validate_sso_explicit_locations(ctx
, prog
,
5009 (gl_shader_stage
) first
,
5010 (gl_shader_stage
) last
);
5012 /* Cross-validate uniform blocks between shader stages */
5013 validate_interstage_uniform_blocks(prog
, prog
->_LinkedShaders
);
5014 if (!prog
->data
->LinkStatus
)
5017 for (unsigned int i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5018 if (prog
->_LinkedShaders
[i
] != NULL
)
5019 lower_named_interface_blocks(mem_ctx
, prog
->_LinkedShaders
[i
]);
5022 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
5023 * it before optimization because we want most of the checks to get
5024 * dropped thanks to constant propagation.
5026 * This rule also applies to GLSL ES 3.00.
5028 if (max_version
>= (prog
->IsES
? 300 : 130)) {
5029 struct gl_linked_shader
*sh
= prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
];
5031 lower_discard_flow(sh
->ir
);
5035 if (prog
->SeparateShader
)
5036 disable_varying_optimizations_for_sso(prog
);
5039 if (!interstage_cross_validate_uniform_blocks(prog
, false))
5043 if (!interstage_cross_validate_uniform_blocks(prog
, true))
5046 /* Do common optimization before assigning storage for attributes,
5047 * uniforms, and varyings. Later optimization could possibly make
5048 * some of that unused.
5050 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5051 if (prog
->_LinkedShaders
[i
] == NULL
)
5054 detect_recursion_linked(prog
, prog
->_LinkedShaders
[i
]->ir
);
5055 if (!prog
->data
->LinkStatus
)
5058 if (ctx
->Const
.ShaderCompilerOptions
[i
].LowerCombinedClipCullDistance
) {
5059 lower_clip_cull_distance(prog
, prog
->_LinkedShaders
[i
]);
5062 if (ctx
->Const
.LowerTessLevel
) {
5063 lower_tess_level(prog
->_LinkedShaders
[i
]);
5066 /* Call opts before lowering const arrays to uniforms so we can const
5067 * propagate any elements accessed directly.
5069 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
5071 /* Call opts after lowering const arrays to copy propagate things. */
5072 if (lower_const_arrays_to_uniforms(prog
->_LinkedShaders
[i
]->ir
, i
))
5073 linker_optimisation_loop(ctx
, prog
->_LinkedShaders
[i
]->ir
, i
);
5075 propagate_invariance(prog
->_LinkedShaders
[i
]->ir
);
5078 /* Validation for special cases where we allow sampler array indexing
5079 * with loop induction variable. This check emits a warning or error
5080 * depending if backend can handle dynamic indexing.
5082 if ((!prog
->IsES
&& prog
->data
->Version
< 130) ||
5083 (prog
->IsES
&& prog
->data
->Version
< 300)) {
5084 if (!validate_sampler_array_indexing(ctx
, prog
))
5088 /* Check and validate stream emissions in geometry shaders */
5089 validate_geometry_shader_emissions(ctx
, prog
);
5091 store_fragdepth_layout(prog
);
5093 if(!link_varyings_and_uniforms(first
, last
, ctx
, prog
, mem_ctx
))
5096 /* Linking varyings can cause some extra, useless swizzles to be generated
5097 * due to packing and unpacking.
5099 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5100 if (prog
->_LinkedShaders
[i
] == NULL
)
5103 optimize_swizzles(prog
->_LinkedShaders
[i
]->ir
);
5106 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
5107 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
5108 * anything about shader linking when one of the shaders (vertex or
5109 * fragment shader) is absent. So, the extension shouldn't change the
5110 * behavior specified in GLSL specification.
5112 * From OpenGL ES 3.1 specification (7.3 Program Objects):
5113 * "Linking can fail for a variety of reasons as specified in the
5114 * OpenGL ES Shading Language Specification, as well as any of the
5115 * following reasons:
5119 * * program contains objects to form either a vertex shader or
5120 * fragment shader, and program is not separable, and does not
5121 * contain objects to form both a vertex shader and fragment
5124 * However, the only scenario in 3.1+ where we don't require them both is
5125 * when we have a compute shader. For example:
5127 * - No shaders is a link error.
5128 * - Geom or Tess without a Vertex shader is a link error which means we
5129 * always require a Vertex shader and hence a Fragment shader.
5130 * - Finally a Compute shader linked with any other stage is a link error.
5132 if (!prog
->SeparateShader
&& ctx
->API
== API_OPENGLES2
&&
5133 num_shaders
[MESA_SHADER_COMPUTE
] == 0) {
5134 if (prog
->_LinkedShaders
[MESA_SHADER_VERTEX
] == NULL
) {
5135 linker_error(prog
, "program lacks a vertex shader\n");
5136 } else if (prog
->_LinkedShaders
[MESA_SHADER_FRAGMENT
] == NULL
) {
5137 linker_error(prog
, "program lacks a fragment shader\n");
5142 for (unsigned i
= 0; i
< MESA_SHADER_STAGES
; i
++) {
5143 free(shader_list
[i
]);
5144 if (prog
->_LinkedShaders
[i
] == NULL
)
5147 /* Do a final validation step to make sure that the IR wasn't
5148 * invalidated by any modifications performed after intrastage linking.
5150 validate_ir_tree(prog
->_LinkedShaders
[i
]->ir
);
5152 /* Retain any live IR, but trash the rest. */
5153 reparent_ir(prog
->_LinkedShaders
[i
]->ir
, prog
->_LinkedShaders
[i
]->ir
);
5155 /* The symbol table in the linked shaders may contain references to
5156 * variables that were removed (e.g., unused uniforms). Since it may
5157 * contain junk, there is no possible valid use. Delete it and set the
5160 delete prog
->_LinkedShaders
[i
]->symbols
;
5161 prog
->_LinkedShaders
[i
]->symbols
= NULL
;
5164 ralloc_free(mem_ctx
);