glsl: don't change the varying type in validation code
[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 gl_shader_stage consumer_stage,
52 gl_shader_stage producer_stage)
53 {
54 /* Check that the types match between stages.
55 */
56 const glsl_type *type_to_match = input->type;
57
58 /* VS -> GS, VS -> TCS, VS -> TES, TES -> GS */
59 const bool extra_array_level = (producer_stage == MESA_SHADER_VERTEX &&
60 consumer_stage != MESA_SHADER_FRAGMENT) ||
61 consumer_stage == MESA_SHADER_GEOMETRY;
62 if (extra_array_level) {
63 assert(type_to_match->is_array());
64 type_to_match = type_to_match->fields.array;
65 }
66
67 if (type_to_match != output->type) {
68 /* There is a bit of a special case for gl_TexCoord. This
69 * built-in is unsized by default. Applications that variable
70 * access it must redeclare it with a size. There is some
71 * language in the GLSL spec that implies the fragment shader
72 * and vertex shader do not have to agree on this size. Other
73 * driver behave this way, and one or two applications seem to
74 * rely on it.
75 *
76 * Neither declaration needs to be modified here because the array
77 * sizes are fixed later when update_array_sizes is called.
78 *
79 * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
80 *
81 * "Unlike user-defined varying variables, the built-in
82 * varying variables don't have a strict one-to-one
83 * correspondence between the vertex language and the
84 * fragment language."
85 */
86 if (!output->type->is_array() || !is_gl_identifier(output->name)) {
87 linker_error(prog,
88 "%s shader output `%s' declared as type `%s', "
89 "but %s shader input declared as type `%s'\n",
90 _mesa_shader_stage_to_string(producer_stage),
91 output->name,
92 output->type->name,
93 _mesa_shader_stage_to_string(consumer_stage),
94 input->type->name);
95 return;
96 }
97 }
98
99 /* Check that all of the qualifiers match between stages.
100 */
101 if (input->data.centroid != output->data.centroid) {
102 linker_error(prog,
103 "%s shader output `%s' %s centroid qualifier, "
104 "but %s shader input %s centroid qualifier\n",
105 _mesa_shader_stage_to_string(producer_stage),
106 output->name,
107 (output->data.centroid) ? "has" : "lacks",
108 _mesa_shader_stage_to_string(consumer_stage),
109 (input->data.centroid) ? "has" : "lacks");
110 return;
111 }
112
113 if (input->data.sample != output->data.sample) {
114 linker_error(prog,
115 "%s shader output `%s' %s sample qualifier, "
116 "but %s shader input %s sample qualifier\n",
117 _mesa_shader_stage_to_string(producer_stage),
118 output->name,
119 (output->data.sample) ? "has" : "lacks",
120 _mesa_shader_stage_to_string(consumer_stage),
121 (input->data.sample) ? "has" : "lacks");
122 return;
123 }
124
125 if (input->data.patch != output->data.patch) {
126 linker_error(prog,
127 "%s shader output `%s' %s patch qualifier, "
128 "but %s shader input %s patch qualifier\n",
129 _mesa_shader_stage_to_string(producer_stage),
130 output->name,
131 (output->data.patch) ? "has" : "lacks",
132 _mesa_shader_stage_to_string(consumer_stage),
133 (input->data.patch) ? "has" : "lacks");
134 return;
135 }
136
137 if (!prog->IsES && input->data.invariant != output->data.invariant) {
138 linker_error(prog,
139 "%s shader output `%s' %s invariant qualifier, "
140 "but %s shader input %s invariant qualifier\n",
141 _mesa_shader_stage_to_string(producer_stage),
142 output->name,
143 (output->data.invariant) ? "has" : "lacks",
144 _mesa_shader_stage_to_string(consumer_stage),
145 (input->data.invariant) ? "has" : "lacks");
146 return;
147 }
148
149 /* GLSL >= 4.40 removes text requiring interpolation qualifiers
150 * to match cross stage, they must only match within the same stage.
151 *
152 * From page 84 (page 90 of the PDF) of the GLSL 4.40 spec:
153 *
154 * "It is a link-time error if, within the same stage, the interpolation
155 * qualifiers of variables of the same name do not match.
156 *
157 */
158 if (input->data.interpolation != output->data.interpolation &&
159 prog->Version < 440) {
160 linker_error(prog,
161 "%s shader output `%s' specifies %s "
162 "interpolation qualifier, "
163 "but %s shader input specifies %s "
164 "interpolation qualifier\n",
165 _mesa_shader_stage_to_string(producer_stage),
166 output->name,
167 interpolation_string(output->data.interpolation),
168 _mesa_shader_stage_to_string(consumer_stage),
169 interpolation_string(input->data.interpolation));
170 return;
171 }
172 }
173
174 /**
175 * Validate front and back color outputs against single color input
176 */
177 static void
178 cross_validate_front_and_back_color(struct gl_shader_program *prog,
179 const ir_variable *input,
180 const ir_variable *front_color,
181 const ir_variable *back_color,
182 gl_shader_stage consumer_stage,
183 gl_shader_stage producer_stage)
184 {
185 if (front_color != NULL && front_color->data.assigned)
186 cross_validate_types_and_qualifiers(prog, input, front_color,
187 consumer_stage, producer_stage);
188
189 if (back_color != NULL && back_color->data.assigned)
190 cross_validate_types_and_qualifiers(prog, input, back_color,
191 consumer_stage, producer_stage);
192 }
193
194 /**
195 * Validate that outputs from one stage match inputs of another
196 */
197 void
198 cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
199 gl_shader *producer, gl_shader *consumer)
200 {
201 glsl_symbol_table parameters;
202 ir_variable *explicit_locations[MAX_VARYING] = { NULL, };
203
204 /* Find all shader outputs in the "producer" stage.
205 */
206 foreach_in_list(ir_instruction, node, producer->ir) {
207 ir_variable *const var = node->as_variable();
208
209 if ((var == NULL) || (var->data.mode != ir_var_shader_out))
210 continue;
211
212 if (!var->data.explicit_location
213 || var->data.location < VARYING_SLOT_VAR0)
214 parameters.add_variable(var);
215 else {
216 /* User-defined varyings with explicit locations are handled
217 * differently because they do not need to have matching names.
218 */
219 const unsigned idx = var->data.location - VARYING_SLOT_VAR0;
220
221 if (explicit_locations[idx] != NULL) {
222 linker_error(prog,
223 "%s shader has multiple outputs explicitly "
224 "assigned to location %d\n",
225 _mesa_shader_stage_to_string(producer->Stage),
226 idx);
227 return;
228 }
229
230 explicit_locations[idx] = var;
231 }
232 }
233
234
235 /* Find all shader inputs in the "consumer" stage. Any variables that have
236 * matching outputs already in the symbol table must have the same type and
237 * qualifiers.
238 *
239 * Exception: if the consumer is the geometry shader, then the inputs
240 * should be arrays and the type of the array element should match the type
241 * of the corresponding producer output.
242 */
243 foreach_in_list(ir_instruction, node, consumer->ir) {
244 ir_variable *const input = node->as_variable();
245
246 if ((input == NULL) || (input->data.mode != ir_var_shader_in))
247 continue;
248
249 if (strcmp(input->name, "gl_Color") == 0 && input->data.used) {
250 const ir_variable *const front_color =
251 parameters.get_variable("gl_FrontColor");
252
253 const ir_variable *const back_color =
254 parameters.get_variable("gl_BackColor");
255
256 cross_validate_front_and_back_color(prog, input,
257 front_color, back_color,
258 consumer->Stage, producer->Stage);
259 } else if (strcmp(input->name, "gl_SecondaryColor") == 0 && input->data.used) {
260 const ir_variable *const front_color =
261 parameters.get_variable("gl_FrontSecondaryColor");
262
263 const ir_variable *const back_color =
264 parameters.get_variable("gl_BackSecondaryColor");
265
266 cross_validate_front_and_back_color(prog, input,
267 front_color, back_color,
268 consumer->Stage, producer->Stage);
269 } else {
270 /* The rules for connecting inputs and outputs change in the presence
271 * of explicit locations. In this case, we no longer care about the
272 * names of the variables. Instead, we care only about the
273 * explicitly assigned location.
274 */
275 ir_variable *output = NULL;
276 if (input->data.explicit_location
277 && input->data.location >= VARYING_SLOT_VAR0) {
278 output = explicit_locations[input->data.location - VARYING_SLOT_VAR0];
279
280 if (output == NULL) {
281 linker_error(prog,
282 "%s shader input `%s' with explicit location "
283 "has no matching output\n",
284 _mesa_shader_stage_to_string(consumer->Stage),
285 input->name);
286 }
287 } else {
288 output = parameters.get_variable(input->name);
289 }
290
291 if (output != NULL) {
292 cross_validate_types_and_qualifiers(prog, input, output,
293 consumer->Stage, producer->Stage);
294 } else {
295 /* Check for input vars with unmatched output vars in prev stage
296 * taking into account that interface blocks could have a matching
297 * output but with different name, so we ignore them.
298 */
299 assert(!input->data.assigned);
300 if (input->data.used && !input->get_interface_type() &&
301 !input->data.explicit_location && !prog->SeparateShader)
302 linker_error(prog,
303 "%s shader input `%s' "
304 "has no matching output in the previous stage\n",
305 _mesa_shader_stage_to_string(consumer->Stage),
306 input->name);
307 }
308 }
309 }
310 }
311
312
313 /**
314 * Initialize this object based on a string that was passed to
315 * glTransformFeedbackVaryings.
316 *
317 * If the input is mal-formed, this call still succeeds, but it sets
318 * this->var_name to a mal-formed input, so tfeedback_decl::find_output_var()
319 * will fail to find any matching variable.
320 */
321 void
322 tfeedback_decl::init(struct gl_context *ctx, const void *mem_ctx,
323 const char *input)
324 {
325 /* We don't have to be pedantic about what is a valid GLSL variable name,
326 * because any variable with an invalid name can't exist in the IR anyway.
327 */
328
329 this->location = -1;
330 this->orig_name = input;
331 this->lowered_builtin_array_variable = none;
332 this->skip_components = 0;
333 this->next_buffer_separator = false;
334 this->matched_candidate = NULL;
335 this->stream_id = 0;
336
337 if (ctx->Extensions.ARB_transform_feedback3) {
338 /* Parse gl_NextBuffer. */
339 if (strcmp(input, "gl_NextBuffer") == 0) {
340 this->next_buffer_separator = true;
341 return;
342 }
343
344 /* Parse gl_SkipComponents. */
345 if (strcmp(input, "gl_SkipComponents1") == 0)
346 this->skip_components = 1;
347 else if (strcmp(input, "gl_SkipComponents2") == 0)
348 this->skip_components = 2;
349 else if (strcmp(input, "gl_SkipComponents3") == 0)
350 this->skip_components = 3;
351 else if (strcmp(input, "gl_SkipComponents4") == 0)
352 this->skip_components = 4;
353
354 if (this->skip_components)
355 return;
356 }
357
358 /* Parse a declaration. */
359 const char *base_name_end;
360 long subscript = parse_program_resource_name(input, &base_name_end);
361 this->var_name = ralloc_strndup(mem_ctx, input, base_name_end - input);
362 if (this->var_name == NULL) {
363 _mesa_error_no_memory(__func__);
364 return;
365 }
366
367 if (subscript >= 0) {
368 this->array_subscript = subscript;
369 this->is_subscripted = true;
370 } else {
371 this->is_subscripted = false;
372 }
373
374 /* For drivers that lower gl_ClipDistance to gl_ClipDistanceMESA, this
375 * class must behave specially to account for the fact that gl_ClipDistance
376 * is converted from a float[8] to a vec4[2].
377 */
378 if (ctx->Const.ShaderCompilerOptions[MESA_SHADER_VERTEX].LowerClipDistance &&
379 strcmp(this->var_name, "gl_ClipDistance") == 0) {
380 this->lowered_builtin_array_variable = clip_distance;
381 }
382
383 if (ctx->Const.LowerTessLevel &&
384 (strcmp(this->var_name, "gl_TessLevelOuter") == 0))
385 this->lowered_builtin_array_variable = tess_level_outer;
386 if (ctx->Const.LowerTessLevel &&
387 (strcmp(this->var_name, "gl_TessLevelInner") == 0))
388 this->lowered_builtin_array_variable = tess_level_inner;
389 }
390
391
392 /**
393 * Determine whether two tfeedback_decl objects refer to the same variable and
394 * array index (if applicable).
395 */
396 bool
397 tfeedback_decl::is_same(const tfeedback_decl &x, const tfeedback_decl &y)
398 {
399 assert(x.is_varying() && y.is_varying());
400
401 if (strcmp(x.var_name, y.var_name) != 0)
402 return false;
403 if (x.is_subscripted != y.is_subscripted)
404 return false;
405 if (x.is_subscripted && x.array_subscript != y.array_subscript)
406 return false;
407 return true;
408 }
409
410
411 /**
412 * Assign a location and stream ID for this tfeedback_decl object based on the
413 * transform feedback candidate found by find_candidate.
414 *
415 * If an error occurs, the error is reported through linker_error() and false
416 * is returned.
417 */
418 bool
419 tfeedback_decl::assign_location(struct gl_context *ctx,
420 struct gl_shader_program *prog)
421 {
422 assert(this->is_varying());
423
424 unsigned fine_location
425 = this->matched_candidate->toplevel_var->data.location * 4
426 + this->matched_candidate->toplevel_var->data.location_frac
427 + this->matched_candidate->offset;
428
429 if (this->matched_candidate->type->is_array()) {
430 /* Array variable */
431 const unsigned matrix_cols =
432 this->matched_candidate->type->fields.array->matrix_columns;
433 const unsigned vector_elements =
434 this->matched_candidate->type->fields.array->vector_elements;
435 const unsigned dmul =
436 this->matched_candidate->type->fields.array->is_double() ? 2 : 1;
437 unsigned actual_array_size;
438 switch (this->lowered_builtin_array_variable) {
439 case clip_distance:
440 actual_array_size = prog->LastClipDistanceArraySize;
441 break;
442 case tess_level_outer:
443 actual_array_size = 4;
444 break;
445 case tess_level_inner:
446 actual_array_size = 2;
447 break;
448 case none:
449 default:
450 actual_array_size = this->matched_candidate->type->array_size();
451 break;
452 }
453
454 if (this->is_subscripted) {
455 /* Check array bounds. */
456 if (this->array_subscript >= actual_array_size) {
457 linker_error(prog, "Transform feedback varying %s has index "
458 "%i, but the array size is %u.",
459 this->orig_name, this->array_subscript,
460 actual_array_size);
461 return false;
462 }
463 unsigned array_elem_size = this->lowered_builtin_array_variable ?
464 1 : vector_elements * matrix_cols * dmul;
465 fine_location += array_elem_size * this->array_subscript;
466 this->size = 1;
467 } else {
468 this->size = actual_array_size;
469 }
470 this->vector_elements = vector_elements;
471 this->matrix_columns = matrix_cols;
472 if (this->lowered_builtin_array_variable)
473 this->type = GL_FLOAT;
474 else
475 this->type = this->matched_candidate->type->fields.array->gl_type;
476 } else {
477 /* Regular variable (scalar, vector, or matrix) */
478 if (this->is_subscripted) {
479 linker_error(prog, "Transform feedback varying %s requested, "
480 "but %s is not an array.",
481 this->orig_name, this->var_name);
482 return false;
483 }
484 this->size = 1;
485 this->vector_elements = this->matched_candidate->type->vector_elements;
486 this->matrix_columns = this->matched_candidate->type->matrix_columns;
487 this->type = this->matched_candidate->type->gl_type;
488 }
489 this->location = fine_location / 4;
490 this->location_frac = fine_location % 4;
491
492 /* From GL_EXT_transform_feedback:
493 * A program will fail to link if:
494 *
495 * * the total number of components to capture in any varying
496 * variable in <varyings> is greater than the constant
497 * MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT and the
498 * buffer mode is SEPARATE_ATTRIBS_EXT;
499 */
500 if (prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS &&
501 this->num_components() >
502 ctx->Const.MaxTransformFeedbackSeparateComponents) {
503 linker_error(prog, "Transform feedback varying %s exceeds "
504 "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS.",
505 this->orig_name);
506 return false;
507 }
508
509 /* Only transform feedback varyings can be assigned to non-zero streams,
510 * so assign the stream id here.
511 */
512 this->stream_id = this->matched_candidate->toplevel_var->data.stream;
513
514 return true;
515 }
516
517
518 unsigned
519 tfeedback_decl::get_num_outputs() const
520 {
521 if (!this->is_varying()) {
522 return 0;
523 }
524 return (this->num_components() + this->location_frac + 3)/4;
525 }
526
527
528 /**
529 * Update gl_transform_feedback_info to reflect this tfeedback_decl.
530 *
531 * If an error occurs, the error is reported through linker_error() and false
532 * is returned.
533 */
534 bool
535 tfeedback_decl::store(struct gl_context *ctx, struct gl_shader_program *prog,
536 struct gl_transform_feedback_info *info,
537 unsigned buffer, const unsigned max_outputs) const
538 {
539 assert(!this->next_buffer_separator);
540
541 /* Handle gl_SkipComponents. */
542 if (this->skip_components) {
543 info->BufferStride[buffer] += this->skip_components;
544 return true;
545 }
546
547 /* From GL_EXT_transform_feedback:
548 * A program will fail to link if:
549 *
550 * * the total number of components to capture is greater than
551 * the constant MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT
552 * and the buffer mode is INTERLEAVED_ATTRIBS_EXT.
553 */
554 if (prog->TransformFeedback.BufferMode == GL_INTERLEAVED_ATTRIBS &&
555 info->BufferStride[buffer] + this->num_components() >
556 ctx->Const.MaxTransformFeedbackInterleavedComponents) {
557 linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
558 "limit has been exceeded.");
559 return false;
560 }
561
562 unsigned location = this->location;
563 unsigned location_frac = this->location_frac;
564 unsigned num_components = this->num_components();
565 while (num_components > 0) {
566 unsigned output_size = MIN2(num_components, 4 - location_frac);
567 assert(info->NumOutputs < max_outputs);
568 info->Outputs[info->NumOutputs].ComponentOffset = location_frac;
569 info->Outputs[info->NumOutputs].OutputRegister = location;
570 info->Outputs[info->NumOutputs].NumComponents = output_size;
571 info->Outputs[info->NumOutputs].StreamId = stream_id;
572 info->Outputs[info->NumOutputs].OutputBuffer = buffer;
573 info->Outputs[info->NumOutputs].DstOffset = info->BufferStride[buffer];
574 ++info->NumOutputs;
575 info->BufferStride[buffer] += output_size;
576 info->BufferStream[buffer] = this->stream_id;
577 num_components -= output_size;
578 location++;
579 location_frac = 0;
580 }
581
582 info->Varyings[info->NumVarying].Name = ralloc_strdup(prog, this->orig_name);
583 info->Varyings[info->NumVarying].Type = this->type;
584 info->Varyings[info->NumVarying].Size = this->size;
585 info->NumVarying++;
586
587 return true;
588 }
589
590
591 const tfeedback_candidate *
592 tfeedback_decl::find_candidate(gl_shader_program *prog,
593 hash_table *tfeedback_candidates)
594 {
595 const char *name = this->var_name;
596 switch (this->lowered_builtin_array_variable) {
597 case none:
598 name = this->var_name;
599 break;
600 case clip_distance:
601 name = "gl_ClipDistanceMESA";
602 break;
603 case tess_level_outer:
604 name = "gl_TessLevelOuterMESA";
605 break;
606 case tess_level_inner:
607 name = "gl_TessLevelInnerMESA";
608 break;
609 }
610 this->matched_candidate = (const tfeedback_candidate *)
611 hash_table_find(tfeedback_candidates, name);
612 if (!this->matched_candidate) {
613 /* From GL_EXT_transform_feedback:
614 * A program will fail to link if:
615 *
616 * * any variable name specified in the <varyings> array is not
617 * declared as an output in the geometry shader (if present) or
618 * the vertex shader (if no geometry shader is present);
619 */
620 linker_error(prog, "Transform feedback varying %s undeclared.",
621 this->orig_name);
622 }
623 return this->matched_candidate;
624 }
625
626
627 /**
628 * Parse all the transform feedback declarations that were passed to
629 * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
630 *
631 * If an error occurs, the error is reported through linker_error() and false
632 * is returned.
633 */
634 bool
635 parse_tfeedback_decls(struct gl_context *ctx, struct gl_shader_program *prog,
636 const void *mem_ctx, unsigned num_names,
637 char **varying_names, tfeedback_decl *decls)
638 {
639 for (unsigned i = 0; i < num_names; ++i) {
640 decls[i].init(ctx, mem_ctx, varying_names[i]);
641
642 if (!decls[i].is_varying())
643 continue;
644
645 /* From GL_EXT_transform_feedback:
646 * A program will fail to link if:
647 *
648 * * any two entries in the <varyings> array specify the same varying
649 * variable;
650 *
651 * We interpret this to mean "any two entries in the <varyings> array
652 * specify the same varying variable and array index", since transform
653 * feedback of arrays would be useless otherwise.
654 */
655 for (unsigned j = 0; j < i; ++j) {
656 if (!decls[j].is_varying())
657 continue;
658
659 if (tfeedback_decl::is_same(decls[i], decls[j])) {
660 linker_error(prog, "Transform feedback varying %s specified "
661 "more than once.", varying_names[i]);
662 return false;
663 }
664 }
665 }
666 return true;
667 }
668
669
670 /**
671 * Store transform feedback location assignments into
672 * prog->LinkedTransformFeedback based on the data stored in tfeedback_decls.
673 *
674 * If an error occurs, the error is reported through linker_error() and false
675 * is returned.
676 */
677 bool
678 store_tfeedback_info(struct gl_context *ctx, struct gl_shader_program *prog,
679 unsigned num_tfeedback_decls,
680 tfeedback_decl *tfeedback_decls)
681 {
682 bool separate_attribs_mode =
683 prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS;
684
685 ralloc_free(prog->LinkedTransformFeedback.Varyings);
686 ralloc_free(prog->LinkedTransformFeedback.Outputs);
687
688 memset(&prog->LinkedTransformFeedback, 0,
689 sizeof(prog->LinkedTransformFeedback));
690
691 prog->LinkedTransformFeedback.Varyings =
692 rzalloc_array(prog,
693 struct gl_transform_feedback_varying_info,
694 num_tfeedback_decls);
695
696 unsigned num_outputs = 0;
697 for (unsigned i = 0; i < num_tfeedback_decls; ++i)
698 num_outputs += tfeedback_decls[i].get_num_outputs();
699
700 prog->LinkedTransformFeedback.Outputs =
701 rzalloc_array(prog,
702 struct gl_transform_feedback_output,
703 num_outputs);
704
705 unsigned num_buffers = 0;
706
707 if (separate_attribs_mode) {
708 /* GL_SEPARATE_ATTRIBS */
709 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
710 if (!tfeedback_decls[i].store(ctx, prog, &prog->LinkedTransformFeedback,
711 num_buffers, num_outputs))
712 return false;
713
714 num_buffers++;
715 }
716 }
717 else {
718 /* GL_INVERLEAVED_ATTRIBS */
719 int buffer_stream_id = -1;
720 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
721 if (tfeedback_decls[i].is_next_buffer_separator()) {
722 num_buffers++;
723 buffer_stream_id = -1;
724 continue;
725 } else if (buffer_stream_id == -1) {
726 /* First varying writing to this buffer: remember its stream */
727 buffer_stream_id = (int) tfeedback_decls[i].get_stream_id();
728 } else if (buffer_stream_id !=
729 (int) tfeedback_decls[i].get_stream_id()) {
730 /* Varying writes to the same buffer from a different stream */
731 linker_error(prog,
732 "Transform feedback can't capture varyings belonging "
733 "to different vertex streams in a single buffer. "
734 "Varying %s writes to buffer from stream %u, other "
735 "varyings in the same buffer write from stream %u.",
736 tfeedback_decls[i].name(),
737 tfeedback_decls[i].get_stream_id(),
738 buffer_stream_id);
739 return false;
740 }
741
742 if (!tfeedback_decls[i].store(ctx, prog,
743 &prog->LinkedTransformFeedback,
744 num_buffers, num_outputs))
745 return false;
746 }
747 num_buffers++;
748 }
749
750 assert(prog->LinkedTransformFeedback.NumOutputs == num_outputs);
751
752 prog->LinkedTransformFeedback.NumBuffers = num_buffers;
753 return true;
754 }
755
756 namespace {
757
758 /**
759 * Data structure recording the relationship between outputs of one shader
760 * stage (the "producer") and inputs of another (the "consumer").
761 */
762 class varying_matches
763 {
764 public:
765 varying_matches(bool disable_varying_packing,
766 gl_shader_stage producer_stage,
767 gl_shader_stage consumer_stage);
768 ~varying_matches();
769 void record(ir_variable *producer_var, ir_variable *consumer_var);
770 unsigned assign_locations(uint64_t reserved_slots, bool separate_shader);
771 void store_locations() const;
772
773 private:
774 /**
775 * If true, this driver disables varying packing, so all varyings need to
776 * be aligned on slot boundaries, and take up a number of slots equal to
777 * their number of matrix columns times their array size.
778 */
779 const bool disable_varying_packing;
780
781 /**
782 * Enum representing the order in which varyings are packed within a
783 * packing class.
784 *
785 * Currently we pack vec4's first, then vec2's, then scalar values, then
786 * vec3's. This order ensures that the only vectors that are at risk of
787 * having to be "double parked" (split between two adjacent varying slots)
788 * are the vec3's.
789 */
790 enum packing_order_enum {
791 PACKING_ORDER_VEC4,
792 PACKING_ORDER_VEC2,
793 PACKING_ORDER_SCALAR,
794 PACKING_ORDER_VEC3,
795 };
796
797 static unsigned compute_packing_class(const ir_variable *var);
798 static packing_order_enum compute_packing_order(const ir_variable *var);
799 static int match_comparator(const void *x_generic, const void *y_generic);
800
801 /**
802 * Structure recording the relationship between a single producer output
803 * and a single consumer input.
804 */
805 struct match {
806 /**
807 * Packing class for this varying, computed by compute_packing_class().
808 */
809 unsigned packing_class;
810
811 /**
812 * Packing order for this varying, computed by compute_packing_order().
813 */
814 packing_order_enum packing_order;
815 unsigned num_components;
816
817 /**
818 * The output variable in the producer stage.
819 */
820 ir_variable *producer_var;
821
822 /**
823 * The input variable in the consumer stage.
824 */
825 ir_variable *consumer_var;
826
827 /**
828 * The location which has been assigned for this varying. This is
829 * expressed in multiples of a float, with the first generic varying
830 * (i.e. the one referred to by VARYING_SLOT_VAR0) represented by the
831 * value 0.
832 */
833 unsigned generic_location;
834 } *matches;
835
836 /**
837 * The number of elements in the \c matches array that are currently in
838 * use.
839 */
840 unsigned num_matches;
841
842 /**
843 * The number of elements that were set aside for the \c matches array when
844 * it was allocated.
845 */
846 unsigned matches_capacity;
847
848 gl_shader_stage producer_stage;
849 gl_shader_stage consumer_stage;
850 };
851
852 } /* anonymous namespace */
853
854 varying_matches::varying_matches(bool disable_varying_packing,
855 gl_shader_stage producer_stage,
856 gl_shader_stage consumer_stage)
857 : disable_varying_packing(disable_varying_packing),
858 producer_stage(producer_stage),
859 consumer_stage(consumer_stage)
860 {
861 /* Note: this initial capacity is rather arbitrarily chosen to be large
862 * enough for many cases without wasting an unreasonable amount of space.
863 * varying_matches::record() will resize the array if there are more than
864 * this number of varyings.
865 */
866 this->matches_capacity = 8;
867 this->matches = (match *)
868 malloc(sizeof(*this->matches) * this->matches_capacity);
869 this->num_matches = 0;
870 }
871
872
873 varying_matches::~varying_matches()
874 {
875 free(this->matches);
876 }
877
878
879 /**
880 * Record the given producer/consumer variable pair in the list of variables
881 * that should later be assigned locations.
882 *
883 * It is permissible for \c consumer_var to be NULL (this happens if a
884 * variable is output by the producer and consumed by transform feedback, but
885 * not consumed by the consumer).
886 *
887 * If \c producer_var has already been paired up with a consumer_var, or
888 * producer_var is part of fixed pipeline functionality (and hence already has
889 * a location assigned), this function has no effect.
890 *
891 * Note: as a side effect this function may change the interpolation type of
892 * \c producer_var, but only when the change couldn't possibly affect
893 * rendering.
894 */
895 void
896 varying_matches::record(ir_variable *producer_var, ir_variable *consumer_var)
897 {
898 assert(producer_var != NULL || consumer_var != NULL);
899
900 if ((producer_var && (!producer_var->data.is_unmatched_generic_inout ||
901 producer_var->data.explicit_location)) ||
902 (consumer_var && (!consumer_var->data.is_unmatched_generic_inout ||
903 consumer_var->data.explicit_location))) {
904 /* Either a location already exists for this variable (since it is part
905 * of fixed functionality), or it has already been recorded as part of a
906 * previous match.
907 */
908 return;
909 }
910
911 if ((consumer_var == NULL && producer_var->type->contains_integer()) ||
912 consumer_stage != MESA_SHADER_FRAGMENT) {
913 /* Since this varying is not being consumed by the fragment shader, its
914 * interpolation type varying cannot possibly affect rendering. Also,
915 * this variable is non-flat and is (or contains) an integer.
916 *
917 * lower_packed_varyings requires all integer varyings to flat,
918 * regardless of where they appear. We can trivially satisfy that
919 * requirement by changing the interpolation type to flat here.
920 */
921 if (producer_var) {
922 producer_var->data.centroid = false;
923 producer_var->data.sample = false;
924 producer_var->data.interpolation = INTERP_QUALIFIER_FLAT;
925 }
926
927 if (consumer_var) {
928 consumer_var->data.centroid = false;
929 consumer_var->data.sample = false;
930 consumer_var->data.interpolation = INTERP_QUALIFIER_FLAT;
931 }
932 }
933
934 if (this->num_matches == this->matches_capacity) {
935 this->matches_capacity *= 2;
936 this->matches = (match *)
937 realloc(this->matches,
938 sizeof(*this->matches) * this->matches_capacity);
939 }
940
941 const ir_variable *const var = (producer_var != NULL)
942 ? producer_var : consumer_var;
943
944 this->matches[this->num_matches].packing_class
945 = this->compute_packing_class(var);
946 this->matches[this->num_matches].packing_order
947 = this->compute_packing_order(var);
948 if (this->disable_varying_packing) {
949 const struct glsl_type *type = var->type;
950 unsigned slots;
951
952 /* Some shader stages have 2-dimensional varyings. Use the inner type. */
953 if (!var->data.patch &&
954 ((var == producer_var && producer_stage == MESA_SHADER_TESS_CTRL) ||
955 (var == consumer_var && (consumer_stage == MESA_SHADER_TESS_CTRL ||
956 consumer_stage == MESA_SHADER_TESS_EVAL ||
957 consumer_stage == MESA_SHADER_GEOMETRY)))) {
958 assert(type->is_array());
959 type = type->fields.array;
960 }
961
962 slots = type->count_attribute_slots(false);
963 this->matches[this->num_matches].num_components = slots * 4;
964 } else {
965 this->matches[this->num_matches].num_components
966 = var->type->component_slots();
967 }
968 this->matches[this->num_matches].producer_var = producer_var;
969 this->matches[this->num_matches].consumer_var = consumer_var;
970 this->num_matches++;
971 if (producer_var)
972 producer_var->data.is_unmatched_generic_inout = 0;
973 if (consumer_var)
974 consumer_var->data.is_unmatched_generic_inout = 0;
975 }
976
977
978 /**
979 * Choose locations for all of the variable matches that were previously
980 * passed to varying_matches::record().
981 */
982 unsigned
983 varying_matches::assign_locations(uint64_t reserved_slots, bool separate_shader)
984 {
985 /* We disable varying sorting for separate shader programs for the
986 * following reasons:
987 *
988 * 1/ All programs must sort the code in the same order to guarantee the
989 * interface matching. However varying_matches::record() will change the
990 * interpolation qualifier of some stages.
991 *
992 * 2/ GLSL version 4.50 removes the matching constrain on the interpolation
993 * qualifier.
994 *
995 * From Section 4.5 (Interpolation Qualifiers) of the GLSL 4.40 spec:
996 *
997 * "The type and presence of interpolation qualifiers of variables with
998 * the same name declared in all linked shaders for the same cross-stage
999 * interface must match, otherwise the link command will fail.
1000 *
1001 * When comparing an output from one stage to an input of a subsequent
1002 * stage, the input and output don't match if their interpolation
1003 * qualifiers (or lack thereof) are not the same."
1004 *
1005 * "It is a link-time error if, within the same stage, the interpolation
1006 * qualifiers of variables of the same name do not match."
1007 */
1008 if (!separate_shader) {
1009 /* Sort varying matches into an order that makes them easy to pack. */
1010 qsort(this->matches, this->num_matches, sizeof(*this->matches),
1011 &varying_matches::match_comparator);
1012 }
1013
1014 unsigned generic_location = 0;
1015 unsigned generic_patch_location = MAX_VARYING*4;
1016
1017 for (unsigned i = 0; i < this->num_matches; i++) {
1018 unsigned *location = &generic_location;
1019
1020 if ((this->matches[i].consumer_var &&
1021 this->matches[i].consumer_var->data.patch) ||
1022 (this->matches[i].producer_var &&
1023 this->matches[i].producer_var->data.patch))
1024 location = &generic_patch_location;
1025
1026 /* Advance to the next slot if this varying has a different packing
1027 * class than the previous one, and we're not already on a slot
1028 * boundary.
1029 */
1030 if (i > 0 &&
1031 this->matches[i - 1].packing_class
1032 != this->matches[i].packing_class) {
1033 *location = ALIGN(*location, 4);
1034 }
1035 while ((*location < MAX_VARYING * 4u) &&
1036 (reserved_slots & (1u << *location / 4u))) {
1037 *location = ALIGN(*location + 1, 4);
1038 }
1039
1040 this->matches[i].generic_location = *location;
1041
1042 *location += this->matches[i].num_components;
1043 }
1044
1045 return (generic_location + 3) / 4;
1046 }
1047
1048
1049 /**
1050 * Update the producer and consumer shaders to reflect the locations
1051 * assignments that were made by varying_matches::assign_locations().
1052 */
1053 void
1054 varying_matches::store_locations() const
1055 {
1056 for (unsigned i = 0; i < this->num_matches; i++) {
1057 ir_variable *producer_var = this->matches[i].producer_var;
1058 ir_variable *consumer_var = this->matches[i].consumer_var;
1059 unsigned generic_location = this->matches[i].generic_location;
1060 unsigned slot = generic_location / 4;
1061 unsigned offset = generic_location % 4;
1062
1063 if (producer_var) {
1064 producer_var->data.location = VARYING_SLOT_VAR0 + slot;
1065 producer_var->data.location_frac = offset;
1066 }
1067
1068 if (consumer_var) {
1069 assert(consumer_var->data.location == -1);
1070 consumer_var->data.location = VARYING_SLOT_VAR0 + slot;
1071 consumer_var->data.location_frac = offset;
1072 }
1073 }
1074 }
1075
1076
1077 /**
1078 * Compute the "packing class" of the given varying. This is an unsigned
1079 * integer with the property that two variables in the same packing class can
1080 * be safely backed into the same vec4.
1081 */
1082 unsigned
1083 varying_matches::compute_packing_class(const ir_variable *var)
1084 {
1085 /* Without help from the back-end, there is no way to pack together
1086 * variables with different interpolation types, because
1087 * lower_packed_varyings must choose exactly one interpolation type for
1088 * each packed varying it creates.
1089 *
1090 * However, we can safely pack together floats, ints, and uints, because:
1091 *
1092 * - varyings of base type "int" and "uint" must use the "flat"
1093 * interpolation type, which can only occur in GLSL 1.30 and above.
1094 *
1095 * - On platforms that support GLSL 1.30 and above, lower_packed_varyings
1096 * can store flat floats as ints without losing any information (using
1097 * the ir_unop_bitcast_* opcodes).
1098 *
1099 * Therefore, the packing class depends only on the interpolation type.
1100 */
1101 unsigned packing_class = var->data.centroid | (var->data.sample << 1) |
1102 (var->data.patch << 2);
1103 packing_class *= 4;
1104 packing_class += var->data.interpolation;
1105 return packing_class;
1106 }
1107
1108
1109 /**
1110 * Compute the "packing order" of the given varying. This is a sort key we
1111 * use to determine when to attempt to pack the given varying relative to
1112 * other varyings in the same packing class.
1113 */
1114 varying_matches::packing_order_enum
1115 varying_matches::compute_packing_order(const ir_variable *var)
1116 {
1117 const glsl_type *element_type = var->type;
1118
1119 while (element_type->base_type == GLSL_TYPE_ARRAY) {
1120 element_type = element_type->fields.array;
1121 }
1122
1123 switch (element_type->component_slots() % 4) {
1124 case 1: return PACKING_ORDER_SCALAR;
1125 case 2: return PACKING_ORDER_VEC2;
1126 case 3: return PACKING_ORDER_VEC3;
1127 case 0: return PACKING_ORDER_VEC4;
1128 default:
1129 assert(!"Unexpected value of vector_elements");
1130 return PACKING_ORDER_VEC4;
1131 }
1132 }
1133
1134
1135 /**
1136 * Comparison function passed to qsort() to sort varyings by packing_class and
1137 * then by packing_order.
1138 */
1139 int
1140 varying_matches::match_comparator(const void *x_generic, const void *y_generic)
1141 {
1142 const match *x = (const match *) x_generic;
1143 const match *y = (const match *) y_generic;
1144
1145 if (x->packing_class != y->packing_class)
1146 return x->packing_class - y->packing_class;
1147 return x->packing_order - y->packing_order;
1148 }
1149
1150
1151 /**
1152 * Is the given variable a varying variable to be counted against the
1153 * limit in ctx->Const.MaxVarying?
1154 * This includes variables such as texcoords, colors and generic
1155 * varyings, but excludes variables such as gl_FrontFacing and gl_FragCoord.
1156 */
1157 static bool
1158 var_counts_against_varying_limit(gl_shader_stage stage, const ir_variable *var)
1159 {
1160 /* Only fragment shaders will take a varying variable as an input */
1161 if (stage == MESA_SHADER_FRAGMENT &&
1162 var->data.mode == ir_var_shader_in) {
1163 switch (var->data.location) {
1164 case VARYING_SLOT_POS:
1165 case VARYING_SLOT_FACE:
1166 case VARYING_SLOT_PNTC:
1167 return false;
1168 default:
1169 return true;
1170 }
1171 }
1172 return false;
1173 }
1174
1175
1176 /**
1177 * Visitor class that generates tfeedback_candidate structs describing all
1178 * possible targets of transform feedback.
1179 *
1180 * tfeedback_candidate structs are stored in the hash table
1181 * tfeedback_candidates, which is passed to the constructor. This hash table
1182 * maps varying names to instances of the tfeedback_candidate struct.
1183 */
1184 class tfeedback_candidate_generator : public program_resource_visitor
1185 {
1186 public:
1187 tfeedback_candidate_generator(void *mem_ctx,
1188 hash_table *tfeedback_candidates)
1189 : mem_ctx(mem_ctx),
1190 tfeedback_candidates(tfeedback_candidates),
1191 toplevel_var(NULL),
1192 varying_floats(0)
1193 {
1194 }
1195
1196 void process(ir_variable *var)
1197 {
1198 this->toplevel_var = var;
1199 this->varying_floats = 0;
1200 if (var->is_interface_instance())
1201 program_resource_visitor::process(var->get_interface_type(),
1202 var->get_interface_type()->name);
1203 else
1204 program_resource_visitor::process(var);
1205 }
1206
1207 private:
1208 virtual void visit_field(const glsl_type *type, const char *name,
1209 bool row_major)
1210 {
1211 assert(!type->without_array()->is_record());
1212 assert(!type->without_array()->is_interface());
1213
1214 (void) row_major;
1215
1216 tfeedback_candidate *candidate
1217 = rzalloc(this->mem_ctx, tfeedback_candidate);
1218 candidate->toplevel_var = this->toplevel_var;
1219 candidate->type = type;
1220 candidate->offset = this->varying_floats;
1221 hash_table_insert(this->tfeedback_candidates, candidate,
1222 ralloc_strdup(this->mem_ctx, name));
1223 this->varying_floats += type->component_slots();
1224 }
1225
1226 /**
1227 * Memory context used to allocate hash table keys and values.
1228 */
1229 void * const mem_ctx;
1230
1231 /**
1232 * Hash table in which tfeedback_candidate objects should be stored.
1233 */
1234 hash_table * const tfeedback_candidates;
1235
1236 /**
1237 * Pointer to the toplevel variable that is being traversed.
1238 */
1239 ir_variable *toplevel_var;
1240
1241 /**
1242 * Total number of varying floats that have been visited so far. This is
1243 * used to determine the offset to each varying within the toplevel
1244 * variable.
1245 */
1246 unsigned varying_floats;
1247 };
1248
1249
1250 namespace linker {
1251
1252 bool
1253 populate_consumer_input_sets(void *mem_ctx, exec_list *ir,
1254 hash_table *consumer_inputs,
1255 hash_table *consumer_interface_inputs,
1256 ir_variable *consumer_inputs_with_locations[VARYING_SLOT_TESS_MAX])
1257 {
1258 memset(consumer_inputs_with_locations,
1259 0,
1260 sizeof(consumer_inputs_with_locations[0]) * VARYING_SLOT_TESS_MAX);
1261
1262 foreach_in_list(ir_instruction, node, ir) {
1263 ir_variable *const input_var = node->as_variable();
1264
1265 if ((input_var != NULL) && (input_var->data.mode == ir_var_shader_in)) {
1266 if (input_var->type->is_interface())
1267 return false;
1268
1269 if (input_var->data.explicit_location) {
1270 /* assign_varying_locations only cares about finding the
1271 * ir_variable at the start of a contiguous location block.
1272 *
1273 * - For !producer, consumer_inputs_with_locations isn't used.
1274 *
1275 * - For !consumer, consumer_inputs_with_locations is empty.
1276 *
1277 * For consumer && producer, if you were trying to set some
1278 * ir_variable to the middle of a location block on the other side
1279 * of producer/consumer, cross_validate_outputs_to_inputs() should
1280 * be link-erroring due to either type mismatch or location
1281 * overlaps. If the variables do match up, then they've got a
1282 * matching data.location and you only looked at
1283 * consumer_inputs_with_locations[var->data.location], not any
1284 * following entries for the array/structure.
1285 */
1286 consumer_inputs_with_locations[input_var->data.location] =
1287 input_var;
1288 } else if (input_var->get_interface_type() != NULL) {
1289 char *const iface_field_name =
1290 ralloc_asprintf(mem_ctx, "%s.%s",
1291 input_var->get_interface_type()->name,
1292 input_var->name);
1293 hash_table_insert(consumer_interface_inputs, input_var,
1294 iface_field_name);
1295 } else {
1296 hash_table_insert(consumer_inputs, input_var,
1297 ralloc_strdup(mem_ctx, input_var->name));
1298 }
1299 }
1300 }
1301
1302 return true;
1303 }
1304
1305 /**
1306 * Find a variable from the consumer that "matches" the specified variable
1307 *
1308 * This function only finds inputs with names that match. There is no
1309 * validation (here) that the types, etc. are compatible.
1310 */
1311 ir_variable *
1312 get_matching_input(void *mem_ctx,
1313 const ir_variable *output_var,
1314 hash_table *consumer_inputs,
1315 hash_table *consumer_interface_inputs,
1316 ir_variable *consumer_inputs_with_locations[VARYING_SLOT_TESS_MAX])
1317 {
1318 ir_variable *input_var;
1319
1320 if (output_var->data.explicit_location) {
1321 input_var = consumer_inputs_with_locations[output_var->data.location];
1322 } else if (output_var->get_interface_type() != NULL) {
1323 char *const iface_field_name =
1324 ralloc_asprintf(mem_ctx, "%s.%s",
1325 output_var->get_interface_type()->name,
1326 output_var->name);
1327 input_var =
1328 (ir_variable *) hash_table_find(consumer_interface_inputs,
1329 iface_field_name);
1330 } else {
1331 input_var =
1332 (ir_variable *) hash_table_find(consumer_inputs, output_var->name);
1333 }
1334
1335 return (input_var == NULL || input_var->data.mode != ir_var_shader_in)
1336 ? NULL : input_var;
1337 }
1338
1339 }
1340
1341 static int
1342 io_variable_cmp(const void *_a, const void *_b)
1343 {
1344 const ir_variable *const a = *(const ir_variable **) _a;
1345 const ir_variable *const b = *(const ir_variable **) _b;
1346
1347 if (a->data.explicit_location && b->data.explicit_location)
1348 return b->data.location - a->data.location;
1349
1350 if (a->data.explicit_location && !b->data.explicit_location)
1351 return 1;
1352
1353 if (!a->data.explicit_location && b->data.explicit_location)
1354 return -1;
1355
1356 return -strcmp(a->name, b->name);
1357 }
1358
1359 /**
1360 * Sort the shader IO variables into canonical order
1361 */
1362 static void
1363 canonicalize_shader_io(exec_list *ir, enum ir_variable_mode io_mode)
1364 {
1365 ir_variable *var_table[MAX_PROGRAM_OUTPUTS * 4];
1366 unsigned num_variables = 0;
1367
1368 foreach_in_list(ir_instruction, node, ir) {
1369 ir_variable *const var = node->as_variable();
1370
1371 if (var == NULL || var->data.mode != io_mode)
1372 continue;
1373
1374 /* If we have already encountered more I/O variables that could
1375 * successfully link, bail.
1376 */
1377 if (num_variables == ARRAY_SIZE(var_table))
1378 return;
1379
1380 var_table[num_variables++] = var;
1381 }
1382
1383 if (num_variables == 0)
1384 return;
1385
1386 /* Sort the list in reverse order (io_variable_cmp handles this). Later
1387 * we're going to push the variables on to the IR list as a stack, so we
1388 * want the last variable (in canonical order) to be first in the list.
1389 */
1390 qsort(var_table, num_variables, sizeof(var_table[0]), io_variable_cmp);
1391
1392 /* Remove the variable from it's current location in the IR, and put it at
1393 * the front.
1394 */
1395 for (unsigned i = 0; i < num_variables; i++) {
1396 var_table[i]->remove();
1397 ir->push_head(var_table[i]);
1398 }
1399 }
1400
1401 /**
1402 * Generate a bitfield map of the explicit locations for shader varyings.
1403 *
1404 * In theory a 32 bits value will be enough but a 64 bits value is future proof.
1405 */
1406 uint64_t
1407 reserved_varying_slot(struct gl_shader *stage, ir_variable_mode io_mode)
1408 {
1409 assert(io_mode == ir_var_shader_in || io_mode == ir_var_shader_out);
1410 assert(MAX_VARYING <= 64); /* avoid an overflow of the returned value */
1411
1412 uint64_t slots = 0;
1413 int var_slot;
1414
1415 if (!stage)
1416 return slots;
1417
1418 foreach_in_list(ir_instruction, node, stage->ir) {
1419 ir_variable *const var = node->as_variable();
1420
1421 if (var == NULL || var->data.mode != io_mode || !var->data.explicit_location)
1422 continue;
1423
1424 var_slot = var->data.location - VARYING_SLOT_VAR0;
1425 if (var_slot >= 0 && var_slot < MAX_VARYING)
1426 slots |= 1u << var_slot;
1427 }
1428
1429 return slots;
1430 }
1431
1432
1433 /**
1434 * Assign locations for all variables that are produced in one pipeline stage
1435 * (the "producer") and consumed in the next stage (the "consumer").
1436 *
1437 * Variables produced by the producer may also be consumed by transform
1438 * feedback.
1439 *
1440 * \param num_tfeedback_decls is the number of declarations indicating
1441 * variables that may be consumed by transform feedback.
1442 *
1443 * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
1444 * representing the result of parsing the strings passed to
1445 * glTransformFeedbackVaryings(). assign_location() will be called for
1446 * each of these objects that matches one of the outputs of the
1447 * producer.
1448 *
1449 * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
1450 * be NULL. In this case, varying locations are assigned solely based on the
1451 * requirements of transform feedback.
1452 */
1453 bool
1454 assign_varying_locations(struct gl_context *ctx,
1455 void *mem_ctx,
1456 struct gl_shader_program *prog,
1457 gl_shader *producer, gl_shader *consumer,
1458 unsigned num_tfeedback_decls,
1459 tfeedback_decl *tfeedback_decls)
1460 {
1461 if (ctx->Const.DisableVaryingPacking) {
1462 /* Transform feedback code assumes varyings are packed, so if the driver
1463 * has disabled varying packing, make sure it does not support transform
1464 * feedback.
1465 */
1466 assert(!ctx->Extensions.EXT_transform_feedback);
1467 }
1468
1469 /* Tessellation shaders treat inputs and outputs as shared memory and can
1470 * access inputs and outputs of other invocations.
1471 * Therefore, they can't be lowered to temps easily (and definitely not
1472 * efficiently).
1473 */
1474 bool disable_varying_packing =
1475 ctx->Const.DisableVaryingPacking ||
1476 (consumer && consumer->Stage == MESA_SHADER_TESS_EVAL) ||
1477 (consumer && consumer->Stage == MESA_SHADER_TESS_CTRL) ||
1478 (producer && producer->Stage == MESA_SHADER_TESS_CTRL);
1479
1480 varying_matches matches(disable_varying_packing,
1481 producer ? producer->Stage : (gl_shader_stage)-1,
1482 consumer ? consumer->Stage : (gl_shader_stage)-1);
1483 hash_table *tfeedback_candidates
1484 = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare);
1485 hash_table *consumer_inputs
1486 = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare);
1487 hash_table *consumer_interface_inputs
1488 = hash_table_ctor(0, hash_table_string_hash, hash_table_string_compare);
1489 ir_variable *consumer_inputs_with_locations[VARYING_SLOT_TESS_MAX] = {
1490 NULL,
1491 };
1492
1493 unsigned consumer_vertices = 0;
1494 if (consumer && consumer->Stage == MESA_SHADER_GEOMETRY)
1495 consumer_vertices = prog->Geom.VerticesIn;
1496
1497 /* Operate in a total of four passes.
1498 *
1499 * 1. Sort inputs / outputs into a canonical order. This is necessary so
1500 * that inputs / outputs of separable shaders will be assigned
1501 * predictable locations regardless of the order in which declarations
1502 * appeared in the shader source.
1503 *
1504 * 2. Assign locations for any matching inputs and outputs.
1505 *
1506 * 3. Mark output variables in the producer that do not have locations as
1507 * not being outputs. This lets the optimizer eliminate them.
1508 *
1509 * 4. Mark input variables in the consumer that do not have locations as
1510 * not being inputs. This lets the optimizer eliminate them.
1511 */
1512 if (consumer)
1513 canonicalize_shader_io(consumer->ir, ir_var_shader_in);
1514
1515 if (producer)
1516 canonicalize_shader_io(producer->ir, ir_var_shader_out);
1517
1518 if (consumer
1519 && !linker::populate_consumer_input_sets(mem_ctx,
1520 consumer->ir,
1521 consumer_inputs,
1522 consumer_interface_inputs,
1523 consumer_inputs_with_locations)) {
1524 assert(!"populate_consumer_input_sets failed");
1525 hash_table_dtor(tfeedback_candidates);
1526 hash_table_dtor(consumer_inputs);
1527 hash_table_dtor(consumer_interface_inputs);
1528 return false;
1529 }
1530
1531 if (producer) {
1532 foreach_in_list(ir_instruction, node, producer->ir) {
1533 ir_variable *const output_var = node->as_variable();
1534
1535 if ((output_var == NULL) ||
1536 (output_var->data.mode != ir_var_shader_out))
1537 continue;
1538
1539 /* Only geometry shaders can use non-zero streams */
1540 assert(output_var->data.stream == 0 ||
1541 (output_var->data.stream < MAX_VERTEX_STREAMS &&
1542 producer->Stage == MESA_SHADER_GEOMETRY));
1543
1544 tfeedback_candidate_generator g(mem_ctx, tfeedback_candidates);
1545 g.process(output_var);
1546
1547 ir_variable *const input_var =
1548 linker::get_matching_input(mem_ctx, output_var, consumer_inputs,
1549 consumer_interface_inputs,
1550 consumer_inputs_with_locations);
1551
1552 /* If a matching input variable was found, add this ouptut (and the
1553 * input) to the set. If this is a separable program and there is no
1554 * consumer stage, add the output.
1555 *
1556 * Always add TCS outputs. They are shared by all invocations
1557 * within a patch and can be used as shared memory.
1558 */
1559 if (input_var || (prog->SeparateShader && consumer == NULL) ||
1560 producer->Type == GL_TESS_CONTROL_SHADER) {
1561 matches.record(output_var, input_var);
1562 }
1563
1564 /* Only stream 0 outputs can be consumed in the next stage */
1565 if (input_var && output_var->data.stream != 0) {
1566 linker_error(prog, "output %s is assigned to stream=%d but "
1567 "is linked to an input, which requires stream=0",
1568 output_var->name, output_var->data.stream);
1569 return false;
1570 }
1571 }
1572 } else {
1573 /* If there's no producer stage, then this must be a separable program.
1574 * For example, we may have a program that has just a fragment shader.
1575 * Later this program will be used with some arbitrary vertex (or
1576 * geometry) shader program. This means that locations must be assigned
1577 * for all the inputs.
1578 */
1579 foreach_in_list(ir_instruction, node, consumer->ir) {
1580 ir_variable *const input_var = node->as_variable();
1581
1582 if ((input_var == NULL) ||
1583 (input_var->data.mode != ir_var_shader_in))
1584 continue;
1585
1586 matches.record(NULL, input_var);
1587 }
1588 }
1589
1590 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1591 if (!tfeedback_decls[i].is_varying())
1592 continue;
1593
1594 const tfeedback_candidate *matched_candidate
1595 = tfeedback_decls[i].find_candidate(prog, tfeedback_candidates);
1596
1597 if (matched_candidate == NULL) {
1598 hash_table_dtor(tfeedback_candidates);
1599 hash_table_dtor(consumer_inputs);
1600 hash_table_dtor(consumer_interface_inputs);
1601 return false;
1602 }
1603
1604 if (matched_candidate->toplevel_var->data.is_unmatched_generic_inout)
1605 matches.record(matched_candidate->toplevel_var, NULL);
1606 }
1607
1608 const uint64_t reserved_slots =
1609 reserved_varying_slot(producer, ir_var_shader_out) |
1610 reserved_varying_slot(consumer, ir_var_shader_in);
1611
1612 const unsigned slots_used = matches.assign_locations(reserved_slots,
1613 prog->SeparateShader);
1614 matches.store_locations();
1615
1616 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1617 if (!tfeedback_decls[i].is_varying())
1618 continue;
1619
1620 if (!tfeedback_decls[i].assign_location(ctx, prog)) {
1621 hash_table_dtor(tfeedback_candidates);
1622 hash_table_dtor(consumer_inputs);
1623 hash_table_dtor(consumer_interface_inputs);
1624 return false;
1625 }
1626 }
1627
1628 hash_table_dtor(tfeedback_candidates);
1629 hash_table_dtor(consumer_inputs);
1630 hash_table_dtor(consumer_interface_inputs);
1631
1632 if (consumer && producer) {
1633 foreach_in_list(ir_instruction, node, consumer->ir) {
1634 ir_variable *const var = node->as_variable();
1635
1636 if (var && var->data.mode == ir_var_shader_in &&
1637 var->data.is_unmatched_generic_inout) {
1638 if (prog->IsES) {
1639 /*
1640 * On Page 91 (Page 97 of the PDF) of the GLSL ES 1.0 spec:
1641 *
1642 * If the vertex shader declares but doesn't write to a
1643 * varying and the fragment shader declares and reads it,
1644 * is this an error?
1645 *
1646 * RESOLUTION: No.
1647 */
1648 linker_warning(prog, "%s shader varying %s not written "
1649 "by %s shader\n.",
1650 _mesa_shader_stage_to_string(consumer->Stage),
1651 var->name,
1652 _mesa_shader_stage_to_string(producer->Stage));
1653 } else if (prog->Version <= 120) {
1654 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1655 *
1656 * Only those varying variables used (i.e. read) in
1657 * the fragment shader executable must be written to
1658 * by the vertex shader executable; declaring
1659 * superfluous varying variables in a vertex shader is
1660 * permissible.
1661 *
1662 * We interpret this text as meaning that the VS must
1663 * write the variable for the FS to read it. See
1664 * "glsl1-varying read but not written" in piglit.
1665 */
1666 linker_error(prog, "%s shader varying %s not written "
1667 "by %s shader\n.",
1668 _mesa_shader_stage_to_string(consumer->Stage),
1669 var->name,
1670 _mesa_shader_stage_to_string(producer->Stage));
1671 }
1672 }
1673 }
1674 }
1675
1676 if (!disable_varying_packing) {
1677 if (producer) {
1678 lower_packed_varyings(mem_ctx, slots_used, ir_var_shader_out,
1679 0, producer);
1680 }
1681 if (consumer) {
1682 lower_packed_varyings(mem_ctx, slots_used, ir_var_shader_in,
1683 consumer_vertices, consumer);
1684 }
1685 }
1686
1687 return true;
1688 }
1689
1690 bool
1691 check_against_output_limit(struct gl_context *ctx,
1692 struct gl_shader_program *prog,
1693 gl_shader *producer)
1694 {
1695 unsigned output_vectors = 0;
1696
1697 foreach_in_list(ir_instruction, node, producer->ir) {
1698 ir_variable *const var = node->as_variable();
1699
1700 if (var && var->data.mode == ir_var_shader_out &&
1701 var_counts_against_varying_limit(producer->Stage, var)) {
1702 /* outputs for fragment shader can't be doubles */
1703 output_vectors += var->type->count_attribute_slots(false);
1704 }
1705 }
1706
1707 assert(producer->Stage != MESA_SHADER_FRAGMENT);
1708 unsigned max_output_components =
1709 ctx->Const.Program[producer->Stage].MaxOutputComponents;
1710
1711 const unsigned output_components = output_vectors * 4;
1712 if (output_components > max_output_components) {
1713 if (ctx->API == API_OPENGLES2 || prog->IsES)
1714 linker_error(prog, "%s shader uses too many output vectors "
1715 "(%u > %u)\n",
1716 _mesa_shader_stage_to_string(producer->Stage),
1717 output_vectors,
1718 max_output_components / 4);
1719 else
1720 linker_error(prog, "%s shader uses too many output components "
1721 "(%u > %u)\n",
1722 _mesa_shader_stage_to_string(producer->Stage),
1723 output_components,
1724 max_output_components);
1725
1726 return false;
1727 }
1728
1729 return true;
1730 }
1731
1732 bool
1733 check_against_input_limit(struct gl_context *ctx,
1734 struct gl_shader_program *prog,
1735 gl_shader *consumer)
1736 {
1737 unsigned input_vectors = 0;
1738
1739 foreach_in_list(ir_instruction, node, consumer->ir) {
1740 ir_variable *const var = node->as_variable();
1741
1742 if (var && var->data.mode == ir_var_shader_in &&
1743 var_counts_against_varying_limit(consumer->Stage, var)) {
1744 /* vertex inputs aren't varying counted */
1745 input_vectors += var->type->count_attribute_slots(false);
1746 }
1747 }
1748
1749 assert(consumer->Stage != MESA_SHADER_VERTEX);
1750 unsigned max_input_components =
1751 ctx->Const.Program[consumer->Stage].MaxInputComponents;
1752
1753 const unsigned input_components = input_vectors * 4;
1754 if (input_components > max_input_components) {
1755 if (ctx->API == API_OPENGLES2 || prog->IsES)
1756 linker_error(prog, "%s shader uses too many input vectors "
1757 "(%u > %u)\n",
1758 _mesa_shader_stage_to_string(consumer->Stage),
1759 input_vectors,
1760 max_input_components / 4);
1761 else
1762 linker_error(prog, "%s shader uses too many input components "
1763 "(%u > %u)\n",
1764 _mesa_shader_stage_to_string(consumer->Stage),
1765 input_components,
1766 max_input_components);
1767
1768 return false;
1769 }
1770
1771 return true;
1772 }