3036ebcb33e11d967283e8d809e933b3ccca1998
[mesa.git] / src / glsl / linker.cpp
1 /*
2 * Copyright © 2010 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
22 */
23
24 /**
25 * \file linker.cpp
26 * GLSL linker implementation
27 *
28 * Given a set of shaders that are to be linked to generate a final program,
29 * there are three distinct stages.
30 *
31 * In the first stage shaders are partitioned into groups based on the shader
32 * type. All shaders of a particular type (e.g., vertex shaders) are linked
33 * together.
34 *
35 * - Undefined references in each shader are resolve to definitions in
36 * another shader.
37 * - Types and qualifiers of uniforms, outputs, and global variables defined
38 * in multiple shaders with the same name are verified to be the same.
39 * - Initializers for uniforms and global variables defined
40 * in multiple shaders with the same name are verified to be the same.
41 *
42 * The result, in the terminology of the GLSL spec, is a set of shader
43 * executables for each processing unit.
44 *
45 * After the first stage is complete, a series of semantic checks are performed
46 * on each of the shader executables.
47 *
48 * - Each shader executable must define a \c main function.
49 * - Each vertex shader executable must write to \c gl_Position.
50 * - Each fragment shader executable must write to either \c gl_FragData or
51 * \c gl_FragColor.
52 *
53 * In the final stage individual shader executables are linked to create a
54 * complete exectuable.
55 *
56 * - Types of uniforms defined in multiple shader stages with the same name
57 * are verified to be the same.
58 * - Initializers for uniforms defined in multiple shader stages with the
59 * same name are verified to be the same.
60 * - Types and qualifiers of outputs defined in one stage are verified to
61 * be the same as the types and qualifiers of inputs defined with the same
62 * name in a later stage.
63 *
64 * \author Ian Romanick <ian.d.romanick@intel.com>
65 */
66
67 #include "main/core.h"
68 #include "glsl_symbol_table.h"
69 #include "glsl_parser_extras.h"
70 #include "ir.h"
71 #include "program.h"
72 #include "program/hash_table.h"
73 #include "linker.h"
74 #include "link_varyings.h"
75 #include "ir_optimization.h"
76 #include "ir_rvalue_visitor.h"
77 #include "ir_uniform.h"
78
79 extern "C" {
80 #include "main/shaderobj.h"
81 #include "main/enums.h"
82 }
83
84 void linker_error(gl_shader_program *, const char *, ...);
85
86 namespace {
87
88 /**
89 * Visitor that determines whether or not a variable is ever written.
90 */
91 class find_assignment_visitor : public ir_hierarchical_visitor {
92 public:
93 find_assignment_visitor(const char *name)
94 : name(name), found(false)
95 {
96 /* empty */
97 }
98
99 virtual ir_visitor_status visit_enter(ir_assignment *ir)
100 {
101 ir_variable *const var = ir->lhs->variable_referenced();
102
103 if (strcmp(name, var->name) == 0) {
104 found = true;
105 return visit_stop;
106 }
107
108 return visit_continue_with_parent;
109 }
110
111 virtual ir_visitor_status visit_enter(ir_call *ir)
112 {
113 foreach_two_lists(formal_node, &ir->callee->parameters,
114 actual_node, &ir->actual_parameters) {
115 ir_rvalue *param_rval = (ir_rvalue *) actual_node;
116 ir_variable *sig_param = (ir_variable *) formal_node;
117
118 if (sig_param->data.mode == ir_var_function_out ||
119 sig_param->data.mode == ir_var_function_inout) {
120 ir_variable *var = param_rval->variable_referenced();
121 if (var && strcmp(name, var->name) == 0) {
122 found = true;
123 return visit_stop;
124 }
125 }
126 }
127
128 if (ir->return_deref != NULL) {
129 ir_variable *const var = ir->return_deref->variable_referenced();
130
131 if (strcmp(name, var->name) == 0) {
132 found = true;
133 return visit_stop;
134 }
135 }
136
137 return visit_continue_with_parent;
138 }
139
140 bool variable_found()
141 {
142 return found;
143 }
144
145 private:
146 const char *name; /**< Find writes to a variable with this name. */
147 bool found; /**< Was a write to the variable found? */
148 };
149
150
151 /**
152 * Visitor that determines whether or not a variable is ever read.
153 */
154 class find_deref_visitor : public ir_hierarchical_visitor {
155 public:
156 find_deref_visitor(const char *name)
157 : name(name), found(false)
158 {
159 /* empty */
160 }
161
162 virtual ir_visitor_status visit(ir_dereference_variable *ir)
163 {
164 if (strcmp(this->name, ir->var->name) == 0) {
165 this->found = true;
166 return visit_stop;
167 }
168
169 return visit_continue;
170 }
171
172 bool variable_found() const
173 {
174 return this->found;
175 }
176
177 private:
178 const char *name; /**< Find writes to a variable with this name. */
179 bool found; /**< Was a write to the variable found? */
180 };
181
182
183 class geom_array_resize_visitor : public ir_hierarchical_visitor {
184 public:
185 unsigned num_vertices;
186 gl_shader_program *prog;
187
188 geom_array_resize_visitor(unsigned num_vertices, gl_shader_program *prog)
189 {
190 this->num_vertices = num_vertices;
191 this->prog = prog;
192 }
193
194 virtual ~geom_array_resize_visitor()
195 {
196 /* empty */
197 }
198
199 virtual ir_visitor_status visit(ir_variable *var)
200 {
201 if (!var->type->is_array() || var->data.mode != ir_var_shader_in)
202 return visit_continue;
203
204 unsigned size = var->type->length;
205
206 /* Generate a link error if the shader has declared this array with an
207 * incorrect size.
208 */
209 if (size && size != this->num_vertices) {
210 linker_error(this->prog, "size of array %s declared as %u, "
211 "but number of input vertices is %u\n",
212 var->name, size, this->num_vertices);
213 return visit_continue;
214 }
215
216 /* Generate a link error if the shader attempts to access an input
217 * array using an index too large for its actual size assigned at link
218 * time.
219 */
220 if (var->data.max_array_access >= this->num_vertices) {
221 linker_error(this->prog, "geometry shader accesses element %i of "
222 "%s, but only %i input vertices\n",
223 var->data.max_array_access, var->name, this->num_vertices);
224 return visit_continue;
225 }
226
227 var->type = glsl_type::get_array_instance(var->type->element_type(),
228 this->num_vertices);
229 var->data.max_array_access = this->num_vertices - 1;
230
231 return visit_continue;
232 }
233
234 /* Dereferences of input variables need to be updated so that their type
235 * matches the newly assigned type of the variable they are accessing. */
236 virtual ir_visitor_status visit(ir_dereference_variable *ir)
237 {
238 ir->type = ir->var->type;
239 return visit_continue;
240 }
241
242 /* Dereferences of 2D input arrays need to be updated so that their type
243 * matches the newly assigned type of the array they are accessing. */
244 virtual ir_visitor_status visit_leave(ir_dereference_array *ir)
245 {
246 const glsl_type *const vt = ir->array->type;
247 if (vt->is_array())
248 ir->type = vt->element_type();
249 return visit_continue;
250 }
251 };
252
253 /**
254 * Visitor that determines the highest stream id to which a (geometry) shader
255 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
256 */
257 class find_emit_vertex_visitor : public ir_hierarchical_visitor {
258 public:
259 find_emit_vertex_visitor(int max_allowed)
260 : max_stream_allowed(max_allowed),
261 invalid_stream_id(0),
262 invalid_stream_id_from_emit_vertex(false),
263 end_primitive_found(false),
264 uses_non_zero_stream(false)
265 {
266 /* empty */
267 }
268
269 virtual ir_visitor_status visit_leave(ir_emit_vertex *ir)
270 {
271 int stream_id = ir->stream_id();
272
273 if (stream_id < 0) {
274 invalid_stream_id = stream_id;
275 invalid_stream_id_from_emit_vertex = true;
276 return visit_stop;
277 }
278
279 if (stream_id > max_stream_allowed) {
280 invalid_stream_id = stream_id;
281 invalid_stream_id_from_emit_vertex = true;
282 return visit_stop;
283 }
284
285 if (stream_id != 0)
286 uses_non_zero_stream = true;
287
288 return visit_continue;
289 }
290
291 virtual ir_visitor_status visit_leave(ir_end_primitive *ir)
292 {
293 end_primitive_found = true;
294
295 int stream_id = ir->stream_id();
296
297 if (stream_id < 0) {
298 invalid_stream_id = stream_id;
299 invalid_stream_id_from_emit_vertex = false;
300 return visit_stop;
301 }
302
303 if (stream_id > max_stream_allowed) {
304 invalid_stream_id = stream_id;
305 invalid_stream_id_from_emit_vertex = false;
306 return visit_stop;
307 }
308
309 if (stream_id != 0)
310 uses_non_zero_stream = true;
311
312 return visit_continue;
313 }
314
315 bool error()
316 {
317 return invalid_stream_id != 0;
318 }
319
320 const char *error_func()
321 {
322 return invalid_stream_id_from_emit_vertex ?
323 "EmitStreamVertex" : "EndStreamPrimitive";
324 }
325
326 int error_stream()
327 {
328 return invalid_stream_id;
329 }
330
331 bool uses_streams()
332 {
333 return uses_non_zero_stream;
334 }
335
336 bool uses_end_primitive()
337 {
338 return end_primitive_found;
339 }
340
341 private:
342 int max_stream_allowed;
343 int invalid_stream_id;
344 bool invalid_stream_id_from_emit_vertex;
345 bool end_primitive_found;
346 bool uses_non_zero_stream;
347 };
348
349 } /* anonymous namespace */
350
351 void
352 linker_error(gl_shader_program *prog, const char *fmt, ...)
353 {
354 va_list ap;
355
356 ralloc_strcat(&prog->InfoLog, "error: ");
357 va_start(ap, fmt);
358 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
359 va_end(ap);
360
361 prog->LinkStatus = false;
362 }
363
364
365 void
366 linker_warning(gl_shader_program *prog, const char *fmt, ...)
367 {
368 va_list ap;
369
370 ralloc_strcat(&prog->InfoLog, "warning: ");
371 va_start(ap, fmt);
372 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
373 va_end(ap);
374
375 }
376
377
378 /**
379 * Given a string identifying a program resource, break it into a base name
380 * and an optional array index in square brackets.
381 *
382 * If an array index is present, \c out_base_name_end is set to point to the
383 * "[" that precedes the array index, and the array index itself is returned
384 * as a long.
385 *
386 * If no array index is present (or if the array index is negative or
387 * mal-formed), \c out_base_name_end, is set to point to the null terminator
388 * at the end of the input string, and -1 is returned.
389 *
390 * Only the final array index is parsed; if the string contains other array
391 * indices (or structure field accesses), they are left in the base name.
392 *
393 * No attempt is made to check that the base name is properly formed;
394 * typically the caller will look up the base name in a hash table, so
395 * ill-formed base names simply turn into hash table lookup failures.
396 */
397 long
398 parse_program_resource_name(const GLchar *name,
399 const GLchar **out_base_name_end)
400 {
401 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
402 *
403 * "When an integer array element or block instance number is part of
404 * the name string, it will be specified in decimal form without a "+"
405 * or "-" sign or any extra leading zeroes. Additionally, the name
406 * string will not include white space anywhere in the string."
407 */
408
409 const size_t len = strlen(name);
410 *out_base_name_end = name + len;
411
412 if (len == 0 || name[len-1] != ']')
413 return -1;
414
415 /* Walk backwards over the string looking for a non-digit character. This
416 * had better be the opening bracket for an array index.
417 *
418 * Initially, i specifies the location of the ']'. Since the string may
419 * contain only the ']' charcater, walk backwards very carefully.
420 */
421 unsigned i;
422 for (i = len - 1; (i > 0) && isdigit(name[i-1]); --i)
423 /* empty */ ;
424
425 if ((i == 0) || name[i-1] != '[')
426 return -1;
427
428 long array_index = strtol(&name[i], NULL, 10);
429 if (array_index < 0)
430 return -1;
431
432 *out_base_name_end = name + (i - 1);
433 return array_index;
434 }
435
436
437 void
438 link_invalidate_variable_locations(exec_list *ir)
439 {
440 foreach_list(node, ir) {
441 ir_variable *const var = ((ir_instruction *) node)->as_variable();
442
443 if (var == NULL)
444 continue;
445
446 /* Only assign locations for variables that lack an explicit location.
447 * Explicit locations are set for all built-in variables, generic vertex
448 * shader inputs (via layout(location=...)), and generic fragment shader
449 * outputs (also via layout(location=...)).
450 */
451 if (!var->data.explicit_location) {
452 var->data.location = -1;
453 var->data.location_frac = 0;
454 }
455
456 /* ir_variable::is_unmatched_generic_inout is used by the linker while
457 * connecting outputs from one stage to inputs of the next stage.
458 *
459 * There are two implicit assumptions here. First, we assume that any
460 * built-in variable (i.e., non-generic in or out) will have
461 * explicit_location set. Second, we assume that any generic in or out
462 * will not have explicit_location set.
463 *
464 * This second assumption will only be valid until
465 * GL_ARB_separate_shader_objects is supported. When that extension is
466 * implemented, this function will need some modifications.
467 */
468 if (!var->data.explicit_location) {
469 var->data.is_unmatched_generic_inout = 1;
470 } else {
471 var->data.is_unmatched_generic_inout = 0;
472 }
473 }
474 }
475
476
477 /**
478 * Set UsesClipDistance and ClipDistanceArraySize based on the given shader.
479 *
480 * Also check for errors based on incorrect usage of gl_ClipVertex and
481 * gl_ClipDistance.
482 *
483 * Return false if an error was reported.
484 */
485 static void
486 analyze_clip_usage(struct gl_shader_program *prog,
487 struct gl_shader *shader, GLboolean *UsesClipDistance,
488 GLuint *ClipDistanceArraySize)
489 {
490 *ClipDistanceArraySize = 0;
491
492 if (!prog->IsES && prog->Version >= 130) {
493 /* From section 7.1 (Vertex Shader Special Variables) of the
494 * GLSL 1.30 spec:
495 *
496 * "It is an error for a shader to statically write both
497 * gl_ClipVertex and gl_ClipDistance."
498 *
499 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
500 * gl_ClipVertex nor gl_ClipDistance.
501 */
502 find_assignment_visitor clip_vertex("gl_ClipVertex");
503 find_assignment_visitor clip_distance("gl_ClipDistance");
504
505 clip_vertex.run(shader->ir);
506 clip_distance.run(shader->ir);
507 if (clip_vertex.variable_found() && clip_distance.variable_found()) {
508 linker_error(prog, "%s shader writes to both `gl_ClipVertex' "
509 "and `gl_ClipDistance'\n",
510 _mesa_shader_stage_to_string(shader->Stage));
511 return;
512 }
513 *UsesClipDistance = clip_distance.variable_found();
514 ir_variable *clip_distance_var =
515 shader->symbols->get_variable("gl_ClipDistance");
516 if (clip_distance_var)
517 *ClipDistanceArraySize = clip_distance_var->type->length;
518 } else {
519 *UsesClipDistance = false;
520 }
521 }
522
523
524 /**
525 * Verify that a vertex shader executable meets all semantic requirements.
526 *
527 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
528 * as a side effect.
529 *
530 * \param shader Vertex shader executable to be verified
531 */
532 void
533 validate_vertex_shader_executable(struct gl_shader_program *prog,
534 struct gl_shader *shader)
535 {
536 if (shader == NULL)
537 return;
538
539 /* From the GLSL 1.10 spec, page 48:
540 *
541 * "The variable gl_Position is available only in the vertex
542 * language and is intended for writing the homogeneous vertex
543 * position. All executions of a well-formed vertex shader
544 * executable must write a value into this variable. [...] The
545 * variable gl_Position is available only in the vertex
546 * language and is intended for writing the homogeneous vertex
547 * position. All executions of a well-formed vertex shader
548 * executable must write a value into this variable."
549 *
550 * while in GLSL 1.40 this text is changed to:
551 *
552 * "The variable gl_Position is available only in the vertex
553 * language and is intended for writing the homogeneous vertex
554 * position. It can be written at any time during shader
555 * execution. It may also be read back by a vertex shader
556 * after being written. This value will be used by primitive
557 * assembly, clipping, culling, and other fixed functionality
558 * operations, if present, that operate on primitives after
559 * vertex processing has occurred. Its value is undefined if
560 * the vertex shader executable does not write gl_Position."
561 *
562 * GLSL ES 3.00 is similar to GLSL 1.40--failing to write to gl_Position is
563 * not an error.
564 */
565 if (prog->Version < (prog->IsES ? 300 : 140)) {
566 find_assignment_visitor find("gl_Position");
567 find.run(shader->ir);
568 if (!find.variable_found()) {
569 linker_error(prog, "vertex shader does not write to `gl_Position'\n");
570 return;
571 }
572 }
573
574 analyze_clip_usage(prog, shader, &prog->Vert.UsesClipDistance,
575 &prog->Vert.ClipDistanceArraySize);
576 }
577
578
579 /**
580 * Verify that a fragment shader executable meets all semantic requirements
581 *
582 * \param shader Fragment shader executable to be verified
583 */
584 void
585 validate_fragment_shader_executable(struct gl_shader_program *prog,
586 struct gl_shader *shader)
587 {
588 if (shader == NULL)
589 return;
590
591 find_assignment_visitor frag_color("gl_FragColor");
592 find_assignment_visitor frag_data("gl_FragData");
593
594 frag_color.run(shader->ir);
595 frag_data.run(shader->ir);
596
597 if (frag_color.variable_found() && frag_data.variable_found()) {
598 linker_error(prog, "fragment shader writes to both "
599 "`gl_FragColor' and `gl_FragData'\n");
600 }
601 }
602
603 /**
604 * Verify that a geometry shader executable meets all semantic requirements
605 *
606 * Also sets prog->Geom.VerticesIn, prog->Geom.UsesClipDistance, and
607 * prog->Geom.ClipDistanceArraySize as a side effect.
608 *
609 * \param shader Geometry shader executable to be verified
610 */
611 void
612 validate_geometry_shader_executable(struct gl_shader_program *prog,
613 struct gl_shader *shader)
614 {
615 if (shader == NULL)
616 return;
617
618 unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
619 prog->Geom.VerticesIn = num_vertices;
620
621 analyze_clip_usage(prog, shader, &prog->Geom.UsesClipDistance,
622 &prog->Geom.ClipDistanceArraySize);
623 }
624
625 /**
626 * Check if geometry shaders emit to non-zero streams and do corresponding
627 * validations.
628 */
629 static void
630 validate_geometry_shader_emissions(struct gl_context *ctx,
631 struct gl_shader_program *prog)
632 {
633 if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
634 find_emit_vertex_visitor emit_vertex(ctx->Const.MaxVertexStreams - 1);
635 emit_vertex.run(prog->_LinkedShaders[MESA_SHADER_GEOMETRY]->ir);
636 if (emit_vertex.error()) {
637 linker_error(prog, "Invalid call %s(%d). Accepted values for the "
638 "stream parameter are in the range [0, %d].",
639 emit_vertex.error_func(),
640 emit_vertex.error_stream(),
641 ctx->Const.MaxVertexStreams - 1);
642 }
643 prog->Geom.UsesStreams = emit_vertex.uses_streams();
644 prog->Geom.UsesEndPrimitive = emit_vertex.uses_end_primitive();
645
646 /* From the ARB_gpu_shader5 spec:
647 *
648 * "Multiple vertex streams are supported only if the output primitive
649 * type is declared to be "points". A program will fail to link if it
650 * contains a geometry shader calling EmitStreamVertex() or
651 * EndStreamPrimitive() if its output primitive type is not "points".
652 *
653 * However, in the same spec:
654 *
655 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
656 * with <stream> set to zero."
657 *
658 * And:
659 *
660 * "The function EndPrimitive() is equivalent to calling
661 * EndStreamPrimitive() with <stream> set to zero."
662 *
663 * Since we can call EmitVertex() and EndPrimitive() when we output
664 * primitives other than points, calling EmitStreamVertex(0) or
665 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
666 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
667 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
668 * stream.
669 */
670 if (prog->Geom.UsesStreams && prog->Geom.OutputType != GL_POINTS) {
671 linker_error(prog, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
672 "with n>0 requires point output");
673 }
674 }
675 }
676
677
678 /**
679 * Perform validation of global variables used across multiple shaders
680 */
681 void
682 cross_validate_globals(struct gl_shader_program *prog,
683 struct gl_shader **shader_list,
684 unsigned num_shaders,
685 bool uniforms_only)
686 {
687 /* Examine all of the uniforms in all of the shaders and cross validate
688 * them.
689 */
690 glsl_symbol_table variables;
691 for (unsigned i = 0; i < num_shaders; i++) {
692 if (shader_list[i] == NULL)
693 continue;
694
695 foreach_list(node, shader_list[i]->ir) {
696 ir_variable *const var = ((ir_instruction *) node)->as_variable();
697
698 if (var == NULL)
699 continue;
700
701 if (uniforms_only && (var->data.mode != ir_var_uniform))
702 continue;
703
704 /* Don't cross validate temporaries that are at global scope. These
705 * will eventually get pulled into the shaders 'main'.
706 */
707 if (var->data.mode == ir_var_temporary)
708 continue;
709
710 /* If a global with this name has already been seen, verify that the
711 * new instance has the same type. In addition, if the globals have
712 * initializers, the values of the initializers must be the same.
713 */
714 ir_variable *const existing = variables.get_variable(var->name);
715 if (existing != NULL) {
716 if (var->type != existing->type) {
717 /* Consider the types to be "the same" if both types are arrays
718 * of the same type and one of the arrays is implicitly sized.
719 * In addition, set the type of the linked variable to the
720 * explicitly sized array.
721 */
722 if (var->type->is_array()
723 && existing->type->is_array()
724 && (var->type->fields.array == existing->type->fields.array)
725 && ((var->type->length == 0)
726 || (existing->type->length == 0))) {
727 if (var->type->length != 0) {
728 existing->type = var->type;
729 }
730 } else if (var->type->is_record()
731 && existing->type->is_record()
732 && existing->type->record_compare(var->type)) {
733 existing->type = var->type;
734 } else {
735 linker_error(prog, "%s `%s' declared as type "
736 "`%s' and type `%s'\n",
737 mode_string(var),
738 var->name, var->type->name,
739 existing->type->name);
740 return;
741 }
742 }
743
744 if (var->data.explicit_location) {
745 if (existing->data.explicit_location
746 && (var->data.location != existing->data.location)) {
747 linker_error(prog, "explicit locations for %s "
748 "`%s' have differing values\n",
749 mode_string(var), var->name);
750 return;
751 }
752
753 existing->data.location = var->data.location;
754 existing->data.explicit_location = true;
755 }
756
757 /* From the GLSL 4.20 specification:
758 * "A link error will result if two compilation units in a program
759 * specify different integer-constant bindings for the same
760 * opaque-uniform name. However, it is not an error to specify a
761 * binding on some but not all declarations for the same name"
762 */
763 if (var->data.explicit_binding) {
764 if (existing->data.explicit_binding &&
765 var->data.binding != existing->data.binding) {
766 linker_error(prog, "explicit bindings for %s "
767 "`%s' have differing values\n",
768 mode_string(var), var->name);
769 return;
770 }
771
772 existing->data.binding = var->data.binding;
773 existing->data.explicit_binding = true;
774 }
775
776 if (var->type->contains_atomic() &&
777 var->data.atomic.offset != existing->data.atomic.offset) {
778 linker_error(prog, "offset specifications for %s "
779 "`%s' have differing values\n",
780 mode_string(var), var->name);
781 return;
782 }
783
784 /* Validate layout qualifiers for gl_FragDepth.
785 *
786 * From the AMD/ARB_conservative_depth specs:
787 *
788 * "If gl_FragDepth is redeclared in any fragment shader in a
789 * program, it must be redeclared in all fragment shaders in
790 * that program that have static assignments to
791 * gl_FragDepth. All redeclarations of gl_FragDepth in all
792 * fragment shaders in a single program must have the same set
793 * of qualifiers."
794 */
795 if (strcmp(var->name, "gl_FragDepth") == 0) {
796 bool layout_declared = var->data.depth_layout != ir_depth_layout_none;
797 bool layout_differs =
798 var->data.depth_layout != existing->data.depth_layout;
799
800 if (layout_declared && layout_differs) {
801 linker_error(prog,
802 "All redeclarations of gl_FragDepth in all "
803 "fragment shaders in a single program must have "
804 "the same set of qualifiers.");
805 }
806
807 if (var->data.used && layout_differs) {
808 linker_error(prog,
809 "If gl_FragDepth is redeclared with a layout "
810 "qualifier in any fragment shader, it must be "
811 "redeclared with the same layout qualifier in "
812 "all fragment shaders that have assignments to "
813 "gl_FragDepth");
814 }
815 }
816
817 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
818 *
819 * "If a shared global has multiple initializers, the
820 * initializers must all be constant expressions, and they
821 * must all have the same value. Otherwise, a link error will
822 * result. (A shared global having only one initializer does
823 * not require that initializer to be a constant expression.)"
824 *
825 * Previous to 4.20 the GLSL spec simply said that initializers
826 * must have the same value. In this case of non-constant
827 * initializers, this was impossible to determine. As a result,
828 * no vendor actually implemented that behavior. The 4.20
829 * behavior matches the implemented behavior of at least one other
830 * vendor, so we'll implement that for all GLSL versions.
831 */
832 if (var->constant_initializer != NULL) {
833 if (existing->constant_initializer != NULL) {
834 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
835 linker_error(prog, "initializers for %s "
836 "`%s' have differing values\n",
837 mode_string(var), var->name);
838 return;
839 }
840 } else {
841 /* If the first-seen instance of a particular uniform did not
842 * have an initializer but a later instance does, copy the
843 * initializer to the version stored in the symbol table.
844 */
845 /* FINISHME: This is wrong. The constant_value field should
846 * FINISHME: not be modified! Imagine a case where a shader
847 * FINISHME: without an initializer is linked in two different
848 * FINISHME: programs with shaders that have differing
849 * FINISHME: initializers. Linking with the first will
850 * FINISHME: modify the shader, and linking with the second
851 * FINISHME: will fail.
852 */
853 existing->constant_initializer =
854 var->constant_initializer->clone(ralloc_parent(existing),
855 NULL);
856 }
857 }
858
859 if (var->data.has_initializer) {
860 if (existing->data.has_initializer
861 && (var->constant_initializer == NULL
862 || existing->constant_initializer == NULL)) {
863 linker_error(prog,
864 "shared global variable `%s' has multiple "
865 "non-constant initializers.\n",
866 var->name);
867 return;
868 }
869
870 /* Some instance had an initializer, so keep track of that. In
871 * this location, all sorts of initializers (constant or
872 * otherwise) will propagate the existence to the variable
873 * stored in the symbol table.
874 */
875 existing->data.has_initializer = true;
876 }
877
878 if (existing->data.invariant != var->data.invariant) {
879 linker_error(prog, "declarations for %s `%s' have "
880 "mismatching invariant qualifiers\n",
881 mode_string(var), var->name);
882 return;
883 }
884 if (existing->data.centroid != var->data.centroid) {
885 linker_error(prog, "declarations for %s `%s' have "
886 "mismatching centroid qualifiers\n",
887 mode_string(var), var->name);
888 return;
889 }
890 if (existing->data.sample != var->data.sample) {
891 linker_error(prog, "declarations for %s `%s` have "
892 "mismatching sample qualifiers\n",
893 mode_string(var), var->name);
894 return;
895 }
896 } else
897 variables.add_variable(var);
898 }
899 }
900 }
901
902
903 /**
904 * Perform validation of uniforms used across multiple shader stages
905 */
906 void
907 cross_validate_uniforms(struct gl_shader_program *prog)
908 {
909 cross_validate_globals(prog, prog->_LinkedShaders,
910 MESA_SHADER_STAGES, true);
911 }
912
913 /**
914 * Accumulates the array of prog->UniformBlocks and checks that all
915 * definitons of blocks agree on their contents.
916 */
917 static bool
918 interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog)
919 {
920 unsigned max_num_uniform_blocks = 0;
921 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
922 if (prog->_LinkedShaders[i])
923 max_num_uniform_blocks += prog->_LinkedShaders[i]->NumUniformBlocks;
924 }
925
926 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
927 struct gl_shader *sh = prog->_LinkedShaders[i];
928
929 prog->UniformBlockStageIndex[i] = ralloc_array(prog, int,
930 max_num_uniform_blocks);
931 for (unsigned int j = 0; j < max_num_uniform_blocks; j++)
932 prog->UniformBlockStageIndex[i][j] = -1;
933
934 if (sh == NULL)
935 continue;
936
937 for (unsigned int j = 0; j < sh->NumUniformBlocks; j++) {
938 int index = link_cross_validate_uniform_block(prog,
939 &prog->UniformBlocks,
940 &prog->NumUniformBlocks,
941 &sh->UniformBlocks[j]);
942
943 if (index == -1) {
944 linker_error(prog, "uniform block `%s' has mismatching definitions",
945 sh->UniformBlocks[j].Name);
946 return false;
947 }
948
949 prog->UniformBlockStageIndex[i][index] = j;
950 }
951 }
952
953 return true;
954 }
955
956
957 /**
958 * Populates a shaders symbol table with all global declarations
959 */
960 static void
961 populate_symbol_table(gl_shader *sh)
962 {
963 sh->symbols = new(sh) glsl_symbol_table;
964
965 foreach_list(node, sh->ir) {
966 ir_instruction *const inst = (ir_instruction *) node;
967 ir_variable *var;
968 ir_function *func;
969
970 if ((func = inst->as_function()) != NULL) {
971 sh->symbols->add_function(func);
972 } else if ((var = inst->as_variable()) != NULL) {
973 sh->symbols->add_variable(var);
974 }
975 }
976 }
977
978
979 /**
980 * Remap variables referenced in an instruction tree
981 *
982 * This is used when instruction trees are cloned from one shader and placed in
983 * another. These trees will contain references to \c ir_variable nodes that
984 * do not exist in the target shader. This function finds these \c ir_variable
985 * references and replaces the references with matching variables in the target
986 * shader.
987 *
988 * If there is no matching variable in the target shader, a clone of the
989 * \c ir_variable is made and added to the target shader. The new variable is
990 * added to \b both the instruction stream and the symbol table.
991 *
992 * \param inst IR tree that is to be processed.
993 * \param symbols Symbol table containing global scope symbols in the
994 * linked shader.
995 * \param instructions Instruction stream where new variable declarations
996 * should be added.
997 */
998 void
999 remap_variables(ir_instruction *inst, struct gl_shader *target,
1000 hash_table *temps)
1001 {
1002 class remap_visitor : public ir_hierarchical_visitor {
1003 public:
1004 remap_visitor(struct gl_shader *target,
1005 hash_table *temps)
1006 {
1007 this->target = target;
1008 this->symbols = target->symbols;
1009 this->instructions = target->ir;
1010 this->temps = temps;
1011 }
1012
1013 virtual ir_visitor_status visit(ir_dereference_variable *ir)
1014 {
1015 if (ir->var->data.mode == ir_var_temporary) {
1016 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
1017
1018 assert(var != NULL);
1019 ir->var = var;
1020 return visit_continue;
1021 }
1022
1023 ir_variable *const existing =
1024 this->symbols->get_variable(ir->var->name);
1025 if (existing != NULL)
1026 ir->var = existing;
1027 else {
1028 ir_variable *copy = ir->var->clone(this->target, NULL);
1029
1030 this->symbols->add_variable(copy);
1031 this->instructions->push_head(copy);
1032 ir->var = copy;
1033 }
1034
1035 return visit_continue;
1036 }
1037
1038 private:
1039 struct gl_shader *target;
1040 glsl_symbol_table *symbols;
1041 exec_list *instructions;
1042 hash_table *temps;
1043 };
1044
1045 remap_visitor v(target, temps);
1046
1047 inst->accept(&v);
1048 }
1049
1050
1051 /**
1052 * Move non-declarations from one instruction stream to another
1053 *
1054 * The intended usage pattern of this function is to pass the pointer to the
1055 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1056 * pointer) for \c last and \c false for \c make_copies on the first
1057 * call. Successive calls pass the return value of the previous call for
1058 * \c last and \c true for \c make_copies.
1059 *
1060 * \param instructions Source instruction stream
1061 * \param last Instruction after which new instructions should be
1062 * inserted in the target instruction stream
1063 * \param make_copies Flag selecting whether instructions in \c instructions
1064 * should be copied (via \c ir_instruction::clone) into the
1065 * target list or moved.
1066 *
1067 * \return
1068 * The new "last" instruction in the target instruction stream. This pointer
1069 * is suitable for use as the \c last parameter of a later call to this
1070 * function.
1071 */
1072 exec_node *
1073 move_non_declarations(exec_list *instructions, exec_node *last,
1074 bool make_copies, gl_shader *target)
1075 {
1076 hash_table *temps = NULL;
1077
1078 if (make_copies)
1079 temps = hash_table_ctor(0, hash_table_pointer_hash,
1080 hash_table_pointer_compare);
1081
1082 foreach_list_safe(node, instructions) {
1083 ir_instruction *inst = (ir_instruction *) node;
1084
1085 if (inst->as_function())
1086 continue;
1087
1088 ir_variable *var = inst->as_variable();
1089 if ((var != NULL) && (var->data.mode != ir_var_temporary))
1090 continue;
1091
1092 assert(inst->as_assignment()
1093 || inst->as_call()
1094 || inst->as_if() /* for initializers with the ?: operator */
1095 || ((var != NULL) && (var->data.mode == ir_var_temporary)));
1096
1097 if (make_copies) {
1098 inst = inst->clone(target, NULL);
1099
1100 if (var != NULL)
1101 hash_table_insert(temps, inst, var);
1102 else
1103 remap_variables(inst, target, temps);
1104 } else {
1105 inst->remove();
1106 }
1107
1108 last->insert_after(inst);
1109 last = inst;
1110 }
1111
1112 if (make_copies)
1113 hash_table_dtor(temps);
1114
1115 return last;
1116 }
1117
1118 /**
1119 * Get the function signature for main from a shader
1120 */
1121 static ir_function_signature *
1122 get_main_function_signature(gl_shader *sh)
1123 {
1124 ir_function *const f = sh->symbols->get_function("main");
1125 if (f != NULL) {
1126 exec_list void_parameters;
1127
1128 /* Look for the 'void main()' signature and ensure that it's defined.
1129 * This keeps the linker from accidentally pick a shader that just
1130 * contains a prototype for main.
1131 *
1132 * We don't have to check for multiple definitions of main (in multiple
1133 * shaders) because that would have already been caught above.
1134 */
1135 ir_function_signature *sig = f->matching_signature(NULL, &void_parameters);
1136 if ((sig != NULL) && sig->is_defined) {
1137 return sig;
1138 }
1139 }
1140
1141 return NULL;
1142 }
1143
1144
1145 /**
1146 * This class is only used in link_intrastage_shaders() below but declaring
1147 * it inside that function leads to compiler warnings with some versions of
1148 * gcc.
1149 */
1150 class array_sizing_visitor : public ir_hierarchical_visitor {
1151 public:
1152 array_sizing_visitor()
1153 : mem_ctx(ralloc_context(NULL)),
1154 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash,
1155 hash_table_pointer_compare))
1156 {
1157 }
1158
1159 ~array_sizing_visitor()
1160 {
1161 hash_table_dtor(this->unnamed_interfaces);
1162 ralloc_free(this->mem_ctx);
1163 }
1164
1165 virtual ir_visitor_status visit(ir_variable *var)
1166 {
1167 fixup_type(&var->type, var->data.max_array_access);
1168 if (var->type->is_interface()) {
1169 if (interface_contains_unsized_arrays(var->type)) {
1170 const glsl_type *new_type =
1171 resize_interface_members(var->type, var->max_ifc_array_access);
1172 var->type = new_type;
1173 var->change_interface_type(new_type);
1174 }
1175 } else if (var->type->is_array() &&
1176 var->type->fields.array->is_interface()) {
1177 if (interface_contains_unsized_arrays(var->type->fields.array)) {
1178 const glsl_type *new_type =
1179 resize_interface_members(var->type->fields.array,
1180 var->max_ifc_array_access);
1181 var->change_interface_type(new_type);
1182 var->type =
1183 glsl_type::get_array_instance(new_type, var->type->length);
1184 }
1185 } else if (const glsl_type *ifc_type = var->get_interface_type()) {
1186 /* Store a pointer to the variable in the unnamed_interfaces
1187 * hashtable.
1188 */
1189 ir_variable **interface_vars = (ir_variable **)
1190 hash_table_find(this->unnamed_interfaces, ifc_type);
1191 if (interface_vars == NULL) {
1192 interface_vars = rzalloc_array(mem_ctx, ir_variable *,
1193 ifc_type->length);
1194 hash_table_insert(this->unnamed_interfaces, interface_vars,
1195 ifc_type);
1196 }
1197 unsigned index = ifc_type->field_index(var->name);
1198 assert(index < ifc_type->length);
1199 assert(interface_vars[index] == NULL);
1200 interface_vars[index] = var;
1201 }
1202 return visit_continue;
1203 }
1204
1205 /**
1206 * For each unnamed interface block that was discovered while running the
1207 * visitor, adjust the interface type to reflect the newly assigned array
1208 * sizes, and fix up the ir_variable nodes to point to the new interface
1209 * type.
1210 */
1211 void fixup_unnamed_interface_types()
1212 {
1213 hash_table_call_foreach(this->unnamed_interfaces,
1214 fixup_unnamed_interface_type, NULL);
1215 }
1216
1217 private:
1218 /**
1219 * If the type pointed to by \c type represents an unsized array, replace
1220 * it with a sized array whose size is determined by max_array_access.
1221 */
1222 static void fixup_type(const glsl_type **type, unsigned max_array_access)
1223 {
1224 if ((*type)->is_unsized_array()) {
1225 *type = glsl_type::get_array_instance((*type)->fields.array,
1226 max_array_access + 1);
1227 assert(*type != NULL);
1228 }
1229 }
1230
1231 /**
1232 * Determine whether the given interface type contains unsized arrays (if
1233 * it doesn't, array_sizing_visitor doesn't need to process it).
1234 */
1235 static bool interface_contains_unsized_arrays(const glsl_type *type)
1236 {
1237 for (unsigned i = 0; i < type->length; i++) {
1238 const glsl_type *elem_type = type->fields.structure[i].type;
1239 if (elem_type->is_unsized_array())
1240 return true;
1241 }
1242 return false;
1243 }
1244
1245 /**
1246 * Create a new interface type based on the given type, with unsized arrays
1247 * replaced by sized arrays whose size is determined by
1248 * max_ifc_array_access.
1249 */
1250 static const glsl_type *
1251 resize_interface_members(const glsl_type *type,
1252 const unsigned *max_ifc_array_access)
1253 {
1254 unsigned num_fields = type->length;
1255 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1256 memcpy(fields, type->fields.structure,
1257 num_fields * sizeof(*fields));
1258 for (unsigned i = 0; i < num_fields; i++) {
1259 fixup_type(&fields[i].type, max_ifc_array_access[i]);
1260 }
1261 glsl_interface_packing packing =
1262 (glsl_interface_packing) type->interface_packing;
1263 const glsl_type *new_ifc_type =
1264 glsl_type::get_interface_instance(fields, num_fields,
1265 packing, type->name);
1266 delete [] fields;
1267 return new_ifc_type;
1268 }
1269
1270 static void fixup_unnamed_interface_type(const void *key, void *data,
1271 void *)
1272 {
1273 const glsl_type *ifc_type = (const glsl_type *) key;
1274 ir_variable **interface_vars = (ir_variable **) data;
1275 unsigned num_fields = ifc_type->length;
1276 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1277 memcpy(fields, ifc_type->fields.structure,
1278 num_fields * sizeof(*fields));
1279 bool interface_type_changed = false;
1280 for (unsigned i = 0; i < num_fields; i++) {
1281 if (interface_vars[i] != NULL &&
1282 fields[i].type != interface_vars[i]->type) {
1283 fields[i].type = interface_vars[i]->type;
1284 interface_type_changed = true;
1285 }
1286 }
1287 if (!interface_type_changed) {
1288 delete [] fields;
1289 return;
1290 }
1291 glsl_interface_packing packing =
1292 (glsl_interface_packing) ifc_type->interface_packing;
1293 const glsl_type *new_ifc_type =
1294 glsl_type::get_interface_instance(fields, num_fields, packing,
1295 ifc_type->name);
1296 delete [] fields;
1297 for (unsigned i = 0; i < num_fields; i++) {
1298 if (interface_vars[i] != NULL)
1299 interface_vars[i]->change_interface_type(new_ifc_type);
1300 }
1301 }
1302
1303 /**
1304 * Memory context used to allocate the data in \c unnamed_interfaces.
1305 */
1306 void *mem_ctx;
1307
1308 /**
1309 * Hash table from const glsl_type * to an array of ir_variable *'s
1310 * pointing to the ir_variables constituting each unnamed interface block.
1311 */
1312 hash_table *unnamed_interfaces;
1313 };
1314
1315 /**
1316 * Performs the cross-validation of layout qualifiers specified in
1317 * redeclaration of gl_FragCoord for the attached fragment shaders,
1318 * and propagates them to the linked FS and linked shader program.
1319 */
1320 static void
1321 link_fs_input_layout_qualifiers(struct gl_shader_program *prog,
1322 struct gl_shader *linked_shader,
1323 struct gl_shader **shader_list,
1324 unsigned num_shaders)
1325 {
1326 linked_shader->redeclares_gl_fragcoord = false;
1327 linked_shader->uses_gl_fragcoord = false;
1328 linked_shader->origin_upper_left = false;
1329 linked_shader->pixel_center_integer = false;
1330
1331 if (linked_shader->Stage != MESA_SHADER_FRAGMENT ||
1332 (prog->Version < 150 && !prog->ARB_fragment_coord_conventions_enable))
1333 return;
1334
1335 for (unsigned i = 0; i < num_shaders; i++) {
1336 struct gl_shader *shader = shader_list[i];
1337 /* From the GLSL 1.50 spec, page 39:
1338 *
1339 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1340 * it must be redeclared in all the fragment shaders in that program
1341 * that have a static use gl_FragCoord."
1342 *
1343 * Exclude the case when one of the 'linked_shader' or 'shader' redeclares
1344 * gl_FragCoord with no layout qualifiers but the other one doesn't
1345 * redeclare it. If we strictly follow GLSL 1.50 spec's language, it
1346 * should be a link error. But, generating link error for this case will
1347 * be a wrong behaviour which spec didn't intend to do and it could also
1348 * break some applications.
1349 */
1350 if ((linked_shader->redeclares_gl_fragcoord
1351 && !shader->redeclares_gl_fragcoord
1352 && shader->uses_gl_fragcoord
1353 && (linked_shader->origin_upper_left
1354 || linked_shader->pixel_center_integer))
1355 || (shader->redeclares_gl_fragcoord
1356 && !linked_shader->redeclares_gl_fragcoord
1357 && linked_shader->uses_gl_fragcoord
1358 && (shader->origin_upper_left
1359 || shader->pixel_center_integer))) {
1360 linker_error(prog, "fragment shader defined with conflicting "
1361 "layout qualifiers for gl_FragCoord\n");
1362 }
1363
1364 /* From the GLSL 1.50 spec, page 39:
1365 *
1366 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1367 * single program must have the same set of qualifiers."
1368 */
1369 if (linked_shader->redeclares_gl_fragcoord && shader->redeclares_gl_fragcoord
1370 && (shader->origin_upper_left != linked_shader->origin_upper_left
1371 || shader->pixel_center_integer != linked_shader->pixel_center_integer)) {
1372 linker_error(prog, "fragment shader defined with conflicting "
1373 "layout qualifiers for gl_FragCoord\n");
1374 }
1375
1376 /* Update the linked shader state.  Note that uses_gl_fragcoord should
1377 * accumulate the results.  The other values should replace.  If there
1378 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1379 * are already known to be the same.
1380 */
1381 if (shader->redeclares_gl_fragcoord || shader->uses_gl_fragcoord) {
1382 linked_shader->redeclares_gl_fragcoord =
1383 shader->redeclares_gl_fragcoord;
1384 linked_shader->uses_gl_fragcoord = linked_shader->uses_gl_fragcoord
1385 || shader->uses_gl_fragcoord;
1386 linked_shader->origin_upper_left = shader->origin_upper_left;
1387 linked_shader->pixel_center_integer = shader->pixel_center_integer;
1388 }
1389 }
1390 }
1391
1392 /**
1393 * Performs the cross-validation of geometry shader max_vertices and
1394 * primitive type layout qualifiers for the attached geometry shaders,
1395 * and propagates them to the linked GS and linked shader program.
1396 */
1397 static void
1398 link_gs_inout_layout_qualifiers(struct gl_shader_program *prog,
1399 struct gl_shader *linked_shader,
1400 struct gl_shader **shader_list,
1401 unsigned num_shaders)
1402 {
1403 linked_shader->Geom.VerticesOut = 0;
1404 linked_shader->Geom.Invocations = 0;
1405 linked_shader->Geom.InputType = PRIM_UNKNOWN;
1406 linked_shader->Geom.OutputType = PRIM_UNKNOWN;
1407
1408 /* No in/out qualifiers defined for anything but GLSL 1.50+
1409 * geometry shaders so far.
1410 */
1411 if (linked_shader->Stage != MESA_SHADER_GEOMETRY || prog->Version < 150)
1412 return;
1413
1414 /* From the GLSL 1.50 spec, page 46:
1415 *
1416 * "All geometry shader output layout declarations in a program
1417 * must declare the same layout and same value for
1418 * max_vertices. There must be at least one geometry output
1419 * layout declaration somewhere in a program, but not all
1420 * geometry shaders (compilation units) are required to
1421 * declare it."
1422 */
1423
1424 for (unsigned i = 0; i < num_shaders; i++) {
1425 struct gl_shader *shader = shader_list[i];
1426
1427 if (shader->Geom.InputType != PRIM_UNKNOWN) {
1428 if (linked_shader->Geom.InputType != PRIM_UNKNOWN &&
1429 linked_shader->Geom.InputType != shader->Geom.InputType) {
1430 linker_error(prog, "geometry shader defined with conflicting "
1431 "input types\n");
1432 return;
1433 }
1434 linked_shader->Geom.InputType = shader->Geom.InputType;
1435 }
1436
1437 if (shader->Geom.OutputType != PRIM_UNKNOWN) {
1438 if (linked_shader->Geom.OutputType != PRIM_UNKNOWN &&
1439 linked_shader->Geom.OutputType != shader->Geom.OutputType) {
1440 linker_error(prog, "geometry shader defined with conflicting "
1441 "output types\n");
1442 return;
1443 }
1444 linked_shader->Geom.OutputType = shader->Geom.OutputType;
1445 }
1446
1447 if (shader->Geom.VerticesOut != 0) {
1448 if (linked_shader->Geom.VerticesOut != 0 &&
1449 linked_shader->Geom.VerticesOut != shader->Geom.VerticesOut) {
1450 linker_error(prog, "geometry shader defined with conflicting "
1451 "output vertex count (%d and %d)\n",
1452 linked_shader->Geom.VerticesOut,
1453 shader->Geom.VerticesOut);
1454 return;
1455 }
1456 linked_shader->Geom.VerticesOut = shader->Geom.VerticesOut;
1457 }
1458
1459 if (shader->Geom.Invocations != 0) {
1460 if (linked_shader->Geom.Invocations != 0 &&
1461 linked_shader->Geom.Invocations != shader->Geom.Invocations) {
1462 linker_error(prog, "geometry shader defined with conflicting "
1463 "invocation count (%d and %d)\n",
1464 linked_shader->Geom.Invocations,
1465 shader->Geom.Invocations);
1466 return;
1467 }
1468 linked_shader->Geom.Invocations = shader->Geom.Invocations;
1469 }
1470 }
1471
1472 /* Just do the intrastage -> interstage propagation right now,
1473 * since we already know we're in the right type of shader program
1474 * for doing it.
1475 */
1476 if (linked_shader->Geom.InputType == PRIM_UNKNOWN) {
1477 linker_error(prog,
1478 "geometry shader didn't declare primitive input type\n");
1479 return;
1480 }
1481 prog->Geom.InputType = linked_shader->Geom.InputType;
1482
1483 if (linked_shader->Geom.OutputType == PRIM_UNKNOWN) {
1484 linker_error(prog,
1485 "geometry shader didn't declare primitive output type\n");
1486 return;
1487 }
1488 prog->Geom.OutputType = linked_shader->Geom.OutputType;
1489
1490 if (linked_shader->Geom.VerticesOut == 0) {
1491 linker_error(prog,
1492 "geometry shader didn't declare max_vertices\n");
1493 return;
1494 }
1495 prog->Geom.VerticesOut = linked_shader->Geom.VerticesOut;
1496
1497 if (linked_shader->Geom.Invocations == 0)
1498 linked_shader->Geom.Invocations = 1;
1499
1500 prog->Geom.Invocations = linked_shader->Geom.Invocations;
1501 }
1502
1503
1504 /**
1505 * Perform cross-validation of compute shader local_size_{x,y,z} layout
1506 * qualifiers for the attached compute shaders, and propagate them to the
1507 * linked CS and linked shader program.
1508 */
1509 static void
1510 link_cs_input_layout_qualifiers(struct gl_shader_program *prog,
1511 struct gl_shader *linked_shader,
1512 struct gl_shader **shader_list,
1513 unsigned num_shaders)
1514 {
1515 for (int i = 0; i < 3; i++)
1516 linked_shader->Comp.LocalSize[i] = 0;
1517
1518 /* This function is called for all shader stages, but it only has an effect
1519 * for compute shaders.
1520 */
1521 if (linked_shader->Stage != MESA_SHADER_COMPUTE)
1522 return;
1523
1524 /* From the ARB_compute_shader spec, in the section describing local size
1525 * declarations:
1526 *
1527 * If multiple compute shaders attached to a single program object
1528 * declare local work-group size, the declarations must be identical;
1529 * otherwise a link-time error results. Furthermore, if a program
1530 * object contains any compute shaders, at least one must contain an
1531 * input layout qualifier specifying the local work sizes of the
1532 * program, or a link-time error will occur.
1533 */
1534 for (unsigned sh = 0; sh < num_shaders; sh++) {
1535 struct gl_shader *shader = shader_list[sh];
1536
1537 if (shader->Comp.LocalSize[0] != 0) {
1538 if (linked_shader->Comp.LocalSize[0] != 0) {
1539 for (int i = 0; i < 3; i++) {
1540 if (linked_shader->Comp.LocalSize[i] !=
1541 shader->Comp.LocalSize[i]) {
1542 linker_error(prog, "compute shader defined with conflicting "
1543 "local sizes\n");
1544 return;
1545 }
1546 }
1547 }
1548 for (int i = 0; i < 3; i++)
1549 linked_shader->Comp.LocalSize[i] = shader->Comp.LocalSize[i];
1550 }
1551 }
1552
1553 /* Just do the intrastage -> interstage propagation right now,
1554 * since we already know we're in the right type of shader program
1555 * for doing it.
1556 */
1557 if (linked_shader->Comp.LocalSize[0] == 0) {
1558 linker_error(prog, "compute shader didn't declare local size\n");
1559 return;
1560 }
1561 for (int i = 0; i < 3; i++)
1562 prog->Comp.LocalSize[i] = linked_shader->Comp.LocalSize[i];
1563 }
1564
1565
1566 /**
1567 * Combine a group of shaders for a single stage to generate a linked shader
1568 *
1569 * \note
1570 * If this function is supplied a single shader, it is cloned, and the new
1571 * shader is returned.
1572 */
1573 static struct gl_shader *
1574 link_intrastage_shaders(void *mem_ctx,
1575 struct gl_context *ctx,
1576 struct gl_shader_program *prog,
1577 struct gl_shader **shader_list,
1578 unsigned num_shaders)
1579 {
1580 struct gl_uniform_block *uniform_blocks = NULL;
1581
1582 /* Check that global variables defined in multiple shaders are consistent.
1583 */
1584 cross_validate_globals(prog, shader_list, num_shaders, false);
1585 if (!prog->LinkStatus)
1586 return NULL;
1587
1588 /* Check that interface blocks defined in multiple shaders are consistent.
1589 */
1590 validate_intrastage_interface_blocks(prog, (const gl_shader **)shader_list,
1591 num_shaders);
1592 if (!prog->LinkStatus)
1593 return NULL;
1594
1595 /* Link up uniform blocks defined within this stage. */
1596 const unsigned num_uniform_blocks =
1597 link_uniform_blocks(mem_ctx, prog, shader_list, num_shaders,
1598 &uniform_blocks);
1599 if (!prog->LinkStatus)
1600 return NULL;
1601
1602 /* Check that there is only a single definition of each function signature
1603 * across all shaders.
1604 */
1605 for (unsigned i = 0; i < (num_shaders - 1); i++) {
1606 foreach_list(node, shader_list[i]->ir) {
1607 ir_function *const f = ((ir_instruction *) node)->as_function();
1608
1609 if (f == NULL)
1610 continue;
1611
1612 for (unsigned j = i + 1; j < num_shaders; j++) {
1613 ir_function *const other =
1614 shader_list[j]->symbols->get_function(f->name);
1615
1616 /* If the other shader has no function (and therefore no function
1617 * signatures) with the same name, skip to the next shader.
1618 */
1619 if (other == NULL)
1620 continue;
1621
1622 foreach_list(n, &f->signatures) {
1623 ir_function_signature *sig = (ir_function_signature *) n;
1624
1625 if (!sig->is_defined || sig->is_builtin())
1626 continue;
1627
1628 ir_function_signature *other_sig =
1629 other->exact_matching_signature(NULL, &sig->parameters);
1630
1631 if ((other_sig != NULL) && other_sig->is_defined
1632 && !other_sig->is_builtin()) {
1633 linker_error(prog, "function `%s' is multiply defined",
1634 f->name);
1635 return NULL;
1636 }
1637 }
1638 }
1639 }
1640 }
1641
1642 /* Find the shader that defines main, and make a clone of it.
1643 *
1644 * Starting with the clone, search for undefined references. If one is
1645 * found, find the shader that defines it. Clone the reference and add
1646 * it to the shader. Repeat until there are no undefined references or
1647 * until a reference cannot be resolved.
1648 */
1649 gl_shader *main = NULL;
1650 for (unsigned i = 0; i < num_shaders; i++) {
1651 if (get_main_function_signature(shader_list[i]) != NULL) {
1652 main = shader_list[i];
1653 break;
1654 }
1655 }
1656
1657 if (main == NULL) {
1658 linker_error(prog, "%s shader lacks `main'\n",
1659 _mesa_shader_stage_to_string(shader_list[0]->Stage));
1660 return NULL;
1661 }
1662
1663 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
1664 linked->ir = new(linked) exec_list;
1665 clone_ir_list(mem_ctx, linked->ir, main->ir);
1666
1667 linked->UniformBlocks = uniform_blocks;
1668 linked->NumUniformBlocks = num_uniform_blocks;
1669 ralloc_steal(linked, linked->UniformBlocks);
1670
1671 link_fs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
1672 link_gs_inout_layout_qualifiers(prog, linked, shader_list, num_shaders);
1673 link_cs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
1674
1675 populate_symbol_table(linked);
1676
1677 /* The a pointer to the main function in the final linked shader (i.e., the
1678 * copy of the original shader that contained the main function).
1679 */
1680 ir_function_signature *const main_sig = get_main_function_signature(linked);
1681
1682 /* Move any instructions other than variable declarations or function
1683 * declarations into main.
1684 */
1685 exec_node *insertion_point =
1686 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
1687 linked);
1688
1689 for (unsigned i = 0; i < num_shaders; i++) {
1690 if (shader_list[i] == main)
1691 continue;
1692
1693 insertion_point = move_non_declarations(shader_list[i]->ir,
1694 insertion_point, true, linked);
1695 }
1696
1697 /* Check if any shader needs built-in functions. */
1698 bool need_builtins = false;
1699 for (unsigned i = 0; i < num_shaders; i++) {
1700 if (shader_list[i]->uses_builtin_functions) {
1701 need_builtins = true;
1702 break;
1703 }
1704 }
1705
1706 bool ok;
1707 if (need_builtins) {
1708 /* Make a temporary array one larger than shader_list, which will hold
1709 * the built-in function shader as well.
1710 */
1711 gl_shader **linking_shaders = (gl_shader **)
1712 calloc(num_shaders + 1, sizeof(gl_shader *));
1713 memcpy(linking_shaders, shader_list, num_shaders * sizeof(gl_shader *));
1714 linking_shaders[num_shaders] = _mesa_glsl_get_builtin_function_shader();
1715
1716 ok = link_function_calls(prog, linked, linking_shaders, num_shaders + 1);
1717
1718 free(linking_shaders);
1719 } else {
1720 ok = link_function_calls(prog, linked, shader_list, num_shaders);
1721 }
1722
1723
1724 if (!ok) {
1725 ctx->Driver.DeleteShader(ctx, linked);
1726 return NULL;
1727 }
1728
1729 /* At this point linked should contain all of the linked IR, so
1730 * validate it to make sure nothing went wrong.
1731 */
1732 validate_ir_tree(linked->ir);
1733
1734 /* Set the size of geometry shader input arrays */
1735 if (linked->Stage == MESA_SHADER_GEOMETRY) {
1736 unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
1737 geom_array_resize_visitor input_resize_visitor(num_vertices, prog);
1738 foreach_list(n, linked->ir) {
1739 ir_instruction *ir = (ir_instruction *) n;
1740 ir->accept(&input_resize_visitor);
1741 }
1742 }
1743
1744 /* Make a pass over all variable declarations to ensure that arrays with
1745 * unspecified sizes have a size specified. The size is inferred from the
1746 * max_array_access field.
1747 */
1748 array_sizing_visitor v;
1749 v.run(linked->ir);
1750 v.fixup_unnamed_interface_types();
1751
1752 return linked;
1753 }
1754
1755 /**
1756 * Update the sizes of linked shader uniform arrays to the maximum
1757 * array index used.
1758 *
1759 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1760 *
1761 * If one or more elements of an array are active,
1762 * GetActiveUniform will return the name of the array in name,
1763 * subject to the restrictions listed above. The type of the array
1764 * is returned in type. The size parameter contains the highest
1765 * array element index used, plus one. The compiler or linker
1766 * determines the highest index used. There will be only one
1767 * active uniform reported by the GL per uniform array.
1768
1769 */
1770 static void
1771 update_array_sizes(struct gl_shader_program *prog)
1772 {
1773 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1774 if (prog->_LinkedShaders[i] == NULL)
1775 continue;
1776
1777 foreach_list(node, prog->_LinkedShaders[i]->ir) {
1778 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1779
1780 if ((var == NULL) || (var->data.mode != ir_var_uniform) ||
1781 !var->type->is_array())
1782 continue;
1783
1784 /* GL_ARB_uniform_buffer_object says that std140 uniforms
1785 * will not be eliminated. Since we always do std140, just
1786 * don't resize arrays in UBOs.
1787 *
1788 * Atomic counters are supposed to get deterministic
1789 * locations assigned based on the declaration ordering and
1790 * sizes, array compaction would mess that up.
1791 */
1792 if (var->is_in_uniform_block() || var->type->contains_atomic())
1793 continue;
1794
1795 unsigned int size = var->data.max_array_access;
1796 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
1797 if (prog->_LinkedShaders[j] == NULL)
1798 continue;
1799
1800 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
1801 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
1802 if (!other_var)
1803 continue;
1804
1805 if (strcmp(var->name, other_var->name) == 0 &&
1806 other_var->data.max_array_access > size) {
1807 size = other_var->data.max_array_access;
1808 }
1809 }
1810 }
1811
1812 if (size + 1 != var->type->length) {
1813 /* If this is a built-in uniform (i.e., it's backed by some
1814 * fixed-function state), adjust the number of state slots to
1815 * match the new array size. The number of slots per array entry
1816 * is not known. It seems safe to assume that the total number of
1817 * slots is an integer multiple of the number of array elements.
1818 * Determine the number of slots per array element by dividing by
1819 * the old (total) size.
1820 */
1821 if (var->num_state_slots > 0) {
1822 var->num_state_slots = (size + 1)
1823 * (var->num_state_slots / var->type->length);
1824 }
1825
1826 var->type = glsl_type::get_array_instance(var->type->fields.array,
1827 size + 1);
1828 /* FINISHME: We should update the types of array
1829 * dereferences of this variable now.
1830 */
1831 }
1832 }
1833 }
1834 }
1835
1836 /**
1837 * Find a contiguous set of available bits in a bitmask.
1838 *
1839 * \param used_mask Bits representing used (1) and unused (0) locations
1840 * \param needed_count Number of contiguous bits needed.
1841 *
1842 * \return
1843 * Base location of the available bits on success or -1 on failure.
1844 */
1845 int
1846 find_available_slots(unsigned used_mask, unsigned needed_count)
1847 {
1848 unsigned needed_mask = (1 << needed_count) - 1;
1849 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1850
1851 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1852 * cannot optimize possibly infinite loops" for the loop below.
1853 */
1854 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1855 return -1;
1856
1857 for (int i = 0; i <= max_bit_to_test; i++) {
1858 if ((needed_mask & ~used_mask) == needed_mask)
1859 return i;
1860
1861 needed_mask <<= 1;
1862 }
1863
1864 return -1;
1865 }
1866
1867
1868 /**
1869 * Assign locations for either VS inputs for FS outputs
1870 *
1871 * \param prog Shader program whose variables need locations assigned
1872 * \param target_index Selector for the program target to receive location
1873 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1874 * \c MESA_SHADER_FRAGMENT.
1875 * \param max_index Maximum number of generic locations. This corresponds
1876 * to either the maximum number of draw buffers or the
1877 * maximum number of generic attributes.
1878 *
1879 * \return
1880 * If locations are successfully assigned, true is returned. Otherwise an
1881 * error is emitted to the shader link log and false is returned.
1882 */
1883 bool
1884 assign_attribute_or_color_locations(gl_shader_program *prog,
1885 unsigned target_index,
1886 unsigned max_index)
1887 {
1888 /* Mark invalid locations as being used.
1889 */
1890 unsigned used_locations = (max_index >= 32)
1891 ? ~0 : ~((1 << max_index) - 1);
1892
1893 assert((target_index == MESA_SHADER_VERTEX)
1894 || (target_index == MESA_SHADER_FRAGMENT));
1895
1896 gl_shader *const sh = prog->_LinkedShaders[target_index];
1897 if (sh == NULL)
1898 return true;
1899
1900 /* Operate in a total of four passes.
1901 *
1902 * 1. Invalidate the location assignments for all vertex shader inputs.
1903 *
1904 * 2. Assign locations for inputs that have user-defined (via
1905 * glBindVertexAttribLocation) locations and outputs that have
1906 * user-defined locations (via glBindFragDataLocation).
1907 *
1908 * 3. Sort the attributes without assigned locations by number of slots
1909 * required in decreasing order. Fragmentation caused by attribute
1910 * locations assigned by the application may prevent large attributes
1911 * from having enough contiguous space.
1912 *
1913 * 4. Assign locations to any inputs without assigned locations.
1914 */
1915
1916 const int generic_base = (target_index == MESA_SHADER_VERTEX)
1917 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
1918
1919 const enum ir_variable_mode direction =
1920 (target_index == MESA_SHADER_VERTEX)
1921 ? ir_var_shader_in : ir_var_shader_out;
1922
1923
1924 /* Temporary storage for the set of attributes that need locations assigned.
1925 */
1926 struct temp_attr {
1927 unsigned slots;
1928 ir_variable *var;
1929
1930 /* Used below in the call to qsort. */
1931 static int compare(const void *a, const void *b)
1932 {
1933 const temp_attr *const l = (const temp_attr *) a;
1934 const temp_attr *const r = (const temp_attr *) b;
1935
1936 /* Reversed because we want a descending order sort below. */
1937 return r->slots - l->slots;
1938 }
1939 } to_assign[16];
1940
1941 unsigned num_attr = 0;
1942
1943 foreach_list(node, sh->ir) {
1944 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1945
1946 if ((var == NULL) || (var->data.mode != (unsigned) direction))
1947 continue;
1948
1949 if (var->data.explicit_location) {
1950 if ((var->data.location >= (int)(max_index + generic_base))
1951 || (var->data.location < 0)) {
1952 linker_error(prog,
1953 "invalid explicit location %d specified for `%s'\n",
1954 (var->data.location < 0)
1955 ? var->data.location
1956 : var->data.location - generic_base,
1957 var->name);
1958 return false;
1959 }
1960 } else if (target_index == MESA_SHADER_VERTEX) {
1961 unsigned binding;
1962
1963 if (prog->AttributeBindings->get(binding, var->name)) {
1964 assert(binding >= VERT_ATTRIB_GENERIC0);
1965 var->data.location = binding;
1966 var->data.is_unmatched_generic_inout = 0;
1967 }
1968 } else if (target_index == MESA_SHADER_FRAGMENT) {
1969 unsigned binding;
1970 unsigned index;
1971
1972 if (prog->FragDataBindings->get(binding, var->name)) {
1973 assert(binding >= FRAG_RESULT_DATA0);
1974 var->data.location = binding;
1975 var->data.is_unmatched_generic_inout = 0;
1976
1977 if (prog->FragDataIndexBindings->get(index, var->name)) {
1978 var->data.index = index;
1979 }
1980 }
1981 }
1982
1983 /* If the variable is not a built-in and has a location statically
1984 * assigned in the shader (presumably via a layout qualifier), make sure
1985 * that it doesn't collide with other assigned locations. Otherwise,
1986 * add it to the list of variables that need linker-assigned locations.
1987 */
1988 const unsigned slots = var->type->count_attribute_slots();
1989 if (var->data.location != -1) {
1990 if (var->data.location >= generic_base && var->data.index < 1) {
1991 /* From page 61 of the OpenGL 4.0 spec:
1992 *
1993 * "LinkProgram will fail if the attribute bindings assigned
1994 * by BindAttribLocation do not leave not enough space to
1995 * assign a location for an active matrix attribute or an
1996 * active attribute array, both of which require multiple
1997 * contiguous generic attributes."
1998 *
1999 * I think above text prohibits the aliasing of explicit and
2000 * automatic assignments. But, aliasing is allowed in manual
2001 * assignments of attribute locations. See below comments for
2002 * the details.
2003 *
2004 * From OpenGL 4.0 spec, page 61:
2005 *
2006 * "It is possible for an application to bind more than one
2007 * attribute name to the same location. This is referred to as
2008 * aliasing. This will only work if only one of the aliased
2009 * attributes is active in the executable program, or if no
2010 * path through the shader consumes more than one attribute of
2011 * a set of attributes aliased to the same location. A link
2012 * error can occur if the linker determines that every path
2013 * through the shader consumes multiple aliased attributes,
2014 * but implementations are not required to generate an error
2015 * in this case."
2016 *
2017 * From GLSL 4.30 spec, page 54:
2018 *
2019 * "A program will fail to link if any two non-vertex shader
2020 * input variables are assigned to the same location. For
2021 * vertex shaders, multiple input variables may be assigned
2022 * to the same location using either layout qualifiers or via
2023 * the OpenGL API. However, such aliasing is intended only to
2024 * support vertex shaders where each execution path accesses
2025 * at most one input per each location. Implementations are
2026 * permitted, but not required, to generate link-time errors
2027 * if they detect that every path through the vertex shader
2028 * executable accesses multiple inputs assigned to any single
2029 * location. For all shader types, a program will fail to link
2030 * if explicit location assignments leave the linker unable
2031 * to find space for other variables without explicit
2032 * assignments."
2033 *
2034 * From OpenGL ES 3.0 spec, page 56:
2035 *
2036 * "Binding more than one attribute name to the same location
2037 * is referred to as aliasing, and is not permitted in OpenGL
2038 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2039 * fail when this condition exists. However, aliasing is
2040 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2041 * This will only work if only one of the aliased attributes
2042 * is active in the executable program, or if no path through
2043 * the shader consumes more than one attribute of a set of
2044 * attributes aliased to the same location. A link error can
2045 * occur if the linker determines that every path through the
2046 * shader consumes multiple aliased attributes, but implemen-
2047 * tations are not required to generate an error in this case."
2048 *
2049 * After looking at above references from OpenGL, OpenGL ES and
2050 * GLSL specifications, we allow aliasing of vertex input variables
2051 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2052 *
2053 * NOTE: This is not required by the spec but its worth mentioning
2054 * here that we're not doing anything to make sure that no path
2055 * through the vertex shader executable accesses multiple inputs
2056 * assigned to any single location.
2057 */
2058
2059 /* Mask representing the contiguous slots that will be used by
2060 * this attribute.
2061 */
2062 const unsigned attr = var->data.location - generic_base;
2063 const unsigned use_mask = (1 << slots) - 1;
2064 const char *const string = (target_index == MESA_SHADER_VERTEX)
2065 ? "vertex shader input" : "fragment shader output";
2066
2067 /* Generate a link error if the requested locations for this
2068 * attribute exceed the maximum allowed attribute location.
2069 */
2070 if (attr + slots > max_index) {
2071 linker_error(prog,
2072 "insufficient contiguous locations "
2073 "available for %s `%s' %d %d %d", string,
2074 var->name, used_locations, use_mask, attr);
2075 return false;
2076 }
2077
2078 /* Generate a link error if the set of bits requested for this
2079 * attribute overlaps any previously allocated bits.
2080 */
2081 if ((~(use_mask << attr) & used_locations) != used_locations) {
2082 if (target_index == MESA_SHADER_FRAGMENT ||
2083 (prog->IsES && prog->Version >= 300)) {
2084 linker_error(prog,
2085 "overlapping location is assigned "
2086 "to %s `%s' %d %d %d\n", string,
2087 var->name, used_locations, use_mask, attr);
2088 return false;
2089 } else {
2090 linker_warning(prog,
2091 "overlapping location is assigned "
2092 "to %s `%s' %d %d %d\n", string,
2093 var->name, used_locations, use_mask, attr);
2094 }
2095 }
2096
2097 used_locations |= (use_mask << attr);
2098 }
2099
2100 continue;
2101 }
2102
2103 to_assign[num_attr].slots = slots;
2104 to_assign[num_attr].var = var;
2105 num_attr++;
2106 }
2107
2108 /* If all of the attributes were assigned locations by the application (or
2109 * are built-in attributes with fixed locations), return early. This should
2110 * be the common case.
2111 */
2112 if (num_attr == 0)
2113 return true;
2114
2115 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
2116
2117 if (target_index == MESA_SHADER_VERTEX) {
2118 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2119 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2120 * reserved to prevent it from being automatically allocated below.
2121 */
2122 find_deref_visitor find("gl_Vertex");
2123 find.run(sh->ir);
2124 if (find.variable_found())
2125 used_locations |= (1 << 0);
2126 }
2127
2128 for (unsigned i = 0; i < num_attr; i++) {
2129 /* Mask representing the contiguous slots that will be used by this
2130 * attribute.
2131 */
2132 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
2133
2134 int location = find_available_slots(used_locations, to_assign[i].slots);
2135
2136 if (location < 0) {
2137 const char *const string = (target_index == MESA_SHADER_VERTEX)
2138 ? "vertex shader input" : "fragment shader output";
2139
2140 linker_error(prog,
2141 "insufficient contiguous locations "
2142 "available for %s `%s'",
2143 string, to_assign[i].var->name);
2144 return false;
2145 }
2146
2147 to_assign[i].var->data.location = generic_base + location;
2148 to_assign[i].var->data.is_unmatched_generic_inout = 0;
2149 used_locations |= (use_mask << location);
2150 }
2151
2152 return true;
2153 }
2154
2155
2156 /**
2157 * Demote shader inputs and outputs that are not used in other stages
2158 */
2159 void
2160 demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
2161 {
2162 foreach_list(node, sh->ir) {
2163 ir_variable *const var = ((ir_instruction *) node)->as_variable();
2164
2165 if ((var == NULL) || (var->data.mode != int(mode)))
2166 continue;
2167
2168 /* A shader 'in' or 'out' variable is only really an input or output if
2169 * its value is used by other shader stages. This will cause the variable
2170 * to have a location assigned.
2171 */
2172 if (var->data.is_unmatched_generic_inout) {
2173 var->data.mode = ir_var_auto;
2174 }
2175 }
2176 }
2177
2178
2179 /**
2180 * Store the gl_FragDepth layout in the gl_shader_program struct.
2181 */
2182 static void
2183 store_fragdepth_layout(struct gl_shader_program *prog)
2184 {
2185 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2186 return;
2187 }
2188
2189 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2190
2191 /* We don't look up the gl_FragDepth symbol directly because if
2192 * gl_FragDepth is not used in the shader, it's removed from the IR.
2193 * However, the symbol won't be removed from the symbol table.
2194 *
2195 * We're only interested in the cases where the variable is NOT removed
2196 * from the IR.
2197 */
2198 foreach_list(node, ir) {
2199 ir_variable *const var = ((ir_instruction *) node)->as_variable();
2200
2201 if (var == NULL || var->data.mode != ir_var_shader_out) {
2202 continue;
2203 }
2204
2205 if (strcmp(var->name, "gl_FragDepth") == 0) {
2206 switch (var->data.depth_layout) {
2207 case ir_depth_layout_none:
2208 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2209 return;
2210 case ir_depth_layout_any:
2211 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2212 return;
2213 case ir_depth_layout_greater:
2214 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2215 return;
2216 case ir_depth_layout_less:
2217 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2218 return;
2219 case ir_depth_layout_unchanged:
2220 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2221 return;
2222 default:
2223 assert(0);
2224 return;
2225 }
2226 }
2227 }
2228 }
2229
2230 /**
2231 * Validate the resources used by a program versus the implementation limits
2232 */
2233 static void
2234 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2235 {
2236 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2237 struct gl_shader *sh = prog->_LinkedShaders[i];
2238
2239 if (sh == NULL)
2240 continue;
2241
2242 if (sh->num_samplers > ctx->Const.Program[i].MaxTextureImageUnits) {
2243 linker_error(prog, "Too many %s shader texture samplers",
2244 _mesa_shader_stage_to_string(i));
2245 }
2246
2247 if (sh->num_uniform_components >
2248 ctx->Const.Program[i].MaxUniformComponents) {
2249 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2250 linker_warning(prog, "Too many %s shader default uniform block "
2251 "components, but the driver will try to optimize "
2252 "them out; this is non-portable out-of-spec "
2253 "behavior\n",
2254 _mesa_shader_stage_to_string(i));
2255 } else {
2256 linker_error(prog, "Too many %s shader default uniform block "
2257 "components",
2258 _mesa_shader_stage_to_string(i));
2259 }
2260 }
2261
2262 if (sh->num_combined_uniform_components >
2263 ctx->Const.Program[i].MaxCombinedUniformComponents) {
2264 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2265 linker_warning(prog, "Too many %s shader uniform components, "
2266 "but the driver will try to optimize them out; "
2267 "this is non-portable out-of-spec behavior\n",
2268 _mesa_shader_stage_to_string(i));
2269 } else {
2270 linker_error(prog, "Too many %s shader uniform components",
2271 _mesa_shader_stage_to_string(i));
2272 }
2273 }
2274 }
2275
2276 unsigned blocks[MESA_SHADER_STAGES] = {0};
2277 unsigned total_uniform_blocks = 0;
2278
2279 for (unsigned i = 0; i < prog->NumUniformBlocks; i++) {
2280 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
2281 if (prog->UniformBlockStageIndex[j][i] != -1) {
2282 blocks[j]++;
2283 total_uniform_blocks++;
2284 }
2285 }
2286
2287 if (total_uniform_blocks > ctx->Const.MaxCombinedUniformBlocks) {
2288 linker_error(prog, "Too many combined uniform blocks (%d/%d)",
2289 prog->NumUniformBlocks,
2290 ctx->Const.MaxCombinedUniformBlocks);
2291 } else {
2292 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2293 const unsigned max_uniform_blocks =
2294 ctx->Const.Program[i].MaxUniformBlocks;
2295 if (blocks[i] > max_uniform_blocks) {
2296 linker_error(prog, "Too many %s uniform blocks (%d/%d)",
2297 _mesa_shader_stage_to_string(i),
2298 blocks[i],
2299 max_uniform_blocks);
2300 break;
2301 }
2302 }
2303 }
2304 }
2305 }
2306
2307 /**
2308 * Validate shader image resources.
2309 */
2310 static void
2311 check_image_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2312 {
2313 unsigned total_image_units = 0;
2314 unsigned fragment_outputs = 0;
2315
2316 if (!ctx->Extensions.ARB_shader_image_load_store)
2317 return;
2318
2319 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2320 struct gl_shader *sh = prog->_LinkedShaders[i];
2321
2322 if (sh) {
2323 if (sh->NumImages > ctx->Const.Program[i].MaxImageUniforms)
2324 linker_error(prog, "Too many %s shader image uniforms",
2325 _mesa_shader_stage_to_string(i));
2326
2327 total_image_units += sh->NumImages;
2328
2329 if (i == MESA_SHADER_FRAGMENT) {
2330 foreach_list(node, sh->ir) {
2331 ir_variable *var = ((ir_instruction *)node)->as_variable();
2332 if (var && var->data.mode == ir_var_shader_out)
2333 fragment_outputs += var->type->count_attribute_slots();
2334 }
2335 }
2336 }
2337 }
2338
2339 if (total_image_units > ctx->Const.MaxCombinedImageUniforms)
2340 linker_error(prog, "Too many combined image uniforms");
2341
2342 if (total_image_units + fragment_outputs >
2343 ctx->Const.MaxCombinedImageUnitsAndFragmentOutputs)
2344 linker_error(prog, "Too many combined image uniforms and fragment outputs");
2345 }
2346
2347
2348 /**
2349 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
2350 * for a variable, checks for overlaps between other uniforms using explicit
2351 * locations.
2352 */
2353 static bool
2354 reserve_explicit_locations(struct gl_shader_program *prog,
2355 string_to_uint_map *map, ir_variable *var)
2356 {
2357 unsigned slots = var->type->uniform_locations();
2358 unsigned max_loc = var->data.location + slots - 1;
2359
2360 /* Resize remap table if locations do not fit in the current one. */
2361 if (max_loc + 1 > prog->NumUniformRemapTable) {
2362 prog->UniformRemapTable =
2363 reralloc(prog, prog->UniformRemapTable,
2364 gl_uniform_storage *,
2365 max_loc + 1);
2366
2367 if (!prog->UniformRemapTable) {
2368 linker_error(prog, "Out of memory during linking.");
2369 return false;
2370 }
2371
2372 /* Initialize allocated space. */
2373 for (unsigned i = prog->NumUniformRemapTable; i < max_loc + 1; i++)
2374 prog->UniformRemapTable[i] = NULL;
2375
2376 prog->NumUniformRemapTable = max_loc + 1;
2377 }
2378
2379 for (unsigned i = 0; i < slots; i++) {
2380 unsigned loc = var->data.location + i;
2381
2382 /* Check if location is already used. */
2383 if (prog->UniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
2384
2385 /* Possibly same uniform from a different stage, this is ok. */
2386 unsigned hash_loc;
2387 if (map->get(hash_loc, var->name) && hash_loc == loc - i)
2388 continue;
2389
2390 /* ARB_explicit_uniform_location specification states:
2391 *
2392 * "No two default-block uniform variables in the program can have
2393 * the same location, even if they are unused, otherwise a compiler
2394 * or linker error will be generated."
2395 */
2396 linker_error(prog,
2397 "location qualifier for uniform %s overlaps"
2398 "previously used location",
2399 var->name);
2400 return false;
2401 }
2402
2403 /* Initialize location as inactive before optimization
2404 * rounds and location assignment.
2405 */
2406 prog->UniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
2407 }
2408
2409 /* Note, base location used for arrays. */
2410 map->put(var->data.location, var->name);
2411
2412 return true;
2413 }
2414
2415 /**
2416 * Check and reserve all explicit uniform locations, called before
2417 * any optimizations happen to handle also inactive uniforms and
2418 * inactive array elements that may get trimmed away.
2419 */
2420 static void
2421 check_explicit_uniform_locations(struct gl_context *ctx,
2422 struct gl_shader_program *prog)
2423 {
2424 if (!ctx->Extensions.ARB_explicit_uniform_location)
2425 return;
2426
2427 /* This map is used to detect if overlapping explicit locations
2428 * occur with the same uniform (from different stage) or a different one.
2429 */
2430 string_to_uint_map *uniform_map = new string_to_uint_map;
2431
2432 if (!uniform_map) {
2433 linker_error(prog, "Out of memory during linking.");
2434 return;
2435 }
2436
2437 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2438 struct gl_shader *sh = prog->_LinkedShaders[i];
2439
2440 if (!sh)
2441 continue;
2442
2443 foreach_list(node, sh->ir) {
2444 ir_variable *var = ((ir_instruction *)node)->as_variable();
2445 if ((var && var->data.mode == ir_var_uniform) &&
2446 var->data.explicit_location) {
2447 if (!reserve_explicit_locations(prog, uniform_map, var))
2448 return;
2449 }
2450 }
2451 }
2452
2453 delete uniform_map;
2454 }
2455
2456 void
2457 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
2458 {
2459 tfeedback_decl *tfeedback_decls = NULL;
2460 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
2461
2462 void *mem_ctx = ralloc_context(NULL); // temporary linker context
2463
2464 prog->LinkStatus = true; /* All error paths will set this to false */
2465 prog->Validated = false;
2466 prog->_Used = false;
2467
2468 ralloc_free(prog->InfoLog);
2469 prog->InfoLog = ralloc_strdup(NULL, "");
2470
2471 ralloc_free(prog->UniformBlocks);
2472 prog->UniformBlocks = NULL;
2473 prog->NumUniformBlocks = 0;
2474 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
2475 ralloc_free(prog->UniformBlockStageIndex[i]);
2476 prog->UniformBlockStageIndex[i] = NULL;
2477 }
2478
2479 ralloc_free(prog->AtomicBuffers);
2480 prog->AtomicBuffers = NULL;
2481 prog->NumAtomicBuffers = 0;
2482 prog->ARB_fragment_coord_conventions_enable = false;
2483
2484 /* Separate the shaders into groups based on their type.
2485 */
2486 struct gl_shader **shader_list[MESA_SHADER_STAGES];
2487 unsigned num_shaders[MESA_SHADER_STAGES];
2488
2489 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
2490 shader_list[i] = (struct gl_shader **)
2491 calloc(prog->NumShaders, sizeof(struct gl_shader *));
2492 num_shaders[i] = 0;
2493 }
2494
2495 unsigned min_version = UINT_MAX;
2496 unsigned max_version = 0;
2497 const bool is_es_prog =
2498 (prog->NumShaders > 0 && prog->Shaders[0]->IsES) ? true : false;
2499 for (unsigned i = 0; i < prog->NumShaders; i++) {
2500 min_version = MIN2(min_version, prog->Shaders[i]->Version);
2501 max_version = MAX2(max_version, prog->Shaders[i]->Version);
2502
2503 if (prog->Shaders[i]->IsES != is_es_prog) {
2504 linker_error(prog, "all shaders must use same shading "
2505 "language version\n");
2506 goto done;
2507 }
2508
2509 prog->ARB_fragment_coord_conventions_enable |=
2510 prog->Shaders[i]->ARB_fragment_coord_conventions_enable;
2511
2512 gl_shader_stage shader_type = prog->Shaders[i]->Stage;
2513 shader_list[shader_type][num_shaders[shader_type]] = prog->Shaders[i];
2514 num_shaders[shader_type]++;
2515 }
2516
2517 /* In desktop GLSL, different shader versions may be linked together. In
2518 * GLSL ES, all shader versions must be the same.
2519 */
2520 if (is_es_prog && min_version != max_version) {
2521 linker_error(prog, "all shaders must use same shading "
2522 "language version\n");
2523 goto done;
2524 }
2525
2526 prog->Version = max_version;
2527 prog->IsES = is_es_prog;
2528
2529 /* Geometry shaders have to be linked with vertex shaders.
2530 */
2531 if (num_shaders[MESA_SHADER_GEOMETRY] > 0 &&
2532 num_shaders[MESA_SHADER_VERTEX] == 0 &&
2533 !prog->SeparateShader) {
2534 linker_error(prog, "Geometry shader must be linked with "
2535 "vertex shader\n");
2536 goto done;
2537 }
2538
2539 /* Compute shaders have additional restrictions. */
2540 if (num_shaders[MESA_SHADER_COMPUTE] > 0 &&
2541 num_shaders[MESA_SHADER_COMPUTE] != prog->NumShaders) {
2542 linker_error(prog, "Compute shaders may not be linked with any other "
2543 "type of shader\n");
2544 }
2545
2546 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
2547 if (prog->_LinkedShaders[i] != NULL)
2548 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
2549
2550 prog->_LinkedShaders[i] = NULL;
2551 }
2552
2553 /* Link all shaders for a particular stage and validate the result.
2554 */
2555 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
2556 if (num_shaders[stage] > 0) {
2557 gl_shader *const sh =
2558 link_intrastage_shaders(mem_ctx, ctx, prog, shader_list[stage],
2559 num_shaders[stage]);
2560
2561 if (!prog->LinkStatus)
2562 goto done;
2563
2564 switch (stage) {
2565 case MESA_SHADER_VERTEX:
2566 validate_vertex_shader_executable(prog, sh);
2567 break;
2568 case MESA_SHADER_GEOMETRY:
2569 validate_geometry_shader_executable(prog, sh);
2570 break;
2571 case MESA_SHADER_FRAGMENT:
2572 validate_fragment_shader_executable(prog, sh);
2573 break;
2574 }
2575 if (!prog->LinkStatus)
2576 goto done;
2577
2578 _mesa_reference_shader(ctx, &prog->_LinkedShaders[stage], sh);
2579 }
2580 }
2581
2582 if (num_shaders[MESA_SHADER_GEOMETRY] > 0)
2583 prog->LastClipDistanceArraySize = prog->Geom.ClipDistanceArraySize;
2584 else if (num_shaders[MESA_SHADER_VERTEX] > 0)
2585 prog->LastClipDistanceArraySize = prog->Vert.ClipDistanceArraySize;
2586 else
2587 prog->LastClipDistanceArraySize = 0; /* Not used */
2588
2589 /* Here begins the inter-stage linking phase. Some initial validation is
2590 * performed, then locations are assigned for uniforms, attributes, and
2591 * varyings.
2592 */
2593 cross_validate_uniforms(prog);
2594 if (!prog->LinkStatus)
2595 goto done;
2596
2597 unsigned prev;
2598
2599 for (prev = 0; prev <= MESA_SHADER_FRAGMENT; prev++) {
2600 if (prog->_LinkedShaders[prev] != NULL)
2601 break;
2602 }
2603
2604 check_explicit_uniform_locations(ctx, prog);
2605 if (!prog->LinkStatus)
2606 goto done;
2607
2608 /* Validate the inputs of each stage with the output of the preceding
2609 * stage.
2610 */
2611 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
2612 if (prog->_LinkedShaders[i] == NULL)
2613 continue;
2614
2615 validate_interstage_inout_blocks(prog, prog->_LinkedShaders[prev],
2616 prog->_LinkedShaders[i]);
2617 if (!prog->LinkStatus)
2618 goto done;
2619
2620 cross_validate_outputs_to_inputs(prog,
2621 prog->_LinkedShaders[prev],
2622 prog->_LinkedShaders[i]);
2623 if (!prog->LinkStatus)
2624 goto done;
2625
2626 prev = i;
2627 }
2628
2629 /* Cross-validate uniform blocks between shader stages */
2630 validate_interstage_uniform_blocks(prog, prog->_LinkedShaders,
2631 MESA_SHADER_STAGES);
2632 if (!prog->LinkStatus)
2633 goto done;
2634
2635 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
2636 if (prog->_LinkedShaders[i] != NULL)
2637 lower_named_interface_blocks(mem_ctx, prog->_LinkedShaders[i]);
2638 }
2639
2640 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
2641 * it before optimization because we want most of the checks to get
2642 * dropped thanks to constant propagation.
2643 *
2644 * This rule also applies to GLSL ES 3.00.
2645 */
2646 if (max_version >= (is_es_prog ? 300 : 130)) {
2647 struct gl_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2648 if (sh) {
2649 lower_discard_flow(sh->ir);
2650 }
2651 }
2652
2653 if (!interstage_cross_validate_uniform_blocks(prog))
2654 goto done;
2655
2656 /* Do common optimization before assigning storage for attributes,
2657 * uniforms, and varyings. Later optimization could possibly make
2658 * some of that unused.
2659 */
2660 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2661 if (prog->_LinkedShaders[i] == NULL)
2662 continue;
2663
2664 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
2665 if (!prog->LinkStatus)
2666 goto done;
2667
2668 if (ctx->ShaderCompilerOptions[i].LowerClipDistance) {
2669 lower_clip_distance(prog->_LinkedShaders[i]);
2670 }
2671
2672 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false,
2673 &ctx->ShaderCompilerOptions[i],
2674 ctx->Const.NativeIntegers))
2675 ;
2676 }
2677
2678 /* Check and validate stream emissions in geometry shaders */
2679 validate_geometry_shader_emissions(ctx, prog);
2680
2681 /* Mark all generic shader inputs and outputs as unpaired. */
2682 for (unsigned i = MESA_SHADER_VERTEX; i <= MESA_SHADER_FRAGMENT; i++) {
2683 if (prog->_LinkedShaders[i] != NULL) {
2684 link_invalidate_variable_locations(prog->_LinkedShaders[i]->ir);
2685 }
2686 }
2687
2688 /* FINISHME: The value of the max_attribute_index parameter is
2689 * FINISHME: implementation dependent based on the value of
2690 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
2691 * FINISHME: at least 16, so hardcode 16 for now.
2692 */
2693 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX, 16)) {
2694 goto done;
2695 }
2696
2697 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, MAX2(ctx->Const.MaxDrawBuffers, ctx->Const.MaxDualSourceDrawBuffers))) {
2698 goto done;
2699 }
2700
2701 unsigned first;
2702 for (first = 0; first <= MESA_SHADER_FRAGMENT; first++) {
2703 if (prog->_LinkedShaders[first] != NULL)
2704 break;
2705 }
2706
2707 if (num_tfeedback_decls != 0) {
2708 /* From GL_EXT_transform_feedback:
2709 * A program will fail to link if:
2710 *
2711 * * the <count> specified by TransformFeedbackVaryingsEXT is
2712 * non-zero, but the program object has no vertex or geometry
2713 * shader;
2714 */
2715 if (first == MESA_SHADER_FRAGMENT) {
2716 linker_error(prog, "Transform feedback varyings specified, but "
2717 "no vertex or geometry shader is present.");
2718 goto done;
2719 }
2720
2721 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
2722 prog->TransformFeedback.NumVarying);
2723 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
2724 prog->TransformFeedback.VaryingNames,
2725 tfeedback_decls))
2726 goto done;
2727 }
2728
2729 /* Linking the stages in the opposite order (from fragment to vertex)
2730 * ensures that inter-shader outputs written to in an earlier stage are
2731 * eliminated if they are (transitively) not used in a later stage.
2732 */
2733 int last, next;
2734 for (last = MESA_SHADER_FRAGMENT; last >= 0; last--) {
2735 if (prog->_LinkedShaders[last] != NULL)
2736 break;
2737 }
2738
2739 if (last >= 0 && last < MESA_SHADER_FRAGMENT) {
2740 gl_shader *const sh = prog->_LinkedShaders[last];
2741
2742 if (num_tfeedback_decls != 0 || prog->SeparateShader) {
2743 /* There was no fragment shader, but we still have to assign varying
2744 * locations for use by transform feedback.
2745 */
2746 if (!assign_varying_locations(ctx, mem_ctx, prog,
2747 sh, NULL,
2748 num_tfeedback_decls, tfeedback_decls,
2749 0))
2750 goto done;
2751 }
2752
2753 do_dead_builtin_varyings(ctx, sh, NULL,
2754 num_tfeedback_decls, tfeedback_decls);
2755
2756 if (!prog->SeparateShader)
2757 demote_shader_inputs_and_outputs(sh, ir_var_shader_out);
2758
2759 /* Eliminate code that is now dead due to unused outputs being demoted.
2760 */
2761 while (do_dead_code(sh->ir, false))
2762 ;
2763 }
2764 else if (first == MESA_SHADER_FRAGMENT) {
2765 /* If the program only contains a fragment shader...
2766 */
2767 gl_shader *const sh = prog->_LinkedShaders[first];
2768
2769 do_dead_builtin_varyings(ctx, NULL, sh,
2770 num_tfeedback_decls, tfeedback_decls);
2771
2772 if (prog->SeparateShader) {
2773 if (!assign_varying_locations(ctx, mem_ctx, prog,
2774 NULL /* producer */,
2775 sh /* consumer */,
2776 0 /* num_tfeedback_decls */,
2777 NULL /* tfeedback_decls */,
2778 0 /* gs_input_vertices */))
2779 goto done;
2780 } else
2781 demote_shader_inputs_and_outputs(sh, ir_var_shader_in);
2782
2783 while (do_dead_code(sh->ir, false))
2784 ;
2785 }
2786
2787 next = last;
2788 for (int i = next - 1; i >= 0; i--) {
2789 if (prog->_LinkedShaders[i] == NULL)
2790 continue;
2791
2792 gl_shader *const sh_i = prog->_LinkedShaders[i];
2793 gl_shader *const sh_next = prog->_LinkedShaders[next];
2794 unsigned gs_input_vertices =
2795 next == MESA_SHADER_GEOMETRY ? prog->Geom.VerticesIn : 0;
2796
2797 if (!assign_varying_locations(ctx, mem_ctx, prog, sh_i, sh_next,
2798 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2799 tfeedback_decls, gs_input_vertices))
2800 goto done;
2801
2802 do_dead_builtin_varyings(ctx, sh_i, sh_next,
2803 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2804 tfeedback_decls);
2805
2806 demote_shader_inputs_and_outputs(sh_i, ir_var_shader_out);
2807 demote_shader_inputs_and_outputs(sh_next, ir_var_shader_in);
2808
2809 /* Eliminate code that is now dead due to unused outputs being demoted.
2810 */
2811 while (do_dead_code(sh_i->ir, false))
2812 ;
2813 while (do_dead_code(sh_next->ir, false))
2814 ;
2815
2816 /* This must be done after all dead varyings are eliminated. */
2817 if (!check_against_output_limit(ctx, prog, sh_i))
2818 goto done;
2819 if (!check_against_input_limit(ctx, prog, sh_next))
2820 goto done;
2821
2822 next = i;
2823 }
2824
2825 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
2826 goto done;
2827
2828 update_array_sizes(prog);
2829 link_assign_uniform_locations(prog);
2830 link_assign_atomic_counter_resources(ctx, prog);
2831 store_fragdepth_layout(prog);
2832
2833 check_resources(ctx, prog);
2834 check_image_resources(ctx, prog);
2835 link_check_atomic_counter_resources(ctx, prog);
2836
2837 if (!prog->LinkStatus)
2838 goto done;
2839
2840 /* OpenGL ES requires that a vertex shader and a fragment shader both be
2841 * present in a linked program. GL_ARB_ES2_compatibility doesn't say
2842 * anything about shader linking when one of the shaders (vertex or
2843 * fragment shader) is absent. So, the extension shouldn't change the
2844 * behavior specified in GLSL specification.
2845 */
2846 if (!prog->SeparateShader && ctx->API == API_OPENGLES2) {
2847 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
2848 linker_error(prog, "program lacks a vertex shader\n");
2849 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2850 linker_error(prog, "program lacks a fragment shader\n");
2851 }
2852 }
2853
2854 /* FINISHME: Assign fragment shader output locations. */
2855
2856 done:
2857 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2858 free(shader_list[i]);
2859 if (prog->_LinkedShaders[i] == NULL)
2860 continue;
2861
2862 /* Do a final validation step to make sure that the IR wasn't
2863 * invalidated by any modifications performed after intrastage linking.
2864 */
2865 validate_ir_tree(prog->_LinkedShaders[i]->ir);
2866
2867 /* Retain any live IR, but trash the rest. */
2868 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
2869
2870 /* The symbol table in the linked shaders may contain references to
2871 * variables that were removed (e.g., unused uniforms). Since it may
2872 * contain junk, there is no possible valid use. Delete it and set the
2873 * pointer to NULL.
2874 */
2875 delete prog->_LinkedShaders[i]->symbols;
2876 prog->_LinkedShaders[i]->symbols = NULL;
2877 }
2878
2879 ralloc_free(mem_ctx);
2880 }