glsl: Remove bogus check on return value of link_uniform_blocks().
[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
77 extern "C" {
78 #include "main/shaderobj.h"
79 }
80
81 /**
82 * Visitor that determines whether or not a variable is ever written.
83 */
84 class find_assignment_visitor : public ir_hierarchical_visitor {
85 public:
86 find_assignment_visitor(const char *name)
87 : name(name), found(false)
88 {
89 /* empty */
90 }
91
92 virtual ir_visitor_status visit_enter(ir_assignment *ir)
93 {
94 ir_variable *const var = ir->lhs->variable_referenced();
95
96 if (strcmp(name, var->name) == 0) {
97 found = true;
98 return visit_stop;
99 }
100
101 return visit_continue_with_parent;
102 }
103
104 virtual ir_visitor_status visit_enter(ir_call *ir)
105 {
106 exec_list_iterator sig_iter = ir->callee->parameters.iterator();
107 foreach_iter(exec_list_iterator, iter, *ir) {
108 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
109 ir_variable *sig_param = (ir_variable *)sig_iter.get();
110
111 if (sig_param->mode == ir_var_function_out ||
112 sig_param->mode == ir_var_function_inout) {
113 ir_variable *var = param_rval->variable_referenced();
114 if (var && strcmp(name, var->name) == 0) {
115 found = true;
116 return visit_stop;
117 }
118 }
119 sig_iter.next();
120 }
121
122 if (ir->return_deref != NULL) {
123 ir_variable *const var = ir->return_deref->variable_referenced();
124
125 if (strcmp(name, var->name) == 0) {
126 found = true;
127 return visit_stop;
128 }
129 }
130
131 return visit_continue_with_parent;
132 }
133
134 bool variable_found()
135 {
136 return found;
137 }
138
139 private:
140 const char *name; /**< Find writes to a variable with this name. */
141 bool found; /**< Was a write to the variable found? */
142 };
143
144
145 /**
146 * Visitor that determines whether or not a variable is ever read.
147 */
148 class find_deref_visitor : public ir_hierarchical_visitor {
149 public:
150 find_deref_visitor(const char *name)
151 : name(name), found(false)
152 {
153 /* empty */
154 }
155
156 virtual ir_visitor_status visit(ir_dereference_variable *ir)
157 {
158 if (strcmp(this->name, ir->var->name) == 0) {
159 this->found = true;
160 return visit_stop;
161 }
162
163 return visit_continue;
164 }
165
166 bool variable_found() const
167 {
168 return this->found;
169 }
170
171 private:
172 const char *name; /**< Find writes to a variable with this name. */
173 bool found; /**< Was a write to the variable found? */
174 };
175
176
177 void
178 linker_error(gl_shader_program *prog, const char *fmt, ...)
179 {
180 va_list ap;
181
182 ralloc_strcat(&prog->InfoLog, "error: ");
183 va_start(ap, fmt);
184 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
185 va_end(ap);
186
187 prog->LinkStatus = false;
188 }
189
190
191 void
192 linker_warning(gl_shader_program *prog, const char *fmt, ...)
193 {
194 va_list ap;
195
196 ralloc_strcat(&prog->InfoLog, "error: ");
197 va_start(ap, fmt);
198 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
199 va_end(ap);
200
201 }
202
203
204 /**
205 * Given a string identifying a program resource, break it into a base name
206 * and an optional array index in square brackets.
207 *
208 * If an array index is present, \c out_base_name_end is set to point to the
209 * "[" that precedes the array index, and the array index itself is returned
210 * as a long.
211 *
212 * If no array index is present (or if the array index is negative or
213 * mal-formed), \c out_base_name_end, is set to point to the null terminator
214 * at the end of the input string, and -1 is returned.
215 *
216 * Only the final array index is parsed; if the string contains other array
217 * indices (or structure field accesses), they are left in the base name.
218 *
219 * No attempt is made to check that the base name is properly formed;
220 * typically the caller will look up the base name in a hash table, so
221 * ill-formed base names simply turn into hash table lookup failures.
222 */
223 long
224 parse_program_resource_name(const GLchar *name,
225 const GLchar **out_base_name_end)
226 {
227 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
228 *
229 * "When an integer array element or block instance number is part of
230 * the name string, it will be specified in decimal form without a "+"
231 * or "-" sign or any extra leading zeroes. Additionally, the name
232 * string will not include white space anywhere in the string."
233 */
234
235 const size_t len = strlen(name);
236 *out_base_name_end = name + len;
237
238 if (len == 0 || name[len-1] != ']')
239 return -1;
240
241 /* Walk backwards over the string looking for a non-digit character. This
242 * had better be the opening bracket for an array index.
243 *
244 * Initially, i specifies the location of the ']'. Since the string may
245 * contain only the ']' charcater, walk backwards very carefully.
246 */
247 unsigned i;
248 for (i = len - 1; (i > 0) && isdigit(name[i-1]); --i)
249 /* empty */ ;
250
251 if ((i == 0) || name[i-1] != '[')
252 return -1;
253
254 long array_index = strtol(&name[i], NULL, 10);
255 if (array_index < 0)
256 return -1;
257
258 *out_base_name_end = name + (i - 1);
259 return array_index;
260 }
261
262
263 void
264 link_invalidate_variable_locations(gl_shader *sh, int input_base,
265 int output_base)
266 {
267 foreach_list(node, sh->ir) {
268 ir_variable *const var = ((ir_instruction *) node)->as_variable();
269
270 if (var == NULL)
271 continue;
272
273 int base;
274 switch (var->mode) {
275 case ir_var_shader_in:
276 base = input_base;
277 break;
278 case ir_var_shader_out:
279 base = output_base;
280 break;
281 default:
282 continue;
283 }
284
285 /* Only assign locations for generic attributes / varyings / etc.
286 */
287 if ((var->location >= base) && !var->explicit_location)
288 var->location = -1;
289
290 if ((var->location == -1) && !var->explicit_location) {
291 var->is_unmatched_generic_inout = 1;
292 var->location_frac = 0;
293 } else {
294 var->is_unmatched_generic_inout = 0;
295 }
296 }
297 }
298
299
300 /**
301 * Determine the number of attribute slots required for a particular type
302 *
303 * This code is here because it implements the language rules of a specific
304 * GLSL version. Since it's a property of the language and not a property of
305 * types in general, it doesn't really belong in glsl_type.
306 */
307 unsigned
308 count_attribute_slots(const glsl_type *t)
309 {
310 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
311 *
312 * "A scalar input counts the same amount against this limit as a vec4,
313 * so applications may want to consider packing groups of four
314 * unrelated float inputs together into a vector to better utilize the
315 * capabilities of the underlying hardware. A matrix input will use up
316 * multiple locations. The number of locations used will equal the
317 * number of columns in the matrix."
318 *
319 * The spec does not explicitly say how arrays are counted. However, it
320 * should be safe to assume the total number of slots consumed by an array
321 * is the number of entries in the array multiplied by the number of slots
322 * consumed by a single element of the array.
323 */
324
325 if (t->is_array())
326 return t->array_size() * count_attribute_slots(t->element_type());
327
328 if (t->is_matrix())
329 return t->matrix_columns;
330
331 return 1;
332 }
333
334
335 /**
336 * Verify that a vertex shader executable meets all semantic requirements.
337 *
338 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
339 * as a side effect.
340 *
341 * \param shader Vertex shader executable to be verified
342 */
343 bool
344 validate_vertex_shader_executable(struct gl_shader_program *prog,
345 struct gl_shader *shader)
346 {
347 if (shader == NULL)
348 return true;
349
350 /* From the GLSL 1.10 spec, page 48:
351 *
352 * "The variable gl_Position is available only in the vertex
353 * language and is intended for writing the homogeneous vertex
354 * position. All executions of a well-formed vertex shader
355 * executable must write a value into this variable. [...] The
356 * variable gl_Position is available only in the vertex
357 * language and is intended for writing the homogeneous vertex
358 * position. All executions of a well-formed vertex shader
359 * executable must write a value into this variable."
360 *
361 * while in GLSL 1.40 this text is changed to:
362 *
363 * "The variable gl_Position is available only in the vertex
364 * language and is intended for writing the homogeneous vertex
365 * position. It can be written at any time during shader
366 * execution. It may also be read back by a vertex shader
367 * after being written. This value will be used by primitive
368 * assembly, clipping, culling, and other fixed functionality
369 * operations, if present, that operate on primitives after
370 * vertex processing has occurred. Its value is undefined if
371 * the vertex shader executable does not write gl_Position."
372 *
373 * GLSL ES 3.00 is similar to GLSL 1.40--failing to write to gl_Position is
374 * not an error.
375 */
376 if (prog->Version < (prog->IsES ? 300 : 140)) {
377 find_assignment_visitor find("gl_Position");
378 find.run(shader->ir);
379 if (!find.variable_found()) {
380 linker_error(prog, "vertex shader does not write to `gl_Position'\n");
381 return false;
382 }
383 }
384
385 prog->Vert.ClipDistanceArraySize = 0;
386
387 if (!prog->IsES && prog->Version >= 130) {
388 /* From section 7.1 (Vertex Shader Special Variables) of the
389 * GLSL 1.30 spec:
390 *
391 * "It is an error for a shader to statically write both
392 * gl_ClipVertex and gl_ClipDistance."
393 *
394 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
395 * gl_ClipVertex nor gl_ClipDistance.
396 */
397 find_assignment_visitor clip_vertex("gl_ClipVertex");
398 find_assignment_visitor clip_distance("gl_ClipDistance");
399
400 clip_vertex.run(shader->ir);
401 clip_distance.run(shader->ir);
402 if (clip_vertex.variable_found() && clip_distance.variable_found()) {
403 linker_error(prog, "vertex shader writes to both `gl_ClipVertex' "
404 "and `gl_ClipDistance'\n");
405 return false;
406 }
407 prog->Vert.UsesClipDistance = clip_distance.variable_found();
408 ir_variable *clip_distance_var =
409 shader->symbols->get_variable("gl_ClipDistance");
410 if (clip_distance_var)
411 prog->Vert.ClipDistanceArraySize = clip_distance_var->type->length;
412 }
413
414 return true;
415 }
416
417
418 /**
419 * Verify that a fragment shader executable meets all semantic requirements
420 *
421 * \param shader Fragment shader executable to be verified
422 */
423 bool
424 validate_fragment_shader_executable(struct gl_shader_program *prog,
425 struct gl_shader *shader)
426 {
427 if (shader == NULL)
428 return true;
429
430 find_assignment_visitor frag_color("gl_FragColor");
431 find_assignment_visitor frag_data("gl_FragData");
432
433 frag_color.run(shader->ir);
434 frag_data.run(shader->ir);
435
436 if (frag_color.variable_found() && frag_data.variable_found()) {
437 linker_error(prog, "fragment shader writes to both "
438 "`gl_FragColor' and `gl_FragData'\n");
439 return false;
440 }
441
442 return true;
443 }
444
445
446 /**
447 * Generate a string describing the mode of a variable
448 */
449 static const char *
450 mode_string(const ir_variable *var)
451 {
452 switch (var->mode) {
453 case ir_var_auto:
454 return (var->read_only) ? "global constant" : "global variable";
455
456 case ir_var_uniform: return "uniform";
457 case ir_var_shader_in: return "shader input";
458 case ir_var_shader_out: return "shader output";
459
460 case ir_var_const_in:
461 case ir_var_temporary:
462 default:
463 assert(!"Should not get here.");
464 return "invalid variable";
465 }
466 }
467
468
469 /**
470 * Perform validation of global variables used across multiple shaders
471 */
472 bool
473 cross_validate_globals(struct gl_shader_program *prog,
474 struct gl_shader **shader_list,
475 unsigned num_shaders,
476 bool uniforms_only)
477 {
478 /* Examine all of the uniforms in all of the shaders and cross validate
479 * them.
480 */
481 glsl_symbol_table variables;
482 for (unsigned i = 0; i < num_shaders; i++) {
483 if (shader_list[i] == NULL)
484 continue;
485
486 foreach_list(node, shader_list[i]->ir) {
487 ir_variable *const var = ((ir_instruction *) node)->as_variable();
488
489 if (var == NULL)
490 continue;
491
492 if (uniforms_only && (var->mode != ir_var_uniform))
493 continue;
494
495 /* Don't cross validate temporaries that are at global scope. These
496 * will eventually get pulled into the shaders 'main'.
497 */
498 if (var->mode == ir_var_temporary)
499 continue;
500
501 /* If a global with this name has already been seen, verify that the
502 * new instance has the same type. In addition, if the globals have
503 * initializers, the values of the initializers must be the same.
504 */
505 ir_variable *const existing = variables.get_variable(var->name);
506 if (existing != NULL) {
507 if (var->type != existing->type) {
508 /* Consider the types to be "the same" if both types are arrays
509 * of the same type and one of the arrays is implicitly sized.
510 * In addition, set the type of the linked variable to the
511 * explicitly sized array.
512 */
513 if (var->type->is_array()
514 && existing->type->is_array()
515 && (var->type->fields.array == existing->type->fields.array)
516 && ((var->type->length == 0)
517 || (existing->type->length == 0))) {
518 if (var->type->length != 0) {
519 existing->type = var->type;
520 }
521 } else {
522 linker_error(prog, "%s `%s' declared as type "
523 "`%s' and type `%s'\n",
524 mode_string(var),
525 var->name, var->type->name,
526 existing->type->name);
527 return false;
528 }
529 }
530
531 if (var->explicit_location) {
532 if (existing->explicit_location
533 && (var->location != existing->location)) {
534 linker_error(prog, "explicit locations for %s "
535 "`%s' have differing values\n",
536 mode_string(var), var->name);
537 return false;
538 }
539
540 existing->location = var->location;
541 existing->explicit_location = true;
542 }
543
544 /* From the GLSL 4.20 specification:
545 * "A link error will result if two compilation units in a program
546 * specify different integer-constant bindings for the same
547 * opaque-uniform name. However, it is not an error to specify a
548 * binding on some but not all declarations for the same name"
549 */
550 if (var->explicit_binding) {
551 if (existing->explicit_binding &&
552 var->binding != existing->binding) {
553 linker_error(prog, "explicit bindings for %s "
554 "`%s' have differing values\n",
555 mode_string(var), var->name);
556 return false;
557 }
558
559 existing->binding = var->binding;
560 existing->explicit_binding = true;
561 }
562
563 /* Validate layout qualifiers for gl_FragDepth.
564 *
565 * From the AMD/ARB_conservative_depth specs:
566 *
567 * "If gl_FragDepth is redeclared in any fragment shader in a
568 * program, it must be redeclared in all fragment shaders in
569 * that program that have static assignments to
570 * gl_FragDepth. All redeclarations of gl_FragDepth in all
571 * fragment shaders in a single program must have the same set
572 * of qualifiers."
573 */
574 if (strcmp(var->name, "gl_FragDepth") == 0) {
575 bool layout_declared = var->depth_layout != ir_depth_layout_none;
576 bool layout_differs =
577 var->depth_layout != existing->depth_layout;
578
579 if (layout_declared && layout_differs) {
580 linker_error(prog,
581 "All redeclarations of gl_FragDepth in all "
582 "fragment shaders in a single program must have "
583 "the same set of qualifiers.");
584 }
585
586 if (var->used && layout_differs) {
587 linker_error(prog,
588 "If gl_FragDepth is redeclared with a layout "
589 "qualifier in any fragment shader, it must be "
590 "redeclared with the same layout qualifier in "
591 "all fragment shaders that have assignments to "
592 "gl_FragDepth");
593 }
594 }
595
596 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
597 *
598 * "If a shared global has multiple initializers, the
599 * initializers must all be constant expressions, and they
600 * must all have the same value. Otherwise, a link error will
601 * result. (A shared global having only one initializer does
602 * not require that initializer to be a constant expression.)"
603 *
604 * Previous to 4.20 the GLSL spec simply said that initializers
605 * must have the same value. In this case of non-constant
606 * initializers, this was impossible to determine. As a result,
607 * no vendor actually implemented that behavior. The 4.20
608 * behavior matches the implemented behavior of at least one other
609 * vendor, so we'll implement that for all GLSL versions.
610 */
611 if (var->constant_initializer != NULL) {
612 if (existing->constant_initializer != NULL) {
613 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
614 linker_error(prog, "initializers for %s "
615 "`%s' have differing values\n",
616 mode_string(var), var->name);
617 return false;
618 }
619 } else {
620 /* If the first-seen instance of a particular uniform did not
621 * have an initializer but a later instance does, copy the
622 * initializer to the version stored in the symbol table.
623 */
624 /* FINISHME: This is wrong. The constant_value field should
625 * FINISHME: not be modified! Imagine a case where a shader
626 * FINISHME: without an initializer is linked in two different
627 * FINISHME: programs with shaders that have differing
628 * FINISHME: initializers. Linking with the first will
629 * FINISHME: modify the shader, and linking with the second
630 * FINISHME: will fail.
631 */
632 existing->constant_initializer =
633 var->constant_initializer->clone(ralloc_parent(existing),
634 NULL);
635 }
636 }
637
638 if (var->has_initializer) {
639 if (existing->has_initializer
640 && (var->constant_initializer == NULL
641 || existing->constant_initializer == NULL)) {
642 linker_error(prog,
643 "shared global variable `%s' has multiple "
644 "non-constant initializers.\n",
645 var->name);
646 return false;
647 }
648
649 /* Some instance had an initializer, so keep track of that. In
650 * this location, all sorts of initializers (constant or
651 * otherwise) will propagate the existence to the variable
652 * stored in the symbol table.
653 */
654 existing->has_initializer = true;
655 }
656
657 if (existing->invariant != var->invariant) {
658 linker_error(prog, "declarations for %s `%s' have "
659 "mismatching invariant qualifiers\n",
660 mode_string(var), var->name);
661 return false;
662 }
663 if (existing->centroid != var->centroid) {
664 linker_error(prog, "declarations for %s `%s' have "
665 "mismatching centroid qualifiers\n",
666 mode_string(var), var->name);
667 return false;
668 }
669 } else
670 variables.add_variable(var);
671 }
672 }
673
674 return true;
675 }
676
677
678 /**
679 * Perform validation of uniforms used across multiple shader stages
680 */
681 bool
682 cross_validate_uniforms(struct gl_shader_program *prog)
683 {
684 return cross_validate_globals(prog, prog->_LinkedShaders,
685 MESA_SHADER_TYPES, true);
686 }
687
688 /**
689 * Accumulates the array of prog->UniformBlocks and checks that all
690 * definitons of blocks agree on their contents.
691 */
692 static bool
693 interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog)
694 {
695 unsigned max_num_uniform_blocks = 0;
696 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
697 if (prog->_LinkedShaders[i])
698 max_num_uniform_blocks += prog->_LinkedShaders[i]->NumUniformBlocks;
699 }
700
701 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
702 struct gl_shader *sh = prog->_LinkedShaders[i];
703
704 prog->UniformBlockStageIndex[i] = ralloc_array(prog, int,
705 max_num_uniform_blocks);
706 for (unsigned int j = 0; j < max_num_uniform_blocks; j++)
707 prog->UniformBlockStageIndex[i][j] = -1;
708
709 if (sh == NULL)
710 continue;
711
712 for (unsigned int j = 0; j < sh->NumUniformBlocks; j++) {
713 int index = link_cross_validate_uniform_block(prog,
714 &prog->UniformBlocks,
715 &prog->NumUniformBlocks,
716 &sh->UniformBlocks[j]);
717
718 if (index == -1) {
719 linker_error(prog, "uniform block `%s' has mismatching definitions",
720 sh->UniformBlocks[j].Name);
721 return false;
722 }
723
724 prog->UniformBlockStageIndex[i][index] = j;
725 }
726 }
727
728 return true;
729 }
730
731
732 /**
733 * Populates a shaders symbol table with all global declarations
734 */
735 static void
736 populate_symbol_table(gl_shader *sh)
737 {
738 sh->symbols = new(sh) glsl_symbol_table;
739
740 foreach_list(node, sh->ir) {
741 ir_instruction *const inst = (ir_instruction *) node;
742 ir_variable *var;
743 ir_function *func;
744
745 if ((func = inst->as_function()) != NULL) {
746 sh->symbols->add_function(func);
747 } else if ((var = inst->as_variable()) != NULL) {
748 sh->symbols->add_variable(var);
749 }
750 }
751 }
752
753
754 /**
755 * Remap variables referenced in an instruction tree
756 *
757 * This is used when instruction trees are cloned from one shader and placed in
758 * another. These trees will contain references to \c ir_variable nodes that
759 * do not exist in the target shader. This function finds these \c ir_variable
760 * references and replaces the references with matching variables in the target
761 * shader.
762 *
763 * If there is no matching variable in the target shader, a clone of the
764 * \c ir_variable is made and added to the target shader. The new variable is
765 * added to \b both the instruction stream and the symbol table.
766 *
767 * \param inst IR tree that is to be processed.
768 * \param symbols Symbol table containing global scope symbols in the
769 * linked shader.
770 * \param instructions Instruction stream where new variable declarations
771 * should be added.
772 */
773 void
774 remap_variables(ir_instruction *inst, struct gl_shader *target,
775 hash_table *temps)
776 {
777 class remap_visitor : public ir_hierarchical_visitor {
778 public:
779 remap_visitor(struct gl_shader *target,
780 hash_table *temps)
781 {
782 this->target = target;
783 this->symbols = target->symbols;
784 this->instructions = target->ir;
785 this->temps = temps;
786 }
787
788 virtual ir_visitor_status visit(ir_dereference_variable *ir)
789 {
790 if (ir->var->mode == ir_var_temporary) {
791 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
792
793 assert(var != NULL);
794 ir->var = var;
795 return visit_continue;
796 }
797
798 ir_variable *const existing =
799 this->symbols->get_variable(ir->var->name);
800 if (existing != NULL)
801 ir->var = existing;
802 else {
803 ir_variable *copy = ir->var->clone(this->target, NULL);
804
805 this->symbols->add_variable(copy);
806 this->instructions->push_head(copy);
807 ir->var = copy;
808 }
809
810 return visit_continue;
811 }
812
813 private:
814 struct gl_shader *target;
815 glsl_symbol_table *symbols;
816 exec_list *instructions;
817 hash_table *temps;
818 };
819
820 remap_visitor v(target, temps);
821
822 inst->accept(&v);
823 }
824
825
826 /**
827 * Move non-declarations from one instruction stream to another
828 *
829 * The intended usage pattern of this function is to pass the pointer to the
830 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
831 * pointer) for \c last and \c false for \c make_copies on the first
832 * call. Successive calls pass the return value of the previous call for
833 * \c last and \c true for \c make_copies.
834 *
835 * \param instructions Source instruction stream
836 * \param last Instruction after which new instructions should be
837 * inserted in the target instruction stream
838 * \param make_copies Flag selecting whether instructions in \c instructions
839 * should be copied (via \c ir_instruction::clone) into the
840 * target list or moved.
841 *
842 * \return
843 * The new "last" instruction in the target instruction stream. This pointer
844 * is suitable for use as the \c last parameter of a later call to this
845 * function.
846 */
847 exec_node *
848 move_non_declarations(exec_list *instructions, exec_node *last,
849 bool make_copies, gl_shader *target)
850 {
851 hash_table *temps = NULL;
852
853 if (make_copies)
854 temps = hash_table_ctor(0, hash_table_pointer_hash,
855 hash_table_pointer_compare);
856
857 foreach_list_safe(node, instructions) {
858 ir_instruction *inst = (ir_instruction *) node;
859
860 if (inst->as_function())
861 continue;
862
863 ir_variable *var = inst->as_variable();
864 if ((var != NULL) && (var->mode != ir_var_temporary))
865 continue;
866
867 assert(inst->as_assignment()
868 || inst->as_call()
869 || inst->as_if() /* for initializers with the ?: operator */
870 || ((var != NULL) && (var->mode == ir_var_temporary)));
871
872 if (make_copies) {
873 inst = inst->clone(target, NULL);
874
875 if (var != NULL)
876 hash_table_insert(temps, inst, var);
877 else
878 remap_variables(inst, target, temps);
879 } else {
880 inst->remove();
881 }
882
883 last->insert_after(inst);
884 last = inst;
885 }
886
887 if (make_copies)
888 hash_table_dtor(temps);
889
890 return last;
891 }
892
893 /**
894 * Get the function signature for main from a shader
895 */
896 static ir_function_signature *
897 get_main_function_signature(gl_shader *sh)
898 {
899 ir_function *const f = sh->symbols->get_function("main");
900 if (f != NULL) {
901 exec_list void_parameters;
902
903 /* Look for the 'void main()' signature and ensure that it's defined.
904 * This keeps the linker from accidentally pick a shader that just
905 * contains a prototype for main.
906 *
907 * We don't have to check for multiple definitions of main (in multiple
908 * shaders) because that would have already been caught above.
909 */
910 ir_function_signature *sig = f->matching_signature(&void_parameters);
911 if ((sig != NULL) && sig->is_defined) {
912 return sig;
913 }
914 }
915
916 return NULL;
917 }
918
919
920 /**
921 * This class is only used in link_intrastage_shaders() below but declaring
922 * it inside that function leads to compiler warnings with some versions of
923 * gcc.
924 */
925 class array_sizing_visitor : public ir_hierarchical_visitor {
926 public:
927 virtual ir_visitor_status visit(ir_variable *var)
928 {
929 if (var->type->is_array() && (var->type->length == 0)) {
930 const glsl_type *type =
931 glsl_type::get_array_instance(var->type->fields.array,
932 var->max_array_access + 1);
933 assert(type != NULL);
934 var->type = type;
935 }
936 return visit_continue;
937 }
938 };
939
940 /**
941 * Combine a group of shaders for a single stage to generate a linked shader
942 *
943 * \note
944 * If this function is supplied a single shader, it is cloned, and the new
945 * shader is returned.
946 */
947 static struct gl_shader *
948 link_intrastage_shaders(void *mem_ctx,
949 struct gl_context *ctx,
950 struct gl_shader_program *prog,
951 struct gl_shader **shader_list,
952 unsigned num_shaders)
953 {
954 struct gl_uniform_block *uniform_blocks = NULL;
955
956 /* Check that global variables defined in multiple shaders are consistent.
957 */
958 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
959 return NULL;
960
961 /* Check that interface blocks defined in multiple shaders are consistent.
962 */
963 if (!validate_intrastage_interface_blocks((const gl_shader **)shader_list,
964 num_shaders))
965 return NULL;
966
967 /* Link up uniform blocks defined within this stage. */
968 const unsigned num_uniform_blocks =
969 link_uniform_blocks(mem_ctx, prog, shader_list, num_shaders,
970 &uniform_blocks);
971
972 /* Check that there is only a single definition of each function signature
973 * across all shaders.
974 */
975 for (unsigned i = 0; i < (num_shaders - 1); i++) {
976 foreach_list(node, shader_list[i]->ir) {
977 ir_function *const f = ((ir_instruction *) node)->as_function();
978
979 if (f == NULL)
980 continue;
981
982 for (unsigned j = i + 1; j < num_shaders; j++) {
983 ir_function *const other =
984 shader_list[j]->symbols->get_function(f->name);
985
986 /* If the other shader has no function (and therefore no function
987 * signatures) with the same name, skip to the next shader.
988 */
989 if (other == NULL)
990 continue;
991
992 foreach_iter (exec_list_iterator, iter, *f) {
993 ir_function_signature *sig =
994 (ir_function_signature *) iter.get();
995
996 if (!sig->is_defined || sig->is_builtin)
997 continue;
998
999 ir_function_signature *other_sig =
1000 other->exact_matching_signature(& sig->parameters);
1001
1002 if ((other_sig != NULL) && other_sig->is_defined
1003 && !other_sig->is_builtin) {
1004 linker_error(prog, "function `%s' is multiply defined",
1005 f->name);
1006 return NULL;
1007 }
1008 }
1009 }
1010 }
1011 }
1012
1013 /* Find the shader that defines main, and make a clone of it.
1014 *
1015 * Starting with the clone, search for undefined references. If one is
1016 * found, find the shader that defines it. Clone the reference and add
1017 * it to the shader. Repeat until there are no undefined references or
1018 * until a reference cannot be resolved.
1019 */
1020 gl_shader *main = NULL;
1021 for (unsigned i = 0; i < num_shaders; i++) {
1022 if (get_main_function_signature(shader_list[i]) != NULL) {
1023 main = shader_list[i];
1024 break;
1025 }
1026 }
1027
1028 if (main == NULL) {
1029 linker_error(prog, "%s shader lacks `main'\n",
1030 _mesa_glsl_shader_target_name(shader_list[0]->Type));
1031 return NULL;
1032 }
1033
1034 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
1035 linked->ir = new(linked) exec_list;
1036 clone_ir_list(mem_ctx, linked->ir, main->ir);
1037
1038 linked->UniformBlocks = uniform_blocks;
1039 linked->NumUniformBlocks = num_uniform_blocks;
1040 ralloc_steal(linked, linked->UniformBlocks);
1041
1042 populate_symbol_table(linked);
1043
1044 /* The a pointer to the main function in the final linked shader (i.e., the
1045 * copy of the original shader that contained the main function).
1046 */
1047 ir_function_signature *const main_sig = get_main_function_signature(linked);
1048
1049 /* Move any instructions other than variable declarations or function
1050 * declarations into main.
1051 */
1052 exec_node *insertion_point =
1053 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
1054 linked);
1055
1056 for (unsigned i = 0; i < num_shaders; i++) {
1057 if (shader_list[i] == main)
1058 continue;
1059
1060 insertion_point = move_non_declarations(shader_list[i]->ir,
1061 insertion_point, true, linked);
1062 }
1063
1064 /* Resolve initializers for global variables in the linked shader.
1065 */
1066 unsigned num_linking_shaders = num_shaders;
1067 for (unsigned i = 0; i < num_shaders; i++)
1068 num_linking_shaders += shader_list[i]->num_builtins_to_link;
1069
1070 gl_shader **linking_shaders =
1071 (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
1072
1073 memcpy(linking_shaders, shader_list,
1074 sizeof(linking_shaders[0]) * num_shaders);
1075
1076 unsigned idx = num_shaders;
1077 for (unsigned i = 0; i < num_shaders; i++) {
1078 memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
1079 sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
1080 idx += shader_list[i]->num_builtins_to_link;
1081 }
1082
1083 assert(idx == num_linking_shaders);
1084
1085 if (!link_function_calls(prog, linked, linking_shaders,
1086 num_linking_shaders)) {
1087 ctx->Driver.DeleteShader(ctx, linked);
1088 linked = NULL;
1089 }
1090
1091 free(linking_shaders);
1092
1093 /* At this point linked should contain all of the linked IR, so
1094 * validate it to make sure nothing went wrong.
1095 */
1096 if (linked)
1097 validate_ir_tree(linked->ir);
1098
1099 /* Make a pass over all variable declarations to ensure that arrays with
1100 * unspecified sizes have a size specified. The size is inferred from the
1101 * max_array_access field.
1102 */
1103 if (linked != NULL) {
1104 array_sizing_visitor v;
1105
1106 v.run(linked->ir);
1107 }
1108
1109 return linked;
1110 }
1111
1112 /**
1113 * Update the sizes of linked shader uniform arrays to the maximum
1114 * array index used.
1115 *
1116 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1117 *
1118 * If one or more elements of an array are active,
1119 * GetActiveUniform will return the name of the array in name,
1120 * subject to the restrictions listed above. The type of the array
1121 * is returned in type. The size parameter contains the highest
1122 * array element index used, plus one. The compiler or linker
1123 * determines the highest index used. There will be only one
1124 * active uniform reported by the GL per uniform array.
1125
1126 */
1127 static void
1128 update_array_sizes(struct gl_shader_program *prog)
1129 {
1130 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1131 if (prog->_LinkedShaders[i] == NULL)
1132 continue;
1133
1134 foreach_list(node, prog->_LinkedShaders[i]->ir) {
1135 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1136
1137 if ((var == NULL) || (var->mode != ir_var_uniform &&
1138 var->mode != ir_var_shader_in &&
1139 var->mode != ir_var_shader_out) ||
1140 !var->type->is_array())
1141 continue;
1142
1143 /* GL_ARB_uniform_buffer_object says that std140 uniforms
1144 * will not be eliminated. Since we always do std140, just
1145 * don't resize arrays in UBOs.
1146 */
1147 if (var->is_in_uniform_block())
1148 continue;
1149
1150 unsigned int size = var->max_array_access;
1151 for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
1152 if (prog->_LinkedShaders[j] == NULL)
1153 continue;
1154
1155 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
1156 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
1157 if (!other_var)
1158 continue;
1159
1160 if (strcmp(var->name, other_var->name) == 0 &&
1161 other_var->max_array_access > size) {
1162 size = other_var->max_array_access;
1163 }
1164 }
1165 }
1166
1167 if (size + 1 != var->type->length) {
1168 /* If this is a built-in uniform (i.e., it's backed by some
1169 * fixed-function state), adjust the number of state slots to
1170 * match the new array size. The number of slots per array entry
1171 * is not known. It seems safe to assume that the total number of
1172 * slots is an integer multiple of the number of array elements.
1173 * Determine the number of slots per array element by dividing by
1174 * the old (total) size.
1175 */
1176 if (var->num_state_slots > 0) {
1177 var->num_state_slots = (size + 1)
1178 * (var->num_state_slots / var->type->length);
1179 }
1180
1181 var->type = glsl_type::get_array_instance(var->type->fields.array,
1182 size + 1);
1183 /* FINISHME: We should update the types of array
1184 * dereferences of this variable now.
1185 */
1186 }
1187 }
1188 }
1189 }
1190
1191 /**
1192 * Find a contiguous set of available bits in a bitmask.
1193 *
1194 * \param used_mask Bits representing used (1) and unused (0) locations
1195 * \param needed_count Number of contiguous bits needed.
1196 *
1197 * \return
1198 * Base location of the available bits on success or -1 on failure.
1199 */
1200 int
1201 find_available_slots(unsigned used_mask, unsigned needed_count)
1202 {
1203 unsigned needed_mask = (1 << needed_count) - 1;
1204 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1205
1206 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1207 * cannot optimize possibly infinite loops" for the loop below.
1208 */
1209 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1210 return -1;
1211
1212 for (int i = 0; i <= max_bit_to_test; i++) {
1213 if ((needed_mask & ~used_mask) == needed_mask)
1214 return i;
1215
1216 needed_mask <<= 1;
1217 }
1218
1219 return -1;
1220 }
1221
1222
1223 /**
1224 * Assign locations for either VS inputs for FS outputs
1225 *
1226 * \param prog Shader program whose variables need locations assigned
1227 * \param target_index Selector for the program target to receive location
1228 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1229 * \c MESA_SHADER_FRAGMENT.
1230 * \param max_index Maximum number of generic locations. This corresponds
1231 * to either the maximum number of draw buffers or the
1232 * maximum number of generic attributes.
1233 *
1234 * \return
1235 * If locations are successfully assigned, true is returned. Otherwise an
1236 * error is emitted to the shader link log and false is returned.
1237 */
1238 bool
1239 assign_attribute_or_color_locations(gl_shader_program *prog,
1240 unsigned target_index,
1241 unsigned max_index)
1242 {
1243 /* Mark invalid locations as being used.
1244 */
1245 unsigned used_locations = (max_index >= 32)
1246 ? ~0 : ~((1 << max_index) - 1);
1247
1248 assert((target_index == MESA_SHADER_VERTEX)
1249 || (target_index == MESA_SHADER_FRAGMENT));
1250
1251 gl_shader *const sh = prog->_LinkedShaders[target_index];
1252 if (sh == NULL)
1253 return true;
1254
1255 /* Operate in a total of four passes.
1256 *
1257 * 1. Invalidate the location assignments for all vertex shader inputs.
1258 *
1259 * 2. Assign locations for inputs that have user-defined (via
1260 * glBindVertexAttribLocation) locations and outputs that have
1261 * user-defined locations (via glBindFragDataLocation).
1262 *
1263 * 3. Sort the attributes without assigned locations by number of slots
1264 * required in decreasing order. Fragmentation caused by attribute
1265 * locations assigned by the application may prevent large attributes
1266 * from having enough contiguous space.
1267 *
1268 * 4. Assign locations to any inputs without assigned locations.
1269 */
1270
1271 const int generic_base = (target_index == MESA_SHADER_VERTEX)
1272 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
1273
1274 const enum ir_variable_mode direction =
1275 (target_index == MESA_SHADER_VERTEX)
1276 ? ir_var_shader_in : ir_var_shader_out;
1277
1278
1279 /* Temporary storage for the set of attributes that need locations assigned.
1280 */
1281 struct temp_attr {
1282 unsigned slots;
1283 ir_variable *var;
1284
1285 /* Used below in the call to qsort. */
1286 static int compare(const void *a, const void *b)
1287 {
1288 const temp_attr *const l = (const temp_attr *) a;
1289 const temp_attr *const r = (const temp_attr *) b;
1290
1291 /* Reversed because we want a descending order sort below. */
1292 return r->slots - l->slots;
1293 }
1294 } to_assign[16];
1295
1296 unsigned num_attr = 0;
1297
1298 foreach_list(node, sh->ir) {
1299 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1300
1301 if ((var == NULL) || (var->mode != (unsigned) direction))
1302 continue;
1303
1304 if (var->explicit_location) {
1305 if ((var->location >= (int)(max_index + generic_base))
1306 || (var->location < 0)) {
1307 linker_error(prog,
1308 "invalid explicit location %d specified for `%s'\n",
1309 (var->location < 0)
1310 ? var->location : var->location - generic_base,
1311 var->name);
1312 return false;
1313 }
1314 } else if (target_index == MESA_SHADER_VERTEX) {
1315 unsigned binding;
1316
1317 if (prog->AttributeBindings->get(binding, var->name)) {
1318 assert(binding >= VERT_ATTRIB_GENERIC0);
1319 var->location = binding;
1320 var->is_unmatched_generic_inout = 0;
1321 }
1322 } else if (target_index == MESA_SHADER_FRAGMENT) {
1323 unsigned binding;
1324 unsigned index;
1325
1326 if (prog->FragDataBindings->get(binding, var->name)) {
1327 assert(binding >= FRAG_RESULT_DATA0);
1328 var->location = binding;
1329 var->is_unmatched_generic_inout = 0;
1330
1331 if (prog->FragDataIndexBindings->get(index, var->name)) {
1332 var->index = index;
1333 }
1334 }
1335 }
1336
1337 /* If the variable is not a built-in and has a location statically
1338 * assigned in the shader (presumably via a layout qualifier), make sure
1339 * that it doesn't collide with other assigned locations. Otherwise,
1340 * add it to the list of variables that need linker-assigned locations.
1341 */
1342 const unsigned slots = count_attribute_slots(var->type);
1343 if (var->location != -1) {
1344 if (var->location >= generic_base && var->index < 1) {
1345 /* From page 61 of the OpenGL 4.0 spec:
1346 *
1347 * "LinkProgram will fail if the attribute bindings assigned
1348 * by BindAttribLocation do not leave not enough space to
1349 * assign a location for an active matrix attribute or an
1350 * active attribute array, both of which require multiple
1351 * contiguous generic attributes."
1352 *
1353 * Previous versions of the spec contain similar language but omit
1354 * the bit about attribute arrays.
1355 *
1356 * Page 61 of the OpenGL 4.0 spec also says:
1357 *
1358 * "It is possible for an application to bind more than one
1359 * attribute name to the same location. This is referred to as
1360 * aliasing. This will only work if only one of the aliased
1361 * attributes is active in the executable program, or if no
1362 * path through the shader consumes more than one attribute of
1363 * a set of attributes aliased to the same location. A link
1364 * error can occur if the linker determines that every path
1365 * through the shader consumes multiple aliased attributes,
1366 * but implementations are not required to generate an error
1367 * in this case."
1368 *
1369 * These two paragraphs are either somewhat contradictory, or I
1370 * don't fully understand one or both of them.
1371 */
1372 /* FINISHME: The code as currently written does not support
1373 * FINISHME: attribute location aliasing (see comment above).
1374 */
1375 /* Mask representing the contiguous slots that will be used by
1376 * this attribute.
1377 */
1378 const unsigned attr = var->location - generic_base;
1379 const unsigned use_mask = (1 << slots) - 1;
1380
1381 /* Generate a link error if the set of bits requested for this
1382 * attribute overlaps any previously allocated bits.
1383 */
1384 if ((~(use_mask << attr) & used_locations) != used_locations) {
1385 const char *const string = (target_index == MESA_SHADER_VERTEX)
1386 ? "vertex shader input" : "fragment shader output";
1387 linker_error(prog,
1388 "insufficient contiguous locations "
1389 "available for %s `%s' %d %d %d", string,
1390 var->name, used_locations, use_mask, attr);
1391 return false;
1392 }
1393
1394 used_locations |= (use_mask << attr);
1395 }
1396
1397 continue;
1398 }
1399
1400 to_assign[num_attr].slots = slots;
1401 to_assign[num_attr].var = var;
1402 num_attr++;
1403 }
1404
1405 /* If all of the attributes were assigned locations by the application (or
1406 * are built-in attributes with fixed locations), return early. This should
1407 * be the common case.
1408 */
1409 if (num_attr == 0)
1410 return true;
1411
1412 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1413
1414 if (target_index == MESA_SHADER_VERTEX) {
1415 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1416 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1417 * reserved to prevent it from being automatically allocated below.
1418 */
1419 find_deref_visitor find("gl_Vertex");
1420 find.run(sh->ir);
1421 if (find.variable_found())
1422 used_locations |= (1 << 0);
1423 }
1424
1425 for (unsigned i = 0; i < num_attr; i++) {
1426 /* Mask representing the contiguous slots that will be used by this
1427 * attribute.
1428 */
1429 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1430
1431 int location = find_available_slots(used_locations, to_assign[i].slots);
1432
1433 if (location < 0) {
1434 const char *const string = (target_index == MESA_SHADER_VERTEX)
1435 ? "vertex shader input" : "fragment shader output";
1436
1437 linker_error(prog,
1438 "insufficient contiguous locations "
1439 "available for %s `%s'",
1440 string, to_assign[i].var->name);
1441 return false;
1442 }
1443
1444 to_assign[i].var->location = generic_base + location;
1445 to_assign[i].var->is_unmatched_generic_inout = 0;
1446 used_locations |= (use_mask << location);
1447 }
1448
1449 return true;
1450 }
1451
1452
1453 /**
1454 * Demote shader inputs and outputs that are not used in other stages
1455 */
1456 void
1457 demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
1458 {
1459 foreach_list(node, sh->ir) {
1460 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1461
1462 if ((var == NULL) || (var->mode != int(mode)))
1463 continue;
1464
1465 /* A shader 'in' or 'out' variable is only really an input or output if
1466 * its value is used by other shader stages. This will cause the variable
1467 * to have a location assigned.
1468 */
1469 if (var->is_unmatched_generic_inout) {
1470 var->mode = ir_var_auto;
1471 }
1472 }
1473 }
1474
1475
1476 /**
1477 * Store the gl_FragDepth layout in the gl_shader_program struct.
1478 */
1479 static void
1480 store_fragdepth_layout(struct gl_shader_program *prog)
1481 {
1482 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
1483 return;
1484 }
1485
1486 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
1487
1488 /* We don't look up the gl_FragDepth symbol directly because if
1489 * gl_FragDepth is not used in the shader, it's removed from the IR.
1490 * However, the symbol won't be removed from the symbol table.
1491 *
1492 * We're only interested in the cases where the variable is NOT removed
1493 * from the IR.
1494 */
1495 foreach_list(node, ir) {
1496 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1497
1498 if (var == NULL || var->mode != ir_var_shader_out) {
1499 continue;
1500 }
1501
1502 if (strcmp(var->name, "gl_FragDepth") == 0) {
1503 switch (var->depth_layout) {
1504 case ir_depth_layout_none:
1505 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
1506 return;
1507 case ir_depth_layout_any:
1508 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
1509 return;
1510 case ir_depth_layout_greater:
1511 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
1512 return;
1513 case ir_depth_layout_less:
1514 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
1515 return;
1516 case ir_depth_layout_unchanged:
1517 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
1518 return;
1519 default:
1520 assert(0);
1521 return;
1522 }
1523 }
1524 }
1525 }
1526
1527 /**
1528 * Validate the resources used by a program versus the implementation limits
1529 */
1530 static bool
1531 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
1532 {
1533 static const char *const shader_names[MESA_SHADER_TYPES] = {
1534 "vertex", "geometry", "fragment"
1535 };
1536
1537 const unsigned max_samplers[MESA_SHADER_TYPES] = {
1538 ctx->Const.VertexProgram.MaxTextureImageUnits,
1539 ctx->Const.GeometryProgram.MaxTextureImageUnits,
1540 ctx->Const.FragmentProgram.MaxTextureImageUnits
1541 };
1542
1543 const unsigned max_default_uniform_components[MESA_SHADER_TYPES] = {
1544 ctx->Const.VertexProgram.MaxUniformComponents,
1545 ctx->Const.GeometryProgram.MaxUniformComponents,
1546 ctx->Const.FragmentProgram.MaxUniformComponents
1547 };
1548
1549 const unsigned max_combined_uniform_components[MESA_SHADER_TYPES] = {
1550 ctx->Const.VertexProgram.MaxCombinedUniformComponents,
1551 ctx->Const.GeometryProgram.MaxCombinedUniformComponents,
1552 ctx->Const.FragmentProgram.MaxCombinedUniformComponents
1553 };
1554
1555 const unsigned max_uniform_blocks[MESA_SHADER_TYPES] = {
1556 ctx->Const.VertexProgram.MaxUniformBlocks,
1557 ctx->Const.GeometryProgram.MaxUniformBlocks,
1558 ctx->Const.FragmentProgram.MaxUniformBlocks
1559 };
1560
1561 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1562 struct gl_shader *sh = prog->_LinkedShaders[i];
1563
1564 if (sh == NULL)
1565 continue;
1566
1567 if (sh->num_samplers > max_samplers[i]) {
1568 linker_error(prog, "Too many %s shader texture samplers",
1569 shader_names[i]);
1570 }
1571
1572 if (sh->num_uniform_components > max_default_uniform_components[i]) {
1573 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
1574 linker_warning(prog, "Too many %s shader default uniform block "
1575 "components, but the driver will try to optimize "
1576 "them out; this is non-portable out-of-spec "
1577 "behavior\n",
1578 shader_names[i]);
1579 } else {
1580 linker_error(prog, "Too many %s shader default uniform block "
1581 "components",
1582 shader_names[i]);
1583 }
1584 }
1585
1586 if (sh->num_combined_uniform_components >
1587 max_combined_uniform_components[i]) {
1588 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
1589 linker_warning(prog, "Too many %s shader uniform components, "
1590 "but the driver will try to optimize them out; "
1591 "this is non-portable out-of-spec behavior\n",
1592 shader_names[i]);
1593 } else {
1594 linker_error(prog, "Too many %s shader uniform components",
1595 shader_names[i]);
1596 }
1597 }
1598 }
1599
1600 unsigned blocks[MESA_SHADER_TYPES] = {0};
1601 unsigned total_uniform_blocks = 0;
1602
1603 for (unsigned i = 0; i < prog->NumUniformBlocks; i++) {
1604 for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
1605 if (prog->UniformBlockStageIndex[j][i] != -1) {
1606 blocks[j]++;
1607 total_uniform_blocks++;
1608 }
1609 }
1610
1611 if (total_uniform_blocks > ctx->Const.MaxCombinedUniformBlocks) {
1612 linker_error(prog, "Too many combined uniform blocks (%d/%d)",
1613 prog->NumUniformBlocks,
1614 ctx->Const.MaxCombinedUniformBlocks);
1615 } else {
1616 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1617 if (blocks[i] > max_uniform_blocks[i]) {
1618 linker_error(prog, "Too many %s uniform blocks (%d/%d)",
1619 shader_names[i],
1620 blocks[i],
1621 max_uniform_blocks[i]);
1622 break;
1623 }
1624 }
1625 }
1626 }
1627
1628 return prog->LinkStatus;
1629 }
1630
1631 void
1632 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
1633 {
1634 tfeedback_decl *tfeedback_decls = NULL;
1635 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
1636
1637 void *mem_ctx = ralloc_context(NULL); // temporary linker context
1638
1639 prog->LinkStatus = false;
1640 prog->Validated = false;
1641 prog->_Used = false;
1642
1643 ralloc_free(prog->InfoLog);
1644 prog->InfoLog = ralloc_strdup(NULL, "");
1645
1646 ralloc_free(prog->UniformBlocks);
1647 prog->UniformBlocks = NULL;
1648 prog->NumUniformBlocks = 0;
1649 for (int i = 0; i < MESA_SHADER_TYPES; i++) {
1650 ralloc_free(prog->UniformBlockStageIndex[i]);
1651 prog->UniformBlockStageIndex[i] = NULL;
1652 }
1653
1654 /* Separate the shaders into groups based on their type.
1655 */
1656 struct gl_shader **vert_shader_list;
1657 unsigned num_vert_shaders = 0;
1658 struct gl_shader **frag_shader_list;
1659 unsigned num_frag_shaders = 0;
1660
1661 vert_shader_list = (struct gl_shader **)
1662 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
1663 frag_shader_list = &vert_shader_list[prog->NumShaders];
1664
1665 unsigned min_version = UINT_MAX;
1666 unsigned max_version = 0;
1667 const bool is_es_prog =
1668 (prog->NumShaders > 0 && prog->Shaders[0]->IsES) ? true : false;
1669 for (unsigned i = 0; i < prog->NumShaders; i++) {
1670 min_version = MIN2(min_version, prog->Shaders[i]->Version);
1671 max_version = MAX2(max_version, prog->Shaders[i]->Version);
1672
1673 if (prog->Shaders[i]->IsES != is_es_prog) {
1674 linker_error(prog, "all shaders must use same shading "
1675 "language version\n");
1676 goto done;
1677 }
1678
1679 switch (prog->Shaders[i]->Type) {
1680 case GL_VERTEX_SHADER:
1681 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
1682 num_vert_shaders++;
1683 break;
1684 case GL_FRAGMENT_SHADER:
1685 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
1686 num_frag_shaders++;
1687 break;
1688 case GL_GEOMETRY_SHADER:
1689 /* FINISHME: Support geometry shaders. */
1690 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
1691 break;
1692 }
1693 }
1694
1695 /* Previous to GLSL version 1.30, different compilation units could mix and
1696 * match shading language versions. With GLSL 1.30 and later, the versions
1697 * of all shaders must match.
1698 *
1699 * GLSL ES has never allowed mixing of shading language versions.
1700 */
1701 if ((is_es_prog || max_version >= 130)
1702 && min_version != max_version) {
1703 linker_error(prog, "all shaders must use same shading "
1704 "language version\n");
1705 goto done;
1706 }
1707
1708 prog->Version = max_version;
1709 prog->IsES = is_es_prog;
1710
1711 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
1712 if (prog->_LinkedShaders[i] != NULL)
1713 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
1714
1715 prog->_LinkedShaders[i] = NULL;
1716 }
1717
1718 /* Link all shaders for a particular stage and validate the result.
1719 */
1720 if (num_vert_shaders > 0) {
1721 gl_shader *const sh =
1722 link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
1723 num_vert_shaders);
1724
1725 if (sh == NULL)
1726 goto done;
1727
1728 if (!validate_vertex_shader_executable(prog, sh))
1729 goto done;
1730
1731 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
1732 sh);
1733 }
1734
1735 if (num_frag_shaders > 0) {
1736 gl_shader *const sh =
1737 link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
1738 num_frag_shaders);
1739
1740 if (sh == NULL)
1741 goto done;
1742
1743 if (!validate_fragment_shader_executable(prog, sh))
1744 goto done;
1745
1746 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
1747 sh);
1748 }
1749
1750 /* Here begins the inter-stage linking phase. Some initial validation is
1751 * performed, then locations are assigned for uniforms, attributes, and
1752 * varyings.
1753 */
1754 if (cross_validate_uniforms(prog)) {
1755 unsigned prev;
1756
1757 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
1758 if (prog->_LinkedShaders[prev] != NULL)
1759 break;
1760 }
1761
1762 /* Validate the inputs of each stage with the output of the preceding
1763 * stage.
1764 */
1765 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
1766 if (prog->_LinkedShaders[i] == NULL)
1767 continue;
1768
1769 if (!validate_interstage_interface_blocks(prog->_LinkedShaders[prev],
1770 prog->_LinkedShaders[i])) {
1771 linker_error(prog, "interface block mismatch between shader stages\n");
1772 goto done;
1773 }
1774
1775 if (!cross_validate_outputs_to_inputs(prog,
1776 prog->_LinkedShaders[prev],
1777 prog->_LinkedShaders[i]))
1778 goto done;
1779
1780 prev = i;
1781 }
1782
1783 prog->LinkStatus = true;
1784 }
1785
1786
1787 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
1788 if (prog->_LinkedShaders[i] != NULL)
1789 lower_named_interface_blocks(mem_ctx, prog->_LinkedShaders[i]);
1790 }
1791
1792 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
1793 * it before optimization because we want most of the checks to get
1794 * dropped thanks to constant propagation.
1795 *
1796 * This rule also applies to GLSL ES 3.00.
1797 */
1798 if (max_version >= (is_es_prog ? 300 : 130)) {
1799 struct gl_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
1800 if (sh) {
1801 lower_discard_flow(sh->ir);
1802 }
1803 }
1804
1805 if (!interstage_cross_validate_uniform_blocks(prog))
1806 goto done;
1807
1808 /* Do common optimization before assigning storage for attributes,
1809 * uniforms, and varyings. Later optimization could possibly make
1810 * some of that unused.
1811 */
1812 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1813 if (prog->_LinkedShaders[i] == NULL)
1814 continue;
1815
1816 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
1817 if (!prog->LinkStatus)
1818 goto done;
1819
1820 if (ctx->ShaderCompilerOptions[i].LowerClipDistance) {
1821 lower_clip_distance(prog->_LinkedShaders[i]);
1822 }
1823
1824 unsigned max_unroll = ctx->ShaderCompilerOptions[i].MaxUnrollIterations;
1825
1826 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false, max_unroll, &ctx->ShaderCompilerOptions[i]))
1827 ;
1828 }
1829
1830 /* Mark all generic shader inputs and outputs as unpaired. */
1831 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
1832 link_invalidate_variable_locations(
1833 prog->_LinkedShaders[MESA_SHADER_VERTEX],
1834 VERT_ATTRIB_GENERIC0, VARYING_SLOT_VAR0);
1835 }
1836 /* FINISHME: Geometry shaders not implemented yet */
1837 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
1838 link_invalidate_variable_locations(
1839 prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
1840 VARYING_SLOT_VAR0, FRAG_RESULT_DATA0);
1841 }
1842
1843 /* FINISHME: The value of the max_attribute_index parameter is
1844 * FINISHME: implementation dependent based on the value of
1845 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1846 * FINISHME: at least 16, so hardcode 16 for now.
1847 */
1848 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX, 16)) {
1849 goto done;
1850 }
1851
1852 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, MAX2(ctx->Const.MaxDrawBuffers, ctx->Const.MaxDualSourceDrawBuffers))) {
1853 goto done;
1854 }
1855
1856 unsigned first;
1857 for (first = 0; first < MESA_SHADER_TYPES; first++) {
1858 if (prog->_LinkedShaders[first] != NULL)
1859 break;
1860 }
1861
1862 if (num_tfeedback_decls != 0) {
1863 /* From GL_EXT_transform_feedback:
1864 * A program will fail to link if:
1865 *
1866 * * the <count> specified by TransformFeedbackVaryingsEXT is
1867 * non-zero, but the program object has no vertex or geometry
1868 * shader;
1869 */
1870 if (first >= MESA_SHADER_FRAGMENT) {
1871 linker_error(prog, "Transform feedback varyings specified, but "
1872 "no vertex or geometry shader is present.");
1873 goto done;
1874 }
1875
1876 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
1877 prog->TransformFeedback.NumVarying);
1878 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
1879 prog->TransformFeedback.VaryingNames,
1880 tfeedback_decls))
1881 goto done;
1882 }
1883
1884 /* Linking the stages in the opposite order (from fragment to vertex)
1885 * ensures that inter-shader outputs written to in an earlier stage are
1886 * eliminated if they are (transitively) not used in a later stage.
1887 */
1888 int last, next;
1889 for (last = MESA_SHADER_TYPES-1; last >= 0; last--) {
1890 if (prog->_LinkedShaders[last] != NULL)
1891 break;
1892 }
1893
1894 if (last >= 0 && last < MESA_SHADER_FRAGMENT) {
1895 gl_shader *const sh = prog->_LinkedShaders[last];
1896
1897 if (num_tfeedback_decls != 0) {
1898 /* There was no fragment shader, but we still have to assign varying
1899 * locations for use by transform feedback.
1900 */
1901 if (!assign_varying_locations(ctx, mem_ctx, prog,
1902 sh, NULL,
1903 num_tfeedback_decls, tfeedback_decls))
1904 goto done;
1905 }
1906
1907 do_dead_builtin_varyings(ctx, sh->ir, NULL,
1908 num_tfeedback_decls, tfeedback_decls);
1909
1910 demote_shader_inputs_and_outputs(sh, ir_var_shader_out);
1911
1912 /* Eliminate code that is now dead due to unused outputs being demoted.
1913 */
1914 while (do_dead_code(sh->ir, false))
1915 ;
1916 }
1917 else if (first == MESA_SHADER_FRAGMENT) {
1918 /* If the program only contains a fragment shader...
1919 */
1920 gl_shader *const sh = prog->_LinkedShaders[first];
1921
1922 do_dead_builtin_varyings(ctx, NULL, sh->ir,
1923 num_tfeedback_decls, tfeedback_decls);
1924
1925 demote_shader_inputs_and_outputs(sh, ir_var_shader_in);
1926
1927 while (do_dead_code(sh->ir, false))
1928 ;
1929 }
1930
1931 next = last;
1932 for (int i = next - 1; i >= 0; i--) {
1933 if (prog->_LinkedShaders[i] == NULL)
1934 continue;
1935
1936 gl_shader *const sh_i = prog->_LinkedShaders[i];
1937 gl_shader *const sh_next = prog->_LinkedShaders[next];
1938
1939 if (!assign_varying_locations(ctx, mem_ctx, prog, sh_i, sh_next,
1940 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
1941 tfeedback_decls))
1942 goto done;
1943
1944 do_dead_builtin_varyings(ctx, sh_i->ir, sh_next->ir,
1945 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
1946 tfeedback_decls);
1947
1948 demote_shader_inputs_and_outputs(sh_i, ir_var_shader_out);
1949 demote_shader_inputs_and_outputs(sh_next, ir_var_shader_in);
1950
1951 /* Eliminate code that is now dead due to unused outputs being demoted.
1952 */
1953 while (do_dead_code(sh_i->ir, false))
1954 ;
1955 while (do_dead_code(sh_next->ir, false))
1956 ;
1957
1958 /* This must be done after all dead varyings are eliminated. */
1959 if (!check_against_varying_limit(ctx, prog, sh_next))
1960 goto done;
1961
1962 next = i;
1963 }
1964
1965 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
1966 goto done;
1967
1968 update_array_sizes(prog);
1969 link_assign_uniform_locations(prog);
1970 store_fragdepth_layout(prog);
1971
1972 if (!check_resources(ctx, prog))
1973 goto done;
1974
1975 /* OpenGL ES requires that a vertex shader and a fragment shader both be
1976 * present in a linked program. By checking prog->IsES, we also
1977 * catch the GL_ARB_ES2_compatibility case.
1978 */
1979 if (!prog->InternalSeparateShader &&
1980 (ctx->API == API_OPENGLES2 || prog->IsES)) {
1981 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
1982 linker_error(prog, "program lacks a vertex shader\n");
1983 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
1984 linker_error(prog, "program lacks a fragment shader\n");
1985 }
1986 }
1987
1988 /* FINISHME: Assign fragment shader output locations. */
1989
1990 done:
1991 free(vert_shader_list);
1992
1993 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1994 if (prog->_LinkedShaders[i] == NULL)
1995 continue;
1996
1997 /* Retain any live IR, but trash the rest. */
1998 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
1999
2000 /* The symbol table in the linked shaders may contain references to
2001 * variables that were removed (e.g., unused uniforms). Since it may
2002 * contain junk, there is no possible valid use. Delete it and set the
2003 * pointer to NULL.
2004 */
2005 delete prog->_LinkedShaders[i]->symbols;
2006 prog->_LinkedShaders[i]->symbols = NULL;
2007 }
2008
2009 ralloc_free(mem_ctx);
2010 }