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