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