1/*
2 * Copyright © 2012 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#include "ir.h"
25#include "linker.h"
26#include "ir_uniform.h"
27#include "link_uniform_block_active_visitor.h"
28#include "util/hash_table.h"
29#include "program.h"
30#include "main/errors.h"
31#include "main/mtypes.h"
32
33namespace {
34
35class ubo_visitor : public program_resource_visitor {
36public:
37   ubo_visitor(void *mem_ctx, gl_uniform_buffer_variable *variables,
38               unsigned num_variables, struct gl_shader_program *prog,
39               bool use_std430_as_default)
40      : index(0), offset(0), buffer_size(0), variables(variables),
41        num_variables(num_variables), mem_ctx(mem_ctx),
42        is_array_instance(false), prog(prog),
43        use_std430_as_default(use_std430_as_default)
44   {
45      /* empty */
46   }
47
48   void process(const glsl_type *type, const char *name)
49   {
50      this->offset = 0;
51      this->buffer_size = 0;
52      this->is_array_instance = strchr(name, ']') != NULL;
53      this->program_resource_visitor::process(type, name,
54                                              use_std430_as_default);
55   }
56
57   unsigned index;
58   unsigned offset;
59   unsigned buffer_size;
60   gl_uniform_buffer_variable *variables;
61   unsigned num_variables;
62   void *mem_ctx;
63   bool is_array_instance;
64   struct gl_shader_program *prog;
65
66private:
67   virtual void enter_record(const glsl_type *type, const char *,
68                             bool row_major,
69                             const enum glsl_interface_packing packing)
70   {
71      assert(type->is_struct());
72      if (packing == GLSL_INTERFACE_PACKING_STD430)
73         this->offset = glsl_align(
74            this->offset, type->std430_base_alignment(row_major));
75      else
76         this->offset = glsl_align(
77            this->offset, type->std140_base_alignment(row_major));
78   }
79
80   virtual void leave_record(const glsl_type *type, const char *,
81                             bool row_major,
82                             const enum glsl_interface_packing packing)
83   {
84      assert(type->is_struct());
85
86      /* If this is the last field of a structure, apply rule #9.  The
87       * ARB_uniform_buffer_object spec says:
88       *
89       *    The structure may have padding at the end; the base offset of the
90       *    member following the sub-structure is rounded up to the next
91       *    multiple of the base alignment of the structure.
92       */
93      if (packing == GLSL_INTERFACE_PACKING_STD430)
94         this->offset = glsl_align(
95            this->offset, type->std430_base_alignment(row_major));
96      else
97         this->offset = glsl_align(
98            this->offset, type->std140_base_alignment(row_major));
99   }
100
101   virtual void set_buffer_offset(unsigned offset)
102   {
103      this->offset = offset;
104   }
105
106   virtual void visit_field(const glsl_type *type, const char *name,
107                            bool row_major, const glsl_type *,
108                            const enum glsl_interface_packing packing,
109                            bool last_field)
110   {
111      assert(this->index < this->num_variables);
112
113      gl_uniform_buffer_variable *v = &this->variables[this->index++];
114
115      v->Name = ralloc_strdup(mem_ctx, name);
116      v->Type = type;
117      v->RowMajor = type->without_array()->is_matrix() && row_major;
118
119      if (this->is_array_instance) {
120         v->IndexName = ralloc_strdup(mem_ctx, name);
121
122         char *open_bracket = strchr(v->IndexName, '[');
123         assert(open_bracket != NULL);
124
125         char *close_bracket = strchr(open_bracket, '.') - 1;
126         assert(close_bracket != NULL);
127
128         /* Length of the tail without the ']' but with the NUL.
129          */
130         unsigned len = strlen(close_bracket + 1) + 1;
131
132         memmove(open_bracket, close_bracket + 1, len);
133      } else {
134         v->IndexName = v->Name;
135      }
136
137      unsigned alignment = 0;
138      unsigned size = 0;
139
140      /* The ARB_program_interface_query spec says:
141       *
142       *    If the final member of an active shader storage block is array
143       *    with no declared size, the minimum buffer size is computed
144       *    assuming the array was declared as an array with one element.
145       *
146       * For that reason, we use the base type of the unsized array to
147       * calculate its size. We don't need to check if the unsized array is
148       * the last member of a shader storage block (that check was already
149       * done by the parser).
150       */
151      const glsl_type *type_for_size = type;
152      if (type->is_unsized_array()) {
153         if (!last_field) {
154            linker_error(prog, "unsized array `%s' definition: "
155                         "only last member of a shader storage block "
156                         "can be defined as unsized array",
157                         name);
158         }
159
160         type_for_size = type->without_array();
161      }
162
163      if (packing == GLSL_INTERFACE_PACKING_STD430) {
164         alignment = type->std430_base_alignment(v->RowMajor);
165         size = type_for_size->std430_size(v->RowMajor);
166      } else {
167         alignment = type->std140_base_alignment(v->RowMajor);
168         size = type_for_size->std140_size(v->RowMajor);
169      }
170
171      this->offset = glsl_align(this->offset, alignment);
172      v->Offset = this->offset;
173
174      this->offset += size;
175
176      /* The ARB_uniform_buffer_object spec says:
177       *
178       *    For uniform blocks laid out according to [std140] rules, the
179       *    minimum buffer object size returned by the UNIFORM_BLOCK_DATA_SIZE
180       *    query is derived by taking the offset of the last basic machine
181       *    unit consumed by the last uniform of the uniform block (including
182       *    any end-of-array or end-of-structure padding), adding one, and
183       *    rounding up to the next multiple of the base alignment required
184       *    for a vec4.
185       */
186      this->buffer_size = glsl_align(this->offset, 16);
187   }
188
189   bool use_std430_as_default;
190};
191
192class count_block_size : public program_resource_visitor {
193public:
194   count_block_size() : num_active_uniforms(0)
195   {
196      /* empty */
197   }
198
199   unsigned num_active_uniforms;
200
201private:
202   virtual void visit_field(const glsl_type * /* type */,
203                            const char * /* name */,
204                            bool /* row_major */,
205                            const glsl_type * /* record_type */,
206                            const enum glsl_interface_packing,
207                            bool /* last_field */)
208   {
209      this->num_active_uniforms++;
210   }
211};
212
213} /* anonymous namespace */
214
215struct block {
216   const glsl_type *type;
217   bool has_instance_name;
218};
219
220static void process_block_array_leaf(const char *name, gl_uniform_block *blocks,
221                                     ubo_visitor *parcel,
222                                     gl_uniform_buffer_variable *variables,
223                                     const struct link_uniform_block_active *const b,
224                                     unsigned *block_index,
225                                     unsigned *binding_offset,
226                                     unsigned linearized_index,
227                                     struct gl_context *ctx,
228                                     struct gl_shader_program *prog);
229
230/**
231 *
232 * \param first_index Value of \c block_index for the first element of the
233 *                    array.
234 */
235static void
236process_block_array(struct uniform_block_array_elements *ub_array, char **name,
237                    size_t name_length, gl_uniform_block *blocks,
238                    ubo_visitor *parcel, gl_uniform_buffer_variable *variables,
239                    const struct link_uniform_block_active *const b,
240                    unsigned *block_index, unsigned *binding_offset,
241                    struct gl_context *ctx, struct gl_shader_program *prog,
242                    unsigned first_index)
243{
244   for (unsigned j = 0; j < ub_array->num_array_elements; j++) {
245      size_t new_length = name_length;
246
247      /* Append the subscript to the current variable name */
248      ralloc_asprintf_rewrite_tail(name, &new_length, "[%u]",
249                                   ub_array->array_elements[j]);
250
251      if (ub_array->array) {
252         process_block_array(ub_array->array, name, new_length, blocks,
253                             parcel, variables, b, block_index,
254                             binding_offset, ctx, prog, first_index);
255      } else {
256         process_block_array_leaf(*name, blocks,
257                                  parcel, variables, b, block_index,
258                                  binding_offset, *block_index - first_index,
259                                  ctx, prog);
260      }
261   }
262}
263
264static void
265process_block_array_leaf(const char *name,
266                         gl_uniform_block *blocks,
267                         ubo_visitor *parcel, gl_uniform_buffer_variable *variables,
268                         const struct link_uniform_block_active *const b,
269                         unsigned *block_index, unsigned *binding_offset,
270                         unsigned linearized_index,
271                         struct gl_context *ctx, struct gl_shader_program *prog)
272{
273   unsigned i = *block_index;
274   const glsl_type *type =  b->type->without_array();
275
276   blocks[i].Name = ralloc_strdup(blocks, name);
277   blocks[i].Uniforms = &variables[(*parcel).index];
278
279   /* The ARB_shading_language_420pack spec says:
280    *
281    *    If the binding identifier is used with a uniform block instanced as
282    *    an array then the first element of the array takes the specified
283    *    block binding and each subsequent element takes the next consecutive
284    *    uniform block binding point.
285    */
286   blocks[i].Binding = (b->has_binding) ? b->binding + *binding_offset : 0;
287
288   blocks[i].UniformBufferSize = 0;
289   blocks[i]._Packing = glsl_interface_packing(type->interface_packing);
290   blocks[i]._RowMajor = type->get_interface_row_major();
291   blocks[i].linearized_array_index = linearized_index;
292
293   parcel->process(type, b->has_instance_name ? blocks[i].Name : "");
294
295   blocks[i].UniformBufferSize = parcel->buffer_size;
296
297   /* Check SSBO size is lower than maximum supported size for SSBO */
298   if (b->is_shader_storage &&
299       parcel->buffer_size > ctx->Const.MaxShaderStorageBlockSize) {
300      linker_error(prog, "shader storage block `%s' has size %d, "
301                   "which is larger than the maximum allowed (%d)",
302                   b->type->name,
303                   parcel->buffer_size,
304                   ctx->Const.MaxShaderStorageBlockSize);
305   }
306   blocks[i].NumUniforms =
307      (unsigned)(ptrdiff_t)(&variables[parcel->index] - blocks[i].Uniforms);
308
309   *block_index = *block_index + 1;
310   *binding_offset = *binding_offset + 1;
311}
312
313/* This function resizes the array types of the block so that later we can use
314 * this new size to correctly calculate the offest for indirect indexing.
315 */
316static const glsl_type *
317resize_block_array(const glsl_type *type,
318                   struct uniform_block_array_elements *ub_array)
319{
320   if (type->is_array()) {
321      struct uniform_block_array_elements *child_array =
322         type->fields.array->is_array() ? ub_array->array : NULL;
323      const glsl_type *new_child_type =
324         resize_block_array(type->fields.array, child_array);
325
326      const glsl_type *new_type =
327         glsl_type::get_array_instance(new_child_type,
328                                       ub_array->num_array_elements);
329      ub_array->ir->array->type = new_type;
330      return new_type;
331   } else {
332      return type;
333   }
334}
335
336static void
337create_buffer_blocks(void *mem_ctx, struct gl_context *ctx,
338                     struct gl_shader_program *prog,
339                     struct gl_uniform_block **out_blks, unsigned num_blocks,
340                     struct hash_table *block_hash, unsigned num_variables,
341                     bool create_ubo_blocks)
342{
343   if (num_blocks == 0) {
344      assert(num_variables == 0);
345      return;
346   }
347
348   assert(num_variables != 0);
349
350   /* Allocate storage to hold all of the information related to uniform
351    * blocks that can be queried through the API.
352    */
353   struct gl_uniform_block *blocks =
354      rzalloc_array(mem_ctx, gl_uniform_block, num_blocks);
355   gl_uniform_buffer_variable *variables =
356      ralloc_array(blocks, gl_uniform_buffer_variable, num_variables);
357
358   /* Add each variable from each uniform block to the API tracking
359    * structures.
360    */
361   ubo_visitor parcel(blocks, variables, num_variables, prog,
362                      ctx->Const.UseSTD430AsDefaultPacking);
363
364   unsigned i = 0;
365   hash_table_foreach (block_hash, entry) {
366      const struct link_uniform_block_active *const b =
367         (const struct link_uniform_block_active *) entry->data;
368      const glsl_type *block_type = b->type;
369
370      if ((create_ubo_blocks && !b->is_shader_storage) ||
371          (!create_ubo_blocks && b->is_shader_storage)) {
372
373         unsigned binding_offset = 0;
374         if (b->array != NULL) {
375            char *name = ralloc_strdup(NULL,
376                                       block_type->without_array()->name);
377            size_t name_length = strlen(name);
378
379            assert(b->has_instance_name);
380            process_block_array(b->array, &name, name_length, blocks, &parcel,
381                                variables, b, &i, &binding_offset, ctx, prog,
382                                i);
383            ralloc_free(name);
384         } else {
385            process_block_array_leaf(block_type->name, blocks, &parcel,
386                                     variables, b, &i, &binding_offset,
387                                     0, ctx, prog);
388         }
389      }
390   }
391
392   *out_blks = blocks;
393
394   assert(parcel.index == num_variables);
395}
396
397void
398link_uniform_blocks(void *mem_ctx,
399                    struct gl_context *ctx,
400                    struct gl_shader_program *prog,
401                    struct gl_linked_shader *shader,
402                    struct gl_uniform_block **ubo_blocks,
403                    unsigned *num_ubo_blocks,
404                    struct gl_uniform_block **ssbo_blocks,
405                    unsigned *num_ssbo_blocks)
406{
407   /* This hash table will track all of the uniform blocks that have been
408    * encountered.  Since blocks with the same block-name must be the same,
409    * the hash is organized by block-name.
410    */
411   struct hash_table *block_hash =
412      _mesa_hash_table_create(mem_ctx, _mesa_key_hash_string,
413                              _mesa_key_string_equal);
414
415   if (block_hash == NULL) {
416      _mesa_error_no_memory(__func__);
417      linker_error(prog, "out of memory\n");
418      return;
419   }
420
421   /* Determine which uniform blocks are active. */
422   link_uniform_block_active_visitor v(mem_ctx, block_hash, prog);
423   visit_list_elements(&v, shader->ir);
424
425   /* Count the number of active uniform blocks.  Count the total number of
426    * active slots in those uniform blocks.
427    */
428   unsigned num_ubo_variables = 0;
429   unsigned num_ssbo_variables = 0;
430   count_block_size block_size;
431
432   hash_table_foreach (block_hash, entry) {
433      struct link_uniform_block_active *const b =
434         (struct link_uniform_block_active *) entry->data;
435
436      assert((b->array != NULL) == b->type->is_array());
437
438      if (b->array != NULL &&
439          (b->type->without_array()->interface_packing ==
440           GLSL_INTERFACE_PACKING_PACKED)) {
441         b->type = resize_block_array(b->type, b->array);
442         b->var->type = b->type;
443      }
444
445      block_size.num_active_uniforms = 0;
446      block_size.process(b->type->without_array(), "",
447                         ctx->Const.UseSTD430AsDefaultPacking);
448
449      if (b->array != NULL) {
450         unsigned aoa_size = b->type->arrays_of_arrays_size();
451         if (b->is_shader_storage) {
452            *num_ssbo_blocks += aoa_size;
453            num_ssbo_variables += aoa_size * block_size.num_active_uniforms;
454         } else {
455            *num_ubo_blocks += aoa_size;
456            num_ubo_variables += aoa_size * block_size.num_active_uniforms;
457         }
458      } else {
459         if (b->is_shader_storage) {
460            (*num_ssbo_blocks)++;
461            num_ssbo_variables += block_size.num_active_uniforms;
462         } else {
463            (*num_ubo_blocks)++;
464            num_ubo_variables += block_size.num_active_uniforms;
465         }
466      }
467
468   }
469
470   create_buffer_blocks(mem_ctx, ctx, prog, ubo_blocks, *num_ubo_blocks,
471                        block_hash, num_ubo_variables, true);
472   create_buffer_blocks(mem_ctx, ctx, prog, ssbo_blocks, *num_ssbo_blocks,
473                        block_hash, num_ssbo_variables, false);
474
475   _mesa_hash_table_destroy(block_hash, NULL);
476}
477
478static bool
479link_uniform_blocks_are_compatible(const gl_uniform_block *a,
480                                   const gl_uniform_block *b)
481{
482   assert(strcmp(a->Name, b->Name) == 0);
483
484   /* Page 35 (page 42 of the PDF) in section 4.3.7 of the GLSL 1.50 spec says:
485    *
486    *    Matched block names within an interface (as defined above) must match
487    *    in terms of having the same number of declarations with the same
488    *    sequence of types and the same sequence of member names, as well as
489    *    having the same member-wise layout qualification....if a matching
490    *    block is declared as an array, then the array sizes must also
491    *    match... Any mismatch will generate a link error.
492    *
493    * Arrays are not yet supported, so there is no check for that.
494    */
495   if (a->NumUniforms != b->NumUniforms)
496      return false;
497
498   if (a->_Packing != b->_Packing)
499      return false;
500
501   if (a->_RowMajor != b->_RowMajor)
502      return false;
503
504   if (a->Binding != b->Binding)
505      return false;
506
507   for (unsigned i = 0; i < a->NumUniforms; i++) {
508      if (strcmp(a->Uniforms[i].Name, b->Uniforms[i].Name) != 0)
509         return false;
510
511      if (a->Uniforms[i].Type != b->Uniforms[i].Type)
512         return false;
513
514      if (a->Uniforms[i].RowMajor != b->Uniforms[i].RowMajor)
515         return false;
516   }
517
518   return true;
519}
520
521/**
522 * Merges a uniform block into an array of uniform blocks that may or
523 * may not already contain a copy of it.
524 *
525 * Returns the index of the new block in the array.
526 */
527int
528link_cross_validate_uniform_block(void *mem_ctx,
529                                  struct gl_uniform_block **linked_blocks,
530                                  unsigned int *num_linked_blocks,
531                                  struct gl_uniform_block *new_block)
532{
533   for (unsigned int i = 0; i < *num_linked_blocks; i++) {
534      struct gl_uniform_block *old_block = &(*linked_blocks)[i];
535
536      if (strcmp(old_block->Name, new_block->Name) == 0)
537         return link_uniform_blocks_are_compatible(old_block, new_block)
538            ? i : -1;
539   }
540
541   *linked_blocks = reralloc(mem_ctx, *linked_blocks,
542                             struct gl_uniform_block,
543                             *num_linked_blocks + 1);
544   int linked_block_index = (*num_linked_blocks)++;
545   struct gl_uniform_block *linked_block = &(*linked_blocks)[linked_block_index];
546
547   memcpy(linked_block, new_block, sizeof(*new_block));
548   linked_block->Uniforms = ralloc_array(*linked_blocks,
549                                         struct gl_uniform_buffer_variable,
550                                         linked_block->NumUniforms);
551
552   memcpy(linked_block->Uniforms,
553          new_block->Uniforms,
554          sizeof(*linked_block->Uniforms) * linked_block->NumUniforms);
555
556   linked_block->Name = ralloc_strdup(*linked_blocks, linked_block->Name);
557
558   for (unsigned int i = 0; i < linked_block->NumUniforms; i++) {
559      struct gl_uniform_buffer_variable *ubo_var =
560         &linked_block->Uniforms[i];
561
562      if (ubo_var->Name == ubo_var->IndexName) {
563         ubo_var->Name = ralloc_strdup(*linked_blocks, ubo_var->Name);
564         ubo_var->IndexName = ubo_var->Name;
565      } else {
566         ubo_var->Name = ralloc_strdup(*linked_blocks, ubo_var->Name);
567         ubo_var->IndexName = ralloc_strdup(*linked_blocks, ubo_var->IndexName);
568      }
569   }
570
571   return linked_block_index;
572}
573