e4bf634abe881986c8fdd83e74a952bf99ae6be3
[mesa.git] / src / compiler / glsl / linker.cpp
1 /*
2 * Copyright © 2010 Intel Corporation
3 *
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:
10 *
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
13 * Software.
14 *
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.
22 */
23
24 /**
25 * \file linker.cpp
26 * GLSL linker implementation
27 *
28 * Given a set of shaders that are to be linked to generate a final program,
29 * there are three distinct stages.
30 *
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
33 * together.
34 *
35 * - Undefined references in each shader are resolve to definitions in
36 * another shader.
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.
41 *
42 * The result, in the terminology of the GLSL spec, is a set of shader
43 * executables for each processing unit.
44 *
45 * After the first stage is complete, a series of semantic checks are performed
46 * on each of the shader executables.
47 *
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
51 * \c gl_FragColor.
52 *
53 * In the final stage individual shader executables are linked to create a
54 * complete exectuable.
55 *
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.
63 *
64 * \author Ian Romanick <ian.d.romanick@intel.com>
65 */
66
67 #include <ctype.h>
68 #include "util/strndup.h"
69 #include "glsl_symbol_table.h"
70 #include "glsl_parser_extras.h"
71 #include "ir.h"
72 #include "program.h"
73 #include "program/prog_instruction.h"
74 #include "program/program.h"
75 #include "util/mesa-sha1.h"
76 #include "util/set.h"
77 #include "string_to_uint_map.h"
78 #include "linker.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"
85
86 #include "main/imports.h"
87 #include "main/shaderobj.h"
88 #include "main/enums.h"
89 #include "main/mtypes.h"
90
91
92 namespace {
93
94 struct find_variable {
95 const char *name;
96 bool found;
97
98 find_variable(const char *name) : name(name), found(false) {}
99 };
100
101 /**
102 * Visitor that determines whether or not a variable is ever written.
103 *
104 * Use \ref find_assignments for convenience.
105 */
106 class find_assignment_visitor : public ir_hierarchical_visitor {
107 public:
108 find_assignment_visitor(unsigned num_vars,
109 find_variable * const *vars)
110 : num_variables(num_vars), num_found(0), variables(vars)
111 {
112 }
113
114 virtual ir_visitor_status visit_enter(ir_assignment *ir)
115 {
116 ir_variable *const var = ir->lhs->variable_referenced();
117
118 return check_variable_name(var->name);
119 }
120
121 virtual ir_visitor_status visit_enter(ir_call *ir)
122 {
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;
127
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)
132 return visit_stop;
133 }
134 }
135
136 if (ir->return_deref != NULL) {
137 ir_variable *const var = ir->return_deref->variable_referenced();
138
139 if (check_variable_name(var->name) == visit_stop)
140 return visit_stop;
141 }
142
143 return visit_continue_with_parent;
144 }
145
146 private:
147 ir_visitor_status check_variable_name(const char *name)
148 {
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;
153
154 assert(num_found < num_variables);
155 if (++num_found == num_variables)
156 return visit_stop;
157 }
158 break;
159 }
160 }
161
162 return visit_continue_with_parent;
163 }
164
165 private:
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 */
169 };
170
171 /**
172 * Determine whether or not any of NULL-terminated list of variables is ever
173 * written to.
174 */
175 static void
176 find_assignments(exec_list *ir, find_variable * const *vars)
177 {
178 unsigned num_variables = 0;
179
180 for (find_variable * const *v = vars; *v; ++v)
181 num_variables++;
182
183 find_assignment_visitor visitor(num_variables, vars);
184 visitor.run(ir);
185 }
186
187 /**
188 * Determine whether or not the given variable is ever written to.
189 */
190 static void
191 find_assignments(exec_list *ir, find_variable *var)
192 {
193 find_assignment_visitor visitor(1, &var);
194 visitor.run(ir);
195 }
196
197 /**
198 * Visitor that determines whether or not a variable is ever read.
199 */
200 class find_deref_visitor : public ir_hierarchical_visitor {
201 public:
202 find_deref_visitor(const char *name)
203 : name(name), found(false)
204 {
205 /* empty */
206 }
207
208 virtual ir_visitor_status visit(ir_dereference_variable *ir)
209 {
210 if (strcmp(this->name, ir->var->name) == 0) {
211 this->found = true;
212 return visit_stop;
213 }
214
215 return visit_continue;
216 }
217
218 bool variable_found() const
219 {
220 return this->found;
221 }
222
223 private:
224 const char *name; /**< Find writes to a variable with this name. */
225 bool found; /**< Was a write to the variable found? */
226 };
227
228
229 /**
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.
233 */
234 class deref_type_updater : public ir_hierarchical_visitor {
235 public:
236 virtual ir_visitor_status visit(ir_dereference_variable *ir)
237 {
238 ir->type = ir->var->type;
239 return visit_continue;
240 }
241
242 virtual ir_visitor_status visit_leave(ir_dereference_array *ir)
243 {
244 const glsl_type *const vt = ir->array->type;
245 if (vt->is_array())
246 ir->type = vt->fields.array;
247 return visit_continue;
248 }
249
250 virtual ir_visitor_status visit_leave(ir_dereference_record *ir)
251 {
252 ir->type = ir->record->type->fields.structure[ir->field_idx].type;
253 return visit_continue;
254 }
255 };
256
257
258 class array_resize_visitor : public deref_type_updater {
259 public:
260 unsigned num_vertices;
261 gl_shader_program *prog;
262 gl_shader_stage stage;
263
264 array_resize_visitor(unsigned num_vertices,
265 gl_shader_program *prog,
266 gl_shader_stage stage)
267 {
268 this->num_vertices = num_vertices;
269 this->prog = prog;
270 this->stage = stage;
271 }
272
273 virtual ~array_resize_visitor()
274 {
275 /* empty */
276 }
277
278 virtual ir_visitor_status visit(ir_variable *var)
279 {
280 if (!var->type->is_array() || var->data.mode != ir_var_shader_in ||
281 var->data.patch)
282 return visit_continue;
283
284 unsigned size = var->type->length;
285
286 if (stage == MESA_SHADER_GEOMETRY) {
287 /* Generate a link error if the shader has declared this array with
288 * an incorrect size.
289 */
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;
296 }
297
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
300 * link time.
301 */
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;
308 }
309 }
310
311 var->type = glsl_type::get_array_instance(var->type->fields.array,
312 this->num_vertices);
313 var->data.max_array_access = this->num_vertices - 1;
314
315 return visit_continue;
316 }
317 };
318
319 /**
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.
322 */
323 class find_emit_vertex_visitor : public ir_hierarchical_visitor {
324 public:
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)
331 {
332 /* empty */
333 }
334
335 virtual ir_visitor_status visit_leave(ir_emit_vertex *ir)
336 {
337 int stream_id = ir->stream_id();
338
339 if (stream_id < 0) {
340 invalid_stream_id = stream_id;
341 invalid_stream_id_from_emit_vertex = true;
342 return visit_stop;
343 }
344
345 if (stream_id > max_stream_allowed) {
346 invalid_stream_id = stream_id;
347 invalid_stream_id_from_emit_vertex = true;
348 return visit_stop;
349 }
350
351 if (stream_id != 0)
352 uses_non_zero_stream = true;
353
354 return visit_continue;
355 }
356
357 virtual ir_visitor_status visit_leave(ir_end_primitive *ir)
358 {
359 end_primitive_found = true;
360
361 int stream_id = ir->stream_id();
362
363 if (stream_id < 0) {
364 invalid_stream_id = stream_id;
365 invalid_stream_id_from_emit_vertex = false;
366 return visit_stop;
367 }
368
369 if (stream_id > max_stream_allowed) {
370 invalid_stream_id = stream_id;
371 invalid_stream_id_from_emit_vertex = false;
372 return visit_stop;
373 }
374
375 if (stream_id != 0)
376 uses_non_zero_stream = true;
377
378 return visit_continue;
379 }
380
381 bool error()
382 {
383 return invalid_stream_id != 0;
384 }
385
386 const char *error_func()
387 {
388 return invalid_stream_id_from_emit_vertex ?
389 "EmitStreamVertex" : "EndStreamPrimitive";
390 }
391
392 int error_stream()
393 {
394 return invalid_stream_id;
395 }
396
397 bool uses_streams()
398 {
399 return uses_non_zero_stream;
400 }
401
402 bool uses_end_primitive()
403 {
404 return end_primitive_found;
405 }
406
407 private:
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;
413 };
414
415 /* Class that finds array derefs and check if indexes are dynamic. */
416 class dynamic_sampler_array_indexing_visitor : public ir_hierarchical_visitor
417 {
418 public:
419 dynamic_sampler_array_indexing_visitor() :
420 dynamic_sampler_array_indexing(false)
421 {
422 }
423
424 ir_visitor_status visit_enter(ir_dereference_array *ir)
425 {
426 if (!ir->variable_referenced())
427 return visit_continue;
428
429 if (!ir->variable_referenced()->type->contains_sampler())
430 return visit_continue;
431
432 if (!ir->array_index->constant_expression_value(ralloc_parent(ir))) {
433 dynamic_sampler_array_indexing = true;
434 return visit_stop;
435 }
436 return visit_continue;
437 }
438
439 bool uses_dynamic_sampler_array_indexing()
440 {
441 return dynamic_sampler_array_indexing;
442 }
443
444 private:
445 bool dynamic_sampler_array_indexing;
446 };
447
448 } /* anonymous namespace */
449
450 void
451 linker_error(gl_shader_program *prog, const char *fmt, ...)
452 {
453 va_list ap;
454
455 ralloc_strcat(&prog->data->InfoLog, "error: ");
456 va_start(ap, fmt);
457 ralloc_vasprintf_append(&prog->data->InfoLog, fmt, ap);
458 va_end(ap);
459
460 prog->data->LinkStatus = LINKING_FAILURE;
461 }
462
463
464 void
465 linker_warning(gl_shader_program *prog, const char *fmt, ...)
466 {
467 va_list ap;
468
469 ralloc_strcat(&prog->data->InfoLog, "warning: ");
470 va_start(ap, fmt);
471 ralloc_vasprintf_append(&prog->data->InfoLog, fmt, ap);
472 va_end(ap);
473
474 }
475
476
477 /**
478 * Given a string identifying a program resource, break it into a base name
479 * and an optional array index in square brackets.
480 *
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
483 * as a long.
484 *
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.
488 *
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.
491 *
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.
495 */
496 long
497 parse_program_resource_name(const GLchar *name,
498 const GLchar **out_base_name_end)
499 {
500 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
501 *
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."
506 */
507
508 const size_t len = strlen(name);
509 *out_base_name_end = name + len;
510
511 if (len == 0 || name[len-1] != ']')
512 return -1;
513
514 /* Walk backwards over the string looking for a non-digit character. This
515 * had better be the opening bracket for an array index.
516 *
517 * Initially, i specifies the location of the ']'. Since the string may
518 * contain only the ']' charcater, walk backwards very carefully.
519 */
520 unsigned i;
521 for (i = len - 1; (i > 0) && isdigit(name[i-1]); --i)
522 /* empty */ ;
523
524 if ((i == 0) || name[i-1] != '[')
525 return -1;
526
527 long array_index = strtol(&name[i], NULL, 10);
528 if (array_index < 0)
529 return -1;
530
531 /* Check for leading zero */
532 if (name[i] == '0' && name[i+1] != ']')
533 return -1;
534
535 *out_base_name_end = name + (i - 1);
536 return array_index;
537 }
538
539
540 void
541 link_invalidate_variable_locations(exec_list *ir)
542 {
543 foreach_in_list(ir_instruction, node, ir) {
544 ir_variable *const var = node->as_variable();
545
546 if (var == NULL)
547 continue;
548
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=...)).
553 */
554 if (!var->data.explicit_location) {
555 var->data.location = -1;
556 var->data.location_frac = 0;
557 }
558
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.
561 */
562 if (var->data.explicit_location &&
563 var->data.location < VARYING_SLOT_VAR0) {
564 var->data.is_unmatched_generic_inout = 0;
565 } else {
566 var->data.is_unmatched_generic_inout = 1;
567 }
568 }
569 }
570
571
572 /**
573 * Set clip_distance_array_size based and cull_distance_array_size on the given
574 * shader.
575 *
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.
580 *
581 * Return false if an error was reported.
582 */
583 static void
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)
589 {
590 *clip_distance_array_size = 0;
591 *cull_distance_array_size = 0;
592
593 if (prog->data->Version >= (prog->IsES ? 300 : 130)) {
594 /* From section 7.1 (Vertex Shader Special Variables) of the
595 * GLSL 1.30 spec:
596 *
597 * "It is an error for a shader to statically write both
598 * gl_ClipVertex and gl_ClipDistance."
599 *
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.
603 */
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[] = {
608 &gl_ClipDistance,
609 &gl_CullDistance,
610 !prog->IsES ? &gl_ClipVertex : NULL,
611 NULL
612 };
613 find_assignments(shader->ir, variables);
614
615 /* From the ARB_cull_distance spec:
616 *
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.
620 *
621 * This does not apply to GLSL ES shaders, since GLSL ES doesn't define
622 * gl_ClipVertex.
623 */
624 if (!prog->IsES) {
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));
629 return;
630 }
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));
635 return;
636 }
637 }
638
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;
644 }
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;
650 }
651 /* From the ARB_cull_distance spec:
652 *
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.
657 */
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 "
662 "be larger than "
663 "gl_MaxCombinedClipAndCullDistances (%u)",
664 _mesa_shader_stage_to_string(shader->Stage),
665 ctx->Const.MaxClipPlanes);
666 }
667 }
668 }
669
670
671 /**
672 * Verify that a vertex shader executable meets all semantic requirements.
673 *
674 * Also sets info.clip_distance_array_size and
675 * info.cull_distance_array_size as a side effect.
676 *
677 * \param shader Vertex shader executable to be verified
678 */
679 static void
680 validate_vertex_shader_executable(struct gl_shader_program *prog,
681 struct gl_linked_shader *shader,
682 struct gl_context *ctx)
683 {
684 if (shader == NULL)
685 return;
686
687 /* From the GLSL 1.10 spec, page 48:
688 *
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."
697 *
698 * while in GLSL 1.40 this text is changed to:
699 *
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."
709 *
710 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
711 * gl_Position is not an error.
712 */
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) {
717 if (prog->IsES) {
718 linker_warning(prog,
719 "vertex shader does not write to `gl_Position'. "
720 "Its value is undefined. \n");
721 } else {
722 linker_error(prog,
723 "vertex shader does not write to `gl_Position'. \n");
724 }
725 return;
726 }
727 }
728
729 analyze_clip_cull_usage(prog, shader, ctx,
730 &shader->Program->info.clip_distance_array_size,
731 &shader->Program->info.cull_distance_array_size);
732 }
733
734 static void
735 validate_tess_eval_shader_executable(struct gl_shader_program *prog,
736 struct gl_linked_shader *shader,
737 struct gl_context *ctx)
738 {
739 if (shader == NULL)
740 return;
741
742 analyze_clip_cull_usage(prog, shader, ctx,
743 &shader->Program->info.clip_distance_array_size,
744 &shader->Program->info.cull_distance_array_size);
745 }
746
747
748 /**
749 * Verify that a fragment shader executable meets all semantic requirements
750 *
751 * \param shader Fragment shader executable to be verified
752 */
753 static void
754 validate_fragment_shader_executable(struct gl_shader_program *prog,
755 struct gl_linked_shader *shader)
756 {
757 if (shader == NULL)
758 return;
759
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);
764
765 if (gl_FragColor.found && gl_FragData.found) {
766 linker_error(prog, "fragment shader writes to both "
767 "`gl_FragColor' and `gl_FragData'\n");
768 }
769 }
770
771 /**
772 * Verify that a geometry shader executable meets all semantic requirements
773 *
774 * Also sets prog->Geom.VerticesIn, and info.clip_distance_array_sizeand
775 * info.cull_distance_array_size as a side effect.
776 *
777 * \param shader Geometry shader executable to be verified
778 */
779 static void
780 validate_geometry_shader_executable(struct gl_shader_program *prog,
781 struct gl_linked_shader *shader,
782 struct gl_context *ctx)
783 {
784 if (shader == NULL)
785 return;
786
787 unsigned num_vertices =
788 vertices_per_prim(shader->Program->info.gs.input_primitive);
789 prog->Geom.VerticesIn = num_vertices;
790
791 analyze_clip_cull_usage(prog, shader, ctx,
792 &shader->Program->info.clip_distance_array_size,
793 &shader->Program->info.cull_distance_array_size);
794 }
795
796 /**
797 * Check if geometry shaders emit to non-zero streams and do corresponding
798 * validations.
799 */
800 static void
801 validate_geometry_shader_emissions(struct gl_context *ctx,
802 struct gl_shader_program *prog)
803 {
804 struct gl_linked_shader *sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
805
806 if (sh != NULL) {
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);
815 }
816 prog->Geom.UsesStreams = emit_vertex.uses_streams();
817 prog->Geom.UsesEndPrimitive = emit_vertex.uses_end_primitive();
818
819 /* From the ARB_gpu_shader5 spec:
820 *
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".
825 *
826 * However, in the same spec:
827 *
828 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
829 * with <stream> set to zero."
830 *
831 * And:
832 *
833 * "The function EndPrimitive() is equivalent to calling
834 * EndStreamPrimitive() with <stream> set to zero."
835 *
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
841 * stream.
842 */
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");
847 }
848 }
849 }
850
851 bool
852 validate_intrastage_arrays(struct gl_shader_program *prog,
853 ir_variable *const var,
854 ir_variable *const existing)
855 {
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.
860 */
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"
868 " of `%i'\n",
869 mode_string(var),
870 var->name, var->type->name,
871 existing->data.max_array_access);
872 }
873 existing->type = var->type;
874 return true;
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"
880 " of `%i'\n",
881 mode_string(var),
882 var->name, existing->type->name,
883 var->data.max_array_access);
884 }
885 return true;
886 }
887 }
888 }
889 return false;
890 }
891
892
893 /**
894 * Perform validation of global variables used across multiple shaders
895 */
896 static void
897 cross_validate_globals(struct gl_shader_program *prog,
898 struct exec_list *ir, glsl_symbol_table *variables,
899 bool uniforms_only)
900 {
901 foreach_in_list(ir_instruction, node, ir) {
902 ir_variable *const var = node->as_variable();
903
904 if (var == NULL)
905 continue;
906
907 if (uniforms_only && (var->data.mode != ir_var_uniform && var->data.mode != ir_var_shader_storage))
908 continue;
909
910 /* don't cross validate subroutine uniforms */
911 if (var->type->contains_subroutine())
912 continue;
913
914 /* Don't cross validate interface instances. These are only relevant
915 * inside a shader. The cross validation is done at the Interface Block
916 * name level.
917 */
918 if (var->is_interface_instance())
919 continue;
920
921 /* Don't cross validate temporaries that are at global scope. These
922 * will eventually get pulled into the shaders 'main'.
923 */
924 if (var->data.mode == ir_var_temporary)
925 continue;
926
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.
930 */
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.
941 */
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",
949 mode_string(var),
950 var->name, var->type->name,
951 existing->type->name);
952 return;
953 }
954 }
955 }
956
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);
963 return;
964 }
965
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);
969 return;
970 }
971
972 existing->data.location = var->data.location;
973 existing->data.explicit_location = true;
974 } else {
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
978 * implicit one.
979 */
980 if (existing->data.explicit_location) {
981 var->data.location = existing->data.location;
982 var->data.explicit_location = true;
983 }
984 }
985
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"
991 */
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);
998 return;
999 }
1000
1001 existing->data.binding = var->data.binding;
1002 existing->data.explicit_binding = true;
1003 }
1004
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);
1010 return;
1011 }
1012
1013 /* Validate layout qualifiers for gl_FragDepth.
1014 *
1015 * From the AMD/ARB_conservative_depth specs:
1016 *
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
1022 * of qualifiers."
1023 */
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;
1028
1029 if (layout_declared && layout_differs) {
1030 linker_error(prog,
1031 "All redeclarations of gl_FragDepth in all "
1032 "fragment shaders in a single program must have "
1033 "the same set of qualifiers.\n");
1034 }
1035
1036 if (var->data.used && layout_differs) {
1037 linker_error(prog,
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 "
1042 "gl_FragDepth\n");
1043 }
1044 }
1045
1046 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1047 *
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.)"
1053 *
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.
1060 */
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);
1067 return;
1068 }
1069 } else {
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.
1073 */
1074 variables->replace_variable(existing->name, var);
1075 }
1076 }
1077
1078 if (var->data.has_initializer) {
1079 if (existing->data.has_initializer
1080 && (var->constant_initializer == NULL
1081 || existing->constant_initializer == NULL)) {
1082 linker_error(prog,
1083 "shared global variable `%s' has multiple "
1084 "non-constant initializers.\n",
1085 var->name);
1086 return;
1087 }
1088 }
1089
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);
1094 return;
1095 }
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);
1100 return;
1101 }
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);
1106 return;
1107 }
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);
1112 return;
1113 }
1114
1115 /* Check the precision qualifier matches for uniform variables on
1116 * GLSL ES.
1117 */
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);
1124 return;
1125 } else {
1126 linker_warning(prog, "declarations for %s `%s` have "
1127 "mismatching precision qualifiers\n",
1128 mode_string(var), var->name);
1129 }
1130 }
1131
1132 /* In OpenGL GLSL 3.20 spec, section 4.3.9:
1133 *
1134 * "It is a link-time error if any particular shader interface
1135 * contains:
1136 *
1137 * - two different blocks, each having no instance name, and each
1138 * having a member of the same name, or
1139 *
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."
1142 */
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);
1151 return;
1152 } else if (strcmp(var_itype->name, existing_itype->name) != 0) {
1153 linker_error(prog, "declarations for %s `%s` are inside blocks "
1154 "`%s` and `%s`",
1155 mode_string(var), var->name,
1156 existing_itype->name,
1157 var_itype->name);
1158 return;
1159 }
1160 }
1161 } else
1162 variables->add_variable(var);
1163 }
1164 }
1165
1166
1167 /**
1168 * Perform validation of uniforms used across multiple shader stages
1169 */
1170 static void
1171 cross_validate_uniforms(struct gl_shader_program *prog)
1172 {
1173 glsl_symbol_table variables;
1174 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1175 if (prog->_LinkedShaders[i] == NULL)
1176 continue;
1177
1178 cross_validate_globals(prog, prog->_LinkedShaders[i]->ir, &variables,
1179 true);
1180 }
1181 }
1182
1183 /**
1184 * Accumulates the array of buffer blocks and checks that all definitions of
1185 * blocks agree on their contents.
1186 */
1187 static bool
1188 interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog,
1189 bool validate_ssbo)
1190 {
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;
1195
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;
1202 } else {
1203 max_num_buffer_blocks +=
1204 prog->_LinkedShaders[i]->Program->info.num_ubos;
1205 }
1206 }
1207 }
1208
1209 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1210 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
1211
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;
1215
1216 if (sh == NULL)
1217 continue;
1218
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;
1224 } else {
1225 sh_num_blocks = prog->_LinkedShaders[i]->Program->info.num_ubos;
1226 sh_blks = sh->Program->sh.UniformBlocks;
1227 }
1228
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]);
1232
1233 if (index == -1) {
1234 linker_error(prog, "buffer block `%s' has mismatching "
1235 "definitions\n", sh_blks[j]->Name);
1236
1237 for (unsigned k = 0; k <= i; k++) {
1238 delete[] InterfaceBlockStageIndex[k];
1239 }
1240
1241 /* Reset the block count. This will help avoid various segfaults
1242 * from api calls that assume the array exists due to the count
1243 * being non-zero.
1244 */
1245 *num_blks = 0;
1246 return false;
1247 }
1248
1249 InterfaceBlockStageIndex[i][index] = j;
1250 }
1251 }
1252
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.
1255 */
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];
1259
1260 if (stage_index != -1) {
1261 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
1262
1263 struct gl_uniform_block **sh_blks = validate_ssbo ?
1264 sh->Program->sh.ShaderStorageBlocks :
1265 sh->Program->sh.UniformBlocks;
1266
1267 blks[j].stageref |= sh_blks[stage_index]->stageref;
1268 sh_blks[stage_index] = &blks[j];
1269 }
1270 }
1271 }
1272
1273 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1274 delete[] InterfaceBlockStageIndex[i];
1275 }
1276
1277 if (validate_ssbo)
1278 prog->data->ShaderStorageBlocks = blks;
1279 else
1280 prog->data->UniformBlocks = blks;
1281
1282 return true;
1283 }
1284
1285
1286 /**
1287 * Populates a shaders symbol table with all global declarations
1288 */
1289 static void
1290 populate_symbol_table(gl_linked_shader *sh, glsl_symbol_table *symbols)
1291 {
1292 sh->symbols = new(sh) glsl_symbol_table;
1293
1294 _mesa_glsl_copy_symbols_from_table(sh->ir, symbols, sh->symbols);
1295 }
1296
1297
1298 /**
1299 * Remap variables referenced in an instruction tree
1300 *
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
1305 * shader.
1306 *
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.
1310 *
1311 * \param inst IR tree that is to be processed.
1312 * \param symbols Symbol table containing global scope symbols in the
1313 * linked shader.
1314 * \param instructions Instruction stream where new variable declarations
1315 * should be added.
1316 */
1317 static void
1318 remap_variables(ir_instruction *inst, struct gl_linked_shader *target,
1319 hash_table *temps)
1320 {
1321 class remap_visitor : public ir_hierarchical_visitor {
1322 public:
1323 remap_visitor(struct gl_linked_shader *target, hash_table *temps)
1324 {
1325 this->target = target;
1326 this->symbols = target->symbols;
1327 this->instructions = target->ir;
1328 this->temps = temps;
1329 }
1330
1331 virtual ir_visitor_status visit(ir_dereference_variable *ir)
1332 {
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;
1336
1337 assert(var != NULL);
1338 ir->var = var;
1339 return visit_continue;
1340 }
1341
1342 ir_variable *const existing =
1343 this->symbols->get_variable(ir->var->name);
1344 if (existing != NULL)
1345 ir->var = existing;
1346 else {
1347 ir_variable *copy = ir->var->clone(this->target, NULL);
1348
1349 this->symbols->add_variable(copy);
1350 this->instructions->push_head(copy);
1351 ir->var = copy;
1352 }
1353
1354 return visit_continue;
1355 }
1356
1357 private:
1358 struct gl_linked_shader *target;
1359 glsl_symbol_table *symbols;
1360 exec_list *instructions;
1361 hash_table *temps;
1362 };
1363
1364 remap_visitor v(target, temps);
1365
1366 inst->accept(&v);
1367 }
1368
1369
1370 /**
1371 * Move non-declarations from one instruction stream to another
1372 *
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.
1378 *
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.
1385 *
1386 * \return
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
1389 * function.
1390 */
1391 static exec_node *
1392 move_non_declarations(exec_list *instructions, exec_node *last,
1393 bool make_copies, gl_linked_shader *target)
1394 {
1395 hash_table *temps = NULL;
1396
1397 if (make_copies)
1398 temps = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
1399 _mesa_key_pointer_equal);
1400
1401 foreach_in_list_safe(ir_instruction, inst, instructions) {
1402 if (inst->as_function())
1403 continue;
1404
1405 ir_variable *var = inst->as_variable();
1406 if ((var != NULL) && (var->data.mode != ir_var_temporary))
1407 continue;
1408
1409 assert(inst->as_assignment()
1410 || inst->as_call()
1411 || inst->as_if() /* for initializers with the ?: operator */
1412 || ((var != NULL) && (var->data.mode == ir_var_temporary)));
1413
1414 if (make_copies) {
1415 inst = inst->clone(target, NULL);
1416
1417 if (var != NULL)
1418 _mesa_hash_table_insert(temps, var, inst);
1419 else
1420 remap_variables(inst, target, temps);
1421 } else {
1422 inst->remove();
1423 }
1424
1425 last->insert_after(inst);
1426 last = inst;
1427 }
1428
1429 if (make_copies)
1430 _mesa_hash_table_destroy(temps, NULL);
1431
1432 return last;
1433 }
1434
1435
1436 /**
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
1439 * gcc.
1440 */
1441 class array_sizing_visitor : public deref_type_updater {
1442 public:
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))
1447 {
1448 }
1449
1450 ~array_sizing_visitor()
1451 {
1452 _mesa_hash_table_destroy(this->unnamed_interfaces, NULL);
1453 ralloc_free(this->mem_ctx);
1454 }
1455
1456 virtual ir_visitor_status visit(ir_variable *var)
1457 {
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);
1473 }
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);
1482 }
1483 } else if (const glsl_type *ifc_type = var->get_interface_type()) {
1484 /* Store a pointer to the variable in the unnamed_interfaces
1485 * hashtable.
1486 */
1487 hash_entry *entry =
1488 _mesa_hash_table_search(this->unnamed_interfaces,
1489 ifc_type);
1490
1491 ir_variable **interface_vars = entry ? (ir_variable **) entry->data : NULL;
1492
1493 if (interface_vars == NULL) {
1494 interface_vars = rzalloc_array(mem_ctx, ir_variable *,
1495 ifc_type->length);
1496 _mesa_hash_table_insert(this->unnamed_interfaces, ifc_type,
1497 interface_vars);
1498 }
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;
1503 }
1504 return visit_continue;
1505 }
1506
1507 /**
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
1511 * type.
1512 */
1513 void fixup_unnamed_interface_types()
1514 {
1515 hash_table_call_foreach(this->unnamed_interfaces,
1516 fixup_unnamed_interface_type, NULL);
1517 }
1518
1519 private:
1520 /**
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.
1523 */
1524 static void fixup_type(const glsl_type **type, unsigned max_array_access,
1525 bool from_ssbo_unsized_array, bool *implicit_sized)
1526 {
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);
1532 }
1533 }
1534
1535 static const glsl_type *
1536 update_interface_members_array(const glsl_type *type,
1537 const glsl_type *new_interface_type)
1538 {
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);
1544 } else {
1545 return glsl_type::get_array_instance(new_interface_type,
1546 type->length);
1547 }
1548 }
1549
1550 /**
1551 * Determine whether the given interface type contains unsized arrays (if
1552 * it doesn't, array_sizing_visitor doesn't need to process it).
1553 */
1554 static bool interface_contains_unsized_arrays(const glsl_type *type)
1555 {
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())
1559 return true;
1560 }
1561 return false;
1562 }
1563
1564 /**
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.
1568 */
1569 static const glsl_type *
1570 resize_interface_members(const glsl_type *type,
1571 const int *max_ifc_array_access,
1572 bool is_ssbo)
1573 {
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
1581 * array.
1582 */
1583 if (is_ssbo && i == (num_fields - 1))
1584 fixup_type(&fields[i].type, max_ifc_array_access[i],
1585 true, &implicit_sized_array);
1586 else
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;
1590 }
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);
1597 delete [] fields;
1598 return new_ifc_type;
1599 }
1600
1601 static void fixup_unnamed_interface_type(const void *key, void *data,
1602 void *)
1603 {
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;
1616 }
1617 }
1618 if (!interface_type_changed) {
1619 delete [] fields;
1620 return;
1621 }
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);
1628 delete [] fields;
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);
1632 }
1633 }
1634
1635 /**
1636 * Memory context used to allocate the data in \c unnamed_interfaces.
1637 */
1638 void *mem_ctx;
1639
1640 /**
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.
1643 */
1644 hash_table *unnamed_interfaces;
1645 };
1646
1647 static bool
1648 validate_xfb_buffer_stride(struct gl_context *ctx, unsigned idx,
1649 struct gl_shader_program *prog)
1650 {
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]);
1657 return false;
1658 }
1659
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.");
1664 return false;
1665 }
1666
1667 return true;
1668 }
1669
1670 /**
1671 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1672 * for later use.
1673 */
1674 static void
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)
1679 {
1680 for (unsigned i = 0; i < MAX_FEEDBACK_BUFFERS; i++) {
1681 prog->TransformFeedback.BufferStride[i] = 0;
1682 }
1683
1684 for (unsigned i = 0; i < num_shaders; i++) {
1685 struct gl_shader *shader = shader_list[i];
1686
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))
1693 return;
1694 } else if (prog->TransformFeedback.BufferStride[j] !=
1695 shader->TransformFeedbackBufferStride[j]){
1696 linker_error(prog,
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]);
1701 return;
1702 }
1703 }
1704 }
1705 }
1706 }
1707
1708 /**
1709 * Check for conflicting bindless/bound sampler/image layout qualifiers at
1710 * global scope.
1711 */
1712 static void
1713 link_bindless_layout_qualifiers(struct gl_shader_program *prog,
1714 struct gl_shader **shader_list,
1715 unsigned num_shaders)
1716 {
1717 bool bindless_sampler, bindless_image;
1718 bool bound_sampler, bound_image;
1719
1720 bindless_sampler = bindless_image = false;
1721 bound_sampler = bound_image = false;
1722
1723 for (unsigned i = 0; i < num_shaders; i++) {
1724 struct gl_shader *shader = shader_list[i];
1725
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)
1733 bound_image = true;
1734
1735 if ((bindless_sampler && bound_sampler) ||
1736 (bindless_image && bound_image)) {
1737 /* From section 4.4.6 of the ARB_bindless_texture spec:
1738 *
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."
1742 */
1743 linker_error(prog, "both bindless_sampler and bound_sampler, or "
1744 "bindless_image and bound_image, can't be declared at "
1745 "global scope");
1746 }
1747 }
1748 }
1749
1750 /**
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.
1754 */
1755 static void
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)
1760 {
1761 if (gl_prog->info.stage != MESA_SHADER_TESS_CTRL)
1762 return;
1763
1764 gl_prog->info.tess.tcs_vertices_out = 0;
1765
1766 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1767 *
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
1773 * shaders."
1774 */
1775
1776 for (unsigned i = 0; i < num_shaders; i++) {
1777 struct gl_shader *shader = shader_list[i];
1778
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);
1787 return;
1788 }
1789 gl_prog->info.tess.tcs_vertices_out =
1790 shader->info.TessCtrl.VerticesOut;
1791 }
1792 }
1793
1794 /* Just do the intrastage -> interstage propagation right now,
1795 * since we already know we're in the right type of shader program
1796 * for doing it.
1797 */
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");
1801 return;
1802 }
1803 }
1804
1805
1806 /**
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.
1811 */
1812 static void
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)
1817 {
1818 if (gl_prog->info.stage != MESA_SHADER_TESS_EVAL)
1819 return;
1820
1821 int point_mode = -1;
1822 unsigned vertex_order = 0;
1823
1824 gl_prog->info.tess.primitive_mode = PRIM_UNKNOWN;
1825 gl_prog->info.tess.spacing = TESS_SPACING_UNSPECIFIED;
1826
1827 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1828 *
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."
1839 */
1840
1841 for (unsigned i = 0; i < num_shaders; i++) {
1842 struct gl_shader *shader = shader_list[i];
1843
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");
1850 return;
1851 }
1852 gl_prog->info.tess.primitive_mode =
1853 shader->info.TessEval.PrimitiveMode;
1854 }
1855
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");
1861 return;
1862 }
1863 gl_prog->info.tess.spacing = shader->info.TessEval.Spacing;
1864 }
1865
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");
1871 return;
1872 }
1873 vertex_order = shader->info.TessEval.VertexOrder;
1874 }
1875
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");
1881 return;
1882 }
1883 point_mode = shader->info.TessEval.PointMode;
1884 }
1885
1886 }
1887
1888 /* Just do the intrastage -> interstage propagation right now,
1889 * since we already know we're in the right type of shader program
1890 * for doing it.
1891 */
1892 if (gl_prog->info.tess.primitive_mode == PRIM_UNKNOWN) {
1893 linker_error(prog,
1894 "tessellation evaluation shader didn't declare input "
1895 "primitive modes.\n");
1896 return;
1897 }
1898
1899 if (gl_prog->info.tess.spacing == TESS_SPACING_UNSPECIFIED)
1900 gl_prog->info.tess.spacing = TESS_SPACING_EQUAL;
1901
1902 if (vertex_order == 0 || vertex_order == GL_CCW)
1903 gl_prog->info.tess.ccw = true;
1904 else
1905 gl_prog->info.tess.ccw = false;
1906
1907
1908 if (point_mode == -1 || point_mode == GL_FALSE)
1909 gl_prog->info.tess.point_mode = false;
1910 else
1911 gl_prog->info.tess.point_mode = true;
1912 }
1913
1914
1915 /**
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.
1919 */
1920 static void
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)
1925 {
1926 bool redeclares_gl_fragcoord = false;
1927 bool uses_gl_fragcoord = false;
1928 bool origin_upper_left = false;
1929 bool pixel_center_integer = false;
1930
1931 if (linked_shader->Stage != MESA_SHADER_FRAGMENT ||
1932 (prog->data->Version < 150 &&
1933 !prog->ARB_fragment_coord_conventions_enable))
1934 return;
1935
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:
1939 *
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."
1943 */
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");
1950 }
1951
1952 /* From the GLSL 1.50 spec, page 39:
1953 *
1954 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1955 * single program must have the same set of qualifiers."
1956 */
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");
1962 }
1963
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.
1968 */
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;
1974 }
1975
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;
1989
1990 linked_shader->Program->sh.fs.BlendSupport |= shader->BlendSupport;
1991 }
1992 }
1993
1994 /**
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.
1998 */
1999 static void
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)
2004 {
2005 /* No in/out qualifiers defined for anything but GLSL 1.50+
2006 * geometry shaders so far.
2007 */
2008 if (gl_prog->info.stage != MESA_SHADER_GEOMETRY ||
2009 prog->data->Version < 150)
2010 return;
2011
2012 int vertices_out = -1;
2013
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;
2017
2018 /* From the GLSL 1.50 spec, page 46:
2019 *
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
2025 * declare it."
2026 */
2027
2028 for (unsigned i = 0; i < num_shaders; i++) {
2029 struct gl_shader *shader = shader_list[i];
2030
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 "
2036 "input types\n");
2037 return;
2038 }
2039 gl_prog->info.gs.input_primitive = shader->info.Geom.InputType;
2040 }
2041
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 "
2047 "output types\n");
2048 return;
2049 }
2050 gl_prog->info.gs.output_primitive = shader->info.Geom.OutputType;
2051 }
2052
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);
2059 return;
2060 }
2061 vertices_out = shader->info.Geom.VerticesOut;
2062 }
2063
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);
2072 return;
2073 }
2074 gl_prog->info.gs.invocations = shader->info.Geom.Invocations;
2075 }
2076 }
2077
2078 /* Just do the intrastage -> interstage propagation right now,
2079 * since we already know we're in the right type of shader program
2080 * for doing it.
2081 */
2082 if (gl_prog->info.gs.input_primitive == PRIM_UNKNOWN) {
2083 linker_error(prog,
2084 "geometry shader didn't declare primitive input type\n");
2085 return;
2086 }
2087
2088 if (gl_prog->info.gs.output_primitive == PRIM_UNKNOWN) {
2089 linker_error(prog,
2090 "geometry shader didn't declare primitive output type\n");
2091 return;
2092 }
2093
2094 if (vertices_out == -1) {
2095 linker_error(prog,
2096 "geometry shader didn't declare max_vertices\n");
2097 return;
2098 } else {
2099 gl_prog->info.gs.vertices_out = vertices_out;
2100 }
2101
2102 if (gl_prog->info.gs.invocations == 0)
2103 gl_prog->info.gs.invocations = 1;
2104 }
2105
2106
2107 /**
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.
2111 */
2112 static void
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)
2117 {
2118 /* This function is called for all shader stages, but it only has an effect
2119 * for compute shaders.
2120 */
2121 if (gl_prog->info.stage != MESA_SHADER_COMPUTE)
2122 return;
2123
2124 for (int i = 0; i < 3; i++)
2125 gl_prog->info.cs.local_size[i] = 0;
2126
2127 gl_prog->info.cs.local_size_variable = false;
2128
2129 /* From the ARB_compute_shader spec, in the section describing local size
2130 * declarations:
2131 *
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.
2138 */
2139 for (unsigned sh = 0; sh < num_shaders; sh++) {
2140 struct gl_shader *shader = shader_list[sh];
2141
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 "
2148 "local sizes\n");
2149 return;
2150 }
2151 }
2152 }
2153 for (int i = 0; i < 3; i++) {
2154 gl_prog->info.cs.local_size[i] =
2155 shader->info.Comp.LocalSize[i];
2156 }
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:
2160 *
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.
2165 */
2166 linker_error(prog, "compute shader defined with both fixed and "
2167 "variable local group size\n");
2168 return;
2169 }
2170 gl_prog->info.cs.local_size_variable = true;
2171 }
2172 }
2173
2174 /* Just do the intrastage -> interstage propagation right now,
2175 * since we already know we're in the right type of shader program
2176 * for doing it.
2177 */
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");
2182 return;
2183 }
2184 }
2185
2186
2187 /**
2188 * Combine a group of shaders for a single stage to generate a linked shader
2189 *
2190 * \note
2191 * If this function is supplied a single shader, it is cloned, and the new
2192 * shader is returned.
2193 */
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)
2201 {
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;
2206
2207 /* Check that global variables defined in multiple shaders are consistent.
2208 */
2209 glsl_symbol_table variables;
2210 for (unsigned i = 0; i < num_shaders; i++) {
2211 if (shader_list[i] == NULL)
2212 continue;
2213 cross_validate_globals(prog, shader_list[i]->ir, &variables, false);
2214 }
2215
2216 if (!prog->data->LinkStatus)
2217 return NULL;
2218
2219 /* Check that interface blocks defined in multiple shaders are consistent.
2220 */
2221 validate_intrastage_interface_blocks(prog, (const gl_shader **)shader_list,
2222 num_shaders);
2223 if (!prog->data->LinkStatus)
2224 return NULL;
2225
2226 /* Check that there is only a single definition of each function signature
2227 * across all shaders.
2228 */
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();
2232
2233 if (f == NULL)
2234 continue;
2235
2236 for (unsigned j = i + 1; j < num_shaders; j++) {
2237 ir_function *const other =
2238 shader_list[j]->symbols->get_function(f->name);
2239
2240 /* If the other shader has no function (and therefore no function
2241 * signatures) with the same name, skip to the next shader.
2242 */
2243 if (other == NULL)
2244 continue;
2245
2246 foreach_in_list(ir_function_signature, sig, &f->signatures) {
2247 if (!sig->is_defined)
2248 continue;
2249
2250 ir_function_signature *other_sig =
2251 other->exact_matching_signature(NULL, &sig->parameters);
2252
2253 if (other_sig != NULL && other_sig->is_defined) {
2254 linker_error(prog, "function `%s' is multiply defined\n",
2255 f->name);
2256 return NULL;
2257 }
2258 }
2259 }
2260 }
2261 }
2262
2263 /* Find the shader that defines main, and make a clone of it.
2264 *
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.
2269 */
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];
2274 break;
2275 }
2276 }
2277
2278 if (main == NULL && allow_missing_main)
2279 main = shader_list[0];
2280
2281 if (main == NULL) {
2282 linker_error(prog, "%s shader lacks `main'\n",
2283 _mesa_shader_stage_to_string(shader_list[0]->Stage));
2284 return NULL;
2285 }
2286
2287 gl_linked_shader *linked = rzalloc(NULL, struct gl_linked_shader);
2288 linked->Stage = shader_list[0]->Stage;
2289
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),
2294 prog->Name, false);
2295 if (!gl_prog) {
2296 prog->data->LinkStatus = LINKING_FAILURE;
2297 _mesa_delete_linked_shader(ctx, linked);
2298 return NULL;
2299 }
2300
2301 _mesa_reference_shader_program_data(ctx, &gl_prog->sh.data, prog->data);
2302
2303 /* Don't use _mesa_reference_program() just take ownership */
2304 linked->Program = gl_prog;
2305
2306 linked->ir = new(linked) exec_list;
2307 clone_ir_list(mem_ctx, linked->ir, main->ir);
2308
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);
2314
2315 if (linked->Stage != MESA_SHADER_FRAGMENT)
2316 link_xfb_stride_layout_qualifiers(ctx, prog, shader_list, num_shaders);
2317
2318 link_bindless_layout_qualifiers(prog, shader_list, num_shaders);
2319
2320 populate_symbol_table(linked, shader_list[0]->symbols);
2321
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).
2324 */
2325 ir_function_signature *const main_sig =
2326 _mesa_get_main_function_signature(linked->symbols);
2327
2328 /* Move any instructions other than variable declarations or function
2329 * declarations into main.
2330 */
2331 if (main_sig != NULL) {
2332 exec_node *insertion_point =
2333 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
2334 linked);
2335
2336 for (unsigned i = 0; i < num_shaders; i++) {
2337 if (shader_list[i] == main)
2338 continue;
2339
2340 insertion_point = move_non_declarations(shader_list[i]->ir,
2341 insertion_point, true, linked);
2342 }
2343 }
2344
2345 if (!link_function_calls(prog, linked, shader_list, num_shaders)) {
2346 _mesa_delete_linked_shader(ctx, linked);
2347 return NULL;
2348 }
2349
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.
2353 */
2354 array_sizing_visitor v;
2355 v.run(linked->ir);
2356 v.fixup_unnamed_interface_types();
2357
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);
2361
2362 if (!prog->data->LinkStatus) {
2363 _mesa_delete_linked_shader(ctx, linked);
2364 return NULL;
2365 }
2366
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];
2373 }
2374 linked->Program->info.num_ubos = num_ubo_blocks;
2375
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];
2382 }
2383 linked->Program->info.num_ssbos = num_ssbo_blocks;
2384
2385 /* At this point linked should contain all of the linked IR, so
2386 * validate it to make sure nothing went wrong.
2387 */
2388 validate_ir_tree(linked->ir);
2389
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);
2398 }
2399 }
2400
2401 if (ctx->Const.VertexID_is_zero_based)
2402 lower_vertex_id(linked);
2403
2404 if (ctx->Const.LowerCsDerivedVariables)
2405 lower_cs_derived(linked);
2406
2407 #ifdef DEBUG
2408 /* Compute the source checksum. */
2409 linked->SourceChecksum = 0;
2410 for (unsigned i = 0; i < num_shaders; i++) {
2411 if (shader_list[i] == NULL)
2412 continue;
2413 linked->SourceChecksum ^= shader_list[i]->SourceChecksum;
2414 }
2415 #endif
2416
2417 return linked;
2418 }
2419
2420 /**
2421 * Update the sizes of linked shader uniform arrays to the maximum
2422 * array index used.
2423 *
2424 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2425 *
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.
2433
2434 */
2435 static void
2436 update_array_sizes(struct gl_shader_program *prog)
2437 {
2438 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2439 if (prog->_LinkedShaders[i] == NULL)
2440 continue;
2441
2442 bool types_were_updated = false;
2443
2444 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
2445 ir_variable *const var = node->as_variable();
2446
2447 if ((var == NULL) || (var->data.mode != ir_var_uniform) ||
2448 !var->type->is_array())
2449 continue;
2450
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.
2454 *
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.
2458 *
2459 * Subroutine uniforms are not removed.
2460 */
2461 if (var->is_in_buffer_block() || var->type->contains_atomic() ||
2462 var->type->contains_subroutine() || var->constant_initializer)
2463 continue;
2464
2465 int size = var->data.max_array_access;
2466 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
2467 if (prog->_LinkedShaders[j] == NULL)
2468 continue;
2469
2470 foreach_in_list(ir_instruction, node2, prog->_LinkedShaders[j]->ir) {
2471 ir_variable *other_var = node2->as_variable();
2472 if (!other_var)
2473 continue;
2474
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;
2478 }
2479 }
2480 }
2481
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.
2490 */
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));
2495 }
2496
2497 var->type = glsl_type::get_array_instance(var->type->fields.array,
2498 size + 1);
2499 types_were_updated = true;
2500 }
2501 }
2502
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);
2507 }
2508 }
2509 }
2510
2511 /**
2512 * Resize tessellation evaluation per-vertex inputs to the size of
2513 * tessellation control per-vertex outputs.
2514 */
2515 static void
2516 resize_tes_inputs(struct gl_context *ctx,
2517 struct gl_shader_program *prog)
2518 {
2519 if (prog->_LinkedShaders[MESA_SHADER_TESS_EVAL] == NULL)
2520 return;
2521
2522 gl_linked_shader *const tcs = prog->_LinkedShaders[MESA_SHADER_TESS_CTRL];
2523 gl_linked_shader *const tes = prog->_LinkedShaders[MESA_SHADER_TESS_EVAL];
2524
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.
2528 */
2529 const int num_vertices = tcs
2530 ? tcs->Program->info.tess.tcs_vertices_out
2531 : ctx->Const.MaxPatchVertices;
2532
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);
2537 }
2538
2539 if (tcs) {
2540 /* Convert the gl_PatchVerticesIn system value into a constant, since
2541 * the value is known at this point.
2542 */
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);
2552 }
2553 }
2554 }
2555 }
2556
2557 /**
2558 * Find a contiguous set of available bits in a bitmask.
2559 *
2560 * \param used_mask Bits representing used (1) and unused (0) locations
2561 * \param needed_count Number of contiguous bits needed.
2562 *
2563 * \return
2564 * Base location of the available bits on success or -1 on failure.
2565 */
2566 static int
2567 find_available_slots(unsigned used_mask, unsigned needed_count)
2568 {
2569 unsigned needed_mask = (1 << needed_count) - 1;
2570 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
2571
2572 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2573 * cannot optimize possibly infinite loops" for the loop below.
2574 */
2575 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
2576 return -1;
2577
2578 for (int i = 0; i <= max_bit_to_test; i++) {
2579 if ((needed_mask & ~used_mask) == needed_mask)
2580 return i;
2581
2582 needed_mask <<= 1;
2583 }
2584
2585 return -1;
2586 }
2587
2588
2589 #define SAFE_MASK_FROM_INDEX(i) (((i) >= 32) ? ~0 : ((1 << (i)) - 1))
2590
2591 /**
2592 * Assign locations for either VS inputs or FS outputs
2593 *
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.
2600 *
2601 * \return
2602 * If locations are successfully assigned, true is returned. Otherwise an
2603 * error is emitted to the shader link log and false is returned.
2604 */
2605 static bool
2606 assign_attribute_or_color_locations(void *mem_ctx,
2607 gl_shader_program *prog,
2608 struct gl_constants *constants,
2609 unsigned target_index)
2610 {
2611 /* Maximum number of generic locations. This corresponds to either the
2612 * maximum number of draw buffers or the maximum number of generic
2613 * attributes.
2614 */
2615 unsigned max_index = (target_index == MESA_SHADER_VERTEX) ?
2616 constants->Program[target_index].MaxAttribs :
2617 MAX2(constants->MaxDrawBuffers, constants->MaxDualSourceDrawBuffers);
2618
2619 /* Mark invalid locations as being used.
2620 */
2621 unsigned used_locations = ~SAFE_MASK_FROM_INDEX(max_index);
2622 unsigned double_storage_locations = 0;
2623
2624 assert((target_index == MESA_SHADER_VERTEX)
2625 || (target_index == MESA_SHADER_FRAGMENT));
2626
2627 gl_linked_shader *const sh = prog->_LinkedShaders[target_index];
2628 if (sh == NULL)
2629 return true;
2630
2631 /* Operate in a total of four passes.
2632 *
2633 * 1. Invalidate the location assignments for all vertex shader inputs.
2634 *
2635 * 2. Assign locations for inputs that have user-defined (via
2636 * glBindVertexAttribLocation) locations and outputs that have
2637 * user-defined locations (via glBindFragDataLocation).
2638 *
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.
2643 *
2644 * 4. Assign locations to any inputs without assigned locations.
2645 */
2646
2647 const int generic_base = (target_index == MESA_SHADER_VERTEX)
2648 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
2649
2650 const enum ir_variable_mode direction =
2651 (target_index == MESA_SHADER_VERTEX)
2652 ? ir_var_shader_in : ir_var_shader_out;
2653
2654
2655 /* Temporary storage for the set of attributes that need locations assigned.
2656 */
2657 struct temp_attr {
2658 unsigned slots;
2659 ir_variable *var;
2660
2661 /* Used below in the call to qsort. */
2662 static int compare(const void *a, const void *b)
2663 {
2664 const temp_attr *const l = (const temp_attr *) a;
2665 const temp_attr *const r = (const temp_attr *) b;
2666
2667 /* Reversed because we want a descending order sort below. */
2668 return r->slots - l->slots;
2669 }
2670 } to_assign[32];
2671 assert(max_index <= 32);
2672
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.
2676 */
2677 ir_variable *assigned[12 * 4]; /* (max # of FS outputs) * # components */
2678 unsigned assigned_attr = 0;
2679
2680 unsigned num_attr = 0;
2681
2682 foreach_in_list(ir_instruction, node, sh->ir) {
2683 ir_variable *const var = node->as_variable();
2684
2685 if ((var == NULL) || (var->data.mode != (unsigned) direction))
2686 continue;
2687
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)) {
2692 linker_error(prog,
2693 "invalid explicit location %d specified for `%s'\n",
2694 (var->data.location < 0)
2695 ? var->data.location
2696 : var->data.location - generic_base,
2697 var->name);
2698 return false;
2699 }
2700 } else if (target_index == MESA_SHADER_VERTEX) {
2701 unsigned binding;
2702
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;
2707 }
2708 } else if (target_index == MESA_SHADER_FRAGMENT) {
2709 unsigned binding;
2710 unsigned index;
2711 const char *name = var->name;
2712 const glsl_type *type = var->type;
2713
2714 while (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;
2720
2721 if (prog->FragDataIndexBindings->get(index, name)) {
2722 var->data.index = index;
2723 }
2724 break;
2725 }
2726
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;
2731 continue;
2732 }
2733
2734 break;
2735 }
2736 }
2737
2738 if (strcmp(var->name, "gl_LastFragData") == 0)
2739 continue;
2740
2741 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2742 *
2743 * "Output binding assignments will cause LinkProgram to fail:
2744 * ...
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;"
2748 */
2749 if (target_index == MESA_SHADER_FRAGMENT && var->data.index >= 1 &&
2750 var->data.location - generic_base >=
2751 (int) constants->MaxDualSourceDrawBuffers) {
2752 linker_error(prog,
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,
2756 var->name);
2757 return false;
2758 }
2759
2760 const unsigned slots = var->type->count_attribute_slots(target_index == MESA_SHADER_VERTEX);
2761
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.
2766 */
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:
2770 *
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."
2776 *
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
2780 * the details.
2781 *
2782 * From OpenGL 4.0 spec, page 61:
2783 *
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
2793 * in this case."
2794 *
2795 * From GLSL 4.30 spec, page 54:
2796 *
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
2810 * assignments."
2811 *
2812 * From OpenGL ES 3.0 spec, page 56:
2813 *
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."
2826 *
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.
2830 *
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.
2835 */
2836
2837 /* Mask representing the contiguous slots that will be used by
2838 * this attribute.
2839 */
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";
2844
2845 /* Generate a link error if the requested locations for this
2846 * attribute exceed the maximum allowed attribute location.
2847 */
2848 if (attr + slots > max_index) {
2849 linker_error(prog,
2850 "insufficient contiguous locations "
2851 "available for %s `%s' %d %d %d\n", string,
2852 var->name, used_locations, use_mask, attr);
2853 return false;
2854 }
2855
2856 /* Generate a link error if the set of bits requested for this
2857 * attribute overlaps any previously allocated bits.
2858 */
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
2862 * 4.40 spec:
2863 *
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.
2869 */
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;
2876
2877 if ((assigned_use_mask << assig_attr) &
2878 (use_mask << attr)) {
2879
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);
2887 return false;
2888 }
2889
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 "
2899 "(component=%d)\n",
2900 string, assigned[i]->name, var->name,
2901 var->data.location_frac);
2902 return false;
2903 }
2904 }
2905 }
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);
2911 return false;
2912 } else {
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);
2916 }
2917 }
2918
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.
2922 *
2923 * At most one variable per fragment output component should
2924 * reach this.
2925 */
2926 assert(assigned_attr < ARRAY_SIZE(assigned));
2927 assigned[assigned_attr] = var;
2928 assigned_attr++;
2929 }
2930
2931 used_locations |= (use_mask << attr);
2932
2933 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2934 *
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."
2947 *
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.
2952 */
2953 if (var->type->without_array()->is_dual_slot())
2954 double_storage_locations |= (use_mask << attr);
2955 }
2956
2957 continue;
2958 }
2959
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",
2964 max_index);
2965 return false;
2966 }
2967 to_assign[num_attr].slots = slots;
2968 to_assign[num_attr].var = var;
2969 num_attr++;
2970 }
2971
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) {
2977 linker_error(prog,
2978 "attempt to use %d vertex attribute slots only %d available ",
2979 total_attribs_size, max_index);
2980 return false;
2981 }
2982 }
2983
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.
2987 */
2988 if (num_attr == 0)
2989 return true;
2990
2991 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
2992
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.
2997 */
2998 find_deref_visitor find("gl_Vertex");
2999 find.run(sh->ir);
3000 if (find.variable_found())
3001 used_locations |= (1 << 0);
3002 }
3003
3004 for (unsigned i = 0; i < num_attr; i++) {
3005 /* Mask representing the contiguous slots that will be used by this
3006 * attribute.
3007 */
3008 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
3009
3010 int location = find_available_slots(used_locations, to_assign[i].slots);
3011
3012 if (location < 0) {
3013 const char *const string = (target_index == MESA_SHADER_VERTEX)
3014 ? "vertex shader input" : "fragment shader output";
3015
3016 linker_error(prog,
3017 "insufficient contiguous locations "
3018 "available for %s `%s'\n",
3019 string, to_assign[i].var->name);
3020 return false;
3021 }
3022
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);
3026
3027 if (to_assign[i].var->type->without_array()->is_dual_slot())
3028 double_storage_locations |= (use_mask << location);
3029 }
3030
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.
3035 */
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) {
3041 linker_error(prog,
3042 "attempt to use %d vertex attribute slots only %d available ",
3043 total_attribs_size, max_index);
3044 return false;
3045 }
3046 }
3047
3048 return true;
3049 }
3050
3051 /**
3052 * Match explicit locations of outputs to inputs and deactivate the
3053 * unmatch flag if found so we don't optimise them away.
3054 */
3055 static void
3056 match_explicit_outputs_to_inputs(gl_linked_shader *producer,
3057 gl_linked_shader *consumer)
3058 {
3059 glsl_symbol_table parameters;
3060 ir_variable *explicit_locations[MAX_VARYINGS_INCL_PATCH][4] =
3061 { {NULL, NULL} };
3062
3063 /* Find all shader outputs in the "producer" stage.
3064 */
3065 foreach_in_list(ir_instruction, node, producer->ir) {
3066 ir_variable *const var = node->as_variable();
3067
3068 if ((var == NULL) || (var->data.mode != ir_var_shader_out))
3069 continue;
3070
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;
3076 }
3077 }
3078
3079 /* Match inputs to outputs */
3080 foreach_in_list(ir_instruction, node, consumer->ir) {
3081 ir_variable *const input = node->as_variable();
3082
3083 if ((input == NULL) || (input->data.mode != ir_var_shader_in))
3084 continue;
3085
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];
3091
3092 if (output != NULL){
3093 input->data.is_unmatched_generic_inout = 0;
3094 output->data.is_unmatched_generic_inout = 0;
3095 }
3096 }
3097 }
3098 }
3099
3100 /**
3101 * Store the gl_FragDepth layout in the gl_shader_program struct.
3102 */
3103 static void
3104 store_fragdepth_layout(struct gl_shader_program *prog)
3105 {
3106 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
3107 return;
3108 }
3109
3110 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
3111
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.
3115 *
3116 * We're only interested in the cases where the variable is NOT removed
3117 * from the IR.
3118 */
3119 foreach_in_list(ir_instruction, node, ir) {
3120 ir_variable *const var = node->as_variable();
3121
3122 if (var == NULL || var->data.mode != ir_var_shader_out) {
3123 continue;
3124 }
3125
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;
3130 return;
3131 case ir_depth_layout_any:
3132 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
3133 return;
3134 case ir_depth_layout_greater:
3135 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
3136 return;
3137 case ir_depth_layout_less:
3138 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
3139 return;
3140 case ir_depth_layout_unchanged:
3141 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
3142 return;
3143 default:
3144 assert(0);
3145 return;
3146 }
3147 }
3148 }
3149 }
3150
3151 /**
3152 * Validate the resources used by a program versus the implementation limits
3153 */
3154 static void
3155 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
3156 {
3157 unsigned total_uniform_blocks = 0;
3158 unsigned total_shader_storage_blocks = 0;
3159
3160 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3161 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
3162
3163 if (sh == NULL)
3164 continue;
3165
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));
3170 }
3171
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 "
3178 "behavior\n",
3179 _mesa_shader_stage_to_string(i));
3180 } else {
3181 linker_error(prog, "Too many %s shader default uniform block "
3182 "components\n",
3183 _mesa_shader_stage_to_string(i));
3184 }
3185 }
3186
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));
3194 } else {
3195 linker_error(prog, "Too many %s shader uniform components\n",
3196 _mesa_shader_stage_to_string(i));
3197 }
3198 }
3199
3200 total_shader_storage_blocks += sh->Program->info.num_ssbos;
3201 total_uniform_blocks += sh->Program->info.num_ubos;
3202
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);
3209 }
3210
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);
3217 }
3218 }
3219
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);
3223 }
3224
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);
3229 }
3230
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);
3238 }
3239 }
3240
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);
3248 }
3249 }
3250 }
3251
3252 static void
3253 link_calculate_subroutine_compat(struct gl_shader_program *prog)
3254 {
3255 unsigned mask = prog->data->linked_stages;
3256 while (mask) {
3257 const int i = u_bit_scan(&mask);
3258 struct gl_program *p = prog->_LinkedShaders[i]->Program;
3259
3260 for (unsigned j = 0; j < p->sh.NumSubroutineUniformRemapTable; j++) {
3261 if (p->sh.SubroutineUniformRemapTable[j] == INACTIVE_UNIFORM_EXPLICIT_LOCATION)
3262 continue;
3263
3264 struct gl_uniform_storage *uni = p->sh.SubroutineUniformRemapTable[j];
3265
3266 if (!uni)
3267 continue;
3268
3269 int count = 0;
3270 if (p->sh.NumSubroutineFunctions == 0) {
3271 linker_error(prog, "subroutine uniform %s defined but no valid functions found\n", uni->type->name);
3272 continue;
3273 }
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) {
3278 count++;
3279 break;
3280 }
3281 }
3282 }
3283 uni->num_compatible_subroutines = count;
3284 }
3285 }
3286 }
3287
3288 static void
3289 check_subroutine_resources(struct gl_shader_program *prog)
3290 {
3291 unsigned mask = prog->data->linked_stages;
3292 while (mask) {
3293 const int i = u_bit_scan(&mask);
3294 struct gl_program *p = prog->_LinkedShaders[i]->Program;
3295
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));
3299 }
3300 }
3301 }
3302 /**
3303 * Validate shader image resources.
3304 */
3305 static void
3306 check_image_resources(struct gl_context *ctx, struct gl_shader_program *prog)
3307 {
3308 unsigned total_image_units = 0;
3309 unsigned fragment_outputs = 0;
3310 unsigned total_shader_storage_blocks = 0;
3311
3312 if (!ctx->Extensions.ARB_shader_image_load_store)
3313 return;
3314
3315 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3316 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
3317
3318 if (sh) {
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);
3324
3325 total_image_units += sh->Program->info.num_images;
3326 total_shader_storage_blocks += sh->Program->info.num_ssbos;
3327
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);
3334 }
3335 }
3336 }
3337 }
3338
3339 if (total_image_units > ctx->Const.MaxCombinedImageUniforms)
3340 linker_error(prog, "Too many combined image uniforms\n");
3341
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");
3346 }
3347
3348
3349 /**
3350 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3351 * for a variable, checks for overlaps between other uniforms using explicit
3352 * locations.
3353 */
3354 static int
3355 reserve_explicit_locations(struct gl_shader_program *prog,
3356 string_to_uint_map *map, ir_variable *var)
3357 {
3358 unsigned slots = var->type->uniform_locations();
3359 unsigned max_loc = var->data.location + slots - 1;
3360 unsigned return_value = slots;
3361
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 *,
3367 max_loc + 1);
3368
3369 if (!prog->UniformRemapTable) {
3370 linker_error(prog, "Out of memory during linking.\n");
3371 return -1;
3372 }
3373
3374 /* Initialize allocated space. */
3375 for (unsigned i = prog->NumUniformRemapTable; i < max_loc + 1; i++)
3376 prog->UniformRemapTable[i] = NULL;
3377
3378 prog->NumUniformRemapTable = max_loc + 1;
3379 }
3380
3381 for (unsigned i = 0; i < slots; i++) {
3382 unsigned loc = var->data.location + i;
3383
3384 /* Check if location is already used. */
3385 if (prog->UniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3386
3387 /* Possibly same uniform from a different stage, this is ok. */
3388 unsigned hash_loc;
3389 if (map->get(hash_loc, var->name) && hash_loc == loc - i) {
3390 return_value = 0;
3391 continue;
3392 }
3393
3394 /* ARB_explicit_uniform_location specification states:
3395 *
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."
3399 */
3400 linker_error(prog,
3401 "location qualifier for uniform %s overlaps "
3402 "previously used location\n",
3403 var->name);
3404 return -1;
3405 }
3406
3407 /* Initialize location as inactive before optimization
3408 * rounds and location assignment.
3409 */
3410 prog->UniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3411 }
3412
3413 /* Note, base location used for arrays. */
3414 map->put(var->data.location, var->name);
3415
3416 return return_value;
3417 }
3418
3419 static bool
3420 reserve_subroutine_explicit_locations(struct gl_shader_program *prog,
3421 struct gl_program *p,
3422 ir_variable *var)
3423 {
3424 unsigned slots = var->type->uniform_locations();
3425 unsigned max_loc = var->data.location + slots - 1;
3426
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 *,
3432 max_loc + 1);
3433
3434 if (!p->sh.SubroutineUniformRemapTable) {
3435 linker_error(prog, "Out of memory during linking.\n");
3436 return false;
3437 }
3438
3439 /* Initialize allocated space. */
3440 for (unsigned i = p->sh.NumSubroutineUniformRemapTable; i < max_loc + 1; i++)
3441 p->sh.SubroutineUniformRemapTable[i] = NULL;
3442
3443 p->sh.NumSubroutineUniformRemapTable = max_loc + 1;
3444 }
3445
3446 for (unsigned i = 0; i < slots; i++) {
3447 unsigned loc = var->data.location + i;
3448
3449 /* Check if location is already used. */
3450 if (p->sh.SubroutineUniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3451
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."
3456 */
3457 linker_error(prog,
3458 "location qualifier for uniform %s overlaps "
3459 "previously used location\n",
3460 var->name);
3461 return false;
3462 }
3463
3464 /* Initialize location as inactive before optimization
3465 * rounds and location assignment.
3466 */
3467 p->sh.SubroutineUniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3468 }
3469
3470 return true;
3471 }
3472 /**
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.
3476 */
3477 static void
3478 check_explicit_uniform_locations(struct gl_context *ctx,
3479 struct gl_shader_program *prog)
3480 {
3481 prog->NumExplicitUniformLocations = 0;
3482
3483 if (!ctx->Extensions.ARB_explicit_uniform_location)
3484 return;
3485
3486 /* This map is used to detect if overlapping explicit locations
3487 * occur with the same uniform (from different stage) or a different one.
3488 */
3489 string_to_uint_map *uniform_map = new string_to_uint_map;
3490
3491 if (!uniform_map) {
3492 linker_error(prog, "Out of memory during linking.\n");
3493 return;
3494 }
3495
3496 unsigned entries_total = 0;
3497 unsigned mask = prog->data->linked_stages;
3498 while (mask) {
3499 const int i = u_bit_scan(&mask);
3500 struct gl_program *p = prog->_LinkedShaders[i]->Program;
3501
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)
3505 continue;
3506
3507 if (var->data.explicit_location) {
3508 bool ret = false;
3509 if (var->type->without_array()->is_subroutine())
3510 ret = reserve_subroutine_explicit_locations(prog, p, var);
3511 else {
3512 int slots = reserve_explicit_locations(prog, uniform_map,
3513 var);
3514 if (slots != -1) {
3515 ret = true;
3516 entries_total += slots;
3517 }
3518 }
3519 if (!ret) {
3520 delete uniform_map;
3521 return;
3522 }
3523 }
3524 }
3525 }
3526
3527 struct empty_uniform_block *current_block = NULL;
3528
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 &current_block->link);
3538 }
3539
3540 /* The current block continues, so we simply increment its slots */
3541 current_block->slots++;
3542 }
3543 }
3544
3545 delete uniform_map;
3546 prog->NumExplicitUniformLocations = entries_total;
3547 }
3548
3549 static bool
3550 should_add_buffer_variable(struct gl_shader_program *shProg,
3551 GLenum type, const char *name)
3552 {
3553 bool found_interface = false;
3554 unsigned block_name_len = 0;
3555 const char *block_name_dot = strchr(name, '.');
3556
3557 /* These rules only apply to buffer variables. So we return
3558 * true for the rest of types.
3559 */
3560 if (type != GL_BUFFER_VARIABLE)
3561 return true;
3562
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);
3566
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.
3571 */
3572 block_name_len -= strlen(block_square_bracket);
3573 }
3574
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.
3579 */
3580 unsigned len = strlen(name) - strlen(block_name_dot);
3581 if (len != block_name_len)
3582 continue;
3583 }
3584
3585 if (strncmp(block_name, name, block_name_len) == 0) {
3586 found_interface = true;
3587 break;
3588 }
3589 }
3590
3591 /* We remove the interface name from the buffer variable name,
3592 * including the dot that follows it.
3593 */
3594 if (found_interface)
3595 name = name + block_name_len + 1;
3596
3597 /* The ARB_program_interface_query spec says:
3598 *
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."
3603 */
3604 const char *struct_first_dot = strchr(name, '.');
3605 const char *first_square_bracket = strchr(name, '[');
3606
3607 /* The buffer variable is on top level and it is not an array */
3608 if (!first_square_bracket) {
3609 return true;
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) {
3612 return true;
3613 } else {
3614 /* Shader storage block member is an array, only generate an entry for the
3615 * first array element.
3616 */
3617 if (strncmp(first_square_bracket, "[0]", 3) == 0)
3618 return true;
3619 }
3620
3621 return false;
3622 }
3623
3624 static bool
3625 add_program_resource(struct gl_shader_program *prog,
3626 struct set *resource_set,
3627 GLenum type, const void *data, uint8_t stages)
3628 {
3629 assert(data);
3630
3631 /* If resource already exists, do not add it again. */
3632 if (_mesa_set_search(resource_set, data))
3633 return true;
3634
3635 prog->data->ProgramResourceList =
3636 reralloc(prog->data,
3637 prog->data->ProgramResourceList,
3638 gl_program_resource,
3639 prog->data->NumProgramResourceList + 1);
3640
3641 if (!prog->data->ProgramResourceList) {
3642 linker_error(prog, "Out of memory during linking.\n");
3643 return false;
3644 }
3645
3646 struct gl_program_resource *res =
3647 &prog->data->ProgramResourceList[prog->data->NumProgramResourceList];
3648
3649 res->Type = type;
3650 res->Data = data;
3651 res->StageReferences = stages;
3652
3653 prog->data->NumProgramResourceList++;
3654
3655 _mesa_set_add(resource_set, data);
3656
3657 return true;
3658 }
3659
3660 /* Function checks if a variable var is a packed varying and
3661 * if given name is part of packed varying's list.
3662 *
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.
3665 */
3666 static bool
3667 included_in_packed_varying(ir_variable *var, const char *name)
3668 {
3669 if (strncmp(var->name, "packed:", 7) != 0)
3670 return false;
3671
3672 char *list = strdup(var->name + 7);
3673 assert(list);
3674
3675 bool found = false;
3676 char *saveptr;
3677 char *token = strtok_r(list, ",", &saveptr);
3678 while (token) {
3679 if (strcmp(token, name) == 0) {
3680 found = true;
3681 break;
3682 }
3683 token = strtok_r(NULL, ",", &saveptr);
3684 }
3685 free(list);
3686 return found;
3687 }
3688
3689 /**
3690 * Function builds a stage reference bitmask from variable name.
3691 */
3692 static uint8_t
3693 build_stageref(struct gl_shader_program *shProg, const char *name,
3694 unsigned mode)
3695 {
3696 uint8_t stages = 0;
3697
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.
3700 */
3701 assert(MESA_SHADER_STAGES < 8);
3702
3703 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3704 struct gl_linked_shader *sh = shProg->_LinkedShaders[i];
3705 if (!sh)
3706 continue;
3707
3708 /* Shader symbol table may contain variables that have
3709 * been optimized away. Search IR for the variable instead.
3710 */
3711 foreach_in_list(ir_instruction, node, sh->ir) {
3712 ir_variable *var = node->as_variable();
3713 if (var) {
3714 unsigned baselen = strlen(var->name);
3715
3716 if (included_in_packed_varying(var, name)) {
3717 stages |= (1 << i);
3718 break;
3719 }
3720
3721 /* Type needs to match if specified, otherwise we might
3722 * pick a variable with same name but different interface.
3723 */
3724 if (var->data.mode != mode)
3725 continue;
3726
3727 if (strncmp(var->name, name, baselen) == 0) {
3728 /* Check for exact name matches but also check for arrays and
3729 * structs.
3730 */
3731 if (name[baselen] == '\0' ||
3732 name[baselen] == '[' ||
3733 name[baselen] == '.') {
3734 stages |= (1 << i);
3735 break;
3736 }
3737 }
3738 }
3739 }
3740 }
3741 return stages;
3742 }
3743
3744 /**
3745 * Create gl_shader_variable from ir_variable class.
3746 */
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)
3754 {
3755 /* Allocate zero-initialized memory to ensure that bitfield padding
3756 * is zero.
3757 */
3758 gl_shader_variable *out = rzalloc(shProg, struct gl_shader_variable);
3759 if (!out)
3760 return NULL;
3761
3762 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3763 * expect to see gl_VertexID in the program resource list. Pretend.
3764 */
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);
3780 } else {
3781 out->name = ralloc_strdup(shProg, name);
3782 }
3783
3784 if (!out->name)
3785 return NULL;
3786
3787 /* The ARB_program_interface_query spec says:
3788 *
3789 * "Not all active variables are assigned valid locations; the
3790 * following variables will have an effective location of -1:
3791 *
3792 * * uniforms declared as atomic counters;
3793 *
3794 * * members of a uniform block;
3795 *
3796 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3797 *
3798 * * inputs or outputs not declared with a "location" layout
3799 * qualifier, except for vertex shader inputs and fragment shader
3800 * outputs."
3801 */
3802 if (in->type->is_atomic_uint() || is_gl_identifier(in->name) ||
3803 !(in->data.explicit_location || use_implicit_location)) {
3804 out->location = -1;
3805 } else {
3806 out->location = location;
3807 }
3808
3809 out->type = type;
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;
3819
3820 return out;
3821 }
3822
3823 static bool
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)
3833 {
3834 const glsl_type *interface_type = var->get_interface_type();
3835
3836 if (outermost_struct_type == NULL) {
3837 if (var->data.from_named_ifc_block) {
3838 const char *interface_name = interface_type->name;
3839
3840 if (interface_type->is_array()) {
3841 /* Issue #16 of the ARB_program_interface_query spec says:
3842 *
3843 * "* If a variable is a member of an interface block without an
3844 * instance name, it is enumerated using just the variable name.
3845 *
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."
3850 *
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.
3854 *
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.
3858 *
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.
3862 */
3863 type = type->fields.array;
3864
3865 interface_name = interface_type->fields.array->name;
3866 }
3867
3868 name = ralloc_asprintf(shProg, "%s.%s", interface_name, name);
3869 }
3870 }
3871
3872 switch (type->base_type) {
3873 case GLSL_TYPE_STRUCT: {
3874 /* The ARB_program_interface_query spec says:
3875 *
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."
3882 */
3883 if (outermost_struct_type == NULL)
3884 outermost_struct_type = type;
3885
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))
3895 return false;
3896
3897 field_location += field->type->count_attribute_slots(false);
3898 }
3899 return true;
3900 }
3901
3902 case GLSL_TYPE_ARRAY: {
3903 /* The ARB_program_interface_query spec says:
3904 *
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]"."
3908 *
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."
3917 */
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))
3931 return false;
3932 elem_location += stride;
3933 }
3934 return true;
3935 }
3936 /* fallthrough */
3937 }
3938
3939 default: {
3940 /* The ARB_program_interface_query spec says:
3941 *
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."
3945 */
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);
3950 if (!sha_v)
3951 return false;
3952
3953 return add_program_resource(shProg, resource_set,
3954 programInterface, sha_v, stage_mask);
3955 }
3956 }
3957 }
3958
3959 static bool
3960 inout_has_same_location(const ir_variable *var, unsigned stage)
3961 {
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))))
3968 return true;
3969 else
3970 return false;
3971 }
3972
3973 static bool
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)
3978 {
3979 exec_list *ir = shProg->_LinkedShaders[stage]->ir;
3980
3981 foreach_in_list(ir_instruction, node, ir) {
3982 ir_variable *var = node->as_variable();
3983
3984 if (!var || var->data.how_declared == ir_var_hidden)
3985 continue;
3986
3987 int loc_bias;
3988
3989 switch (var->data.mode) {
3990 case ir_var_system_value:
3991 case ir_var_shader_in:
3992 if (programInterface != GL_PROGRAM_INPUT)
3993 continue;
3994 loc_bias = (stage == MESA_SHADER_VERTEX) ? int(VERT_ATTRIB_GENERIC0)
3995 : int(VARYING_SLOT_VAR0);
3996 break;
3997 case ir_var_shader_out:
3998 if (programInterface != GL_PROGRAM_OUTPUT)
3999 continue;
4000 loc_bias = (stage == MESA_SHADER_FRAGMENT) ? int(FRAG_RESULT_DATA0)
4001 : int(VARYING_SLOT_VAR0);
4002 break;
4003 default:
4004 continue;
4005 };
4006
4007 if (var->data.patch)
4008 loc_bias = int(VARYING_SLOT_PATCH0);
4009
4010 /* Skip packed varyings, packed varyings are handled separately
4011 * by add_packed_varyings.
4012 */
4013 if (strncmp(var->name, "packed:", 7) == 0)
4014 continue;
4015
4016 /* Skip fragdata arrays, these are handled separately
4017 * by add_fragdata_arrays.
4018 */
4019 if (strncmp(var->name, "gl_out_FragData", 15) == 0)
4020 continue;
4021
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);
4025
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)))
4031 return false;
4032 }
4033 return true;
4034 }
4035
4036 static bool
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)
4041 {
4042 struct gl_linked_shader *sh = shProg->_LinkedShaders[stage];
4043 GLenum iface;
4044
4045 if (!sh || !sh->packed_varyings)
4046 return true;
4047
4048 foreach_in_list(ir_instruction, node, sh->packed_varyings) {
4049 ir_variable *var = node->as_variable();
4050 if (var) {
4051 switch (var->data.mode) {
4052 case ir_var_shader_in:
4053 iface = GL_PROGRAM_INPUT;
4054 break;
4055 case ir_var_shader_out:
4056 iface = GL_PROGRAM_OUTPUT;
4057 break;
4058 default:
4059 unreachable("unexpected type");
4060 }
4061
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,
4066 stage_mask,
4067 iface, var, var->name, var->type, false,
4068 var->data.location - VARYING_SLOT_VAR0,
4069 inout_has_same_location(var, stage)))
4070 return false;
4071 }
4072 }
4073 }
4074 return true;
4075 }
4076
4077 static bool
4078 add_fragdata_arrays(const struct gl_context *ctx,
4079 struct gl_shader_program *shProg,
4080 struct set *resource_set)
4081 {
4082 struct gl_linked_shader *sh = shProg->_LinkedShaders[MESA_SHADER_FRAGMENT];
4083
4084 if (!sh || !sh->fragdata_arrays)
4085 return true;
4086
4087 foreach_in_list(ir_instruction, node, sh->fragdata_arrays) {
4088 ir_variable *var = node->as_variable();
4089 if (var) {
4090 assert(var->data.mode == ir_var_shader_out);
4091
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,
4096 false))
4097 return false;
4098 }
4099 }
4100 return true;
4101 }
4102
4103 static char*
4104 get_top_level_name(const char *name)
4105 {
4106 const char *first_dot = strchr(name, '.');
4107 const char *first_square_bracket = strchr(name, '[');
4108 int name_size = 0;
4109
4110 /* The ARB_program_interface_query spec says:
4111 *
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
4118 * to <params>."
4119 */
4120
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;
4127 else
4128 name_size = first_square_bracket - name;
4129
4130 return strndup(name, name_size);
4131 }
4132
4133 static char*
4134 get_var_name(const char *name)
4135 {
4136 const char *first_dot = strchr(name, '.');
4137
4138 if (!first_dot)
4139 return strdup(name);
4140
4141 return strndup(first_dot+1, strlen(first_dot) - 1);
4142 }
4143
4144 static bool
4145 is_top_level_shader_storage_block_member(const char* name,
4146 const char* interface_name,
4147 const char* field_name)
4148 {
4149 bool result = false;
4150
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.
4155 *
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.
4159 *
4160 * Full instanced name is: interface name + '.' + var name +
4161 * NULL character
4162 */
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__);
4167 return false;
4168 }
4169
4170 snprintf(full_instanced_name, name_length, "%s.%s",
4171 interface_name, field_name);
4172
4173 /* Check if its top-level shader storage block member of an
4174 * instanced interface block, or of a unnamed interface block.
4175 */
4176 if (strcmp(name, full_instanced_name) == 0 ||
4177 strcmp(name, field_name) == 0)
4178 result = true;
4179
4180 free(full_instanced_name);
4181 return result;
4182 }
4183
4184 static int
4185 get_array_size(struct gl_uniform_storage *uni, const glsl_struct_field *field,
4186 char *interface_name, char *var_name)
4187 {
4188 /* The ARB_program_interface_query spec says:
4189 *
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
4196 * to <params>."
4197 */
4198 if (is_top_level_shader_storage_block_member(uni->name,
4199 interface_name,
4200 var_name))
4201 return 1;
4202 else if (field->type->is_unsized_array())
4203 return 0;
4204 else if (field->type->is_array())
4205 return field->type->length;
4206
4207 return 1;
4208 }
4209
4210 static int
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)
4214 {
4215 /* The ARB_program_interface_query spec says:
4216 *
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>."
4225 */
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;
4231
4232 if (is_top_level_shader_storage_block_member(uni->name,
4233 interface_name,
4234 var_name))
4235 return 0;
4236
4237 if (GLSL_INTERFACE_PACKING_STD140 ==
4238 iface->
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);
4242 else
4243 return MAX2(array_type->std140_base_alignment(row_major), 16);
4244 } else {
4245 return array_type->std430_array_stride(row_major);
4246 }
4247 }
4248 return 0;
4249 }
4250
4251 static void
4252 calculate_array_size_and_stride(struct gl_context *ctx,
4253 struct gl_shader_program *shProg,
4254 struct gl_uniform_storage *uni)
4255 {
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);
4264
4265 if (strcmp(var_name, interface_name) == 0) {
4266 /* Deal with instanced array of SSBOs */
4267 char *temp_name = get_var_name(uni->name);
4268 if (!temp_name) {
4269 linker_error(shProg, "Out of memory during linking.\n");
4270 goto write_top_level_array_size_and_stride;
4271 }
4272 free(var_name);
4273 var_name = get_top_level_name(temp_name);
4274 free(temp_name);
4275 if (!var_name) {
4276 linker_error(shProg, "Out of memory during linking.\n");
4277 goto write_top_level_array_size_and_stride;
4278 }
4279 }
4280
4281 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4282 const gl_linked_shader *sh = shProg->_LinkedShaders[i];
4283 if (sh == NULL)
4284 continue;
4285
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)
4290 continue;
4291
4292 const glsl_type *iface = var->get_interface_type();
4293
4294 if (strcmp(interface_name, iface->name) != 0)
4295 continue;
4296
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)
4300 continue;
4301
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;
4306 }
4307 }
4308 }
4309 write_top_level_array_size_and_stride:
4310 free(interface_name);
4311 free(var_name);
4312 uni->top_level_array_stride = array_stride;
4313 uni->top_level_array_size = array_size;
4314 }
4315
4316 /**
4317 * Builds up a list of program resources that point to existing
4318 * resource data.
4319 */
4320 void
4321 build_program_resource_list(struct gl_context *ctx,
4322 struct gl_shader_program *shProg)
4323 {
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;
4329 }
4330
4331 int input_stage = MESA_SHADER_STAGES, output_stage = 0;
4332
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.
4336 */
4337 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4338 if (!shProg->_LinkedShaders[i])
4339 continue;
4340 if (input_stage == MESA_SHADER_STAGES)
4341 input_stage = i;
4342 output_stage = i;
4343 }
4344
4345 /* Empty shader, no resources. */
4346 if (input_stage == MESA_SHADER_STAGES && output_stage == 0)
4347 return;
4348
4349 struct set *resource_set = _mesa_set_create(NULL,
4350 _mesa_hash_pointer,
4351 _mesa_key_pointer_equal);
4352
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))
4357 return;
4358
4359 if (!add_packed_varyings(ctx, shProg, resource_set,
4360 output_stage, GL_PROGRAM_OUTPUT))
4361 return;
4362 }
4363
4364 if (!add_fragdata_arrays(ctx, shProg, resource_set))
4365 return;
4366
4367 /* Add inputs and outputs to the resource list. */
4368 if (!add_interface_variables(ctx, shProg, resource_set,
4369 input_stage, GL_PROGRAM_INPUT))
4370 return;
4371
4372 if (!add_interface_variables(ctx, shProg, resource_set,
4373 output_stage, GL_PROGRAM_OUTPUT))
4374 return;
4375
4376 if (shProg->last_vert_prog) {
4377 struct gl_transform_feedback_info *linked_xfb =
4378 shProg->last_vert_prog->sh.LinkedTransformFeedback;
4379
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))
4386 return;
4387 }
4388 }
4389
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))
4397 return;
4398 }
4399 }
4400 }
4401
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)
4406 continue;
4407
4408 uint8_t stageref =
4409 build_stageref(shProg, shProg->data->UniformStorage[i].name,
4410 ir_var_uniform);
4411
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;
4420 }
4421
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))
4425 continue;
4426
4427 if (is_shader_storage) {
4428 calculate_array_size_and_stride(ctx, shProg,
4429 &shProg->data->UniformStorage[i]);
4430 }
4431
4432 if (!add_program_resource(shProg, resource_set, type,
4433 &shProg->data->UniformStorage[i], stageref))
4434 return;
4435 }
4436
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))
4441 return;
4442 }
4443
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))
4448 return;
4449 }
4450
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))
4455 return;
4456 }
4457
4458 for (unsigned i = 0; i < shProg->data->NumUniformStorage; i++) {
4459 GLenum type;
4460 if (!shProg->data->UniformStorage[i].hidden)
4461 continue;
4462
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())
4466 continue;
4467
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))
4472 return;
4473 }
4474 }
4475
4476 unsigned mask = shProg->data->linked_stages;
4477 while (mask) {
4478 const int i = u_bit_scan(&mask);
4479 struct gl_program *p = shProg->_LinkedShaders[i]->Program;
4480
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))
4485 return;
4486 }
4487 }
4488
4489 _mesa_set_destroy(resource_set, NULL);
4490 }
4491
4492 /**
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).
4496 */
4497 static bool
4498 validate_sampler_array_indexing(struct gl_context *ctx,
4499 struct gl_shader_program *prog)
4500 {
4501 dynamic_sampler_array_indexing_visitor v;
4502 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4503 if (prog->_LinkedShaders[i] == NULL)
4504 continue;
4505
4506 bool no_dynamic_indexing =
4507 ctx->Const.ShaderCompilerOptions[i].EmitNoIndirectSampler;
4508
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);
4518 return false;
4519 } else {
4520 linker_warning(prog, msg, prog->IsES ? "ES" : "",
4521 prog->data->Version);
4522 }
4523 }
4524 }
4525 return true;
4526 }
4527
4528 static void
4529 link_assign_subroutine_types(struct gl_shader_program *prog)
4530 {
4531 unsigned mask = prog->data->linked_stages;
4532 while (mask) {
4533 const int i = u_bit_scan(&mask);
4534 gl_program *p = prog->_LinkedShaders[i]->Program;
4535
4536 p->sh.MaxSubroutineFunctionIndex = 0;
4537 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
4538 ir_function *fn = node->as_function();
4539 if (!fn)
4540 continue;
4541
4542 if (fn->is_subroutine)
4543 p->sh.NumSubroutineUniformTypes++;
4544
4545 if (!fn->num_subroutine_types)
4546 continue;
4547
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");
4552 return;
4553 }
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);
4562
4563 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4564 * GLSL 4.5 spec:
4565 *
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
4568 * generated."
4569 */
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");
4575 return;
4576 }
4577 }
4578 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].index =
4579 fn->subroutine_index;
4580
4581 if (fn->subroutine_index > (int)p->sh.MaxSubroutineFunctionIndex)
4582 p->sh.MaxSubroutineFunctionIndex = fn->subroutine_index;
4583
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++;
4587 }
4588 }
4589 }
4590
4591 static void
4592 set_always_active_io(exec_list *ir, ir_variable_mode io_mode)
4593 {
4594 assert(io_mode == ir_var_shader_in || io_mode == ir_var_shader_out);
4595
4596 foreach_in_list(ir_instruction, node, ir) {
4597 ir_variable *const var = node->as_variable();
4598
4599 if (var == NULL || var->data.mode != io_mode)
4600 continue;
4601
4602 /* Don't set always active on builtins that haven't been redeclared */
4603 if (var->data.how_declared == ir_var_declared_implicitly)
4604 continue;
4605
4606 var->data.always_active_io = true;
4607 }
4608 }
4609
4610 /**
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.
4614 */
4615 static void
4616 disable_varying_optimizations_for_sso(struct gl_shader_program *prog)
4617 {
4618 unsigned first, last;
4619 assert(prog->SeparateShader);
4620
4621 first = MESA_SHADER_STAGES;
4622 last = 0;
4623
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])
4627 continue;
4628 if (first == MESA_SHADER_STAGES)
4629 first = i;
4630 last = i;
4631 }
4632
4633 if (first == MESA_SHADER_STAGES)
4634 return;
4635
4636 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
4637 gl_linked_shader *sh = prog->_LinkedShaders[stage];
4638 if (!sh)
4639 continue;
4640
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.
4644 *
4645 * The removal of IO between shaders in the same program is always
4646 * allowed.
4647 */
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);
4652 }
4653 }
4654
4655 static void
4656 link_and_validate_uniforms(struct gl_context *ctx,
4657 struct gl_shader_program *prog)
4658 {
4659 update_array_sizes(prog);
4660 link_assign_uniform_locations(prog, ctx);
4661
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);
4668 }
4669
4670 static bool
4671 link_varyings_and_uniforms(unsigned first, unsigned last,
4672 struct gl_context *ctx,
4673 struct gl_shader_program *prog, void *mem_ctx)
4674 {
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);
4679 }
4680 }
4681
4682 unsigned prev = first;
4683 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
4684 if (prog->_LinkedShaders[i] == NULL)
4685 continue;
4686
4687 match_explicit_outputs_to_inputs(prog->_LinkedShaders[prev],
4688 prog->_LinkedShaders[i]);
4689 prev = i;
4690 }
4691
4692 if (!assign_attribute_or_color_locations(mem_ctx, prog, &ctx->Const,
4693 MESA_SHADER_VERTEX)) {
4694 return false;
4695 }
4696
4697 if (!assign_attribute_or_color_locations(mem_ctx, prog, &ctx->Const,
4698 MESA_SHADER_FRAGMENT)) {
4699 return false;
4700 }
4701
4702 prog->last_vert_prog = NULL;
4703 for (int i = MESA_SHADER_GEOMETRY; i >= MESA_SHADER_VERTEX; i--) {
4704 if (prog->_LinkedShaders[i] == NULL)
4705 continue;
4706
4707 prog->last_vert_prog = prog->_LinkedShaders[i]->Program;
4708 break;
4709 }
4710
4711 if (!link_varyings(prog, first, last, ctx, mem_ctx))
4712 return false;
4713
4714 link_and_validate_uniforms(ctx, prog);
4715
4716 if (!prog->data->LinkStatus)
4717 return false;
4718
4719 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4720 if (prog->_LinkedShaders[i] == NULL)
4721 continue;
4722
4723 const struct gl_shader_compiler_options *options =
4724 &ctx->Const.ShaderCompilerOptions[i];
4725
4726 if (options->LowerBufferInterfaceBlocks)
4727 lower_ubo_reference(prog->_LinkedShaders[i],
4728 options->ClampBlockIndicesToArrayBounds,
4729 ctx->Const.UseSTD430AsDefaultPacking);
4730
4731 if (i == MESA_SHADER_COMPUTE)
4732 lower_shared_reference(ctx, prog, prog->_LinkedShaders[i]);
4733
4734 lower_vector_derefs(prog->_LinkedShaders[i]);
4735 do_vec_index_to_swizzle(prog->_LinkedShaders[i]->ir);
4736 }
4737
4738 return true;
4739 }
4740
4741 static void
4742 linker_optimisation_loop(struct gl_context *ctx, exec_list *ir,
4743 unsigned stage)
4744 {
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);
4750 } else {
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))
4755 ;
4756 }
4757 }
4758
4759 void
4760 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
4761 {
4762 prog->data->LinkStatus = LINKING_SUCCESS; /* All error paths will set this to false */
4763 prog->data->Validated = false;
4764
4765 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4766 *
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:
4770 *
4771 * - No shader objects are attached to program."
4772 *
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
4776 * missing.
4777 */
4778 if (prog->NumShaders == 0) {
4779 if (ctx->API != API_OPENGL_COMPAT)
4780 linker_error(prog, "no shaders attached to the program\n");
4781 return;
4782 }
4783
4784 #ifdef ENABLE_SHADER_CACHE
4785 if (shader_cache_read_program_metadata(ctx, prog))
4786 return;
4787 #endif
4788
4789 void *mem_ctx = ralloc_context(NULL); // temporary linker context
4790
4791 prog->ARB_fragment_coord_conventions_enable = false;
4792
4793 /* Separate the shaders into groups based on their type.
4794 */
4795 struct gl_shader **shader_list[MESA_SHADER_STAGES];
4796 unsigned num_shaders[MESA_SHADER_STAGES];
4797
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 *));
4801 num_shaders[i] = 0;
4802 }
4803
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);
4809
4810 if (prog->Shaders[i]->IsES != prog->Shaders[0]->IsES) {
4811 linker_error(prog, "all shaders must use same shading "
4812 "language version\n");
4813 goto done;
4814 }
4815
4816 if (prog->Shaders[i]->ARB_fragment_coord_conventions_enable) {
4817 prog->ARB_fragment_coord_conventions_enable = true;
4818 }
4819
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]++;
4823 }
4824
4825 /* In desktop GLSL, different shader versions may be linked together. In
4826 * GLSL ES, all shader versions must be the same.
4827 */
4828 if (prog->Shaders[0]->IsES && min_version != max_version) {
4829 linker_error(prog, "all shaders must use same shading "
4830 "language version\n");
4831 goto done;
4832 }
4833
4834 prog->data->Version = max_version;
4835 prog->IsES = prog->Shaders[0]->IsES;
4836
4837 /* Some shaders have to be linked with some other shaders present.
4838 */
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 "
4843 "vertex shader\n");
4844 goto done;
4845 }
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");
4850 goto done;
4851 }
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 "
4855 "vertex shader\n");
4856 goto done;
4857 }
4858
4859 /* Section 7.3 of the OpenGL ES 3.2 specification says:
4860 *
4861 * "Linking can fail for [...] any of the following reasons:
4862 *
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"
4866 *
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.
4871 *
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.
4876 *
4877 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4878 * spec bug.
4879 *
4880 * Do what's reasonable and always require a tess eval shader if a tess
4881 * control shader is present.
4882 */
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");
4887 goto done;
4888 }
4889
4890 if (prog->IsES) {
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");
4896 goto done;
4897 }
4898 }
4899 }
4900
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");
4906 }
4907
4908 /* Link all shaders for a particular stage and validate the result.
4909 */
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);
4915
4916 if (!prog->data->LinkStatus) {
4917 if (sh)
4918 _mesa_delete_linked_shader(ctx, sh);
4919 goto done;
4920 }
4921
4922 switch (stage) {
4923 case MESA_SHADER_VERTEX:
4924 validate_vertex_shader_executable(prog, sh, ctx);
4925 break;
4926 case MESA_SHADER_TESS_CTRL:
4927 /* nothing to be done */
4928 break;
4929 case MESA_SHADER_TESS_EVAL:
4930 validate_tess_eval_shader_executable(prog, sh, ctx);
4931 break;
4932 case MESA_SHADER_GEOMETRY:
4933 validate_geometry_shader_executable(prog, sh, ctx);
4934 break;
4935 case MESA_SHADER_FRAGMENT:
4936 validate_fragment_shader_executable(prog, sh);
4937 break;
4938 }
4939 if (!prog->data->LinkStatus) {
4940 if (sh)
4941 _mesa_delete_linked_shader(ctx, sh);
4942 goto done;
4943 }
4944
4945 prog->_LinkedShaders[stage] = sh;
4946 prog->data->linked_stages |= 1 << stage;
4947 }
4948 }
4949
4950 /* Here begins the inter-stage linking phase. Some initial validation is
4951 * performed, then locations are assigned for uniforms, attributes, and
4952 * varyings.
4953 */
4954 cross_validate_uniforms(prog);
4955 if (!prog->data->LinkStatus)
4956 goto done;
4957
4958 unsigned first, last, prev;
4959
4960 first = MESA_SHADER_STAGES;
4961 last = 0;
4962
4963 /* Determine first and last stage. */
4964 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4965 if (!prog->_LinkedShaders[i])
4966 continue;
4967 if (first == MESA_SHADER_STAGES)
4968 first = i;
4969 last = i;
4970 }
4971
4972 check_explicit_uniform_locations(ctx, prog);
4973 link_assign_subroutine_types(prog);
4974
4975 if (!prog->data->LinkStatus)
4976 goto done;
4977
4978 resize_tes_inputs(ctx, prog);
4979
4980 /* Validate the inputs of each stage with the output of the preceding
4981 * stage.
4982 */
4983 prev = first;
4984 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
4985 if (prog->_LinkedShaders[i] == NULL)
4986 continue;
4987
4988 validate_interstage_inout_blocks(prog, prog->_LinkedShaders[prev],
4989 prog->_LinkedShaders[i]);
4990 if (!prog->data->LinkStatus)
4991 goto done;
4992
4993 cross_validate_outputs_to_inputs(ctx, prog,
4994 prog->_LinkedShaders[prev],
4995 prog->_LinkedShaders[i]);
4996 if (!prog->data->LinkStatus)
4997 goto done;
4998
4999 prev = i;
5000 }
5001
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.
5006 */
5007 if (prog->SeparateShader)
5008 validate_sso_explicit_locations(ctx, prog,
5009 (gl_shader_stage) first,
5010 (gl_shader_stage) last);
5011
5012 /* Cross-validate uniform blocks between shader stages */
5013 validate_interstage_uniform_blocks(prog, prog->_LinkedShaders);
5014 if (!prog->data->LinkStatus)
5015 goto done;
5016
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]);
5020 }
5021
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.
5025 *
5026 * This rule also applies to GLSL ES 3.00.
5027 */
5028 if (max_version >= (prog->IsES ? 300 : 130)) {
5029 struct gl_linked_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
5030 if (sh) {
5031 lower_discard_flow(sh->ir);
5032 }
5033 }
5034
5035 if (prog->SeparateShader)
5036 disable_varying_optimizations_for_sso(prog);
5037
5038 /* Process UBOs */
5039 if (!interstage_cross_validate_uniform_blocks(prog, false))
5040 goto done;
5041
5042 /* Process SSBOs */
5043 if (!interstage_cross_validate_uniform_blocks(prog, true))
5044 goto done;
5045
5046 /* Do common optimization before assigning storage for attributes,
5047 * uniforms, and varyings. Later optimization could possibly make
5048 * some of that unused.
5049 */
5050 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
5051 if (prog->_LinkedShaders[i] == NULL)
5052 continue;
5053
5054 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
5055 if (!prog->data->LinkStatus)
5056 goto done;
5057
5058 if (ctx->Const.ShaderCompilerOptions[i].LowerCombinedClipCullDistance) {
5059 lower_clip_cull_distance(prog, prog->_LinkedShaders[i]);
5060 }
5061
5062 if (ctx->Const.LowerTessLevel) {
5063 lower_tess_level(prog->_LinkedShaders[i]);
5064 }
5065
5066 /* Call opts before lowering const arrays to uniforms so we can const
5067 * propagate any elements accessed directly.
5068 */
5069 linker_optimisation_loop(ctx, prog->_LinkedShaders[i]->ir, i);
5070
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);
5074
5075 propagate_invariance(prog->_LinkedShaders[i]->ir);
5076 }
5077
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.
5081 */
5082 if ((!prog->IsES && prog->data->Version < 130) ||
5083 (prog->IsES && prog->data->Version < 300)) {
5084 if (!validate_sampler_array_indexing(ctx, prog))
5085 goto done;
5086 }
5087
5088 /* Check and validate stream emissions in geometry shaders */
5089 validate_geometry_shader_emissions(ctx, prog);
5090
5091 store_fragdepth_layout(prog);
5092
5093 if(!link_varyings_and_uniforms(first, last, ctx, prog, mem_ctx))
5094 goto done;
5095
5096 /* Linking varyings can cause some extra, useless swizzles to be generated
5097 * due to packing and unpacking.
5098 */
5099 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
5100 if (prog->_LinkedShaders[i] == NULL)
5101 continue;
5102
5103 optimize_swizzles(prog->_LinkedShaders[i]->ir);
5104 }
5105
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.
5111 *
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:
5116 *
5117 * ...
5118 *
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
5122 * shader."
5123 *
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:
5126 *
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.
5131 */
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");
5138 }
5139 }
5140
5141 done:
5142 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
5143 free(shader_list[i]);
5144 if (prog->_LinkedShaders[i] == NULL)
5145 continue;
5146
5147 /* Do a final validation step to make sure that the IR wasn't
5148 * invalidated by any modifications performed after intrastage linking.
5149 */
5150 validate_ir_tree(prog->_LinkedShaders[i]->ir);
5151
5152 /* Retain any live IR, but trash the rest. */
5153 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
5154
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
5158 * pointer to NULL.
5159 */
5160 delete prog->_LinkedShaders[i]->symbols;
5161 prog->_LinkedShaders[i]->symbols = NULL;
5162 }
5163
5164 ralloc_free(mem_ctx);
5165 }