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