st/glsl_to_nir: make use of nir linker for linking uniforms
[mesa.git] / src / compiler / 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 <ctype.h>
68 #include "util/strndup.h"
69 #include "glsl_symbol_table.h"
70 #include "glsl_parser_extras.h"
71 #include "ir.h"
72 #include "program.h"
73 #include "program/prog_instruction.h"
74 #include "program/program.h"
75 #include "util/mesa-sha1.h"
76 #include "util/set.h"
77 #include "string_to_uint_map.h"
78 #include "linker.h"
79 #include "linker_util.h"
80 #include "link_varyings.h"
81 #include "ir_optimization.h"
82 #include "ir_rvalue_visitor.h"
83 #include "ir_uniform.h"
84 #include "builtin_functions.h"
85 #include "shader_cache.h"
86 #include "util/u_string.h"
87 #include "util/u_math.h"
88
89 #include "util/imports.h"
90 #include "main/shaderobj.h"
91 #include "main/enums.h"
92 #include "main/mtypes.h"
93
94
95 namespace {
96
97 struct find_variable {
98 const char *name;
99 bool found;
100
101 find_variable(const char *name) : name(name), found(false) {}
102 };
103
104 /**
105 * Visitor that determines whether or not a variable is ever written.
106 *
107 * Use \ref find_assignments for convenience.
108 */
109 class find_assignment_visitor : public ir_hierarchical_visitor {
110 public:
111 find_assignment_visitor(unsigned num_vars,
112 find_variable * const *vars)
113 : num_variables(num_vars), num_found(0), variables(vars)
114 {
115 }
116
117 virtual ir_visitor_status visit_enter(ir_assignment *ir)
118 {
119 ir_variable *const var = ir->lhs->variable_referenced();
120
121 return check_variable_name(var->name);
122 }
123
124 virtual ir_visitor_status visit_enter(ir_call *ir)
125 {
126 foreach_two_lists(formal_node, &ir->callee->parameters,
127 actual_node, &ir->actual_parameters) {
128 ir_rvalue *param_rval = (ir_rvalue *) actual_node;
129 ir_variable *sig_param = (ir_variable *) formal_node;
130
131 if (sig_param->data.mode == ir_var_function_out ||
132 sig_param->data.mode == ir_var_function_inout) {
133 ir_variable *var = param_rval->variable_referenced();
134 if (var && check_variable_name(var->name) == visit_stop)
135 return visit_stop;
136 }
137 }
138
139 if (ir->return_deref != NULL) {
140 ir_variable *const var = ir->return_deref->variable_referenced();
141
142 if (check_variable_name(var->name) == visit_stop)
143 return visit_stop;
144 }
145
146 return visit_continue_with_parent;
147 }
148
149 private:
150 ir_visitor_status check_variable_name(const char *name)
151 {
152 for (unsigned i = 0; i < num_variables; ++i) {
153 if (strcmp(variables[i]->name, name) == 0) {
154 if (!variables[i]->found) {
155 variables[i]->found = true;
156
157 assert(num_found < num_variables);
158 if (++num_found == num_variables)
159 return visit_stop;
160 }
161 break;
162 }
163 }
164
165 return visit_continue_with_parent;
166 }
167
168 private:
169 unsigned num_variables; /**< Number of variables to find */
170 unsigned num_found; /**< Number of variables already found */
171 find_variable * const *variables; /**< Variables to find */
172 };
173
174 /**
175 * Determine whether or not any of NULL-terminated list of variables is ever
176 * written to.
177 */
178 static void
179 find_assignments(exec_list *ir, find_variable * const *vars)
180 {
181 unsigned num_variables = 0;
182
183 for (find_variable * const *v = vars; *v; ++v)
184 num_variables++;
185
186 find_assignment_visitor visitor(num_variables, vars);
187 visitor.run(ir);
188 }
189
190 /**
191 * Determine whether or not the given variable is ever written to.
192 */
193 static void
194 find_assignments(exec_list *ir, find_variable *var)
195 {
196 find_assignment_visitor visitor(1, &var);
197 visitor.run(ir);
198 }
199
200 /**
201 * Visitor that determines whether or not a variable is ever read.
202 */
203 class find_deref_visitor : public ir_hierarchical_visitor {
204 public:
205 find_deref_visitor(const char *name)
206 : name(name), found(false)
207 {
208 /* empty */
209 }
210
211 virtual ir_visitor_status visit(ir_dereference_variable *ir)
212 {
213 if (strcmp(this->name, ir->var->name) == 0) {
214 this->found = true;
215 return visit_stop;
216 }
217
218 return visit_continue;
219 }
220
221 bool variable_found() const
222 {
223 return this->found;
224 }
225
226 private:
227 const char *name; /**< Find writes to a variable with this name. */
228 bool found; /**< Was a write to the variable found? */
229 };
230
231
232 /**
233 * A visitor helper that provides methods for updating the types of
234 * ir_dereferences. Classes that update variable types (say, updating
235 * array sizes) will want to use this so that dereference types stay in sync.
236 */
237 class deref_type_updater : public ir_hierarchical_visitor {
238 public:
239 virtual ir_visitor_status visit(ir_dereference_variable *ir)
240 {
241 ir->type = ir->var->type;
242 return visit_continue;
243 }
244
245 virtual ir_visitor_status visit_leave(ir_dereference_array *ir)
246 {
247 const glsl_type *const vt = ir->array->type;
248 if (vt->is_array())
249 ir->type = vt->fields.array;
250 return visit_continue;
251 }
252
253 virtual ir_visitor_status visit_leave(ir_dereference_record *ir)
254 {
255 ir->type = ir->record->type->fields.structure[ir->field_idx].type;
256 return visit_continue;
257 }
258 };
259
260
261 class array_resize_visitor : public deref_type_updater {
262 public:
263 using deref_type_updater::visit;
264
265 unsigned num_vertices;
266 gl_shader_program *prog;
267 gl_shader_stage stage;
268
269 array_resize_visitor(unsigned num_vertices,
270 gl_shader_program *prog,
271 gl_shader_stage stage)
272 {
273 this->num_vertices = num_vertices;
274 this->prog = prog;
275 this->stage = stage;
276 }
277
278 virtual ~array_resize_visitor()
279 {
280 /* empty */
281 }
282
283 virtual ir_visitor_status visit(ir_variable *var)
284 {
285 if (!var->type->is_array() || var->data.mode != ir_var_shader_in ||
286 var->data.patch)
287 return visit_continue;
288
289 unsigned size = var->type->length;
290
291 if (stage == MESA_SHADER_GEOMETRY) {
292 /* Generate a link error if the shader has declared this array with
293 * an incorrect size.
294 */
295 if (!var->data.implicit_sized_array &&
296 size && size != this->num_vertices) {
297 linker_error(this->prog, "size of array %s declared as %u, "
298 "but number of input vertices is %u\n",
299 var->name, size, this->num_vertices);
300 return visit_continue;
301 }
302
303 /* Generate a link error if the shader attempts to access an input
304 * array using an index too large for its actual size assigned at
305 * link time.
306 */
307 if (var->data.max_array_access >= (int)this->num_vertices) {
308 linker_error(this->prog, "%s shader accesses element %i of "
309 "%s, but only %i input vertices\n",
310 _mesa_shader_stage_to_string(this->stage),
311 var->data.max_array_access, var->name, this->num_vertices);
312 return visit_continue;
313 }
314 }
315
316 var->type = glsl_type::get_array_instance(var->type->fields.array,
317 this->num_vertices);
318 var->data.max_array_access = this->num_vertices - 1;
319
320 return visit_continue;
321 }
322 };
323
324 /**
325 * Visitor that determines the highest stream id to which a (geometry) shader
326 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
327 */
328 class find_emit_vertex_visitor : public ir_hierarchical_visitor {
329 public:
330 find_emit_vertex_visitor(int max_allowed)
331 : max_stream_allowed(max_allowed),
332 invalid_stream_id(0),
333 invalid_stream_id_from_emit_vertex(false),
334 end_primitive_found(false),
335 uses_non_zero_stream(false)
336 {
337 /* empty */
338 }
339
340 virtual ir_visitor_status visit_leave(ir_emit_vertex *ir)
341 {
342 int stream_id = ir->stream_id();
343
344 if (stream_id < 0) {
345 invalid_stream_id = stream_id;
346 invalid_stream_id_from_emit_vertex = true;
347 return visit_stop;
348 }
349
350 if (stream_id > max_stream_allowed) {
351 invalid_stream_id = stream_id;
352 invalid_stream_id_from_emit_vertex = true;
353 return visit_stop;
354 }
355
356 if (stream_id != 0)
357 uses_non_zero_stream = true;
358
359 return visit_continue;
360 }
361
362 virtual ir_visitor_status visit_leave(ir_end_primitive *ir)
363 {
364 end_primitive_found = true;
365
366 int stream_id = ir->stream_id();
367
368 if (stream_id < 0) {
369 invalid_stream_id = stream_id;
370 invalid_stream_id_from_emit_vertex = false;
371 return visit_stop;
372 }
373
374 if (stream_id > max_stream_allowed) {
375 invalid_stream_id = stream_id;
376 invalid_stream_id_from_emit_vertex = false;
377 return visit_stop;
378 }
379
380 if (stream_id != 0)
381 uses_non_zero_stream = true;
382
383 return visit_continue;
384 }
385
386 bool error()
387 {
388 return invalid_stream_id != 0;
389 }
390
391 const char *error_func()
392 {
393 return invalid_stream_id_from_emit_vertex ?
394 "EmitStreamVertex" : "EndStreamPrimitive";
395 }
396
397 int error_stream()
398 {
399 return invalid_stream_id;
400 }
401
402 bool uses_streams()
403 {
404 return uses_non_zero_stream;
405 }
406
407 bool uses_end_primitive()
408 {
409 return end_primitive_found;
410 }
411
412 private:
413 int max_stream_allowed;
414 int invalid_stream_id;
415 bool invalid_stream_id_from_emit_vertex;
416 bool end_primitive_found;
417 bool uses_non_zero_stream;
418 };
419
420 /* Class that finds array derefs and check if indexes are dynamic. */
421 class dynamic_sampler_array_indexing_visitor : public ir_hierarchical_visitor
422 {
423 public:
424 dynamic_sampler_array_indexing_visitor() :
425 dynamic_sampler_array_indexing(false)
426 {
427 }
428
429 ir_visitor_status visit_enter(ir_dereference_array *ir)
430 {
431 if (!ir->variable_referenced())
432 return visit_continue;
433
434 if (!ir->variable_referenced()->type->contains_sampler())
435 return visit_continue;
436
437 if (!ir->array_index->constant_expression_value(ralloc_parent(ir))) {
438 dynamic_sampler_array_indexing = true;
439 return visit_stop;
440 }
441 return visit_continue;
442 }
443
444 bool uses_dynamic_sampler_array_indexing()
445 {
446 return dynamic_sampler_array_indexing;
447 }
448
449 private:
450 bool dynamic_sampler_array_indexing;
451 };
452
453 } /* anonymous namespace */
454
455 void
456 linker_error(gl_shader_program *prog, const char *fmt, ...)
457 {
458 va_list ap;
459
460 ralloc_strcat(&prog->data->InfoLog, "error: ");
461 va_start(ap, fmt);
462 ralloc_vasprintf_append(&prog->data->InfoLog, fmt, ap);
463 va_end(ap);
464
465 prog->data->LinkStatus = LINKING_FAILURE;
466 }
467
468
469 void
470 linker_warning(gl_shader_program *prog, const char *fmt, ...)
471 {
472 va_list ap;
473
474 ralloc_strcat(&prog->data->InfoLog, "warning: ");
475 va_start(ap, fmt);
476 ralloc_vasprintf_append(&prog->data->InfoLog, fmt, ap);
477 va_end(ap);
478
479 }
480
481
482 /**
483 * Given a string identifying a program resource, break it into a base name
484 * and an optional array index in square brackets.
485 *
486 * If an array index is present, \c out_base_name_end is set to point to the
487 * "[" that precedes the array index, and the array index itself is returned
488 * as a long.
489 *
490 * If no array index is present (or if the array index is negative or
491 * mal-formed), \c out_base_name_end, is set to point to the null terminator
492 * at the end of the input string, and -1 is returned.
493 *
494 * Only the final array index is parsed; if the string contains other array
495 * indices (or structure field accesses), they are left in the base name.
496 *
497 * No attempt is made to check that the base name is properly formed;
498 * typically the caller will look up the base name in a hash table, so
499 * ill-formed base names simply turn into hash table lookup failures.
500 */
501 long
502 parse_program_resource_name(const GLchar *name,
503 const GLchar **out_base_name_end)
504 {
505 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
506 *
507 * "When an integer array element or block instance number is part of
508 * the name string, it will be specified in decimal form without a "+"
509 * or "-" sign or any extra leading zeroes. Additionally, the name
510 * string will not include white space anywhere in the string."
511 */
512
513 const size_t len = strlen(name);
514 *out_base_name_end = name + len;
515
516 if (len == 0 || name[len-1] != ']')
517 return -1;
518
519 /* Walk backwards over the string looking for a non-digit character. This
520 * had better be the opening bracket for an array index.
521 *
522 * Initially, i specifies the location of the ']'. Since the string may
523 * contain only the ']' charcater, walk backwards very carefully.
524 */
525 unsigned i;
526 for (i = len - 1; (i > 0) && isdigit(name[i-1]); --i)
527 /* empty */ ;
528
529 if ((i == 0) || name[i-1] != '[')
530 return -1;
531
532 long array_index = strtol(&name[i], NULL, 10);
533 if (array_index < 0)
534 return -1;
535
536 /* Check for leading zero */
537 if (name[i] == '0' && name[i+1] != ']')
538 return -1;
539
540 *out_base_name_end = name + (i - 1);
541 return array_index;
542 }
543
544
545 void
546 link_invalidate_variable_locations(exec_list *ir)
547 {
548 foreach_in_list(ir_instruction, node, ir) {
549 ir_variable *const var = node->as_variable();
550
551 if (var == NULL)
552 continue;
553
554 /* Only assign locations for variables that lack an explicit location.
555 * Explicit locations are set for all built-in variables, generic vertex
556 * shader inputs (via layout(location=...)), and generic fragment shader
557 * outputs (also via layout(location=...)).
558 */
559 if (!var->data.explicit_location) {
560 var->data.location = -1;
561 var->data.location_frac = 0;
562 }
563
564 /* ir_variable::is_unmatched_generic_inout is used by the linker while
565 * connecting outputs from one stage to inputs of the next stage.
566 */
567 if (var->data.explicit_location &&
568 var->data.location < VARYING_SLOT_VAR0) {
569 var->data.is_unmatched_generic_inout = 0;
570 } else {
571 var->data.is_unmatched_generic_inout = 1;
572 }
573 }
574 }
575
576
577 /**
578 * Set clip_distance_array_size based and cull_distance_array_size on the given
579 * shader.
580 *
581 * Also check for errors based on incorrect usage of gl_ClipVertex and
582 * gl_ClipDistance and gl_CullDistance.
583 * Additionally test whether the arrays gl_ClipDistance and gl_CullDistance
584 * exceed the maximum size defined by gl_MaxCombinedClipAndCullDistances.
585 *
586 * Return false if an error was reported.
587 */
588 static void
589 analyze_clip_cull_usage(struct gl_shader_program *prog,
590 struct gl_linked_shader *shader,
591 struct gl_context *ctx,
592 struct shader_info *info)
593 {
594 info->clip_distance_array_size = 0;
595 info->cull_distance_array_size = 0;
596
597 if (prog->data->Version >= (prog->IsES ? 300 : 130)) {
598 /* From section 7.1 (Vertex Shader Special Variables) of the
599 * GLSL 1.30 spec:
600 *
601 * "It is an error for a shader to statically write both
602 * gl_ClipVertex and gl_ClipDistance."
603 *
604 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
605 * gl_ClipVertex nor gl_ClipDistance. However with
606 * GL_EXT_clip_cull_distance, this functionality is exposed in ES 3.0.
607 */
608 find_variable gl_ClipDistance("gl_ClipDistance");
609 find_variable gl_CullDistance("gl_CullDistance");
610 find_variable gl_ClipVertex("gl_ClipVertex");
611 find_variable * const variables[] = {
612 &gl_ClipDistance,
613 &gl_CullDistance,
614 !prog->IsES ? &gl_ClipVertex : NULL,
615 NULL
616 };
617 find_assignments(shader->ir, variables);
618
619 /* From the ARB_cull_distance spec:
620 *
621 * It is a compile-time or link-time error for the set of shaders forming
622 * a program to statically read or write both gl_ClipVertex and either
623 * gl_ClipDistance or gl_CullDistance.
624 *
625 * This does not apply to GLSL ES shaders, since GLSL ES doesn't define
626 * gl_ClipVertex.
627 */
628 if (!prog->IsES) {
629 if (gl_ClipVertex.found && gl_ClipDistance.found) {
630 linker_error(prog, "%s shader writes to both `gl_ClipVertex' "
631 "and `gl_ClipDistance'\n",
632 _mesa_shader_stage_to_string(shader->Stage));
633 return;
634 }
635 if (gl_ClipVertex.found && gl_CullDistance.found) {
636 linker_error(prog, "%s shader writes to both `gl_ClipVertex' "
637 "and `gl_CullDistance'\n",
638 _mesa_shader_stage_to_string(shader->Stage));
639 return;
640 }
641 }
642
643 if (gl_ClipDistance.found) {
644 ir_variable *clip_distance_var =
645 shader->symbols->get_variable("gl_ClipDistance");
646 assert(clip_distance_var);
647 info->clip_distance_array_size = clip_distance_var->type->length;
648 }
649 if (gl_CullDistance.found) {
650 ir_variable *cull_distance_var =
651 shader->symbols->get_variable("gl_CullDistance");
652 assert(cull_distance_var);
653 info->cull_distance_array_size = cull_distance_var->type->length;
654 }
655 /* From the ARB_cull_distance spec:
656 *
657 * It is a compile-time or link-time error for the set of shaders forming
658 * a program to have the sum of the sizes of the gl_ClipDistance and
659 * gl_CullDistance arrays to be larger than
660 * gl_MaxCombinedClipAndCullDistances.
661 */
662 if ((uint32_t)(info->clip_distance_array_size + info->cull_distance_array_size) >
663 ctx->Const.MaxClipPlanes) {
664 linker_error(prog, "%s shader: the combined size of "
665 "'gl_ClipDistance' and 'gl_CullDistance' size cannot "
666 "be larger than "
667 "gl_MaxCombinedClipAndCullDistances (%u)",
668 _mesa_shader_stage_to_string(shader->Stage),
669 ctx->Const.MaxClipPlanes);
670 }
671 }
672 }
673
674
675 /**
676 * Verify that a vertex shader executable meets all semantic requirements.
677 *
678 * Also sets info.clip_distance_array_size and
679 * info.cull_distance_array_size as a side effect.
680 *
681 * \param shader Vertex shader executable to be verified
682 */
683 static void
684 validate_vertex_shader_executable(struct gl_shader_program *prog,
685 struct gl_linked_shader *shader,
686 struct gl_context *ctx)
687 {
688 if (shader == NULL)
689 return;
690
691 /* From the GLSL 1.10 spec, page 48:
692 *
693 * "The variable gl_Position is available only in the vertex
694 * language and is intended for writing the homogeneous vertex
695 * position. All executions of a well-formed vertex shader
696 * executable must write a value into this variable. [...] The
697 * variable gl_Position is available only in the vertex
698 * language and is intended for writing the homogeneous vertex
699 * position. All executions of a well-formed vertex shader
700 * executable must write a value into this variable."
701 *
702 * while in GLSL 1.40 this text is changed to:
703 *
704 * "The variable gl_Position is available only in the vertex
705 * language and is intended for writing the homogeneous vertex
706 * position. It can be written at any time during shader
707 * execution. It may also be read back by a vertex shader
708 * after being written. This value will be used by primitive
709 * assembly, clipping, culling, and other fixed functionality
710 * operations, if present, that operate on primitives after
711 * vertex processing has occurred. Its value is undefined if
712 * the vertex shader executable does not write gl_Position."
713 *
714 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
715 * gl_Position is not an error.
716 */
717 if (prog->data->Version < (prog->IsES ? 300 : 140)) {
718 find_variable gl_Position("gl_Position");
719 find_assignments(shader->ir, &gl_Position);
720 if (!gl_Position.found) {
721 if (prog->IsES) {
722 linker_warning(prog,
723 "vertex shader does not write to `gl_Position'. "
724 "Its value is undefined. \n");
725 } else {
726 linker_error(prog,
727 "vertex shader does not write to `gl_Position'. \n");
728 }
729 return;
730 }
731 }
732
733 analyze_clip_cull_usage(prog, shader, ctx, &shader->Program->info);
734 }
735
736 static void
737 validate_tess_eval_shader_executable(struct gl_shader_program *prog,
738 struct gl_linked_shader *shader,
739 struct gl_context *ctx)
740 {
741 if (shader == NULL)
742 return;
743
744 analyze_clip_cull_usage(prog, shader, ctx, &shader->Program->info);
745 }
746
747
748 /**
749 * Verify that a fragment shader executable meets all semantic requirements
750 *
751 * \param shader Fragment shader executable to be verified
752 */
753 static void
754 validate_fragment_shader_executable(struct gl_shader_program *prog,
755 struct gl_linked_shader *shader)
756 {
757 if (shader == NULL)
758 return;
759
760 find_variable gl_FragColor("gl_FragColor");
761 find_variable gl_FragData("gl_FragData");
762 find_variable * const variables[] = { &gl_FragColor, &gl_FragData, NULL };
763 find_assignments(shader->ir, variables);
764
765 if (gl_FragColor.found && gl_FragData.found) {
766 linker_error(prog, "fragment shader writes to both "
767 "`gl_FragColor' and `gl_FragData'\n");
768 }
769 }
770
771 /**
772 * Verify that a geometry shader executable meets all semantic requirements
773 *
774 * Also sets prog->Geom.VerticesIn, and info.clip_distance_array_sizeand
775 * info.cull_distance_array_size as a side effect.
776 *
777 * \param shader Geometry shader executable to be verified
778 */
779 static void
780 validate_geometry_shader_executable(struct gl_shader_program *prog,
781 struct gl_linked_shader *shader,
782 struct gl_context *ctx)
783 {
784 if (shader == NULL)
785 return;
786
787 unsigned num_vertices =
788 vertices_per_prim(shader->Program->info.gs.input_primitive);
789 prog->Geom.VerticesIn = num_vertices;
790
791 analyze_clip_cull_usage(prog, shader, ctx, &shader->Program->info);
792 }
793
794 /**
795 * Check if geometry shaders emit to non-zero streams and do corresponding
796 * validations.
797 */
798 static void
799 validate_geometry_shader_emissions(struct gl_context *ctx,
800 struct gl_shader_program *prog)
801 {
802 struct gl_linked_shader *sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
803
804 if (sh != NULL) {
805 find_emit_vertex_visitor emit_vertex(ctx->Const.MaxVertexStreams - 1);
806 emit_vertex.run(sh->ir);
807 if (emit_vertex.error()) {
808 linker_error(prog, "Invalid call %s(%d). Accepted values for the "
809 "stream parameter are in the range [0, %d].\n",
810 emit_vertex.error_func(),
811 emit_vertex.error_stream(),
812 ctx->Const.MaxVertexStreams - 1);
813 }
814 prog->Geom.UsesStreams = emit_vertex.uses_streams();
815 prog->Geom.UsesEndPrimitive = emit_vertex.uses_end_primitive();
816
817 /* From the ARB_gpu_shader5 spec:
818 *
819 * "Multiple vertex streams are supported only if the output primitive
820 * type is declared to be "points". A program will fail to link if it
821 * contains a geometry shader calling EmitStreamVertex() or
822 * EndStreamPrimitive() if its output primitive type is not "points".
823 *
824 * However, in the same spec:
825 *
826 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
827 * with <stream> set to zero."
828 *
829 * And:
830 *
831 * "The function EndPrimitive() is equivalent to calling
832 * EndStreamPrimitive() with <stream> set to zero."
833 *
834 * Since we can call EmitVertex() and EndPrimitive() when we output
835 * primitives other than points, calling EmitStreamVertex(0) or
836 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
837 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
838 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
839 * stream.
840 */
841 if (prog->Geom.UsesStreams &&
842 sh->Program->info.gs.output_primitive != GL_POINTS) {
843 linker_error(prog, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
844 "with n>0 requires point output\n");
845 }
846 }
847 }
848
849 bool
850 validate_intrastage_arrays(struct gl_shader_program *prog,
851 ir_variable *const var,
852 ir_variable *const existing,
853 bool match_precision)
854 {
855 /* Consider the types to be "the same" if both types are arrays
856 * of the same type and one of the arrays is implicitly sized.
857 * In addition, set the type of the linked variable to the
858 * explicitly sized array.
859 */
860 if (var->type->is_array() && existing->type->is_array()) {
861 const glsl_type *no_array_var = var->type->fields.array;
862 const glsl_type *no_array_existing = existing->type->fields.array;
863 bool type_matches;
864
865 type_matches = (match_precision ?
866 no_array_var == no_array_existing :
867 no_array_var->compare_no_precision(no_array_existing));
868
869 if (type_matches &&
870 ((var->type->length == 0)|| (existing->type->length == 0))) {
871 if (var->type->length != 0) {
872 if ((int)var->type->length <= existing->data.max_array_access) {
873 linker_error(prog, "%s `%s' declared as type "
874 "`%s' but outermost dimension has an index"
875 " of `%i'\n",
876 mode_string(var),
877 var->name, var->type->name,
878 existing->data.max_array_access);
879 }
880 existing->type = var->type;
881 return true;
882 } else if (existing->type->length != 0) {
883 if((int)existing->type->length <= var->data.max_array_access &&
884 !existing->data.from_ssbo_unsized_array) {
885 linker_error(prog, "%s `%s' declared as type "
886 "`%s' but outermost dimension has an index"
887 " of `%i'\n",
888 mode_string(var),
889 var->name, existing->type->name,
890 var->data.max_array_access);
891 }
892 return true;
893 }
894 }
895 }
896 return false;
897 }
898
899
900 /**
901 * Perform validation of global variables used across multiple shaders
902 */
903 static void
904 cross_validate_globals(struct gl_context *ctx, struct gl_shader_program *prog,
905 struct exec_list *ir, glsl_symbol_table *variables,
906 bool uniforms_only)
907 {
908 foreach_in_list(ir_instruction, node, ir) {
909 ir_variable *const var = node->as_variable();
910
911 if (var == NULL)
912 continue;
913
914 if (uniforms_only && (var->data.mode != ir_var_uniform && var->data.mode != ir_var_shader_storage))
915 continue;
916
917 /* don't cross validate subroutine uniforms */
918 if (var->type->contains_subroutine())
919 continue;
920
921 /* Don't cross validate interface instances. These are only relevant
922 * inside a shader. The cross validation is done at the Interface Block
923 * name level.
924 */
925 if (var->is_interface_instance())
926 continue;
927
928 /* Don't cross validate temporaries that are at global scope. These
929 * will eventually get pulled into the shaders 'main'.
930 */
931 if (var->data.mode == ir_var_temporary)
932 continue;
933
934 /* If a global with this name has already been seen, verify that the
935 * new instance has the same type. In addition, if the globals have
936 * initializers, the values of the initializers must be the same.
937 */
938 ir_variable *const existing = variables->get_variable(var->name);
939 if (existing != NULL) {
940 /* Check if types match. */
941 if (var->type != existing->type) {
942 if (!validate_intrastage_arrays(prog, var, existing)) {
943 /* If it is an unsized array in a Shader Storage Block,
944 * two different shaders can access to different elements.
945 * Because of that, they might be converted to different
946 * sized arrays, then check that they are compatible but
947 * ignore the array size.
948 */
949 if (!(var->data.mode == ir_var_shader_storage &&
950 var->data.from_ssbo_unsized_array &&
951 existing->data.mode == ir_var_shader_storage &&
952 existing->data.from_ssbo_unsized_array &&
953 var->type->gl_type == existing->type->gl_type)) {
954 linker_error(prog, "%s `%s' declared as type "
955 "`%s' and type `%s'\n",
956 mode_string(var),
957 var->name, var->type->name,
958 existing->type->name);
959 return;
960 }
961 }
962 }
963
964 if (var->data.explicit_location) {
965 if (existing->data.explicit_location
966 && (var->data.location != existing->data.location)) {
967 linker_error(prog, "explicit locations for %s "
968 "`%s' have differing values\n",
969 mode_string(var), var->name);
970 return;
971 }
972
973 if (var->data.location_frac != existing->data.location_frac) {
974 linker_error(prog, "explicit components for %s `%s' have "
975 "differing values\n", mode_string(var), var->name);
976 return;
977 }
978
979 existing->data.location = var->data.location;
980 existing->data.explicit_location = true;
981 } else {
982 /* Check if uniform with implicit location was marked explicit
983 * by earlier shader stage. If so, mark it explicit in this stage
984 * too to make sure later processing does not treat it as
985 * implicit one.
986 */
987 if (existing->data.explicit_location) {
988 var->data.location = existing->data.location;
989 var->data.explicit_location = true;
990 }
991 }
992
993 /* From the GLSL 4.20 specification:
994 * "A link error will result if two compilation units in a program
995 * specify different integer-constant bindings for the same
996 * opaque-uniform name. However, it is not an error to specify a
997 * binding on some but not all declarations for the same name"
998 */
999 if (var->data.explicit_binding) {
1000 if (existing->data.explicit_binding &&
1001 var->data.binding != existing->data.binding) {
1002 linker_error(prog, "explicit bindings for %s "
1003 "`%s' have differing values\n",
1004 mode_string(var), var->name);
1005 return;
1006 }
1007
1008 existing->data.binding = var->data.binding;
1009 existing->data.explicit_binding = true;
1010 }
1011
1012 if (var->type->contains_atomic() &&
1013 var->data.offset != existing->data.offset) {
1014 linker_error(prog, "offset specifications for %s "
1015 "`%s' have differing values\n",
1016 mode_string(var), var->name);
1017 return;
1018 }
1019
1020 /* Validate layout qualifiers for gl_FragDepth.
1021 *
1022 * From the AMD/ARB_conservative_depth specs:
1023 *
1024 * "If gl_FragDepth is redeclared in any fragment shader in a
1025 * program, it must be redeclared in all fragment shaders in
1026 * that program that have static assignments to
1027 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1028 * fragment shaders in a single program must have the same set
1029 * of qualifiers."
1030 */
1031 if (strcmp(var->name, "gl_FragDepth") == 0) {
1032 bool layout_declared = var->data.depth_layout != ir_depth_layout_none;
1033 bool layout_differs =
1034 var->data.depth_layout != existing->data.depth_layout;
1035
1036 if (layout_declared && layout_differs) {
1037 linker_error(prog,
1038 "All redeclarations of gl_FragDepth in all "
1039 "fragment shaders in a single program must have "
1040 "the same set of qualifiers.\n");
1041 }
1042
1043 if (var->data.used && layout_differs) {
1044 linker_error(prog,
1045 "If gl_FragDepth is redeclared with a layout "
1046 "qualifier in any fragment shader, it must be "
1047 "redeclared with the same layout qualifier in "
1048 "all fragment shaders that have assignments to "
1049 "gl_FragDepth\n");
1050 }
1051 }
1052
1053 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1054 *
1055 * "If a shared global has multiple initializers, the
1056 * initializers must all be constant expressions, and they
1057 * must all have the same value. Otherwise, a link error will
1058 * result. (A shared global having only one initializer does
1059 * not require that initializer to be a constant expression.)"
1060 *
1061 * Previous to 4.20 the GLSL spec simply said that initializers
1062 * must have the same value. In this case of non-constant
1063 * initializers, this was impossible to determine. As a result,
1064 * no vendor actually implemented that behavior. The 4.20
1065 * behavior matches the implemented behavior of at least one other
1066 * vendor, so we'll implement that for all GLSL versions.
1067 */
1068 if (var->constant_initializer != NULL) {
1069 if (existing->constant_initializer != NULL) {
1070 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
1071 linker_error(prog, "initializers for %s "
1072 "`%s' have differing values\n",
1073 mode_string(var), var->name);
1074 return;
1075 }
1076 } else {
1077 /* If the first-seen instance of a particular uniform did
1078 * not have an initializer but a later instance does,
1079 * replace the former with the later.
1080 */
1081 variables->replace_variable(existing->name, var);
1082 }
1083 }
1084
1085 if (var->data.has_initializer) {
1086 if (existing->data.has_initializer
1087 && (var->constant_initializer == NULL
1088 || existing->constant_initializer == NULL)) {
1089 linker_error(prog,
1090 "shared global variable `%s' has multiple "
1091 "non-constant initializers.\n",
1092 var->name);
1093 return;
1094 }
1095 }
1096
1097 if (existing->data.explicit_invariant != var->data.explicit_invariant) {
1098 linker_error(prog, "declarations for %s `%s' have "
1099 "mismatching invariant qualifiers\n",
1100 mode_string(var), var->name);
1101 return;
1102 }
1103 if (existing->data.centroid != var->data.centroid) {
1104 linker_error(prog, "declarations for %s `%s' have "
1105 "mismatching centroid qualifiers\n",
1106 mode_string(var), var->name);
1107 return;
1108 }
1109 if (existing->data.sample != var->data.sample) {
1110 linker_error(prog, "declarations for %s `%s` have "
1111 "mismatching sample qualifiers\n",
1112 mode_string(var), var->name);
1113 return;
1114 }
1115 if (existing->data.image_format != var->data.image_format) {
1116 linker_error(prog, "declarations for %s `%s` have "
1117 "mismatching image format qualifiers\n",
1118 mode_string(var), var->name);
1119 return;
1120 }
1121
1122 /* Check the precision qualifier matches for uniform variables on
1123 * GLSL ES.
1124 */
1125 if (!ctx->Const.AllowGLSLRelaxedES &&
1126 prog->IsES && !var->get_interface_type() &&
1127 existing->data.precision != var->data.precision) {
1128 if ((existing->data.used && var->data.used) || prog->data->Version >= 300) {
1129 linker_error(prog, "declarations for %s `%s` have "
1130 "mismatching precision qualifiers\n",
1131 mode_string(var), var->name);
1132 return;
1133 } else {
1134 linker_warning(prog, "declarations for %s `%s` have "
1135 "mismatching precision qualifiers\n",
1136 mode_string(var), var->name);
1137 }
1138 }
1139
1140 /* In OpenGL GLSL 3.20 spec, section 4.3.9:
1141 *
1142 * "It is a link-time error if any particular shader interface
1143 * contains:
1144 *
1145 * - two different blocks, each having no instance name, and each
1146 * having a member of the same name, or
1147 *
1148 * - a variable outside a block, and a block with no instance name,
1149 * where the variable has the same name as a member in the block."
1150 */
1151 const glsl_type *var_itype = var->get_interface_type();
1152 const glsl_type *existing_itype = existing->get_interface_type();
1153 if (var_itype != existing_itype) {
1154 if (!var_itype || !existing_itype) {
1155 linker_error(prog, "declarations for %s `%s` are inside block "
1156 "`%s` and outside a block",
1157 mode_string(var), var->name,
1158 var_itype ? var_itype->name : existing_itype->name);
1159 return;
1160 } else if (strcmp(var_itype->name, existing_itype->name) != 0) {
1161 linker_error(prog, "declarations for %s `%s` are inside blocks "
1162 "`%s` and `%s`",
1163 mode_string(var), var->name,
1164 existing_itype->name,
1165 var_itype->name);
1166 return;
1167 }
1168 }
1169 } else
1170 variables->add_variable(var);
1171 }
1172 }
1173
1174
1175 /**
1176 * Perform validation of uniforms used across multiple shader stages
1177 */
1178 static void
1179 cross_validate_uniforms(struct gl_context *ctx,
1180 struct gl_shader_program *prog)
1181 {
1182 glsl_symbol_table variables;
1183 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1184 if (prog->_LinkedShaders[i] == NULL)
1185 continue;
1186
1187 cross_validate_globals(ctx, prog, prog->_LinkedShaders[i]->ir,
1188 &variables, true);
1189 }
1190 }
1191
1192 /**
1193 * Accumulates the array of buffer blocks and checks that all definitions of
1194 * blocks agree on their contents.
1195 */
1196 static bool
1197 interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog,
1198 bool validate_ssbo)
1199 {
1200 int *InterfaceBlockStageIndex[MESA_SHADER_STAGES];
1201 struct gl_uniform_block *blks = NULL;
1202 unsigned *num_blks = validate_ssbo ? &prog->data->NumShaderStorageBlocks :
1203 &prog->data->NumUniformBlocks;
1204
1205 unsigned max_num_buffer_blocks = 0;
1206 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1207 if (prog->_LinkedShaders[i]) {
1208 if (validate_ssbo) {
1209 max_num_buffer_blocks +=
1210 prog->_LinkedShaders[i]->Program->info.num_ssbos;
1211 } else {
1212 max_num_buffer_blocks +=
1213 prog->_LinkedShaders[i]->Program->info.num_ubos;
1214 }
1215 }
1216 }
1217
1218 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1219 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
1220
1221 InterfaceBlockStageIndex[i] = new int[max_num_buffer_blocks];
1222 for (unsigned int j = 0; j < max_num_buffer_blocks; j++)
1223 InterfaceBlockStageIndex[i][j] = -1;
1224
1225 if (sh == NULL)
1226 continue;
1227
1228 unsigned sh_num_blocks;
1229 struct gl_uniform_block **sh_blks;
1230 if (validate_ssbo) {
1231 sh_num_blocks = prog->_LinkedShaders[i]->Program->info.num_ssbos;
1232 sh_blks = sh->Program->sh.ShaderStorageBlocks;
1233 } else {
1234 sh_num_blocks = prog->_LinkedShaders[i]->Program->info.num_ubos;
1235 sh_blks = sh->Program->sh.UniformBlocks;
1236 }
1237
1238 for (unsigned int j = 0; j < sh_num_blocks; j++) {
1239 int index = link_cross_validate_uniform_block(prog->data, &blks,
1240 num_blks, sh_blks[j]);
1241
1242 if (index == -1) {
1243 linker_error(prog, "buffer block `%s' has mismatching "
1244 "definitions\n", sh_blks[j]->Name);
1245
1246 for (unsigned k = 0; k <= i; k++) {
1247 delete[] InterfaceBlockStageIndex[k];
1248 }
1249
1250 /* Reset the block count. This will help avoid various segfaults
1251 * from api calls that assume the array exists due to the count
1252 * being non-zero.
1253 */
1254 *num_blks = 0;
1255 return false;
1256 }
1257
1258 InterfaceBlockStageIndex[i][index] = j;
1259 }
1260 }
1261
1262 /* Update per stage block pointers to point to the program list.
1263 * FIXME: We should be able to free the per stage blocks here.
1264 */
1265 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1266 for (unsigned j = 0; j < *num_blks; j++) {
1267 int stage_index = InterfaceBlockStageIndex[i][j];
1268
1269 if (stage_index != -1) {
1270 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
1271
1272 struct gl_uniform_block **sh_blks = validate_ssbo ?
1273 sh->Program->sh.ShaderStorageBlocks :
1274 sh->Program->sh.UniformBlocks;
1275
1276 blks[j].stageref |= sh_blks[stage_index]->stageref;
1277 sh_blks[stage_index] = &blks[j];
1278 }
1279 }
1280 }
1281
1282 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1283 delete[] InterfaceBlockStageIndex[i];
1284 }
1285
1286 if (validate_ssbo)
1287 prog->data->ShaderStorageBlocks = blks;
1288 else
1289 prog->data->UniformBlocks = blks;
1290
1291 return true;
1292 }
1293
1294 /**
1295 * Verifies the invariance of built-in special variables.
1296 */
1297 static bool
1298 validate_invariant_builtins(struct gl_shader_program *prog,
1299 const gl_linked_shader *vert,
1300 const gl_linked_shader *frag)
1301 {
1302 const ir_variable *var_vert;
1303 const ir_variable *var_frag;
1304
1305 if (!vert || !frag)
1306 return true;
1307
1308 /*
1309 * From OpenGL ES Shading Language 1.0 specification
1310 * (4.6.4 Invariance and Linkage):
1311 * "The invariance of varyings that are declared in both the vertex and
1312 * fragment shaders must match. For the built-in special variables,
1313 * gl_FragCoord can only be declared invariant if and only if
1314 * gl_Position is declared invariant. Similarly gl_PointCoord can only
1315 * be declared invariant if and only if gl_PointSize is declared
1316 * invariant. It is an error to declare gl_FrontFacing as invariant.
1317 * The invariance of gl_FrontFacing is the same as the invariance of
1318 * gl_Position."
1319 */
1320 var_frag = frag->symbols->get_variable("gl_FragCoord");
1321 if (var_frag && var_frag->data.invariant) {
1322 var_vert = vert->symbols->get_variable("gl_Position");
1323 if (var_vert && !var_vert->data.invariant) {
1324 linker_error(prog,
1325 "fragment shader built-in `%s' has invariant qualifier, "
1326 "but vertex shader built-in `%s' lacks invariant qualifier\n",
1327 var_frag->name, var_vert->name);
1328 return false;
1329 }
1330 }
1331
1332 var_frag = frag->symbols->get_variable("gl_PointCoord");
1333 if (var_frag && var_frag->data.invariant) {
1334 var_vert = vert->symbols->get_variable("gl_PointSize");
1335 if (var_vert && !var_vert->data.invariant) {
1336 linker_error(prog,
1337 "fragment shader built-in `%s' has invariant qualifier, "
1338 "but vertex shader built-in `%s' lacks invariant qualifier\n",
1339 var_frag->name, var_vert->name);
1340 return false;
1341 }
1342 }
1343
1344 var_frag = frag->symbols->get_variable("gl_FrontFacing");
1345 if (var_frag && var_frag->data.invariant) {
1346 linker_error(prog,
1347 "fragment shader built-in `%s' can not be declared as invariant\n",
1348 var_frag->name);
1349 return false;
1350 }
1351
1352 return true;
1353 }
1354
1355 /**
1356 * Populates a shaders symbol table with all global declarations
1357 */
1358 static void
1359 populate_symbol_table(gl_linked_shader *sh, glsl_symbol_table *symbols)
1360 {
1361 sh->symbols = new(sh) glsl_symbol_table;
1362
1363 _mesa_glsl_copy_symbols_from_table(sh->ir, symbols, sh->symbols);
1364 }
1365
1366
1367 /**
1368 * Remap variables referenced in an instruction tree
1369 *
1370 * This is used when instruction trees are cloned from one shader and placed in
1371 * another. These trees will contain references to \c ir_variable nodes that
1372 * do not exist in the target shader. This function finds these \c ir_variable
1373 * references and replaces the references with matching variables in the target
1374 * shader.
1375 *
1376 * If there is no matching variable in the target shader, a clone of the
1377 * \c ir_variable is made and added to the target shader. The new variable is
1378 * added to \b both the instruction stream and the symbol table.
1379 *
1380 * \param inst IR tree that is to be processed.
1381 * \param symbols Symbol table containing global scope symbols in the
1382 * linked shader.
1383 * \param instructions Instruction stream where new variable declarations
1384 * should be added.
1385 */
1386 static void
1387 remap_variables(ir_instruction *inst, struct gl_linked_shader *target,
1388 hash_table *temps)
1389 {
1390 class remap_visitor : public ir_hierarchical_visitor {
1391 public:
1392 remap_visitor(struct gl_linked_shader *target, hash_table *temps)
1393 {
1394 this->target = target;
1395 this->symbols = target->symbols;
1396 this->instructions = target->ir;
1397 this->temps = temps;
1398 }
1399
1400 virtual ir_visitor_status visit(ir_dereference_variable *ir)
1401 {
1402 if (ir->var->data.mode == ir_var_temporary) {
1403 hash_entry *entry = _mesa_hash_table_search(temps, ir->var);
1404 ir_variable *var = entry ? (ir_variable *) entry->data : NULL;
1405
1406 assert(var != NULL);
1407 ir->var = var;
1408 return visit_continue;
1409 }
1410
1411 ir_variable *const existing =
1412 this->symbols->get_variable(ir->var->name);
1413 if (existing != NULL)
1414 ir->var = existing;
1415 else {
1416 ir_variable *copy = ir->var->clone(this->target, NULL);
1417
1418 this->symbols->add_variable(copy);
1419 this->instructions->push_head(copy);
1420 ir->var = copy;
1421 }
1422
1423 return visit_continue;
1424 }
1425
1426 private:
1427 struct gl_linked_shader *target;
1428 glsl_symbol_table *symbols;
1429 exec_list *instructions;
1430 hash_table *temps;
1431 };
1432
1433 remap_visitor v(target, temps);
1434
1435 inst->accept(&v);
1436 }
1437
1438
1439 /**
1440 * Move non-declarations from one instruction stream to another
1441 *
1442 * The intended usage pattern of this function is to pass the pointer to the
1443 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1444 * pointer) for \c last and \c false for \c make_copies on the first
1445 * call. Successive calls pass the return value of the previous call for
1446 * \c last and \c true for \c make_copies.
1447 *
1448 * \param instructions Source instruction stream
1449 * \param last Instruction after which new instructions should be
1450 * inserted in the target instruction stream
1451 * \param make_copies Flag selecting whether instructions in \c instructions
1452 * should be copied (via \c ir_instruction::clone) into the
1453 * target list or moved.
1454 *
1455 * \return
1456 * The new "last" instruction in the target instruction stream. This pointer
1457 * is suitable for use as the \c last parameter of a later call to this
1458 * function.
1459 */
1460 static exec_node *
1461 move_non_declarations(exec_list *instructions, exec_node *last,
1462 bool make_copies, gl_linked_shader *target)
1463 {
1464 hash_table *temps = NULL;
1465
1466 if (make_copies)
1467 temps = _mesa_pointer_hash_table_create(NULL);
1468
1469 foreach_in_list_safe(ir_instruction, inst, instructions) {
1470 if (inst->as_function())
1471 continue;
1472
1473 ir_variable *var = inst->as_variable();
1474 if ((var != NULL) && (var->data.mode != ir_var_temporary))
1475 continue;
1476
1477 assert(inst->as_assignment()
1478 || inst->as_call()
1479 || inst->as_if() /* for initializers with the ?: operator */
1480 || ((var != NULL) && (var->data.mode == ir_var_temporary)));
1481
1482 if (make_copies) {
1483 inst = inst->clone(target, NULL);
1484
1485 if (var != NULL)
1486 _mesa_hash_table_insert(temps, var, inst);
1487 else
1488 remap_variables(inst, target, temps);
1489 } else {
1490 inst->remove();
1491 }
1492
1493 last->insert_after(inst);
1494 last = inst;
1495 }
1496
1497 if (make_copies)
1498 _mesa_hash_table_destroy(temps, NULL);
1499
1500 return last;
1501 }
1502
1503
1504 /**
1505 * This class is only used in link_intrastage_shaders() below but declaring
1506 * it inside that function leads to compiler warnings with some versions of
1507 * gcc.
1508 */
1509 class array_sizing_visitor : public deref_type_updater {
1510 public:
1511 using deref_type_updater::visit;
1512
1513 array_sizing_visitor()
1514 : mem_ctx(ralloc_context(NULL)),
1515 unnamed_interfaces(_mesa_pointer_hash_table_create(NULL))
1516 {
1517 }
1518
1519 ~array_sizing_visitor()
1520 {
1521 _mesa_hash_table_destroy(this->unnamed_interfaces, NULL);
1522 ralloc_free(this->mem_ctx);
1523 }
1524
1525 virtual ir_visitor_status visit(ir_variable *var)
1526 {
1527 const glsl_type *type_without_array;
1528 bool implicit_sized_array = var->data.implicit_sized_array;
1529 fixup_type(&var->type, var->data.max_array_access,
1530 var->data.from_ssbo_unsized_array,
1531 &implicit_sized_array);
1532 var->data.implicit_sized_array = implicit_sized_array;
1533 type_without_array = var->type->without_array();
1534 if (var->type->is_interface()) {
1535 if (interface_contains_unsized_arrays(var->type)) {
1536 const glsl_type *new_type =
1537 resize_interface_members(var->type,
1538 var->get_max_ifc_array_access(),
1539 var->is_in_shader_storage_block());
1540 var->type = new_type;
1541 var->change_interface_type(new_type);
1542 }
1543 } else if (type_without_array->is_interface()) {
1544 if (interface_contains_unsized_arrays(type_without_array)) {
1545 const glsl_type *new_type =
1546 resize_interface_members(type_without_array,
1547 var->get_max_ifc_array_access(),
1548 var->is_in_shader_storage_block());
1549 var->change_interface_type(new_type);
1550 var->type = update_interface_members_array(var->type, new_type);
1551 }
1552 } else if (const glsl_type *ifc_type = var->get_interface_type()) {
1553 /* Store a pointer to the variable in the unnamed_interfaces
1554 * hashtable.
1555 */
1556 hash_entry *entry =
1557 _mesa_hash_table_search(this->unnamed_interfaces,
1558 ifc_type);
1559
1560 ir_variable **interface_vars = entry ? (ir_variable **) entry->data : NULL;
1561
1562 if (interface_vars == NULL) {
1563 interface_vars = rzalloc_array(mem_ctx, ir_variable *,
1564 ifc_type->length);
1565 _mesa_hash_table_insert(this->unnamed_interfaces, ifc_type,
1566 interface_vars);
1567 }
1568 unsigned index = ifc_type->field_index(var->name);
1569 assert(index < ifc_type->length);
1570 assert(interface_vars[index] == NULL);
1571 interface_vars[index] = var;
1572 }
1573 return visit_continue;
1574 }
1575
1576 /**
1577 * For each unnamed interface block that was discovered while running the
1578 * visitor, adjust the interface type to reflect the newly assigned array
1579 * sizes, and fix up the ir_variable nodes to point to the new interface
1580 * type.
1581 */
1582 void fixup_unnamed_interface_types()
1583 {
1584 hash_table_call_foreach(this->unnamed_interfaces,
1585 fixup_unnamed_interface_type, NULL);
1586 }
1587
1588 private:
1589 /**
1590 * If the type pointed to by \c type represents an unsized array, replace
1591 * it with a sized array whose size is determined by max_array_access.
1592 */
1593 static void fixup_type(const glsl_type **type, unsigned max_array_access,
1594 bool from_ssbo_unsized_array, bool *implicit_sized)
1595 {
1596 if (!from_ssbo_unsized_array && (*type)->is_unsized_array()) {
1597 *type = glsl_type::get_array_instance((*type)->fields.array,
1598 max_array_access + 1);
1599 *implicit_sized = true;
1600 assert(*type != NULL);
1601 }
1602 }
1603
1604 static const glsl_type *
1605 update_interface_members_array(const glsl_type *type,
1606 const glsl_type *new_interface_type)
1607 {
1608 const glsl_type *element_type = type->fields.array;
1609 if (element_type->is_array()) {
1610 const glsl_type *new_array_type =
1611 update_interface_members_array(element_type, new_interface_type);
1612 return glsl_type::get_array_instance(new_array_type, type->length);
1613 } else {
1614 return glsl_type::get_array_instance(new_interface_type,
1615 type->length);
1616 }
1617 }
1618
1619 /**
1620 * Determine whether the given interface type contains unsized arrays (if
1621 * it doesn't, array_sizing_visitor doesn't need to process it).
1622 */
1623 static bool interface_contains_unsized_arrays(const glsl_type *type)
1624 {
1625 for (unsigned i = 0; i < type->length; i++) {
1626 const glsl_type *elem_type = type->fields.structure[i].type;
1627 if (elem_type->is_unsized_array())
1628 return true;
1629 }
1630 return false;
1631 }
1632
1633 /**
1634 * Create a new interface type based on the given type, with unsized arrays
1635 * replaced by sized arrays whose size is determined by
1636 * max_ifc_array_access.
1637 */
1638 static const glsl_type *
1639 resize_interface_members(const glsl_type *type,
1640 const int *max_ifc_array_access,
1641 bool is_ssbo)
1642 {
1643 unsigned num_fields = type->length;
1644 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1645 memcpy(fields, type->fields.structure,
1646 num_fields * sizeof(*fields));
1647 for (unsigned i = 0; i < num_fields; i++) {
1648 bool implicit_sized_array = fields[i].implicit_sized_array;
1649 /* If SSBO last member is unsized array, we don't replace it by a sized
1650 * array.
1651 */
1652 if (is_ssbo && i == (num_fields - 1))
1653 fixup_type(&fields[i].type, max_ifc_array_access[i],
1654 true, &implicit_sized_array);
1655 else
1656 fixup_type(&fields[i].type, max_ifc_array_access[i],
1657 false, &implicit_sized_array);
1658 fields[i].implicit_sized_array = implicit_sized_array;
1659 }
1660 glsl_interface_packing packing =
1661 (glsl_interface_packing) type->interface_packing;
1662 bool row_major = (bool) type->interface_row_major;
1663 const glsl_type *new_ifc_type =
1664 glsl_type::get_interface_instance(fields, num_fields,
1665 packing, row_major, type->name);
1666 delete [] fields;
1667 return new_ifc_type;
1668 }
1669
1670 static void fixup_unnamed_interface_type(const void *key, void *data,
1671 void *)
1672 {
1673 const glsl_type *ifc_type = (const glsl_type *) key;
1674 ir_variable **interface_vars = (ir_variable **) data;
1675 unsigned num_fields = ifc_type->length;
1676 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1677 memcpy(fields, ifc_type->fields.structure,
1678 num_fields * sizeof(*fields));
1679 bool interface_type_changed = false;
1680 for (unsigned i = 0; i < num_fields; i++) {
1681 if (interface_vars[i] != NULL &&
1682 fields[i].type != interface_vars[i]->type) {
1683 fields[i].type = interface_vars[i]->type;
1684 interface_type_changed = true;
1685 }
1686 }
1687 if (!interface_type_changed) {
1688 delete [] fields;
1689 return;
1690 }
1691 glsl_interface_packing packing =
1692 (glsl_interface_packing) ifc_type->interface_packing;
1693 bool row_major = (bool) ifc_type->interface_row_major;
1694 const glsl_type *new_ifc_type =
1695 glsl_type::get_interface_instance(fields, num_fields, packing,
1696 row_major, ifc_type->name);
1697 delete [] fields;
1698 for (unsigned i = 0; i < num_fields; i++) {
1699 if (interface_vars[i] != NULL)
1700 interface_vars[i]->change_interface_type(new_ifc_type);
1701 }
1702 }
1703
1704 /**
1705 * Memory context used to allocate the data in \c unnamed_interfaces.
1706 */
1707 void *mem_ctx;
1708
1709 /**
1710 * Hash table from const glsl_type * to an array of ir_variable *'s
1711 * pointing to the ir_variables constituting each unnamed interface block.
1712 */
1713 hash_table *unnamed_interfaces;
1714 };
1715
1716 static bool
1717 validate_xfb_buffer_stride(struct gl_context *ctx, unsigned idx,
1718 struct gl_shader_program *prog)
1719 {
1720 /* We will validate doubles at a later stage */
1721 if (prog->TransformFeedback.BufferStride[idx] % 4) {
1722 linker_error(prog, "invalid qualifier xfb_stride=%d must be a "
1723 "multiple of 4 or if its applied to a type that is "
1724 "or contains a double a multiple of 8.",
1725 prog->TransformFeedback.BufferStride[idx]);
1726 return false;
1727 }
1728
1729 if (prog->TransformFeedback.BufferStride[idx] / 4 >
1730 ctx->Const.MaxTransformFeedbackInterleavedComponents) {
1731 linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1732 "limit has been exceeded.");
1733 return false;
1734 }
1735
1736 return true;
1737 }
1738
1739 /**
1740 * Check for conflicting xfb_stride default qualifiers and store buffer stride
1741 * for later use.
1742 */
1743 static void
1744 link_xfb_stride_layout_qualifiers(struct gl_context *ctx,
1745 struct gl_shader_program *prog,
1746 struct gl_shader **shader_list,
1747 unsigned num_shaders)
1748 {
1749 for (unsigned i = 0; i < MAX_FEEDBACK_BUFFERS; i++) {
1750 prog->TransformFeedback.BufferStride[i] = 0;
1751 }
1752
1753 for (unsigned i = 0; i < num_shaders; i++) {
1754 struct gl_shader *shader = shader_list[i];
1755
1756 for (unsigned j = 0; j < MAX_FEEDBACK_BUFFERS; j++) {
1757 if (shader->TransformFeedbackBufferStride[j]) {
1758 if (prog->TransformFeedback.BufferStride[j] == 0) {
1759 prog->TransformFeedback.BufferStride[j] =
1760 shader->TransformFeedbackBufferStride[j];
1761 if (!validate_xfb_buffer_stride(ctx, j, prog))
1762 return;
1763 } else if (prog->TransformFeedback.BufferStride[j] !=
1764 shader->TransformFeedbackBufferStride[j]){
1765 linker_error(prog,
1766 "intrastage shaders defined with conflicting "
1767 "xfb_stride for buffer %d (%d and %d)\n", j,
1768 prog->TransformFeedback.BufferStride[j],
1769 shader->TransformFeedbackBufferStride[j]);
1770 return;
1771 }
1772 }
1773 }
1774 }
1775 }
1776
1777 /**
1778 * Check for conflicting bindless/bound sampler/image layout qualifiers at
1779 * global scope.
1780 */
1781 static void
1782 link_bindless_layout_qualifiers(struct gl_shader_program *prog,
1783 struct gl_shader **shader_list,
1784 unsigned num_shaders)
1785 {
1786 bool bindless_sampler, bindless_image;
1787 bool bound_sampler, bound_image;
1788
1789 bindless_sampler = bindless_image = false;
1790 bound_sampler = bound_image = false;
1791
1792 for (unsigned i = 0; i < num_shaders; i++) {
1793 struct gl_shader *shader = shader_list[i];
1794
1795 if (shader->bindless_sampler)
1796 bindless_sampler = true;
1797 if (shader->bindless_image)
1798 bindless_image = true;
1799 if (shader->bound_sampler)
1800 bound_sampler = true;
1801 if (shader->bound_image)
1802 bound_image = true;
1803
1804 if ((bindless_sampler && bound_sampler) ||
1805 (bindless_image && bound_image)) {
1806 /* From section 4.4.6 of the ARB_bindless_texture spec:
1807 *
1808 * "If both bindless_sampler and bound_sampler, or bindless_image
1809 * and bound_image, are declared at global scope in any
1810 * compilation unit, a link- time error will be generated."
1811 */
1812 linker_error(prog, "both bindless_sampler and bound_sampler, or "
1813 "bindless_image and bound_image, can't be declared at "
1814 "global scope");
1815 }
1816 }
1817 }
1818
1819 /**
1820 * Check for conflicting viewport_relative settings across shaders, and sets
1821 * the value for the linked shader.
1822 */
1823 static void
1824 link_layer_viewport_relative_qualifier(struct gl_shader_program *prog,
1825 struct gl_program *gl_prog,
1826 struct gl_shader **shader_list,
1827 unsigned num_shaders)
1828 {
1829 unsigned i;
1830
1831 /* Find first shader with explicit layer declaration */
1832 for (i = 0; i < num_shaders; i++) {
1833 if (shader_list[i]->redeclares_gl_layer) {
1834 gl_prog->info.layer_viewport_relative =
1835 shader_list[i]->layer_viewport_relative;
1836 break;
1837 }
1838 }
1839
1840 /* Now make sure that each subsequent shader's explicit layer declaration
1841 * matches the first one's.
1842 */
1843 for (; i < num_shaders; i++) {
1844 if (shader_list[i]->redeclares_gl_layer &&
1845 shader_list[i]->layer_viewport_relative !=
1846 gl_prog->info.layer_viewport_relative) {
1847 linker_error(prog, "all gl_Layer redeclarations must have identical "
1848 "viewport_relative settings");
1849 }
1850 }
1851 }
1852
1853 /**
1854 * Performs the cross-validation of tessellation control shader vertices and
1855 * layout qualifiers for the attached tessellation control shaders,
1856 * and propagates them to the linked TCS and linked shader program.
1857 */
1858 static void
1859 link_tcs_out_layout_qualifiers(struct gl_shader_program *prog,
1860 struct gl_program *gl_prog,
1861 struct gl_shader **shader_list,
1862 unsigned num_shaders)
1863 {
1864 if (gl_prog->info.stage != MESA_SHADER_TESS_CTRL)
1865 return;
1866
1867 gl_prog->info.tess.tcs_vertices_out = 0;
1868
1869 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1870 *
1871 * "All tessellation control shader layout declarations in a program
1872 * must specify the same output patch vertex count. There must be at
1873 * least one layout qualifier specifying an output patch vertex count
1874 * in any program containing tessellation control shaders; however,
1875 * such a declaration is not required in all tessellation control
1876 * shaders."
1877 */
1878
1879 for (unsigned i = 0; i < num_shaders; i++) {
1880 struct gl_shader *shader = shader_list[i];
1881
1882 if (shader->info.TessCtrl.VerticesOut != 0) {
1883 if (gl_prog->info.tess.tcs_vertices_out != 0 &&
1884 gl_prog->info.tess.tcs_vertices_out !=
1885 (unsigned) shader->info.TessCtrl.VerticesOut) {
1886 linker_error(prog, "tessellation control shader defined with "
1887 "conflicting output vertex count (%d and %d)\n",
1888 gl_prog->info.tess.tcs_vertices_out,
1889 shader->info.TessCtrl.VerticesOut);
1890 return;
1891 }
1892 gl_prog->info.tess.tcs_vertices_out =
1893 shader->info.TessCtrl.VerticesOut;
1894 }
1895 }
1896
1897 /* Just do the intrastage -> interstage propagation right now,
1898 * since we already know we're in the right type of shader program
1899 * for doing it.
1900 */
1901 if (gl_prog->info.tess.tcs_vertices_out == 0) {
1902 linker_error(prog, "tessellation control shader didn't declare "
1903 "vertices out layout qualifier\n");
1904 return;
1905 }
1906 }
1907
1908
1909 /**
1910 * Performs the cross-validation of tessellation evaluation shader
1911 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1912 * for the attached tessellation evaluation shaders, and propagates them
1913 * to the linked TES and linked shader program.
1914 */
1915 static void
1916 link_tes_in_layout_qualifiers(struct gl_shader_program *prog,
1917 struct gl_program *gl_prog,
1918 struct gl_shader **shader_list,
1919 unsigned num_shaders)
1920 {
1921 if (gl_prog->info.stage != MESA_SHADER_TESS_EVAL)
1922 return;
1923
1924 int point_mode = -1;
1925 unsigned vertex_order = 0;
1926
1927 gl_prog->info.tess.primitive_mode = PRIM_UNKNOWN;
1928 gl_prog->info.tess.spacing = TESS_SPACING_UNSPECIFIED;
1929
1930 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1931 *
1932 * "At least one tessellation evaluation shader (compilation unit) in
1933 * a program must declare a primitive mode in its input layout.
1934 * Declaration vertex spacing, ordering, and point mode identifiers is
1935 * optional. It is not required that all tessellation evaluation
1936 * shaders in a program declare a primitive mode. If spacing or
1937 * vertex ordering declarations are omitted, the tessellation
1938 * primitive generator will use equal spacing or counter-clockwise
1939 * vertex ordering, respectively. If a point mode declaration is
1940 * omitted, the tessellation primitive generator will produce lines or
1941 * triangles according to the primitive mode."
1942 */
1943
1944 for (unsigned i = 0; i < num_shaders; i++) {
1945 struct gl_shader *shader = shader_list[i];
1946
1947 if (shader->info.TessEval.PrimitiveMode != PRIM_UNKNOWN) {
1948 if (gl_prog->info.tess.primitive_mode != PRIM_UNKNOWN &&
1949 gl_prog->info.tess.primitive_mode !=
1950 shader->info.TessEval.PrimitiveMode) {
1951 linker_error(prog, "tessellation evaluation shader defined with "
1952 "conflicting input primitive modes.\n");
1953 return;
1954 }
1955 gl_prog->info.tess.primitive_mode =
1956 shader->info.TessEval.PrimitiveMode;
1957 }
1958
1959 if (shader->info.TessEval.Spacing != 0) {
1960 if (gl_prog->info.tess.spacing != 0 && gl_prog->info.tess.spacing !=
1961 shader->info.TessEval.Spacing) {
1962 linker_error(prog, "tessellation evaluation shader defined with "
1963 "conflicting vertex spacing.\n");
1964 return;
1965 }
1966 gl_prog->info.tess.spacing = shader->info.TessEval.Spacing;
1967 }
1968
1969 if (shader->info.TessEval.VertexOrder != 0) {
1970 if (vertex_order != 0 &&
1971 vertex_order != shader->info.TessEval.VertexOrder) {
1972 linker_error(prog, "tessellation evaluation shader defined with "
1973 "conflicting ordering.\n");
1974 return;
1975 }
1976 vertex_order = shader->info.TessEval.VertexOrder;
1977 }
1978
1979 if (shader->info.TessEval.PointMode != -1) {
1980 if (point_mode != -1 &&
1981 point_mode != shader->info.TessEval.PointMode) {
1982 linker_error(prog, "tessellation evaluation shader defined with "
1983 "conflicting point modes.\n");
1984 return;
1985 }
1986 point_mode = shader->info.TessEval.PointMode;
1987 }
1988
1989 }
1990
1991 /* Just do the intrastage -> interstage propagation right now,
1992 * since we already know we're in the right type of shader program
1993 * for doing it.
1994 */
1995 if (gl_prog->info.tess.primitive_mode == PRIM_UNKNOWN) {
1996 linker_error(prog,
1997 "tessellation evaluation shader didn't declare input "
1998 "primitive modes.\n");
1999 return;
2000 }
2001
2002 if (gl_prog->info.tess.spacing == TESS_SPACING_UNSPECIFIED)
2003 gl_prog->info.tess.spacing = TESS_SPACING_EQUAL;
2004
2005 if (vertex_order == 0 || vertex_order == GL_CCW)
2006 gl_prog->info.tess.ccw = true;
2007 else
2008 gl_prog->info.tess.ccw = false;
2009
2010
2011 if (point_mode == -1 || point_mode == GL_FALSE)
2012 gl_prog->info.tess.point_mode = false;
2013 else
2014 gl_prog->info.tess.point_mode = true;
2015 }
2016
2017
2018 /**
2019 * Performs the cross-validation of layout qualifiers specified in
2020 * redeclaration of gl_FragCoord for the attached fragment shaders,
2021 * and propagates them to the linked FS and linked shader program.
2022 */
2023 static void
2024 link_fs_inout_layout_qualifiers(struct gl_shader_program *prog,
2025 struct gl_linked_shader *linked_shader,
2026 struct gl_shader **shader_list,
2027 unsigned num_shaders)
2028 {
2029 bool redeclares_gl_fragcoord = false;
2030 bool uses_gl_fragcoord = false;
2031 bool origin_upper_left = false;
2032 bool pixel_center_integer = false;
2033
2034 if (linked_shader->Stage != MESA_SHADER_FRAGMENT ||
2035 (prog->data->Version < 150 &&
2036 !prog->ARB_fragment_coord_conventions_enable))
2037 return;
2038
2039 for (unsigned i = 0; i < num_shaders; i++) {
2040 struct gl_shader *shader = shader_list[i];
2041 /* From the GLSL 1.50 spec, page 39:
2042 *
2043 * "If gl_FragCoord is redeclared in any fragment shader in a program,
2044 * it must be redeclared in all the fragment shaders in that program
2045 * that have a static use gl_FragCoord."
2046 */
2047 if ((redeclares_gl_fragcoord && !shader->redeclares_gl_fragcoord &&
2048 shader->uses_gl_fragcoord)
2049 || (shader->redeclares_gl_fragcoord && !redeclares_gl_fragcoord &&
2050 uses_gl_fragcoord)) {
2051 linker_error(prog, "fragment shader defined with conflicting "
2052 "layout qualifiers for gl_FragCoord\n");
2053 }
2054
2055 /* From the GLSL 1.50 spec, page 39:
2056 *
2057 * "All redeclarations of gl_FragCoord in all fragment shaders in a
2058 * single program must have the same set of qualifiers."
2059 */
2060 if (redeclares_gl_fragcoord && shader->redeclares_gl_fragcoord &&
2061 (shader->origin_upper_left != origin_upper_left ||
2062 shader->pixel_center_integer != pixel_center_integer)) {
2063 linker_error(prog, "fragment shader defined with conflicting "
2064 "layout qualifiers for gl_FragCoord\n");
2065 }
2066
2067 /* Update the linked shader state. Note that uses_gl_fragcoord should
2068 * accumulate the results. The other values should replace. If there
2069 * are multiple redeclarations, all the fields except uses_gl_fragcoord
2070 * are already known to be the same.
2071 */
2072 if (shader->redeclares_gl_fragcoord || shader->uses_gl_fragcoord) {
2073 redeclares_gl_fragcoord = shader->redeclares_gl_fragcoord;
2074 uses_gl_fragcoord |= shader->uses_gl_fragcoord;
2075 origin_upper_left = shader->origin_upper_left;
2076 pixel_center_integer = shader->pixel_center_integer;
2077 }
2078
2079 linked_shader->Program->info.fs.early_fragment_tests |=
2080 shader->EarlyFragmentTests || shader->PostDepthCoverage;
2081 linked_shader->Program->info.fs.inner_coverage |= shader->InnerCoverage;
2082 linked_shader->Program->info.fs.post_depth_coverage |=
2083 shader->PostDepthCoverage;
2084 linked_shader->Program->info.fs.pixel_interlock_ordered |=
2085 shader->PixelInterlockOrdered;
2086 linked_shader->Program->info.fs.pixel_interlock_unordered |=
2087 shader->PixelInterlockUnordered;
2088 linked_shader->Program->info.fs.sample_interlock_ordered |=
2089 shader->SampleInterlockOrdered;
2090 linked_shader->Program->info.fs.sample_interlock_unordered |=
2091 shader->SampleInterlockUnordered;
2092 linked_shader->Program->sh.fs.BlendSupport |= shader->BlendSupport;
2093 }
2094
2095 linked_shader->Program->info.fs.pixel_center_integer = pixel_center_integer;
2096 linked_shader->Program->info.fs.origin_upper_left = origin_upper_left;
2097 }
2098
2099 /**
2100 * Performs the cross-validation of geometry shader max_vertices and
2101 * primitive type layout qualifiers for the attached geometry shaders,
2102 * and propagates them to the linked GS and linked shader program.
2103 */
2104 static void
2105 link_gs_inout_layout_qualifiers(struct gl_shader_program *prog,
2106 struct gl_program *gl_prog,
2107 struct gl_shader **shader_list,
2108 unsigned num_shaders)
2109 {
2110 /* No in/out qualifiers defined for anything but GLSL 1.50+
2111 * geometry shaders so far.
2112 */
2113 if (gl_prog->info.stage != MESA_SHADER_GEOMETRY ||
2114 prog->data->Version < 150)
2115 return;
2116
2117 int vertices_out = -1;
2118
2119 gl_prog->info.gs.invocations = 0;
2120 gl_prog->info.gs.input_primitive = PRIM_UNKNOWN;
2121 gl_prog->info.gs.output_primitive = PRIM_UNKNOWN;
2122
2123 /* From the GLSL 1.50 spec, page 46:
2124 *
2125 * "All geometry shader output layout declarations in a program
2126 * must declare the same layout and same value for
2127 * max_vertices. There must be at least one geometry output
2128 * layout declaration somewhere in a program, but not all
2129 * geometry shaders (compilation units) are required to
2130 * declare it."
2131 */
2132
2133 for (unsigned i = 0; i < num_shaders; i++) {
2134 struct gl_shader *shader = shader_list[i];
2135
2136 if (shader->info.Geom.InputType != PRIM_UNKNOWN) {
2137 if (gl_prog->info.gs.input_primitive != PRIM_UNKNOWN &&
2138 gl_prog->info.gs.input_primitive !=
2139 shader->info.Geom.InputType) {
2140 linker_error(prog, "geometry shader defined with conflicting "
2141 "input types\n");
2142 return;
2143 }
2144 gl_prog->info.gs.input_primitive = shader->info.Geom.InputType;
2145 }
2146
2147 if (shader->info.Geom.OutputType != PRIM_UNKNOWN) {
2148 if (gl_prog->info.gs.output_primitive != PRIM_UNKNOWN &&
2149 gl_prog->info.gs.output_primitive !=
2150 shader->info.Geom.OutputType) {
2151 linker_error(prog, "geometry shader defined with conflicting "
2152 "output types\n");
2153 return;
2154 }
2155 gl_prog->info.gs.output_primitive = shader->info.Geom.OutputType;
2156 }
2157
2158 if (shader->info.Geom.VerticesOut != -1) {
2159 if (vertices_out != -1 &&
2160 vertices_out != shader->info.Geom.VerticesOut) {
2161 linker_error(prog, "geometry shader defined with conflicting "
2162 "output vertex count (%d and %d)\n",
2163 vertices_out, shader->info.Geom.VerticesOut);
2164 return;
2165 }
2166 vertices_out = shader->info.Geom.VerticesOut;
2167 }
2168
2169 if (shader->info.Geom.Invocations != 0) {
2170 if (gl_prog->info.gs.invocations != 0 &&
2171 gl_prog->info.gs.invocations !=
2172 (unsigned) shader->info.Geom.Invocations) {
2173 linker_error(prog, "geometry shader defined with conflicting "
2174 "invocation count (%d and %d)\n",
2175 gl_prog->info.gs.invocations,
2176 shader->info.Geom.Invocations);
2177 return;
2178 }
2179 gl_prog->info.gs.invocations = shader->info.Geom.Invocations;
2180 }
2181 }
2182
2183 /* Just do the intrastage -> interstage propagation right now,
2184 * since we already know we're in the right type of shader program
2185 * for doing it.
2186 */
2187 if (gl_prog->info.gs.input_primitive == PRIM_UNKNOWN) {
2188 linker_error(prog,
2189 "geometry shader didn't declare primitive input type\n");
2190 return;
2191 }
2192
2193 if (gl_prog->info.gs.output_primitive == PRIM_UNKNOWN) {
2194 linker_error(prog,
2195 "geometry shader didn't declare primitive output type\n");
2196 return;
2197 }
2198
2199 if (vertices_out == -1) {
2200 linker_error(prog,
2201 "geometry shader didn't declare max_vertices\n");
2202 return;
2203 } else {
2204 gl_prog->info.gs.vertices_out = vertices_out;
2205 }
2206
2207 if (gl_prog->info.gs.invocations == 0)
2208 gl_prog->info.gs.invocations = 1;
2209 }
2210
2211
2212 /**
2213 * Perform cross-validation of compute shader local_size_{x,y,z} layout and
2214 * derivative arrangement qualifiers for the attached compute shaders, and
2215 * propagate them to the linked CS and linked shader program.
2216 */
2217 static void
2218 link_cs_input_layout_qualifiers(struct gl_shader_program *prog,
2219 struct gl_program *gl_prog,
2220 struct gl_shader **shader_list,
2221 unsigned num_shaders)
2222 {
2223 /* This function is called for all shader stages, but it only has an effect
2224 * for compute shaders.
2225 */
2226 if (gl_prog->info.stage != MESA_SHADER_COMPUTE)
2227 return;
2228
2229 for (int i = 0; i < 3; i++)
2230 gl_prog->info.cs.local_size[i] = 0;
2231
2232 gl_prog->info.cs.local_size_variable = false;
2233
2234 gl_prog->info.cs.derivative_group = DERIVATIVE_GROUP_NONE;
2235
2236 /* From the ARB_compute_shader spec, in the section describing local size
2237 * declarations:
2238 *
2239 * If multiple compute shaders attached to a single program object
2240 * declare local work-group size, the declarations must be identical;
2241 * otherwise a link-time error results. Furthermore, if a program
2242 * object contains any compute shaders, at least one must contain an
2243 * input layout qualifier specifying the local work sizes of the
2244 * program, or a link-time error will occur.
2245 */
2246 for (unsigned sh = 0; sh < num_shaders; sh++) {
2247 struct gl_shader *shader = shader_list[sh];
2248
2249 if (shader->info.Comp.LocalSize[0] != 0) {
2250 if (gl_prog->info.cs.local_size[0] != 0) {
2251 for (int i = 0; i < 3; i++) {
2252 if (gl_prog->info.cs.local_size[i] !=
2253 shader->info.Comp.LocalSize[i]) {
2254 linker_error(prog, "compute shader defined with conflicting "
2255 "local sizes\n");
2256 return;
2257 }
2258 }
2259 }
2260 for (int i = 0; i < 3; i++) {
2261 gl_prog->info.cs.local_size[i] =
2262 shader->info.Comp.LocalSize[i];
2263 }
2264 } else if (shader->info.Comp.LocalSizeVariable) {
2265 if (gl_prog->info.cs.local_size[0] != 0) {
2266 /* The ARB_compute_variable_group_size spec says:
2267 *
2268 * If one compute shader attached to a program declares a
2269 * variable local group size and a second compute shader
2270 * attached to the same program declares a fixed local group
2271 * size, a link-time error results.
2272 */
2273 linker_error(prog, "compute shader defined with both fixed and "
2274 "variable local group size\n");
2275 return;
2276 }
2277 gl_prog->info.cs.local_size_variable = true;
2278 }
2279
2280 enum gl_derivative_group group = shader->info.Comp.DerivativeGroup;
2281 if (group != DERIVATIVE_GROUP_NONE) {
2282 if (gl_prog->info.cs.derivative_group != DERIVATIVE_GROUP_NONE &&
2283 gl_prog->info.cs.derivative_group != group) {
2284 linker_error(prog, "compute shader defined with conflicting "
2285 "derivative groups\n");
2286 return;
2287 }
2288 gl_prog->info.cs.derivative_group = group;
2289 }
2290 }
2291
2292 /* Just do the intrastage -> interstage propagation right now,
2293 * since we already know we're in the right type of shader program
2294 * for doing it.
2295 */
2296 if (gl_prog->info.cs.local_size[0] == 0 &&
2297 !gl_prog->info.cs.local_size_variable) {
2298 linker_error(prog, "compute shader must contain a fixed or a variable "
2299 "local group size\n");
2300 return;
2301 }
2302
2303 if (gl_prog->info.cs.derivative_group == DERIVATIVE_GROUP_QUADS) {
2304 if (gl_prog->info.cs.local_size[0] % 2 != 0) {
2305 linker_error(prog, "derivative_group_quadsNV must be used with a "
2306 "local group size whose first dimension "
2307 "is a multiple of 2\n");
2308 return;
2309 }
2310 if (gl_prog->info.cs.local_size[1] % 2 != 0) {
2311 linker_error(prog, "derivative_group_quadsNV must be used with a local"
2312 "group size whose second dimension "
2313 "is a multiple of 2\n");
2314 return;
2315 }
2316 } else if (gl_prog->info.cs.derivative_group == DERIVATIVE_GROUP_LINEAR) {
2317 if ((gl_prog->info.cs.local_size[0] *
2318 gl_prog->info.cs.local_size[1] *
2319 gl_prog->info.cs.local_size[2]) % 4 != 0) {
2320 linker_error(prog, "derivative_group_linearNV must be used with a "
2321 "local group size whose total number of invocations "
2322 "is a multiple of 4\n");
2323 return;
2324 }
2325 }
2326 }
2327
2328 /**
2329 * Link all out variables on a single stage which are not
2330 * directly used in a shader with the main function.
2331 */
2332 static void
2333 link_output_variables(struct gl_linked_shader *linked_shader,
2334 struct gl_shader **shader_list,
2335 unsigned num_shaders)
2336 {
2337 struct glsl_symbol_table *symbols = linked_shader->symbols;
2338
2339 for (unsigned i = 0; i < num_shaders; i++) {
2340
2341 /* Skip shader object with main function */
2342 if (shader_list[i]->symbols->get_function("main"))
2343 continue;
2344
2345 foreach_in_list(ir_instruction, ir, shader_list[i]->ir) {
2346 if (ir->ir_type != ir_type_variable)
2347 continue;
2348
2349 ir_variable *var = (ir_variable *) ir;
2350
2351 if (var->data.mode == ir_var_shader_out &&
2352 !symbols->get_variable(var->name)) {
2353 var = var->clone(linked_shader, NULL);
2354 symbols->add_variable(var);
2355 linked_shader->ir->push_head(var);
2356 }
2357 }
2358 }
2359
2360 return;
2361 }
2362
2363
2364 /**
2365 * Combine a group of shaders for a single stage to generate a linked shader
2366 *
2367 * \note
2368 * If this function is supplied a single shader, it is cloned, and the new
2369 * shader is returned.
2370 */
2371 struct gl_linked_shader *
2372 link_intrastage_shaders(void *mem_ctx,
2373 struct gl_context *ctx,
2374 struct gl_shader_program *prog,
2375 struct gl_shader **shader_list,
2376 unsigned num_shaders,
2377 bool allow_missing_main)
2378 {
2379 struct gl_uniform_block *ubo_blocks = NULL;
2380 struct gl_uniform_block *ssbo_blocks = NULL;
2381 unsigned num_ubo_blocks = 0;
2382 unsigned num_ssbo_blocks = 0;
2383
2384 /* Check that global variables defined in multiple shaders are consistent.
2385 */
2386 glsl_symbol_table variables;
2387 for (unsigned i = 0; i < num_shaders; i++) {
2388 if (shader_list[i] == NULL)
2389 continue;
2390 cross_validate_globals(ctx, prog, shader_list[i]->ir, &variables,
2391 false);
2392 }
2393
2394 if (!prog->data->LinkStatus)
2395 return NULL;
2396
2397 /* Check that interface blocks defined in multiple shaders are consistent.
2398 */
2399 validate_intrastage_interface_blocks(prog, (const gl_shader **)shader_list,
2400 num_shaders);
2401 if (!prog->data->LinkStatus)
2402 return NULL;
2403
2404 /* Check that there is only a single definition of each function signature
2405 * across all shaders.
2406 */
2407 for (unsigned i = 0; i < (num_shaders - 1); i++) {
2408 foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
2409 ir_function *const f = node->as_function();
2410
2411 if (f == NULL)
2412 continue;
2413
2414 for (unsigned j = i + 1; j < num_shaders; j++) {
2415 ir_function *const other =
2416 shader_list[j]->symbols->get_function(f->name);
2417
2418 /* If the other shader has no function (and therefore no function
2419 * signatures) with the same name, skip to the next shader.
2420 */
2421 if (other == NULL)
2422 continue;
2423
2424 foreach_in_list(ir_function_signature, sig, &f->signatures) {
2425 if (!sig->is_defined)
2426 continue;
2427
2428 ir_function_signature *other_sig =
2429 other->exact_matching_signature(NULL, &sig->parameters);
2430
2431 if (other_sig != NULL && other_sig->is_defined) {
2432 linker_error(prog, "function `%s' is multiply defined\n",
2433 f->name);
2434 return NULL;
2435 }
2436 }
2437 }
2438 }
2439 }
2440
2441 /* Find the shader that defines main, and make a clone of it.
2442 *
2443 * Starting with the clone, search for undefined references. If one is
2444 * found, find the shader that defines it. Clone the reference and add
2445 * it to the shader. Repeat until there are no undefined references or
2446 * until a reference cannot be resolved.
2447 */
2448 gl_shader *main = NULL;
2449 for (unsigned i = 0; i < num_shaders; i++) {
2450 if (_mesa_get_main_function_signature(shader_list[i]->symbols)) {
2451 main = shader_list[i];
2452 break;
2453 }
2454 }
2455
2456 if (main == NULL && allow_missing_main)
2457 main = shader_list[0];
2458
2459 if (main == NULL) {
2460 linker_error(prog, "%s shader lacks `main'\n",
2461 _mesa_shader_stage_to_string(shader_list[0]->Stage));
2462 return NULL;
2463 }
2464
2465 gl_linked_shader *linked = rzalloc(NULL, struct gl_linked_shader);
2466 linked->Stage = shader_list[0]->Stage;
2467
2468 /* Create program and attach it to the linked shader */
2469 struct gl_program *gl_prog =
2470 ctx->Driver.NewProgram(ctx,
2471 _mesa_shader_stage_to_program(shader_list[0]->Stage),
2472 prog->Name, false);
2473 if (!gl_prog) {
2474 prog->data->LinkStatus = LINKING_FAILURE;
2475 _mesa_delete_linked_shader(ctx, linked);
2476 return NULL;
2477 }
2478
2479 _mesa_reference_shader_program_data(ctx, &gl_prog->sh.data, prog->data);
2480
2481 /* Don't use _mesa_reference_program() just take ownership */
2482 linked->Program = gl_prog;
2483
2484 linked->ir = new(linked) exec_list;
2485 clone_ir_list(mem_ctx, linked->ir, main->ir);
2486
2487 link_fs_inout_layout_qualifiers(prog, linked, shader_list, num_shaders);
2488 link_tcs_out_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2489 link_tes_in_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2490 link_gs_inout_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2491 link_cs_input_layout_qualifiers(prog, gl_prog, shader_list, num_shaders);
2492
2493 if (linked->Stage != MESA_SHADER_FRAGMENT)
2494 link_xfb_stride_layout_qualifiers(ctx, prog, shader_list, num_shaders);
2495
2496 link_bindless_layout_qualifiers(prog, shader_list, num_shaders);
2497
2498 link_layer_viewport_relative_qualifier(prog, gl_prog, shader_list, num_shaders);
2499
2500 populate_symbol_table(linked, shader_list[0]->symbols);
2501
2502 /* The pointer to the main function in the final linked shader (i.e., the
2503 * copy of the original shader that contained the main function).
2504 */
2505 ir_function_signature *const main_sig =
2506 _mesa_get_main_function_signature(linked->symbols);
2507
2508 /* Move any instructions other than variable declarations or function
2509 * declarations into main.
2510 */
2511 if (main_sig != NULL) {
2512 exec_node *insertion_point =
2513 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
2514 linked);
2515
2516 for (unsigned i = 0; i < num_shaders; i++) {
2517 if (shader_list[i] == main)
2518 continue;
2519
2520 insertion_point = move_non_declarations(shader_list[i]->ir,
2521 insertion_point, true, linked);
2522 }
2523 }
2524
2525 if (!link_function_calls(prog, linked, shader_list, num_shaders)) {
2526 _mesa_delete_linked_shader(ctx, linked);
2527 return NULL;
2528 }
2529
2530 if (linked->Stage != MESA_SHADER_FRAGMENT)
2531 link_output_variables(linked, shader_list, num_shaders);
2532
2533 /* Make a pass over all variable declarations to ensure that arrays with
2534 * unspecified sizes have a size specified. The size is inferred from the
2535 * max_array_access field.
2536 */
2537 array_sizing_visitor v;
2538 v.run(linked->ir);
2539 v.fixup_unnamed_interface_types();
2540
2541 /* Link up uniform blocks defined within this stage. */
2542 link_uniform_blocks(mem_ctx, ctx, prog, linked, &ubo_blocks,
2543 &num_ubo_blocks, &ssbo_blocks, &num_ssbo_blocks);
2544
2545 const unsigned max_uniform_blocks =
2546 ctx->Const.Program[linked->Stage].MaxUniformBlocks;
2547 if (num_ubo_blocks > max_uniform_blocks) {
2548 linker_error(prog, "Too many %s uniform blocks (%d/%d)\n",
2549 _mesa_shader_stage_to_string(linked->Stage),
2550 num_ubo_blocks, max_uniform_blocks);
2551 }
2552
2553 const unsigned max_shader_storage_blocks =
2554 ctx->Const.Program[linked->Stage].MaxShaderStorageBlocks;
2555 if (num_ssbo_blocks > max_shader_storage_blocks) {
2556 linker_error(prog, "Too many %s shader storage blocks (%d/%d)\n",
2557 _mesa_shader_stage_to_string(linked->Stage),
2558 num_ssbo_blocks, max_shader_storage_blocks);
2559 }
2560
2561 if (!prog->data->LinkStatus) {
2562 _mesa_delete_linked_shader(ctx, linked);
2563 return NULL;
2564 }
2565
2566 /* Copy ubo blocks to linked shader list */
2567 linked->Program->sh.UniformBlocks =
2568 ralloc_array(linked, gl_uniform_block *, num_ubo_blocks);
2569 ralloc_steal(linked, ubo_blocks);
2570 for (unsigned i = 0; i < num_ubo_blocks; i++) {
2571 linked->Program->sh.UniformBlocks[i] = &ubo_blocks[i];
2572 }
2573 linked->Program->info.num_ubos = num_ubo_blocks;
2574
2575 /* Copy ssbo blocks to linked shader list */
2576 linked->Program->sh.ShaderStorageBlocks =
2577 ralloc_array(linked, gl_uniform_block *, num_ssbo_blocks);
2578 ralloc_steal(linked, ssbo_blocks);
2579 for (unsigned i = 0; i < num_ssbo_blocks; i++) {
2580 linked->Program->sh.ShaderStorageBlocks[i] = &ssbo_blocks[i];
2581 }
2582 linked->Program->info.num_ssbos = num_ssbo_blocks;
2583
2584 /* At this point linked should contain all of the linked IR, so
2585 * validate it to make sure nothing went wrong.
2586 */
2587 validate_ir_tree(linked->ir);
2588
2589 /* Set the size of geometry shader input arrays */
2590 if (linked->Stage == MESA_SHADER_GEOMETRY) {
2591 unsigned num_vertices =
2592 vertices_per_prim(gl_prog->info.gs.input_primitive);
2593 array_resize_visitor input_resize_visitor(num_vertices, prog,
2594 MESA_SHADER_GEOMETRY);
2595 foreach_in_list(ir_instruction, ir, linked->ir) {
2596 ir->accept(&input_resize_visitor);
2597 }
2598 }
2599
2600 if (ctx->Const.VertexID_is_zero_based)
2601 lower_vertex_id(linked);
2602
2603 if (ctx->Const.LowerCsDerivedVariables)
2604 lower_cs_derived(linked);
2605
2606 #ifdef DEBUG
2607 /* Compute the source checksum. */
2608 linked->SourceChecksum = 0;
2609 for (unsigned i = 0; i < num_shaders; i++) {
2610 if (shader_list[i] == NULL)
2611 continue;
2612 linked->SourceChecksum ^= shader_list[i]->SourceChecksum;
2613 }
2614 #endif
2615
2616 return linked;
2617 }
2618
2619 /**
2620 * Update the sizes of linked shader uniform arrays to the maximum
2621 * array index used.
2622 *
2623 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2624 *
2625 * If one or more elements of an array are active,
2626 * GetActiveUniform will return the name of the array in name,
2627 * subject to the restrictions listed above. The type of the array
2628 * is returned in type. The size parameter contains the highest
2629 * array element index used, plus one. The compiler or linker
2630 * determines the highest index used. There will be only one
2631 * active uniform reported by the GL per uniform array.
2632
2633 */
2634 static void
2635 update_array_sizes(struct gl_shader_program *prog)
2636 {
2637 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2638 if (prog->_LinkedShaders[i] == NULL)
2639 continue;
2640
2641 bool types_were_updated = false;
2642
2643 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
2644 ir_variable *const var = node->as_variable();
2645
2646 if ((var == NULL) || (var->data.mode != ir_var_uniform) ||
2647 !var->type->is_array())
2648 continue;
2649
2650 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2651 * will not be eliminated. Since we always do std140, just
2652 * don't resize arrays in UBOs.
2653 *
2654 * Atomic counters are supposed to get deterministic
2655 * locations assigned based on the declaration ordering and
2656 * sizes, array compaction would mess that up.
2657 *
2658 * Subroutine uniforms are not removed.
2659 */
2660 if (var->is_in_buffer_block() || var->type->contains_atomic() ||
2661 var->type->contains_subroutine() || var->constant_initializer)
2662 continue;
2663
2664 int size = var->data.max_array_access;
2665 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
2666 if (prog->_LinkedShaders[j] == NULL)
2667 continue;
2668
2669 foreach_in_list(ir_instruction, node2, prog->_LinkedShaders[j]->ir) {
2670 ir_variable *other_var = node2->as_variable();
2671 if (!other_var)
2672 continue;
2673
2674 if (strcmp(var->name, other_var->name) == 0 &&
2675 other_var->data.max_array_access > size) {
2676 size = other_var->data.max_array_access;
2677 }
2678 }
2679 }
2680
2681 if (size + 1 != (int)var->type->length) {
2682 /* If this is a built-in uniform (i.e., it's backed by some
2683 * fixed-function state), adjust the number of state slots to
2684 * match the new array size. The number of slots per array entry
2685 * is not known. It seems safe to assume that the total number of
2686 * slots is an integer multiple of the number of array elements.
2687 * Determine the number of slots per array element by dividing by
2688 * the old (total) size.
2689 */
2690 const unsigned num_slots = var->get_num_state_slots();
2691 if (num_slots > 0) {
2692 var->set_num_state_slots((size + 1)
2693 * (num_slots / var->type->length));
2694 }
2695
2696 var->type = glsl_type::get_array_instance(var->type->fields.array,
2697 size + 1);
2698 types_were_updated = true;
2699 }
2700 }
2701
2702 /* Update the types of dereferences in case we changed any. */
2703 if (types_were_updated) {
2704 deref_type_updater v;
2705 v.run(prog->_LinkedShaders[i]->ir);
2706 }
2707 }
2708 }
2709
2710 /**
2711 * Resize tessellation evaluation per-vertex inputs to the size of
2712 * tessellation control per-vertex outputs.
2713 */
2714 static void
2715 resize_tes_inputs(struct gl_context *ctx,
2716 struct gl_shader_program *prog)
2717 {
2718 if (prog->_LinkedShaders[MESA_SHADER_TESS_EVAL] == NULL)
2719 return;
2720
2721 gl_linked_shader *const tcs = prog->_LinkedShaders[MESA_SHADER_TESS_CTRL];
2722 gl_linked_shader *const tes = prog->_LinkedShaders[MESA_SHADER_TESS_EVAL];
2723
2724 /* If no control shader is present, then the TES inputs are statically
2725 * sized to MaxPatchVertices; the actual size of the arrays won't be
2726 * known until draw time.
2727 */
2728 const int num_vertices = tcs
2729 ? tcs->Program->info.tess.tcs_vertices_out
2730 : ctx->Const.MaxPatchVertices;
2731
2732 array_resize_visitor input_resize_visitor(num_vertices, prog,
2733 MESA_SHADER_TESS_EVAL);
2734 foreach_in_list(ir_instruction, ir, tes->ir) {
2735 ir->accept(&input_resize_visitor);
2736 }
2737
2738 if (tcs) {
2739 /* Convert the gl_PatchVerticesIn system value into a constant, since
2740 * the value is known at this point.
2741 */
2742 foreach_in_list(ir_instruction, ir, tes->ir) {
2743 ir_variable *var = ir->as_variable();
2744 if (var && var->data.mode == ir_var_system_value &&
2745 var->data.location == SYSTEM_VALUE_VERTICES_IN) {
2746 void *mem_ctx = ralloc_parent(var);
2747 var->data.location = 0;
2748 var->data.explicit_location = false;
2749 var->data.mode = ir_var_auto;
2750 var->constant_value = new(mem_ctx) ir_constant(num_vertices);
2751 }
2752 }
2753 }
2754 }
2755
2756 /**
2757 * Find a contiguous set of available bits in a bitmask.
2758 *
2759 * \param used_mask Bits representing used (1) and unused (0) locations
2760 * \param needed_count Number of contiguous bits needed.
2761 *
2762 * \return
2763 * Base location of the available bits on success or -1 on failure.
2764 */
2765 static int
2766 find_available_slots(unsigned used_mask, unsigned needed_count)
2767 {
2768 unsigned needed_mask = (1 << needed_count) - 1;
2769 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
2770
2771 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2772 * cannot optimize possibly infinite loops" for the loop below.
2773 */
2774 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
2775 return -1;
2776
2777 for (int i = 0; i <= max_bit_to_test; i++) {
2778 if ((needed_mask & ~used_mask) == needed_mask)
2779 return i;
2780
2781 needed_mask <<= 1;
2782 }
2783
2784 return -1;
2785 }
2786
2787
2788 #define SAFE_MASK_FROM_INDEX(i) (((i) >= 32) ? ~0 : ((1 << (i)) - 1))
2789
2790 /**
2791 * Assign locations for either VS inputs or FS outputs.
2792 *
2793 * \param mem_ctx Temporary ralloc context used for linking.
2794 * \param prog Shader program whose variables need locations
2795 * assigned.
2796 * \param constants Driver specific constant values for the program.
2797 * \param target_index Selector for the program target to receive location
2798 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2799 * \c MESA_SHADER_FRAGMENT.
2800 * \param do_assignment Whether we are actually marking the assignment or we
2801 * are just doing a dry-run checking.
2802 *
2803 * \return
2804 * If locations are (or can be, in case of dry-running) successfully assigned,
2805 * true is returned. Otherwise an error is emitted to the shader link log and
2806 * false is returned.
2807 */
2808 static bool
2809 assign_attribute_or_color_locations(void *mem_ctx,
2810 gl_shader_program *prog,
2811 struct gl_constants *constants,
2812 unsigned target_index,
2813 bool do_assignment)
2814 {
2815 /* Maximum number of generic locations. This corresponds to either the
2816 * maximum number of draw buffers or the maximum number of generic
2817 * attributes.
2818 */
2819 unsigned max_index = (target_index == MESA_SHADER_VERTEX) ?
2820 constants->Program[target_index].MaxAttribs :
2821 MAX2(constants->MaxDrawBuffers, constants->MaxDualSourceDrawBuffers);
2822
2823 /* Mark invalid locations as being used.
2824 */
2825 unsigned used_locations = ~SAFE_MASK_FROM_INDEX(max_index);
2826 unsigned double_storage_locations = 0;
2827
2828 assert((target_index == MESA_SHADER_VERTEX)
2829 || (target_index == MESA_SHADER_FRAGMENT));
2830
2831 gl_linked_shader *const sh = prog->_LinkedShaders[target_index];
2832 if (sh == NULL)
2833 return true;
2834
2835 /* Operate in a total of four passes.
2836 *
2837 * 1. Invalidate the location assignments for all vertex shader inputs.
2838 *
2839 * 2. Assign locations for inputs that have user-defined (via
2840 * glBindVertexAttribLocation) locations and outputs that have
2841 * user-defined locations (via glBindFragDataLocation).
2842 *
2843 * 3. Sort the attributes without assigned locations by number of slots
2844 * required in decreasing order. Fragmentation caused by attribute
2845 * locations assigned by the application may prevent large attributes
2846 * from having enough contiguous space.
2847 *
2848 * 4. Assign locations to any inputs without assigned locations.
2849 */
2850
2851 const int generic_base = (target_index == MESA_SHADER_VERTEX)
2852 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
2853
2854 const enum ir_variable_mode direction =
2855 (target_index == MESA_SHADER_VERTEX)
2856 ? ir_var_shader_in : ir_var_shader_out;
2857
2858
2859 /* Temporary storage for the set of attributes that need locations assigned.
2860 */
2861 struct temp_attr {
2862 unsigned slots;
2863 ir_variable *var;
2864
2865 /* Used below in the call to qsort. */
2866 static int compare(const void *a, const void *b)
2867 {
2868 const temp_attr *const l = (const temp_attr *) a;
2869 const temp_attr *const r = (const temp_attr *) b;
2870
2871 /* Reversed because we want a descending order sort below. */
2872 return r->slots - l->slots;
2873 }
2874 } to_assign[32];
2875 assert(max_index <= 32);
2876
2877 /* Temporary array for the set of attributes that have locations assigned,
2878 * for the purpose of checking overlapping slots/components of (non-ES)
2879 * fragment shader outputs.
2880 */
2881 ir_variable *assigned[12 * 4]; /* (max # of FS outputs) * # components */
2882 unsigned assigned_attr = 0;
2883
2884 unsigned num_attr = 0;
2885
2886 foreach_in_list(ir_instruction, node, sh->ir) {
2887 ir_variable *const var = node->as_variable();
2888
2889 if ((var == NULL) || (var->data.mode != (unsigned) direction))
2890 continue;
2891
2892 if (var->data.explicit_location) {
2893 var->data.is_unmatched_generic_inout = 0;
2894 if ((var->data.location >= (int)(max_index + generic_base))
2895 || (var->data.location < 0)) {
2896 linker_error(prog,
2897 "invalid explicit location %d specified for `%s'\n",
2898 (var->data.location < 0)
2899 ? var->data.location
2900 : var->data.location - generic_base,
2901 var->name);
2902 return false;
2903 }
2904 } else if (target_index == MESA_SHADER_VERTEX) {
2905 unsigned binding;
2906
2907 if (prog->AttributeBindings->get(binding, var->name)) {
2908 assert(binding >= VERT_ATTRIB_GENERIC0);
2909 var->data.location = binding;
2910 var->data.is_unmatched_generic_inout = 0;
2911 }
2912 } else if (target_index == MESA_SHADER_FRAGMENT) {
2913 unsigned binding;
2914 unsigned index;
2915 const char *name = var->name;
2916 const glsl_type *type = var->type;
2917
2918 while (type) {
2919 /* Check if there's a binding for the variable name */
2920 if (prog->FragDataBindings->get(binding, name)) {
2921 assert(binding >= FRAG_RESULT_DATA0);
2922 var->data.location = binding;
2923 var->data.is_unmatched_generic_inout = 0;
2924
2925 if (prog->FragDataIndexBindings->get(index, name)) {
2926 var->data.index = index;
2927 }
2928 break;
2929 }
2930
2931 /* If not, but it's an array type, look for name[0] */
2932 if (type->is_array()) {
2933 name = ralloc_asprintf(mem_ctx, "%s[0]", name);
2934 type = type->fields.array;
2935 continue;
2936 }
2937
2938 break;
2939 }
2940 }
2941
2942 if (strcmp(var->name, "gl_LastFragData") == 0)
2943 continue;
2944
2945 /* From GL4.5 core spec, section 15.2 (Shader Execution):
2946 *
2947 * "Output binding assignments will cause LinkProgram to fail:
2948 * ...
2949 * If the program has an active output assigned to a location greater
2950 * than or equal to the value of MAX_DUAL_SOURCE_DRAW_BUFFERS and has
2951 * an active output assigned an index greater than or equal to one;"
2952 */
2953 if (target_index == MESA_SHADER_FRAGMENT && var->data.index >= 1 &&
2954 var->data.location - generic_base >=
2955 (int) constants->MaxDualSourceDrawBuffers) {
2956 linker_error(prog,
2957 "output location %d >= GL_MAX_DUAL_SOURCE_DRAW_BUFFERS "
2958 "with index %u for %s\n",
2959 var->data.location - generic_base, var->data.index,
2960 var->name);
2961 return false;
2962 }
2963
2964 const unsigned slots = var->type->count_attribute_slots(target_index == MESA_SHADER_VERTEX);
2965
2966 /* If the variable is not a built-in and has a location statically
2967 * assigned in the shader (presumably via a layout qualifier), make sure
2968 * that it doesn't collide with other assigned locations. Otherwise,
2969 * add it to the list of variables that need linker-assigned locations.
2970 */
2971 if (var->data.location != -1) {
2972 if (var->data.location >= generic_base && var->data.index < 1) {
2973 /* From page 61 of the OpenGL 4.0 spec:
2974 *
2975 * "LinkProgram will fail if the attribute bindings assigned
2976 * by BindAttribLocation do not leave not enough space to
2977 * assign a location for an active matrix attribute or an
2978 * active attribute array, both of which require multiple
2979 * contiguous generic attributes."
2980 *
2981 * I think above text prohibits the aliasing of explicit and
2982 * automatic assignments. But, aliasing is allowed in manual
2983 * assignments of attribute locations. See below comments for
2984 * the details.
2985 *
2986 * From OpenGL 4.0 spec, page 61:
2987 *
2988 * "It is possible for an application to bind more than one
2989 * attribute name to the same location. This is referred to as
2990 * aliasing. This will only work if only one of the aliased
2991 * attributes is active in the executable program, or if no
2992 * path through the shader consumes more than one attribute of
2993 * a set of attributes aliased to the same location. A link
2994 * error can occur if the linker determines that every path
2995 * through the shader consumes multiple aliased attributes,
2996 * but implementations are not required to generate an error
2997 * in this case."
2998 *
2999 * From GLSL 4.30 spec, page 54:
3000 *
3001 * "A program will fail to link if any two non-vertex shader
3002 * input variables are assigned to the same location. For
3003 * vertex shaders, multiple input variables may be assigned
3004 * to the same location using either layout qualifiers or via
3005 * the OpenGL API. However, such aliasing is intended only to
3006 * support vertex shaders where each execution path accesses
3007 * at most one input per each location. Implementations are
3008 * permitted, but not required, to generate link-time errors
3009 * if they detect that every path through the vertex shader
3010 * executable accesses multiple inputs assigned to any single
3011 * location. For all shader types, a program will fail to link
3012 * if explicit location assignments leave the linker unable
3013 * to find space for other variables without explicit
3014 * assignments."
3015 *
3016 * From OpenGL ES 3.0 spec, page 56:
3017 *
3018 * "Binding more than one attribute name to the same location
3019 * is referred to as aliasing, and is not permitted in OpenGL
3020 * ES Shading Language 3.00 vertex shaders. LinkProgram will
3021 * fail when this condition exists. However, aliasing is
3022 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
3023 * This will only work if only one of the aliased attributes
3024 * is active in the executable program, or if no path through
3025 * the shader consumes more than one attribute of a set of
3026 * attributes aliased to the same location. A link error can
3027 * occur if the linker determines that every path through the
3028 * shader consumes multiple aliased attributes, but implemen-
3029 * tations are not required to generate an error in this case."
3030 *
3031 * After looking at above references from OpenGL, OpenGL ES and
3032 * GLSL specifications, we allow aliasing of vertex input variables
3033 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
3034 *
3035 * NOTE: This is not required by the spec but its worth mentioning
3036 * here that we're not doing anything to make sure that no path
3037 * through the vertex shader executable accesses multiple inputs
3038 * assigned to any single location.
3039 */
3040
3041 /* Mask representing the contiguous slots that will be used by
3042 * this attribute.
3043 */
3044 const unsigned attr = var->data.location - generic_base;
3045 const unsigned use_mask = (1 << slots) - 1;
3046 const char *const string = (target_index == MESA_SHADER_VERTEX)
3047 ? "vertex shader input" : "fragment shader output";
3048
3049 /* Generate a link error if the requested locations for this
3050 * attribute exceed the maximum allowed attribute location.
3051 */
3052 if (attr + slots > max_index) {
3053 linker_error(prog,
3054 "insufficient contiguous locations "
3055 "available for %s `%s' %d %d %d\n", string,
3056 var->name, used_locations, use_mask, attr);
3057 return false;
3058 }
3059
3060 /* Generate a link error if the set of bits requested for this
3061 * attribute overlaps any previously allocated bits.
3062 */
3063 if ((~(use_mask << attr) & used_locations) != used_locations) {
3064 if (target_index == MESA_SHADER_FRAGMENT && !prog->IsES) {
3065 /* From section 4.4.2 (Output Layout Qualifiers) of the GLSL
3066 * 4.40 spec:
3067 *
3068 * "Additionally, for fragment shader outputs, if two
3069 * variables are placed within the same location, they
3070 * must have the same underlying type (floating-point or
3071 * integer). No component aliasing of output variables or
3072 * members is allowed.
3073 */
3074 for (unsigned i = 0; i < assigned_attr; i++) {
3075 unsigned assigned_slots =
3076 assigned[i]->type->count_attribute_slots(false);
3077 unsigned assig_attr =
3078 assigned[i]->data.location - generic_base;
3079 unsigned assigned_use_mask = (1 << assigned_slots) - 1;
3080
3081 if ((assigned_use_mask << assig_attr) &
3082 (use_mask << attr)) {
3083
3084 const glsl_type *assigned_type =
3085 assigned[i]->type->without_array();
3086 const glsl_type *type = var->type->without_array();
3087 if (assigned_type->base_type != type->base_type) {
3088 linker_error(prog, "types do not match for aliased"
3089 " %ss %s and %s\n", string,
3090 assigned[i]->name, var->name);
3091 return false;
3092 }
3093
3094 unsigned assigned_component_mask =
3095 ((1 << assigned_type->vector_elements) - 1) <<
3096 assigned[i]->data.location_frac;
3097 unsigned component_mask =
3098 ((1 << type->vector_elements) - 1) <<
3099 var->data.location_frac;
3100 if (assigned_component_mask & component_mask) {
3101 linker_error(prog, "overlapping component is "
3102 "assigned to %ss %s and %s "
3103 "(component=%d)\n",
3104 string, assigned[i]->name, var->name,
3105 var->data.location_frac);
3106 return false;
3107 }
3108 }
3109 }
3110 } else if (target_index == MESA_SHADER_FRAGMENT ||
3111 (prog->IsES && prog->data->Version >= 300)) {
3112 linker_error(prog, "overlapping location is assigned "
3113 "to %s `%s' %d %d %d\n", string, var->name,
3114 used_locations, use_mask, attr);
3115 return false;
3116 } else {
3117 linker_warning(prog, "overlapping location is assigned "
3118 "to %s `%s' %d %d %d\n", string, var->name,
3119 used_locations, use_mask, attr);
3120 }
3121 }
3122
3123 if (target_index == MESA_SHADER_FRAGMENT && !prog->IsES) {
3124 /* Only track assigned variables for non-ES fragment shaders
3125 * to avoid overflowing the array.
3126 *
3127 * At most one variable per fragment output component should
3128 * reach this.
3129 */
3130 assert(assigned_attr < ARRAY_SIZE(assigned));
3131 assigned[assigned_attr] = var;
3132 assigned_attr++;
3133 }
3134
3135 used_locations |= (use_mask << attr);
3136
3137 /* From the GL 4.5 core spec, section 11.1.1 (Vertex Attributes):
3138 *
3139 * "A program with more than the value of MAX_VERTEX_ATTRIBS
3140 * active attribute variables may fail to link, unless
3141 * device-dependent optimizations are able to make the program
3142 * fit within available hardware resources. For the purposes
3143 * of this test, attribute variables of the type dvec3, dvec4,
3144 * dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3, and dmat4 may
3145 * count as consuming twice as many attributes as equivalent
3146 * single-precision types. While these types use the same number
3147 * of generic attributes as their single-precision equivalents,
3148 * implementations are permitted to consume two single-precision
3149 * vectors of internal storage for each three- or four-component
3150 * double-precision vector."
3151 *
3152 * Mark this attribute slot as taking up twice as much space
3153 * so we can count it properly against limits. According to
3154 * issue (3) of the GL_ARB_vertex_attrib_64bit behavior, this
3155 * is optional behavior, but it seems preferable.
3156 */
3157 if (var->type->without_array()->is_dual_slot())
3158 double_storage_locations |= (use_mask << attr);
3159 }
3160
3161 continue;
3162 }
3163
3164 if (num_attr >= max_index) {
3165 linker_error(prog, "too many %s (max %u)",
3166 target_index == MESA_SHADER_VERTEX ?
3167 "vertex shader inputs" : "fragment shader outputs",
3168 max_index);
3169 return false;
3170 }
3171 to_assign[num_attr].slots = slots;
3172 to_assign[num_attr].var = var;
3173 num_attr++;
3174 }
3175
3176 if (!do_assignment)
3177 return true;
3178
3179 if (target_index == MESA_SHADER_VERTEX) {
3180 unsigned total_attribs_size =
3181 util_bitcount(used_locations & SAFE_MASK_FROM_INDEX(max_index)) +
3182 util_bitcount(double_storage_locations);
3183 if (total_attribs_size > max_index) {
3184 linker_error(prog,
3185 "attempt to use %d vertex attribute slots only %d available ",
3186 total_attribs_size, max_index);
3187 return false;
3188 }
3189 }
3190
3191 /* If all of the attributes were assigned locations by the application (or
3192 * are built-in attributes with fixed locations), return early. This should
3193 * be the common case.
3194 */
3195 if (num_attr == 0)
3196 return true;
3197
3198 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
3199
3200 if (target_index == MESA_SHADER_VERTEX) {
3201 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
3202 * only be explicitly assigned by via glBindAttribLocation. Mark it as
3203 * reserved to prevent it from being automatically allocated below.
3204 */
3205 find_deref_visitor find("gl_Vertex");
3206 find.run(sh->ir);
3207 if (find.variable_found())
3208 used_locations |= (1 << 0);
3209 }
3210
3211 for (unsigned i = 0; i < num_attr; i++) {
3212 /* Mask representing the contiguous slots that will be used by this
3213 * attribute.
3214 */
3215 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
3216
3217 int location = find_available_slots(used_locations, to_assign[i].slots);
3218
3219 if (location < 0) {
3220 const char *const string = (target_index == MESA_SHADER_VERTEX)
3221 ? "vertex shader input" : "fragment shader output";
3222
3223 linker_error(prog,
3224 "insufficient contiguous locations "
3225 "available for %s `%s'\n",
3226 string, to_assign[i].var->name);
3227 return false;
3228 }
3229
3230 to_assign[i].var->data.location = generic_base + location;
3231 to_assign[i].var->data.is_unmatched_generic_inout = 0;
3232 used_locations |= (use_mask << location);
3233
3234 if (to_assign[i].var->type->without_array()->is_dual_slot())
3235 double_storage_locations |= (use_mask << location);
3236 }
3237
3238 /* Now that we have all the locations, from the GL 4.5 core spec, section
3239 * 11.1.1 (Vertex Attributes), dvec3, dvec4, dmat2x3, dmat2x4, dmat3,
3240 * dmat3x4, dmat4x3, and dmat4 count as consuming twice as many attributes
3241 * as equivalent single-precision types.
3242 */
3243 if (target_index == MESA_SHADER_VERTEX) {
3244 unsigned total_attribs_size =
3245 util_bitcount(used_locations & SAFE_MASK_FROM_INDEX(max_index)) +
3246 util_bitcount(double_storage_locations);
3247 if (total_attribs_size > max_index) {
3248 linker_error(prog,
3249 "attempt to use %d vertex attribute slots only %d available ",
3250 total_attribs_size, max_index);
3251 return false;
3252 }
3253 }
3254
3255 return true;
3256 }
3257
3258 /**
3259 * Match explicit locations of outputs to inputs and deactivate the
3260 * unmatch flag if found so we don't optimise them away.
3261 */
3262 static void
3263 match_explicit_outputs_to_inputs(gl_linked_shader *producer,
3264 gl_linked_shader *consumer)
3265 {
3266 glsl_symbol_table parameters;
3267 ir_variable *explicit_locations[MAX_VARYINGS_INCL_PATCH][4] =
3268 { {NULL, NULL} };
3269
3270 /* Find all shader outputs in the "producer" stage.
3271 */
3272 foreach_in_list(ir_instruction, node, producer->ir) {
3273 ir_variable *const var = node->as_variable();
3274
3275 if ((var == NULL) || (var->data.mode != ir_var_shader_out))
3276 continue;
3277
3278 if (var->data.explicit_location &&
3279 var->data.location >= VARYING_SLOT_VAR0) {
3280 const unsigned idx = var->data.location - VARYING_SLOT_VAR0;
3281 if (explicit_locations[idx][var->data.location_frac] == NULL)
3282 explicit_locations[idx][var->data.location_frac] = var;
3283
3284 /* Always match TCS outputs. They are shared by all invocations
3285 * within a patch and can be used as shared memory.
3286 */
3287 if (producer->Stage == MESA_SHADER_TESS_CTRL)
3288 var->data.is_unmatched_generic_inout = 0;
3289 }
3290 }
3291
3292 /* Match inputs to outputs */
3293 foreach_in_list(ir_instruction, node, consumer->ir) {
3294 ir_variable *const input = node->as_variable();
3295
3296 if ((input == NULL) || (input->data.mode != ir_var_shader_in))
3297 continue;
3298
3299 ir_variable *output = NULL;
3300 if (input->data.explicit_location
3301 && input->data.location >= VARYING_SLOT_VAR0) {
3302 output = explicit_locations[input->data.location - VARYING_SLOT_VAR0]
3303 [input->data.location_frac];
3304
3305 if (output != NULL){
3306 input->data.is_unmatched_generic_inout = 0;
3307 output->data.is_unmatched_generic_inout = 0;
3308 }
3309 }
3310 }
3311 }
3312
3313 /**
3314 * Store the gl_FragDepth layout in the gl_shader_program struct.
3315 */
3316 static void
3317 store_fragdepth_layout(struct gl_shader_program *prog)
3318 {
3319 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
3320 return;
3321 }
3322
3323 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
3324
3325 /* We don't look up the gl_FragDepth symbol directly because if
3326 * gl_FragDepth is not used in the shader, it's removed from the IR.
3327 * However, the symbol won't be removed from the symbol table.
3328 *
3329 * We're only interested in the cases where the variable is NOT removed
3330 * from the IR.
3331 */
3332 foreach_in_list(ir_instruction, node, ir) {
3333 ir_variable *const var = node->as_variable();
3334
3335 if (var == NULL || var->data.mode != ir_var_shader_out) {
3336 continue;
3337 }
3338
3339 if (strcmp(var->name, "gl_FragDepth") == 0) {
3340 switch (var->data.depth_layout) {
3341 case ir_depth_layout_none:
3342 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
3343 return;
3344 case ir_depth_layout_any:
3345 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
3346 return;
3347 case ir_depth_layout_greater:
3348 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
3349 return;
3350 case ir_depth_layout_less:
3351 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
3352 return;
3353 case ir_depth_layout_unchanged:
3354 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
3355 return;
3356 default:
3357 assert(0);
3358 return;
3359 }
3360 }
3361 }
3362 }
3363
3364 /**
3365 * Validate shader image resources.
3366 */
3367 static void
3368 check_image_resources(struct gl_context *ctx, struct gl_shader_program *prog)
3369 {
3370 unsigned total_image_units = 0;
3371 unsigned fragment_outputs = 0;
3372 unsigned total_shader_storage_blocks = 0;
3373
3374 if (!ctx->Extensions.ARB_shader_image_load_store)
3375 return;
3376
3377 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3378 struct gl_linked_shader *sh = prog->_LinkedShaders[i];
3379
3380 if (sh) {
3381 total_image_units += sh->Program->info.num_images;
3382 total_shader_storage_blocks += sh->Program->info.num_ssbos;
3383
3384 if (i == MESA_SHADER_FRAGMENT) {
3385 foreach_in_list(ir_instruction, node, sh->ir) {
3386 ir_variable *var = node->as_variable();
3387 if (var && var->data.mode == ir_var_shader_out)
3388 /* since there are no double fs outputs - pass false */
3389 fragment_outputs += var->type->count_attribute_slots(false);
3390 }
3391 }
3392 }
3393 }
3394
3395 if (total_image_units > ctx->Const.MaxCombinedImageUniforms)
3396 linker_error(prog, "Too many combined image uniforms\n");
3397
3398 if (total_image_units + fragment_outputs + total_shader_storage_blocks >
3399 ctx->Const.MaxCombinedShaderOutputResources)
3400 linker_error(prog, "Too many combined image uniforms, shader storage "
3401 " buffers and fragment outputs\n");
3402 }
3403
3404
3405 /**
3406 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
3407 * for a variable, checks for overlaps between other uniforms using explicit
3408 * locations.
3409 */
3410 static int
3411 reserve_explicit_locations(struct gl_shader_program *prog,
3412 string_to_uint_map *map, ir_variable *var)
3413 {
3414 unsigned slots = var->type->uniform_locations();
3415 unsigned max_loc = var->data.location + slots - 1;
3416 unsigned return_value = slots;
3417
3418 /* Resize remap table if locations do not fit in the current one. */
3419 if (max_loc + 1 > prog->NumUniformRemapTable) {
3420 prog->UniformRemapTable =
3421 reralloc(prog, prog->UniformRemapTable,
3422 gl_uniform_storage *,
3423 max_loc + 1);
3424
3425 if (!prog->UniformRemapTable) {
3426 linker_error(prog, "Out of memory during linking.\n");
3427 return -1;
3428 }
3429
3430 /* Initialize allocated space. */
3431 for (unsigned i = prog->NumUniformRemapTable; i < max_loc + 1; i++)
3432 prog->UniformRemapTable[i] = NULL;
3433
3434 prog->NumUniformRemapTable = max_loc + 1;
3435 }
3436
3437 for (unsigned i = 0; i < slots; i++) {
3438 unsigned loc = var->data.location + i;
3439
3440 /* Check if location is already used. */
3441 if (prog->UniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3442
3443 /* Possibly same uniform from a different stage, this is ok. */
3444 unsigned hash_loc;
3445 if (map->get(hash_loc, var->name) && hash_loc == loc - i) {
3446 return_value = 0;
3447 continue;
3448 }
3449
3450 /* ARB_explicit_uniform_location specification states:
3451 *
3452 * "No two default-block uniform variables in the program can have
3453 * the same location, even if they are unused, otherwise a compiler
3454 * or linker error will be generated."
3455 */
3456 linker_error(prog,
3457 "location qualifier for uniform %s overlaps "
3458 "previously used location\n",
3459 var->name);
3460 return -1;
3461 }
3462
3463 /* Initialize location as inactive before optimization
3464 * rounds and location assignment.
3465 */
3466 prog->UniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3467 }
3468
3469 /* Note, base location used for arrays. */
3470 map->put(var->data.location, var->name);
3471
3472 return return_value;
3473 }
3474
3475 static bool
3476 reserve_subroutine_explicit_locations(struct gl_shader_program *prog,
3477 struct gl_program *p,
3478 ir_variable *var)
3479 {
3480 unsigned slots = var->type->uniform_locations();
3481 unsigned max_loc = var->data.location + slots - 1;
3482
3483 /* Resize remap table if locations do not fit in the current one. */
3484 if (max_loc + 1 > p->sh.NumSubroutineUniformRemapTable) {
3485 p->sh.SubroutineUniformRemapTable =
3486 reralloc(p, p->sh.SubroutineUniformRemapTable,
3487 gl_uniform_storage *,
3488 max_loc + 1);
3489
3490 if (!p->sh.SubroutineUniformRemapTable) {
3491 linker_error(prog, "Out of memory during linking.\n");
3492 return false;
3493 }
3494
3495 /* Initialize allocated space. */
3496 for (unsigned i = p->sh.NumSubroutineUniformRemapTable; i < max_loc + 1; i++)
3497 p->sh.SubroutineUniformRemapTable[i] = NULL;
3498
3499 p->sh.NumSubroutineUniformRemapTable = max_loc + 1;
3500 }
3501
3502 for (unsigned i = 0; i < slots; i++) {
3503 unsigned loc = var->data.location + i;
3504
3505 /* Check if location is already used. */
3506 if (p->sh.SubroutineUniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
3507
3508 /* ARB_explicit_uniform_location specification states:
3509 * "No two subroutine uniform variables can have the same location
3510 * in the same shader stage, otherwise a compiler or linker error
3511 * will be generated."
3512 */
3513 linker_error(prog,
3514 "location qualifier for uniform %s overlaps "
3515 "previously used location\n",
3516 var->name);
3517 return false;
3518 }
3519
3520 /* Initialize location as inactive before optimization
3521 * rounds and location assignment.
3522 */
3523 p->sh.SubroutineUniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
3524 }
3525
3526 return true;
3527 }
3528 /**
3529 * Check and reserve all explicit uniform locations, called before
3530 * any optimizations happen to handle also inactive uniforms and
3531 * inactive array elements that may get trimmed away.
3532 */
3533 static void
3534 check_explicit_uniform_locations(struct gl_context *ctx,
3535 struct gl_shader_program *prog)
3536 {
3537 prog->NumExplicitUniformLocations = 0;
3538
3539 if (!ctx->Extensions.ARB_explicit_uniform_location)
3540 return;
3541
3542 /* This map is used to detect if overlapping explicit locations
3543 * occur with the same uniform (from different stage) or a different one.
3544 */
3545 string_to_uint_map *uniform_map = new string_to_uint_map;
3546
3547 if (!uniform_map) {
3548 linker_error(prog, "Out of memory during linking.\n");
3549 return;
3550 }
3551
3552 unsigned entries_total = 0;
3553 unsigned mask = prog->data->linked_stages;
3554 while (mask) {
3555 const int i = u_bit_scan(&mask);
3556 struct gl_program *p = prog->_LinkedShaders[i]->Program;
3557
3558 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
3559 ir_variable *var = node->as_variable();
3560 if (!var || var->data.mode != ir_var_uniform)
3561 continue;
3562
3563 if (var->data.explicit_location) {
3564 bool ret = false;
3565 if (var->type->without_array()->is_subroutine())
3566 ret = reserve_subroutine_explicit_locations(prog, p, var);
3567 else {
3568 int slots = reserve_explicit_locations(prog, uniform_map,
3569 var);
3570 if (slots != -1) {
3571 ret = true;
3572 entries_total += slots;
3573 }
3574 }
3575 if (!ret) {
3576 delete uniform_map;
3577 return;
3578 }
3579 }
3580 }
3581 }
3582
3583 link_util_update_empty_uniform_locations(prog);
3584
3585 delete uniform_map;
3586 prog->NumExplicitUniformLocations = entries_total;
3587 }
3588
3589 /* Function checks if a variable var is a packed varying and
3590 * if given name is part of packed varying's list.
3591 *
3592 * If a variable is a packed varying, it has a name like
3593 * 'packed:a,b,c' where a, b and c are separate variables.
3594 */
3595 static bool
3596 included_in_packed_varying(ir_variable *var, const char *name)
3597 {
3598 if (strncmp(var->name, "packed:", 7) != 0)
3599 return false;
3600
3601 char *list = strdup(var->name + 7);
3602 assert(list);
3603
3604 bool found = false;
3605 char *saveptr;
3606 char *token = strtok_r(list, ",", &saveptr);
3607 while (token) {
3608 if (strcmp(token, name) == 0) {
3609 found = true;
3610 break;
3611 }
3612 token = strtok_r(NULL, ",", &saveptr);
3613 }
3614 free(list);
3615 return found;
3616 }
3617
3618 /**
3619 * Function builds a stage reference bitmask from variable name.
3620 */
3621 static uint8_t
3622 build_stageref(struct gl_shader_program *shProg, const char *name,
3623 unsigned mode)
3624 {
3625 uint8_t stages = 0;
3626
3627 /* Note, that we assume MAX 8 stages, if there will be more stages, type
3628 * used for reference mask in gl_program_resource will need to be changed.
3629 */
3630 assert(MESA_SHADER_STAGES < 8);
3631
3632 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3633 struct gl_linked_shader *sh = shProg->_LinkedShaders[i];
3634 if (!sh)
3635 continue;
3636
3637 /* Shader symbol table may contain variables that have
3638 * been optimized away. Search IR for the variable instead.
3639 */
3640 foreach_in_list(ir_instruction, node, sh->ir) {
3641 ir_variable *var = node->as_variable();
3642 if (var) {
3643 unsigned baselen = strlen(var->name);
3644
3645 if (included_in_packed_varying(var, name)) {
3646 stages |= (1 << i);
3647 break;
3648 }
3649
3650 /* Type needs to match if specified, otherwise we might
3651 * pick a variable with same name but different interface.
3652 */
3653 if (var->data.mode != mode)
3654 continue;
3655
3656 if (strncmp(var->name, name, baselen) == 0) {
3657 /* Check for exact name matches but also check for arrays and
3658 * structs.
3659 */
3660 if (name[baselen] == '\0' ||
3661 name[baselen] == '[' ||
3662 name[baselen] == '.') {
3663 stages |= (1 << i);
3664 break;
3665 }
3666 }
3667 }
3668 }
3669 }
3670 return stages;
3671 }
3672
3673 /**
3674 * Create gl_shader_variable from ir_variable class.
3675 */
3676 static gl_shader_variable *
3677 create_shader_variable(struct gl_shader_program *shProg,
3678 const ir_variable *in,
3679 const char *name, const glsl_type *type,
3680 const glsl_type *interface_type,
3681 bool use_implicit_location, int location,
3682 const glsl_type *outermost_struct_type)
3683 {
3684 /* Allocate zero-initialized memory to ensure that bitfield padding
3685 * is zero.
3686 */
3687 gl_shader_variable *out = rzalloc(shProg, struct gl_shader_variable);
3688 if (!out)
3689 return NULL;
3690
3691 /* Since gl_VertexID may be lowered to gl_VertexIDMESA, but applications
3692 * expect to see gl_VertexID in the program resource list. Pretend.
3693 */
3694 if (in->data.mode == ir_var_system_value &&
3695 in->data.location == SYSTEM_VALUE_VERTEX_ID_ZERO_BASE) {
3696 out->name = ralloc_strdup(shProg, "gl_VertexID");
3697 } else if ((in->data.mode == ir_var_shader_out &&
3698 in->data.location == VARYING_SLOT_TESS_LEVEL_OUTER) ||
3699 (in->data.mode == ir_var_system_value &&
3700 in->data.location == SYSTEM_VALUE_TESS_LEVEL_OUTER)) {
3701 out->name = ralloc_strdup(shProg, "gl_TessLevelOuter");
3702 type = glsl_type::get_array_instance(glsl_type::float_type, 4);
3703 } else if ((in->data.mode == ir_var_shader_out &&
3704 in->data.location == VARYING_SLOT_TESS_LEVEL_INNER) ||
3705 (in->data.mode == ir_var_system_value &&
3706 in->data.location == SYSTEM_VALUE_TESS_LEVEL_INNER)) {
3707 out->name = ralloc_strdup(shProg, "gl_TessLevelInner");
3708 type = glsl_type::get_array_instance(glsl_type::float_type, 2);
3709 } else {
3710 out->name = ralloc_strdup(shProg, name);
3711 }
3712
3713 if (!out->name)
3714 return NULL;
3715
3716 /* The ARB_program_interface_query spec says:
3717 *
3718 * "Not all active variables are assigned valid locations; the
3719 * following variables will have an effective location of -1:
3720 *
3721 * * uniforms declared as atomic counters;
3722 *
3723 * * members of a uniform block;
3724 *
3725 * * built-in inputs, outputs, and uniforms (starting with "gl_"); and
3726 *
3727 * * inputs or outputs not declared with a "location" layout
3728 * qualifier, except for vertex shader inputs and fragment shader
3729 * outputs."
3730 */
3731 if (in->type->is_atomic_uint() || is_gl_identifier(in->name) ||
3732 !(in->data.explicit_location || use_implicit_location)) {
3733 out->location = -1;
3734 } else {
3735 out->location = location;
3736 }
3737
3738 out->type = type;
3739 out->outermost_struct_type = outermost_struct_type;
3740 out->interface_type = interface_type;
3741 out->component = in->data.location_frac;
3742 out->index = in->data.index;
3743 out->patch = in->data.patch;
3744 out->mode = in->data.mode;
3745 out->interpolation = in->data.interpolation;
3746 out->explicit_location = in->data.explicit_location;
3747 out->precision = in->data.precision;
3748
3749 return out;
3750 }
3751
3752 static bool
3753 add_shader_variable(const struct gl_context *ctx,
3754 struct gl_shader_program *shProg,
3755 struct set *resource_set,
3756 unsigned stage_mask,
3757 GLenum programInterface, ir_variable *var,
3758 const char *name, const glsl_type *type,
3759 bool use_implicit_location, int location,
3760 bool inouts_share_location,
3761 const glsl_type *outermost_struct_type = NULL)
3762 {
3763 const glsl_type *interface_type = var->get_interface_type();
3764
3765 if (outermost_struct_type == NULL) {
3766 if (var->data.from_named_ifc_block) {
3767 const char *interface_name = interface_type->name;
3768
3769 if (interface_type->is_array()) {
3770 /* Issue #16 of the ARB_program_interface_query spec says:
3771 *
3772 * "* If a variable is a member of an interface block without an
3773 * instance name, it is enumerated using just the variable name.
3774 *
3775 * * If a variable is a member of an interface block with an
3776 * instance name, it is enumerated as "BlockName.Member", where
3777 * "BlockName" is the name of the interface block (not the
3778 * instance name) and "Member" is the name of the variable."
3779 *
3780 * In particular, it indicates that it should be "BlockName",
3781 * not "BlockName[array length]". The conformance suite and
3782 * dEQP both require this behavior.
3783 *
3784 * Here, we unwrap the extra array level added by named interface
3785 * block array lowering so we have the correct variable type. We
3786 * also unwrap the interface type when constructing the name.
3787 *
3788 * We leave interface_type the same so that ES 3.x SSO pipeline
3789 * validation can enforce the rules requiring array length to
3790 * match on interface blocks.
3791 */
3792 type = type->fields.array;
3793
3794 interface_name = interface_type->fields.array->name;
3795 }
3796
3797 name = ralloc_asprintf(shProg, "%s.%s", interface_name, name);
3798 }
3799 }
3800
3801 switch (type->base_type) {
3802 case GLSL_TYPE_STRUCT: {
3803 /* The ARB_program_interface_query spec says:
3804 *
3805 * "For an active variable declared as a structure, a separate entry
3806 * will be generated for each active structure member. The name of
3807 * each entry is formed by concatenating the name of the structure,
3808 * the "." character, and the name of the structure member. If a
3809 * structure member to enumerate is itself a structure or array,
3810 * these enumeration rules are applied recursively."
3811 */
3812 if (outermost_struct_type == NULL)
3813 outermost_struct_type = type;
3814
3815 unsigned field_location = location;
3816 for (unsigned i = 0; i < type->length; i++) {
3817 const struct glsl_struct_field *field = &type->fields.structure[i];
3818 char *field_name = ralloc_asprintf(shProg, "%s.%s", name, field->name);
3819 if (!add_shader_variable(ctx, shProg, resource_set,
3820 stage_mask, programInterface,
3821 var, field_name, field->type,
3822 use_implicit_location, field_location,
3823 false, outermost_struct_type))
3824 return false;
3825
3826 field_location += field->type->count_attribute_slots(false);
3827 }
3828 return true;
3829 }
3830
3831 case GLSL_TYPE_ARRAY: {
3832 /* The ARB_program_interface_query spec says:
3833 *
3834 * "For an active variable declared as an array of basic types, a
3835 * single entry will be generated, with its name string formed by
3836 * concatenating the name of the array and the string "[0]"."
3837 *
3838 * "For an active variable declared as an array of an aggregate data
3839 * type (structures or arrays), a separate entry will be generated
3840 * for each active array element, unless noted immediately below.
3841 * The name of each entry is formed by concatenating the name of
3842 * the array, the "[" character, an integer identifying the element
3843 * number, and the "]" character. These enumeration rules are
3844 * applied recursively, treating each enumerated array element as a
3845 * separate active variable."
3846 */
3847 const struct glsl_type *array_type = type->fields.array;
3848 if (array_type->base_type == GLSL_TYPE_STRUCT ||
3849 array_type->base_type == GLSL_TYPE_ARRAY) {
3850 unsigned elem_location = location;
3851 unsigned stride = inouts_share_location ? 0 :
3852 array_type->count_attribute_slots(false);
3853 for (unsigned i = 0; i < type->length; i++) {
3854 char *elem = ralloc_asprintf(shProg, "%s[%d]", name, i);
3855 if (!add_shader_variable(ctx, shProg, resource_set,
3856 stage_mask, programInterface,
3857 var, elem, array_type,
3858 use_implicit_location, elem_location,
3859 false, outermost_struct_type))
3860 return false;
3861 elem_location += stride;
3862 }
3863 return true;
3864 }
3865 /* fallthrough */
3866 }
3867
3868 default: {
3869 /* The ARB_program_interface_query spec says:
3870 *
3871 * "For an active variable declared as a single instance of a basic
3872 * type, a single entry will be generated, using the variable name
3873 * from the shader source."
3874 */
3875 gl_shader_variable *sha_v =
3876 create_shader_variable(shProg, var, name, type, interface_type,
3877 use_implicit_location, location,
3878 outermost_struct_type);
3879 if (!sha_v)
3880 return false;
3881
3882 return link_util_add_program_resource(shProg, resource_set,
3883 programInterface, sha_v, stage_mask);
3884 }
3885 }
3886 }
3887
3888 static bool
3889 inout_has_same_location(const ir_variable *var, unsigned stage)
3890 {
3891 if (!var->data.patch &&
3892 ((var->data.mode == ir_var_shader_out &&
3893 stage == MESA_SHADER_TESS_CTRL) ||
3894 (var->data.mode == ir_var_shader_in &&
3895 (stage == MESA_SHADER_TESS_CTRL || stage == MESA_SHADER_TESS_EVAL ||
3896 stage == MESA_SHADER_GEOMETRY))))
3897 return true;
3898 else
3899 return false;
3900 }
3901
3902 static bool
3903 add_interface_variables(const struct gl_context *ctx,
3904 struct gl_shader_program *shProg,
3905 struct set *resource_set,
3906 unsigned stage, GLenum programInterface)
3907 {
3908 exec_list *ir = shProg->_LinkedShaders[stage]->ir;
3909
3910 foreach_in_list(ir_instruction, node, ir) {
3911 ir_variable *var = node->as_variable();
3912
3913 if (!var || var->data.how_declared == ir_var_hidden)
3914 continue;
3915
3916 int loc_bias;
3917
3918 switch (var->data.mode) {
3919 case ir_var_system_value:
3920 case ir_var_shader_in:
3921 if (programInterface != GL_PROGRAM_INPUT)
3922 continue;
3923 loc_bias = (stage == MESA_SHADER_VERTEX) ? int(VERT_ATTRIB_GENERIC0)
3924 : int(VARYING_SLOT_VAR0);
3925 break;
3926 case ir_var_shader_out:
3927 if (programInterface != GL_PROGRAM_OUTPUT)
3928 continue;
3929 loc_bias = (stage == MESA_SHADER_FRAGMENT) ? int(FRAG_RESULT_DATA0)
3930 : int(VARYING_SLOT_VAR0);
3931 break;
3932 default:
3933 continue;
3934 };
3935
3936 if (var->data.patch)
3937 loc_bias = int(VARYING_SLOT_PATCH0);
3938
3939 /* Skip packed varyings, packed varyings are handled separately
3940 * by add_packed_varyings.
3941 */
3942 if (strncmp(var->name, "packed:", 7) == 0)
3943 continue;
3944
3945 /* Skip fragdata arrays, these are handled separately
3946 * by add_fragdata_arrays.
3947 */
3948 if (strncmp(var->name, "gl_out_FragData", 15) == 0)
3949 continue;
3950
3951 const bool vs_input_or_fs_output =
3952 (stage == MESA_SHADER_VERTEX && var->data.mode == ir_var_shader_in) ||
3953 (stage == MESA_SHADER_FRAGMENT && var->data.mode == ir_var_shader_out);
3954
3955 if (!add_shader_variable(ctx, shProg, resource_set,
3956 1 << stage, programInterface,
3957 var, var->name, var->type, vs_input_or_fs_output,
3958 var->data.location - loc_bias,
3959 inout_has_same_location(var, stage)))
3960 return false;
3961 }
3962 return true;
3963 }
3964
3965 static bool
3966 add_packed_varyings(const struct gl_context *ctx,
3967 struct gl_shader_program *shProg,
3968 struct set *resource_set,
3969 int stage, GLenum type)
3970 {
3971 struct gl_linked_shader *sh = shProg->_LinkedShaders[stage];
3972 GLenum iface;
3973
3974 if (!sh || !sh->packed_varyings)
3975 return true;
3976
3977 foreach_in_list(ir_instruction, node, sh->packed_varyings) {
3978 ir_variable *var = node->as_variable();
3979 if (var) {
3980 switch (var->data.mode) {
3981 case ir_var_shader_in:
3982 iface = GL_PROGRAM_INPUT;
3983 break;
3984 case ir_var_shader_out:
3985 iface = GL_PROGRAM_OUTPUT;
3986 break;
3987 default:
3988 unreachable("unexpected type");
3989 }
3990
3991 if (type == iface) {
3992 const int stage_mask =
3993 build_stageref(shProg, var->name, var->data.mode);
3994 if (!add_shader_variable(ctx, shProg, resource_set,
3995 stage_mask,
3996 iface, var, var->name, var->type, false,
3997 var->data.location - VARYING_SLOT_VAR0,
3998 inout_has_same_location(var, stage)))
3999 return false;
4000 }
4001 }
4002 }
4003 return true;
4004 }
4005
4006 static bool
4007 add_fragdata_arrays(const struct gl_context *ctx,
4008 struct gl_shader_program *shProg,
4009 struct set *resource_set)
4010 {
4011 struct gl_linked_shader *sh = shProg->_LinkedShaders[MESA_SHADER_FRAGMENT];
4012
4013 if (!sh || !sh->fragdata_arrays)
4014 return true;
4015
4016 foreach_in_list(ir_instruction, node, sh->fragdata_arrays) {
4017 ir_variable *var = node->as_variable();
4018 if (var) {
4019 assert(var->data.mode == ir_var_shader_out);
4020
4021 if (!add_shader_variable(ctx, shProg, resource_set,
4022 1 << MESA_SHADER_FRAGMENT,
4023 GL_PROGRAM_OUTPUT, var, var->name, var->type,
4024 true, var->data.location - FRAG_RESULT_DATA0,
4025 false))
4026 return false;
4027 }
4028 }
4029 return true;
4030 }
4031
4032 /**
4033 * Builds up a list of program resources that point to existing
4034 * resource data.
4035 */
4036 void
4037 build_program_resource_list(struct gl_context *ctx,
4038 struct gl_shader_program *shProg,
4039 bool add_packed_varyings_only)
4040 {
4041 /* Rebuild resource list. */
4042 if (shProg->data->ProgramResourceList) {
4043 ralloc_free(shProg->data->ProgramResourceList);
4044 shProg->data->ProgramResourceList = NULL;
4045 shProg->data->NumProgramResourceList = 0;
4046 }
4047
4048 int input_stage = MESA_SHADER_STAGES, output_stage = 0;
4049
4050 /* Determine first input and final output stage. These are used to
4051 * detect which variables should be enumerated in the resource list
4052 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
4053 */
4054 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4055 if (!shProg->_LinkedShaders[i])
4056 continue;
4057 if (input_stage == MESA_SHADER_STAGES)
4058 input_stage = i;
4059 output_stage = i;
4060 }
4061
4062 /* Empty shader, no resources. */
4063 if (input_stage == MESA_SHADER_STAGES && output_stage == 0)
4064 return;
4065
4066 struct set *resource_set = _mesa_pointer_set_create(NULL);
4067
4068 /* Program interface needs to expose varyings in case of SSO. */
4069 if (shProg->SeparateShader) {
4070 if (!add_packed_varyings(ctx, shProg, resource_set,
4071 input_stage, GL_PROGRAM_INPUT))
4072 return;
4073
4074 if (!add_packed_varyings(ctx, shProg, resource_set,
4075 output_stage, GL_PROGRAM_OUTPUT))
4076 return;
4077 }
4078
4079 if (add_packed_varyings_only) {
4080 _mesa_set_destroy(resource_set, NULL);
4081 return;
4082 }
4083
4084 if (!add_fragdata_arrays(ctx, shProg, resource_set))
4085 return;
4086
4087 /* Add inputs and outputs to the resource list. */
4088 if (!add_interface_variables(ctx, shProg, resource_set,
4089 input_stage, GL_PROGRAM_INPUT))
4090 return;
4091
4092 if (!add_interface_variables(ctx, shProg, resource_set,
4093 output_stage, GL_PROGRAM_OUTPUT))
4094 return;
4095
4096 if (shProg->last_vert_prog) {
4097 struct gl_transform_feedback_info *linked_xfb =
4098 shProg->last_vert_prog->sh.LinkedTransformFeedback;
4099
4100 /* Add transform feedback varyings. */
4101 if (linked_xfb->NumVarying > 0) {
4102 for (int i = 0; i < linked_xfb->NumVarying; i++) {
4103 if (!link_util_add_program_resource(shProg, resource_set,
4104 GL_TRANSFORM_FEEDBACK_VARYING,
4105 &linked_xfb->Varyings[i], 0))
4106 return;
4107 }
4108 }
4109
4110 /* Add transform feedback buffers. */
4111 for (unsigned i = 0; i < ctx->Const.MaxTransformFeedbackBuffers; i++) {
4112 if ((linked_xfb->ActiveBuffers >> i) & 1) {
4113 linked_xfb->Buffers[i].Binding = i;
4114 if (!link_util_add_program_resource(shProg, resource_set,
4115 GL_TRANSFORM_FEEDBACK_BUFFER,
4116 &linked_xfb->Buffers[i], 0))
4117 return;
4118 }
4119 }
4120 }
4121
4122 int top_level_array_base_offset = -1;
4123 int top_level_array_size_in_bytes = -1;
4124 int second_element_offset = -1;
4125 int buffer_block_index = -1;
4126
4127 /* Add uniforms from uniform storage. */
4128 for (unsigned i = 0; i < shProg->data->NumUniformStorage; i++) {
4129 /* Do not add uniforms internally used by Mesa. */
4130 if (shProg->data->UniformStorage[i].hidden)
4131 continue;
4132
4133 bool is_shader_storage =
4134 shProg->data->UniformStorage[i].is_shader_storage;
4135 GLenum type = is_shader_storage ? GL_BUFFER_VARIABLE : GL_UNIFORM;
4136 if (!link_util_should_add_buffer_variable(shProg,
4137 &shProg->data->UniformStorage[i],
4138 top_level_array_base_offset,
4139 top_level_array_size_in_bytes,
4140 second_element_offset,
4141 buffer_block_index))
4142 continue;
4143
4144 if (is_shader_storage) {
4145 /* From the OpenGL 4.6 specification, 7.3.1.1 Naming Active Resources:
4146 *
4147 * "For an active shader storage block member declared as an array
4148 * of an aggregate type, an entry will be generated only for the
4149 * first array element, regardless of its type. Such block members
4150 * are referred to as top-level arrays. If the block member is an
4151 * aggregate type, the enumeration rules are then applied
4152 * recursively."
4153 *
4154 * Below we update our tracking values used by
4155 * link_util_should_add_buffer_variable(). We only want to reset the
4156 * offsets once we have moved past the first element.
4157 */
4158 if (shProg->data->UniformStorage[i].offset >= second_element_offset) {
4159 top_level_array_base_offset =
4160 shProg->data->UniformStorage[i].offset;
4161
4162 top_level_array_size_in_bytes =
4163 shProg->data->UniformStorage[i].top_level_array_size *
4164 shProg->data->UniformStorage[i].top_level_array_stride;
4165
4166 /* Set or reset the second element offset. For non arrays this
4167 * will be set to -1.
4168 */
4169 second_element_offset = top_level_array_size_in_bytes ?
4170 top_level_array_base_offset +
4171 shProg->data->UniformStorage[i].top_level_array_stride : -1;
4172 }
4173
4174 buffer_block_index = shProg->data->UniformStorage[i].block_index;
4175 }
4176
4177 uint8_t stageref = shProg->data->UniformStorage[i].active_shader_mask;
4178 if (!link_util_add_program_resource(shProg, resource_set, type,
4179 &shProg->data->UniformStorage[i], stageref))
4180 return;
4181 }
4182
4183 /* Add program uniform blocks. */
4184 for (unsigned i = 0; i < shProg->data->NumUniformBlocks; i++) {
4185 if (!link_util_add_program_resource(shProg, resource_set, GL_UNIFORM_BLOCK,
4186 &shProg->data->UniformBlocks[i], 0))
4187 return;
4188 }
4189
4190 /* Add program shader storage blocks. */
4191 for (unsigned i = 0; i < shProg->data->NumShaderStorageBlocks; i++) {
4192 if (!link_util_add_program_resource(shProg, resource_set, GL_SHADER_STORAGE_BLOCK,
4193 &shProg->data->ShaderStorageBlocks[i], 0))
4194 return;
4195 }
4196
4197 /* Add atomic counter buffers. */
4198 for (unsigned i = 0; i < shProg->data->NumAtomicBuffers; i++) {
4199 if (!link_util_add_program_resource(shProg, resource_set, GL_ATOMIC_COUNTER_BUFFER,
4200 &shProg->data->AtomicBuffers[i], 0))
4201 return;
4202 }
4203
4204 for (unsigned i = 0; i < shProg->data->NumUniformStorage; i++) {
4205 GLenum type;
4206 if (!shProg->data->UniformStorage[i].hidden)
4207 continue;
4208
4209 for (int j = MESA_SHADER_VERTEX; j < MESA_SHADER_STAGES; j++) {
4210 if (!shProg->data->UniformStorage[i].opaque[j].active ||
4211 !shProg->data->UniformStorage[i].type->is_subroutine())
4212 continue;
4213
4214 type = _mesa_shader_stage_to_subroutine_uniform((gl_shader_stage)j);
4215 /* add shader subroutines */
4216 if (!link_util_add_program_resource(shProg, resource_set,
4217 type, &shProg->data->UniformStorage[i], 0))
4218 return;
4219 }
4220 }
4221
4222 unsigned mask = shProg->data->linked_stages;
4223 while (mask) {
4224 const int i = u_bit_scan(&mask);
4225 struct gl_program *p = shProg->_LinkedShaders[i]->Program;
4226
4227 GLuint type = _mesa_shader_stage_to_subroutine((gl_shader_stage)i);
4228 for (unsigned j = 0; j < p->sh.NumSubroutineFunctions; j++) {
4229 if (!link_util_add_program_resource(shProg, resource_set,
4230 type, &p->sh.SubroutineFunctions[j], 0))
4231 return;
4232 }
4233 }
4234
4235 _mesa_set_destroy(resource_set, NULL);
4236 }
4237
4238 /**
4239 * This check is done to make sure we allow only constant expression
4240 * indexing and "constant-index-expression" (indexing with an expression
4241 * that includes loop induction variable).
4242 */
4243 static bool
4244 validate_sampler_array_indexing(struct gl_context *ctx,
4245 struct gl_shader_program *prog)
4246 {
4247 dynamic_sampler_array_indexing_visitor v;
4248 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4249 if (prog->_LinkedShaders[i] == NULL)
4250 continue;
4251
4252 bool no_dynamic_indexing =
4253 ctx->Const.ShaderCompilerOptions[i].EmitNoIndirectSampler;
4254
4255 /* Search for array derefs in shader. */
4256 v.run(prog->_LinkedShaders[i]->ir);
4257 if (v.uses_dynamic_sampler_array_indexing()) {
4258 const char *msg = "sampler arrays indexed with non-constant "
4259 "expressions is forbidden in GLSL %s %u";
4260 /* Backend has indicated that it has no dynamic indexing support. */
4261 if (no_dynamic_indexing) {
4262 linker_error(prog, msg, prog->IsES ? "ES" : "",
4263 prog->data->Version);
4264 return false;
4265 } else {
4266 linker_warning(prog, msg, prog->IsES ? "ES" : "",
4267 prog->data->Version);
4268 }
4269 }
4270 }
4271 return true;
4272 }
4273
4274 static void
4275 link_assign_subroutine_types(struct gl_shader_program *prog)
4276 {
4277 unsigned mask = prog->data->linked_stages;
4278 while (mask) {
4279 const int i = u_bit_scan(&mask);
4280 gl_program *p = prog->_LinkedShaders[i]->Program;
4281
4282 p->sh.MaxSubroutineFunctionIndex = 0;
4283 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
4284 ir_function *fn = node->as_function();
4285 if (!fn)
4286 continue;
4287
4288 if (fn->is_subroutine)
4289 p->sh.NumSubroutineUniformTypes++;
4290
4291 if (!fn->num_subroutine_types)
4292 continue;
4293
4294 /* these should have been calculated earlier. */
4295 assert(fn->subroutine_index != -1);
4296 if (p->sh.NumSubroutineFunctions + 1 > MAX_SUBROUTINES) {
4297 linker_error(prog, "Too many subroutine functions declared.\n");
4298 return;
4299 }
4300 p->sh.SubroutineFunctions = reralloc(p, p->sh.SubroutineFunctions,
4301 struct gl_subroutine_function,
4302 p->sh.NumSubroutineFunctions + 1);
4303 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].name = ralloc_strdup(p, fn->name);
4304 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].num_compat_types = fn->num_subroutine_types;
4305 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].types =
4306 ralloc_array(p, const struct glsl_type *,
4307 fn->num_subroutine_types);
4308
4309 /* From Section 4.4.4(Subroutine Function Layout Qualifiers) of the
4310 * GLSL 4.5 spec:
4311 *
4312 * "Each subroutine with an index qualifier in the shader must be
4313 * given a unique index, otherwise a compile or link error will be
4314 * generated."
4315 */
4316 for (unsigned j = 0; j < p->sh.NumSubroutineFunctions; j++) {
4317 if (p->sh.SubroutineFunctions[j].index != -1 &&
4318 p->sh.SubroutineFunctions[j].index == fn->subroutine_index) {
4319 linker_error(prog, "each subroutine index qualifier in the "
4320 "shader must be unique\n");
4321 return;
4322 }
4323 }
4324 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].index =
4325 fn->subroutine_index;
4326
4327 if (fn->subroutine_index > (int)p->sh.MaxSubroutineFunctionIndex)
4328 p->sh.MaxSubroutineFunctionIndex = fn->subroutine_index;
4329
4330 for (int j = 0; j < fn->num_subroutine_types; j++)
4331 p->sh.SubroutineFunctions[p->sh.NumSubroutineFunctions].types[j] = fn->subroutine_types[j];
4332 p->sh.NumSubroutineFunctions++;
4333 }
4334 }
4335 }
4336
4337 static void
4338 verify_subroutine_associated_funcs(struct gl_shader_program *prog)
4339 {
4340 unsigned mask = prog->data->linked_stages;
4341 while (mask) {
4342 const int i = u_bit_scan(&mask);
4343 gl_program *p = prog->_LinkedShaders[i]->Program;
4344 glsl_symbol_table *symbols = prog->_LinkedShaders[i]->symbols;
4345
4346 /* Section 6.1.2 (Subroutines) of the GLSL 4.00 spec says:
4347 *
4348 * "A program will fail to compile or link if any shader
4349 * or stage contains two or more functions with the same
4350 * name if the name is associated with a subroutine type."
4351 */
4352 for (unsigned j = 0; j < p->sh.NumSubroutineFunctions; j++) {
4353 unsigned definitions = 0;
4354 char *name = p->sh.SubroutineFunctions[j].name;
4355 ir_function *fn = symbols->get_function(name);
4356
4357 /* Calculate number of function definitions with the same name */
4358 foreach_in_list(ir_function_signature, sig, &fn->signatures) {
4359 if (sig->is_defined) {
4360 if (++definitions > 1) {
4361 linker_error(prog, "%s shader contains two or more function "
4362 "definitions with name `%s', which is "
4363 "associated with a subroutine type.\n",
4364 _mesa_shader_stage_to_string(i),
4365 fn->name);
4366 return;
4367 }
4368 }
4369 }
4370 }
4371 }
4372 }
4373
4374
4375 static void
4376 set_always_active_io(exec_list *ir, ir_variable_mode io_mode)
4377 {
4378 assert(io_mode == ir_var_shader_in || io_mode == ir_var_shader_out);
4379
4380 foreach_in_list(ir_instruction, node, ir) {
4381 ir_variable *const var = node->as_variable();
4382
4383 if (var == NULL || var->data.mode != io_mode)
4384 continue;
4385
4386 /* Don't set always active on builtins that haven't been redeclared */
4387 if (var->data.how_declared == ir_var_declared_implicitly)
4388 continue;
4389
4390 var->data.always_active_io = true;
4391 }
4392 }
4393
4394 /**
4395 * When separate shader programs are enabled, only input/outputs between
4396 * the stages of a multi-stage separate program can be safely removed
4397 * from the shader interface. Other inputs/outputs must remain active.
4398 */
4399 static void
4400 disable_varying_optimizations_for_sso(struct gl_shader_program *prog)
4401 {
4402 unsigned first, last;
4403 assert(prog->SeparateShader);
4404
4405 first = MESA_SHADER_STAGES;
4406 last = 0;
4407
4408 /* Determine first and last stage. Excluding the compute stage */
4409 for (unsigned i = 0; i < MESA_SHADER_COMPUTE; i++) {
4410 if (!prog->_LinkedShaders[i])
4411 continue;
4412 if (first == MESA_SHADER_STAGES)
4413 first = i;
4414 last = i;
4415 }
4416
4417 if (first == MESA_SHADER_STAGES)
4418 return;
4419
4420 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
4421 gl_linked_shader *sh = prog->_LinkedShaders[stage];
4422 if (!sh)
4423 continue;
4424
4425 /* Prevent the removal of inputs to the first and outputs from the last
4426 * stage, unless they are the initial pipeline inputs or final pipeline
4427 * outputs, respectively.
4428 *
4429 * The removal of IO between shaders in the same program is always
4430 * allowed.
4431 */
4432 if (stage == first && stage != MESA_SHADER_VERTEX)
4433 set_always_active_io(sh->ir, ir_var_shader_in);
4434 if (stage == last && stage != MESA_SHADER_FRAGMENT)
4435 set_always_active_io(sh->ir, ir_var_shader_out);
4436 }
4437 }
4438
4439 static void
4440 link_and_validate_uniforms(struct gl_context *ctx,
4441 struct gl_shader_program *prog)
4442 {
4443 update_array_sizes(prog);
4444
4445 if (!ctx->Const.UseNIRGLSLLinker) {
4446 link_assign_uniform_locations(prog, ctx);
4447
4448 if (prog->data->LinkStatus == LINKING_FAILURE)
4449 return;
4450
4451 link_util_calculate_subroutine_compat(prog);
4452 link_util_check_uniform_resources(ctx, prog);
4453 link_util_check_subroutine_resources(prog);
4454 check_image_resources(ctx, prog);
4455 link_assign_atomic_counter_resources(ctx, prog);
4456 link_check_atomic_counter_resources(ctx, prog);
4457 }
4458 }
4459
4460 static bool
4461 link_varyings_and_uniforms(unsigned first, unsigned last,
4462 struct gl_context *ctx,
4463 struct gl_shader_program *prog, void *mem_ctx)
4464 {
4465 /* Mark all generic shader inputs and outputs as unpaired. */
4466 for (unsigned i = MESA_SHADER_VERTEX; i <= MESA_SHADER_FRAGMENT; i++) {
4467 if (prog->_LinkedShaders[i] != NULL) {
4468 link_invalidate_variable_locations(prog->_LinkedShaders[i]->ir);
4469 }
4470 }
4471
4472 unsigned prev = first;
4473 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
4474 if (prog->_LinkedShaders[i] == NULL)
4475 continue;
4476
4477 match_explicit_outputs_to_inputs(prog->_LinkedShaders[prev],
4478 prog->_LinkedShaders[i]);
4479 prev = i;
4480 }
4481
4482 if (!assign_attribute_or_color_locations(mem_ctx, prog, &ctx->Const,
4483 MESA_SHADER_VERTEX, true)) {
4484 return false;
4485 }
4486
4487 if (!assign_attribute_or_color_locations(mem_ctx, prog, &ctx->Const,
4488 MESA_SHADER_FRAGMENT, true)) {
4489 return false;
4490 }
4491
4492 prog->last_vert_prog = NULL;
4493 for (int i = MESA_SHADER_GEOMETRY; i >= MESA_SHADER_VERTEX; i--) {
4494 if (prog->_LinkedShaders[i] == NULL)
4495 continue;
4496
4497 prog->last_vert_prog = prog->_LinkedShaders[i]->Program;
4498 break;
4499 }
4500
4501 if (!link_varyings(prog, first, last, ctx, mem_ctx))
4502 return false;
4503
4504 link_and_validate_uniforms(ctx, prog);
4505
4506 if (!prog->data->LinkStatus)
4507 return false;
4508
4509 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4510 if (prog->_LinkedShaders[i] == NULL)
4511 continue;
4512
4513 const struct gl_shader_compiler_options *options =
4514 &ctx->Const.ShaderCompilerOptions[i];
4515
4516 if (options->LowerBufferInterfaceBlocks)
4517 lower_ubo_reference(prog->_LinkedShaders[i],
4518 options->ClampBlockIndicesToArrayBounds,
4519 ctx->Const.UseSTD430AsDefaultPacking);
4520
4521 if (i == MESA_SHADER_COMPUTE)
4522 lower_shared_reference(ctx, prog, prog->_LinkedShaders[i]);
4523
4524 lower_vector_derefs(prog->_LinkedShaders[i]);
4525 do_vec_index_to_swizzle(prog->_LinkedShaders[i]->ir);
4526 }
4527
4528 return true;
4529 }
4530
4531 static void
4532 linker_optimisation_loop(struct gl_context *ctx, exec_list *ir,
4533 unsigned stage)
4534 {
4535 if (ctx->Const.GLSLOptimizeConservatively) {
4536 /* Run it just once. */
4537 do_common_optimization(ir, true, false,
4538 &ctx->Const.ShaderCompilerOptions[stage],
4539 ctx->Const.NativeIntegers);
4540 } else {
4541 /* Repeat it until it stops making changes. */
4542 while (do_common_optimization(ir, true, false,
4543 &ctx->Const.ShaderCompilerOptions[stage],
4544 ctx->Const.NativeIntegers))
4545 ;
4546 }
4547 }
4548
4549 void
4550 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
4551 {
4552 prog->data->LinkStatus = LINKING_SUCCESS; /* All error paths will set this to false */
4553 prog->data->Validated = false;
4554
4555 /* Section 7.3 (Program Objects) of the OpenGL 4.5 Core Profile spec says:
4556 *
4557 * "Linking can fail for a variety of reasons as specified in the
4558 * OpenGL Shading Language Specification, as well as any of the
4559 * following reasons:
4560 *
4561 * - No shader objects are attached to program."
4562 *
4563 * The Compatibility Profile specification does not list the error. In
4564 * Compatibility Profile missing shader stages are replaced by
4565 * fixed-function. This applies to the case where all stages are
4566 * missing.
4567 */
4568 if (prog->NumShaders == 0) {
4569 if (ctx->API != API_OPENGL_COMPAT)
4570 linker_error(prog, "no shaders attached to the program\n");
4571 return;
4572 }
4573
4574 #ifdef ENABLE_SHADER_CACHE
4575 if (shader_cache_read_program_metadata(ctx, prog))
4576 return;
4577 #endif
4578
4579 void *mem_ctx = ralloc_context(NULL); // temporary linker context
4580
4581 prog->ARB_fragment_coord_conventions_enable = false;
4582
4583 /* Separate the shaders into groups based on their type.
4584 */
4585 struct gl_shader **shader_list[MESA_SHADER_STAGES];
4586 unsigned num_shaders[MESA_SHADER_STAGES];
4587
4588 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
4589 shader_list[i] = (struct gl_shader **)
4590 calloc(prog->NumShaders, sizeof(struct gl_shader *));
4591 num_shaders[i] = 0;
4592 }
4593
4594 unsigned min_version = UINT_MAX;
4595 unsigned max_version = 0;
4596 for (unsigned i = 0; i < prog->NumShaders; i++) {
4597 min_version = MIN2(min_version, prog->Shaders[i]->Version);
4598 max_version = MAX2(max_version, prog->Shaders[i]->Version);
4599
4600 if (!ctx->Const.AllowGLSLRelaxedES &&
4601 prog->Shaders[i]->IsES != prog->Shaders[0]->IsES) {
4602 linker_error(prog, "all shaders must use same shading "
4603 "language version\n");
4604 goto done;
4605 }
4606
4607 if (prog->Shaders[i]->ARB_fragment_coord_conventions_enable) {
4608 prog->ARB_fragment_coord_conventions_enable = true;
4609 }
4610
4611 gl_shader_stage shader_type = prog->Shaders[i]->Stage;
4612 shader_list[shader_type][num_shaders[shader_type]] = prog->Shaders[i];
4613 num_shaders[shader_type]++;
4614 }
4615
4616 /* In desktop GLSL, different shader versions may be linked together. In
4617 * GLSL ES, all shader versions must be the same.
4618 */
4619 if (!ctx->Const.AllowGLSLRelaxedES && prog->Shaders[0]->IsES &&
4620 min_version != max_version) {
4621 linker_error(prog, "all shaders must use same shading "
4622 "language version\n");
4623 goto done;
4624 }
4625
4626 prog->data->Version = max_version;
4627 prog->IsES = prog->Shaders[0]->IsES;
4628
4629 /* Some shaders have to be linked with some other shaders present.
4630 */
4631 if (!prog->SeparateShader) {
4632 if (num_shaders[MESA_SHADER_GEOMETRY] > 0 &&
4633 num_shaders[MESA_SHADER_VERTEX] == 0) {
4634 linker_error(prog, "Geometry shader must be linked with "
4635 "vertex shader\n");
4636 goto done;
4637 }
4638 if (num_shaders[MESA_SHADER_TESS_EVAL] > 0 &&
4639 num_shaders[MESA_SHADER_VERTEX] == 0) {
4640 linker_error(prog, "Tessellation evaluation shader must be linked "
4641 "with vertex shader\n");
4642 goto done;
4643 }
4644 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
4645 num_shaders[MESA_SHADER_VERTEX] == 0) {
4646 linker_error(prog, "Tessellation control shader must be linked with "
4647 "vertex shader\n");
4648 goto done;
4649 }
4650
4651 /* Section 7.3 of the OpenGL ES 3.2 specification says:
4652 *
4653 * "Linking can fail for [...] any of the following reasons:
4654 *
4655 * * program contains an object to form a tessellation control
4656 * shader [...] and [...] the program is not separable and
4657 * contains no object to form a tessellation evaluation shader"
4658 *
4659 * The OpenGL spec is contradictory. It allows linking without a tess
4660 * eval shader, but that can only be used with transform feedback and
4661 * rasterization disabled. However, transform feedback isn't allowed
4662 * with GL_PATCHES, so it can't be used.
4663 *
4664 * More investigation showed that the idea of transform feedback after
4665 * a tess control shader was dropped, because some hw vendors couldn't
4666 * support tessellation without a tess eval shader, but the linker
4667 * section wasn't updated to reflect that.
4668 *
4669 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
4670 * spec bug.
4671 *
4672 * Do what's reasonable and always require a tess eval shader if a tess
4673 * control shader is present.
4674 */
4675 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
4676 num_shaders[MESA_SHADER_TESS_EVAL] == 0) {
4677 linker_error(prog, "Tessellation control shader must be linked with "
4678 "tessellation evaluation shader\n");
4679 goto done;
4680 }
4681
4682 if (prog->IsES) {
4683 if (num_shaders[MESA_SHADER_TESS_EVAL] > 0 &&
4684 num_shaders[MESA_SHADER_TESS_CTRL] == 0) {
4685 linker_error(prog, "GLSL ES requires non-separable programs "
4686 "containing a tessellation evaluation shader to also "
4687 "be linked with a tessellation control shader\n");
4688 goto done;
4689 }
4690 }
4691 }
4692
4693 /* Compute shaders have additional restrictions. */
4694 if (num_shaders[MESA_SHADER_COMPUTE] > 0 &&
4695 num_shaders[MESA_SHADER_COMPUTE] != prog->NumShaders) {
4696 linker_error(prog, "Compute shaders may not be linked with any other "
4697 "type of shader\n");
4698 }
4699
4700 /* Link all shaders for a particular stage and validate the result.
4701 */
4702 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
4703 if (num_shaders[stage] > 0) {
4704 gl_linked_shader *const sh =
4705 link_intrastage_shaders(mem_ctx, ctx, prog, shader_list[stage],
4706 num_shaders[stage], false);
4707
4708 if (!prog->data->LinkStatus) {
4709 if (sh)
4710 _mesa_delete_linked_shader(ctx, sh);
4711 goto done;
4712 }
4713
4714 switch (stage) {
4715 case MESA_SHADER_VERTEX:
4716 validate_vertex_shader_executable(prog, sh, ctx);
4717 break;
4718 case MESA_SHADER_TESS_CTRL:
4719 /* nothing to be done */
4720 break;
4721 case MESA_SHADER_TESS_EVAL:
4722 validate_tess_eval_shader_executable(prog, sh, ctx);
4723 break;
4724 case MESA_SHADER_GEOMETRY:
4725 validate_geometry_shader_executable(prog, sh, ctx);
4726 break;
4727 case MESA_SHADER_FRAGMENT:
4728 validate_fragment_shader_executable(prog, sh);
4729 break;
4730 }
4731 if (!prog->data->LinkStatus) {
4732 if (sh)
4733 _mesa_delete_linked_shader(ctx, sh);
4734 goto done;
4735 }
4736
4737 prog->_LinkedShaders[stage] = sh;
4738 prog->data->linked_stages |= 1 << stage;
4739 }
4740 }
4741
4742 /* Here begins the inter-stage linking phase. Some initial validation is
4743 * performed, then locations are assigned for uniforms, attributes, and
4744 * varyings.
4745 */
4746 cross_validate_uniforms(ctx, prog);
4747 if (!prog->data->LinkStatus)
4748 goto done;
4749
4750 unsigned first, last, prev;
4751
4752 first = MESA_SHADER_STAGES;
4753 last = 0;
4754
4755 /* Determine first and last stage. */
4756 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4757 if (!prog->_LinkedShaders[i])
4758 continue;
4759 if (first == MESA_SHADER_STAGES)
4760 first = i;
4761 last = i;
4762 }
4763
4764 check_explicit_uniform_locations(ctx, prog);
4765 link_assign_subroutine_types(prog);
4766 verify_subroutine_associated_funcs(prog);
4767
4768 if (!prog->data->LinkStatus)
4769 goto done;
4770
4771 resize_tes_inputs(ctx, prog);
4772
4773 /* Validate the inputs of each stage with the output of the preceding
4774 * stage.
4775 */
4776 prev = first;
4777 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
4778 if (prog->_LinkedShaders[i] == NULL)
4779 continue;
4780
4781 validate_interstage_inout_blocks(prog, prog->_LinkedShaders[prev],
4782 prog->_LinkedShaders[i]);
4783 if (!prog->data->LinkStatus)
4784 goto done;
4785
4786 cross_validate_outputs_to_inputs(ctx, prog,
4787 prog->_LinkedShaders[prev],
4788 prog->_LinkedShaders[i]);
4789 if (!prog->data->LinkStatus)
4790 goto done;
4791
4792 prev = i;
4793 }
4794
4795 /* The cross validation of outputs/inputs above validates interstage
4796 * explicit locations. We need to do this also for the inputs in the first
4797 * stage and outputs of the last stage included in the program, since there
4798 * is no cross validation for these.
4799 */
4800 validate_first_and_last_interface_explicit_locations(ctx, prog,
4801 (gl_shader_stage) first,
4802 (gl_shader_stage) last);
4803
4804 /* Cross-validate uniform blocks between shader stages */
4805 validate_interstage_uniform_blocks(prog, prog->_LinkedShaders);
4806 if (!prog->data->LinkStatus)
4807 goto done;
4808
4809 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
4810 if (prog->_LinkedShaders[i] != NULL)
4811 lower_named_interface_blocks(mem_ctx, prog->_LinkedShaders[i]);
4812 }
4813
4814 if (prog->IsES && prog->data->Version == 100)
4815 if (!validate_invariant_builtins(prog,
4816 prog->_LinkedShaders[MESA_SHADER_VERTEX],
4817 prog->_LinkedShaders[MESA_SHADER_FRAGMENT]))
4818 goto done;
4819
4820 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
4821 * it before optimization because we want most of the checks to get
4822 * dropped thanks to constant propagation.
4823 *
4824 * This rule also applies to GLSL ES 3.00.
4825 */
4826 if (max_version >= (prog->IsES ? 300 : 130)) {
4827 struct gl_linked_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
4828 if (sh) {
4829 lower_discard_flow(sh->ir);
4830 }
4831 }
4832
4833 if (prog->SeparateShader)
4834 disable_varying_optimizations_for_sso(prog);
4835
4836 /* Process UBOs */
4837 if (!interstage_cross_validate_uniform_blocks(prog, false))
4838 goto done;
4839
4840 /* Process SSBOs */
4841 if (!interstage_cross_validate_uniform_blocks(prog, true))
4842 goto done;
4843
4844 /* Do common optimization before assigning storage for attributes,
4845 * uniforms, and varyings. Later optimization could possibly make
4846 * some of that unused.
4847 */
4848 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4849 if (prog->_LinkedShaders[i] == NULL)
4850 continue;
4851
4852 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
4853 if (!prog->data->LinkStatus)
4854 goto done;
4855
4856 if (ctx->Const.ShaderCompilerOptions[i].LowerCombinedClipCullDistance) {
4857 lower_clip_cull_distance(prog, prog->_LinkedShaders[i]);
4858 }
4859
4860 if (ctx->Const.LowerTessLevel) {
4861 lower_tess_level(prog->_LinkedShaders[i]);
4862 }
4863
4864 /* Section 13.46 (Vertex Attribute Aliasing) of the OpenGL ES 3.2
4865 * specification says:
4866 *
4867 * "In general, the behavior of GLSL ES should not depend on compiler
4868 * optimizations which might be implementation-dependent. Name matching
4869 * rules in most languages, including C++ from which GLSL ES is derived,
4870 * are based on declarations rather than use.
4871 *
4872 * RESOLUTION: The existence of aliasing is determined by declarations
4873 * present after preprocessing."
4874 *
4875 * Because of this rule, we do a 'dry-run' of attribute assignment for
4876 * vertex shader inputs here.
4877 */
4878 if (prog->IsES && i == MESA_SHADER_VERTEX) {
4879 if (!assign_attribute_or_color_locations(mem_ctx, prog, &ctx->Const,
4880 MESA_SHADER_VERTEX, false)) {
4881 goto done;
4882 }
4883 }
4884
4885 /* Call opts before lowering const arrays to uniforms so we can const
4886 * propagate any elements accessed directly.
4887 */
4888 linker_optimisation_loop(ctx, prog->_LinkedShaders[i]->ir, i);
4889
4890 /* Call opts after lowering const arrays to copy propagate things. */
4891 if (ctx->Const.GLSLLowerConstArrays &&
4892 lower_const_arrays_to_uniforms(prog->_LinkedShaders[i]->ir, i,
4893 ctx->Const.Program[i].MaxUniformComponents))
4894 linker_optimisation_loop(ctx, prog->_LinkedShaders[i]->ir, i);
4895
4896 }
4897
4898 /* Validation for special cases where we allow sampler array indexing
4899 * with loop induction variable. This check emits a warning or error
4900 * depending if backend can handle dynamic indexing.
4901 */
4902 if ((!prog->IsES && prog->data->Version < 130) ||
4903 (prog->IsES && prog->data->Version < 300)) {
4904 if (!validate_sampler_array_indexing(ctx, prog))
4905 goto done;
4906 }
4907
4908 /* Check and validate stream emissions in geometry shaders */
4909 validate_geometry_shader_emissions(ctx, prog);
4910
4911 store_fragdepth_layout(prog);
4912
4913 if(!link_varyings_and_uniforms(first, last, ctx, prog, mem_ctx))
4914 goto done;
4915
4916 /* Linking varyings can cause some extra, useless swizzles to be generated
4917 * due to packing and unpacking.
4918 */
4919 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4920 if (prog->_LinkedShaders[i] == NULL)
4921 continue;
4922
4923 optimize_swizzles(prog->_LinkedShaders[i]->ir);
4924 }
4925
4926 /* OpenGL ES < 3.1 requires that a vertex shader and a fragment shader both
4927 * be present in a linked program. GL_ARB_ES2_compatibility doesn't say
4928 * anything about shader linking when one of the shaders (vertex or
4929 * fragment shader) is absent. So, the extension shouldn't change the
4930 * behavior specified in GLSL specification.
4931 *
4932 * From OpenGL ES 3.1 specification (7.3 Program Objects):
4933 * "Linking can fail for a variety of reasons as specified in the
4934 * OpenGL ES Shading Language Specification, as well as any of the
4935 * following reasons:
4936 *
4937 * ...
4938 *
4939 * * program contains objects to form either a vertex shader or
4940 * fragment shader, and program is not separable, and does not
4941 * contain objects to form both a vertex shader and fragment
4942 * shader."
4943 *
4944 * However, the only scenario in 3.1+ where we don't require them both is
4945 * when we have a compute shader. For example:
4946 *
4947 * - No shaders is a link error.
4948 * - Geom or Tess without a Vertex shader is a link error which means we
4949 * always require a Vertex shader and hence a Fragment shader.
4950 * - Finally a Compute shader linked with any other stage is a link error.
4951 */
4952 if (!prog->SeparateShader && ctx->API == API_OPENGLES2 &&
4953 num_shaders[MESA_SHADER_COMPUTE] == 0) {
4954 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
4955 linker_error(prog, "program lacks a vertex shader\n");
4956 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
4957 linker_error(prog, "program lacks a fragment shader\n");
4958 }
4959 }
4960
4961 done:
4962 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
4963 free(shader_list[i]);
4964 if (prog->_LinkedShaders[i] == NULL)
4965 continue;
4966
4967 /* Do a final validation step to make sure that the IR wasn't
4968 * invalidated by any modifications performed after intrastage linking.
4969 */
4970 validate_ir_tree(prog->_LinkedShaders[i]->ir);
4971
4972 /* Retain any live IR, but trash the rest. */
4973 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
4974
4975 /* The symbol table in the linked shaders may contain references to
4976 * variables that were removed (e.g., unused uniforms). Since it may
4977 * contain junk, there is no possible valid use. Delete it and set the
4978 * pointer to NULL.
4979 */
4980 delete prog->_LinkedShaders[i]->symbols;
4981 prog->_LinkedShaders[i]->symbols = NULL;
4982 }
4983
4984 ralloc_free(mem_ctx);
4985 }