glsl: validate restrictions on use of barrier()
[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 *ir)
321 {
322 in_main = false;
323 after_return = false;
324 return visit_continue;
325 }
326
327 virtual ir_visitor_status visit_leave(ir_return *ir)
328 {
329 after_return = true;
330 return visit_continue;
331 }
332
333 virtual ir_visitor_status visit_enter(ir_if *ir)
334 {
335 ++control_flow;
336 return visit_continue;
337 }
338
339 virtual ir_visitor_status visit_leave(ir_if *ir)
340 {
341 --control_flow;
342 return visit_continue;
343 }
344
345 virtual ir_visitor_status visit_enter(ir_loop *ir)
346 {
347 ++control_flow;
348 return visit_continue;
349 }
350
351 virtual ir_visitor_status visit_leave(ir_loop *ir)
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 (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 linker_error(prog, "%s `%s' declared as type "
897 "`%s' but outermost dimension has an index"
898 " of `%i'\n",
899 mode_string(var),
900 var->name, existing->type->name,
901 var->data.max_array_access);
902 }
903 return true;
904 }
905 }
906 return false;
907 }
908
909
910 /**
911 * Perform validation of global variables used across multiple shaders
912 */
913 void
914 cross_validate_globals(struct gl_shader_program *prog,
915 struct gl_shader **shader_list,
916 unsigned num_shaders,
917 bool uniforms_only)
918 {
919 /* Examine all of the uniforms in all of the shaders and cross validate
920 * them.
921 */
922 glsl_symbol_table variables;
923 for (unsigned i = 0; i < num_shaders; i++) {
924 if (shader_list[i] == NULL)
925 continue;
926
927 foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
928 ir_variable *const var = node->as_variable();
929
930 if (var == NULL)
931 continue;
932
933 if (uniforms_only && (var->data.mode != ir_var_uniform && var->data.mode != ir_var_shader_storage))
934 continue;
935
936 /* Don't cross validate temporaries that are at global scope. These
937 * will eventually get pulled into the shaders 'main'.
938 */
939 if (var->data.mode == ir_var_temporary)
940 continue;
941
942 /* If a global with this name has already been seen, verify that the
943 * new instance has the same type. In addition, if the globals have
944 * initializers, the values of the initializers must be the same.
945 */
946 ir_variable *const existing = variables.get_variable(var->name);
947 if (existing != NULL) {
948 /* Check if types match. Interface blocks have some special
949 * rules so we handle those elsewhere.
950 */
951 if (var->type != existing->type &&
952 !var->is_interface_instance()) {
953 if (!validate_intrastage_arrays(prog, var, existing)) {
954 if (var->type->is_record() && existing->type->is_record()
955 && existing->type->record_compare(var->type)) {
956 existing->type = var->type;
957 } else {
958 linker_error(prog, "%s `%s' declared as type "
959 "`%s' and type `%s'\n",
960 mode_string(var),
961 var->name, var->type->name,
962 existing->type->name);
963 return;
964 }
965 }
966 }
967
968 if (var->data.explicit_location) {
969 if (existing->data.explicit_location
970 && (var->data.location != existing->data.location)) {
971 linker_error(prog, "explicit locations for %s "
972 "`%s' have differing values\n",
973 mode_string(var), var->name);
974 return;
975 }
976
977 existing->data.location = var->data.location;
978 existing->data.explicit_location = true;
979 }
980
981 /* From the GLSL 4.20 specification:
982 * "A link error will result if two compilation units in a program
983 * specify different integer-constant bindings for the same
984 * opaque-uniform name. However, it is not an error to specify a
985 * binding on some but not all declarations for the same name"
986 */
987 if (var->data.explicit_binding) {
988 if (existing->data.explicit_binding &&
989 var->data.binding != existing->data.binding) {
990 linker_error(prog, "explicit bindings for %s "
991 "`%s' have differing values\n",
992 mode_string(var), var->name);
993 return;
994 }
995
996 existing->data.binding = var->data.binding;
997 existing->data.explicit_binding = true;
998 }
999
1000 if (var->type->contains_atomic() &&
1001 var->data.atomic.offset != existing->data.atomic.offset) {
1002 linker_error(prog, "offset specifications for %s "
1003 "`%s' have differing values\n",
1004 mode_string(var), var->name);
1005 return;
1006 }
1007
1008 /* Validate layout qualifiers for gl_FragDepth.
1009 *
1010 * From the AMD/ARB_conservative_depth specs:
1011 *
1012 * "If gl_FragDepth is redeclared in any fragment shader in a
1013 * program, it must be redeclared in all fragment shaders in
1014 * that program that have static assignments to
1015 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1016 * fragment shaders in a single program must have the same set
1017 * of qualifiers."
1018 */
1019 if (strcmp(var->name, "gl_FragDepth") == 0) {
1020 bool layout_declared = var->data.depth_layout != ir_depth_layout_none;
1021 bool layout_differs =
1022 var->data.depth_layout != existing->data.depth_layout;
1023
1024 if (layout_declared && layout_differs) {
1025 linker_error(prog,
1026 "All redeclarations of gl_FragDepth in all "
1027 "fragment shaders in a single program must have "
1028 "the same set of qualifiers.\n");
1029 }
1030
1031 if (var->data.used && layout_differs) {
1032 linker_error(prog,
1033 "If gl_FragDepth is redeclared with a layout "
1034 "qualifier in any fragment shader, it must be "
1035 "redeclared with the same layout qualifier in "
1036 "all fragment shaders that have assignments to "
1037 "gl_FragDepth\n");
1038 }
1039 }
1040
1041 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1042 *
1043 * "If a shared global has multiple initializers, the
1044 * initializers must all be constant expressions, and they
1045 * must all have the same value. Otherwise, a link error will
1046 * result. (A shared global having only one initializer does
1047 * not require that initializer to be a constant expression.)"
1048 *
1049 * Previous to 4.20 the GLSL spec simply said that initializers
1050 * must have the same value. In this case of non-constant
1051 * initializers, this was impossible to determine. As a result,
1052 * no vendor actually implemented that behavior. The 4.20
1053 * behavior matches the implemented behavior of at least one other
1054 * vendor, so we'll implement that for all GLSL versions.
1055 */
1056 if (var->constant_initializer != NULL) {
1057 if (existing->constant_initializer != NULL) {
1058 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
1059 linker_error(prog, "initializers for %s "
1060 "`%s' have differing values\n",
1061 mode_string(var), var->name);
1062 return;
1063 }
1064 } else {
1065 /* If the first-seen instance of a particular uniform did not
1066 * have an initializer but a later instance does, copy the
1067 * initializer to the version stored in the symbol table.
1068 */
1069 /* FINISHME: This is wrong. The constant_value field should
1070 * FINISHME: not be modified! Imagine a case where a shader
1071 * FINISHME: without an initializer is linked in two different
1072 * FINISHME: programs with shaders that have differing
1073 * FINISHME: initializers. Linking with the first will
1074 * FINISHME: modify the shader, and linking with the second
1075 * FINISHME: will fail.
1076 */
1077 existing->constant_initializer =
1078 var->constant_initializer->clone(ralloc_parent(existing),
1079 NULL);
1080 }
1081 }
1082
1083 if (var->data.has_initializer) {
1084 if (existing->data.has_initializer
1085 && (var->constant_initializer == NULL
1086 || existing->constant_initializer == NULL)) {
1087 linker_error(prog,
1088 "shared global variable `%s' has multiple "
1089 "non-constant initializers.\n",
1090 var->name);
1091 return;
1092 }
1093
1094 /* Some instance had an initializer, so keep track of that. In
1095 * this location, all sorts of initializers (constant or
1096 * otherwise) will propagate the existence to the variable
1097 * stored in the symbol table.
1098 */
1099 existing->data.has_initializer = true;
1100 }
1101
1102 if (existing->data.invariant != var->data.invariant) {
1103 linker_error(prog, "declarations for %s `%s' have "
1104 "mismatching invariant qualifiers\n",
1105 mode_string(var), var->name);
1106 return;
1107 }
1108 if (existing->data.centroid != var->data.centroid) {
1109 linker_error(prog, "declarations for %s `%s' have "
1110 "mismatching centroid qualifiers\n",
1111 mode_string(var), var->name);
1112 return;
1113 }
1114 if (existing->data.sample != var->data.sample) {
1115 linker_error(prog, "declarations for %s `%s` have "
1116 "mismatching sample qualifiers\n",
1117 mode_string(var), var->name);
1118 return;
1119 }
1120 } else
1121 variables.add_variable(var);
1122 }
1123 }
1124 }
1125
1126
1127 /**
1128 * Perform validation of uniforms used across multiple shader stages
1129 */
1130 void
1131 cross_validate_uniforms(struct gl_shader_program *prog)
1132 {
1133 cross_validate_globals(prog, prog->_LinkedShaders,
1134 MESA_SHADER_STAGES, true);
1135 }
1136
1137 /**
1138 * Accumulates the array of prog->UniformBlocks and checks that all
1139 * definitons of blocks agree on their contents.
1140 */
1141 static bool
1142 interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog)
1143 {
1144 unsigned max_num_uniform_blocks = 0;
1145 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1146 if (prog->_LinkedShaders[i])
1147 max_num_uniform_blocks += prog->_LinkedShaders[i]->NumUniformBlocks;
1148 }
1149
1150 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1151 struct gl_shader *sh = prog->_LinkedShaders[i];
1152
1153 prog->UniformBlockStageIndex[i] = ralloc_array(prog, int,
1154 max_num_uniform_blocks);
1155 for (unsigned int j = 0; j < max_num_uniform_blocks; j++)
1156 prog->UniformBlockStageIndex[i][j] = -1;
1157
1158 if (sh == NULL)
1159 continue;
1160
1161 for (unsigned int j = 0; j < sh->NumUniformBlocks; j++) {
1162 int index = link_cross_validate_uniform_block(prog,
1163 &prog->UniformBlocks,
1164 &prog->NumUniformBlocks,
1165 &sh->UniformBlocks[j]);
1166
1167 if (index == -1) {
1168 linker_error(prog, "uniform block `%s' has mismatching definitions\n",
1169 sh->UniformBlocks[j].Name);
1170 return false;
1171 }
1172
1173 prog->UniformBlockStageIndex[i][index] = j;
1174 }
1175 }
1176
1177 return true;
1178 }
1179
1180
1181 /**
1182 * Populates a shaders symbol table with all global declarations
1183 */
1184 static void
1185 populate_symbol_table(gl_shader *sh)
1186 {
1187 sh->symbols = new(sh) glsl_symbol_table;
1188
1189 foreach_in_list(ir_instruction, inst, sh->ir) {
1190 ir_variable *var;
1191 ir_function *func;
1192
1193 if ((func = inst->as_function()) != NULL) {
1194 sh->symbols->add_function(func);
1195 } else if ((var = inst->as_variable()) != NULL) {
1196 if (var->data.mode != ir_var_temporary)
1197 sh->symbols->add_variable(var);
1198 }
1199 }
1200 }
1201
1202
1203 /**
1204 * Remap variables referenced in an instruction tree
1205 *
1206 * This is used when instruction trees are cloned from one shader and placed in
1207 * another. These trees will contain references to \c ir_variable nodes that
1208 * do not exist in the target shader. This function finds these \c ir_variable
1209 * references and replaces the references with matching variables in the target
1210 * shader.
1211 *
1212 * If there is no matching variable in the target shader, a clone of the
1213 * \c ir_variable is made and added to the target shader. The new variable is
1214 * added to \b both the instruction stream and the symbol table.
1215 *
1216 * \param inst IR tree that is to be processed.
1217 * \param symbols Symbol table containing global scope symbols in the
1218 * linked shader.
1219 * \param instructions Instruction stream where new variable declarations
1220 * should be added.
1221 */
1222 void
1223 remap_variables(ir_instruction *inst, struct gl_shader *target,
1224 hash_table *temps)
1225 {
1226 class remap_visitor : public ir_hierarchical_visitor {
1227 public:
1228 remap_visitor(struct gl_shader *target,
1229 hash_table *temps)
1230 {
1231 this->target = target;
1232 this->symbols = target->symbols;
1233 this->instructions = target->ir;
1234 this->temps = temps;
1235 }
1236
1237 virtual ir_visitor_status visit(ir_dereference_variable *ir)
1238 {
1239 if (ir->var->data.mode == ir_var_temporary) {
1240 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
1241
1242 assert(var != NULL);
1243 ir->var = var;
1244 return visit_continue;
1245 }
1246
1247 ir_variable *const existing =
1248 this->symbols->get_variable(ir->var->name);
1249 if (existing != NULL)
1250 ir->var = existing;
1251 else {
1252 ir_variable *copy = ir->var->clone(this->target, NULL);
1253
1254 this->symbols->add_variable(copy);
1255 this->instructions->push_head(copy);
1256 ir->var = copy;
1257 }
1258
1259 return visit_continue;
1260 }
1261
1262 private:
1263 struct gl_shader *target;
1264 glsl_symbol_table *symbols;
1265 exec_list *instructions;
1266 hash_table *temps;
1267 };
1268
1269 remap_visitor v(target, temps);
1270
1271 inst->accept(&v);
1272 }
1273
1274
1275 /**
1276 * Move non-declarations from one instruction stream to another
1277 *
1278 * The intended usage pattern of this function is to pass the pointer to the
1279 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1280 * pointer) for \c last and \c false for \c make_copies on the first
1281 * call. Successive calls pass the return value of the previous call for
1282 * \c last and \c true for \c make_copies.
1283 *
1284 * \param instructions Source instruction stream
1285 * \param last Instruction after which new instructions should be
1286 * inserted in the target instruction stream
1287 * \param make_copies Flag selecting whether instructions in \c instructions
1288 * should be copied (via \c ir_instruction::clone) into the
1289 * target list or moved.
1290 *
1291 * \return
1292 * The new "last" instruction in the target instruction stream. This pointer
1293 * is suitable for use as the \c last parameter of a later call to this
1294 * function.
1295 */
1296 exec_node *
1297 move_non_declarations(exec_list *instructions, exec_node *last,
1298 bool make_copies, gl_shader *target)
1299 {
1300 hash_table *temps = NULL;
1301
1302 if (make_copies)
1303 temps = hash_table_ctor(0, hash_table_pointer_hash,
1304 hash_table_pointer_compare);
1305
1306 foreach_in_list_safe(ir_instruction, inst, instructions) {
1307 if (inst->as_function())
1308 continue;
1309
1310 ir_variable *var = inst->as_variable();
1311 if ((var != NULL) && (var->data.mode != ir_var_temporary))
1312 continue;
1313
1314 assert(inst->as_assignment()
1315 || inst->as_call()
1316 || inst->as_if() /* for initializers with the ?: operator */
1317 || ((var != NULL) && (var->data.mode == ir_var_temporary)));
1318
1319 if (make_copies) {
1320 inst = inst->clone(target, NULL);
1321
1322 if (var != NULL)
1323 hash_table_insert(temps, inst, var);
1324 else
1325 remap_variables(inst, target, temps);
1326 } else {
1327 inst->remove();
1328 }
1329
1330 last->insert_after(inst);
1331 last = inst;
1332 }
1333
1334 if (make_copies)
1335 hash_table_dtor(temps);
1336
1337 return last;
1338 }
1339
1340 /**
1341 * Get the function signature for main from a shader
1342 */
1343 ir_function_signature *
1344 link_get_main_function_signature(gl_shader *sh)
1345 {
1346 ir_function *const f = sh->symbols->get_function("main");
1347 if (f != NULL) {
1348 exec_list void_parameters;
1349
1350 /* Look for the 'void main()' signature and ensure that it's defined.
1351 * This keeps the linker from accidentally pick a shader that just
1352 * contains a prototype for main.
1353 *
1354 * We don't have to check for multiple definitions of main (in multiple
1355 * shaders) because that would have already been caught above.
1356 */
1357 ir_function_signature *sig =
1358 f->matching_signature(NULL, &void_parameters, false);
1359 if ((sig != NULL) && sig->is_defined) {
1360 return sig;
1361 }
1362 }
1363
1364 return NULL;
1365 }
1366
1367
1368 /**
1369 * This class is only used in link_intrastage_shaders() below but declaring
1370 * it inside that function leads to compiler warnings with some versions of
1371 * gcc.
1372 */
1373 class array_sizing_visitor : public ir_hierarchical_visitor {
1374 public:
1375 array_sizing_visitor()
1376 : mem_ctx(ralloc_context(NULL)),
1377 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash,
1378 hash_table_pointer_compare))
1379 {
1380 }
1381
1382 ~array_sizing_visitor()
1383 {
1384 hash_table_dtor(this->unnamed_interfaces);
1385 ralloc_free(this->mem_ctx);
1386 }
1387
1388 virtual ir_visitor_status visit(ir_variable *var)
1389 {
1390 fixup_type(&var->type, var->data.max_array_access);
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->type = new_type;
1397 var->change_interface_type(new_type);
1398 }
1399 } else if (var->type->is_array() &&
1400 var->type->fields.array->is_interface()) {
1401 if (interface_contains_unsized_arrays(var->type->fields.array)) {
1402 const glsl_type *new_type =
1403 resize_interface_members(var->type->fields.array,
1404 var->get_max_ifc_array_access());
1405 var->change_interface_type(new_type);
1406 var->type = update_interface_members_array(var->type, new_type);
1407 }
1408 } else if (const glsl_type *ifc_type = var->get_interface_type()) {
1409 /* Store a pointer to the variable in the unnamed_interfaces
1410 * hashtable.
1411 */
1412 ir_variable **interface_vars = (ir_variable **)
1413 hash_table_find(this->unnamed_interfaces, ifc_type);
1414 if (interface_vars == NULL) {
1415 interface_vars = rzalloc_array(mem_ctx, ir_variable *,
1416 ifc_type->length);
1417 hash_table_insert(this->unnamed_interfaces, interface_vars,
1418 ifc_type);
1419 }
1420 unsigned index = ifc_type->field_index(var->name);
1421 assert(index < ifc_type->length);
1422 assert(interface_vars[index] == NULL);
1423 interface_vars[index] = var;
1424 }
1425 return visit_continue;
1426 }
1427
1428 /**
1429 * For each unnamed interface block that was discovered while running the
1430 * visitor, adjust the interface type to reflect the newly assigned array
1431 * sizes, and fix up the ir_variable nodes to point to the new interface
1432 * type.
1433 */
1434 void fixup_unnamed_interface_types()
1435 {
1436 hash_table_call_foreach(this->unnamed_interfaces,
1437 fixup_unnamed_interface_type, NULL);
1438 }
1439
1440 private:
1441 /**
1442 * If the type pointed to by \c type represents an unsized array, replace
1443 * it with a sized array whose size is determined by max_array_access.
1444 */
1445 static void fixup_type(const glsl_type **type, unsigned max_array_access)
1446 {
1447 if ((*type)->is_unsized_array()) {
1448 *type = glsl_type::get_array_instance((*type)->fields.array,
1449 max_array_access + 1);
1450 assert(*type != NULL);
1451 }
1452 }
1453
1454 static const glsl_type *
1455 update_interface_members_array(const glsl_type *type,
1456 const glsl_type *new_interface_type)
1457 {
1458 const glsl_type *element_type = type->fields.array;
1459 if (element_type->is_array()) {
1460 const glsl_type *new_array_type =
1461 update_interface_members_array(element_type, new_interface_type);
1462 return glsl_type::get_array_instance(new_array_type, type->length);
1463 } else {
1464 return glsl_type::get_array_instance(new_interface_type,
1465 type->length);
1466 }
1467 }
1468
1469 /**
1470 * Determine whether the given interface type contains unsized arrays (if
1471 * it doesn't, array_sizing_visitor doesn't need to process it).
1472 */
1473 static bool interface_contains_unsized_arrays(const glsl_type *type)
1474 {
1475 for (unsigned i = 0; i < type->length; i++) {
1476 const glsl_type *elem_type = type->fields.structure[i].type;
1477 if (elem_type->is_unsized_array())
1478 return true;
1479 }
1480 return false;
1481 }
1482
1483 /**
1484 * Create a new interface type based on the given type, with unsized arrays
1485 * replaced by sized arrays whose size is determined by
1486 * max_ifc_array_access.
1487 */
1488 static const glsl_type *
1489 resize_interface_members(const glsl_type *type,
1490 const unsigned *max_ifc_array_access)
1491 {
1492 unsigned num_fields = type->length;
1493 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1494 memcpy(fields, type->fields.structure,
1495 num_fields * sizeof(*fields));
1496 for (unsigned i = 0; i < num_fields; i++) {
1497 fixup_type(&fields[i].type, max_ifc_array_access[i]);
1498 }
1499 glsl_interface_packing packing =
1500 (glsl_interface_packing) type->interface_packing;
1501 const glsl_type *new_ifc_type =
1502 glsl_type::get_interface_instance(fields, num_fields,
1503 packing, type->name);
1504 delete [] fields;
1505 return new_ifc_type;
1506 }
1507
1508 static void fixup_unnamed_interface_type(const void *key, void *data,
1509 void *)
1510 {
1511 const glsl_type *ifc_type = (const glsl_type *) key;
1512 ir_variable **interface_vars = (ir_variable **) data;
1513 unsigned num_fields = ifc_type->length;
1514 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1515 memcpy(fields, ifc_type->fields.structure,
1516 num_fields * sizeof(*fields));
1517 bool interface_type_changed = false;
1518 for (unsigned i = 0; i < num_fields; i++) {
1519 if (interface_vars[i] != NULL &&
1520 fields[i].type != interface_vars[i]->type) {
1521 fields[i].type = interface_vars[i]->type;
1522 interface_type_changed = true;
1523 }
1524 }
1525 if (!interface_type_changed) {
1526 delete [] fields;
1527 return;
1528 }
1529 glsl_interface_packing packing =
1530 (glsl_interface_packing) ifc_type->interface_packing;
1531 const glsl_type *new_ifc_type =
1532 glsl_type::get_interface_instance(fields, num_fields, packing,
1533 ifc_type->name);
1534 delete [] fields;
1535 for (unsigned i = 0; i < num_fields; i++) {
1536 if (interface_vars[i] != NULL)
1537 interface_vars[i]->change_interface_type(new_ifc_type);
1538 }
1539 }
1540
1541 /**
1542 * Memory context used to allocate the data in \c unnamed_interfaces.
1543 */
1544 void *mem_ctx;
1545
1546 /**
1547 * Hash table from const glsl_type * to an array of ir_variable *'s
1548 * pointing to the ir_variables constituting each unnamed interface block.
1549 */
1550 hash_table *unnamed_interfaces;
1551 };
1552
1553
1554 /**
1555 * Performs the cross-validation of tessellation control shader vertices and
1556 * layout qualifiers for the attached tessellation control shaders,
1557 * and propagates them to the linked TCS and linked shader program.
1558 */
1559 static void
1560 link_tcs_out_layout_qualifiers(struct gl_shader_program *prog,
1561 struct gl_shader *linked_shader,
1562 struct gl_shader **shader_list,
1563 unsigned num_shaders)
1564 {
1565 linked_shader->TessCtrl.VerticesOut = 0;
1566
1567 if (linked_shader->Stage != MESA_SHADER_TESS_CTRL)
1568 return;
1569
1570 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1571 *
1572 * "All tessellation control shader layout declarations in a program
1573 * must specify the same output patch vertex count. There must be at
1574 * least one layout qualifier specifying an output patch vertex count
1575 * in any program containing tessellation control shaders; however,
1576 * such a declaration is not required in all tessellation control
1577 * shaders."
1578 */
1579
1580 for (unsigned i = 0; i < num_shaders; i++) {
1581 struct gl_shader *shader = shader_list[i];
1582
1583 if (shader->TessCtrl.VerticesOut != 0) {
1584 if (linked_shader->TessCtrl.VerticesOut != 0 &&
1585 linked_shader->TessCtrl.VerticesOut != shader->TessCtrl.VerticesOut) {
1586 linker_error(prog, "tessellation control shader defined with "
1587 "conflicting output vertex count (%d and %d)\n",
1588 linked_shader->TessCtrl.VerticesOut,
1589 shader->TessCtrl.VerticesOut);
1590 return;
1591 }
1592 linked_shader->TessCtrl.VerticesOut = shader->TessCtrl.VerticesOut;
1593 }
1594 }
1595
1596 /* Just do the intrastage -> interstage propagation right now,
1597 * since we already know we're in the right type of shader program
1598 * for doing it.
1599 */
1600 if (linked_shader->TessCtrl.VerticesOut == 0) {
1601 linker_error(prog, "tessellation control shader didn't declare "
1602 "vertices out layout qualifier\n");
1603 return;
1604 }
1605 prog->TessCtrl.VerticesOut = linked_shader->TessCtrl.VerticesOut;
1606 }
1607
1608
1609 /**
1610 * Performs the cross-validation of tessellation evaluation shader
1611 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1612 * for the attached tessellation evaluation shaders, and propagates them
1613 * to the linked TES and linked shader program.
1614 */
1615 static void
1616 link_tes_in_layout_qualifiers(struct gl_shader_program *prog,
1617 struct gl_shader *linked_shader,
1618 struct gl_shader **shader_list,
1619 unsigned num_shaders)
1620 {
1621 linked_shader->TessEval.PrimitiveMode = PRIM_UNKNOWN;
1622 linked_shader->TessEval.Spacing = 0;
1623 linked_shader->TessEval.VertexOrder = 0;
1624 linked_shader->TessEval.PointMode = -1;
1625
1626 if (linked_shader->Stage != MESA_SHADER_TESS_EVAL)
1627 return;
1628
1629 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1630 *
1631 * "At least one tessellation evaluation shader (compilation unit) in
1632 * a program must declare a primitive mode in its input layout.
1633 * Declaration vertex spacing, ordering, and point mode identifiers is
1634 * optional. It is not required that all tessellation evaluation
1635 * shaders in a program declare a primitive mode. If spacing or
1636 * vertex ordering declarations are omitted, the tessellation
1637 * primitive generator will use equal spacing or counter-clockwise
1638 * vertex ordering, respectively. If a point mode declaration is
1639 * omitted, the tessellation primitive generator will produce lines or
1640 * triangles according to the primitive mode."
1641 */
1642
1643 for (unsigned i = 0; i < num_shaders; i++) {
1644 struct gl_shader *shader = shader_list[i];
1645
1646 if (shader->TessEval.PrimitiveMode != PRIM_UNKNOWN) {
1647 if (linked_shader->TessEval.PrimitiveMode != PRIM_UNKNOWN &&
1648 linked_shader->TessEval.PrimitiveMode != shader->TessEval.PrimitiveMode) {
1649 linker_error(prog, "tessellation evaluation shader defined with "
1650 "conflicting input primitive modes.\n");
1651 return;
1652 }
1653 linked_shader->TessEval.PrimitiveMode = shader->TessEval.PrimitiveMode;
1654 }
1655
1656 if (shader->TessEval.Spacing != 0) {
1657 if (linked_shader->TessEval.Spacing != 0 &&
1658 linked_shader->TessEval.Spacing != shader->TessEval.Spacing) {
1659 linker_error(prog, "tessellation evaluation shader defined with "
1660 "conflicting vertex spacing.\n");
1661 return;
1662 }
1663 linked_shader->TessEval.Spacing = shader->TessEval.Spacing;
1664 }
1665
1666 if (shader->TessEval.VertexOrder != 0) {
1667 if (linked_shader->TessEval.VertexOrder != 0 &&
1668 linked_shader->TessEval.VertexOrder != shader->TessEval.VertexOrder) {
1669 linker_error(prog, "tessellation evaluation shader defined with "
1670 "conflicting ordering.\n");
1671 return;
1672 }
1673 linked_shader->TessEval.VertexOrder = shader->TessEval.VertexOrder;
1674 }
1675
1676 if (shader->TessEval.PointMode != -1) {
1677 if (linked_shader->TessEval.PointMode != -1 &&
1678 linked_shader->TessEval.PointMode != shader->TessEval.PointMode) {
1679 linker_error(prog, "tessellation evaluation shader defined with "
1680 "conflicting point modes.\n");
1681 return;
1682 }
1683 linked_shader->TessEval.PointMode = shader->TessEval.PointMode;
1684 }
1685
1686 }
1687
1688 /* Just do the intrastage -> interstage propagation right now,
1689 * since we already know we're in the right type of shader program
1690 * for doing it.
1691 */
1692 if (linked_shader->TessEval.PrimitiveMode == PRIM_UNKNOWN) {
1693 linker_error(prog,
1694 "tessellation evaluation shader didn't declare input "
1695 "primitive modes.\n");
1696 return;
1697 }
1698 prog->TessEval.PrimitiveMode = linked_shader->TessEval.PrimitiveMode;
1699
1700 if (linked_shader->TessEval.Spacing == 0)
1701 linked_shader->TessEval.Spacing = GL_EQUAL;
1702 prog->TessEval.Spacing = linked_shader->TessEval.Spacing;
1703
1704 if (linked_shader->TessEval.VertexOrder == 0)
1705 linked_shader->TessEval.VertexOrder = GL_CCW;
1706 prog->TessEval.VertexOrder = linked_shader->TessEval.VertexOrder;
1707
1708 if (linked_shader->TessEval.PointMode == -1)
1709 linked_shader->TessEval.PointMode = GL_FALSE;
1710 prog->TessEval.PointMode = linked_shader->TessEval.PointMode;
1711 }
1712
1713
1714 /**
1715 * Performs the cross-validation of layout qualifiers specified in
1716 * redeclaration of gl_FragCoord for the attached fragment shaders,
1717 * and propagates them to the linked FS and linked shader program.
1718 */
1719 static void
1720 link_fs_input_layout_qualifiers(struct gl_shader_program *prog,
1721 struct gl_shader *linked_shader,
1722 struct gl_shader **shader_list,
1723 unsigned num_shaders)
1724 {
1725 linked_shader->redeclares_gl_fragcoord = false;
1726 linked_shader->uses_gl_fragcoord = false;
1727 linked_shader->origin_upper_left = false;
1728 linked_shader->pixel_center_integer = false;
1729
1730 if (linked_shader->Stage != MESA_SHADER_FRAGMENT ||
1731 (prog->Version < 150 && !prog->ARB_fragment_coord_conventions_enable))
1732 return;
1733
1734 for (unsigned i = 0; i < num_shaders; i++) {
1735 struct gl_shader *shader = shader_list[i];
1736 /* From the GLSL 1.50 spec, page 39:
1737 *
1738 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1739 * it must be redeclared in all the fragment shaders in that program
1740 * that have a static use gl_FragCoord."
1741 */
1742 if ((linked_shader->redeclares_gl_fragcoord
1743 && !shader->redeclares_gl_fragcoord
1744 && shader->uses_gl_fragcoord)
1745 || (shader->redeclares_gl_fragcoord
1746 && !linked_shader->redeclares_gl_fragcoord
1747 && linked_shader->uses_gl_fragcoord)) {
1748 linker_error(prog, "fragment shader defined with conflicting "
1749 "layout qualifiers for gl_FragCoord\n");
1750 }
1751
1752 /* From the GLSL 1.50 spec, page 39:
1753 *
1754 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1755 * single program must have the same set of qualifiers."
1756 */
1757 if (linked_shader->redeclares_gl_fragcoord && shader->redeclares_gl_fragcoord
1758 && (shader->origin_upper_left != linked_shader->origin_upper_left
1759 || shader->pixel_center_integer != linked_shader->pixel_center_integer)) {
1760 linker_error(prog, "fragment shader defined with conflicting "
1761 "layout qualifiers for gl_FragCoord\n");
1762 }
1763
1764 /* Update the linked shader state. Note that uses_gl_fragcoord should
1765 * accumulate the results. The other values should replace. If there
1766 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1767 * are already known to be the same.
1768 */
1769 if (shader->redeclares_gl_fragcoord || shader->uses_gl_fragcoord) {
1770 linked_shader->redeclares_gl_fragcoord =
1771 shader->redeclares_gl_fragcoord;
1772 linked_shader->uses_gl_fragcoord = linked_shader->uses_gl_fragcoord
1773 || shader->uses_gl_fragcoord;
1774 linked_shader->origin_upper_left = shader->origin_upper_left;
1775 linked_shader->pixel_center_integer = shader->pixel_center_integer;
1776 }
1777
1778 linked_shader->EarlyFragmentTests |= shader->EarlyFragmentTests;
1779 }
1780 }
1781
1782 /**
1783 * Performs the cross-validation of geometry shader max_vertices and
1784 * primitive type layout qualifiers for the attached geometry shaders,
1785 * and propagates them to the linked GS and linked shader program.
1786 */
1787 static void
1788 link_gs_inout_layout_qualifiers(struct gl_shader_program *prog,
1789 struct gl_shader *linked_shader,
1790 struct gl_shader **shader_list,
1791 unsigned num_shaders)
1792 {
1793 linked_shader->Geom.VerticesOut = 0;
1794 linked_shader->Geom.Invocations = 0;
1795 linked_shader->Geom.InputType = PRIM_UNKNOWN;
1796 linked_shader->Geom.OutputType = PRIM_UNKNOWN;
1797
1798 /* No in/out qualifiers defined for anything but GLSL 1.50+
1799 * geometry shaders so far.
1800 */
1801 if (linked_shader->Stage != MESA_SHADER_GEOMETRY || prog->Version < 150)
1802 return;
1803
1804 /* From the GLSL 1.50 spec, page 46:
1805 *
1806 * "All geometry shader output layout declarations in a program
1807 * must declare the same layout and same value for
1808 * max_vertices. There must be at least one geometry output
1809 * layout declaration somewhere in a program, but not all
1810 * geometry shaders (compilation units) are required to
1811 * declare it."
1812 */
1813
1814 for (unsigned i = 0; i < num_shaders; i++) {
1815 struct gl_shader *shader = shader_list[i];
1816
1817 if (shader->Geom.InputType != PRIM_UNKNOWN) {
1818 if (linked_shader->Geom.InputType != PRIM_UNKNOWN &&
1819 linked_shader->Geom.InputType != shader->Geom.InputType) {
1820 linker_error(prog, "geometry shader defined with conflicting "
1821 "input types\n");
1822 return;
1823 }
1824 linked_shader->Geom.InputType = shader->Geom.InputType;
1825 }
1826
1827 if (shader->Geom.OutputType != PRIM_UNKNOWN) {
1828 if (linked_shader->Geom.OutputType != PRIM_UNKNOWN &&
1829 linked_shader->Geom.OutputType != shader->Geom.OutputType) {
1830 linker_error(prog, "geometry shader defined with conflicting "
1831 "output types\n");
1832 return;
1833 }
1834 linked_shader->Geom.OutputType = shader->Geom.OutputType;
1835 }
1836
1837 if (shader->Geom.VerticesOut != 0) {
1838 if (linked_shader->Geom.VerticesOut != 0 &&
1839 linked_shader->Geom.VerticesOut != shader->Geom.VerticesOut) {
1840 linker_error(prog, "geometry shader defined with conflicting "
1841 "output vertex count (%d and %d)\n",
1842 linked_shader->Geom.VerticesOut,
1843 shader->Geom.VerticesOut);
1844 return;
1845 }
1846 linked_shader->Geom.VerticesOut = shader->Geom.VerticesOut;
1847 }
1848
1849 if (shader->Geom.Invocations != 0) {
1850 if (linked_shader->Geom.Invocations != 0 &&
1851 linked_shader->Geom.Invocations != shader->Geom.Invocations) {
1852 linker_error(prog, "geometry shader defined with conflicting "
1853 "invocation count (%d and %d)\n",
1854 linked_shader->Geom.Invocations,
1855 shader->Geom.Invocations);
1856 return;
1857 }
1858 linked_shader->Geom.Invocations = shader->Geom.Invocations;
1859 }
1860 }
1861
1862 /* Just do the intrastage -> interstage propagation right now,
1863 * since we already know we're in the right type of shader program
1864 * for doing it.
1865 */
1866 if (linked_shader->Geom.InputType == PRIM_UNKNOWN) {
1867 linker_error(prog,
1868 "geometry shader didn't declare primitive input type\n");
1869 return;
1870 }
1871 prog->Geom.InputType = linked_shader->Geom.InputType;
1872
1873 if (linked_shader->Geom.OutputType == PRIM_UNKNOWN) {
1874 linker_error(prog,
1875 "geometry shader didn't declare primitive output type\n");
1876 return;
1877 }
1878 prog->Geom.OutputType = linked_shader->Geom.OutputType;
1879
1880 if (linked_shader->Geom.VerticesOut == 0) {
1881 linker_error(prog,
1882 "geometry shader didn't declare max_vertices\n");
1883 return;
1884 }
1885 prog->Geom.VerticesOut = linked_shader->Geom.VerticesOut;
1886
1887 if (linked_shader->Geom.Invocations == 0)
1888 linked_shader->Geom.Invocations = 1;
1889
1890 prog->Geom.Invocations = linked_shader->Geom.Invocations;
1891 }
1892
1893
1894 /**
1895 * Perform cross-validation of compute shader local_size_{x,y,z} layout
1896 * qualifiers for the attached compute shaders, and propagate them to the
1897 * linked CS and linked shader program.
1898 */
1899 static void
1900 link_cs_input_layout_qualifiers(struct gl_shader_program *prog,
1901 struct gl_shader *linked_shader,
1902 struct gl_shader **shader_list,
1903 unsigned num_shaders)
1904 {
1905 for (int i = 0; i < 3; i++)
1906 linked_shader->Comp.LocalSize[i] = 0;
1907
1908 /* This function is called for all shader stages, but it only has an effect
1909 * for compute shaders.
1910 */
1911 if (linked_shader->Stage != MESA_SHADER_COMPUTE)
1912 return;
1913
1914 /* From the ARB_compute_shader spec, in the section describing local size
1915 * declarations:
1916 *
1917 * If multiple compute shaders attached to a single program object
1918 * declare local work-group size, the declarations must be identical;
1919 * otherwise a link-time error results. Furthermore, if a program
1920 * object contains any compute shaders, at least one must contain an
1921 * input layout qualifier specifying the local work sizes of the
1922 * program, or a link-time error will occur.
1923 */
1924 for (unsigned sh = 0; sh < num_shaders; sh++) {
1925 struct gl_shader *shader = shader_list[sh];
1926
1927 if (shader->Comp.LocalSize[0] != 0) {
1928 if (linked_shader->Comp.LocalSize[0] != 0) {
1929 for (int i = 0; i < 3; i++) {
1930 if (linked_shader->Comp.LocalSize[i] !=
1931 shader->Comp.LocalSize[i]) {
1932 linker_error(prog, "compute shader defined with conflicting "
1933 "local sizes\n");
1934 return;
1935 }
1936 }
1937 }
1938 for (int i = 0; i < 3; i++)
1939 linked_shader->Comp.LocalSize[i] = shader->Comp.LocalSize[i];
1940 }
1941 }
1942
1943 /* Just do the intrastage -> interstage propagation right now,
1944 * since we already know we're in the right type of shader program
1945 * for doing it.
1946 */
1947 if (linked_shader->Comp.LocalSize[0] == 0) {
1948 linker_error(prog, "compute shader didn't declare local size\n");
1949 return;
1950 }
1951 for (int i = 0; i < 3; i++)
1952 prog->Comp.LocalSize[i] = linked_shader->Comp.LocalSize[i];
1953 }
1954
1955
1956 /**
1957 * Combine a group of shaders for a single stage to generate a linked shader
1958 *
1959 * \note
1960 * If this function is supplied a single shader, it is cloned, and the new
1961 * shader is returned.
1962 */
1963 static struct gl_shader *
1964 link_intrastage_shaders(void *mem_ctx,
1965 struct gl_context *ctx,
1966 struct gl_shader_program *prog,
1967 struct gl_shader **shader_list,
1968 unsigned num_shaders)
1969 {
1970 struct gl_uniform_block *uniform_blocks = NULL;
1971
1972 /* Check that global variables defined in multiple shaders are consistent.
1973 */
1974 cross_validate_globals(prog, shader_list, num_shaders, false);
1975 if (!prog->LinkStatus)
1976 return NULL;
1977
1978 /* Check that interface blocks defined in multiple shaders are consistent.
1979 */
1980 validate_intrastage_interface_blocks(prog, (const gl_shader **)shader_list,
1981 num_shaders);
1982 if (!prog->LinkStatus)
1983 return NULL;
1984
1985 /* Link up uniform blocks defined within this stage. */
1986 const unsigned num_uniform_blocks =
1987 link_uniform_blocks(mem_ctx, prog, shader_list, num_shaders,
1988 &uniform_blocks);
1989 if (!prog->LinkStatus)
1990 return NULL;
1991
1992 /* Check that there is only a single definition of each function signature
1993 * across all shaders.
1994 */
1995 for (unsigned i = 0; i < (num_shaders - 1); i++) {
1996 foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
1997 ir_function *const f = node->as_function();
1998
1999 if (f == NULL)
2000 continue;
2001
2002 for (unsigned j = i + 1; j < num_shaders; j++) {
2003 ir_function *const other =
2004 shader_list[j]->symbols->get_function(f->name);
2005
2006 /* If the other shader has no function (and therefore no function
2007 * signatures) with the same name, skip to the next shader.
2008 */
2009 if (other == NULL)
2010 continue;
2011
2012 foreach_in_list(ir_function_signature, sig, &f->signatures) {
2013 if (!sig->is_defined || sig->is_builtin())
2014 continue;
2015
2016 ir_function_signature *other_sig =
2017 other->exact_matching_signature(NULL, &sig->parameters);
2018
2019 if ((other_sig != NULL) && other_sig->is_defined
2020 && !other_sig->is_builtin()) {
2021 linker_error(prog, "function `%s' is multiply defined\n",
2022 f->name);
2023 return NULL;
2024 }
2025 }
2026 }
2027 }
2028 }
2029
2030 /* Find the shader that defines main, and make a clone of it.
2031 *
2032 * Starting with the clone, search for undefined references. If one is
2033 * found, find the shader that defines it. Clone the reference and add
2034 * it to the shader. Repeat until there are no undefined references or
2035 * until a reference cannot be resolved.
2036 */
2037 gl_shader *main = NULL;
2038 for (unsigned i = 0; i < num_shaders; i++) {
2039 if (link_get_main_function_signature(shader_list[i]) != NULL) {
2040 main = shader_list[i];
2041 break;
2042 }
2043 }
2044
2045 if (main == NULL) {
2046 linker_error(prog, "%s shader lacks `main'\n",
2047 _mesa_shader_stage_to_string(shader_list[0]->Stage));
2048 return NULL;
2049 }
2050
2051 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
2052 linked->ir = new(linked) exec_list;
2053 clone_ir_list(mem_ctx, linked->ir, main->ir);
2054
2055 linked->UniformBlocks = uniform_blocks;
2056 linked->NumUniformBlocks = num_uniform_blocks;
2057 ralloc_steal(linked, linked->UniformBlocks);
2058
2059 link_fs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
2060 link_tcs_out_layout_qualifiers(prog, linked, shader_list, num_shaders);
2061 link_tes_in_layout_qualifiers(prog, linked, shader_list, num_shaders);
2062 link_gs_inout_layout_qualifiers(prog, linked, shader_list, num_shaders);
2063 link_cs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
2064
2065 populate_symbol_table(linked);
2066
2067 /* The pointer to the main function in the final linked shader (i.e., the
2068 * copy of the original shader that contained the main function).
2069 */
2070 ir_function_signature *const main_sig =
2071 link_get_main_function_signature(linked);
2072
2073 /* Move any instructions other than variable declarations or function
2074 * declarations into main.
2075 */
2076 exec_node *insertion_point =
2077 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
2078 linked);
2079
2080 for (unsigned i = 0; i < num_shaders; i++) {
2081 if (shader_list[i] == main)
2082 continue;
2083
2084 insertion_point = move_non_declarations(shader_list[i]->ir,
2085 insertion_point, true, linked);
2086 }
2087
2088 /* Check if any shader needs built-in functions. */
2089 bool need_builtins = false;
2090 for (unsigned i = 0; i < num_shaders; i++) {
2091 if (shader_list[i]->uses_builtin_functions) {
2092 need_builtins = true;
2093 break;
2094 }
2095 }
2096
2097 bool ok;
2098 if (need_builtins) {
2099 /* Make a temporary array one larger than shader_list, which will hold
2100 * the built-in function shader as well.
2101 */
2102 gl_shader **linking_shaders = (gl_shader **)
2103 calloc(num_shaders + 1, sizeof(gl_shader *));
2104
2105 ok = linking_shaders != NULL;
2106
2107 if (ok) {
2108 memcpy(linking_shaders, shader_list, num_shaders * sizeof(gl_shader *));
2109 linking_shaders[num_shaders] = _mesa_glsl_get_builtin_function_shader();
2110
2111 ok = link_function_calls(prog, linked, linking_shaders, num_shaders + 1);
2112
2113 free(linking_shaders);
2114 } else {
2115 _mesa_error_no_memory(__func__);
2116 }
2117 } else {
2118 ok = link_function_calls(prog, linked, shader_list, num_shaders);
2119 }
2120
2121
2122 if (!ok) {
2123 ctx->Driver.DeleteShader(ctx, linked);
2124 return NULL;
2125 }
2126
2127 /* At this point linked should contain all of the linked IR, so
2128 * validate it to make sure nothing went wrong.
2129 */
2130 validate_ir_tree(linked->ir);
2131
2132 /* Set the size of geometry shader input arrays */
2133 if (linked->Stage == MESA_SHADER_GEOMETRY) {
2134 unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
2135 geom_array_resize_visitor input_resize_visitor(num_vertices, prog);
2136 foreach_in_list(ir_instruction, ir, linked->ir) {
2137 ir->accept(&input_resize_visitor);
2138 }
2139 }
2140
2141 if (ctx->Const.VertexID_is_zero_based)
2142 lower_vertex_id(linked);
2143
2144 /* Validate correct usage of barrier() in the tess control shader */
2145 if (linked->Stage == MESA_SHADER_TESS_CTRL) {
2146 barrier_use_visitor visitor(prog);
2147 foreach_in_list(ir_instruction, ir, linked->ir) {
2148 ir->accept(&visitor);
2149 }
2150 }
2151
2152 /* Make a pass over all variable declarations to ensure that arrays with
2153 * unspecified sizes have a size specified. The size is inferred from the
2154 * max_array_access field.
2155 */
2156 array_sizing_visitor v;
2157 v.run(linked->ir);
2158 v.fixup_unnamed_interface_types();
2159
2160 return linked;
2161 }
2162
2163 /**
2164 * Update the sizes of linked shader uniform arrays to the maximum
2165 * array index used.
2166 *
2167 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2168 *
2169 * If one or more elements of an array are active,
2170 * GetActiveUniform will return the name of the array in name,
2171 * subject to the restrictions listed above. The type of the array
2172 * is returned in type. The size parameter contains the highest
2173 * array element index used, plus one. The compiler or linker
2174 * determines the highest index used. There will be only one
2175 * active uniform reported by the GL per uniform array.
2176
2177 */
2178 static void
2179 update_array_sizes(struct gl_shader_program *prog)
2180 {
2181 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2182 if (prog->_LinkedShaders[i] == NULL)
2183 continue;
2184
2185 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
2186 ir_variable *const var = node->as_variable();
2187
2188 if ((var == NULL) || (var->data.mode != ir_var_uniform) ||
2189 !var->type->is_array())
2190 continue;
2191
2192 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2193 * will not be eliminated. Since we always do std140, just
2194 * don't resize arrays in UBOs.
2195 *
2196 * Atomic counters are supposed to get deterministic
2197 * locations assigned based on the declaration ordering and
2198 * sizes, array compaction would mess that up.
2199 */
2200 if (var->is_in_buffer_block() || var->type->contains_atomic())
2201 continue;
2202
2203 unsigned int size = var->data.max_array_access;
2204 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
2205 if (prog->_LinkedShaders[j] == NULL)
2206 continue;
2207
2208 foreach_in_list(ir_instruction, node2, prog->_LinkedShaders[j]->ir) {
2209 ir_variable *other_var = node2->as_variable();
2210 if (!other_var)
2211 continue;
2212
2213 if (strcmp(var->name, other_var->name) == 0 &&
2214 other_var->data.max_array_access > size) {
2215 size = other_var->data.max_array_access;
2216 }
2217 }
2218 }
2219
2220 if (size + 1 != var->type->length) {
2221 /* If this is a built-in uniform (i.e., it's backed by some
2222 * fixed-function state), adjust the number of state slots to
2223 * match the new array size. The number of slots per array entry
2224 * is not known. It seems safe to assume that the total number of
2225 * slots is an integer multiple of the number of array elements.
2226 * Determine the number of slots per array element by dividing by
2227 * the old (total) size.
2228 */
2229 const unsigned num_slots = var->get_num_state_slots();
2230 if (num_slots > 0) {
2231 var->set_num_state_slots((size + 1)
2232 * (num_slots / var->type->length));
2233 }
2234
2235 var->type = glsl_type::get_array_instance(var->type->fields.array,
2236 size + 1);
2237 /* FINISHME: We should update the types of array
2238 * dereferences of this variable now.
2239 */
2240 }
2241 }
2242 }
2243 }
2244
2245 /**
2246 * Resize tessellation evaluation per-vertex inputs to the size of
2247 * tessellation control per-vertex outputs.
2248 */
2249 static void
2250 resize_tes_inputs(struct gl_context *ctx,
2251 struct gl_shader_program *prog)
2252 {
2253 if (prog->_LinkedShaders[MESA_SHADER_TESS_EVAL] == NULL)
2254 return;
2255
2256 gl_shader *const tcs = prog->_LinkedShaders[MESA_SHADER_TESS_CTRL];
2257 gl_shader *const tes = prog->_LinkedShaders[MESA_SHADER_TESS_EVAL];
2258
2259 /* If no control shader is present, then the TES inputs are statically
2260 * sized to MaxPatchVertices; the actual size of the arrays won't be
2261 * known until draw time.
2262 */
2263 const int num_vertices = tcs
2264 ? tcs->TessCtrl.VerticesOut
2265 : ctx->Const.MaxPatchVertices;
2266
2267 tess_eval_array_resize_visitor input_resize_visitor(num_vertices, prog);
2268 foreach_in_list(ir_instruction, ir, tes->ir) {
2269 ir->accept(&input_resize_visitor);
2270 }
2271 }
2272
2273 /**
2274 * Find a contiguous set of available bits in a bitmask.
2275 *
2276 * \param used_mask Bits representing used (1) and unused (0) locations
2277 * \param needed_count Number of contiguous bits needed.
2278 *
2279 * \return
2280 * Base location of the available bits on success or -1 on failure.
2281 */
2282 int
2283 find_available_slots(unsigned used_mask, unsigned needed_count)
2284 {
2285 unsigned needed_mask = (1 << needed_count) - 1;
2286 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
2287
2288 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2289 * cannot optimize possibly infinite loops" for the loop below.
2290 */
2291 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
2292 return -1;
2293
2294 for (int i = 0; i <= max_bit_to_test; i++) {
2295 if ((needed_mask & ~used_mask) == needed_mask)
2296 return i;
2297
2298 needed_mask <<= 1;
2299 }
2300
2301 return -1;
2302 }
2303
2304
2305 /**
2306 * Assign locations for either VS inputs or FS outputs
2307 *
2308 * \param prog Shader program whose variables need locations assigned
2309 * \param target_index Selector for the program target to receive location
2310 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2311 * \c MESA_SHADER_FRAGMENT.
2312 * \param max_index Maximum number of generic locations. This corresponds
2313 * to either the maximum number of draw buffers or the
2314 * maximum number of generic attributes.
2315 *
2316 * \return
2317 * If locations are successfully assigned, true is returned. Otherwise an
2318 * error is emitted to the shader link log and false is returned.
2319 */
2320 bool
2321 assign_attribute_or_color_locations(gl_shader_program *prog,
2322 unsigned target_index,
2323 unsigned max_index)
2324 {
2325 /* Mark invalid locations as being used.
2326 */
2327 unsigned used_locations = (max_index >= 32)
2328 ? ~0 : ~((1 << max_index) - 1);
2329
2330 assert((target_index == MESA_SHADER_VERTEX)
2331 || (target_index == MESA_SHADER_FRAGMENT));
2332
2333 gl_shader *const sh = prog->_LinkedShaders[target_index];
2334 if (sh == NULL)
2335 return true;
2336
2337 /* Operate in a total of four passes.
2338 *
2339 * 1. Invalidate the location assignments for all vertex shader inputs.
2340 *
2341 * 2. Assign locations for inputs that have user-defined (via
2342 * glBindVertexAttribLocation) locations and outputs that have
2343 * user-defined locations (via glBindFragDataLocation).
2344 *
2345 * 3. Sort the attributes without assigned locations by number of slots
2346 * required in decreasing order. Fragmentation caused by attribute
2347 * locations assigned by the application may prevent large attributes
2348 * from having enough contiguous space.
2349 *
2350 * 4. Assign locations to any inputs without assigned locations.
2351 */
2352
2353 const int generic_base = (target_index == MESA_SHADER_VERTEX)
2354 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
2355
2356 const enum ir_variable_mode direction =
2357 (target_index == MESA_SHADER_VERTEX)
2358 ? ir_var_shader_in : ir_var_shader_out;
2359
2360
2361 /* Temporary storage for the set of attributes that need locations assigned.
2362 */
2363 struct temp_attr {
2364 unsigned slots;
2365 ir_variable *var;
2366
2367 /* Used below in the call to qsort. */
2368 static int compare(const void *a, const void *b)
2369 {
2370 const temp_attr *const l = (const temp_attr *) a;
2371 const temp_attr *const r = (const temp_attr *) b;
2372
2373 /* Reversed because we want a descending order sort below. */
2374 return r->slots - l->slots;
2375 }
2376 } to_assign[16];
2377
2378 unsigned num_attr = 0;
2379 unsigned total_attribs_size = 0;
2380
2381 foreach_in_list(ir_instruction, node, sh->ir) {
2382 ir_variable *const var = node->as_variable();
2383
2384 if ((var == NULL) || (var->data.mode != (unsigned) direction))
2385 continue;
2386
2387 if (var->data.explicit_location) {
2388 if ((var->data.location >= (int)(max_index + generic_base))
2389 || (var->data.location < 0)) {
2390 linker_error(prog,
2391 "invalid explicit location %d specified for `%s'\n",
2392 (var->data.location < 0)
2393 ? var->data.location
2394 : var->data.location - generic_base,
2395 var->name);
2396 return false;
2397 }
2398 } else if (target_index == MESA_SHADER_VERTEX) {
2399 unsigned binding;
2400
2401 if (prog->AttributeBindings->get(binding, var->name)) {
2402 assert(binding >= VERT_ATTRIB_GENERIC0);
2403 var->data.location = binding;
2404 var->data.is_unmatched_generic_inout = 0;
2405 }
2406 } else if (target_index == MESA_SHADER_FRAGMENT) {
2407 unsigned binding;
2408 unsigned index;
2409
2410 if (prog->FragDataBindings->get(binding, var->name)) {
2411 assert(binding >= FRAG_RESULT_DATA0);
2412 var->data.location = binding;
2413 var->data.is_unmatched_generic_inout = 0;
2414
2415 if (prog->FragDataIndexBindings->get(index, var->name)) {
2416 var->data.index = index;
2417 }
2418 }
2419 }
2420
2421 const unsigned slots = var->type->count_attribute_slots();
2422
2423 /* From GL4.5 core spec, section 11.1.1 (Vertex Attributes):
2424 *
2425 * "A program with more than the value of MAX_VERTEX_ATTRIBS active
2426 * attribute variables may fail to link, unless device-dependent
2427 * optimizations are able to make the program fit within available
2428 * hardware resources. For the purposes of this test, attribute variables
2429 * of the type dvec3, dvec4, dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3,
2430 * and dmat4 may count as consuming twice as many attributes as equivalent
2431 * single-precision types. While these types use the same number of
2432 * generic attributes as their single-precision equivalents,
2433 * implementations are permitted to consume two single-precision vectors
2434 * of internal storage for each three- or four-component double-precision
2435 * vector."
2436 * Until someone has a good reason in Mesa, enforce that now.
2437 */
2438 if (target_index == MESA_SHADER_VERTEX) {
2439 total_attribs_size += slots;
2440 if (var->type->without_array() == glsl_type::dvec3_type ||
2441 var->type->without_array() == glsl_type::dvec4_type ||
2442 var->type->without_array() == glsl_type::dmat2x3_type ||
2443 var->type->without_array() == glsl_type::dmat2x4_type ||
2444 var->type->without_array() == glsl_type::dmat3_type ||
2445 var->type->without_array() == glsl_type::dmat3x4_type ||
2446 var->type->without_array() == glsl_type::dmat4x3_type ||
2447 var->type->without_array() == glsl_type::dmat4_type)
2448 total_attribs_size += slots;
2449 }
2450
2451 /* If the variable is not a built-in and has a location statically
2452 * assigned in the shader (presumably via a layout qualifier), make sure
2453 * that it doesn't collide with other assigned locations. Otherwise,
2454 * add it to the list of variables that need linker-assigned locations.
2455 */
2456 if (var->data.location != -1) {
2457 if (var->data.location >= generic_base && var->data.index < 1) {
2458 /* From page 61 of the OpenGL 4.0 spec:
2459 *
2460 * "LinkProgram will fail if the attribute bindings assigned
2461 * by BindAttribLocation do not leave not enough space to
2462 * assign a location for an active matrix attribute or an
2463 * active attribute array, both of which require multiple
2464 * contiguous generic attributes."
2465 *
2466 * I think above text prohibits the aliasing of explicit and
2467 * automatic assignments. But, aliasing is allowed in manual
2468 * assignments of attribute locations. See below comments for
2469 * the details.
2470 *
2471 * From OpenGL 4.0 spec, page 61:
2472 *
2473 * "It is possible for an application to bind more than one
2474 * attribute name to the same location. This is referred to as
2475 * aliasing. This will only work if only one of the aliased
2476 * attributes is active in the executable program, or if no
2477 * path through the shader consumes more than one attribute of
2478 * a set of attributes aliased to the same location. A link
2479 * error can occur if the linker determines that every path
2480 * through the shader consumes multiple aliased attributes,
2481 * but implementations are not required to generate an error
2482 * in this case."
2483 *
2484 * From GLSL 4.30 spec, page 54:
2485 *
2486 * "A program will fail to link if any two non-vertex shader
2487 * input variables are assigned to the same location. For
2488 * vertex shaders, multiple input variables may be assigned
2489 * to the same location using either layout qualifiers or via
2490 * the OpenGL API. However, such aliasing is intended only to
2491 * support vertex shaders where each execution path accesses
2492 * at most one input per each location. Implementations are
2493 * permitted, but not required, to generate link-time errors
2494 * if they detect that every path through the vertex shader
2495 * executable accesses multiple inputs assigned to any single
2496 * location. For all shader types, a program will fail to link
2497 * if explicit location assignments leave the linker unable
2498 * to find space for other variables without explicit
2499 * assignments."
2500 *
2501 * From OpenGL ES 3.0 spec, page 56:
2502 *
2503 * "Binding more than one attribute name to the same location
2504 * is referred to as aliasing, and is not permitted in OpenGL
2505 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2506 * fail when this condition exists. However, aliasing is
2507 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2508 * This will only work if only one of the aliased attributes
2509 * is active in the executable program, or if no path through
2510 * the shader consumes more than one attribute of a set of
2511 * attributes aliased to the same location. A link error can
2512 * occur if the linker determines that every path through the
2513 * shader consumes multiple aliased attributes, but implemen-
2514 * tations are not required to generate an error in this case."
2515 *
2516 * After looking at above references from OpenGL, OpenGL ES and
2517 * GLSL specifications, we allow aliasing of vertex input variables
2518 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2519 *
2520 * NOTE: This is not required by the spec but its worth mentioning
2521 * here that we're not doing anything to make sure that no path
2522 * through the vertex shader executable accesses multiple inputs
2523 * assigned to any single location.
2524 */
2525
2526 /* Mask representing the contiguous slots that will be used by
2527 * this attribute.
2528 */
2529 const unsigned attr = var->data.location - generic_base;
2530 const unsigned use_mask = (1 << slots) - 1;
2531 const char *const string = (target_index == MESA_SHADER_VERTEX)
2532 ? "vertex shader input" : "fragment shader output";
2533
2534 /* Generate a link error if the requested locations for this
2535 * attribute exceed the maximum allowed attribute location.
2536 */
2537 if (attr + slots > max_index) {
2538 linker_error(prog,
2539 "insufficient contiguous locations "
2540 "available for %s `%s' %d %d %d\n", string,
2541 var->name, used_locations, use_mask, attr);
2542 return false;
2543 }
2544
2545 /* Generate a link error if the set of bits requested for this
2546 * attribute overlaps any previously allocated bits.
2547 */
2548 if ((~(use_mask << attr) & used_locations) != used_locations) {
2549 if (target_index == MESA_SHADER_FRAGMENT ||
2550 (prog->IsES && prog->Version >= 300)) {
2551 linker_error(prog,
2552 "overlapping location is assigned "
2553 "to %s `%s' %d %d %d\n", string,
2554 var->name, used_locations, use_mask, attr);
2555 return false;
2556 } else {
2557 linker_warning(prog,
2558 "overlapping location is assigned "
2559 "to %s `%s' %d %d %d\n", string,
2560 var->name, used_locations, use_mask, attr);
2561 }
2562 }
2563
2564 used_locations |= (use_mask << attr);
2565 }
2566
2567 continue;
2568 }
2569
2570 to_assign[num_attr].slots = slots;
2571 to_assign[num_attr].var = var;
2572 num_attr++;
2573 }
2574
2575 if (target_index == MESA_SHADER_VERTEX) {
2576 if (total_attribs_size > max_index) {
2577 linker_error(prog,
2578 "attempt to use %d vertex attribute slots only %d available ",
2579 total_attribs_size, max_index);
2580 return false;
2581 }
2582 }
2583
2584 /* If all of the attributes were assigned locations by the application (or
2585 * are built-in attributes with fixed locations), return early. This should
2586 * be the common case.
2587 */
2588 if (num_attr == 0)
2589 return true;
2590
2591 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
2592
2593 if (target_index == MESA_SHADER_VERTEX) {
2594 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2595 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2596 * reserved to prevent it from being automatically allocated below.
2597 */
2598 find_deref_visitor find("gl_Vertex");
2599 find.run(sh->ir);
2600 if (find.variable_found())
2601 used_locations |= (1 << 0);
2602 }
2603
2604 for (unsigned i = 0; i < num_attr; i++) {
2605 /* Mask representing the contiguous slots that will be used by this
2606 * attribute.
2607 */
2608 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
2609
2610 int location = find_available_slots(used_locations, to_assign[i].slots);
2611
2612 if (location < 0) {
2613 const char *const string = (target_index == MESA_SHADER_VERTEX)
2614 ? "vertex shader input" : "fragment shader output";
2615
2616 linker_error(prog,
2617 "insufficient contiguous locations "
2618 "available for %s `%s'\n",
2619 string, to_assign[i].var->name);
2620 return false;
2621 }
2622
2623 to_assign[i].var->data.location = generic_base + location;
2624 to_assign[i].var->data.is_unmatched_generic_inout = 0;
2625 used_locations |= (use_mask << location);
2626 }
2627
2628 return true;
2629 }
2630
2631
2632 /**
2633 * Demote shader inputs and outputs that are not used in other stages
2634 */
2635 void
2636 demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
2637 {
2638 foreach_in_list(ir_instruction, node, sh->ir) {
2639 ir_variable *const var = node->as_variable();
2640
2641 if ((var == NULL) || (var->data.mode != int(mode)))
2642 continue;
2643
2644 /* A shader 'in' or 'out' variable is only really an input or output if
2645 * its value is used by other shader stages. This will cause the variable
2646 * to have a location assigned.
2647 */
2648 if (var->data.is_unmatched_generic_inout) {
2649 assert(var->data.mode != ir_var_temporary);
2650 var->data.mode = ir_var_auto;
2651 }
2652 }
2653 }
2654
2655
2656 /**
2657 * Store the gl_FragDepth layout in the gl_shader_program struct.
2658 */
2659 static void
2660 store_fragdepth_layout(struct gl_shader_program *prog)
2661 {
2662 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2663 return;
2664 }
2665
2666 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2667
2668 /* We don't look up the gl_FragDepth symbol directly because if
2669 * gl_FragDepth is not used in the shader, it's removed from the IR.
2670 * However, the symbol won't be removed from the symbol table.
2671 *
2672 * We're only interested in the cases where the variable is NOT removed
2673 * from the IR.
2674 */
2675 foreach_in_list(ir_instruction, node, ir) {
2676 ir_variable *const var = node->as_variable();
2677
2678 if (var == NULL || var->data.mode != ir_var_shader_out) {
2679 continue;
2680 }
2681
2682 if (strcmp(var->name, "gl_FragDepth") == 0) {
2683 switch (var->data.depth_layout) {
2684 case ir_depth_layout_none:
2685 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2686 return;
2687 case ir_depth_layout_any:
2688 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2689 return;
2690 case ir_depth_layout_greater:
2691 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2692 return;
2693 case ir_depth_layout_less:
2694 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2695 return;
2696 case ir_depth_layout_unchanged:
2697 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2698 return;
2699 default:
2700 assert(0);
2701 return;
2702 }
2703 }
2704 }
2705 }
2706
2707 /**
2708 * Validate the resources used by a program versus the implementation limits
2709 */
2710 static void
2711 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2712 {
2713 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2714 struct gl_shader *sh = prog->_LinkedShaders[i];
2715
2716 if (sh == NULL)
2717 continue;
2718
2719 if (sh->num_samplers > ctx->Const.Program[i].MaxTextureImageUnits) {
2720 linker_error(prog, "Too many %s shader texture samplers\n",
2721 _mesa_shader_stage_to_string(i));
2722 }
2723
2724 if (sh->num_uniform_components >
2725 ctx->Const.Program[i].MaxUniformComponents) {
2726 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2727 linker_warning(prog, "Too many %s shader default uniform block "
2728 "components, but the driver will try to optimize "
2729 "them out; this is non-portable out-of-spec "
2730 "behavior\n",
2731 _mesa_shader_stage_to_string(i));
2732 } else {
2733 linker_error(prog, "Too many %s shader default uniform block "
2734 "components\n",
2735 _mesa_shader_stage_to_string(i));
2736 }
2737 }
2738
2739 if (sh->num_combined_uniform_components >
2740 ctx->Const.Program[i].MaxCombinedUniformComponents) {
2741 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2742 linker_warning(prog, "Too many %s shader uniform components, "
2743 "but the driver will try to optimize them out; "
2744 "this is non-portable out-of-spec behavior\n",
2745 _mesa_shader_stage_to_string(i));
2746 } else {
2747 linker_error(prog, "Too many %s shader uniform components\n",
2748 _mesa_shader_stage_to_string(i));
2749 }
2750 }
2751 }
2752
2753 unsigned blocks[MESA_SHADER_STAGES] = {0};
2754 unsigned total_uniform_blocks = 0;
2755
2756 for (unsigned i = 0; i < prog->NumUniformBlocks; i++) {
2757 if (prog->UniformBlocks[i].UniformBufferSize > ctx->Const.MaxUniformBlockSize) {
2758 linker_error(prog, "Uniform block %s too big (%d/%d)\n",
2759 prog->UniformBlocks[i].Name,
2760 prog->UniformBlocks[i].UniformBufferSize,
2761 ctx->Const.MaxUniformBlockSize);
2762 }
2763
2764 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
2765 if (prog->UniformBlockStageIndex[j][i] != -1) {
2766 blocks[j]++;
2767 total_uniform_blocks++;
2768 }
2769 }
2770
2771 if (total_uniform_blocks > ctx->Const.MaxCombinedUniformBlocks) {
2772 linker_error(prog, "Too many combined uniform blocks (%d/%d)\n",
2773 prog->NumUniformBlocks,
2774 ctx->Const.MaxCombinedUniformBlocks);
2775 } else {
2776 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2777 const unsigned max_uniform_blocks =
2778 ctx->Const.Program[i].MaxUniformBlocks;
2779 if (blocks[i] > max_uniform_blocks) {
2780 linker_error(prog, "Too many %s uniform blocks (%d/%d)\n",
2781 _mesa_shader_stage_to_string(i),
2782 blocks[i],
2783 max_uniform_blocks);
2784 break;
2785 }
2786 }
2787 }
2788 }
2789 }
2790
2791 /**
2792 * Validate shader image resources.
2793 */
2794 static void
2795 check_image_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2796 {
2797 unsigned total_image_units = 0;
2798 unsigned fragment_outputs = 0;
2799
2800 if (!ctx->Extensions.ARB_shader_image_load_store)
2801 return;
2802
2803 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2804 struct gl_shader *sh = prog->_LinkedShaders[i];
2805
2806 if (sh) {
2807 if (sh->NumImages > ctx->Const.Program[i].MaxImageUniforms)
2808 linker_error(prog, "Too many %s shader image uniforms\n",
2809 _mesa_shader_stage_to_string(i));
2810
2811 total_image_units += sh->NumImages;
2812
2813 if (i == MESA_SHADER_FRAGMENT) {
2814 foreach_in_list(ir_instruction, node, sh->ir) {
2815 ir_variable *var = node->as_variable();
2816 if (var && var->data.mode == ir_var_shader_out)
2817 fragment_outputs += var->type->count_attribute_slots();
2818 }
2819 }
2820 }
2821 }
2822
2823 if (total_image_units > ctx->Const.MaxCombinedImageUniforms)
2824 linker_error(prog, "Too many combined image uniforms\n");
2825
2826 if (total_image_units + fragment_outputs >
2827 ctx->Const.MaxCombinedImageUnitsAndFragmentOutputs)
2828 linker_error(prog, "Too many combined image uniforms and fragment outputs\n");
2829 }
2830
2831
2832 /**
2833 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
2834 * for a variable, checks for overlaps between other uniforms using explicit
2835 * locations.
2836 */
2837 static bool
2838 reserve_explicit_locations(struct gl_shader_program *prog,
2839 string_to_uint_map *map, ir_variable *var)
2840 {
2841 unsigned slots = var->type->uniform_locations();
2842 unsigned max_loc = var->data.location + slots - 1;
2843
2844 /* Resize remap table if locations do not fit in the current one. */
2845 if (max_loc + 1 > prog->NumUniformRemapTable) {
2846 prog->UniformRemapTable =
2847 reralloc(prog, prog->UniformRemapTable,
2848 gl_uniform_storage *,
2849 max_loc + 1);
2850
2851 if (!prog->UniformRemapTable) {
2852 linker_error(prog, "Out of memory during linking.\n");
2853 return false;
2854 }
2855
2856 /* Initialize allocated space. */
2857 for (unsigned i = prog->NumUniformRemapTable; i < max_loc + 1; i++)
2858 prog->UniformRemapTable[i] = NULL;
2859
2860 prog->NumUniformRemapTable = max_loc + 1;
2861 }
2862
2863 for (unsigned i = 0; i < slots; i++) {
2864 unsigned loc = var->data.location + i;
2865
2866 /* Check if location is already used. */
2867 if (prog->UniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
2868
2869 /* Possibly same uniform from a different stage, this is ok. */
2870 unsigned hash_loc;
2871 if (map->get(hash_loc, var->name) && hash_loc == loc - i)
2872 continue;
2873
2874 /* ARB_explicit_uniform_location specification states:
2875 *
2876 * "No two default-block uniform variables in the program can have
2877 * the same location, even if they are unused, otherwise a compiler
2878 * or linker error will be generated."
2879 */
2880 linker_error(prog,
2881 "location qualifier for uniform %s overlaps "
2882 "previously used location\n",
2883 var->name);
2884 return false;
2885 }
2886
2887 /* Initialize location as inactive before optimization
2888 * rounds and location assignment.
2889 */
2890 prog->UniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
2891 }
2892
2893 /* Note, base location used for arrays. */
2894 map->put(var->data.location, var->name);
2895
2896 return true;
2897 }
2898
2899 /**
2900 * Check and reserve all explicit uniform locations, called before
2901 * any optimizations happen to handle also inactive uniforms and
2902 * inactive array elements that may get trimmed away.
2903 */
2904 static void
2905 check_explicit_uniform_locations(struct gl_context *ctx,
2906 struct gl_shader_program *prog)
2907 {
2908 if (!ctx->Extensions.ARB_explicit_uniform_location)
2909 return;
2910
2911 /* This map is used to detect if overlapping explicit locations
2912 * occur with the same uniform (from different stage) or a different one.
2913 */
2914 string_to_uint_map *uniform_map = new string_to_uint_map;
2915
2916 if (!uniform_map) {
2917 linker_error(prog, "Out of memory during linking.\n");
2918 return;
2919 }
2920
2921 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2922 struct gl_shader *sh = prog->_LinkedShaders[i];
2923
2924 if (!sh)
2925 continue;
2926
2927 foreach_in_list(ir_instruction, node, sh->ir) {
2928 ir_variable *var = node->as_variable();
2929 if (var && (var->data.mode == ir_var_uniform || var->data.mode == ir_var_shader_storage) &&
2930 var->data.explicit_location) {
2931 if (!reserve_explicit_locations(prog, uniform_map, var)) {
2932 delete uniform_map;
2933 return;
2934 }
2935 }
2936 }
2937 }
2938
2939 delete uniform_map;
2940 }
2941
2942 static bool
2943 add_program_resource(struct gl_shader_program *prog, GLenum type,
2944 const void *data, uint8_t stages)
2945 {
2946 assert(data);
2947
2948 /* If resource already exists, do not add it again. */
2949 for (unsigned i = 0; i < prog->NumProgramResourceList; i++)
2950 if (prog->ProgramResourceList[i].Data == data)
2951 return true;
2952
2953 prog->ProgramResourceList =
2954 reralloc(prog,
2955 prog->ProgramResourceList,
2956 gl_program_resource,
2957 prog->NumProgramResourceList + 1);
2958
2959 if (!prog->ProgramResourceList) {
2960 linker_error(prog, "Out of memory during linking.\n");
2961 return false;
2962 }
2963
2964 struct gl_program_resource *res =
2965 &prog->ProgramResourceList[prog->NumProgramResourceList];
2966
2967 res->Type = type;
2968 res->Data = data;
2969 res->StageReferences = stages;
2970
2971 prog->NumProgramResourceList++;
2972
2973 return true;
2974 }
2975
2976 /**
2977 * Function builds a stage reference bitmask from variable name.
2978 */
2979 static uint8_t
2980 build_stageref(struct gl_shader_program *shProg, const char *name)
2981 {
2982 uint8_t stages = 0;
2983
2984 /* Note, that we assume MAX 8 stages, if there will be more stages, type
2985 * used for reference mask in gl_program_resource will need to be changed.
2986 */
2987 assert(MESA_SHADER_STAGES < 8);
2988
2989 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2990 struct gl_shader *sh = shProg->_LinkedShaders[i];
2991 if (!sh)
2992 continue;
2993
2994 /* Shader symbol table may contain variables that have
2995 * been optimized away. Search IR for the variable instead.
2996 */
2997 foreach_in_list(ir_instruction, node, sh->ir) {
2998 ir_variable *var = node->as_variable();
2999 if (var && strcmp(var->name, name) == 0) {
3000 stages |= (1 << i);
3001 break;
3002 }
3003 }
3004 }
3005 return stages;
3006 }
3007
3008 static bool
3009 add_interface_variables(struct gl_shader_program *shProg,
3010 struct gl_shader *sh, GLenum programInterface)
3011 {
3012 foreach_in_list(ir_instruction, node, sh->ir) {
3013 ir_variable *var = node->as_variable();
3014 uint8_t mask = 0;
3015
3016 if (!var)
3017 continue;
3018
3019 switch (var->data.mode) {
3020 /* From GL 4.3 core spec, section 11.1.1 (Vertex Attributes):
3021 * "For GetActiveAttrib, all active vertex shader input variables
3022 * are enumerated, including the special built-in inputs gl_VertexID
3023 * and gl_InstanceID."
3024 */
3025 case ir_var_system_value:
3026 if (var->data.location != SYSTEM_VALUE_VERTEX_ID &&
3027 var->data.location != SYSTEM_VALUE_VERTEX_ID_ZERO_BASE &&
3028 var->data.location != SYSTEM_VALUE_INSTANCE_ID)
3029 continue;
3030 /* Mark special built-in inputs referenced by the vertex stage so
3031 * that they are considered active by the shader queries.
3032 */
3033 mask = (1 << (MESA_SHADER_VERTEX));
3034 /* FALLTHROUGH */
3035 case ir_var_shader_in:
3036 if (programInterface != GL_PROGRAM_INPUT)
3037 continue;
3038 break;
3039 case ir_var_shader_out:
3040 if (programInterface != GL_PROGRAM_OUTPUT)
3041 continue;
3042 break;
3043 default:
3044 continue;
3045 };
3046
3047 if (!add_program_resource(shProg, programInterface, var,
3048 build_stageref(shProg, var->name) | mask))
3049 return false;
3050 }
3051 return true;
3052 }
3053
3054 /**
3055 * Builds up a list of program resources that point to existing
3056 * resource data.
3057 */
3058 void
3059 build_program_resource_list(struct gl_context *ctx,
3060 struct gl_shader_program *shProg)
3061 {
3062 /* Rebuild resource list. */
3063 if (shProg->ProgramResourceList) {
3064 ralloc_free(shProg->ProgramResourceList);
3065 shProg->ProgramResourceList = NULL;
3066 shProg->NumProgramResourceList = 0;
3067 }
3068
3069 int input_stage = MESA_SHADER_STAGES, output_stage = 0;
3070
3071 /* Determine first input and final output stage. These are used to
3072 * detect which variables should be enumerated in the resource list
3073 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
3074 */
3075 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3076 if (!shProg->_LinkedShaders[i])
3077 continue;
3078 if (input_stage == MESA_SHADER_STAGES)
3079 input_stage = i;
3080 output_stage = i;
3081 }
3082
3083 /* Empty shader, no resources. */
3084 if (input_stage == MESA_SHADER_STAGES && output_stage == 0)
3085 return;
3086
3087 /* Add inputs and outputs to the resource list. */
3088 if (!add_interface_variables(shProg, shProg->_LinkedShaders[input_stage],
3089 GL_PROGRAM_INPUT))
3090 return;
3091
3092 if (!add_interface_variables(shProg, shProg->_LinkedShaders[output_stage],
3093 GL_PROGRAM_OUTPUT))
3094 return;
3095
3096 /* Add transform feedback varyings. */
3097 if (shProg->LinkedTransformFeedback.NumVarying > 0) {
3098 for (int i = 0; i < shProg->LinkedTransformFeedback.NumVarying; i++) {
3099 uint8_t stageref =
3100 build_stageref(shProg,
3101 shProg->LinkedTransformFeedback.Varyings[i].Name);
3102 if (!add_program_resource(shProg, GL_TRANSFORM_FEEDBACK_VARYING,
3103 &shProg->LinkedTransformFeedback.Varyings[i],
3104 stageref))
3105 return;
3106 }
3107 }
3108
3109 /* Add uniforms from uniform storage. */
3110 for (unsigned i = 0; i < shProg->NumUniformStorage; i++) {
3111 /* Do not add uniforms internally used by Mesa. */
3112 if (shProg->UniformStorage[i].hidden)
3113 continue;
3114
3115 uint8_t stageref =
3116 build_stageref(shProg, shProg->UniformStorage[i].name);
3117
3118 /* Add stagereferences for uniforms in a uniform block. */
3119 int block_index = shProg->UniformStorage[i].block_index;
3120 if (block_index != -1) {
3121 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
3122 if (shProg->UniformBlockStageIndex[j][block_index] != -1)
3123 stageref |= (1 << j);
3124 }
3125 }
3126
3127 if (!add_program_resource(shProg, GL_UNIFORM,
3128 &shProg->UniformStorage[i], stageref))
3129 return;
3130 }
3131
3132 /* Add program uniform blocks. */
3133 for (unsigned i = 0; i < shProg->NumUniformBlocks; i++) {
3134 if (!add_program_resource(shProg, GL_UNIFORM_BLOCK,
3135 &shProg->UniformBlocks[i], 0))
3136 return;
3137 }
3138
3139 /* Add atomic counter buffers. */
3140 for (unsigned i = 0; i < shProg->NumAtomicBuffers; i++) {
3141 if (!add_program_resource(shProg, GL_ATOMIC_COUNTER_BUFFER,
3142 &shProg->AtomicBuffers[i], 0))
3143 return;
3144 }
3145
3146 /* TODO - following extensions will require more resource types:
3147 *
3148 * GL_ARB_shader_storage_buffer_object
3149 * GL_ARB_shader_subroutine
3150 */
3151 }
3152
3153 /**
3154 * This check is done to make sure we allow only constant expression
3155 * indexing and "constant-index-expression" (indexing with an expression
3156 * that includes loop induction variable).
3157 */
3158 static bool
3159 validate_sampler_array_indexing(struct gl_context *ctx,
3160 struct gl_shader_program *prog)
3161 {
3162 dynamic_sampler_array_indexing_visitor v;
3163 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3164 if (prog->_LinkedShaders[i] == NULL)
3165 continue;
3166
3167 bool no_dynamic_indexing =
3168 ctx->Const.ShaderCompilerOptions[i].EmitNoIndirectSampler;
3169
3170 /* Search for array derefs in shader. */
3171 v.run(prog->_LinkedShaders[i]->ir);
3172 if (v.uses_dynamic_sampler_array_indexing()) {
3173 const char *msg = "sampler arrays indexed with non-constant "
3174 "expressions is forbidden in GLSL %s %u";
3175 /* Backend has indicated that it has no dynamic indexing support. */
3176 if (no_dynamic_indexing) {
3177 linker_error(prog, msg, prog->IsES ? "ES" : "", prog->Version);
3178 return false;
3179 } else {
3180 linker_warning(prog, msg, prog->IsES ? "ES" : "", prog->Version);
3181 }
3182 }
3183 }
3184 return true;
3185 }
3186
3187
3188 void
3189 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
3190 {
3191 tfeedback_decl *tfeedback_decls = NULL;
3192 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
3193
3194 void *mem_ctx = ralloc_context(NULL); // temporary linker context
3195
3196 prog->LinkStatus = true; /* All error paths will set this to false */
3197 prog->Validated = false;
3198 prog->_Used = false;
3199
3200 prog->ARB_fragment_coord_conventions_enable = false;
3201
3202 /* Separate the shaders into groups based on their type.
3203 */
3204 struct gl_shader **shader_list[MESA_SHADER_STAGES];
3205 unsigned num_shaders[MESA_SHADER_STAGES];
3206
3207 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
3208 shader_list[i] = (struct gl_shader **)
3209 calloc(prog->NumShaders, sizeof(struct gl_shader *));
3210 num_shaders[i] = 0;
3211 }
3212
3213 unsigned min_version = UINT_MAX;
3214 unsigned max_version = 0;
3215 const bool is_es_prog =
3216 (prog->NumShaders > 0 && prog->Shaders[0]->IsES) ? true : false;
3217 for (unsigned i = 0; i < prog->NumShaders; i++) {
3218 min_version = MIN2(min_version, prog->Shaders[i]->Version);
3219 max_version = MAX2(max_version, prog->Shaders[i]->Version);
3220
3221 if (prog->Shaders[i]->IsES != is_es_prog) {
3222 linker_error(prog, "all shaders must use same shading "
3223 "language version\n");
3224 goto done;
3225 }
3226
3227 if (prog->Shaders[i]->ARB_fragment_coord_conventions_enable) {
3228 prog->ARB_fragment_coord_conventions_enable = true;
3229 }
3230
3231 gl_shader_stage shader_type = prog->Shaders[i]->Stage;
3232 shader_list[shader_type][num_shaders[shader_type]] = prog->Shaders[i];
3233 num_shaders[shader_type]++;
3234 }
3235
3236 /* In desktop GLSL, different shader versions may be linked together. In
3237 * GLSL ES, all shader versions must be the same.
3238 */
3239 if (is_es_prog && min_version != max_version) {
3240 linker_error(prog, "all shaders must use same shading "
3241 "language version\n");
3242 goto done;
3243 }
3244
3245 prog->Version = max_version;
3246 prog->IsES = is_es_prog;
3247
3248 /* Some shaders have to be linked with some other shaders present.
3249 */
3250 if (num_shaders[MESA_SHADER_GEOMETRY] > 0 &&
3251 num_shaders[MESA_SHADER_VERTEX] == 0 &&
3252 !prog->SeparateShader) {
3253 linker_error(prog, "Geometry shader must be linked with "
3254 "vertex shader\n");
3255 goto done;
3256 }
3257 if (num_shaders[MESA_SHADER_TESS_EVAL] > 0 &&
3258 num_shaders[MESA_SHADER_VERTEX] == 0 &&
3259 !prog->SeparateShader) {
3260 linker_error(prog, "Tessellation evaluation shader must be linked with "
3261 "vertex shader\n");
3262 goto done;
3263 }
3264 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
3265 num_shaders[MESA_SHADER_VERTEX] == 0 &&
3266 !prog->SeparateShader) {
3267 linker_error(prog, "Tessellation control shader must be linked with "
3268 "vertex shader\n");
3269 goto done;
3270 }
3271
3272 /* The spec is self-contradictory here. It allows linking without a tess
3273 * eval shader, but that can only be used with transform feedback and
3274 * rasterization disabled. However, transform feedback isn't allowed
3275 * with GL_PATCHES, so it can't be used.
3276 *
3277 * More investigation showed that the idea of transform feedback after
3278 * a tess control shader was dropped, because some hw vendors couldn't
3279 * support tessellation without a tess eval shader, but the linker section
3280 * wasn't updated to reflect that.
3281 *
3282 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
3283 * spec bug.
3284 *
3285 * Do what's reasonable and always require a tess eval shader if a tess
3286 * control shader is present.
3287 */
3288 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
3289 num_shaders[MESA_SHADER_TESS_EVAL] == 0 &&
3290 !prog->SeparateShader) {
3291 linker_error(prog, "Tessellation control shader must be linked with "
3292 "tessellation evaluation shader\n");
3293 goto done;
3294 }
3295
3296 /* Compute shaders have additional restrictions. */
3297 if (num_shaders[MESA_SHADER_COMPUTE] > 0 &&
3298 num_shaders[MESA_SHADER_COMPUTE] != prog->NumShaders) {
3299 linker_error(prog, "Compute shaders may not be linked with any other "
3300 "type of shader\n");
3301 }
3302
3303 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
3304 if (prog->_LinkedShaders[i] != NULL)
3305 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
3306
3307 prog->_LinkedShaders[i] = NULL;
3308 }
3309
3310 /* Link all shaders for a particular stage and validate the result.
3311 */
3312 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
3313 if (num_shaders[stage] > 0) {
3314 gl_shader *const sh =
3315 link_intrastage_shaders(mem_ctx, ctx, prog, shader_list[stage],
3316 num_shaders[stage]);
3317
3318 if (!prog->LinkStatus) {
3319 if (sh)
3320 ctx->Driver.DeleteShader(ctx, sh);
3321 goto done;
3322 }
3323
3324 switch (stage) {
3325 case MESA_SHADER_VERTEX:
3326 validate_vertex_shader_executable(prog, sh);
3327 break;
3328 case MESA_SHADER_TESS_CTRL:
3329 /* nothing to be done */
3330 break;
3331 case MESA_SHADER_TESS_EVAL:
3332 validate_tess_eval_shader_executable(prog, sh);
3333 break;
3334 case MESA_SHADER_GEOMETRY:
3335 validate_geometry_shader_executable(prog, sh);
3336 break;
3337 case MESA_SHADER_FRAGMENT:
3338 validate_fragment_shader_executable(prog, sh);
3339 break;
3340 }
3341 if (!prog->LinkStatus) {
3342 if (sh)
3343 ctx->Driver.DeleteShader(ctx, sh);
3344 goto done;
3345 }
3346
3347 _mesa_reference_shader(ctx, &prog->_LinkedShaders[stage], sh);
3348 }
3349 }
3350
3351 if (num_shaders[MESA_SHADER_GEOMETRY] > 0)
3352 prog->LastClipDistanceArraySize = prog->Geom.ClipDistanceArraySize;
3353 else if (num_shaders[MESA_SHADER_TESS_EVAL] > 0)
3354 prog->LastClipDistanceArraySize = prog->TessEval.ClipDistanceArraySize;
3355 else if (num_shaders[MESA_SHADER_VERTEX] > 0)
3356 prog->LastClipDistanceArraySize = prog->Vert.ClipDistanceArraySize;
3357 else
3358 prog->LastClipDistanceArraySize = 0; /* Not used */
3359
3360 /* Here begins the inter-stage linking phase. Some initial validation is
3361 * performed, then locations are assigned for uniforms, attributes, and
3362 * varyings.
3363 */
3364 cross_validate_uniforms(prog);
3365 if (!prog->LinkStatus)
3366 goto done;
3367
3368 unsigned prev;
3369
3370 for (prev = 0; prev <= MESA_SHADER_FRAGMENT; prev++) {
3371 if (prog->_LinkedShaders[prev] != NULL)
3372 break;
3373 }
3374
3375 check_explicit_uniform_locations(ctx, prog);
3376 if (!prog->LinkStatus)
3377 goto done;
3378
3379 resize_tes_inputs(ctx, prog);
3380
3381 /* Validate the inputs of each stage with the output of the preceding
3382 * stage.
3383 */
3384 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
3385 if (prog->_LinkedShaders[i] == NULL)
3386 continue;
3387
3388 validate_interstage_inout_blocks(prog, prog->_LinkedShaders[prev],
3389 prog->_LinkedShaders[i]);
3390 if (!prog->LinkStatus)
3391 goto done;
3392
3393 cross_validate_outputs_to_inputs(prog,
3394 prog->_LinkedShaders[prev],
3395 prog->_LinkedShaders[i]);
3396 if (!prog->LinkStatus)
3397 goto done;
3398
3399 prev = i;
3400 }
3401
3402 /* Cross-validate uniform blocks between shader stages */
3403 validate_interstage_uniform_blocks(prog, prog->_LinkedShaders,
3404 MESA_SHADER_STAGES);
3405 if (!prog->LinkStatus)
3406 goto done;
3407
3408 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
3409 if (prog->_LinkedShaders[i] != NULL)
3410 lower_named_interface_blocks(mem_ctx, prog->_LinkedShaders[i]);
3411 }
3412
3413 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
3414 * it before optimization because we want most of the checks to get
3415 * dropped thanks to constant propagation.
3416 *
3417 * This rule also applies to GLSL ES 3.00.
3418 */
3419 if (max_version >= (is_es_prog ? 300 : 130)) {
3420 struct gl_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
3421 if (sh) {
3422 lower_discard_flow(sh->ir);
3423 }
3424 }
3425
3426 if (!interstage_cross_validate_uniform_blocks(prog))
3427 goto done;
3428
3429 /* Do common optimization before assigning storage for attributes,
3430 * uniforms, and varyings. Later optimization could possibly make
3431 * some of that unused.
3432 */
3433 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3434 if (prog->_LinkedShaders[i] == NULL)
3435 continue;
3436
3437 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
3438 if (!prog->LinkStatus)
3439 goto done;
3440
3441 if (ctx->Const.ShaderCompilerOptions[i].LowerClipDistance) {
3442 lower_clip_distance(prog->_LinkedShaders[i]);
3443 }
3444
3445 if (ctx->Const.LowerTessLevel) {
3446 lower_tess_level(prog->_LinkedShaders[i]);
3447 }
3448
3449 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false,
3450 &ctx->Const.ShaderCompilerOptions[i],
3451 ctx->Const.NativeIntegers))
3452 ;
3453
3454 lower_const_arrays_to_uniforms(prog->_LinkedShaders[i]->ir);
3455 }
3456
3457 /* Validation for special cases where we allow sampler array indexing
3458 * with loop induction variable. This check emits a warning or error
3459 * depending if backend can handle dynamic indexing.
3460 */
3461 if ((!prog->IsES && prog->Version < 130) ||
3462 (prog->IsES && prog->Version < 300)) {
3463 if (!validate_sampler_array_indexing(ctx, prog))
3464 goto done;
3465 }
3466
3467 /* Check and validate stream emissions in geometry shaders */
3468 validate_geometry_shader_emissions(ctx, prog);
3469
3470 /* Mark all generic shader inputs and outputs as unpaired. */
3471 for (unsigned i = MESA_SHADER_VERTEX; i <= MESA_SHADER_FRAGMENT; i++) {
3472 if (prog->_LinkedShaders[i] != NULL) {
3473 link_invalidate_variable_locations(prog->_LinkedShaders[i]->ir);
3474 }
3475 }
3476
3477 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX,
3478 ctx->Const.Program[MESA_SHADER_VERTEX].MaxAttribs)) {
3479 goto done;
3480 }
3481
3482 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, MAX2(ctx->Const.MaxDrawBuffers, ctx->Const.MaxDualSourceDrawBuffers))) {
3483 goto done;
3484 }
3485
3486 unsigned first, last;
3487
3488 first = MESA_SHADER_STAGES;
3489 last = 0;
3490
3491 /* Determine first and last stage. */
3492 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3493 if (!prog->_LinkedShaders[i])
3494 continue;
3495 if (first == MESA_SHADER_STAGES)
3496 first = i;
3497 last = i;
3498 }
3499
3500 if (num_tfeedback_decls != 0) {
3501 /* From GL_EXT_transform_feedback:
3502 * A program will fail to link if:
3503 *
3504 * * the <count> specified by TransformFeedbackVaryingsEXT is
3505 * non-zero, but the program object has no vertex or geometry
3506 * shader;
3507 */
3508 if (first == MESA_SHADER_FRAGMENT) {
3509 linker_error(prog, "Transform feedback varyings specified, but "
3510 "no vertex or geometry shader is present.\n");
3511 goto done;
3512 }
3513
3514 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
3515 prog->TransformFeedback.NumVarying);
3516 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
3517 prog->TransformFeedback.VaryingNames,
3518 tfeedback_decls))
3519 goto done;
3520 }
3521
3522 /* Linking the stages in the opposite order (from fragment to vertex)
3523 * ensures that inter-shader outputs written to in an earlier stage are
3524 * eliminated if they are (transitively) not used in a later stage.
3525 */
3526 int next;
3527
3528 if (first < MESA_SHADER_FRAGMENT) {
3529 gl_shader *const sh = prog->_LinkedShaders[last];
3530
3531 if (first == MESA_SHADER_GEOMETRY) {
3532 /* There was no vertex shader, but we still have to assign varying
3533 * locations for use by geometry shader inputs in SSO.
3534 *
3535 * If the shader is not separable (i.e., prog->SeparateShader is
3536 * false), linking will have already failed when first is
3537 * MESA_SHADER_GEOMETRY.
3538 */
3539 if (!assign_varying_locations(ctx, mem_ctx, prog,
3540 NULL, prog->_LinkedShaders[first],
3541 num_tfeedback_decls, tfeedback_decls))
3542 goto done;
3543 }
3544
3545 if (last != MESA_SHADER_FRAGMENT &&
3546 (num_tfeedback_decls != 0 || prog->SeparateShader)) {
3547 /* There was no fragment shader, but we still have to assign varying
3548 * locations for use by transform feedback.
3549 */
3550 if (!assign_varying_locations(ctx, mem_ctx, prog,
3551 sh, NULL,
3552 num_tfeedback_decls, tfeedback_decls))
3553 goto done;
3554 }
3555
3556 do_dead_builtin_varyings(ctx, sh, NULL,
3557 num_tfeedback_decls, tfeedback_decls);
3558
3559 if (!prog->SeparateShader)
3560 demote_shader_inputs_and_outputs(sh, ir_var_shader_out);
3561
3562 /* Eliminate code that is now dead due to unused outputs being demoted.
3563 */
3564 while (do_dead_code(sh->ir, false))
3565 ;
3566 }
3567 else if (first == MESA_SHADER_FRAGMENT) {
3568 /* If the program only contains a fragment shader...
3569 */
3570 gl_shader *const sh = prog->_LinkedShaders[first];
3571
3572 do_dead_builtin_varyings(ctx, NULL, sh,
3573 num_tfeedback_decls, tfeedback_decls);
3574
3575 if (prog->SeparateShader) {
3576 if (!assign_varying_locations(ctx, mem_ctx, prog,
3577 NULL /* producer */,
3578 sh /* consumer */,
3579 0 /* num_tfeedback_decls */,
3580 NULL /* tfeedback_decls */))
3581 goto done;
3582 } else
3583 demote_shader_inputs_and_outputs(sh, ir_var_shader_in);
3584
3585 while (do_dead_code(sh->ir, false))
3586 ;
3587 }
3588
3589 next = last;
3590 for (int i = next - 1; i >= 0; i--) {
3591 if (prog->_LinkedShaders[i] == NULL)
3592 continue;
3593
3594 gl_shader *const sh_i = prog->_LinkedShaders[i];
3595 gl_shader *const sh_next = prog->_LinkedShaders[next];
3596
3597 if (!assign_varying_locations(ctx, mem_ctx, prog, sh_i, sh_next,
3598 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
3599 tfeedback_decls))
3600 goto done;
3601
3602 do_dead_builtin_varyings(ctx, sh_i, sh_next,
3603 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
3604 tfeedback_decls);
3605
3606 demote_shader_inputs_and_outputs(sh_i, ir_var_shader_out);
3607 demote_shader_inputs_and_outputs(sh_next, ir_var_shader_in);
3608
3609 /* Eliminate code that is now dead due to unused outputs being demoted.
3610 */
3611 while (do_dead_code(sh_i->ir, false))
3612 ;
3613 while (do_dead_code(sh_next->ir, false))
3614 ;
3615
3616 /* This must be done after all dead varyings are eliminated. */
3617 if (!check_against_output_limit(ctx, prog, sh_i))
3618 goto done;
3619 if (!check_against_input_limit(ctx, prog, sh_next))
3620 goto done;
3621
3622 next = i;
3623 }
3624
3625 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
3626 goto done;
3627
3628 update_array_sizes(prog);
3629 link_assign_uniform_locations(prog, ctx->Const.UniformBooleanTrue);
3630 link_assign_atomic_counter_resources(ctx, prog);
3631 store_fragdepth_layout(prog);
3632
3633 check_resources(ctx, prog);
3634 check_image_resources(ctx, prog);
3635 link_check_atomic_counter_resources(ctx, prog);
3636
3637 if (!prog->LinkStatus)
3638 goto done;
3639
3640 /* OpenGL ES requires that a vertex shader and a fragment shader both be
3641 * present in a linked program. GL_ARB_ES2_compatibility doesn't say
3642 * anything about shader linking when one of the shaders (vertex or
3643 * fragment shader) is absent. So, the extension shouldn't change the
3644 * behavior specified in GLSL specification.
3645 */
3646 if (!prog->SeparateShader && ctx->API == API_OPENGLES2) {
3647 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
3648 linker_error(prog, "program lacks a vertex shader\n");
3649 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
3650 linker_error(prog, "program lacks a fragment shader\n");
3651 }
3652 }
3653
3654 /* FINISHME: Assign fragment shader output locations. */
3655
3656 done:
3657 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3658 free(shader_list[i]);
3659 if (prog->_LinkedShaders[i] == NULL)
3660 continue;
3661
3662 /* Do a final validation step to make sure that the IR wasn't
3663 * invalidated by any modifications performed after intrastage linking.
3664 */
3665 validate_ir_tree(prog->_LinkedShaders[i]->ir);
3666
3667 /* Retain any live IR, but trash the rest. */
3668 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
3669
3670 /* The symbol table in the linked shaders may contain references to
3671 * variables that were removed (e.g., unused uniforms). Since it may
3672 * contain junk, there is no possible valid use. Delete it and set the
3673 * pointer to NULL.
3674 */
3675 delete prog->_LinkedShaders[i]->symbols;
3676 prog->_LinkedShaders[i]->symbols = NULL;
3677 }
3678
3679 ralloc_free(mem_ctx);
3680 }