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