mesa: include mtypes.h less
[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
1982 linked_shader->Program->sh.fs.BlendSupport |= shader->BlendSupport;
1983 }
1984 }
1985
1986 /**
1987 * Performs the cross-validation of geometry shader max_vertices and
1988 * primitive type layout qualifiers for the attached geometry shaders,
1989 * and propagates them to the linked GS and linked shader program.
1990 */
1991 static void
1992 link_gs_inout_layout_qualifiers(struct gl_shader_program *prog,
1993 struct gl_program *gl_prog,
1994 struct gl_shader **shader_list,
1995 unsigned num_shaders)
1996 {
1997 /* No in/out qualifiers defined for anything but GLSL 1.50+
1998 * geometry shaders so far.
1999 */
2000 if (gl_prog->info.stage != MESA_SHADER_GEOMETRY ||
2001 prog->data->Version < 150)
2002 return;
2003
2004 int vertices_out = -1;
2005
2006 gl_prog->info.gs.invocations = 0;
2007 gl_prog->info.gs.input_primitive = PRIM_UNKNOWN;
2008 gl_prog->info.gs.output_primitive = PRIM_UNKNOWN;
2009
2010 /* From the GLSL 1.50 spec, page 46:
2011 *
2012 * "All geometry shader output layout declarations in a program
2013 * must declare the same layout and same value for
2014 * max_vertices. There must be at least one geometry output
2015 * layout declaration somewhere in a program, but not all
2016 * geometry shaders (compilation units) are required to
2017 * declare it."
2018 */
2019
2020 for (unsigned i = 0; i < num_shaders; i++) {
2021 struct gl_shader *shader = shader_list[i];
2022
2023 if (shader->info.Geom.InputType != PRIM_UNKNOWN) {
2024 if (gl_prog->info.gs.input_primitive != PRIM_UNKNOWN &&
2025 gl_prog->info.gs.input_primitive !=
2026 shader->info.Geom.InputType) {
2027 linker_error(prog, "geometry shader defined with conflicting "
2028 "input types\n");
2029 return;
2030 }
2031 gl_prog->info.gs.input_primitive = shader->info.Geom.InputType;
2032 }
2033
2034 if (shader->info.Geom.OutputType != PRIM_UNKNOWN) {
2035 if (gl_prog->info.gs.output_primitive != PRIM_UNKNOWN &&
2036 gl_prog->info.gs.output_primitive !=
2037 shader->info.Geom.OutputType) {
2038 linker_error(prog, "geometry shader defined with conflicting "
2039 "output types\n");
2040 return;
2041 }
2042 gl_prog->info.gs.output_primitive = shader->info.Geom.OutputType;
2043 }
2044
2045 if (shader->info.Geom.VerticesOut != -1) {
2046 if (vertices_out != -1 &&
2047 vertices_out != shader->info.Geom.VerticesOut) {
2048 linker_error(prog, "geometry shader defined with conflicting "
2049 "output vertex count (%d and %d)\n",
2050 vertices_out, shader->info.Geom.VerticesOut);
2051 return;
2052 }
2053 vertices_out = shader->info.Geom.VerticesOut;
2054 }
2055
2056 if (shader->info.Geom.Invocations != 0) {
2057 if (gl_prog->info.gs.invocations != 0 &&
2058 gl_prog->info.gs.invocations !=
2059 (unsigned) shader->info.Geom.Invocations) {
2060 linker_error(prog, "geometry shader defined with conflicting "
2061 "invocation count (%d and %d)\n",
2062 gl_prog->info.gs.invocations,
2063 shader->info.Geom.Invocations);
2064 return;
2065 }
2066 gl_prog->info.gs.invocations = shader->info.Geom.Invocations;
2067 }
2068 }
2069
2070 /* Just do the intrastage -> interstage propagation right now,
2071 * since we already know we're in the right type of shader program
2072 * for doing it.
2073 */
2074 if (gl_prog->info.gs.input_primitive == PRIM_UNKNOWN) {
2075 linker_error(prog,
2076 "geometry shader didn't declare primitive input type\n");
2077 return;
2078 }
2079
2080 if (gl_prog->info.gs.output_primitive == PRIM_UNKNOWN) {
2081 linker_error(prog,
2082 "geometry shader didn't declare primitive output type\n");
2083 return;
2084 }
2085
2086 if (vertices_out == -1) {
2087 linker_error(prog,
2088 "geometry shader didn't declare max_vertices\n");
2089 return;
2090 } else {
2091 gl_prog->info.gs.vertices_out = vertices_out;
2092 }
2093
2094 if (gl_prog->info.gs.invocations == 0)
2095 gl_prog->info.gs.invocations = 1;
2096 }
2097
2098
2099 /**
2100 * Perform cross-validation of compute shader local_size_{x,y,z} layout
2101 * qualifiers for the attached compute shaders, and propagate them to the
2102 * linked CS and linked shader program.
2103 */
2104 static void
2105 link_cs_input_layout_qualifiers(struct gl_shader_program *prog,
2106 struct gl_program *gl_prog,
2107 struct gl_shader **shader_list,
2108 unsigned num_shaders)
2109 {
2110 /* This function is called for all shader stages, but it only has an effect
2111 * for compute shaders.
2112 */
2113 if (gl_prog->info.stage != MESA_SHADER_COMPUTE)
2114 return;
2115
2116 for (int i = 0; i < 3; i++)
2117 gl_prog->info.cs.local_size[i] = 0;
2118
2119 gl_prog->info.cs.local_size_variable = false;
2120
2121 /* From the ARB_compute_shader spec, in the section describing local size
2122 * declarations:
2123 *
2124 * If multiple compute shaders attached to a single program object
2125 * declare local work-group size, the declarations must be identical;
2126 * otherwise a link-time error results. Furthermore, if a program
2127 * object contains any compute shaders, at least one must contain an
2128 * input layout qualifier specifying the local work sizes of the
2129 * program, or a link-time error will occur.
2130 */
2131 for (unsigned sh = 0; sh < num_shaders; sh++) {
2132 struct gl_shader *shader = shader_list[sh];
2133
2134 if (shader->info.Comp.LocalSize[0] != 0) {
2135 if (gl_prog->info.cs.local_size[0] != 0) {
2136 for (int i = 0; i < 3; i++) {
2137 if (gl_prog->info.cs.local_size[i] !=
2138 shader->info.Comp.LocalSize[i]) {
2139 linker_error(prog, "compute shader defined with conflicting "
2140 "local sizes\n");
2141 return;
2142 }
2143 }
2144 }
2145 for (int i = 0; i < 3; i++) {
2146 gl_prog->info.cs.local_size[i] =
2147 shader->info.Comp.LocalSize[i];
2148 }
2149 } else if (shader->info.Comp.LocalSizeVariable) {
2150 if (gl_prog->info.cs.local_size[0] != 0) {
2151 /* The ARB_compute_variable_group_size spec says:
2152 *
2153 * If one compute shader attached to a program declares a
2154 * variable local group size and a second compute shader
2155 * attached to the same program declares a fixed local group
2156 * size, a link-time error results.
2157 */
2158 linker_error(prog, "compute shader defined with both fixed and "
2159 "variable local group size\n");
2160 return;
2161 }
2162 gl_prog->info.cs.local_size_variable = true;
2163 }
2164 }
2165
2166 /* Just do the intrastage -> interstage propagation right now,
2167 * since we already know we're in the right type of shader program
2168 * for doing it.
2169 */
2170 if (gl_prog->info.cs.local_size[0] == 0 &&
2171 !gl_prog->info.cs.local_size_variable) {
2172 linker_error(prog, "compute shader must contain a fixed or a variable "
2173 "local group size\n");
2174 return;
2175 }
2176 }
2177
2178
2179 /**
2180 * Combine a group of shaders for a single stage to generate a linked shader
2181 *
2182 * \note
2183 * If this function is supplied a single shader, it is cloned, and the new
2184 * shader is returned.
2185 */
2186 struct gl_linked_shader *
2187 link_intrastage_shaders(void *mem_ctx,
2188 struct gl_context *ctx,
2189 struct gl_shader_program *prog,
2190 struct gl_shader **shader_list,
2191 unsigned num_shaders,
2192 bool allow_missing_main)
2193 {
2194 struct gl_uniform_block *ubo_blocks = NULL;
2195 struct gl_uniform_block *ssbo_blocks = NULL;
2196 unsigned num_ubo_blocks = 0;
2197 unsigned num_ssbo_blocks = 0;
2198
2199 /* Check that global variables defined in multiple shaders are consistent.
2200 */
2201 glsl_symbol_table variables;
2202 for (unsigned i = 0; i < num_shaders; i++) {
2203 if (shader_list[i] == NULL)
2204 continue;
2205 cross_validate_globals(prog, shader_list[i]->ir, &variables, false);
2206 }
2207
2208 if (!prog->data->LinkStatus)
2209 return NULL;
2210
2211 /* Check that interface blocks defined in multiple shaders are consistent.
2212 */
2213 validate_intrastage_interface_blocks(prog, (const gl_shader **)shader_list,
2214 num_shaders);
2215 if (!prog->data->LinkStatus)
2216 return NULL;
2217
2218 /* Check that there is only a single definition of each function signature
2219 * across all shaders.
2220 */
2221 for (unsigned i = 0; i < (num_shaders - 1); i++) {
2222 foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
2223 ir_function *const f = node->as_function();
2224
2225 if (f == NULL)
2226 continue;
2227
2228 for (unsigned j = i + 1; j < num_shaders; j++) {
2229 ir_function *const other =
2230 shader_list[j]->symbols->get_function(f->name);
2231
2232 /* If the other shader has no function (and therefore no function
2233 * signatures) with the same name, skip to the next shader.
2234 */
2235 if (other == NULL)
2236 continue;
2237
2238 foreach_in_list(ir_function_signature, sig, &f->signatures) {
2239 if (!sig->is_defined)
2240 continue;
2241
2242 ir_function_signature *other_sig =
2243 other->exact_matching_signature(NULL, &sig->parameters);
2244
2245 if (other_sig != NULL && other_sig->is_defined) {
2246 linker_error(prog, "function `%s' is multiply defined\n",
2247 f->name);
2248 return NULL;
2249 }
2250 }
2251 }
2252 }
2253 }
2254
2255 /* Find the shader that defines main, and make a clone of it.
2256 *
2257 * Starting with the clone, search for undefined references. If one is
2258 * found, find the shader that defines it. Clone the reference and add
2259 * it to the shader. Repeat until there are no undefined references or
2260 * until a reference cannot be resolved.
2261 */
2262 gl_shader *main = NULL;
2263 for (unsigned i = 0; i < num_shaders; i++) {
2264 if (_mesa_get_main_function_signature(shader_list[i]->symbols)) {
2265 main = shader_list[i];
2266 break;
2267 }
2268 }
2269
2270 if (main == NULL && allow_missing_main)
2271 main = shader_list[0];
2272
2273 if (main == NULL) {
2274 linker_error(prog, "%s shader lacks `main'\n",
2275 _mesa_shader_stage_to_string(shader_list[0]->Stage));
2276 return NULL;
2277 }
2278
2279 gl_linked_shader *linked = rzalloc(NULL, struct gl_linked_shader);
2280 linked->Stage = shader_list[0]->Stage;
2281
2282 /* Create program and attach it to the linked shader */
2283 struct gl_program *gl_prog =
2284 ctx->Driver.NewProgram(ctx,
2285 _mesa_shader_stage_to_program(shader_list[0]->Stage),
2286 prog->Name, false);
2287 if (!gl_prog) {
2288 prog->data->LinkStatus = LINKING_FAILURE;
2289 _mesa_delete_linked_shader(ctx, linked);
2290 return NULL;
2291 }
2292
2293 _mesa_reference_shader_program_data(ctx, &gl_prog->sh.data, prog->data);
2294
2295 /* Don't use _mesa_reference_program() just take ownership */
2296 linked->Program = gl_prog;
2297
2298 linked->ir = new(linked) exec_list;
2299 clone_ir_list(mem_ctx, linked->ir, main->ir);
2300
2301 link_fs_inout_layout_qualifiers(prog, linked, shader_list, num_shaders);
2302 link_tcs_out_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2303 link_tes_in_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2304 link_gs_inout_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2305 link_cs_input_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2306
2307 if (linked->Stage != MESA_SHADER_FRAGMENT)
2308 link_xfb_stride_layout_qualifiers(ctx, prog, shader_list, num_shaders);
2309
2310 link_bindless_layout_qualifiers(prog, shader_list, num_shaders);
2311
2312 populate_symbol_table(linked, shader_list[0]->symbols);
2313
2314 /* The pointer to the main function in the final linked shader (i.e., the
2315 * copy of the original shader that contained the main function).
2316 */
2317 ir_function_signature *const main_sig =
2318 _mesa_get_main_function_signature(linked->symbols);
2319
2320 /* Move any instructions other than variable declarations or function
2321 * declarations into main.
2322 */
2323 if (main_sig != NULL) {
2324 exec_node *insertion_point =
2325 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
2326 linked);
2327
2328 for (unsigned i = 0; i < num_shaders; i++) {
2329 if (shader_list[i] == main)
2330 continue;
2331
2332 insertion_point = move_non_declarations(shader_list[i]->ir,
2333 insertion_point, true, linked);
2334 }
2335 }
2336
2337 if (!link_function_calls(prog, linked, shader_list, num_shaders)) {
2338 _mesa_delete_linked_shader(ctx, linked);
2339 return NULL;
2340 }
2341
2342 /* Make a pass over all variable declarations to ensure that arrays with
2343 * unspecified sizes have a size specified. The size is inferred from the
2344 * max_array_access field.
2345 */
2346 array_sizing_visitor v;
2347 v.run(linked->ir);
2348 v.fixup_unnamed_interface_types();
2349
2350 /* Link up uniform blocks defined within this stage. */
2351 link_uniform_blocks(mem_ctx, ctx, prog, linked, &ubo_blocks,
2352 &num_ubo_blocks, &ssbo_blocks, &num_ssbo_blocks);
2353
2354 if (!prog->data->LinkStatus) {
2355 _mesa_delete_linked_shader(ctx, linked);
2356 return NULL;
2357 }
2358
2359 /* Copy ubo blocks to linked shader list */
2360 linked->Program->sh.UniformBlocks =
2361 ralloc_array(linked, gl_uniform_block *, num_ubo_blocks);
2362 ralloc_steal(linked, ubo_blocks);
2363 for (unsigned i = 0; i < num_ubo_blocks; i++) {
2364 linked->Program->sh.UniformBlocks[i] = &ubo_blocks[i];
2365 }
2366 linked->Program->info.num_ubos = num_ubo_blocks;
2367
2368 /* Copy ssbo blocks to linked shader list */
2369 linked->Program->sh.ShaderStorageBlocks =
2370 ralloc_array(linked, gl_uniform_block *, num_ssbo_blocks);
2371 ralloc_steal(linked, ssbo_blocks);
2372 for (unsigned i = 0; i < num_ssbo_blocks; i++) {
2373 linked->Program->sh.ShaderStorageBlocks[i] = &ssbo_blocks[i];
2374 }
2375 linked->Program->info.num_ssbos = num_ssbo_blocks;
2376
2377 /* At this point linked should contain all of the linked IR, so
2378 * validate it to make sure nothing went wrong.
2379 */
2380 validate_ir_tree(linked->ir);
2381
2382 /* Set the size of geometry shader input arrays */
2383 if (linked->Stage == MESA_SHADER_GEOMETRY) {
2384 unsigned num_vertices =
2385 vertices_per_prim(gl_prog->info.gs.input_primitive);
2386 array_resize_visitor input_resize_visitor(num_vertices, prog,
2387 MESA_SHADER_GEOMETRY);
2388 foreach_in_list(ir_instruction, ir, linked->ir) {
2389 ir->accept(&input_resize_visitor);
2390 }
2391 }
2392
2393 if (ctx->Const.VertexID_is_zero_based)
2394 lower_vertex_id(linked);
2395
2396 if (ctx->Const.LowerCsDerivedVariables)
2397 lower_cs_derived(linked);
2398
2399 #ifdef DEBUG
2400 /* Compute the source checksum. */
2401 linked->SourceChecksum = 0;
2402 for (unsigned i = 0; i < num_shaders; i++) {
2403 if (shader_list[i] == NULL)
2404 continue;
2405 linked->SourceChecksum ^= shader_list[i]->SourceChecksum;
2406 }
2407 #endif
2408
2409 return linked;
2410 }
2411
2412 /**
2413 * Update the sizes of linked shader uniform arrays to the maximum
2414 * array index used.
2415 *
2416 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2417 *
2418 * If one or more elements of an array are active,
2419 * GetActiveUniform will return the name of the array in name,
2420 * subject to the restrictions listed above. The type of the array
2421 * is returned in type. The size parameter contains the highest
2422 * array element index used, plus one. The compiler or linker
2423 * determines the highest index used. There will be only one
2424 * active uniform reported by the GL per uniform array.
2425
2426 */
2427 static void
2428 update_array_sizes(struct gl_shader_program *prog)
2429 {
2430 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2431 if (prog->_LinkedShaders[i] == NULL)
2432 continue;
2433
2434 bool types_were_updated = false;
2435
2436 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
2437 ir_variable *const var = node->as_variable();
2438
2439 if ((var == NULL) || (var->data.mode != ir_var_uniform) ||
2440 !var->type->is_array())
2441 continue;
2442
2443 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2444 * will not be eliminated. Since we always do std140, just
2445 * don't resize arrays in UBOs.
2446 *
2447 * Atomic counters are supposed to get deterministic
2448 * locations assigned based on the declaration ordering and
2449 * sizes, array compaction would mess that up.
2450 *
2451 * Subroutine uniforms are not removed.
2452 */
2453 if (var->is_in_buffer_block() || var->type->contains_atomic() ||
2454 var->type->contains_subroutine() || var->constant_initializer)
2455 continue;
2456
2457 int size = var->data.max_array_access;
2458 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
2459 if (prog->_LinkedShaders[j] == NULL)
2460 continue;
2461
2462 foreach_in_list(ir_instruction, node2, prog->_LinkedShaders[j]->ir) {
2463 ir_variable *other_var = node2->as_variable();
2464 if (!other_var)
2465 continue;
2466
2467 if (strcmp(var->name, other_var->name) == 0 &&
2468 other_var->data.max_array_access > size) {
2469 size = other_var->data.max_array_access;
2470 }
2471 }
2472 }
2473
2474 if (size + 1 != (int)var->type->length) {
2475 /* If this is a built-in uniform (i.e., it's backed by some
2476 * fixed-function state), adjust the number of state slots to
2477 * match the new array size. The number of slots per array entry
2478 * is not known. It seems safe to assume that the total number of
2479 * slots is an integer multiple of the number of array elements.
2480 * Determine the number of slots per array element by dividing by
2481 * the old (total) size.
2482 */
2483 const unsigned num_slots = var->get_num_state_slots();
2484 if (num_slots > 0) {
2485 var->set_num_state_slots((size + 1)
2486 * (num_slots / var->type->length));
2487 }
2488
2489 var->type = glsl_type::get_array_instance(var->type->fields.array,
2490 size + 1);
2491 types_were_updated = true;
2492 }
2493 }
2494
2495 /* Update the types of dereferences in case we changed any. */
2496 if (types_were_updated) {
2497 deref_type_updater v;
2498 v.run(prog->_LinkedShaders[i]->ir);
2499 }
2500 }
2501 }
2502
2503 /**
2504 * Resize tessellation evaluation per-vertex inputs to the size of
2505 * tessellation control per-vertex outputs.
2506 */
2507 static void
2508 resize_tes_inputs(struct gl_context *ctx,
2509 struct gl_shader_program *prog)
2510 {
2511 if (prog->_LinkedShaders[MESA_SHADER_TESS_EVAL] == NULL)
2512 return;
2513
2514 gl_linked_shader *const tcs = prog->_LinkedShaders[MESA_SHADER_TESS_CTRL];
2515 gl_linked_shader *const tes = prog->_LinkedShaders[MESA_SHADER_TESS_EVAL];
2516
2517 /* If no control shader is present, then the TES inputs are statically
2518 * sized to MaxPatchVertices; the actual size of the arrays won't be
2519 * known until draw time.
2520 */
2521 const int num_vertices = tcs
2522 ? tcs->Program->info.tess.tcs_vertices_out
2523 : ctx->Const.MaxPatchVertices;
2524
2525 array_resize_visitor input_resize_visitor(num_vertices, prog,
2526 MESA_SHADER_TESS_EVAL);
2527 foreach_in_list(ir_instruction, ir, tes->ir) {
2528 ir->accept(&input_resize_visitor);
2529 }
2530
2531 if (tcs) {
2532 /* Convert the gl_PatchVerticesIn system value into a constant, since
2533 * the value is known at this point.
2534 */
2535 foreach_in_list(ir_instruction, ir, tes->ir) {
2536 ir_variable *var = ir->as_variable();
2537 if (var && var->data.mode == ir_var_system_value &&
2538 var->data.location == SYSTEM_VALUE_VERTICES_IN) {
2539 void *mem_ctx = ralloc_parent(var);
2540 var->data.location = 0;
2541 var->data.explicit_location = false;
2542 var->data.mode = ir_var_auto;
2543 var->constant_value = new(mem_ctx) ir_constant(num_vertices);
2544 }
2545 }
2546 }
2547 }
2548
2549 /**
2550 * Find a contiguous set of available bits in a bitmask.
2551 *
2552 * \param used_mask Bits representing used (1) and unused (0) locations
2553 * \param needed_count Number of contiguous bits needed.
2554 *
2555 * \return
2556 * Base location of the available bits on success or -1 on failure.
2557 */
2558 static int
2559 find_available_slots(unsigned used_mask, unsigned needed_count)
2560 {
2561 unsigned needed_mask = (1 << needed_count) - 1;
2562 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
2563
2564 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2565 * cannot optimize possibly infinite loops" for the loop below.
2566 */
2567 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
2568 return -1;
2569
2570 for (int i = 0; i <= max_bit_to_test; i++) {
2571 if ((needed_mask & ~used_mask) == needed_mask)
2572 return i;
2573
2574 needed_mask <<= 1;
2575 }
2576
2577 return -1;
2578 }
2579
2580
2581 #define SAFE_MASK_FROM_INDEX(i) (((i) >= 32) ? ~0 : ((1 << (i)) - 1))
2582
2583 /**
2584 * Assign locations for either VS inputs or FS outputs
2585 *
2586 * \param mem_ctx Temporary ralloc context used for linking
2587 * \param prog Shader program whose variables need locations assigned
2588 * \param constants Driver specific constant values for the program.
2589 * \param target_index Selector for the program target to receive location
2590 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2591 * \c MESA_SHADER_FRAGMENT.
2592 *
2593 * \return
2594 * If locations are successfully assigned, true is returned. Otherwise an
2595 * error is emitted to the shader link log and false is returned.
2596 */
2597 static bool
2598 assign_attribute_or_color_locations(void *mem_ctx,
2599 gl_shader_program *prog,
2600 struct gl_constants *constants,
2601 unsigned target_index)
2602 {
2603 /* Maximum number of generic locations. This corresponds to either the
2604 * maximum number of draw buffers or the maximum number of generic
2605 * attributes.
2606 */
2607 unsigned max_index = (target_index == MESA_SHADER_VERTEX) ?
2608 constants->Program[target_index].MaxAttribs :
2609 MAX2(constants->MaxDrawBuffers, constants->MaxDualSourceDrawBuffers);
2610
2611 /* Mark invalid locations as being used.
2612 */
2613 unsigned used_locations = ~SAFE_MASK_FROM_INDEX(max_index);
2614 unsigned double_storage_locations = 0;
2615
2616 assert((target_index == MESA_SHADER_VERTEX)
2617 || (target_index == MESA_SHADER_FRAGMENT));
2618
2619 gl_linked_shader *const sh = prog->_LinkedShaders[target_index];
2620 if (sh == NULL)
2621 return true;
2622
2623 /* Operate in a total of four passes.
2624 *
2625 * 1. Invalidate the location assignments for all vertex shader inputs.
2626 *
2627 * 2. Assign locations for inputs that have user-defined (via
2628 * glBindVertexAttribLocation) locations and outputs that have
2629 * user-defined locations (via glBindFragDataLocation).
2630 *
2631 * 3. Sort the attributes without assigned locations by number of slots
2632 * required in decreasing order. Fragmentation caused by attribute
2633 * locations assigned by the application may prevent large attributes
2634 * from having enough contiguous space.
2635 *
2636 * 4. Assign locations to any inputs without assigned locations.
2637 */
2638
2639 const int generic_base = (target_index == MESA_SHADER_VERTEX)
2640 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
2641
2642 const enum ir_variable_mode direction =
2643 (target_index == MESA_SHADER_VERTEX)
2644 ? ir_var_shader_in : ir_var_shader_out;
2645
2646
2647 /* Temporary storage for the set of attributes that need locations assigned.
2648 */
2649 struct temp_attr {
2650 unsigned slots;
2651 ir_variable *var;
2652
2653 /* Used below in the call to qsort. */
2654 static int compare(const void *a, const void *b)
2655 {
2656 const temp_attr *const l = (const temp_attr *) a;
2657 const temp_attr *const r = (const temp_attr *) b;
2658
2659 /* Reversed because we want a descending order sort below. */
2660 return r->slots - l->slots;
2661 }
2662 } to_assign[32];
2663 assert(max_index <= 32);
2664
2665 /* Temporary array for the set of attributes that have locations assigned,
2666 * for the purpose of checking overlapping slots/components of (non-ES)
2667 * fragment shader outputs.
2668 */
2669 ir_variable *assigned[12 * 4]; /* (max # of FS outputs) * # components */
2670 unsigned assigned_attr = 0;
2671
2672 unsigned num_attr = 0;
2673
2674 foreach_in_list(ir_instruction, node, sh->ir) {
2675 ir_variable *const var = node->as_variable();
2676
2677 if ((var == NULL) || (var->data.mode != (unsigned) direction))
2678 continue;
2679
2680 if (var->data.explicit_location) {
2681 var->data.is_unmatched_generic_inout = 0;
2682 if ((var->data.location >= (int)(max_index + generic_base))
2683 || (var->data.location < 0)) {
2684 linker_error(prog,
2685 "invalid explicit location %d specified for `%s'\n",
2686 (var->data.location < 0)
2687 ? var->data.location
2688 : var->data.location - generic_base,
2689 var->name);
2690 return false;
2691 }
2692 } else if (target_index == MESA_SHADER_VERTEX) {
2693 unsigned binding;
2694
2695 if (prog->AttributeBindings->get(binding, var->name)) {
2696 assert(binding >= VERT_ATTRIB_GENERIC0);
2697 var->data.location = binding;
2698 var->data.is_unmatched_generic_inout = 0;
2699 }
2700 } else if (target_index == MESA_SHADER_FRAGMENT) {
2701 unsigned binding;
2702 unsigned index;
2703 const char *name = var->name;
2704 const glsl_type *type = var->type;
2705
2706 while (type) {
2707 /* Check if there's a binding for the variable name */
2708 if (prog->FragDataBindings->get(binding, name)) {
2709 assert(binding >= FRAG_RESULT_DATA0);
2710 var->data.location = binding;
2711 var->data.is_unmatched_generic_inout = 0;
2712
2713 if (prog->FragDataIndexBindings->get(index, name)) {
2714 var->data.index = index;
2715 }
2716 break;
2717 }
2718
2719 /* If not, but it's an array type, look for name[0] */
2720 if (type->is_array()) {
2721 name = ralloc_asprintf(mem_ctx, "%s[0]", name);
2722 type = type->fields.array;
2723 continue;
2724 }
2725
2726 break;
2727 }
2728 }
2729
2730 if (strcmp(var->name, "gl_LastFragData") == 0)
2731 continue;
2732
2733 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2734 *
2735 * "Output binding assignments will cause LinkProgram to fail:
2736 * ...
2737 * If the program has an active output assigned to a location greater
2738 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2739 * an active output assigned an index greater than or equal to one;"
2740 */
2741 if (target_index == MESA_SHADER_FRAGMENT && var->data.index >= 1 &&
2742 var->data.location - generic_base >=
2743 (int) constants->MaxDualSourceDrawBuffers) {
2744 linker_error(prog,
2745 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2746 "with index %u for %s\n",
2747 var->data.location - generic_base, var->data.index,
2748 var->name);
2749 return false;
2750 }
2751
2752 const unsigned slots = var->type->count_attribute_slots(target_index == MESA_SHADER_VERTEX);
2753
2754 /* If the variable is not a built-in and has a location statically
2755 * assigned in the shader (presumably via a layout qualifier), make sure
2756 * that it doesn't collide with other assigned locations. Otherwise,
2757 * add it to the list of variables that need linker-assigned locations.
2758 */
2759 if (var->data.location != -1) {
2760 if (var->data.location >= generic_base && var->data.index < 1) {
2761 /* From page 61 of the OpenGL 4.0 spec:
2762 *
2763 * "LinkProgram will fail if the attribute bindings assigned
2764 * by BindAttribLocation do not leave not enough space to
2765 * assign a location for an active matrix attribute or an
2766 * active attribute array, both of which require multiple
2767 * contiguous generic attributes."
2768 *
2769 * I think above text prohibits the aliasing of explicit and
2770 * automatic assignments. But, aliasing is allowed in manual
2771 * assignments of attribute locations. See below comments for
2772 * the details.
2773 *
2774 * From OpenGL 4.0 spec, page 61:
2775 *
2776 * "It is possible for an application to bind more than one
2777 * attribute name to the same location. This is referred to as
2778 * aliasing. This will only work if only one of the aliased
2779 * attributes is active in the executable program, or if no
2780 * path through the shader consumes more than one attribute of
2781 * a set of attributes aliased to the same location. A link
2782 * error can occur if the linker determines that every path
2783 * through the shader consumes multiple aliased attributes,
2784 * but implementations are not required to generate an error
2785 * in this case."
2786 *
2787 * From GLSL 4.30 spec, page 54:
2788 *
2789 * "A program will fail to link if any two non-vertex shader
2790 * input variables are assigned to the same location. For
2791 * vertex shaders, multiple input variables may be assigned
2792 * to the same location using either layout qualifiers or via
2793 * the OpenGL API. However, such aliasing is intended only to
2794 * support vertex shaders where each execution path accesses
2795 * at most one input per each location. Implementations are
2796 * permitted, but not required, to generate link-time errors
2797 * if they detect that every path through the vertex shader
2798 * executable accesses multiple inputs assigned to any single
2799 * location. For all shader types, a program will fail to link
2800 * if explicit location assignments leave the linker unable
2801 * to find space for other variables without explicit
2802 * assignments."
2803 *
2804 * From OpenGL ES 3.0 spec, page 56:
2805 *
2806 * "Binding more than one attribute name to the same location
2807 * is referred to as aliasing, and is not permitted in OpenGL
2808 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2809 * fail when this condition exists. However, aliasing is
2810 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2811 * This will only work if only one of the aliased attributes
2812 * is active in the executable program, or if no path through
2813 * the shader consumes more than one attribute of a set of
2814 * attributes aliased to the same location. A link error can
2815 * occur if the linker determines that every path through the
2816 * shader consumes multiple aliased attributes, but implemen-
2817 * tations are not required to generate an error in this case."
2818 *
2819 * After looking at above references from OpenGL, OpenGL ES and
2820 * GLSL specifications, we allow aliasing of vertex input variables
2821 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2822 *
2823 * NOTE: This is not required by the spec but its worth mentioning
2824 * here that we're not doing anything to make sure that no path
2825 * through the vertex shader executable accesses multiple inputs
2826 * assigned to any single location.
2827 */
2828
2829 /* Mask representing the contiguous slots that will be used by
2830 * this attribute.
2831 */
2832 const unsigned attr = var->data.location - generic_base;
2833 const unsigned use_mask = (1 << slots) - 1;
2834 const char *const string = (target_index == MESA_SHADER_VERTEX)
2835 ? "vertex shader input" : "fragment shader output";
2836
2837 /* Generate a link error if the requested locations for this
2838 * attribute exceed the maximum allowed attribute location.
2839 */
2840 if (attr + slots > max_index) {
2841 linker_error(prog,
2842 "insufficient contiguous locations "
2843 "available for %s `%s' %d %d %d\n", string,
2844 var->name, used_locations, use_mask, attr);
2845 return false;
2846 }
2847
2848 /* Generate a link error if the set of bits requested for this
2849 * attribute overlaps any previously allocated bits.
2850 */
2851 if ((~(use_mask << attr) & used_locations) != used_locations) {
2852 if (target_index == MESA_SHADER_FRAGMENT && !prog->IsES) {
2853 /* From section 4.4.2 (Output Layout Qualifiers) of the GLSL
2854 * 4.40 spec:
2855 *
2856 * "Additionally, for fragment shader outputs, if two
2857 * variables are placed within the same location, they
2858 * must have the same underlying type (floating-point or
2859 * integer). No component aliasing of output variables or
2860 * members is allowed.
2861 */
2862 for (unsigned i = 0; i < assigned_attr; i++) {
2863 unsigned assigned_slots =
2864 assigned[i]->type->count_attribute_slots(false);
2865 unsigned assig_attr =
2866 assigned[i]->data.location - generic_base;
2867 unsigned assigned_use_mask = (1 << assigned_slots) - 1;
2868
2869 if ((assigned_use_mask << assig_attr) &
2870 (use_mask << attr)) {
2871
2872 const glsl_type *assigned_type =
2873 assigned[i]->type->without_array();
2874 const glsl_type *type = var->type->without_array();
2875 if (assigned_type->base_type != type->base_type) {
2876 linker_error(prog, "types do not match for aliased"
2877 " %ss %s and %s\n", string,
2878 assigned[i]->name, var->name);
2879 return false;
2880 }
2881
2882 unsigned assigned_component_mask =
2883 ((1 << assigned_type->vector_elements) - 1) <<
2884 assigned[i]->data.location_frac;
2885 unsigned component_mask =
2886 ((1 << type->vector_elements) - 1) <<
2887 var->data.location_frac;
2888 if (assigned_component_mask & component_mask) {
2889 linker_error(prog, "overlapping component is "
2890 "assigned to %ss %s and %s "
2891 "(component=%d)\n",
2892 string, assigned[i]->name, var->name,
2893 var->data.location_frac);
2894 return false;
2895 }
2896 }
2897 }
2898 } else if (target_index == MESA_SHADER_FRAGMENT ||
2899 (prog->IsES && prog->data->Version >= 300)) {
2900 linker_error(prog, "overlapping location is assigned "
2901 "to %s `%s' %d %d %d\n", string, var->name,
2902 used_locations, use_mask, attr);
2903 return false;
2904 } else {
2905 linker_warning(prog, "overlapping location is assigned "
2906 "to %s `%s' %d %d %d\n", string, var->name,
2907 used_locations, use_mask, attr);
2908 }
2909 }
2910
2911 if (target_index == MESA_SHADER_FRAGMENT && !prog->IsES) {
2912 /* Only track assigned variables for non-ES fragment shaders
2913 * to avoid overflowing the array.
2914 *
2915 * At most one variable per fragment output component should
2916 * reach this.
2917 */
2918 assert(assigned_attr < ARRAY_SIZE(assigned));
2919 assigned[assigned_attr] = var;
2920 assigned_attr++;
2921 }
2922
2923 used_locations |= (use_mask << attr);
2924
2925 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2926 *
2927 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2928 * active attribute variables may fail to link, unless
2929 * device-dependent optimizations are able to make the program
2930 * fit within available hardware resources. For the purposes
2931 * of this test, attribute variables of the type dvec3, dvec4,
2932 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2933 * count as consuming twice as many attributes as equivalent
2934 * single-precision types. While these types use the same number
2935 * of generic attributes as their single-precision equivalents,
2936 * implementations are permitted to consume two single-precision
2937 * vectors of internal storage for each three- or four-component
2938 * double-precision vector."
2939 *
2940 * Mark this attribute slot as taking up twice as much space
2941 * so we can count it properly against limits. According to
2942 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2943 * is optional behavior, but it seems preferable.
2944 */
2945 if (var->type->without_array()->is_dual_slot())
2946 double_storage_locations |= (use_mask << attr);
2947 }
2948
2949 continue;
2950 }
2951
2952 if (num_attr >= max_index) {
2953 linker_error(prog, "too many %s (max %u)",
2954 target_index == MESA_SHADER_VERTEX ?
2955 "vertex shader inputs" : "fragment shader outputs",
2956 max_index);
2957 return false;
2958 }
2959 to_assign[num_attr].slots = slots;
2960 to_assign[num_attr].var = var;
2961 num_attr++;
2962 }
2963
2964 if (target_index == MESA_SHADER_VERTEX) {
2965 unsigned total_attribs_size =
2966 _mesa_bitcount(used_locations & SAFE_MASK_FROM_INDEX(max_index)) +
2967 _mesa_bitcount(double_storage_locations);
2968 if (total_attribs_size > max_index) {
2969 linker_error(prog,
2970 "attempt to use %d vertex attribute slots only %d available ",
2971 total_attribs_size, max_index);
2972 return false;
2973 }
2974 }
2975
2976 /* If all of the attributes were assigned locations by the application (or
2977 * are built-in attributes with fixed locations), return early. This should
2978 * be the common case.
2979 */
2980 if (num_attr == 0)
2981 return true;
2982
2983 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
2984
2985 if (target_index == MESA_SHADER_VERTEX) {
2986 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2987 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2988 * reserved to prevent it from being automatically allocated below.
2989 */
2990 find_deref_visitor find("gl_Vertex");
2991 find.run(sh->ir);
2992 if (find.variable_found())
2993 used_locations |= (1 << 0);
2994 }
2995
2996 for (unsigned i = 0; i < num_attr; i++) {
2997 /* Mask representing the contiguous slots that will be used by this
2998 * attribute.
2999 */
3000 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
3001
3002 int location = find_available_slots(used_locations, to_assign[i].slots);
3003
3004 if (location < 0) {
3005 const char *const string = (target_index == MESA_SHADER_VERTEX)
3006 ? "vertex shader input" : "fragment shader output";
3007
3008 linker_error(prog,
3009 "insufficient contiguous locations "
3010 "available for %s `%s'\n",
3011 string, to_assign[i].var->name);
3012 return false;
3013 }
3014
3015 to_assign[i].var->data.location = generic_base + location;
3016 to_assign[i].var->data.is_unmatched_generic_inout = 0;
3017 used_locations |= (use_mask << location);
3018
3019 if (to_assign[i].var->type->without_array()->is_dual_slot())
3020 double_storage_locations |= (use_mask << location);
3021 }
3022
3023 /* Now that we have all the locations, from the GL 4.5 core spec, section
3024 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
3025 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
3026 * as equivalent single-precision types.
3027 */
3028 if (target_index == MESA_SHADER_VERTEX) {
3029 unsigned total_attribs_size =
3030 _mesa_bitcount(used_locations & SAFE_MASK_FROM_INDEX(max_index)) +
3031 _mesa_bitcount(double_storage_locations);
3032 if (total_attribs_size > max_index) {
3033 linker_error(prog,
3034 "attempt to use %d vertex attribute slots only %d available ",
3035 total_attribs_size, max_index);
3036 return false;
3037 }
3038 }
3039
3040 return true;
3041 }
3042
3043 /**
3044 * Match explicit locations of outputs to inputs and deactivate the
3045 * unmatch flag if found so we don't optimise them away.
3046 */
3047 static void
3048 match_explicit_outputs_to_inputs(gl_linked_shader *producer,
3049 gl_linked_shader *consumer)
3050 {
3051 glsl_symbol_table parameters;
3052 ir_variable *explicit_locations[MAX_VARYINGS_INCL_PATCH][4] =
3053 { {NULL, NULL} };
3054
3055 /* Find all shader outputs in the "producer" stage.
3056 */
3057 foreach_in_list(ir_instruction, node, producer->ir) {
3058 ir_variable *const var = node->as_variable();
3059
3060 if ((var == NULL) || (var->data.mode != ir_var_shader_out))
3061 continue;
3062
3063 if (var->data.explicit_location &&
3064 var->data.location >= VARYING_SLOT_VAR0) {
3065 const unsigned idx = var->data.location - VARYING_SLOT_VAR0;
3066 if (explicit_locations[idx][var->data.location_frac] == NULL)
3067 explicit_locations[idx][var->data.location_frac] = var;
3068 }
3069 }
3070
3071 /* Match inputs to outputs */
3072 foreach_in_list(ir_instruction, node, consumer->ir) {
3073 ir_variable *const input = node->as_variable();
3074
3075 if ((input == NULL) || (input->data.mode != ir_var_shader_in))
3076 continue;
3077
3078 ir_variable *output = NULL;
3079 if (input->data.explicit_location
3080 && input->data.location >= VARYING_SLOT_VAR0) {
3081 output = explicit_locations[input->data.location - VARYING_SLOT_VAR0]
3082 [input->data.location_frac];
3083
3084 if (output != NULL){
3085 input->data.is_unmatched_generic_inout = 0;
3086 output->data.is_unmatched_generic_inout = 0;
3087 }
3088 }
3089 }
3090 }
3091
3092 /**
3093 * Store the gl_FragDepth layout in the gl_shader_program struct.
3094 */
3095 static void
3096 store_fragdepth_layout(struct gl_shader_program *prog)
3097 {
3098 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
3099 return;
3100 }
3101
3102 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
3103
3104 /* We don't look up the gl_FragDepth symbol directly because if
3105 * gl_FragDepth is not used in the shader, it's removed from the IR.
3106 * However, the symbol won't be removed from the symbol table.
3107 *
3108 * We're only interested in the cases where the variable is NOT removed
3109 * from the IR.
3110 */
3111 foreach_in_list(ir_instruction, node, ir) {
3112 ir_variable *const var = node->as_variable();
3113
3114 if (var == NULL || var->data.mode != ir_var_shader_out) {
3115 continue;
3116 }
3117
3118 if (strcmp(var->name, "gl_FragDepth") == 0) {
3119 switch (var->data.depth_layout) {
3120 case ir_depth_layout_none:
3121 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
3122 return;
3123 case ir_depth_layout_any:
3124 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
3125 return;
3126 case ir_depth_layout_greater:
3127 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
3128 return;
3129 case ir_depth_layout_less:
3130 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
3131 return;
3132 case ir_depth_layout_unchanged:
3133 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
3134 return;
3135 default:
3136 assert(0);
3137 return;
3138 }
3139 }
3140 }
3141 }
3142
3143 /**
3144 * Validate the resources used by a program versus the implementation limits
3145 */
3146 static void
3147 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
3148 {
3149 unsigned total_uniform_blocks = 0;
3150 unsigned total_shader_storage_blocks = 0;
3151
3152 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3153 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
3154
3155 if (sh == NULL)
3156 continue;
3157
3158 if (sh->Program->info.num_textures >
3159 ctx->Const.Program[i].MaxTextureImageUnits) {
3160 linker_error(prog, "Too many %s shader texture samplers\n",
3161 _mesa_shader_stage_to_string(i));
3162 }
3163
3164 if (sh->num_uniform_components >
3165 ctx->Const.Program[i].MaxUniformComponents) {
3166 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
3167 linker_warning(prog, "Too many %s shader default uniform block "
3168 "components, but the driver will try to optimize "
3169 "them out; this is non-portable out-of-spec "
3170 "behavior\n",
3171 _mesa_shader_stage_to_string(i));
3172 } else {
3173 linker_error(prog, "Too many %s shader default uniform block "
3174 "components\n",
3175 _mesa_shader_stage_to_string(i));
3176 }
3177 }
3178
3179 if (sh->num_combined_uniform_components >
3180 ctx->Const.Program[i].MaxCombinedUniformComponents) {
3181 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
3182 linker_warning(prog, "Too many %s shader uniform components, "
3183 "but the driver will try to optimize them out; "
3184 "this is non-portable out-of-spec behavior\n",
3185 _mesa_shader_stage_to_string(i));
3186 } else {
3187 linker_error(prog, "Too many %s shader uniform components\n",
3188 _mesa_shader_stage_to_string(i));
3189 }
3190 }
3191
3192 total_shader_storage_blocks += sh->Program->info.num_ssbos;
3193 total_uniform_blocks += sh->Program->info.num_ubos;
3194
3195 const unsigned max_uniform_blocks =
3196 ctx->Const.Program[i].MaxUniformBlocks;
3197 if (max_uniform_blocks < sh->Program->info.num_ubos) {
3198 linker_error(prog, "Too many %s uniform blocks (%d/%d)\n",
3199 _mesa_shader_stage_to_string(i),
3200 sh->Program->info.num_ubos, max_uniform_blocks);
3201 }
3202
3203 const unsigned max_shader_storage_blocks =
3204 ctx->Const.Program[i].MaxShaderStorageBlocks;
3205 if (max_shader_storage_blocks < sh->Program->info.num_ssbos) {
3206 linker_error(prog, "Too many %s shader storage blocks (%d/%d)\n",
3207 _mesa_shader_stage_to_string(i),
3208 sh->Program->info.num_ssbos, max_shader_storage_blocks);
3209 }
3210 }
3211
3212 if (total_uniform_blocks > ctx->Const.MaxCombinedUniformBlocks) {
3213 linker_error(prog, "Too many combined uniform blocks (%d/%d)\n",
3214 total_uniform_blocks, ctx->Const.MaxCombinedUniformBlocks);
3215 }
3216
3217 if (total_shader_storage_blocks > ctx->Const.MaxCombinedShaderStorageBlocks) {
3218 linker_error(prog, "Too many combined shader storage blocks (%d/%d)\n",
3219 total_shader_storage_blocks,
3220 ctx->Const.MaxCombinedShaderStorageBlocks);
3221 }
3222
3223 for (unsigned i = 0; i < prog->data->NumUniformBlocks; i++) {
3224 if (prog->data->UniformBlocks[i].UniformBufferSize >
3225 ctx->Const.MaxUniformBlockSize) {
3226 linker_error(prog, "Uniform block %s too big (%d/%d)\n",
3227 prog->data->UniformBlocks[i].Name,
3228 prog->data->UniformBlocks[i].UniformBufferSize,
3229 ctx->Const.MaxUniformBlockSize);
3230 }
3231 }
3232
3233 for (unsigned i = 0; i < prog->data->NumShaderStorageBlocks; i++) {
3234 if (prog->data->ShaderStorageBlocks[i].UniformBufferSize >
3235 ctx->Const.MaxShaderStorageBlockSize) {
3236 linker_error(prog, "Shader storage block %s too big (%d/%d)\n",
3237 prog->data->ShaderStorageBlocks[i].Name,
3238 prog->data->ShaderStorageBlocks[i].UniformBufferSize,
3239 ctx->Const.MaxShaderStorageBlockSize);
3240 }
3241 }
3242 }
3243
3244 static void
3245 link_calculate_subroutine_compat(struct gl_shader_program *prog)
3246 {
3247 unsigned mask = prog->data->linked_stages;
3248 while (mask) {
3249 const int i = u_bit_scan(&mask);
3250 struct gl_program *p = prog->_LinkedShaders[i]->Program;
3251
3252 for (unsigned j = 0; j < p->sh.NumSubroutineUniformRemapTable; j++) {
3253 if (p->sh.SubroutineUniformRemapTable[j] == INACTIVE_UNIFORM_EXPLICIT_LOCATION)
3254 continue;
3255
3256 struct gl_uniform_storage *uni = p->sh.SubroutineUniformRemapTable[j];
3257
3258 if (!uni)
3259 continue;
3260
3261 int count = 0;
3262 if (p->sh.NumSubroutineFunctions == 0) {
3263 linker_error(prog, "subroutine uniform %s defined but no valid functions found\n", uni->type->name);
3264 continue;
3265 }
3266 for (unsigned f = 0; f < p->sh.NumSubroutineFunctions; f++) {
3267 struct gl_subroutine_function *fn = &p->sh.SubroutineFunctions[f];
3268 for (int k = 0; k < fn->num_compat_types; k++) {
3269 if (fn->types[k] == uni->type) {
3270 count++;
3271 break;
3272 }
3273 }
3274 }
3275 uni->num_compatible_subroutines = count;
3276 }
3277 }
3278 }
3279
3280 static void
3281 check_subroutine_resources(struct gl_shader_program *prog)
3282 {
3283 unsigned mask = prog->data->linked_stages;
3284 while (mask) {
3285 const int i = u_bit_scan(&mask);
3286 struct gl_program *p = prog->_LinkedShaders[i]->Program;
3287
3288 if (p->sh.NumSubroutineUniformRemapTable > MAX_SUBROUTINE_UNIFORM_LOCATIONS) {
3289 linker_error(prog, "Too many %s shader subroutine uniforms\n",
3290 _mesa_shader_stage_to_string(i));
3291 }
3292 }
3293 }
3294 /**
3295 * Validate shader image resources.
3296 */
3297 static void
3298 check_image_resources(struct gl_context *ctx, struct gl_shader_program *prog)
3299 {
3300 unsigned total_image_units = 0;
3301 unsigned fragment_outputs = 0;
3302 unsigned total_shader_storage_blocks = 0;
3303
3304 if (!ctx->Extensions.ARB_shader_image_load_store)
3305 return;
3306
3307 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3308 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
3309
3310 if (sh) {
3311 if (sh->Program->info.num_images > ctx->Const.Program[i].MaxImageUniforms)
3312 linker_error(prog, "Too many %s shader image uniforms (%u > %u)\n",
3313 _mesa_shader_stage_to_string(i),
3314 sh->Program->info.num_images,
3315 ctx->Const.Program[i].MaxImageUniforms);
3316
3317 total_image_units += sh->Program->info.num_images;
3318 total_shader_storage_blocks += sh->Program->info.num_ssbos;
3319
3320 if (i == MESA_SHADER_FRAGMENT) {
3321 foreach_in_list(ir_instruction, node, sh->ir) {
3322 ir_variable *var = node->as_variable();
3323 if (var && var->data.mode == ir_var_shader_out)
3324 /* since there are no double fs outputs - pass false */
3325 fragment_outputs += var->type->count_attribute_slots(false);
3326 }
3327 }
3328 }
3329 }
3330
3331 if (total_image_units > ctx->Const.MaxCombinedImageUniforms)
3332 linker_error(prog, "Too many combined image uniforms\n");
3333
3334 if (total_image_units + fragment_outputs + total_shader_storage_blocks >
3335 ctx->Const.MaxCombinedShaderOutputResources)
3336 linker_error(prog, "Too many combined image uniforms, shader storage "
3337 " buffers and fragment outputs\n");
3338 }
3339
3340
3341 /**
3342 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3343 * for a variable, checks for overlaps between other uniforms using explicit
3344 * locations.
3345 */
3346 static int
3347 reserve_explicit_locations(struct gl_shader_program *prog,
3348 string_to_uint_map *map, ir_variable *var)
3349 {
3350 unsigned slots = var->type->uniform_locations();
3351 unsigned max_loc = var->data.location + slots - 1;
3352 unsigned return_value = slots;
3353
3354 /* Resize remap table if locations do not fit in the current one. */
3355 if (max_loc + 1 > prog->NumUniformRemapTable) {
3356 prog->UniformRemapTable =
3357 reralloc(prog, prog->UniformRemapTable,
3358 gl_uniform_storage *,
3359 max_loc + 1);
3360
3361 if (!prog->UniformRemapTable) {
3362 linker_error(prog, "Out of memory during linking.\n");
3363 return -1;
3364 }
3365
3366 /* Initialize allocated space. */
3367 for (unsigned i = prog->NumUniformRemapTable; i < max_loc + 1; i++)
3368 prog->UniformRemapTable[i] = NULL;
3369
3370 prog->NumUniformRemapTable = max_loc + 1;
3371 }
3372
3373 for (unsigned i = 0; i < slots; i++) {
3374 unsigned loc = var->data.location + i;
3375
3376 /* Check if location is already used. */
3377 if (prog->UniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3378
3379 /* Possibly same uniform from a different stage, this is ok. */
3380 unsigned hash_loc;
3381 if (map->get(hash_loc, var->name) && hash_loc == loc - i) {
3382 return_value = 0;
3383 continue;
3384 }
3385
3386 /* ARB_explicit_uniform_location specification states:
3387 *
3388 * "No two default-block uniform variables in the program can have
3389 * the same location, even if they are unused, otherwise a compiler
3390 * or linker error will be generated."
3391 */
3392 linker_error(prog,
3393 "location qualifier for uniform %s overlaps "
3394 "previously used location\n",
3395 var->name);
3396 return -1;
3397 }
3398
3399 /* Initialize location as inactive before optimization
3400 * rounds and location assignment.
3401 */
3402 prog->UniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3403 }
3404
3405 /* Note, base location used for arrays. */
3406 map->put(var->data.location, var->name);
3407
3408 return return_value;
3409 }
3410
3411 static bool
3412 reserve_subroutine_explicit_locations(struct gl_shader_program *prog,
3413 struct gl_program *p,
3414 ir_variable *var)
3415 {
3416 unsigned slots = var->type->uniform_locations();
3417 unsigned max_loc = var->data.location + slots - 1;
3418
3419 /* Resize remap table if locations do not fit in the current one. */
3420 if (max_loc + 1 > p->sh.NumSubroutineUniformRemapTable) {
3421 p->sh.SubroutineUniformRemapTable =
3422 reralloc(p, p->sh.SubroutineUniformRemapTable,
3423 gl_uniform_storage *,
3424 max_loc + 1);
3425
3426 if (!p->sh.SubroutineUniformRemapTable) {
3427 linker_error(prog, "Out of memory during linking.\n");
3428 return false;
3429 }
3430
3431 /* Initialize allocated space. */
3432 for (unsigned i = p->sh.NumSubroutineUniformRemapTable; i < max_loc + 1; i++)
3433 p->sh.SubroutineUniformRemapTable[i] = NULL;
3434
3435 p->sh.NumSubroutineUniformRemapTable = max_loc + 1;
3436 }
3437
3438 for (unsigned i = 0; i < slots; i++) {
3439 unsigned loc = var->data.location + i;
3440
3441 /* Check if location is already used. */
3442 if (p->sh.SubroutineUniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3443
3444 /* ARB_explicit_uniform_location specification states:
3445 * "No two subroutine uniform variables can have the same location
3446 * in the same shader stage, otherwise a compiler or linker error
3447 * will be generated."
3448 */
3449 linker_error(prog,
3450 "location qualifier for uniform %s overlaps "
3451 "previously used location\n",
3452 var->name);
3453 return false;
3454 }
3455
3456 /* Initialize location as inactive before optimization
3457 * rounds and location assignment.
3458 */
3459 p->sh.SubroutineUniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3460 }
3461
3462 return true;
3463 }
3464 /**
3465 * Check and reserve all explicit uniform locations, called before
3466 * any optimizations happen to handle also inactive uniforms and
3467 * inactive array elements that may get trimmed away.
3468 */
3469 static void
3470 check_explicit_uniform_locations(struct gl_context *ctx,
3471 struct gl_shader_program *prog)
3472 {
3473 prog->NumExplicitUniformLocations = 0;
3474
3475 if (!ctx->Extensions.ARB_explicit_uniform_location)
3476 return;
3477
3478 /* This map is used to detect if overlapping explicit locations
3479 * occur with the same uniform (from different stage) or a different one.
3480 */
3481 string_to_uint_map *uniform_map = new string_to_uint_map;
3482
3483 if (!uniform_map) {
3484 linker_error(prog, "Out of memory during linking.\n");
3485 return;
3486 }
3487
3488 unsigned entries_total = 0;
3489 unsigned mask = prog->data->linked_stages;
3490 while (mask) {
3491 const int i = u_bit_scan(&mask);
3492 struct gl_program *p = prog->_LinkedShaders[i]->Program;
3493
3494 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
3495 ir_variable *var = node->as_variable();
3496 if (!var || var->data.mode != ir_var_uniform)
3497 continue;
3498
3499 if (var->data.explicit_location) {
3500 bool ret = false;
3501 if (var->type->without_array()->is_subroutine())
3502 ret = reserve_subroutine_explicit_locations(prog, p, var);
3503 else {
3504 int slots = reserve_explicit_locations(prog, uniform_map,
3505 var);
3506 if (slots != -1) {
3507 ret = true;
3508 entries_total += slots;
3509 }
3510 }
3511 if (!ret) {
3512 delete uniform_map;
3513 return;
3514 }
3515 }
3516 }
3517 }
3518
3519 struct empty_uniform_block *current_block = NULL;
3520
3521 for (unsigned i = 0; i < prog->NumUniformRemapTable; i++) {
3522 /* We found empty space in UniformRemapTable. */
3523 if (prog->UniformRemapTable[i] == NULL) {
3524 /* We've found the beginning of a new continous block of empty slots */
3525 if (!current_block || current_block->start + current_block->slots != i) {
3526 current_block = rzalloc(prog, struct empty_uniform_block);
3527 current_block->start = i;
3528 exec_list_push_tail(&prog->EmptyUniformLocations,
3529 &current_block->link);
3530 }
3531
3532 /* The current block continues, so we simply increment its slots */
3533 current_block->slots++;
3534 }
3535 }
3536
3537 delete uniform_map;
3538 prog->NumExplicitUniformLocations = entries_total;
3539 }
3540
3541 static bool
3542 should_add_buffer_variable(struct gl_shader_program *shProg,
3543 GLenum type, const char *name)
3544 {
3545 bool found_interface = false;
3546 unsigned block_name_len = 0;
3547 const char *block_name_dot = strchr(name, '.');
3548
3549 /* These rules only apply to buffer variables. So we return
3550 * true for the rest of types.
3551 */
3552 if (type != GL_BUFFER_VARIABLE)
3553 return true;
3554
3555 for (unsigned i = 0; i < shProg->data->NumShaderStorageBlocks; i++) {
3556 const char *block_name = shProg->data->ShaderStorageBlocks[i].Name;
3557 block_name_len = strlen(block_name);
3558
3559 const char *block_square_bracket = strchr(block_name, '[');
3560 if (block_square_bracket) {
3561 /* The block is part of an array of named interfaces,
3562 * for the name comparison we ignore the "[x]" part.
3563 */
3564 block_name_len -= strlen(block_square_bracket);
3565 }
3566
3567 if (block_name_dot) {
3568 /* Check if the variable name starts with the interface
3569 * name. The interface name (if present) should have the
3570 * length than the interface block name we are comparing to.
3571 */
3572 unsigned len = strlen(name) - strlen(block_name_dot);
3573 if (len != block_name_len)
3574 continue;
3575 }
3576
3577 if (strncmp(block_name, name, block_name_len) == 0) {
3578 found_interface = true;
3579 break;
3580 }
3581 }
3582
3583 /* We remove the interface name from the buffer variable name,
3584 * including the dot that follows it.
3585 */
3586 if (found_interface)
3587 name = name + block_name_len + 1;
3588
3589 /* The ARB_program_interface_query spec says:
3590 *
3591 * "For an active shader storage block member declared as an array, an
3592 * entry will be generated only for the first array element, regardless
3593 * of its type. For arrays of aggregate types, the enumeration rules
3594 * are applied recursively for the single enumerated array element."
3595 */
3596 const char *struct_first_dot = strchr(name, '.');
3597 const char *first_square_bracket = strchr(name, '[');
3598
3599 /* The buffer variable is on top level and it is not an array */
3600 if (!first_square_bracket) {
3601 return true;
3602 /* The shader storage block member is a struct, then generate the entry */
3603 } else if (struct_first_dot && struct_first_dot < first_square_bracket) {
3604 return true;
3605 } else {
3606 /* Shader storage block member is an array, only generate an entry for the
3607 * first array element.
3608 */
3609 if (strncmp(first_square_bracket, "[0]", 3) == 0)
3610 return true;
3611 }
3612
3613 return false;
3614 }
3615
3616 static bool
3617 add_program_resource(struct gl_shader_program *prog,
3618 struct set *resource_set,
3619 GLenum type, const void *data, uint8_t stages)
3620 {
3621 assert(data);
3622
3623 /* If resource already exists, do not add it again. */
3624 if (_mesa_set_search(resource_set, data))
3625 return true;
3626
3627 prog->data->ProgramResourceList =
3628 reralloc(prog->data,
3629 prog->data->ProgramResourceList,
3630 gl_program_resource,
3631 prog->data->NumProgramResourceList + 1);
3632
3633 if (!prog->data->ProgramResourceList) {
3634 linker_error(prog, "Out of memory during linking.\n");
3635 return false;
3636 }
3637
3638 struct gl_program_resource *res =
3639 &prog->data->ProgramResourceList[prog->data->NumProgramResourceList];
3640
3641 res->Type = type;
3642 res->Data = data;
3643 res->StageReferences = stages;
3644
3645 prog->data->NumProgramResourceList++;
3646
3647 _mesa_set_add(resource_set, data);
3648
3649 return true;
3650 }
3651
3652 /* Function checks if a variable var is a packed varying and
3653 * if given name is part of packed varying's list.
3654 *
3655 * If a variable is a packed varying, it has a name like
3656 * 'packed:a,b,c' where a, b and c are separate variables.
3657 */
3658 static bool
3659 included_in_packed_varying(ir_variable *var, const char *name)
3660 {
3661 if (strncmp(var->name, "packed:", 7) != 0)
3662 return false;
3663
3664 char *list = strdup(var->name + 7);
3665 assert(list);
3666
3667 bool found = false;
3668 char *saveptr;
3669 char *token = strtok_r(list, ",", &saveptr);
3670 while (token) {
3671 if (strcmp(token, name) == 0) {
3672 found = true;
3673 break;
3674 }
3675 token = strtok_r(NULL, ",", &saveptr);
3676 }
3677 free(list);
3678 return found;
3679 }
3680
3681 /**
3682 * Function builds a stage reference bitmask from variable name.
3683 */
3684 static uint8_t
3685 build_stageref(struct gl_shader_program *shProg, const char *name,
3686 unsigned mode)
3687 {
3688 uint8_t stages = 0;
3689
3690 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3691 * used for reference mask in gl_program_resource will need to be changed.
3692 */
3693 assert(MESA_SHADER_STAGES < 8);
3694
3695 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3696 struct gl_linked_shader *sh = shProg->_LinkedShaders[i];
3697 if (!sh)
3698 continue;
3699
3700 /* Shader symbol table may contain variables that have
3701 * been optimized away. Search IR for the variable instead.
3702 */
3703 foreach_in_list(ir_instruction, node, sh->ir) {
3704 ir_variable *var = node->as_variable();
3705 if (var) {
3706 unsigned baselen = strlen(var->name);
3707
3708 if (included_in_packed_varying(var, name)) {
3709 stages |= (1 << i);
3710 break;
3711 }
3712
3713 /* Type needs to match if specified, otherwise we might
3714 * pick a variable with same name but different interface.
3715 */
3716 if (var->data.mode != mode)
3717 continue;
3718
3719 if (strncmp(var->name, name, baselen) == 0) {
3720 /* Check for exact name matches but also check for arrays and
3721 * structs.
3722 */
3723 if (name[baselen] == '\0' ||
3724 name[baselen] == '[' ||
3725 name[baselen] == '.') {
3726 stages |= (1 << i);
3727 break;
3728 }
3729 }
3730 }
3731 }
3732 }
3733 return stages;
3734 }
3735
3736 /**
3737 * Create gl_shader_variable from ir_variable class.
3738 */
3739 static gl_shader_variable *
3740 create_shader_variable(struct gl_shader_program *shProg,
3741 const ir_variable *in,
3742 const char *name, const glsl_type *type,
3743 const glsl_type *interface_type,
3744 bool use_implicit_location, int location,
3745 const glsl_type *outermost_struct_type)
3746 {
3747 /* Allocate zero-initialized memory to ensure that bitfield padding
3748 * is zero.
3749 */
3750 gl_shader_variable *out = rzalloc(shProg, struct gl_shader_variable);
3751 if (!out)
3752 return NULL;
3753
3754 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3755 * expect to see gl_VertexID in the program resource list. Pretend.
3756 */
3757 if (in->data.mode == ir_var_system_value &&
3758 in->data.location == SYSTEM_VALUE_VERTEX_ID_ZERO_BASE) {
3759 out->name = ralloc_strdup(shProg, "gl_VertexID");
3760 } else if ((in->data.mode == ir_var_shader_out &&
3761 in->data.location == VARYING_SLOT_TESS_LEVEL_OUTER) ||
3762 (in->data.mode == ir_var_system_value &&
3763 in->data.location == SYSTEM_VALUE_TESS_LEVEL_OUTER)) {
3764 out->name = ralloc_strdup(shProg, "gl_TessLevelOuter");
3765 type = glsl_type::get_array_instance(glsl_type::float_type, 4);
3766 } else if ((in->data.mode == ir_var_shader_out &&
3767 in->data.location == VARYING_SLOT_TESS_LEVEL_INNER) ||
3768 (in->data.mode == ir_var_system_value &&
3769 in->data.location == SYSTEM_VALUE_TESS_LEVEL_INNER)) {
3770 out->name = ralloc_strdup(shProg, "gl_TessLevelInner");
3771 type = glsl_type::get_array_instance(glsl_type::float_type, 2);
3772 } else {
3773 out->name = ralloc_strdup(shProg, name);
3774 }
3775
3776 if (!out->name)
3777 return NULL;
3778
3779 /* The ARB_program_interface_query spec says:
3780 *
3781 * "Not all active variables are assigned valid locations; the
3782 * following variables will have an effective location of -1:
3783 *
3784 * * uniforms declared as atomic counters;
3785 *
3786 * * members of a uniform block;
3787 *
3788 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3789 *
3790 * * inputs or outputs not declared with a "location" layout
3791 * qualifier, except for vertex shader inputs and fragment shader
3792 * outputs."
3793 */
3794 if (in->type->is_atomic_uint() || is_gl_identifier(in->name) ||
3795 !(in->data.explicit_location || use_implicit_location)) {
3796 out->location = -1;
3797 } else {
3798 out->location = location;
3799 }
3800
3801 out->type = type;
3802 out->outermost_struct_type = outermost_struct_type;
3803 out->interface_type = interface_type;
3804 out->component = in->data.location_frac;
3805 out->index = in->data.index;
3806 out->patch = in->data.patch;
3807 out->mode = in->data.mode;
3808 out->interpolation = in->data.interpolation;
3809 out->explicit_location = in->data.explicit_location;
3810 out->precision = in->data.precision;
3811
3812 return out;
3813 }
3814
3815 static bool
3816 add_shader_variable(const struct gl_context *ctx,
3817 struct gl_shader_program *shProg,
3818 struct set *resource_set,
3819 unsigned stage_mask,
3820 GLenum programInterface, ir_variable *var,
3821 const char *name, const glsl_type *type,
3822 bool use_implicit_location, int location,
3823 bool inouts_share_location,
3824 const glsl_type *outermost_struct_type = NULL)
3825 {
3826 const glsl_type *interface_type = var->get_interface_type();
3827
3828 if (outermost_struct_type == NULL) {
3829 if (var->data.from_named_ifc_block) {
3830 const char *interface_name = interface_type->name;
3831
3832 if (interface_type->is_array()) {
3833 /* Issue #16 of the ARB_program_interface_query spec says:
3834 *
3835 * "* If a variable is a member of an interface block without an
3836 * instance name, it is enumerated using just the variable name.
3837 *
3838 * * If a variable is a member of an interface block with an
3839 * instance name, it is enumerated as "BlockName.Member", where
3840 * "BlockName" is the name of the interface block (not the
3841 * instance name) and "Member" is the name of the variable."
3842 *
3843 * In particular, it indicates that it should be "BlockName",
3844 * not "BlockName[array length]". The conformance suite and
3845 * dEQP both require this behavior.
3846 *
3847 * Here, we unwrap the extra array level added by named interface
3848 * block array lowering so we have the correct variable type. We
3849 * also unwrap the interface type when constructing the name.
3850 *
3851 * We leave interface_type the same so that ES 3.x SSO pipeline
3852 * validation can enforce the rules requiring array length to
3853 * match on interface blocks.
3854 */
3855 type = type->fields.array;
3856
3857 interface_name = interface_type->fields.array->name;
3858 }
3859
3860 name = ralloc_asprintf(shProg, "%s.%s", interface_name, name);
3861 }
3862 }
3863
3864 switch (type->base_type) {
3865 case GLSL_TYPE_STRUCT: {
3866 /* The ARB_program_interface_query spec says:
3867 *
3868 * "For an active variable declared as a structure, a separate entry
3869 * will be generated for each active structure member. The name of
3870 * each entry is formed by concatenating the name of the structure,
3871 * the "." character, and the name of the structure member. If a
3872 * structure member to enumerate is itself a structure or array,
3873 * these enumeration rules are applied recursively."
3874 */
3875 if (outermost_struct_type == NULL)
3876 outermost_struct_type = type;
3877
3878 unsigned field_location = location;
3879 for (unsigned i = 0; i < type->length; i++) {
3880 const struct glsl_struct_field *field = &type->fields.structure[i];
3881 char *field_name = ralloc_asprintf(shProg, "%s.%s", name, field->name);
3882 if (!add_shader_variable(ctx, shProg, resource_set,
3883 stage_mask, programInterface,
3884 var, field_name, field->type,
3885 use_implicit_location, field_location,
3886 false, outermost_struct_type))
3887 return false;
3888
3889 field_location += field->type->count_attribute_slots(false);
3890 }
3891 return true;
3892 }
3893
3894 case GLSL_TYPE_ARRAY: {
3895 /* The ARB_program_interface_query spec says:
3896 *
3897 * "For an active variable declared as an array of basic types, a
3898 * single entry will be generated, with its name string formed by
3899 * concatenating the name of the array and the string "[0]"."
3900 *
3901 * "For an active variable declared as an array of an aggregate data
3902 * type (structures or arrays), a separate entry will be generated
3903 * for each active array element, unless noted immediately below.
3904 * The name of each entry is formed by concatenating the name of
3905 * the array, the "[" character, an integer identifying the element
3906 * number, and the "]" character. These enumeration rules are
3907 * applied recursively, treating each enumerated array element as a
3908 * separate active variable."
3909 */
3910 const struct glsl_type *array_type = type->fields.array;
3911 if (array_type->base_type == GLSL_TYPE_STRUCT ||
3912 array_type->base_type == GLSL_TYPE_ARRAY) {
3913 unsigned elem_location = location;
3914 unsigned stride = inouts_share_location ? 0 :
3915 array_type->count_attribute_slots(false);
3916 for (unsigned i = 0; i < type->length; i++) {
3917 char *elem = ralloc_asprintf(shProg, "%s[%d]", name, i);
3918 if (!add_shader_variable(ctx, shProg, resource_set,
3919 stage_mask, programInterface,
3920 var, elem, array_type,
3921 use_implicit_location, elem_location,
3922 false, outermost_struct_type))
3923 return false;
3924 elem_location += stride;
3925 }
3926 return true;
3927 }
3928 /* fallthrough */
3929 }
3930
3931 default: {
3932 /* The ARB_program_interface_query spec says:
3933 *
3934 * "For an active variable declared as a single instance of a basic
3935 * type, a single entry will be generated, using the variable name
3936 * from the shader source."
3937 */
3938 gl_shader_variable *sha_v =
3939 create_shader_variable(shProg, var, name, type, interface_type,
3940 use_implicit_location, location,
3941 outermost_struct_type);
3942 if (!sha_v)
3943 return false;
3944
3945 return add_program_resource(shProg, resource_set,
3946 programInterface, sha_v, stage_mask);
3947 }
3948 }
3949 }
3950
3951 static bool
3952 inout_has_same_location(const ir_variable *var, unsigned stage)
3953 {
3954 if (!var->data.patch &&
3955 ((var->data.mode == ir_var_shader_out &&
3956 stage == MESA_SHADER_TESS_CTRL) ||
3957 (var->data.mode == ir_var_shader_in &&
3958 (stage == MESA_SHADER_TESS_CTRL || stage == MESA_SHADER_TESS_EVAL ||
3959 stage == MESA_SHADER_GEOMETRY))))
3960 return true;
3961 else
3962 return false;
3963 }
3964
3965 static bool
3966 add_interface_variables(const struct gl_context *ctx,
3967 struct gl_shader_program *shProg,
3968 struct set *resource_set,
3969 unsigned stage, GLenum programInterface)
3970 {
3971 exec_list *ir = shProg->_LinkedShaders[stage]->ir;
3972
3973 foreach_in_list(ir_instruction, node, ir) {
3974 ir_variable *var = node->as_variable();
3975
3976 if (!var || var->data.how_declared == ir_var_hidden)
3977 continue;
3978
3979 int loc_bias;
3980
3981 switch (var->data.mode) {
3982 case ir_var_system_value:
3983 case ir_var_shader_in:
3984 if (programInterface != GL_PROGRAM_INPUT)
3985 continue;
3986 loc_bias = (stage == MESA_SHADER_VERTEX) ? int(VERT_ATTRIB_GENERIC0)
3987 : int(VARYING_SLOT_VAR0);
3988 break;
3989 case ir_var_shader_out:
3990 if (programInterface != GL_PROGRAM_OUTPUT)
3991 continue;
3992 loc_bias = (stage == MESA_SHADER_FRAGMENT) ? int(FRAG_RESULT_DATA0)
3993 : int(VARYING_SLOT_VAR0);
3994 break;
3995 default:
3996 continue;
3997 };
3998
3999 if (var->data.patch)
4000 loc_bias = int(VARYING_SLOT_PATCH0);
4001
4002 /* Skip packed varyings, packed varyings are handled separately
4003 * by add_packed_varyings.
4004 */
4005 if (strncmp(var->name, "packed:", 7) == 0)
4006 continue;
4007
4008 /* Skip fragdata arrays, these are handled separately
4009 * by add_fragdata_arrays.
4010 */
4011 if (strncmp(var->name, "gl_out_FragData", 15) == 0)
4012 continue;
4013
4014 const bool vs_input_or_fs_output =
4015 (stage == MESA_SHADER_VERTEX && var->data.mode == ir_var_shader_in) ||
4016 (stage == MESA_SHADER_FRAGMENT && var->data.mode == ir_var_shader_out);
4017
4018 if (!add_shader_variable(ctx, shProg, resource_set,
4019 1 << stage, programInterface,
4020 var, var->name, var->type, vs_input_or_fs_output,
4021 var->data.location - loc_bias,
4022 inout_has_same_location(var, stage)))
4023 return false;
4024 }
4025 return true;
4026 }
4027
4028 static bool
4029 add_packed_varyings(const struct gl_context *ctx,
4030 struct gl_shader_program *shProg,
4031 struct set *resource_set,
4032 int stage, GLenum type)
4033 {
4034 struct gl_linked_shader *sh = shProg->_LinkedShaders[stage];
4035 GLenum iface;
4036
4037 if (!sh || !sh->packed_varyings)
4038 return true;
4039
4040 foreach_in_list(ir_instruction, node, sh->packed_varyings) {
4041 ir_variable *var = node->as_variable();
4042 if (var) {
4043 switch (var->data.mode) {
4044 case ir_var_shader_in:
4045 iface = GL_PROGRAM_INPUT;
4046 break;
4047 case ir_var_shader_out:
4048 iface = GL_PROGRAM_OUTPUT;
4049 break;
4050 default:
4051 unreachable("unexpected type");
4052 }
4053
4054 if (type == iface) {
4055 const int stage_mask =
4056 build_stageref(shProg, var->name, var->data.mode);
4057 if (!add_shader_variable(ctx, shProg, resource_set,
4058 stage_mask,
4059 iface, var, var->name, var->type, false,
4060 var->data.location - VARYING_SLOT_VAR0,
4061 inout_has_same_location(var, stage)))
4062 return false;
4063 }
4064 }
4065 }
4066 return true;
4067 }
4068
4069 static bool
4070 add_fragdata_arrays(const struct gl_context *ctx,
4071 struct gl_shader_program *shProg,
4072 struct set *resource_set)
4073 {
4074 struct gl_linked_shader *sh = shProg->_LinkedShaders[MESA_SHADER_FRAGMENT];
4075
4076 if (!sh || !sh->fragdata_arrays)
4077 return true;
4078
4079 foreach_in_list(ir_instruction, node, sh->fragdata_arrays) {
4080 ir_variable *var = node->as_variable();
4081 if (var) {
4082 assert(var->data.mode == ir_var_shader_out);
4083
4084 if (!add_shader_variable(ctx, shProg, resource_set,
4085 1 << MESA_SHADER_FRAGMENT,
4086 GL_PROGRAM_OUTPUT, var, var->name, var->type,
4087 true, var->data.location - FRAG_RESULT_DATA0,
4088 false))
4089 return false;
4090 }
4091 }
4092 return true;
4093 }
4094
4095 static char*
4096 get_top_level_name(const char *name)
4097 {
4098 const char *first_dot = strchr(name, '.');
4099 const char *first_square_bracket = strchr(name, '[');
4100 int name_size = 0;
4101
4102 /* The ARB_program_interface_query spec says:
4103 *
4104 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4105 * the number of active array elements of the top-level shader storage
4106 * block member containing to the active variable is written to
4107 * <params>. If the top-level block member is not declared as an
4108 * array, the value one is written to <params>. If the top-level block
4109 * member is an array with no declared size, the value zero is written
4110 * to <params>."
4111 */
4112
4113 /* The buffer variable is on top level.*/
4114 if (!first_square_bracket && !first_dot)
4115 name_size = strlen(name);
4116 else if ((!first_square_bracket ||
4117 (first_dot && first_dot < first_square_bracket)))
4118 name_size = first_dot - name;
4119 else
4120 name_size = first_square_bracket - name;
4121
4122 return strndup(name, name_size);
4123 }
4124
4125 static char*
4126 get_var_name(const char *name)
4127 {
4128 const char *first_dot = strchr(name, '.');
4129
4130 if (!first_dot)
4131 return strdup(name);
4132
4133 return strndup(first_dot+1, strlen(first_dot) - 1);
4134 }
4135
4136 static bool
4137 is_top_level_shader_storage_block_member(const char* name,
4138 const char* interface_name,
4139 const char* field_name)
4140 {
4141 bool result = false;
4142
4143 /* If the given variable is already a top-level shader storage
4144 * block member, then return array_size = 1.
4145 * We could have two possibilities: if we have an instanced
4146 * shader storage block or not instanced.
4147 *
4148 * For the first, we check create a name as it was in top level and
4149 * compare it with the real name. If they are the same, then
4150 * the variable is already at top-level.
4151 *
4152 * Full instanced name is: interface name + '.' + var name +
4153 * NULL character
4154 */
4155 int name_length = strlen(interface_name) + 1 + strlen(field_name) + 1;
4156 char *full_instanced_name = (char *) calloc(name_length, sizeof(char));
4157 if (!full_instanced_name) {
4158 fprintf(stderr, "%s: Cannot allocate space for name\n", __func__);
4159 return false;
4160 }
4161
4162 snprintf(full_instanced_name, name_length, "%s.%s",
4163 interface_name, field_name);
4164
4165 /* Check if its top-level shader storage block member of an
4166 * instanced interface block, or of a unnamed interface block.
4167 */
4168 if (strcmp(name, full_instanced_name) == 0 ||
4169 strcmp(name, field_name) == 0)
4170 result = true;
4171
4172 free(full_instanced_name);
4173 return result;
4174 }
4175
4176 static int
4177 get_array_size(struct gl_uniform_storage *uni, const glsl_struct_field *field,
4178 char *interface_name, char *var_name)
4179 {
4180 /* The ARB_program_interface_query spec says:
4181 *
4182 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4183 * the number of active array elements of the top-level shader storage
4184 * block member containing to the active variable is written to
4185 * <params>. If the top-level block member is not declared as an
4186 * array, the value one is written to <params>. If the top-level block
4187 * member is an array with no declared size, the value zero is written
4188 * to <params>."
4189 */
4190 if (is_top_level_shader_storage_block_member(uni->name,
4191 interface_name,
4192 var_name))
4193 return 1;
4194 else if (field->type->is_unsized_array())
4195 return 0;
4196 else if (field->type->is_array())
4197 return field->type->length;
4198
4199 return 1;
4200 }
4201
4202 static int
4203 get_array_stride(struct gl_context *ctx, struct gl_uniform_storage *uni,
4204 const glsl_type *interface, const glsl_struct_field *field,
4205 char *interface_name, char *var_name)
4206 {
4207 /* The ARB_program_interface_query spec says:
4208 *
4209 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
4210 * identifying the stride between array elements of the top-level
4211 * shader storage block member containing the active variable is
4212 * written to <params>. For top-level block members declared as
4213 * arrays, the value written is the difference, in basic machine units,
4214 * between the offsets of the active variable for consecutive elements
4215 * in the top-level array. For top-level block members not declared as
4216 * an array, zero is written to <params>."
4217 */
4218 if (field->type->is_array()) {
4219 const enum glsl_matrix_layout matrix_layout =
4220 glsl_matrix_layout(field->matrix_layout);
4221 bool row_major = matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR;
4222 const glsl_type *array_type = field->type->fields.array;
4223
4224 if (is_top_level_shader_storage_block_member(uni->name,
4225 interface_name,
4226 var_name))
4227 return 0;
4228
4229 if (GLSL_INTERFACE_PACKING_STD140 ==
4230 interface->
4231 get_internal_ifc_packing(ctx->Const.UseSTD430AsDefaultPacking)) {
4232 if (array_type->is_record() || array_type->is_array())
4233 return glsl_align(array_type->std140_size(row_major), 16);
4234 else
4235 return MAX2(array_type->std140_base_alignment(row_major), 16);
4236 } else {
4237 return array_type->std430_array_stride(row_major);
4238 }
4239 }
4240 return 0;
4241 }
4242
4243 static void
4244 calculate_array_size_and_stride(struct gl_context *ctx,
4245 struct gl_shader_program *shProg,
4246 struct gl_uniform_storage *uni)
4247 {
4248 int block_index = uni->block_index;
4249 int array_size = -1;
4250 int array_stride = -1;
4251 char *var_name = get_top_level_name(uni->name);
4252 char *interface_name =
4253 get_top_level_name(uni->is_shader_storage ?
4254 shProg->data->ShaderStorageBlocks[block_index].Name :
4255 shProg->data->UniformBlocks[block_index].Name);
4256
4257 if (strcmp(var_name, interface_name) == 0) {
4258 /* Deal with instanced array of SSBOs */
4259 char *temp_name = get_var_name(uni->name);
4260 if (!temp_name) {
4261 linker_error(shProg, "Out of memory during linking.\n");
4262 goto write_top_level_array_size_and_stride;
4263 }
4264 free(var_name);
4265 var_name = get_top_level_name(temp_name);
4266 free(temp_name);
4267 if (!var_name) {
4268 linker_error(shProg, "Out of memory during linking.\n");
4269 goto write_top_level_array_size_and_stride;
4270 }
4271 }
4272
4273 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4274 const gl_linked_shader *sh = shProg->_LinkedShaders[i];
4275 if (sh == NULL)
4276 continue;
4277
4278 foreach_in_list(ir_instruction, node, sh->ir) {
4279 ir_variable *var = node->as_variable();
4280 if (!var || !var->get_interface_type() ||
4281 var->data.mode != ir_var_shader_storage)
4282 continue;
4283
4284 const glsl_type *interface = var->get_interface_type();
4285
4286 if (strcmp(interface_name, interface->name) != 0)
4287 continue;
4288
4289 for (unsigned i = 0; i < interface->length; i++) {
4290 const glsl_struct_field *field = &interface->fields.structure[i];
4291 if (strcmp(field->name, var_name) != 0)
4292 continue;
4293
4294 array_stride = get_array_stride(ctx, uni, interface, field,
4295 interface_name, var_name);
4296 array_size = get_array_size(uni, field, interface_name, var_name);
4297 goto write_top_level_array_size_and_stride;
4298 }
4299 }
4300 }
4301 write_top_level_array_size_and_stride:
4302 free(interface_name);
4303 free(var_name);
4304 uni->top_level_array_stride = array_stride;
4305 uni->top_level_array_size = array_size;
4306 }
4307
4308 /**
4309 * Builds up a list of program resources that point to existing
4310 * resource data.
4311 */
4312 void
4313 build_program_resource_list(struct gl_context *ctx,
4314 struct gl_shader_program *shProg)
4315 {
4316 /* Rebuild resource list. */
4317 if (shProg->data->ProgramResourceList) {
4318 ralloc_free(shProg->data->ProgramResourceList);
4319 shProg->data->ProgramResourceList = NULL;
4320 shProg->data->NumProgramResourceList = 0;
4321 }
4322
4323 int input_stage = MESA_SHADER_STAGES, output_stage = 0;
4324
4325 /* Determine first input and final output stage. These are used to
4326 * detect which variables should be enumerated in the resource list
4327 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4328 */
4329 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4330 if (!shProg->_LinkedShaders[i])
4331 continue;
4332 if (input_stage == MESA_SHADER_STAGES)
4333 input_stage = i;
4334 output_stage = i;
4335 }
4336
4337 /* Empty shader, no resources. */
4338 if (input_stage == MESA_SHADER_STAGES && output_stage == 0)
4339 return;
4340
4341 struct set *resource_set = _mesa_set_create(NULL,
4342 _mesa_hash_pointer,
4343 _mesa_key_pointer_equal);
4344
4345 /* Program interface needs to expose varyings in case of SSO. */
4346 if (shProg->SeparateShader) {
4347 if (!add_packed_varyings(ctx, shProg, resource_set,
4348 input_stage, GL_PROGRAM_INPUT))
4349 return;
4350
4351 if (!add_packed_varyings(ctx, shProg, resource_set,
4352 output_stage, GL_PROGRAM_OUTPUT))
4353 return;
4354 }
4355
4356 if (!add_fragdata_arrays(ctx, shProg, resource_set))
4357 return;
4358
4359 /* Add inputs and outputs to the resource list. */
4360 if (!add_interface_variables(ctx, shProg, resource_set,
4361 input_stage, GL_PROGRAM_INPUT))
4362 return;
4363
4364 if (!add_interface_variables(ctx, shProg, resource_set,
4365 output_stage, GL_PROGRAM_OUTPUT))
4366 return;
4367
4368 if (shProg->last_vert_prog) {
4369 struct gl_transform_feedback_info *linked_xfb =
4370 shProg->last_vert_prog->sh.LinkedTransformFeedback;
4371
4372 /* Add transform feedback varyings. */
4373 if (linked_xfb->NumVarying > 0) {
4374 for (int i = 0; i < linked_xfb->NumVarying; i++) {
4375 if (!add_program_resource(shProg, resource_set,
4376 GL_TRANSFORM_FEEDBACK_VARYING,
4377 &linked_xfb->Varyings[i], 0))
4378 return;
4379 }
4380 }
4381
4382 /* Add transform feedback buffers. */
4383 for (unsigned i = 0; i < ctx->Const.MaxTransformFeedbackBuffers; i++) {
4384 if ((linked_xfb->ActiveBuffers >> i) & 1) {
4385 linked_xfb->Buffers[i].Binding = i;
4386 if (!add_program_resource(shProg, resource_set,
4387 GL_TRANSFORM_FEEDBACK_BUFFER,
4388 &linked_xfb->Buffers[i], 0))
4389 return;
4390 }
4391 }
4392 }
4393
4394 /* Add uniforms from uniform storage. */
4395 for (unsigned i = 0; i < shProg->data->NumUniformStorage; i++) {
4396 /* Do not add uniforms internally used by Mesa. */
4397 if (shProg->data->UniformStorage[i].hidden)
4398 continue;
4399
4400 uint8_t stageref =
4401 build_stageref(shProg, shProg->data->UniformStorage[i].name,
4402 ir_var_uniform);
4403
4404 /* Add stagereferences for uniforms in a uniform block. */
4405 bool is_shader_storage =
4406 shProg->data->UniformStorage[i].is_shader_storage;
4407 int block_index = shProg->data->UniformStorage[i].block_index;
4408 if (block_index != -1) {
4409 stageref |= is_shader_storage ?
4410 shProg->data->ShaderStorageBlocks[block_index].stageref :
4411 shProg->data->UniformBlocks[block_index].stageref;
4412 }
4413
4414 GLenum type = is_shader_storage ? GL_BUFFER_VARIABLE : GL_UNIFORM;
4415 if (!should_add_buffer_variable(shProg, type,
4416 shProg->data->UniformStorage[i].name))
4417 continue;
4418
4419 if (is_shader_storage) {
4420 calculate_array_size_and_stride(ctx, shProg,
4421 &shProg->data->UniformStorage[i]);
4422 }
4423
4424 if (!add_program_resource(shProg, resource_set, type,
4425 &shProg->data->UniformStorage[i], stageref))
4426 return;
4427 }
4428
4429 /* Add program uniform blocks. */
4430 for (unsigned i = 0; i < shProg->data->NumUniformBlocks; i++) {
4431 if (!add_program_resource(shProg, resource_set, GL_UNIFORM_BLOCK,
4432 &shProg->data->UniformBlocks[i], 0))
4433 return;
4434 }
4435
4436 /* Add program shader storage blocks. */
4437 for (unsigned i = 0; i < shProg->data->NumShaderStorageBlocks; i++) {
4438 if (!add_program_resource(shProg, resource_set, GL_SHADER_STORAGE_BLOCK,
4439 &shProg->data->ShaderStorageBlocks[i], 0))
4440 return;
4441 }
4442
4443 /* Add atomic counter buffers. */
4444 for (unsigned i = 0; i < shProg->data->NumAtomicBuffers; i++) {
4445 if (!add_program_resource(shProg, resource_set, GL_ATOMIC_COUNTER_BUFFER,
4446 &shProg->data->AtomicBuffers[i], 0))
4447 return;
4448 }
4449
4450 for (unsigned i = 0; i < shProg->data->NumUniformStorage; i++) {
4451 GLenum type;
4452 if (!shProg->data->UniformStorage[i].hidden)
4453 continue;
4454
4455 for (int j = MESA_SHADER_VERTEX; j < MESA_SHADER_STAGES; j++) {
4456 if (!shProg->data->UniformStorage[i].opaque[j].active ||
4457 !shProg->data->UniformStorage[i].type->is_subroutine())
4458 continue;
4459
4460 type = _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage)j);
4461 /* add shader subroutines */
4462 if (!add_program_resource(shProg, resource_set,
4463 type, &shProg->data->UniformStorage[i], 0))
4464 return;
4465 }
4466 }
4467
4468 unsigned mask = shProg->data->linked_stages;
4469 while (mask) {
4470 const int i = u_bit_scan(&mask);
4471 struct gl_program *p = shProg->_LinkedShaders[i]->Program;
4472
4473 GLuint type = _mesa_shader_stage_to_subroutine((gl_shader_stage)i);
4474 for (unsigned j = 0; j < p->sh.NumSubroutineFunctions; j++) {
4475 if (!add_program_resource(shProg, resource_set,
4476 type, &p->sh.SubroutineFunctions[j], 0))
4477 return;
4478 }
4479 }
4480
4481 _mesa_set_destroy(resource_set, NULL);
4482 }
4483
4484 /**
4485 * This check is done to make sure we allow only constant expression
4486 * indexing and "constant-index-expression" (indexing with an expression
4487 * that includes loop induction variable).
4488 */
4489 static bool
4490 validate_sampler_array_indexing(struct gl_context *ctx,
4491 struct gl_shader_program *prog)
4492 {
4493 dynamic_sampler_array_indexing_visitor v;
4494 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4495 if (prog->_LinkedShaders[i] == NULL)
4496 continue;
4497
4498 bool no_dynamic_indexing =
4499 ctx->Const.ShaderCompilerOptions[i].EmitNoIndirectSampler;
4500
4501 /* Search for array derefs in shader. */
4502 v.run(prog->_LinkedShaders[i]->ir);
4503 if (v.uses_dynamic_sampler_array_indexing()) {
4504 const char *msg = "sampler arrays indexed with non-constant "
4505 "expressions is forbidden in GLSL %s %u";
4506 /* Backend has indicated that it has no dynamic indexing support. */
4507 if (no_dynamic_indexing) {
4508 linker_error(prog, msg, prog->IsES ? "ES" : "",
4509 prog->data->Version);
4510 return false;
4511 } else {
4512 linker_warning(prog, msg, prog->IsES ? "ES" : "",
4513 prog->data->Version);
4514 }
4515 }
4516 }
4517 return true;
4518 }
4519
4520 static void
4521 link_assign_subroutine_types(struct gl_shader_program *prog)
4522 {
4523 unsigned mask = prog->data->linked_stages;
4524 while (mask) {
4525 const int i = u_bit_scan(&mask);
4526 gl_program *p = prog->_LinkedShaders[i]->Program;
4527
4528 p->sh.MaxSubroutineFunctionIndex = 0;
4529 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
4530 ir_function *fn = node->as_function();
4531 if (!fn)
4532 continue;
4533
4534 if (fn->is_subroutine)
4535 p->sh.NumSubroutineUniformTypes++;
4536
4537 if (!fn->num_subroutine_types)
4538 continue;
4539
4540 /* these should have been calculated earlier. */
4541 assert(fn->subroutine_index != -1);
4542 if (p->sh.NumSubroutineFunctions + 1 > MAX_SUBROUTINES) {
4543 linker_error(prog, "Too many subroutine functions declared.\n");
4544 return;
4545 }
4546 p->sh.SubroutineFunctions = reralloc(p, p->sh.SubroutineFunctions,
4547 struct gl_subroutine_function,
4548 p->sh.NumSubroutineFunctions + 1);
4549 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].name = ralloc_strdup(p, fn->name);
4550 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].num_compat_types = fn->num_subroutine_types;
4551 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].types =
4552 ralloc_array(p, const struct glsl_type *,
4553 fn->num_subroutine_types);
4554
4555 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4556 * GLSL 4.5 spec:
4557 *
4558 * "Each subroutine with an index qualifier in the shader must be
4559 * given a unique index, otherwise a compile or link error will be
4560 * generated."
4561 */
4562 for (unsigned j = 0; j < p->sh.NumSubroutineFunctions; j++) {
4563 if (p->sh.SubroutineFunctions[j].index != -1 &&
4564 p->sh.SubroutineFunctions[j].index == fn->subroutine_index) {
4565 linker_error(prog, "each subroutine index qualifier in the "
4566 "shader must be unique\n");
4567 return;
4568 }
4569 }
4570 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].index =
4571 fn->subroutine_index;
4572
4573 if (fn->subroutine_index > (int)p->sh.MaxSubroutineFunctionIndex)
4574 p->sh.MaxSubroutineFunctionIndex = fn->subroutine_index;
4575
4576 for (int j = 0; j < fn->num_subroutine_types; j++)
4577 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].types[j] = fn->subroutine_types[j];
4578 p->sh.NumSubroutineFunctions++;
4579 }
4580 }
4581 }
4582
4583 static void
4584 set_always_active_io(exec_list *ir, ir_variable_mode io_mode)
4585 {
4586 assert(io_mode == ir_var_shader_in || io_mode == ir_var_shader_out);
4587
4588 foreach_in_list(ir_instruction, node, ir) {
4589 ir_variable *const var = node->as_variable();
4590
4591 if (var == NULL || var->data.mode != io_mode)
4592 continue;
4593
4594 /* Don't set always active on builtins that haven't been redeclared */
4595 if (var->data.how_declared == ir_var_declared_implicitly)
4596 continue;
4597
4598 var->data.always_active_io = true;
4599 }
4600 }
4601
4602 /**
4603 * When separate shader programs are enabled, only input/outputs between
4604 * the stages of a multi-stage separate program can be safely removed
4605 * from the shader interface. Other inputs/outputs must remain active.
4606 */
4607 static void
4608 disable_varying_optimizations_for_sso(struct gl_shader_program *prog)
4609 {
4610 unsigned first, last;
4611 assert(prog->SeparateShader);
4612
4613 first = MESA_SHADER_STAGES;
4614 last = 0;
4615
4616 /* Determine first and last stage. Excluding the compute stage */
4617 for (unsigned i = 0; i < MESA_SHADER_COMPUTE; i++) {
4618 if (!prog->_LinkedShaders[i])
4619 continue;
4620 if (first == MESA_SHADER_STAGES)
4621 first = i;
4622 last = i;
4623 }
4624
4625 if (first == MESA_SHADER_STAGES)
4626 return;
4627
4628 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
4629 gl_linked_shader *sh = prog->_LinkedShaders[stage];
4630 if (!sh)
4631 continue;
4632
4633 /* Prevent the removal of inputs to the first and outputs from the last
4634 * stage, unless they are the initial pipeline inputs or final pipeline
4635 * outputs, respectively.
4636 *
4637 * The removal of IO between shaders in the same program is always
4638 * allowed.
4639 */
4640 if (stage == first && stage != MESA_SHADER_VERTEX)
4641 set_always_active_io(sh->ir, ir_var_shader_in);
4642 if (stage == last && stage != MESA_SHADER_FRAGMENT)
4643 set_always_active_io(sh->ir, ir_var_shader_out);
4644 }
4645 }
4646
4647 static void
4648 link_and_validate_uniforms(struct gl_context *ctx,
4649 struct gl_shader_program *prog)
4650 {
4651 update_array_sizes(prog);
4652 link_assign_uniform_locations(prog, ctx);
4653
4654 link_assign_atomic_counter_resources(ctx, prog);
4655 link_calculate_subroutine_compat(prog);
4656 check_resources(ctx, prog);
4657 check_subroutine_resources(prog);
4658 check_image_resources(ctx, prog);
4659 link_check_atomic_counter_resources(ctx, prog);
4660 }
4661
4662 static bool
4663 link_varyings_and_uniforms(unsigned first, unsigned last,
4664 struct gl_context *ctx,
4665 struct gl_shader_program *prog, void *mem_ctx)
4666 {
4667 /* Mark all generic shader inputs and outputs as unpaired. */
4668 for (unsigned i = MESA_SHADER_VERTEX; i <= MESA_SHADER_FRAGMENT; i++) {
4669 if (prog->_LinkedShaders[i] != NULL) {
4670 link_invalidate_variable_locations(prog->_LinkedShaders[i]->ir);
4671 }
4672 }
4673
4674 unsigned prev = first;
4675 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
4676 if (prog->_LinkedShaders[i] == NULL)
4677 continue;
4678
4679 match_explicit_outputs_to_inputs(prog->_LinkedShaders[prev],
4680 prog->_LinkedShaders[i]);
4681 prev = i;
4682 }
4683
4684 if (!assign_attribute_or_color_locations(mem_ctx, prog, &ctx->Const,
4685 MESA_SHADER_VERTEX)) {
4686 return false;
4687 }
4688
4689 if (!assign_attribute_or_color_locations(mem_ctx, prog, &ctx->Const,
4690 MESA_SHADER_FRAGMENT)) {
4691 return false;
4692 }
4693
4694 prog->last_vert_prog = NULL;
4695 for (int i = MESA_SHADER_GEOMETRY; i >= MESA_SHADER_VERTEX; i--) {
4696 if (prog->_LinkedShaders[i] == NULL)
4697 continue;
4698
4699 prog->last_vert_prog = prog->_LinkedShaders[i]->Program;
4700 break;
4701 }
4702
4703 if (!link_varyings(prog, first, last, ctx, mem_ctx))
4704 return false;
4705
4706 link_and_validate_uniforms(ctx, prog);
4707
4708 if (!prog->data->LinkStatus)
4709 return false;
4710
4711 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4712 if (prog->_LinkedShaders[i] == NULL)
4713 continue;
4714
4715 const struct gl_shader_compiler_options *options =
4716 &ctx->Const.ShaderCompilerOptions[i];
4717
4718 if (options->LowerBufferInterfaceBlocks)
4719 lower_ubo_reference(prog->_LinkedShaders[i],
4720 options->ClampBlockIndicesToArrayBounds,
4721 ctx->Const.UseSTD430AsDefaultPacking);
4722
4723 if (i == MESA_SHADER_COMPUTE)
4724 lower_shared_reference(ctx, prog, prog->_LinkedShaders[i]);
4725
4726 lower_vector_derefs(prog->_LinkedShaders[i]);
4727 do_vec_index_to_swizzle(prog->_LinkedShaders[i]->ir);
4728 }
4729
4730 return true;
4731 }
4732
4733 static void
4734 linker_optimisation_loop(struct gl_context *ctx, exec_list *ir,
4735 unsigned stage)
4736 {
4737 if (ctx->Const.GLSLOptimizeConservatively) {
4738 /* Run it just once. */
4739 do_common_optimization(ir, true, false,
4740 &ctx->Const.ShaderCompilerOptions[stage],
4741 ctx->Const.NativeIntegers);
4742 } else {
4743 /* Repeat it until it stops making changes. */
4744 while (do_common_optimization(ir, true, false,
4745 &ctx->Const.ShaderCompilerOptions[stage],
4746 ctx->Const.NativeIntegers))
4747 ;
4748 }
4749 }
4750
4751 void
4752 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
4753 {
4754 prog->data->LinkStatus = LINKING_SUCCESS; /* All error paths will set this to false */
4755 prog->data->Validated = false;
4756
4757 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4758 *
4759 * "Linking can fail for a variety of reasons as specified in the
4760 * OpenGL Shading Language Specification, as well as any of the
4761 * following reasons:
4762 *
4763 * - No shader objects are attached to program."
4764 *
4765 * The Compatibility Profile specification does not list the error. In
4766 * Compatibility Profile missing shader stages are replaced by
4767 * fixed-function. This applies to the case where all stages are
4768 * missing.
4769 */
4770 if (prog->NumShaders == 0) {
4771 if (ctx->API != API_OPENGL_COMPAT)
4772 linker_error(prog, "no shaders attached to the program\n");
4773 return;
4774 }
4775
4776 #ifdef ENABLE_SHADER_CACHE
4777 if (shader_cache_read_program_metadata(ctx, prog))
4778 return;
4779 #endif
4780
4781 void *mem_ctx = ralloc_context(NULL); // temporary linker context
4782
4783 prog->ARB_fragment_coord_conventions_enable = false;
4784
4785 /* Separate the shaders into groups based on their type.
4786 */
4787 struct gl_shader **shader_list[MESA_SHADER_STAGES];
4788 unsigned num_shaders[MESA_SHADER_STAGES];
4789
4790 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
4791 shader_list[i] = (struct gl_shader **)
4792 calloc(prog->NumShaders, sizeof(struct gl_shader *));
4793 num_shaders[i] = 0;
4794 }
4795
4796 unsigned min_version = UINT_MAX;
4797 unsigned max_version = 0;
4798 for (unsigned i = 0; i < prog->NumShaders; i++) {
4799 min_version = MIN2(min_version, prog->Shaders[i]->Version);
4800 max_version = MAX2(max_version, prog->Shaders[i]->Version);
4801
4802 if (prog->Shaders[i]->IsES != prog->Shaders[0]->IsES) {
4803 linker_error(prog, "all shaders must use same shading "
4804 "language version\n");
4805 goto done;
4806 }
4807
4808 if (prog->Shaders[i]->ARB_fragment_coord_conventions_enable) {
4809 prog->ARB_fragment_coord_conventions_enable = true;
4810 }
4811
4812 gl_shader_stage shader_type = prog->Shaders[i]->Stage;
4813 shader_list[shader_type][num_shaders[shader_type]] = prog->Shaders[i];
4814 num_shaders[shader_type]++;
4815 }
4816
4817 /* In desktop GLSL, different shader versions may be linked together. In
4818 * GLSL ES, all shader versions must be the same.
4819 */
4820 if (prog->Shaders[0]->IsES && min_version != max_version) {
4821 linker_error(prog, "all shaders must use same shading "
4822 "language version\n");
4823 goto done;
4824 }
4825
4826 prog->data->Version = max_version;
4827 prog->IsES = prog->Shaders[0]->IsES;
4828
4829 /* Some shaders have to be linked with some other shaders present.
4830 */
4831 if (!prog->SeparateShader) {
4832 if (num_shaders[MESA_SHADER_GEOMETRY] > 0 &&
4833 num_shaders[MESA_SHADER_VERTEX] == 0) {
4834 linker_error(prog, "Geometry shader must be linked with "
4835 "vertex shader\n");
4836 goto done;
4837 }
4838 if (num_shaders[MESA_SHADER_TESS_EVAL] > 0 &&
4839 num_shaders[MESA_SHADER_VERTEX] == 0) {
4840 linker_error(prog, "Tessellation evaluation shader must be linked "
4841 "with vertex shader\n");
4842 goto done;
4843 }
4844 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
4845 num_shaders[MESA_SHADER_VERTEX] == 0) {
4846 linker_error(prog, "Tessellation control shader must be linked with "
4847 "vertex shader\n");
4848 goto done;
4849 }
4850
4851 /* Section 7.3 of the OpenGL ES 3.2 specification says:
4852 *
4853 * "Linking can fail for [...] any of the following reasons:
4854 *
4855 * * program contains an object to form a tessellation control
4856 * shader [...] and [...] the program is not separable and
4857 * contains no object to form a tessellation evaluation shader"
4858 *
4859 * The OpenGL spec is contradictory. It allows linking without a tess
4860 * eval shader, but that can only be used with transform feedback and
4861 * rasterization disabled. However, transform feedback isn't allowed
4862 * with GL_PATCHES, so it can't be used.
4863 *
4864 * More investigation showed that the idea of transform feedback after
4865 * a tess control shader was dropped, because some hw vendors couldn't
4866 * support tessellation without a tess eval shader, but the linker
4867 * section wasn't updated to reflect that.
4868 *
4869 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4870 * spec bug.
4871 *
4872 * Do what's reasonable and always require a tess eval shader if a tess
4873 * control shader is present.
4874 */
4875 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
4876 num_shaders[MESA_SHADER_TESS_EVAL] == 0) {
4877 linker_error(prog, "Tessellation control shader must be linked with "
4878 "tessellation evaluation shader\n");
4879 goto done;
4880 }
4881
4882 if (prog->IsES) {
4883 if (num_shaders[MESA_SHADER_TESS_EVAL] > 0 &&
4884 num_shaders[MESA_SHADER_TESS_CTRL] == 0) {
4885 linker_error(prog, "GLSL ES requires non-separable programs "
4886 "containing a tessellation evaluation shader to also "
4887 "be linked with a tessellation control shader\n");
4888 goto done;
4889 }
4890 }
4891 }
4892
4893 /* Compute shaders have additional restrictions. */
4894 if (num_shaders[MESA_SHADER_COMPUTE] > 0 &&
4895 num_shaders[MESA_SHADER_COMPUTE] != prog->NumShaders) {
4896 linker_error(prog, "Compute shaders may not be linked with any other "
4897 "type of shader\n");
4898 }
4899
4900 /* Link all shaders for a particular stage and validate the result.
4901 */
4902 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
4903 if (num_shaders[stage] > 0) {
4904 gl_linked_shader *const sh =
4905 link_intrastage_shaders(mem_ctx, ctx, prog, shader_list[stage],
4906 num_shaders[stage], false);
4907
4908 if (!prog->data->LinkStatus) {
4909 if (sh)
4910 _mesa_delete_linked_shader(ctx, sh);
4911 goto done;
4912 }
4913
4914 switch (stage) {
4915 case MESA_SHADER_VERTEX:
4916 validate_vertex_shader_executable(prog, sh, ctx);
4917 break;
4918 case MESA_SHADER_TESS_CTRL:
4919 /* nothing to be done */
4920 break;
4921 case MESA_SHADER_TESS_EVAL:
4922 validate_tess_eval_shader_executable(prog, sh, ctx);
4923 break;
4924 case MESA_SHADER_GEOMETRY:
4925 validate_geometry_shader_executable(prog, sh, ctx);
4926 break;
4927 case MESA_SHADER_FRAGMENT:
4928 validate_fragment_shader_executable(prog, sh);
4929 break;
4930 }
4931 if (!prog->data->LinkStatus) {
4932 if (sh)
4933 _mesa_delete_linked_shader(ctx, sh);
4934 goto done;
4935 }
4936
4937 prog->_LinkedShaders[stage] = sh;
4938 prog->data->linked_stages |= 1 << stage;
4939 }
4940 }
4941
4942 /* Here begins the inter-stage linking phase. Some initial validation is
4943 * performed, then locations are assigned for uniforms, attributes, and
4944 * varyings.
4945 */
4946 cross_validate_uniforms(prog);
4947 if (!prog->data->LinkStatus)
4948 goto done;
4949
4950 unsigned first, last, prev;
4951
4952 first = MESA_SHADER_STAGES;
4953 last = 0;
4954
4955 /* Determine first and last stage. */
4956 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4957 if (!prog->_LinkedShaders[i])
4958 continue;
4959 if (first == MESA_SHADER_STAGES)
4960 first = i;
4961 last = i;
4962 }
4963
4964 check_explicit_uniform_locations(ctx, prog);
4965 link_assign_subroutine_types(prog);
4966
4967 if (!prog->data->LinkStatus)
4968 goto done;
4969
4970 resize_tes_inputs(ctx, prog);
4971
4972 /* Validate the inputs of each stage with the output of the preceding
4973 * stage.
4974 */
4975 prev = first;
4976 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
4977 if (prog->_LinkedShaders[i] == NULL)
4978 continue;
4979
4980 validate_interstage_inout_blocks(prog, prog->_LinkedShaders[prev],
4981 prog->_LinkedShaders[i]);
4982 if (!prog->data->LinkStatus)
4983 goto done;
4984
4985 cross_validate_outputs_to_inputs(ctx, prog,
4986 prog->_LinkedShaders[prev],
4987 prog->_LinkedShaders[i]);
4988 if (!prog->data->LinkStatus)
4989 goto done;
4990
4991 prev = i;
4992 }
4993
4994 /* The cross validation of outputs/inputs above validates explicit locations
4995 * but for SSO programs we need to do this also for the inputs in the
4996 * first stage and outputs of the last stage included in the program, since
4997 * there is no cross validation for these.
4998 */
4999 if (prog->SeparateShader)
5000 validate_sso_explicit_locations(ctx, prog,
5001 (gl_shader_stage) first,
5002 (gl_shader_stage) last);
5003
5004 /* Cross-validate uniform blocks between shader stages */
5005 validate_interstage_uniform_blocks(prog, prog->_LinkedShaders);
5006 if (!prog->data->LinkStatus)
5007 goto done;
5008
5009 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
5010 if (prog->_LinkedShaders[i] != NULL)
5011 lower_named_interface_blocks(mem_ctx, prog->_LinkedShaders[i]);
5012 }
5013
5014 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
5015 * it before optimization because we want most of the checks to get
5016 * dropped thanks to constant propagation.
5017 *
5018 * This rule also applies to GLSL ES 3.00.
5019 */
5020 if (max_version >= (prog->IsES ? 300 : 130)) {
5021 struct gl_linked_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
5022 if (sh) {
5023 lower_discard_flow(sh->ir);
5024 }
5025 }
5026
5027 if (prog->SeparateShader)
5028 disable_varying_optimizations_for_sso(prog);
5029
5030 /* Process UBOs */
5031 if (!interstage_cross_validate_uniform_blocks(prog, false))
5032 goto done;
5033
5034 /* Process SSBOs */
5035 if (!interstage_cross_validate_uniform_blocks(prog, true))
5036 goto done;
5037
5038 /* Do common optimization before assigning storage for attributes,
5039 * uniforms, and varyings. Later optimization could possibly make
5040 * some of that unused.
5041 */
5042 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
5043 if (prog->_LinkedShaders[i] == NULL)
5044 continue;
5045
5046 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
5047 if (!prog->data->LinkStatus)
5048 goto done;
5049
5050 if (ctx->Const.ShaderCompilerOptions[i].LowerCombinedClipCullDistance) {
5051 lower_clip_cull_distance(prog, prog->_LinkedShaders[i]);
5052 }
5053
5054 if (ctx->Const.LowerTessLevel) {
5055 lower_tess_level(prog->_LinkedShaders[i]);
5056 }
5057
5058 /* Call opts before lowering const arrays to uniforms so we can const
5059 * propagate any elements accessed directly.
5060 */
5061 linker_optimisation_loop(ctx, prog->_LinkedShaders[i]->ir, i);
5062
5063 /* Call opts after lowering const arrays to copy propagate things. */
5064 if (lower_const_arrays_to_uniforms(prog->_LinkedShaders[i]->ir, i))
5065 linker_optimisation_loop(ctx, prog->_LinkedShaders[i]->ir, i);
5066
5067 propagate_invariance(prog->_LinkedShaders[i]->ir);
5068 }
5069
5070 /* Validation for special cases where we allow sampler array indexing
5071 * with loop induction variable. This check emits a warning or error
5072 * depending if backend can handle dynamic indexing.
5073 */
5074 if ((!prog->IsES && prog->data->Version < 130) ||
5075 (prog->IsES && prog->data->Version < 300)) {
5076 if (!validate_sampler_array_indexing(ctx, prog))
5077 goto done;
5078 }
5079
5080 /* Check and validate stream emissions in geometry shaders */
5081 validate_geometry_shader_emissions(ctx, prog);
5082
5083 store_fragdepth_layout(prog);
5084
5085 if(!link_varyings_and_uniforms(first, last, ctx, prog, mem_ctx))
5086 goto done;
5087
5088 /* Linking varyings can cause some extra, useless swizzles to be generated
5089 * due to packing and unpacking.
5090 */
5091 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
5092 if (prog->_LinkedShaders[i] == NULL)
5093 continue;
5094
5095 optimize_swizzles(prog->_LinkedShaders[i]->ir);
5096 }
5097
5098 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
5099 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
5100 * anything about shader linking when one of the shaders (vertex or
5101 * fragment shader) is absent. So, the extension shouldn't change the
5102 * behavior specified in GLSL specification.
5103 *
5104 * From OpenGL ES 3.1 specification (7.3 Program Objects):
5105 * "Linking can fail for a variety of reasons as specified in the
5106 * OpenGL ES Shading Language Specification, as well as any of the
5107 * following reasons:
5108 *
5109 * ...
5110 *
5111 * * program contains objects to form either a vertex shader or
5112 * fragment shader, and program is not separable, and does not
5113 * contain objects to form both a vertex shader and fragment
5114 * shader."
5115 *
5116 * However, the only scenario in 3.1+ where we don't require them both is
5117 * when we have a compute shader. For example:
5118 *
5119 * - No shaders is a link error.
5120 * - Geom or Tess without a Vertex shader is a link error which means we
5121 * always require a Vertex shader and hence a Fragment shader.
5122 * - Finally a Compute shader linked with any other stage is a link error.
5123 */
5124 if (!prog->SeparateShader && ctx->API == API_OPENGLES2 &&
5125 num_shaders[MESA_SHADER_COMPUTE] == 0) {
5126 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
5127 linker_error(prog, "program lacks a vertex shader\n");
5128 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
5129 linker_error(prog, "program lacks a fragment shader\n");
5130 }
5131 }
5132
5133 done:
5134 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
5135 free(shader_list[i]);
5136 if (prog->_LinkedShaders[i] == NULL)
5137 continue;
5138
5139 /* Do a final validation step to make sure that the IR wasn't
5140 * invalidated by any modifications performed after intrastage linking.
5141 */
5142 validate_ir_tree(prog->_LinkedShaders[i]->ir);
5143
5144 /* Retain any live IR, but trash the rest. */
5145 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
5146
5147 /* The symbol table in the linked shaders may contain references to
5148 * variables that were removed (e.g., unused uniforms). Since it may
5149 * contain junk, there is no possible valid use. Delete it and set the
5150 * pointer to NULL.
5151 */
5152 delete prog->_LinkedShaders[i]->symbols;
5153 prog->_LinkedShaders[i]->symbols = NULL;
5154 }
5155
5156 ralloc_free(mem_ctx);
5157 }