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