compiler/glsl: Fix uniform location counting.
[mesa.git] / src / compiler / glsl / link_uniforms.cpp
1 /*
2 * Copyright © 2011 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 "main/core.h"
25 #include "ir.h"
26 #include "linker.h"
27 #include "ir_uniform.h"
28 #include "glsl_symbol_table.h"
29 #include "program/hash_table.h"
30 #include "program.h"
31 #include "util/hash_table.h"
32
33 /**
34 * \file link_uniforms.cpp
35 * Assign locations for GLSL uniforms.
36 *
37 * \author Ian Romanick <ian.d.romanick@intel.com>
38 */
39
40 /**
41 * Used by linker to indicate uniforms that have no location set.
42 */
43 #define UNMAPPED_UNIFORM_LOC ~0u
44
45 /**
46 * Count the backing storage requirements for a type
47 */
48 static unsigned
49 values_for_type(const glsl_type *type)
50 {
51 if (type->is_sampler()) {
52 return 1;
53 } else if (type->is_array() && type->fields.array->is_sampler()) {
54 return type->array_size();
55 } else {
56 return type->component_slots();
57 }
58 }
59
60 void
61 program_resource_visitor::process(const glsl_type *type, const char *name)
62 {
63 assert(type->without_array()->is_record()
64 || type->without_array()->is_interface());
65
66 unsigned record_array_count = 1;
67 char *name_copy = ralloc_strdup(NULL, name);
68 unsigned packing = type->interface_packing;
69
70 recursion(type, &name_copy, strlen(name), false, NULL, packing, false,
71 record_array_count);
72 ralloc_free(name_copy);
73 }
74
75 void
76 program_resource_visitor::process(ir_variable *var)
77 {
78 unsigned record_array_count = 1;
79 const glsl_type *t = var->type;
80 const glsl_type *t_without_array = var->type->without_array();
81 const bool row_major =
82 var->data.matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR;
83
84 const unsigned packing = var->get_interface_type() ?
85 var->get_interface_type()->interface_packing :
86 var->type->interface_packing;
87
88 /* false is always passed for the row_major parameter to the other
89 * processing functions because no information is available to do
90 * otherwise. See the warning in linker.h.
91 */
92
93 /* Only strdup the name if we actually will need to modify it. */
94 if (var->data.from_named_ifc_block_array) {
95 /* lower_named_interface_blocks created this variable by lowering an
96 * interface block array to an array variable. For example if the
97 * original source code was:
98 *
99 * out Blk { vec4 bar } foo[3];
100 *
101 * Then the variable is now:
102 *
103 * out vec4 bar[3];
104 *
105 * We need to visit each array element using the names constructed like
106 * so:
107 *
108 * Blk[0].bar
109 * Blk[1].bar
110 * Blk[2].bar
111 */
112 assert(t->is_array());
113 const glsl_type *ifc_type = var->get_interface_type();
114 char *name = ralloc_strdup(NULL, ifc_type->name);
115 size_t name_length = strlen(name);
116 for (unsigned i = 0; i < t->length; i++) {
117 size_t new_length = name_length;
118 ralloc_asprintf_rewrite_tail(&name, &new_length, "[%u].%s", i,
119 var->name);
120 /* Note: row_major is only meaningful for uniform blocks, and
121 * lowering is only applied to non-uniform interface blocks, so we
122 * can safely pass false for row_major.
123 */
124 recursion(var->type, &name, new_length, row_major, NULL, packing,
125 false, record_array_count);
126 }
127 ralloc_free(name);
128 } else if (var->data.from_named_ifc_block_nonarray) {
129 /* lower_named_interface_blocks created this variable by lowering a
130 * named interface block (non-array) to an ordinary variable. For
131 * example if the original source code was:
132 *
133 * out Blk { vec4 bar } foo;
134 *
135 * Then the variable is now:
136 *
137 * out vec4 bar;
138 *
139 * We need to visit this variable using the name:
140 *
141 * Blk.bar
142 */
143 const glsl_type *ifc_type = var->get_interface_type();
144 char *name = ralloc_asprintf(NULL, "%s.%s", ifc_type->name, var->name);
145 /* Note: row_major is only meaningful for uniform blocks, and lowering
146 * is only applied to non-uniform interface blocks, so we can safely
147 * pass false for row_major.
148 */
149 recursion(var->type, &name, strlen(name), row_major, NULL, packing,
150 false, record_array_count);
151 ralloc_free(name);
152 } else if (t_without_array->is_record() ||
153 (t->is_array() && t->fields.array->is_array())) {
154 char *name = ralloc_strdup(NULL, var->name);
155 recursion(var->type, &name, strlen(name), row_major, NULL, packing,
156 false, record_array_count);
157 ralloc_free(name);
158 } else if (t_without_array->is_interface()) {
159 char *name = ralloc_strdup(NULL, t_without_array->name);
160 recursion(var->type, &name, strlen(name), row_major, NULL, packing,
161 false, record_array_count);
162 ralloc_free(name);
163 } else {
164 this->set_record_array_count(record_array_count);
165 this->visit_field(t, var->name, row_major, NULL, packing, false);
166 }
167 }
168
169 void
170 program_resource_visitor::recursion(const glsl_type *t, char **name,
171 size_t name_length, bool row_major,
172 const glsl_type *record_type,
173 const unsigned packing,
174 bool last_field,
175 unsigned record_array_count)
176 {
177 /* Records need to have each field processed individually.
178 *
179 * Arrays of records need to have each array element processed
180 * individually, then each field of the resulting array elements processed
181 * individually.
182 */
183 if (t->is_record() || t->is_interface()) {
184 if (record_type == NULL && t->is_record())
185 record_type = t;
186
187 if (t->is_record())
188 this->enter_record(t, *name, row_major, packing);
189
190 for (unsigned i = 0; i < t->length; i++) {
191 const char *field = t->fields.structure[i].name;
192 size_t new_length = name_length;
193
194 if (t->fields.structure[i].type->is_record())
195 this->visit_field(&t->fields.structure[i]);
196
197 /* Append '.field' to the current variable name. */
198 if (name_length == 0) {
199 ralloc_asprintf_rewrite_tail(name, &new_length, "%s", field);
200 } else {
201 ralloc_asprintf_rewrite_tail(name, &new_length, ".%s", field);
202 }
203
204 /* The layout of structures at the top level of the block is set
205 * during parsing. For matrices contained in multiple levels of
206 * structures in the block, the inner structures have no layout.
207 * These cases must potentially inherit the layout from the outer
208 * levels.
209 */
210 bool field_row_major = row_major;
211 const enum glsl_matrix_layout matrix_layout =
212 glsl_matrix_layout(t->fields.structure[i].matrix_layout);
213 if (matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR) {
214 field_row_major = true;
215 } else if (matrix_layout == GLSL_MATRIX_LAYOUT_COLUMN_MAJOR) {
216 field_row_major = false;
217 }
218
219 recursion(t->fields.structure[i].type, name, new_length,
220 field_row_major,
221 record_type,
222 packing,
223 (i + 1) == t->length, record_array_count);
224
225 /* Only the first leaf-field of the record gets called with the
226 * record type pointer.
227 */
228 record_type = NULL;
229 }
230
231 if (t->is_record()) {
232 (*name)[name_length] = '\0';
233 this->leave_record(t, *name, row_major, packing);
234 }
235 } else if (t->without_array()->is_record() ||
236 t->without_array()->is_interface() ||
237 (t->is_array() && t->fields.array->is_array())) {
238 if (record_type == NULL && t->fields.array->is_record())
239 record_type = t->fields.array;
240
241 unsigned length = t->length;
242 /* Shader storage block unsized arrays: add subscript [0] to variable
243 * names */
244 if (t->is_unsized_array())
245 length = 1;
246
247 record_array_count *= length;
248
249 for (unsigned i = 0; i < length; i++) {
250 size_t new_length = name_length;
251
252 /* Append the subscript to the current variable name */
253 ralloc_asprintf_rewrite_tail(name, &new_length, "[%u]", i);
254
255 recursion(t->fields.array, name, new_length, row_major,
256 record_type,
257 packing,
258 (i + 1) == t->length, record_array_count);
259
260 /* Only the first leaf-field of the record gets called with the
261 * record type pointer.
262 */
263 record_type = NULL;
264 }
265 } else {
266 this->set_record_array_count(record_array_count);
267 this->visit_field(t, *name, row_major, record_type, packing, last_field);
268 }
269 }
270
271 void
272 program_resource_visitor::visit_field(const glsl_type *type, const char *name,
273 bool row_major,
274 const glsl_type *,
275 const unsigned,
276 bool /* last_field */)
277 {
278 visit_field(type, name, row_major);
279 }
280
281 void
282 program_resource_visitor::visit_field(const glsl_struct_field *field)
283 {
284 (void) field;
285 /* empty */
286 }
287
288 void
289 program_resource_visitor::enter_record(const glsl_type *, const char *, bool,
290 const unsigned)
291 {
292 }
293
294 void
295 program_resource_visitor::leave_record(const glsl_type *, const char *, bool,
296 const unsigned)
297 {
298 }
299
300 void
301 program_resource_visitor::set_record_array_count(unsigned)
302 {
303 }
304
305 namespace {
306
307 /**
308 * Class to help calculate the storage requirements for a set of uniforms
309 *
310 * As uniforms are added to the active set the number of active uniforms and
311 * the storage requirements for those uniforms are accumulated. The active
312 * uniforms are added to the hash table supplied to the constructor.
313 *
314 * If the same uniform is added multiple times (i.e., once for each shader
315 * target), it will only be accounted once.
316 */
317 class count_uniform_size : public program_resource_visitor {
318 public:
319 count_uniform_size(struct string_to_uint_map *map,
320 struct string_to_uint_map *hidden_map)
321 : num_active_uniforms(0), num_hidden_uniforms(0), num_values(0),
322 num_shader_samplers(0), num_shader_images(0),
323 num_shader_uniform_components(0), num_shader_subroutines(0),
324 is_ubo_var(false), is_shader_storage(false), map(map),
325 hidden_map(hidden_map)
326 {
327 /* empty */
328 }
329
330 void start_shader()
331 {
332 this->num_shader_samplers = 0;
333 this->num_shader_images = 0;
334 this->num_shader_uniform_components = 0;
335 this->num_shader_subroutines = 0;
336 }
337
338 void process(ir_variable *var)
339 {
340 this->current_var = var;
341 this->is_ubo_var = var->is_in_buffer_block();
342 this->is_shader_storage = var->is_in_shader_storage_block();
343 if (var->is_interface_instance())
344 program_resource_visitor::process(var->get_interface_type(),
345 var->get_interface_type()->name);
346 else
347 program_resource_visitor::process(var);
348 }
349
350 /**
351 * Total number of active uniforms counted
352 */
353 unsigned num_active_uniforms;
354
355 unsigned num_hidden_uniforms;
356
357 /**
358 * Number of data values required to back the storage for the active uniforms
359 */
360 unsigned num_values;
361
362 /**
363 * Number of samplers used
364 */
365 unsigned num_shader_samplers;
366
367 /**
368 * Number of images used
369 */
370 unsigned num_shader_images;
371
372 /**
373 * Number of uniforms used in the current shader
374 */
375 unsigned num_shader_uniform_components;
376
377 /**
378 * Number of subroutine uniforms used
379 */
380 unsigned num_shader_subroutines;
381
382 bool is_ubo_var;
383 bool is_shader_storage;
384
385 struct string_to_uint_map *map;
386
387 private:
388 virtual void visit_field(const glsl_type *type, const char *name,
389 bool row_major)
390 {
391 assert(!type->without_array()->is_record());
392 assert(!type->without_array()->is_interface());
393 assert(!(type->is_array() && type->fields.array->is_array()));
394
395 (void) row_major;
396
397 /* Count the number of samplers regardless of whether the uniform is
398 * already in the hash table. The hash table prevents adding the same
399 * uniform for multiple shader targets, but in this case we want to
400 * count it for each shader target.
401 */
402 const unsigned values = values_for_type(type);
403 if (type->contains_subroutine()) {
404 this->num_shader_subroutines += values;
405 } else if (type->contains_sampler()) {
406 this->num_shader_samplers += values;
407 } else if (type->contains_image()) {
408 this->num_shader_images += values;
409
410 /* As drivers are likely to represent image uniforms as
411 * scalar indices, count them against the limit of uniform
412 * components in the default block. The spec allows image
413 * uniforms to use up no more than one scalar slot.
414 */
415 if(!is_shader_storage)
416 this->num_shader_uniform_components += values;
417 } else {
418 /* Accumulate the total number of uniform slots used by this shader.
419 * Note that samplers do not count against this limit because they
420 * don't use any storage on current hardware.
421 */
422 if (!is_ubo_var && !is_shader_storage)
423 this->num_shader_uniform_components += values;
424 }
425
426 /* If the uniform is already in the map, there's nothing more to do.
427 */
428 unsigned id;
429 if (this->map->get(id, name))
430 return;
431
432 if (this->current_var->data.how_declared == ir_var_hidden) {
433 this->hidden_map->put(this->num_hidden_uniforms, name);
434 this->num_hidden_uniforms++;
435 } else {
436 this->map->put(this->num_active_uniforms-this->num_hidden_uniforms,
437 name);
438 }
439
440 /* Each leaf uniform occupies one entry in the list of active
441 * uniforms.
442 */
443 this->num_active_uniforms++;
444 this->num_values += values;
445 }
446
447 struct string_to_uint_map *hidden_map;
448
449 /**
450 * Current variable being processed.
451 */
452 ir_variable *current_var;
453 };
454
455 } /* anonymous namespace */
456
457 /**
458 * Class to help parcel out pieces of backing storage to uniforms
459 *
460 * Each uniform processed has some range of the \c gl_constant_value
461 * structures associated with it. The association is done by finding
462 * the uniform in the \c string_to_uint_map and using the value from
463 * the map to connect that slot in the \c gl_uniform_storage table
464 * with the next available slot in the \c gl_constant_value array.
465 *
466 * \warning
467 * This class assumes that every uniform that will be processed is
468 * already in the \c string_to_uint_map. In addition, it assumes that
469 * the \c gl_uniform_storage and \c gl_constant_value arrays are "big
470 * enough."
471 */
472 class parcel_out_uniform_storage : public program_resource_visitor {
473 public:
474 parcel_out_uniform_storage(struct gl_shader_program *prog,
475 struct string_to_uint_map *map,
476 struct gl_uniform_storage *uniforms,
477 union gl_constant_value *values)
478 : prog(prog), map(map), uniforms(uniforms), values(values)
479 {
480 }
481
482 void start_shader(gl_shader_stage shader_type)
483 {
484 assert(shader_type < MESA_SHADER_STAGES);
485 this->shader_type = shader_type;
486
487 this->shader_samplers_used = 0;
488 this->shader_shadow_samplers = 0;
489 this->next_sampler = 0;
490 this->next_image = 0;
491 this->next_subroutine = 0;
492 this->record_array_count = 1;
493 memset(this->targets, 0, sizeof(this->targets));
494 }
495
496 void set_and_process(ir_variable *var)
497 {
498 current_var = var;
499 field_counter = 0;
500 this->record_next_sampler = new string_to_uint_map;
501
502 ubo_block_index = -1;
503 if (var->is_in_buffer_block()) {
504 if (var->is_interface_instance() && var->type->is_array()) {
505 unsigned l = strlen(var->get_interface_type()->name);
506
507 for (unsigned i = 0; i < prog->NumBufferInterfaceBlocks; i++) {
508 if (strncmp(var->get_interface_type()->name,
509 prog->BufferInterfaceBlocks[i].Name,
510 l) == 0
511 && prog->BufferInterfaceBlocks[i].Name[l] == '[') {
512 ubo_block_index = i;
513 break;
514 }
515 }
516 } else {
517 for (unsigned i = 0; i < prog->NumBufferInterfaceBlocks; i++) {
518 if (strcmp(var->get_interface_type()->name,
519 prog->BufferInterfaceBlocks[i].Name) == 0) {
520 ubo_block_index = i;
521 break;
522 }
523 }
524 }
525 assert(ubo_block_index != -1);
526
527 /* Uniform blocks that were specified with an instance name must be
528 * handled a little bit differently. The name of the variable is the
529 * name used to reference the uniform block instead of being the name
530 * of a variable within the block. Therefore, searching for the name
531 * within the block will fail.
532 */
533 if (var->is_interface_instance()) {
534 ubo_byte_offset = 0;
535 process(var->get_interface_type(),
536 var->get_interface_type()->name);
537 } else {
538 const struct gl_uniform_block *const block =
539 &prog->BufferInterfaceBlocks[ubo_block_index];
540
541 assert(var->data.location != -1);
542
543 const struct gl_uniform_buffer_variable *const ubo_var =
544 &block->Uniforms[var->data.location];
545
546 ubo_byte_offset = ubo_var->Offset;
547 process(var);
548 }
549 } else {
550 /* Store any explicit location and reset data location so we can
551 * reuse this variable for storing the uniform slot number.
552 */
553 this->explicit_location = current_var->data.location;
554 current_var->data.location = -1;
555
556 process(var);
557 }
558 delete this->record_next_sampler;
559 }
560
561 int ubo_block_index;
562 int ubo_byte_offset;
563 gl_shader_stage shader_type;
564
565 private:
566 void handle_samplers(const glsl_type *base_type,
567 struct gl_uniform_storage *uniform, const char *name)
568 {
569 if (base_type->is_sampler()) {
570 uniform->opaque[shader_type].active = true;
571
572 /* Handle multiple samplers inside struct arrays */
573 if (this->record_array_count > 1) {
574 unsigned inner_array_size = MAX2(1, uniform->array_elements);
575 char *name_copy = ralloc_strdup(NULL, name);
576
577 /* Remove all array subscripts from the sampler name */
578 char *str_start;
579 const char *str_end;
580 while((str_start = strchr(name_copy, '[')) &&
581 (str_end = strchr(name_copy, ']'))) {
582 memmove(str_start, str_end + 1, 1 + strlen(str_end));
583 }
584
585 unsigned index = 0;
586 if (this->record_next_sampler->get(index, name_copy)) {
587 /* In this case, we've already seen this uniform so we just use
588 * the next sampler index recorded the last time we visited.
589 */
590 uniform->opaque[shader_type].index = index;
591 index = inner_array_size + uniform->opaque[shader_type].index;
592 this->record_next_sampler->put(index, name_copy);
593
594 ralloc_free(name_copy);
595 /* Return as everything else has already been initialised in a
596 * previous pass.
597 */
598 return;
599 } else {
600 /* We've never seen this uniform before so we need to allocate
601 * enough indices to store it.
602 *
603 * Nested struct arrays behave like arrays of arrays so we need
604 * to increase the index by the total number of elements of the
605 * sampler in case there is more than one sampler inside the
606 * structs. This allows the offset to be easily calculated for
607 * indirect indexing.
608 */
609 uniform->opaque[shader_type].index = this->next_sampler;
610 this->next_sampler +=
611 inner_array_size * this->record_array_count;
612
613 /* Store the next index for future passes over the struct array
614 */
615 index = uniform->opaque[shader_type].index + inner_array_size;
616 this->record_next_sampler->put(index, name_copy);
617 ralloc_free(name_copy);
618 }
619 } else {
620 /* Increment the sampler by 1 for non-arrays and by the number of
621 * array elements for arrays.
622 */
623 uniform->opaque[shader_type].index = this->next_sampler;
624 this->next_sampler += MAX2(1, uniform->array_elements);
625 }
626
627 const gl_texture_index target = base_type->sampler_index();
628 const unsigned shadow = base_type->sampler_shadow;
629 for (unsigned i = uniform->opaque[shader_type].index;
630 i < MIN2(this->next_sampler, MAX_SAMPLERS);
631 i++) {
632 this->targets[i] = target;
633 this->shader_samplers_used |= 1U << i;
634 this->shader_shadow_samplers |= shadow << i;
635 }
636 }
637 }
638
639 void handle_images(const glsl_type *base_type,
640 struct gl_uniform_storage *uniform)
641 {
642 if (base_type->is_image()) {
643 uniform->opaque[shader_type].index = this->next_image;
644 uniform->opaque[shader_type].active = true;
645
646 /* Set image access qualifiers */
647 const GLenum access =
648 (current_var->data.image_read_only ? GL_READ_ONLY :
649 current_var->data.image_write_only ? GL_WRITE_ONLY :
650 GL_READ_WRITE);
651
652 const unsigned first = this->next_image;
653
654 /* Increment the image index by 1 for non-arrays and by the
655 * number of array elements for arrays.
656 */
657 this->next_image += MAX2(1, uniform->array_elements);
658
659 for (unsigned i = first; i < MIN2(next_image, MAX_IMAGE_UNIFORMS); i++)
660 prog->_LinkedShaders[shader_type]->ImageAccess[i] = access;
661 }
662 }
663
664 void handle_subroutines(const glsl_type *base_type,
665 struct gl_uniform_storage *uniform)
666 {
667 if (base_type->is_subroutine()) {
668 uniform->opaque[shader_type].index = this->next_subroutine;
669 uniform->opaque[shader_type].active = true;
670
671 /* Increment the subroutine index by 1 for non-arrays and by the
672 * number of array elements for arrays.
673 */
674 this->next_subroutine += MAX2(1, uniform->array_elements);
675
676 }
677 }
678
679 virtual void set_record_array_count(unsigned record_array_count)
680 {
681 this->record_array_count = record_array_count;
682 }
683
684 virtual void visit_field(const glsl_type *type, const char *name,
685 bool row_major)
686 {
687 (void) type;
688 (void) name;
689 (void) row_major;
690 assert(!"Should not get here.");
691 }
692
693 virtual void enter_record(const glsl_type *type, const char *,
694 bool row_major, const unsigned packing) {
695 assert(type->is_record());
696 if (this->ubo_block_index == -1)
697 return;
698 if (packing == GLSL_INTERFACE_PACKING_STD430)
699 this->ubo_byte_offset = glsl_align(
700 this->ubo_byte_offset, type->std430_base_alignment(row_major));
701 else
702 this->ubo_byte_offset = glsl_align(
703 this->ubo_byte_offset, type->std140_base_alignment(row_major));
704 }
705
706 virtual void leave_record(const glsl_type *type, const char *,
707 bool row_major, const unsigned packing) {
708 assert(type->is_record());
709 if (this->ubo_block_index == -1)
710 return;
711 if (packing == GLSL_INTERFACE_PACKING_STD430)
712 this->ubo_byte_offset = glsl_align(
713 this->ubo_byte_offset, type->std430_base_alignment(row_major));
714 else
715 this->ubo_byte_offset = glsl_align(
716 this->ubo_byte_offset, type->std140_base_alignment(row_major));
717 }
718
719 virtual void visit_field(const glsl_type *type, const char *name,
720 bool row_major, const glsl_type *record_type,
721 const unsigned packing,
722 bool /* last_field */)
723 {
724 assert(!type->without_array()->is_record());
725 assert(!type->without_array()->is_interface());
726 assert(!(type->is_array() && type->fields.array->is_array()));
727
728 unsigned id;
729 bool found = this->map->get(id, name);
730 assert(found);
731
732 if (!found)
733 return;
734
735 const glsl_type *base_type;
736 if (type->is_array()) {
737 this->uniforms[id].array_elements = type->length;
738 base_type = type->fields.array;
739 } else {
740 this->uniforms[id].array_elements = 0;
741 base_type = type;
742 }
743
744 /* Initialise opaque data */
745 this->uniforms[id].opaque[shader_type].index = ~0;
746 this->uniforms[id].opaque[shader_type].active = false;
747
748 /* This assigns uniform indices to sampler and image uniforms. */
749 handle_samplers(base_type, &this->uniforms[id], name);
750 handle_images(base_type, &this->uniforms[id]);
751 handle_subroutines(base_type, &this->uniforms[id]);
752
753 /* For array of arrays or struct arrays the base location may have
754 * already been set so don't set it again.
755 */
756 if (ubo_block_index == -1 && current_var->data.location == -1) {
757 current_var->data.location = id;
758 }
759
760 /* If there is already storage associated with this uniform or if the
761 * uniform is set as builtin, it means that it was set while processing
762 * an earlier shader stage. For example, we may be processing the
763 * uniform in the fragment shader, but the uniform was already processed
764 * in the vertex shader.
765 */
766 if (this->uniforms[id].storage != NULL || this->uniforms[id].builtin) {
767 return;
768 }
769
770 /* Assign explicit locations. */
771 if (current_var->data.explicit_location) {
772 /* Set sequential locations for struct fields. */
773 if (current_var->type->without_array()->is_record() ||
774 current_var->type->is_array_of_arrays()) {
775 const unsigned entries = MAX2(1, this->uniforms[id].array_elements);
776 this->uniforms[id].remap_location =
777 this->explicit_location + field_counter;
778 field_counter += entries;
779 } else {
780 this->uniforms[id].remap_location = this->explicit_location;
781 }
782 } else {
783 /* Initialize to to indicate that no location is set */
784 this->uniforms[id].remap_location = UNMAPPED_UNIFORM_LOC;
785 }
786
787 this->uniforms[id].name = ralloc_strdup(this->uniforms, name);
788 this->uniforms[id].type = base_type;
789 this->uniforms[id].initialized = 0;
790 this->uniforms[id].num_driver_storage = 0;
791 this->uniforms[id].driver_storage = NULL;
792 this->uniforms[id].atomic_buffer_index = -1;
793 this->uniforms[id].hidden =
794 current_var->data.how_declared == ir_var_hidden;
795 this->uniforms[id].builtin = is_gl_identifier(name);
796
797 /* Do not assign storage if the uniform is builtin */
798 if (!this->uniforms[id].builtin)
799 this->uniforms[id].storage = this->values;
800
801 this->uniforms[id].is_shader_storage =
802 current_var->is_in_shader_storage_block();
803
804 if (this->ubo_block_index != -1) {
805 this->uniforms[id].block_index = this->ubo_block_index;
806
807 unsigned alignment = type->std140_base_alignment(row_major);
808 if (packing == GLSL_INTERFACE_PACKING_STD430)
809 alignment = type->std430_base_alignment(row_major);
810 this->ubo_byte_offset = glsl_align(this->ubo_byte_offset, alignment);
811 this->uniforms[id].offset = this->ubo_byte_offset;
812 if (packing == GLSL_INTERFACE_PACKING_STD430)
813 this->ubo_byte_offset += type->std430_size(row_major);
814 else
815 this->ubo_byte_offset += type->std140_size(row_major);
816
817 if (type->is_array()) {
818 if (packing == GLSL_INTERFACE_PACKING_STD430)
819 this->uniforms[id].array_stride =
820 type->without_array()->std430_array_stride(row_major);
821 else
822 this->uniforms[id].array_stride =
823 glsl_align(type->without_array()->std140_size(row_major),
824 16);
825 } else {
826 this->uniforms[id].array_stride = 0;
827 }
828
829 if (type->without_array()->is_matrix()) {
830 const glsl_type *matrix = type->without_array();
831 const unsigned N = matrix->base_type == GLSL_TYPE_DOUBLE ? 8 : 4;
832 const unsigned items =
833 row_major ? matrix->matrix_columns : matrix->vector_elements;
834
835 assert(items <= 4);
836 if (packing == GLSL_INTERFACE_PACKING_STD430)
837 this->uniforms[id].matrix_stride = items < 3 ? items * N :
838 glsl_align(items * N, 16);
839 else
840 this->uniforms[id].matrix_stride = glsl_align(items * N, 16);
841 this->uniforms[id].row_major = row_major;
842 } else {
843 this->uniforms[id].matrix_stride = 0;
844 this->uniforms[id].row_major = false;
845 }
846 } else {
847 this->uniforms[id].block_index = -1;
848 this->uniforms[id].offset = -1;
849 this->uniforms[id].array_stride = -1;
850 this->uniforms[id].matrix_stride = -1;
851 this->uniforms[id].row_major = false;
852 }
853
854 this->values += values_for_type(type);
855 }
856
857 /**
858 * Current program being processed.
859 */
860 struct gl_shader_program *prog;
861
862 struct string_to_uint_map *map;
863
864 struct gl_uniform_storage *uniforms;
865 unsigned next_sampler;
866 unsigned next_image;
867 unsigned next_subroutine;
868
869 /**
870 * Field counter is used to take care that uniform structures
871 * with explicit locations get sequential locations.
872 */
873 unsigned field_counter;
874
875 /**
876 * Current variable being processed.
877 */
878 ir_variable *current_var;
879
880 /* Used to store the explicit location from current_var so that we can
881 * reuse the location field for storing the uniform slot id.
882 */
883 int explicit_location;
884
885 /* Stores total struct array elements including nested structs */
886 unsigned record_array_count;
887
888 /* Map for temporarily storing next sampler index when handling samplers in
889 * struct arrays.
890 */
891 struct string_to_uint_map *record_next_sampler;
892
893 public:
894 union gl_constant_value *values;
895
896 gl_texture_index targets[MAX_SAMPLERS];
897
898 /**
899 * Mask of samplers used by the current shader stage.
900 */
901 unsigned shader_samplers_used;
902
903 /**
904 * Mask of samplers used by the current shader stage for shadows.
905 */
906 unsigned shader_shadow_samplers;
907 };
908
909 /**
910 * Merges a uniform block into an array of uniform blocks that may or
911 * may not already contain a copy of it.
912 *
913 * Returns the index of the new block in the array.
914 */
915 int
916 link_cross_validate_uniform_block(void *mem_ctx,
917 struct gl_uniform_block **linked_blocks,
918 unsigned int *num_linked_blocks,
919 struct gl_uniform_block *new_block)
920 {
921 for (unsigned int i = 0; i < *num_linked_blocks; i++) {
922 struct gl_uniform_block *old_block = &(*linked_blocks)[i];
923
924 if (strcmp(old_block->Name, new_block->Name) == 0)
925 return link_uniform_blocks_are_compatible(old_block, new_block)
926 ? i : -1;
927 }
928
929 *linked_blocks = reralloc(mem_ctx, *linked_blocks,
930 struct gl_uniform_block,
931 *num_linked_blocks + 1);
932 int linked_block_index = (*num_linked_blocks)++;
933 struct gl_uniform_block *linked_block = &(*linked_blocks)[linked_block_index];
934
935 memcpy(linked_block, new_block, sizeof(*new_block));
936 linked_block->Uniforms = ralloc_array(*linked_blocks,
937 struct gl_uniform_buffer_variable,
938 linked_block->NumUniforms);
939
940 memcpy(linked_block->Uniforms,
941 new_block->Uniforms,
942 sizeof(*linked_block->Uniforms) * linked_block->NumUniforms);
943
944 for (unsigned int i = 0; i < linked_block->NumUniforms; i++) {
945 struct gl_uniform_buffer_variable *ubo_var =
946 &linked_block->Uniforms[i];
947
948 if (ubo_var->Name == ubo_var->IndexName) {
949 ubo_var->Name = ralloc_strdup(*linked_blocks, ubo_var->Name);
950 ubo_var->IndexName = ubo_var->Name;
951 } else {
952 ubo_var->Name = ralloc_strdup(*linked_blocks, ubo_var->Name);
953 ubo_var->IndexName = ralloc_strdup(*linked_blocks, ubo_var->IndexName);
954 }
955 }
956
957 return linked_block_index;
958 }
959
960 /**
961 * Walks the IR and update the references to uniform blocks in the
962 * ir_variables to point at linked shader's list (previously, they
963 * would point at the uniform block list in one of the pre-linked
964 * shaders).
965 */
966 static void
967 link_update_uniform_buffer_variables(struct gl_shader *shader)
968 {
969 foreach_in_list(ir_instruction, node, shader->ir) {
970 ir_variable *const var = node->as_variable();
971
972 if ((var == NULL) || !var->is_in_buffer_block())
973 continue;
974
975 assert(var->data.mode == ir_var_uniform ||
976 var->data.mode == ir_var_shader_storage);
977
978 if (var->is_interface_instance()) {
979 var->data.location = 0;
980 continue;
981 }
982
983 bool found = false;
984 char sentinel = '\0';
985
986 if (var->type->is_record()) {
987 sentinel = '.';
988 } else if (var->type->is_array() && (var->type->fields.array->is_array()
989 || var->type->without_array()->is_record())) {
990 sentinel = '[';
991 }
992
993 const unsigned l = strlen(var->name);
994 for (unsigned i = 0; i < shader->NumBufferInterfaceBlocks; i++) {
995 for (unsigned j = 0; j < shader->BufferInterfaceBlocks[i].NumUniforms; j++) {
996 if (sentinel) {
997 const char *begin = shader->BufferInterfaceBlocks[i].Uniforms[j].Name;
998 const char *end = strchr(begin, sentinel);
999
1000 if (end == NULL)
1001 continue;
1002
1003 if ((ptrdiff_t) l != (end - begin))
1004 continue;
1005
1006 if (strncmp(var->name, begin, l) == 0) {
1007 found = true;
1008 var->data.location = j;
1009 break;
1010 }
1011 } else if (!strcmp(var->name,
1012 shader->BufferInterfaceBlocks[i].Uniforms[j].Name)) {
1013 found = true;
1014 var->data.location = j;
1015 break;
1016 }
1017 }
1018 if (found)
1019 break;
1020 }
1021 assert(found);
1022 }
1023 }
1024
1025 /**
1026 * Combine the hidden uniform hash map with the uniform hash map so that the
1027 * hidden uniforms will be given indicies at the end of the uniform storage
1028 * array.
1029 */
1030 static void
1031 assign_hidden_uniform_slot_id(const char *name, unsigned hidden_id,
1032 void *closure)
1033 {
1034 count_uniform_size *uniform_size = (count_uniform_size *) closure;
1035 unsigned hidden_uniform_start = uniform_size->num_active_uniforms -
1036 uniform_size->num_hidden_uniforms;
1037
1038 uniform_size->map->put(hidden_uniform_start + hidden_id, name);
1039 }
1040
1041 /**
1042 * Search through the list of empty blocks to find one that fits the current
1043 * uniform.
1044 */
1045 static int
1046 find_empty_block(struct gl_shader_program *prog,
1047 struct gl_uniform_storage *uniform)
1048 {
1049 const unsigned entries = MAX2(1, uniform->array_elements);
1050
1051 foreach_list_typed(struct empty_uniform_block, block, link,
1052 &prog->EmptyUniformLocations) {
1053 /* Found a block with enough slots to fit the uniform */
1054 if (block->slots == entries) {
1055 unsigned start = block->start;
1056 exec_node_remove(&block->link);
1057 ralloc_free(block);
1058
1059 return start;
1060 /* Found a block with more slots than needed. It can still be used. */
1061 } else if (block->slots > entries) {
1062 unsigned start = block->start;
1063 block->start += entries;
1064 block->slots -= entries;
1065
1066 return start;
1067 }
1068 }
1069
1070 return -1;
1071 }
1072
1073 void
1074 link_assign_uniform_locations(struct gl_shader_program *prog,
1075 unsigned int boolean_true,
1076 unsigned int num_explicit_uniform_locs,
1077 unsigned int max_uniform_locs)
1078 {
1079 ralloc_free(prog->UniformStorage);
1080 prog->UniformStorage = NULL;
1081 prog->NumUniformStorage = 0;
1082
1083 if (prog->UniformHash != NULL) {
1084 prog->UniformHash->clear();
1085 } else {
1086 prog->UniformHash = new string_to_uint_map;
1087 }
1088
1089 /* First pass: Count the uniform resources used by the user-defined
1090 * uniforms. While this happens, each active uniform will have an index
1091 * assigned to it.
1092 *
1093 * Note: this is *NOT* the index that is returned to the application by
1094 * glGetUniformLocation.
1095 */
1096 struct string_to_uint_map *hiddenUniforms = new string_to_uint_map;
1097 count_uniform_size uniform_size(prog->UniformHash, hiddenUniforms);
1098 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1099 struct gl_shader *sh = prog->_LinkedShaders[i];
1100
1101 if (sh == NULL)
1102 continue;
1103
1104 /* Uniforms that lack an initializer in the shader code have an initial
1105 * value of zero. This includes sampler uniforms.
1106 *
1107 * Page 24 (page 30 of the PDF) of the GLSL 1.20 spec says:
1108 *
1109 * "The link time initial value is either the value of the variable's
1110 * initializer, if present, or 0 if no initializer is present. Sampler
1111 * types cannot have initializers."
1112 */
1113 memset(sh->SamplerUnits, 0, sizeof(sh->SamplerUnits));
1114 memset(sh->ImageUnits, 0, sizeof(sh->ImageUnits));
1115
1116 link_update_uniform_buffer_variables(sh);
1117
1118 /* Reset various per-shader target counts.
1119 */
1120 uniform_size.start_shader();
1121
1122 foreach_in_list(ir_instruction, node, sh->ir) {
1123 ir_variable *const var = node->as_variable();
1124
1125 if ((var == NULL) || (var->data.mode != ir_var_uniform &&
1126 var->data.mode != ir_var_shader_storage))
1127 continue;
1128
1129 uniform_size.process(var);
1130 }
1131
1132 sh->num_samplers = uniform_size.num_shader_samplers;
1133 sh->NumImages = uniform_size.num_shader_images;
1134 sh->num_uniform_components = uniform_size.num_shader_uniform_components;
1135 sh->num_combined_uniform_components = sh->num_uniform_components;
1136
1137 for (unsigned i = 0; i < sh->NumBufferInterfaceBlocks; i++) {
1138 if (!sh->BufferInterfaceBlocks[i].IsShaderStorage) {
1139 sh->num_combined_uniform_components +=
1140 sh->BufferInterfaceBlocks[i].UniformBufferSize / 4;
1141 }
1142 }
1143 }
1144
1145 const unsigned num_uniforms = uniform_size.num_active_uniforms;
1146 const unsigned num_data_slots = uniform_size.num_values;
1147 const unsigned hidden_uniforms = uniform_size.num_hidden_uniforms;
1148
1149 /* assign hidden uniforms a slot id */
1150 hiddenUniforms->iterate(assign_hidden_uniform_slot_id, &uniform_size);
1151 delete hiddenUniforms;
1152
1153 /* On the outside chance that there were no uniforms, bail out.
1154 */
1155 if (num_uniforms == 0)
1156 return;
1157
1158 struct gl_uniform_storage *uniforms =
1159 rzalloc_array(prog, struct gl_uniform_storage, num_uniforms);
1160 union gl_constant_value *data =
1161 rzalloc_array(uniforms, union gl_constant_value, num_data_slots);
1162 #ifndef NDEBUG
1163 union gl_constant_value *data_end = &data[num_data_slots];
1164 #endif
1165
1166 parcel_out_uniform_storage parcel(prog, prog->UniformHash, uniforms, data);
1167
1168 unsigned total_entries = num_explicit_uniform_locs;
1169 unsigned empty_locs = prog->NumUniformRemapTable - num_explicit_uniform_locs;
1170
1171 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
1172 if (prog->_LinkedShaders[i] == NULL)
1173 continue;
1174
1175 parcel.start_shader((gl_shader_stage)i);
1176
1177 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
1178 ir_variable *const var = node->as_variable();
1179
1180 if ((var == NULL) || (var->data.mode != ir_var_uniform &&
1181 var->data.mode != ir_var_shader_storage))
1182 continue;
1183
1184 parcel.set_and_process(var);
1185 }
1186
1187 prog->_LinkedShaders[i]->active_samplers = parcel.shader_samplers_used;
1188 prog->_LinkedShaders[i]->shadow_samplers = parcel.shader_shadow_samplers;
1189
1190 STATIC_ASSERT(sizeof(prog->_LinkedShaders[i]->SamplerTargets) ==
1191 sizeof(parcel.targets));
1192 memcpy(prog->_LinkedShaders[i]->SamplerTargets, parcel.targets,
1193 sizeof(prog->_LinkedShaders[i]->SamplerTargets));
1194 }
1195
1196 /* Reserve all the explicit locations of the active uniforms. */
1197 for (unsigned i = 0; i < num_uniforms; i++) {
1198 if (uniforms[i].type->is_subroutine() ||
1199 uniforms[i].is_shader_storage)
1200 continue;
1201
1202 if (uniforms[i].remap_location != UNMAPPED_UNIFORM_LOC) {
1203 /* How many new entries for this uniform? */
1204 const unsigned entries = MAX2(1, uniforms[i].array_elements);
1205
1206 /* Set remap table entries point to correct gl_uniform_storage. */
1207 for (unsigned j = 0; j < entries; j++) {
1208 unsigned element_loc = uniforms[i].remap_location + j;
1209 assert(prog->UniformRemapTable[element_loc] ==
1210 INACTIVE_UNIFORM_EXPLICIT_LOCATION);
1211 prog->UniformRemapTable[element_loc] = &uniforms[i];
1212 }
1213 }
1214 }
1215
1216 /* Reserve locations for rest of the uniforms. */
1217 for (unsigned i = 0; i < num_uniforms; i++) {
1218
1219 if (uniforms[i].type->is_subroutine() ||
1220 uniforms[i].is_shader_storage)
1221 continue;
1222
1223 /* Built-in uniforms should not get any location. */
1224 if (uniforms[i].builtin)
1225 continue;
1226
1227 /* Explicit ones have been set already. */
1228 if (uniforms[i].remap_location != UNMAPPED_UNIFORM_LOC)
1229 continue;
1230
1231 /* how many new entries for this uniform? */
1232 const unsigned entries = MAX2(1, uniforms[i].array_elements);
1233
1234 /* Find UniformRemapTable for empty blocks where we can fit this uniform. */
1235 int chosen_location = -1;
1236
1237 if (empty_locs)
1238 chosen_location = find_empty_block(prog, &uniforms[i]);
1239
1240 /* Add new entries to the total amount of entries. */
1241 total_entries += entries;
1242
1243 if (chosen_location != -1) {
1244 empty_locs -= entries;
1245 } else {
1246 chosen_location = prog->NumUniformRemapTable;
1247
1248 /* resize remap table to fit new entries */
1249 prog->UniformRemapTable =
1250 reralloc(prog,
1251 prog->UniformRemapTable,
1252 gl_uniform_storage *,
1253 prog->NumUniformRemapTable + entries);
1254 prog->NumUniformRemapTable += entries;
1255 }
1256
1257 /* set pointers for this uniform */
1258 for (unsigned j = 0; j < entries; j++)
1259 prog->UniformRemapTable[chosen_location + j] = &uniforms[i];
1260
1261 /* set the base location in remap table for the uniform */
1262 uniforms[i].remap_location = chosen_location;
1263 }
1264
1265 /* Verify that total amount of entries for explicit and implicit locations
1266 * is less than MAX_UNIFORM_LOCATIONS.
1267 */
1268
1269 if (total_entries > max_uniform_locs) {
1270 linker_error(prog, "count of uniform locations > MAX_UNIFORM_LOCATIONS"
1271 "(%u > %u)", total_entries, max_uniform_locs);
1272 }
1273
1274 /* Reserve all the explicit locations of the active subroutine uniforms. */
1275 for (unsigned i = 0; i < num_uniforms; i++) {
1276 if (!uniforms[i].type->is_subroutine())
1277 continue;
1278
1279 if (uniforms[i].remap_location == UNMAPPED_UNIFORM_LOC)
1280 continue;
1281
1282 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
1283 struct gl_shader *sh = prog->_LinkedShaders[j];
1284 if (!sh)
1285 continue;
1286
1287 if (!uniforms[i].opaque[j].active)
1288 continue;
1289
1290 /* How many new entries for this uniform? */
1291 const unsigned entries = MAX2(1, uniforms[i].array_elements);
1292
1293 /* Set remap table entries point to correct gl_uniform_storage. */
1294 for (unsigned k = 0; k < entries; k++) {
1295 unsigned element_loc = uniforms[i].remap_location + k;
1296 assert(sh->SubroutineUniformRemapTable[element_loc] ==
1297 INACTIVE_UNIFORM_EXPLICIT_LOCATION);
1298 sh->SubroutineUniformRemapTable[element_loc] = &uniforms[i];
1299 }
1300 }
1301 }
1302
1303 /* reserve subroutine locations */
1304 for (unsigned i = 0; i < num_uniforms; i++) {
1305
1306 if (!uniforms[i].type->is_subroutine())
1307 continue;
1308 const unsigned entries = MAX2(1, uniforms[i].array_elements);
1309
1310 if (uniforms[i].remap_location != UNMAPPED_UNIFORM_LOC)
1311 continue;
1312 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
1313 struct gl_shader *sh = prog->_LinkedShaders[j];
1314 if (!sh)
1315 continue;
1316
1317 if (!uniforms[i].opaque[j].active)
1318 continue;
1319
1320 sh->SubroutineUniformRemapTable =
1321 reralloc(sh,
1322 sh->SubroutineUniformRemapTable,
1323 gl_uniform_storage *,
1324 sh->NumSubroutineUniformRemapTable + entries);
1325
1326 for (unsigned k = 0; k < entries; k++)
1327 sh->SubroutineUniformRemapTable[sh->NumSubroutineUniformRemapTable + k] = &uniforms[i];
1328 uniforms[i].remap_location = sh->NumSubroutineUniformRemapTable;
1329 sh->NumSubroutineUniformRemapTable += entries;
1330 }
1331 }
1332
1333 #ifndef NDEBUG
1334 for (unsigned i = 0; i < num_uniforms; i++) {
1335 assert(uniforms[i].storage != NULL || uniforms[i].builtin);
1336 }
1337
1338 assert(parcel.values == data_end);
1339 #endif
1340
1341 prog->NumUniformStorage = num_uniforms;
1342 prog->NumHiddenUniforms = hidden_uniforms;
1343 prog->UniformStorage = uniforms;
1344
1345 link_set_uniform_initializers(prog, boolean_true);
1346
1347 return;
1348 }