glsl: fix linker error message context for frag shader output.
[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
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 /* From the GLSL 1.10 spec, page 48:
262 *
263 * "The variable gl_Position is available only in the vertex
264 * language and is intended for writing the homogeneous vertex
265 * position. All executions of a well-formed vertex shader
266 * executable must write a value into this variable. [...] The
267 * variable gl_Position is available only in the vertex
268 * language and is intended for writing the homogeneous vertex
269 * position. All executions of a well-formed vertex shader
270 * executable must write a value into this variable."
271 *
272 * while in GLSL 1.40 this text is changed to:
273 *
274 * "The variable gl_Position is available only in the vertex
275 * language and is intended for writing the homogeneous vertex
276 * position. It can be written at any time during shader
277 * execution. It may also be read back by a vertex shader
278 * after being written. This value will be used by primitive
279 * assembly, clipping, culling, and other fixed functionality
280 * operations, if present, that operate on primitives after
281 * vertex processing has occurred. Its value is undefined if
282 * the vertex shader executable does not write gl_Position."
283 */
284 if (prog->Version < 140) {
285 find_assignment_visitor find("gl_Position");
286 find.run(shader->ir);
287 if (!find.variable_found()) {
288 linker_error(prog, "vertex shader does not write to `gl_Position'\n");
289 return false;
290 }
291 }
292
293 prog->Vert.ClipDistanceArraySize = 0;
294
295 if (prog->Version >= 130) {
296 /* From section 7.1 (Vertex Shader Special Variables) of the
297 * GLSL 1.30 spec:
298 *
299 * "It is an error for a shader to statically write both
300 * gl_ClipVertex and gl_ClipDistance."
301 */
302 find_assignment_visitor clip_vertex("gl_ClipVertex");
303 find_assignment_visitor clip_distance("gl_ClipDistance");
304
305 clip_vertex.run(shader->ir);
306 clip_distance.run(shader->ir);
307 if (clip_vertex.variable_found() && clip_distance.variable_found()) {
308 linker_error(prog, "vertex shader writes to both `gl_ClipVertex' "
309 "and `gl_ClipDistance'\n");
310 return false;
311 }
312 prog->Vert.UsesClipDistance = clip_distance.variable_found();
313 ir_variable *clip_distance_var =
314 shader->symbols->get_variable("gl_ClipDistance");
315 if (clip_distance_var)
316 prog->Vert.ClipDistanceArraySize = clip_distance_var->type->length;
317 }
318
319 return true;
320 }
321
322
323 /**
324 * Verify that a fragment shader executable meets all semantic requirements
325 *
326 * \param shader Fragment shader executable to be verified
327 */
328 bool
329 validate_fragment_shader_executable(struct gl_shader_program *prog,
330 struct gl_shader *shader)
331 {
332 if (shader == NULL)
333 return true;
334
335 find_assignment_visitor frag_color("gl_FragColor");
336 find_assignment_visitor frag_data("gl_FragData");
337
338 frag_color.run(shader->ir);
339 frag_data.run(shader->ir);
340
341 if (frag_color.variable_found() && frag_data.variable_found()) {
342 linker_error(prog, "fragment shader writes to both "
343 "`gl_FragColor' and `gl_FragData'\n");
344 return false;
345 }
346
347 return true;
348 }
349
350
351 /**
352 * Generate a string describing the mode of a variable
353 */
354 static const char *
355 mode_string(const ir_variable *var)
356 {
357 switch (var->mode) {
358 case ir_var_auto:
359 return (var->read_only) ? "global constant" : "global variable";
360
361 case ir_var_uniform: return "uniform";
362 case ir_var_in: return "shader input";
363 case ir_var_out: return "shader output";
364 case ir_var_inout: return "shader inout";
365
366 case ir_var_const_in:
367 case ir_var_temporary:
368 default:
369 assert(!"Should not get here.");
370 return "invalid variable";
371 }
372 }
373
374
375 /**
376 * Perform validation of global variables used across multiple shaders
377 */
378 bool
379 cross_validate_globals(struct gl_shader_program *prog,
380 struct gl_shader **shader_list,
381 unsigned num_shaders,
382 bool uniforms_only)
383 {
384 /* Examine all of the uniforms in all of the shaders and cross validate
385 * them.
386 */
387 glsl_symbol_table variables;
388 for (unsigned i = 0; i < num_shaders; i++) {
389 if (shader_list[i] == NULL)
390 continue;
391
392 foreach_list(node, shader_list[i]->ir) {
393 ir_variable *const var = ((ir_instruction *) node)->as_variable();
394
395 if (var == NULL)
396 continue;
397
398 if (uniforms_only && (var->mode != ir_var_uniform))
399 continue;
400
401 /* Don't cross validate temporaries that are at global scope. These
402 * will eventually get pulled into the shaders 'main'.
403 */
404 if (var->mode == ir_var_temporary)
405 continue;
406
407 /* If a global with this name has already been seen, verify that the
408 * new instance has the same type. In addition, if the globals have
409 * initializers, the values of the initializers must be the same.
410 */
411 ir_variable *const existing = variables.get_variable(var->name);
412 if (existing != NULL) {
413 if (var->type != existing->type) {
414 /* Consider the types to be "the same" if both types are arrays
415 * of the same type and one of the arrays is implicitly sized.
416 * In addition, set the type of the linked variable to the
417 * explicitly sized array.
418 */
419 if (var->type->is_array()
420 && existing->type->is_array()
421 && (var->type->fields.array == existing->type->fields.array)
422 && ((var->type->length == 0)
423 || (existing->type->length == 0))) {
424 if (var->type->length != 0) {
425 existing->type = var->type;
426 }
427 } else {
428 linker_error(prog, "%s `%s' declared as type "
429 "`%s' and type `%s'\n",
430 mode_string(var),
431 var->name, var->type->name,
432 existing->type->name);
433 return false;
434 }
435 }
436
437 if (var->explicit_location) {
438 if (existing->explicit_location
439 && (var->location != existing->location)) {
440 linker_error(prog, "explicit locations for %s "
441 "`%s' have differing values\n",
442 mode_string(var), var->name);
443 return false;
444 }
445
446 existing->location = var->location;
447 existing->explicit_location = true;
448 }
449
450 /* Validate layout qualifiers for gl_FragDepth.
451 *
452 * From the AMD/ARB_conservative_depth specs:
453 *
454 * "If gl_FragDepth is redeclared in any fragment shader in a
455 * program, it must be redeclared in all fragment shaders in
456 * that program that have static assignments to
457 * gl_FragDepth. All redeclarations of gl_FragDepth in all
458 * fragment shaders in a single program must have the same set
459 * of qualifiers."
460 */
461 if (strcmp(var->name, "gl_FragDepth") == 0) {
462 bool layout_declared = var->depth_layout != ir_depth_layout_none;
463 bool layout_differs =
464 var->depth_layout != existing->depth_layout;
465
466 if (layout_declared && layout_differs) {
467 linker_error(prog,
468 "All redeclarations of gl_FragDepth in all "
469 "fragment shaders in a single program must have "
470 "the same set of qualifiers.");
471 }
472
473 if (var->used && layout_differs) {
474 linker_error(prog,
475 "If gl_FragDepth is redeclared with a layout "
476 "qualifier in any fragment shader, it must be "
477 "redeclared with the same layout qualifier in "
478 "all fragment shaders that have assignments to "
479 "gl_FragDepth");
480 }
481 }
482
483 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
484 *
485 * "If a shared global has multiple initializers, the
486 * initializers must all be constant expressions, and they
487 * must all have the same value. Otherwise, a link error will
488 * result. (A shared global having only one initializer does
489 * not require that initializer to be a constant expression.)"
490 *
491 * Previous to 4.20 the GLSL spec simply said that initializers
492 * must have the same value. In this case of non-constant
493 * initializers, this was impossible to determine. As a result,
494 * no vendor actually implemented that behavior. The 4.20
495 * behavior matches the implemented behavior of at least one other
496 * vendor, so we'll implement that for all GLSL versions.
497 */
498 if (var->constant_initializer != NULL) {
499 if (existing->constant_initializer != NULL) {
500 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
501 linker_error(prog, "initializers for %s "
502 "`%s' have differing values\n",
503 mode_string(var), var->name);
504 return false;
505 }
506 } else {
507 /* If the first-seen instance of a particular uniform did not
508 * have an initializer but a later instance does, copy the
509 * initializer to the version stored in the symbol table.
510 */
511 /* FINISHME: This is wrong. The constant_value field should
512 * FINISHME: not be modified! Imagine a case where a shader
513 * FINISHME: without an initializer is linked in two different
514 * FINISHME: programs with shaders that have differing
515 * FINISHME: initializers. Linking with the first will
516 * FINISHME: modify the shader, and linking with the second
517 * FINISHME: will fail.
518 */
519 existing->constant_initializer =
520 var->constant_initializer->clone(ralloc_parent(existing),
521 NULL);
522 }
523 }
524
525 if (var->has_initializer) {
526 if (existing->has_initializer
527 && (var->constant_initializer == NULL
528 || existing->constant_initializer == NULL)) {
529 linker_error(prog,
530 "shared global variable `%s' has multiple "
531 "non-constant initializers.\n",
532 var->name);
533 return false;
534 }
535
536 /* Some instance had an initializer, so keep track of that. In
537 * this location, all sorts of initializers (constant or
538 * otherwise) will propagate the existence to the variable
539 * stored in the symbol table.
540 */
541 existing->has_initializer = true;
542 }
543
544 if (existing->invariant != var->invariant) {
545 linker_error(prog, "declarations for %s `%s' have "
546 "mismatching invariant qualifiers\n",
547 mode_string(var), var->name);
548 return false;
549 }
550 if (existing->centroid != var->centroid) {
551 linker_error(prog, "declarations for %s `%s' have "
552 "mismatching centroid qualifiers\n",
553 mode_string(var), var->name);
554 return false;
555 }
556 } else
557 variables.add_variable(var);
558 }
559 }
560
561 return true;
562 }
563
564
565 /**
566 * Perform validation of uniforms used across multiple shader stages
567 */
568 bool
569 cross_validate_uniforms(struct gl_shader_program *prog)
570 {
571 return cross_validate_globals(prog, prog->_LinkedShaders,
572 MESA_SHADER_TYPES, true);
573 }
574
575
576 /**
577 * Validate that outputs from one stage match inputs of another
578 */
579 bool
580 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
581 gl_shader *producer, gl_shader *consumer)
582 {
583 glsl_symbol_table parameters;
584 /* FINISHME: Figure these out dynamically. */
585 const char *const producer_stage = "vertex";
586 const char *const consumer_stage = "fragment";
587
588 /* Find all shader outputs in the "producer" stage.
589 */
590 foreach_list(node, producer->ir) {
591 ir_variable *const var = ((ir_instruction *) node)->as_variable();
592
593 /* FINISHME: For geometry shaders, this should also look for inout
594 * FINISHME: variables.
595 */
596 if ((var == NULL) || (var->mode != ir_var_out))
597 continue;
598
599 parameters.add_variable(var);
600 }
601
602
603 /* Find all shader inputs in the "consumer" stage. Any variables that have
604 * matching outputs already in the symbol table must have the same type and
605 * qualifiers.
606 */
607 foreach_list(node, consumer->ir) {
608 ir_variable *const input = ((ir_instruction *) node)->as_variable();
609
610 /* FINISHME: For geometry shaders, this should also look for inout
611 * FINISHME: variables.
612 */
613 if ((input == NULL) || (input->mode != ir_var_in))
614 continue;
615
616 ir_variable *const output = parameters.get_variable(input->name);
617 if (output != NULL) {
618 /* Check that the types match between stages.
619 */
620 if (input->type != output->type) {
621 /* There is a bit of a special case for gl_TexCoord. This
622 * built-in is unsized by default. Applications that variable
623 * access it must redeclare it with a size. There is some
624 * language in the GLSL spec that implies the fragment shader
625 * and vertex shader do not have to agree on this size. Other
626 * driver behave this way, and one or two applications seem to
627 * rely on it.
628 *
629 * Neither declaration needs to be modified here because the array
630 * sizes are fixed later when update_array_sizes is called.
631 *
632 * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
633 *
634 * "Unlike user-defined varying variables, the built-in
635 * varying variables don't have a strict one-to-one
636 * correspondence between the vertex language and the
637 * fragment language."
638 */
639 if (!output->type->is_array()
640 || (strncmp("gl_", output->name, 3) != 0)) {
641 linker_error(prog,
642 "%s shader output `%s' declared as type `%s', "
643 "but %s shader input declared as type `%s'\n",
644 producer_stage, output->name,
645 output->type->name,
646 consumer_stage, input->type->name);
647 return false;
648 }
649 }
650
651 /* Check that all of the qualifiers match between stages.
652 */
653 if (input->centroid != output->centroid) {
654 linker_error(prog,
655 "%s shader output `%s' %s centroid qualifier, "
656 "but %s shader input %s centroid qualifier\n",
657 producer_stage,
658 output->name,
659 (output->centroid) ? "has" : "lacks",
660 consumer_stage,
661 (input->centroid) ? "has" : "lacks");
662 return false;
663 }
664
665 if (input->invariant != output->invariant) {
666 linker_error(prog,
667 "%s shader output `%s' %s invariant qualifier, "
668 "but %s shader input %s invariant qualifier\n",
669 producer_stage,
670 output->name,
671 (output->invariant) ? "has" : "lacks",
672 consumer_stage,
673 (input->invariant) ? "has" : "lacks");
674 return false;
675 }
676
677 if (input->interpolation != output->interpolation) {
678 linker_error(prog,
679 "%s shader output `%s' specifies %s "
680 "interpolation qualifier, "
681 "but %s shader input specifies %s "
682 "interpolation qualifier\n",
683 producer_stage,
684 output->name,
685 output->interpolation_string(),
686 consumer_stage,
687 input->interpolation_string());
688 return false;
689 }
690 }
691 }
692
693 return true;
694 }
695
696
697 /**
698 * Populates a shaders symbol table with all global declarations
699 */
700 static void
701 populate_symbol_table(gl_shader *sh)
702 {
703 sh->symbols = new(sh) glsl_symbol_table;
704
705 foreach_list(node, sh->ir) {
706 ir_instruction *const inst = (ir_instruction *) node;
707 ir_variable *var;
708 ir_function *func;
709
710 if ((func = inst->as_function()) != NULL) {
711 sh->symbols->add_function(func);
712 } else if ((var = inst->as_variable()) != NULL) {
713 sh->symbols->add_variable(var);
714 }
715 }
716 }
717
718
719 /**
720 * Remap variables referenced in an instruction tree
721 *
722 * This is used when instruction trees are cloned from one shader and placed in
723 * another. These trees will contain references to \c ir_variable nodes that
724 * do not exist in the target shader. This function finds these \c ir_variable
725 * references and replaces the references with matching variables in the target
726 * shader.
727 *
728 * If there is no matching variable in the target shader, a clone of the
729 * \c ir_variable is made and added to the target shader. The new variable is
730 * added to \b both the instruction stream and the symbol table.
731 *
732 * \param inst IR tree that is to be processed.
733 * \param symbols Symbol table containing global scope symbols in the
734 * linked shader.
735 * \param instructions Instruction stream where new variable declarations
736 * should be added.
737 */
738 void
739 remap_variables(ir_instruction *inst, struct gl_shader *target,
740 hash_table *temps)
741 {
742 class remap_visitor : public ir_hierarchical_visitor {
743 public:
744 remap_visitor(struct gl_shader *target,
745 hash_table *temps)
746 {
747 this->target = target;
748 this->symbols = target->symbols;
749 this->instructions = target->ir;
750 this->temps = temps;
751 }
752
753 virtual ir_visitor_status visit(ir_dereference_variable *ir)
754 {
755 if (ir->var->mode == ir_var_temporary) {
756 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
757
758 assert(var != NULL);
759 ir->var = var;
760 return visit_continue;
761 }
762
763 ir_variable *const existing =
764 this->symbols->get_variable(ir->var->name);
765 if (existing != NULL)
766 ir->var = existing;
767 else {
768 ir_variable *copy = ir->var->clone(this->target, NULL);
769
770 this->symbols->add_variable(copy);
771 this->instructions->push_head(copy);
772 ir->var = copy;
773 }
774
775 return visit_continue;
776 }
777
778 private:
779 struct gl_shader *target;
780 glsl_symbol_table *symbols;
781 exec_list *instructions;
782 hash_table *temps;
783 };
784
785 remap_visitor v(target, temps);
786
787 inst->accept(&v);
788 }
789
790
791 /**
792 * Move non-declarations from one instruction stream to another
793 *
794 * The intended usage pattern of this function is to pass the pointer to the
795 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
796 * pointer) for \c last and \c false for \c make_copies on the first
797 * call. Successive calls pass the return value of the previous call for
798 * \c last and \c true for \c make_copies.
799 *
800 * \param instructions Source instruction stream
801 * \param last Instruction after which new instructions should be
802 * inserted in the target instruction stream
803 * \param make_copies Flag selecting whether instructions in \c instructions
804 * should be copied (via \c ir_instruction::clone) into the
805 * target list or moved.
806 *
807 * \return
808 * The new "last" instruction in the target instruction stream. This pointer
809 * is suitable for use as the \c last parameter of a later call to this
810 * function.
811 */
812 exec_node *
813 move_non_declarations(exec_list *instructions, exec_node *last,
814 bool make_copies, gl_shader *target)
815 {
816 hash_table *temps = NULL;
817
818 if (make_copies)
819 temps = hash_table_ctor(0, hash_table_pointer_hash,
820 hash_table_pointer_compare);
821
822 foreach_list_safe(node, instructions) {
823 ir_instruction *inst = (ir_instruction *) node;
824
825 if (inst->as_function())
826 continue;
827
828 ir_variable *var = inst->as_variable();
829 if ((var != NULL) && (var->mode != ir_var_temporary))
830 continue;
831
832 assert(inst->as_assignment()
833 || ((var != NULL) && (var->mode == ir_var_temporary)));
834
835 if (make_copies) {
836 inst = inst->clone(target, NULL);
837
838 if (var != NULL)
839 hash_table_insert(temps, inst, var);
840 else
841 remap_variables(inst, target, temps);
842 } else {
843 inst->remove();
844 }
845
846 last->insert_after(inst);
847 last = inst;
848 }
849
850 if (make_copies)
851 hash_table_dtor(temps);
852
853 return last;
854 }
855
856 /**
857 * Get the function signature for main from a shader
858 */
859 static ir_function_signature *
860 get_main_function_signature(gl_shader *sh)
861 {
862 ir_function *const f = sh->symbols->get_function("main");
863 if (f != NULL) {
864 exec_list void_parameters;
865
866 /* Look for the 'void main()' signature and ensure that it's defined.
867 * This keeps the linker from accidentally pick a shader that just
868 * contains a prototype for main.
869 *
870 * We don't have to check for multiple definitions of main (in multiple
871 * shaders) because that would have already been caught above.
872 */
873 ir_function_signature *sig = f->matching_signature(&void_parameters);
874 if ((sig != NULL) && sig->is_defined) {
875 return sig;
876 }
877 }
878
879 return NULL;
880 }
881
882
883 /**
884 * This class is only used in link_intrastage_shaders() below but declaring
885 * it inside that function leads to compiler warnings with some versions of
886 * gcc.
887 */
888 class array_sizing_visitor : public ir_hierarchical_visitor {
889 public:
890 virtual ir_visitor_status visit(ir_variable *var)
891 {
892 if (var->type->is_array() && (var->type->length == 0)) {
893 const glsl_type *type =
894 glsl_type::get_array_instance(var->type->fields.array,
895 var->max_array_access + 1);
896 assert(type != NULL);
897 var->type = type;
898 }
899 return visit_continue;
900 }
901 };
902
903
904 /**
905 * Combine a group of shaders for a single stage to generate a linked shader
906 *
907 * \note
908 * If this function is supplied a single shader, it is cloned, and the new
909 * shader is returned.
910 */
911 static struct gl_shader *
912 link_intrastage_shaders(void *mem_ctx,
913 struct gl_context *ctx,
914 struct gl_shader_program *prog,
915 struct gl_shader **shader_list,
916 unsigned num_shaders)
917 {
918 /* Check that global variables defined in multiple shaders are consistent.
919 */
920 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
921 return NULL;
922
923 /* Check that there is only a single definition of each function signature
924 * across all shaders.
925 */
926 for (unsigned i = 0; i < (num_shaders - 1); i++) {
927 foreach_list(node, shader_list[i]->ir) {
928 ir_function *const f = ((ir_instruction *) node)->as_function();
929
930 if (f == NULL)
931 continue;
932
933 for (unsigned j = i + 1; j < num_shaders; j++) {
934 ir_function *const other =
935 shader_list[j]->symbols->get_function(f->name);
936
937 /* If the other shader has no function (and therefore no function
938 * signatures) with the same name, skip to the next shader.
939 */
940 if (other == NULL)
941 continue;
942
943 foreach_iter (exec_list_iterator, iter, *f) {
944 ir_function_signature *sig =
945 (ir_function_signature *) iter.get();
946
947 if (!sig->is_defined || sig->is_builtin)
948 continue;
949
950 ir_function_signature *other_sig =
951 other->exact_matching_signature(& sig->parameters);
952
953 if ((other_sig != NULL) && other_sig->is_defined
954 && !other_sig->is_builtin) {
955 linker_error(prog, "function `%s' is multiply defined",
956 f->name);
957 return NULL;
958 }
959 }
960 }
961 }
962 }
963
964 /* Find the shader that defines main, and make a clone of it.
965 *
966 * Starting with the clone, search for undefined references. If one is
967 * found, find the shader that defines it. Clone the reference and add
968 * it to the shader. Repeat until there are no undefined references or
969 * until a reference cannot be resolved.
970 */
971 gl_shader *main = NULL;
972 for (unsigned i = 0; i < num_shaders; i++) {
973 if (get_main_function_signature(shader_list[i]) != NULL) {
974 main = shader_list[i];
975 break;
976 }
977 }
978
979 if (main == NULL) {
980 linker_error(prog, "%s shader lacks `main'\n",
981 (shader_list[0]->Type == GL_VERTEX_SHADER)
982 ? "vertex" : "fragment");
983 return NULL;
984 }
985
986 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
987 linked->ir = new(linked) exec_list;
988 clone_ir_list(mem_ctx, linked->ir, main->ir);
989
990 populate_symbol_table(linked);
991
992 /* The a pointer to the main function in the final linked shader (i.e., the
993 * copy of the original shader that contained the main function).
994 */
995 ir_function_signature *const main_sig = get_main_function_signature(linked);
996
997 /* Move any instructions other than variable declarations or function
998 * declarations into main.
999 */
1000 exec_node *insertion_point =
1001 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
1002 linked);
1003
1004 for (unsigned i = 0; i < num_shaders; i++) {
1005 if (shader_list[i] == main)
1006 continue;
1007
1008 insertion_point = move_non_declarations(shader_list[i]->ir,
1009 insertion_point, true, linked);
1010 }
1011
1012 /* Resolve initializers for global variables in the linked shader.
1013 */
1014 unsigned num_linking_shaders = num_shaders;
1015 for (unsigned i = 0; i < num_shaders; i++)
1016 num_linking_shaders += shader_list[i]->num_builtins_to_link;
1017
1018 gl_shader **linking_shaders =
1019 (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
1020
1021 memcpy(linking_shaders, shader_list,
1022 sizeof(linking_shaders[0]) * num_shaders);
1023
1024 unsigned idx = num_shaders;
1025 for (unsigned i = 0; i < num_shaders; i++) {
1026 memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
1027 sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
1028 idx += shader_list[i]->num_builtins_to_link;
1029 }
1030
1031 assert(idx == num_linking_shaders);
1032
1033 if (!link_function_calls(prog, linked, linking_shaders,
1034 num_linking_shaders)) {
1035 ctx->Driver.DeleteShader(ctx, linked);
1036 linked = NULL;
1037 }
1038
1039 free(linking_shaders);
1040
1041 #ifdef DEBUG
1042 /* At this point linked should contain all of the linked IR, so
1043 * validate it to make sure nothing went wrong.
1044 */
1045 if (linked)
1046 validate_ir_tree(linked->ir);
1047 #endif
1048
1049 /* Make a pass over all variable declarations to ensure that arrays with
1050 * unspecified sizes have a size specified. The size is inferred from the
1051 * max_array_access field.
1052 */
1053 if (linked != NULL) {
1054 array_sizing_visitor v;
1055
1056 v.run(linked->ir);
1057 }
1058
1059 return linked;
1060 }
1061
1062 /**
1063 * Update the sizes of linked shader uniform arrays to the maximum
1064 * array index used.
1065 *
1066 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1067 *
1068 * If one or more elements of an array are active,
1069 * GetActiveUniform will return the name of the array in name,
1070 * subject to the restrictions listed above. The type of the array
1071 * is returned in type. The size parameter contains the highest
1072 * array element index used, plus one. The compiler or linker
1073 * determines the highest index used. There will be only one
1074 * active uniform reported by the GL per uniform array.
1075
1076 */
1077 static void
1078 update_array_sizes(struct gl_shader_program *prog)
1079 {
1080 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1081 if (prog->_LinkedShaders[i] == NULL)
1082 continue;
1083
1084 foreach_list(node, prog->_LinkedShaders[i]->ir) {
1085 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1086
1087 if ((var == NULL) || (var->mode != ir_var_uniform &&
1088 var->mode != ir_var_in &&
1089 var->mode != ir_var_out) ||
1090 !var->type->is_array())
1091 continue;
1092
1093 unsigned int size = var->max_array_access;
1094 for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
1095 if (prog->_LinkedShaders[j] == NULL)
1096 continue;
1097
1098 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
1099 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
1100 if (!other_var)
1101 continue;
1102
1103 if (strcmp(var->name, other_var->name) == 0 &&
1104 other_var->max_array_access > size) {
1105 size = other_var->max_array_access;
1106 }
1107 }
1108 }
1109
1110 if (size + 1 != var->type->fields.array->length) {
1111 /* If this is a built-in uniform (i.e., it's backed by some
1112 * fixed-function state), adjust the number of state slots to
1113 * match the new array size. The number of slots per array entry
1114 * is not known. It seems safe to assume that the total number of
1115 * slots is an integer multiple of the number of array elements.
1116 * Determine the number of slots per array element by dividing by
1117 * the old (total) size.
1118 */
1119 if (var->num_state_slots > 0) {
1120 var->num_state_slots = (size + 1)
1121 * (var->num_state_slots / var->type->length);
1122 }
1123
1124 var->type = glsl_type::get_array_instance(var->type->fields.array,
1125 size + 1);
1126 /* FINISHME: We should update the types of array
1127 * dereferences of this variable now.
1128 */
1129 }
1130 }
1131 }
1132 }
1133
1134 /**
1135 * Find a contiguous set of available bits in a bitmask.
1136 *
1137 * \param used_mask Bits representing used (1) and unused (0) locations
1138 * \param needed_count Number of contiguous bits needed.
1139 *
1140 * \return
1141 * Base location of the available bits on success or -1 on failure.
1142 */
1143 int
1144 find_available_slots(unsigned used_mask, unsigned needed_count)
1145 {
1146 unsigned needed_mask = (1 << needed_count) - 1;
1147 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1148
1149 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1150 * cannot optimize possibly infinite loops" for the loop below.
1151 */
1152 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1153 return -1;
1154
1155 for (int i = 0; i <= max_bit_to_test; i++) {
1156 if ((needed_mask & ~used_mask) == needed_mask)
1157 return i;
1158
1159 needed_mask <<= 1;
1160 }
1161
1162 return -1;
1163 }
1164
1165
1166 /**
1167 * Assign locations for either VS inputs for FS outputs
1168 *
1169 * \param prog Shader program whose variables need locations assigned
1170 * \param target_index Selector for the program target to receive location
1171 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1172 * \c MESA_SHADER_FRAGMENT.
1173 * \param max_index Maximum number of generic locations. This corresponds
1174 * to either the maximum number of draw buffers or the
1175 * maximum number of generic attributes.
1176 *
1177 * \return
1178 * If locations are successfully assigned, true is returned. Otherwise an
1179 * error is emitted to the shader link log and false is returned.
1180 */
1181 bool
1182 assign_attribute_or_color_locations(gl_shader_program *prog,
1183 unsigned target_index,
1184 unsigned max_index)
1185 {
1186 /* Mark invalid locations as being used.
1187 */
1188 unsigned used_locations = (max_index >= 32)
1189 ? ~0 : ~((1 << max_index) - 1);
1190
1191 assert((target_index == MESA_SHADER_VERTEX)
1192 || (target_index == MESA_SHADER_FRAGMENT));
1193
1194 gl_shader *const sh = prog->_LinkedShaders[target_index];
1195 if (sh == NULL)
1196 return true;
1197
1198 /* Operate in a total of four passes.
1199 *
1200 * 1. Invalidate the location assignments for all vertex shader inputs.
1201 *
1202 * 2. Assign locations for inputs that have user-defined (via
1203 * glBindVertexAttribLocation) locations and outputs that have
1204 * user-defined locations (via glBindFragDataLocation).
1205 *
1206 * 3. Sort the attributes without assigned locations by number of slots
1207 * required in decreasing order. Fragmentation caused by attribute
1208 * locations assigned by the application may prevent large attributes
1209 * from having enough contiguous space.
1210 *
1211 * 4. Assign locations to any inputs without assigned locations.
1212 */
1213
1214 const int generic_base = (target_index == MESA_SHADER_VERTEX)
1215 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
1216
1217 const enum ir_variable_mode direction =
1218 (target_index == MESA_SHADER_VERTEX) ? ir_var_in : ir_var_out;
1219
1220
1221 link_invalidate_variable_locations(sh, direction, generic_base);
1222
1223 /* Temporary storage for the set of attributes that need locations assigned.
1224 */
1225 struct temp_attr {
1226 unsigned slots;
1227 ir_variable *var;
1228
1229 /* Used below in the call to qsort. */
1230 static int compare(const void *a, const void *b)
1231 {
1232 const temp_attr *const l = (const temp_attr *) a;
1233 const temp_attr *const r = (const temp_attr *) b;
1234
1235 /* Reversed because we want a descending order sort below. */
1236 return r->slots - l->slots;
1237 }
1238 } to_assign[16];
1239
1240 unsigned num_attr = 0;
1241
1242 foreach_list(node, sh->ir) {
1243 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1244
1245 if ((var == NULL) || (var->mode != (unsigned) direction))
1246 continue;
1247
1248 if (var->explicit_location) {
1249 if ((var->location >= (int)(max_index + generic_base))
1250 || (var->location < 0)) {
1251 linker_error(prog,
1252 "invalid explicit location %d specified for `%s'\n",
1253 (var->location < 0)
1254 ? var->location : var->location - generic_base,
1255 var->name);
1256 return false;
1257 }
1258 } else if (target_index == MESA_SHADER_VERTEX) {
1259 unsigned binding;
1260
1261 if (prog->AttributeBindings->get(binding, var->name)) {
1262 assert(binding >= VERT_ATTRIB_GENERIC0);
1263 var->location = binding;
1264 }
1265 } else if (target_index == MESA_SHADER_FRAGMENT) {
1266 unsigned binding;
1267
1268 if (prog->FragDataBindings->get(binding, var->name)) {
1269 assert(binding >= FRAG_RESULT_DATA0);
1270 var->location = binding;
1271 }
1272 }
1273
1274 /* If the variable is not a built-in and has a location statically
1275 * assigned in the shader (presumably via a layout qualifier), make sure
1276 * that it doesn't collide with other assigned locations. Otherwise,
1277 * add it to the list of variables that need linker-assigned locations.
1278 */
1279 const unsigned slots = count_attribute_slots(var->type);
1280 if (var->location != -1) {
1281 if (var->location >= generic_base) {
1282 /* From page 61 of the OpenGL 4.0 spec:
1283 *
1284 * "LinkProgram will fail if the attribute bindings assigned
1285 * by BindAttribLocation do not leave not enough space to
1286 * assign a location for an active matrix attribute or an
1287 * active attribute array, both of which require multiple
1288 * contiguous generic attributes."
1289 *
1290 * Previous versions of the spec contain similar language but omit
1291 * the bit about attribute arrays.
1292 *
1293 * Page 61 of the OpenGL 4.0 spec also says:
1294 *
1295 * "It is possible for an application to bind more than one
1296 * attribute name to the same location. This is referred to as
1297 * aliasing. This will only work if only one of the aliased
1298 * attributes is active in the executable program, or if no
1299 * path through the shader consumes more than one attribute of
1300 * a set of attributes aliased to the same location. A link
1301 * error can occur if the linker determines that every path
1302 * through the shader consumes multiple aliased attributes,
1303 * but implementations are not required to generate an error
1304 * in this case."
1305 *
1306 * These two paragraphs are either somewhat contradictory, or I
1307 * don't fully understand one or both of them.
1308 */
1309 /* FINISHME: The code as currently written does not support
1310 * FINISHME: attribute location aliasing (see comment above).
1311 */
1312 /* Mask representing the contiguous slots that will be used by
1313 * this attribute.
1314 */
1315 const unsigned attr = var->location - generic_base;
1316 const unsigned use_mask = (1 << slots) - 1;
1317
1318 /* Generate a link error if the set of bits requested for this
1319 * attribute overlaps any previously allocated bits.
1320 */
1321 if ((~(use_mask << attr) & used_locations) != used_locations) {
1322 const char *const string = (target_index == MESA_SHADER_VERTEX)
1323 ? "vertex shader input" : "fragment shader output";
1324 linker_error(prog,
1325 "insufficient contiguous locations "
1326 "available for %s `%s'", string,
1327 var->name);
1328 return false;
1329 }
1330
1331 used_locations |= (use_mask << attr);
1332 }
1333
1334 continue;
1335 }
1336
1337 to_assign[num_attr].slots = slots;
1338 to_assign[num_attr].var = var;
1339 num_attr++;
1340 }
1341
1342 /* If all of the attributes were assigned locations by the application (or
1343 * are built-in attributes with fixed locations), return early. This should
1344 * be the common case.
1345 */
1346 if (num_attr == 0)
1347 return true;
1348
1349 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1350
1351 if (target_index == MESA_SHADER_VERTEX) {
1352 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1353 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1354 * reserved to prevent it from being automatically allocated below.
1355 */
1356 find_deref_visitor find("gl_Vertex");
1357 find.run(sh->ir);
1358 if (find.variable_found())
1359 used_locations |= (1 << 0);
1360 }
1361
1362 for (unsigned i = 0; i < num_attr; i++) {
1363 /* Mask representing the contiguous slots that will be used by this
1364 * attribute.
1365 */
1366 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1367
1368 int location = find_available_slots(used_locations, to_assign[i].slots);
1369
1370 if (location < 0) {
1371 const char *const string = (target_index == MESA_SHADER_VERTEX)
1372 ? "vertex shader input" : "fragment shader output";
1373
1374 linker_error(prog,
1375 "insufficient contiguous locations "
1376 "available for %s `%s'",
1377 string, to_assign[i].var->name);
1378 return false;
1379 }
1380
1381 to_assign[i].var->location = generic_base + location;
1382 used_locations |= (use_mask << location);
1383 }
1384
1385 return true;
1386 }
1387
1388
1389 /**
1390 * Demote shader inputs and outputs that are not used in other stages
1391 */
1392 void
1393 demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
1394 {
1395 foreach_list(node, sh->ir) {
1396 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1397
1398 if ((var == NULL) || (var->mode != int(mode)))
1399 continue;
1400
1401 /* A shader 'in' or 'out' variable is only really an input or output if
1402 * its value is used by other shader stages. This will cause the variable
1403 * to have a location assigned.
1404 */
1405 if (var->location == -1) {
1406 var->mode = ir_var_auto;
1407 }
1408 }
1409 }
1410
1411
1412 /**
1413 * Data structure tracking information about a transform feedback declaration
1414 * during linking.
1415 */
1416 class tfeedback_decl
1417 {
1418 public:
1419 bool init(struct gl_context *ctx, struct gl_shader_program *prog,
1420 const void *mem_ctx, const char *input);
1421 static bool is_same(const tfeedback_decl &x, const tfeedback_decl &y);
1422 bool assign_location(struct gl_context *ctx, struct gl_shader_program *prog,
1423 ir_variable *output_var);
1424 bool accumulate_num_outputs(struct gl_shader_program *prog, unsigned *count);
1425 bool store(struct gl_context *ctx, struct gl_shader_program *prog,
1426 struct gl_transform_feedback_info *info, unsigned buffer,
1427 unsigned varying, const unsigned max_outputs) const;
1428
1429
1430 /**
1431 * True if assign_location() has been called for this object.
1432 */
1433 bool is_assigned() const
1434 {
1435 return this->location != -1;
1436 }
1437
1438 /**
1439 * Determine whether this object refers to the variable var.
1440 */
1441 bool matches_var(ir_variable *var) const
1442 {
1443 if (this->is_clip_distance_mesa)
1444 return strcmp(var->name, "gl_ClipDistanceMESA") == 0;
1445 else
1446 return strcmp(var->name, this->var_name) == 0;
1447 }
1448
1449 /**
1450 * The total number of varying components taken up by this variable. Only
1451 * valid if is_assigned() is true.
1452 */
1453 unsigned num_components() const
1454 {
1455 if (this->is_clip_distance_mesa)
1456 return this->size;
1457 else
1458 return this->vector_elements * this->matrix_columns * this->size;
1459 }
1460
1461 private:
1462 /**
1463 * The name that was supplied to glTransformFeedbackVaryings. Used for
1464 * error reporting and glGetTransformFeedbackVarying().
1465 */
1466 const char *orig_name;
1467
1468 /**
1469 * The name of the variable, parsed from orig_name.
1470 */
1471 const char *var_name;
1472
1473 /**
1474 * True if the declaration in orig_name represents an array.
1475 */
1476 bool is_subscripted;
1477
1478 /**
1479 * If is_subscripted is true, the subscript that was specified in orig_name.
1480 */
1481 unsigned array_subscript;
1482
1483 /**
1484 * True if the variable is gl_ClipDistance and the driver lowers
1485 * gl_ClipDistance to gl_ClipDistanceMESA.
1486 */
1487 bool is_clip_distance_mesa;
1488
1489 /**
1490 * The vertex shader output location that the linker assigned for this
1491 * variable. -1 if a location hasn't been assigned yet.
1492 */
1493 int location;
1494
1495 /**
1496 * If location != -1, the number of vector elements in this variable, or 1
1497 * if this variable is a scalar.
1498 */
1499 unsigned vector_elements;
1500
1501 /**
1502 * If location != -1, the number of matrix columns in this variable, or 1
1503 * if this variable is not a matrix.
1504 */
1505 unsigned matrix_columns;
1506
1507 /** Type of the varying returned by glGetTransformFeedbackVarying() */
1508 GLenum type;
1509
1510 /**
1511 * If location != -1, the size that should be returned by
1512 * glGetTransformFeedbackVarying().
1513 */
1514 unsigned size;
1515 };
1516
1517
1518 /**
1519 * Initialize this object based on a string that was passed to
1520 * glTransformFeedbackVaryings. If there is a parse error, the error is
1521 * reported using linker_error(), and false is returned.
1522 */
1523 bool
1524 tfeedback_decl::init(struct gl_context *ctx, struct gl_shader_program *prog,
1525 const void *mem_ctx, const char *input)
1526 {
1527 /* We don't have to be pedantic about what is a valid GLSL variable name,
1528 * because any variable with an invalid name can't exist in the IR anyway.
1529 */
1530
1531 this->location = -1;
1532 this->orig_name = input;
1533 this->is_clip_distance_mesa = false;
1534
1535 const char *bracket = strrchr(input, '[');
1536
1537 if (bracket) {
1538 this->var_name = ralloc_strndup(mem_ctx, input, bracket - input);
1539 if (sscanf(bracket, "[%u]", &this->array_subscript) != 1) {
1540 linker_error(prog, "Cannot parse transform feedback varying %s", input);
1541 return false;
1542 }
1543 this->is_subscripted = true;
1544 } else {
1545 this->var_name = ralloc_strdup(mem_ctx, input);
1546 this->is_subscripted = false;
1547 }
1548
1549 /* For drivers that lower gl_ClipDistance to gl_ClipDistanceMESA, this
1550 * class must behave specially to account for the fact that gl_ClipDistance
1551 * is converted from a float[8] to a vec4[2].
1552 */
1553 if (ctx->ShaderCompilerOptions[MESA_SHADER_VERTEX].LowerClipDistance &&
1554 strcmp(this->var_name, "gl_ClipDistance") == 0) {
1555 this->is_clip_distance_mesa = true;
1556 }
1557
1558 return true;
1559 }
1560
1561
1562 /**
1563 * Determine whether two tfeedback_decl objects refer to the same variable and
1564 * array index (if applicable).
1565 */
1566 bool
1567 tfeedback_decl::is_same(const tfeedback_decl &x, const tfeedback_decl &y)
1568 {
1569 if (strcmp(x.var_name, y.var_name) != 0)
1570 return false;
1571 if (x.is_subscripted != y.is_subscripted)
1572 return false;
1573 if (x.is_subscripted && x.array_subscript != y.array_subscript)
1574 return false;
1575 return true;
1576 }
1577
1578
1579 /**
1580 * Assign a location for this tfeedback_decl object based on the location
1581 * assignment in output_var.
1582 *
1583 * If an error occurs, the error is reported through linker_error() and false
1584 * is returned.
1585 */
1586 bool
1587 tfeedback_decl::assign_location(struct gl_context *ctx,
1588 struct gl_shader_program *prog,
1589 ir_variable *output_var)
1590 {
1591 if (output_var->type->is_array()) {
1592 /* Array variable */
1593 const unsigned matrix_cols =
1594 output_var->type->fields.array->matrix_columns;
1595 unsigned actual_array_size = this->is_clip_distance_mesa ?
1596 prog->Vert.ClipDistanceArraySize : output_var->type->array_size();
1597
1598 if (this->is_subscripted) {
1599 /* Check array bounds. */
1600 if (this->array_subscript >= actual_array_size) {
1601 linker_error(prog, "Transform feedback varying %s has index "
1602 "%i, but the array size is %u.",
1603 this->orig_name, this->array_subscript,
1604 actual_array_size);
1605 return false;
1606 }
1607 if (this->is_clip_distance_mesa) {
1608 this->location =
1609 output_var->location + this->array_subscript / 4;
1610 } else {
1611 this->location =
1612 output_var->location + this->array_subscript * matrix_cols;
1613 }
1614 this->size = 1;
1615 } else {
1616 this->location = output_var->location;
1617 this->size = actual_array_size;
1618 }
1619 this->vector_elements = output_var->type->fields.array->vector_elements;
1620 this->matrix_columns = matrix_cols;
1621 if (this->is_clip_distance_mesa)
1622 this->type = GL_FLOAT;
1623 else
1624 this->type = output_var->type->fields.array->gl_type;
1625 } else {
1626 /* Regular variable (scalar, vector, or matrix) */
1627 if (this->is_subscripted) {
1628 linker_error(prog, "Transform feedback varying %s requested, "
1629 "but %s is not an array.",
1630 this->orig_name, this->var_name);
1631 return false;
1632 }
1633 this->location = output_var->location;
1634 this->size = 1;
1635 this->vector_elements = output_var->type->vector_elements;
1636 this->matrix_columns = output_var->type->matrix_columns;
1637 this->type = output_var->type->gl_type;
1638 }
1639
1640 /* From GL_EXT_transform_feedback:
1641 * A program will fail to link if:
1642 *
1643 * * the total number of components to capture in any varying
1644 * variable in <varyings> is greater than the constant
1645 * MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT and the
1646 * buffer mode is SEPARATE_ATTRIBS_EXT;
1647 */
1648 if (prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS &&
1649 this->num_components() >
1650 ctx->Const.MaxTransformFeedbackSeparateComponents) {
1651 linker_error(prog, "Transform feedback varying %s exceeds "
1652 "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS.",
1653 this->orig_name);
1654 return false;
1655 }
1656
1657 return true;
1658 }
1659
1660
1661 bool
1662 tfeedback_decl::accumulate_num_outputs(struct gl_shader_program *prog,
1663 unsigned *count)
1664 {
1665 if (!this->is_assigned()) {
1666 /* From GL_EXT_transform_feedback:
1667 * A program will fail to link if:
1668 *
1669 * * any variable name specified in the <varyings> array is not
1670 * declared as an output in the geometry shader (if present) or
1671 * the vertex shader (if no geometry shader is present);
1672 */
1673 linker_error(prog, "Transform feedback varying %s undeclared.",
1674 this->orig_name);
1675 return false;
1676 }
1677
1678 unsigned translated_size = this->size;
1679 if (this->is_clip_distance_mesa)
1680 translated_size = (translated_size + 3) / 4;
1681
1682 *count += translated_size * this->matrix_columns;
1683
1684 return true;
1685 }
1686
1687
1688 /**
1689 * Update gl_transform_feedback_info to reflect this tfeedback_decl.
1690 *
1691 * If an error occurs, the error is reported through linker_error() and false
1692 * is returned.
1693 */
1694 bool
1695 tfeedback_decl::store(struct gl_context *ctx, struct gl_shader_program *prog,
1696 struct gl_transform_feedback_info *info,
1697 unsigned buffer,
1698 unsigned varying, const unsigned max_outputs) const
1699 {
1700 /* From GL_EXT_transform_feedback:
1701 * A program will fail to link if:
1702 *
1703 * * the total number of components to capture is greater than
1704 * the constant MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT
1705 * and the buffer mode is INTERLEAVED_ATTRIBS_EXT.
1706 */
1707 if (prog->TransformFeedback.BufferMode == GL_INTERLEAVED_ATTRIBS &&
1708 info->BufferStride[buffer] + this->num_components() >
1709 ctx->Const.MaxTransformFeedbackInterleavedComponents) {
1710 linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1711 "limit has been exceeded.");
1712 return false;
1713 }
1714
1715 unsigned translated_size = this->size;
1716 if (this->is_clip_distance_mesa)
1717 translated_size = (translated_size + 3) / 4;
1718 unsigned components_so_far = 0;
1719 for (unsigned index = 0; index < translated_size; ++index) {
1720 for (unsigned v = 0; v < this->matrix_columns; ++v) {
1721 unsigned num_components = this->vector_elements;
1722 assert(info->NumOutputs < max_outputs);
1723 info->Outputs[info->NumOutputs].ComponentOffset = 0;
1724 if (this->is_clip_distance_mesa) {
1725 if (this->is_subscripted) {
1726 num_components = 1;
1727 info->Outputs[info->NumOutputs].ComponentOffset =
1728 this->array_subscript % 4;
1729 } else {
1730 num_components = MIN2(4, this->size - components_so_far);
1731 }
1732 }
1733 info->Outputs[info->NumOutputs].OutputRegister =
1734 this->location + v + index * this->matrix_columns;
1735 info->Outputs[info->NumOutputs].NumComponents = num_components;
1736 info->Outputs[info->NumOutputs].OutputBuffer = buffer;
1737 info->Outputs[info->NumOutputs].DstOffset = info->BufferStride[buffer];
1738 ++info->NumOutputs;
1739 info->BufferStride[buffer] += num_components;
1740 components_so_far += num_components;
1741 }
1742 }
1743 assert(components_so_far == this->num_components());
1744
1745 info->Varyings[varying].Name = ralloc_strdup(prog, this->orig_name);
1746 info->Varyings[varying].Type = this->type;
1747 info->Varyings[varying].Size = this->size;
1748 info->NumVarying++;
1749
1750 return true;
1751 }
1752
1753
1754 /**
1755 * Parse all the transform feedback declarations that were passed to
1756 * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
1757 *
1758 * If an error occurs, the error is reported through linker_error() and false
1759 * is returned.
1760 */
1761 static bool
1762 parse_tfeedback_decls(struct gl_context *ctx, struct gl_shader_program *prog,
1763 const void *mem_ctx, unsigned num_names,
1764 char **varying_names, tfeedback_decl *decls)
1765 {
1766 for (unsigned i = 0; i < num_names; ++i) {
1767 if (!decls[i].init(ctx, prog, mem_ctx, varying_names[i]))
1768 return false;
1769 /* From GL_EXT_transform_feedback:
1770 * A program will fail to link if:
1771 *
1772 * * any two entries in the <varyings> array specify the same varying
1773 * variable;
1774 *
1775 * We interpret this to mean "any two entries in the <varyings> array
1776 * specify the same varying variable and array index", since transform
1777 * feedback of arrays would be useless otherwise.
1778 */
1779 for (unsigned j = 0; j < i; ++j) {
1780 if (tfeedback_decl::is_same(decls[i], decls[j])) {
1781 linker_error(prog, "Transform feedback varying %s specified "
1782 "more than once.", varying_names[i]);
1783 return false;
1784 }
1785 }
1786 }
1787 return true;
1788 }
1789
1790
1791 /**
1792 * Assign a location for a variable that is produced in one pipeline stage
1793 * (the "producer") and consumed in the next stage (the "consumer").
1794 *
1795 * \param input_var is the input variable declaration in the consumer.
1796 *
1797 * \param output_var is the output variable declaration in the producer.
1798 *
1799 * \param input_index is the counter that keeps track of assigned input
1800 * locations in the consumer.
1801 *
1802 * \param output_index is the counter that keeps track of assigned output
1803 * locations in the producer.
1804 *
1805 * It is permissible for \c input_var to be NULL (this happens if a variable
1806 * is output by the producer and consumed by transform feedback, but not
1807 * consumed by the consumer).
1808 *
1809 * If the variable has already been assigned a location, this function has no
1810 * effect.
1811 */
1812 void
1813 assign_varying_location(ir_variable *input_var, ir_variable *output_var,
1814 unsigned *input_index, unsigned *output_index)
1815 {
1816 if (output_var->location != -1) {
1817 /* Location already assigned. */
1818 return;
1819 }
1820
1821 if (input_var) {
1822 assert(input_var->location == -1);
1823 input_var->location = *input_index;
1824 }
1825
1826 output_var->location = *output_index;
1827
1828 /* FINISHME: Support for "varying" records in GLSL 1.50. */
1829 assert(!output_var->type->is_record());
1830
1831 if (output_var->type->is_array()) {
1832 const unsigned slots = output_var->type->length
1833 * output_var->type->fields.array->matrix_columns;
1834
1835 *output_index += slots;
1836 *input_index += slots;
1837 } else {
1838 const unsigned slots = output_var->type->matrix_columns;
1839
1840 *output_index += slots;
1841 *input_index += slots;
1842 }
1843 }
1844
1845
1846 /**
1847 * Assign locations for all variables that are produced in one pipeline stage
1848 * (the "producer") and consumed in the next stage (the "consumer").
1849 *
1850 * Variables produced by the producer may also be consumed by transform
1851 * feedback.
1852 *
1853 * \param num_tfeedback_decls is the number of declarations indicating
1854 * variables that may be consumed by transform feedback.
1855 *
1856 * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
1857 * representing the result of parsing the strings passed to
1858 * glTransformFeedbackVaryings(). assign_location() will be called for
1859 * each of these objects that matches one of the outputs of the
1860 * producer.
1861 *
1862 * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
1863 * be NULL. In this case, varying locations are assigned solely based on the
1864 * requirements of transform feedback.
1865 */
1866 bool
1867 assign_varying_locations(struct gl_context *ctx,
1868 struct gl_shader_program *prog,
1869 gl_shader *producer, gl_shader *consumer,
1870 unsigned num_tfeedback_decls,
1871 tfeedback_decl *tfeedback_decls)
1872 {
1873 /* FINISHME: Set dynamically when geometry shader support is added. */
1874 unsigned output_index = VERT_RESULT_VAR0;
1875 unsigned input_index = FRAG_ATTRIB_VAR0;
1876
1877 /* Operate in a total of three passes.
1878 *
1879 * 1. Assign locations for any matching inputs and outputs.
1880 *
1881 * 2. Mark output variables in the producer that do not have locations as
1882 * not being outputs. This lets the optimizer eliminate them.
1883 *
1884 * 3. Mark input variables in the consumer that do not have locations as
1885 * not being inputs. This lets the optimizer eliminate them.
1886 */
1887
1888 link_invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
1889 if (consumer)
1890 link_invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
1891
1892 foreach_list(node, producer->ir) {
1893 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1894
1895 if ((output_var == NULL) || (output_var->mode != ir_var_out))
1896 continue;
1897
1898 ir_variable *input_var =
1899 consumer ? consumer->symbols->get_variable(output_var->name) : NULL;
1900
1901 if (input_var && input_var->mode != ir_var_in)
1902 input_var = NULL;
1903
1904 if (input_var) {
1905 assign_varying_location(input_var, output_var, &input_index,
1906 &output_index);
1907 }
1908
1909 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1910 if (!tfeedback_decls[i].is_assigned() &&
1911 tfeedback_decls[i].matches_var(output_var)) {
1912 if (output_var->location == -1) {
1913 assign_varying_location(input_var, output_var, &input_index,
1914 &output_index);
1915 }
1916 if (!tfeedback_decls[i].assign_location(ctx, prog, output_var))
1917 return false;
1918 }
1919 }
1920 }
1921
1922 unsigned varying_vectors = 0;
1923
1924 if (consumer) {
1925 foreach_list(node, consumer->ir) {
1926 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1927
1928 if ((var == NULL) || (var->mode != ir_var_in))
1929 continue;
1930
1931 if (var->location == -1) {
1932 if (prog->Version <= 120) {
1933 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1934 *
1935 * Only those varying variables used (i.e. read) in
1936 * the fragment shader executable must be written to
1937 * by the vertex shader executable; declaring
1938 * superfluous varying variables in a vertex shader is
1939 * permissible.
1940 *
1941 * We interpret this text as meaning that the VS must
1942 * write the variable for the FS to read it. See
1943 * "glsl1-varying read but not written" in piglit.
1944 */
1945
1946 linker_error(prog, "fragment shader varying %s not written "
1947 "by vertex shader\n.", var->name);
1948 }
1949
1950 /* An 'in' variable is only really a shader input if its
1951 * value is written by the previous stage.
1952 */
1953 var->mode = ir_var_auto;
1954 } else {
1955 /* The packing rules are used for vertex shader inputs are also
1956 * used for fragment shader inputs.
1957 */
1958 varying_vectors += count_attribute_slots(var->type);
1959 }
1960 }
1961 }
1962
1963 if (ctx->API == API_OPENGLES2 || prog->Version == 100) {
1964 if (varying_vectors > ctx->Const.MaxVarying) {
1965 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
1966 linker_warning(prog, "shader uses too many varying vectors "
1967 "(%u > %u), but the driver will try to optimize "
1968 "them out; this is non-portable out-of-spec "
1969 "behavior\n",
1970 varying_vectors, ctx->Const.MaxVarying);
1971 } else {
1972 linker_error(prog, "shader uses too many varying vectors "
1973 "(%u > %u)\n",
1974 varying_vectors, ctx->Const.MaxVarying);
1975 return false;
1976 }
1977 }
1978 } else {
1979 const unsigned float_components = varying_vectors * 4;
1980 if (float_components > ctx->Const.MaxVarying * 4) {
1981 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
1982 linker_warning(prog, "shader uses too many varying components "
1983 "(%u > %u), but the driver will try to optimize "
1984 "them out; this is non-portable out-of-spec "
1985 "behavior\n",
1986 float_components, ctx->Const.MaxVarying * 4);
1987 } else {
1988 linker_error(prog, "shader uses too many varying components "
1989 "(%u > %u)\n",
1990 float_components, ctx->Const.MaxVarying * 4);
1991 return false;
1992 }
1993 }
1994 }
1995
1996 return true;
1997 }
1998
1999
2000 /**
2001 * Store transform feedback location assignments into
2002 * prog->LinkedTransformFeedback based on the data stored in tfeedback_decls.
2003 *
2004 * If an error occurs, the error is reported through linker_error() and false
2005 * is returned.
2006 */
2007 static bool
2008 store_tfeedback_info(struct gl_context *ctx, struct gl_shader_program *prog,
2009 unsigned num_tfeedback_decls,
2010 tfeedback_decl *tfeedback_decls)
2011 {
2012 bool separate_attribs_mode =
2013 prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS;
2014
2015 ralloc_free(prog->LinkedTransformFeedback.Varyings);
2016 ralloc_free(prog->LinkedTransformFeedback.Outputs);
2017
2018 memset(&prog->LinkedTransformFeedback, 0,
2019 sizeof(prog->LinkedTransformFeedback));
2020
2021 prog->LinkedTransformFeedback.NumBuffers =
2022 separate_attribs_mode ? num_tfeedback_decls : 1;
2023
2024 prog->LinkedTransformFeedback.Varyings =
2025 rzalloc_array(prog,
2026 struct gl_transform_feedback_varying_info,
2027 num_tfeedback_decls);
2028
2029 unsigned num_outputs = 0;
2030 for (unsigned i = 0; i < num_tfeedback_decls; ++i)
2031 if (!tfeedback_decls[i].accumulate_num_outputs(prog, &num_outputs))
2032 return false;
2033
2034 prog->LinkedTransformFeedback.Outputs =
2035 rzalloc_array(prog,
2036 struct gl_transform_feedback_output,
2037 num_outputs);
2038
2039 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
2040 unsigned buffer = separate_attribs_mode ? i : 0;
2041 if (!tfeedback_decls[i].store(ctx, prog, &prog->LinkedTransformFeedback,
2042 buffer, i, num_outputs))
2043 return false;
2044 }
2045 assert(prog->LinkedTransformFeedback.NumOutputs == num_outputs);
2046
2047 return true;
2048 }
2049
2050 /**
2051 * Store the gl_FragDepth layout in the gl_shader_program struct.
2052 */
2053 static void
2054 store_fragdepth_layout(struct gl_shader_program *prog)
2055 {
2056 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2057 return;
2058 }
2059
2060 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2061
2062 /* We don't look up the gl_FragDepth symbol directly because if
2063 * gl_FragDepth is not used in the shader, it's removed from the IR.
2064 * However, the symbol won't be removed from the symbol table.
2065 *
2066 * We're only interested in the cases where the variable is NOT removed
2067 * from the IR.
2068 */
2069 foreach_list(node, ir) {
2070 ir_variable *const var = ((ir_instruction *) node)->as_variable();
2071
2072 if (var == NULL || var->mode != ir_var_out) {
2073 continue;
2074 }
2075
2076 if (strcmp(var->name, "gl_FragDepth") == 0) {
2077 switch (var->depth_layout) {
2078 case ir_depth_layout_none:
2079 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2080 return;
2081 case ir_depth_layout_any:
2082 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2083 return;
2084 case ir_depth_layout_greater:
2085 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2086 return;
2087 case ir_depth_layout_less:
2088 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2089 return;
2090 case ir_depth_layout_unchanged:
2091 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2092 return;
2093 default:
2094 assert(0);
2095 return;
2096 }
2097 }
2098 }
2099 }
2100
2101 /**
2102 * Validate the resources used by a program versus the implementation limits
2103 */
2104 static bool
2105 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2106 {
2107 static const char *const shader_names[MESA_SHADER_TYPES] = {
2108 "vertex", "fragment", "geometry"
2109 };
2110
2111 const unsigned max_samplers[MESA_SHADER_TYPES] = {
2112 ctx->Const.MaxVertexTextureImageUnits,
2113 ctx->Const.MaxTextureImageUnits,
2114 ctx->Const.MaxGeometryTextureImageUnits
2115 };
2116
2117 const unsigned max_uniform_components[MESA_SHADER_TYPES] = {
2118 ctx->Const.VertexProgram.MaxUniformComponents,
2119 ctx->Const.FragmentProgram.MaxUniformComponents,
2120 0 /* FINISHME: Geometry shaders. */
2121 };
2122
2123 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2124 struct gl_shader *sh = prog->_LinkedShaders[i];
2125
2126 if (sh == NULL)
2127 continue;
2128
2129 if (sh->num_samplers > max_samplers[i]) {
2130 linker_error(prog, "Too many %s shader texture samplers",
2131 shader_names[i]);
2132 }
2133
2134 if (sh->num_uniform_components > max_uniform_components[i]) {
2135 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2136 linker_warning(prog, "Too many %s shader uniform components, "
2137 "but the driver will try to optimize them out; "
2138 "this is non-portable out-of-spec behavior\n",
2139 shader_names[i]);
2140 } else {
2141 linker_error(prog, "Too many %s shader uniform components",
2142 shader_names[i]);
2143 }
2144 }
2145 }
2146
2147 return prog->LinkStatus;
2148 }
2149
2150 void
2151 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
2152 {
2153 tfeedback_decl *tfeedback_decls = NULL;
2154 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
2155
2156 void *mem_ctx = ralloc_context(NULL); // temporary linker context
2157
2158 prog->LinkStatus = false;
2159 prog->Validated = false;
2160 prog->_Used = false;
2161
2162 if (prog->InfoLog != NULL)
2163 ralloc_free(prog->InfoLog);
2164
2165 prog->InfoLog = ralloc_strdup(NULL, "");
2166
2167 /* Separate the shaders into groups based on their type.
2168 */
2169 struct gl_shader **vert_shader_list;
2170 unsigned num_vert_shaders = 0;
2171 struct gl_shader **frag_shader_list;
2172 unsigned num_frag_shaders = 0;
2173
2174 vert_shader_list = (struct gl_shader **)
2175 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
2176 frag_shader_list = &vert_shader_list[prog->NumShaders];
2177
2178 unsigned min_version = UINT_MAX;
2179 unsigned max_version = 0;
2180 for (unsigned i = 0; i < prog->NumShaders; i++) {
2181 min_version = MIN2(min_version, prog->Shaders[i]->Version);
2182 max_version = MAX2(max_version, prog->Shaders[i]->Version);
2183
2184 switch (prog->Shaders[i]->Type) {
2185 case GL_VERTEX_SHADER:
2186 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
2187 num_vert_shaders++;
2188 break;
2189 case GL_FRAGMENT_SHADER:
2190 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
2191 num_frag_shaders++;
2192 break;
2193 case GL_GEOMETRY_SHADER:
2194 /* FINISHME: Support geometry shaders. */
2195 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
2196 break;
2197 }
2198 }
2199
2200 /* Previous to GLSL version 1.30, different compilation units could mix and
2201 * match shading language versions. With GLSL 1.30 and later, the versions
2202 * of all shaders must match.
2203 */
2204 assert(min_version >= 100);
2205 assert(max_version <= 140);
2206 if ((max_version >= 130 || min_version == 100)
2207 && min_version != max_version) {
2208 linker_error(prog, "all shaders must use same shading "
2209 "language version\n");
2210 goto done;
2211 }
2212
2213 prog->Version = max_version;
2214
2215 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
2216 if (prog->_LinkedShaders[i] != NULL)
2217 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
2218
2219 prog->_LinkedShaders[i] = NULL;
2220 }
2221
2222 /* Link all shaders for a particular stage and validate the result.
2223 */
2224 if (num_vert_shaders > 0) {
2225 gl_shader *const sh =
2226 link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
2227 num_vert_shaders);
2228
2229 if (sh == NULL)
2230 goto done;
2231
2232 if (!validate_vertex_shader_executable(prog, sh))
2233 goto done;
2234
2235 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
2236 sh);
2237 }
2238
2239 if (num_frag_shaders > 0) {
2240 gl_shader *const sh =
2241 link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
2242 num_frag_shaders);
2243
2244 if (sh == NULL)
2245 goto done;
2246
2247 if (!validate_fragment_shader_executable(prog, sh))
2248 goto done;
2249
2250 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
2251 sh);
2252 }
2253
2254 /* Here begins the inter-stage linking phase. Some initial validation is
2255 * performed, then locations are assigned for uniforms, attributes, and
2256 * varyings.
2257 */
2258 if (cross_validate_uniforms(prog)) {
2259 unsigned prev;
2260
2261 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2262 if (prog->_LinkedShaders[prev] != NULL)
2263 break;
2264 }
2265
2266 /* Validate the inputs of each stage with the output of the preceding
2267 * stage.
2268 */
2269 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2270 if (prog->_LinkedShaders[i] == NULL)
2271 continue;
2272
2273 if (!cross_validate_outputs_to_inputs(prog,
2274 prog->_LinkedShaders[prev],
2275 prog->_LinkedShaders[i]))
2276 goto done;
2277
2278 prev = i;
2279 }
2280
2281 prog->LinkStatus = true;
2282 }
2283
2284 /* Do common optimization before assigning storage for attributes,
2285 * uniforms, and varyings. Later optimization could possibly make
2286 * some of that unused.
2287 */
2288 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2289 if (prog->_LinkedShaders[i] == NULL)
2290 continue;
2291
2292 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
2293 if (!prog->LinkStatus)
2294 goto done;
2295
2296 if (ctx->ShaderCompilerOptions[i].LowerClipDistance)
2297 lower_clip_distance(prog->_LinkedShaders[i]->ir);
2298
2299 unsigned max_unroll = ctx->ShaderCompilerOptions[i].MaxUnrollIterations;
2300
2301 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false, max_unroll))
2302 ;
2303 }
2304
2305 /* FINISHME: The value of the max_attribute_index parameter is
2306 * FINISHME: implementation dependent based on the value of
2307 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
2308 * FINISHME: at least 16, so hardcode 16 for now.
2309 */
2310 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX, 16)) {
2311 goto done;
2312 }
2313
2314 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, ctx->Const.MaxDrawBuffers)) {
2315 goto done;
2316 }
2317
2318 unsigned prev;
2319 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2320 if (prog->_LinkedShaders[prev] != NULL)
2321 break;
2322 }
2323
2324 if (num_tfeedback_decls != 0) {
2325 /* From GL_EXT_transform_feedback:
2326 * A program will fail to link if:
2327 *
2328 * * the <count> specified by TransformFeedbackVaryingsEXT is
2329 * non-zero, but the program object has no vertex or geometry
2330 * shader;
2331 */
2332 if (prev >= MESA_SHADER_FRAGMENT) {
2333 linker_error(prog, "Transform feedback varyings specified, but "
2334 "no vertex or geometry shader is present.");
2335 goto done;
2336 }
2337
2338 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
2339 prog->TransformFeedback.NumVarying);
2340 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
2341 prog->TransformFeedback.VaryingNames,
2342 tfeedback_decls))
2343 goto done;
2344 }
2345
2346 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2347 if (prog->_LinkedShaders[i] == NULL)
2348 continue;
2349
2350 if (!assign_varying_locations(
2351 ctx, prog, prog->_LinkedShaders[prev], prog->_LinkedShaders[i],
2352 i == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2353 tfeedback_decls))
2354 goto done;
2355
2356 prev = i;
2357 }
2358
2359 if (prev != MESA_SHADER_FRAGMENT && num_tfeedback_decls != 0) {
2360 /* There was no fragment shader, but we still have to assign varying
2361 * locations for use by transform feedback.
2362 */
2363 if (!assign_varying_locations(
2364 ctx, prog, prog->_LinkedShaders[prev], NULL, num_tfeedback_decls,
2365 tfeedback_decls))
2366 goto done;
2367 }
2368
2369 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
2370 goto done;
2371
2372 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
2373 demote_shader_inputs_and_outputs(prog->_LinkedShaders[MESA_SHADER_VERTEX],
2374 ir_var_out);
2375
2376 /* Eliminate code that is now dead due to unused vertex outputs being
2377 * demoted.
2378 */
2379 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_VERTEX]->ir, false))
2380 ;
2381 }
2382
2383 if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
2384 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
2385
2386 demote_shader_inputs_and_outputs(sh, ir_var_in);
2387 demote_shader_inputs_and_outputs(sh, ir_var_inout);
2388 demote_shader_inputs_and_outputs(sh, ir_var_out);
2389
2390 /* Eliminate code that is now dead due to unused geometry outputs being
2391 * demoted.
2392 */
2393 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_GEOMETRY]->ir, false))
2394 ;
2395 }
2396
2397 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
2398 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2399
2400 demote_shader_inputs_and_outputs(sh, ir_var_in);
2401
2402 /* Eliminate code that is now dead due to unused fragment inputs being
2403 * demoted. This shouldn't actually do anything other than remove
2404 * declarations of the (now unused) global variables.
2405 */
2406 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir, false))
2407 ;
2408 }
2409
2410 update_array_sizes(prog);
2411 link_assign_uniform_locations(prog);
2412 store_fragdepth_layout(prog);
2413
2414 if (!check_resources(ctx, prog))
2415 goto done;
2416
2417 /* OpenGL ES requires that a vertex shader and a fragment shader both be
2418 * present in a linked program. By checking for use of shading language
2419 * version 1.00, we also catch the GL_ARB_ES2_compatibility case.
2420 */
2421 if (!prog->InternalSeparateShader &&
2422 (ctx->API == API_OPENGLES2 || prog->Version == 100)) {
2423 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
2424 linker_error(prog, "program lacks a vertex shader\n");
2425 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2426 linker_error(prog, "program lacks a fragment shader\n");
2427 }
2428 }
2429
2430 /* FINISHME: Assign fragment shader output locations. */
2431
2432 done:
2433 free(vert_shader_list);
2434
2435 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2436 if (prog->_LinkedShaders[i] == NULL)
2437 continue;
2438
2439 /* Retain any live IR, but trash the rest. */
2440 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
2441
2442 /* The symbol table in the linked shaders may contain references to
2443 * variables that were removed (e.g., unused uniforms). Since it may
2444 * contain junk, there is no possible valid use. Delete it and set the
2445 * pointer to NULL.
2446 */
2447 delete prog->_LinkedShaders[i]->symbols;
2448 prog->_LinkedShaders[i]->symbols = NULL;
2449 }
2450
2451 ralloc_free(mem_ctx);
2452 }