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