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