glsl: Rename "vertex_input_slots" -> "is_vertex_input"
[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 buffer blocks and checks that all definitions of
1169 * blocks agree on their contents.
1170 */
1171 static bool
1172 interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog,
1173 bool validate_ssbo)
1174 {
1175 int *InterfaceBlockStageIndex[MESA_SHADER_STAGES];
1176 struct gl_uniform_block *blks = NULL;
1177 unsigned *num_blks = validate_ssbo ? &prog->NumShaderStorageBlocks :
1178 &prog->NumUniformBlocks;
1179
1180 unsigned max_num_buffer_blocks = 0;
1181 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1182 if (prog->_LinkedShaders[i]) {
1183 if (validate_ssbo) {
1184 max_num_buffer_blocks +=
1185 prog->_LinkedShaders[i]->NumShaderStorageBlocks;
1186 } else {
1187 max_num_buffer_blocks +=
1188 prog->_LinkedShaders[i]->NumUniformBlocks;
1189 }
1190 }
1191 }
1192
1193 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1194 struct gl_shader *sh = prog->_LinkedShaders[i];
1195
1196 InterfaceBlockStageIndex[i] = new int[max_num_buffer_blocks];
1197 for (unsigned int j = 0; j < max_num_buffer_blocks; j++)
1198 InterfaceBlockStageIndex[i][j] = -1;
1199
1200 if (sh == NULL)
1201 continue;
1202
1203 unsigned sh_num_blocks;
1204 struct gl_uniform_block **sh_blks;
1205 if (validate_ssbo) {
1206 sh_num_blocks = prog->_LinkedShaders[i]->NumShaderStorageBlocks;
1207 sh_blks = sh->ShaderStorageBlocks;
1208 } else {
1209 sh_num_blocks = prog->_LinkedShaders[i]->NumUniformBlocks;
1210 sh_blks = sh->UniformBlocks;
1211 }
1212
1213 for (unsigned int j = 0; j < sh_num_blocks; j++) {
1214 int index = link_cross_validate_uniform_block(prog, &blks, num_blks,
1215 sh_blks[j]);
1216
1217 if (index == -1) {
1218 linker_error(prog, "buffer block `%s' has mismatching "
1219 "definitions\n", sh_blks[j]->Name);
1220
1221 for (unsigned k = 0; k <= i; k++) {
1222 delete[] InterfaceBlockStageIndex[k];
1223 }
1224 return false;
1225 }
1226
1227 InterfaceBlockStageIndex[i][index] = j;
1228 }
1229 }
1230
1231 /* Update per stage block pointers to point to the program list.
1232 * FIXME: We should be able to free the per stage blocks here.
1233 */
1234 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1235 for (unsigned j = 0; j < *num_blks; j++) {
1236 int stage_index = InterfaceBlockStageIndex[i][j];
1237
1238 if (stage_index != -1) {
1239 struct gl_shader *sh = prog->_LinkedShaders[i];
1240
1241 blks[j].stageref |= (1 << i);
1242
1243 struct gl_uniform_block **sh_blks = validate_ssbo ?
1244 sh->ShaderStorageBlocks : sh->UniformBlocks;
1245
1246 sh_blks[stage_index] = &blks[j];
1247 }
1248 }
1249 }
1250
1251 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1252 delete[] InterfaceBlockStageIndex[i];
1253 }
1254
1255 if (validate_ssbo)
1256 prog->ShaderStorageBlocks = blks;
1257 else
1258 prog->UniformBlocks = blks;
1259
1260 return true;
1261 }
1262
1263
1264 /**
1265 * Populates a shaders symbol table with all global declarations
1266 */
1267 static void
1268 populate_symbol_table(gl_shader *sh)
1269 {
1270 sh->symbols = new(sh) glsl_symbol_table;
1271
1272 foreach_in_list(ir_instruction, inst, sh->ir) {
1273 ir_variable *var;
1274 ir_function *func;
1275
1276 if ((func = inst->as_function()) != NULL) {
1277 sh->symbols->add_function(func);
1278 } else if ((var = inst->as_variable()) != NULL) {
1279 if (var->data.mode != ir_var_temporary)
1280 sh->symbols->add_variable(var);
1281 }
1282 }
1283 }
1284
1285
1286 /**
1287 * Remap variables referenced in an instruction tree
1288 *
1289 * This is used when instruction trees are cloned from one shader and placed in
1290 * another. These trees will contain references to \c ir_variable nodes that
1291 * do not exist in the target shader. This function finds these \c ir_variable
1292 * references and replaces the references with matching variables in the target
1293 * shader.
1294 *
1295 * If there is no matching variable in the target shader, a clone of the
1296 * \c ir_variable is made and added to the target shader. The new variable is
1297 * added to \b both the instruction stream and the symbol table.
1298 *
1299 * \param inst IR tree that is to be processed.
1300 * \param symbols Symbol table containing global scope symbols in the
1301 * linked shader.
1302 * \param instructions Instruction stream where new variable declarations
1303 * should be added.
1304 */
1305 void
1306 remap_variables(ir_instruction *inst, struct gl_shader *target,
1307 hash_table *temps)
1308 {
1309 class remap_visitor : public ir_hierarchical_visitor {
1310 public:
1311 remap_visitor(struct gl_shader *target,
1312 hash_table *temps)
1313 {
1314 this->target = target;
1315 this->symbols = target->symbols;
1316 this->instructions = target->ir;
1317 this->temps = temps;
1318 }
1319
1320 virtual ir_visitor_status visit(ir_dereference_variable *ir)
1321 {
1322 if (ir->var->data.mode == ir_var_temporary) {
1323 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
1324
1325 assert(var != NULL);
1326 ir->var = var;
1327 return visit_continue;
1328 }
1329
1330 ir_variable *const existing =
1331 this->symbols->get_variable(ir->var->name);
1332 if (existing != NULL)
1333 ir->var = existing;
1334 else {
1335 ir_variable *copy = ir->var->clone(this->target, NULL);
1336
1337 this->symbols->add_variable(copy);
1338 this->instructions->push_head(copy);
1339 ir->var = copy;
1340 }
1341
1342 return visit_continue;
1343 }
1344
1345 private:
1346 struct gl_shader *target;
1347 glsl_symbol_table *symbols;
1348 exec_list *instructions;
1349 hash_table *temps;
1350 };
1351
1352 remap_visitor v(target, temps);
1353
1354 inst->accept(&v);
1355 }
1356
1357
1358 /**
1359 * Move non-declarations from one instruction stream to another
1360 *
1361 * The intended usage pattern of this function is to pass the pointer to the
1362 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1363 * pointer) for \c last and \c false for \c make_copies on the first
1364 * call. Successive calls pass the return value of the previous call for
1365 * \c last and \c true for \c make_copies.
1366 *
1367 * \param instructions Source instruction stream
1368 * \param last Instruction after which new instructions should be
1369 * inserted in the target instruction stream
1370 * \param make_copies Flag selecting whether instructions in \c instructions
1371 * should be copied (via \c ir_instruction::clone) into the
1372 * target list or moved.
1373 *
1374 * \return
1375 * The new "last" instruction in the target instruction stream. This pointer
1376 * is suitable for use as the \c last parameter of a later call to this
1377 * function.
1378 */
1379 exec_node *
1380 move_non_declarations(exec_list *instructions, exec_node *last,
1381 bool make_copies, gl_shader *target)
1382 {
1383 hash_table *temps = NULL;
1384
1385 if (make_copies)
1386 temps = hash_table_ctor(0, hash_table_pointer_hash,
1387 hash_table_pointer_compare);
1388
1389 foreach_in_list_safe(ir_instruction, inst, instructions) {
1390 if (inst->as_function())
1391 continue;
1392
1393 ir_variable *var = inst->as_variable();
1394 if ((var != NULL) && (var->data.mode != ir_var_temporary))
1395 continue;
1396
1397 assert(inst->as_assignment()
1398 || inst->as_call()
1399 || inst->as_if() /* for initializers with the ?: operator */
1400 || ((var != NULL) && (var->data.mode == ir_var_temporary)));
1401
1402 if (make_copies) {
1403 inst = inst->clone(target, NULL);
1404
1405 if (var != NULL)
1406 hash_table_insert(temps, inst, var);
1407 else
1408 remap_variables(inst, target, temps);
1409 } else {
1410 inst->remove();
1411 }
1412
1413 last->insert_after(inst);
1414 last = inst;
1415 }
1416
1417 if (make_copies)
1418 hash_table_dtor(temps);
1419
1420 return last;
1421 }
1422
1423
1424 /**
1425 * This class is only used in link_intrastage_shaders() below but declaring
1426 * it inside that function leads to compiler warnings with some versions of
1427 * gcc.
1428 */
1429 class array_sizing_visitor : public ir_hierarchical_visitor {
1430 public:
1431 array_sizing_visitor()
1432 : mem_ctx(ralloc_context(NULL)),
1433 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash,
1434 hash_table_pointer_compare))
1435 {
1436 }
1437
1438 ~array_sizing_visitor()
1439 {
1440 hash_table_dtor(this->unnamed_interfaces);
1441 ralloc_free(this->mem_ctx);
1442 }
1443
1444 virtual ir_visitor_status visit(ir_variable *var)
1445 {
1446 const glsl_type *type_without_array;
1447 fixup_type(&var->type, var->data.max_array_access,
1448 var->data.from_ssbo_unsized_array);
1449 type_without_array = var->type->without_array();
1450 if (var->type->is_interface()) {
1451 if (interface_contains_unsized_arrays(var->type)) {
1452 const glsl_type *new_type =
1453 resize_interface_members(var->type,
1454 var->get_max_ifc_array_access(),
1455 var->is_in_shader_storage_block());
1456 var->type = new_type;
1457 var->change_interface_type(new_type);
1458 }
1459 } else if (type_without_array->is_interface()) {
1460 if (interface_contains_unsized_arrays(type_without_array)) {
1461 const glsl_type *new_type =
1462 resize_interface_members(type_without_array,
1463 var->get_max_ifc_array_access(),
1464 var->is_in_shader_storage_block());
1465 var->change_interface_type(new_type);
1466 var->type = update_interface_members_array(var->type, new_type);
1467 }
1468 } else if (const glsl_type *ifc_type = var->get_interface_type()) {
1469 /* Store a pointer to the variable in the unnamed_interfaces
1470 * hashtable.
1471 */
1472 ir_variable **interface_vars = (ir_variable **)
1473 hash_table_find(this->unnamed_interfaces, ifc_type);
1474 if (interface_vars == NULL) {
1475 interface_vars = rzalloc_array(mem_ctx, ir_variable *,
1476 ifc_type->length);
1477 hash_table_insert(this->unnamed_interfaces, interface_vars,
1478 ifc_type);
1479 }
1480 unsigned index = ifc_type->field_index(var->name);
1481 assert(index < ifc_type->length);
1482 assert(interface_vars[index] == NULL);
1483 interface_vars[index] = var;
1484 }
1485 return visit_continue;
1486 }
1487
1488 /**
1489 * For each unnamed interface block that was discovered while running the
1490 * visitor, adjust the interface type to reflect the newly assigned array
1491 * sizes, and fix up the ir_variable nodes to point to the new interface
1492 * type.
1493 */
1494 void fixup_unnamed_interface_types()
1495 {
1496 hash_table_call_foreach(this->unnamed_interfaces,
1497 fixup_unnamed_interface_type, NULL);
1498 }
1499
1500 private:
1501 /**
1502 * If the type pointed to by \c type represents an unsized array, replace
1503 * it with a sized array whose size is determined by max_array_access.
1504 */
1505 static void fixup_type(const glsl_type **type, unsigned max_array_access,
1506 bool from_ssbo_unsized_array)
1507 {
1508 if (!from_ssbo_unsized_array && (*type)->is_unsized_array()) {
1509 *type = glsl_type::get_array_instance((*type)->fields.array,
1510 max_array_access + 1);
1511 assert(*type != NULL);
1512 }
1513 }
1514
1515 static const glsl_type *
1516 update_interface_members_array(const glsl_type *type,
1517 const glsl_type *new_interface_type)
1518 {
1519 const glsl_type *element_type = type->fields.array;
1520 if (element_type->is_array()) {
1521 const glsl_type *new_array_type =
1522 update_interface_members_array(element_type, new_interface_type);
1523 return glsl_type::get_array_instance(new_array_type, type->length);
1524 } else {
1525 return glsl_type::get_array_instance(new_interface_type,
1526 type->length);
1527 }
1528 }
1529
1530 /**
1531 * Determine whether the given interface type contains unsized arrays (if
1532 * it doesn't, array_sizing_visitor doesn't need to process it).
1533 */
1534 static bool interface_contains_unsized_arrays(const glsl_type *type)
1535 {
1536 for (unsigned i = 0; i < type->length; i++) {
1537 const glsl_type *elem_type = type->fields.structure[i].type;
1538 if (elem_type->is_unsized_array())
1539 return true;
1540 }
1541 return false;
1542 }
1543
1544 /**
1545 * Create a new interface type based on the given type, with unsized arrays
1546 * replaced by sized arrays whose size is determined by
1547 * max_ifc_array_access.
1548 */
1549 static const glsl_type *
1550 resize_interface_members(const glsl_type *type,
1551 const unsigned *max_ifc_array_access,
1552 bool is_ssbo)
1553 {
1554 unsigned num_fields = type->length;
1555 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1556 memcpy(fields, type->fields.structure,
1557 num_fields * sizeof(*fields));
1558 for (unsigned i = 0; i < num_fields; i++) {
1559 /* If SSBO last member is unsized array, we don't replace it by a sized
1560 * array.
1561 */
1562 if (is_ssbo && i == (num_fields - 1))
1563 fixup_type(&fields[i].type, max_ifc_array_access[i],
1564 true);
1565 else
1566 fixup_type(&fields[i].type, max_ifc_array_access[i],
1567 false);
1568 }
1569 glsl_interface_packing packing =
1570 (glsl_interface_packing) type->interface_packing;
1571 const glsl_type *new_ifc_type =
1572 glsl_type::get_interface_instance(fields, num_fields,
1573 packing, type->name);
1574 delete [] fields;
1575 return new_ifc_type;
1576 }
1577
1578 static void fixup_unnamed_interface_type(const void *key, void *data,
1579 void *)
1580 {
1581 const glsl_type *ifc_type = (const glsl_type *) key;
1582 ir_variable **interface_vars = (ir_variable **) data;
1583 unsigned num_fields = ifc_type->length;
1584 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1585 memcpy(fields, ifc_type->fields.structure,
1586 num_fields * sizeof(*fields));
1587 bool interface_type_changed = false;
1588 for (unsigned i = 0; i < num_fields; i++) {
1589 if (interface_vars[i] != NULL &&
1590 fields[i].type != interface_vars[i]->type) {
1591 fields[i].type = interface_vars[i]->type;
1592 interface_type_changed = true;
1593 }
1594 }
1595 if (!interface_type_changed) {
1596 delete [] fields;
1597 return;
1598 }
1599 glsl_interface_packing packing =
1600 (glsl_interface_packing) ifc_type->interface_packing;
1601 const glsl_type *new_ifc_type =
1602 glsl_type::get_interface_instance(fields, num_fields, packing,
1603 ifc_type->name);
1604 delete [] fields;
1605 for (unsigned i = 0; i < num_fields; i++) {
1606 if (interface_vars[i] != NULL)
1607 interface_vars[i]->change_interface_type(new_ifc_type);
1608 }
1609 }
1610
1611 /**
1612 * Memory context used to allocate the data in \c unnamed_interfaces.
1613 */
1614 void *mem_ctx;
1615
1616 /**
1617 * Hash table from const glsl_type * to an array of ir_variable *'s
1618 * pointing to the ir_variables constituting each unnamed interface block.
1619 */
1620 hash_table *unnamed_interfaces;
1621 };
1622
1623 /**
1624 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1625 * for later use.
1626 */
1627 static void
1628 link_xfb_stride_layout_qualifiers(struct gl_context *ctx,
1629 struct gl_shader_program *prog,
1630 struct gl_shader *linked_shader,
1631 struct gl_shader **shader_list,
1632 unsigned num_shaders)
1633 {
1634 for (unsigned i = 0; i < MAX_FEEDBACK_BUFFERS; i++) {
1635 linked_shader->TransformFeedback.BufferStride[i] = 0;
1636 }
1637
1638 for (unsigned i = 0; i < num_shaders; i++) {
1639 struct gl_shader *shader = shader_list[i];
1640
1641 for (unsigned j = 0; j < MAX_FEEDBACK_BUFFERS; j++) {
1642 if (shader->TransformFeedback.BufferStride[j]) {
1643 if (linked_shader->TransformFeedback.BufferStride[j] != 0 &&
1644 shader->TransformFeedback.BufferStride[j] != 0 &&
1645 linked_shader->TransformFeedback.BufferStride[j] !=
1646 shader->TransformFeedback.BufferStride[j]) {
1647 linker_error(prog,
1648 "intrastage shaders defined with conflicting "
1649 "xfb_stride for buffer %d (%d and %d)\n", j,
1650 linked_shader->TransformFeedback.BufferStride[j],
1651 shader->TransformFeedback.BufferStride[j]);
1652 return;
1653 }
1654
1655 if (shader->TransformFeedback.BufferStride[j])
1656 linked_shader->TransformFeedback.BufferStride[j] =
1657 shader->TransformFeedback.BufferStride[j];
1658 }
1659 }
1660 }
1661
1662 for (unsigned j = 0; j < MAX_FEEDBACK_BUFFERS; j++) {
1663 if (linked_shader->TransformFeedback.BufferStride[j]) {
1664 prog->TransformFeedback.BufferStride[j] =
1665 linked_shader->TransformFeedback.BufferStride[j];
1666
1667 /* We will validate doubles at a later stage */
1668 if (prog->TransformFeedback.BufferStride[j] % 4) {
1669 linker_error(prog, "invalid qualifier xfb_stride=%d must be a "
1670 "multiple of 4 or if its applied to a type that is "
1671 "or contains a double a multiple of 8.",
1672 prog->TransformFeedback.BufferStride[j]);
1673 return;
1674 }
1675
1676 if (prog->TransformFeedback.BufferStride[j] / 4 >
1677 ctx->Const.MaxTransformFeedbackInterleavedComponents) {
1678 linker_error(prog,
1679 "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1680 "limit has been exceeded.");
1681 return;
1682 }
1683 }
1684 }
1685 }
1686
1687 /**
1688 * Performs the cross-validation of tessellation control shader vertices and
1689 * layout qualifiers for the attached tessellation control shaders,
1690 * and propagates them to the linked TCS and linked shader program.
1691 */
1692 static void
1693 link_tcs_out_layout_qualifiers(struct gl_shader_program *prog,
1694 struct gl_shader *linked_shader,
1695 struct gl_shader **shader_list,
1696 unsigned num_shaders)
1697 {
1698 linked_shader->TessCtrl.VerticesOut = 0;
1699
1700 if (linked_shader->Stage != MESA_SHADER_TESS_CTRL)
1701 return;
1702
1703 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1704 *
1705 * "All tessellation control shader layout declarations in a program
1706 * must specify the same output patch vertex count. There must be at
1707 * least one layout qualifier specifying an output patch vertex count
1708 * in any program containing tessellation control shaders; however,
1709 * such a declaration is not required in all tessellation control
1710 * shaders."
1711 */
1712
1713 for (unsigned i = 0; i < num_shaders; i++) {
1714 struct gl_shader *shader = shader_list[i];
1715
1716 if (shader->TessCtrl.VerticesOut != 0) {
1717 if (linked_shader->TessCtrl.VerticesOut != 0 &&
1718 linked_shader->TessCtrl.VerticesOut != shader->TessCtrl.VerticesOut) {
1719 linker_error(prog, "tessellation control shader defined with "
1720 "conflicting output vertex count (%d and %d)\n",
1721 linked_shader->TessCtrl.VerticesOut,
1722 shader->TessCtrl.VerticesOut);
1723 return;
1724 }
1725 linked_shader->TessCtrl.VerticesOut = shader->TessCtrl.VerticesOut;
1726 }
1727 }
1728
1729 /* Just do the intrastage -> interstage propagation right now,
1730 * since we already know we're in the right type of shader program
1731 * for doing it.
1732 */
1733 if (linked_shader->TessCtrl.VerticesOut == 0) {
1734 linker_error(prog, "tessellation control shader didn't declare "
1735 "vertices out layout qualifier\n");
1736 return;
1737 }
1738 prog->TessCtrl.VerticesOut = linked_shader->TessCtrl.VerticesOut;
1739 }
1740
1741
1742 /**
1743 * Performs the cross-validation of tessellation evaluation shader
1744 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1745 * for the attached tessellation evaluation shaders, and propagates them
1746 * to the linked TES and linked shader program.
1747 */
1748 static void
1749 link_tes_in_layout_qualifiers(struct gl_shader_program *prog,
1750 struct gl_shader *linked_shader,
1751 struct gl_shader **shader_list,
1752 unsigned num_shaders)
1753 {
1754 linked_shader->TessEval.PrimitiveMode = PRIM_UNKNOWN;
1755 linked_shader->TessEval.Spacing = 0;
1756 linked_shader->TessEval.VertexOrder = 0;
1757 linked_shader->TessEval.PointMode = -1;
1758
1759 if (linked_shader->Stage != MESA_SHADER_TESS_EVAL)
1760 return;
1761
1762 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1763 *
1764 * "At least one tessellation evaluation shader (compilation unit) in
1765 * a program must declare a primitive mode in its input layout.
1766 * Declaration vertex spacing, ordering, and point mode identifiers is
1767 * optional. It is not required that all tessellation evaluation
1768 * shaders in a program declare a primitive mode. If spacing or
1769 * vertex ordering declarations are omitted, the tessellation
1770 * primitive generator will use equal spacing or counter-clockwise
1771 * vertex ordering, respectively. If a point mode declaration is
1772 * omitted, the tessellation primitive generator will produce lines or
1773 * triangles according to the primitive mode."
1774 */
1775
1776 for (unsigned i = 0; i < num_shaders; i++) {
1777 struct gl_shader *shader = shader_list[i];
1778
1779 if (shader->TessEval.PrimitiveMode != PRIM_UNKNOWN) {
1780 if (linked_shader->TessEval.PrimitiveMode != PRIM_UNKNOWN &&
1781 linked_shader->TessEval.PrimitiveMode != shader->TessEval.PrimitiveMode) {
1782 linker_error(prog, "tessellation evaluation shader defined with "
1783 "conflicting input primitive modes.\n");
1784 return;
1785 }
1786 linked_shader->TessEval.PrimitiveMode = shader->TessEval.PrimitiveMode;
1787 }
1788
1789 if (shader->TessEval.Spacing != 0) {
1790 if (linked_shader->TessEval.Spacing != 0 &&
1791 linked_shader->TessEval.Spacing != shader->TessEval.Spacing) {
1792 linker_error(prog, "tessellation evaluation shader defined with "
1793 "conflicting vertex spacing.\n");
1794 return;
1795 }
1796 linked_shader->TessEval.Spacing = shader->TessEval.Spacing;
1797 }
1798
1799 if (shader->TessEval.VertexOrder != 0) {
1800 if (linked_shader->TessEval.VertexOrder != 0 &&
1801 linked_shader->TessEval.VertexOrder != shader->TessEval.VertexOrder) {
1802 linker_error(prog, "tessellation evaluation shader defined with "
1803 "conflicting ordering.\n");
1804 return;
1805 }
1806 linked_shader->TessEval.VertexOrder = shader->TessEval.VertexOrder;
1807 }
1808
1809 if (shader->TessEval.PointMode != -1) {
1810 if (linked_shader->TessEval.PointMode != -1 &&
1811 linked_shader->TessEval.PointMode != shader->TessEval.PointMode) {
1812 linker_error(prog, "tessellation evaluation shader defined with "
1813 "conflicting point modes.\n");
1814 return;
1815 }
1816 linked_shader->TessEval.PointMode = shader->TessEval.PointMode;
1817 }
1818
1819 }
1820
1821 /* Just do the intrastage -> interstage propagation right now,
1822 * since we already know we're in the right type of shader program
1823 * for doing it.
1824 */
1825 if (linked_shader->TessEval.PrimitiveMode == PRIM_UNKNOWN) {
1826 linker_error(prog,
1827 "tessellation evaluation shader didn't declare input "
1828 "primitive modes.\n");
1829 return;
1830 }
1831 prog->TessEval.PrimitiveMode = linked_shader->TessEval.PrimitiveMode;
1832
1833 if (linked_shader->TessEval.Spacing == 0)
1834 linked_shader->TessEval.Spacing = GL_EQUAL;
1835 prog->TessEval.Spacing = linked_shader->TessEval.Spacing;
1836
1837 if (linked_shader->TessEval.VertexOrder == 0)
1838 linked_shader->TessEval.VertexOrder = GL_CCW;
1839 prog->TessEval.VertexOrder = linked_shader->TessEval.VertexOrder;
1840
1841 if (linked_shader->TessEval.PointMode == -1)
1842 linked_shader->TessEval.PointMode = GL_FALSE;
1843 prog->TessEval.PointMode = linked_shader->TessEval.PointMode;
1844 }
1845
1846
1847 /**
1848 * Performs the cross-validation of layout qualifiers specified in
1849 * redeclaration of gl_FragCoord for the attached fragment shaders,
1850 * and propagates them to the linked FS and linked shader program.
1851 */
1852 static void
1853 link_fs_input_layout_qualifiers(struct gl_shader_program *prog,
1854 struct gl_shader *linked_shader,
1855 struct gl_shader **shader_list,
1856 unsigned num_shaders)
1857 {
1858 linked_shader->redeclares_gl_fragcoord = false;
1859 linked_shader->uses_gl_fragcoord = false;
1860 linked_shader->origin_upper_left = false;
1861 linked_shader->pixel_center_integer = false;
1862
1863 if (linked_shader->Stage != MESA_SHADER_FRAGMENT ||
1864 (prog->Version < 150 && !prog->ARB_fragment_coord_conventions_enable))
1865 return;
1866
1867 for (unsigned i = 0; i < num_shaders; i++) {
1868 struct gl_shader *shader = shader_list[i];
1869 /* From the GLSL 1.50 spec, page 39:
1870 *
1871 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1872 * it must be redeclared in all the fragment shaders in that program
1873 * that have a static use gl_FragCoord."
1874 */
1875 if ((linked_shader->redeclares_gl_fragcoord
1876 && !shader->redeclares_gl_fragcoord
1877 && shader->uses_gl_fragcoord)
1878 || (shader->redeclares_gl_fragcoord
1879 && !linked_shader->redeclares_gl_fragcoord
1880 && linked_shader->uses_gl_fragcoord)) {
1881 linker_error(prog, "fragment shader defined with conflicting "
1882 "layout qualifiers for gl_FragCoord\n");
1883 }
1884
1885 /* From the GLSL 1.50 spec, page 39:
1886 *
1887 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1888 * single program must have the same set of qualifiers."
1889 */
1890 if (linked_shader->redeclares_gl_fragcoord && shader->redeclares_gl_fragcoord
1891 && (shader->origin_upper_left != linked_shader->origin_upper_left
1892 || shader->pixel_center_integer != linked_shader->pixel_center_integer)) {
1893 linker_error(prog, "fragment shader defined with conflicting "
1894 "layout qualifiers for gl_FragCoord\n");
1895 }
1896
1897 /* Update the linked shader state. Note that uses_gl_fragcoord should
1898 * accumulate the results. The other values should replace. If there
1899 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1900 * are already known to be the same.
1901 */
1902 if (shader->redeclares_gl_fragcoord || shader->uses_gl_fragcoord) {
1903 linked_shader->redeclares_gl_fragcoord =
1904 shader->redeclares_gl_fragcoord;
1905 linked_shader->uses_gl_fragcoord = linked_shader->uses_gl_fragcoord
1906 || shader->uses_gl_fragcoord;
1907 linked_shader->origin_upper_left = shader->origin_upper_left;
1908 linked_shader->pixel_center_integer = shader->pixel_center_integer;
1909 }
1910
1911 linked_shader->EarlyFragmentTests |= shader->EarlyFragmentTests;
1912 }
1913 }
1914
1915 /**
1916 * Performs the cross-validation of geometry shader max_vertices and
1917 * primitive type layout qualifiers for the attached geometry shaders,
1918 * and propagates them to the linked GS and linked shader program.
1919 */
1920 static void
1921 link_gs_inout_layout_qualifiers(struct gl_shader_program *prog,
1922 struct gl_shader *linked_shader,
1923 struct gl_shader **shader_list,
1924 unsigned num_shaders)
1925 {
1926 linked_shader->Geom.VerticesOut = 0;
1927 linked_shader->Geom.Invocations = 0;
1928 linked_shader->Geom.InputType = PRIM_UNKNOWN;
1929 linked_shader->Geom.OutputType = PRIM_UNKNOWN;
1930
1931 /* No in/out qualifiers defined for anything but GLSL 1.50+
1932 * geometry shaders so far.
1933 */
1934 if (linked_shader->Stage != MESA_SHADER_GEOMETRY || prog->Version < 150)
1935 return;
1936
1937 /* From the GLSL 1.50 spec, page 46:
1938 *
1939 * "All geometry shader output layout declarations in a program
1940 * must declare the same layout and same value for
1941 * max_vertices. There must be at least one geometry output
1942 * layout declaration somewhere in a program, but not all
1943 * geometry shaders (compilation units) are required to
1944 * declare it."
1945 */
1946
1947 for (unsigned i = 0; i < num_shaders; i++) {
1948 struct gl_shader *shader = shader_list[i];
1949
1950 if (shader->Geom.InputType != PRIM_UNKNOWN) {
1951 if (linked_shader->Geom.InputType != PRIM_UNKNOWN &&
1952 linked_shader->Geom.InputType != shader->Geom.InputType) {
1953 linker_error(prog, "geometry shader defined with conflicting "
1954 "input types\n");
1955 return;
1956 }
1957 linked_shader->Geom.InputType = shader->Geom.InputType;
1958 }
1959
1960 if (shader->Geom.OutputType != PRIM_UNKNOWN) {
1961 if (linked_shader->Geom.OutputType != PRIM_UNKNOWN &&
1962 linked_shader->Geom.OutputType != shader->Geom.OutputType) {
1963 linker_error(prog, "geometry shader defined with conflicting "
1964 "output types\n");
1965 return;
1966 }
1967 linked_shader->Geom.OutputType = shader->Geom.OutputType;
1968 }
1969
1970 if (shader->Geom.VerticesOut != 0) {
1971 if (linked_shader->Geom.VerticesOut != 0 &&
1972 linked_shader->Geom.VerticesOut != shader->Geom.VerticesOut) {
1973 linker_error(prog, "geometry shader defined with conflicting "
1974 "output vertex count (%d and %d)\n",
1975 linked_shader->Geom.VerticesOut,
1976 shader->Geom.VerticesOut);
1977 return;
1978 }
1979 linked_shader->Geom.VerticesOut = shader->Geom.VerticesOut;
1980 }
1981
1982 if (shader->Geom.Invocations != 0) {
1983 if (linked_shader->Geom.Invocations != 0 &&
1984 linked_shader->Geom.Invocations != shader->Geom.Invocations) {
1985 linker_error(prog, "geometry shader defined with conflicting "
1986 "invocation count (%d and %d)\n",
1987 linked_shader->Geom.Invocations,
1988 shader->Geom.Invocations);
1989 return;
1990 }
1991 linked_shader->Geom.Invocations = shader->Geom.Invocations;
1992 }
1993 }
1994
1995 /* Just do the intrastage -> interstage propagation right now,
1996 * since we already know we're in the right type of shader program
1997 * for doing it.
1998 */
1999 if (linked_shader->Geom.InputType == PRIM_UNKNOWN) {
2000 linker_error(prog,
2001 "geometry shader didn't declare primitive input type\n");
2002 return;
2003 }
2004 prog->Geom.InputType = linked_shader->Geom.InputType;
2005
2006 if (linked_shader->Geom.OutputType == PRIM_UNKNOWN) {
2007 linker_error(prog,
2008 "geometry shader didn't declare primitive output type\n");
2009 return;
2010 }
2011 prog->Geom.OutputType = linked_shader->Geom.OutputType;
2012
2013 if (linked_shader->Geom.VerticesOut == 0) {
2014 linker_error(prog,
2015 "geometry shader didn't declare max_vertices\n");
2016 return;
2017 }
2018 prog->Geom.VerticesOut = linked_shader->Geom.VerticesOut;
2019
2020 if (linked_shader->Geom.Invocations == 0)
2021 linked_shader->Geom.Invocations = 1;
2022
2023 prog->Geom.Invocations = linked_shader->Geom.Invocations;
2024 }
2025
2026
2027 /**
2028 * Perform cross-validation of compute shader local_size_{x,y,z} layout
2029 * qualifiers for the attached compute shaders, and propagate them to the
2030 * linked CS and linked shader program.
2031 */
2032 static void
2033 link_cs_input_layout_qualifiers(struct gl_shader_program *prog,
2034 struct gl_shader *linked_shader,
2035 struct gl_shader **shader_list,
2036 unsigned num_shaders)
2037 {
2038 for (int i = 0; i < 3; i++)
2039 linked_shader->Comp.LocalSize[i] = 0;
2040
2041 /* This function is called for all shader stages, but it only has an effect
2042 * for compute shaders.
2043 */
2044 if (linked_shader->Stage != MESA_SHADER_COMPUTE)
2045 return;
2046
2047 /* From the ARB_compute_shader spec, in the section describing local size
2048 * declarations:
2049 *
2050 * If multiple compute shaders attached to a single program object
2051 * declare local work-group size, the declarations must be identical;
2052 * otherwise a link-time error results. Furthermore, if a program
2053 * object contains any compute shaders, at least one must contain an
2054 * input layout qualifier specifying the local work sizes of the
2055 * program, or a link-time error will occur.
2056 */
2057 for (unsigned sh = 0; sh < num_shaders; sh++) {
2058 struct gl_shader *shader = shader_list[sh];
2059
2060 if (shader->Comp.LocalSize[0] != 0) {
2061 if (linked_shader->Comp.LocalSize[0] != 0) {
2062 for (int i = 0; i < 3; i++) {
2063 if (linked_shader->Comp.LocalSize[i] !=
2064 shader->Comp.LocalSize[i]) {
2065 linker_error(prog, "compute shader defined with conflicting "
2066 "local sizes\n");
2067 return;
2068 }
2069 }
2070 }
2071 for (int i = 0; i < 3; i++)
2072 linked_shader->Comp.LocalSize[i] = shader->Comp.LocalSize[i];
2073 }
2074 }
2075
2076 /* Just do the intrastage -> interstage propagation right now,
2077 * since we already know we're in the right type of shader program
2078 * for doing it.
2079 */
2080 if (linked_shader->Comp.LocalSize[0] == 0) {
2081 linker_error(prog, "compute shader didn't declare local size\n");
2082 return;
2083 }
2084 for (int i = 0; i < 3; i++)
2085 prog->Comp.LocalSize[i] = linked_shader->Comp.LocalSize[i];
2086 }
2087
2088
2089 /**
2090 * Combine a group of shaders for a single stage to generate a linked shader
2091 *
2092 * \note
2093 * If this function is supplied a single shader, it is cloned, and the new
2094 * shader is returned.
2095 */
2096 static struct gl_shader *
2097 link_intrastage_shaders(void *mem_ctx,
2098 struct gl_context *ctx,
2099 struct gl_shader_program *prog,
2100 struct gl_shader **shader_list,
2101 unsigned num_shaders)
2102 {
2103 struct gl_uniform_block *ubo_blocks = NULL;
2104 struct gl_uniform_block *ssbo_blocks = NULL;
2105 unsigned num_ubo_blocks = 0;
2106 unsigned num_ssbo_blocks = 0;
2107
2108 /* Check that global variables defined in multiple shaders are consistent.
2109 */
2110 cross_validate_globals(prog, shader_list, num_shaders, false);
2111 if (!prog->LinkStatus)
2112 return NULL;
2113
2114 /* Check that interface blocks defined in multiple shaders are consistent.
2115 */
2116 validate_intrastage_interface_blocks(prog, (const gl_shader **)shader_list,
2117 num_shaders);
2118 if (!prog->LinkStatus)
2119 return NULL;
2120
2121 /* Link up uniform blocks defined within this stage. */
2122 link_uniform_blocks(mem_ctx, ctx, prog, shader_list, num_shaders,
2123 &ubo_blocks, &num_ubo_blocks, &ssbo_blocks,
2124 &num_ssbo_blocks);
2125
2126 if (!prog->LinkStatus)
2127 return NULL;
2128
2129 /* Check that there is only a single definition of each function signature
2130 * across all shaders.
2131 */
2132 for (unsigned i = 0; i < (num_shaders - 1); i++) {
2133 foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
2134 ir_function *const f = node->as_function();
2135
2136 if (f == NULL)
2137 continue;
2138
2139 for (unsigned j = i + 1; j < num_shaders; j++) {
2140 ir_function *const other =
2141 shader_list[j]->symbols->get_function(f->name);
2142
2143 /* If the other shader has no function (and therefore no function
2144 * signatures) with the same name, skip to the next shader.
2145 */
2146 if (other == NULL)
2147 continue;
2148
2149 foreach_in_list(ir_function_signature, sig, &f->signatures) {
2150 if (!sig->is_defined || sig->is_builtin())
2151 continue;
2152
2153 ir_function_signature *other_sig =
2154 other->exact_matching_signature(NULL, &sig->parameters);
2155
2156 if ((other_sig != NULL) && other_sig->is_defined
2157 && !other_sig->is_builtin()) {
2158 linker_error(prog, "function `%s' is multiply defined\n",
2159 f->name);
2160 return NULL;
2161 }
2162 }
2163 }
2164 }
2165 }
2166
2167 /* Find the shader that defines main, and make a clone of it.
2168 *
2169 * Starting with the clone, search for undefined references. If one is
2170 * found, find the shader that defines it. Clone the reference and add
2171 * it to the shader. Repeat until there are no undefined references or
2172 * until a reference cannot be resolved.
2173 */
2174 gl_shader *main = NULL;
2175 for (unsigned i = 0; i < num_shaders; i++) {
2176 if (_mesa_get_main_function_signature(shader_list[i]) != NULL) {
2177 main = shader_list[i];
2178 break;
2179 }
2180 }
2181
2182 if (main == NULL) {
2183 linker_error(prog, "%s shader lacks `main'\n",
2184 _mesa_shader_stage_to_string(shader_list[0]->Stage));
2185 return NULL;
2186 }
2187
2188 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
2189 linked->ir = new(linked) exec_list;
2190 clone_ir_list(mem_ctx, linked->ir, main->ir);
2191
2192 /* Copy ubo blocks to linked shader list */
2193 linked->UniformBlocks =
2194 ralloc_array(linked, gl_uniform_block *, num_ubo_blocks);
2195 ralloc_steal(linked, ubo_blocks);
2196 for (unsigned i = 0; i < num_ubo_blocks; i++) {
2197 linked->UniformBlocks[i] = &ubo_blocks[i];
2198 }
2199 linked->NumUniformBlocks = num_ubo_blocks;
2200
2201 /* Copy ssbo blocks to linked shader list */
2202 linked->ShaderStorageBlocks =
2203 ralloc_array(linked, gl_uniform_block *, num_ssbo_blocks);
2204 ralloc_steal(linked, ssbo_blocks);
2205 for (unsigned i = 0; i < num_ssbo_blocks; i++) {
2206 linked->ShaderStorageBlocks[i] = &ssbo_blocks[i];
2207 }
2208 linked->NumShaderStorageBlocks = num_ssbo_blocks;
2209
2210 link_fs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
2211 link_tcs_out_layout_qualifiers(prog, linked, shader_list, num_shaders);
2212 link_tes_in_layout_qualifiers(prog, linked, shader_list, num_shaders);
2213 link_gs_inout_layout_qualifiers(prog, linked, shader_list, num_shaders);
2214 link_cs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
2215 link_xfb_stride_layout_qualifiers(ctx, prog, linked, shader_list,
2216 num_shaders);
2217
2218 populate_symbol_table(linked);
2219
2220 /* The pointer to the main function in the final linked shader (i.e., the
2221 * copy of the original shader that contained the main function).
2222 */
2223 ir_function_signature *const main_sig =
2224 _mesa_get_main_function_signature(linked);
2225
2226 /* Move any instructions other than variable declarations or function
2227 * declarations into main.
2228 */
2229 exec_node *insertion_point =
2230 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
2231 linked);
2232
2233 for (unsigned i = 0; i < num_shaders; i++) {
2234 if (shader_list[i] == main)
2235 continue;
2236
2237 insertion_point = move_non_declarations(shader_list[i]->ir,
2238 insertion_point, true, linked);
2239 }
2240
2241 /* Check if any shader needs built-in functions. */
2242 bool need_builtins = false;
2243 for (unsigned i = 0; i < num_shaders; i++) {
2244 if (shader_list[i]->uses_builtin_functions) {
2245 need_builtins = true;
2246 break;
2247 }
2248 }
2249
2250 bool ok;
2251 if (need_builtins) {
2252 /* Make a temporary array one larger than shader_list, which will hold
2253 * the built-in function shader as well.
2254 */
2255 gl_shader **linking_shaders = (gl_shader **)
2256 calloc(num_shaders + 1, sizeof(gl_shader *));
2257
2258 ok = linking_shaders != NULL;
2259
2260 if (ok) {
2261 memcpy(linking_shaders, shader_list, num_shaders * sizeof(gl_shader *));
2262 _mesa_glsl_initialize_builtin_functions();
2263 linking_shaders[num_shaders] = _mesa_glsl_get_builtin_function_shader();
2264
2265 ok = link_function_calls(prog, linked, linking_shaders, num_shaders + 1);
2266
2267 free(linking_shaders);
2268 } else {
2269 _mesa_error_no_memory(__func__);
2270 }
2271 } else {
2272 ok = link_function_calls(prog, linked, shader_list, num_shaders);
2273 }
2274
2275
2276 if (!ok) {
2277 _mesa_delete_shader(ctx, linked);
2278 return NULL;
2279 }
2280
2281 /* At this point linked should contain all of the linked IR, so
2282 * validate it to make sure nothing went wrong.
2283 */
2284 validate_ir_tree(linked->ir);
2285
2286 /* Set the size of geometry shader input arrays */
2287 if (linked->Stage == MESA_SHADER_GEOMETRY) {
2288 unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
2289 geom_array_resize_visitor input_resize_visitor(num_vertices, prog);
2290 foreach_in_list(ir_instruction, ir, linked->ir) {
2291 ir->accept(&input_resize_visitor);
2292 }
2293 }
2294
2295 if (ctx->Const.VertexID_is_zero_based)
2296 lower_vertex_id(linked);
2297
2298 /* Validate correct usage of barrier() in the tess control shader */
2299 if (linked->Stage == MESA_SHADER_TESS_CTRL) {
2300 barrier_use_visitor visitor(prog);
2301 foreach_in_list(ir_instruction, ir, linked->ir) {
2302 ir->accept(&visitor);
2303 }
2304 }
2305
2306 /* Make a pass over all variable declarations to ensure that arrays with
2307 * unspecified sizes have a size specified. The size is inferred from the
2308 * max_array_access field.
2309 */
2310 array_sizing_visitor v;
2311 v.run(linked->ir);
2312 v.fixup_unnamed_interface_types();
2313
2314 return linked;
2315 }
2316
2317 /**
2318 * Update the sizes of linked shader uniform arrays to the maximum
2319 * array index used.
2320 *
2321 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2322 *
2323 * If one or more elements of an array are active,
2324 * GetActiveUniform will return the name of the array in name,
2325 * subject to the restrictions listed above. The type of the array
2326 * is returned in type. The size parameter contains the highest
2327 * array element index used, plus one. The compiler or linker
2328 * determines the highest index used. There will be only one
2329 * active uniform reported by the GL per uniform array.
2330
2331 */
2332 static void
2333 update_array_sizes(struct gl_shader_program *prog)
2334 {
2335 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2336 if (prog->_LinkedShaders[i] == NULL)
2337 continue;
2338
2339 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
2340 ir_variable *const var = node->as_variable();
2341
2342 if ((var == NULL) || (var->data.mode != ir_var_uniform) ||
2343 !var->type->is_array())
2344 continue;
2345
2346 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2347 * will not be eliminated. Since we always do std140, just
2348 * don't resize arrays in UBOs.
2349 *
2350 * Atomic counters are supposed to get deterministic
2351 * locations assigned based on the declaration ordering and
2352 * sizes, array compaction would mess that up.
2353 *
2354 * Subroutine uniforms are not removed.
2355 */
2356 if (var->is_in_buffer_block() || var->type->contains_atomic() ||
2357 var->type->contains_subroutine())
2358 continue;
2359
2360 unsigned int size = var->data.max_array_access;
2361 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
2362 if (prog->_LinkedShaders[j] == NULL)
2363 continue;
2364
2365 foreach_in_list(ir_instruction, node2, prog->_LinkedShaders[j]->ir) {
2366 ir_variable *other_var = node2->as_variable();
2367 if (!other_var)
2368 continue;
2369
2370 if (strcmp(var->name, other_var->name) == 0 &&
2371 other_var->data.max_array_access > size) {
2372 size = other_var->data.max_array_access;
2373 }
2374 }
2375 }
2376
2377 if (size + 1 != var->type->length) {
2378 /* If this is a built-in uniform (i.e., it's backed by some
2379 * fixed-function state), adjust the number of state slots to
2380 * match the new array size. The number of slots per array entry
2381 * is not known. It seems safe to assume that the total number of
2382 * slots is an integer multiple of the number of array elements.
2383 * Determine the number of slots per array element by dividing by
2384 * the old (total) size.
2385 */
2386 const unsigned num_slots = var->get_num_state_slots();
2387 if (num_slots > 0) {
2388 var->set_num_state_slots((size + 1)
2389 * (num_slots / var->type->length));
2390 }
2391
2392 var->type = glsl_type::get_array_instance(var->type->fields.array,
2393 size + 1);
2394 /* FINISHME: We should update the types of array
2395 * dereferences of this variable now.
2396 */
2397 }
2398 }
2399 }
2400 }
2401
2402 /**
2403 * Resize tessellation evaluation per-vertex inputs to the size of
2404 * tessellation control per-vertex outputs.
2405 */
2406 static void
2407 resize_tes_inputs(struct gl_context *ctx,
2408 struct gl_shader_program *prog)
2409 {
2410 if (prog->_LinkedShaders[MESA_SHADER_TESS_EVAL] == NULL)
2411 return;
2412
2413 gl_shader *const tcs = prog->_LinkedShaders[MESA_SHADER_TESS_CTRL];
2414 gl_shader *const tes = prog->_LinkedShaders[MESA_SHADER_TESS_EVAL];
2415
2416 /* If no control shader is present, then the TES inputs are statically
2417 * sized to MaxPatchVertices; the actual size of the arrays won't be
2418 * known until draw time.
2419 */
2420 const int num_vertices = tcs
2421 ? tcs->TessCtrl.VerticesOut
2422 : ctx->Const.MaxPatchVertices;
2423
2424 tess_eval_array_resize_visitor input_resize_visitor(num_vertices, prog);
2425 foreach_in_list(ir_instruction, ir, tes->ir) {
2426 ir->accept(&input_resize_visitor);
2427 }
2428
2429 if (tcs) {
2430 /* Convert the gl_PatchVerticesIn system value into a constant, since
2431 * the value is known at this point.
2432 */
2433 foreach_in_list(ir_instruction, ir, tes->ir) {
2434 ir_variable *var = ir->as_variable();
2435 if (var && var->data.mode == ir_var_system_value &&
2436 var->data.location == SYSTEM_VALUE_VERTICES_IN) {
2437 void *mem_ctx = ralloc_parent(var);
2438 var->data.mode = ir_var_auto;
2439 var->data.location = 0;
2440 var->constant_value = new(mem_ctx) ir_constant(num_vertices);
2441 }
2442 }
2443 }
2444 }
2445
2446 /**
2447 * Find a contiguous set of available bits in a bitmask.
2448 *
2449 * \param used_mask Bits representing used (1) and unused (0) locations
2450 * \param needed_count Number of contiguous bits needed.
2451 *
2452 * \return
2453 * Base location of the available bits on success or -1 on failure.
2454 */
2455 int
2456 find_available_slots(unsigned used_mask, unsigned needed_count)
2457 {
2458 unsigned needed_mask = (1 << needed_count) - 1;
2459 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
2460
2461 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2462 * cannot optimize possibly infinite loops" for the loop below.
2463 */
2464 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
2465 return -1;
2466
2467 for (int i = 0; i <= max_bit_to_test; i++) {
2468 if ((needed_mask & ~used_mask) == needed_mask)
2469 return i;
2470
2471 needed_mask <<= 1;
2472 }
2473
2474 return -1;
2475 }
2476
2477
2478 /**
2479 * Assign locations for either VS inputs or FS outputs
2480 *
2481 * \param prog Shader program whose variables need locations assigned
2482 * \param constants Driver specific constant values for the program.
2483 * \param target_index Selector for the program target to receive location
2484 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2485 * \c MESA_SHADER_FRAGMENT.
2486 *
2487 * \return
2488 * If locations are successfully assigned, true is returned. Otherwise an
2489 * error is emitted to the shader link log and false is returned.
2490 */
2491 bool
2492 assign_attribute_or_color_locations(gl_shader_program *prog,
2493 struct gl_constants *constants,
2494 unsigned target_index)
2495 {
2496 /* Maximum number of generic locations. This corresponds to either the
2497 * maximum number of draw buffers or the maximum number of generic
2498 * attributes.
2499 */
2500 unsigned max_index = (target_index == MESA_SHADER_VERTEX) ?
2501 constants->Program[target_index].MaxAttribs :
2502 MAX2(constants->MaxDrawBuffers, constants->MaxDualSourceDrawBuffers);
2503
2504 /* Mark invalid locations as being used.
2505 */
2506 unsigned used_locations = (max_index >= 32)
2507 ? ~0 : ~((1 << max_index) - 1);
2508 unsigned double_storage_locations = 0;
2509
2510 assert((target_index == MESA_SHADER_VERTEX)
2511 || (target_index == MESA_SHADER_FRAGMENT));
2512
2513 gl_shader *const sh = prog->_LinkedShaders[target_index];
2514 if (sh == NULL)
2515 return true;
2516
2517 /* Operate in a total of four passes.
2518 *
2519 * 1. Invalidate the location assignments for all vertex shader inputs.
2520 *
2521 * 2. Assign locations for inputs that have user-defined (via
2522 * glBindVertexAttribLocation) locations and outputs that have
2523 * user-defined locations (via glBindFragDataLocation).
2524 *
2525 * 3. Sort the attributes without assigned locations by number of slots
2526 * required in decreasing order. Fragmentation caused by attribute
2527 * locations assigned by the application may prevent large attributes
2528 * from having enough contiguous space.
2529 *
2530 * 4. Assign locations to any inputs without assigned locations.
2531 */
2532
2533 const int generic_base = (target_index == MESA_SHADER_VERTEX)
2534 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
2535
2536 const enum ir_variable_mode direction =
2537 (target_index == MESA_SHADER_VERTEX)
2538 ? ir_var_shader_in : ir_var_shader_out;
2539
2540
2541 /* Temporary storage for the set of attributes that need locations assigned.
2542 */
2543 struct temp_attr {
2544 unsigned slots;
2545 ir_variable *var;
2546
2547 /* Used below in the call to qsort. */
2548 static int compare(const void *a, const void *b)
2549 {
2550 const temp_attr *const l = (const temp_attr *) a;
2551 const temp_attr *const r = (const temp_attr *) b;
2552
2553 /* Reversed because we want a descending order sort below. */
2554 return r->slots - l->slots;
2555 }
2556 } to_assign[32];
2557 assert(max_index <= 32);
2558
2559 unsigned num_attr = 0;
2560
2561 foreach_in_list(ir_instruction, node, sh->ir) {
2562 ir_variable *const var = node->as_variable();
2563
2564 if ((var == NULL) || (var->data.mode != (unsigned) direction))
2565 continue;
2566
2567 if (var->data.explicit_location) {
2568 var->data.is_unmatched_generic_inout = 0;
2569 if ((var->data.location >= (int)(max_index + generic_base))
2570 || (var->data.location < 0)) {
2571 linker_error(prog,
2572 "invalid explicit location %d specified for `%s'\n",
2573 (var->data.location < 0)
2574 ? var->data.location
2575 : var->data.location - generic_base,
2576 var->name);
2577 return false;
2578 }
2579 } else if (target_index == MESA_SHADER_VERTEX) {
2580 unsigned binding;
2581
2582 if (prog->AttributeBindings->get(binding, var->name)) {
2583 assert(binding >= VERT_ATTRIB_GENERIC0);
2584 var->data.location = binding;
2585 var->data.is_unmatched_generic_inout = 0;
2586 }
2587 } else if (target_index == MESA_SHADER_FRAGMENT) {
2588 unsigned binding;
2589 unsigned index;
2590
2591 if (prog->FragDataBindings->get(binding, var->name)) {
2592 assert(binding >= FRAG_RESULT_DATA0);
2593 var->data.location = binding;
2594 var->data.is_unmatched_generic_inout = 0;
2595
2596 if (prog->FragDataIndexBindings->get(index, var->name)) {
2597 var->data.index = index;
2598 }
2599 }
2600 }
2601
2602 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2603 *
2604 * "Output binding assignments will cause LinkProgram to fail:
2605 * ...
2606 * If the program has an active output assigned to a location greater
2607 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2608 * an active output assigned an index greater than or equal to one;"
2609 */
2610 if (target_index == MESA_SHADER_FRAGMENT && var->data.index >= 1 &&
2611 var->data.location - generic_base >=
2612 (int) constants->MaxDualSourceDrawBuffers) {
2613 linker_error(prog,
2614 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2615 "with index %u for %s\n",
2616 var->data.location - generic_base, var->data.index,
2617 var->name);
2618 return false;
2619 }
2620
2621 const unsigned slots = var->type->count_attribute_slots(target_index == MESA_SHADER_VERTEX);
2622
2623 /* If the variable is not a built-in and has a location statically
2624 * assigned in the shader (presumably via a layout qualifier), make sure
2625 * that it doesn't collide with other assigned locations. Otherwise,
2626 * add it to the list of variables that need linker-assigned locations.
2627 */
2628 if (var->data.location != -1) {
2629 if (var->data.location >= generic_base && var->data.index < 1) {
2630 /* From page 61 of the OpenGL 4.0 spec:
2631 *
2632 * "LinkProgram will fail if the attribute bindings assigned
2633 * by BindAttribLocation do not leave not enough space to
2634 * assign a location for an active matrix attribute or an
2635 * active attribute array, both of which require multiple
2636 * contiguous generic attributes."
2637 *
2638 * I think above text prohibits the aliasing of explicit and
2639 * automatic assignments. But, aliasing is allowed in manual
2640 * assignments of attribute locations. See below comments for
2641 * the details.
2642 *
2643 * From OpenGL 4.0 spec, page 61:
2644 *
2645 * "It is possible for an application to bind more than one
2646 * attribute name to the same location. This is referred to as
2647 * aliasing. This will only work if only one of the aliased
2648 * attributes is active in the executable program, or if no
2649 * path through the shader consumes more than one attribute of
2650 * a set of attributes aliased to the same location. A link
2651 * error can occur if the linker determines that every path
2652 * through the shader consumes multiple aliased attributes,
2653 * but implementations are not required to generate an error
2654 * in this case."
2655 *
2656 * From GLSL 4.30 spec, page 54:
2657 *
2658 * "A program will fail to link if any two non-vertex shader
2659 * input variables are assigned to the same location. For
2660 * vertex shaders, multiple input variables may be assigned
2661 * to the same location using either layout qualifiers or via
2662 * the OpenGL API. However, such aliasing is intended only to
2663 * support vertex shaders where each execution path accesses
2664 * at most one input per each location. Implementations are
2665 * permitted, but not required, to generate link-time errors
2666 * if they detect that every path through the vertex shader
2667 * executable accesses multiple inputs assigned to any single
2668 * location. For all shader types, a program will fail to link
2669 * if explicit location assignments leave the linker unable
2670 * to find space for other variables without explicit
2671 * assignments."
2672 *
2673 * From OpenGL ES 3.0 spec, page 56:
2674 *
2675 * "Binding more than one attribute name to the same location
2676 * is referred to as aliasing, and is not permitted in OpenGL
2677 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2678 * fail when this condition exists. However, aliasing is
2679 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2680 * This will only work if only one of the aliased attributes
2681 * is active in the executable program, or if no path through
2682 * the shader consumes more than one attribute of a set of
2683 * attributes aliased to the same location. A link error can
2684 * occur if the linker determines that every path through the
2685 * shader consumes multiple aliased attributes, but implemen-
2686 * tations are not required to generate an error in this case."
2687 *
2688 * After looking at above references from OpenGL, OpenGL ES and
2689 * GLSL specifications, we allow aliasing of vertex input variables
2690 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2691 *
2692 * NOTE: This is not required by the spec but its worth mentioning
2693 * here that we're not doing anything to make sure that no path
2694 * through the vertex shader executable accesses multiple inputs
2695 * assigned to any single location.
2696 */
2697
2698 /* Mask representing the contiguous slots that will be used by
2699 * this attribute.
2700 */
2701 const unsigned attr = var->data.location - generic_base;
2702 const unsigned use_mask = (1 << slots) - 1;
2703 const char *const string = (target_index == MESA_SHADER_VERTEX)
2704 ? "vertex shader input" : "fragment shader output";
2705
2706 /* Generate a link error if the requested locations for this
2707 * attribute exceed the maximum allowed attribute location.
2708 */
2709 if (attr + slots > max_index) {
2710 linker_error(prog,
2711 "insufficient contiguous locations "
2712 "available for %s `%s' %d %d %d\n", string,
2713 var->name, used_locations, use_mask, attr);
2714 return false;
2715 }
2716
2717 /* Generate a link error if the set of bits requested for this
2718 * attribute overlaps any previously allocated bits.
2719 */
2720 if ((~(use_mask << attr) & used_locations) != used_locations) {
2721 if (target_index == MESA_SHADER_FRAGMENT ||
2722 (prog->IsES && prog->Version >= 300)) {
2723 linker_error(prog,
2724 "overlapping location is assigned "
2725 "to %s `%s' %d %d %d\n", string,
2726 var->name, used_locations, use_mask, attr);
2727 return false;
2728 } else {
2729 linker_warning(prog,
2730 "overlapping location is assigned "
2731 "to %s `%s' %d %d %d\n", string,
2732 var->name, used_locations, use_mask, attr);
2733 }
2734 }
2735
2736 used_locations |= (use_mask << attr);
2737
2738 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
2739 *
2740 * "A program with more than the value of MAX_VERTEX_ATTRIBS
2741 * active attribute variables may fail to link, unless
2742 * device-dependent optimizations are able to make the program
2743 * fit within available hardware resources. For the purposes
2744 * of this test, attribute variables of the type dvec3, dvec4,
2745 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
2746 * count as consuming twice as many attributes as equivalent
2747 * single-precision types. While these types use the same number
2748 * of generic attributes as their single-precision equivalents,
2749 * implementations are permitted to consume two single-precision
2750 * vectors of internal storage for each three- or four-component
2751 * double-precision vector."
2752 *
2753 * Mark this attribute slot as taking up twice as much space
2754 * so we can count it properly against limits. According to
2755 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
2756 * is optional behavior, but it seems preferable.
2757 */
2758 if (var->type->without_array()->is_dual_slot_double())
2759 double_storage_locations |= (use_mask << attr);
2760 }
2761
2762 continue;
2763 }
2764
2765 if (num_attr >= max_index) {
2766 linker_error(prog, "too many %s (max %u)",
2767 target_index == MESA_SHADER_VERTEX ?
2768 "vertex shader inputs" : "fragment shader outputs",
2769 max_index);
2770 return false;
2771 }
2772 to_assign[num_attr].slots = slots;
2773 to_assign[num_attr].var = var;
2774 num_attr++;
2775 }
2776
2777 if (target_index == MESA_SHADER_VERTEX) {
2778 unsigned total_attribs_size =
2779 _mesa_bitcount(used_locations & ((1 << max_index) - 1)) +
2780 _mesa_bitcount(double_storage_locations);
2781 if (total_attribs_size > max_index) {
2782 linker_error(prog,
2783 "attempt to use %d vertex attribute slots only %d available ",
2784 total_attribs_size, max_index);
2785 return false;
2786 }
2787 }
2788
2789 /* If all of the attributes were assigned locations by the application (or
2790 * are built-in attributes with fixed locations), return early. This should
2791 * be the common case.
2792 */
2793 if (num_attr == 0)
2794 return true;
2795
2796 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
2797
2798 if (target_index == MESA_SHADER_VERTEX) {
2799 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2800 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2801 * reserved to prevent it from being automatically allocated below.
2802 */
2803 find_deref_visitor find("gl_Vertex");
2804 find.run(sh->ir);
2805 if (find.variable_found())
2806 used_locations |= (1 << 0);
2807 }
2808
2809 for (unsigned i = 0; i < num_attr; i++) {
2810 /* Mask representing the contiguous slots that will be used by this
2811 * attribute.
2812 */
2813 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
2814
2815 int location = find_available_slots(used_locations, to_assign[i].slots);
2816
2817 if (location < 0) {
2818 const char *const string = (target_index == MESA_SHADER_VERTEX)
2819 ? "vertex shader input" : "fragment shader output";
2820
2821 linker_error(prog,
2822 "insufficient contiguous locations "
2823 "available for %s `%s'\n",
2824 string, to_assign[i].var->name);
2825 return false;
2826 }
2827
2828 to_assign[i].var->data.location = generic_base + location;
2829 to_assign[i].var->data.is_unmatched_generic_inout = 0;
2830 used_locations |= (use_mask << location);
2831 }
2832
2833 return true;
2834 }
2835
2836 /**
2837 * Match explicit locations of outputs to inputs and deactivate the
2838 * unmatch flag if found so we don't optimise them away.
2839 */
2840 static void
2841 match_explicit_outputs_to_inputs(struct gl_shader_program *prog,
2842 gl_shader *producer,
2843 gl_shader *consumer)
2844 {
2845 glsl_symbol_table parameters;
2846 ir_variable *explicit_locations[MAX_VARYING] = { NULL };
2847
2848 /* Find all shader outputs in the "producer" stage.
2849 */
2850 foreach_in_list(ir_instruction, node, producer->ir) {
2851 ir_variable *const var = node->as_variable();
2852
2853 if ((var == NULL) || (var->data.mode != ir_var_shader_out))
2854 continue;
2855
2856 if (var->data.explicit_location &&
2857 var->data.location >= VARYING_SLOT_VAR0) {
2858 const unsigned idx = var->data.location - VARYING_SLOT_VAR0;
2859 if (explicit_locations[idx] == NULL)
2860 explicit_locations[idx] = var;
2861 }
2862 }
2863
2864 /* Match inputs to outputs */
2865 foreach_in_list(ir_instruction, node, consumer->ir) {
2866 ir_variable *const input = node->as_variable();
2867
2868 if ((input == NULL) || (input->data.mode != ir_var_shader_in))
2869 continue;
2870
2871 ir_variable *output = NULL;
2872 if (input->data.explicit_location
2873 && input->data.location >= VARYING_SLOT_VAR0) {
2874 output = explicit_locations[input->data.location - VARYING_SLOT_VAR0];
2875
2876 if (output != NULL){
2877 input->data.is_unmatched_generic_inout = 0;
2878 output->data.is_unmatched_generic_inout = 0;
2879 }
2880 }
2881 }
2882 }
2883
2884 /**
2885 * Store the gl_FragDepth layout in the gl_shader_program struct.
2886 */
2887 static void
2888 store_fragdepth_layout(struct gl_shader_program *prog)
2889 {
2890 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2891 return;
2892 }
2893
2894 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2895
2896 /* We don't look up the gl_FragDepth symbol directly because if
2897 * gl_FragDepth is not used in the shader, it's removed from the IR.
2898 * However, the symbol won't be removed from the symbol table.
2899 *
2900 * We're only interested in the cases where the variable is NOT removed
2901 * from the IR.
2902 */
2903 foreach_in_list(ir_instruction, node, ir) {
2904 ir_variable *const var = node->as_variable();
2905
2906 if (var == NULL || var->data.mode != ir_var_shader_out) {
2907 continue;
2908 }
2909
2910 if (strcmp(var->name, "gl_FragDepth") == 0) {
2911 switch (var->data.depth_layout) {
2912 case ir_depth_layout_none:
2913 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2914 return;
2915 case ir_depth_layout_any:
2916 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2917 return;
2918 case ir_depth_layout_greater:
2919 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2920 return;
2921 case ir_depth_layout_less:
2922 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2923 return;
2924 case ir_depth_layout_unchanged:
2925 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2926 return;
2927 default:
2928 assert(0);
2929 return;
2930 }
2931 }
2932 }
2933 }
2934
2935 /**
2936 * Validate the resources used by a program versus the implementation limits
2937 */
2938 static void
2939 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2940 {
2941 unsigned total_uniform_blocks = 0;
2942 unsigned total_shader_storage_blocks = 0;
2943
2944 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2945 struct gl_shader *sh = prog->_LinkedShaders[i];
2946
2947 if (sh == NULL)
2948 continue;
2949
2950 if (sh->num_samplers > ctx->Const.Program[i].MaxTextureImageUnits) {
2951 linker_error(prog, "Too many %s shader texture samplers\n",
2952 _mesa_shader_stage_to_string(i));
2953 }
2954
2955 if (sh->num_uniform_components >
2956 ctx->Const.Program[i].MaxUniformComponents) {
2957 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2958 linker_warning(prog, "Too many %s shader default uniform block "
2959 "components, but the driver will try to optimize "
2960 "them out; this is non-portable out-of-spec "
2961 "behavior\n",
2962 _mesa_shader_stage_to_string(i));
2963 } else {
2964 linker_error(prog, "Too many %s shader default uniform block "
2965 "components\n",
2966 _mesa_shader_stage_to_string(i));
2967 }
2968 }
2969
2970 if (sh->num_combined_uniform_components >
2971 ctx->Const.Program[i].MaxCombinedUniformComponents) {
2972 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2973 linker_warning(prog, "Too many %s shader uniform components, "
2974 "but the driver will try to optimize them out; "
2975 "this is non-portable out-of-spec behavior\n",
2976 _mesa_shader_stage_to_string(i));
2977 } else {
2978 linker_error(prog, "Too many %s shader uniform components\n",
2979 _mesa_shader_stage_to_string(i));
2980 }
2981 }
2982
2983 total_shader_storage_blocks += sh->NumShaderStorageBlocks;
2984 total_uniform_blocks += sh->NumUniformBlocks;
2985
2986 const unsigned max_uniform_blocks =
2987 ctx->Const.Program[i].MaxUniformBlocks;
2988 if (max_uniform_blocks < sh->NumUniformBlocks) {
2989 linker_error(prog, "Too many %s uniform blocks (%d/%d)\n",
2990 _mesa_shader_stage_to_string(i), sh->NumUniformBlocks,
2991 max_uniform_blocks);
2992 }
2993
2994 const unsigned max_shader_storage_blocks =
2995 ctx->Const.Program[i].MaxShaderStorageBlocks;
2996 if (max_shader_storage_blocks < sh->NumShaderStorageBlocks) {
2997 linker_error(prog, "Too many %s shader storage blocks (%d/%d)\n",
2998 _mesa_shader_stage_to_string(i),
2999 sh->NumShaderStorageBlocks, max_shader_storage_blocks);
3000 }
3001 }
3002
3003 if (total_uniform_blocks > ctx->Const.MaxCombinedUniformBlocks) {
3004 linker_error(prog, "Too many combined uniform blocks (%d/%d)\n",
3005 total_uniform_blocks, ctx->Const.MaxCombinedUniformBlocks);
3006 }
3007
3008 if (total_shader_storage_blocks > ctx->Const.MaxCombinedShaderStorageBlocks) {
3009 linker_error(prog, "Too many combined shader storage blocks (%d/%d)\n",
3010 total_shader_storage_blocks,
3011 ctx->Const.MaxCombinedShaderStorageBlocks);
3012 }
3013
3014 for (unsigned i = 0; i < prog->NumUniformBlocks; i++) {
3015 if (prog->UniformBlocks[i].UniformBufferSize >
3016 ctx->Const.MaxUniformBlockSize) {
3017 linker_error(prog, "Uniform block %s too big (%d/%d)\n",
3018 prog->UniformBlocks[i].Name,
3019 prog->UniformBlocks[i].UniformBufferSize,
3020 ctx->Const.MaxUniformBlockSize);
3021 }
3022 }
3023
3024 for (unsigned i = 0; i < prog->NumShaderStorageBlocks; i++) {
3025 if (prog->ShaderStorageBlocks[i].UniformBufferSize >
3026 ctx->Const.MaxShaderStorageBlockSize) {
3027 linker_error(prog, "Shader storage block %s too big (%d/%d)\n",
3028 prog->ShaderStorageBlocks[i].Name,
3029 prog->ShaderStorageBlocks[i].UniformBufferSize,
3030 ctx->Const.MaxShaderStorageBlockSize);
3031 }
3032 }
3033 }
3034
3035 static void
3036 link_calculate_subroutine_compat(struct gl_shader_program *prog)
3037 {
3038 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3039 struct gl_shader *sh = prog->_LinkedShaders[i];
3040 int count;
3041 if (!sh)
3042 continue;
3043
3044 for (unsigned j = 0; j < sh->NumSubroutineUniformRemapTable; j++) {
3045 struct gl_uniform_storage *uni = sh->SubroutineUniformRemapTable[j];
3046
3047 if (!uni)
3048 continue;
3049
3050 count = 0;
3051 for (unsigned f = 0; f < sh->NumSubroutineFunctions; f++) {
3052 struct gl_subroutine_function *fn = &sh->SubroutineFunctions[f];
3053 for (int k = 0; k < fn->num_compat_types; k++) {
3054 if (fn->types[k] == uni->type) {
3055 count++;
3056 break;
3057 }
3058 }
3059 }
3060 uni->num_compatible_subroutines = count;
3061 }
3062 }
3063 }
3064
3065 static void
3066 check_subroutine_resources(struct gl_shader_program *prog)
3067 {
3068 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3069 struct gl_shader *sh = prog->_LinkedShaders[i];
3070
3071 if (sh) {
3072 if (sh->NumSubroutineUniformRemapTable > MAX_SUBROUTINE_UNIFORM_LOCATIONS)
3073 linker_error(prog, "Too many %s shader subroutine uniforms\n",
3074 _mesa_shader_stage_to_string(i));
3075 }
3076 }
3077 }
3078 /**
3079 * Validate shader image resources.
3080 */
3081 static void
3082 check_image_resources(struct gl_context *ctx, struct gl_shader_program *prog)
3083 {
3084 unsigned total_image_units = 0;
3085 unsigned fragment_outputs = 0;
3086 unsigned total_shader_storage_blocks = 0;
3087
3088 if (!ctx->Extensions.ARB_shader_image_load_store)
3089 return;
3090
3091 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3092 struct gl_shader *sh = prog->_LinkedShaders[i];
3093
3094 if (sh) {
3095 if (sh->NumImages > ctx->Const.Program[i].MaxImageUniforms)
3096 linker_error(prog, "Too many %s shader image uniforms (%u > %u)\n",
3097 _mesa_shader_stage_to_string(i), sh->NumImages,
3098 ctx->Const.Program[i].MaxImageUniforms);
3099
3100 total_image_units += sh->NumImages;
3101 total_shader_storage_blocks += sh->NumShaderStorageBlocks;
3102
3103 if (i == MESA_SHADER_FRAGMENT) {
3104 foreach_in_list(ir_instruction, node, sh->ir) {
3105 ir_variable *var = node->as_variable();
3106 if (var && var->data.mode == ir_var_shader_out)
3107 /* since there are no double fs outputs - pass false */
3108 fragment_outputs += var->type->count_attribute_slots(false);
3109 }
3110 }
3111 }
3112 }
3113
3114 if (total_image_units > ctx->Const.MaxCombinedImageUniforms)
3115 linker_error(prog, "Too many combined image uniforms\n");
3116
3117 if (total_image_units + fragment_outputs + total_shader_storage_blocks >
3118 ctx->Const.MaxCombinedShaderOutputResources)
3119 linker_error(prog, "Too many combined image uniforms, shader storage "
3120 " buffers and fragment outputs\n");
3121 }
3122
3123
3124 /**
3125 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3126 * for a variable, checks for overlaps between other uniforms using explicit
3127 * locations.
3128 */
3129 static int
3130 reserve_explicit_locations(struct gl_shader_program *prog,
3131 string_to_uint_map *map, ir_variable *var)
3132 {
3133 unsigned slots = var->type->uniform_locations();
3134 unsigned max_loc = var->data.location + slots - 1;
3135 unsigned return_value = slots;
3136
3137 /* Resize remap table if locations do not fit in the current one. */
3138 if (max_loc + 1 > prog->NumUniformRemapTable) {
3139 prog->UniformRemapTable =
3140 reralloc(prog, prog->UniformRemapTable,
3141 gl_uniform_storage *,
3142 max_loc + 1);
3143
3144 if (!prog->UniformRemapTable) {
3145 linker_error(prog, "Out of memory during linking.\n");
3146 return -1;
3147 }
3148
3149 /* Initialize allocated space. */
3150 for (unsigned i = prog->NumUniformRemapTable; i < max_loc + 1; i++)
3151 prog->UniformRemapTable[i] = NULL;
3152
3153 prog->NumUniformRemapTable = max_loc + 1;
3154 }
3155
3156 for (unsigned i = 0; i < slots; i++) {
3157 unsigned loc = var->data.location + i;
3158
3159 /* Check if location is already used. */
3160 if (prog->UniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3161
3162 /* Possibly same uniform from a different stage, this is ok. */
3163 unsigned hash_loc;
3164 if (map->get(hash_loc, var->name) && hash_loc == loc - i) {
3165 return_value = 0;
3166 continue;
3167 }
3168
3169 /* ARB_explicit_uniform_location specification states:
3170 *
3171 * "No two default-block uniform variables in the program can have
3172 * the same location, even if they are unused, otherwise a compiler
3173 * or linker error will be generated."
3174 */
3175 linker_error(prog,
3176 "location qualifier for uniform %s overlaps "
3177 "previously used location\n",
3178 var->name);
3179 return -1;
3180 }
3181
3182 /* Initialize location as inactive before optimization
3183 * rounds and location assignment.
3184 */
3185 prog->UniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3186 }
3187
3188 /* Note, base location used for arrays. */
3189 map->put(var->data.location, var->name);
3190
3191 return return_value;
3192 }
3193
3194 static bool
3195 reserve_subroutine_explicit_locations(struct gl_shader_program *prog,
3196 struct gl_shader *sh,
3197 ir_variable *var)
3198 {
3199 unsigned slots = var->type->uniform_locations();
3200 unsigned max_loc = var->data.location + slots - 1;
3201
3202 /* Resize remap table if locations do not fit in the current one. */
3203 if (max_loc + 1 > sh->NumSubroutineUniformRemapTable) {
3204 sh->SubroutineUniformRemapTable =
3205 reralloc(sh, sh->SubroutineUniformRemapTable,
3206 gl_uniform_storage *,
3207 max_loc + 1);
3208
3209 if (!sh->SubroutineUniformRemapTable) {
3210 linker_error(prog, "Out of memory during linking.\n");
3211 return false;
3212 }
3213
3214 /* Initialize allocated space. */
3215 for (unsigned i = sh->NumSubroutineUniformRemapTable; i < max_loc + 1; i++)
3216 sh->SubroutineUniformRemapTable[i] = NULL;
3217
3218 sh->NumSubroutineUniformRemapTable = max_loc + 1;
3219 }
3220
3221 for (unsigned i = 0; i < slots; i++) {
3222 unsigned loc = var->data.location + i;
3223
3224 /* Check if location is already used. */
3225 if (sh->SubroutineUniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3226
3227 /* ARB_explicit_uniform_location specification states:
3228 * "No two subroutine uniform variables can have the same location
3229 * in the same shader stage, otherwise a compiler or linker error
3230 * will be generated."
3231 */
3232 linker_error(prog,
3233 "location qualifier for uniform %s overlaps "
3234 "previously used location\n",
3235 var->name);
3236 return false;
3237 }
3238
3239 /* Initialize location as inactive before optimization
3240 * rounds and location assignment.
3241 */
3242 sh->SubroutineUniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3243 }
3244
3245 return true;
3246 }
3247 /**
3248 * Check and reserve all explicit uniform locations, called before
3249 * any optimizations happen to handle also inactive uniforms and
3250 * inactive array elements that may get trimmed away.
3251 */
3252 static unsigned
3253 check_explicit_uniform_locations(struct gl_context *ctx,
3254 struct gl_shader_program *prog)
3255 {
3256 if (!ctx->Extensions.ARB_explicit_uniform_location)
3257 return 0;
3258
3259 /* This map is used to detect if overlapping explicit locations
3260 * occur with the same uniform (from different stage) or a different one.
3261 */
3262 string_to_uint_map *uniform_map = new string_to_uint_map;
3263
3264 if (!uniform_map) {
3265 linker_error(prog, "Out of memory during linking.\n");
3266 return 0;
3267 }
3268
3269 unsigned entries_total = 0;
3270 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3271 struct gl_shader *sh = prog->_LinkedShaders[i];
3272
3273 if (!sh)
3274 continue;
3275
3276 foreach_in_list(ir_instruction, node, sh->ir) {
3277 ir_variable *var = node->as_variable();
3278 if (!var || var->data.mode != ir_var_uniform)
3279 continue;
3280
3281 if (var->data.explicit_location) {
3282 bool ret = false;
3283 if (var->type->without_array()->is_subroutine())
3284 ret = reserve_subroutine_explicit_locations(prog, sh, var);
3285 else {
3286 int slots = reserve_explicit_locations(prog, uniform_map,
3287 var);
3288 if (slots != -1) {
3289 ret = true;
3290 entries_total += slots;
3291 }
3292 }
3293 if (!ret) {
3294 delete uniform_map;
3295 return 0;
3296 }
3297 }
3298 }
3299 }
3300
3301 struct empty_uniform_block *current_block = NULL;
3302
3303 for (unsigned i = 0; i < prog->NumUniformRemapTable; i++) {
3304 /* We found empty space in UniformRemapTable. */
3305 if (prog->UniformRemapTable[i] == NULL) {
3306 /* We've found the beginning of a new continous block of empty slots */
3307 if (!current_block || current_block->start + current_block->slots != i) {
3308 current_block = rzalloc(prog, struct empty_uniform_block);
3309 current_block->start = i;
3310 exec_list_push_tail(&prog->EmptyUniformLocations,
3311 &current_block->link);
3312 }
3313
3314 /* The current block continues, so we simply increment its slots */
3315 current_block->slots++;
3316 }
3317 }
3318
3319 delete uniform_map;
3320 return entries_total;
3321 }
3322
3323 static bool
3324 should_add_buffer_variable(struct gl_shader_program *shProg,
3325 GLenum type, const char *name)
3326 {
3327 bool found_interface = false;
3328 unsigned block_name_len = 0;
3329 const char *block_name_dot = strchr(name, '.');
3330
3331 /* These rules only apply to buffer variables. So we return
3332 * true for the rest of types.
3333 */
3334 if (type != GL_BUFFER_VARIABLE)
3335 return true;
3336
3337 for (unsigned i = 0; i < shProg->NumShaderStorageBlocks; i++) {
3338 const char *block_name = shProg->ShaderStorageBlocks[i].Name;
3339 block_name_len = strlen(block_name);
3340
3341 const char *block_square_bracket = strchr(block_name, '[');
3342 if (block_square_bracket) {
3343 /* The block is part of an array of named interfaces,
3344 * for the name comparison we ignore the "[x]" part.
3345 */
3346 block_name_len -= strlen(block_square_bracket);
3347 }
3348
3349 if (block_name_dot) {
3350 /* Check if the variable name starts with the interface
3351 * name. The interface name (if present) should have the
3352 * length than the interface block name we are comparing to.
3353 */
3354 unsigned len = strlen(name) - strlen(block_name_dot);
3355 if (len != block_name_len)
3356 continue;
3357 }
3358
3359 if (strncmp(block_name, name, block_name_len) == 0) {
3360 found_interface = true;
3361 break;
3362 }
3363 }
3364
3365 /* We remove the interface name from the buffer variable name,
3366 * including the dot that follows it.
3367 */
3368 if (found_interface)
3369 name = name + block_name_len + 1;
3370
3371 /* From: ARB_program_interface_query extension:
3372 *
3373 * "For an active shader storage block member declared as an array, an
3374 * entry will be generated only for the first array element, regardless
3375 * of its type. For arrays of aggregate types, the enumeration rules are
3376 * applied recursively for the single enumerated array element.
3377 */
3378 const char *struct_first_dot = strchr(name, '.');
3379 const char *first_square_bracket = strchr(name, '[');
3380
3381 /* The buffer variable is on top level and it is not an array */
3382 if (!first_square_bracket) {
3383 return true;
3384 /* The shader storage block member is a struct, then generate the entry */
3385 } else if (struct_first_dot && struct_first_dot < first_square_bracket) {
3386 return true;
3387 } else {
3388 /* Shader storage block member is an array, only generate an entry for the
3389 * first array element.
3390 */
3391 if (strncmp(first_square_bracket, "[0]", 3) == 0)
3392 return true;
3393 }
3394
3395 return false;
3396 }
3397
3398 static bool
3399 add_program_resource(struct gl_shader_program *prog, GLenum type,
3400 const void *data, uint8_t stages)
3401 {
3402 assert(data);
3403
3404 /* If resource already exists, do not add it again. */
3405 for (unsigned i = 0; i < prog->NumProgramResourceList; i++)
3406 if (prog->ProgramResourceList[i].Data == data)
3407 return true;
3408
3409 prog->ProgramResourceList =
3410 reralloc(prog,
3411 prog->ProgramResourceList,
3412 gl_program_resource,
3413 prog->NumProgramResourceList + 1);
3414
3415 if (!prog->ProgramResourceList) {
3416 linker_error(prog, "Out of memory during linking.\n");
3417 return false;
3418 }
3419
3420 struct gl_program_resource *res =
3421 &prog->ProgramResourceList[prog->NumProgramResourceList];
3422
3423 res->Type = type;
3424 res->Data = data;
3425 res->StageReferences = stages;
3426
3427 prog->NumProgramResourceList++;
3428
3429 return true;
3430 }
3431
3432 /* Function checks if a variable var is a packed varying and
3433 * if given name is part of packed varying's list.
3434 *
3435 * If a variable is a packed varying, it has a name like
3436 * 'packed:a,b,c' where a, b and c are separate variables.
3437 */
3438 static bool
3439 included_in_packed_varying(ir_variable *var, const char *name)
3440 {
3441 if (strncmp(var->name, "packed:", 7) != 0)
3442 return false;
3443
3444 char *list = strdup(var->name + 7);
3445 assert(list);
3446
3447 bool found = false;
3448 char *saveptr;
3449 char *token = strtok_r(list, ",", &saveptr);
3450 while (token) {
3451 if (strcmp(token, name) == 0) {
3452 found = true;
3453 break;
3454 }
3455 token = strtok_r(NULL, ",", &saveptr);
3456 }
3457 free(list);
3458 return found;
3459 }
3460
3461 /**
3462 * Function builds a stage reference bitmask from variable name.
3463 */
3464 static uint8_t
3465 build_stageref(struct gl_shader_program *shProg, const char *name,
3466 unsigned mode)
3467 {
3468 uint8_t stages = 0;
3469
3470 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3471 * used for reference mask in gl_program_resource will need to be changed.
3472 */
3473 assert(MESA_SHADER_STAGES < 8);
3474
3475 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3476 struct gl_shader *sh = shProg->_LinkedShaders[i];
3477 if (!sh)
3478 continue;
3479
3480 /* Shader symbol table may contain variables that have
3481 * been optimized away. Search IR for the variable instead.
3482 */
3483 foreach_in_list(ir_instruction, node, sh->ir) {
3484 ir_variable *var = node->as_variable();
3485 if (var) {
3486 unsigned baselen = strlen(var->name);
3487
3488 if (included_in_packed_varying(var, name)) {
3489 stages |= (1 << i);
3490 break;
3491 }
3492
3493 /* Type needs to match if specified, otherwise we might
3494 * pick a variable with same name but different interface.
3495 */
3496 if (var->data.mode != mode)
3497 continue;
3498
3499 if (strncmp(var->name, name, baselen) == 0) {
3500 /* Check for exact name matches but also check for arrays and
3501 * structs.
3502 */
3503 if (name[baselen] == '\0' ||
3504 name[baselen] == '[' ||
3505 name[baselen] == '.') {
3506 stages |= (1 << i);
3507 break;
3508 }
3509 }
3510 }
3511 }
3512 }
3513 return stages;
3514 }
3515
3516 /**
3517 * Create gl_shader_variable from ir_variable class.
3518 */
3519 static gl_shader_variable *
3520 create_shader_variable(struct gl_shader_program *shProg,
3521 const ir_variable *in,
3522 const char *name, const glsl_type *type,
3523 bool use_implicit_location, int location)
3524 {
3525 gl_shader_variable *out = ralloc(shProg, struct gl_shader_variable);
3526 if (!out)
3527 return NULL;
3528
3529 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3530 * expect to see gl_VertexID in the program resource list. Pretend.
3531 */
3532 if (in->data.mode == ir_var_system_value &&
3533 in->data.location == SYSTEM_VALUE_VERTEX_ID_ZERO_BASE) {
3534 out->name = ralloc_strdup(shProg, "gl_VertexID");
3535 } else {
3536 out->name = ralloc_strdup(shProg, name);
3537 }
3538
3539 if (!out->name)
3540 return NULL;
3541
3542 /* From the ARB_program_interface_query specification:
3543 *
3544 * "Not all active variables are assigned valid locations; the
3545 * following variables will have an effective location of -1:
3546 *
3547 * * uniforms declared as atomic counters;
3548 *
3549 * * members of a uniform block;
3550 *
3551 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3552 *
3553 * * inputs or outputs not declared with a "location" layout qualifier,
3554 * except for vertex shader inputs and fragment shader outputs."
3555 */
3556 if (in->type->base_type == GLSL_TYPE_ATOMIC_UINT ||
3557 is_gl_identifier(in->name) ||
3558 !(in->data.explicit_location || use_implicit_location)) {
3559 out->location = -1;
3560 } else {
3561 out->location = location;
3562 }
3563
3564 out->type = type;
3565 out->index = in->data.index;
3566 out->patch = in->data.patch;
3567 out->mode = in->data.mode;
3568
3569 return out;
3570 }
3571
3572 static bool
3573 add_shader_variable(struct gl_shader_program *shProg, unsigned stage_mask,
3574 GLenum programInterface, ir_variable *var,
3575 const char *name, const glsl_type *type,
3576 bool use_implicit_location, int location)
3577 {
3578 const bool is_vertex_input =
3579 programInterface == GL_PROGRAM_INPUT &&
3580 stage_mask == MESA_SHADER_VERTEX;
3581
3582 switch (type->base_type) {
3583 case GLSL_TYPE_STRUCT: {
3584 /* From the ARB_program_interface_query specification:
3585 *
3586 * "For an active variable declared as a structure, a separate entry
3587 * will be generated for each active structure member. The name of
3588 * each entry is formed by concatenating the name of the structure,
3589 * the "." character, and the name of the structure member. If a
3590 * structure member to enumerate is itself a structure or array, these
3591 * enumeration rules are applied recursively."
3592 */
3593 unsigned field_location = location;
3594 for (unsigned i = 0; i < type->length; i++) {
3595 const struct glsl_struct_field *field = &type->fields.structure[i];
3596 char *field_name = ralloc_asprintf(shProg, "%s.%s", name, field->name);
3597 if (!add_shader_variable(shProg, stage_mask, programInterface,
3598 var, field_name, field->type,
3599 use_implicit_location, field_location))
3600 return false;
3601
3602 field_location +=
3603 field->type->count_attribute_slots(is_vertex_input);
3604 }
3605 return true;
3606 }
3607
3608 default: {
3609 /* From the ARB_program_interface_query specification:
3610 *
3611 * "For an active variable declared as a single instance of a basic
3612 * type, a single entry will be generated, using the variable name
3613 * from the shader source."
3614 */
3615 gl_shader_variable *sha_v =
3616 create_shader_variable(shProg, var, name, type,
3617 use_implicit_location, location);
3618 if (!sha_v)
3619 return false;
3620
3621 return add_program_resource(shProg, programInterface, sha_v, stage_mask);
3622 }
3623 }
3624 }
3625
3626 static bool
3627 add_interface_variables(struct gl_shader_program *shProg,
3628 unsigned stage, GLenum programInterface)
3629 {
3630 exec_list *ir = shProg->_LinkedShaders[stage]->ir;
3631
3632 foreach_in_list(ir_instruction, node, ir) {
3633 ir_variable *var = node->as_variable();
3634
3635 if (!var || var->data.how_declared == ir_var_hidden)
3636 continue;
3637
3638 int loc_bias;
3639
3640 switch (var->data.mode) {
3641 case ir_var_system_value:
3642 case ir_var_shader_in:
3643 if (programInterface != GL_PROGRAM_INPUT)
3644 continue;
3645 loc_bias = (stage == MESA_SHADER_VERTEX) ? int(VERT_ATTRIB_GENERIC0)
3646 : int(VARYING_SLOT_VAR0);
3647 break;
3648 case ir_var_shader_out:
3649 if (programInterface != GL_PROGRAM_OUTPUT)
3650 continue;
3651 loc_bias = (stage == MESA_SHADER_FRAGMENT) ? int(FRAG_RESULT_DATA0)
3652 : int(VARYING_SLOT_VAR0);
3653 break;
3654 default:
3655 continue;
3656 };
3657
3658 /* Skip packed varyings, packed varyings are handled separately
3659 * by add_packed_varyings.
3660 */
3661 if (strncmp(var->name, "packed:", 7) == 0)
3662 continue;
3663
3664 /* Skip fragdata arrays, these are handled separately
3665 * by add_fragdata_arrays.
3666 */
3667 if (strncmp(var->name, "gl_out_FragData", 15) == 0)
3668 continue;
3669
3670 const bool vs_input_or_fs_output =
3671 (stage == MESA_SHADER_VERTEX && var->data.mode == ir_var_shader_in) ||
3672 (stage == MESA_SHADER_FRAGMENT && var->data.mode == ir_var_shader_out);
3673
3674 if (!add_shader_variable(shProg, 1 << stage, programInterface,
3675 var, var->name, var->type, vs_input_or_fs_output,
3676 var->data.location - loc_bias))
3677 return false;
3678 }
3679 return true;
3680 }
3681
3682 static bool
3683 add_packed_varyings(struct gl_shader_program *shProg, int stage, GLenum type)
3684 {
3685 struct gl_shader *sh = shProg->_LinkedShaders[stage];
3686 GLenum iface;
3687
3688 if (!sh || !sh->packed_varyings)
3689 return true;
3690
3691 foreach_in_list(ir_instruction, node, sh->packed_varyings) {
3692 ir_variable *var = node->as_variable();
3693 if (var) {
3694 switch (var->data.mode) {
3695 case ir_var_shader_in:
3696 iface = GL_PROGRAM_INPUT;
3697 break;
3698 case ir_var_shader_out:
3699 iface = GL_PROGRAM_OUTPUT;
3700 break;
3701 default:
3702 unreachable("unexpected type");
3703 }
3704
3705 if (type == iface) {
3706 const int stage_mask =
3707 build_stageref(shProg, var->name, var->data.mode);
3708 if (!add_shader_variable(shProg, stage_mask,
3709 iface, var, var->name, var->type, false,
3710 var->data.location - VARYING_SLOT_VAR0))
3711 return false;
3712 }
3713 }
3714 }
3715 return true;
3716 }
3717
3718 static bool
3719 add_fragdata_arrays(struct gl_shader_program *shProg)
3720 {
3721 struct gl_shader *sh = shProg->_LinkedShaders[MESA_SHADER_FRAGMENT];
3722
3723 if (!sh || !sh->fragdata_arrays)
3724 return true;
3725
3726 foreach_in_list(ir_instruction, node, sh->fragdata_arrays) {
3727 ir_variable *var = node->as_variable();
3728 if (var) {
3729 assert(var->data.mode == ir_var_shader_out);
3730
3731 if (!add_shader_variable(shProg,
3732 1 << MESA_SHADER_FRAGMENT,
3733 GL_PROGRAM_OUTPUT, var, var->name, var->type,
3734 true, var->data.location - FRAG_RESULT_DATA0))
3735 return false;
3736 }
3737 }
3738 return true;
3739 }
3740
3741 static char*
3742 get_top_level_name(const char *name)
3743 {
3744 const char *first_dot = strchr(name, '.');
3745 const char *first_square_bracket = strchr(name, '[');
3746 int name_size = 0;
3747 /* From ARB_program_interface_query spec:
3748 *
3749 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer identifying the
3750 * number of active array elements of the top-level shader storage block
3751 * member containing to the active variable is written to <params>. If the
3752 * top-level block member is not declared as an array, the value one is
3753 * written to <params>. If the top-level block member is an array with no
3754 * declared size, the value zero is written to <params>.
3755 */
3756
3757 /* The buffer variable is on top level.*/
3758 if (!first_square_bracket && !first_dot)
3759 name_size = strlen(name);
3760 else if ((!first_square_bracket ||
3761 (first_dot && first_dot < first_square_bracket)))
3762 name_size = first_dot - name;
3763 else
3764 name_size = first_square_bracket - name;
3765
3766 return strndup(name, name_size);
3767 }
3768
3769 static char*
3770 get_var_name(const char *name)
3771 {
3772 const char *first_dot = strchr(name, '.');
3773
3774 if (!first_dot)
3775 return strdup(name);
3776
3777 return strndup(first_dot+1, strlen(first_dot) - 1);
3778 }
3779
3780 static bool
3781 is_top_level_shader_storage_block_member(const char* name,
3782 const char* interface_name,
3783 const char* field_name)
3784 {
3785 bool result = false;
3786
3787 /* If the given variable is already a top-level shader storage
3788 * block member, then return array_size = 1.
3789 * We could have two possibilities: if we have an instanced
3790 * shader storage block or not instanced.
3791 *
3792 * For the first, we check create a name as it was in top level and
3793 * compare it with the real name. If they are the same, then
3794 * the variable is already at top-level.
3795 *
3796 * Full instanced name is: interface name + '.' + var name +
3797 * NULL character
3798 */
3799 int name_length = strlen(interface_name) + 1 + strlen(field_name) + 1;
3800 char *full_instanced_name = (char *) calloc(name_length, sizeof(char));
3801 if (!full_instanced_name) {
3802 fprintf(stderr, "%s: Cannot allocate space for name\n", __func__);
3803 return false;
3804 }
3805
3806 snprintf(full_instanced_name, name_length, "%s.%s",
3807 interface_name, field_name);
3808
3809 /* Check if its top-level shader storage block member of an
3810 * instanced interface block, or of a unnamed interface block.
3811 */
3812 if (strcmp(name, full_instanced_name) == 0 ||
3813 strcmp(name, field_name) == 0)
3814 result = true;
3815
3816 free(full_instanced_name);
3817 return result;
3818 }
3819
3820 static int
3821 get_array_size(struct gl_uniform_storage *uni, const glsl_struct_field *field,
3822 char *interface_name, char *var_name)
3823 {
3824 /* From GL_ARB_program_interface_query spec:
3825 *
3826 * "For the property TOP_LEVEL_ARRAY_SIZE, a single integer
3827 * identifying the number of active array elements of the top-level
3828 * shader storage block member containing to the active variable is
3829 * written to <params>. If the top-level block member is not
3830 * declared as an array, the value one is written to <params>. If
3831 * the top-level block member is an array with no declared size,
3832 * the value zero is written to <params>.
3833 */
3834 if (is_top_level_shader_storage_block_member(uni->name,
3835 interface_name,
3836 var_name))
3837 return 1;
3838 else if (field->type->is_unsized_array())
3839 return 0;
3840 else if (field->type->is_array())
3841 return field->type->length;
3842
3843 return 1;
3844 }
3845
3846 static int
3847 get_array_stride(struct gl_uniform_storage *uni, const glsl_type *interface,
3848 const glsl_struct_field *field, char *interface_name,
3849 char *var_name)
3850 {
3851 /* From GL_ARB_program_interface_query:
3852 *
3853 * "For the property TOP_LEVEL_ARRAY_STRIDE, a single integer
3854 * identifying the stride between array elements of the top-level
3855 * shader storage block member containing the active variable is
3856 * written to <params>. For top-level block members declared as
3857 * arrays, the value written is the difference, in basic machine
3858 * units, between the offsets of the active variable for
3859 * consecutive elements in the top-level array. For top-level
3860 * block members not declared as an array, zero is written to
3861 * <params>."
3862 */
3863 if (field->type->is_array()) {
3864 const enum glsl_matrix_layout matrix_layout =
3865 glsl_matrix_layout(field->matrix_layout);
3866 bool row_major = matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR;
3867 const glsl_type *array_type = field->type->fields.array;
3868
3869 if (is_top_level_shader_storage_block_member(uni->name,
3870 interface_name,
3871 var_name))
3872 return 0;
3873
3874 if (interface->interface_packing != GLSL_INTERFACE_PACKING_STD430) {
3875 if (array_type->is_record() || array_type->is_array())
3876 return glsl_align(array_type->std140_size(row_major), 16);
3877 else
3878 return MAX2(array_type->std140_base_alignment(row_major), 16);
3879 } else {
3880 return array_type->std430_array_stride(row_major);
3881 }
3882 }
3883 return 0;
3884 }
3885
3886 static void
3887 calculate_array_size_and_stride(struct gl_shader_program *shProg,
3888 struct gl_uniform_storage *uni)
3889 {
3890 int block_index = uni->block_index;
3891 int array_size = -1;
3892 int array_stride = -1;
3893 char *var_name = get_top_level_name(uni->name);
3894 char *interface_name =
3895 get_top_level_name(uni->is_shader_storage ?
3896 shProg->ShaderStorageBlocks[block_index].Name :
3897 shProg->UniformBlocks[block_index].Name);
3898
3899 if (strcmp(var_name, interface_name) == 0) {
3900 /* Deal with instanced array of SSBOs */
3901 char *temp_name = get_var_name(uni->name);
3902 if (!temp_name) {
3903 linker_error(shProg, "Out of memory during linking.\n");
3904 goto write_top_level_array_size_and_stride;
3905 }
3906 free(var_name);
3907 var_name = get_top_level_name(temp_name);
3908 free(temp_name);
3909 if (!var_name) {
3910 linker_error(shProg, "Out of memory during linking.\n");
3911 goto write_top_level_array_size_and_stride;
3912 }
3913 }
3914
3915 for (unsigned i = 0; i < shProg->NumShaders; i++) {
3916 if (shProg->Shaders[i] == NULL)
3917 continue;
3918
3919 const gl_shader *stage = shProg->Shaders[i];
3920 foreach_in_list(ir_instruction, node, stage->ir) {
3921 ir_variable *var = node->as_variable();
3922 if (!var || !var->get_interface_type() ||
3923 var->data.mode != ir_var_shader_storage)
3924 continue;
3925
3926 const glsl_type *interface = var->get_interface_type();
3927
3928 if (strcmp(interface_name, interface->name) != 0)
3929 continue;
3930
3931 for (unsigned i = 0; i < interface->length; i++) {
3932 const glsl_struct_field *field = &interface->fields.structure[i];
3933 if (strcmp(field->name, var_name) != 0)
3934 continue;
3935
3936 array_stride = get_array_stride(uni, interface, field,
3937 interface_name, var_name);
3938 array_size = get_array_size(uni, field, interface_name, var_name);
3939 goto write_top_level_array_size_and_stride;
3940 }
3941 }
3942 }
3943 write_top_level_array_size_and_stride:
3944 free(interface_name);
3945 free(var_name);
3946 uni->top_level_array_stride = array_stride;
3947 uni->top_level_array_size = array_size;
3948 }
3949
3950 /**
3951 * Builds up a list of program resources that point to existing
3952 * resource data.
3953 */
3954 void
3955 build_program_resource_list(struct gl_context *ctx,
3956 struct gl_shader_program *shProg)
3957 {
3958 /* Rebuild resource list. */
3959 if (shProg->ProgramResourceList) {
3960 ralloc_free(shProg->ProgramResourceList);
3961 shProg->ProgramResourceList = NULL;
3962 shProg->NumProgramResourceList = 0;
3963 }
3964
3965 int input_stage = MESA_SHADER_STAGES, output_stage = 0;
3966
3967 /* Determine first input and final output stage. These are used to
3968 * detect which variables should be enumerated in the resource list
3969 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
3970 */
3971 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3972 if (!shProg->_LinkedShaders[i])
3973 continue;
3974 if (input_stage == MESA_SHADER_STAGES)
3975 input_stage = i;
3976 output_stage = i;
3977 }
3978
3979 /* Empty shader, no resources. */
3980 if (input_stage == MESA_SHADER_STAGES && output_stage == 0)
3981 return;
3982
3983 /* Program interface needs to expose varyings in case of SSO. */
3984 if (shProg->SeparateShader) {
3985 if (!add_packed_varyings(shProg, input_stage, GL_PROGRAM_INPUT))
3986 return;
3987
3988 if (!add_packed_varyings(shProg, output_stage, GL_PROGRAM_OUTPUT))
3989 return;
3990 }
3991
3992 if (!add_fragdata_arrays(shProg))
3993 return;
3994
3995 /* Add inputs and outputs to the resource list. */
3996 if (!add_interface_variables(shProg, input_stage, GL_PROGRAM_INPUT))
3997 return;
3998
3999 if (!add_interface_variables(shProg, output_stage, GL_PROGRAM_OUTPUT))
4000 return;
4001
4002 /* Add transform feedback varyings. */
4003 if (shProg->LinkedTransformFeedback.NumVarying > 0) {
4004 for (int i = 0; i < shProg->LinkedTransformFeedback.NumVarying; i++) {
4005 if (!add_program_resource(shProg, GL_TRANSFORM_FEEDBACK_VARYING,
4006 &shProg->LinkedTransformFeedback.Varyings[i],
4007 0))
4008 return;
4009 }
4010 }
4011
4012 /* Add transform feedback buffers. */
4013 for (unsigned i = 0; i < ctx->Const.MaxTransformFeedbackBuffers; i++) {
4014 if ((shProg->LinkedTransformFeedback.ActiveBuffers >> i) & 1) {
4015 shProg->LinkedTransformFeedback.Buffers[i].Binding = i;
4016 if (!add_program_resource(shProg, GL_TRANSFORM_FEEDBACK_BUFFER,
4017 &shProg->LinkedTransformFeedback.Buffers[i],
4018 0))
4019 return;
4020 }
4021 }
4022
4023 /* Add uniforms from uniform storage. */
4024 for (unsigned i = 0; i < shProg->NumUniformStorage; i++) {
4025 /* Do not add uniforms internally used by Mesa. */
4026 if (shProg->UniformStorage[i].hidden)
4027 continue;
4028
4029 uint8_t stageref =
4030 build_stageref(shProg, shProg->UniformStorage[i].name,
4031 ir_var_uniform);
4032
4033 /* Add stagereferences for uniforms in a uniform block. */
4034 bool is_shader_storage = shProg->UniformStorage[i].is_shader_storage;
4035 int block_index = shProg->UniformStorage[i].block_index;
4036 if (block_index != -1) {
4037 stageref |= is_shader_storage ?
4038 shProg->ShaderStorageBlocks[block_index].stageref :
4039 shProg->UniformBlocks[block_index].stageref;
4040 }
4041
4042 GLenum type = is_shader_storage ? GL_BUFFER_VARIABLE : GL_UNIFORM;
4043 if (!should_add_buffer_variable(shProg, type,
4044 shProg->UniformStorage[i].name))
4045 continue;
4046
4047 if (is_shader_storage) {
4048 calculate_array_size_and_stride(shProg, &shProg->UniformStorage[i]);
4049 }
4050
4051 if (!add_program_resource(shProg, type,
4052 &shProg->UniformStorage[i], stageref))
4053 return;
4054 }
4055
4056 /* Add program uniform blocks. */
4057 for (unsigned i = 0; i < shProg->NumUniformBlocks; i++) {
4058 if (!add_program_resource(shProg, GL_UNIFORM_BLOCK,
4059 &shProg->UniformBlocks[i], 0))
4060 return;
4061 }
4062
4063 /* Add program shader storage blocks. */
4064 for (unsigned i = 0; i < shProg->NumShaderStorageBlocks; i++) {
4065 if (!add_program_resource(shProg, GL_SHADER_STORAGE_BLOCK,
4066 &shProg->ShaderStorageBlocks[i], 0))
4067 return;
4068 }
4069
4070 /* Add atomic counter buffers. */
4071 for (unsigned i = 0; i < shProg->NumAtomicBuffers; i++) {
4072 if (!add_program_resource(shProg, GL_ATOMIC_COUNTER_BUFFER,
4073 &shProg->AtomicBuffers[i], 0))
4074 return;
4075 }
4076
4077 for (unsigned i = 0; i < shProg->NumUniformStorage; i++) {
4078 GLenum type;
4079 if (!shProg->UniformStorage[i].hidden)
4080 continue;
4081
4082 for (int j = MESA_SHADER_VERTEX; j < MESA_SHADER_STAGES; j++) {
4083 if (!shProg->UniformStorage[i].opaque[j].active ||
4084 !shProg->UniformStorage[i].type->is_subroutine())
4085 continue;
4086
4087 type = _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage)j);
4088 /* add shader subroutines */
4089 if (!add_program_resource(shProg, type, &shProg->UniformStorage[i], 0))
4090 return;
4091 }
4092 }
4093
4094 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4095 struct gl_shader *sh = shProg->_LinkedShaders[i];
4096 GLuint type;
4097
4098 if (!sh)
4099 continue;
4100
4101 type = _mesa_shader_stage_to_subroutine((gl_shader_stage)i);
4102 for (unsigned j = 0; j < sh->NumSubroutineFunctions; j++) {
4103 if (!add_program_resource(shProg, type, &sh->SubroutineFunctions[j], 0))
4104 return;
4105 }
4106 }
4107 }
4108
4109 /**
4110 * This check is done to make sure we allow only constant expression
4111 * indexing and "constant-index-expression" (indexing with an expression
4112 * that includes loop induction variable).
4113 */
4114 static bool
4115 validate_sampler_array_indexing(struct gl_context *ctx,
4116 struct gl_shader_program *prog)
4117 {
4118 dynamic_sampler_array_indexing_visitor v;
4119 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4120 if (prog->_LinkedShaders[i] == NULL)
4121 continue;
4122
4123 bool no_dynamic_indexing =
4124 ctx->Const.ShaderCompilerOptions[i].EmitNoIndirectSampler;
4125
4126 /* Search for array derefs in shader. */
4127 v.run(prog->_LinkedShaders[i]->ir);
4128 if (v.uses_dynamic_sampler_array_indexing()) {
4129 const char *msg = "sampler arrays indexed with non-constant "
4130 "expressions is forbidden in GLSL %s %u";
4131 /* Backend has indicated that it has no dynamic indexing support. */
4132 if (no_dynamic_indexing) {
4133 linker_error(prog, msg, prog->IsES ? "ES" : "", prog->Version);
4134 return false;
4135 } else {
4136 linker_warning(prog, msg, prog->IsES ? "ES" : "", prog->Version);
4137 }
4138 }
4139 }
4140 return true;
4141 }
4142
4143 static void
4144 link_assign_subroutine_types(struct gl_shader_program *prog)
4145 {
4146 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4147 gl_shader *sh = prog->_LinkedShaders[i];
4148
4149 if (sh == NULL)
4150 continue;
4151
4152 foreach_in_list(ir_instruction, node, sh->ir) {
4153 ir_function *fn = node->as_function();
4154 if (!fn)
4155 continue;
4156
4157 if (fn->is_subroutine)
4158 sh->NumSubroutineUniformTypes++;
4159
4160 if (!fn->num_subroutine_types)
4161 continue;
4162
4163 sh->SubroutineFunctions = reralloc(sh, sh->SubroutineFunctions,
4164 struct gl_subroutine_function,
4165 sh->NumSubroutineFunctions + 1);
4166 sh->SubroutineFunctions[sh->NumSubroutineFunctions].name = ralloc_strdup(sh, fn->name);
4167 sh->SubroutineFunctions[sh->NumSubroutineFunctions].num_compat_types = fn->num_subroutine_types;
4168 sh->SubroutineFunctions[sh->NumSubroutineFunctions].types =
4169 ralloc_array(sh, const struct glsl_type *,
4170 fn->num_subroutine_types);
4171
4172 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4173 * GLSL 4.5 spec:
4174 *
4175 * "Each subroutine with an index qualifier in the shader must be
4176 * given a unique index, otherwise a compile or link error will be
4177 * generated."
4178 */
4179 for (unsigned j = 0; j < sh->NumSubroutineFunctions; j++) {
4180 if (sh->SubroutineFunctions[j].index != -1 &&
4181 sh->SubroutineFunctions[j].index == fn->subroutine_index) {
4182 linker_error(prog, "each subroutine index qualifier in the "
4183 "shader must be unique\n");
4184 return;
4185 }
4186 }
4187 sh->SubroutineFunctions[sh->NumSubroutineFunctions].index =
4188 fn->subroutine_index;
4189
4190 for (int j = 0; j < fn->num_subroutine_types; j++)
4191 sh->SubroutineFunctions[sh->NumSubroutineFunctions].types[j] = fn->subroutine_types[j];
4192 sh->NumSubroutineFunctions++;
4193 }
4194
4195 /* Assign index for subroutines without an explicit index*/
4196 int index = 0;
4197 for (unsigned j = 0; j < sh->NumSubroutineFunctions; j++) {
4198 while (sh->SubroutineFunctions[j].index == -1) {
4199 for (unsigned k = 0; k < sh->NumSubroutineFunctions; k++) {
4200 if (sh->SubroutineFunctions[k].index == index)
4201 break;
4202 else if (k == sh->NumSubroutineFunctions - 1)
4203 sh->SubroutineFunctions[j].index = index;
4204 }
4205 index++;
4206 }
4207 }
4208 }
4209 }
4210
4211 static void
4212 set_always_active_io(exec_list *ir, ir_variable_mode io_mode)
4213 {
4214 assert(io_mode == ir_var_shader_in || io_mode == ir_var_shader_out);
4215
4216 foreach_in_list(ir_instruction, node, ir) {
4217 ir_variable *const var = node->as_variable();
4218
4219 if (var == NULL || var->data.mode != io_mode)
4220 continue;
4221
4222 /* Don't set always active on builtins that haven't been redeclared */
4223 if (var->data.how_declared == ir_var_declared_implicitly)
4224 continue;
4225
4226 var->data.always_active_io = true;
4227 }
4228 }
4229
4230 /**
4231 * When separate shader programs are enabled, only input/outputs between
4232 * the stages of a multi-stage separate program can be safely removed
4233 * from the shader interface. Other inputs/outputs must remain active.
4234 */
4235 static void
4236 disable_varying_optimizations_for_sso(struct gl_shader_program *prog)
4237 {
4238 unsigned first, last;
4239 assert(prog->SeparateShader);
4240
4241 first = MESA_SHADER_STAGES;
4242 last = 0;
4243
4244 /* Determine first and last stage. Excluding the compute stage */
4245 for (unsigned i = 0; i < MESA_SHADER_COMPUTE; i++) {
4246 if (!prog->_LinkedShaders[i])
4247 continue;
4248 if (first == MESA_SHADER_STAGES)
4249 first = i;
4250 last = i;
4251 }
4252
4253 if (first == MESA_SHADER_STAGES)
4254 return;
4255
4256 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
4257 gl_shader *sh = prog->_LinkedShaders[stage];
4258 if (!sh)
4259 continue;
4260
4261 if (first == last) {
4262 /* For a single shader program only allow inputs to the vertex shader
4263 * and outputs from the fragment shader to be removed.
4264 */
4265 if (stage != MESA_SHADER_VERTEX)
4266 set_always_active_io(sh->ir, ir_var_shader_in);
4267 if (stage != MESA_SHADER_FRAGMENT)
4268 set_always_active_io(sh->ir, ir_var_shader_out);
4269 } else {
4270 /* For multi-stage separate shader programs only allow inputs and
4271 * outputs between the shader stages to be removed as well as inputs
4272 * to the vertex shader and outputs from the fragment shader.
4273 */
4274 if (stage == first && stage != MESA_SHADER_VERTEX)
4275 set_always_active_io(sh->ir, ir_var_shader_in);
4276 else if (stage == last && stage != MESA_SHADER_FRAGMENT)
4277 set_always_active_io(sh->ir, ir_var_shader_out);
4278 }
4279 }
4280 }
4281
4282 void
4283 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
4284 {
4285 prog->LinkStatus = true; /* All error paths will set this to false */
4286 prog->Validated = false;
4287 prog->_Used = false;
4288
4289 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4290 *
4291 * "Linking can fail for a variety of reasons as specified in the
4292 * OpenGL Shading Language Specification, as well as any of the
4293 * following reasons:
4294 *
4295 * - No shader objects are attached to program."
4296 *
4297 * The Compatibility Profile specification does not list the error. In
4298 * Compatibility Profile missing shader stages are replaced by
4299 * fixed-function. This applies to the case where all stages are
4300 * missing.
4301 */
4302 if (prog->NumShaders == 0) {
4303 if (ctx->API != API_OPENGL_COMPAT)
4304 linker_error(prog, "no shaders attached to the program\n");
4305 return;
4306 }
4307
4308 unsigned num_tfeedback_decls = 0;
4309 unsigned int num_explicit_uniform_locs = 0;
4310 bool has_xfb_qualifiers = false;
4311 char **varying_names = NULL;
4312 tfeedback_decl *tfeedback_decls = NULL;
4313
4314 void *mem_ctx = ralloc_context(NULL); // temporary linker context
4315
4316 prog->ARB_fragment_coord_conventions_enable = false;
4317
4318 /* Separate the shaders into groups based on their type.
4319 */
4320 struct gl_shader **shader_list[MESA_SHADER_STAGES];
4321 unsigned num_shaders[MESA_SHADER_STAGES];
4322
4323 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
4324 shader_list[i] = (struct gl_shader **)
4325 calloc(prog->NumShaders, sizeof(struct gl_shader *));
4326 num_shaders[i] = 0;
4327 }
4328
4329 unsigned min_version = UINT_MAX;
4330 unsigned max_version = 0;
4331 for (unsigned i = 0; i < prog->NumShaders; i++) {
4332 min_version = MIN2(min_version, prog->Shaders[i]->Version);
4333 max_version = MAX2(max_version, prog->Shaders[i]->Version);
4334
4335 if (prog->Shaders[i]->IsES != prog->Shaders[0]->IsES) {
4336 linker_error(prog, "all shaders must use same shading "
4337 "language version\n");
4338 goto done;
4339 }
4340
4341 if (prog->Shaders[i]->ARB_fragment_coord_conventions_enable) {
4342 prog->ARB_fragment_coord_conventions_enable = true;
4343 }
4344
4345 gl_shader_stage shader_type = prog->Shaders[i]->Stage;
4346 shader_list[shader_type][num_shaders[shader_type]] = prog->Shaders[i];
4347 num_shaders[shader_type]++;
4348 }
4349
4350 /* In desktop GLSL, different shader versions may be linked together. In
4351 * GLSL ES, all shader versions must be the same.
4352 */
4353 if (prog->Shaders[0]->IsES && min_version != max_version) {
4354 linker_error(prog, "all shaders must use same shading "
4355 "language version\n");
4356 goto done;
4357 }
4358
4359 prog->Version = max_version;
4360 prog->IsES = prog->Shaders[0]->IsES;
4361
4362 /* Some shaders have to be linked with some other shaders present.
4363 */
4364 if (!prog->SeparateShader) {
4365 if (num_shaders[MESA_SHADER_GEOMETRY] > 0 &&
4366 num_shaders[MESA_SHADER_VERTEX] == 0) {
4367 linker_error(prog, "Geometry shader must be linked with "
4368 "vertex shader\n");
4369 goto done;
4370 }
4371 if (num_shaders[MESA_SHADER_TESS_EVAL] > 0 &&
4372 num_shaders[MESA_SHADER_VERTEX] == 0) {
4373 linker_error(prog, "Tessellation evaluation shader must be linked "
4374 "with vertex shader\n");
4375 goto done;
4376 }
4377 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
4378 num_shaders[MESA_SHADER_VERTEX] == 0) {
4379 linker_error(prog, "Tessellation control shader must be linked with "
4380 "vertex shader\n");
4381 goto done;
4382 }
4383
4384 /* The spec is self-contradictory here. It allows linking without a tess
4385 * eval shader, but that can only be used with transform feedback and
4386 * rasterization disabled. However, transform feedback isn't allowed
4387 * with GL_PATCHES, so it can't be used.
4388 *
4389 * More investigation showed that the idea of transform feedback after
4390 * a tess control shader was dropped, because some hw vendors couldn't
4391 * support tessellation without a tess eval shader, but the linker
4392 * section wasn't updated to reflect that.
4393 *
4394 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4395 * spec bug.
4396 *
4397 * Do what's reasonable and always require a tess eval shader if a tess
4398 * control shader is present.
4399 */
4400 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
4401 num_shaders[MESA_SHADER_TESS_EVAL] == 0) {
4402 linker_error(prog, "Tessellation control shader must be linked with "
4403 "tessellation evaluation shader\n");
4404 goto done;
4405 }
4406 }
4407
4408 /* Compute shaders have additional restrictions. */
4409 if (num_shaders[MESA_SHADER_COMPUTE] > 0 &&
4410 num_shaders[MESA_SHADER_COMPUTE] != prog->NumShaders) {
4411 linker_error(prog, "Compute shaders may not be linked with any other "
4412 "type of shader\n");
4413 }
4414
4415 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
4416 if (prog->_LinkedShaders[i] != NULL)
4417 _mesa_delete_shader(ctx, prog->_LinkedShaders[i]);
4418
4419 prog->_LinkedShaders[i] = NULL;
4420 }
4421
4422 /* Link all shaders for a particular stage and validate the result.
4423 */
4424 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
4425 if (num_shaders[stage] > 0) {
4426 gl_shader *const sh =
4427 link_intrastage_shaders(mem_ctx, ctx, prog, shader_list[stage],
4428 num_shaders[stage]);
4429
4430 if (!prog->LinkStatus) {
4431 if (sh)
4432 _mesa_delete_shader(ctx, sh);
4433 goto done;
4434 }
4435
4436 switch (stage) {
4437 case MESA_SHADER_VERTEX:
4438 validate_vertex_shader_executable(prog, sh);
4439 break;
4440 case MESA_SHADER_TESS_CTRL:
4441 /* nothing to be done */
4442 break;
4443 case MESA_SHADER_TESS_EVAL:
4444 validate_tess_eval_shader_executable(prog, sh);
4445 break;
4446 case MESA_SHADER_GEOMETRY:
4447 validate_geometry_shader_executable(prog, sh);
4448 break;
4449 case MESA_SHADER_FRAGMENT:
4450 validate_fragment_shader_executable(prog, sh);
4451 break;
4452 }
4453 if (!prog->LinkStatus) {
4454 if (sh)
4455 _mesa_delete_shader(ctx, sh);
4456 goto done;
4457 }
4458
4459 _mesa_reference_shader(ctx, &prog->_LinkedShaders[stage], sh);
4460 }
4461 }
4462
4463 if (num_shaders[MESA_SHADER_GEOMETRY] > 0)
4464 prog->LastClipDistanceArraySize = prog->Geom.ClipDistanceArraySize;
4465 else if (num_shaders[MESA_SHADER_TESS_EVAL] > 0)
4466 prog->LastClipDistanceArraySize = prog->TessEval.ClipDistanceArraySize;
4467 else if (num_shaders[MESA_SHADER_VERTEX] > 0)
4468 prog->LastClipDistanceArraySize = prog->Vert.ClipDistanceArraySize;
4469 else
4470 prog->LastClipDistanceArraySize = 0; /* Not used */
4471
4472 /* Here begins the inter-stage linking phase. Some initial validation is
4473 * performed, then locations are assigned for uniforms, attributes, and
4474 * varyings.
4475 */
4476 cross_validate_uniforms(prog);
4477 if (!prog->LinkStatus)
4478 goto done;
4479
4480 unsigned first, last, prev;
4481
4482 first = MESA_SHADER_STAGES;
4483 last = 0;
4484
4485 /* Determine first and last stage. */
4486 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4487 if (!prog->_LinkedShaders[i])
4488 continue;
4489 if (first == MESA_SHADER_STAGES)
4490 first = i;
4491 last = i;
4492 }
4493
4494 num_explicit_uniform_locs = check_explicit_uniform_locations(ctx, prog);
4495 link_assign_subroutine_types(prog);
4496
4497 if (!prog->LinkStatus)
4498 goto done;
4499
4500 resize_tes_inputs(ctx, prog);
4501
4502 /* Validate the inputs of each stage with the output of the preceding
4503 * stage.
4504 */
4505 prev = first;
4506 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
4507 if (prog->_LinkedShaders[i] == NULL)
4508 continue;
4509
4510 validate_interstage_inout_blocks(prog, prog->_LinkedShaders[prev],
4511 prog->_LinkedShaders[i]);
4512 if (!prog->LinkStatus)
4513 goto done;
4514
4515 cross_validate_outputs_to_inputs(prog,
4516 prog->_LinkedShaders[prev],
4517 prog->_LinkedShaders[i]);
4518 if (!prog->LinkStatus)
4519 goto done;
4520
4521 prev = i;
4522 }
4523
4524 /* Cross-validate uniform blocks between shader stages */
4525 validate_interstage_uniform_blocks(prog, prog->_LinkedShaders,
4526 MESA_SHADER_STAGES);
4527 if (!prog->LinkStatus)
4528 goto done;
4529
4530 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
4531 if (prog->_LinkedShaders[i] != NULL)
4532 lower_named_interface_blocks(mem_ctx, prog->_LinkedShaders[i]);
4533 }
4534
4535 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4536 * it before optimization because we want most of the checks to get
4537 * dropped thanks to constant propagation.
4538 *
4539 * This rule also applies to GLSL ES 3.00.
4540 */
4541 if (max_version >= (prog->IsES ? 300 : 130)) {
4542 struct gl_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
4543 if (sh) {
4544 lower_discard_flow(sh->ir);
4545 }
4546 }
4547
4548 if (prog->SeparateShader)
4549 disable_varying_optimizations_for_sso(prog);
4550
4551 /* Process UBOs */
4552 if (!interstage_cross_validate_uniform_blocks(prog, false))
4553 goto done;
4554
4555 /* Process SSBOs */
4556 if (!interstage_cross_validate_uniform_blocks(prog, true))
4557 goto done;
4558
4559 /* Do common optimization before assigning storage for attributes,
4560 * uniforms, and varyings. Later optimization could possibly make
4561 * some of that unused.
4562 */
4563 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4564 if (prog->_LinkedShaders[i] == NULL)
4565 continue;
4566
4567 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
4568 if (!prog->LinkStatus)
4569 goto done;
4570
4571 if (ctx->Const.ShaderCompilerOptions[i].LowerClipDistance) {
4572 lower_clip_distance(prog->_LinkedShaders[i]);
4573 }
4574
4575 if (ctx->Const.LowerTessLevel) {
4576 lower_tess_level(prog->_LinkedShaders[i]);
4577 }
4578
4579 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false,
4580 &ctx->Const.ShaderCompilerOptions[i],
4581 ctx->Const.NativeIntegers))
4582 ;
4583
4584 lower_const_arrays_to_uniforms(prog->_LinkedShaders[i]->ir);
4585 }
4586
4587 /* Validation for special cases where we allow sampler array indexing
4588 * with loop induction variable. This check emits a warning or error
4589 * depending if backend can handle dynamic indexing.
4590 */
4591 if ((!prog->IsES && prog->Version < 130) ||
4592 (prog->IsES && prog->Version < 300)) {
4593 if (!validate_sampler_array_indexing(ctx, prog))
4594 goto done;
4595 }
4596
4597 /* Check and validate stream emissions in geometry shaders */
4598 validate_geometry_shader_emissions(ctx, prog);
4599
4600 /* Mark all generic shader inputs and outputs as unpaired. */
4601 for (unsigned i = MESA_SHADER_VERTEX; i <= MESA_SHADER_FRAGMENT; i++) {
4602 if (prog->_LinkedShaders[i] != NULL) {
4603 link_invalidate_variable_locations(prog->_LinkedShaders[i]->ir);
4604 }
4605 }
4606
4607 prev = first;
4608 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
4609 if (prog->_LinkedShaders[i] == NULL)
4610 continue;
4611
4612 match_explicit_outputs_to_inputs(prog, prog->_LinkedShaders[prev],
4613 prog->_LinkedShaders[i]);
4614 prev = i;
4615 }
4616
4617 if (!assign_attribute_or_color_locations(prog, &ctx->Const,
4618 MESA_SHADER_VERTEX)) {
4619 goto done;
4620 }
4621
4622 if (!assign_attribute_or_color_locations(prog, &ctx->Const,
4623 MESA_SHADER_FRAGMENT)) {
4624 goto done;
4625 }
4626
4627 /* From the ARB_enhanced_layouts spec:
4628 *
4629 * "If the shader used to record output variables for transform feedback
4630 * varyings uses the "xfb_buffer", "xfb_offset", or "xfb_stride" layout
4631 * qualifiers, the values specified by TransformFeedbackVaryings are
4632 * ignored, and the set of variables captured for transform feedback is
4633 * instead derived from the specified layout qualifiers."
4634 */
4635 for (int i = MESA_SHADER_FRAGMENT - 1; i >= 0; i--) {
4636 /* Find last stage before fragment shader */
4637 if (prog->_LinkedShaders[i]) {
4638 has_xfb_qualifiers =
4639 process_xfb_layout_qualifiers(mem_ctx, prog->_LinkedShaders[i],
4640 &num_tfeedback_decls,
4641 &varying_names);
4642 break;
4643 }
4644 }
4645
4646 if (!has_xfb_qualifiers) {
4647 num_tfeedback_decls = prog->TransformFeedback.NumVarying;
4648 varying_names = prog->TransformFeedback.VaryingNames;
4649 }
4650
4651 if (num_tfeedback_decls != 0) {
4652 /* From GL_EXT_transform_feedback:
4653 * A program will fail to link if:
4654 *
4655 * * the <count> specified by TransformFeedbackVaryingsEXT is
4656 * non-zero, but the program object has no vertex or geometry
4657 * shader;
4658 */
4659 if (first >= MESA_SHADER_FRAGMENT) {
4660 linker_error(prog, "Transform feedback varyings specified, but "
4661 "no vertex, tessellation, or geometry shader is "
4662 "present.\n");
4663 goto done;
4664 }
4665
4666 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
4667 num_tfeedback_decls);
4668 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
4669 varying_names, tfeedback_decls))
4670 goto done;
4671 }
4672
4673 /* If there is no fragment shader we need to set transform feedback.
4674 *
4675 * For SSO we need also need to assign output locations, we assign them
4676 * here because we need to do it for both single stage programs and multi
4677 * stage programs.
4678 */
4679 if (last < MESA_SHADER_FRAGMENT &&
4680 (num_tfeedback_decls != 0 || prog->SeparateShader)) {
4681 if (!assign_varying_locations(ctx, mem_ctx, prog,
4682 prog->_LinkedShaders[last], NULL,
4683 num_tfeedback_decls, tfeedback_decls))
4684 goto done;
4685 }
4686
4687 if (last <= MESA_SHADER_FRAGMENT) {
4688 /* Remove unused varyings from the first/last stage unless SSO */
4689 remove_unused_shader_inputs_and_outputs(prog->SeparateShader,
4690 prog->_LinkedShaders[first],
4691 ir_var_shader_in);
4692 remove_unused_shader_inputs_and_outputs(prog->SeparateShader,
4693 prog->_LinkedShaders[last],
4694 ir_var_shader_out);
4695
4696 /* If the program is made up of only a single stage */
4697 if (first == last) {
4698
4699 gl_shader *const sh = prog->_LinkedShaders[last];
4700 if (prog->SeparateShader) {
4701 /* Assign input locations for SSO, output locations are already
4702 * assigned.
4703 */
4704 if (!assign_varying_locations(ctx, mem_ctx, prog,
4705 NULL /* producer */,
4706 sh /* consumer */,
4707 0 /* num_tfeedback_decls */,
4708 NULL /* tfeedback_decls */))
4709 goto done;
4710 }
4711
4712 do_dead_builtin_varyings(ctx, NULL, sh, 0, NULL);
4713 do_dead_builtin_varyings(ctx, sh, NULL, num_tfeedback_decls,
4714 tfeedback_decls);
4715 } else {
4716 /* Linking the stages in the opposite order (from fragment to vertex)
4717 * ensures that inter-shader outputs written to in an earlier stage
4718 * are eliminated if they are (transitively) not used in a later
4719 * stage.
4720 */
4721 int next = last;
4722 for (int i = next - 1; i >= 0; i--) {
4723 if (prog->_LinkedShaders[i] == NULL)
4724 continue;
4725
4726 gl_shader *const sh_i = prog->_LinkedShaders[i];
4727 gl_shader *const sh_next = prog->_LinkedShaders[next];
4728
4729 if (!assign_varying_locations(ctx, mem_ctx, prog, sh_i, sh_next,
4730 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
4731 tfeedback_decls))
4732 goto done;
4733
4734 do_dead_builtin_varyings(ctx, sh_i, sh_next,
4735 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
4736 tfeedback_decls);
4737
4738 /* This must be done after all dead varyings are eliminated. */
4739 if (!check_against_output_limit(ctx, prog, sh_i))
4740 goto done;
4741 if (!check_against_input_limit(ctx, prog, sh_next))
4742 goto done;
4743
4744 next = i;
4745 }
4746 }
4747 }
4748
4749 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls,
4750 has_xfb_qualifiers))
4751 goto done;
4752
4753 update_array_sizes(prog);
4754 link_assign_uniform_locations(prog, ctx->Const.UniformBooleanTrue,
4755 num_explicit_uniform_locs,
4756 ctx->Const.MaxUserAssignableUniformLocations);
4757 link_assign_atomic_counter_resources(ctx, prog);
4758 store_fragdepth_layout(prog);
4759
4760 link_calculate_subroutine_compat(prog);
4761 check_resources(ctx, prog);
4762 check_subroutine_resources(prog);
4763 check_image_resources(ctx, prog);
4764 link_check_atomic_counter_resources(ctx, prog);
4765
4766 if (!prog->LinkStatus)
4767 goto done;
4768
4769 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
4770 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
4771 * anything about shader linking when one of the shaders (vertex or
4772 * fragment shader) is absent. So, the extension shouldn't change the
4773 * behavior specified in GLSL specification.
4774 *
4775 * From OpenGL ES 3.1 specification (7.3 Program Objects):
4776 * "Linking can fail for a variety of reasons as specified in the
4777 * OpenGL ES Shading Language Specification, as well as any of the
4778 * following reasons:
4779 *
4780 * ...
4781 *
4782 * * program contains objects to form either a vertex shader or
4783 * fragment shader, and program is not separable, and does not
4784 * contain objects to form both a vertex shader and fragment
4785 * shader."
4786 *
4787 * However, the only scenario in 3.1+ where we don't require them both is
4788 * when we have a compute shader. For example:
4789 *
4790 * - No shaders is a link error.
4791 * - Geom or Tess without a Vertex shader is a link error which means we
4792 * always require a Vertex shader and hence a Fragment shader.
4793 * - Finally a Compute shader linked with any other stage is a link error.
4794 */
4795 if (!prog->SeparateShader && ctx->API == API_OPENGLES2 &&
4796 num_shaders[MESA_SHADER_COMPUTE] == 0) {
4797 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
4798 linker_error(prog, "program lacks a vertex shader\n");
4799 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
4800 linker_error(prog, "program lacks a fragment shader\n");
4801 }
4802 }
4803
4804 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4805 if (prog->_LinkedShaders[i] == NULL)
4806 continue;
4807
4808 if (ctx->Const.ShaderCompilerOptions[i].LowerBufferInterfaceBlocks)
4809 lower_ubo_reference(prog->_LinkedShaders[i]);
4810
4811 if (ctx->Const.ShaderCompilerOptions[i].LowerShaderSharedVariables)
4812 lower_shared_reference(prog->_LinkedShaders[i],
4813 &prog->Comp.SharedSize);
4814
4815 lower_vector_derefs(prog->_LinkedShaders[i]);
4816 }
4817
4818 done:
4819 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4820 free(shader_list[i]);
4821 if (prog->_LinkedShaders[i] == NULL)
4822 continue;
4823
4824 /* Do a final validation step to make sure that the IR wasn't
4825 * invalidated by any modifications performed after intrastage linking.
4826 */
4827 validate_ir_tree(prog->_LinkedShaders[i]->ir);
4828
4829 /* Retain any live IR, but trash the rest. */
4830 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
4831
4832 /* The symbol table in the linked shaders may contain references to
4833 * variables that were removed (e.g., unused uniforms). Since it may
4834 * contain junk, there is no possible valid use. Delete it and set the
4835 * pointer to NULL.
4836 */
4837 delete prog->_LinkedShaders[i]->symbols;
4838 prog->_LinkedShaders[i]->symbols = NULL;
4839 }
4840
4841 ralloc_free(mem_ctx);
4842 }