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