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