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