OSDN Git Service

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