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