OSDN Git Service

glsl: validate sampler array indexing for 'constant-index-expression'
[android-x86/external-mesa.git] / src / glsl / linker.cpp
1 /*
2  * Copyright © 2010 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  */
23
24 /**
25  * \file linker.cpp
26  * GLSL linker implementation
27  *
28  * Given a set of shaders that are to be linked to generate a final program,
29  * there are three distinct stages.
30  *
31  * In the first stage shaders are partitioned into groups based on the shader
32  * type.  All shaders of a particular type (e.g., vertex shaders) are linked
33  * together.
34  *
35  *   - Undefined references in each shader are resolve to definitions in
36  *     another shader.
37  *   - Types and qualifiers of uniforms, outputs, and global variables defined
38  *     in multiple shaders with the same name are verified to be the same.
39  *   - Initializers for uniforms and global variables defined
40  *     in multiple shaders with the same name are verified to be the same.
41  *
42  * The result, in the terminology of the GLSL spec, is a set of shader
43  * executables for each processing unit.
44  *
45  * After the first stage is complete, a series of semantic checks are performed
46  * on each of the shader executables.
47  *
48  *   - Each shader executable must define a \c main function.
49  *   - Each vertex shader executable must write to \c gl_Position.
50  *   - Each fragment shader executable must write to either \c gl_FragData or
51  *     \c gl_FragColor.
52  *
53  * In the final stage individual shader executables are linked to create a
54  * complete exectuable.
55  *
56  *   - Types of uniforms defined in multiple shader stages with the same name
57  *     are verified to be the same.
58  *   - Initializers for uniforms defined in multiple shader stages with the
59  *     same name are verified to be the same.
60  *   - Types and qualifiers of outputs defined in one stage are verified to
61  *     be the same as the types and qualifiers of inputs defined with the same
62  *     name in a later stage.
63  *
64  * \author Ian Romanick <ian.d.romanick@intel.com>
65  */
66
67 #include "main/core.h"
68 #include "glsl_symbol_table.h"
69 #include "glsl_parser_extras.h"
70 #include "ir.h"
71 #include "program.h"
72 #include "program/hash_table.h"
73 #include "linker.h"
74 #include "link_varyings.h"
75 #include "ir_optimization.h"
76 #include "ir_rvalue_visitor.h"
77 #include "ir_uniform.h"
78
79 #include "main/shaderobj.h"
80 #include "main/enums.h"
81
82
83 void linker_error(gl_shader_program *, const char *, ...);
84
85 namespace {
86
87 /**
88  * Visitor that determines whether or not a variable is ever written.
89  */
90 class find_assignment_visitor : public ir_hierarchical_visitor {
91 public:
92    find_assignment_visitor(const char *name)
93       : name(name), found(false)
94    {
95       /* empty */
96    }
97
98    virtual ir_visitor_status visit_enter(ir_assignment *ir)
99    {
100       ir_variable *const var = ir->lhs->variable_referenced();
101
102       if (strcmp(name, var->name) == 0) {
103          found = true;
104          return visit_stop;
105       }
106
107       return visit_continue_with_parent;
108    }
109
110    virtual ir_visitor_status visit_enter(ir_call *ir)
111    {
112       foreach_two_lists(formal_node, &ir->callee->parameters,
113                         actual_node, &ir->actual_parameters) {
114          ir_rvalue *param_rval = (ir_rvalue *) actual_node;
115          ir_variable *sig_param = (ir_variable *) formal_node;
116
117          if (sig_param->data.mode == ir_var_function_out ||
118              sig_param->data.mode == ir_var_function_inout) {
119             ir_variable *var = param_rval->variable_referenced();
120             if (var && strcmp(name, var->name) == 0) {
121                found = true;
122                return visit_stop;
123             }
124          }
125       }
126
127       if (ir->return_deref != NULL) {
128          ir_variable *const var = ir->return_deref->variable_referenced();
129
130          if (strcmp(name, var->name) == 0) {
131             found = true;
132             return visit_stop;
133          }
134       }
135
136       return visit_continue_with_parent;
137    }
138
139    bool variable_found()
140    {
141       return found;
142    }
143
144 private:
145    const char *name;       /**< Find writes to a variable with this name. */
146    bool found;             /**< Was a write to the variable found? */
147 };
148
149
150 /**
151  * Visitor that determines whether or not a variable is ever read.
152  */
153 class find_deref_visitor : public ir_hierarchical_visitor {
154 public:
155    find_deref_visitor(const char *name)
156       : name(name), found(false)
157    {
158       /* empty */
159    }
160
161    virtual ir_visitor_status visit(ir_dereference_variable *ir)
162    {
163       if (strcmp(this->name, ir->var->name) == 0) {
164          this->found = true;
165          return visit_stop;
166       }
167
168       return visit_continue;
169    }
170
171    bool variable_found() const
172    {
173       return this->found;
174    }
175
176 private:
177    const char *name;       /**< Find writes to a variable with this name. */
178    bool found;             /**< Was a write to the variable found? */
179 };
180
181
182 class geom_array_resize_visitor : public ir_hierarchical_visitor {
183 public:
184    unsigned num_vertices;
185    gl_shader_program *prog;
186
187    geom_array_resize_visitor(unsigned num_vertices, gl_shader_program *prog)
188    {
189       this->num_vertices = num_vertices;
190       this->prog = prog;
191    }
192
193    virtual ~geom_array_resize_visitor()
194    {
195       /* empty */
196    }
197
198    virtual ir_visitor_status visit(ir_variable *var)
199    {
200       if (!var->type->is_array() || var->data.mode != ir_var_shader_in)
201          return visit_continue;
202
203       unsigned size = var->type->length;
204
205       /* Generate a link error if the shader has declared this array with an
206        * incorrect size.
207        */
208       if (size && size != this->num_vertices) {
209          linker_error(this->prog, "size of array %s declared as %u, "
210                       "but number of input vertices is %u\n",
211                       var->name, size, this->num_vertices);
212          return visit_continue;
213       }
214
215       /* Generate a link error if the shader attempts to access an input
216        * array using an index too large for its actual size assigned at link
217        * time.
218        */
219       if (var->data.max_array_access >= this->num_vertices) {
220          linker_error(this->prog, "geometry shader accesses element %i of "
221                       "%s, but only %i input vertices\n",
222                       var->data.max_array_access, var->name, this->num_vertices);
223          return visit_continue;
224       }
225
226       var->type = glsl_type::get_array_instance(var->type->element_type(),
227                                                 this->num_vertices);
228       var->data.max_array_access = this->num_vertices - 1;
229
230       return visit_continue;
231    }
232
233    /* Dereferences of input variables need to be updated so that their type
234     * matches the newly assigned type of the variable they are accessing. */
235    virtual ir_visitor_status visit(ir_dereference_variable *ir)
236    {
237       ir->type = ir->var->type;
238       return visit_continue;
239    }
240
241    /* Dereferences of 2D input arrays need to be updated so that their type
242     * matches the newly assigned type of the array they are accessing. */
243    virtual ir_visitor_status visit_leave(ir_dereference_array *ir)
244    {
245       const glsl_type *const vt = ir->array->type;
246       if (vt->is_array())
247          ir->type = vt->element_type();
248       return visit_continue;
249    }
250 };
251
252 /**
253  * Visitor that determines the highest stream id to which a (geometry) shader
254  * emits vertices. It also checks whether End{Stream}Primitive is ever called.
255  */
256 class find_emit_vertex_visitor : public ir_hierarchical_visitor {
257 public:
258    find_emit_vertex_visitor(int max_allowed)
259       : max_stream_allowed(max_allowed),
260         invalid_stream_id(0),
261         invalid_stream_id_from_emit_vertex(false),
262         end_primitive_found(false),
263         uses_non_zero_stream(false)
264    {
265       /* empty */
266    }
267
268    virtual ir_visitor_status visit_leave(ir_emit_vertex *ir)
269    {
270       int stream_id = ir->stream_id();
271
272       if (stream_id < 0) {
273          invalid_stream_id = stream_id;
274          invalid_stream_id_from_emit_vertex = true;
275          return visit_stop;
276       }
277
278       if (stream_id > max_stream_allowed) {
279          invalid_stream_id = stream_id;
280          invalid_stream_id_from_emit_vertex = true;
281          return visit_stop;
282       }
283
284       if (stream_id != 0)
285          uses_non_zero_stream = true;
286
287       return visit_continue;
288    }
289
290    virtual ir_visitor_status visit_leave(ir_end_primitive *ir)
291    {
292       end_primitive_found = true;
293
294       int stream_id = ir->stream_id();
295
296       if (stream_id < 0) {
297          invalid_stream_id = stream_id;
298          invalid_stream_id_from_emit_vertex = false;
299          return visit_stop;
300       }
301
302       if (stream_id > max_stream_allowed) {
303          invalid_stream_id = stream_id;
304          invalid_stream_id_from_emit_vertex = false;
305          return visit_stop;
306       }
307
308       if (stream_id != 0)
309          uses_non_zero_stream = true;
310
311       return visit_continue;
312    }
313
314    bool error()
315    {
316       return invalid_stream_id != 0;
317    }
318
319    const char *error_func()
320    {
321       return invalid_stream_id_from_emit_vertex ?
322          "EmitStreamVertex" : "EndStreamPrimitive";
323    }
324
325    int error_stream()
326    {
327       return invalid_stream_id;
328    }
329
330    bool uses_streams()
331    {
332       return uses_non_zero_stream;
333    }
334
335    bool uses_end_primitive()
336    {
337       return end_primitive_found;
338    }
339
340 private:
341    int max_stream_allowed;
342    int invalid_stream_id;
343    bool invalid_stream_id_from_emit_vertex;
344    bool end_primitive_found;
345    bool uses_non_zero_stream;
346 };
347
348 /* Class that finds array derefs and check if indexes are dynamic. */
349 class dynamic_sampler_array_indexing_visitor : public ir_hierarchical_visitor
350 {
351 public:
352    dynamic_sampler_array_indexing_visitor() :
353       dynamic_sampler_array_indexing(false)
354    {
355    }
356
357    ir_visitor_status visit_enter(ir_dereference_array *ir)
358    {
359       if (!ir->variable_referenced())
360          return visit_continue;
361
362       if (!ir->variable_referenced()->type->contains_sampler())
363          return visit_continue;
364
365       if (!ir->array_index->constant_expression_value()) {
366          dynamic_sampler_array_indexing = true;
367          return visit_stop;
368       }
369       return visit_continue;
370    }
371
372    bool uses_dynamic_sampler_array_indexing()
373    {
374       return dynamic_sampler_array_indexing;
375    }
376
377 private:
378    bool dynamic_sampler_array_indexing;
379 };
380
381 } /* anonymous namespace */
382
383 void
384 linker_error(gl_shader_program *prog, const char *fmt, ...)
385 {
386    va_list ap;
387
388    ralloc_strcat(&prog->InfoLog, "error: ");
389    va_start(ap, fmt);
390    ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
391    va_end(ap);
392
393    prog->LinkStatus = false;
394 }
395
396
397 void
398 linker_warning(gl_shader_program *prog, const char *fmt, ...)
399 {
400    va_list ap;
401
402    ralloc_strcat(&prog->InfoLog, "warning: ");
403    va_start(ap, fmt);
404    ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
405    va_end(ap);
406
407 }
408
409
410 /**
411  * Given a string identifying a program resource, break it into a base name
412  * and an optional array index in square brackets.
413  *
414  * If an array index is present, \c out_base_name_end is set to point to the
415  * "[" that precedes the array index, and the array index itself is returned
416  * as a long.
417  *
418  * If no array index is present (or if the array index is negative or
419  * mal-formed), \c out_base_name_end, is set to point to the null terminator
420  * at the end of the input string, and -1 is returned.
421  *
422  * Only the final array index is parsed; if the string contains other array
423  * indices (or structure field accesses), they are left in the base name.
424  *
425  * No attempt is made to check that the base name is properly formed;
426  * typically the caller will look up the base name in a hash table, so
427  * ill-formed base names simply turn into hash table lookup failures.
428  */
429 long
430 parse_program_resource_name(const GLchar *name,
431                             const GLchar **out_base_name_end)
432 {
433    /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
434     *
435     *     "When an integer array element or block instance number is part of
436     *     the name string, it will be specified in decimal form without a "+"
437     *     or "-" sign or any extra leading zeroes. Additionally, the name
438     *     string will not include white space anywhere in the string."
439     */
440
441    const size_t len = strlen(name);
442    *out_base_name_end = name + len;
443
444    if (len == 0 || name[len-1] != ']')
445       return -1;
446
447    /* Walk backwards over the string looking for a non-digit character.  This
448     * had better be the opening bracket for an array index.
449     *
450     * Initially, i specifies the location of the ']'.  Since the string may
451     * contain only the ']' charcater, walk backwards very carefully.
452     */
453    unsigned i;
454    for (i = len - 1; (i > 0) && isdigit(name[i-1]); --i)
455       /* empty */ ;
456
457    if ((i == 0) || name[i-1] != '[')
458       return -1;
459
460    long array_index = strtol(&name[i], NULL, 10);
461    if (array_index < 0)
462       return -1;
463
464    *out_base_name_end = name + (i - 1);
465    return array_index;
466 }
467
468
469 void
470 link_invalidate_variable_locations(exec_list *ir)
471 {
472    foreach_in_list(ir_instruction, node, ir) {
473       ir_variable *const var = node->as_variable();
474
475       if (var == NULL)
476          continue;
477
478       /* Only assign locations for variables that lack an explicit location.
479        * Explicit locations are set for all built-in variables, generic vertex
480        * shader inputs (via layout(location=...)), and generic fragment shader
481        * outputs (also via layout(location=...)).
482        */
483       if (!var->data.explicit_location) {
484          var->data.location = -1;
485          var->data.location_frac = 0;
486       }
487
488       /* ir_variable::is_unmatched_generic_inout is used by the linker while
489        * connecting outputs from one stage to inputs of the next stage.
490        *
491        * There are two implicit assumptions here.  First, we assume that any
492        * built-in variable (i.e., non-generic in or out) will have
493        * explicit_location set.  Second, we assume that any generic in or out
494        * will not have explicit_location set.
495        *
496        * This second assumption will only be valid until
497        * GL_ARB_separate_shader_objects is supported.  When that extension is
498        * implemented, this function will need some modifications.
499        */
500       if (!var->data.explicit_location) {
501          var->data.is_unmatched_generic_inout = 1;
502       } else {
503          var->data.is_unmatched_generic_inout = 0;
504       }
505    }
506 }
507
508
509 /**
510  * Set UsesClipDistance and ClipDistanceArraySize based on the given shader.
511  *
512  * Also check for errors based on incorrect usage of gl_ClipVertex and
513  * gl_ClipDistance.
514  *
515  * Return false if an error was reported.
516  */
517 static void
518 analyze_clip_usage(struct gl_shader_program *prog,
519                    struct gl_shader *shader, GLboolean *UsesClipDistance,
520                    GLuint *ClipDistanceArraySize)
521 {
522    *ClipDistanceArraySize = 0;
523
524    if (!prog->IsES && prog->Version >= 130) {
525       /* From section 7.1 (Vertex Shader Special Variables) of the
526        * GLSL 1.30 spec:
527        *
528        *   "It is an error for a shader to statically write both
529        *   gl_ClipVertex and gl_ClipDistance."
530        *
531        * This does not apply to GLSL ES shaders, since GLSL ES defines neither
532        * gl_ClipVertex nor gl_ClipDistance.
533        */
534       find_assignment_visitor clip_vertex("gl_ClipVertex");
535       find_assignment_visitor clip_distance("gl_ClipDistance");
536
537       clip_vertex.run(shader->ir);
538       clip_distance.run(shader->ir);
539       if (clip_vertex.variable_found() && clip_distance.variable_found()) {
540          linker_error(prog, "%s shader writes to both `gl_ClipVertex' "
541                       "and `gl_ClipDistance'\n",
542                       _mesa_shader_stage_to_string(shader->Stage));
543          return;
544       }
545       *UsesClipDistance = clip_distance.variable_found();
546       ir_variable *clip_distance_var =
547          shader->symbols->get_variable("gl_ClipDistance");
548       if (clip_distance_var)
549          *ClipDistanceArraySize = clip_distance_var->type->length;
550    } else {
551       *UsesClipDistance = false;
552    }
553 }
554
555
556 /**
557  * Verify that a vertex shader executable meets all semantic requirements.
558  *
559  * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
560  * as a side effect.
561  *
562  * \param shader  Vertex shader executable to be verified
563  */
564 void
565 validate_vertex_shader_executable(struct gl_shader_program *prog,
566                                   struct gl_shader *shader)
567 {
568    if (shader == NULL)
569       return;
570
571    /* From the GLSL 1.10 spec, page 48:
572     *
573     *     "The variable gl_Position is available only in the vertex
574     *      language and is intended for writing the homogeneous vertex
575     *      position. All executions of a well-formed vertex shader
576     *      executable must write a value into this variable. [...] The
577     *      variable gl_Position is available only in the vertex
578     *      language and is intended for writing the homogeneous vertex
579     *      position. All executions of a well-formed vertex shader
580     *      executable must write a value into this variable."
581     *
582     * while in GLSL 1.40 this text is changed to:
583     *
584     *     "The variable gl_Position is available only in the vertex
585     *      language and is intended for writing the homogeneous vertex
586     *      position. It can be written at any time during shader
587     *      execution. It may also be read back by a vertex shader
588     *      after being written. This value will be used by primitive
589     *      assembly, clipping, culling, and other fixed functionality
590     *      operations, if present, that operate on primitives after
591     *      vertex processing has occurred. Its value is undefined if
592     *      the vertex shader executable does not write gl_Position."
593     *
594     * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
595     * gl_Position is not an error.
596     */
597    if (prog->Version < (prog->IsES ? 300 : 140)) {
598       find_assignment_visitor find("gl_Position");
599       find.run(shader->ir);
600       if (!find.variable_found()) {
601         if (prog->IsES) {
602           linker_warning(prog,
603                          "vertex shader does not write to `gl_Position'."
604                          "It's value is undefined. \n");
605         } else {
606           linker_error(prog,
607                        "vertex shader does not write to `gl_Position'. \n");
608         }
609          return;
610       }
611    }
612
613    analyze_clip_usage(prog, shader, &prog->Vert.UsesClipDistance,
614                       &prog->Vert.ClipDistanceArraySize);
615 }
616
617
618 /**
619  * Verify that a fragment shader executable meets all semantic requirements
620  *
621  * \param shader  Fragment shader executable to be verified
622  */
623 void
624 validate_fragment_shader_executable(struct gl_shader_program *prog,
625                                     struct gl_shader *shader)
626 {
627    if (shader == NULL)
628       return;
629
630    find_assignment_visitor frag_color("gl_FragColor");
631    find_assignment_visitor frag_data("gl_FragData");
632
633    frag_color.run(shader->ir);
634    frag_data.run(shader->ir);
635
636    if (frag_color.variable_found() && frag_data.variable_found()) {
637       linker_error(prog,  "fragment shader writes to both "
638                    "`gl_FragColor' and `gl_FragData'\n");
639    }
640 }
641
642 /**
643  * Verify that a geometry shader executable meets all semantic requirements
644  *
645  * Also sets prog->Geom.VerticesIn, prog->Geom.UsesClipDistance, and
646  * prog->Geom.ClipDistanceArraySize as a side effect.
647  *
648  * \param shader Geometry shader executable to be verified
649  */
650 void
651 validate_geometry_shader_executable(struct gl_shader_program *prog,
652                                     struct gl_shader *shader)
653 {
654    if (shader == NULL)
655       return;
656
657    unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
658    prog->Geom.VerticesIn = num_vertices;
659
660    analyze_clip_usage(prog, shader, &prog->Geom.UsesClipDistance,
661                       &prog->Geom.ClipDistanceArraySize);
662 }
663
664 /**
665  * Check if geometry shaders emit to non-zero streams and do corresponding
666  * validations.
667  */
668 static void
669 validate_geometry_shader_emissions(struct gl_context *ctx,
670                                    struct gl_shader_program *prog)
671 {
672    if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
673       find_emit_vertex_visitor emit_vertex(ctx->Const.MaxVertexStreams - 1);
674       emit_vertex.run(prog->_LinkedShaders[MESA_SHADER_GEOMETRY]->ir);
675       if (emit_vertex.error()) {
676          linker_error(prog, "Invalid call %s(%d). Accepted values for the "
677                       "stream parameter are in the range [0, %d].\n",
678                       emit_vertex.error_func(),
679                       emit_vertex.error_stream(),
680                       ctx->Const.MaxVertexStreams - 1);
681       }
682       prog->Geom.UsesStreams = emit_vertex.uses_streams();
683       prog->Geom.UsesEndPrimitive = emit_vertex.uses_end_primitive();
684
685       /* From the ARB_gpu_shader5 spec:
686        *
687        *   "Multiple vertex streams are supported only if the output primitive
688        *    type is declared to be "points".  A program will fail to link if it
689        *    contains a geometry shader calling EmitStreamVertex() or
690        *    EndStreamPrimitive() if its output primitive type is not "points".
691        *
692        * However, in the same spec:
693        *
694        *   "The function EmitVertex() is equivalent to calling EmitStreamVertex()
695        *    with <stream> set to zero."
696        *
697        * And:
698        *
699        *   "The function EndPrimitive() is equivalent to calling
700        *    EndStreamPrimitive() with <stream> set to zero."
701        *
702        * Since we can call EmitVertex() and EndPrimitive() when we output
703        * primitives other than points, calling EmitStreamVertex(0) or
704        * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
705        * does. Currently we only set prog->Geom.UsesStreams to TRUE when
706        * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
707        * stream.
708        */
709       if (prog->Geom.UsesStreams && prog->Geom.OutputType != GL_POINTS) {
710          linker_error(prog, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
711                       "with n>0 requires point output\n");
712       }
713    }
714 }
715
716
717 /**
718  * Perform validation of global variables used across multiple shaders
719  */
720 void
721 cross_validate_globals(struct gl_shader_program *prog,
722                        struct gl_shader **shader_list,
723                        unsigned num_shaders,
724                        bool uniforms_only)
725 {
726    /* Examine all of the uniforms in all of the shaders and cross validate
727     * them.
728     */
729    glsl_symbol_table variables;
730    for (unsigned i = 0; i < num_shaders; i++) {
731       if (shader_list[i] == NULL)
732          continue;
733
734       foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
735          ir_variable *const var = node->as_variable();
736
737          if (var == NULL)
738             continue;
739
740          if (uniforms_only && (var->data.mode != ir_var_uniform))
741             continue;
742
743          /* Don't cross validate temporaries that are at global scope.  These
744           * will eventually get pulled into the shaders 'main'.
745           */
746          if (var->data.mode == ir_var_temporary)
747             continue;
748
749          /* If a global with this name has already been seen, verify that the
750           * new instance has the same type.  In addition, if the globals have
751           * initializers, the values of the initializers must be the same.
752           */
753          ir_variable *const existing = variables.get_variable(var->name);
754          if (existing != NULL) {
755             if (var->type != existing->type) {
756                /* Consider the types to be "the same" if both types are arrays
757                 * of the same type and one of the arrays is implicitly sized.
758                 * In addition, set the type of the linked variable to the
759                 * explicitly sized array.
760                 */
761                if (var->type->is_array()
762                    && existing->type->is_array()
763                    && (var->type->fields.array == existing->type->fields.array)
764                    && ((var->type->length == 0)
765                        || (existing->type->length == 0))) {
766                   if (var->type->length != 0) {
767                      if (var->type->length <= existing->data.max_array_access) {
768                         linker_error(prog, "%s `%s' declared as type "
769                                      "`%s' but outermost dimension has an index"
770                                      " of `%i'\n",
771                                      mode_string(var),
772                                      var->name, var->type->name,
773                                      existing->data.max_array_access);
774                         return;
775                      }
776                      existing->type = var->type;
777                   } else if (existing->type->length != 0
778                              && existing->type->length <=
779                                 var->data.max_array_access) {
780                      linker_error(prog, "%s `%s' declared as type "
781                                   "`%s' but outermost dimension has an index"
782                                   " of `%i'\n",
783                                   mode_string(var),
784                                   var->name, existing->type->name,
785                                   var->data.max_array_access);
786                      return;
787                   }
788                } else if (var->type->is_record()
789                    && existing->type->is_record()
790                    && existing->type->record_compare(var->type)) {
791                   existing->type = var->type;
792                } else {
793                   linker_error(prog, "%s `%s' declared as type "
794                                "`%s' and type `%s'\n",
795                                mode_string(var),
796                                var->name, var->type->name,
797                                existing->type->name);
798                   return;
799                }
800             }
801
802             if (var->data.explicit_location) {
803                if (existing->data.explicit_location
804                    && (var->data.location != existing->data.location)) {
805                      linker_error(prog, "explicit locations for %s "
806                                   "`%s' have differing values\n",
807                                   mode_string(var), var->name);
808                      return;
809                }
810
811                existing->data.location = var->data.location;
812                existing->data.explicit_location = true;
813             }
814
815             /* From the GLSL 4.20 specification:
816              * "A link error will result if two compilation units in a program
817              *  specify different integer-constant bindings for the same
818              *  opaque-uniform name.  However, it is not an error to specify a
819              *  binding on some but not all declarations for the same name"
820              */
821             if (var->data.explicit_binding) {
822                if (existing->data.explicit_binding &&
823                    var->data.binding != existing->data.binding) {
824                   linker_error(prog, "explicit bindings for %s "
825                                "`%s' have differing values\n",
826                                mode_string(var), var->name);
827                   return;
828                }
829
830                existing->data.binding = var->data.binding;
831                existing->data.explicit_binding = true;
832             }
833
834             if (var->type->contains_atomic() &&
835                 var->data.atomic.offset != existing->data.atomic.offset) {
836                linker_error(prog, "offset specifications for %s "
837                             "`%s' have differing values\n",
838                             mode_string(var), var->name);
839                return;
840             }
841
842             /* Validate layout qualifiers for gl_FragDepth.
843              *
844              * From the AMD/ARB_conservative_depth specs:
845              *
846              *    "If gl_FragDepth is redeclared in any fragment shader in a
847              *    program, it must be redeclared in all fragment shaders in
848              *    that program that have static assignments to
849              *    gl_FragDepth. All redeclarations of gl_FragDepth in all
850              *    fragment shaders in a single program must have the same set
851              *    of qualifiers."
852              */
853             if (strcmp(var->name, "gl_FragDepth") == 0) {
854                bool layout_declared = var->data.depth_layout != ir_depth_layout_none;
855                bool layout_differs =
856                   var->data.depth_layout != existing->data.depth_layout;
857
858                if (layout_declared && layout_differs) {
859                   linker_error(prog,
860                                "All redeclarations of gl_FragDepth in all "
861                                "fragment shaders in a single program must have "
862                                "the same set of qualifiers.\n");
863                }
864
865                if (var->data.used && layout_differs) {
866                   linker_error(prog,
867                                "If gl_FragDepth is redeclared with a layout "
868                                "qualifier in any fragment shader, it must be "
869                                "redeclared with the same layout qualifier in "
870                                "all fragment shaders that have assignments to "
871                                "gl_FragDepth\n");
872                }
873             }
874
875             /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
876              *
877              *     "If a shared global has multiple initializers, the
878              *     initializers must all be constant expressions, and they
879              *     must all have the same value. Otherwise, a link error will
880              *     result. (A shared global having only one initializer does
881              *     not require that initializer to be a constant expression.)"
882              *
883              * Previous to 4.20 the GLSL spec simply said that initializers
884              * must have the same value.  In this case of non-constant
885              * initializers, this was impossible to determine.  As a result,
886              * no vendor actually implemented that behavior.  The 4.20
887              * behavior matches the implemented behavior of at least one other
888              * vendor, so we'll implement that for all GLSL versions.
889              */
890             if (var->constant_initializer != NULL) {
891                if (existing->constant_initializer != NULL) {
892                   if (!var->constant_initializer->has_value(existing->constant_initializer)) {
893                      linker_error(prog, "initializers for %s "
894                                   "`%s' have differing values\n",
895                                   mode_string(var), var->name);
896                      return;
897                   }
898                } else {
899                   /* If the first-seen instance of a particular uniform did not
900                    * have an initializer but a later instance does, copy the
901                    * initializer to the version stored in the symbol table.
902                    */
903                   /* FINISHME: This is wrong.  The constant_value field should
904                    * FINISHME: not be modified!  Imagine a case where a shader
905                    * FINISHME: without an initializer is linked in two different
906                    * FINISHME: programs with shaders that have differing
907                    * FINISHME: initializers.  Linking with the first will
908                    * FINISHME: modify the shader, and linking with the second
909                    * FINISHME: will fail.
910                    */
911                   existing->constant_initializer =
912                      var->constant_initializer->clone(ralloc_parent(existing),
913                                                       NULL);
914                }
915             }
916
917             if (var->data.has_initializer) {
918                if (existing->data.has_initializer
919                    && (var->constant_initializer == NULL
920                        || existing->constant_initializer == NULL)) {
921                   linker_error(prog,
922                                "shared global variable `%s' has multiple "
923                                "non-constant initializers.\n",
924                                var->name);
925                   return;
926                }
927
928                /* Some instance had an initializer, so keep track of that.  In
929                 * this location, all sorts of initializers (constant or
930                 * otherwise) will propagate the existence to the variable
931                 * stored in the symbol table.
932                 */
933                existing->data.has_initializer = true;
934             }
935
936             if (existing->data.invariant != var->data.invariant) {
937                linker_error(prog, "declarations for %s `%s' have "
938                             "mismatching invariant qualifiers\n",
939                             mode_string(var), var->name);
940                return;
941             }
942             if (existing->data.centroid != var->data.centroid) {
943                linker_error(prog, "declarations for %s `%s' have "
944                             "mismatching centroid qualifiers\n",
945                             mode_string(var), var->name);
946                return;
947             }
948             if (existing->data.sample != var->data.sample) {
949                linker_error(prog, "declarations for %s `%s` have "
950                             "mismatching sample qualifiers\n",
951                             mode_string(var), var->name);
952                return;
953             }
954          } else
955             variables.add_variable(var);
956       }
957    }
958 }
959
960
961 /**
962  * Perform validation of uniforms used across multiple shader stages
963  */
964 void
965 cross_validate_uniforms(struct gl_shader_program *prog)
966 {
967    cross_validate_globals(prog, prog->_LinkedShaders,
968                           MESA_SHADER_STAGES, true);
969 }
970
971 /**
972  * Accumulates the array of prog->UniformBlocks and checks that all
973  * definitons of blocks agree on their contents.
974  */
975 static bool
976 interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog)
977 {
978    unsigned max_num_uniform_blocks = 0;
979    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
980       if (prog->_LinkedShaders[i])
981          max_num_uniform_blocks += prog->_LinkedShaders[i]->NumUniformBlocks;
982    }
983
984    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
985       struct gl_shader *sh = prog->_LinkedShaders[i];
986
987       prog->UniformBlockStageIndex[i] = ralloc_array(prog, int,
988                                                      max_num_uniform_blocks);
989       for (unsigned int j = 0; j < max_num_uniform_blocks; j++)
990          prog->UniformBlockStageIndex[i][j] = -1;
991
992       if (sh == NULL)
993          continue;
994
995       for (unsigned int j = 0; j < sh->NumUniformBlocks; j++) {
996          int index = link_cross_validate_uniform_block(prog,
997                                                        &prog->UniformBlocks,
998                                                        &prog->NumUniformBlocks,
999                                                        &sh->UniformBlocks[j]);
1000
1001          if (index == -1) {
1002             linker_error(prog, "uniform block `%s' has mismatching definitions\n",
1003                          sh->UniformBlocks[j].Name);
1004             return false;
1005          }
1006
1007          prog->UniformBlockStageIndex[i][index] = j;
1008       }
1009    }
1010
1011    return true;
1012 }
1013
1014
1015 /**
1016  * Populates a shaders symbol table with all global declarations
1017  */
1018 static void
1019 populate_symbol_table(gl_shader *sh)
1020 {
1021    sh->symbols = new(sh) glsl_symbol_table;
1022
1023    foreach_in_list(ir_instruction, inst, sh->ir) {
1024       ir_variable *var;
1025       ir_function *func;
1026
1027       if ((func = inst->as_function()) != NULL) {
1028          sh->symbols->add_function(func);
1029       } else if ((var = inst->as_variable()) != NULL) {
1030          if (var->data.mode != ir_var_temporary)
1031             sh->symbols->add_variable(var);
1032       }
1033    }
1034 }
1035
1036
1037 /**
1038  * Remap variables referenced in an instruction tree
1039  *
1040  * This is used when instruction trees are cloned from one shader and placed in
1041  * another.  These trees will contain references to \c ir_variable nodes that
1042  * do not exist in the target shader.  This function finds these \c ir_variable
1043  * references and replaces the references with matching variables in the target
1044  * shader.
1045  *
1046  * If there is no matching variable in the target shader, a clone of the
1047  * \c ir_variable is made and added to the target shader.  The new variable is
1048  * added to \b both the instruction stream and the symbol table.
1049  *
1050  * \param inst         IR tree that is to be processed.
1051  * \param symbols      Symbol table containing global scope symbols in the
1052  *                     linked shader.
1053  * \param instructions Instruction stream where new variable declarations
1054  *                     should be added.
1055  */
1056 void
1057 remap_variables(ir_instruction *inst, struct gl_shader *target,
1058                 hash_table *temps)
1059 {
1060    class remap_visitor : public ir_hierarchical_visitor {
1061    public:
1062          remap_visitor(struct gl_shader *target,
1063                     hash_table *temps)
1064       {
1065          this->target = target;
1066          this->symbols = target->symbols;
1067          this->instructions = target->ir;
1068          this->temps = temps;
1069       }
1070
1071       virtual ir_visitor_status visit(ir_dereference_variable *ir)
1072       {
1073          if (ir->var->data.mode == ir_var_temporary) {
1074             ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
1075
1076             assert(var != NULL);
1077             ir->var = var;
1078             return visit_continue;
1079          }
1080
1081          ir_variable *const existing =
1082             this->symbols->get_variable(ir->var->name);
1083          if (existing != NULL)
1084             ir->var = existing;
1085          else {
1086             ir_variable *copy = ir->var->clone(this->target, NULL);
1087
1088             this->symbols->add_variable(copy);
1089             this->instructions->push_head(copy);
1090             ir->var = copy;
1091          }
1092
1093          return visit_continue;
1094       }
1095
1096    private:
1097       struct gl_shader *target;
1098       glsl_symbol_table *symbols;
1099       exec_list *instructions;
1100       hash_table *temps;
1101    };
1102
1103    remap_visitor v(target, temps);
1104
1105    inst->accept(&v);
1106 }
1107
1108
1109 /**
1110  * Move non-declarations from one instruction stream to another
1111  *
1112  * The intended usage pattern of this function is to pass the pointer to the
1113  * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
1114  * pointer) for \c last and \c false for \c make_copies on the first
1115  * call.  Successive calls pass the return value of the previous call for
1116  * \c last and \c true for \c make_copies.
1117  *
1118  * \param instructions Source instruction stream
1119  * \param last         Instruction after which new instructions should be
1120  *                     inserted in the target instruction stream
1121  * \param make_copies  Flag selecting whether instructions in \c instructions
1122  *                     should be copied (via \c ir_instruction::clone) into the
1123  *                     target list or moved.
1124  *
1125  * \return
1126  * The new "last" instruction in the target instruction stream.  This pointer
1127  * is suitable for use as the \c last parameter of a later call to this
1128  * function.
1129  */
1130 exec_node *
1131 move_non_declarations(exec_list *instructions, exec_node *last,
1132                       bool make_copies, gl_shader *target)
1133 {
1134    hash_table *temps = NULL;
1135
1136    if (make_copies)
1137       temps = hash_table_ctor(0, hash_table_pointer_hash,
1138                               hash_table_pointer_compare);
1139
1140    foreach_in_list_safe(ir_instruction, inst, instructions) {
1141       if (inst->as_function())
1142          continue;
1143
1144       ir_variable *var = inst->as_variable();
1145       if ((var != NULL) && (var->data.mode != ir_var_temporary))
1146          continue;
1147
1148       assert(inst->as_assignment()
1149              || inst->as_call()
1150              || inst->as_if() /* for initializers with the ?: operator */
1151              || ((var != NULL) && (var->data.mode == ir_var_temporary)));
1152
1153       if (make_copies) {
1154          inst = inst->clone(target, NULL);
1155
1156          if (var != NULL)
1157             hash_table_insert(temps, inst, var);
1158          else
1159             remap_variables(inst, target, temps);
1160       } else {
1161          inst->remove();
1162       }
1163
1164       last->insert_after(inst);
1165       last = inst;
1166    }
1167
1168    if (make_copies)
1169       hash_table_dtor(temps);
1170
1171    return last;
1172 }
1173
1174 /**
1175  * Get the function signature for main from a shader
1176  */
1177 ir_function_signature *
1178 link_get_main_function_signature(gl_shader *sh)
1179 {
1180    ir_function *const f = sh->symbols->get_function("main");
1181    if (f != NULL) {
1182       exec_list void_parameters;
1183
1184       /* Look for the 'void main()' signature and ensure that it's defined.
1185        * This keeps the linker from accidentally pick a shader that just
1186        * contains a prototype for main.
1187        *
1188        * We don't have to check for multiple definitions of main (in multiple
1189        * shaders) because that would have already been caught above.
1190        */
1191       ir_function_signature *sig =
1192          f->matching_signature(NULL, &void_parameters, false);
1193       if ((sig != NULL) && sig->is_defined) {
1194          return sig;
1195       }
1196    }
1197
1198    return NULL;
1199 }
1200
1201
1202 /**
1203  * This class is only used in link_intrastage_shaders() below but declaring
1204  * it inside that function leads to compiler warnings with some versions of
1205  * gcc.
1206  */
1207 class array_sizing_visitor : public ir_hierarchical_visitor {
1208 public:
1209    array_sizing_visitor()
1210       : mem_ctx(ralloc_context(NULL)),
1211         unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash,
1212                                            hash_table_pointer_compare))
1213    {
1214    }
1215
1216    ~array_sizing_visitor()
1217    {
1218       hash_table_dtor(this->unnamed_interfaces);
1219       ralloc_free(this->mem_ctx);
1220    }
1221
1222    virtual ir_visitor_status visit(ir_variable *var)
1223    {
1224       fixup_type(&var->type, var->data.max_array_access);
1225       if (var->type->is_interface()) {
1226          if (interface_contains_unsized_arrays(var->type)) {
1227             const glsl_type *new_type =
1228                resize_interface_members(var->type,
1229                                         var->get_max_ifc_array_access());
1230             var->type = new_type;
1231             var->change_interface_type(new_type);
1232          }
1233       } else if (var->type->is_array() &&
1234                  var->type->fields.array->is_interface()) {
1235          if (interface_contains_unsized_arrays(var->type->fields.array)) {
1236             const glsl_type *new_type =
1237                resize_interface_members(var->type->fields.array,
1238                                         var->get_max_ifc_array_access());
1239             var->change_interface_type(new_type);
1240             var->type =
1241                glsl_type::get_array_instance(new_type, var->type->length);
1242          }
1243       } else if (const glsl_type *ifc_type = var->get_interface_type()) {
1244          /* Store a pointer to the variable in the unnamed_interfaces
1245           * hashtable.
1246           */
1247          ir_variable **interface_vars = (ir_variable **)
1248             hash_table_find(this->unnamed_interfaces, ifc_type);
1249          if (interface_vars == NULL) {
1250             interface_vars = rzalloc_array(mem_ctx, ir_variable *,
1251                                            ifc_type->length);
1252             hash_table_insert(this->unnamed_interfaces, interface_vars,
1253                               ifc_type);
1254          }
1255          unsigned index = ifc_type->field_index(var->name);
1256          assert(index < ifc_type->length);
1257          assert(interface_vars[index] == NULL);
1258          interface_vars[index] = var;
1259       }
1260       return visit_continue;
1261    }
1262
1263    /**
1264     * For each unnamed interface block that was discovered while running the
1265     * visitor, adjust the interface type to reflect the newly assigned array
1266     * sizes, and fix up the ir_variable nodes to point to the new interface
1267     * type.
1268     */
1269    void fixup_unnamed_interface_types()
1270    {
1271       hash_table_call_foreach(this->unnamed_interfaces,
1272                               fixup_unnamed_interface_type, NULL);
1273    }
1274
1275 private:
1276    /**
1277     * If the type pointed to by \c type represents an unsized array, replace
1278     * it with a sized array whose size is determined by max_array_access.
1279     */
1280    static void fixup_type(const glsl_type **type, unsigned max_array_access)
1281    {
1282       if ((*type)->is_unsized_array()) {
1283          *type = glsl_type::get_array_instance((*type)->fields.array,
1284                                                max_array_access + 1);
1285          assert(*type != NULL);
1286       }
1287    }
1288
1289    /**
1290     * Determine whether the given interface type contains unsized arrays (if
1291     * it doesn't, array_sizing_visitor doesn't need to process it).
1292     */
1293    static bool interface_contains_unsized_arrays(const glsl_type *type)
1294    {
1295       for (unsigned i = 0; i < type->length; i++) {
1296          const glsl_type *elem_type = type->fields.structure[i].type;
1297          if (elem_type->is_unsized_array())
1298             return true;
1299       }
1300       return false;
1301    }
1302
1303    /**
1304     * Create a new interface type based on the given type, with unsized arrays
1305     * replaced by sized arrays whose size is determined by
1306     * max_ifc_array_access.
1307     */
1308    static const glsl_type *
1309    resize_interface_members(const glsl_type *type,
1310                             const unsigned *max_ifc_array_access)
1311    {
1312       unsigned num_fields = type->length;
1313       glsl_struct_field *fields = new glsl_struct_field[num_fields];
1314       memcpy(fields, type->fields.structure,
1315              num_fields * sizeof(*fields));
1316       for (unsigned i = 0; i < num_fields; i++) {
1317          fixup_type(&fields[i].type, max_ifc_array_access[i]);
1318       }
1319       glsl_interface_packing packing =
1320          (glsl_interface_packing) type->interface_packing;
1321       const glsl_type *new_ifc_type =
1322          glsl_type::get_interface_instance(fields, num_fields,
1323                                            packing, type->name);
1324       delete [] fields;
1325       return new_ifc_type;
1326    }
1327
1328    static void fixup_unnamed_interface_type(const void *key, void *data,
1329                                             void *)
1330    {
1331       const glsl_type *ifc_type = (const glsl_type *) key;
1332       ir_variable **interface_vars = (ir_variable **) data;
1333       unsigned num_fields = ifc_type->length;
1334       glsl_struct_field *fields = new glsl_struct_field[num_fields];
1335       memcpy(fields, ifc_type->fields.structure,
1336              num_fields * sizeof(*fields));
1337       bool interface_type_changed = false;
1338       for (unsigned i = 0; i < num_fields; i++) {
1339          if (interface_vars[i] != NULL &&
1340              fields[i].type != interface_vars[i]->type) {
1341             fields[i].type = interface_vars[i]->type;
1342             interface_type_changed = true;
1343          }
1344       }
1345       if (!interface_type_changed) {
1346          delete [] fields;
1347          return;
1348       }
1349       glsl_interface_packing packing =
1350          (glsl_interface_packing) ifc_type->interface_packing;
1351       const glsl_type *new_ifc_type =
1352          glsl_type::get_interface_instance(fields, num_fields, packing,
1353                                            ifc_type->name);
1354       delete [] fields;
1355       for (unsigned i = 0; i < num_fields; i++) {
1356          if (interface_vars[i] != NULL)
1357             interface_vars[i]->change_interface_type(new_ifc_type);
1358       }
1359    }
1360
1361    /**
1362     * Memory context used to allocate the data in \c unnamed_interfaces.
1363     */
1364    void *mem_ctx;
1365
1366    /**
1367     * Hash table from const glsl_type * to an array of ir_variable *'s
1368     * pointing to the ir_variables constituting each unnamed interface block.
1369     */
1370    hash_table *unnamed_interfaces;
1371 };
1372
1373 /**
1374  * Performs the cross-validation of layout qualifiers specified in
1375  * redeclaration of gl_FragCoord for the attached fragment shaders,
1376  * and propagates them to the linked FS and linked shader program.
1377  */
1378 static void
1379 link_fs_input_layout_qualifiers(struct gl_shader_program *prog,
1380                                 struct gl_shader *linked_shader,
1381                                 struct gl_shader **shader_list,
1382                                 unsigned num_shaders)
1383 {
1384    linked_shader->redeclares_gl_fragcoord = false;
1385    linked_shader->uses_gl_fragcoord = false;
1386    linked_shader->origin_upper_left = false;
1387    linked_shader->pixel_center_integer = false;
1388
1389    if (linked_shader->Stage != MESA_SHADER_FRAGMENT ||
1390        (prog->Version < 150 && !prog->ARB_fragment_coord_conventions_enable))
1391       return;
1392
1393    for (unsigned i = 0; i < num_shaders; i++) {
1394       struct gl_shader *shader = shader_list[i];
1395       /* From the GLSL 1.50 spec, page 39:
1396        *
1397        *   "If gl_FragCoord is redeclared in any fragment shader in a program,
1398        *    it must be redeclared in all the fragment shaders in that program
1399        *    that have a static use gl_FragCoord."
1400        */
1401       if ((linked_shader->redeclares_gl_fragcoord
1402            && !shader->redeclares_gl_fragcoord
1403            && shader->uses_gl_fragcoord)
1404           || (shader->redeclares_gl_fragcoord
1405               && !linked_shader->redeclares_gl_fragcoord
1406               && linked_shader->uses_gl_fragcoord)) {
1407              linker_error(prog, "fragment shader defined with conflicting "
1408                          "layout qualifiers for gl_FragCoord\n");
1409       }
1410
1411       /* From the GLSL 1.50 spec, page 39:
1412        *
1413        *   "All redeclarations of gl_FragCoord in all fragment shaders in a
1414        *    single program must have the same set of qualifiers."
1415        */
1416       if (linked_shader->redeclares_gl_fragcoord && shader->redeclares_gl_fragcoord
1417           && (shader->origin_upper_left != linked_shader->origin_upper_left
1418           || shader->pixel_center_integer != linked_shader->pixel_center_integer)) {
1419          linker_error(prog, "fragment shader defined with conflicting "
1420                       "layout qualifiers for gl_FragCoord\n");
1421       }
1422
1423       /* Update the linked shader state.  Note that uses_gl_fragcoord should
1424        * accumulate the results.  The other values should replace.  If there
1425        * are multiple redeclarations, all the fields except uses_gl_fragcoord
1426        * are already known to be the same.
1427        */
1428       if (shader->redeclares_gl_fragcoord || shader->uses_gl_fragcoord) {
1429          linked_shader->redeclares_gl_fragcoord =
1430             shader->redeclares_gl_fragcoord;
1431          linked_shader->uses_gl_fragcoord = linked_shader->uses_gl_fragcoord
1432             || shader->uses_gl_fragcoord;
1433          linked_shader->origin_upper_left = shader->origin_upper_left;
1434          linked_shader->pixel_center_integer = shader->pixel_center_integer;
1435       }
1436    }
1437 }
1438
1439 /**
1440  * Performs the cross-validation of geometry shader max_vertices and
1441  * primitive type layout qualifiers for the attached geometry shaders,
1442  * and propagates them to the linked GS and linked shader program.
1443  */
1444 static void
1445 link_gs_inout_layout_qualifiers(struct gl_shader_program *prog,
1446                                 struct gl_shader *linked_shader,
1447                                 struct gl_shader **shader_list,
1448                                 unsigned num_shaders)
1449 {
1450    linked_shader->Geom.VerticesOut = 0;
1451    linked_shader->Geom.Invocations = 0;
1452    linked_shader->Geom.InputType = PRIM_UNKNOWN;
1453    linked_shader->Geom.OutputType = PRIM_UNKNOWN;
1454
1455    /* No in/out qualifiers defined for anything but GLSL 1.50+
1456     * geometry shaders so far.
1457     */
1458    if (linked_shader->Stage != MESA_SHADER_GEOMETRY || prog->Version < 150)
1459       return;
1460
1461    /* From the GLSL 1.50 spec, page 46:
1462     *
1463     *     "All geometry shader output layout declarations in a program
1464     *      must declare the same layout and same value for
1465     *      max_vertices. There must be at least one geometry output
1466     *      layout declaration somewhere in a program, but not all
1467     *      geometry shaders (compilation units) are required to
1468     *      declare it."
1469     */
1470
1471    for (unsigned i = 0; i < num_shaders; i++) {
1472       struct gl_shader *shader = shader_list[i];
1473
1474       if (shader->Geom.InputType != PRIM_UNKNOWN) {
1475          if (linked_shader->Geom.InputType != PRIM_UNKNOWN &&
1476              linked_shader->Geom.InputType != shader->Geom.InputType) {
1477             linker_error(prog, "geometry shader defined with conflicting "
1478                          "input types\n");
1479             return;
1480          }
1481          linked_shader->Geom.InputType = shader->Geom.InputType;
1482       }
1483
1484       if (shader->Geom.OutputType != PRIM_UNKNOWN) {
1485          if (linked_shader->Geom.OutputType != PRIM_UNKNOWN &&
1486              linked_shader->Geom.OutputType != shader->Geom.OutputType) {
1487             linker_error(prog, "geometry shader defined with conflicting "
1488                          "output types\n");
1489             return;
1490          }
1491          linked_shader->Geom.OutputType = shader->Geom.OutputType;
1492       }
1493
1494       if (shader->Geom.VerticesOut != 0) {
1495          if (linked_shader->Geom.VerticesOut != 0 &&
1496              linked_shader->Geom.VerticesOut != shader->Geom.VerticesOut) {
1497             linker_error(prog, "geometry shader defined with conflicting "
1498                          "output vertex count (%d and %d)\n",
1499                          linked_shader->Geom.VerticesOut,
1500                          shader->Geom.VerticesOut);
1501             return;
1502          }
1503          linked_shader->Geom.VerticesOut = shader->Geom.VerticesOut;
1504       }
1505
1506       if (shader->Geom.Invocations != 0) {
1507          if (linked_shader->Geom.Invocations != 0 &&
1508              linked_shader->Geom.Invocations != shader->Geom.Invocations) {
1509             linker_error(prog, "geometry shader defined with conflicting "
1510                          "invocation count (%d and %d)\n",
1511                          linked_shader->Geom.Invocations,
1512                          shader->Geom.Invocations);
1513             return;
1514          }
1515          linked_shader->Geom.Invocations = shader->Geom.Invocations;
1516       }
1517    }
1518
1519    /* Just do the intrastage -> interstage propagation right now,
1520     * since we already know we're in the right type of shader program
1521     * for doing it.
1522     */
1523    if (linked_shader->Geom.InputType == PRIM_UNKNOWN) {
1524       linker_error(prog,
1525                    "geometry shader didn't declare primitive input type\n");
1526       return;
1527    }
1528    prog->Geom.InputType = linked_shader->Geom.InputType;
1529
1530    if (linked_shader->Geom.OutputType == PRIM_UNKNOWN) {
1531       linker_error(prog,
1532                    "geometry shader didn't declare primitive output type\n");
1533       return;
1534    }
1535    prog->Geom.OutputType = linked_shader->Geom.OutputType;
1536
1537    if (linked_shader->Geom.VerticesOut == 0) {
1538       linker_error(prog,
1539                    "geometry shader didn't declare max_vertices\n");
1540       return;
1541    }
1542    prog->Geom.VerticesOut = linked_shader->Geom.VerticesOut;
1543
1544    if (linked_shader->Geom.Invocations == 0)
1545       linked_shader->Geom.Invocations = 1;
1546
1547    prog->Geom.Invocations = linked_shader->Geom.Invocations;
1548 }
1549
1550
1551 /**
1552  * Perform cross-validation of compute shader local_size_{x,y,z} layout
1553  * qualifiers for the attached compute shaders, and propagate them to the
1554  * linked CS and linked shader program.
1555  */
1556 static void
1557 link_cs_input_layout_qualifiers(struct gl_shader_program *prog,
1558                                 struct gl_shader *linked_shader,
1559                                 struct gl_shader **shader_list,
1560                                 unsigned num_shaders)
1561 {
1562    for (int i = 0; i < 3; i++)
1563       linked_shader->Comp.LocalSize[i] = 0;
1564
1565    /* This function is called for all shader stages, but it only has an effect
1566     * for compute shaders.
1567     */
1568    if (linked_shader->Stage != MESA_SHADER_COMPUTE)
1569       return;
1570
1571    /* From the ARB_compute_shader spec, in the section describing local size
1572     * declarations:
1573     *
1574     *     If multiple compute shaders attached to a single program object
1575     *     declare local work-group size, the declarations must be identical;
1576     *     otherwise a link-time error results. Furthermore, if a program
1577     *     object contains any compute shaders, at least one must contain an
1578     *     input layout qualifier specifying the local work sizes of the
1579     *     program, or a link-time error will occur.
1580     */
1581    for (unsigned sh = 0; sh < num_shaders; sh++) {
1582       struct gl_shader *shader = shader_list[sh];
1583
1584       if (shader->Comp.LocalSize[0] != 0) {
1585          if (linked_shader->Comp.LocalSize[0] != 0) {
1586             for (int i = 0; i < 3; i++) {
1587                if (linked_shader->Comp.LocalSize[i] !=
1588                    shader->Comp.LocalSize[i]) {
1589                   linker_error(prog, "compute shader defined with conflicting "
1590                                "local sizes\n");
1591                   return;
1592                }
1593             }
1594          }
1595          for (int i = 0; i < 3; i++)
1596             linked_shader->Comp.LocalSize[i] = shader->Comp.LocalSize[i];
1597       }
1598    }
1599
1600    /* Just do the intrastage -> interstage propagation right now,
1601     * since we already know we're in the right type of shader program
1602     * for doing it.
1603     */
1604    if (linked_shader->Comp.LocalSize[0] == 0) {
1605       linker_error(prog, "compute shader didn't declare local size\n");
1606       return;
1607    }
1608    for (int i = 0; i < 3; i++)
1609       prog->Comp.LocalSize[i] = linked_shader->Comp.LocalSize[i];
1610 }
1611
1612
1613 /**
1614  * Combine a group of shaders for a single stage to generate a linked shader
1615  *
1616  * \note
1617  * If this function is supplied a single shader, it is cloned, and the new
1618  * shader is returned.
1619  */
1620 static struct gl_shader *
1621 link_intrastage_shaders(void *mem_ctx,
1622                         struct gl_context *ctx,
1623                         struct gl_shader_program *prog,
1624                         struct gl_shader **shader_list,
1625                         unsigned num_shaders)
1626 {
1627    struct gl_uniform_block *uniform_blocks = NULL;
1628
1629    /* Check that global variables defined in multiple shaders are consistent.
1630     */
1631    cross_validate_globals(prog, shader_list, num_shaders, false);
1632    if (!prog->LinkStatus)
1633       return NULL;
1634
1635    /* Check that interface blocks defined in multiple shaders are consistent.
1636     */
1637    validate_intrastage_interface_blocks(prog, (const gl_shader **)shader_list,
1638                                         num_shaders);
1639    if (!prog->LinkStatus)
1640       return NULL;
1641
1642    /* Link up uniform blocks defined within this stage. */
1643    const unsigned num_uniform_blocks =
1644       link_uniform_blocks(mem_ctx, prog, shader_list, num_shaders,
1645                           &uniform_blocks);
1646    if (!prog->LinkStatus)
1647       return NULL;
1648
1649    /* Check that there is only a single definition of each function signature
1650     * across all shaders.
1651     */
1652    for (unsigned i = 0; i < (num_shaders - 1); i++) {
1653       foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
1654          ir_function *const f = node->as_function();
1655
1656          if (f == NULL)
1657             continue;
1658
1659          for (unsigned j = i + 1; j < num_shaders; j++) {
1660             ir_function *const other =
1661                shader_list[j]->symbols->get_function(f->name);
1662
1663             /* If the other shader has no function (and therefore no function
1664              * signatures) with the same name, skip to the next shader.
1665              */
1666             if (other == NULL)
1667                continue;
1668
1669             foreach_in_list(ir_function_signature, sig, &f->signatures) {
1670                if (!sig->is_defined || sig->is_builtin())
1671                   continue;
1672
1673                ir_function_signature *other_sig =
1674                   other->exact_matching_signature(NULL, &sig->parameters);
1675
1676                if ((other_sig != NULL) && other_sig->is_defined
1677                    && !other_sig->is_builtin()) {
1678                   linker_error(prog, "function `%s' is multiply defined\n",
1679                                f->name);
1680                   return NULL;
1681                }
1682             }
1683          }
1684       }
1685    }
1686
1687    /* Find the shader that defines main, and make a clone of it.
1688     *
1689     * Starting with the clone, search for undefined references.  If one is
1690     * found, find the shader that defines it.  Clone the reference and add
1691     * it to the shader.  Repeat until there are no undefined references or
1692     * until a reference cannot be resolved.
1693     */
1694    gl_shader *main = NULL;
1695    for (unsigned i = 0; i < num_shaders; i++) {
1696       if (link_get_main_function_signature(shader_list[i]) != NULL) {
1697          main = shader_list[i];
1698          break;
1699       }
1700    }
1701
1702    if (main == NULL) {
1703       linker_error(prog, "%s shader lacks `main'\n",
1704                    _mesa_shader_stage_to_string(shader_list[0]->Stage));
1705       return NULL;
1706    }
1707
1708    gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
1709    linked->ir = new(linked) exec_list;
1710    clone_ir_list(mem_ctx, linked->ir, main->ir);
1711
1712    linked->UniformBlocks = uniform_blocks;
1713    linked->NumUniformBlocks = num_uniform_blocks;
1714    ralloc_steal(linked, linked->UniformBlocks);
1715
1716    link_fs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
1717    link_gs_inout_layout_qualifiers(prog, linked, shader_list, num_shaders);
1718    link_cs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
1719
1720    populate_symbol_table(linked);
1721
1722    /* The pointer to the main function in the final linked shader (i.e., the
1723     * copy of the original shader that contained the main function).
1724     */
1725    ir_function_signature *const main_sig =
1726       link_get_main_function_signature(linked);
1727
1728    /* Move any instructions other than variable declarations or function
1729     * declarations into main.
1730     */
1731    exec_node *insertion_point =
1732       move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
1733                             linked);
1734
1735    for (unsigned i = 0; i < num_shaders; i++) {
1736       if (shader_list[i] == main)
1737          continue;
1738
1739       insertion_point = move_non_declarations(shader_list[i]->ir,
1740                                               insertion_point, true, linked);
1741    }
1742
1743    /* Check if any shader needs built-in functions. */
1744    bool need_builtins = false;
1745    for (unsigned i = 0; i < num_shaders; i++) {
1746       if (shader_list[i]->uses_builtin_functions) {
1747          need_builtins = true;
1748          break;
1749       }
1750    }
1751
1752    bool ok;
1753    if (need_builtins) {
1754       /* Make a temporary array one larger than shader_list, which will hold
1755        * the built-in function shader as well.
1756        */
1757       gl_shader **linking_shaders = (gl_shader **)
1758          calloc(num_shaders + 1, sizeof(gl_shader *));
1759
1760       ok = linking_shaders != NULL;
1761
1762       if (ok) {
1763          memcpy(linking_shaders, shader_list, num_shaders * sizeof(gl_shader *));
1764          linking_shaders[num_shaders] = _mesa_glsl_get_builtin_function_shader();
1765
1766          ok = link_function_calls(prog, linked, linking_shaders, num_shaders + 1);
1767
1768          free(linking_shaders);
1769       } else {
1770          _mesa_error_no_memory(__func__);
1771       }
1772    } else {
1773       ok = link_function_calls(prog, linked, shader_list, num_shaders);
1774    }
1775
1776
1777    if (!ok) {
1778       ctx->Driver.DeleteShader(ctx, linked);
1779       return NULL;
1780    }
1781
1782    /* At this point linked should contain all of the linked IR, so
1783     * validate it to make sure nothing went wrong.
1784     */
1785    validate_ir_tree(linked->ir);
1786
1787    /* Set the size of geometry shader input arrays */
1788    if (linked->Stage == MESA_SHADER_GEOMETRY) {
1789       unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
1790       geom_array_resize_visitor input_resize_visitor(num_vertices, prog);
1791       foreach_in_list(ir_instruction, ir, linked->ir) {
1792          ir->accept(&input_resize_visitor);
1793       }
1794    }
1795
1796    if (ctx->Const.VertexID_is_zero_based)
1797       lower_vertex_id(linked);
1798
1799    /* Make a pass over all variable declarations to ensure that arrays with
1800     * unspecified sizes have a size specified.  The size is inferred from the
1801     * max_array_access field.
1802     */
1803    array_sizing_visitor v;
1804    v.run(linked->ir);
1805    v.fixup_unnamed_interface_types();
1806
1807    return linked;
1808 }
1809
1810 /**
1811  * Update the sizes of linked shader uniform arrays to the maximum
1812  * array index used.
1813  *
1814  * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1815  *
1816  *     If one or more elements of an array are active,
1817  *     GetActiveUniform will return the name of the array in name,
1818  *     subject to the restrictions listed above. The type of the array
1819  *     is returned in type. The size parameter contains the highest
1820  *     array element index used, plus one. The compiler or linker
1821  *     determines the highest index used.  There will be only one
1822  *     active uniform reported by the GL per uniform array.
1823
1824  */
1825 static void
1826 update_array_sizes(struct gl_shader_program *prog)
1827 {
1828    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1829          if (prog->_LinkedShaders[i] == NULL)
1830             continue;
1831
1832       foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
1833          ir_variable *const var = node->as_variable();
1834
1835          if ((var == NULL) || (var->data.mode != ir_var_uniform) ||
1836              !var->type->is_array())
1837             continue;
1838
1839          /* GL_ARB_uniform_buffer_object says that std140 uniforms
1840           * will not be eliminated.  Since we always do std140, just
1841           * don't resize arrays in UBOs.
1842           *
1843           * Atomic counters are supposed to get deterministic
1844           * locations assigned based on the declaration ordering and
1845           * sizes, array compaction would mess that up.
1846           */
1847          if (var->is_in_uniform_block() || var->type->contains_atomic())
1848             continue;
1849
1850          unsigned int size = var->data.max_array_access;
1851          for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
1852                if (prog->_LinkedShaders[j] == NULL)
1853                   continue;
1854
1855             foreach_in_list(ir_instruction, node2, prog->_LinkedShaders[j]->ir) {
1856                ir_variable *other_var = node2->as_variable();
1857                if (!other_var)
1858                   continue;
1859
1860                if (strcmp(var->name, other_var->name) == 0 &&
1861                    other_var->data.max_array_access > size) {
1862                   size = other_var->data.max_array_access;
1863                }
1864             }
1865          }
1866
1867          if (size + 1 != var->type->length) {
1868             /* If this is a built-in uniform (i.e., it's backed by some
1869              * fixed-function state), adjust the number of state slots to
1870              * match the new array size.  The number of slots per array entry
1871              * is not known.  It seems safe to assume that the total number of
1872              * slots is an integer multiple of the number of array elements.
1873              * Determine the number of slots per array element by dividing by
1874              * the old (total) size.
1875              */
1876             const unsigned num_slots = var->get_num_state_slots();
1877             if (num_slots > 0) {
1878                var->set_num_state_slots((size + 1)
1879                                         * (num_slots / var->type->length));
1880             }
1881
1882             var->type = glsl_type::get_array_instance(var->type->fields.array,
1883                                                       size + 1);
1884             /* FINISHME: We should update the types of array
1885              * dereferences of this variable now.
1886              */
1887          }
1888       }
1889    }
1890 }
1891
1892 /**
1893  * Find a contiguous set of available bits in a bitmask.
1894  *
1895  * \param used_mask     Bits representing used (1) and unused (0) locations
1896  * \param needed_count  Number of contiguous bits needed.
1897  *
1898  * \return
1899  * Base location of the available bits on success or -1 on failure.
1900  */
1901 int
1902 find_available_slots(unsigned used_mask, unsigned needed_count)
1903 {
1904    unsigned needed_mask = (1 << needed_count) - 1;
1905    const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1906
1907    /* The comparison to 32 is redundant, but without it GCC emits "warning:
1908     * cannot optimize possibly infinite loops" for the loop below.
1909     */
1910    if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1911       return -1;
1912
1913    for (int i = 0; i <= max_bit_to_test; i++) {
1914       if ((needed_mask & ~used_mask) == needed_mask)
1915          return i;
1916
1917       needed_mask <<= 1;
1918    }
1919
1920    return -1;
1921 }
1922
1923
1924 /**
1925  * Assign locations for either VS inputs or FS outputs
1926  *
1927  * \param prog          Shader program whose variables need locations assigned
1928  * \param target_index  Selector for the program target to receive location
1929  *                      assignmnets.  Must be either \c MESA_SHADER_VERTEX or
1930  *                      \c MESA_SHADER_FRAGMENT.
1931  * \param max_index     Maximum number of generic locations.  This corresponds
1932  *                      to either the maximum number of draw buffers or the
1933  *                      maximum number of generic attributes.
1934  *
1935  * \return
1936  * If locations are successfully assigned, true is returned.  Otherwise an
1937  * error is emitted to the shader link log and false is returned.
1938  */
1939 bool
1940 assign_attribute_or_color_locations(gl_shader_program *prog,
1941                                     unsigned target_index,
1942                                     unsigned max_index)
1943 {
1944    /* Mark invalid locations as being used.
1945     */
1946    unsigned used_locations = (max_index >= 32)
1947       ? ~0 : ~((1 << max_index) - 1);
1948
1949    assert((target_index == MESA_SHADER_VERTEX)
1950           || (target_index == MESA_SHADER_FRAGMENT));
1951
1952    gl_shader *const sh = prog->_LinkedShaders[target_index];
1953    if (sh == NULL)
1954       return true;
1955
1956    /* Operate in a total of four passes.
1957     *
1958     * 1. Invalidate the location assignments for all vertex shader inputs.
1959     *
1960     * 2. Assign locations for inputs that have user-defined (via
1961     *    glBindVertexAttribLocation) locations and outputs that have
1962     *    user-defined locations (via glBindFragDataLocation).
1963     *
1964     * 3. Sort the attributes without assigned locations by number of slots
1965     *    required in decreasing order.  Fragmentation caused by attribute
1966     *    locations assigned by the application may prevent large attributes
1967     *    from having enough contiguous space.
1968     *
1969     * 4. Assign locations to any inputs without assigned locations.
1970     */
1971
1972    const int generic_base = (target_index == MESA_SHADER_VERTEX)
1973       ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
1974
1975    const enum ir_variable_mode direction =
1976       (target_index == MESA_SHADER_VERTEX)
1977       ? ir_var_shader_in : ir_var_shader_out;
1978
1979
1980    /* Temporary storage for the set of attributes that need locations assigned.
1981     */
1982    struct temp_attr {
1983       unsigned slots;
1984       ir_variable *var;
1985
1986       /* Used below in the call to qsort. */
1987       static int compare(const void *a, const void *b)
1988       {
1989          const temp_attr *const l = (const temp_attr *) a;
1990          const temp_attr *const r = (const temp_attr *) b;
1991
1992          /* Reversed because we want a descending order sort below. */
1993          return r->slots - l->slots;
1994       }
1995    } to_assign[16];
1996
1997    unsigned num_attr = 0;
1998
1999    foreach_in_list(ir_instruction, node, sh->ir) {
2000       ir_variable *const var = node->as_variable();
2001
2002       if ((var == NULL) || (var->data.mode != (unsigned) direction))
2003          continue;
2004
2005       if (var->data.explicit_location) {
2006          if ((var->data.location >= (int)(max_index + generic_base))
2007              || (var->data.location < 0)) {
2008             linker_error(prog,
2009                          "invalid explicit location %d specified for `%s'\n",
2010                          (var->data.location < 0)
2011                          ? var->data.location
2012                          : var->data.location - generic_base,
2013                          var->name);
2014             return false;
2015          }
2016       } else if (target_index == MESA_SHADER_VERTEX) {
2017          unsigned binding;
2018
2019          if (prog->AttributeBindings->get(binding, var->name)) {
2020             assert(binding >= VERT_ATTRIB_GENERIC0);
2021             var->data.location = binding;
2022             var->data.is_unmatched_generic_inout = 0;
2023          }
2024       } else if (target_index == MESA_SHADER_FRAGMENT) {
2025          unsigned binding;
2026          unsigned index;
2027
2028          if (prog->FragDataBindings->get(binding, var->name)) {
2029             assert(binding >= FRAG_RESULT_DATA0);
2030             var->data.location = binding;
2031             var->data.is_unmatched_generic_inout = 0;
2032
2033             if (prog->FragDataIndexBindings->get(index, var->name)) {
2034                var->data.index = index;
2035             }
2036          }
2037       }
2038
2039       /* If the variable is not a built-in and has a location statically
2040        * assigned in the shader (presumably via a layout qualifier), make sure
2041        * that it doesn't collide with other assigned locations.  Otherwise,
2042        * add it to the list of variables that need linker-assigned locations.
2043        */
2044       const unsigned slots = var->type->count_attribute_slots();
2045       if (var->data.location != -1) {
2046          if (var->data.location >= generic_base && var->data.index < 1) {
2047             /* From page 61 of the OpenGL 4.0 spec:
2048              *
2049              *     "LinkProgram will fail if the attribute bindings assigned
2050              *     by BindAttribLocation do not leave not enough space to
2051              *     assign a location for an active matrix attribute or an
2052              *     active attribute array, both of which require multiple
2053              *     contiguous generic attributes."
2054              *
2055              * I think above text prohibits the aliasing of explicit and
2056              * automatic assignments. But, aliasing is allowed in manual
2057              * assignments of attribute locations. See below comments for
2058              * the details.
2059              *
2060              * From OpenGL 4.0 spec, page 61:
2061              *
2062              *     "It is possible for an application to bind more than one
2063              *     attribute name to the same location. This is referred to as
2064              *     aliasing. This will only work if only one of the aliased
2065              *     attributes is active in the executable program, or if no
2066              *     path through the shader consumes more than one attribute of
2067              *     a set of attributes aliased to the same location. A link
2068              *     error can occur if the linker determines that every path
2069              *     through the shader consumes multiple aliased attributes,
2070              *     but implementations are not required to generate an error
2071              *     in this case."
2072              *
2073              * From GLSL 4.30 spec, page 54:
2074              *
2075              *    "A program will fail to link if any two non-vertex shader
2076              *     input variables are assigned to the same location. For
2077              *     vertex shaders, multiple input variables may be assigned
2078              *     to the same location using either layout qualifiers or via
2079              *     the OpenGL API. However, such aliasing is intended only to
2080              *     support vertex shaders where each execution path accesses
2081              *     at most one input per each location. Implementations are
2082              *     permitted, but not required, to generate link-time errors
2083              *     if they detect that every path through the vertex shader
2084              *     executable accesses multiple inputs assigned to any single
2085              *     location. For all shader types, a program will fail to link
2086              *     if explicit location assignments leave the linker unable
2087              *     to find space for other variables without explicit
2088              *     assignments."
2089              *
2090              * From OpenGL ES 3.0 spec, page 56:
2091              *
2092              *    "Binding more than one attribute name to the same location
2093              *     is referred to as aliasing, and is not permitted in OpenGL
2094              *     ES Shading Language 3.00 vertex shaders. LinkProgram will
2095              *     fail when this condition exists. However, aliasing is
2096              *     possible in OpenGL ES Shading Language 1.00 vertex shaders.
2097              *     This will only work if only one of the aliased attributes
2098              *     is active in the executable program, or if no path through
2099              *     the shader consumes more than one attribute of a set of
2100              *     attributes aliased to the same location. A link error can
2101              *     occur if the linker determines that every path through the
2102              *     shader consumes multiple aliased attributes, but implemen-
2103              *     tations are not required to generate an error in this case."
2104              *
2105              * After looking at above references from OpenGL, OpenGL ES and
2106              * GLSL specifications, we allow aliasing of vertex input variables
2107              * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2108              *
2109              * NOTE: This is not required by the spec but its worth mentioning
2110              * here that we're not doing anything to make sure that no path
2111              * through the vertex shader executable accesses multiple inputs
2112              * assigned to any single location.
2113              */
2114
2115             /* Mask representing the contiguous slots that will be used by
2116              * this attribute.
2117              */
2118             const unsigned attr = var->data.location - generic_base;
2119             const unsigned use_mask = (1 << slots) - 1;
2120             const char *const string = (target_index == MESA_SHADER_VERTEX)
2121                ? "vertex shader input" : "fragment shader output";
2122
2123             /* Generate a link error if the requested locations for this
2124              * attribute exceed the maximum allowed attribute location.
2125              */
2126             if (attr + slots > max_index) {
2127                linker_error(prog,
2128                            "insufficient contiguous locations "
2129                            "available for %s `%s' %d %d %d\n", string,
2130                            var->name, used_locations, use_mask, attr);
2131                return false;
2132             }
2133
2134             /* Generate a link error if the set of bits requested for this
2135              * attribute overlaps any previously allocated bits.
2136              */
2137             if ((~(use_mask << attr) & used_locations) != used_locations) {
2138                if (target_index == MESA_SHADER_FRAGMENT ||
2139                    (prog->IsES && prog->Version >= 300)) {
2140                   linker_error(prog,
2141                                "overlapping location is assigned "
2142                                "to %s `%s' %d %d %d\n", string,
2143                                var->name, used_locations, use_mask, attr);
2144                   return false;
2145                } else {
2146                   linker_warning(prog,
2147                                  "overlapping location is assigned "
2148                                  "to %s `%s' %d %d %d\n", string,
2149                                  var->name, used_locations, use_mask, attr);
2150                }
2151             }
2152
2153             used_locations |= (use_mask << attr);
2154          }
2155
2156          continue;
2157       }
2158
2159       to_assign[num_attr].slots = slots;
2160       to_assign[num_attr].var = var;
2161       num_attr++;
2162    }
2163
2164    /* If all of the attributes were assigned locations by the application (or
2165     * are built-in attributes with fixed locations), return early.  This should
2166     * be the common case.
2167     */
2168    if (num_attr == 0)
2169       return true;
2170
2171    qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
2172
2173    if (target_index == MESA_SHADER_VERTEX) {
2174       /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS.  It can
2175        * only be explicitly assigned by via glBindAttribLocation.  Mark it as
2176        * reserved to prevent it from being automatically allocated below.
2177        */
2178       find_deref_visitor find("gl_Vertex");
2179       find.run(sh->ir);
2180       if (find.variable_found())
2181          used_locations |= (1 << 0);
2182    }
2183
2184    for (unsigned i = 0; i < num_attr; i++) {
2185       /* Mask representing the contiguous slots that will be used by this
2186        * attribute.
2187        */
2188       const unsigned use_mask = (1 << to_assign[i].slots) - 1;
2189
2190       int location = find_available_slots(used_locations, to_assign[i].slots);
2191
2192       if (location < 0) {
2193          const char *const string = (target_index == MESA_SHADER_VERTEX)
2194             ? "vertex shader input" : "fragment shader output";
2195
2196          linker_error(prog,
2197                       "insufficient contiguous locations "
2198                       "available for %s `%s'\n",
2199                       string, to_assign[i].var->name);
2200          return false;
2201       }
2202
2203       to_assign[i].var->data.location = generic_base + location;
2204       to_assign[i].var->data.is_unmatched_generic_inout = 0;
2205       used_locations |= (use_mask << location);
2206    }
2207
2208    return true;
2209 }
2210
2211
2212 /**
2213  * Demote shader inputs and outputs that are not used in other stages
2214  */
2215 void
2216 demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
2217 {
2218    foreach_in_list(ir_instruction, node, sh->ir) {
2219       ir_variable *const var = node->as_variable();
2220
2221       if ((var == NULL) || (var->data.mode != int(mode)))
2222          continue;
2223
2224       /* A shader 'in' or 'out' variable is only really an input or output if
2225        * its value is used by other shader stages.  This will cause the variable
2226        * to have a location assigned.
2227        */
2228       if (var->data.is_unmatched_generic_inout) {
2229          assert(var->data.mode != ir_var_temporary);
2230          var->data.mode = ir_var_auto;
2231       }
2232    }
2233 }
2234
2235
2236 /**
2237  * Store the gl_FragDepth layout in the gl_shader_program struct.
2238  */
2239 static void
2240 store_fragdepth_layout(struct gl_shader_program *prog)
2241 {
2242    if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2243       return;
2244    }
2245
2246    struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2247
2248    /* We don't look up the gl_FragDepth symbol directly because if
2249     * gl_FragDepth is not used in the shader, it's removed from the IR.
2250     * However, the symbol won't be removed from the symbol table.
2251     *
2252     * We're only interested in the cases where the variable is NOT removed
2253     * from the IR.
2254     */
2255    foreach_in_list(ir_instruction, node, ir) {
2256       ir_variable *const var = node->as_variable();
2257
2258       if (var == NULL || var->data.mode != ir_var_shader_out) {
2259          continue;
2260       }
2261
2262       if (strcmp(var->name, "gl_FragDepth") == 0) {
2263          switch (var->data.depth_layout) {
2264          case ir_depth_layout_none:
2265             prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2266             return;
2267          case ir_depth_layout_any:
2268             prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2269             return;
2270          case ir_depth_layout_greater:
2271             prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2272             return;
2273          case ir_depth_layout_less:
2274             prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2275             return;
2276          case ir_depth_layout_unchanged:
2277             prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2278             return;
2279          default:
2280             assert(0);
2281             return;
2282          }
2283       }
2284    }
2285 }
2286
2287 /**
2288  * Validate the resources used by a program versus the implementation limits
2289  */
2290 static void
2291 check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2292 {
2293    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2294       struct gl_shader *sh = prog->_LinkedShaders[i];
2295
2296       if (sh == NULL)
2297          continue;
2298
2299       if (sh->num_samplers > ctx->Const.Program[i].MaxTextureImageUnits) {
2300          linker_error(prog, "Too many %s shader texture samplers\n",
2301                       _mesa_shader_stage_to_string(i));
2302       }
2303
2304       if (sh->num_uniform_components >
2305           ctx->Const.Program[i].MaxUniformComponents) {
2306          if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2307             linker_warning(prog, "Too many %s shader default uniform block "
2308                            "components, but the driver will try to optimize "
2309                            "them out; this is non-portable out-of-spec "
2310                            "behavior\n",
2311                            _mesa_shader_stage_to_string(i));
2312          } else {
2313             linker_error(prog, "Too many %s shader default uniform block "
2314                          "components\n",
2315                          _mesa_shader_stage_to_string(i));
2316          }
2317       }
2318
2319       if (sh->num_combined_uniform_components >
2320           ctx->Const.Program[i].MaxCombinedUniformComponents) {
2321          if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2322             linker_warning(prog, "Too many %s shader uniform components, "
2323                            "but the driver will try to optimize them out; "
2324                            "this is non-portable out-of-spec behavior\n",
2325                            _mesa_shader_stage_to_string(i));
2326          } else {
2327             linker_error(prog, "Too many %s shader uniform components\n",
2328                          _mesa_shader_stage_to_string(i));
2329          }
2330       }
2331    }
2332
2333    unsigned blocks[MESA_SHADER_STAGES] = {0};
2334    unsigned total_uniform_blocks = 0;
2335
2336    for (unsigned i = 0; i < prog->NumUniformBlocks; i++) {
2337       for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
2338          if (prog->UniformBlockStageIndex[j][i] != -1) {
2339             blocks[j]++;
2340             total_uniform_blocks++;
2341          }
2342       }
2343
2344       if (total_uniform_blocks > ctx->Const.MaxCombinedUniformBlocks) {
2345          linker_error(prog, "Too many combined uniform blocks (%d/%d)\n",
2346                       prog->NumUniformBlocks,
2347                       ctx->Const.MaxCombinedUniformBlocks);
2348       } else {
2349          for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2350             const unsigned max_uniform_blocks =
2351                ctx->Const.Program[i].MaxUniformBlocks;
2352             if (blocks[i] > max_uniform_blocks) {
2353                linker_error(prog, "Too many %s uniform blocks (%d/%d)\n",
2354                             _mesa_shader_stage_to_string(i),
2355                             blocks[i],
2356                             max_uniform_blocks);
2357                break;
2358             }
2359          }
2360       }
2361    }
2362 }
2363
2364 /**
2365  * Validate shader image resources.
2366  */
2367 static void
2368 check_image_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2369 {
2370    unsigned total_image_units = 0;
2371    unsigned fragment_outputs = 0;
2372
2373    if (!ctx->Extensions.ARB_shader_image_load_store)
2374       return;
2375
2376    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2377       struct gl_shader *sh = prog->_LinkedShaders[i];
2378
2379       if (sh) {
2380          if (sh->NumImages > ctx->Const.Program[i].MaxImageUniforms)
2381             linker_error(prog, "Too many %s shader image uniforms\n",
2382                          _mesa_shader_stage_to_string(i));
2383
2384          total_image_units += sh->NumImages;
2385
2386          if (i == MESA_SHADER_FRAGMENT) {
2387             foreach_in_list(ir_instruction, node, sh->ir) {
2388                ir_variable *var = node->as_variable();
2389                if (var && var->data.mode == ir_var_shader_out)
2390                   fragment_outputs += var->type->count_attribute_slots();
2391             }
2392          }
2393       }
2394    }
2395
2396    if (total_image_units > ctx->Const.MaxCombinedImageUniforms)
2397       linker_error(prog, "Too many combined image uniforms\n");
2398
2399    if (total_image_units + fragment_outputs >
2400        ctx->Const.MaxCombinedImageUnitsAndFragmentOutputs)
2401       linker_error(prog, "Too many combined image uniforms and fragment outputs\n");
2402 }
2403
2404
2405 /**
2406  * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
2407  * for a variable, checks for overlaps between other uniforms using explicit
2408  * locations.
2409  */
2410 static bool
2411 reserve_explicit_locations(struct gl_shader_program *prog,
2412                            string_to_uint_map *map, ir_variable *var)
2413 {
2414    unsigned slots = var->type->uniform_locations();
2415    unsigned max_loc = var->data.location + slots - 1;
2416
2417    /* Resize remap table if locations do not fit in the current one. */
2418    if (max_loc + 1 > prog->NumUniformRemapTable) {
2419       prog->UniformRemapTable =
2420          reralloc(prog, prog->UniformRemapTable,
2421                   gl_uniform_storage *,
2422                   max_loc + 1);
2423
2424       if (!prog->UniformRemapTable) {
2425          linker_error(prog, "Out of memory during linking.\n");
2426          return false;
2427       }
2428
2429       /* Initialize allocated space. */
2430       for (unsigned i = prog->NumUniformRemapTable; i < max_loc + 1; i++)
2431          prog->UniformRemapTable[i] = NULL;
2432
2433       prog->NumUniformRemapTable = max_loc + 1;
2434    }
2435
2436    for (unsigned i = 0; i < slots; i++) {
2437       unsigned loc = var->data.location + i;
2438
2439       /* Check if location is already used. */
2440       if (prog->UniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
2441
2442          /* Possibly same uniform from a different stage, this is ok. */
2443          unsigned hash_loc;
2444          if (map->get(hash_loc, var->name) && hash_loc == loc - i)
2445                continue;
2446
2447          /* ARB_explicit_uniform_location specification states:
2448           *
2449           *     "No two default-block uniform variables in the program can have
2450           *     the same location, even if they are unused, otherwise a compiler
2451           *     or linker error will be generated."
2452           */
2453          linker_error(prog,
2454                       "location qualifier for uniform %s overlaps "
2455                       "previously used location\n",
2456                       var->name);
2457          return false;
2458       }
2459
2460       /* Initialize location as inactive before optimization
2461        * rounds and location assignment.
2462        */
2463       prog->UniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
2464    }
2465
2466    /* Note, base location used for arrays. */
2467    map->put(var->data.location, var->name);
2468
2469    return true;
2470 }
2471
2472 /**
2473  * Check and reserve all explicit uniform locations, called before
2474  * any optimizations happen to handle also inactive uniforms and
2475  * inactive array elements that may get trimmed away.
2476  */
2477 static void
2478 check_explicit_uniform_locations(struct gl_context *ctx,
2479                                  struct gl_shader_program *prog)
2480 {
2481    if (!ctx->Extensions.ARB_explicit_uniform_location)
2482       return;
2483
2484    /* This map is used to detect if overlapping explicit locations
2485     * occur with the same uniform (from different stage) or a different one.
2486     */
2487    string_to_uint_map *uniform_map = new string_to_uint_map;
2488
2489    if (!uniform_map) {
2490       linker_error(prog, "Out of memory during linking.\n");
2491       return;
2492    }
2493
2494    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2495       struct gl_shader *sh = prog->_LinkedShaders[i];
2496
2497       if (!sh)
2498          continue;
2499
2500       foreach_in_list(ir_instruction, node, sh->ir) {
2501          ir_variable *var = node->as_variable();
2502          if ((var && var->data.mode == ir_var_uniform) &&
2503              var->data.explicit_location) {
2504             if (!reserve_explicit_locations(prog, uniform_map, var)) {
2505                delete uniform_map;
2506                return;
2507             }
2508          }
2509       }
2510    }
2511
2512    delete uniform_map;
2513 }
2514
2515 /**
2516  * This check is done to make sure we allow only constant expression
2517  * indexing and "constant-index-expression" (indexing with an expression
2518  * that includes loop induction variable).
2519  */
2520 static bool
2521 validate_sampler_array_indexing(struct gl_context *ctx,
2522                                 struct gl_shader_program *prog)
2523 {
2524    dynamic_sampler_array_indexing_visitor v;
2525    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2526       if (prog->_LinkedShaders[i] == NULL)
2527          continue;
2528
2529       bool no_dynamic_indexing =
2530          ctx->Const.ShaderCompilerOptions[i].EmitNoIndirectSampler;
2531
2532       /* Search for array derefs in shader. */
2533       v.run(prog->_LinkedShaders[i]->ir);
2534       if (v.uses_dynamic_sampler_array_indexing()) {
2535          const char *msg = "sampler arrays indexed with non-constant "
2536                            "expressions is forbidden in GLSL %s %u";
2537          /* Backend has indicated that it has no dynamic indexing support. */
2538          if (no_dynamic_indexing) {
2539             linker_error(prog, msg, prog->IsES ? "ES" : "", prog->Version);
2540             return false;
2541          } else {
2542             linker_warning(prog, msg, prog->IsES ? "ES" : "", prog->Version);
2543          }
2544       }
2545    }
2546    return true;
2547 }
2548
2549
2550 void
2551 link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
2552 {
2553    tfeedback_decl *tfeedback_decls = NULL;
2554    unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
2555
2556    void *mem_ctx = ralloc_context(NULL); // temporary linker context
2557
2558    prog->LinkStatus = true; /* All error paths will set this to false */
2559    prog->Validated = false;
2560    prog->_Used = false;
2561
2562    prog->ARB_fragment_coord_conventions_enable = false;
2563
2564    /* Separate the shaders into groups based on their type.
2565     */
2566    struct gl_shader **shader_list[MESA_SHADER_STAGES];
2567    unsigned num_shaders[MESA_SHADER_STAGES];
2568
2569    for (int i = 0; i < MESA_SHADER_STAGES; i++) {
2570       shader_list[i] = (struct gl_shader **)
2571          calloc(prog->NumShaders, sizeof(struct gl_shader *));
2572       num_shaders[i] = 0;
2573    }
2574
2575    unsigned min_version = UINT_MAX;
2576    unsigned max_version = 0;
2577    const bool is_es_prog =
2578       (prog->NumShaders > 0 && prog->Shaders[0]->IsES) ? true : false;
2579    for (unsigned i = 0; i < prog->NumShaders; i++) {
2580       min_version = MIN2(min_version, prog->Shaders[i]->Version);
2581       max_version = MAX2(max_version, prog->Shaders[i]->Version);
2582
2583       if (prog->Shaders[i]->IsES != is_es_prog) {
2584          linker_error(prog, "all shaders must use same shading "
2585                       "language version\n");
2586          goto done;
2587       }
2588
2589       prog->ARB_fragment_coord_conventions_enable |=
2590          prog->Shaders[i]->ARB_fragment_coord_conventions_enable;
2591
2592       gl_shader_stage shader_type = prog->Shaders[i]->Stage;
2593       shader_list[shader_type][num_shaders[shader_type]] = prog->Shaders[i];
2594       num_shaders[shader_type]++;
2595    }
2596
2597    /* In desktop GLSL, different shader versions may be linked together.  In
2598     * GLSL ES, all shader versions must be the same.
2599     */
2600    if (is_es_prog && min_version != max_version) {
2601       linker_error(prog, "all shaders must use same shading "
2602                    "language version\n");
2603       goto done;
2604    }
2605
2606    prog->Version = max_version;
2607    prog->IsES = is_es_prog;
2608
2609    /* Geometry shaders have to be linked with vertex shaders.
2610     */
2611    if (num_shaders[MESA_SHADER_GEOMETRY] > 0 &&
2612        num_shaders[MESA_SHADER_VERTEX] == 0 &&
2613        !prog->SeparateShader) {
2614       linker_error(prog, "Geometry shader must be linked with "
2615                    "vertex shader\n");
2616       goto done;
2617    }
2618
2619    /* Compute shaders have additional restrictions. */
2620    if (num_shaders[MESA_SHADER_COMPUTE] > 0 &&
2621        num_shaders[MESA_SHADER_COMPUTE] != prog->NumShaders) {
2622       linker_error(prog, "Compute shaders may not be linked with any other "
2623                    "type of shader\n");
2624    }
2625
2626    for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
2627       if (prog->_LinkedShaders[i] != NULL)
2628          ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
2629
2630       prog->_LinkedShaders[i] = NULL;
2631    }
2632
2633    /* Link all shaders for a particular stage and validate the result.
2634     */
2635    for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
2636       if (num_shaders[stage] > 0) {
2637          gl_shader *const sh =
2638             link_intrastage_shaders(mem_ctx, ctx, prog, shader_list[stage],
2639                                     num_shaders[stage]);
2640
2641          if (!prog->LinkStatus) {
2642             if (sh)
2643                ctx->Driver.DeleteShader(ctx, sh);
2644             goto done;
2645          }
2646
2647          switch (stage) {
2648          case MESA_SHADER_VERTEX:
2649             validate_vertex_shader_executable(prog, sh);
2650             break;
2651          case MESA_SHADER_GEOMETRY:
2652             validate_geometry_shader_executable(prog, sh);
2653             break;
2654          case MESA_SHADER_FRAGMENT:
2655             validate_fragment_shader_executable(prog, sh);
2656             break;
2657          }
2658          if (!prog->LinkStatus) {
2659             if (sh)
2660                ctx->Driver.DeleteShader(ctx, sh);
2661             goto done;
2662          }
2663
2664          _mesa_reference_shader(ctx, &prog->_LinkedShaders[stage], sh);
2665       }
2666    }
2667
2668    if (num_shaders[MESA_SHADER_GEOMETRY] > 0)
2669       prog->LastClipDistanceArraySize = prog->Geom.ClipDistanceArraySize;
2670    else if (num_shaders[MESA_SHADER_VERTEX] > 0)
2671       prog->LastClipDistanceArraySize = prog->Vert.ClipDistanceArraySize;
2672    else
2673       prog->LastClipDistanceArraySize = 0; /* Not used */
2674
2675    /* Here begins the inter-stage linking phase.  Some initial validation is
2676     * performed, then locations are assigned for uniforms, attributes, and
2677     * varyings.
2678     */
2679    cross_validate_uniforms(prog);
2680    if (!prog->LinkStatus)
2681       goto done;
2682
2683    unsigned prev;
2684
2685    for (prev = 0; prev <= MESA_SHADER_FRAGMENT; prev++) {
2686       if (prog->_LinkedShaders[prev] != NULL)
2687          break;
2688    }
2689
2690    check_explicit_uniform_locations(ctx, prog);
2691    if (!prog->LinkStatus)
2692       goto done;
2693
2694    /* Validate the inputs of each stage with the output of the preceding
2695     * stage.
2696     */
2697    for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
2698       if (prog->_LinkedShaders[i] == NULL)
2699          continue;
2700
2701       validate_interstage_inout_blocks(prog, prog->_LinkedShaders[prev],
2702                                        prog->_LinkedShaders[i]);
2703       if (!prog->LinkStatus)
2704          goto done;
2705
2706       cross_validate_outputs_to_inputs(prog,
2707                                        prog->_LinkedShaders[prev],
2708                                        prog->_LinkedShaders[i]);
2709       if (!prog->LinkStatus)
2710          goto done;
2711
2712       prev = i;
2713    }
2714
2715    /* Cross-validate uniform blocks between shader stages */
2716    validate_interstage_uniform_blocks(prog, prog->_LinkedShaders,
2717                                       MESA_SHADER_STAGES);
2718    if (!prog->LinkStatus)
2719       goto done;
2720
2721    for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
2722       if (prog->_LinkedShaders[i] != NULL)
2723          lower_named_interface_blocks(mem_ctx, prog->_LinkedShaders[i]);
2724    }
2725
2726    /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
2727     * it before optimization because we want most of the checks to get
2728     * dropped thanks to constant propagation.
2729     *
2730     * This rule also applies to GLSL ES 3.00.
2731     */
2732    if (max_version >= (is_es_prog ? 300 : 130)) {
2733       struct gl_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2734       if (sh) {
2735          lower_discard_flow(sh->ir);
2736       }
2737    }
2738
2739    if (!interstage_cross_validate_uniform_blocks(prog))
2740       goto done;
2741
2742    /* Do common optimization before assigning storage for attributes,
2743     * uniforms, and varyings.  Later optimization could possibly make
2744     * some of that unused.
2745     */
2746    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2747       if (prog->_LinkedShaders[i] == NULL)
2748          continue;
2749
2750       detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
2751       if (!prog->LinkStatus)
2752          goto done;
2753
2754       if (ctx->Const.ShaderCompilerOptions[i].LowerClipDistance) {
2755          lower_clip_distance(prog->_LinkedShaders[i]);
2756       }
2757
2758       while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false,
2759                                     &ctx->Const.ShaderCompilerOptions[i],
2760                                     ctx->Const.NativeIntegers))
2761          ;
2762
2763       lower_const_arrays_to_uniforms(prog->_LinkedShaders[i]->ir);
2764    }
2765
2766    /* Validation for special cases where we allow sampler array indexing
2767     * with loop induction variable. This check emits a warning or error
2768     * depending if backend can handle dynamic indexing.
2769     */
2770    if ((!prog->IsES && prog->Version < 130) ||
2771        (prog->IsES && prog->Version < 300)) {
2772       if (!validate_sampler_array_indexing(ctx, prog))
2773          goto done;
2774    }
2775
2776    /* Check and validate stream emissions in geometry shaders */
2777    validate_geometry_shader_emissions(ctx, prog);
2778
2779    /* Mark all generic shader inputs and outputs as unpaired. */
2780    for (unsigned i = MESA_SHADER_VERTEX; i <= MESA_SHADER_FRAGMENT; i++) {
2781       if (prog->_LinkedShaders[i] != NULL) {
2782          link_invalidate_variable_locations(prog->_LinkedShaders[i]->ir);
2783       }
2784    }
2785
2786    /* FINISHME: The value of the max_attribute_index parameter is
2787     * FINISHME: implementation dependent based on the value of
2788     * FINISHME: GL_MAX_VERTEX_ATTRIBS.  GL_MAX_VERTEX_ATTRIBS must be
2789     * FINISHME: at least 16, so hardcode 16 for now.
2790     */
2791    if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX, 16)) {
2792       goto done;
2793    }
2794
2795    if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, MAX2(ctx->Const.MaxDrawBuffers, ctx->Const.MaxDualSourceDrawBuffers))) {
2796       goto done;
2797    }
2798
2799    unsigned first;
2800    for (first = 0; first <= MESA_SHADER_FRAGMENT; first++) {
2801       if (prog->_LinkedShaders[first] != NULL)
2802          break;
2803    }
2804
2805    if (num_tfeedback_decls != 0) {
2806       /* From GL_EXT_transform_feedback:
2807        *   A program will fail to link if:
2808        *
2809        *   * the <count> specified by TransformFeedbackVaryingsEXT is
2810        *     non-zero, but the program object has no vertex or geometry
2811        *     shader;
2812        */
2813       if (first == MESA_SHADER_FRAGMENT) {
2814          linker_error(prog, "Transform feedback varyings specified, but "
2815                       "no vertex or geometry shader is present.\n");
2816          goto done;
2817       }
2818
2819       tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
2820                                      prog->TransformFeedback.NumVarying);
2821       if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
2822                                  prog->TransformFeedback.VaryingNames,
2823                                  tfeedback_decls))
2824          goto done;
2825    }
2826
2827    /* Linking the stages in the opposite order (from fragment to vertex)
2828     * ensures that inter-shader outputs written to in an earlier stage are
2829     * eliminated if they are (transitively) not used in a later stage.
2830     */
2831    int last, next;
2832    for (last = MESA_SHADER_FRAGMENT; last >= 0; last--) {
2833       if (prog->_LinkedShaders[last] != NULL)
2834          break;
2835    }
2836
2837    if (last >= 0 && last < MESA_SHADER_FRAGMENT) {
2838       gl_shader *const sh = prog->_LinkedShaders[last];
2839
2840       if (first == MESA_SHADER_GEOMETRY) {
2841          /* There was no vertex shader, but we still have to assign varying
2842           * locations for use by geometry shader inputs in SSO.
2843           *
2844           * If the shader is not separable (i.e., prog->SeparateShader is
2845           * false), linking will have already failed when first is
2846           * MESA_SHADER_GEOMETRY.
2847           */
2848          if (!assign_varying_locations(ctx, mem_ctx, prog,
2849                                        NULL, sh,
2850                                        num_tfeedback_decls, tfeedback_decls,
2851                                        prog->Geom.VerticesIn))
2852             goto done;
2853       }
2854
2855       if (num_tfeedback_decls != 0 || prog->SeparateShader) {
2856          /* There was no fragment shader, but we still have to assign varying
2857           * locations for use by transform feedback.
2858           */
2859          if (!assign_varying_locations(ctx, mem_ctx, prog,
2860                                        sh, NULL,
2861                                        num_tfeedback_decls, tfeedback_decls,
2862                                        0))
2863             goto done;
2864       }
2865
2866       do_dead_builtin_varyings(ctx, sh, NULL,
2867                                num_tfeedback_decls, tfeedback_decls);
2868
2869       if (!prog->SeparateShader)
2870          demote_shader_inputs_and_outputs(sh, ir_var_shader_out);
2871
2872       /* Eliminate code that is now dead due to unused outputs being demoted.
2873        */
2874       while (do_dead_code(sh->ir, false))
2875          ;
2876    }
2877    else if (first == MESA_SHADER_FRAGMENT) {
2878       /* If the program only contains a fragment shader...
2879        */
2880       gl_shader *const sh = prog->_LinkedShaders[first];
2881
2882       do_dead_builtin_varyings(ctx, NULL, sh,
2883                                num_tfeedback_decls, tfeedback_decls);
2884
2885       if (prog->SeparateShader) {
2886          if (!assign_varying_locations(ctx, mem_ctx, prog,
2887                                        NULL /* producer */,
2888                                        sh /* consumer */,
2889                                        0 /* num_tfeedback_decls */,
2890                                        NULL /* tfeedback_decls */,
2891                                        0 /* gs_input_vertices */))
2892             goto done;
2893       } else
2894          demote_shader_inputs_and_outputs(sh, ir_var_shader_in);
2895
2896       while (do_dead_code(sh->ir, false))
2897          ;
2898    }
2899
2900    next = last;
2901    for (int i = next - 1; i >= 0; i--) {
2902       if (prog->_LinkedShaders[i] == NULL)
2903          continue;
2904
2905       gl_shader *const sh_i = prog->_LinkedShaders[i];
2906       gl_shader *const sh_next = prog->_LinkedShaders[next];
2907       unsigned gs_input_vertices =
2908          next == MESA_SHADER_GEOMETRY ? prog->Geom.VerticesIn : 0;
2909
2910       if (!assign_varying_locations(ctx, mem_ctx, prog, sh_i, sh_next,
2911                 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2912                 tfeedback_decls, gs_input_vertices))
2913          goto done;
2914
2915       do_dead_builtin_varyings(ctx, sh_i, sh_next,
2916                 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2917                 tfeedback_decls);
2918
2919       demote_shader_inputs_and_outputs(sh_i, ir_var_shader_out);
2920       demote_shader_inputs_and_outputs(sh_next, ir_var_shader_in);
2921
2922       /* Eliminate code that is now dead due to unused outputs being demoted.
2923        */
2924       while (do_dead_code(sh_i->ir, false))
2925          ;
2926       while (do_dead_code(sh_next->ir, false))
2927          ;
2928
2929       /* This must be done after all dead varyings are eliminated. */
2930       if (!check_against_output_limit(ctx, prog, sh_i))
2931          goto done;
2932       if (!check_against_input_limit(ctx, prog, sh_next))
2933          goto done;
2934
2935       next = i;
2936    }
2937
2938    if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
2939       goto done;
2940
2941    update_array_sizes(prog);
2942    link_assign_uniform_locations(prog, ctx->Const.UniformBooleanTrue);
2943    link_assign_atomic_counter_resources(ctx, prog);
2944    store_fragdepth_layout(prog);
2945
2946    check_resources(ctx, prog);
2947    check_image_resources(ctx, prog);
2948    link_check_atomic_counter_resources(ctx, prog);
2949
2950    if (!prog->LinkStatus)
2951       goto done;
2952
2953    /* OpenGL ES requires that a vertex shader and a fragment shader both be
2954     * present in a linked program. GL_ARB_ES2_compatibility doesn't say
2955     * anything about shader linking when one of the shaders (vertex or
2956     * fragment shader) is absent. So, the extension shouldn't change the
2957     * behavior specified in GLSL specification.
2958     */
2959    if (!prog->SeparateShader && ctx->API == API_OPENGLES2) {
2960       if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
2961          linker_error(prog, "program lacks a vertex shader\n");
2962       } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2963          linker_error(prog, "program lacks a fragment shader\n");
2964       }
2965    }
2966
2967    /* FINISHME: Assign fragment shader output locations. */
2968
2969 done:
2970    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2971       free(shader_list[i]);
2972       if (prog->_LinkedShaders[i] == NULL)
2973          continue;
2974
2975       /* Do a final validation step to make sure that the IR wasn't
2976        * invalidated by any modifications performed after intrastage linking.
2977        */
2978       validate_ir_tree(prog->_LinkedShaders[i]->ir);
2979
2980       /* Retain any live IR, but trash the rest. */
2981       reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
2982
2983       /* The symbol table in the linked shaders may contain references to
2984        * variables that were removed (e.g., unused uniforms).  Since it may
2985        * contain junk, there is no possible valid use.  Delete it and set the
2986        * pointer to NULL.
2987        */
2988       delete prog->_LinkedShaders[i]->symbols;
2989       prog->_LinkedShaders[i]->symbols = NULL;
2990    }
2991
2992    ralloc_free(mem_ctx);
2993 }