linker: Remove redundant check for 'main' in shaders
[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 #include <cstdlib>
67 #include <cstdio>
68 #include <cstdarg>
69 #include <climits>
70
71 extern "C" {
72 #include <talloc.h>
73 }
74
75 #include "main/mtypes.h"
76 #include "main/macros.h"
77 #include "glsl_symbol_table.h"
78 #include "ir.h"
79 #include "program.h"
80 #include "hash_table.h"
81 #include "shader_api.h"
82 #include "linker.h"
83
84 /**
85 * Visitor that determines whether or not a variable is ever written.
86 */
87 class find_assignment_visitor : public ir_hierarchical_visitor {
88 public:
89 find_assignment_visitor(const char *name)
90 : name(name), found(false)
91 {
92 /* empty */
93 }
94
95 virtual ir_visitor_status visit_enter(ir_assignment *ir)
96 {
97 ir_variable *const var = ir->lhs->variable_referenced();
98
99 if (strcmp(name, var->name) == 0) {
100 found = true;
101 return visit_stop;
102 }
103
104 return visit_continue_with_parent;
105 }
106
107 bool variable_found()
108 {
109 return found;
110 }
111
112 private:
113 const char *name; /**< Find writes to a variable with this name. */
114 bool found; /**< Was a write to the variable found? */
115 };
116
117
118 void
119 linker_error_printf(gl_shader_program *prog, const char *fmt, ...)
120 {
121 va_list ap;
122
123 prog->InfoLog = talloc_strdup_append(prog->InfoLog, "error: ");
124 va_start(ap, fmt);
125 prog->InfoLog = talloc_vasprintf_append(prog->InfoLog, fmt, ap);
126 va_end(ap);
127 }
128
129
130 void
131 invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
132 int generic_base)
133 {
134 foreach_list(node, sh->ir) {
135 ir_variable *const var = ((ir_instruction *) node)->as_variable();
136
137 if ((var == NULL) || (var->mode != (unsigned) mode))
138 continue;
139
140 /* Only assign locations for generic attributes / varyings / etc.
141 */
142 if (var->location >= generic_base)
143 var->location = -1;
144 }
145 }
146
147
148 /**
149 * Determine the number of attribute slots required for a particular type
150 *
151 * This code is here because it implements the language rules of a specific
152 * GLSL version. Since it's a property of the language and not a property of
153 * types in general, it doesn't really belong in glsl_type.
154 */
155 unsigned
156 count_attribute_slots(const glsl_type *t)
157 {
158 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
159 *
160 * "A scalar input counts the same amount against this limit as a vec4,
161 * so applications may want to consider packing groups of four
162 * unrelated float inputs together into a vector to better utilize the
163 * capabilities of the underlying hardware. A matrix input will use up
164 * multiple locations. The number of locations used will equal the
165 * number of columns in the matrix."
166 *
167 * The spec does not explicitly say how arrays are counted. However, it
168 * should be safe to assume the total number of slots consumed by an array
169 * is the number of entries in the array multiplied by the number of slots
170 * consumed by a single element of the array.
171 */
172
173 if (t->is_array())
174 return t->array_size() * count_attribute_slots(t->element_type());
175
176 if (t->is_matrix())
177 return t->matrix_columns;
178
179 return 1;
180 }
181
182
183 /**
184 * Verify that a vertex shader executable meets all semantic requirements
185 *
186 * \param shader Vertex shader executable to be verified
187 */
188 bool
189 validate_vertex_shader_executable(struct gl_shader_program *prog,
190 struct gl_shader *shader)
191 {
192 if (shader == NULL)
193 return true;
194
195 find_assignment_visitor find("gl_Position");
196 find.run(shader->ir);
197 if (!find.variable_found()) {
198 linker_error_printf(prog,
199 "vertex shader does not write to `gl_Position'\n");
200 return false;
201 }
202
203 return true;
204 }
205
206
207 /**
208 * Verify that a fragment shader executable meets all semantic requirements
209 *
210 * \param shader Fragment shader executable to be verified
211 */
212 bool
213 validate_fragment_shader_executable(struct gl_shader_program *prog,
214 struct gl_shader *shader)
215 {
216 if (shader == NULL)
217 return true;
218
219 find_assignment_visitor frag_color("gl_FragColor");
220 find_assignment_visitor frag_data("gl_FragData");
221
222 frag_color.run(shader->ir);
223 frag_data.run(shader->ir);
224
225 if (frag_color.variable_found() && frag_data.variable_found()) {
226 linker_error_printf(prog, "fragment shader writes to both "
227 "`gl_FragColor' and `gl_FragData'\n");
228 return false;
229 }
230
231 return true;
232 }
233
234
235 /**
236 * Generate a string describing the mode of a variable
237 */
238 static const char *
239 mode_string(const ir_variable *var)
240 {
241 switch (var->mode) {
242 case ir_var_auto:
243 return (var->read_only) ? "global constant" : "global variable";
244
245 case ir_var_uniform: return "uniform";
246 case ir_var_in: return "shader input";
247 case ir_var_out: return "shader output";
248 case ir_var_inout: return "shader inout";
249 default:
250 assert(!"Should not get here.");
251 return "invalid variable";
252 }
253 }
254
255
256 /**
257 * Perform validation of global variables used across multiple shaders
258 */
259 bool
260 cross_validate_globals(struct gl_shader_program *prog,
261 struct gl_shader **shader_list,
262 unsigned num_shaders,
263 bool uniforms_only)
264 {
265 /* Examine all of the uniforms in all of the shaders and cross validate
266 * them.
267 */
268 glsl_symbol_table variables;
269 for (unsigned i = 0; i < num_shaders; i++) {
270 foreach_list(node, shader_list[i]->ir) {
271 ir_variable *const var = ((ir_instruction *) node)->as_variable();
272
273 if (var == NULL)
274 continue;
275
276 if (uniforms_only && (var->mode != ir_var_uniform))
277 continue;
278
279 /* If a global with this name has already been seen, verify that the
280 * new instance has the same type. In addition, if the globals have
281 * initializers, the values of the initializers must be the same.
282 */
283 ir_variable *const existing = variables.get_variable(var->name);
284 if (existing != NULL) {
285 if (var->type != existing->type) {
286 linker_error_printf(prog, "%s `%s' declared as type "
287 "`%s' and type `%s'\n",
288 mode_string(var),
289 var->name, var->type->name,
290 existing->type->name);
291 return false;
292 }
293
294 /* FINISHME: Handle non-constant initializers.
295 */
296 if (var->constant_value != NULL) {
297 if (existing->constant_value != NULL) {
298 if (!var->constant_value->has_value(existing->constant_value)) {
299 linker_error_printf(prog, "initializers for %s "
300 "`%s' have differing values\n",
301 mode_string(var), var->name);
302 return false;
303 }
304 } else
305 /* If the first-seen instance of a particular uniform did not
306 * have an initializer but a later instance does, copy the
307 * initializer to the version stored in the symbol table.
308 */
309 /* FINISHME: This is wrong. The constant_value field should
310 * FINISHME: not be modified! Imagine a case where a shader
311 * FINISHME: without an initializer is linked in two different
312 * FINISHME: programs with shaders that have differing
313 * FINISHME: initializers. Linking with the first will
314 * FINISHME: modify the shader, and linking with the second
315 * FINISHME: will fail.
316 */
317 existing->constant_value = var->constant_value->clone(NULL);
318 }
319 } else
320 variables.add_variable(var->name, var);
321 }
322 }
323
324 return true;
325 }
326
327
328 /**
329 * Perform validation of uniforms used across multiple shader stages
330 */
331 bool
332 cross_validate_uniforms(struct gl_shader_program *prog)
333 {
334 return cross_validate_globals(prog, prog->_LinkedShaders,
335 prog->_NumLinkedShaders, true);
336 }
337
338
339 /**
340 * Validate that outputs from one stage match inputs of another
341 */
342 bool
343 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
344 gl_shader *producer, gl_shader *consumer)
345 {
346 glsl_symbol_table parameters;
347 /* FINISHME: Figure these out dynamically. */
348 const char *const producer_stage = "vertex";
349 const char *const consumer_stage = "fragment";
350
351 /* Find all shader outputs in the "producer" stage.
352 */
353 foreach_list(node, producer->ir) {
354 ir_variable *const var = ((ir_instruction *) node)->as_variable();
355
356 /* FINISHME: For geometry shaders, this should also look for inout
357 * FINISHME: variables.
358 */
359 if ((var == NULL) || (var->mode != ir_var_out))
360 continue;
361
362 parameters.add_variable(var->name, var);
363 }
364
365
366 /* Find all shader inputs in the "consumer" stage. Any variables that have
367 * matching outputs already in the symbol table must have the same type and
368 * qualifiers.
369 */
370 foreach_list(node, consumer->ir) {
371 ir_variable *const input = ((ir_instruction *) node)->as_variable();
372
373 /* FINISHME: For geometry shaders, this should also look for inout
374 * FINISHME: variables.
375 */
376 if ((input == NULL) || (input->mode != ir_var_in))
377 continue;
378
379 ir_variable *const output = parameters.get_variable(input->name);
380 if (output != NULL) {
381 /* Check that the types match between stages.
382 */
383 if (input->type != output->type) {
384 linker_error_printf(prog,
385 "%s shader output `%s' delcared as "
386 "type `%s', but %s shader input declared "
387 "as type `%s'\n",
388 producer_stage, output->name,
389 output->type->name,
390 consumer_stage, input->type->name);
391 return false;
392 }
393
394 /* Check that all of the qualifiers match between stages.
395 */
396 if (input->centroid != output->centroid) {
397 linker_error_printf(prog,
398 "%s shader output `%s' %s centroid qualifier, "
399 "but %s shader input %s centroid qualifier\n",
400 producer_stage,
401 output->name,
402 (output->centroid) ? "has" : "lacks",
403 consumer_stage,
404 (input->centroid) ? "has" : "lacks");
405 return false;
406 }
407
408 if (input->invariant != output->invariant) {
409 linker_error_printf(prog,
410 "%s shader output `%s' %s invariant qualifier, "
411 "but %s shader input %s invariant qualifier\n",
412 producer_stage,
413 output->name,
414 (output->invariant) ? "has" : "lacks",
415 consumer_stage,
416 (input->invariant) ? "has" : "lacks");
417 return false;
418 }
419
420 if (input->interpolation != output->interpolation) {
421 linker_error_printf(prog,
422 "%s shader output `%s' specifies %s "
423 "interpolation qualifier, "
424 "but %s shader input specifies %s "
425 "interpolation qualifier\n",
426 producer_stage,
427 output->name,
428 output->interpolation_string(),
429 consumer_stage,
430 input->interpolation_string());
431 return false;
432 }
433 }
434 }
435
436 return true;
437 }
438
439
440 /**
441 * Populates a shaders symbol table with all global declarations
442 */
443 static void
444 populate_symbol_table(gl_shader *sh)
445 {
446 sh->symbols = new(sh) glsl_symbol_table;
447
448 foreach_list(node, sh->ir) {
449 ir_instruction *const inst = (ir_instruction *) node;
450 ir_variable *var;
451 ir_function *func;
452
453 if ((func = inst->as_function()) != NULL) {
454 sh->symbols->add_function(func->name, func);
455 } else if ((var = inst->as_variable()) != NULL) {
456 sh->symbols->add_variable(var->name, var);
457 }
458 }
459 }
460
461
462 /**
463 * Remap variables referenced in an instruction tree
464 *
465 * This is used when instruction trees are cloned from one shader and placed in
466 * another. These trees will contain references to \c ir_variable nodes that
467 * do not exist in the target shader. This function finds these \c ir_variable
468 * references and replaces the references with matching variables in the target
469 * shader.
470 *
471 * If there is no matching variable in the target shader, a clone of the
472 * \c ir_variable is made and added to the target shader. The new variable is
473 * added to \b both the instruction stream and the symbol table.
474 *
475 * \param inst IR tree that is to be processed.
476 * \param symbols Symbol table containing global scope symbols in the
477 * linked shader.
478 * \param instructions Instruction stream where new variable declarations
479 * should be added.
480 */
481 void
482 remap_variables(ir_instruction *inst, glsl_symbol_table *symbols,
483 exec_list *instructions)
484 {
485 class remap_visitor : public ir_hierarchical_visitor {
486 public:
487 remap_visitor(glsl_symbol_table *symbols, exec_list *instructions)
488 {
489 this->symbols = symbols;
490 this->instructions = instructions;
491 }
492
493 virtual ir_visitor_status visit(ir_dereference_variable *ir)
494 {
495 ir_variable *const existing =
496 this->symbols->get_variable(ir->var->name);
497 if (existing != NULL)
498 ir->var = existing;
499 else {
500 ir_variable *copy = ir->var->clone(NULL);
501
502 this->symbols->add_variable(copy->name, copy);
503 this->instructions->push_head(copy);
504 }
505
506 return visit_continue;
507 }
508
509 private:
510 glsl_symbol_table *symbols;
511 exec_list *instructions;
512 };
513
514 remap_visitor v(symbols, instructions);
515
516 inst->accept(&v);
517 }
518
519
520 /**
521 * Move non-declarations from one instruction stream to another
522 *
523 * The intended usage pattern of this function is to pass the pointer to the
524 * head sentinal of a list (i.e., a pointer to the list cast to an \c exec_node
525 * pointer) for \c last and \c false for \c make_copies on the first
526 * call. Successive calls pass the return value of the previous call for
527 * \c last and \c true for \c make_copies.
528 *
529 * \param instructions Source instruction stream
530 * \param last Instruction after which new instructions should be
531 * inserted in the target instruction stream
532 * \param make_copies Flag selecting whether instructions in \c instructions
533 * should be copied (via \c ir_instruction::clone) into the
534 * target list or moved.
535 *
536 * \return
537 * The new "last" instruction in the target instruction stream. This pointer
538 * is suitable for use as the \c last parameter of a later call to this
539 * function.
540 */
541 exec_node *
542 move_non_declarations(exec_list *instructions, exec_node *last,
543 bool make_copies, gl_shader *target)
544 {
545 foreach_list_safe(node, instructions) {
546 ir_instruction *inst = (ir_instruction *) node;
547
548 if (inst->as_variable() || inst->as_function())
549 continue;
550
551 assert(inst->as_assignment());
552
553 if (make_copies) {
554 inst = inst->clone(NULL);
555 remap_variables(inst, target->symbols, target->ir);
556 } else {
557 inst->remove();
558 }
559
560 last->insert_after(inst);
561 last = inst;
562 }
563
564 return last;
565 }
566
567 /**
568 * Get the function signature for main from a shader
569 */
570 static ir_function_signature *
571 get_main_function_signature(gl_shader *sh)
572 {
573 ir_function *const f = sh->symbols->get_function("main");
574 if (f != NULL) {
575 exec_list void_parameters;
576
577 /* Look for the 'void main()' signature and ensure that it's defined.
578 * This keeps the linker from accidentally pick a shader that just
579 * contains a prototype for main.
580 *
581 * We don't have to check for multiple definitions of main (in multiple
582 * shaders) because that would have already been caught above.
583 */
584 ir_function_signature *sig = f->matching_signature(&void_parameters);
585 if ((sig != NULL) && sig->is_defined) {
586 return sig;
587 }
588 }
589
590 return NULL;
591 }
592
593
594 /**
595 * Combine a group of shaders for a single stage to generate a linked shader
596 *
597 * \note
598 * If this function is supplied a single shader, it is cloned, and the new
599 * shader is returned.
600 */
601 static struct gl_shader *
602 link_intrastage_shaders(struct gl_shader_program *prog,
603 struct gl_shader **shader_list,
604 unsigned num_shaders)
605 {
606 /* Check that global variables defined in multiple shaders are consistent.
607 */
608 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
609 return NULL;
610
611 /* Check that there is only a single definition of each function signature
612 * across all shaders.
613 */
614 for (unsigned i = 0; i < (num_shaders - 1); i++) {
615 foreach_list(node, shader_list[i]->ir) {
616 ir_function *const f = ((ir_instruction *) node)->as_function();
617
618 if (f == NULL)
619 continue;
620
621 for (unsigned j = i + 1; j < num_shaders; j++) {
622 ir_function *const other =
623 shader_list[j]->symbols->get_function(f->name);
624
625 /* If the other shader has no function (and therefore no function
626 * signatures) with the same name, skip to the next shader.
627 */
628 if (other == NULL)
629 continue;
630
631 foreach_iter (exec_list_iterator, iter, *f) {
632 ir_function_signature *sig =
633 (ir_function_signature *) iter.get();
634
635 if (!sig->is_defined || sig->is_built_in)
636 continue;
637
638 ir_function_signature *other_sig =
639 other->exact_matching_signature(& sig->parameters);
640
641 if ((other_sig != NULL) && other_sig->is_defined
642 && !other_sig->is_built_in) {
643 linker_error_printf(prog,
644 "function `%s' is multiply defined",
645 f->name);
646 return NULL;
647 }
648 }
649 }
650 }
651 }
652
653 /* Find the shader that defines main, and make a clone of it.
654 *
655 * Starting with the clone, search for undefined references. If one is
656 * found, find the shader that defines it. Clone the reference and add
657 * it to the shader. Repeat until there are no undefined references or
658 * until a reference cannot be resolved.
659 */
660 gl_shader *main = NULL;
661 for (unsigned i = 0; i < num_shaders; i++) {
662 if (get_main_function_signature(shader_list[i]) != NULL) {
663 main = shader_list[i];
664 break;
665 }
666 }
667
668 if (main == NULL) {
669 linker_error_printf(prog, "%s shader lacks `main'\n",
670 (shader_list[0]->Type == GL_VERTEX_SHADER)
671 ? "vertex" : "fragment");
672 return NULL;
673 }
674
675 gl_shader *const linked = _mesa_new_shader(NULL, 0, main->Type);
676 linked->ir = new(linked) exec_list;
677 clone_ir_list(linked->ir, main->ir);
678
679 populate_symbol_table(linked);
680
681 /* The a pointer to the main function in the final linked shader (i.e., the
682 * copy of the original shader that contained the main function).
683 */
684 ir_function_signature *const main_sig = get_main_function_signature(linked);
685
686 /* Move any instructions other than variable declarations or function
687 * declarations into main.
688 */
689 exec_node *insertion_point =
690 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
691 linked);
692
693 for (unsigned i = 0; i < num_shaders; i++) {
694 if (shader_list[i] == main)
695 continue;
696
697 insertion_point = move_non_declarations(shader_list[i]->ir,
698 insertion_point, true, linked);
699 }
700
701 /* Resolve initializers for global variables in the linked shader.
702 */
703 link_function_calls(prog, linked, shader_list, num_shaders);
704
705 return linked;
706 }
707
708
709 struct uniform_node {
710 exec_node link;
711 struct gl_uniform *u;
712 unsigned slots;
713 };
714
715 void
716 assign_uniform_locations(struct gl_shader_program *prog)
717 {
718 /* */
719 exec_list uniforms;
720 unsigned total_uniforms = 0;
721 hash_table *ht = hash_table_ctor(32, hash_table_string_hash,
722 hash_table_string_compare);
723
724 for (unsigned i = 0; i < prog->_NumLinkedShaders; i++) {
725 unsigned next_position = 0;
726
727 foreach_list(node, prog->_LinkedShaders[i]->ir) {
728 ir_variable *const var = ((ir_instruction *) node)->as_variable();
729
730 if ((var == NULL) || (var->mode != ir_var_uniform))
731 continue;
732
733 const unsigned vec4_slots = (var->component_slots() + 3) / 4;
734 assert(vec4_slots != 0);
735
736 uniform_node *n = (uniform_node *) hash_table_find(ht, var->name);
737 if (n == NULL) {
738 n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
739 n->u = (gl_uniform *) calloc(vec4_slots, sizeof(struct gl_uniform));
740 n->slots = vec4_slots;
741
742 n->u[0].Name = strdup(var->name);
743 for (unsigned j = 1; j < vec4_slots; j++)
744 n->u[j].Name = n->u[0].Name;
745
746 hash_table_insert(ht, n, n->u[0].Name);
747 uniforms.push_tail(& n->link);
748 total_uniforms += vec4_slots;
749 }
750
751 if (var->constant_value != NULL)
752 for (unsigned j = 0; j < vec4_slots; j++)
753 n->u[j].Initialized = true;
754
755 var->location = next_position;
756
757 for (unsigned j = 0; j < vec4_slots; j++) {
758 switch (prog->_LinkedShaders[i]->Type) {
759 case GL_VERTEX_SHADER:
760 n->u[j].VertPos = next_position;
761 break;
762 case GL_FRAGMENT_SHADER:
763 n->u[j].FragPos = next_position;
764 break;
765 case GL_GEOMETRY_SHADER:
766 /* FINISHME: Support geometry shaders. */
767 assert(prog->_LinkedShaders[i]->Type != GL_GEOMETRY_SHADER);
768 break;
769 }
770
771 next_position++;
772 }
773 }
774 }
775
776 gl_uniform_list *ul = (gl_uniform_list *)
777 calloc(1, sizeof(gl_uniform_list));
778
779 ul->Size = total_uniforms;
780 ul->NumUniforms = total_uniforms;
781 ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
782
783 unsigned idx = 0;
784 uniform_node *next;
785 for (uniform_node *node = (uniform_node *) uniforms.head
786 ; node->link.next != NULL
787 ; node = next) {
788 next = (uniform_node *) node->link.next;
789
790 node->link.remove();
791 memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform) * node->slots);
792 idx += node->slots;
793
794 free(node->u);
795 free(node);
796 }
797
798 hash_table_dtor(ht);
799
800 prog->Uniforms = ul;
801 }
802
803
804 /**
805 * Find a contiguous set of available bits in a bitmask
806 *
807 * \param used_mask Bits representing used (1) and unused (0) locations
808 * \param needed_count Number of contiguous bits needed.
809 *
810 * \return
811 * Base location of the available bits on success or -1 on failure.
812 */
813 int
814 find_available_slots(unsigned used_mask, unsigned needed_count)
815 {
816 unsigned needed_mask = (1 << needed_count) - 1;
817 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
818
819 /* The comparison to 32 is redundant, but without it GCC emits "warning:
820 * cannot optimize possibly infinite loops" for the loop below.
821 */
822 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
823 return -1;
824
825 for (int i = 0; i <= max_bit_to_test; i++) {
826 if ((needed_mask & ~used_mask) == needed_mask)
827 return i;
828
829 needed_mask <<= 1;
830 }
831
832 return -1;
833 }
834
835
836 bool
837 assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
838 {
839 /* Mark invalid attribute locations as being used.
840 */
841 unsigned used_locations = (max_attribute_index >= 32)
842 ? ~0 : ~((1 << max_attribute_index) - 1);
843
844 gl_shader *const sh = prog->_LinkedShaders[0];
845 assert(sh->Type == GL_VERTEX_SHADER);
846
847 /* Operate in a total of four passes.
848 *
849 * 1. Invalidate the location assignments for all vertex shader inputs.
850 *
851 * 2. Assign locations for inputs that have user-defined (via
852 * glBindVertexAttribLocation) locatoins.
853 *
854 * 3. Sort the attributes without assigned locations by number of slots
855 * required in decreasing order. Fragmentation caused by attribute
856 * locations assigned by the application may prevent large attributes
857 * from having enough contiguous space.
858 *
859 * 4. Assign locations to any inputs without assigned locations.
860 */
861
862 invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
863
864 if (prog->Attributes != NULL) {
865 for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
866 ir_variable *const var =
867 sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
868
869 /* Note: attributes that occupy multiple slots, such as arrays or
870 * matrices, may appear in the attrib array multiple times.
871 */
872 if ((var == NULL) || (var->location != -1))
873 continue;
874
875 /* From page 61 of the OpenGL 4.0 spec:
876 *
877 * "LinkProgram will fail if the attribute bindings assigned by
878 * BindAttribLocation do not leave not enough space to assign a
879 * location for an active matrix attribute or an active attribute
880 * array, both of which require multiple contiguous generic
881 * attributes."
882 *
883 * Previous versions of the spec contain similar language but omit the
884 * bit about attribute arrays.
885 *
886 * Page 61 of the OpenGL 4.0 spec also says:
887 *
888 * "It is possible for an application to bind more than one
889 * attribute name to the same location. This is referred to as
890 * aliasing. This will only work if only one of the aliased
891 * attributes is active in the executable program, or if no path
892 * through the shader consumes more than one attribute of a set
893 * of attributes aliased to the same location. A link error can
894 * occur if the linker determines that every path through the
895 * shader consumes multiple aliased attributes, but
896 * implementations are not required to generate an error in this
897 * case."
898 *
899 * These two paragraphs are either somewhat contradictory, or I don't
900 * fully understand one or both of them.
901 */
902 /* FINISHME: The code as currently written does not support attribute
903 * FINISHME: location aliasing (see comment above).
904 */
905 const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
906 const unsigned slots = count_attribute_slots(var->type);
907
908 /* Mask representing the contiguous slots that will be used by this
909 * attribute.
910 */
911 const unsigned use_mask = (1 << slots) - 1;
912
913 /* Generate a link error if the set of bits requested for this
914 * attribute overlaps any previously allocated bits.
915 */
916 if ((~(use_mask << attr) & used_locations) != used_locations) {
917 linker_error_printf(prog,
918 "insufficient contiguous attribute locations "
919 "available for vertex shader input `%s'",
920 var->name);
921 return false;
922 }
923
924 var->location = VERT_ATTRIB_GENERIC0 + attr;
925 used_locations |= (use_mask << attr);
926 }
927 }
928
929 /* Temporary storage for the set of attributes that need locations assigned.
930 */
931 struct temp_attr {
932 unsigned slots;
933 ir_variable *var;
934
935 /* Used below in the call to qsort. */
936 static int compare(const void *a, const void *b)
937 {
938 const temp_attr *const l = (const temp_attr *) a;
939 const temp_attr *const r = (const temp_attr *) b;
940
941 /* Reversed because we want a descending order sort below. */
942 return r->slots - l->slots;
943 }
944 } to_assign[16];
945
946 unsigned num_attr = 0;
947
948 foreach_list(node, sh->ir) {
949 ir_variable *const var = ((ir_instruction *) node)->as_variable();
950
951 if ((var == NULL) || (var->mode != ir_var_in))
952 continue;
953
954 /* The location was explicitly assigned, nothing to do here.
955 */
956 if (var->location != -1)
957 continue;
958
959 to_assign[num_attr].slots = count_attribute_slots(var->type);
960 to_assign[num_attr].var = var;
961 num_attr++;
962 }
963
964 /* If all of the attributes were assigned locations by the application (or
965 * are built-in attributes with fixed locations), return early. This should
966 * be the common case.
967 */
968 if (num_attr == 0)
969 return true;
970
971 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
972
973 /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
974 * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
975 * to prevent it from being automatically allocated below.
976 */
977 used_locations |= (1 << 0);
978
979 for (unsigned i = 0; i < num_attr; i++) {
980 /* Mask representing the contiguous slots that will be used by this
981 * attribute.
982 */
983 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
984
985 int location = find_available_slots(used_locations, to_assign[i].slots);
986
987 if (location < 0) {
988 linker_error_printf(prog,
989 "insufficient contiguous attribute locations "
990 "available for vertex shader input `%s'",
991 to_assign[i].var->name);
992 return false;
993 }
994
995 to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
996 used_locations |= (use_mask << location);
997 }
998
999 return true;
1000 }
1001
1002
1003 void
1004 assign_varying_locations(gl_shader *producer, gl_shader *consumer)
1005 {
1006 /* FINISHME: Set dynamically when geometry shader support is added. */
1007 unsigned output_index = VERT_RESULT_VAR0;
1008 unsigned input_index = FRAG_ATTRIB_VAR0;
1009
1010 /* Operate in a total of three passes.
1011 *
1012 * 1. Assign locations for any matching inputs and outputs.
1013 *
1014 * 2. Mark output variables in the producer that do not have locations as
1015 * not being outputs. This lets the optimizer eliminate them.
1016 *
1017 * 3. Mark input variables in the consumer that do not have locations as
1018 * not being inputs. This lets the optimizer eliminate them.
1019 */
1020
1021 invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
1022 invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
1023
1024 foreach_list(node, producer->ir) {
1025 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1026
1027 if ((output_var == NULL) || (output_var->mode != ir_var_out)
1028 || (output_var->location != -1))
1029 continue;
1030
1031 ir_variable *const input_var =
1032 consumer->symbols->get_variable(output_var->name);
1033
1034 if ((input_var == NULL) || (input_var->mode != ir_var_in))
1035 continue;
1036
1037 assert(input_var->location == -1);
1038
1039 /* FINISHME: Location assignment will need some changes when arrays,
1040 * FINISHME: matrices, and structures are allowed as shader inputs /
1041 * FINISHME: outputs.
1042 */
1043 output_var->location = output_index;
1044 input_var->location = input_index;
1045
1046 output_index++;
1047 input_index++;
1048 }
1049
1050 foreach_list(node, producer->ir) {
1051 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1052
1053 if ((var == NULL) || (var->mode != ir_var_out))
1054 continue;
1055
1056 /* An 'out' variable is only really a shader output if its value is read
1057 * by the following stage.
1058 */
1059 if (var->location == -1) {
1060 var->shader_out = false;
1061 var->mode = ir_var_auto;
1062 }
1063 }
1064
1065 foreach_list(node, consumer->ir) {
1066 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1067
1068 if ((var == NULL) || (var->mode != ir_var_in))
1069 continue;
1070
1071 /* An 'in' variable is only really a shader input if its value is written
1072 * by the previous stage.
1073 */
1074 var->shader_in = (var->location != -1);
1075 }
1076 }
1077
1078
1079 void
1080 link_shaders(struct gl_shader_program *prog)
1081 {
1082 prog->LinkStatus = false;
1083 prog->Validated = false;
1084 prog->_Used = false;
1085
1086 if (prog->InfoLog != NULL)
1087 talloc_free(prog->InfoLog);
1088
1089 prog->InfoLog = talloc_strdup(NULL, "");
1090
1091 /* Separate the shaders into groups based on their type.
1092 */
1093 struct gl_shader **vert_shader_list;
1094 unsigned num_vert_shaders = 0;
1095 struct gl_shader **frag_shader_list;
1096 unsigned num_frag_shaders = 0;
1097
1098 vert_shader_list = (struct gl_shader **)
1099 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
1100 frag_shader_list = &vert_shader_list[prog->NumShaders];
1101
1102 unsigned min_version = UINT_MAX;
1103 unsigned max_version = 0;
1104 for (unsigned i = 0; i < prog->NumShaders; i++) {
1105 min_version = MIN2(min_version, prog->Shaders[i]->Version);
1106 max_version = MAX2(max_version, prog->Shaders[i]->Version);
1107
1108 switch (prog->Shaders[i]->Type) {
1109 case GL_VERTEX_SHADER:
1110 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
1111 num_vert_shaders++;
1112 break;
1113 case GL_FRAGMENT_SHADER:
1114 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
1115 num_frag_shaders++;
1116 break;
1117 case GL_GEOMETRY_SHADER:
1118 /* FINISHME: Support geometry shaders. */
1119 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
1120 break;
1121 }
1122 }
1123
1124 /* Previous to GLSL version 1.30, different compilation units could mix and
1125 * match shading language versions. With GLSL 1.30 and later, the versions
1126 * of all shaders must match.
1127 */
1128 assert(min_version >= 110);
1129 assert(max_version <= 130);
1130 if ((max_version >= 130) && (min_version != max_version)) {
1131 linker_error_printf(prog, "all shaders must use same shading "
1132 "language version\n");
1133 goto done;
1134 }
1135
1136 prog->Version = max_version;
1137
1138 /* FINISHME: Implement intra-stage linking. */
1139 prog->_NumLinkedShaders = 0;
1140 if (num_vert_shaders > 0) {
1141 gl_shader *const sh =
1142 link_intrastage_shaders(prog, vert_shader_list, num_vert_shaders);
1143
1144 if (sh == NULL)
1145 goto done;
1146
1147 if (!validate_vertex_shader_executable(prog, sh))
1148 goto done;
1149
1150 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
1151 prog->_NumLinkedShaders++;
1152 }
1153
1154 if (num_frag_shaders > 0) {
1155 gl_shader *const sh =
1156 link_intrastage_shaders(prog, frag_shader_list, num_frag_shaders);
1157
1158 if (sh == NULL)
1159 goto done;
1160
1161 if (!validate_fragment_shader_executable(prog, sh))
1162 goto done;
1163
1164 prog->_LinkedShaders[prog->_NumLinkedShaders] = sh;
1165 prog->_NumLinkedShaders++;
1166 }
1167
1168 /* Here begins the inter-stage linking phase. Some initial validation is
1169 * performed, then locations are assigned for uniforms, attributes, and
1170 * varyings.
1171 */
1172 if (cross_validate_uniforms(prog)) {
1173 /* Validate the inputs of each stage with the output of the preceeding
1174 * stage.
1175 */
1176 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++) {
1177 if (!cross_validate_outputs_to_inputs(prog,
1178 prog->_LinkedShaders[i - 1],
1179 prog->_LinkedShaders[i]))
1180 goto done;
1181 }
1182
1183 prog->LinkStatus = true;
1184 }
1185
1186 /* FINISHME: Perform whole-program optimization here. */
1187
1188 assign_uniform_locations(prog);
1189
1190 if (prog->_LinkedShaders[0]->Type == GL_VERTEX_SHADER)
1191 /* FINISHME: The value of the max_attribute_index parameter is
1192 * FINISHME: implementation dependent based on the value of
1193 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1194 * FINISHME: at least 16, so hardcode 16 for now.
1195 */
1196 if (!assign_attribute_locations(prog, 16))
1197 goto done;
1198
1199 for (unsigned i = 1; i < prog->_NumLinkedShaders; i++)
1200 assign_varying_locations(prog->_LinkedShaders[i - 1],
1201 prog->_LinkedShaders[i]);
1202
1203 /* FINISHME: Assign fragment shader output locations. */
1204
1205 done:
1206 free(vert_shader_list);
1207 }