r600g: Fix memory leak in r600_bytecode_add_vtx.
[mesa.git] / src / glsl / link_varyings.cpp
1 /*
2 * Copyright © 2012 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
22 */
23
24 /**
25 * \file link_varyings.cpp
26 *
27 * Linker functions related specifically to linking varyings between shader
28 * stages.
29 */
30
31
32 #include "main/mtypes.h"
33 #include "glsl_symbol_table.h"
34 #include "ir_optimization.h"
35 #include "linker.h"
36 #include "link_varyings.h"
37 #include "main/macros.h"
38
39
40 /**
41 * Validate that outputs from one stage match inputs of another
42 */
43 bool
44 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
45 gl_shader *producer, gl_shader *consumer)
46 {
47 glsl_symbol_table parameters;
48 /* FINISHME: Figure these out dynamically. */
49 const char *const producer_stage = "vertex";
50 const char *const consumer_stage = "fragment";
51
52 /* Find all shader outputs in the "producer" stage.
53 */
54 foreach_list(node, producer->ir) {
55 ir_variable *const var = ((ir_instruction *) node)->as_variable();
56
57 /* FINISHME: For geometry shaders, this should also look for inout
58 * FINISHME: variables.
59 */
60 if ((var == NULL) || (var->mode != ir_var_out))
61 continue;
62
63 parameters.add_variable(var);
64 }
65
66
67 /* Find all shader inputs in the "consumer" stage. Any variables that have
68 * matching outputs already in the symbol table must have the same type and
69 * qualifiers.
70 */
71 foreach_list(node, consumer->ir) {
72 ir_variable *const input = ((ir_instruction *) node)->as_variable();
73
74 /* FINISHME: For geometry shaders, this should also look for inout
75 * FINISHME: variables.
76 */
77 if ((input == NULL) || (input->mode != ir_var_in))
78 continue;
79
80 ir_variable *const output = parameters.get_variable(input->name);
81 if (output != NULL) {
82 /* Check that the types match between stages.
83 */
84 if (input->type != output->type) {
85 /* There is a bit of a special case for gl_TexCoord. This
86 * built-in is unsized by default. Applications that variable
87 * access it must redeclare it with a size. There is some
88 * language in the GLSL spec that implies the fragment shader
89 * and vertex shader do not have to agree on this size. Other
90 * driver behave this way, and one or two applications seem to
91 * rely on it.
92 *
93 * Neither declaration needs to be modified here because the array
94 * sizes are fixed later when update_array_sizes is called.
95 *
96 * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
97 *
98 * "Unlike user-defined varying variables, the built-in
99 * varying variables don't have a strict one-to-one
100 * correspondence between the vertex language and the
101 * fragment language."
102 */
103 if (!output->type->is_array()
104 || (strncmp("gl_", output->name, 3) != 0)) {
105 linker_error(prog,
106 "%s shader output `%s' declared as type `%s', "
107 "but %s shader input declared as type `%s'\n",
108 producer_stage, output->name,
109 output->type->name,
110 consumer_stage, input->type->name);
111 return false;
112 }
113 }
114
115 /* Check that all of the qualifiers match between stages.
116 */
117 if (input->centroid != output->centroid) {
118 linker_error(prog,
119 "%s shader output `%s' %s centroid qualifier, "
120 "but %s shader input %s centroid qualifier\n",
121 producer_stage,
122 output->name,
123 (output->centroid) ? "has" : "lacks",
124 consumer_stage,
125 (input->centroid) ? "has" : "lacks");
126 return false;
127 }
128
129 if (input->invariant != output->invariant) {
130 linker_error(prog,
131 "%s shader output `%s' %s invariant qualifier, "
132 "but %s shader input %s invariant qualifier\n",
133 producer_stage,
134 output->name,
135 (output->invariant) ? "has" : "lacks",
136 consumer_stage,
137 (input->invariant) ? "has" : "lacks");
138 return false;
139 }
140
141 if (input->interpolation != output->interpolation) {
142 linker_error(prog,
143 "%s shader output `%s' specifies %s "
144 "interpolation qualifier, "
145 "but %s shader input specifies %s "
146 "interpolation qualifier\n",
147 producer_stage,
148 output->name,
149 output->interpolation_string(),
150 consumer_stage,
151 input->interpolation_string());
152 return false;
153 }
154 }
155 }
156
157 return true;
158 }
159
160
161 /**
162 * Initialize this object based on a string that was passed to
163 * glTransformFeedbackVaryings. If there is a parse error, the error is
164 * reported using linker_error(), and false is returned.
165 */
166 bool
167 tfeedback_decl::init(struct gl_context *ctx, struct gl_shader_program *prog,
168 const void *mem_ctx, const char *input)
169 {
170 /* We don't have to be pedantic about what is a valid GLSL variable name,
171 * because any variable with an invalid name can't exist in the IR anyway.
172 */
173
174 this->location = -1;
175 this->orig_name = input;
176 this->is_clip_distance_mesa = false;
177 this->skip_components = 0;
178 this->next_buffer_separator = false;
179
180 if (ctx->Extensions.ARB_transform_feedback3) {
181 /* Parse gl_NextBuffer. */
182 if (strcmp(input, "gl_NextBuffer") == 0) {
183 this->next_buffer_separator = true;
184 return true;
185 }
186
187 /* Parse gl_SkipComponents. */
188 if (strcmp(input, "gl_SkipComponents1") == 0)
189 this->skip_components = 1;
190 else if (strcmp(input, "gl_SkipComponents2") == 0)
191 this->skip_components = 2;
192 else if (strcmp(input, "gl_SkipComponents3") == 0)
193 this->skip_components = 3;
194 else if (strcmp(input, "gl_SkipComponents4") == 0)
195 this->skip_components = 4;
196
197 if (this->skip_components)
198 return true;
199 }
200
201 /* Parse a declaration. */
202 const char *bracket = strrchr(input, '[');
203
204 if (bracket) {
205 this->var_name = ralloc_strndup(mem_ctx, input, bracket - input);
206 if (sscanf(bracket, "[%u]", &this->array_subscript) != 1) {
207 linker_error(prog, "Cannot parse transform feedback varying %s", input);
208 return false;
209 }
210 this->is_subscripted = true;
211 } else {
212 this->var_name = ralloc_strdup(mem_ctx, input);
213 this->is_subscripted = false;
214 }
215
216 /* For drivers that lower gl_ClipDistance to gl_ClipDistanceMESA, this
217 * class must behave specially to account for the fact that gl_ClipDistance
218 * is converted from a float[8] to a vec4[2].
219 */
220 if (ctx->ShaderCompilerOptions[MESA_SHADER_VERTEX].LowerClipDistance &&
221 strcmp(this->var_name, "gl_ClipDistance") == 0) {
222 this->is_clip_distance_mesa = true;
223 }
224
225 return true;
226 }
227
228
229 /**
230 * Determine whether two tfeedback_decl objects refer to the same variable and
231 * array index (if applicable).
232 */
233 bool
234 tfeedback_decl::is_same(const tfeedback_decl &x, const tfeedback_decl &y)
235 {
236 assert(x.is_varying() && y.is_varying());
237
238 if (strcmp(x.var_name, y.var_name) != 0)
239 return false;
240 if (x.is_subscripted != y.is_subscripted)
241 return false;
242 if (x.is_subscripted && x.array_subscript != y.array_subscript)
243 return false;
244 return true;
245 }
246
247
248 /**
249 * Assign a location for this tfeedback_decl object based on the location
250 * assignment in output_var.
251 *
252 * If an error occurs, the error is reported through linker_error() and false
253 * is returned.
254 */
255 bool
256 tfeedback_decl::assign_location(struct gl_context *ctx,
257 struct gl_shader_program *prog,
258 ir_variable *output_var)
259 {
260 assert(this->is_varying());
261
262 if (output_var->type->is_array()) {
263 /* Array variable */
264 const unsigned matrix_cols =
265 output_var->type->fields.array->matrix_columns;
266 const unsigned vector_elements =
267 output_var->type->fields.array->vector_elements;
268 unsigned actual_array_size = this->is_clip_distance_mesa ?
269 prog->Vert.ClipDistanceArraySize : output_var->type->array_size();
270
271 if (this->is_subscripted) {
272 /* Check array bounds. */
273 if (this->array_subscript >= actual_array_size) {
274 linker_error(prog, "Transform feedback varying %s has index "
275 "%i, but the array size is %u.",
276 this->orig_name, this->array_subscript,
277 actual_array_size);
278 return false;
279 }
280 if (this->is_clip_distance_mesa) {
281 this->location =
282 output_var->location + this->array_subscript / 4;
283 this->location_frac = this->array_subscript % 4;
284 } else {
285 unsigned fine_location
286 = output_var->location * 4 + output_var->location_frac;
287 unsigned array_elem_size = vector_elements * matrix_cols;
288 fine_location += array_elem_size * this->array_subscript;
289 this->location = fine_location / 4;
290 this->location_frac = fine_location % 4;
291 }
292 this->size = 1;
293 } else {
294 this->location = output_var->location;
295 this->location_frac = output_var->location_frac;
296 this->size = actual_array_size;
297 }
298 this->vector_elements = vector_elements;
299 this->matrix_columns = matrix_cols;
300 if (this->is_clip_distance_mesa)
301 this->type = GL_FLOAT;
302 else
303 this->type = output_var->type->fields.array->gl_type;
304 } else {
305 /* Regular variable (scalar, vector, or matrix) */
306 if (this->is_subscripted) {
307 linker_error(prog, "Transform feedback varying %s requested, "
308 "but %s is not an array.",
309 this->orig_name, this->var_name);
310 return false;
311 }
312 this->location = output_var->location;
313 this->location_frac = output_var->location_frac;
314 this->size = 1;
315 this->vector_elements = output_var->type->vector_elements;
316 this->matrix_columns = output_var->type->matrix_columns;
317 this->type = output_var->type->gl_type;
318 }
319
320 /* From GL_EXT_transform_feedback:
321 * A program will fail to link if:
322 *
323 * * the total number of components to capture in any varying
324 * variable in <varyings> is greater than the constant
325 * MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT and the
326 * buffer mode is SEPARATE_ATTRIBS_EXT;
327 */
328 if (prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS &&
329 this->num_components() >
330 ctx->Const.MaxTransformFeedbackSeparateComponents) {
331 linker_error(prog, "Transform feedback varying %s exceeds "
332 "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS.",
333 this->orig_name);
334 return false;
335 }
336
337 return true;
338 }
339
340
341 unsigned
342 tfeedback_decl::get_num_outputs() const
343 {
344 if (!this->is_varying()) {
345 return 0;
346 }
347
348 return (this->num_components() + this->location_frac + 3)/4;
349 }
350
351
352 /**
353 * Update gl_transform_feedback_info to reflect this tfeedback_decl.
354 *
355 * If an error occurs, the error is reported through linker_error() and false
356 * is returned.
357 */
358 bool
359 tfeedback_decl::store(struct gl_context *ctx, struct gl_shader_program *prog,
360 struct gl_transform_feedback_info *info,
361 unsigned buffer, const unsigned max_outputs) const
362 {
363 assert(!this->next_buffer_separator);
364
365 /* Handle gl_SkipComponents. */
366 if (this->skip_components) {
367 info->BufferStride[buffer] += this->skip_components;
368 return true;
369 }
370
371 /* From GL_EXT_transform_feedback:
372 * A program will fail to link if:
373 *
374 * * the total number of components to capture is greater than
375 * the constant MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT
376 * and the buffer mode is INTERLEAVED_ATTRIBS_EXT.
377 */
378 if (prog->TransformFeedback.BufferMode == GL_INTERLEAVED_ATTRIBS &&
379 info->BufferStride[buffer] + this->num_components() >
380 ctx->Const.MaxTransformFeedbackInterleavedComponents) {
381 linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
382 "limit has been exceeded.");
383 return false;
384 }
385
386 unsigned location = this->location;
387 unsigned location_frac = this->location_frac;
388 unsigned num_components = this->num_components();
389 while (num_components > 0) {
390 unsigned output_size = MIN2(num_components, 4 - location_frac);
391 assert(info->NumOutputs < max_outputs);
392 info->Outputs[info->NumOutputs].ComponentOffset = location_frac;
393 info->Outputs[info->NumOutputs].OutputRegister = location;
394 info->Outputs[info->NumOutputs].NumComponents = output_size;
395 info->Outputs[info->NumOutputs].OutputBuffer = buffer;
396 info->Outputs[info->NumOutputs].DstOffset = info->BufferStride[buffer];
397 ++info->NumOutputs;
398 info->BufferStride[buffer] += output_size;
399 num_components -= output_size;
400 location++;
401 location_frac = 0;
402 }
403
404 info->Varyings[info->NumVarying].Name = ralloc_strdup(prog, this->orig_name);
405 info->Varyings[info->NumVarying].Type = this->type;
406 info->Varyings[info->NumVarying].Size = this->size;
407 info->NumVarying++;
408
409 return true;
410 }
411
412
413 ir_variable *
414 tfeedback_decl::find_output_var(gl_shader_program *prog,
415 gl_shader *producer) const
416 {
417 const char *name = this->is_clip_distance_mesa
418 ? "gl_ClipDistanceMESA" : this->var_name;
419 ir_variable *var = producer->symbols->get_variable(name);
420 if (var && var->mode == ir_var_out)
421 return var;
422
423 /* From GL_EXT_transform_feedback:
424 * A program will fail to link if:
425 *
426 * * any variable name specified in the <varyings> array is not
427 * declared as an output in the geometry shader (if present) or
428 * the vertex shader (if no geometry shader is present);
429 */
430 linker_error(prog, "Transform feedback varying %s undeclared.",
431 this->orig_name);
432 return NULL;
433 }
434
435
436 /**
437 * Parse all the transform feedback declarations that were passed to
438 * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
439 *
440 * If an error occurs, the error is reported through linker_error() and false
441 * is returned.
442 */
443 bool
444 parse_tfeedback_decls(struct gl_context *ctx, struct gl_shader_program *prog,
445 const void *mem_ctx, unsigned num_names,
446 char **varying_names, tfeedback_decl *decls)
447 {
448 for (unsigned i = 0; i < num_names; ++i) {
449 if (!decls[i].init(ctx, prog, mem_ctx, varying_names[i]))
450 return false;
451
452 if (!decls[i].is_varying())
453 continue;
454
455 /* From GL_EXT_transform_feedback:
456 * A program will fail to link if:
457 *
458 * * any two entries in the <varyings> array specify the same varying
459 * variable;
460 *
461 * We interpret this to mean "any two entries in the <varyings> array
462 * specify the same varying variable and array index", since transform
463 * feedback of arrays would be useless otherwise.
464 */
465 for (unsigned j = 0; j < i; ++j) {
466 if (!decls[j].is_varying())
467 continue;
468
469 if (tfeedback_decl::is_same(decls[i], decls[j])) {
470 linker_error(prog, "Transform feedback varying %s specified "
471 "more than once.", varying_names[i]);
472 return false;
473 }
474 }
475 }
476 return true;
477 }
478
479
480 /**
481 * Store transform feedback location assignments into
482 * prog->LinkedTransformFeedback based on the data stored in tfeedback_decls.
483 *
484 * If an error occurs, the error is reported through linker_error() and false
485 * is returned.
486 */
487 bool
488 store_tfeedback_info(struct gl_context *ctx, struct gl_shader_program *prog,
489 unsigned num_tfeedback_decls,
490 tfeedback_decl *tfeedback_decls)
491 {
492 bool separate_attribs_mode =
493 prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS;
494
495 ralloc_free(prog->LinkedTransformFeedback.Varyings);
496 ralloc_free(prog->LinkedTransformFeedback.Outputs);
497
498 memset(&prog->LinkedTransformFeedback, 0,
499 sizeof(prog->LinkedTransformFeedback));
500
501 prog->LinkedTransformFeedback.Varyings =
502 rzalloc_array(prog,
503 struct gl_transform_feedback_varying_info,
504 num_tfeedback_decls);
505
506 unsigned num_outputs = 0;
507 for (unsigned i = 0; i < num_tfeedback_decls; ++i)
508 num_outputs += tfeedback_decls[i].get_num_outputs();
509
510 prog->LinkedTransformFeedback.Outputs =
511 rzalloc_array(prog,
512 struct gl_transform_feedback_output,
513 num_outputs);
514
515 unsigned num_buffers = 0;
516
517 if (separate_attribs_mode) {
518 /* GL_SEPARATE_ATTRIBS */
519 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
520 if (!tfeedback_decls[i].store(ctx, prog, &prog->LinkedTransformFeedback,
521 num_buffers, num_outputs))
522 return false;
523
524 num_buffers++;
525 }
526 }
527 else {
528 /* GL_INVERLEAVED_ATTRIBS */
529 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
530 if (tfeedback_decls[i].is_next_buffer_separator()) {
531 num_buffers++;
532 continue;
533 }
534
535 if (!tfeedback_decls[i].store(ctx, prog,
536 &prog->LinkedTransformFeedback,
537 num_buffers, num_outputs))
538 return false;
539 }
540 num_buffers++;
541 }
542
543 assert(prog->LinkedTransformFeedback.NumOutputs == num_outputs);
544
545 prog->LinkedTransformFeedback.NumBuffers = num_buffers;
546 return true;
547 }
548
549
550 /**
551 * Data structure recording the relationship between outputs of one shader
552 * stage (the "producer") and inputs of another (the "consumer").
553 */
554 class varying_matches
555 {
556 public:
557 varying_matches(bool disable_varying_packing);
558 ~varying_matches();
559 void record(ir_variable *producer_var, ir_variable *consumer_var);
560 unsigned assign_locations();
561 void store_locations(unsigned producer_base, unsigned consumer_base) const;
562
563 private:
564 /**
565 * If true, this driver disables varying packing, so all varyings need to
566 * be aligned on slot boundaries, and take up a number of slots equal to
567 * their number of matrix columns times their array size.
568 */
569 const bool disable_varying_packing;
570
571 /**
572 * Enum representing the order in which varyings are packed within a
573 * packing class.
574 *
575 * Currently we pack vec4's first, then vec2's, then scalar values, then
576 * vec3's. This order ensures that the only vectors that are at risk of
577 * having to be "double parked" (split between two adjacent varying slots)
578 * are the vec3's.
579 */
580 enum packing_order_enum {
581 PACKING_ORDER_VEC4,
582 PACKING_ORDER_VEC2,
583 PACKING_ORDER_SCALAR,
584 PACKING_ORDER_VEC3,
585 };
586
587 static unsigned compute_packing_class(ir_variable *var);
588 static packing_order_enum compute_packing_order(ir_variable *var);
589 static int match_comparator(const void *x_generic, const void *y_generic);
590
591 /**
592 * Structure recording the relationship between a single producer output
593 * and a single consumer input.
594 */
595 struct match {
596 /**
597 * Packing class for this varying, computed by compute_packing_class().
598 */
599 unsigned packing_class;
600
601 /**
602 * Packing order for this varying, computed by compute_packing_order().
603 */
604 packing_order_enum packing_order;
605 unsigned num_components;
606
607 /**
608 * The output variable in the producer stage.
609 */
610 ir_variable *producer_var;
611
612 /**
613 * The input variable in the consumer stage.
614 */
615 ir_variable *consumer_var;
616
617 /**
618 * The location which has been assigned for this varying. This is
619 * expressed in multiples of a float, with the first generic varying
620 * (i.e. the one referred to by VERT_RESULT_VAR0 or FRAG_ATTRIB_VAR0)
621 * represented by the value 0.
622 */
623 unsigned generic_location;
624 } *matches;
625
626 /**
627 * The number of elements in the \c matches array that are currently in
628 * use.
629 */
630 unsigned num_matches;
631
632 /**
633 * The number of elements that were set aside for the \c matches array when
634 * it was allocated.
635 */
636 unsigned matches_capacity;
637 };
638
639
640 varying_matches::varying_matches(bool disable_varying_packing)
641 : disable_varying_packing(disable_varying_packing)
642 {
643 /* Note: this initial capacity is rather arbitrarily chosen to be large
644 * enough for many cases without wasting an unreasonable amount of space.
645 * varying_matches::record() will resize the array if there are more than
646 * this number of varyings.
647 */
648 this->matches_capacity = 8;
649 this->matches = (match *)
650 malloc(sizeof(*this->matches) * this->matches_capacity);
651 this->num_matches = 0;
652 }
653
654
655 varying_matches::~varying_matches()
656 {
657 free(this->matches);
658 }
659
660
661 /**
662 * Record the given producer/consumer variable pair in the list of variables
663 * that should later be assigned locations.
664 *
665 * It is permissible for \c consumer_var to be NULL (this happens if a
666 * variable is output by the producer and consumed by transform feedback, but
667 * not consumed by the consumer).
668 *
669 * If \c producer_var has already been paired up with a consumer_var, or
670 * producer_var is part of fixed pipeline functionality (and hence already has
671 * a location assigned), this function has no effect.
672 */
673 void
674 varying_matches::record(ir_variable *producer_var, ir_variable *consumer_var)
675 {
676 if (!producer_var->is_unmatched_generic_inout) {
677 /* Either a location already exists for this variable (since it is part
678 * of fixed functionality), or it has already been recorded as part of a
679 * previous match.
680 */
681 return;
682 }
683
684 if (this->num_matches == this->matches_capacity) {
685 this->matches_capacity *= 2;
686 this->matches = (match *)
687 realloc(this->matches,
688 sizeof(*this->matches) * this->matches_capacity);
689 }
690 this->matches[this->num_matches].packing_class
691 = this->compute_packing_class(producer_var);
692 this->matches[this->num_matches].packing_order
693 = this->compute_packing_order(producer_var);
694 if (this->disable_varying_packing) {
695 unsigned slots = producer_var->type->is_array()
696 ? (producer_var->type->length
697 * producer_var->type->fields.array->matrix_columns)
698 : producer_var->type->matrix_columns;
699 this->matches[this->num_matches].num_components = 4 * slots;
700 } else {
701 this->matches[this->num_matches].num_components
702 = producer_var->type->component_slots();
703 }
704 this->matches[this->num_matches].producer_var = producer_var;
705 this->matches[this->num_matches].consumer_var = consumer_var;
706 this->num_matches++;
707 producer_var->is_unmatched_generic_inout = 0;
708 if (consumer_var)
709 consumer_var->is_unmatched_generic_inout = 0;
710 }
711
712
713 /**
714 * Choose locations for all of the variable matches that were previously
715 * passed to varying_matches::record().
716 */
717 unsigned
718 varying_matches::assign_locations()
719 {
720 /* Sort varying matches into an order that makes them easy to pack. */
721 qsort(this->matches, this->num_matches, sizeof(*this->matches),
722 &varying_matches::match_comparator);
723
724 unsigned generic_location = 0;
725
726 for (unsigned i = 0; i < this->num_matches; i++) {
727 /* Advance to the next slot if this varying has a different packing
728 * class than the previous one, and we're not already on a slot
729 * boundary.
730 */
731 if (i > 0 &&
732 this->matches[i - 1].packing_class
733 != this->matches[i].packing_class) {
734 generic_location = ALIGN(generic_location, 4);
735 }
736
737 this->matches[i].generic_location = generic_location;
738
739 generic_location += this->matches[i].num_components;
740 }
741
742 return (generic_location + 3) / 4;
743 }
744
745
746 /**
747 * Update the producer and consumer shaders to reflect the locations
748 * assignments that were made by varying_matches::assign_locations().
749 */
750 void
751 varying_matches::store_locations(unsigned producer_base,
752 unsigned consumer_base) const
753 {
754 for (unsigned i = 0; i < this->num_matches; i++) {
755 ir_variable *producer_var = this->matches[i].producer_var;
756 ir_variable *consumer_var = this->matches[i].consumer_var;
757 unsigned generic_location = this->matches[i].generic_location;
758 unsigned slot = generic_location / 4;
759 unsigned offset = generic_location % 4;
760
761 producer_var->location = producer_base + slot;
762 producer_var->location_frac = offset;
763 if (consumer_var) {
764 assert(consumer_var->location == -1);
765 consumer_var->location = consumer_base + slot;
766 consumer_var->location_frac = offset;
767 }
768 }
769 }
770
771
772 /**
773 * Compute the "packing class" of the given varying. This is an unsigned
774 * integer with the property that two variables in the same packing class can
775 * be safely backed into the same vec4.
776 */
777 unsigned
778 varying_matches::compute_packing_class(ir_variable *var)
779 {
780 /* Without help from the back-end, there is no way to pack together
781 * variables with different interpolation types, because
782 * lower_packed_varyings must choose exactly one interpolation type for
783 * each packed varying it creates.
784 *
785 * However, we can safely pack together floats, ints, and uints, because:
786 *
787 * - varyings of base type "int" and "uint" must use the "flat"
788 * interpolation type, which can only occur in GLSL 1.30 and above.
789 *
790 * - On platforms that support GLSL 1.30 and above, lower_packed_varyings
791 * can store flat floats as ints without losing any information (using
792 * the ir_unop_bitcast_* opcodes).
793 *
794 * Therefore, the packing class depends only on the interpolation type.
795 */
796 unsigned packing_class = var->centroid ? 1 : 0;
797 packing_class *= 4;
798 packing_class += var->interpolation;
799 return packing_class;
800 }
801
802
803 /**
804 * Compute the "packing order" of the given varying. This is a sort key we
805 * use to determine when to attempt to pack the given varying relative to
806 * other varyings in the same packing class.
807 */
808 varying_matches::packing_order_enum
809 varying_matches::compute_packing_order(ir_variable *var)
810 {
811 const glsl_type *element_type = var->type;
812
813 /* FINISHME: Support for "varying" records in GLSL 1.50. */
814 while (element_type->base_type == GLSL_TYPE_ARRAY) {
815 element_type = element_type->fields.array;
816 }
817
818 switch (element_type->vector_elements) {
819 case 1: return PACKING_ORDER_SCALAR;
820 case 2: return PACKING_ORDER_VEC2;
821 case 3: return PACKING_ORDER_VEC3;
822 case 4: return PACKING_ORDER_VEC4;
823 default:
824 assert(!"Unexpected value of vector_elements");
825 return PACKING_ORDER_VEC4;
826 }
827 }
828
829
830 /**
831 * Comparison function passed to qsort() to sort varyings by packing_class and
832 * then by packing_order.
833 */
834 int
835 varying_matches::match_comparator(const void *x_generic, const void *y_generic)
836 {
837 const match *x = (const match *) x_generic;
838 const match *y = (const match *) y_generic;
839
840 if (x->packing_class != y->packing_class)
841 return x->packing_class - y->packing_class;
842 return x->packing_order - y->packing_order;
843 }
844
845
846 /**
847 * Is the given variable a varying variable to be counted against the
848 * limit in ctx->Const.MaxVarying?
849 * This includes variables such as texcoords, colors and generic
850 * varyings, but excludes variables such as gl_FrontFacing and gl_FragCoord.
851 */
852 static bool
853 is_varying_var(GLenum shaderType, const ir_variable *var)
854 {
855 /* Only fragment shaders will take a varying variable as an input */
856 if (shaderType == GL_FRAGMENT_SHADER &&
857 var->mode == ir_var_in) {
858 switch (var->location) {
859 case FRAG_ATTRIB_WPOS:
860 case FRAG_ATTRIB_FACE:
861 case FRAG_ATTRIB_PNTC:
862 return false;
863 default:
864 return true;
865 }
866 }
867 return false;
868 }
869
870
871 /**
872 * Assign locations for all variables that are produced in one pipeline stage
873 * (the "producer") and consumed in the next stage (the "consumer").
874 *
875 * Variables produced by the producer may also be consumed by transform
876 * feedback.
877 *
878 * \param num_tfeedback_decls is the number of declarations indicating
879 * variables that may be consumed by transform feedback.
880 *
881 * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
882 * representing the result of parsing the strings passed to
883 * glTransformFeedbackVaryings(). assign_location() will be called for
884 * each of these objects that matches one of the outputs of the
885 * producer.
886 *
887 * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
888 * be NULL. In this case, varying locations are assigned solely based on the
889 * requirements of transform feedback.
890 */
891 bool
892 assign_varying_locations(struct gl_context *ctx,
893 void *mem_ctx,
894 struct gl_shader_program *prog,
895 gl_shader *producer, gl_shader *consumer,
896 unsigned num_tfeedback_decls,
897 tfeedback_decl *tfeedback_decls)
898 {
899 /* FINISHME: Set dynamically when geometry shader support is added. */
900 const unsigned producer_base = VERT_RESULT_VAR0;
901 const unsigned consumer_base = FRAG_ATTRIB_VAR0;
902 varying_matches matches(ctx->Const.DisableVaryingPacking);
903
904 /* Operate in a total of three passes.
905 *
906 * 1. Assign locations for any matching inputs and outputs.
907 *
908 * 2. Mark output variables in the producer that do not have locations as
909 * not being outputs. This lets the optimizer eliminate them.
910 *
911 * 3. Mark input variables in the consumer that do not have locations as
912 * not being inputs. This lets the optimizer eliminate them.
913 */
914
915 foreach_list(node, producer->ir) {
916 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
917
918 if ((output_var == NULL) || (output_var->mode != ir_var_out))
919 continue;
920
921 ir_variable *input_var =
922 consumer ? consumer->symbols->get_variable(output_var->name) : NULL;
923
924 if (input_var && input_var->mode != ir_var_in)
925 input_var = NULL;
926
927 if (input_var) {
928 matches.record(output_var, input_var);
929 }
930 }
931
932 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
933 if (!tfeedback_decls[i].is_varying())
934 continue;
935
936 ir_variable *output_var
937 = tfeedback_decls[i].find_output_var(prog, producer);
938
939 if (output_var == NULL)
940 return false;
941
942 if (output_var->is_unmatched_generic_inout) {
943 matches.record(output_var, NULL);
944 }
945 }
946
947 const unsigned slots_used = matches.assign_locations();
948 matches.store_locations(producer_base, consumer_base);
949
950 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
951 if (!tfeedback_decls[i].is_varying())
952 continue;
953
954 ir_variable *output_var
955 = tfeedback_decls[i].find_output_var(prog, producer);
956
957 if (!tfeedback_decls[i].assign_location(ctx, prog, output_var))
958 return false;
959 }
960
961 if (ctx->Const.DisableVaryingPacking) {
962 /* Transform feedback code assumes varyings are packed, so if the driver
963 * has disabled varying packing, make sure it does not support transform
964 * feedback.
965 */
966 assert(!ctx->Extensions.EXT_transform_feedback);
967 } else {
968 lower_packed_varyings(mem_ctx, producer_base, slots_used, ir_var_out,
969 producer);
970 if (consumer) {
971 lower_packed_varyings(mem_ctx, consumer_base, slots_used, ir_var_in,
972 consumer);
973 }
974 }
975
976 unsigned varying_vectors = 0;
977
978 if (consumer) {
979 foreach_list(node, consumer->ir) {
980 ir_variable *const var = ((ir_instruction *) node)->as_variable();
981
982 if ((var == NULL) || (var->mode != ir_var_in))
983 continue;
984
985 if (var->is_unmatched_generic_inout) {
986 if (prog->Version <= 120) {
987 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
988 *
989 * Only those varying variables used (i.e. read) in
990 * the fragment shader executable must be written to
991 * by the vertex shader executable; declaring
992 * superfluous varying variables in a vertex shader is
993 * permissible.
994 *
995 * We interpret this text as meaning that the VS must
996 * write the variable for the FS to read it. See
997 * "glsl1-varying read but not written" in piglit.
998 */
999
1000 linker_error(prog, "fragment shader varying %s not written "
1001 "by vertex shader\n.", var->name);
1002 }
1003
1004 /* An 'in' variable is only really a shader input if its
1005 * value is written by the previous stage.
1006 */
1007 var->mode = ir_var_auto;
1008 } else if (is_varying_var(consumer->Type, var)) {
1009 /* The packing rules are used for vertex shader inputs are also
1010 * used for fragment shader inputs.
1011 */
1012 varying_vectors += count_attribute_slots(var->type);
1013 }
1014 }
1015 }
1016
1017 if (ctx->API == API_OPENGLES2 || prog->IsES) {
1018 if (varying_vectors > ctx->Const.MaxVarying) {
1019 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
1020 linker_warning(prog, "shader uses too many varying vectors "
1021 "(%u > %u), but the driver will try to optimize "
1022 "them out; this is non-portable out-of-spec "
1023 "behavior\n",
1024 varying_vectors, ctx->Const.MaxVarying);
1025 } else {
1026 linker_error(prog, "shader uses too many varying vectors "
1027 "(%u > %u)\n",
1028 varying_vectors, ctx->Const.MaxVarying);
1029 return false;
1030 }
1031 }
1032 } else {
1033 const unsigned float_components = varying_vectors * 4;
1034 if (float_components > ctx->Const.MaxVarying * 4) {
1035 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
1036 linker_warning(prog, "shader uses too many varying components "
1037 "(%u > %u), but the driver will try to optimize "
1038 "them out; this is non-portable out-of-spec "
1039 "behavior\n",
1040 float_components, ctx->Const.MaxVarying * 4);
1041 } else {
1042 linker_error(prog, "shader uses too many varying components "
1043 "(%u > %u)\n",
1044 float_components, ctx->Const.MaxVarying * 4);
1045 return false;
1046 }
1047 }
1048 }
1049
1050 return true;
1051 }