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