llvmpipe: implement 64 bit mul opcodes in llvmpipe
[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 "glsl_parser_extras.h"
35 #include "ir_optimization.h"
36 #include "linker.h"
37 #include "link_varyings.h"
38 #include "main/macros.h"
39 #include "program/hash_table.h"
40 #include "program.h"
41
42
43 /**
44 * Validate the types and qualifiers of an output from one stage against the
45 * matching input to another stage.
46 */
47 static void
48 cross_validate_types_and_qualifiers(struct gl_shader_program *prog,
49 const ir_variable *input,
50 const ir_variable *output,
51 GLenum consumer_type,
52 GLenum producer_type)
53 {
54 /* Check that the types match between stages.
55 */
56 const glsl_type *type_to_match = input->type;
57 if (consumer_type == GL_GEOMETRY_SHADER) {
58 assert(type_to_match->is_array()); /* Enforced by ast_to_hir */
59 type_to_match = type_to_match->element_type();
60 }
61 if (type_to_match != output->type) {
62 /* There is a bit of a special case for gl_TexCoord. This
63 * built-in is unsized by default. Applications that variable
64 * access it must redeclare it with a size. There is some
65 * language in the GLSL spec that implies the fragment shader
66 * and vertex shader do not have to agree on this size. Other
67 * driver behave this way, and one or two applications seem to
68 * rely on it.
69 *
70 * Neither declaration needs to be modified here because the array
71 * sizes are fixed later when update_array_sizes is called.
72 *
73 * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
74 *
75 * "Unlike user-defined varying variables, the built-in
76 * varying variables don't have a strict one-to-one
77 * correspondence between the vertex language and the
78 * fragment language."
79 */
80 if (!output->type->is_array()
81 || (strncmp("gl_", output->name, 3) != 0)) {
82 linker_error(prog,
83 "%s shader output `%s' declared as type `%s', "
84 "but %s shader input declared as type `%s'\n",
85 _mesa_glsl_shader_target_name(producer_type),
86 output->name,
87 output->type->name,
88 _mesa_glsl_shader_target_name(consumer_type),
89 input->type->name);
90 return;
91 }
92 }
93
94 /* Check that all of the qualifiers match between stages.
95 */
96 if (input->centroid != output->centroid) {
97 linker_error(prog,
98 "%s shader output `%s' %s centroid qualifier, "
99 "but %s shader input %s centroid qualifier\n",
100 _mesa_glsl_shader_target_name(producer_type),
101 output->name,
102 (output->centroid) ? "has" : "lacks",
103 _mesa_glsl_shader_target_name(consumer_type),
104 (input->centroid) ? "has" : "lacks");
105 return;
106 }
107
108 if (input->invariant != output->invariant) {
109 linker_error(prog,
110 "%s shader output `%s' %s invariant qualifier, "
111 "but %s shader input %s invariant qualifier\n",
112 _mesa_glsl_shader_target_name(producer_type),
113 output->name,
114 (output->invariant) ? "has" : "lacks",
115 _mesa_glsl_shader_target_name(consumer_type),
116 (input->invariant) ? "has" : "lacks");
117 return;
118 }
119
120 if (input->interpolation != output->interpolation) {
121 linker_error(prog,
122 "%s shader output `%s' specifies %s "
123 "interpolation qualifier, "
124 "but %s shader input specifies %s "
125 "interpolation qualifier\n",
126 _mesa_glsl_shader_target_name(producer_type),
127 output->name,
128 output->interpolation_string(),
129 _mesa_glsl_shader_target_name(consumer_type),
130 input->interpolation_string());
131 return;
132 }
133 }
134
135 /**
136 * Validate front and back color outputs against single color input
137 */
138 static void
139 cross_validate_front_and_back_color(struct gl_shader_program *prog,
140 const ir_variable *input,
141 const ir_variable *front_color,
142 const ir_variable *back_color,
143 GLenum consumer_type,
144 GLenum producer_type)
145 {
146 if (front_color != NULL && front_color->assigned)
147 cross_validate_types_and_qualifiers(prog, input, front_color,
148 consumer_type, producer_type);
149
150 if (back_color != NULL && back_color->assigned)
151 cross_validate_types_and_qualifiers(prog, input, back_color,
152 consumer_type, producer_type);
153 }
154
155 /**
156 * Validate that outputs from one stage match inputs of another
157 */
158 void
159 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
160 gl_shader *producer, gl_shader *consumer)
161 {
162 glsl_symbol_table parameters;
163
164 /* Find all shader outputs in the "producer" stage.
165 */
166 foreach_list(node, producer->ir) {
167 ir_variable *const var = ((ir_instruction *) node)->as_variable();
168
169 if ((var == NULL) || (var->mode != ir_var_shader_out))
170 continue;
171
172 parameters.add_variable(var);
173 }
174
175
176 /* Find all shader inputs in the "consumer" stage. Any variables that have
177 * matching outputs already in the symbol table must have the same type and
178 * qualifiers.
179 *
180 * Exception: if the consumer is the geometry shader, then the inputs
181 * should be arrays and the type of the array element should match the type
182 * of the corresponding producer output.
183 */
184 foreach_list(node, consumer->ir) {
185 ir_variable *const input = ((ir_instruction *) node)->as_variable();
186
187 if ((input == NULL) || (input->mode != ir_var_shader_in))
188 continue;
189
190 if (strcmp(input->name, "gl_Color") == 0 && input->used) {
191 const ir_variable *const front_color =
192 parameters.get_variable("gl_FrontColor");
193
194 const ir_variable *const back_color =
195 parameters.get_variable("gl_BackColor");
196
197 cross_validate_front_and_back_color(prog, input,
198 front_color, back_color,
199 consumer->Type, producer->Type);
200 } else if (strcmp(input->name, "gl_SecondaryColor") == 0 && input->used) {
201 const ir_variable *const front_color =
202 parameters.get_variable("gl_FrontSecondaryColor");
203
204 const ir_variable *const back_color =
205 parameters.get_variable("gl_BackSecondaryColor");
206
207 cross_validate_front_and_back_color(prog, input,
208 front_color, back_color,
209 consumer->Type, producer->Type);
210 } else {
211 ir_variable *const output = parameters.get_variable(input->name);
212 if (output != NULL) {
213 cross_validate_types_and_qualifiers(prog, input, output,
214 consumer->Type, producer->Type);
215 }
216 }
217 }
218 }
219
220
221 /**
222 * Initialize this object based on a string that was passed to
223 * glTransformFeedbackVaryings.
224 *
225 * If the input is mal-formed, this call still succeeds, but it sets
226 * this->var_name to a mal-formed input, so tfeedback_decl::find_output_var()
227 * will fail to find any matching variable.
228 */
229 void
230 tfeedback_decl::init(struct gl_context *ctx, const void *mem_ctx,
231 const char *input)
232 {
233 /* We don't have to be pedantic about what is a valid GLSL variable name,
234 * because any variable with an invalid name can't exist in the IR anyway.
235 */
236
237 this->location = -1;
238 this->orig_name = input;
239 this->is_clip_distance_mesa = false;
240 this->skip_components = 0;
241 this->next_buffer_separator = false;
242 this->matched_candidate = NULL;
243
244 if (ctx->Extensions.ARB_transform_feedback3) {
245 /* Parse gl_NextBuffer. */
246 if (strcmp(input, "gl_NextBuffer") == 0) {
247 this->next_buffer_separator = true;
248 return;
249 }
250
251 /* Parse gl_SkipComponents. */
252 if (strcmp(input, "gl_SkipComponents1") == 0)
253 this->skip_components = 1;
254 else if (strcmp(input, "gl_SkipComponents2") == 0)
255 this->skip_components = 2;
256 else if (strcmp(input, "gl_SkipComponents3") == 0)
257 this->skip_components = 3;
258 else if (strcmp(input, "gl_SkipComponents4") == 0)
259 this->skip_components = 4;
260
261 if (this->skip_components)
262 return;
263 }
264
265 /* Parse a declaration. */
266 const char *base_name_end;
267 long subscript = parse_program_resource_name(input, &base_name_end);
268 this->var_name = ralloc_strndup(mem_ctx, input, base_name_end - input);
269 if (subscript >= 0) {
270 this->array_subscript = subscript;
271 this->is_subscripted = true;
272 } else {
273 this->is_subscripted = false;
274 }
275
276 /* For drivers that lower gl_ClipDistance to gl_ClipDistanceMESA, this
277 * class must behave specially to account for the fact that gl_ClipDistance
278 * is converted from a float[8] to a vec4[2].
279 */
280 if (ctx->ShaderCompilerOptions[MESA_SHADER_VERTEX].LowerClipDistance &&
281 strcmp(this->var_name, "gl_ClipDistance") == 0) {
282 this->is_clip_distance_mesa = true;
283 }
284 }
285
286
287 /**
288 * Determine whether two tfeedback_decl objects refer to the same variable and
289 * array index (if applicable).
290 */
291 bool
292 tfeedback_decl::is_same(const tfeedback_decl &x, const tfeedback_decl &y)
293 {
294 assert(x.is_varying() && y.is_varying());
295
296 if (strcmp(x.var_name, y.var_name) != 0)
297 return false;
298 if (x.is_subscripted != y.is_subscripted)
299 return false;
300 if (x.is_subscripted && x.array_subscript != y.array_subscript)
301 return false;
302 return true;
303 }
304
305
306 /**
307 * Assign a location for this tfeedback_decl object based on the transform
308 * feedback candidate found by find_candidate.
309 *
310 * If an error occurs, the error is reported through linker_error() and false
311 * is returned.
312 */
313 bool
314 tfeedback_decl::assign_location(struct gl_context *ctx,
315 struct gl_shader_program *prog)
316 {
317 assert(this->is_varying());
318
319 unsigned fine_location
320 = this->matched_candidate->toplevel_var->location * 4
321 + this->matched_candidate->toplevel_var->location_frac
322 + this->matched_candidate->offset;
323
324 if (this->matched_candidate->type->is_array()) {
325 /* Array variable */
326 const unsigned matrix_cols =
327 this->matched_candidate->type->fields.array->matrix_columns;
328 const unsigned vector_elements =
329 this->matched_candidate->type->fields.array->vector_elements;
330 unsigned actual_array_size = this->is_clip_distance_mesa ?
331 prog->Vert.ClipDistanceArraySize :
332 this->matched_candidate->type->array_size();
333
334 if (this->is_subscripted) {
335 /* Check array bounds. */
336 if (this->array_subscript >= actual_array_size) {
337 linker_error(prog, "Transform feedback varying %s has index "
338 "%i, but the array size is %u.",
339 this->orig_name, this->array_subscript,
340 actual_array_size);
341 return false;
342 }
343 unsigned array_elem_size = this->is_clip_distance_mesa ?
344 1 : vector_elements * matrix_cols;
345 fine_location += array_elem_size * this->array_subscript;
346 this->size = 1;
347 } else {
348 this->size = actual_array_size;
349 }
350 this->vector_elements = vector_elements;
351 this->matrix_columns = matrix_cols;
352 if (this->is_clip_distance_mesa)
353 this->type = GL_FLOAT;
354 else
355 this->type = this->matched_candidate->type->fields.array->gl_type;
356 } else {
357 /* Regular variable (scalar, vector, or matrix) */
358 if (this->is_subscripted) {
359 linker_error(prog, "Transform feedback varying %s requested, "
360 "but %s is not an array.",
361 this->orig_name, this->var_name);
362 return false;
363 }
364 this->size = 1;
365 this->vector_elements = this->matched_candidate->type->vector_elements;
366 this->matrix_columns = this->matched_candidate->type->matrix_columns;
367 this->type = this->matched_candidate->type->gl_type;
368 }
369 this->location = fine_location / 4;
370 this->location_frac = fine_location % 4;
371
372 /* From GL_EXT_transform_feedback:
373 * A program will fail to link if:
374 *
375 * * the total number of components to capture in any varying
376 * variable in <varyings> is greater than the constant
377 * MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT and the
378 * buffer mode is SEPARATE_ATTRIBS_EXT;
379 */
380 if (prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS &&
381 this->num_components() >
382 ctx->Const.MaxTransformFeedbackSeparateComponents) {
383 linker_error(prog, "Transform feedback varying %s exceeds "
384 "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS.",
385 this->orig_name);
386 return false;
387 }
388
389 return true;
390 }
391
392
393 unsigned
394 tfeedback_decl::get_num_outputs() const
395 {
396 if (!this->is_varying()) {
397 return 0;
398 }
399
400 return (this->num_components() + this->location_frac + 3)/4;
401 }
402
403
404 /**
405 * Update gl_transform_feedback_info to reflect this tfeedback_decl.
406 *
407 * If an error occurs, the error is reported through linker_error() and false
408 * is returned.
409 */
410 bool
411 tfeedback_decl::store(struct gl_context *ctx, struct gl_shader_program *prog,
412 struct gl_transform_feedback_info *info,
413 unsigned buffer, const unsigned max_outputs) const
414 {
415 assert(!this->next_buffer_separator);
416
417 /* Handle gl_SkipComponents. */
418 if (this->skip_components) {
419 info->BufferStride[buffer] += this->skip_components;
420 return true;
421 }
422
423 /* From GL_EXT_transform_feedback:
424 * A program will fail to link if:
425 *
426 * * the total number of components to capture is greater than
427 * the constant MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT
428 * and the buffer mode is INTERLEAVED_ATTRIBS_EXT.
429 */
430 if (prog->TransformFeedback.BufferMode == GL_INTERLEAVED_ATTRIBS &&
431 info->BufferStride[buffer] + this->num_components() >
432 ctx->Const.MaxTransformFeedbackInterleavedComponents) {
433 linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
434 "limit has been exceeded.");
435 return false;
436 }
437
438 unsigned location = this->location;
439 unsigned location_frac = this->location_frac;
440 unsigned num_components = this->num_components();
441 while (num_components > 0) {
442 unsigned output_size = MIN2(num_components, 4 - location_frac);
443 assert(info->NumOutputs < max_outputs);
444 info->Outputs[info->NumOutputs].ComponentOffset = location_frac;
445 info->Outputs[info->NumOutputs].OutputRegister = location;
446 info->Outputs[info->NumOutputs].NumComponents = output_size;
447 info->Outputs[info->NumOutputs].OutputBuffer = buffer;
448 info->Outputs[info->NumOutputs].DstOffset = info->BufferStride[buffer];
449 ++info->NumOutputs;
450 info->BufferStride[buffer] += output_size;
451 num_components -= output_size;
452 location++;
453 location_frac = 0;
454 }
455
456 info->Varyings[info->NumVarying].Name = ralloc_strdup(prog, this->orig_name);
457 info->Varyings[info->NumVarying].Type = this->type;
458 info->Varyings[info->NumVarying].Size = this->size;
459 info->NumVarying++;
460
461 return true;
462 }
463
464
465 const tfeedback_candidate *
466 tfeedback_decl::find_candidate(gl_shader_program *prog,
467 hash_table *tfeedback_candidates)
468 {
469 const char *name = this->is_clip_distance_mesa
470 ? "gl_ClipDistanceMESA" : this->var_name;
471 this->matched_candidate = (const tfeedback_candidate *)
472 hash_table_find(tfeedback_candidates, name);
473 if (!this->matched_candidate) {
474 /* From GL_EXT_transform_feedback:
475 * A program will fail to link if:
476 *
477 * * any variable name specified in the <varyings> array is not
478 * declared as an output in the geometry shader (if present) or
479 * the vertex shader (if no geometry shader is present);
480 */
481 linker_error(prog, "Transform feedback varying %s undeclared.",
482 this->orig_name);
483 }
484 return this->matched_candidate;
485 }
486
487
488 /**
489 * Parse all the transform feedback declarations that were passed to
490 * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
491 *
492 * If an error occurs, the error is reported through linker_error() and false
493 * is returned.
494 */
495 bool
496 parse_tfeedback_decls(struct gl_context *ctx, struct gl_shader_program *prog,
497 const void *mem_ctx, unsigned num_names,
498 char **varying_names, tfeedback_decl *decls)
499 {
500 for (unsigned i = 0; i < num_names; ++i) {
501 decls[i].init(ctx, mem_ctx, varying_names[i]);
502
503 if (!decls[i].is_varying())
504 continue;
505
506 /* From GL_EXT_transform_feedback:
507 * A program will fail to link if:
508 *
509 * * any two entries in the <varyings> array specify the same varying
510 * variable;
511 *
512 * We interpret this to mean "any two entries in the <varyings> array
513 * specify the same varying variable and array index", since transform
514 * feedback of arrays would be useless otherwise.
515 */
516 for (unsigned j = 0; j < i; ++j) {
517 if (!decls[j].is_varying())
518 continue;
519
520 if (tfeedback_decl::is_same(decls[i], decls[j])) {
521 linker_error(prog, "Transform feedback varying %s specified "
522 "more than once.", varying_names[i]);
523 return false;
524 }
525 }
526 }
527 return true;
528 }
529
530
531 /**
532 * Store transform feedback location assignments into
533 * prog->LinkedTransformFeedback based on the data stored in tfeedback_decls.
534 *
535 * If an error occurs, the error is reported through linker_error() and false
536 * is returned.
537 */
538 bool
539 store_tfeedback_info(struct gl_context *ctx, struct gl_shader_program *prog,
540 unsigned num_tfeedback_decls,
541 tfeedback_decl *tfeedback_decls)
542 {
543 bool separate_attribs_mode =
544 prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS;
545
546 ralloc_free(prog->LinkedTransformFeedback.Varyings);
547 ralloc_free(prog->LinkedTransformFeedback.Outputs);
548
549 memset(&prog->LinkedTransformFeedback, 0,
550 sizeof(prog->LinkedTransformFeedback));
551
552 prog->LinkedTransformFeedback.Varyings =
553 rzalloc_array(prog,
554 struct gl_transform_feedback_varying_info,
555 num_tfeedback_decls);
556
557 unsigned num_outputs = 0;
558 for (unsigned i = 0; i < num_tfeedback_decls; ++i)
559 num_outputs += tfeedback_decls[i].get_num_outputs();
560
561 prog->LinkedTransformFeedback.Outputs =
562 rzalloc_array(prog,
563 struct gl_transform_feedback_output,
564 num_outputs);
565
566 unsigned num_buffers = 0;
567
568 if (separate_attribs_mode) {
569 /* GL_SEPARATE_ATTRIBS */
570 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
571 if (!tfeedback_decls[i].store(ctx, prog, &prog->LinkedTransformFeedback,
572 num_buffers, num_outputs))
573 return false;
574
575 num_buffers++;
576 }
577 }
578 else {
579 /* GL_INVERLEAVED_ATTRIBS */
580 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
581 if (tfeedback_decls[i].is_next_buffer_separator()) {
582 num_buffers++;
583 continue;
584 }
585
586 if (!tfeedback_decls[i].store(ctx, prog,
587 &prog->LinkedTransformFeedback,
588 num_buffers, num_outputs))
589 return false;
590 }
591 num_buffers++;
592 }
593
594 assert(prog->LinkedTransformFeedback.NumOutputs == num_outputs);
595
596 prog->LinkedTransformFeedback.NumBuffers = num_buffers;
597 return true;
598 }
599
600 namespace {
601
602 /**
603 * Data structure recording the relationship between outputs of one shader
604 * stage (the "producer") and inputs of another (the "consumer").
605 */
606 class varying_matches
607 {
608 public:
609 varying_matches(bool disable_varying_packing, bool consumer_is_fs);
610 ~varying_matches();
611 void record(ir_variable *producer_var, ir_variable *consumer_var);
612 unsigned assign_locations();
613 void store_locations(unsigned producer_base, unsigned consumer_base) const;
614
615 private:
616 /**
617 * If true, this driver disables varying packing, so all varyings need to
618 * be aligned on slot boundaries, and take up a number of slots equal to
619 * their number of matrix columns times their array size.
620 */
621 const bool disable_varying_packing;
622
623 /**
624 * Enum representing the order in which varyings are packed within a
625 * packing class.
626 *
627 * Currently we pack vec4's first, then vec2's, then scalar values, then
628 * vec3's. This order ensures that the only vectors that are at risk of
629 * having to be "double parked" (split between two adjacent varying slots)
630 * are the vec3's.
631 */
632 enum packing_order_enum {
633 PACKING_ORDER_VEC4,
634 PACKING_ORDER_VEC2,
635 PACKING_ORDER_SCALAR,
636 PACKING_ORDER_VEC3,
637 };
638
639 static unsigned compute_packing_class(ir_variable *var);
640 static packing_order_enum compute_packing_order(ir_variable *var);
641 static int match_comparator(const void *x_generic, const void *y_generic);
642
643 /**
644 * Structure recording the relationship between a single producer output
645 * and a single consumer input.
646 */
647 struct match {
648 /**
649 * Packing class for this varying, computed by compute_packing_class().
650 */
651 unsigned packing_class;
652
653 /**
654 * Packing order for this varying, computed by compute_packing_order().
655 */
656 packing_order_enum packing_order;
657 unsigned num_components;
658
659 /**
660 * The output variable in the producer stage.
661 */
662 ir_variable *producer_var;
663
664 /**
665 * The input variable in the consumer stage.
666 */
667 ir_variable *consumer_var;
668
669 /**
670 * The location which has been assigned for this varying. This is
671 * expressed in multiples of a float, with the first generic varying
672 * (i.e. the one referred to by VARYING_SLOT_VAR0) represented by the
673 * value 0.
674 */
675 unsigned generic_location;
676 } *matches;
677
678 /**
679 * The number of elements in the \c matches array that are currently in
680 * use.
681 */
682 unsigned num_matches;
683
684 /**
685 * The number of elements that were set aside for the \c matches array when
686 * it was allocated.
687 */
688 unsigned matches_capacity;
689
690 const bool consumer_is_fs;
691 };
692
693 } /* anonymous namespace */
694
695 varying_matches::varying_matches(bool disable_varying_packing,
696 bool consumer_is_fs)
697 : disable_varying_packing(disable_varying_packing),
698 consumer_is_fs(consumer_is_fs)
699 {
700 /* Note: this initial capacity is rather arbitrarily chosen to be large
701 * enough for many cases without wasting an unreasonable amount of space.
702 * varying_matches::record() will resize the array if there are more than
703 * this number of varyings.
704 */
705 this->matches_capacity = 8;
706 this->matches = (match *)
707 malloc(sizeof(*this->matches) * this->matches_capacity);
708 this->num_matches = 0;
709 }
710
711
712 varying_matches::~varying_matches()
713 {
714 free(this->matches);
715 }
716
717
718 /**
719 * Record the given producer/consumer variable pair in the list of variables
720 * that should later be assigned locations.
721 *
722 * It is permissible for \c consumer_var to be NULL (this happens if a
723 * variable is output by the producer and consumed by transform feedback, but
724 * not consumed by the consumer).
725 *
726 * If \c producer_var has already been paired up with a consumer_var, or
727 * producer_var is part of fixed pipeline functionality (and hence already has
728 * a location assigned), this function has no effect.
729 *
730 * Note: as a side effect this function may change the interpolation type of
731 * \c producer_var, but only when the change couldn't possibly affect
732 * rendering.
733 */
734 void
735 varying_matches::record(ir_variable *producer_var, ir_variable *consumer_var)
736 {
737 if (!producer_var->is_unmatched_generic_inout) {
738 /* Either a location already exists for this variable (since it is part
739 * of fixed functionality), or it has already been recorded as part of a
740 * previous match.
741 */
742 return;
743 }
744
745 if ((consumer_var == NULL && producer_var->type->contains_integer()) ||
746 !consumer_is_fs) {
747 /* Since this varying is not being consumed by the fragment shader, its
748 * interpolation type varying cannot possibly affect rendering. Also,
749 * this variable is non-flat and is (or contains) an integer.
750 *
751 * lower_packed_varyings requires all integer varyings to flat,
752 * regardless of where they appear. We can trivially satisfy that
753 * requirement by changing the interpolation type to flat here.
754 */
755 producer_var->centroid = false;
756 producer_var->interpolation = INTERP_QUALIFIER_FLAT;
757
758 if (consumer_var) {
759 consumer_var->centroid = false;
760 consumer_var->interpolation = INTERP_QUALIFIER_FLAT;
761 }
762 }
763
764 if (this->num_matches == this->matches_capacity) {
765 this->matches_capacity *= 2;
766 this->matches = (match *)
767 realloc(this->matches,
768 sizeof(*this->matches) * this->matches_capacity);
769 }
770 this->matches[this->num_matches].packing_class
771 = this->compute_packing_class(producer_var);
772 this->matches[this->num_matches].packing_order
773 = this->compute_packing_order(producer_var);
774 if (this->disable_varying_packing) {
775 unsigned slots = producer_var->type->is_array()
776 ? (producer_var->type->length
777 * producer_var->type->fields.array->matrix_columns)
778 : producer_var->type->matrix_columns;
779 this->matches[this->num_matches].num_components = 4 * slots;
780 } else {
781 this->matches[this->num_matches].num_components
782 = producer_var->type->component_slots();
783 }
784 this->matches[this->num_matches].producer_var = producer_var;
785 this->matches[this->num_matches].consumer_var = consumer_var;
786 this->num_matches++;
787 producer_var->is_unmatched_generic_inout = 0;
788 if (consumer_var)
789 consumer_var->is_unmatched_generic_inout = 0;
790 }
791
792
793 /**
794 * Choose locations for all of the variable matches that were previously
795 * passed to varying_matches::record().
796 */
797 unsigned
798 varying_matches::assign_locations()
799 {
800 /* Sort varying matches into an order that makes them easy to pack. */
801 qsort(this->matches, this->num_matches, sizeof(*this->matches),
802 &varying_matches::match_comparator);
803
804 unsigned generic_location = 0;
805
806 for (unsigned i = 0; i < this->num_matches; i++) {
807 /* Advance to the next slot if this varying has a different packing
808 * class than the previous one, and we're not already on a slot
809 * boundary.
810 */
811 if (i > 0 &&
812 this->matches[i - 1].packing_class
813 != this->matches[i].packing_class) {
814 generic_location = ALIGN(generic_location, 4);
815 }
816
817 this->matches[i].generic_location = generic_location;
818
819 generic_location += this->matches[i].num_components;
820 }
821
822 return (generic_location + 3) / 4;
823 }
824
825
826 /**
827 * Update the producer and consumer shaders to reflect the locations
828 * assignments that were made by varying_matches::assign_locations().
829 */
830 void
831 varying_matches::store_locations(unsigned producer_base,
832 unsigned consumer_base) const
833 {
834 for (unsigned i = 0; i < this->num_matches; i++) {
835 ir_variable *producer_var = this->matches[i].producer_var;
836 ir_variable *consumer_var = this->matches[i].consumer_var;
837 unsigned generic_location = this->matches[i].generic_location;
838 unsigned slot = generic_location / 4;
839 unsigned offset = generic_location % 4;
840
841 producer_var->location = producer_base + slot;
842 producer_var->location_frac = offset;
843 if (consumer_var) {
844 assert(consumer_var->location == -1);
845 consumer_var->location = consumer_base + slot;
846 consumer_var->location_frac = offset;
847 }
848 }
849 }
850
851
852 /**
853 * Compute the "packing class" of the given varying. This is an unsigned
854 * integer with the property that two variables in the same packing class can
855 * be safely backed into the same vec4.
856 */
857 unsigned
858 varying_matches::compute_packing_class(ir_variable *var)
859 {
860 /* Without help from the back-end, there is no way to pack together
861 * variables with different interpolation types, because
862 * lower_packed_varyings must choose exactly one interpolation type for
863 * each packed varying it creates.
864 *
865 * However, we can safely pack together floats, ints, and uints, because:
866 *
867 * - varyings of base type "int" and "uint" must use the "flat"
868 * interpolation type, which can only occur in GLSL 1.30 and above.
869 *
870 * - On platforms that support GLSL 1.30 and above, lower_packed_varyings
871 * can store flat floats as ints without losing any information (using
872 * the ir_unop_bitcast_* opcodes).
873 *
874 * Therefore, the packing class depends only on the interpolation type.
875 */
876 unsigned packing_class = var->centroid ? 1 : 0;
877 packing_class *= 4;
878 packing_class += var->interpolation;
879 return packing_class;
880 }
881
882
883 /**
884 * Compute the "packing order" of the given varying. This is a sort key we
885 * use to determine when to attempt to pack the given varying relative to
886 * other varyings in the same packing class.
887 */
888 varying_matches::packing_order_enum
889 varying_matches::compute_packing_order(ir_variable *var)
890 {
891 const glsl_type *element_type = var->type;
892
893 while (element_type->base_type == GLSL_TYPE_ARRAY) {
894 element_type = element_type->fields.array;
895 }
896
897 switch (element_type->component_slots() % 4) {
898 case 1: return PACKING_ORDER_SCALAR;
899 case 2: return PACKING_ORDER_VEC2;
900 case 3: return PACKING_ORDER_VEC3;
901 case 0: return PACKING_ORDER_VEC4;
902 default:
903 assert(!"Unexpected value of vector_elements");
904 return PACKING_ORDER_VEC4;
905 }
906 }
907
908
909 /**
910 * Comparison function passed to qsort() to sort varyings by packing_class and
911 * then by packing_order.
912 */
913 int
914 varying_matches::match_comparator(const void *x_generic, const void *y_generic)
915 {
916 const match *x = (const match *) x_generic;
917 const match *y = (const match *) y_generic;
918
919 if (x->packing_class != y->packing_class)
920 return x->packing_class - y->packing_class;
921 return x->packing_order - y->packing_order;
922 }
923
924
925 /**
926 * Is the given variable a varying variable to be counted against the
927 * limit in ctx->Const.MaxVarying?
928 * This includes variables such as texcoords, colors and generic
929 * varyings, but excludes variables such as gl_FrontFacing and gl_FragCoord.
930 */
931 static bool
932 is_varying_var(GLenum shaderType, const ir_variable *var)
933 {
934 /* Only fragment shaders will take a varying variable as an input */
935 if (shaderType == GL_FRAGMENT_SHADER &&
936 var->mode == ir_var_shader_in) {
937 switch (var->location) {
938 case VARYING_SLOT_POS:
939 case VARYING_SLOT_FACE:
940 case VARYING_SLOT_PNTC:
941 return false;
942 default:
943 return true;
944 }
945 }
946 return false;
947 }
948
949
950 /**
951 * Visitor class that generates tfeedback_candidate structs describing all
952 * possible targets of transform feedback.
953 *
954 * tfeedback_candidate structs are stored in the hash table
955 * tfeedback_candidates, which is passed to the constructor. This hash table
956 * maps varying names to instances of the tfeedback_candidate struct.
957 */
958 class tfeedback_candidate_generator : public program_resource_visitor
959 {
960 public:
961 tfeedback_candidate_generator(void *mem_ctx,
962 hash_table *tfeedback_candidates)
963 : mem_ctx(mem_ctx),
964 tfeedback_candidates(tfeedback_candidates),
965 toplevel_var(NULL),
966 varying_floats(0)
967 {
968 }
969
970 void process(ir_variable *var)
971 {
972 this->toplevel_var = var;
973 this->varying_floats = 0;
974 if (var->is_interface_instance())
975 program_resource_visitor::process(var->interface_type,
976 var->interface_type->name);
977 else
978 program_resource_visitor::process(var);
979 }
980
981 private:
982 virtual void visit_field(const glsl_type *type, const char *name,
983 bool row_major)
984 {
985 assert(!type->is_record());
986 assert(!(type->is_array() && type->fields.array->is_record()));
987 assert(!type->is_interface());
988 assert(!(type->is_array() && type->fields.array->is_interface()));
989
990 (void) row_major;
991
992 tfeedback_candidate *candidate
993 = rzalloc(this->mem_ctx, tfeedback_candidate);
994 candidate->toplevel_var = this->toplevel_var;
995 candidate->type = type;
996 candidate->offset = this->varying_floats;
997 hash_table_insert(this->tfeedback_candidates, candidate,
998 ralloc_strdup(this->mem_ctx, name));
999 this->varying_floats += type->component_slots();
1000 }
1001
1002 /**
1003 * Memory context used to allocate hash table keys and values.
1004 */
1005 void * const mem_ctx;
1006
1007 /**
1008 * Hash table in which tfeedback_candidate objects should be stored.
1009 */
1010 hash_table * const tfeedback_candidates;
1011
1012 /**
1013 * Pointer to the toplevel variable that is being traversed.
1014 */
1015 ir_variable *toplevel_var;
1016
1017 /**
1018 * Total number of varying floats that have been visited so far. This is
1019 * used to determine the offset to each varying within the toplevel
1020 * variable.
1021 */
1022 unsigned varying_floats;
1023 };
1024
1025
1026 /**
1027 * Assign locations for all variables that are produced in one pipeline stage
1028 * (the "producer") and consumed in the next stage (the "consumer").
1029 *
1030 * Variables produced by the producer may also be consumed by transform
1031 * feedback.
1032 *
1033 * \param num_tfeedback_decls is the number of declarations indicating
1034 * variables that may be consumed by transform feedback.
1035 *
1036 * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
1037 * representing the result of parsing the strings passed to
1038 * glTransformFeedbackVaryings(). assign_location() will be called for
1039 * each of these objects that matches one of the outputs of the
1040 * producer.
1041 *
1042 * \param gs_input_vertices: if \c consumer is a geometry shader, this is the
1043 * number of input vertices it accepts. Otherwise zero.
1044 *
1045 * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
1046 * be NULL. In this case, varying locations are assigned solely based on the
1047 * requirements of transform feedback.
1048 */
1049 bool
1050 assign_varying_locations(struct gl_context *ctx,
1051 void *mem_ctx,
1052 struct gl_shader_program *prog,
1053 gl_shader *producer, gl_shader *consumer,
1054 unsigned num_tfeedback_decls,
1055 tfeedback_decl *tfeedback_decls,
1056 unsigned gs_input_vertices)
1057 {
1058 const unsigned producer_base = VARYING_SLOT_VAR0;
1059 const unsigned consumer_base = VARYING_SLOT_VAR0;
1060 varying_matches matches(ctx->Const.DisableVaryingPacking,
1061 consumer && consumer->Type == GL_FRAGMENT_SHADER);
1062 hash_table *tfeedback_candidates
1063 = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare);
1064 hash_table *consumer_inputs
1065 = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare);
1066 hash_table *consumer_interface_inputs
1067 = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare);
1068
1069 /* Operate in a total of three passes.
1070 *
1071 * 1. Assign locations for any matching inputs and outputs.
1072 *
1073 * 2. Mark output variables in the producer that do not have locations as
1074 * not being outputs. This lets the optimizer eliminate them.
1075 *
1076 * 3. Mark input variables in the consumer that do not have locations as
1077 * not being inputs. This lets the optimizer eliminate them.
1078 */
1079
1080 if (consumer) {
1081 foreach_list(node, consumer->ir) {
1082 ir_variable *const input_var =
1083 ((ir_instruction *) node)->as_variable();
1084
1085 if ((input_var != NULL) && (input_var->mode == ir_var_shader_in)) {
1086 if (input_var->interface_type != NULL) {
1087 char *const iface_field_name =
1088 ralloc_asprintf(mem_ctx, "%s.%s",
1089 input_var->interface_type->name,
1090 input_var->name);
1091 hash_table_insert(consumer_interface_inputs, input_var,
1092 iface_field_name);
1093 } else {
1094 hash_table_insert(consumer_inputs, input_var,
1095 ralloc_strdup(mem_ctx, input_var->name));
1096 }
1097 }
1098 }
1099 }
1100
1101 foreach_list(node, producer->ir) {
1102 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1103
1104 if ((output_var == NULL) || (output_var->mode != ir_var_shader_out))
1105 continue;
1106
1107 tfeedback_candidate_generator g(mem_ctx, tfeedback_candidates);
1108 g.process(output_var);
1109
1110 ir_variable *input_var;
1111 if (output_var->interface_type != NULL) {
1112 char *const iface_field_name =
1113 ralloc_asprintf(mem_ctx, "%s.%s",
1114 output_var->interface_type->name,
1115 output_var->name);
1116 input_var =
1117 (ir_variable *) hash_table_find(consumer_interface_inputs,
1118 iface_field_name);
1119 } else {
1120 input_var =
1121 (ir_variable *) hash_table_find(consumer_inputs, output_var->name);
1122 }
1123
1124 if (input_var && input_var->mode != ir_var_shader_in)
1125 input_var = NULL;
1126
1127 if (input_var) {
1128 matches.record(output_var, input_var);
1129 }
1130 }
1131
1132 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1133 if (!tfeedback_decls[i].is_varying())
1134 continue;
1135
1136 const tfeedback_candidate *matched_candidate
1137 = tfeedback_decls[i].find_candidate(prog, tfeedback_candidates);
1138
1139 if (matched_candidate == NULL) {
1140 hash_table_dtor(tfeedback_candidates);
1141 hash_table_dtor(consumer_inputs);
1142 hash_table_dtor(consumer_interface_inputs);
1143 return false;
1144 }
1145
1146 if (matched_candidate->toplevel_var->is_unmatched_generic_inout)
1147 matches.record(matched_candidate->toplevel_var, NULL);
1148 }
1149
1150 const unsigned slots_used = matches.assign_locations();
1151 matches.store_locations(producer_base, consumer_base);
1152
1153 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1154 if (!tfeedback_decls[i].is_varying())
1155 continue;
1156
1157 if (!tfeedback_decls[i].assign_location(ctx, prog)) {
1158 hash_table_dtor(tfeedback_candidates);
1159 hash_table_dtor(consumer_inputs);
1160 hash_table_dtor(consumer_interface_inputs);
1161 return false;
1162 }
1163 }
1164
1165 hash_table_dtor(tfeedback_candidates);
1166 hash_table_dtor(consumer_inputs);
1167 hash_table_dtor(consumer_interface_inputs);
1168
1169 if (ctx->Const.DisableVaryingPacking) {
1170 /* Transform feedback code assumes varyings are packed, so if the driver
1171 * has disabled varying packing, make sure it does not support transform
1172 * feedback.
1173 */
1174 assert(!ctx->Extensions.EXT_transform_feedback);
1175 } else {
1176 lower_packed_varyings(mem_ctx, producer_base, slots_used,
1177 ir_var_shader_out, 0, producer);
1178 if (consumer) {
1179 lower_packed_varyings(mem_ctx, consumer_base, slots_used,
1180 ir_var_shader_in, gs_input_vertices, consumer);
1181 }
1182 }
1183
1184 if (consumer) {
1185 foreach_list(node, consumer->ir) {
1186 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1187
1188 if (var && var->mode == ir_var_shader_in &&
1189 var->is_unmatched_generic_inout) {
1190 if (prog->Version <= 120) {
1191 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1192 *
1193 * Only those varying variables used (i.e. read) in
1194 * the fragment shader executable must be written to
1195 * by the vertex shader executable; declaring
1196 * superfluous varying variables in a vertex shader is
1197 * permissible.
1198 *
1199 * We interpret this text as meaning that the VS must
1200 * write the variable for the FS to read it. See
1201 * "glsl1-varying read but not written" in piglit.
1202 */
1203
1204 linker_error(prog, "%s shader varying %s not written "
1205 "by %s shader\n.",
1206 _mesa_glsl_shader_target_name(consumer->Type),
1207 var->name,
1208 _mesa_glsl_shader_target_name(producer->Type));
1209 }
1210
1211 /* An 'in' variable is only really a shader input if its
1212 * value is written by the previous stage.
1213 */
1214 var->mode = ir_var_auto;
1215 }
1216 }
1217 }
1218
1219 return true;
1220 }
1221
1222 bool
1223 check_against_output_limit(struct gl_context *ctx,
1224 struct gl_shader_program *prog,
1225 gl_shader *producer)
1226 {
1227 unsigned output_vectors = 0;
1228
1229 foreach_list(node, producer->ir) {
1230 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1231
1232 if (var && var->mode == ir_var_shader_out &&
1233 is_varying_var(producer->Type, var)) {
1234 output_vectors += var->type->count_attribute_slots();
1235 }
1236 }
1237
1238 unsigned max_output_components;
1239 switch (producer->Type) {
1240 case GL_VERTEX_SHADER:
1241 max_output_components = ctx->Const.VertexProgram.MaxOutputComponents;
1242 break;
1243 case GL_GEOMETRY_SHADER:
1244 max_output_components = ctx->Const.GeometryProgram.MaxOutputComponents;
1245 break;
1246 case GL_FRAGMENT_SHADER:
1247 default:
1248 assert(!"Should not get here.");
1249 return false;
1250 }
1251
1252 const unsigned output_components = output_vectors * 4;
1253 if (output_components > max_output_components) {
1254 if (ctx->API == API_OPENGLES2 || prog->IsES)
1255 linker_error(prog, "shader uses too many output vectors "
1256 "(%u > %u)\n",
1257 output_vectors,
1258 max_output_components / 4);
1259 else
1260 linker_error(prog, "shader uses too many output components "
1261 "(%u > %u)\n",
1262 output_components,
1263 max_output_components);
1264
1265 return false;
1266 }
1267
1268 return true;
1269 }
1270
1271 bool
1272 check_against_input_limit(struct gl_context *ctx,
1273 struct gl_shader_program *prog,
1274 gl_shader *consumer)
1275 {
1276 unsigned input_vectors = 0;
1277
1278 foreach_list(node, consumer->ir) {
1279 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1280
1281 if (var && var->mode == ir_var_shader_in &&
1282 is_varying_var(consumer->Type, var)) {
1283 input_vectors += var->type->count_attribute_slots();
1284 }
1285 }
1286
1287 unsigned max_input_components;
1288 switch (consumer->Type) {
1289 case GL_GEOMETRY_SHADER:
1290 max_input_components = ctx->Const.GeometryProgram.MaxInputComponents;
1291 break;
1292 case GL_FRAGMENT_SHADER:
1293 max_input_components = ctx->Const.FragmentProgram.MaxInputComponents;
1294 break;
1295 case GL_VERTEX_SHADER:
1296 default:
1297 assert(!"Should not get here.");
1298 return false;
1299 }
1300
1301 const unsigned input_components = input_vectors * 4;
1302 if (input_components > max_input_components) {
1303 if (ctx->API == API_OPENGLES2 || prog->IsES)
1304 linker_error(prog, "shader uses too many input vectors "
1305 "(%u > %u)\n",
1306 input_vectors,
1307 max_input_components / 4);
1308 else
1309 linker_error(prog, "shader uses too many input components "
1310 "(%u > %u)\n",
1311 input_components,
1312 max_input_components);
1313
1314 return false;
1315 }
1316
1317 return true;
1318 }