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