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