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