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