glsl: remove propagate_invariance() call from the linker
[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 "linker_util.h"
80 #include "link_varyings.h"
81 #include "ir_optimization.h"
82 #include "ir_rvalue_visitor.h"
83 #include "ir_uniform.h"
84 #include "builtin_functions.h"
85 #include "shader_cache.h"
86 #include "util/u_string.h"
87 #include "util/u_math.h"
88
89 #include "main/imports.h"
90 #include "main/shaderobj.h"
91 #include "main/enums.h"
92 #include "main/mtypes.h"
93
94
95 namespace {
96
97 struct find_variable {
98 const char *name;
99 bool found;
100
101 find_variable(const char *name) : name(name), found(false) {}
102 };
103
104 /**
105 * Visitor that determines whether or not a variable is ever written.
106 *
107 * Use \ref find_assignments for convenience.
108 */
109 class find_assignment_visitor : public ir_hierarchical_visitor {
110 public:
111 find_assignment_visitor(unsigned num_vars,
112 find_variable * const *vars)
113 : num_variables(num_vars), num_found(0), variables(vars)
114 {
115 }
116
117 virtual ir_visitor_status visit_enter(ir_assignment *ir)
118 {
119 ir_variable *const var = ir->lhs->variable_referenced();
120
121 return check_variable_name(var->name);
122 }
123
124 virtual ir_visitor_status visit_enter(ir_call *ir)
125 {
126 foreach_two_lists(formal_node, &ir->callee->parameters,
127 actual_node, &ir->actual_parameters) {
128 ir_rvalue *param_rval = (ir_rvalue *) actual_node;
129 ir_variable *sig_param = (ir_variable *) formal_node;
130
131 if (sig_param->data.mode == ir_var_function_out ||
132 sig_param->data.mode == ir_var_function_inout) {
133 ir_variable *var = param_rval->variable_referenced();
134 if (var && check_variable_name(var->name) == visit_stop)
135 return visit_stop;
136 }
137 }
138
139 if (ir->return_deref != NULL) {
140 ir_variable *const var = ir->return_deref->variable_referenced();
141
142 if (check_variable_name(var->name) == visit_stop)
143 return visit_stop;
144 }
145
146 return visit_continue_with_parent;
147 }
148
149 private:
150 ir_visitor_status check_variable_name(const char *name)
151 {
152 for (unsigned i = 0; i < num_variables; ++i) {
153 if (strcmp(variables[i]->name, name) == 0) {
154 if (!variables[i]->found) {
155 variables[i]->found = true;
156
157 assert(num_found < num_variables);
158 if (++num_found == num_variables)
159 return visit_stop;
160 }
161 break;
162 }
163 }
164
165 return visit_continue_with_parent;
166 }
167
168 private:
169 unsigned num_variables; /**< Number of variables to find */
170 unsigned num_found; /**< Number of variables already found */
171 find_variable * const *variables; /**< Variables to find */
172 };
173
174 /**
175 * Determine whether or not any of NULL-terminated list of variables is ever
176 * written to.
177 */
178 static void
179 find_assignments(exec_list *ir, find_variable * const *vars)
180 {
181 unsigned num_variables = 0;
182
183 for (find_variable * const *v = vars; *v; ++v)
184 num_variables++;
185
186 find_assignment_visitor visitor(num_variables, vars);
187 visitor.run(ir);
188 }
189
190 /**
191 * Determine whether or not the given variable is ever written to.
192 */
193 static void
194 find_assignments(exec_list *ir, find_variable *var)
195 {
196 find_assignment_visitor visitor(1, &var);
197 visitor.run(ir);
198 }
199
200 /**
201 * Visitor that determines whether or not a variable is ever read.
202 */
203 class find_deref_visitor : public ir_hierarchical_visitor {
204 public:
205 find_deref_visitor(const char *name)
206 : name(name), found(false)
207 {
208 /* empty */
209 }
210
211 virtual ir_visitor_status visit(ir_dereference_variable *ir)
212 {
213 if (strcmp(this->name, ir->var->name) == 0) {
214 this->found = true;
215 return visit_stop;
216 }
217
218 return visit_continue;
219 }
220
221 bool variable_found() const
222 {
223 return this->found;
224 }
225
226 private:
227 const char *name; /**< Find writes to a variable with this name. */
228 bool found; /**< Was a write to the variable found? */
229 };
230
231
232 /**
233 * A visitor helper that provides methods for updating the types of
234 * ir_dereferences. Classes that update variable types (say, updating
235 * array sizes) will want to use this so that dereference types stay in sync.
236 */
237 class deref_type_updater : public ir_hierarchical_visitor {
238 public:
239 virtual ir_visitor_status visit(ir_dereference_variable *ir)
240 {
241 ir->type = ir->var->type;
242 return visit_continue;
243 }
244
245 virtual ir_visitor_status visit_leave(ir_dereference_array *ir)
246 {
247 const glsl_type *const vt = ir->array->type;
248 if (vt->is_array())
249 ir->type = vt->fields.array;
250 return visit_continue;
251 }
252
253 virtual ir_visitor_status visit_leave(ir_dereference_record *ir)
254 {
255 ir->type = ir->record->type->fields.structure[ir->field_idx].type;
256 return visit_continue;
257 }
258 };
259
260
261 class array_resize_visitor : public deref_type_updater {
262 public:
263 unsigned num_vertices;
264 gl_shader_program *prog;
265 gl_shader_stage stage;
266
267 array_resize_visitor(unsigned num_vertices,
268 gl_shader_program *prog,
269 gl_shader_stage stage)
270 {
271 this->num_vertices = num_vertices;
272 this->prog = prog;
273 this->stage = stage;
274 }
275
276 virtual ~array_resize_visitor()
277 {
278 /* empty */
279 }
280
281 virtual ir_visitor_status visit(ir_variable *var)
282 {
283 if (!var->type->is_array() || var->data.mode != ir_var_shader_in ||
284 var->data.patch)
285 return visit_continue;
286
287 unsigned size = var->type->length;
288
289 if (stage == MESA_SHADER_GEOMETRY) {
290 /* Generate a link error if the shader has declared this array with
291 * an incorrect size.
292 */
293 if (!var->data.implicit_sized_array &&
294 size && size != this->num_vertices) {
295 linker_error(this->prog, "size of array %s declared as %u, "
296 "but number of input vertices is %u\n",
297 var->name, size, this->num_vertices);
298 return visit_continue;
299 }
300
301 /* Generate a link error if the shader attempts to access an input
302 * array using an index too large for its actual size assigned at
303 * link time.
304 */
305 if (var->data.max_array_access >= (int)this->num_vertices) {
306 linker_error(this->prog, "%s shader accesses element %i of "
307 "%s, but only %i input vertices\n",
308 _mesa_shader_stage_to_string(this->stage),
309 var->data.max_array_access, var->name, this->num_vertices);
310 return visit_continue;
311 }
312 }
313
314 var->type = glsl_type::get_array_instance(var->type->fields.array,
315 this->num_vertices);
316 var->data.max_array_access = this->num_vertices - 1;
317
318 return visit_continue;
319 }
320 };
321
322 /**
323 * Visitor that determines the highest stream id to which a (geometry) shader
324 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
325 */
326 class find_emit_vertex_visitor : public ir_hierarchical_visitor {
327 public:
328 find_emit_vertex_visitor(int max_allowed)
329 : max_stream_allowed(max_allowed),
330 invalid_stream_id(0),
331 invalid_stream_id_from_emit_vertex(false),
332 end_primitive_found(false),
333 uses_non_zero_stream(false)
334 {
335 /* empty */
336 }
337
338 virtual ir_visitor_status visit_leave(ir_emit_vertex *ir)
339 {
340 int stream_id = ir->stream_id();
341
342 if (stream_id < 0) {
343 invalid_stream_id = stream_id;
344 invalid_stream_id_from_emit_vertex = true;
345 return visit_stop;
346 }
347
348 if (stream_id > max_stream_allowed) {
349 invalid_stream_id = stream_id;
350 invalid_stream_id_from_emit_vertex = true;
351 return visit_stop;
352 }
353
354 if (stream_id != 0)
355 uses_non_zero_stream = true;
356
357 return visit_continue;
358 }
359
360 virtual ir_visitor_status visit_leave(ir_end_primitive *ir)
361 {
362 end_primitive_found = true;
363
364 int stream_id = ir->stream_id();
365
366 if (stream_id < 0) {
367 invalid_stream_id = stream_id;
368 invalid_stream_id_from_emit_vertex = false;
369 return visit_stop;
370 }
371
372 if (stream_id > max_stream_allowed) {
373 invalid_stream_id = stream_id;
374 invalid_stream_id_from_emit_vertex = false;
375 return visit_stop;
376 }
377
378 if (stream_id != 0)
379 uses_non_zero_stream = true;
380
381 return visit_continue;
382 }
383
384 bool error()
385 {
386 return invalid_stream_id != 0;
387 }
388
389 const char *error_func()
390 {
391 return invalid_stream_id_from_emit_vertex ?
392 "EmitStreamVertex" : "EndStreamPrimitive";
393 }
394
395 int error_stream()
396 {
397 return invalid_stream_id;
398 }
399
400 bool uses_streams()
401 {
402 return uses_non_zero_stream;
403 }
404
405 bool uses_end_primitive()
406 {
407 return end_primitive_found;
408 }
409
410 private:
411 int max_stream_allowed;
412 int invalid_stream_id;
413 bool invalid_stream_id_from_emit_vertex;
414 bool end_primitive_found;
415 bool uses_non_zero_stream;
416 };
417
418 /* Class that finds array derefs and check if indexes are dynamic. */
419 class dynamic_sampler_array_indexing_visitor : public ir_hierarchical_visitor
420 {
421 public:
422 dynamic_sampler_array_indexing_visitor() :
423 dynamic_sampler_array_indexing(false)
424 {
425 }
426
427 ir_visitor_status visit_enter(ir_dereference_array *ir)
428 {
429 if (!ir->variable_referenced())
430 return visit_continue;
431
432 if (!ir->variable_referenced()->type->contains_sampler())
433 return visit_continue;
434
435 if (!ir->array_index->constant_expression_value(ralloc_parent(ir))) {
436 dynamic_sampler_array_indexing = true;
437 return visit_stop;
438 }
439 return visit_continue;
440 }
441
442 bool uses_dynamic_sampler_array_indexing()
443 {
444 return dynamic_sampler_array_indexing;
445 }
446
447 private:
448 bool dynamic_sampler_array_indexing;
449 };
450
451 } /* anonymous namespace */
452
453 void
454 linker_error(gl_shader_program *prog, const char *fmt, ...)
455 {
456 va_list ap;
457
458 ralloc_strcat(&prog->data->InfoLog, "error: ");
459 va_start(ap, fmt);
460 ralloc_vasprintf_append(&prog->data->InfoLog, fmt, ap);
461 va_end(ap);
462
463 prog->data->LinkStatus = LINKING_FAILURE;
464 }
465
466
467 void
468 linker_warning(gl_shader_program *prog, const char *fmt, ...)
469 {
470 va_list ap;
471
472 ralloc_strcat(&prog->data->InfoLog, "warning: ");
473 va_start(ap, fmt);
474 ralloc_vasprintf_append(&prog->data->InfoLog, fmt, ap);
475 va_end(ap);
476
477 }
478
479
480 /**
481 * Given a string identifying a program resource, break it into a base name
482 * and an optional array index in square brackets.
483 *
484 * If an array index is present, \c out_base_name_end is set to point to the
485 * "[" that precedes the array index, and the array index itself is returned
486 * as a long.
487 *
488 * If no array index is present (or if the array index is negative or
489 * mal-formed), \c out_base_name_end, is set to point to the null terminator
490 * at the end of the input string, and -1 is returned.
491 *
492 * Only the final array index is parsed; if the string contains other array
493 * indices (or structure field accesses), they are left in the base name.
494 *
495 * No attempt is made to check that the base name is properly formed;
496 * typically the caller will look up the base name in a hash table, so
497 * ill-formed base names simply turn into hash table lookup failures.
498 */
499 long
500 parse_program_resource_name(const GLchar *name,
501 const GLchar **out_base_name_end)
502 {
503 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
504 *
505 * "When an integer array element or block instance number is part of
506 * the name string, it will be specified in decimal form without a "+"
507 * or "-" sign or any extra leading zeroes. Additionally, the name
508 * string will not include white space anywhere in the string."
509 */
510
511 const size_t len = strlen(name);
512 *out_base_name_end = name + len;
513
514 if (len == 0 || name[len-1] != ']')
515 return -1;
516
517 /* Walk backwards over the string looking for a non-digit character. This
518 * had better be the opening bracket for an array index.
519 *
520 * Initially, i specifies the location of the ']'. Since the string may
521 * contain only the ']' charcater, walk backwards very carefully.
522 */
523 unsigned i;
524 for (i = len - 1; (i > 0) && isdigit(name[i-1]); --i)
525 /* empty */ ;
526
527 if ((i == 0) || name[i-1] != '[')
528 return -1;
529
530 long array_index = strtol(&name[i], NULL, 10);
531 if (array_index < 0)
532 return -1;
533
534 /* Check for leading zero */
535 if (name[i] == '0' && name[i+1] != ']')
536 return -1;
537
538 *out_base_name_end = name + (i - 1);
539 return array_index;
540 }
541
542
543 void
544 link_invalidate_variable_locations(exec_list *ir)
545 {
546 foreach_in_list(ir_instruction, node, ir) {
547 ir_variable *const var = node->as_variable();
548
549 if (var == NULL)
550 continue;
551
552 /* Only assign locations for variables that lack an explicit location.
553 * Explicit locations are set for all built-in variables, generic vertex
554 * shader inputs (via layout(location=...)), and generic fragment shader
555 * outputs (also via layout(location=...)).
556 */
557 if (!var->data.explicit_location) {
558 var->data.location = -1;
559 var->data.location_frac = 0;
560 }
561
562 /* ir_variable::is_unmatched_generic_inout is used by the linker while
563 * connecting outputs from one stage to inputs of the next stage.
564 */
565 if (var->data.explicit_location &&
566 var->data.location < VARYING_SLOT_VAR0) {
567 var->data.is_unmatched_generic_inout = 0;
568 } else {
569 var->data.is_unmatched_generic_inout = 1;
570 }
571 }
572 }
573
574
575 /**
576 * Set clip_distance_array_size based and cull_distance_array_size on the given
577 * shader.
578 *
579 * Also check for errors based on incorrect usage of gl_ClipVertex and
580 * gl_ClipDistance and gl_CullDistance.
581 * Additionally test whether the arrays gl_ClipDistance and gl_CullDistance
582 * exceed the maximum size defined by gl_MaxCombinedClipAndCullDistances.
583 *
584 * Return false if an error was reported.
585 */
586 static void
587 analyze_clip_cull_usage(struct gl_shader_program *prog,
588 struct gl_linked_shader *shader,
589 struct gl_context *ctx,
590 GLuint *clip_distance_array_size,
591 GLuint *cull_distance_array_size)
592 {
593 *clip_distance_array_size = 0;
594 *cull_distance_array_size = 0;
595
596 if (prog->data->Version >= (prog->IsES ? 300 : 130)) {
597 /* From section 7.1 (Vertex Shader Special Variables) of the
598 * GLSL 1.30 spec:
599 *
600 * "It is an error for a shader to statically write both
601 * gl_ClipVertex and gl_ClipDistance."
602 *
603 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
604 * gl_ClipVertex nor gl_ClipDistance. However with
605 * GL_EXT_clip_cull_distance, this functionality is exposed in ES 3.0.
606 */
607 find_variable gl_ClipDistance("gl_ClipDistance");
608 find_variable gl_CullDistance("gl_CullDistance");
609 find_variable gl_ClipVertex("gl_ClipVertex");
610 find_variable * const variables[] = {
611 &gl_ClipDistance,
612 &gl_CullDistance,
613 !prog->IsES ? &gl_ClipVertex : NULL,
614 NULL
615 };
616 find_assignments(shader->ir, variables);
617
618 /* From the ARB_cull_distance spec:
619 *
620 * It is a compile-time or link-time error for the set of shaders forming
621 * a program to statically read or write both gl_ClipVertex and either
622 * gl_ClipDistance or gl_CullDistance.
623 *
624 * This does not apply to GLSL ES shaders, since GLSL ES doesn't define
625 * gl_ClipVertex.
626 */
627 if (!prog->IsES) {
628 if (gl_ClipVertex.found && gl_ClipDistance.found) {
629 linker_error(prog, "%s shader writes to both `gl_ClipVertex' "
630 "and `gl_ClipDistance'\n",
631 _mesa_shader_stage_to_string(shader->Stage));
632 return;
633 }
634 if (gl_ClipVertex.found && gl_CullDistance.found) {
635 linker_error(prog, "%s shader writes to both `gl_ClipVertex' "
636 "and `gl_CullDistance'\n",
637 _mesa_shader_stage_to_string(shader->Stage));
638 return;
639 }
640 }
641
642 if (gl_ClipDistance.found) {
643 ir_variable *clip_distance_var =
644 shader->symbols->get_variable("gl_ClipDistance");
645 assert(clip_distance_var);
646 *clip_distance_array_size = clip_distance_var->type->length;
647 }
648 if (gl_CullDistance.found) {
649 ir_variable *cull_distance_var =
650 shader->symbols->get_variable("gl_CullDistance");
651 assert(cull_distance_var);
652 *cull_distance_array_size = cull_distance_var->type->length;
653 }
654 /* From the ARB_cull_distance spec:
655 *
656 * It is a compile-time or link-time error for the set of shaders forming
657 * a program to have the sum of the sizes of the gl_ClipDistance and
658 * gl_CullDistance arrays to be larger than
659 * gl_MaxCombinedClipAndCullDistances.
660 */
661 if ((*clip_distance_array_size + *cull_distance_array_size) >
662 ctx->Const.MaxClipPlanes) {
663 linker_error(prog, "%s shader: the combined size of "
664 "'gl_ClipDistance' and 'gl_CullDistance' size cannot "
665 "be larger than "
666 "gl_MaxCombinedClipAndCullDistances (%u)",
667 _mesa_shader_stage_to_string(shader->Stage),
668 ctx->Const.MaxClipPlanes);
669 }
670 }
671 }
672
673
674 /**
675 * Verify that a vertex shader executable meets all semantic requirements.
676 *
677 * Also sets info.clip_distance_array_size and
678 * info.cull_distance_array_size as a side effect.
679 *
680 * \param shader Vertex shader executable to be verified
681 */
682 static void
683 validate_vertex_shader_executable(struct gl_shader_program *prog,
684 struct gl_linked_shader *shader,
685 struct gl_context *ctx)
686 {
687 if (shader == NULL)
688 return;
689
690 /* From the GLSL 1.10 spec, page 48:
691 *
692 * "The variable gl_Position is available only in the vertex
693 * language and is intended for writing the homogeneous vertex
694 * position. All executions of a well-formed vertex shader
695 * executable must write a value into this variable. [...] The
696 * variable gl_Position is available only in the vertex
697 * language and is intended for writing the homogeneous vertex
698 * position. All executions of a well-formed vertex shader
699 * executable must write a value into this variable."
700 *
701 * while in GLSL 1.40 this text is changed to:
702 *
703 * "The variable gl_Position is available only in the vertex
704 * language and is intended for writing the homogeneous vertex
705 * position. It can be written at any time during shader
706 * execution. It may also be read back by a vertex shader
707 * after being written. This value will be used by primitive
708 * assembly, clipping, culling, and other fixed functionality
709 * operations, if present, that operate on primitives after
710 * vertex processing has occurred. Its value is undefined if
711 * the vertex shader executable does not write gl_Position."
712 *
713 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
714 * gl_Position is not an error.
715 */
716 if (prog->data->Version < (prog->IsES ? 300 : 140)) {
717 find_variable gl_Position("gl_Position");
718 find_assignments(shader->ir, &gl_Position);
719 if (!gl_Position.found) {
720 if (prog->IsES) {
721 linker_warning(prog,
722 "vertex shader does not write to `gl_Position'. "
723 "Its value is undefined. \n");
724 } else {
725 linker_error(prog,
726 "vertex shader does not write to `gl_Position'. \n");
727 }
728 return;
729 }
730 }
731
732 analyze_clip_cull_usage(prog, shader, ctx,
733 &shader->Program->info.clip_distance_array_size,
734 &shader->Program->info.cull_distance_array_size);
735 }
736
737 static void
738 validate_tess_eval_shader_executable(struct gl_shader_program *prog,
739 struct gl_linked_shader *shader,
740 struct gl_context *ctx)
741 {
742 if (shader == NULL)
743 return;
744
745 analyze_clip_cull_usage(prog, shader, ctx,
746 &shader->Program->info.clip_distance_array_size,
747 &shader->Program->info.cull_distance_array_size);
748 }
749
750
751 /**
752 * Verify that a fragment shader executable meets all semantic requirements
753 *
754 * \param shader Fragment shader executable to be verified
755 */
756 static void
757 validate_fragment_shader_executable(struct gl_shader_program *prog,
758 struct gl_linked_shader *shader)
759 {
760 if (shader == NULL)
761 return;
762
763 find_variable gl_FragColor("gl_FragColor");
764 find_variable gl_FragData("gl_FragData");
765 find_variable * const variables[] = { &gl_FragColor, &gl_FragData, NULL };
766 find_assignments(shader->ir, variables);
767
768 if (gl_FragColor.found && gl_FragData.found) {
769 linker_error(prog, "fragment shader writes to both "
770 "`gl_FragColor' and `gl_FragData'\n");
771 }
772 }
773
774 /**
775 * Verify that a geometry shader executable meets all semantic requirements
776 *
777 * Also sets prog->Geom.VerticesIn, and info.clip_distance_array_sizeand
778 * info.cull_distance_array_size as a side effect.
779 *
780 * \param shader Geometry shader executable to be verified
781 */
782 static void
783 validate_geometry_shader_executable(struct gl_shader_program *prog,
784 struct gl_linked_shader *shader,
785 struct gl_context *ctx)
786 {
787 if (shader == NULL)
788 return;
789
790 unsigned num_vertices =
791 vertices_per_prim(shader->Program->info.gs.input_primitive);
792 prog->Geom.VerticesIn = num_vertices;
793
794 analyze_clip_cull_usage(prog, shader, ctx,
795 &shader->Program->info.clip_distance_array_size,
796 &shader->Program->info.cull_distance_array_size);
797 }
798
799 /**
800 * Check if geometry shaders emit to non-zero streams and do corresponding
801 * validations.
802 */
803 static void
804 validate_geometry_shader_emissions(struct gl_context *ctx,
805 struct gl_shader_program *prog)
806 {
807 struct gl_linked_shader *sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
808
809 if (sh != NULL) {
810 find_emit_vertex_visitor emit_vertex(ctx->Const.MaxVertexStreams - 1);
811 emit_vertex.run(sh->ir);
812 if (emit_vertex.error()) {
813 linker_error(prog, "Invalid call %s(%d). Accepted values for the "
814 "stream parameter are in the range [0, %d].\n",
815 emit_vertex.error_func(),
816 emit_vertex.error_stream(),
817 ctx->Const.MaxVertexStreams - 1);
818 }
819 prog->Geom.UsesStreams = emit_vertex.uses_streams();
820 prog->Geom.UsesEndPrimitive = emit_vertex.uses_end_primitive();
821
822 /* From the ARB_gpu_shader5 spec:
823 *
824 * "Multiple vertex streams are supported only if the output primitive
825 * type is declared to be "points". A program will fail to link if it
826 * contains a geometry shader calling EmitStreamVertex() or
827 * EndStreamPrimitive() if its output primitive type is not "points".
828 *
829 * However, in the same spec:
830 *
831 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
832 * with <stream> set to zero."
833 *
834 * And:
835 *
836 * "The function EndPrimitive() is equivalent to calling
837 * EndStreamPrimitive() with <stream> set to zero."
838 *
839 * Since we can call EmitVertex() and EndPrimitive() when we output
840 * primitives other than points, calling EmitStreamVertex(0) or
841 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
842 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
843 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
844 * stream.
845 */
846 if (prog->Geom.UsesStreams &&
847 sh->Program->info.gs.output_primitive != GL_POINTS) {
848 linker_error(prog, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
849 "with n>0 requires point output\n");
850 }
851 }
852 }
853
854 bool
855 validate_intrastage_arrays(struct gl_shader_program *prog,
856 ir_variable *const var,
857 ir_variable *const existing,
858 bool match_precision)
859 {
860 /* Consider the types to be "the same" if both types are arrays
861 * of the same type and one of the arrays is implicitly sized.
862 * In addition, set the type of the linked variable to the
863 * explicitly sized array.
864 */
865 if (var->type->is_array() && existing->type->is_array()) {
866 const glsl_type *no_array_var = var->type->fields.array;
867 const glsl_type *no_array_existing = existing->type->fields.array;
868 bool type_matches;
869
870 type_matches = (match_precision ?
871 no_array_var == no_array_existing :
872 no_array_var->compare_no_precision(no_array_existing));
873
874 if (type_matches &&
875 ((var->type->length == 0)|| (existing->type->length == 0))) {
876 if (var->type->length != 0) {
877 if ((int)var->type->length <= existing->data.max_array_access) {
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, var->type->name,
883 existing->data.max_array_access);
884 }
885 existing->type = var->type;
886 return true;
887 } else if (existing->type->length != 0) {
888 if((int)existing->type->length <= var->data.max_array_access &&
889 !existing->data.from_ssbo_unsized_array) {
890 linker_error(prog, "%s `%s' declared as type "
891 "`%s' but outermost dimension has an index"
892 " of `%i'\n",
893 mode_string(var),
894 var->name, existing->type->name,
895 var->data.max_array_access);
896 }
897 return true;
898 }
899 }
900 }
901 return false;
902 }
903
904
905 /**
906 * Perform validation of global variables used across multiple shaders
907 */
908 static void
909 cross_validate_globals(struct gl_context *ctx, struct gl_shader_program *prog,
910 struct exec_list *ir, glsl_symbol_table *variables,
911 bool uniforms_only)
912 {
913 foreach_in_list(ir_instruction, node, ir) {
914 ir_variable *const var = node->as_variable();
915
916 if (var == NULL)
917 continue;
918
919 if (uniforms_only && (var->data.mode != ir_var_uniform && var->data.mode != ir_var_shader_storage))
920 continue;
921
922 /* don't cross validate subroutine uniforms */
923 if (var->type->contains_subroutine())
924 continue;
925
926 /* Don't cross validate interface instances. These are only relevant
927 * inside a shader. The cross validation is done at the Interface Block
928 * name level.
929 */
930 if (var->is_interface_instance())
931 continue;
932
933 /* Don't cross validate temporaries that are at global scope. These
934 * will eventually get pulled into the shaders 'main'.
935 */
936 if (var->data.mode == ir_var_temporary)
937 continue;
938
939 /* If a global with this name has already been seen, verify that the
940 * new instance has the same type. In addition, if the globals have
941 * initializers, the values of the initializers must be the same.
942 */
943 ir_variable *const existing = variables->get_variable(var->name);
944 if (existing != NULL) {
945 /* Check if types match. */
946 if (var->type != existing->type) {
947 if (!validate_intrastage_arrays(prog, var, existing)) {
948 /* If it is an unsized array in a Shader Storage Block,
949 * two different shaders can access to different elements.
950 * Because of that, they might be converted to different
951 * sized arrays, then check that they are compatible but
952 * ignore the array size.
953 */
954 if (!(var->data.mode == ir_var_shader_storage &&
955 var->data.from_ssbo_unsized_array &&
956 existing->data.mode == ir_var_shader_storage &&
957 existing->data.from_ssbo_unsized_array &&
958 var->type->gl_type == existing->type->gl_type)) {
959 linker_error(prog, "%s `%s' declared as type "
960 "`%s' and type `%s'\n",
961 mode_string(var),
962 var->name, var->type->name,
963 existing->type->name);
964 return;
965 }
966 }
967 }
968
969 if (var->data.explicit_location) {
970 if (existing->data.explicit_location
971 && (var->data.location != existing->data.location)) {
972 linker_error(prog, "explicit locations for %s "
973 "`%s' have differing values\n",
974 mode_string(var), var->name);
975 return;
976 }
977
978 if (var->data.location_frac != existing->data.location_frac) {
979 linker_error(prog, "explicit components for %s `%s' have "
980 "differing values\n", mode_string(var), var->name);
981 return;
982 }
983
984 existing->data.location = var->data.location;
985 existing->data.explicit_location = true;
986 } else {
987 /* Check if uniform with implicit location was marked explicit
988 * by earlier shader stage. If so, mark it explicit in this stage
989 * too to make sure later processing does not treat it as
990 * implicit one.
991 */
992 if (existing->data.explicit_location) {
993 var->data.location = existing->data.location;
994 var->data.explicit_location = true;
995 }
996 }
997
998 /* From the GLSL 4.20 specification:
999 * "A link error will result if two compilation units in a program
1000 * specify different integer-constant bindings for the same
1001 * opaque-uniform name. However, it is not an error to specify a
1002 * binding on some but not all declarations for the same name"
1003 */
1004 if (var->data.explicit_binding) {
1005 if (existing->data.explicit_binding &&
1006 var->data.binding != existing->data.binding) {
1007 linker_error(prog, "explicit bindings for %s "
1008 "`%s' have differing values\n",
1009 mode_string(var), var->name);
1010 return;
1011 }
1012
1013 existing->data.binding = var->data.binding;
1014 existing->data.explicit_binding = true;
1015 }
1016
1017 if (var->type->contains_atomic() &&
1018 var->data.offset != existing->data.offset) {
1019 linker_error(prog, "offset specifications for %s "
1020 "`%s' have differing values\n",
1021 mode_string(var), var->name);
1022 return;
1023 }
1024
1025 /* Validate layout qualifiers for gl_FragDepth.
1026 *
1027 * From the AMD/ARB_conservative_depth specs:
1028 *
1029 * "If gl_FragDepth is redeclared in any fragment shader in a
1030 * program, it must be redeclared in all fragment shaders in
1031 * that program that have static assignments to
1032 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1033 * fragment shaders in a single program must have the same set
1034 * of qualifiers."
1035 */
1036 if (strcmp(var->name, "gl_FragDepth") == 0) {
1037 bool layout_declared = var->data.depth_layout != ir_depth_layout_none;
1038 bool layout_differs =
1039 var->data.depth_layout != existing->data.depth_layout;
1040
1041 if (layout_declared && layout_differs) {
1042 linker_error(prog,
1043 "All redeclarations of gl_FragDepth in all "
1044 "fragment shaders in a single program must have "
1045 "the same set of qualifiers.\n");
1046 }
1047
1048 if (var->data.used && layout_differs) {
1049 linker_error(prog,
1050 "If gl_FragDepth is redeclared with a layout "
1051 "qualifier in any fragment shader, it must be "
1052 "redeclared with the same layout qualifier in "
1053 "all fragment shaders that have assignments to "
1054 "gl_FragDepth\n");
1055 }
1056 }
1057
1058 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1059 *
1060 * "If a shared global has multiple initializers, the
1061 * initializers must all be constant expressions, and they
1062 * must all have the same value. Otherwise, a link error will
1063 * result. (A shared global having only one initializer does
1064 * not require that initializer to be a constant expression.)"
1065 *
1066 * Previous to 4.20 the GLSL spec simply said that initializers
1067 * must have the same value. In this case of non-constant
1068 * initializers, this was impossible to determine. As a result,
1069 * no vendor actually implemented that behavior. The 4.20
1070 * behavior matches the implemented behavior of at least one other
1071 * vendor, so we'll implement that for all GLSL versions.
1072 */
1073 if (var->constant_initializer != NULL) {
1074 if (existing->constant_initializer != NULL) {
1075 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
1076 linker_error(prog, "initializers for %s "
1077 "`%s' have differing values\n",
1078 mode_string(var), var->name);
1079 return;
1080 }
1081 } else {
1082 /* If the first-seen instance of a particular uniform did
1083 * not have an initializer but a later instance does,
1084 * replace the former with the later.
1085 */
1086 variables->replace_variable(existing->name, var);
1087 }
1088 }
1089
1090 if (var->data.has_initializer) {
1091 if (existing->data.has_initializer
1092 && (var->constant_initializer == NULL
1093 || existing->constant_initializer == NULL)) {
1094 linker_error(prog,
1095 "shared global variable `%s' has multiple "
1096 "non-constant initializers.\n",
1097 var->name);
1098 return;
1099 }
1100 }
1101
1102 if (existing->data.explicit_invariant != var->data.explicit_invariant) {
1103 linker_error(prog, "declarations for %s `%s' have "
1104 "mismatching invariant qualifiers\n",
1105 mode_string(var), var->name);
1106 return;
1107 }
1108 if (existing->data.centroid != var->data.centroid) {
1109 linker_error(prog, "declarations for %s `%s' have "
1110 "mismatching centroid qualifiers\n",
1111 mode_string(var), var->name);
1112 return;
1113 }
1114 if (existing->data.sample != var->data.sample) {
1115 linker_error(prog, "declarations for %s `%s` have "
1116 "mismatching sample qualifiers\n",
1117 mode_string(var), var->name);
1118 return;
1119 }
1120 if (existing->data.image_format != var->data.image_format) {
1121 linker_error(prog, "declarations for %s `%s` have "
1122 "mismatching image format qualifiers\n",
1123 mode_string(var), var->name);
1124 return;
1125 }
1126
1127 /* Check the precision qualifier matches for uniform variables on
1128 * GLSL ES.
1129 */
1130 if (!ctx->Const.AllowGLSLRelaxedES &&
1131 prog->IsES && !var->get_interface_type() &&
1132 existing->data.precision != var->data.precision) {
1133 if ((existing->data.used && var->data.used) || prog->data->Version >= 300) {
1134 linker_error(prog, "declarations for %s `%s` have "
1135 "mismatching precision qualifiers\n",
1136 mode_string(var), var->name);
1137 return;
1138 } else {
1139 linker_warning(prog, "declarations for %s `%s` have "
1140 "mismatching precision qualifiers\n",
1141 mode_string(var), var->name);
1142 }
1143 }
1144
1145 /* In OpenGL GLSL 3.20 spec, section 4.3.9:
1146 *
1147 * "It is a link-time error if any particular shader interface
1148 * contains:
1149 *
1150 * - two different blocks, each having no instance name, and each
1151 * having a member of the same name, or
1152 *
1153 * - a variable outside a block, and a block with no instance name,
1154 * where the variable has the same name as a member in the block."
1155 */
1156 const glsl_type *var_itype = var->get_interface_type();
1157 const glsl_type *existing_itype = existing->get_interface_type();
1158 if (var_itype != existing_itype) {
1159 if (!var_itype || !existing_itype) {
1160 linker_error(prog, "declarations for %s `%s` are inside block "
1161 "`%s` and outside a block",
1162 mode_string(var), var->name,
1163 var_itype ? var_itype->name : existing_itype->name);
1164 return;
1165 } else if (strcmp(var_itype->name, existing_itype->name) != 0) {
1166 linker_error(prog, "declarations for %s `%s` are inside blocks "
1167 "`%s` and `%s`",
1168 mode_string(var), var->name,
1169 existing_itype->name,
1170 var_itype->name);
1171 return;
1172 }
1173 }
1174 } else
1175 variables->add_variable(var);
1176 }
1177 }
1178
1179
1180 /**
1181 * Perform validation of uniforms used across multiple shader stages
1182 */
1183 static void
1184 cross_validate_uniforms(struct gl_context *ctx,
1185 struct gl_shader_program *prog)
1186 {
1187 glsl_symbol_table variables;
1188 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1189 if (prog->_LinkedShaders[i] == NULL)
1190 continue;
1191
1192 cross_validate_globals(ctx, prog, prog->_LinkedShaders[i]->ir,
1193 &variables, true);
1194 }
1195 }
1196
1197 /**
1198 * Accumulates the array of buffer blocks and checks that all definitions of
1199 * blocks agree on their contents.
1200 */
1201 static bool
1202 interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog,
1203 bool validate_ssbo)
1204 {
1205 int *InterfaceBlockStageIndex[MESA_SHADER_STAGES];
1206 struct gl_uniform_block *blks = NULL;
1207 unsigned *num_blks = validate_ssbo ? &prog->data->NumShaderStorageBlocks :
1208 &prog->data->NumUniformBlocks;
1209
1210 unsigned max_num_buffer_blocks = 0;
1211 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1212 if (prog->_LinkedShaders[i]) {
1213 if (validate_ssbo) {
1214 max_num_buffer_blocks +=
1215 prog->_LinkedShaders[i]->Program->info.num_ssbos;
1216 } else {
1217 max_num_buffer_blocks +=
1218 prog->_LinkedShaders[i]->Program->info.num_ubos;
1219 }
1220 }
1221 }
1222
1223 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1224 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
1225
1226 InterfaceBlockStageIndex[i] = new int[max_num_buffer_blocks];
1227 for (unsigned int j = 0; j < max_num_buffer_blocks; j++)
1228 InterfaceBlockStageIndex[i][j] = -1;
1229
1230 if (sh == NULL)
1231 continue;
1232
1233 unsigned sh_num_blocks;
1234 struct gl_uniform_block **sh_blks;
1235 if (validate_ssbo) {
1236 sh_num_blocks = prog->_LinkedShaders[i]->Program->info.num_ssbos;
1237 sh_blks = sh->Program->sh.ShaderStorageBlocks;
1238 } else {
1239 sh_num_blocks = prog->_LinkedShaders[i]->Program->info.num_ubos;
1240 sh_blks = sh->Program->sh.UniformBlocks;
1241 }
1242
1243 for (unsigned int j = 0; j < sh_num_blocks; j++) {
1244 int index = link_cross_validate_uniform_block(prog->data, &blks,
1245 num_blks, sh_blks[j]);
1246
1247 if (index == -1) {
1248 linker_error(prog, "buffer block `%s' has mismatching "
1249 "definitions\n", sh_blks[j]->Name);
1250
1251 for (unsigned k = 0; k <= i; k++) {
1252 delete[] InterfaceBlockStageIndex[k];
1253 }
1254
1255 /* Reset the block count. This will help avoid various segfaults
1256 * from api calls that assume the array exists due to the count
1257 * being non-zero.
1258 */
1259 *num_blks = 0;
1260 return false;
1261 }
1262
1263 InterfaceBlockStageIndex[i][index] = j;
1264 }
1265 }
1266
1267 /* Update per stage block pointers to point to the program list.
1268 * FIXME: We should be able to free the per stage blocks here.
1269 */
1270 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1271 for (unsigned j = 0; j < *num_blks; j++) {
1272 int stage_index = InterfaceBlockStageIndex[i][j];
1273
1274 if (stage_index != -1) {
1275 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
1276
1277 struct gl_uniform_block **sh_blks = validate_ssbo ?
1278 sh->Program->sh.ShaderStorageBlocks :
1279 sh->Program->sh.UniformBlocks;
1280
1281 blks[j].stageref |= sh_blks[stage_index]->stageref;
1282 sh_blks[stage_index] = &blks[j];
1283 }
1284 }
1285 }
1286
1287 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1288 delete[] InterfaceBlockStageIndex[i];
1289 }
1290
1291 if (validate_ssbo)
1292 prog->data->ShaderStorageBlocks = blks;
1293 else
1294 prog->data->UniformBlocks = blks;
1295
1296 return true;
1297 }
1298
1299 /**
1300 * Verifies the invariance of built-in special variables.
1301 */
1302 static bool
1303 validate_invariant_builtins(struct gl_shader_program *prog,
1304 const gl_linked_shader *vert,
1305 const gl_linked_shader *frag)
1306 {
1307 const ir_variable *var_vert;
1308 const ir_variable *var_frag;
1309
1310 if (!vert || !frag)
1311 return true;
1312
1313 /*
1314 * From OpenGL ES Shading Language 1.0 specification
1315 * (4.6.4 Invariance and Linkage):
1316 * "The invariance of varyings that are declared in both the vertex and
1317 * fragment shaders must match. For the built-in special variables,
1318 * gl_FragCoord can only be declared invariant if and only if
1319 * gl_Position is declared invariant. Similarly gl_PointCoord can only
1320 * be declared invariant if and only if gl_PointSize is declared
1321 * invariant. It is an error to declare gl_FrontFacing as invariant.
1322 * The invariance of gl_FrontFacing is the same as the invariance of
1323 * gl_Position."
1324 */
1325 var_frag = frag->symbols->get_variable("gl_FragCoord");
1326 if (var_frag && var_frag->data.invariant) {
1327 var_vert = vert->symbols->get_variable("gl_Position");
1328 if (var_vert && !var_vert->data.invariant) {
1329 linker_error(prog,
1330 "fragment shader built-in `%s' has invariant qualifier, "
1331 "but vertex shader built-in `%s' lacks invariant qualifier\n",
1332 var_frag->name, var_vert->name);
1333 return false;
1334 }
1335 }
1336
1337 var_frag = frag->symbols->get_variable("gl_PointCoord");
1338 if (var_frag && var_frag->data.invariant) {
1339 var_vert = vert->symbols->get_variable("gl_PointSize");
1340 if (var_vert && !var_vert->data.invariant) {
1341 linker_error(prog,
1342 "fragment shader built-in `%s' has invariant qualifier, "
1343 "but vertex shader built-in `%s' lacks invariant qualifier\n",
1344 var_frag->name, var_vert->name);
1345 return false;
1346 }
1347 }
1348
1349 var_frag = frag->symbols->get_variable("gl_FrontFacing");
1350 if (var_frag && var_frag->data.invariant) {
1351 linker_error(prog,
1352 "fragment shader built-in `%s' can not be declared as invariant\n",
1353 var_frag->name);
1354 return false;
1355 }
1356
1357 return true;
1358 }
1359
1360 /**
1361 * Populates a shaders symbol table with all global declarations
1362 */
1363 static void
1364 populate_symbol_table(gl_linked_shader *sh, glsl_symbol_table *symbols)
1365 {
1366 sh->symbols = new(sh) glsl_symbol_table;
1367
1368 _mesa_glsl_copy_symbols_from_table(sh->ir, symbols, sh->symbols);
1369 }
1370
1371
1372 /**
1373 * Remap variables referenced in an instruction tree
1374 *
1375 * This is used when instruction trees are cloned from one shader and placed in
1376 * another. These trees will contain references to \c ir_variable nodes that
1377 * do not exist in the target shader. This function finds these \c ir_variable
1378 * references and replaces the references with matching variables in the target
1379 * shader.
1380 *
1381 * If there is no matching variable in the target shader, a clone of the
1382 * \c ir_variable is made and added to the target shader. The new variable is
1383 * added to \b both the instruction stream and the symbol table.
1384 *
1385 * \param inst IR tree that is to be processed.
1386 * \param symbols Symbol table containing global scope symbols in the
1387 * linked shader.
1388 * \param instructions Instruction stream where new variable declarations
1389 * should be added.
1390 */
1391 static void
1392 remap_variables(ir_instruction *inst, struct gl_linked_shader *target,
1393 hash_table *temps)
1394 {
1395 class remap_visitor : public ir_hierarchical_visitor {
1396 public:
1397 remap_visitor(struct gl_linked_shader *target, hash_table *temps)
1398 {
1399 this->target = target;
1400 this->symbols = target->symbols;
1401 this->instructions = target->ir;
1402 this->temps = temps;
1403 }
1404
1405 virtual ir_visitor_status visit(ir_dereference_variable *ir)
1406 {
1407 if (ir->var->data.mode == ir_var_temporary) {
1408 hash_entry *entry = _mesa_hash_table_search(temps, ir->var);
1409 ir_variable *var = entry ? (ir_variable *) entry->data : NULL;
1410
1411 assert(var != NULL);
1412 ir->var = var;
1413 return visit_continue;
1414 }
1415
1416 ir_variable *const existing =
1417 this->symbols->get_variable(ir->var->name);
1418 if (existing != NULL)
1419 ir->var = existing;
1420 else {
1421 ir_variable *copy = ir->var->clone(this->target, NULL);
1422
1423 this->symbols->add_variable(copy);
1424 this->instructions->push_head(copy);
1425 ir->var = copy;
1426 }
1427
1428 return visit_continue;
1429 }
1430
1431 private:
1432 struct gl_linked_shader *target;
1433 glsl_symbol_table *symbols;
1434 exec_list *instructions;
1435 hash_table *temps;
1436 };
1437
1438 remap_visitor v(target, temps);
1439
1440 inst->accept(&v);
1441 }
1442
1443
1444 /**
1445 * Move non-declarations from one instruction stream to another
1446 *
1447 * The intended usage pattern of this function is to pass the pointer to the
1448 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1449 * pointer) for \c last and \c false for \c make_copies on the first
1450 * call. Successive calls pass the return value of the previous call for
1451 * \c last and \c true for \c make_copies.
1452 *
1453 * \param instructions Source instruction stream
1454 * \param last Instruction after which new instructions should be
1455 * inserted in the target instruction stream
1456 * \param make_copies Flag selecting whether instructions in \c instructions
1457 * should be copied (via \c ir_instruction::clone) into the
1458 * target list or moved.
1459 *
1460 * \return
1461 * The new "last" instruction in the target instruction stream. This pointer
1462 * is suitable for use as the \c last parameter of a later call to this
1463 * function.
1464 */
1465 static exec_node *
1466 move_non_declarations(exec_list *instructions, exec_node *last,
1467 bool make_copies, gl_linked_shader *target)
1468 {
1469 hash_table *temps = NULL;
1470
1471 if (make_copies)
1472 temps = _mesa_pointer_hash_table_create(NULL);
1473
1474 foreach_in_list_safe(ir_instruction, inst, instructions) {
1475 if (inst->as_function())
1476 continue;
1477
1478 ir_variable *var = inst->as_variable();
1479 if ((var != NULL) && (var->data.mode != ir_var_temporary))
1480 continue;
1481
1482 assert(inst->as_assignment()
1483 || inst->as_call()
1484 || inst->as_if() /* for initializers with the ?: operator */
1485 || ((var != NULL) && (var->data.mode == ir_var_temporary)));
1486
1487 if (make_copies) {
1488 inst = inst->clone(target, NULL);
1489
1490 if (var != NULL)
1491 _mesa_hash_table_insert(temps, var, inst);
1492 else
1493 remap_variables(inst, target, temps);
1494 } else {
1495 inst->remove();
1496 }
1497
1498 last->insert_after(inst);
1499 last = inst;
1500 }
1501
1502 if (make_copies)
1503 _mesa_hash_table_destroy(temps, NULL);
1504
1505 return last;
1506 }
1507
1508
1509 /**
1510 * This class is only used in link_intrastage_shaders() below but declaring
1511 * it inside that function leads to compiler warnings with some versions of
1512 * gcc.
1513 */
1514 class array_sizing_visitor : public deref_type_updater {
1515 public:
1516 array_sizing_visitor()
1517 : mem_ctx(ralloc_context(NULL)),
1518 unnamed_interfaces(_mesa_pointer_hash_table_create(NULL))
1519 {
1520 }
1521
1522 ~array_sizing_visitor()
1523 {
1524 _mesa_hash_table_destroy(this->unnamed_interfaces, NULL);
1525 ralloc_free(this->mem_ctx);
1526 }
1527
1528 virtual ir_visitor_status visit(ir_variable *var)
1529 {
1530 const glsl_type *type_without_array;
1531 bool implicit_sized_array = var->data.implicit_sized_array;
1532 fixup_type(&var->type, var->data.max_array_access,
1533 var->data.from_ssbo_unsized_array,
1534 &implicit_sized_array);
1535 var->data.implicit_sized_array = implicit_sized_array;
1536 type_without_array = var->type->without_array();
1537 if (var->type->is_interface()) {
1538 if (interface_contains_unsized_arrays(var->type)) {
1539 const glsl_type *new_type =
1540 resize_interface_members(var->type,
1541 var->get_max_ifc_array_access(),
1542 var->is_in_shader_storage_block());
1543 var->type = new_type;
1544 var->change_interface_type(new_type);
1545 }
1546 } else if (type_without_array->is_interface()) {
1547 if (interface_contains_unsized_arrays(type_without_array)) {
1548 const glsl_type *new_type =
1549 resize_interface_members(type_without_array,
1550 var->get_max_ifc_array_access(),
1551 var->is_in_shader_storage_block());
1552 var->change_interface_type(new_type);
1553 var->type = update_interface_members_array(var->type, new_type);
1554 }
1555 } else if (const glsl_type *ifc_type = var->get_interface_type()) {
1556 /* Store a pointer to the variable in the unnamed_interfaces
1557 * hashtable.
1558 */
1559 hash_entry *entry =
1560 _mesa_hash_table_search(this->unnamed_interfaces,
1561 ifc_type);
1562
1563 ir_variable **interface_vars = entry ? (ir_variable **) entry->data : NULL;
1564
1565 if (interface_vars == NULL) {
1566 interface_vars = rzalloc_array(mem_ctx, ir_variable *,
1567 ifc_type->length);
1568 _mesa_hash_table_insert(this->unnamed_interfaces, ifc_type,
1569 interface_vars);
1570 }
1571 unsigned index = ifc_type->field_index(var->name);
1572 assert(index < ifc_type->length);
1573 assert(interface_vars[index] == NULL);
1574 interface_vars[index] = var;
1575 }
1576 return visit_continue;
1577 }
1578
1579 /**
1580 * For each unnamed interface block that was discovered while running the
1581 * visitor, adjust the interface type to reflect the newly assigned array
1582 * sizes, and fix up the ir_variable nodes to point to the new interface
1583 * type.
1584 */
1585 void fixup_unnamed_interface_types()
1586 {
1587 hash_table_call_foreach(this->unnamed_interfaces,
1588 fixup_unnamed_interface_type, NULL);
1589 }
1590
1591 private:
1592 /**
1593 * If the type pointed to by \c type represents an unsized array, replace
1594 * it with a sized array whose size is determined by max_array_access.
1595 */
1596 static void fixup_type(const glsl_type **type, unsigned max_array_access,
1597 bool from_ssbo_unsized_array, bool *implicit_sized)
1598 {
1599 if (!from_ssbo_unsized_array && (*type)->is_unsized_array()) {
1600 *type = glsl_type::get_array_instance((*type)->fields.array,
1601 max_array_access + 1);
1602 *implicit_sized = true;
1603 assert(*type != NULL);
1604 }
1605 }
1606
1607 static const glsl_type *
1608 update_interface_members_array(const glsl_type *type,
1609 const glsl_type *new_interface_type)
1610 {
1611 const glsl_type *element_type = type->fields.array;
1612 if (element_type->is_array()) {
1613 const glsl_type *new_array_type =
1614 update_interface_members_array(element_type, new_interface_type);
1615 return glsl_type::get_array_instance(new_array_type, type->length);
1616 } else {
1617 return glsl_type::get_array_instance(new_interface_type,
1618 type->length);
1619 }
1620 }
1621
1622 /**
1623 * Determine whether the given interface type contains unsized arrays (if
1624 * it doesn't, array_sizing_visitor doesn't need to process it).
1625 */
1626 static bool interface_contains_unsized_arrays(const glsl_type *type)
1627 {
1628 for (unsigned i = 0; i < type->length; i++) {
1629 const glsl_type *elem_type = type->fields.structure[i].type;
1630 if (elem_type->is_unsized_array())
1631 return true;
1632 }
1633 return false;
1634 }
1635
1636 /**
1637 * Create a new interface type based on the given type, with unsized arrays
1638 * replaced by sized arrays whose size is determined by
1639 * max_ifc_array_access.
1640 */
1641 static const glsl_type *
1642 resize_interface_members(const glsl_type *type,
1643 const int *max_ifc_array_access,
1644 bool is_ssbo)
1645 {
1646 unsigned num_fields = type->length;
1647 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1648 memcpy(fields, type->fields.structure,
1649 num_fields * sizeof(*fields));
1650 for (unsigned i = 0; i < num_fields; i++) {
1651 bool implicit_sized_array = fields[i].implicit_sized_array;
1652 /* If SSBO last member is unsized array, we don't replace it by a sized
1653 * array.
1654 */
1655 if (is_ssbo && i == (num_fields - 1))
1656 fixup_type(&fields[i].type, max_ifc_array_access[i],
1657 true, &implicit_sized_array);
1658 else
1659 fixup_type(&fields[i].type, max_ifc_array_access[i],
1660 false, &implicit_sized_array);
1661 fields[i].implicit_sized_array = implicit_sized_array;
1662 }
1663 glsl_interface_packing packing =
1664 (glsl_interface_packing) type->interface_packing;
1665 bool row_major = (bool) type->interface_row_major;
1666 const glsl_type *new_ifc_type =
1667 glsl_type::get_interface_instance(fields, num_fields,
1668 packing, row_major, type->name);
1669 delete [] fields;
1670 return new_ifc_type;
1671 }
1672
1673 static void fixup_unnamed_interface_type(const void *key, void *data,
1674 void *)
1675 {
1676 const glsl_type *ifc_type = (const glsl_type *) key;
1677 ir_variable **interface_vars = (ir_variable **) data;
1678 unsigned num_fields = ifc_type->length;
1679 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1680 memcpy(fields, ifc_type->fields.structure,
1681 num_fields * sizeof(*fields));
1682 bool interface_type_changed = false;
1683 for (unsigned i = 0; i < num_fields; i++) {
1684 if (interface_vars[i] != NULL &&
1685 fields[i].type != interface_vars[i]->type) {
1686 fields[i].type = interface_vars[i]->type;
1687 interface_type_changed = true;
1688 }
1689 }
1690 if (!interface_type_changed) {
1691 delete [] fields;
1692 return;
1693 }
1694 glsl_interface_packing packing =
1695 (glsl_interface_packing) ifc_type->interface_packing;
1696 bool row_major = (bool) ifc_type->interface_row_major;
1697 const glsl_type *new_ifc_type =
1698 glsl_type::get_interface_instance(fields, num_fields, packing,
1699 row_major, ifc_type->name);
1700 delete [] fields;
1701 for (unsigned i = 0; i < num_fields; i++) {
1702 if (interface_vars[i] != NULL)
1703 interface_vars[i]->change_interface_type(new_ifc_type);
1704 }
1705 }
1706
1707 /**
1708 * Memory context used to allocate the data in \c unnamed_interfaces.
1709 */
1710 void *mem_ctx;
1711
1712 /**
1713 * Hash table from const glsl_type * to an array of ir_variable *'s
1714 * pointing to the ir_variables constituting each unnamed interface block.
1715 */
1716 hash_table *unnamed_interfaces;
1717 };
1718
1719 static bool
1720 validate_xfb_buffer_stride(struct gl_context *ctx, unsigned idx,
1721 struct gl_shader_program *prog)
1722 {
1723 /* We will validate doubles at a later stage */
1724 if (prog->TransformFeedback.BufferStride[idx] % 4) {
1725 linker_error(prog, "invalid qualifier xfb_stride=%d must be a "
1726 "multiple of 4 or if its applied to a type that is "
1727 "or contains a double a multiple of 8.",
1728 prog->TransformFeedback.BufferStride[idx]);
1729 return false;
1730 }
1731
1732 if (prog->TransformFeedback.BufferStride[idx] / 4 >
1733 ctx->Const.MaxTransformFeedbackInterleavedComponents) {
1734 linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1735 "limit has been exceeded.");
1736 return false;
1737 }
1738
1739 return true;
1740 }
1741
1742 /**
1743 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1744 * for later use.
1745 */
1746 static void
1747 link_xfb_stride_layout_qualifiers(struct gl_context *ctx,
1748 struct gl_shader_program *prog,
1749 struct gl_shader **shader_list,
1750 unsigned num_shaders)
1751 {
1752 for (unsigned i = 0; i < MAX_FEEDBACK_BUFFERS; i++) {
1753 prog->TransformFeedback.BufferStride[i] = 0;
1754 }
1755
1756 for (unsigned i = 0; i < num_shaders; i++) {
1757 struct gl_shader *shader = shader_list[i];
1758
1759 for (unsigned j = 0; j < MAX_FEEDBACK_BUFFERS; j++) {
1760 if (shader->TransformFeedbackBufferStride[j]) {
1761 if (prog->TransformFeedback.BufferStride[j] == 0) {
1762 prog->TransformFeedback.BufferStride[j] =
1763 shader->TransformFeedbackBufferStride[j];
1764 if (!validate_xfb_buffer_stride(ctx, j, prog))
1765 return;
1766 } else if (prog->TransformFeedback.BufferStride[j] !=
1767 shader->TransformFeedbackBufferStride[j]){
1768 linker_error(prog,
1769 "intrastage shaders defined with conflicting "
1770 "xfb_stride for buffer %d (%d and %d)\n", j,
1771 prog->TransformFeedback.BufferStride[j],
1772 shader->TransformFeedbackBufferStride[j]);
1773 return;
1774 }
1775 }
1776 }
1777 }
1778 }
1779
1780 /**
1781 * Check for conflicting bindless/bound sampler/image layout qualifiers at
1782 * global scope.
1783 */
1784 static void
1785 link_bindless_layout_qualifiers(struct gl_shader_program *prog,
1786 struct gl_shader **shader_list,
1787 unsigned num_shaders)
1788 {
1789 bool bindless_sampler, bindless_image;
1790 bool bound_sampler, bound_image;
1791
1792 bindless_sampler = bindless_image = false;
1793 bound_sampler = bound_image = false;
1794
1795 for (unsigned i = 0; i < num_shaders; i++) {
1796 struct gl_shader *shader = shader_list[i];
1797
1798 if (shader->bindless_sampler)
1799 bindless_sampler = true;
1800 if (shader->bindless_image)
1801 bindless_image = true;
1802 if (shader->bound_sampler)
1803 bound_sampler = true;
1804 if (shader->bound_image)
1805 bound_image = true;
1806
1807 if ((bindless_sampler && bound_sampler) ||
1808 (bindless_image && bound_image)) {
1809 /* From section 4.4.6 of the ARB_bindless_texture spec:
1810 *
1811 * "If both bindless_sampler and bound_sampler, or bindless_image
1812 * and bound_image, are declared at global scope in any
1813 * compilation unit, a link- time error will be generated."
1814 */
1815 linker_error(prog, "both bindless_sampler and bound_sampler, or "
1816 "bindless_image and bound_image, can't be declared at "
1817 "global scope");
1818 }
1819 }
1820 }
1821
1822 /**
1823 * Performs the cross-validation of tessellation control shader vertices and
1824 * layout qualifiers for the attached tessellation control shaders,
1825 * and propagates them to the linked TCS and linked shader program.
1826 */
1827 static void
1828 link_tcs_out_layout_qualifiers(struct gl_shader_program *prog,
1829 struct gl_program *gl_prog,
1830 struct gl_shader **shader_list,
1831 unsigned num_shaders)
1832 {
1833 if (gl_prog->info.stage != MESA_SHADER_TESS_CTRL)
1834 return;
1835
1836 gl_prog->info.tess.tcs_vertices_out = 0;
1837
1838 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1839 *
1840 * "All tessellation control shader layout declarations in a program
1841 * must specify the same output patch vertex count. There must be at
1842 * least one layout qualifier specifying an output patch vertex count
1843 * in any program containing tessellation control shaders; however,
1844 * such a declaration is not required in all tessellation control
1845 * shaders."
1846 */
1847
1848 for (unsigned i = 0; i < num_shaders; i++) {
1849 struct gl_shader *shader = shader_list[i];
1850
1851 if (shader->info.TessCtrl.VerticesOut != 0) {
1852 if (gl_prog->info.tess.tcs_vertices_out != 0 &&
1853 gl_prog->info.tess.tcs_vertices_out !=
1854 (unsigned) shader->info.TessCtrl.VerticesOut) {
1855 linker_error(prog, "tessellation control shader defined with "
1856 "conflicting output vertex count (%d and %d)\n",
1857 gl_prog->info.tess.tcs_vertices_out,
1858 shader->info.TessCtrl.VerticesOut);
1859 return;
1860 }
1861 gl_prog->info.tess.tcs_vertices_out =
1862 shader->info.TessCtrl.VerticesOut;
1863 }
1864 }
1865
1866 /* Just do the intrastage -> interstage propagation right now,
1867 * since we already know we're in the right type of shader program
1868 * for doing it.
1869 */
1870 if (gl_prog->info.tess.tcs_vertices_out == 0) {
1871 linker_error(prog, "tessellation control shader didn't declare "
1872 "vertices out layout qualifier\n");
1873 return;
1874 }
1875 }
1876
1877
1878 /**
1879 * Performs the cross-validation of tessellation evaluation shader
1880 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1881 * for the attached tessellation evaluation shaders, and propagates them
1882 * to the linked TES and linked shader program.
1883 */
1884 static void
1885 link_tes_in_layout_qualifiers(struct gl_shader_program *prog,
1886 struct gl_program *gl_prog,
1887 struct gl_shader **shader_list,
1888 unsigned num_shaders)
1889 {
1890 if (gl_prog->info.stage != MESA_SHADER_TESS_EVAL)
1891 return;
1892
1893 int point_mode = -1;
1894 unsigned vertex_order = 0;
1895
1896 gl_prog->info.tess.primitive_mode = PRIM_UNKNOWN;
1897 gl_prog->info.tess.spacing = TESS_SPACING_UNSPECIFIED;
1898
1899 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1900 *
1901 * "At least one tessellation evaluation shader (compilation unit) in
1902 * a program must declare a primitive mode in its input layout.
1903 * Declaration vertex spacing, ordering, and point mode identifiers is
1904 * optional. It is not required that all tessellation evaluation
1905 * shaders in a program declare a primitive mode. If spacing or
1906 * vertex ordering declarations are omitted, the tessellation
1907 * primitive generator will use equal spacing or counter-clockwise
1908 * vertex ordering, respectively. If a point mode declaration is
1909 * omitted, the tessellation primitive generator will produce lines or
1910 * triangles according to the primitive mode."
1911 */
1912
1913 for (unsigned i = 0; i < num_shaders; i++) {
1914 struct gl_shader *shader = shader_list[i];
1915
1916 if (shader->info.TessEval.PrimitiveMode != PRIM_UNKNOWN) {
1917 if (gl_prog->info.tess.primitive_mode != PRIM_UNKNOWN &&
1918 gl_prog->info.tess.primitive_mode !=
1919 shader->info.TessEval.PrimitiveMode) {
1920 linker_error(prog, "tessellation evaluation shader defined with "
1921 "conflicting input primitive modes.\n");
1922 return;
1923 }
1924 gl_prog->info.tess.primitive_mode =
1925 shader->info.TessEval.PrimitiveMode;
1926 }
1927
1928 if (shader->info.TessEval.Spacing != 0) {
1929 if (gl_prog->info.tess.spacing != 0 && gl_prog->info.tess.spacing !=
1930 shader->info.TessEval.Spacing) {
1931 linker_error(prog, "tessellation evaluation shader defined with "
1932 "conflicting vertex spacing.\n");
1933 return;
1934 }
1935 gl_prog->info.tess.spacing = shader->info.TessEval.Spacing;
1936 }
1937
1938 if (shader->info.TessEval.VertexOrder != 0) {
1939 if (vertex_order != 0 &&
1940 vertex_order != shader->info.TessEval.VertexOrder) {
1941 linker_error(prog, "tessellation evaluation shader defined with "
1942 "conflicting ordering.\n");
1943 return;
1944 }
1945 vertex_order = shader->info.TessEval.VertexOrder;
1946 }
1947
1948 if (shader->info.TessEval.PointMode != -1) {
1949 if (point_mode != -1 &&
1950 point_mode != shader->info.TessEval.PointMode) {
1951 linker_error(prog, "tessellation evaluation shader defined with "
1952 "conflicting point modes.\n");
1953 return;
1954 }
1955 point_mode = shader->info.TessEval.PointMode;
1956 }
1957
1958 }
1959
1960 /* Just do the intrastage -> interstage propagation right now,
1961 * since we already know we're in the right type of shader program
1962 * for doing it.
1963 */
1964 if (gl_prog->info.tess.primitive_mode == PRIM_UNKNOWN) {
1965 linker_error(prog,
1966 "tessellation evaluation shader didn't declare input "
1967 "primitive modes.\n");
1968 return;
1969 }
1970
1971 if (gl_prog->info.tess.spacing == TESS_SPACING_UNSPECIFIED)
1972 gl_prog->info.tess.spacing = TESS_SPACING_EQUAL;
1973
1974 if (vertex_order == 0 || vertex_order == GL_CCW)
1975 gl_prog->info.tess.ccw = true;
1976 else
1977 gl_prog->info.tess.ccw = false;
1978
1979
1980 if (point_mode == -1 || point_mode == GL_FALSE)
1981 gl_prog->info.tess.point_mode = false;
1982 else
1983 gl_prog->info.tess.point_mode = true;
1984 }
1985
1986
1987 /**
1988 * Performs the cross-validation of layout qualifiers specified in
1989 * redeclaration of gl_FragCoord for the attached fragment shaders,
1990 * and propagates them to the linked FS and linked shader program.
1991 */
1992 static void
1993 link_fs_inout_layout_qualifiers(struct gl_shader_program *prog,
1994 struct gl_linked_shader *linked_shader,
1995 struct gl_shader **shader_list,
1996 unsigned num_shaders)
1997 {
1998 bool redeclares_gl_fragcoord = false;
1999 bool uses_gl_fragcoord = false;
2000 bool origin_upper_left = false;
2001 bool pixel_center_integer = false;
2002
2003 if (linked_shader->Stage != MESA_SHADER_FRAGMENT ||
2004 (prog->data->Version < 150 &&
2005 !prog->ARB_fragment_coord_conventions_enable))
2006 return;
2007
2008 for (unsigned i = 0; i < num_shaders; i++) {
2009 struct gl_shader *shader = shader_list[i];
2010 /* From the GLSL 1.50 spec, page 39:
2011 *
2012 * "If gl_FragCoord is redeclared in any fragment shader in a program,
2013 * it must be redeclared in all the fragment shaders in that program
2014 * that have a static use gl_FragCoord."
2015 */
2016 if ((redeclares_gl_fragcoord && !shader->redeclares_gl_fragcoord &&
2017 shader->uses_gl_fragcoord)
2018 || (shader->redeclares_gl_fragcoord && !redeclares_gl_fragcoord &&
2019 uses_gl_fragcoord)) {
2020 linker_error(prog, "fragment shader defined with conflicting "
2021 "layout qualifiers for gl_FragCoord\n");
2022 }
2023
2024 /* From the GLSL 1.50 spec, page 39:
2025 *
2026 * "All redeclarations of gl_FragCoord in all fragment shaders in a
2027 * single program must have the same set of qualifiers."
2028 */
2029 if (redeclares_gl_fragcoord && shader->redeclares_gl_fragcoord &&
2030 (shader->origin_upper_left != origin_upper_left ||
2031 shader->pixel_center_integer != pixel_center_integer)) {
2032 linker_error(prog, "fragment shader defined with conflicting "
2033 "layout qualifiers for gl_FragCoord\n");
2034 }
2035
2036 /* Update the linked shader state. Note that uses_gl_fragcoord should
2037 * accumulate the results. The other values should replace. If there
2038 * are multiple redeclarations, all the fields except uses_gl_fragcoord
2039 * are already known to be the same.
2040 */
2041 if (shader->redeclares_gl_fragcoord || shader->uses_gl_fragcoord) {
2042 redeclares_gl_fragcoord = shader->redeclares_gl_fragcoord;
2043 uses_gl_fragcoord |= shader->uses_gl_fragcoord;
2044 origin_upper_left = shader->origin_upper_left;
2045 pixel_center_integer = shader->pixel_center_integer;
2046 }
2047
2048 linked_shader->Program->info.fs.early_fragment_tests |=
2049 shader->EarlyFragmentTests || shader->PostDepthCoverage;
2050 linked_shader->Program->info.fs.inner_coverage |= shader->InnerCoverage;
2051 linked_shader->Program->info.fs.post_depth_coverage |=
2052 shader->PostDepthCoverage;
2053 linked_shader->Program->info.fs.pixel_interlock_ordered |=
2054 shader->PixelInterlockOrdered;
2055 linked_shader->Program->info.fs.pixel_interlock_unordered |=
2056 shader->PixelInterlockUnordered;
2057 linked_shader->Program->info.fs.sample_interlock_ordered |=
2058 shader->SampleInterlockOrdered;
2059 linked_shader->Program->info.fs.sample_interlock_unordered |=
2060 shader->SampleInterlockUnordered;
2061 linked_shader->Program->sh.fs.BlendSupport |= shader->BlendSupport;
2062 }
2063
2064 linked_shader->Program->info.fs.pixel_center_integer = pixel_center_integer;
2065 linked_shader->Program->info.fs.origin_upper_left = origin_upper_left;
2066 }
2067
2068 /**
2069 * Performs the cross-validation of geometry shader max_vertices and
2070 * primitive type layout qualifiers for the attached geometry shaders,
2071 * and propagates them to the linked GS and linked shader program.
2072 */
2073 static void
2074 link_gs_inout_layout_qualifiers(struct gl_shader_program *prog,
2075 struct gl_program *gl_prog,
2076 struct gl_shader **shader_list,
2077 unsigned num_shaders)
2078 {
2079 /* No in/out qualifiers defined for anything but GLSL 1.50+
2080 * geometry shaders so far.
2081 */
2082 if (gl_prog->info.stage != MESA_SHADER_GEOMETRY ||
2083 prog->data->Version < 150)
2084 return;
2085
2086 int vertices_out = -1;
2087
2088 gl_prog->info.gs.invocations = 0;
2089 gl_prog->info.gs.input_primitive = PRIM_UNKNOWN;
2090 gl_prog->info.gs.output_primitive = PRIM_UNKNOWN;
2091
2092 /* From the GLSL 1.50 spec, page 46:
2093 *
2094 * "All geometry shader output layout declarations in a program
2095 * must declare the same layout and same value for
2096 * max_vertices. There must be at least one geometry output
2097 * layout declaration somewhere in a program, but not all
2098 * geometry shaders (compilation units) are required to
2099 * declare it."
2100 */
2101
2102 for (unsigned i = 0; i < num_shaders; i++) {
2103 struct gl_shader *shader = shader_list[i];
2104
2105 if (shader->info.Geom.InputType != PRIM_UNKNOWN) {
2106 if (gl_prog->info.gs.input_primitive != PRIM_UNKNOWN &&
2107 gl_prog->info.gs.input_primitive !=
2108 shader->info.Geom.InputType) {
2109 linker_error(prog, "geometry shader defined with conflicting "
2110 "input types\n");
2111 return;
2112 }
2113 gl_prog->info.gs.input_primitive = shader->info.Geom.InputType;
2114 }
2115
2116 if (shader->info.Geom.OutputType != PRIM_UNKNOWN) {
2117 if (gl_prog->info.gs.output_primitive != PRIM_UNKNOWN &&
2118 gl_prog->info.gs.output_primitive !=
2119 shader->info.Geom.OutputType) {
2120 linker_error(prog, "geometry shader defined with conflicting "
2121 "output types\n");
2122 return;
2123 }
2124 gl_prog->info.gs.output_primitive = shader->info.Geom.OutputType;
2125 }
2126
2127 if (shader->info.Geom.VerticesOut != -1) {
2128 if (vertices_out != -1 &&
2129 vertices_out != shader->info.Geom.VerticesOut) {
2130 linker_error(prog, "geometry shader defined with conflicting "
2131 "output vertex count (%d and %d)\n",
2132 vertices_out, shader->info.Geom.VerticesOut);
2133 return;
2134 }
2135 vertices_out = shader->info.Geom.VerticesOut;
2136 }
2137
2138 if (shader->info.Geom.Invocations != 0) {
2139 if (gl_prog->info.gs.invocations != 0 &&
2140 gl_prog->info.gs.invocations !=
2141 (unsigned) shader->info.Geom.Invocations) {
2142 linker_error(prog, "geometry shader defined with conflicting "
2143 "invocation count (%d and %d)\n",
2144 gl_prog->info.gs.invocations,
2145 shader->info.Geom.Invocations);
2146 return;
2147 }
2148 gl_prog->info.gs.invocations = shader->info.Geom.Invocations;
2149 }
2150 }
2151
2152 /* Just do the intrastage -> interstage propagation right now,
2153 * since we already know we're in the right type of shader program
2154 * for doing it.
2155 */
2156 if (gl_prog->info.gs.input_primitive == PRIM_UNKNOWN) {
2157 linker_error(prog,
2158 "geometry shader didn't declare primitive input type\n");
2159 return;
2160 }
2161
2162 if (gl_prog->info.gs.output_primitive == PRIM_UNKNOWN) {
2163 linker_error(prog,
2164 "geometry shader didn't declare primitive output type\n");
2165 return;
2166 }
2167
2168 if (vertices_out == -1) {
2169 linker_error(prog,
2170 "geometry shader didn't declare max_vertices\n");
2171 return;
2172 } else {
2173 gl_prog->info.gs.vertices_out = vertices_out;
2174 }
2175
2176 if (gl_prog->info.gs.invocations == 0)
2177 gl_prog->info.gs.invocations = 1;
2178 }
2179
2180
2181 /**
2182 * Perform cross-validation of compute shader local_size_{x,y,z} layout and
2183 * derivative arrangement qualifiers for the attached compute shaders, and
2184 * propagate them to the linked CS and linked shader program.
2185 */
2186 static void
2187 link_cs_input_layout_qualifiers(struct gl_shader_program *prog,
2188 struct gl_program *gl_prog,
2189 struct gl_shader **shader_list,
2190 unsigned num_shaders)
2191 {
2192 /* This function is called for all shader stages, but it only has an effect
2193 * for compute shaders.
2194 */
2195 if (gl_prog->info.stage != MESA_SHADER_COMPUTE)
2196 return;
2197
2198 for (int i = 0; i < 3; i++)
2199 gl_prog->info.cs.local_size[i] = 0;
2200
2201 gl_prog->info.cs.local_size_variable = false;
2202
2203 gl_prog->info.cs.derivative_group = DERIVATIVE_GROUP_NONE;
2204
2205 /* From the ARB_compute_shader spec, in the section describing local size
2206 * declarations:
2207 *
2208 * If multiple compute shaders attached to a single program object
2209 * declare local work-group size, the declarations must be identical;
2210 * otherwise a link-time error results. Furthermore, if a program
2211 * object contains any compute shaders, at least one must contain an
2212 * input layout qualifier specifying the local work sizes of the
2213 * program, or a link-time error will occur.
2214 */
2215 for (unsigned sh = 0; sh < num_shaders; sh++) {
2216 struct gl_shader *shader = shader_list[sh];
2217
2218 if (shader->info.Comp.LocalSize[0] != 0) {
2219 if (gl_prog->info.cs.local_size[0] != 0) {
2220 for (int i = 0; i < 3; i++) {
2221 if (gl_prog->info.cs.local_size[i] !=
2222 shader->info.Comp.LocalSize[i]) {
2223 linker_error(prog, "compute shader defined with conflicting "
2224 "local sizes\n");
2225 return;
2226 }
2227 }
2228 }
2229 for (int i = 0; i < 3; i++) {
2230 gl_prog->info.cs.local_size[i] =
2231 shader->info.Comp.LocalSize[i];
2232 }
2233 } else if (shader->info.Comp.LocalSizeVariable) {
2234 if (gl_prog->info.cs.local_size[0] != 0) {
2235 /* The ARB_compute_variable_group_size spec says:
2236 *
2237 * If one compute shader attached to a program declares a
2238 * variable local group size and a second compute shader
2239 * attached to the same program declares a fixed local group
2240 * size, a link-time error results.
2241 */
2242 linker_error(prog, "compute shader defined with both fixed and "
2243 "variable local group size\n");
2244 return;
2245 }
2246 gl_prog->info.cs.local_size_variable = true;
2247 }
2248
2249 enum gl_derivative_group group = shader->info.Comp.DerivativeGroup;
2250 if (group != DERIVATIVE_GROUP_NONE) {
2251 if (gl_prog->info.cs.derivative_group != DERIVATIVE_GROUP_NONE &&
2252 gl_prog->info.cs.derivative_group != group) {
2253 linker_error(prog, "compute shader defined with conflicting "
2254 "derivative groups\n");
2255 return;
2256 }
2257 gl_prog->info.cs.derivative_group = group;
2258 }
2259 }
2260
2261 /* Just do the intrastage -> interstage propagation right now,
2262 * since we already know we're in the right type of shader program
2263 * for doing it.
2264 */
2265 if (gl_prog->info.cs.local_size[0] == 0 &&
2266 !gl_prog->info.cs.local_size_variable) {
2267 linker_error(prog, "compute shader must contain a fixed or a variable "
2268 "local group size\n");
2269 return;
2270 }
2271
2272 if (gl_prog->info.cs.derivative_group == DERIVATIVE_GROUP_QUADS) {
2273 if (gl_prog->info.cs.local_size[0] % 2 != 0) {
2274 linker_error(prog, "derivative_group_quadsNV must be used with a "
2275 "local group size whose first dimension "
2276 "is a multiple of 2\n");
2277 return;
2278 }
2279 if (gl_prog->info.cs.local_size[1] % 2 != 0) {
2280 linker_error(prog, "derivative_group_quadsNV must be used with a local"
2281 "group size whose second dimension "
2282 "is a multiple of 2\n");
2283 return;
2284 }
2285 } else if (gl_prog->info.cs.derivative_group == DERIVATIVE_GROUP_LINEAR) {
2286 if ((gl_prog->info.cs.local_size[0] *
2287 gl_prog->info.cs.local_size[1] *
2288 gl_prog->info.cs.local_size[2]) % 4 != 0) {
2289 linker_error(prog, "derivative_group_linearNV must be used with a "
2290 "local group size whose total number of invocations "
2291 "is a multiple of 4\n");
2292 return;
2293 }
2294 }
2295 }
2296
2297 /**
2298 * Link all out variables on a single stage which are not
2299 * directly used in a shader with the main function.
2300 */
2301 static void
2302 link_output_variables(struct gl_linked_shader *linked_shader,
2303 struct gl_shader **shader_list,
2304 unsigned num_shaders)
2305 {
2306 struct glsl_symbol_table *symbols = linked_shader->symbols;
2307
2308 for (unsigned i = 0; i < num_shaders; i++) {
2309
2310 /* Skip shader object with main function */
2311 if (shader_list[i]->symbols->get_function("main"))
2312 continue;
2313
2314 foreach_in_list(ir_instruction, ir, shader_list[i]->ir) {
2315 if (ir->ir_type != ir_type_variable)
2316 continue;
2317
2318 ir_variable *var = (ir_variable *) ir;
2319
2320 if (var->data.mode == ir_var_shader_out &&
2321 !symbols->get_variable(var->name)) {
2322 var = var->clone(linked_shader, NULL);
2323 symbols->add_variable(var);
2324 linked_shader->ir->push_head(var);
2325 }
2326 }
2327 }
2328
2329 return;
2330 }
2331
2332
2333 /**
2334 * Combine a group of shaders for a single stage to generate a linked shader
2335 *
2336 * \note
2337 * If this function is supplied a single shader, it is cloned, and the new
2338 * shader is returned.
2339 */
2340 struct gl_linked_shader *
2341 link_intrastage_shaders(void *mem_ctx,
2342 struct gl_context *ctx,
2343 struct gl_shader_program *prog,
2344 struct gl_shader **shader_list,
2345 unsigned num_shaders,
2346 bool allow_missing_main)
2347 {
2348 struct gl_uniform_block *ubo_blocks = NULL;
2349 struct gl_uniform_block *ssbo_blocks = NULL;
2350 unsigned num_ubo_blocks = 0;
2351 unsigned num_ssbo_blocks = 0;
2352
2353 /* Check that global variables defined in multiple shaders are consistent.
2354 */
2355 glsl_symbol_table variables;
2356 for (unsigned i = 0; i < num_shaders; i++) {
2357 if (shader_list[i] == NULL)
2358 continue;
2359 cross_validate_globals(ctx, prog, shader_list[i]->ir, &variables,
2360 false);
2361 }
2362
2363 if (!prog->data->LinkStatus)
2364 return NULL;
2365
2366 /* Check that interface blocks defined in multiple shaders are consistent.
2367 */
2368 validate_intrastage_interface_blocks(prog, (const gl_shader **)shader_list,
2369 num_shaders);
2370 if (!prog->data->LinkStatus)
2371 return NULL;
2372
2373 /* Check that there is only a single definition of each function signature
2374 * across all shaders.
2375 */
2376 for (unsigned i = 0; i < (num_shaders - 1); i++) {
2377 foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
2378 ir_function *const f = node->as_function();
2379
2380 if (f == NULL)
2381 continue;
2382
2383 for (unsigned j = i + 1; j < num_shaders; j++) {
2384 ir_function *const other =
2385 shader_list[j]->symbols->get_function(f->name);
2386
2387 /* If the other shader has no function (and therefore no function
2388 * signatures) with the same name, skip to the next shader.
2389 */
2390 if (other == NULL)
2391 continue;
2392
2393 foreach_in_list(ir_function_signature, sig, &f->signatures) {
2394 if (!sig->is_defined)
2395 continue;
2396
2397 ir_function_signature *other_sig =
2398 other->exact_matching_signature(NULL, &sig->parameters);
2399
2400 if (other_sig != NULL && other_sig->is_defined) {
2401 linker_error(prog, "function `%s' is multiply defined\n",
2402 f->name);
2403 return NULL;
2404 }
2405 }
2406 }
2407 }
2408 }
2409
2410 /* Find the shader that defines main, and make a clone of it.
2411 *
2412 * Starting with the clone, search for undefined references. If one is
2413 * found, find the shader that defines it. Clone the reference and add
2414 * it to the shader. Repeat until there are no undefined references or
2415 * until a reference cannot be resolved.
2416 */
2417 gl_shader *main = NULL;
2418 for (unsigned i = 0; i < num_shaders; i++) {
2419 if (_mesa_get_main_function_signature(shader_list[i]->symbols)) {
2420 main = shader_list[i];
2421 break;
2422 }
2423 }
2424
2425 if (main == NULL && allow_missing_main)
2426 main = shader_list[0];
2427
2428 if (main == NULL) {
2429 linker_error(prog, "%s shader lacks `main'\n",
2430 _mesa_shader_stage_to_string(shader_list[0]->Stage));
2431 return NULL;
2432 }
2433
2434 gl_linked_shader *linked = rzalloc(NULL, struct gl_linked_shader);
2435 linked->Stage = shader_list[0]->Stage;
2436
2437 /* Create program and attach it to the linked shader */
2438 struct gl_program *gl_prog =
2439 ctx->Driver.NewProgram(ctx,
2440 _mesa_shader_stage_to_program(shader_list[0]->Stage),
2441 prog->Name, false);
2442 if (!gl_prog) {
2443 prog->data->LinkStatus = LINKING_FAILURE;
2444 _mesa_delete_linked_shader(ctx, linked);
2445 return NULL;
2446 }
2447
2448 _mesa_reference_shader_program_data(ctx, &gl_prog->sh.data, prog->data);
2449
2450 /* Don't use _mesa_reference_program() just take ownership */
2451 linked->Program = gl_prog;
2452
2453 linked->ir = new(linked) exec_list;
2454 clone_ir_list(mem_ctx, linked->ir, main->ir);
2455
2456 link_fs_inout_layout_qualifiers(prog, linked, shader_list, num_shaders);
2457 link_tcs_out_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2458 link_tes_in_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2459 link_gs_inout_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2460 link_cs_input_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2461
2462 if (linked->Stage != MESA_SHADER_FRAGMENT)
2463 link_xfb_stride_layout_qualifiers(ctx, prog, shader_list, num_shaders);
2464
2465 link_bindless_layout_qualifiers(prog, shader_list, num_shaders);
2466
2467 populate_symbol_table(linked, shader_list[0]->symbols);
2468
2469 /* The pointer to the main function in the final linked shader (i.e., the
2470 * copy of the original shader that contained the main function).
2471 */
2472 ir_function_signature *const main_sig =
2473 _mesa_get_main_function_signature(linked->symbols);
2474
2475 /* Move any instructions other than variable declarations or function
2476 * declarations into main.
2477 */
2478 if (main_sig != NULL) {
2479 exec_node *insertion_point =
2480 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
2481 linked);
2482
2483 for (unsigned i = 0; i < num_shaders; i++) {
2484 if (shader_list[i] == main)
2485 continue;
2486
2487 insertion_point = move_non_declarations(shader_list[i]->ir,
2488 insertion_point, true, linked);
2489 }
2490 }
2491
2492 if (!link_function_calls(prog, linked, shader_list, num_shaders)) {
2493 _mesa_delete_linked_shader(ctx, linked);
2494 return NULL;
2495 }
2496
2497 if (linked->Stage != MESA_SHADER_FRAGMENT)
2498 link_output_variables(linked, shader_list, num_shaders);
2499
2500 /* Make a pass over all variable declarations to ensure that arrays with
2501 * unspecified sizes have a size specified. The size is inferred from the
2502 * max_array_access field.
2503 */
2504 array_sizing_visitor v;
2505 v.run(linked->ir);
2506 v.fixup_unnamed_interface_types();
2507
2508 /* Link up uniform blocks defined within this stage. */
2509 link_uniform_blocks(mem_ctx, ctx, prog, linked, &ubo_blocks,
2510 &num_ubo_blocks, &ssbo_blocks, &num_ssbo_blocks);
2511
2512 if (!prog->data->LinkStatus) {
2513 _mesa_delete_linked_shader(ctx, linked);
2514 return NULL;
2515 }
2516
2517 /* Copy ubo blocks to linked shader list */
2518 linked->Program->sh.UniformBlocks =
2519 ralloc_array(linked, gl_uniform_block *, num_ubo_blocks);
2520 ralloc_steal(linked, ubo_blocks);
2521 for (unsigned i = 0; i < num_ubo_blocks; i++) {
2522 linked->Program->sh.UniformBlocks[i] = &ubo_blocks[i];
2523 }
2524 linked->Program->info.num_ubos = num_ubo_blocks;
2525
2526 /* Copy ssbo blocks to linked shader list */
2527 linked->Program->sh.ShaderStorageBlocks =
2528 ralloc_array(linked, gl_uniform_block *, num_ssbo_blocks);
2529 ralloc_steal(linked, ssbo_blocks);
2530 for (unsigned i = 0; i < num_ssbo_blocks; i++) {
2531 linked->Program->sh.ShaderStorageBlocks[i] = &ssbo_blocks[i];
2532 }
2533 linked->Program->info.num_ssbos = num_ssbo_blocks;
2534
2535 /* At this point linked should contain all of the linked IR, so
2536 * validate it to make sure nothing went wrong.
2537 */
2538 validate_ir_tree(linked->ir);
2539
2540 /* Set the size of geometry shader input arrays */
2541 if (linked->Stage == MESA_SHADER_GEOMETRY) {
2542 unsigned num_vertices =
2543 vertices_per_prim(gl_prog->info.gs.input_primitive);
2544 array_resize_visitor input_resize_visitor(num_vertices, prog,
2545 MESA_SHADER_GEOMETRY);
2546 foreach_in_list(ir_instruction, ir, linked->ir) {
2547 ir->accept(&input_resize_visitor);
2548 }
2549 }
2550
2551 if (ctx->Const.VertexID_is_zero_based)
2552 lower_vertex_id(linked);
2553
2554 if (ctx->Const.LowerCsDerivedVariables)
2555 lower_cs_derived(linked);
2556
2557 #ifdef DEBUG
2558 /* Compute the source checksum. */
2559 linked->SourceChecksum = 0;
2560 for (unsigned i = 0; i < num_shaders; i++) {
2561 if (shader_list[i] == NULL)
2562 continue;
2563 linked->SourceChecksum ^= shader_list[i]->SourceChecksum;
2564 }
2565 #endif
2566
2567 return linked;
2568 }
2569
2570 /**
2571 * Update the sizes of linked shader uniform arrays to the maximum
2572 * array index used.
2573 *
2574 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2575 *
2576 * If one or more elements of an array are active,
2577 * GetActiveUniform will return the name of the array in name,
2578 * subject to the restrictions listed above. The type of the array
2579 * is returned in type. The size parameter contains the highest
2580 * array element index used, plus one. The compiler or linker
2581 * determines the highest index used. There will be only one
2582 * active uniform reported by the GL per uniform array.
2583
2584 */
2585 static void
2586 update_array_sizes(struct gl_shader_program *prog)
2587 {
2588 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2589 if (prog->_LinkedShaders[i] == NULL)
2590 continue;
2591
2592 bool types_were_updated = false;
2593
2594 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
2595 ir_variable *const var = node->as_variable();
2596
2597 if ((var == NULL) || (var->data.mode != ir_var_uniform) ||
2598 !var->type->is_array())
2599 continue;
2600
2601 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2602 * will not be eliminated. Since we always do std140, just
2603 * don't resize arrays in UBOs.
2604 *
2605 * Atomic counters are supposed to get deterministic
2606 * locations assigned based on the declaration ordering and
2607 * sizes, array compaction would mess that up.
2608 *
2609 * Subroutine uniforms are not removed.
2610 */
2611 if (var->is_in_buffer_block() || var->type->contains_atomic() ||
2612 var->type->contains_subroutine() || var->constant_initializer)
2613 continue;
2614
2615 int size = var->data.max_array_access;
2616 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
2617 if (prog->_LinkedShaders[j] == NULL)
2618 continue;
2619
2620 foreach_in_list(ir_instruction, node2, prog->_LinkedShaders[j]->ir) {
2621 ir_variable *other_var = node2->as_variable();
2622 if (!other_var)
2623 continue;
2624
2625 if (strcmp(var->name, other_var->name) == 0 &&
2626 other_var->data.max_array_access > size) {
2627 size = other_var->data.max_array_access;
2628 }
2629 }
2630 }
2631
2632 if (size + 1 != (int)var->type->length) {
2633 /* If this is a built-in uniform (i.e., it's backed by some
2634 * fixed-function state), adjust the number of state slots to
2635 * match the new array size. The number of slots per array entry
2636 * is not known. It seems safe to assume that the total number of
2637 * slots is an integer multiple of the number of array elements.
2638 * Determine the number of slots per array element by dividing by
2639 * the old (total) size.
2640 */
2641 const unsigned num_slots = var->get_num_state_slots();
2642 if (num_slots > 0) {
2643 var->set_num_state_slots((size + 1)
2644 * (num_slots / var->type->length));
2645 }
2646
2647 var->type = glsl_type::get_array_instance(var->type->fields.array,
2648 size + 1);
2649 types_were_updated = true;
2650 }
2651 }
2652
2653 /* Update the types of dereferences in case we changed any. */
2654 if (types_were_updated) {
2655 deref_type_updater v;
2656 v.run(prog->_LinkedShaders[i]->ir);
2657 }
2658 }
2659 }
2660
2661 /**
2662 * Resize tessellation evaluation per-vertex inputs to the size of
2663 * tessellation control per-vertex outputs.
2664 */
2665 static void
2666 resize_tes_inputs(struct gl_context *ctx,
2667 struct gl_shader_program *prog)
2668 {
2669 if (prog->_LinkedShaders[MESA_SHADER_TESS_EVAL] == NULL)
2670 return;
2671
2672 gl_linked_shader *const tcs = prog->_LinkedShaders[MESA_SHADER_TESS_CTRL];
2673 gl_linked_shader *const tes = prog->_LinkedShaders[MESA_SHADER_TESS_EVAL];
2674
2675 /* If no control shader is present, then the TES inputs are statically
2676 * sized to MaxPatchVertices; the actual size of the arrays won't be
2677 * known until draw time.
2678 */
2679 const int num_vertices = tcs
2680 ? tcs->Program->info.tess.tcs_vertices_out
2681 : ctx->Const.MaxPatchVertices;
2682
2683 array_resize_visitor input_resize_visitor(num_vertices, prog,
2684 MESA_SHADER_TESS_EVAL);
2685 foreach_in_list(ir_instruction, ir, tes->ir) {
2686 ir->accept(&input_resize_visitor);
2687 }
2688
2689 if (tcs) {
2690 /* Convert the gl_PatchVerticesIn system value into a constant, since
2691 * the value is known at this point.
2692 */
2693 foreach_in_list(ir_instruction, ir, tes->ir) {
2694 ir_variable *var = ir->as_variable();
2695 if (var && var->data.mode == ir_var_system_value &&
2696 var->data.location == SYSTEM_VALUE_VERTICES_IN) {
2697 void *mem_ctx = ralloc_parent(var);
2698 var->data.location = 0;
2699 var->data.explicit_location = false;
2700 var->data.mode = ir_var_auto;
2701 var->constant_value = new(mem_ctx) ir_constant(num_vertices);
2702 }
2703 }
2704 }
2705 }
2706
2707 /**
2708 * Find a contiguous set of available bits in a bitmask.
2709 *
2710 * \param used_mask Bits representing used (1) and unused (0) locations
2711 * \param needed_count Number of contiguous bits needed.
2712 *
2713 * \return
2714 * Base location of the available bits on success or -1 on failure.
2715 */
2716 static int
2717 find_available_slots(unsigned used_mask, unsigned needed_count)
2718 {
2719 unsigned needed_mask = (1 << needed_count) - 1;
2720 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
2721
2722 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2723 * cannot optimize possibly infinite loops" for the loop below.
2724 */
2725 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
2726 return -1;
2727
2728 for (int i = 0; i <= max_bit_to_test; i++) {
2729 if ((needed_mask & ~used_mask) == needed_mask)
2730 return i;
2731
2732 needed_mask <<= 1;
2733 }
2734
2735 return -1;
2736 }
2737
2738
2739 #define SAFE_MASK_FROM_INDEX(i) (((i) >= 32) ? ~0 : ((1 << (i)) - 1))
2740
2741 /**
2742 * Assign locations for either VS inputs or FS outputs.
2743 *
2744 * \param mem_ctx Temporary ralloc context used for linking.
2745 * \param prog Shader program whose variables need locations
2746 * assigned.
2747 * \param constants Driver specific constant values for the program.
2748 * \param target_index Selector for the program target to receive location
2749 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2750 * \c MESA_SHADER_FRAGMENT.
2751 * \param do_assignment Whether we are actually marking the assignment or we
2752 * are just doing a dry-run checking.
2753 *
2754 * \return
2755 * If locations are (or can be, in case of dry-running) successfully assigned,
2756 * true is returned. Otherwise an error is emitted to the shader link log and
2757 * false is returned.
2758 */
2759 static bool
2760 assign_attribute_or_color_locations(void *mem_ctx,
2761 gl_shader_program *prog,
2762 struct gl_constants *constants,
2763 unsigned target_index,
2764 bool do_assignment)
2765 {
2766 /* Maximum number of generic locations. This corresponds to either the
2767 * maximum number of draw buffers or the maximum number of generic
2768 * attributes.
2769 */
2770 unsigned max_index = (target_index == MESA_SHADER_VERTEX) ?
2771 constants->Program[target_index].MaxAttribs :
2772 MAX2(constants->MaxDrawBuffers, constants->MaxDualSourceDrawBuffers);
2773
2774 /* Mark invalid locations as being used.
2775 */
2776 unsigned used_locations = ~SAFE_MASK_FROM_INDEX(max_index);
2777 unsigned double_storage_locations = 0;
2778
2779 assert((target_index == MESA_SHADER_VERTEX)
2780 || (target_index == MESA_SHADER_FRAGMENT));
2781
2782 gl_linked_shader *const sh = prog->_LinkedShaders[target_index];
2783 if (sh == NULL)
2784 return true;
2785
2786 /* Operate in a total of four passes.
2787 *
2788 * 1. Invalidate the location assignments for all vertex shader inputs.
2789 *
2790 * 2. Assign locations for inputs that have user-defined (via
2791 * glBindVertexAttribLocation) locations and outputs that have
2792 * user-defined locations (via glBindFragDataLocation).
2793 *
2794 * 3. Sort the attributes without assigned locations by number of slots
2795 * required in decreasing order. Fragmentation caused by attribute
2796 * locations assigned by the application may prevent large attributes
2797 * from having enough contiguous space.
2798 *
2799 * 4. Assign locations to any inputs without assigned locations.
2800 */
2801
2802 const int generic_base = (target_index == MESA_SHADER_VERTEX)
2803 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
2804
2805 const enum ir_variable_mode direction =
2806 (target_index == MESA_SHADER_VERTEX)
2807 ? ir_var_shader_in : ir_var_shader_out;
2808
2809
2810 /* Temporary storage for the set of attributes that need locations assigned.
2811 */
2812 struct temp_attr {
2813 unsigned slots;
2814 ir_variable *var;
2815
2816 /* Used below in the call to qsort. */
2817 static int compare(const void *a, const void *b)
2818 {
2819 const temp_attr *const l = (const temp_attr *) a;
2820 const temp_attr *const r = (const temp_attr *) b;
2821
2822 /* Reversed because we want a descending order sort below. */
2823 return r->slots - l->slots;
2824 }
2825 } to_assign[32];
2826 assert(max_index <= 32);
2827
2828 /* Temporary array for the set of attributes that have locations assigned,
2829 * for the purpose of checking overlapping slots/components of (non-ES)
2830 * fragment shader outputs.
2831 */
2832 ir_variable *assigned[12 * 4]; /* (max # of FS outputs) * # components */
2833 unsigned assigned_attr = 0;
2834
2835 unsigned num_attr = 0;
2836
2837 foreach_in_list(ir_instruction, node, sh->ir) {
2838 ir_variable *const var = node->as_variable();
2839
2840 if ((var == NULL) || (var->data.mode != (unsigned) direction))
2841 continue;
2842
2843 if (var->data.explicit_location) {
2844 var->data.is_unmatched_generic_inout = 0;
2845 if ((var->data.location >= (int)(max_index + generic_base))
2846 || (var->data.location < 0)) {
2847 linker_error(prog,
2848 "invalid explicit location %d specified for `%s'\n",
2849 (var->data.location < 0)
2850 ? var->data.location
2851 : var->data.location - generic_base,
2852 var->name);
2853 return false;
2854 }
2855 } else if (target_index == MESA_SHADER_VERTEX) {
2856 unsigned binding;
2857
2858 if (prog->AttributeBindings->get(binding, var->name)) {
2859 assert(binding >= VERT_ATTRIB_GENERIC0);
2860 var->data.location = binding;
2861 var->data.is_unmatched_generic_inout = 0;
2862 }
2863 } else if (target_index == MESA_SHADER_FRAGMENT) {
2864 unsigned binding;
2865 unsigned index;
2866 const char *name = var->name;
2867 const glsl_type *type = var->type;
2868
2869 while (type) {
2870 /* Check if there's a binding for the variable name */
2871 if (prog->FragDataBindings->get(binding, name)) {
2872 assert(binding >= FRAG_RESULT_DATA0);
2873 var->data.location = binding;
2874 var->data.is_unmatched_generic_inout = 0;
2875
2876 if (prog->FragDataIndexBindings->get(index, name)) {
2877 var->data.index = index;
2878 }
2879 break;
2880 }
2881
2882 /* If not, but it's an array type, look for name[0] */
2883 if (type->is_array()) {
2884 name = ralloc_asprintf(mem_ctx, "%s[0]", name);
2885 type = type->fields.array;
2886 continue;
2887 }
2888
2889 break;
2890 }
2891 }
2892
2893 if (strcmp(var->name, "gl_LastFragData") == 0)
2894 continue;
2895
2896 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2897 *
2898 * "Output binding assignments will cause LinkProgram to fail:
2899 * ...
2900 * If the program has an active output assigned to a location greater
2901 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2902 * an active output assigned an index greater than or equal to one;"
2903 */
2904 if (target_index == MESA_SHADER_FRAGMENT && var->data.index >= 1 &&
2905 var->data.location - generic_base >=
2906 (int) constants->MaxDualSourceDrawBuffers) {
2907 linker_error(prog,
2908 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2909 "with index %u for %s\n",
2910 var->data.location - generic_base, var->data.index,
2911 var->name);
2912 return false;
2913 }
2914
2915 const unsigned slots = var->type->count_attribute_slots(target_index == MESA_SHADER_VERTEX);
2916
2917 /* If the variable is not a built-in and has a location statically
2918 * assigned in the shader (presumably via a layout qualifier), make sure
2919 * that it doesn't collide with other assigned locations. Otherwise,
2920 * add it to the list of variables that need linker-assigned locations.
2921 */
2922 if (var->data.location != -1) {
2923 if (var->data.location >= generic_base && var->data.index < 1) {
2924 /* From page 61 of the OpenGL 4.0 spec:
2925 *
2926 * "LinkProgram will fail if the attribute bindings assigned
2927 * by BindAttribLocation do not leave not enough space to
2928 * assign a location for an active matrix attribute or an
2929 * active attribute array, both of which require multiple
2930 * contiguous generic attributes."
2931 *
2932 * I think above text prohibits the aliasing of explicit and
2933 * automatic assignments. But, aliasing is allowed in manual
2934 * assignments of attribute locations. See below comments for
2935 * the details.
2936 *
2937 * From OpenGL 4.0 spec, page 61:
2938 *
2939 * "It is possible for an application to bind more than one
2940 * attribute name to the same location. This is referred to as
2941 * aliasing. This will only work if only one of the aliased
2942 * attributes is active in the executable program, or if no
2943 * path through the shader consumes more than one attribute of
2944 * a set of attributes aliased to the same location. A link
2945 * error can occur if the linker determines that every path
2946 * through the shader consumes multiple aliased attributes,
2947 * but implementations are not required to generate an error
2948 * in this case."
2949 *
2950 * From GLSL 4.30 spec, page 54:
2951 *
2952 * "A program will fail to link if any two non-vertex shader
2953 * input variables are assigned to the same location. For
2954 * vertex shaders, multiple input variables may be assigned
2955 * to the same location using either layout qualifiers or via
2956 * the OpenGL API. However, such aliasing is intended only to
2957 * support vertex shaders where each execution path accesses
2958 * at most one input per each location. Implementations are
2959 * permitted, but not required, to generate link-time errors
2960 * if they detect that every path through the vertex shader
2961 * executable accesses multiple inputs assigned to any single
2962 * location. For all shader types, a program will fail to link
2963 * if explicit location assignments leave the linker unable
2964 * to find space for other variables without explicit
2965 * assignments."
2966 *
2967 * From OpenGL ES 3.0 spec, page 56:
2968 *
2969 * "Binding more than one attribute name to the same location
2970 * is referred to as aliasing, and is not permitted in OpenGL
2971 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2972 * fail when this condition exists. However, aliasing is
2973 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2974 * This will only work if only one of the aliased attributes
2975 * is active in the executable program, or if no path through
2976 * the shader consumes more than one attribute of a set of
2977 * attributes aliased to the same location. A link error can
2978 * occur if the linker determines that every path through the
2979 * shader consumes multiple aliased attributes, but implemen-
2980 * tations are not required to generate an error in this case."
2981 *
2982 * After looking at above references from OpenGL, OpenGL ES and
2983 * GLSL specifications, we allow aliasing of vertex input variables
2984 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2985 *
2986 * NOTE: This is not required by the spec but its worth mentioning
2987 * here that we're not doing anything to make sure that no path
2988 * through the vertex shader executable accesses multiple inputs
2989 * assigned to any single location.
2990 */
2991
2992 /* Mask representing the contiguous slots that will be used by
2993 * this attribute.
2994 */
2995 const unsigned attr = var->data.location - generic_base;
2996 const unsigned use_mask = (1 << slots) - 1;
2997 const char *const string = (target_index == MESA_SHADER_VERTEX)
2998 ? "vertex shader input" : "fragment shader output";
2999
3000 /* Generate a link error if the requested locations for this
3001 * attribute exceed the maximum allowed attribute location.
3002 */
3003 if (attr + slots > max_index) {
3004 linker_error(prog,
3005 "insufficient contiguous locations "
3006 "available for %s `%s' %d %d %d\n", string,
3007 var->name, used_locations, use_mask, attr);
3008 return false;
3009 }
3010
3011 /* Generate a link error if the set of bits requested for this
3012 * attribute overlaps any previously allocated bits.
3013 */
3014 if ((~(use_mask << attr) & used_locations) != used_locations) {
3015 if (target_index == MESA_SHADER_FRAGMENT && !prog->IsES) {
3016 /* From section 4.4.2 (Output Layout Qualifiers) of the GLSL
3017 * 4.40 spec:
3018 *
3019 * "Additionally, for fragment shader outputs, if two
3020 * variables are placed within the same location, they
3021 * must have the same underlying type (floating-point or
3022 * integer). No component aliasing of output variables or
3023 * members is allowed.
3024 */
3025 for (unsigned i = 0; i < assigned_attr; i++) {
3026 unsigned assigned_slots =
3027 assigned[i]->type->count_attribute_slots(false);
3028 unsigned assig_attr =
3029 assigned[i]->data.location - generic_base;
3030 unsigned assigned_use_mask = (1 << assigned_slots) - 1;
3031
3032 if ((assigned_use_mask << assig_attr) &
3033 (use_mask << attr)) {
3034
3035 const glsl_type *assigned_type =
3036 assigned[i]->type->without_array();
3037 const glsl_type *type = var->type->without_array();
3038 if (assigned_type->base_type != type->base_type) {
3039 linker_error(prog, "types do not match for aliased"
3040 " %ss %s and %s\n", string,
3041 assigned[i]->name, var->name);
3042 return false;
3043 }
3044
3045 unsigned assigned_component_mask =
3046 ((1 << assigned_type->vector_elements) - 1) <<
3047 assigned[i]->data.location_frac;
3048 unsigned component_mask =
3049 ((1 << type->vector_elements) - 1) <<
3050 var->data.location_frac;
3051 if (assigned_component_mask & component_mask) {
3052 linker_error(prog, "overlapping component is "
3053 "assigned to %ss %s and %s "
3054 "(component=%d)\n",
3055 string, assigned[i]->name, var->name,
3056 var->data.location_frac);
3057 return false;
3058 }
3059 }
3060 }
3061 } else if (target_index == MESA_SHADER_FRAGMENT ||
3062 (prog->IsES && prog->data->Version >= 300)) {
3063 linker_error(prog, "overlapping location is assigned "
3064 "to %s `%s' %d %d %d\n", string, var->name,
3065 used_locations, use_mask, attr);
3066 return false;
3067 } else {
3068 linker_warning(prog, "overlapping location is assigned "
3069 "to %s `%s' %d %d %d\n", string, var->name,
3070 used_locations, use_mask, attr);
3071 }
3072 }
3073
3074 if (target_index == MESA_SHADER_FRAGMENT && !prog->IsES) {
3075 /* Only track assigned variables for non-ES fragment shaders
3076 * to avoid overflowing the array.
3077 *
3078 * At most one variable per fragment output component should
3079 * reach this.
3080 */
3081 assert(assigned_attr < ARRAY_SIZE(assigned));
3082 assigned[assigned_attr] = var;
3083 assigned_attr++;
3084 }
3085
3086 used_locations |= (use_mask << attr);
3087
3088 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
3089 *
3090 * "A program with more than the value of MAX_VERTEX_ATTRIBS
3091 * active attribute variables may fail to link, unless
3092 * device-dependent optimizations are able to make the program
3093 * fit within available hardware resources. For the purposes
3094 * of this test, attribute variables of the type dvec3, dvec4,
3095 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
3096 * count as consuming twice as many attributes as equivalent
3097 * single-precision types. While these types use the same number
3098 * of generic attributes as their single-precision equivalents,
3099 * implementations are permitted to consume two single-precision
3100 * vectors of internal storage for each three- or four-component
3101 * double-precision vector."
3102 *
3103 * Mark this attribute slot as taking up twice as much space
3104 * so we can count it properly against limits. According to
3105 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
3106 * is optional behavior, but it seems preferable.
3107 */
3108 if (var->type->without_array()->is_dual_slot())
3109 double_storage_locations |= (use_mask << attr);
3110 }
3111
3112 continue;
3113 }
3114
3115 if (num_attr >= max_index) {
3116 linker_error(prog, "too many %s (max %u)",
3117 target_index == MESA_SHADER_VERTEX ?
3118 "vertex shader inputs" : "fragment shader outputs",
3119 max_index);
3120 return false;
3121 }
3122 to_assign[num_attr].slots = slots;
3123 to_assign[num_attr].var = var;
3124 num_attr++;
3125 }
3126
3127 if (!do_assignment)
3128 return true;
3129
3130 if (target_index == MESA_SHADER_VERTEX) {
3131 unsigned total_attribs_size =
3132 util_bitcount(used_locations & SAFE_MASK_FROM_INDEX(max_index)) +
3133 util_bitcount(double_storage_locations);
3134 if (total_attribs_size > max_index) {
3135 linker_error(prog,
3136 "attempt to use %d vertex attribute slots only %d available ",
3137 total_attribs_size, max_index);
3138 return false;
3139 }
3140 }
3141
3142 /* If all of the attributes were assigned locations by the application (or
3143 * are built-in attributes with fixed locations), return early. This should
3144 * be the common case.
3145 */
3146 if (num_attr == 0)
3147 return true;
3148
3149 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
3150
3151 if (target_index == MESA_SHADER_VERTEX) {
3152 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
3153 * only be explicitly assigned by via glBindAttribLocation. Mark it as
3154 * reserved to prevent it from being automatically allocated below.
3155 */
3156 find_deref_visitor find("gl_Vertex");
3157 find.run(sh->ir);
3158 if (find.variable_found())
3159 used_locations |= (1 << 0);
3160 }
3161
3162 for (unsigned i = 0; i < num_attr; i++) {
3163 /* Mask representing the contiguous slots that will be used by this
3164 * attribute.
3165 */
3166 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
3167
3168 int location = find_available_slots(used_locations, to_assign[i].slots);
3169
3170 if (location < 0) {
3171 const char *const string = (target_index == MESA_SHADER_VERTEX)
3172 ? "vertex shader input" : "fragment shader output";
3173
3174 linker_error(prog,
3175 "insufficient contiguous locations "
3176 "available for %s `%s'\n",
3177 string, to_assign[i].var->name);
3178 return false;
3179 }
3180
3181 to_assign[i].var->data.location = generic_base + location;
3182 to_assign[i].var->data.is_unmatched_generic_inout = 0;
3183 used_locations |= (use_mask << location);
3184
3185 if (to_assign[i].var->type->without_array()->is_dual_slot())
3186 double_storage_locations |= (use_mask << location);
3187 }
3188
3189 /* Now that we have all the locations, from the GL 4.5 core spec, section
3190 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
3191 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
3192 * as equivalent single-precision types.
3193 */
3194 if (target_index == MESA_SHADER_VERTEX) {
3195 unsigned total_attribs_size =
3196 util_bitcount(used_locations & SAFE_MASK_FROM_INDEX(max_index)) +
3197 util_bitcount(double_storage_locations);
3198 if (total_attribs_size > max_index) {
3199 linker_error(prog,
3200 "attempt to use %d vertex attribute slots only %d available ",
3201 total_attribs_size, max_index);
3202 return false;
3203 }
3204 }
3205
3206 return true;
3207 }
3208
3209 /**
3210 * Match explicit locations of outputs to inputs and deactivate the
3211 * unmatch flag if found so we don't optimise them away.
3212 */
3213 static void
3214 match_explicit_outputs_to_inputs(gl_linked_shader *producer,
3215 gl_linked_shader *consumer)
3216 {
3217 glsl_symbol_table parameters;
3218 ir_variable *explicit_locations[MAX_VARYINGS_INCL_PATCH][4] =
3219 { {NULL, NULL} };
3220
3221 /* Find all shader outputs in the "producer" stage.
3222 */
3223 foreach_in_list(ir_instruction, node, producer->ir) {
3224 ir_variable *const var = node->as_variable();
3225
3226 if ((var == NULL) || (var->data.mode != ir_var_shader_out))
3227 continue;
3228
3229 if (var->data.explicit_location &&
3230 var->data.location >= VARYING_SLOT_VAR0) {
3231 const unsigned idx = var->data.location - VARYING_SLOT_VAR0;
3232 if (explicit_locations[idx][var->data.location_frac] == NULL)
3233 explicit_locations[idx][var->data.location_frac] = var;
3234
3235 /* Always match TCS outputs. They are shared by all invocations
3236 * within a patch and can be used as shared memory.
3237 */
3238 if (producer->Stage == MESA_SHADER_TESS_CTRL)
3239 var->data.is_unmatched_generic_inout = 0;
3240 }
3241 }
3242
3243 /* Match inputs to outputs */
3244 foreach_in_list(ir_instruction, node, consumer->ir) {
3245 ir_variable *const input = node->as_variable();
3246
3247 if ((input == NULL) || (input->data.mode != ir_var_shader_in))
3248 continue;
3249
3250 ir_variable *output = NULL;
3251 if (input->data.explicit_location
3252 && input->data.location >= VARYING_SLOT_VAR0) {
3253 output = explicit_locations[input->data.location - VARYING_SLOT_VAR0]
3254 [input->data.location_frac];
3255
3256 if (output != NULL){
3257 input->data.is_unmatched_generic_inout = 0;
3258 output->data.is_unmatched_generic_inout = 0;
3259 }
3260 }
3261 }
3262 }
3263
3264 /**
3265 * Store the gl_FragDepth layout in the gl_shader_program struct.
3266 */
3267 static void
3268 store_fragdepth_layout(struct gl_shader_program *prog)
3269 {
3270 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
3271 return;
3272 }
3273
3274 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
3275
3276 /* We don't look up the gl_FragDepth symbol directly because if
3277 * gl_FragDepth is not used in the shader, it's removed from the IR.
3278 * However, the symbol won't be removed from the symbol table.
3279 *
3280 * We're only interested in the cases where the variable is NOT removed
3281 * from the IR.
3282 */
3283 foreach_in_list(ir_instruction, node, ir) {
3284 ir_variable *const var = node->as_variable();
3285
3286 if (var == NULL || var->data.mode != ir_var_shader_out) {
3287 continue;
3288 }
3289
3290 if (strcmp(var->name, "gl_FragDepth") == 0) {
3291 switch (var->data.depth_layout) {
3292 case ir_depth_layout_none:
3293 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
3294 return;
3295 case ir_depth_layout_any:
3296 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
3297 return;
3298 case ir_depth_layout_greater:
3299 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
3300 return;
3301 case ir_depth_layout_less:
3302 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
3303 return;
3304 case ir_depth_layout_unchanged:
3305 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
3306 return;
3307 default:
3308 assert(0);
3309 return;
3310 }
3311 }
3312 }
3313 }
3314
3315 /**
3316 * Validate the resources used by a program versus the implementation limits
3317 */
3318 static void
3319 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
3320 {
3321 unsigned total_uniform_blocks = 0;
3322 unsigned total_shader_storage_blocks = 0;
3323
3324 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3325 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
3326
3327 if (sh == NULL)
3328 continue;
3329
3330 if (sh->Program->info.num_textures >
3331 ctx->Const.Program[i].MaxTextureImageUnits) {
3332 linker_error(prog, "Too many %s shader texture samplers\n",
3333 _mesa_shader_stage_to_string(i));
3334 }
3335
3336 if (sh->num_uniform_components >
3337 ctx->Const.Program[i].MaxUniformComponents) {
3338 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
3339 linker_warning(prog, "Too many %s shader default uniform block "
3340 "components, but the driver will try to optimize "
3341 "them out; this is non-portable out-of-spec "
3342 "behavior\n",
3343 _mesa_shader_stage_to_string(i));
3344 } else {
3345 linker_error(prog, "Too many %s shader default uniform block "
3346 "components\n",
3347 _mesa_shader_stage_to_string(i));
3348 }
3349 }
3350
3351 if (sh->num_combined_uniform_components >
3352 ctx->Const.Program[i].MaxCombinedUniformComponents) {
3353 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
3354 linker_warning(prog, "Too many %s shader uniform components, "
3355 "but the driver will try to optimize them out; "
3356 "this is non-portable out-of-spec behavior\n",
3357 _mesa_shader_stage_to_string(i));
3358 } else {
3359 linker_error(prog, "Too many %s shader uniform components\n",
3360 _mesa_shader_stage_to_string(i));
3361 }
3362 }
3363
3364 total_shader_storage_blocks += sh->Program->info.num_ssbos;
3365 total_uniform_blocks += sh->Program->info.num_ubos;
3366
3367 const unsigned max_uniform_blocks =
3368 ctx->Const.Program[i].MaxUniformBlocks;
3369 if (max_uniform_blocks < sh->Program->info.num_ubos) {
3370 linker_error(prog, "Too many %s uniform blocks (%d/%d)\n",
3371 _mesa_shader_stage_to_string(i),
3372 sh->Program->info.num_ubos, max_uniform_blocks);
3373 }
3374
3375 const unsigned max_shader_storage_blocks =
3376 ctx->Const.Program[i].MaxShaderStorageBlocks;
3377 if (max_shader_storage_blocks < sh->Program->info.num_ssbos) {
3378 linker_error(prog, "Too many %s shader storage blocks (%d/%d)\n",
3379 _mesa_shader_stage_to_string(i),
3380 sh->Program->info.num_ssbos, max_shader_storage_blocks);
3381 }
3382 }
3383
3384 if (total_uniform_blocks > ctx->Const.MaxCombinedUniformBlocks) {
3385 linker_error(prog, "Too many combined uniform blocks (%d/%d)\n",
3386 total_uniform_blocks, ctx->Const.MaxCombinedUniformBlocks);
3387 }
3388
3389 if (total_shader_storage_blocks > ctx->Const.MaxCombinedShaderStorageBlocks) {
3390 linker_error(prog, "Too many combined shader storage blocks (%d/%d)\n",
3391 total_shader_storage_blocks,
3392 ctx->Const.MaxCombinedShaderStorageBlocks);
3393 }
3394
3395 for (unsigned i = 0; i < prog->data->NumUniformBlocks; i++) {
3396 if (prog->data->UniformBlocks[i].UniformBufferSize >
3397 ctx->Const.MaxUniformBlockSize) {
3398 linker_error(prog, "Uniform block %s too big (%d/%d)\n",
3399 prog->data->UniformBlocks[i].Name,
3400 prog->data->UniformBlocks[i].UniformBufferSize,
3401 ctx->Const.MaxUniformBlockSize);
3402 }
3403 }
3404
3405 for (unsigned i = 0; i < prog->data->NumShaderStorageBlocks; i++) {
3406 if (prog->data->ShaderStorageBlocks[i].UniformBufferSize >
3407 ctx->Const.MaxShaderStorageBlockSize) {
3408 linker_error(prog, "Shader storage block %s too big (%d/%d)\n",
3409 prog->data->ShaderStorageBlocks[i].Name,
3410 prog->data->ShaderStorageBlocks[i].UniformBufferSize,
3411 ctx->Const.MaxShaderStorageBlockSize);
3412 }
3413 }
3414 }
3415
3416 static void
3417 link_calculate_subroutine_compat(struct gl_shader_program *prog)
3418 {
3419 unsigned mask = prog->data->linked_stages;
3420 while (mask) {
3421 const int i = u_bit_scan(&mask);
3422 struct gl_program *p = prog->_LinkedShaders[i]->Program;
3423
3424 for (unsigned j = 0; j < p->sh.NumSubroutineUniformRemapTable; j++) {
3425 if (p->sh.SubroutineUniformRemapTable[j] == INACTIVE_UNIFORM_EXPLICIT_LOCATION)
3426 continue;
3427
3428 struct gl_uniform_storage *uni = p->sh.SubroutineUniformRemapTable[j];
3429
3430 if (!uni)
3431 continue;
3432
3433 int count = 0;
3434 if (p->sh.NumSubroutineFunctions == 0) {
3435 linker_error(prog, "subroutine uniform %s defined but no valid functions found\n", uni->type->name);
3436 continue;
3437 }
3438 for (unsigned f = 0; f < p->sh.NumSubroutineFunctions; f++) {
3439 struct gl_subroutine_function *fn = &p->sh.SubroutineFunctions[f];
3440 for (int k = 0; k < fn->num_compat_types; k++) {
3441 if (fn->types[k] == uni->type) {
3442 count++;
3443 break;
3444 }
3445 }
3446 }
3447 uni->num_compatible_subroutines = count;
3448 }
3449 }
3450 }
3451
3452 static void
3453 check_subroutine_resources(struct gl_shader_program *prog)
3454 {
3455 unsigned mask = prog->data->linked_stages;
3456 while (mask) {
3457 const int i = u_bit_scan(&mask);
3458 struct gl_program *p = prog->_LinkedShaders[i]->Program;
3459
3460 if (p->sh.NumSubroutineUniformRemapTable > MAX_SUBROUTINE_UNIFORM_LOCATIONS) {
3461 linker_error(prog, "Too many %s shader subroutine uniforms\n",
3462 _mesa_shader_stage_to_string(i));
3463 }
3464 }
3465 }
3466 /**
3467 * Validate shader image resources.
3468 */
3469 static void
3470 check_image_resources(struct gl_context *ctx, struct gl_shader_program *prog)
3471 {
3472 unsigned total_image_units = 0;
3473 unsigned fragment_outputs = 0;
3474 unsigned total_shader_storage_blocks = 0;
3475
3476 if (!ctx->Extensions.ARB_shader_image_load_store)
3477 return;
3478
3479 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3480 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
3481
3482 if (sh) {
3483 if (sh->Program->info.num_images > ctx->Const.Program[i].MaxImageUniforms)
3484 linker_error(prog, "Too many %s shader image uniforms (%u > %u)\n",
3485 _mesa_shader_stage_to_string(i),
3486 sh->Program->info.num_images,
3487 ctx->Const.Program[i].MaxImageUniforms);
3488
3489 total_image_units += sh->Program->info.num_images;
3490 total_shader_storage_blocks += sh->Program->info.num_ssbos;
3491
3492 if (i == MESA_SHADER_FRAGMENT) {
3493 foreach_in_list(ir_instruction, node, sh->ir) {
3494 ir_variable *var = node->as_variable();
3495 if (var && var->data.mode == ir_var_shader_out)
3496 /* since there are no double fs outputs - pass false */
3497 fragment_outputs += var->type->count_attribute_slots(false);
3498 }
3499 }
3500 }
3501 }
3502
3503 if (total_image_units > ctx->Const.MaxCombinedImageUniforms)
3504 linker_error(prog, "Too many combined image uniforms\n");
3505
3506 if (total_image_units + fragment_outputs + total_shader_storage_blocks >
3507 ctx->Const.MaxCombinedShaderOutputResources)
3508 linker_error(prog, "Too many combined image uniforms, shader storage "
3509 " buffers and fragment outputs\n");
3510 }
3511
3512
3513 /**
3514 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3515 * for a variable, checks for overlaps between other uniforms using explicit
3516 * locations.
3517 */
3518 static int
3519 reserve_explicit_locations(struct gl_shader_program *prog,
3520 string_to_uint_map *map, ir_variable *var)
3521 {
3522 unsigned slots = var->type->uniform_locations();
3523 unsigned max_loc = var->data.location + slots - 1;
3524 unsigned return_value = slots;
3525
3526 /* Resize remap table if locations do not fit in the current one. */
3527 if (max_loc + 1 > prog->NumUniformRemapTable) {
3528 prog->UniformRemapTable =
3529 reralloc(prog, prog->UniformRemapTable,
3530 gl_uniform_storage *,
3531 max_loc + 1);
3532
3533 if (!prog->UniformRemapTable) {
3534 linker_error(prog, "Out of memory during linking.\n");
3535 return -1;
3536 }
3537
3538 /* Initialize allocated space. */
3539 for (unsigned i = prog->NumUniformRemapTable; i < max_loc + 1; i++)
3540 prog->UniformRemapTable[i] = NULL;
3541
3542 prog->NumUniformRemapTable = max_loc + 1;
3543 }
3544
3545 for (unsigned i = 0; i < slots; i++) {
3546 unsigned loc = var->data.location + i;
3547
3548 /* Check if location is already used. */
3549 if (prog->UniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3550
3551 /* Possibly same uniform from a different stage, this is ok. */
3552 unsigned hash_loc;
3553 if (map->get(hash_loc, var->name) && hash_loc == loc - i) {
3554 return_value = 0;
3555 continue;
3556 }
3557
3558 /* ARB_explicit_uniform_location specification states:
3559 *
3560 * "No two default-block uniform variables in the program can have
3561 * the same location, even if they are unused, otherwise a compiler
3562 * or linker error will be generated."
3563 */
3564 linker_error(prog,
3565 "location qualifier for uniform %s overlaps "
3566 "previously used location\n",
3567 var->name);
3568 return -1;
3569 }
3570
3571 /* Initialize location as inactive before optimization
3572 * rounds and location assignment.
3573 */
3574 prog->UniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3575 }
3576
3577 /* Note, base location used for arrays. */
3578 map->put(var->data.location, var->name);
3579
3580 return return_value;
3581 }
3582
3583 static bool
3584 reserve_subroutine_explicit_locations(struct gl_shader_program *prog,
3585 struct gl_program *p,
3586 ir_variable *var)
3587 {
3588 unsigned slots = var->type->uniform_locations();
3589 unsigned max_loc = var->data.location + slots - 1;
3590
3591 /* Resize remap table if locations do not fit in the current one. */
3592 if (max_loc + 1 > p->sh.NumSubroutineUniformRemapTable) {
3593 p->sh.SubroutineUniformRemapTable =
3594 reralloc(p, p->sh.SubroutineUniformRemapTable,
3595 gl_uniform_storage *,
3596 max_loc + 1);
3597
3598 if (!p->sh.SubroutineUniformRemapTable) {
3599 linker_error(prog, "Out of memory during linking.\n");
3600 return false;
3601 }
3602
3603 /* Initialize allocated space. */
3604 for (unsigned i = p->sh.NumSubroutineUniformRemapTable; i < max_loc + 1; i++)
3605 p->sh.SubroutineUniformRemapTable[i] = NULL;
3606
3607 p->sh.NumSubroutineUniformRemapTable = max_loc + 1;
3608 }
3609
3610 for (unsigned i = 0; i < slots; i++) {
3611 unsigned loc = var->data.location + i;
3612
3613 /* Check if location is already used. */
3614 if (p->sh.SubroutineUniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3615
3616 /* ARB_explicit_uniform_location specification states:
3617 * "No two subroutine uniform variables can have the same location
3618 * in the same shader stage, otherwise a compiler or linker error
3619 * will be generated."
3620 */
3621 linker_error(prog,
3622 "location qualifier for uniform %s overlaps "
3623 "previously used location\n",
3624 var->name);
3625 return false;
3626 }
3627
3628 /* Initialize location as inactive before optimization
3629 * rounds and location assignment.
3630 */
3631 p->sh.SubroutineUniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3632 }
3633
3634 return true;
3635 }
3636 /**
3637 * Check and reserve all explicit uniform locations, called before
3638 * any optimizations happen to handle also inactive uniforms and
3639 * inactive array elements that may get trimmed away.
3640 */
3641 static void
3642 check_explicit_uniform_locations(struct gl_context *ctx,
3643 struct gl_shader_program *prog)
3644 {
3645 prog->NumExplicitUniformLocations = 0;
3646
3647 if (!ctx->Extensions.ARB_explicit_uniform_location)
3648 return;
3649
3650 /* This map is used to detect if overlapping explicit locations
3651 * occur with the same uniform (from different stage) or a different one.
3652 */
3653 string_to_uint_map *uniform_map = new string_to_uint_map;
3654
3655 if (!uniform_map) {
3656 linker_error(prog, "Out of memory during linking.\n");
3657 return;
3658 }
3659
3660 unsigned entries_total = 0;
3661 unsigned mask = prog->data->linked_stages;
3662 while (mask) {
3663 const int i = u_bit_scan(&mask);
3664 struct gl_program *p = prog->_LinkedShaders[i]->Program;
3665
3666 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
3667 ir_variable *var = node->as_variable();
3668 if (!var || var->data.mode != ir_var_uniform)
3669 continue;
3670
3671 if (var->data.explicit_location) {
3672 bool ret = false;
3673 if (var->type->without_array()->is_subroutine())
3674 ret = reserve_subroutine_explicit_locations(prog, p, var);
3675 else {
3676 int slots = reserve_explicit_locations(prog, uniform_map,
3677 var);
3678 if (slots != -1) {
3679 ret = true;
3680 entries_total += slots;
3681 }
3682 }
3683 if (!ret) {
3684 delete uniform_map;
3685 return;
3686 }
3687 }
3688 }
3689 }
3690
3691 link_util_update_empty_uniform_locations(prog);
3692
3693 delete uniform_map;
3694 prog->NumExplicitUniformLocations = entries_total;
3695 }
3696
3697 /* Function checks if a variable var is a packed varying and
3698 * if given name is part of packed varying's list.
3699 *
3700 * If a variable is a packed varying, it has a name like
3701 * 'packed:a,b,c' where a, b and c are separate variables.
3702 */
3703 static bool
3704 included_in_packed_varying(ir_variable *var, const char *name)
3705 {
3706 if (strncmp(var->name, "packed:", 7) != 0)
3707 return false;
3708
3709 char *list = strdup(var->name + 7);
3710 assert(list);
3711
3712 bool found = false;
3713 char *saveptr;
3714 char *token = strtok_r(list, ",", &saveptr);
3715 while (token) {
3716 if (strcmp(token, name) == 0) {
3717 found = true;
3718 break;
3719 }
3720 token = strtok_r(NULL, ",", &saveptr);
3721 }
3722 free(list);
3723 return found;
3724 }
3725
3726 /**
3727 * Function builds a stage reference bitmask from variable name.
3728 */
3729 static uint8_t
3730 build_stageref(struct gl_shader_program *shProg, const char *name,
3731 unsigned mode)
3732 {
3733 uint8_t stages = 0;
3734
3735 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3736 * used for reference mask in gl_program_resource will need to be changed.
3737 */
3738 assert(MESA_SHADER_STAGES < 8);
3739
3740 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3741 struct gl_linked_shader *sh = shProg->_LinkedShaders[i];
3742 if (!sh)
3743 continue;
3744
3745 /* Shader symbol table may contain variables that have
3746 * been optimized away. Search IR for the variable instead.
3747 */
3748 foreach_in_list(ir_instruction, node, sh->ir) {
3749 ir_variable *var = node->as_variable();
3750 if (var) {
3751 unsigned baselen = strlen(var->name);
3752
3753 if (included_in_packed_varying(var, name)) {
3754 stages |= (1 << i);
3755 break;
3756 }
3757
3758 /* Type needs to match if specified, otherwise we might
3759 * pick a variable with same name but different interface.
3760 */
3761 if (var->data.mode != mode)
3762 continue;
3763
3764 if (strncmp(var->name, name, baselen) == 0) {
3765 /* Check for exact name matches but also check for arrays and
3766 * structs.
3767 */
3768 if (name[baselen] == '\0' ||
3769 name[baselen] == '[' ||
3770 name[baselen] == '.') {
3771 stages |= (1 << i);
3772 break;
3773 }
3774 }
3775 }
3776 }
3777 }
3778 return stages;
3779 }
3780
3781 /**
3782 * Create gl_shader_variable from ir_variable class.
3783 */
3784 static gl_shader_variable *
3785 create_shader_variable(struct gl_shader_program *shProg,
3786 const ir_variable *in,
3787 const char *name, const glsl_type *type,
3788 const glsl_type *interface_type,
3789 bool use_implicit_location, int location,
3790 const glsl_type *outermost_struct_type)
3791 {
3792 /* Allocate zero-initialized memory to ensure that bitfield padding
3793 * is zero.
3794 */
3795 gl_shader_variable *out = rzalloc(shProg, struct gl_shader_variable);
3796 if (!out)
3797 return NULL;
3798
3799 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3800 * expect to see gl_VertexID in the program resource list. Pretend.
3801 */
3802 if (in->data.mode == ir_var_system_value &&
3803 in->data.location == SYSTEM_VALUE_VERTEX_ID_ZERO_BASE) {
3804 out->name = ralloc_strdup(shProg, "gl_VertexID");
3805 } else if ((in->data.mode == ir_var_shader_out &&
3806 in->data.location == VARYING_SLOT_TESS_LEVEL_OUTER) ||
3807 (in->data.mode == ir_var_system_value &&
3808 in->data.location == SYSTEM_VALUE_TESS_LEVEL_OUTER)) {
3809 out->name = ralloc_strdup(shProg, "gl_TessLevelOuter");
3810 type = glsl_type::get_array_instance(glsl_type::float_type, 4);
3811 } else if ((in->data.mode == ir_var_shader_out &&
3812 in->data.location == VARYING_SLOT_TESS_LEVEL_INNER) ||
3813 (in->data.mode == ir_var_system_value &&
3814 in->data.location == SYSTEM_VALUE_TESS_LEVEL_INNER)) {
3815 out->name = ralloc_strdup(shProg, "gl_TessLevelInner");
3816 type = glsl_type::get_array_instance(glsl_type::float_type, 2);
3817 } else {
3818 out->name = ralloc_strdup(shProg, name);
3819 }
3820
3821 if (!out->name)
3822 return NULL;
3823
3824 /* The ARB_program_interface_query spec says:
3825 *
3826 * "Not all active variables are assigned valid locations; the
3827 * following variables will have an effective location of -1:
3828 *
3829 * * uniforms declared as atomic counters;
3830 *
3831 * * members of a uniform block;
3832 *
3833 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3834 *
3835 * * inputs or outputs not declared with a "location" layout
3836 * qualifier, except for vertex shader inputs and fragment shader
3837 * outputs."
3838 */
3839 if (in->type->is_atomic_uint() || is_gl_identifier(in->name) ||
3840 !(in->data.explicit_location || use_implicit_location)) {
3841 out->location = -1;
3842 } else {
3843 out->location = location;
3844 }
3845
3846 out->type = type;
3847 out->outermost_struct_type = outermost_struct_type;
3848 out->interface_type = interface_type;
3849 out->component = in->data.location_frac;
3850 out->index = in->data.index;
3851 out->patch = in->data.patch;
3852 out->mode = in->data.mode;
3853 out->interpolation = in->data.interpolation;
3854 out->explicit_location = in->data.explicit_location;
3855 out->precision = in->data.precision;
3856
3857 return out;
3858 }
3859
3860 static bool
3861 add_shader_variable(const struct gl_context *ctx,
3862 struct gl_shader_program *shProg,
3863 struct set *resource_set,
3864 unsigned stage_mask,
3865 GLenum programInterface, ir_variable *var,
3866 const char *name, const glsl_type *type,
3867 bool use_implicit_location, int location,
3868 bool inouts_share_location,
3869 const glsl_type *outermost_struct_type = NULL)
3870 {
3871 const glsl_type *interface_type = var->get_interface_type();
3872
3873 if (outermost_struct_type == NULL) {
3874 if (var->data.from_named_ifc_block) {
3875 const char *interface_name = interface_type->name;
3876
3877 if (interface_type->is_array()) {
3878 /* Issue #16 of the ARB_program_interface_query spec says:
3879 *
3880 * "* If a variable is a member of an interface block without an
3881 * instance name, it is enumerated using just the variable name.
3882 *
3883 * * If a variable is a member of an interface block with an
3884 * instance name, it is enumerated as "BlockName.Member", where
3885 * "BlockName" is the name of the interface block (not the
3886 * instance name) and "Member" is the name of the variable."
3887 *
3888 * In particular, it indicates that it should be "BlockName",
3889 * not "BlockName[array length]". The conformance suite and
3890 * dEQP both require this behavior.
3891 *
3892 * Here, we unwrap the extra array level added by named interface
3893 * block array lowering so we have the correct variable type. We
3894 * also unwrap the interface type when constructing the name.
3895 *
3896 * We leave interface_type the same so that ES 3.x SSO pipeline
3897 * validation can enforce the rules requiring array length to
3898 * match on interface blocks.
3899 */
3900 type = type->fields.array;
3901
3902 interface_name = interface_type->fields.array->name;
3903 }
3904
3905 name = ralloc_asprintf(shProg, "%s.%s", interface_name, name);
3906 }
3907 }
3908
3909 switch (type->base_type) {
3910 case GLSL_TYPE_STRUCT: {
3911 /* The ARB_program_interface_query spec says:
3912 *
3913 * "For an active variable declared as a structure, a separate entry
3914 * will be generated for each active structure member. The name of
3915 * each entry is formed by concatenating the name of the structure,
3916 * the "." character, and the name of the structure member. If a
3917 * structure member to enumerate is itself a structure or array,
3918 * these enumeration rules are applied recursively."
3919 */
3920 if (outermost_struct_type == NULL)
3921 outermost_struct_type = type;
3922
3923 unsigned field_location = location;
3924 for (unsigned i = 0; i < type->length; i++) {
3925 const struct glsl_struct_field *field = &type->fields.structure[i];
3926 char *field_name = ralloc_asprintf(shProg, "%s.%s", name, field->name);
3927 if (!add_shader_variable(ctx, shProg, resource_set,
3928 stage_mask, programInterface,
3929 var, field_name, field->type,
3930 use_implicit_location, field_location,
3931 false, outermost_struct_type))
3932 return false;
3933
3934 field_location += field->type->count_attribute_slots(false);
3935 }
3936 return true;
3937 }
3938
3939 case GLSL_TYPE_ARRAY: {
3940 /* The ARB_program_interface_query spec says:
3941 *
3942 * "For an active variable declared as an array of basic types, a
3943 * single entry will be generated, with its name string formed by
3944 * concatenating the name of the array and the string "[0]"."
3945 *
3946 * "For an active variable declared as an array of an aggregate data
3947 * type (structures or arrays), a separate entry will be generated
3948 * for each active array element, unless noted immediately below.
3949 * The name of each entry is formed by concatenating the name of
3950 * the array, the "[" character, an integer identifying the element
3951 * number, and the "]" character. These enumeration rules are
3952 * applied recursively, treating each enumerated array element as a
3953 * separate active variable."
3954 */
3955 const struct glsl_type *array_type = type->fields.array;
3956 if (array_type->base_type == GLSL_TYPE_STRUCT ||
3957 array_type->base_type == GLSL_TYPE_ARRAY) {
3958 unsigned elem_location = location;
3959 unsigned stride = inouts_share_location ? 0 :
3960 array_type->count_attribute_slots(false);
3961 for (unsigned i = 0; i < type->length; i++) {
3962 char *elem = ralloc_asprintf(shProg, "%s[%d]", name, i);
3963 if (!add_shader_variable(ctx, shProg, resource_set,
3964 stage_mask, programInterface,
3965 var, elem, array_type,
3966 use_implicit_location, elem_location,
3967 false, outermost_struct_type))
3968 return false;
3969 elem_location += stride;
3970 }
3971 return true;
3972 }
3973 /* fallthrough */
3974 }
3975
3976 default: {
3977 /* The ARB_program_interface_query spec says:
3978 *
3979 * "For an active variable declared as a single instance of a basic
3980 * type, a single entry will be generated, using the variable name
3981 * from the shader source."
3982 */
3983 gl_shader_variable *sha_v =
3984 create_shader_variable(shProg, var, name, type, interface_type,
3985 use_implicit_location, location,
3986 outermost_struct_type);
3987 if (!sha_v)
3988 return false;
3989
3990 return link_util_add_program_resource(shProg, resource_set,
3991 programInterface, sha_v, stage_mask);
3992 }
3993 }
3994 }
3995
3996 static bool
3997 inout_has_same_location(const ir_variable *var, unsigned stage)
3998 {
3999 if (!var->data.patch &&
4000 ((var->data.mode == ir_var_shader_out &&
4001 stage == MESA_SHADER_TESS_CTRL) ||
4002 (var->data.mode == ir_var_shader_in &&
4003 (stage == MESA_SHADER_TESS_CTRL || stage == MESA_SHADER_TESS_EVAL ||
4004 stage == MESA_SHADER_GEOMETRY))))
4005 return true;
4006 else
4007 return false;
4008 }
4009
4010 static bool
4011 add_interface_variables(const struct gl_context *ctx,
4012 struct gl_shader_program *shProg,
4013 struct set *resource_set,
4014 unsigned stage, GLenum programInterface)
4015 {
4016 exec_list *ir = shProg->_LinkedShaders[stage]->ir;
4017
4018 foreach_in_list(ir_instruction, node, ir) {
4019 ir_variable *var = node->as_variable();
4020
4021 if (!var || var->data.how_declared == ir_var_hidden)
4022 continue;
4023
4024 int loc_bias;
4025
4026 switch (var->data.mode) {
4027 case ir_var_system_value:
4028 case ir_var_shader_in:
4029 if (programInterface != GL_PROGRAM_INPUT)
4030 continue;
4031 loc_bias = (stage == MESA_SHADER_VERTEX) ? int(VERT_ATTRIB_GENERIC0)
4032 : int(VARYING_SLOT_VAR0);
4033 break;
4034 case ir_var_shader_out:
4035 if (programInterface != GL_PROGRAM_OUTPUT)
4036 continue;
4037 loc_bias = (stage == MESA_SHADER_FRAGMENT) ? int(FRAG_RESULT_DATA0)
4038 : int(VARYING_SLOT_VAR0);
4039 break;
4040 default:
4041 continue;
4042 };
4043
4044 if (var->data.patch)
4045 loc_bias = int(VARYING_SLOT_PATCH0);
4046
4047 /* Skip packed varyings, packed varyings are handled separately
4048 * by add_packed_varyings.
4049 */
4050 if (strncmp(var->name, "packed:", 7) == 0)
4051 continue;
4052
4053 /* Skip fragdata arrays, these are handled separately
4054 * by add_fragdata_arrays.
4055 */
4056 if (strncmp(var->name, "gl_out_FragData", 15) == 0)
4057 continue;
4058
4059 const bool vs_input_or_fs_output =
4060 (stage == MESA_SHADER_VERTEX && var->data.mode == ir_var_shader_in) ||
4061 (stage == MESA_SHADER_FRAGMENT && var->data.mode == ir_var_shader_out);
4062
4063 if (!add_shader_variable(ctx, shProg, resource_set,
4064 1 << stage, programInterface,
4065 var, var->name, var->type, vs_input_or_fs_output,
4066 var->data.location - loc_bias,
4067 inout_has_same_location(var, stage)))
4068 return false;
4069 }
4070 return true;
4071 }
4072
4073 static bool
4074 add_packed_varyings(const struct gl_context *ctx,
4075 struct gl_shader_program *shProg,
4076 struct set *resource_set,
4077 int stage, GLenum type)
4078 {
4079 struct gl_linked_shader *sh = shProg->_LinkedShaders[stage];
4080 GLenum iface;
4081
4082 if (!sh || !sh->packed_varyings)
4083 return true;
4084
4085 foreach_in_list(ir_instruction, node, sh->packed_varyings) {
4086 ir_variable *var = node->as_variable();
4087 if (var) {
4088 switch (var->data.mode) {
4089 case ir_var_shader_in:
4090 iface = GL_PROGRAM_INPUT;
4091 break;
4092 case ir_var_shader_out:
4093 iface = GL_PROGRAM_OUTPUT;
4094 break;
4095 default:
4096 unreachable("unexpected type");
4097 }
4098
4099 if (type == iface) {
4100 const int stage_mask =
4101 build_stageref(shProg, var->name, var->data.mode);
4102 if (!add_shader_variable(ctx, shProg, resource_set,
4103 stage_mask,
4104 iface, var, var->name, var->type, false,
4105 var->data.location - VARYING_SLOT_VAR0,
4106 inout_has_same_location(var, stage)))
4107 return false;
4108 }
4109 }
4110 }
4111 return true;
4112 }
4113
4114 static bool
4115 add_fragdata_arrays(const struct gl_context *ctx,
4116 struct gl_shader_program *shProg,
4117 struct set *resource_set)
4118 {
4119 struct gl_linked_shader *sh = shProg->_LinkedShaders[MESA_SHADER_FRAGMENT];
4120
4121 if (!sh || !sh->fragdata_arrays)
4122 return true;
4123
4124 foreach_in_list(ir_instruction, node, sh->fragdata_arrays) {
4125 ir_variable *var = node->as_variable();
4126 if (var) {
4127 assert(var->data.mode == ir_var_shader_out);
4128
4129 if (!add_shader_variable(ctx, shProg, resource_set,
4130 1 << MESA_SHADER_FRAGMENT,
4131 GL_PROGRAM_OUTPUT, var, var->name, var->type,
4132 true, var->data.location - FRAG_RESULT_DATA0,
4133 false))
4134 return false;
4135 }
4136 }
4137 return true;
4138 }
4139
4140 static char*
4141 get_top_level_name(const char *name)
4142 {
4143 const char *first_dot = strchr(name, '.');
4144 const char *first_square_bracket = strchr(name, '[');
4145 int name_size = 0;
4146
4147 /* The ARB_program_interface_query spec says:
4148 *
4149 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4150 * the number of active array elements of the top-level shader storage
4151 * block member containing to the active variable is written to
4152 * <params>. If the top-level block member is not declared as an
4153 * array, the value one is written to <params>. If the top-level block
4154 * member is an array with no declared size, the value zero is written
4155 * to <params>."
4156 */
4157
4158 /* The buffer variable is on top level.*/
4159 if (!first_square_bracket && !first_dot)
4160 name_size = strlen(name);
4161 else if ((!first_square_bracket ||
4162 (first_dot && first_dot < first_square_bracket)))
4163 name_size = first_dot - name;
4164 else
4165 name_size = first_square_bracket - name;
4166
4167 return strndup(name, name_size);
4168 }
4169
4170 static char*
4171 get_var_name(const char *name)
4172 {
4173 const char *first_dot = strchr(name, '.');
4174
4175 if (!first_dot)
4176 return strdup(name);
4177
4178 return strndup(first_dot+1, strlen(first_dot) - 1);
4179 }
4180
4181 static bool
4182 is_top_level_shader_storage_block_member(const char* name,
4183 const char* interface_name,
4184 const char* field_name)
4185 {
4186 bool result = false;
4187
4188 /* If the given variable is already a top-level shader storage
4189 * block member, then return array_size = 1.
4190 * We could have two possibilities: if we have an instanced
4191 * shader storage block or not instanced.
4192 *
4193 * For the first, we check create a name as it was in top level and
4194 * compare it with the real name. If they are the same, then
4195 * the variable is already at top-level.
4196 *
4197 * Full instanced name is: interface name + '.' + var name +
4198 * NULL character
4199 */
4200 int name_length = strlen(interface_name) + 1 + strlen(field_name) + 1;
4201 char *full_instanced_name = (char *) calloc(name_length, sizeof(char));
4202 if (!full_instanced_name) {
4203 fprintf(stderr, "%s: Cannot allocate space for name\n", __func__);
4204 return false;
4205 }
4206
4207 snprintf(full_instanced_name, name_length, "%s.%s",
4208 interface_name, field_name);
4209
4210 /* Check if its top-level shader storage block member of an
4211 * instanced interface block, or of a unnamed interface block.
4212 */
4213 if (strcmp(name, full_instanced_name) == 0 ||
4214 strcmp(name, field_name) == 0)
4215 result = true;
4216
4217 free(full_instanced_name);
4218 return result;
4219 }
4220
4221 static int
4222 get_array_size(struct gl_uniform_storage *uni, const glsl_struct_field *field,
4223 char *interface_name, char *var_name)
4224 {
4225 /* The ARB_program_interface_query spec says:
4226 *
4227 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying
4228 * the number of active array elements of the top-level shader storage
4229 * block member containing to the active variable is written to
4230 * <params>. If the top-level block member is not declared as an
4231 * array, the value one is written to <params>. If the top-level block
4232 * member is an array with no declared size, the value zero is written
4233 * to <params>."
4234 */
4235 if (is_top_level_shader_storage_block_member(uni->name,
4236 interface_name,
4237 var_name))
4238 return 1;
4239 else if (field->type->is_unsized_array())
4240 return 0;
4241 else if (field->type->is_array())
4242 return field->type->length;
4243
4244 return 1;
4245 }
4246
4247 static int
4248 get_array_stride(struct gl_context *ctx, struct gl_uniform_storage *uni,
4249 const glsl_type *iface, const glsl_struct_field *field,
4250 char *interface_name, char *var_name)
4251 {
4252 /* The ARB_program_interface_query spec says:
4253 *
4254 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
4255 * identifying the stride between array elements of the top-level
4256 * shader storage block member containing the active variable is
4257 * written to <params>. For top-level block members declared as
4258 * arrays, the value written is the difference, in basic machine units,
4259 * between the offsets of the active variable for consecutive elements
4260 * in the top-level array. For top-level block members not declared as
4261 * an array, zero is written to <params>."
4262 */
4263 if (field->type->is_array()) {
4264 const enum glsl_matrix_layout matrix_layout =
4265 glsl_matrix_layout(field->matrix_layout);
4266 bool row_major = matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR;
4267 const glsl_type *array_type = field->type->fields.array;
4268
4269 if (is_top_level_shader_storage_block_member(uni->name,
4270 interface_name,
4271 var_name))
4272 return 0;
4273
4274 if (GLSL_INTERFACE_PACKING_STD140 ==
4275 iface->
4276 get_internal_ifc_packing(ctx->Const.UseSTD430AsDefaultPacking)) {
4277 if (array_type->is_struct() || array_type->is_array())
4278 return glsl_align(array_type->std140_size(row_major), 16);
4279 else
4280 return MAX2(array_type->std140_base_alignment(row_major), 16);
4281 } else {
4282 return array_type->std430_array_stride(row_major);
4283 }
4284 }
4285 return 0;
4286 }
4287
4288 static void
4289 calculate_array_size_and_stride(struct gl_context *ctx,
4290 struct gl_shader_program *shProg,
4291 struct gl_uniform_storage *uni)
4292 {
4293 int block_index = uni->block_index;
4294 int array_size = -1;
4295 int array_stride = -1;
4296 char *var_name = get_top_level_name(uni->name);
4297 char *interface_name =
4298 get_top_level_name(uni->is_shader_storage ?
4299 shProg->data->ShaderStorageBlocks[block_index].Name :
4300 shProg->data->UniformBlocks[block_index].Name);
4301
4302 if (strcmp(var_name, interface_name) == 0) {
4303 /* Deal with instanced array of SSBOs */
4304 char *temp_name = get_var_name(uni->name);
4305 if (!temp_name) {
4306 linker_error(shProg, "Out of memory during linking.\n");
4307 goto write_top_level_array_size_and_stride;
4308 }
4309 free(var_name);
4310 var_name = get_top_level_name(temp_name);
4311 free(temp_name);
4312 if (!var_name) {
4313 linker_error(shProg, "Out of memory during linking.\n");
4314 goto write_top_level_array_size_and_stride;
4315 }
4316 }
4317
4318 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4319 const gl_linked_shader *sh = shProg->_LinkedShaders[i];
4320 if (sh == NULL)
4321 continue;
4322
4323 foreach_in_list(ir_instruction, node, sh->ir) {
4324 ir_variable *var = node->as_variable();
4325 if (!var || !var->get_interface_type() ||
4326 var->data.mode != ir_var_shader_storage)
4327 continue;
4328
4329 const glsl_type *iface = var->get_interface_type();
4330
4331 if (strcmp(interface_name, iface->name) != 0)
4332 continue;
4333
4334 for (unsigned i = 0; i < iface->length; i++) {
4335 const glsl_struct_field *field = &iface->fields.structure[i];
4336 if (strcmp(field->name, var_name) != 0)
4337 continue;
4338
4339 array_stride = get_array_stride(ctx, uni, iface, field,
4340 interface_name, var_name);
4341 array_size = get_array_size(uni, field, interface_name, var_name);
4342 goto write_top_level_array_size_and_stride;
4343 }
4344 }
4345 }
4346 write_top_level_array_size_and_stride:
4347 free(interface_name);
4348 free(var_name);
4349 uni->top_level_array_stride = array_stride;
4350 uni->top_level_array_size = array_size;
4351 }
4352
4353 /**
4354 * Builds up a list of program resources that point to existing
4355 * resource data.
4356 */
4357 void
4358 build_program_resource_list(struct gl_context *ctx,
4359 struct gl_shader_program *shProg)
4360 {
4361 /* Rebuild resource list. */
4362 if (shProg->data->ProgramResourceList) {
4363 ralloc_free(shProg->data->ProgramResourceList);
4364 shProg->data->ProgramResourceList = NULL;
4365 shProg->data->NumProgramResourceList = 0;
4366 }
4367
4368 int input_stage = MESA_SHADER_STAGES, output_stage = 0;
4369
4370 /* Determine first input and final output stage. These are used to
4371 * detect which variables should be enumerated in the resource list
4372 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4373 */
4374 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4375 if (!shProg->_LinkedShaders[i])
4376 continue;
4377 if (input_stage == MESA_SHADER_STAGES)
4378 input_stage = i;
4379 output_stage = i;
4380 }
4381
4382 /* Empty shader, no resources. */
4383 if (input_stage == MESA_SHADER_STAGES && output_stage == 0)
4384 return;
4385
4386 struct set *resource_set = _mesa_pointer_set_create(NULL);
4387
4388 /* Program interface needs to expose varyings in case of SSO. */
4389 if (shProg->SeparateShader) {
4390 if (!add_packed_varyings(ctx, shProg, resource_set,
4391 input_stage, GL_PROGRAM_INPUT))
4392 return;
4393
4394 if (!add_packed_varyings(ctx, shProg, resource_set,
4395 output_stage, GL_PROGRAM_OUTPUT))
4396 return;
4397 }
4398
4399 if (!add_fragdata_arrays(ctx, shProg, resource_set))
4400 return;
4401
4402 /* Add inputs and outputs to the resource list. */
4403 if (!add_interface_variables(ctx, shProg, resource_set,
4404 input_stage, GL_PROGRAM_INPUT))
4405 return;
4406
4407 if (!add_interface_variables(ctx, shProg, resource_set,
4408 output_stage, GL_PROGRAM_OUTPUT))
4409 return;
4410
4411 if (shProg->last_vert_prog) {
4412 struct gl_transform_feedback_info *linked_xfb =
4413 shProg->last_vert_prog->sh.LinkedTransformFeedback;
4414
4415 /* Add transform feedback varyings. */
4416 if (linked_xfb->NumVarying > 0) {
4417 for (int i = 0; i < linked_xfb->NumVarying; i++) {
4418 if (!link_util_add_program_resource(shProg, resource_set,
4419 GL_TRANSFORM_FEEDBACK_VARYING,
4420 &linked_xfb->Varyings[i], 0))
4421 return;
4422 }
4423 }
4424
4425 /* Add transform feedback buffers. */
4426 for (unsigned i = 0; i < ctx->Const.MaxTransformFeedbackBuffers; i++) {
4427 if ((linked_xfb->ActiveBuffers >> i) & 1) {
4428 linked_xfb->Buffers[i].Binding = i;
4429 if (!link_util_add_program_resource(shProg, resource_set,
4430 GL_TRANSFORM_FEEDBACK_BUFFER,
4431 &linked_xfb->Buffers[i], 0))
4432 return;
4433 }
4434 }
4435 }
4436
4437 int top_level_array_base_offset = -1;
4438 int top_level_array_size_in_bytes = -1;
4439 int second_element_offset = -1;
4440 int buffer_block_index = -1;
4441
4442 /* Add uniforms from uniform storage. */
4443 for (unsigned i = 0; i < shProg->data->NumUniformStorage; i++) {
4444 /* Do not add uniforms internally used by Mesa. */
4445 if (shProg->data->UniformStorage[i].hidden)
4446 continue;
4447
4448 uint8_t stageref =
4449 build_stageref(shProg, shProg->data->UniformStorage[i].name,
4450 ir_var_uniform);
4451
4452 /* Add stagereferences for uniforms in a uniform block. */
4453 bool is_shader_storage =
4454 shProg->data->UniformStorage[i].is_shader_storage;
4455 int block_index = shProg->data->UniformStorage[i].block_index;
4456 if (block_index != -1) {
4457 stageref |= is_shader_storage ?
4458 shProg->data->ShaderStorageBlocks[block_index].stageref :
4459 shProg->data->UniformBlocks[block_index].stageref;
4460 }
4461
4462 GLenum type = is_shader_storage ? GL_BUFFER_VARIABLE : GL_UNIFORM;
4463 if (!link_util_should_add_buffer_variable(shProg,
4464 &shProg->data->UniformStorage[i],
4465 top_level_array_base_offset,
4466 top_level_array_size_in_bytes,
4467 second_element_offset,
4468 buffer_block_index))
4469 continue;
4470
4471 if (is_shader_storage) {
4472 calculate_array_size_and_stride(ctx, shProg,
4473 &shProg->data->UniformStorage[i]);
4474
4475 /* From the OpenGL 4.6 specification, 7.3.1.1 Naming Active Resources:
4476 *
4477 * "For an active shader storage block member declared as an array
4478 * of an aggregate type, an entry will be generated only for the
4479 * first array element, regardless of its type. Such block members
4480 * are referred to as top-level arrays. If the block member is an
4481 * aggregate type, the enumeration rules are then applied
4482 * recursively."
4483 *
4484 * Below we update our tracking values used by
4485 * link_util_should_add_buffer_variable(). We only want to reset the
4486 * offsets once we have moved past the first element.
4487 */
4488 if (shProg->data->UniformStorage[i].offset >= second_element_offset) {
4489 top_level_array_base_offset =
4490 shProg->data->UniformStorage[i].offset;
4491
4492 top_level_array_size_in_bytes =
4493 shProg->data->UniformStorage[i].top_level_array_size *
4494 shProg->data->UniformStorage[i].top_level_array_stride;
4495
4496 /* Set or reset the second element offset. For non arrays this
4497 * will be set to -1.
4498 */
4499 second_element_offset = top_level_array_size_in_bytes ?
4500 top_level_array_base_offset +
4501 shProg->data->UniformStorage[i].top_level_array_stride : -1;
4502 }
4503
4504 buffer_block_index = shProg->data->UniformStorage[i].block_index;
4505 }
4506
4507 if (!link_util_add_program_resource(shProg, resource_set, type,
4508 &shProg->data->UniformStorage[i], stageref))
4509 return;
4510 }
4511
4512 /* Add program uniform blocks. */
4513 for (unsigned i = 0; i < shProg->data->NumUniformBlocks; i++) {
4514 if (!link_util_add_program_resource(shProg, resource_set, GL_UNIFORM_BLOCK,
4515 &shProg->data->UniformBlocks[i], 0))
4516 return;
4517 }
4518
4519 /* Add program shader storage blocks. */
4520 for (unsigned i = 0; i < shProg->data->NumShaderStorageBlocks; i++) {
4521 if (!link_util_add_program_resource(shProg, resource_set, GL_SHADER_STORAGE_BLOCK,
4522 &shProg->data->ShaderStorageBlocks[i], 0))
4523 return;
4524 }
4525
4526 /* Add atomic counter buffers. */
4527 for (unsigned i = 0; i < shProg->data->NumAtomicBuffers; i++) {
4528 if (!link_util_add_program_resource(shProg, resource_set, GL_ATOMIC_COUNTER_BUFFER,
4529 &shProg->data->AtomicBuffers[i], 0))
4530 return;
4531 }
4532
4533 for (unsigned i = 0; i < shProg->data->NumUniformStorage; i++) {
4534 GLenum type;
4535 if (!shProg->data->UniformStorage[i].hidden)
4536 continue;
4537
4538 for (int j = MESA_SHADER_VERTEX; j < MESA_SHADER_STAGES; j++) {
4539 if (!shProg->data->UniformStorage[i].opaque[j].active ||
4540 !shProg->data->UniformStorage[i].type->is_subroutine())
4541 continue;
4542
4543 type = _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage)j);
4544 /* add shader subroutines */
4545 if (!link_util_add_program_resource(shProg, resource_set,
4546 type, &shProg->data->UniformStorage[i], 0))
4547 return;
4548 }
4549 }
4550
4551 unsigned mask = shProg->data->linked_stages;
4552 while (mask) {
4553 const int i = u_bit_scan(&mask);
4554 struct gl_program *p = shProg->_LinkedShaders[i]->Program;
4555
4556 GLuint type = _mesa_shader_stage_to_subroutine((gl_shader_stage)i);
4557 for (unsigned j = 0; j < p->sh.NumSubroutineFunctions; j++) {
4558 if (!link_util_add_program_resource(shProg, resource_set,
4559 type, &p->sh.SubroutineFunctions[j], 0))
4560 return;
4561 }
4562 }
4563
4564 _mesa_set_destroy(resource_set, NULL);
4565 }
4566
4567 /**
4568 * This check is done to make sure we allow only constant expression
4569 * indexing and "constant-index-expression" (indexing with an expression
4570 * that includes loop induction variable).
4571 */
4572 static bool
4573 validate_sampler_array_indexing(struct gl_context *ctx,
4574 struct gl_shader_program *prog)
4575 {
4576 dynamic_sampler_array_indexing_visitor v;
4577 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4578 if (prog->_LinkedShaders[i] == NULL)
4579 continue;
4580
4581 bool no_dynamic_indexing =
4582 ctx->Const.ShaderCompilerOptions[i].EmitNoIndirectSampler;
4583
4584 /* Search for array derefs in shader. */
4585 v.run(prog->_LinkedShaders[i]->ir);
4586 if (v.uses_dynamic_sampler_array_indexing()) {
4587 const char *msg = "sampler arrays indexed with non-constant "
4588 "expressions is forbidden in GLSL %s %u";
4589 /* Backend has indicated that it has no dynamic indexing support. */
4590 if (no_dynamic_indexing) {
4591 linker_error(prog, msg, prog->IsES ? "ES" : "",
4592 prog->data->Version);
4593 return false;
4594 } else {
4595 linker_warning(prog, msg, prog->IsES ? "ES" : "",
4596 prog->data->Version);
4597 }
4598 }
4599 }
4600 return true;
4601 }
4602
4603 static void
4604 link_assign_subroutine_types(struct gl_shader_program *prog)
4605 {
4606 unsigned mask = prog->data->linked_stages;
4607 while (mask) {
4608 const int i = u_bit_scan(&mask);
4609 gl_program *p = prog->_LinkedShaders[i]->Program;
4610
4611 p->sh.MaxSubroutineFunctionIndex = 0;
4612 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
4613 ir_function *fn = node->as_function();
4614 if (!fn)
4615 continue;
4616
4617 if (fn->is_subroutine)
4618 p->sh.NumSubroutineUniformTypes++;
4619
4620 if (!fn->num_subroutine_types)
4621 continue;
4622
4623 /* these should have been calculated earlier. */
4624 assert(fn->subroutine_index != -1);
4625 if (p->sh.NumSubroutineFunctions + 1 > MAX_SUBROUTINES) {
4626 linker_error(prog, "Too many subroutine functions declared.\n");
4627 return;
4628 }
4629 p->sh.SubroutineFunctions = reralloc(p, p->sh.SubroutineFunctions,
4630 struct gl_subroutine_function,
4631 p->sh.NumSubroutineFunctions + 1);
4632 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].name = ralloc_strdup(p, fn->name);
4633 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].num_compat_types = fn->num_subroutine_types;
4634 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].types =
4635 ralloc_array(p, const struct glsl_type *,
4636 fn->num_subroutine_types);
4637
4638 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4639 * GLSL 4.5 spec:
4640 *
4641 * "Each subroutine with an index qualifier in the shader must be
4642 * given a unique index, otherwise a compile or link error will be
4643 * generated."
4644 */
4645 for (unsigned j = 0; j < p->sh.NumSubroutineFunctions; j++) {
4646 if (p->sh.SubroutineFunctions[j].index != -1 &&
4647 p->sh.SubroutineFunctions[j].index == fn->subroutine_index) {
4648 linker_error(prog, "each subroutine index qualifier in the "
4649 "shader must be unique\n");
4650 return;
4651 }
4652 }
4653 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].index =
4654 fn->subroutine_index;
4655
4656 if (fn->subroutine_index > (int)p->sh.MaxSubroutineFunctionIndex)
4657 p->sh.MaxSubroutineFunctionIndex = fn->subroutine_index;
4658
4659 for (int j = 0; j < fn->num_subroutine_types; j++)
4660 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].types[j] = fn->subroutine_types[j];
4661 p->sh.NumSubroutineFunctions++;
4662 }
4663 }
4664 }
4665
4666 static void
4667 verify_subroutine_associated_funcs(struct gl_shader_program *prog)
4668 {
4669 unsigned mask = prog->data->linked_stages;
4670 while (mask) {
4671 const int i = u_bit_scan(&mask);
4672 gl_program *p = prog->_LinkedShaders[i]->Program;
4673 glsl_symbol_table *symbols = prog->_LinkedShaders[i]->symbols;
4674
4675 /* Section 6.1.2 (Subroutines) of the GLSL 4.00 spec says:
4676 *
4677 * "A program will fail to compile or link if any shader
4678 * or stage contains two or more functions with the same
4679 * name if the name is associated with a subroutine type."
4680 */
4681 for (unsigned j = 0; j < p->sh.NumSubroutineFunctions; j++) {
4682 unsigned definitions = 0;
4683 char *name = p->sh.SubroutineFunctions[j].name;
4684 ir_function *fn = symbols->get_function(name);
4685
4686 /* Calculate number of function definitions with the same name */
4687 foreach_in_list(ir_function_signature, sig, &fn->signatures) {
4688 if (sig->is_defined) {
4689 if (++definitions > 1) {
4690 linker_error(prog, "%s shader contains two or more function "
4691 "definitions with name `%s', which is "
4692 "associated with a subroutine type.\n",
4693 _mesa_shader_stage_to_string(i),
4694 fn->name);
4695 return;
4696 }
4697 }
4698 }
4699 }
4700 }
4701 }
4702
4703
4704 static void
4705 set_always_active_io(exec_list *ir, ir_variable_mode io_mode)
4706 {
4707 assert(io_mode == ir_var_shader_in || io_mode == ir_var_shader_out);
4708
4709 foreach_in_list(ir_instruction, node, ir) {
4710 ir_variable *const var = node->as_variable();
4711
4712 if (var == NULL || var->data.mode != io_mode)
4713 continue;
4714
4715 /* Don't set always active on builtins that haven't been redeclared */
4716 if (var->data.how_declared == ir_var_declared_implicitly)
4717 continue;
4718
4719 var->data.always_active_io = true;
4720 }
4721 }
4722
4723 /**
4724 * When separate shader programs are enabled, only input/outputs between
4725 * the stages of a multi-stage separate program can be safely removed
4726 * from the shader interface. Other inputs/outputs must remain active.
4727 */
4728 static void
4729 disable_varying_optimizations_for_sso(struct gl_shader_program *prog)
4730 {
4731 unsigned first, last;
4732 assert(prog->SeparateShader);
4733
4734 first = MESA_SHADER_STAGES;
4735 last = 0;
4736
4737 /* Determine first and last stage. Excluding the compute stage */
4738 for (unsigned i = 0; i < MESA_SHADER_COMPUTE; i++) {
4739 if (!prog->_LinkedShaders[i])
4740 continue;
4741 if (first == MESA_SHADER_STAGES)
4742 first = i;
4743 last = i;
4744 }
4745
4746 if (first == MESA_SHADER_STAGES)
4747 return;
4748
4749 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
4750 gl_linked_shader *sh = prog->_LinkedShaders[stage];
4751 if (!sh)
4752 continue;
4753
4754 /* Prevent the removal of inputs to the first and outputs from the last
4755 * stage, unless they are the initial pipeline inputs or final pipeline
4756 * outputs, respectively.
4757 *
4758 * The removal of IO between shaders in the same program is always
4759 * allowed.
4760 */
4761 if (stage == first && stage != MESA_SHADER_VERTEX)
4762 set_always_active_io(sh->ir, ir_var_shader_in);
4763 if (stage == last && stage != MESA_SHADER_FRAGMENT)
4764 set_always_active_io(sh->ir, ir_var_shader_out);
4765 }
4766 }
4767
4768 static void
4769 link_and_validate_uniforms(struct gl_context *ctx,
4770 struct gl_shader_program *prog)
4771 {
4772 update_array_sizes(prog);
4773 link_assign_uniform_locations(prog, ctx);
4774
4775 link_assign_atomic_counter_resources(ctx, prog);
4776 link_calculate_subroutine_compat(prog);
4777 check_resources(ctx, prog);
4778 check_subroutine_resources(prog);
4779 check_image_resources(ctx, prog);
4780 link_check_atomic_counter_resources(ctx, prog);
4781 }
4782
4783 static bool
4784 link_varyings_and_uniforms(unsigned first, unsigned last,
4785 struct gl_context *ctx,
4786 struct gl_shader_program *prog, void *mem_ctx)
4787 {
4788 /* Mark all generic shader inputs and outputs as unpaired. */
4789 for (unsigned i = MESA_SHADER_VERTEX; i <= MESA_SHADER_FRAGMENT; i++) {
4790 if (prog->_LinkedShaders[i] != NULL) {
4791 link_invalidate_variable_locations(prog->_LinkedShaders[i]->ir);
4792 }
4793 }
4794
4795 unsigned prev = first;
4796 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
4797 if (prog->_LinkedShaders[i] == NULL)
4798 continue;
4799
4800 match_explicit_outputs_to_inputs(prog->_LinkedShaders[prev],
4801 prog->_LinkedShaders[i]);
4802 prev = i;
4803 }
4804
4805 if (!assign_attribute_or_color_locations(mem_ctx, prog, &ctx->Const,
4806 MESA_SHADER_VERTEX, true)) {
4807 return false;
4808 }
4809
4810 if (!assign_attribute_or_color_locations(mem_ctx, prog, &ctx->Const,
4811 MESA_SHADER_FRAGMENT, true)) {
4812 return false;
4813 }
4814
4815 prog->last_vert_prog = NULL;
4816 for (int i = MESA_SHADER_GEOMETRY; i >= MESA_SHADER_VERTEX; i--) {
4817 if (prog->_LinkedShaders[i] == NULL)
4818 continue;
4819
4820 prog->last_vert_prog = prog->_LinkedShaders[i]->Program;
4821 break;
4822 }
4823
4824 if (!link_varyings(prog, first, last, ctx, mem_ctx))
4825 return false;
4826
4827 link_and_validate_uniforms(ctx, prog);
4828
4829 if (!prog->data->LinkStatus)
4830 return false;
4831
4832 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4833 if (prog->_LinkedShaders[i] == NULL)
4834 continue;
4835
4836 const struct gl_shader_compiler_options *options =
4837 &ctx->Const.ShaderCompilerOptions[i];
4838
4839 if (options->LowerBufferInterfaceBlocks)
4840 lower_ubo_reference(prog->_LinkedShaders[i],
4841 options->ClampBlockIndicesToArrayBounds,
4842 ctx->Const.UseSTD430AsDefaultPacking);
4843
4844 if (i == MESA_SHADER_COMPUTE)
4845 lower_shared_reference(ctx, prog, prog->_LinkedShaders[i]);
4846
4847 lower_vector_derefs(prog->_LinkedShaders[i]);
4848 do_vec_index_to_swizzle(prog->_LinkedShaders[i]->ir);
4849 }
4850
4851 return true;
4852 }
4853
4854 static void
4855 linker_optimisation_loop(struct gl_context *ctx, exec_list *ir,
4856 unsigned stage)
4857 {
4858 if (ctx->Const.GLSLOptimizeConservatively) {
4859 /* Run it just once. */
4860 do_common_optimization(ir, true, false,
4861 &ctx->Const.ShaderCompilerOptions[stage],
4862 ctx->Const.NativeIntegers);
4863 } else {
4864 /* Repeat it until it stops making changes. */
4865 while (do_common_optimization(ir, true, false,
4866 &ctx->Const.ShaderCompilerOptions[stage],
4867 ctx->Const.NativeIntegers))
4868 ;
4869 }
4870 }
4871
4872 void
4873 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
4874 {
4875 prog->data->LinkStatus = LINKING_SUCCESS; /* All error paths will set this to false */
4876 prog->data->Validated = false;
4877
4878 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4879 *
4880 * "Linking can fail for a variety of reasons as specified in the
4881 * OpenGL Shading Language Specification, as well as any of the
4882 * following reasons:
4883 *
4884 * - No shader objects are attached to program."
4885 *
4886 * The Compatibility Profile specification does not list the error. In
4887 * Compatibility Profile missing shader stages are replaced by
4888 * fixed-function. This applies to the case where all stages are
4889 * missing.
4890 */
4891 if (prog->NumShaders == 0) {
4892 if (ctx->API != API_OPENGL_COMPAT)
4893 linker_error(prog, "no shaders attached to the program\n");
4894 return;
4895 }
4896
4897 #ifdef ENABLE_SHADER_CACHE
4898 if (shader_cache_read_program_metadata(ctx, prog))
4899 return;
4900 #endif
4901
4902 void *mem_ctx = ralloc_context(NULL); // temporary linker context
4903
4904 prog->ARB_fragment_coord_conventions_enable = false;
4905
4906 /* Separate the shaders into groups based on their type.
4907 */
4908 struct gl_shader **shader_list[MESA_SHADER_STAGES];
4909 unsigned num_shaders[MESA_SHADER_STAGES];
4910
4911 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
4912 shader_list[i] = (struct gl_shader **)
4913 calloc(prog->NumShaders, sizeof(struct gl_shader *));
4914 num_shaders[i] = 0;
4915 }
4916
4917 unsigned min_version = UINT_MAX;
4918 unsigned max_version = 0;
4919 for (unsigned i = 0; i < prog->NumShaders; i++) {
4920 min_version = MIN2(min_version, prog->Shaders[i]->Version);
4921 max_version = MAX2(max_version, prog->Shaders[i]->Version);
4922
4923 if (!ctx->Const.AllowGLSLRelaxedES &&
4924 prog->Shaders[i]->IsES != prog->Shaders[0]->IsES) {
4925 linker_error(prog, "all shaders must use same shading "
4926 "language version\n");
4927 goto done;
4928 }
4929
4930 if (prog->Shaders[i]->ARB_fragment_coord_conventions_enable) {
4931 prog->ARB_fragment_coord_conventions_enable = true;
4932 }
4933
4934 gl_shader_stage shader_type = prog->Shaders[i]->Stage;
4935 shader_list[shader_type][num_shaders[shader_type]] = prog->Shaders[i];
4936 num_shaders[shader_type]++;
4937 }
4938
4939 /* In desktop GLSL, different shader versions may be linked together. In
4940 * GLSL ES, all shader versions must be the same.
4941 */
4942 if (!ctx->Const.AllowGLSLRelaxedES && prog->Shaders[0]->IsES &&
4943 min_version != max_version) {
4944 linker_error(prog, "all shaders must use same shading "
4945 "language version\n");
4946 goto done;
4947 }
4948
4949 prog->data->Version = max_version;
4950 prog->IsES = prog->Shaders[0]->IsES;
4951
4952 /* Some shaders have to be linked with some other shaders present.
4953 */
4954 if (!prog->SeparateShader) {
4955 if (num_shaders[MESA_SHADER_GEOMETRY] > 0 &&
4956 num_shaders[MESA_SHADER_VERTEX] == 0) {
4957 linker_error(prog, "Geometry shader must be linked with "
4958 "vertex shader\n");
4959 goto done;
4960 }
4961 if (num_shaders[MESA_SHADER_TESS_EVAL] > 0 &&
4962 num_shaders[MESA_SHADER_VERTEX] == 0) {
4963 linker_error(prog, "Tessellation evaluation shader must be linked "
4964 "with vertex shader\n");
4965 goto done;
4966 }
4967 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
4968 num_shaders[MESA_SHADER_VERTEX] == 0) {
4969 linker_error(prog, "Tessellation control shader must be linked with "
4970 "vertex shader\n");
4971 goto done;
4972 }
4973
4974 /* Section 7.3 of the OpenGL ES 3.2 specification says:
4975 *
4976 * "Linking can fail for [...] any of the following reasons:
4977 *
4978 * * program contains an object to form a tessellation control
4979 * shader [...] and [...] the program is not separable and
4980 * contains no object to form a tessellation evaluation shader"
4981 *
4982 * The OpenGL spec is contradictory. It allows linking without a tess
4983 * eval shader, but that can only be used with transform feedback and
4984 * rasterization disabled. However, transform feedback isn't allowed
4985 * with GL_PATCHES, so it can't be used.
4986 *
4987 * More investigation showed that the idea of transform feedback after
4988 * a tess control shader was dropped, because some hw vendors couldn't
4989 * support tessellation without a tess eval shader, but the linker
4990 * section wasn't updated to reflect that.
4991 *
4992 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4993 * spec bug.
4994 *
4995 * Do what's reasonable and always require a tess eval shader if a tess
4996 * control shader is present.
4997 */
4998 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
4999 num_shaders[MESA_SHADER_TESS_EVAL] == 0) {
5000 linker_error(prog, "Tessellation control shader must be linked with "
5001 "tessellation evaluation shader\n");
5002 goto done;
5003 }
5004
5005 if (prog->IsES) {
5006 if (num_shaders[MESA_SHADER_TESS_EVAL] > 0 &&
5007 num_shaders[MESA_SHADER_TESS_CTRL] == 0) {
5008 linker_error(prog, "GLSL ES requires non-separable programs "
5009 "containing a tessellation evaluation shader to also "
5010 "be linked with a tessellation control shader\n");
5011 goto done;
5012 }
5013 }
5014 }
5015
5016 /* Compute shaders have additional restrictions. */
5017 if (num_shaders[MESA_SHADER_COMPUTE] > 0 &&
5018 num_shaders[MESA_SHADER_COMPUTE] != prog->NumShaders) {
5019 linker_error(prog, "Compute shaders may not be linked with any other "
5020 "type of shader\n");
5021 }
5022
5023 /* Link all shaders for a particular stage and validate the result.
5024 */
5025 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
5026 if (num_shaders[stage] > 0) {
5027 gl_linked_shader *const sh =
5028 link_intrastage_shaders(mem_ctx, ctx, prog, shader_list[stage],
5029 num_shaders[stage], false);
5030
5031 if (!prog->data->LinkStatus) {
5032 if (sh)
5033 _mesa_delete_linked_shader(ctx, sh);
5034 goto done;
5035 }
5036
5037 switch (stage) {
5038 case MESA_SHADER_VERTEX:
5039 validate_vertex_shader_executable(prog, sh, ctx);
5040 break;
5041 case MESA_SHADER_TESS_CTRL:
5042 /* nothing to be done */
5043 break;
5044 case MESA_SHADER_TESS_EVAL:
5045 validate_tess_eval_shader_executable(prog, sh, ctx);
5046 break;
5047 case MESA_SHADER_GEOMETRY:
5048 validate_geometry_shader_executable(prog, sh, ctx);
5049 break;
5050 case MESA_SHADER_FRAGMENT:
5051 validate_fragment_shader_executable(prog, sh);
5052 break;
5053 }
5054 if (!prog->data->LinkStatus) {
5055 if (sh)
5056 _mesa_delete_linked_shader(ctx, sh);
5057 goto done;
5058 }
5059
5060 prog->_LinkedShaders[stage] = sh;
5061 prog->data->linked_stages |= 1 << stage;
5062 }
5063 }
5064
5065 /* Here begins the inter-stage linking phase. Some initial validation is
5066 * performed, then locations are assigned for uniforms, attributes, and
5067 * varyings.
5068 */
5069 cross_validate_uniforms(ctx, prog);
5070 if (!prog->data->LinkStatus)
5071 goto done;
5072
5073 unsigned first, last, prev;
5074
5075 first = MESA_SHADER_STAGES;
5076 last = 0;
5077
5078 /* Determine first and last stage. */
5079 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
5080 if (!prog->_LinkedShaders[i])
5081 continue;
5082 if (first == MESA_SHADER_STAGES)
5083 first = i;
5084 last = i;
5085 }
5086
5087 check_explicit_uniform_locations(ctx, prog);
5088 link_assign_subroutine_types(prog);
5089 verify_subroutine_associated_funcs(prog);
5090
5091 if (!prog->data->LinkStatus)
5092 goto done;
5093
5094 resize_tes_inputs(ctx, prog);
5095
5096 /* Validate the inputs of each stage with the output of the preceding
5097 * stage.
5098 */
5099 prev = first;
5100 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
5101 if (prog->_LinkedShaders[i] == NULL)
5102 continue;
5103
5104 validate_interstage_inout_blocks(prog, prog->_LinkedShaders[prev],
5105 prog->_LinkedShaders[i]);
5106 if (!prog->data->LinkStatus)
5107 goto done;
5108
5109 cross_validate_outputs_to_inputs(ctx, prog,
5110 prog->_LinkedShaders[prev],
5111 prog->_LinkedShaders[i]);
5112 if (!prog->data->LinkStatus)
5113 goto done;
5114
5115 prev = i;
5116 }
5117
5118 /* The cross validation of outputs/inputs above validates interstage
5119 * explicit locations. We need to do this also for the inputs in the first
5120 * stage and outputs of the last stage included in the program, since there
5121 * is no cross validation for these.
5122 */
5123 validate_first_and_last_interface_explicit_locations(ctx, prog,
5124 (gl_shader_stage) first,
5125 (gl_shader_stage) last);
5126
5127 /* Cross-validate uniform blocks between shader stages */
5128 validate_interstage_uniform_blocks(prog, prog->_LinkedShaders);
5129 if (!prog->data->LinkStatus)
5130 goto done;
5131
5132 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
5133 if (prog->_LinkedShaders[i] != NULL)
5134 lower_named_interface_blocks(mem_ctx, prog->_LinkedShaders[i]);
5135 }
5136
5137 if (prog->IsES && prog->data->Version == 100)
5138 if (!validate_invariant_builtins(prog,
5139 prog->_LinkedShaders[MESA_SHADER_VERTEX],
5140 prog->_LinkedShaders[MESA_SHADER_FRAGMENT]))
5141 goto done;
5142
5143 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
5144 * it before optimization because we want most of the checks to get
5145 * dropped thanks to constant propagation.
5146 *
5147 * This rule also applies to GLSL ES 3.00.
5148 */
5149 if (max_version >= (prog->IsES ? 300 : 130)) {
5150 struct gl_linked_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
5151 if (sh) {
5152 lower_discard_flow(sh->ir);
5153 }
5154 }
5155
5156 if (prog->SeparateShader)
5157 disable_varying_optimizations_for_sso(prog);
5158
5159 /* Process UBOs */
5160 if (!interstage_cross_validate_uniform_blocks(prog, false))
5161 goto done;
5162
5163 /* Process SSBOs */
5164 if (!interstage_cross_validate_uniform_blocks(prog, true))
5165 goto done;
5166
5167 /* Do common optimization before assigning storage for attributes,
5168 * uniforms, and varyings. Later optimization could possibly make
5169 * some of that unused.
5170 */
5171 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
5172 if (prog->_LinkedShaders[i] == NULL)
5173 continue;
5174
5175 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
5176 if (!prog->data->LinkStatus)
5177 goto done;
5178
5179 if (ctx->Const.ShaderCompilerOptions[i].LowerCombinedClipCullDistance) {
5180 lower_clip_cull_distance(prog, prog->_LinkedShaders[i]);
5181 }
5182
5183 if (ctx->Const.LowerTessLevel) {
5184 lower_tess_level(prog->_LinkedShaders[i]);
5185 }
5186
5187 /* Section 13.46 (Vertex Attribute Aliasing) of the OpenGL ES 3.2
5188 * specification says:
5189 *
5190 * "In general, the behavior of GLSL ES should not depend on compiler
5191 * optimizations which might be implementation-dependent. Name matching
5192 * rules in most languages, including C++ from which GLSL ES is derived,
5193 * are based on declarations rather than use.
5194 *
5195 * RESOLUTION: The existence of aliasing is determined by declarations
5196 * present after preprocessing."
5197 *
5198 * Because of this rule, we do a 'dry-run' of attribute assignment for
5199 * vertex shader inputs here.
5200 */
5201 if (prog->IsES && i == MESA_SHADER_VERTEX) {
5202 if (!assign_attribute_or_color_locations(mem_ctx, prog, &ctx->Const,
5203 MESA_SHADER_VERTEX, false)) {
5204 goto done;
5205 }
5206 }
5207
5208 /* Call opts before lowering const arrays to uniforms so we can const
5209 * propagate any elements accessed directly.
5210 */
5211 linker_optimisation_loop(ctx, prog->_LinkedShaders[i]->ir, i);
5212
5213 /* Call opts after lowering const arrays to copy propagate things. */
5214 if (ctx->Const.GLSLLowerConstArrays &&
5215 lower_const_arrays_to_uniforms(prog->_LinkedShaders[i]->ir, i))
5216 linker_optimisation_loop(ctx, prog->_LinkedShaders[i]->ir, i);
5217 }
5218
5219 /* Validation for special cases where we allow sampler array indexing
5220 * with loop induction variable. This check emits a warning or error
5221 * depending if backend can handle dynamic indexing.
5222 */
5223 if ((!prog->IsES && prog->data->Version < 130) ||
5224 (prog->IsES && prog->data->Version < 300)) {
5225 if (!validate_sampler_array_indexing(ctx, prog))
5226 goto done;
5227 }
5228
5229 /* Check and validate stream emissions in geometry shaders */
5230 validate_geometry_shader_emissions(ctx, prog);
5231
5232 store_fragdepth_layout(prog);
5233
5234 if(!link_varyings_and_uniforms(first, last, ctx, prog, mem_ctx))
5235 goto done;
5236
5237 /* Linking varyings can cause some extra, useless swizzles to be generated
5238 * due to packing and unpacking.
5239 */
5240 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
5241 if (prog->_LinkedShaders[i] == NULL)
5242 continue;
5243
5244 optimize_swizzles(prog->_LinkedShaders[i]->ir);
5245 }
5246
5247 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
5248 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
5249 * anything about shader linking when one of the shaders (vertex or
5250 * fragment shader) is absent. So, the extension shouldn't change the
5251 * behavior specified in GLSL specification.
5252 *
5253 * From OpenGL ES 3.1 specification (7.3 Program Objects):
5254 * "Linking can fail for a variety of reasons as specified in the
5255 * OpenGL ES Shading Language Specification, as well as any of the
5256 * following reasons:
5257 *
5258 * ...
5259 *
5260 * * program contains objects to form either a vertex shader or
5261 * fragment shader, and program is not separable, and does not
5262 * contain objects to form both a vertex shader and fragment
5263 * shader."
5264 *
5265 * However, the only scenario in 3.1+ where we don't require them both is
5266 * when we have a compute shader. For example:
5267 *
5268 * - No shaders is a link error.
5269 * - Geom or Tess without a Vertex shader is a link error which means we
5270 * always require a Vertex shader and hence a Fragment shader.
5271 * - Finally a Compute shader linked with any other stage is a link error.
5272 */
5273 if (!prog->SeparateShader && ctx->API == API_OPENGLES2 &&
5274 num_shaders[MESA_SHADER_COMPUTE] == 0) {
5275 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
5276 linker_error(prog, "program lacks a vertex shader\n");
5277 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
5278 linker_error(prog, "program lacks a fragment shader\n");
5279 }
5280 }
5281
5282 done:
5283 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
5284 free(shader_list[i]);
5285 if (prog->_LinkedShaders[i] == NULL)
5286 continue;
5287
5288 /* Do a final validation step to make sure that the IR wasn't
5289 * invalidated by any modifications performed after intrastage linking.
5290 */
5291 validate_ir_tree(prog->_LinkedShaders[i]->ir);
5292
5293 /* Retain any live IR, but trash the rest. */
5294 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
5295
5296 /* The symbol table in the linked shaders may contain references to
5297 * variables that were removed (e.g., unused uniforms). Since it may
5298 * contain junk, there is no possible valid use. Delete it and set the
5299 * pointer to NULL.
5300 */
5301 delete prog->_LinkedShaders[i]->symbols;
5302 prog->_LinkedShaders[i]->symbols = NULL;
5303 }
5304
5305 ralloc_free(mem_ctx);
5306 }