dddac43c316aab9312f9f0d58a95e60daa7ce566
[mesa.git] / src / 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
31 /**
32 * \file link_uniforms.cpp
33 * Assign locations for GLSL uniforms.
34 *
35 * \author Ian Romanick <ian.d.romanick@intel.com>
36 */
37
38 /**
39 * Count the backing storage requirements for a type
40 */
41 static unsigned
42 values_for_type(const glsl_type *type)
43 {
44 if (type->is_sampler()) {
45 return 1;
46 } else if (type->is_array() && type->fields.array->is_sampler()) {
47 return type->array_size();
48 } else {
49 return type->component_slots();
50 }
51 }
52
53 void
54 uniform_field_visitor::process(ir_variable *var)
55 {
56 const glsl_type *t = var->type;
57
58 /* Only strdup the name if we actually will need to modify it. */
59 if (t->is_record() || (t->is_array() && t->fields.array->is_record())) {
60 char *name = ralloc_strdup(NULL, var->name);
61 recursion(var->type, &name, strlen(name));
62 ralloc_free(name);
63 } else {
64 this->visit_field(t, var->name);
65 }
66 }
67
68 void
69 uniform_field_visitor::recursion(const glsl_type *t, char **name,
70 size_t name_length)
71 {
72 /* Records need to have each field processed individually.
73 *
74 * Arrays of records need to have each array element processed
75 * individually, then each field of the resulting array elements processed
76 * individually.
77 */
78 if (t->is_record()) {
79 for (unsigned i = 0; i < t->length; i++) {
80 const char *field = t->fields.structure[i].name;
81 size_t new_length = name_length;
82
83 /* Append '.field' to the current uniform name. */
84 ralloc_asprintf_rewrite_tail(name, &new_length, ".%s", field);
85
86 recursion(t->fields.structure[i].type, name, new_length);
87 }
88 } else if (t->is_array() && t->fields.array->is_record()) {
89 for (unsigned i = 0; i < t->length; i++) {
90 size_t new_length = name_length;
91
92 /* Append the subscript to the current uniform name */
93 ralloc_asprintf_rewrite_tail(name, &new_length, "[%u]", i);
94
95 recursion(t->fields.array, name, new_length);
96 }
97 } else {
98 this->visit_field(t, *name);
99 }
100 }
101
102 /**
103 * Class to help calculate the storage requirements for a set of uniforms
104 *
105 * As uniforms are added to the active set the number of active uniforms and
106 * the storage requirements for those uniforms are accumulated. The active
107 * uniforms are added the the hash table supplied to the constructor.
108 *
109 * If the same uniform is added multiple times (i.e., once for each shader
110 * target), it will only be accounted once.
111 */
112 class count_uniform_size : public uniform_field_visitor {
113 public:
114 count_uniform_size(struct string_to_uint_map *map)
115 : num_active_uniforms(0), num_values(0), num_shader_samplers(0),
116 num_shader_uniform_components(0), map(map)
117 {
118 /* empty */
119 }
120
121 void start_shader()
122 {
123 this->num_shader_samplers = 0;
124 this->num_shader_uniform_components = 0;
125 }
126
127 /**
128 * Total number of active uniforms counted
129 */
130 unsigned num_active_uniforms;
131
132 /**
133 * Number of data values required to back the storage for the active uniforms
134 */
135 unsigned num_values;
136
137 /**
138 * Number of samplers used
139 */
140 unsigned num_shader_samplers;
141
142 /**
143 * Number of uniforms used in the current shader
144 */
145 unsigned num_shader_uniform_components;
146
147 private:
148 virtual void visit_field(const glsl_type *type, const char *name)
149 {
150 assert(!type->is_record());
151 assert(!(type->is_array() && type->fields.array->is_record()));
152
153 /* Count the number of samplers regardless of whether the uniform is
154 * already in the hash table. The hash table prevents adding the same
155 * uniform for multiple shader targets, but in this case we want to
156 * count it for each shader target.
157 */
158 const unsigned values = values_for_type(type);
159 if (type->contains_sampler()) {
160 this->num_shader_samplers +=
161 type->is_array() ? type->array_size() : 1;
162 } else {
163 /* Accumulate the total number of uniform slots used by this shader.
164 * Note that samplers do not count against this limit because they
165 * don't use any storage on current hardware.
166 */
167 this->num_shader_uniform_components += values;
168 }
169
170 /* If the uniform is already in the map, there's nothing more to do.
171 */
172 unsigned id;
173 if (this->map->get(id, name))
174 return;
175
176 this->map->put(this->num_active_uniforms, name);
177
178 /* Each leaf uniform occupies one entry in the list of active
179 * uniforms.
180 */
181 this->num_active_uniforms++;
182 this->num_values += values;
183 }
184
185 struct string_to_uint_map *map;
186 };
187
188 /**
189 * Class to help parcel out pieces of backing storage to uniforms
190 *
191 * Each uniform processed has some range of the \c gl_constant_value
192 * structures associated with it. The association is done by finding
193 * the uniform in the \c string_to_uint_map and using the value from
194 * the map to connect that slot in the \c gl_uniform_storage table
195 * with the next available slot in the \c gl_constant_value array.
196 *
197 * \warning
198 * This class assumes that every uniform that will be processed is
199 * already in the \c string_to_uint_map. In addition, it assumes that
200 * the \c gl_uniform_storage and \c gl_constant_value arrays are "big
201 * enough."
202 */
203 class parcel_out_uniform_storage : public uniform_field_visitor {
204 public:
205 parcel_out_uniform_storage(struct string_to_uint_map *map,
206 struct gl_uniform_storage *uniforms,
207 union gl_constant_value *values)
208 : map(map), uniforms(uniforms), next_sampler(0), values(values)
209 {
210 memset(this->targets, 0, sizeof(this->targets));
211 }
212
213 void start_shader()
214 {
215 this->shader_samplers_used = 0;
216 this->shader_shadow_samplers = 0;
217 }
218
219 private:
220 virtual void visit_field(const glsl_type *type, const char *name)
221 {
222 assert(!type->is_record());
223 assert(!(type->is_array() && type->fields.array->is_record()));
224
225 unsigned id;
226 bool found = this->map->get(id, name);
227 assert(found);
228
229 if (!found)
230 return;
231
232 /* If there is already storage associated with this uniform, it means
233 * that it was set while processing an earlier shader stage. For
234 * example, we may be processing the uniform in the fragment shader, but
235 * the uniform was already processed in the vertex shader.
236 */
237 if (this->uniforms[id].storage != NULL) {
238 /* If the uniform already has storage set from another shader stage,
239 * mark the samplers used for this shader stage.
240 */
241 if (type->contains_sampler()) {
242 const unsigned count = MAX2(1, this->uniforms[id].array_elements);
243 const unsigned shadow = (type->is_array())
244 ? type->fields.array->sampler_shadow : type->sampler_shadow;
245
246 for (unsigned i = 0; i < count; i++) {
247 const unsigned s = this->uniforms[id].sampler + i;
248
249 this->shader_samplers_used |= 1U << s;
250 this->shader_shadow_samplers |= shadow << s;
251 }
252 }
253
254 return;
255 }
256
257 const glsl_type *base_type;
258 if (type->is_array()) {
259 this->uniforms[id].array_elements = type->length;
260 base_type = type->fields.array;
261 } else {
262 this->uniforms[id].array_elements = 0;
263 base_type = type;
264 }
265
266 if (base_type->is_sampler()) {
267 this->uniforms[id].sampler = this->next_sampler;
268
269 /* Increment the sampler by 1 for non-arrays and by the number of
270 * array elements for arrays.
271 */
272 this->next_sampler += MAX2(1, this->uniforms[id].array_elements);
273
274 const gl_texture_index target = base_type->sampler_index();
275 const unsigned shadow = base_type->sampler_shadow;
276 for (unsigned i = this->uniforms[id].sampler
277 ; i < this->next_sampler
278 ; i++) {
279 this->targets[i] = target;
280 this->shader_samplers_used |= 1U << i;
281 this->shader_shadow_samplers |= shadow << i;
282 }
283
284 } else {
285 this->uniforms[id].sampler = ~0;
286 }
287
288 this->uniforms[id].name = ralloc_strdup(this->uniforms, name);
289 this->uniforms[id].type = base_type;
290 this->uniforms[id].initialized = 0;
291 this->uniforms[id].num_driver_storage = 0;
292 this->uniforms[id].driver_storage = NULL;
293 this->uniforms[id].storage = this->values;
294
295 this->values += values_for_type(type);
296 }
297
298 struct string_to_uint_map *map;
299
300 struct gl_uniform_storage *uniforms;
301 unsigned next_sampler;
302
303 public:
304 union gl_constant_value *values;
305
306 gl_texture_index targets[MAX_SAMPLERS];
307
308 /**
309 * Mask of samplers used by the current shader stage.
310 */
311 unsigned shader_samplers_used;
312
313 /**
314 * Mask of samplers used by the current shader stage for shadows.
315 */
316 unsigned shader_shadow_samplers;
317 };
318
319 /**
320 * Merges a uniform block into an array of uniform blocks that may or
321 * may not already contain a copy of it.
322 *
323 * Returns the index of the new block in the array.
324 */
325 int
326 link_cross_validate_uniform_block(void *mem_ctx,
327 struct gl_uniform_block **linked_blocks,
328 unsigned int *num_linked_blocks,
329 struct gl_uniform_block *new_block)
330 {
331 for (unsigned int i = 0; i < *num_linked_blocks; i++) {
332 struct gl_uniform_block *old_block = &(*linked_blocks)[i];
333 if (strcmp(old_block->Name, new_block->Name) == 0) {
334 if (old_block->NumUniforms != new_block->NumUniforms) {
335 return -1;
336 }
337
338 for (unsigned j = 0; j < old_block->NumUniforms; j++) {
339 if (strcmp(old_block->Uniforms[j].Name,
340 new_block->Uniforms[j].Name) != 0)
341 return -1;
342
343 if (old_block->Uniforms[j].Offset !=
344 new_block->Uniforms[j].Offset)
345 return -1;
346
347 if (old_block->Uniforms[j].RowMajor !=
348 new_block->Uniforms[j].RowMajor)
349 return -1;
350 }
351 return i;
352 }
353 }
354
355 *linked_blocks = reralloc(mem_ctx, *linked_blocks,
356 struct gl_uniform_block,
357 *num_linked_blocks + 1);
358 int linked_block_index = (*num_linked_blocks)++;
359 struct gl_uniform_block *linked_block = &(*linked_blocks)[linked_block_index];
360
361 memcpy(linked_block, new_block, sizeof(*new_block));
362 linked_block->Uniforms = ralloc_array(*linked_blocks,
363 struct gl_uniform_buffer_variable,
364 linked_block->NumUniforms);
365
366 memcpy(linked_block->Uniforms,
367 new_block->Uniforms,
368 sizeof(*linked_block->Uniforms) * linked_block->NumUniforms);
369
370 for (unsigned int i = 0; i < linked_block->NumUniforms; i++) {
371 struct gl_uniform_buffer_variable *ubo_var =
372 &linked_block->Uniforms[i];
373
374 ubo_var->Name = ralloc_strdup(*linked_blocks, ubo_var->Name);
375 }
376
377 return linked_block_index;
378 }
379
380 void
381 link_assign_uniform_locations(struct gl_shader_program *prog)
382 {
383 ralloc_free(prog->UniformStorage);
384 prog->UniformStorage = NULL;
385 prog->NumUserUniformStorage = 0;
386
387 if (prog->UniformHash != NULL) {
388 prog->UniformHash->clear();
389 } else {
390 prog->UniformHash = new string_to_uint_map;
391 }
392
393 /* Uniforms that lack an initializer in the shader code have an initial
394 * value of zero. This includes sampler uniforms.
395 *
396 * Page 24 (page 30 of the PDF) of the GLSL 1.20 spec says:
397 *
398 * "The link time initial value is either the value of the variable's
399 * initializer, if present, or 0 if no initializer is present. Sampler
400 * types cannot have initializers."
401 */
402 memset(prog->SamplerUnits, 0, sizeof(prog->SamplerUnits));
403
404 /* First pass: Count the uniform resources used by the user-defined
405 * uniforms. While this happens, each active uniform will have an index
406 * assigned to it.
407 *
408 * Note: this is *NOT* the index that is returned to the application by
409 * glGetUniformLocation.
410 */
411 count_uniform_size uniform_size(prog->UniformHash);
412 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
413 if (prog->_LinkedShaders[i] == NULL)
414 continue;
415
416 /* Reset various per-shader target counts.
417 */
418 uniform_size.start_shader();
419
420 foreach_list(node, prog->_LinkedShaders[i]->ir) {
421 ir_variable *const var = ((ir_instruction *) node)->as_variable();
422
423 if ((var == NULL) || (var->mode != ir_var_uniform))
424 continue;
425
426 /* FINISHME: Update code to process built-in uniforms!
427 */
428 if (strncmp("gl_", var->name, 3) == 0)
429 continue;
430
431 uniform_size.process(var);
432 }
433
434 prog->_LinkedShaders[i]->num_samplers = uniform_size.num_shader_samplers;
435 prog->_LinkedShaders[i]->num_uniform_components =
436 uniform_size.num_shader_uniform_components;
437 }
438
439 const unsigned num_user_uniforms = uniform_size.num_active_uniforms;
440 const unsigned num_data_slots = uniform_size.num_values;
441
442 /* On the outside chance that there were no uniforms, bail out.
443 */
444 if (num_user_uniforms == 0)
445 return;
446
447 struct gl_uniform_storage *uniforms =
448 rzalloc_array(prog, struct gl_uniform_storage, num_user_uniforms);
449 union gl_constant_value *data =
450 rzalloc_array(uniforms, union gl_constant_value, num_data_slots);
451 #ifndef NDEBUG
452 union gl_constant_value *data_end = &data[num_data_slots];
453 #endif
454
455 parcel_out_uniform_storage parcel(prog->UniformHash, uniforms, data);
456
457 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
458 if (prog->_LinkedShaders[i] == NULL)
459 continue;
460
461 /* Reset various per-shader target counts.
462 */
463 parcel.start_shader();
464
465 foreach_list(node, prog->_LinkedShaders[i]->ir) {
466 ir_variable *const var = ((ir_instruction *) node)->as_variable();
467
468 if ((var == NULL) || (var->mode != ir_var_uniform))
469 continue;
470
471 /* FINISHME: Update code to process built-in uniforms!
472 */
473 if (strncmp("gl_", var->name, 3) == 0)
474 continue;
475
476 parcel.process(var);
477 }
478
479 prog->_LinkedShaders[i]->active_samplers = parcel.shader_samplers_used;
480 prog->_LinkedShaders[i]->shadow_samplers = parcel.shader_shadow_samplers;
481 }
482
483 assert(sizeof(prog->SamplerTargets) == sizeof(parcel.targets));
484 memcpy(prog->SamplerTargets, parcel.targets, sizeof(prog->SamplerTargets));
485
486 #ifndef NDEBUG
487 for (unsigned i = 0; i < num_user_uniforms; i++) {
488 assert(uniforms[i].storage != NULL);
489 }
490
491 assert(parcel.values == data_end);
492 #endif
493
494 prog->NumUserUniformStorage = num_user_uniforms;
495 prog->UniformStorage = uniforms;
496
497 link_set_uniform_initializers(prog);
498
499 return;
500 }