2 * Copyright © 2010 Intel Corporation
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:
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
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.
26 * GLSL linker implementation
28 * Given a set of shaders that are to be linked to generate a final program,
29 * there are three distinct stages.
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
35 * - Undefined references in each shader are resolve to definitions in
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.
42 * The result, in the terminology of the GLSL spec, is a set of shader
43 * executables for each processing unit.
45 * After the first stage is complete, a series of semantic checks are performed
46 * on each of the shader executables.
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
53 * In the final stage individual shader executables are linked to create a
54 * complete exectuable.
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.
64 * \author Ian Romanick <ian.d.romanick@intel.com>
67 #include "main/core.h"
68 #include "glsl_symbol_table.h"
71 #include "program/hash_table.h"
73 #include "ir_optimization.h"
76 #include "main/shaderobj.h"
80 * Visitor that determines whether or not a variable is ever written.
82 class find_assignment_visitor : public ir_hierarchical_visitor {
84 find_assignment_visitor(const char *name)
85 : name(name), found(false)
90 virtual ir_visitor_status visit_enter(ir_assignment *ir)
92 ir_variable *const var = ir->lhs->variable_referenced();
94 if (strcmp(name, var->name) == 0) {
99 return visit_continue_with_parent;
102 virtual ir_visitor_status visit_enter(ir_call *ir)
104 exec_list_iterator sig_iter = ir->get_callee()->parameters.iterator();
105 foreach_iter(exec_list_iterator, iter, *ir) {
106 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
107 ir_variable *sig_param = (ir_variable *)sig_iter.get();
109 if (sig_param->mode == ir_var_out ||
110 sig_param->mode == ir_var_inout) {
111 ir_variable *var = param_rval->variable_referenced();
112 if (var && strcmp(name, var->name) == 0) {
120 return visit_continue_with_parent;
123 bool variable_found()
129 const char *name; /**< Find writes to a variable with this name. */
130 bool found; /**< Was a write to the variable found? */
135 * Visitor that determines whether or not a variable is ever read.
137 class find_deref_visitor : public ir_hierarchical_visitor {
139 find_deref_visitor(const char *name)
140 : name(name), found(false)
145 virtual ir_visitor_status visit(ir_dereference_variable *ir)
147 if (strcmp(this->name, ir->var->name) == 0) {
152 return visit_continue;
155 bool variable_found() const
161 const char *name; /**< Find writes to a variable with this name. */
162 bool found; /**< Was a write to the variable found? */
167 linker_error(gl_shader_program *prog, const char *fmt, ...)
171 ralloc_strcat(&prog->InfoLog, "error: ");
173 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
176 prog->LinkStatus = false;
181 linker_warning(gl_shader_program *prog, const char *fmt, ...)
185 ralloc_strcat(&prog->InfoLog, "error: ");
187 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
194 link_invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
197 foreach_list(node, sh->ir) {
198 ir_variable *const var = ((ir_instruction *) node)->as_variable();
200 if ((var == NULL) || (var->mode != (unsigned) mode))
203 /* Only assign locations for generic attributes / varyings / etc.
205 if ((var->location >= generic_base) && !var->explicit_location)
212 * Determine the number of attribute slots required for a particular type
214 * This code is here because it implements the language rules of a specific
215 * GLSL version. Since it's a property of the language and not a property of
216 * types in general, it doesn't really belong in glsl_type.
219 count_attribute_slots(const glsl_type *t)
221 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
223 * "A scalar input counts the same amount against this limit as a vec4,
224 * so applications may want to consider packing groups of four
225 * unrelated float inputs together into a vector to better utilize the
226 * capabilities of the underlying hardware. A matrix input will use up
227 * multiple locations. The number of locations used will equal the
228 * number of columns in the matrix."
230 * The spec does not explicitly say how arrays are counted. However, it
231 * should be safe to assume the total number of slots consumed by an array
232 * is the number of entries in the array multiplied by the number of slots
233 * consumed by a single element of the array.
237 return t->array_size() * count_attribute_slots(t->element_type());
240 return t->matrix_columns;
247 * Verify that a vertex shader executable meets all semantic requirements.
249 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
252 * \param shader Vertex shader executable to be verified
255 validate_vertex_shader_executable(struct gl_shader_program *prog,
256 struct gl_shader *shader)
261 find_assignment_visitor find("gl_Position");
262 find.run(shader->ir);
263 if (!find.variable_found()) {
264 linker_error(prog, "vertex shader does not write to `gl_Position'\n");
268 prog->Vert.ClipDistanceArraySize = 0;
270 if (prog->Version >= 130) {
271 /* From section 7.1 (Vertex Shader Special Variables) of the
274 * "It is an error for a shader to statically write both
275 * gl_ClipVertex and gl_ClipDistance."
277 find_assignment_visitor clip_vertex("gl_ClipVertex");
278 find_assignment_visitor clip_distance("gl_ClipDistance");
280 clip_vertex.run(shader->ir);
281 clip_distance.run(shader->ir);
282 if (clip_vertex.variable_found() && clip_distance.variable_found()) {
283 linker_error(prog, "vertex shader writes to both `gl_ClipVertex' "
284 "and `gl_ClipDistance'\n");
287 prog->Vert.UsesClipDistance = clip_distance.variable_found();
288 ir_variable *clip_distance_var =
289 shader->symbols->get_variable("gl_ClipDistance");
290 if (clip_distance_var)
291 prog->Vert.ClipDistanceArraySize = clip_distance_var->type->length;
299 * Verify that a fragment shader executable meets all semantic requirements
301 * \param shader Fragment shader executable to be verified
304 validate_fragment_shader_executable(struct gl_shader_program *prog,
305 struct gl_shader *shader)
310 find_assignment_visitor frag_color("gl_FragColor");
311 find_assignment_visitor frag_data("gl_FragData");
313 frag_color.run(shader->ir);
314 frag_data.run(shader->ir);
316 if (frag_color.variable_found() && frag_data.variable_found()) {
317 linker_error(prog, "fragment shader writes to both "
318 "`gl_FragColor' and `gl_FragData'\n");
327 * Generate a string describing the mode of a variable
330 mode_string(const ir_variable *var)
334 return (var->read_only) ? "global constant" : "global variable";
336 case ir_var_uniform: return "uniform";
337 case ir_var_in: return "shader input";
338 case ir_var_out: return "shader output";
339 case ir_var_inout: return "shader inout";
341 case ir_var_const_in:
342 case ir_var_temporary:
344 assert(!"Should not get here.");
345 return "invalid variable";
351 * Perform validation of global variables used across multiple shaders
354 cross_validate_globals(struct gl_shader_program *prog,
355 struct gl_shader **shader_list,
356 unsigned num_shaders,
359 /* Examine all of the uniforms in all of the shaders and cross validate
362 glsl_symbol_table variables;
363 for (unsigned i = 0; i < num_shaders; i++) {
364 if (shader_list[i] == NULL)
367 foreach_list(node, shader_list[i]->ir) {
368 ir_variable *const var = ((ir_instruction *) node)->as_variable();
373 if (uniforms_only && (var->mode != ir_var_uniform))
376 /* Don't cross validate temporaries that are at global scope. These
377 * will eventually get pulled into the shaders 'main'.
379 if (var->mode == ir_var_temporary)
382 /* If a global with this name has already been seen, verify that the
383 * new instance has the same type. In addition, if the globals have
384 * initializers, the values of the initializers must be the same.
386 ir_variable *const existing = variables.get_variable(var->name);
387 if (existing != NULL) {
388 if (var->type != existing->type) {
389 /* Consider the types to be "the same" if both types are arrays
390 * of the same type and one of the arrays is implicitly sized.
391 * In addition, set the type of the linked variable to the
392 * explicitly sized array.
394 if (var->type->is_array()
395 && existing->type->is_array()
396 && (var->type->fields.array == existing->type->fields.array)
397 && ((var->type->length == 0)
398 || (existing->type->length == 0))) {
399 if (var->type->length != 0) {
400 existing->type = var->type;
403 linker_error(prog, "%s `%s' declared as type "
404 "`%s' and type `%s'\n",
406 var->name, var->type->name,
407 existing->type->name);
412 if (var->explicit_location) {
413 if (existing->explicit_location
414 && (var->location != existing->location)) {
415 linker_error(prog, "explicit locations for %s "
416 "`%s' have differing values\n",
417 mode_string(var), var->name);
421 existing->location = var->location;
422 existing->explicit_location = true;
425 /* Validate layout qualifiers for gl_FragDepth.
427 * From the AMD/ARB_conservative_depth specs:
429 * "If gl_FragDepth is redeclared in any fragment shader in a
430 * program, it must be redeclared in all fragment shaders in
431 * that program that have static assignments to
432 * gl_FragDepth. All redeclarations of gl_FragDepth in all
433 * fragment shaders in a single program must have the same set
436 if (strcmp(var->name, "gl_FragDepth") == 0) {
437 bool layout_declared = var->depth_layout != ir_depth_layout_none;
438 bool layout_differs =
439 var->depth_layout != existing->depth_layout;
441 if (layout_declared && layout_differs) {
443 "All redeclarations of gl_FragDepth in all "
444 "fragment shaders in a single program must have "
445 "the same set of qualifiers.");
448 if (var->used && layout_differs) {
450 "If gl_FragDepth is redeclared with a layout "
451 "qualifier in any fragment shader, it must be "
452 "redeclared with the same layout qualifier in "
453 "all fragment shaders that have assignments to "
458 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
460 * "If a shared global has multiple initializers, the
461 * initializers must all be constant expressions, and they
462 * must all have the same value. Otherwise, a link error will
463 * result. (A shared global having only one initializer does
464 * not require that initializer to be a constant expression.)"
466 * Previous to 4.20 the GLSL spec simply said that initializers
467 * must have the same value. In this case of non-constant
468 * initializers, this was impossible to determine. As a result,
469 * no vendor actually implemented that behavior. The 4.20
470 * behavior matches the implemented behavior of at least one other
471 * vendor, so we'll implement that for all GLSL versions.
473 if (var->constant_initializer != NULL) {
474 if (existing->constant_initializer != NULL) {
475 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
476 linker_error(prog, "initializers for %s "
477 "`%s' have differing values\n",
478 mode_string(var), var->name);
482 /* If the first-seen instance of a particular uniform did not
483 * have an initializer but a later instance does, copy the
484 * initializer to the version stored in the symbol table.
486 /* FINISHME: This is wrong. The constant_value field should
487 * FINISHME: not be modified! Imagine a case where a shader
488 * FINISHME: without an initializer is linked in two different
489 * FINISHME: programs with shaders that have differing
490 * FINISHME: initializers. Linking with the first will
491 * FINISHME: modify the shader, and linking with the second
492 * FINISHME: will fail.
494 existing->constant_initializer =
495 var->constant_initializer->clone(ralloc_parent(existing),
500 if (var->has_initializer) {
501 if (existing->has_initializer
502 && (var->constant_initializer == NULL
503 || existing->constant_initializer == NULL)) {
505 "shared global variable `%s' has multiple "
506 "non-constant initializers.\n",
511 /* Some instance had an initializer, so keep track of that. In
512 * this location, all sorts of initializers (constant or
513 * otherwise) will propagate the existence to the variable
514 * stored in the symbol table.
516 existing->has_initializer = true;
519 if (existing->invariant != var->invariant) {
520 linker_error(prog, "declarations for %s `%s' have "
521 "mismatching invariant qualifiers\n",
522 mode_string(var), var->name);
525 if (existing->centroid != var->centroid) {
526 linker_error(prog, "declarations for %s `%s' have "
527 "mismatching centroid qualifiers\n",
528 mode_string(var), var->name);
532 variables.add_variable(var);
541 * Perform validation of uniforms used across multiple shader stages
544 cross_validate_uniforms(struct gl_shader_program *prog)
546 return cross_validate_globals(prog, prog->_LinkedShaders,
547 MESA_SHADER_TYPES, true);
552 * Validate that outputs from one stage match inputs of another
555 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
556 gl_shader *producer, gl_shader *consumer)
558 glsl_symbol_table parameters;
559 /* FINISHME: Figure these out dynamically. */
560 const char *const producer_stage = "vertex";
561 const char *const consumer_stage = "fragment";
563 /* Find all shader outputs in the "producer" stage.
565 foreach_list(node, producer->ir) {
566 ir_variable *const var = ((ir_instruction *) node)->as_variable();
568 /* FINISHME: For geometry shaders, this should also look for inout
569 * FINISHME: variables.
571 if ((var == NULL) || (var->mode != ir_var_out))
574 parameters.add_variable(var);
578 /* Find all shader inputs in the "consumer" stage. Any variables that have
579 * matching outputs already in the symbol table must have the same type and
582 foreach_list(node, consumer->ir) {
583 ir_variable *const input = ((ir_instruction *) node)->as_variable();
585 /* FINISHME: For geometry shaders, this should also look for inout
586 * FINISHME: variables.
588 if ((input == NULL) || (input->mode != ir_var_in))
591 ir_variable *const output = parameters.get_variable(input->name);
592 if (output != NULL) {
593 /* Check that the types match between stages.
595 if (input->type != output->type) {
596 /* There is a bit of a special case for gl_TexCoord. This
597 * built-in is unsized by default. Applications that variable
598 * access it must redeclare it with a size. There is some
599 * language in the GLSL spec that implies the fragment shader
600 * and vertex shader do not have to agree on this size. Other
601 * driver behave this way, and one or two applications seem to
604 * Neither declaration needs to be modified here because the array
605 * sizes are fixed later when update_array_sizes is called.
607 * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
609 * "Unlike user-defined varying variables, the built-in
610 * varying variables don't have a strict one-to-one
611 * correspondence between the vertex language and the
612 * fragment language."
614 if (!output->type->is_array()
615 || (strncmp("gl_", output->name, 3) != 0)) {
617 "%s shader output `%s' declared as type `%s', "
618 "but %s shader input declared as type `%s'\n",
619 producer_stage, output->name,
621 consumer_stage, input->type->name);
626 /* Check that all of the qualifiers match between stages.
628 if (input->centroid != output->centroid) {
630 "%s shader output `%s' %s centroid qualifier, "
631 "but %s shader input %s centroid qualifier\n",
634 (output->centroid) ? "has" : "lacks",
636 (input->centroid) ? "has" : "lacks");
640 if (input->invariant != output->invariant) {
642 "%s shader output `%s' %s invariant qualifier, "
643 "but %s shader input %s invariant qualifier\n",
646 (output->invariant) ? "has" : "lacks",
648 (input->invariant) ? "has" : "lacks");
652 if (input->interpolation != output->interpolation) {
654 "%s shader output `%s' specifies %s "
655 "interpolation qualifier, "
656 "but %s shader input specifies %s "
657 "interpolation qualifier\n",
660 output->interpolation_string(),
662 input->interpolation_string());
673 * Populates a shaders symbol table with all global declarations
676 populate_symbol_table(gl_shader *sh)
678 sh->symbols = new(sh) glsl_symbol_table;
680 foreach_list(node, sh->ir) {
681 ir_instruction *const inst = (ir_instruction *) node;
685 if ((func = inst->as_function()) != NULL) {
686 sh->symbols->add_function(func);
687 } else if ((var = inst->as_variable()) != NULL) {
688 sh->symbols->add_variable(var);
695 * Remap variables referenced in an instruction tree
697 * This is used when instruction trees are cloned from one shader and placed in
698 * another. These trees will contain references to \c ir_variable nodes that
699 * do not exist in the target shader. This function finds these \c ir_variable
700 * references and replaces the references with matching variables in the target
703 * If there is no matching variable in the target shader, a clone of the
704 * \c ir_variable is made and added to the target shader. The new variable is
705 * added to \b both the instruction stream and the symbol table.
707 * \param inst IR tree that is to be processed.
708 * \param symbols Symbol table containing global scope symbols in the
710 * \param instructions Instruction stream where new variable declarations
714 remap_variables(ir_instruction *inst, struct gl_shader *target,
717 class remap_visitor : public ir_hierarchical_visitor {
719 remap_visitor(struct gl_shader *target,
722 this->target = target;
723 this->symbols = target->symbols;
724 this->instructions = target->ir;
728 virtual ir_visitor_status visit(ir_dereference_variable *ir)
730 if (ir->var->mode == ir_var_temporary) {
731 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
735 return visit_continue;
738 ir_variable *const existing =
739 this->symbols->get_variable(ir->var->name);
740 if (existing != NULL)
743 ir_variable *copy = ir->var->clone(this->target, NULL);
745 this->symbols->add_variable(copy);
746 this->instructions->push_head(copy);
750 return visit_continue;
754 struct gl_shader *target;
755 glsl_symbol_table *symbols;
756 exec_list *instructions;
760 remap_visitor v(target, temps);
767 * Move non-declarations from one instruction stream to another
769 * The intended usage pattern of this function is to pass the pointer to the
770 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
771 * pointer) for \c last and \c false for \c make_copies on the first
772 * call. Successive calls pass the return value of the previous call for
773 * \c last and \c true for \c make_copies.
775 * \param instructions Source instruction stream
776 * \param last Instruction after which new instructions should be
777 * inserted in the target instruction stream
778 * \param make_copies Flag selecting whether instructions in \c instructions
779 * should be copied (via \c ir_instruction::clone) into the
780 * target list or moved.
783 * The new "last" instruction in the target instruction stream. This pointer
784 * is suitable for use as the \c last parameter of a later call to this
788 move_non_declarations(exec_list *instructions, exec_node *last,
789 bool make_copies, gl_shader *target)
791 hash_table *temps = NULL;
794 temps = hash_table_ctor(0, hash_table_pointer_hash,
795 hash_table_pointer_compare);
797 foreach_list_safe(node, instructions) {
798 ir_instruction *inst = (ir_instruction *) node;
800 if (inst->as_function())
803 ir_variable *var = inst->as_variable();
804 if ((var != NULL) && (var->mode != ir_var_temporary))
807 assert(inst->as_assignment()
808 || ((var != NULL) && (var->mode == ir_var_temporary)));
811 inst = inst->clone(target, NULL);
814 hash_table_insert(temps, inst, var);
816 remap_variables(inst, target, temps);
821 last->insert_after(inst);
826 hash_table_dtor(temps);
832 * Get the function signature for main from a shader
834 static ir_function_signature *
835 get_main_function_signature(gl_shader *sh)
837 ir_function *const f = sh->symbols->get_function("main");
839 exec_list void_parameters;
841 /* Look for the 'void main()' signature and ensure that it's defined.
842 * This keeps the linker from accidentally pick a shader that just
843 * contains a prototype for main.
845 * We don't have to check for multiple definitions of main (in multiple
846 * shaders) because that would have already been caught above.
848 ir_function_signature *sig = f->matching_signature(&void_parameters);
849 if ((sig != NULL) && sig->is_defined) {
859 * Combine a group of shaders for a single stage to generate a linked shader
862 * If this function is supplied a single shader, it is cloned, and the new
863 * shader is returned.
865 static struct gl_shader *
866 link_intrastage_shaders(void *mem_ctx,
867 struct gl_context *ctx,
868 struct gl_shader_program *prog,
869 struct gl_shader **shader_list,
870 unsigned num_shaders)
872 /* Check that global variables defined in multiple shaders are consistent.
874 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
877 /* Check that there is only a single definition of each function signature
878 * across all shaders.
880 for (unsigned i = 0; i < (num_shaders - 1); i++) {
881 foreach_list(node, shader_list[i]->ir) {
882 ir_function *const f = ((ir_instruction *) node)->as_function();
887 for (unsigned j = i + 1; j < num_shaders; j++) {
888 ir_function *const other =
889 shader_list[j]->symbols->get_function(f->name);
891 /* If the other shader has no function (and therefore no function
892 * signatures) with the same name, skip to the next shader.
897 foreach_iter (exec_list_iterator, iter, *f) {
898 ir_function_signature *sig =
899 (ir_function_signature *) iter.get();
901 if (!sig->is_defined || sig->is_builtin)
904 ir_function_signature *other_sig =
905 other->exact_matching_signature(& sig->parameters);
907 if ((other_sig != NULL) && other_sig->is_defined
908 && !other_sig->is_builtin) {
909 linker_error(prog, "function `%s' is multiply defined",
918 /* Find the shader that defines main, and make a clone of it.
920 * Starting with the clone, search for undefined references. If one is
921 * found, find the shader that defines it. Clone the reference and add
922 * it to the shader. Repeat until there are no undefined references or
923 * until a reference cannot be resolved.
925 gl_shader *main = NULL;
926 for (unsigned i = 0; i < num_shaders; i++) {
927 if (get_main_function_signature(shader_list[i]) != NULL) {
928 main = shader_list[i];
934 linker_error(prog, "%s shader lacks `main'\n",
935 (shader_list[0]->Type == GL_VERTEX_SHADER)
936 ? "vertex" : "fragment");
940 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
941 linked->ir = new(linked) exec_list;
942 clone_ir_list(mem_ctx, linked->ir, main->ir);
944 populate_symbol_table(linked);
946 /* The a pointer to the main function in the final linked shader (i.e., the
947 * copy of the original shader that contained the main function).
949 ir_function_signature *const main_sig = get_main_function_signature(linked);
951 /* Move any instructions other than variable declarations or function
952 * declarations into main.
954 exec_node *insertion_point =
955 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
958 for (unsigned i = 0; i < num_shaders; i++) {
959 if (shader_list[i] == main)
962 insertion_point = move_non_declarations(shader_list[i]->ir,
963 insertion_point, true, linked);
966 /* Resolve initializers for global variables in the linked shader.
968 unsigned num_linking_shaders = num_shaders;
969 for (unsigned i = 0; i < num_shaders; i++)
970 num_linking_shaders += shader_list[i]->num_builtins_to_link;
972 gl_shader **linking_shaders =
973 (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
975 memcpy(linking_shaders, shader_list,
976 sizeof(linking_shaders[0]) * num_shaders);
978 unsigned idx = num_shaders;
979 for (unsigned i = 0; i < num_shaders; i++) {
980 memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
981 sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
982 idx += shader_list[i]->num_builtins_to_link;
985 assert(idx == num_linking_shaders);
987 if (!link_function_calls(prog, linked, linking_shaders,
988 num_linking_shaders)) {
989 ctx->Driver.DeleteShader(ctx, linked);
993 free(linking_shaders);
996 /* At this point linked should contain all of the linked IR, so
997 * validate it to make sure nothing went wrong.
1000 validate_ir_tree(linked->ir);
1003 /* Make a pass over all variable declarations to ensure that arrays with
1004 * unspecified sizes have a size specified. The size is inferred from the
1005 * max_array_access field.
1007 if (linked != NULL) {
1008 class array_sizing_visitor : public ir_hierarchical_visitor {
1010 virtual ir_visitor_status visit(ir_variable *var)
1012 if (var->type->is_array() && (var->type->length == 0)) {
1013 const glsl_type *type =
1014 glsl_type::get_array_instance(var->type->fields.array,
1015 var->max_array_access + 1);
1017 assert(type != NULL);
1021 return visit_continue;
1032 * Update the sizes of linked shader uniform arrays to the maximum
1035 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1037 * If one or more elements of an array are active,
1038 * GetActiveUniform will return the name of the array in name,
1039 * subject to the restrictions listed above. The type of the array
1040 * is returned in type. The size parameter contains the highest
1041 * array element index used, plus one. The compiler or linker
1042 * determines the highest index used. There will be only one
1043 * active uniform reported by the GL per uniform array.
1047 update_array_sizes(struct gl_shader_program *prog)
1049 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1050 if (prog->_LinkedShaders[i] == NULL)
1053 foreach_list(node, prog->_LinkedShaders[i]->ir) {
1054 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1056 if ((var == NULL) || (var->mode != ir_var_uniform &&
1057 var->mode != ir_var_in &&
1058 var->mode != ir_var_out) ||
1059 !var->type->is_array())
1062 unsigned int size = var->max_array_access;
1063 for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
1064 if (prog->_LinkedShaders[j] == NULL)
1067 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
1068 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
1072 if (strcmp(var->name, other_var->name) == 0 &&
1073 other_var->max_array_access > size) {
1074 size = other_var->max_array_access;
1079 if (size + 1 != var->type->fields.array->length) {
1080 /* If this is a built-in uniform (i.e., it's backed by some
1081 * fixed-function state), adjust the number of state slots to
1082 * match the new array size. The number of slots per array entry
1083 * is not known. It seems safe to assume that the total number of
1084 * slots is an integer multiple of the number of array elements.
1085 * Determine the number of slots per array element by dividing by
1086 * the old (total) size.
1088 if (var->num_state_slots > 0) {
1089 var->num_state_slots = (size + 1)
1090 * (var->num_state_slots / var->type->length);
1093 var->type = glsl_type::get_array_instance(var->type->fields.array,
1095 /* FINISHME: We should update the types of array
1096 * dereferences of this variable now.
1104 * Find a contiguous set of available bits in a bitmask.
1106 * \param used_mask Bits representing used (1) and unused (0) locations
1107 * \param needed_count Number of contiguous bits needed.
1110 * Base location of the available bits on success or -1 on failure.
1113 find_available_slots(unsigned used_mask, unsigned needed_count)
1115 unsigned needed_mask = (1 << needed_count) - 1;
1116 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1118 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1119 * cannot optimize possibly infinite loops" for the loop below.
1121 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1124 for (int i = 0; i <= max_bit_to_test; i++) {
1125 if ((needed_mask & ~used_mask) == needed_mask)
1136 * Assign locations for either VS inputs for FS outputs
1138 * \param prog Shader program whose variables need locations assigned
1139 * \param target_index Selector for the program target to receive location
1140 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1141 * \c MESA_SHADER_FRAGMENT.
1142 * \param max_index Maximum number of generic locations. This corresponds
1143 * to either the maximum number of draw buffers or the
1144 * maximum number of generic attributes.
1147 * If locations are successfully assigned, true is returned. Otherwise an
1148 * error is emitted to the shader link log and false is returned.
1151 assign_attribute_or_color_locations(gl_shader_program *prog,
1152 unsigned target_index,
1155 /* Mark invalid locations as being used.
1157 unsigned used_locations = (max_index >= 32)
1158 ? ~0 : ~((1 << max_index) - 1);
1160 assert((target_index == MESA_SHADER_VERTEX)
1161 || (target_index == MESA_SHADER_FRAGMENT));
1163 gl_shader *const sh = prog->_LinkedShaders[target_index];
1167 /* Operate in a total of four passes.
1169 * 1. Invalidate the location assignments for all vertex shader inputs.
1171 * 2. Assign locations for inputs that have user-defined (via
1172 * glBindVertexAttribLocation) locations and outputs that have
1173 * user-defined locations (via glBindFragDataLocation).
1175 * 3. Sort the attributes without assigned locations by number of slots
1176 * required in decreasing order. Fragmentation caused by attribute
1177 * locations assigned by the application may prevent large attributes
1178 * from having enough contiguous space.
1180 * 4. Assign locations to any inputs without assigned locations.
1183 const int generic_base = (target_index == MESA_SHADER_VERTEX)
1184 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
1186 const enum ir_variable_mode direction =
1187 (target_index == MESA_SHADER_VERTEX) ? ir_var_in : ir_var_out;
1190 link_invalidate_variable_locations(sh, direction, generic_base);
1192 /* Temporary storage for the set of attributes that need locations assigned.
1198 /* Used below in the call to qsort. */
1199 static int compare(const void *a, const void *b)
1201 const temp_attr *const l = (const temp_attr *) a;
1202 const temp_attr *const r = (const temp_attr *) b;
1204 /* Reversed because we want a descending order sort below. */
1205 return r->slots - l->slots;
1209 unsigned num_attr = 0;
1211 foreach_list(node, sh->ir) {
1212 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1214 if ((var == NULL) || (var->mode != (unsigned) direction))
1217 if (var->explicit_location) {
1218 if ((var->location >= (int)(max_index + generic_base))
1219 || (var->location < 0)) {
1221 "invalid explicit location %d specified for `%s'\n",
1223 ? var->location : var->location - generic_base,
1227 } else if (target_index == MESA_SHADER_VERTEX) {
1230 if (prog->AttributeBindings->get(binding, var->name)) {
1231 assert(binding >= VERT_ATTRIB_GENERIC0);
1232 var->location = binding;
1234 } else if (target_index == MESA_SHADER_FRAGMENT) {
1237 if (prog->FragDataBindings->get(binding, var->name)) {
1238 assert(binding >= FRAG_RESULT_DATA0);
1239 var->location = binding;
1243 /* If the variable is not a built-in and has a location statically
1244 * assigned in the shader (presumably via a layout qualifier), make sure
1245 * that it doesn't collide with other assigned locations. Otherwise,
1246 * add it to the list of variables that need linker-assigned locations.
1248 const unsigned slots = count_attribute_slots(var->type);
1249 if (var->location != -1) {
1250 if (var->location >= generic_base) {
1251 /* From page 61 of the OpenGL 4.0 spec:
1253 * "LinkProgram will fail if the attribute bindings assigned
1254 * by BindAttribLocation do not leave not enough space to
1255 * assign a location for an active matrix attribute or an
1256 * active attribute array, both of which require multiple
1257 * contiguous generic attributes."
1259 * Previous versions of the spec contain similar language but omit
1260 * the bit about attribute arrays.
1262 * Page 61 of the OpenGL 4.0 spec also says:
1264 * "It is possible for an application to bind more than one
1265 * attribute name to the same location. This is referred to as
1266 * aliasing. This will only work if only one of the aliased
1267 * attributes is active in the executable program, or if no
1268 * path through the shader consumes more than one attribute of
1269 * a set of attributes aliased to the same location. A link
1270 * error can occur if the linker determines that every path
1271 * through the shader consumes multiple aliased attributes,
1272 * but implementations are not required to generate an error
1275 * These two paragraphs are either somewhat contradictory, or I
1276 * don't fully understand one or both of them.
1278 /* FINISHME: The code as currently written does not support
1279 * FINISHME: attribute location aliasing (see comment above).
1281 /* Mask representing the contiguous slots that will be used by
1284 const unsigned attr = var->location - generic_base;
1285 const unsigned use_mask = (1 << slots) - 1;
1287 /* Generate a link error if the set of bits requested for this
1288 * attribute overlaps any previously allocated bits.
1290 if ((~(use_mask << attr) & used_locations) != used_locations) {
1292 "insufficient contiguous attribute locations "
1293 "available for vertex shader input `%s'",
1298 used_locations |= (use_mask << attr);
1304 to_assign[num_attr].slots = slots;
1305 to_assign[num_attr].var = var;
1309 /* If all of the attributes were assigned locations by the application (or
1310 * are built-in attributes with fixed locations), return early. This should
1311 * be the common case.
1316 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1318 if (target_index == MESA_SHADER_VERTEX) {
1319 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1320 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1321 * reserved to prevent it from being automatically allocated below.
1323 find_deref_visitor find("gl_Vertex");
1325 if (find.variable_found())
1326 used_locations |= (1 << 0);
1329 for (unsigned i = 0; i < num_attr; i++) {
1330 /* Mask representing the contiguous slots that will be used by this
1333 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1335 int location = find_available_slots(used_locations, to_assign[i].slots);
1338 const char *const string = (target_index == MESA_SHADER_VERTEX)
1339 ? "vertex shader input" : "fragment shader output";
1342 "insufficient contiguous attribute locations "
1343 "available for %s `%s'",
1344 string, to_assign[i].var->name);
1348 to_assign[i].var->location = generic_base + location;
1349 used_locations |= (use_mask << location);
1357 * Demote shader inputs and outputs that are not used in other stages
1360 demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
1362 foreach_list(node, sh->ir) {
1363 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1365 if ((var == NULL) || (var->mode != int(mode)))
1368 /* A shader 'in' or 'out' variable is only really an input or output if
1369 * its value is used by other shader stages. This will cause the variable
1370 * to have a location assigned.
1372 if (var->location == -1) {
1373 var->mode = ir_var_auto;
1380 * Data structure tracking information about a transform feedback declaration
1383 class tfeedback_decl
1386 bool init(struct gl_context *ctx, struct gl_shader_program *prog,
1387 const void *mem_ctx, const char *input);
1388 static bool is_same(const tfeedback_decl &x, const tfeedback_decl &y);
1389 bool assign_location(struct gl_context *ctx, struct gl_shader_program *prog,
1390 ir_variable *output_var);
1391 bool accumulate_num_outputs(struct gl_shader_program *prog, unsigned *count);
1392 bool store(struct gl_context *ctx, struct gl_shader_program *prog,
1393 struct gl_transform_feedback_info *info, unsigned buffer,
1394 unsigned varying, const unsigned max_outputs) const;
1398 * True if assign_location() has been called for this object.
1400 bool is_assigned() const
1402 return this->location != -1;
1406 * Determine whether this object refers to the variable var.
1408 bool matches_var(ir_variable *var) const
1410 if (this->is_clip_distance_mesa)
1411 return strcmp(var->name, "gl_ClipDistanceMESA") == 0;
1413 return strcmp(var->name, this->var_name) == 0;
1417 * The total number of varying components taken up by this variable. Only
1418 * valid if is_assigned() is true.
1420 unsigned num_components() const
1422 if (this->is_clip_distance_mesa)
1425 return this->vector_elements * this->matrix_columns * this->size;
1430 * The name that was supplied to glTransformFeedbackVaryings. Used for
1431 * error reporting and glGetTransformFeedbackVarying().
1433 const char *orig_name;
1436 * The name of the variable, parsed from orig_name.
1438 const char *var_name;
1441 * True if the declaration in orig_name represents an array.
1443 bool is_subscripted;
1446 * If is_subscripted is true, the subscript that was specified in orig_name.
1448 unsigned array_subscript;
1451 * True if the variable is gl_ClipDistance and the driver lowers
1452 * gl_ClipDistance to gl_ClipDistanceMESA.
1454 bool is_clip_distance_mesa;
1457 * The vertex shader output location that the linker assigned for this
1458 * variable. -1 if a location hasn't been assigned yet.
1463 * If location != -1, the number of vector elements in this variable, or 1
1464 * if this variable is a scalar.
1466 unsigned vector_elements;
1469 * If location != -1, the number of matrix columns in this variable, or 1
1470 * if this variable is not a matrix.
1472 unsigned matrix_columns;
1474 /** Type of the varying returned by glGetTransformFeedbackVarying() */
1478 * If location != -1, the size that should be returned by
1479 * glGetTransformFeedbackVarying().
1486 * Initialize this object based on a string that was passed to
1487 * glTransformFeedbackVaryings. If there is a parse error, the error is
1488 * reported using linker_error(), and false is returned.
1491 tfeedback_decl::init(struct gl_context *ctx, struct gl_shader_program *prog,
1492 const void *mem_ctx, const char *input)
1494 /* We don't have to be pedantic about what is a valid GLSL variable name,
1495 * because any variable with an invalid name can't exist in the IR anyway.
1498 this->location = -1;
1499 this->orig_name = input;
1500 this->is_clip_distance_mesa = false;
1502 const char *bracket = strrchr(input, '[');
1505 this->var_name = ralloc_strndup(mem_ctx, input, bracket - input);
1506 if (sscanf(bracket, "[%u]", &this->array_subscript) != 1) {
1507 linker_error(prog, "Cannot parse transform feedback varying %s", input);
1510 this->is_subscripted = true;
1512 this->var_name = ralloc_strdup(mem_ctx, input);
1513 this->is_subscripted = false;
1516 /* For drivers that lower gl_ClipDistance to gl_ClipDistanceMESA, this
1517 * class must behave specially to account for the fact that gl_ClipDistance
1518 * is converted from a float[8] to a vec4[2].
1520 if (ctx->ShaderCompilerOptions[MESA_SHADER_VERTEX].LowerClipDistance &&
1521 strcmp(this->var_name, "gl_ClipDistance") == 0) {
1522 this->is_clip_distance_mesa = true;
1530 * Determine whether two tfeedback_decl objects refer to the same variable and
1531 * array index (if applicable).
1534 tfeedback_decl::is_same(const tfeedback_decl &x, const tfeedback_decl &y)
1536 if (strcmp(x.var_name, y.var_name) != 0)
1538 if (x.is_subscripted != y.is_subscripted)
1540 if (x.is_subscripted && x.array_subscript != y.array_subscript)
1547 * Assign a location for this tfeedback_decl object based on the location
1548 * assignment in output_var.
1550 * If an error occurs, the error is reported through linker_error() and false
1554 tfeedback_decl::assign_location(struct gl_context *ctx,
1555 struct gl_shader_program *prog,
1556 ir_variable *output_var)
1558 if (output_var->type->is_array()) {
1559 /* Array variable */
1560 const unsigned matrix_cols =
1561 output_var->type->fields.array->matrix_columns;
1562 unsigned actual_array_size = this->is_clip_distance_mesa ?
1563 prog->Vert.ClipDistanceArraySize : output_var->type->array_size();
1565 if (this->is_subscripted) {
1566 /* Check array bounds. */
1567 if (this->array_subscript >= actual_array_size) {
1568 linker_error(prog, "Transform feedback varying %s has index "
1569 "%i, but the array size is %u.",
1570 this->orig_name, this->array_subscript,
1574 if (this->is_clip_distance_mesa) {
1576 output_var->location + this->array_subscript / 4;
1579 output_var->location + this->array_subscript * matrix_cols;
1583 this->location = output_var->location;
1584 this->size = actual_array_size;
1586 this->vector_elements = output_var->type->fields.array->vector_elements;
1587 this->matrix_columns = matrix_cols;
1588 if (this->is_clip_distance_mesa)
1589 this->type = GL_FLOAT;
1591 this->type = output_var->type->fields.array->gl_type;
1593 /* Regular variable (scalar, vector, or matrix) */
1594 if (this->is_subscripted) {
1595 linker_error(prog, "Transform feedback varying %s requested, "
1596 "but %s is not an array.",
1597 this->orig_name, this->var_name);
1600 this->location = output_var->location;
1602 this->vector_elements = output_var->type->vector_elements;
1603 this->matrix_columns = output_var->type->matrix_columns;
1604 this->type = output_var->type->gl_type;
1607 /* From GL_EXT_transform_feedback:
1608 * A program will fail to link if:
1610 * * the total number of components to capture in any varying
1611 * variable in <varyings> is greater than the constant
1612 * MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT and the
1613 * buffer mode is SEPARATE_ATTRIBS_EXT;
1615 if (prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS &&
1616 this->num_components() >
1617 ctx->Const.MaxTransformFeedbackSeparateComponents) {
1618 linker_error(prog, "Transform feedback varying %s exceeds "
1619 "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS.",
1629 tfeedback_decl::accumulate_num_outputs(struct gl_shader_program *prog,
1632 if (!this->is_assigned()) {
1633 /* From GL_EXT_transform_feedback:
1634 * A program will fail to link if:
1636 * * any variable name specified in the <varyings> array is not
1637 * declared as an output in the geometry shader (if present) or
1638 * the vertex shader (if no geometry shader is present);
1640 linker_error(prog, "Transform feedback varying %s undeclared.",
1645 unsigned translated_size = this->size;
1646 if (this->is_clip_distance_mesa)
1647 translated_size = (translated_size + 3) / 4;
1649 *count += translated_size * this->matrix_columns;
1656 * Update gl_transform_feedback_info to reflect this tfeedback_decl.
1658 * If an error occurs, the error is reported through linker_error() and false
1662 tfeedback_decl::store(struct gl_context *ctx, struct gl_shader_program *prog,
1663 struct gl_transform_feedback_info *info,
1665 unsigned varying, const unsigned max_outputs) const
1667 /* From GL_EXT_transform_feedback:
1668 * A program will fail to link if:
1670 * * the total number of components to capture is greater than
1671 * the constant MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT
1672 * and the buffer mode is INTERLEAVED_ATTRIBS_EXT.
1674 if (prog->TransformFeedback.BufferMode == GL_INTERLEAVED_ATTRIBS &&
1675 info->BufferStride[buffer] + this->num_components() >
1676 ctx->Const.MaxTransformFeedbackInterleavedComponents) {
1677 linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1678 "limit has been exceeded.");
1682 unsigned translated_size = this->size;
1683 if (this->is_clip_distance_mesa)
1684 translated_size = (translated_size + 3) / 4;
1685 unsigned components_so_far = 0;
1686 for (unsigned index = 0; index < translated_size; ++index) {
1687 for (unsigned v = 0; v < this->matrix_columns; ++v) {
1688 unsigned num_components = this->vector_elements;
1689 assert(info->NumOutputs < max_outputs);
1690 info->Outputs[info->NumOutputs].ComponentOffset = 0;
1691 if (this->is_clip_distance_mesa) {
1692 if (this->is_subscripted) {
1694 info->Outputs[info->NumOutputs].ComponentOffset =
1695 this->array_subscript % 4;
1697 num_components = MIN2(4, this->size - components_so_far);
1700 info->Outputs[info->NumOutputs].OutputRegister =
1701 this->location + v + index * this->matrix_columns;
1702 info->Outputs[info->NumOutputs].NumComponents = num_components;
1703 info->Outputs[info->NumOutputs].OutputBuffer = buffer;
1704 info->Outputs[info->NumOutputs].DstOffset = info->BufferStride[buffer];
1706 info->BufferStride[buffer] += num_components;
1707 components_so_far += num_components;
1710 assert(components_so_far == this->num_components());
1712 info->Varyings[varying].Name = ralloc_strdup(prog, this->orig_name);
1713 info->Varyings[varying].Type = this->type;
1714 info->Varyings[varying].Size = this->size;
1722 * Parse all the transform feedback declarations that were passed to
1723 * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
1725 * If an error occurs, the error is reported through linker_error() and false
1729 parse_tfeedback_decls(struct gl_context *ctx, struct gl_shader_program *prog,
1730 const void *mem_ctx, unsigned num_names,
1731 char **varying_names, tfeedback_decl *decls)
1733 for (unsigned i = 0; i < num_names; ++i) {
1734 if (!decls[i].init(ctx, prog, mem_ctx, varying_names[i]))
1736 /* From GL_EXT_transform_feedback:
1737 * A program will fail to link if:
1739 * * any two entries in the <varyings> array specify the same varying
1742 * We interpret this to mean "any two entries in the <varyings> array
1743 * specify the same varying variable and array index", since transform
1744 * feedback of arrays would be useless otherwise.
1746 for (unsigned j = 0; j < i; ++j) {
1747 if (tfeedback_decl::is_same(decls[i], decls[j])) {
1748 linker_error(prog, "Transform feedback varying %s specified "
1749 "more than once.", varying_names[i]);
1759 * Assign a location for a variable that is produced in one pipeline stage
1760 * (the "producer") and consumed in the next stage (the "consumer").
1762 * \param input_var is the input variable declaration in the consumer.
1764 * \param output_var is the output variable declaration in the producer.
1766 * \param input_index is the counter that keeps track of assigned input
1767 * locations in the consumer.
1769 * \param output_index is the counter that keeps track of assigned output
1770 * locations in the producer.
1772 * It is permissible for \c input_var to be NULL (this happens if a variable
1773 * is output by the producer and consumed by transform feedback, but not
1774 * consumed by the consumer).
1776 * If the variable has already been assigned a location, this function has no
1780 assign_varying_location(ir_variable *input_var, ir_variable *output_var,
1781 unsigned *input_index, unsigned *output_index)
1783 if (output_var->location != -1) {
1784 /* Location already assigned. */
1789 assert(input_var->location == -1);
1790 input_var->location = *input_index;
1793 output_var->location = *output_index;
1795 /* FINISHME: Support for "varying" records in GLSL 1.50. */
1796 assert(!output_var->type->is_record());
1798 if (output_var->type->is_array()) {
1799 const unsigned slots = output_var->type->length
1800 * output_var->type->fields.array->matrix_columns;
1802 *output_index += slots;
1803 *input_index += slots;
1805 const unsigned slots = output_var->type->matrix_columns;
1807 *output_index += slots;
1808 *input_index += slots;
1814 * Assign locations for all variables that are produced in one pipeline stage
1815 * (the "producer") and consumed in the next stage (the "consumer").
1817 * Variables produced by the producer may also be consumed by transform
1820 * \param num_tfeedback_decls is the number of declarations indicating
1821 * variables that may be consumed by transform feedback.
1823 * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
1824 * representing the result of parsing the strings passed to
1825 * glTransformFeedbackVaryings(). assign_location() will be called for
1826 * each of these objects that matches one of the outputs of the
1829 * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
1830 * be NULL. In this case, varying locations are assigned solely based on the
1831 * requirements of transform feedback.
1834 assign_varying_locations(struct gl_context *ctx,
1835 struct gl_shader_program *prog,
1836 gl_shader *producer, gl_shader *consumer,
1837 unsigned num_tfeedback_decls,
1838 tfeedback_decl *tfeedback_decls)
1840 /* FINISHME: Set dynamically when geometry shader support is added. */
1841 unsigned output_index = VERT_RESULT_VAR0;
1842 unsigned input_index = FRAG_ATTRIB_VAR0;
1844 /* Operate in a total of three passes.
1846 * 1. Assign locations for any matching inputs and outputs.
1848 * 2. Mark output variables in the producer that do not have locations as
1849 * not being outputs. This lets the optimizer eliminate them.
1851 * 3. Mark input variables in the consumer that do not have locations as
1852 * not being inputs. This lets the optimizer eliminate them.
1855 link_invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
1857 link_invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
1859 foreach_list(node, producer->ir) {
1860 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1862 if ((output_var == NULL) || (output_var->mode != ir_var_out))
1865 ir_variable *input_var =
1866 consumer ? consumer->symbols->get_variable(output_var->name) : NULL;
1868 if (input_var && input_var->mode != ir_var_in)
1872 assign_varying_location(input_var, output_var, &input_index,
1876 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1877 if (!tfeedback_decls[i].is_assigned() &&
1878 tfeedback_decls[i].matches_var(output_var)) {
1879 if (output_var->location == -1) {
1880 assign_varying_location(input_var, output_var, &input_index,
1883 if (!tfeedback_decls[i].assign_location(ctx, prog, output_var))
1889 unsigned varying_vectors = 0;
1892 foreach_list(node, consumer->ir) {
1893 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1895 if ((var == NULL) || (var->mode != ir_var_in))
1898 if (var->location == -1) {
1899 if (prog->Version <= 120) {
1900 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1902 * Only those varying variables used (i.e. read) in
1903 * the fragment shader executable must be written to
1904 * by the vertex shader executable; declaring
1905 * superfluous varying variables in a vertex shader is
1908 * We interpret this text as meaning that the VS must
1909 * write the variable for the FS to read it. See
1910 * "glsl1-varying read but not written" in piglit.
1913 linker_error(prog, "fragment shader varying %s not written "
1914 "by vertex shader\n.", var->name);
1917 /* An 'in' variable is only really a shader input if its
1918 * value is written by the previous stage.
1920 var->mode = ir_var_auto;
1922 /* The packing rules are used for vertex shader inputs are also
1923 * used for fragment shader inputs.
1925 varying_vectors += count_attribute_slots(var->type);
1930 if (ctx->API == API_OPENGLES2 || prog->Version == 100) {
1931 if (varying_vectors > ctx->Const.MaxVarying) {
1932 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
1933 linker_warning(prog, "shader uses too many varying vectors "
1934 "(%u > %u), but the driver will try to optimize "
1935 "them out; this is non-portable out-of-spec "
1937 varying_vectors, ctx->Const.MaxVarying);
1939 linker_error(prog, "shader uses too many varying vectors "
1941 varying_vectors, ctx->Const.MaxVarying);
1946 const unsigned float_components = varying_vectors * 4;
1947 if (float_components > ctx->Const.MaxVarying * 4) {
1948 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
1949 linker_warning(prog, "shader uses too many varying components "
1950 "(%u > %u), but the driver will try to optimize "
1951 "them out; this is non-portable out-of-spec "
1953 float_components, ctx->Const.MaxVarying * 4);
1955 linker_error(prog, "shader uses too many varying components "
1957 float_components, ctx->Const.MaxVarying * 4);
1968 * Store transform feedback location assignments into
1969 * prog->LinkedTransformFeedback based on the data stored in tfeedback_decls.
1971 * If an error occurs, the error is reported through linker_error() and false
1975 store_tfeedback_info(struct gl_context *ctx, struct gl_shader_program *prog,
1976 unsigned num_tfeedback_decls,
1977 tfeedback_decl *tfeedback_decls)
1979 bool separate_attribs_mode =
1980 prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS;
1982 ralloc_free(prog->LinkedTransformFeedback.Varyings);
1983 ralloc_free(prog->LinkedTransformFeedback.Outputs);
1985 memset(&prog->LinkedTransformFeedback, 0,
1986 sizeof(prog->LinkedTransformFeedback));
1988 prog->LinkedTransformFeedback.NumBuffers =
1989 separate_attribs_mode ? num_tfeedback_decls : 1;
1991 prog->LinkedTransformFeedback.Varyings =
1993 struct gl_transform_feedback_varying_info,
1994 num_tfeedback_decls);
1996 unsigned num_outputs = 0;
1997 for (unsigned i = 0; i < num_tfeedback_decls; ++i)
1998 if (!tfeedback_decls[i].accumulate_num_outputs(prog, &num_outputs))
2001 prog->LinkedTransformFeedback.Outputs =
2003 struct gl_transform_feedback_output,
2006 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
2007 unsigned buffer = separate_attribs_mode ? i : 0;
2008 if (!tfeedback_decls[i].store(ctx, prog, &prog->LinkedTransformFeedback,
2009 buffer, i, num_outputs))
2012 assert(prog->LinkedTransformFeedback.NumOutputs == num_outputs);
2018 * Store the gl_FragDepth layout in the gl_shader_program struct.
2021 store_fragdepth_layout(struct gl_shader_program *prog)
2023 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2027 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2029 /* We don't look up the gl_FragDepth symbol directly because if
2030 * gl_FragDepth is not used in the shader, it's removed from the IR.
2031 * However, the symbol won't be removed from the symbol table.
2033 * We're only interested in the cases where the variable is NOT removed
2036 foreach_list(node, ir) {
2037 ir_variable *const var = ((ir_instruction *) node)->as_variable();
2039 if (var == NULL || var->mode != ir_var_out) {
2043 if (strcmp(var->name, "gl_FragDepth") == 0) {
2044 switch (var->depth_layout) {
2045 case ir_depth_layout_none:
2046 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2048 case ir_depth_layout_any:
2049 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2051 case ir_depth_layout_greater:
2052 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2054 case ir_depth_layout_less:
2055 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2057 case ir_depth_layout_unchanged:
2058 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2069 * Validate the resources used by a program versus the implementation limits
2072 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2074 static const char *const shader_names[MESA_SHADER_TYPES] = {
2075 "vertex", "fragment", "geometry"
2078 const unsigned max_samplers[MESA_SHADER_TYPES] = {
2079 ctx->Const.MaxVertexTextureImageUnits,
2080 ctx->Const.MaxTextureImageUnits,
2081 ctx->Const.MaxGeometryTextureImageUnits
2084 const unsigned max_uniform_components[MESA_SHADER_TYPES] = {
2085 ctx->Const.VertexProgram.MaxUniformComponents,
2086 ctx->Const.FragmentProgram.MaxUniformComponents,
2087 0 /* FINISHME: Geometry shaders. */
2090 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2091 struct gl_shader *sh = prog->_LinkedShaders[i];
2096 if (sh->num_samplers > max_samplers[i]) {
2097 linker_error(prog, "Too many %s shader texture samplers",
2101 if (sh->num_uniform_components > max_uniform_components[i]) {
2102 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2103 linker_warning(prog, "Too many %s shader uniform components, "
2104 "but the driver will try to optimize them out; "
2105 "this is non-portable out-of-spec behavior\n",
2108 linker_error(prog, "Too many %s shader uniform components",
2114 return prog->LinkStatus;
2118 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
2120 tfeedback_decl *tfeedback_decls = NULL;
2121 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
2123 void *mem_ctx = ralloc_context(NULL); // temporary linker context
2125 prog->LinkStatus = false;
2126 prog->Validated = false;
2127 prog->_Used = false;
2129 if (prog->InfoLog != NULL)
2130 ralloc_free(prog->InfoLog);
2132 prog->InfoLog = ralloc_strdup(NULL, "");
2134 /* Separate the shaders into groups based on their type.
2136 struct gl_shader **vert_shader_list;
2137 unsigned num_vert_shaders = 0;
2138 struct gl_shader **frag_shader_list;
2139 unsigned num_frag_shaders = 0;
2141 vert_shader_list = (struct gl_shader **)
2142 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
2143 frag_shader_list = &vert_shader_list[prog->NumShaders];
2145 unsigned min_version = UINT_MAX;
2146 unsigned max_version = 0;
2147 for (unsigned i = 0; i < prog->NumShaders; i++) {
2148 min_version = MIN2(min_version, prog->Shaders[i]->Version);
2149 max_version = MAX2(max_version, prog->Shaders[i]->Version);
2151 switch (prog->Shaders[i]->Type) {
2152 case GL_VERTEX_SHADER:
2153 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
2156 case GL_FRAGMENT_SHADER:
2157 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
2160 case GL_GEOMETRY_SHADER:
2161 /* FINISHME: Support geometry shaders. */
2162 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
2167 /* Previous to GLSL version 1.30, different compilation units could mix and
2168 * match shading language versions. With GLSL 1.30 and later, the versions
2169 * of all shaders must match.
2171 assert(min_version >= 100);
2172 assert(max_version <= 130);
2173 if ((max_version >= 130 || min_version == 100)
2174 && min_version != max_version) {
2175 linker_error(prog, "all shaders must use same shading "
2176 "language version\n");
2180 prog->Version = max_version;
2182 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
2183 if (prog->_LinkedShaders[i] != NULL)
2184 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
2186 prog->_LinkedShaders[i] = NULL;
2189 /* Link all shaders for a particular stage and validate the result.
2191 if (num_vert_shaders > 0) {
2192 gl_shader *const sh =
2193 link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
2199 if (!validate_vertex_shader_executable(prog, sh))
2202 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
2206 if (num_frag_shaders > 0) {
2207 gl_shader *const sh =
2208 link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
2214 if (!validate_fragment_shader_executable(prog, sh))
2217 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
2221 /* Here begins the inter-stage linking phase. Some initial validation is
2222 * performed, then locations are assigned for uniforms, attributes, and
2225 if (cross_validate_uniforms(prog)) {
2228 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2229 if (prog->_LinkedShaders[prev] != NULL)
2233 /* Validate the inputs of each stage with the output of the preceding
2236 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2237 if (prog->_LinkedShaders[i] == NULL)
2240 if (!cross_validate_outputs_to_inputs(prog,
2241 prog->_LinkedShaders[prev],
2242 prog->_LinkedShaders[i]))
2248 prog->LinkStatus = true;
2251 /* Do common optimization before assigning storage for attributes,
2252 * uniforms, and varyings. Later optimization could possibly make
2253 * some of that unused.
2255 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2256 if (prog->_LinkedShaders[i] == NULL)
2259 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
2260 if (!prog->LinkStatus)
2263 if (ctx->ShaderCompilerOptions[i].LowerClipDistance)
2264 lower_clip_distance(prog->_LinkedShaders[i]->ir);
2266 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false, 32))
2270 /* FINISHME: The value of the max_attribute_index parameter is
2271 * FINISHME: implementation dependent based on the value of
2272 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
2273 * FINISHME: at least 16, so hardcode 16 for now.
2275 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX, 16)) {
2279 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, ctx->Const.MaxDrawBuffers)) {
2284 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2285 if (prog->_LinkedShaders[prev] != NULL)
2289 if (num_tfeedback_decls != 0) {
2290 /* From GL_EXT_transform_feedback:
2291 * A program will fail to link if:
2293 * * the <count> specified by TransformFeedbackVaryingsEXT is
2294 * non-zero, but the program object has no vertex or geometry
2297 if (prev >= MESA_SHADER_FRAGMENT) {
2298 linker_error(prog, "Transform feedback varyings specified, but "
2299 "no vertex or geometry shader is present.");
2303 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
2304 prog->TransformFeedback.NumVarying);
2305 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
2306 prog->TransformFeedback.VaryingNames,
2311 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2312 if (prog->_LinkedShaders[i] == NULL)
2315 if (!assign_varying_locations(
2316 ctx, prog, prog->_LinkedShaders[prev], prog->_LinkedShaders[i],
2317 i == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2324 if (prev != MESA_SHADER_FRAGMENT && num_tfeedback_decls != 0) {
2325 /* There was no fragment shader, but we still have to assign varying
2326 * locations for use by transform feedback.
2328 if (!assign_varying_locations(
2329 ctx, prog, prog->_LinkedShaders[prev], NULL, num_tfeedback_decls,
2334 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
2337 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
2338 demote_shader_inputs_and_outputs(prog->_LinkedShaders[MESA_SHADER_VERTEX],
2341 /* Eliminate code that is now dead due to unused vertex outputs being
2344 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_VERTEX]->ir, false))
2348 if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
2349 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
2351 demote_shader_inputs_and_outputs(sh, ir_var_in);
2352 demote_shader_inputs_and_outputs(sh, ir_var_inout);
2353 demote_shader_inputs_and_outputs(sh, ir_var_out);
2355 /* Eliminate code that is now dead due to unused geometry outputs being
2358 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_GEOMETRY]->ir, false))
2362 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
2363 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2365 demote_shader_inputs_and_outputs(sh, ir_var_in);
2367 /* Eliminate code that is now dead due to unused fragment inputs being
2368 * demoted. This shouldn't actually do anything other than remove
2369 * declarations of the (now unused) global variables.
2371 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir, false))
2375 update_array_sizes(prog);
2376 link_assign_uniform_locations(prog);
2377 store_fragdepth_layout(prog);
2379 if (!check_resources(ctx, prog))
2382 /* OpenGL ES requires that a vertex shader and a fragment shader both be
2383 * present in a linked program. By checking for use of shading language
2384 * version 1.00, we also catch the GL_ARB_ES2_compatibility case.
2386 if (!prog->InternalSeparateShader &&
2387 (ctx->API == API_OPENGLES2 || prog->Version == 100)) {
2388 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
2389 linker_error(prog, "program lacks a vertex shader\n");
2390 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2391 linker_error(prog, "program lacks a fragment shader\n");
2395 /* FINISHME: Assign fragment shader output locations. */
2398 free(vert_shader_list);
2400 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2401 if (prog->_LinkedShaders[i] == NULL)
2404 /* Retain any live IR, but trash the rest. */
2405 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
2407 /* The symbol table in the linked shaders may contain references to
2408 * variables that were removed (e.g., unused uniforms). Since it may
2409 * contain junk, there is no possible valid use. Delete it and set the
2412 delete prog->_LinkedShaders[i]->symbols;
2413 prog->_LinkedShaders[i]->symbols = NULL;
2416 ralloc_free(mem_ctx);