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