1/*
2 * Copyright © 2013 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 link_interface_blocks.cpp
26 * Linker support for GLSL's interface blocks.
27 */
28
29#include "ir.h"
30#include "glsl_symbol_table.h"
31#include "linker.h"
32#include "main/macros.h"
33#include "main/shader_types.h"
34#include "util/hash_table.h"
35#include "util/u_string.h"
36
37
38namespace {
39
40/**
41 * Return true if interface members mismatch and its not allowed by GLSL.
42 */
43static bool
44interstage_member_mismatch(struct gl_shader_program *prog,
45                           const glsl_type *c, const glsl_type *p) {
46
47   if (c->length != p->length)
48      return true;
49
50   for (unsigned i = 0; i < c->length; i++) {
51      if (c->fields.structure[i].type != p->fields.structure[i].type)
52         return true;
53      if (strcmp(c->fields.structure[i].name,
54                 p->fields.structure[i].name) != 0)
55         return true;
56      if (c->fields.structure[i].location !=
57          p->fields.structure[i].location)
58         return true;
59      if (c->fields.structure[i].component !=
60          p->fields.structure[i].component)
61         return true;
62      if (c->fields.structure[i].patch !=
63          p->fields.structure[i].patch)
64         return true;
65
66      /* From Section 4.5 (Interpolation Qualifiers) of the GLSL 4.40 spec:
67       *
68       *    "It is a link-time error if, within the same stage, the
69       *    interpolation qualifiers of variables of the same name do not
70       *    match."
71       */
72      if (prog->IsES || prog->data->Version < 440)
73         if (c->fields.structure[i].interpolation !=
74             p->fields.structure[i].interpolation)
75            return true;
76
77      /* From Section 4.3.4 (Input Variables) of the GLSL ES 3.0 spec:
78       *
79       *    "The output of the vertex shader and the input of the fragment
80       *    shader form an interface.  For this interface, vertex shader
81       *    output variables and fragment shader input variables of the same
82       *    name must match in type and qualification (other than precision
83       *    and out matching to in).
84       *
85       * The table in Section 9.2.1 Linked Shaders of the GLSL ES 3.1 spec
86       * says that centroid no longer needs to match for varyings.
87       *
88       * The table in Section 9.2.1 Linked Shaders of the GLSL ES 3.2 spec
89       * says that sample need not match for varyings.
90       */
91      if (!prog->IsES || prog->data->Version < 310)
92         if (c->fields.structure[i].centroid !=
93             p->fields.structure[i].centroid)
94            return true;
95      if (!prog->IsES)
96         if (c->fields.structure[i].sample !=
97             p->fields.structure[i].sample)
98            return true;
99   }
100
101   return false;
102}
103
104/**
105 * Check if two interfaces match, according to intrastage interface matching
106 * rules.  If they do, and the first interface uses an unsized array, it will
107 * be updated to reflect the array size declared in the second interface.
108 */
109bool
110intrastage_match(ir_variable *a,
111                 ir_variable *b,
112                 struct gl_shader_program *prog,
113                 bool match_precision)
114{
115   /* From section 4.7 "Precision and Precision Qualifiers" in GLSL 4.50:
116    *
117    *    "For the purposes of determining if an output from one shader
118    *    stage matches an input of the next stage, the precision qualifier
119    *    need not match."
120    */
121   bool interface_type_match =
122      (prog->IsES ?
123       a->get_interface_type() == b->get_interface_type() :
124       a->get_interface_type()->compare_no_precision(b->get_interface_type()));
125
126   /* Types must match. */
127   if (!interface_type_match) {
128      /* Exception: if both the interface blocks are implicitly declared,
129       * don't force their types to match.  They might mismatch due to the two
130       * shaders using different GLSL versions, and that's ok.
131       */
132      if ((a->data.how_declared != ir_var_declared_implicitly ||
133           b->data.how_declared != ir_var_declared_implicitly) &&
134          (!prog->IsES ||
135           interstage_member_mismatch(prog, a->get_interface_type(),
136                                      b->get_interface_type())))
137         return false;
138   }
139
140   /* Presence/absence of interface names must match. */
141   if (a->is_interface_instance() != b->is_interface_instance())
142      return false;
143
144   /* For uniforms, instance names need not match.  For shader ins/outs,
145    * it's not clear from the spec whether they need to match, but
146    * Mesa's implementation relies on them matching.
147    */
148   if (a->is_interface_instance() && b->data.mode != ir_var_uniform &&
149       b->data.mode != ir_var_shader_storage &&
150       strcmp(a->name, b->name) != 0) {
151      return false;
152   }
153
154   bool type_match = (match_precision ?
155                      a->type == b->type :
156                      a->type->compare_no_precision(b->type));
157
158   /* If a block is an array then it must match across the shader.
159    * Unsized arrays are also processed and matched agaist sized arrays.
160    */
161   if (!type_match && (b->type->is_array() || a->type->is_array()) &&
162       (b->is_interface_instance() || a->is_interface_instance()) &&
163       !validate_intrastage_arrays(prog, b, a, match_precision))
164      return false;
165
166   return true;
167}
168
169/**
170 * Check if two interfaces match, according to interstage (in/out) interface
171 * matching rules.
172 *
173 * If \c extra_array_level is true, the consumer interface is required to be
174 * an array and the producer interface is required to be a non-array.
175 * This is used for tessellation control and geometry shader consumers.
176 */
177static bool
178interstage_match(struct gl_shader_program *prog, ir_variable *producer,
179                 ir_variable *consumer, bool extra_array_level)
180{
181   /* Types must match. */
182   if (consumer->get_interface_type() != producer->get_interface_type()) {
183      /* Exception: if both the interface blocks are implicitly declared,
184       * don't force their types to match.  They might mismatch due to the two
185       * shaders using different GLSL versions, and that's ok.
186       *
187       * Also we store some member information such as interpolation in
188       * glsl_type that doesn't always have to match across shader stages.
189       * Therefore we make a pass over the members glsl_struct_field to make
190       * sure we don't reject shaders where fields don't need to match.
191       */
192      if ((consumer->data.how_declared != ir_var_declared_implicitly ||
193           producer->data.how_declared != ir_var_declared_implicitly) &&
194          interstage_member_mismatch(prog, consumer->get_interface_type(),
195                                     producer->get_interface_type()))
196         return false;
197   }
198
199   /* Ignore outermost array if geom shader */
200   const glsl_type *consumer_instance_type;
201   if (extra_array_level) {
202      consumer_instance_type = consumer->type->fields.array;
203   } else {
204      consumer_instance_type = consumer->type;
205   }
206
207   /* If a block is an array then it must match across shaders.
208    * Since unsized arrays have been ruled out, we can check this by just
209    * making sure the types are equal.
210    */
211   if ((consumer->is_interface_instance() &&
212        consumer_instance_type->is_array()) ||
213       (producer->is_interface_instance() &&
214        producer->type->is_array())) {
215      if (consumer_instance_type != producer->type)
216         return false;
217   }
218
219   return true;
220}
221
222
223/**
224 * This class keeps track of a mapping from an interface block name to the
225 * necessary information about that interface block to determine whether to
226 * generate a link error.
227 *
228 * Note: this class is expected to be short lived, so it doesn't make copies
229 * of the strings it references; it simply borrows the pointers from the
230 * ir_variable class.
231 */
232class interface_block_definitions
233{
234public:
235   interface_block_definitions()
236      : mem_ctx(ralloc_context(NULL)),
237        ht(_mesa_hash_table_create(NULL, _mesa_hash_string,
238                                   _mesa_key_string_equal))
239   {
240   }
241
242   ~interface_block_definitions()
243   {
244      ralloc_free(mem_ctx);
245      _mesa_hash_table_destroy(ht, NULL);
246   }
247
248   /**
249    * Lookup the interface definition. Return NULL if none is found.
250    */
251   ir_variable *lookup(ir_variable *var)
252   {
253      if (var->data.explicit_location &&
254          var->data.location >= VARYING_SLOT_VAR0) {
255         char location_str[11];
256         snprintf(location_str, 11, "%d", var->data.location);
257
258         const struct hash_entry *entry =
259            _mesa_hash_table_search(ht, location_str);
260         return entry ? (ir_variable *) entry->data : NULL;
261      } else {
262         const struct hash_entry *entry =
263            _mesa_hash_table_search(ht,
264               var->get_interface_type()->without_array()->name);
265         return entry ? (ir_variable *) entry->data : NULL;
266      }
267   }
268
269   /**
270    * Add a new interface definition.
271    */
272   void store(ir_variable *var)
273   {
274      if (var->data.explicit_location &&
275          var->data.location >= VARYING_SLOT_VAR0) {
276         /* If explicit location is given then lookup the variable by location.
277          * We turn the location into a string and use this as the hash key
278          * rather than the name. Note: We allocate enough space for a 32-bit
279          * unsigned location value which is overkill but future proof.
280          */
281         char location_str[11];
282         snprintf(location_str, 11, "%d", var->data.location);
283         _mesa_hash_table_insert(ht, ralloc_strdup(mem_ctx, location_str), var);
284      } else {
285         _mesa_hash_table_insert(ht,
286            var->get_interface_type()->without_array()->name, var);
287      }
288   }
289
290private:
291   /**
292    * Ralloc context for data structures allocated by this class.
293    */
294   void *mem_ctx;
295
296   /**
297    * Hash table mapping interface block name to an \c
298    * ir_variable.
299    */
300   hash_table *ht;
301};
302
303
304}; /* anonymous namespace */
305
306
307void
308validate_intrastage_interface_blocks(struct gl_shader_program *prog,
309                                     const gl_shader **shader_list,
310                                     unsigned num_shaders)
311{
312   interface_block_definitions in_interfaces;
313   interface_block_definitions out_interfaces;
314   interface_block_definitions uniform_interfaces;
315   interface_block_definitions buffer_interfaces;
316
317   for (unsigned int i = 0; i < num_shaders; i++) {
318      if (shader_list[i] == NULL)
319         continue;
320
321      foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
322         ir_variable *var = node->as_variable();
323         if (!var)
324            continue;
325
326         const glsl_type *iface_type = var->get_interface_type();
327
328         if (iface_type == NULL)
329            continue;
330
331         interface_block_definitions *definitions;
332         switch (var->data.mode) {
333         case ir_var_shader_in:
334            definitions = &in_interfaces;
335            break;
336         case ir_var_shader_out:
337            definitions = &out_interfaces;
338            break;
339         case ir_var_uniform:
340            definitions = &uniform_interfaces;
341            break;
342         case ir_var_shader_storage:
343            definitions = &buffer_interfaces;
344            break;
345         default:
346            /* Only in, out, and uniform interfaces are legal, so we should
347             * never get here.
348             */
349            assert(!"illegal interface type");
350            continue;
351         }
352
353         ir_variable *prev_def = definitions->lookup(var);
354         if (prev_def == NULL) {
355            /* This is the first time we've seen the interface, so save
356             * it into the appropriate data structure.
357             */
358            definitions->store(var);
359         } else if (!intrastage_match(prev_def, var, prog,
360                                      true /* match_precision */)) {
361            linker_error(prog, "definitions of interface block `%s' do not"
362                         " match\n", iface_type->name);
363            return;
364         }
365      }
366   }
367}
368
369static bool
370is_builtin_gl_in_block(ir_variable *var, int consumer_stage)
371{
372   return !strcmp(var->name, "gl_in") &&
373          (consumer_stage == MESA_SHADER_TESS_CTRL ||
374           consumer_stage == MESA_SHADER_TESS_EVAL ||
375           consumer_stage == MESA_SHADER_GEOMETRY);
376}
377
378void
379validate_interstage_inout_blocks(struct gl_shader_program *prog,
380                                 const gl_linked_shader *producer,
381                                 const gl_linked_shader *consumer)
382{
383   interface_block_definitions definitions;
384   /* VS -> GS, VS -> TCS, VS -> TES, TES -> GS */
385   const bool extra_array_level = (producer->Stage == MESA_SHADER_VERTEX &&
386                                   consumer->Stage != MESA_SHADER_FRAGMENT) ||
387                                  consumer->Stage == MESA_SHADER_GEOMETRY;
388
389   /* Check that block re-declarations of gl_PerVertex are compatible
390    * across shaders: From OpenGL Shading Language 4.5, section
391    * "7.1 Built-In Language Variables", page 130 of the PDF:
392    *
393    *    "If multiple shaders using members of a built-in block belonging
394    *     to the same interface are linked together in the same program,
395    *     they must all redeclare the built-in block in the same way, as
396    *     described in section 4.3.9 “Interface Blocks” for interface-block
397    *     matching, or a link-time error will result."
398    *
399    * This is done explicitly outside of iterating the member variable
400    * declarations because it is possible that the variables are not used and
401    * so they would have been optimised out.
402    */
403   const glsl_type *consumer_iface =
404      consumer->symbols->get_interface("gl_PerVertex",
405                                       ir_var_shader_in);
406
407   const glsl_type *producer_iface =
408      producer->symbols->get_interface("gl_PerVertex",
409                                       ir_var_shader_out);
410
411   if (producer_iface && consumer_iface &&
412       interstage_member_mismatch(prog, consumer_iface, producer_iface)) {
413      linker_error(prog, "Incompatible or missing gl_PerVertex re-declaration "
414                   "in consecutive shaders");
415      return;
416   }
417
418   /* Desktop OpenGL requires redeclaration of the built-in interfaces for
419    * SSO programs. Passes above implement following rules:
420    *
421    * From Section 7.4 (Program Pipeline Objects) of the OpenGL 4.6 Core
422    * spec:
423    *
424    *    "To use any built-in input or output in the gl_PerVertex and
425    *     gl_PerFragment blocks in separable program objects, shader code
426    *     must redeclare those blocks prior to use.  A separable program
427    *     will fail to link if:
428    *
429    *     it contains multiple shaders of a single type with different
430    *     redeclarations of these built-in input and output blocks; or
431    *
432    *     any shader uses a built-in block member not found in the
433    *     redeclaration of that block."
434    *
435    * ARB_separate_shader_objects issues section (issue #28) states that
436    * redeclaration is not required for GLSL shaders using #version 140 or
437    * earlier (since interface blocks are not possible with older versions).
438    *
439    * From Section 7.4.1 (Shader Interface Matching) of the OpenGL ES 3.1
440    * spec:
441    *
442    *    "Built-in inputs or outputs do not affect interface matching."
443    *
444    * GL_OES_shader_io_blocks adds following:
445    *
446    *    "When using any built-in input or output in the gl_PerVertex block
447    *     in separable program objects, shader code may redeclare that block
448    *     prior to use. If the shader does not redeclare the block, the
449    *     intrinsically declared definition of that block will be used."
450    */
451
452   /* Add output interfaces from the producer to the symbol table. */
453   foreach_in_list(ir_instruction, node, producer->ir) {
454      ir_variable *var = node->as_variable();
455      if (!var || !var->get_interface_type() || var->data.mode != ir_var_shader_out)
456         continue;
457
458      /* Built-in interface redeclaration check. */
459      if (prog->SeparateShader && !prog->IsES && prog->data->Version >= 150 &&
460          var->data.how_declared == ir_var_declared_implicitly &&
461          var->data.used && !producer_iface) {
462         linker_error(prog, "missing output builtin block %s redeclaration "
463                      "in separable shader program",
464                      var->get_interface_type()->name);
465         return;
466      }
467
468      definitions.store(var);
469   }
470
471   /* Verify that the consumer's input interfaces match. */
472   foreach_in_list(ir_instruction, node, consumer->ir) {
473      ir_variable *var = node->as_variable();
474      if (!var || !var->get_interface_type() || var->data.mode != ir_var_shader_in)
475         continue;
476
477      ir_variable *producer_def = definitions.lookup(var);
478
479      /* Built-in interface redeclaration check. */
480      if (prog->SeparateShader && !prog->IsES && prog->data->Version >= 150 &&
481          var->data.how_declared == ir_var_declared_implicitly &&
482          var->data.used && !producer_iface) {
483         linker_error(prog, "missing input builtin block %s redeclaration "
484                      "in separable shader program",
485                      var->get_interface_type()->name);
486         return;
487      }
488
489      /* The producer doesn't generate this input: fail to link. Skip built-in
490       * 'gl_in[]' since that may not be present if the producer does not
491       * write to any of the pre-defined outputs (e.g. if the vertex shader
492       * does not write to gl_Position, etc), which is allowed and results in
493       * undefined behavior.
494       *
495       * From Section 4.3.4 (Inputs) of the GLSL 1.50 spec:
496       *
497       *    "Only the input variables that are actually read need to be written
498       *     by the previous stage; it is allowed to have superfluous
499       *     declarations of input variables."
500       */
501      if (producer_def == NULL &&
502          !is_builtin_gl_in_block(var, consumer->Stage) && var->data.used) {
503         linker_error(prog, "Input block `%s' is not an output of "
504                      "the previous stage\n", var->get_interface_type()->name);
505         return;
506      }
507
508      if (producer_def &&
509          !interstage_match(prog, producer_def, var, extra_array_level)) {
510         linker_error(prog, "definitions of interface block `%s' do not "
511                      "match\n", var->get_interface_type()->name);
512         return;
513      }
514   }
515}
516
517
518void
519validate_interstage_uniform_blocks(struct gl_shader_program *prog,
520                                   gl_linked_shader **stages)
521{
522   interface_block_definitions definitions;
523
524   for (int i = 0; i < MESA_SHADER_STAGES; i++) {
525      if (stages[i] == NULL)
526         continue;
527
528      const gl_linked_shader *stage = stages[i];
529      foreach_in_list(ir_instruction, node, stage->ir) {
530         ir_variable *var = node->as_variable();
531         if (!var || !var->get_interface_type() ||
532             (var->data.mode != ir_var_uniform &&
533              var->data.mode != ir_var_shader_storage))
534            continue;
535
536         ir_variable *old_def = definitions.lookup(var);
537         if (old_def == NULL) {
538            definitions.store(var);
539         } else {
540            /* Interstage uniform matching rules are the same as intrastage
541             * uniform matchin rules (for uniforms, it is as though all
542             * shaders are in the same shader stage).
543             */
544            if (!intrastage_match(old_def, var, prog, false /* precision */)) {
545               linker_error(prog, "definitions of uniform block `%s' do not "
546                            "match\n", var->get_interface_type()->name);
547               return;
548            }
549         }
550      }
551   }
552}
553