blob: 09ffdff63fbb1d1700f8521057c47adca8c7b978 [file] [log] [blame]
Ian Romanick832dfa52010-06-17 15:04:20 -07001/*
2 * Copyright © 2010 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 linker.cpp
26 * GLSL linker implementation
27 *
28 * Given a set of shaders that are to be linked to generate a final program,
29 * there are three distinct stages.
30 *
31 * In the first stage shaders are partitioned into groups based on the shader
32 * type. All shaders of a particular type (e.g., vertex shaders) are linked
33 * together.
34 *
35 * - Undefined references in each shader are resolve to definitions in
36 * another shader.
37 * - Types and qualifiers of uniforms, outputs, and global variables defined
38 * in multiple shaders with the same name are verified to be the same.
39 * - Initializers for uniforms and global variables defined
40 * in multiple shaders with the same name are verified to be the same.
41 *
42 * The result, in the terminology of the GLSL spec, is a set of shader
43 * executables for each processing unit.
44 *
45 * After the first stage is complete, a series of semantic checks are performed
46 * on each of the shader executables.
47 *
48 * - Each shader executable must define a \c main function.
49 * - Each vertex shader executable must write to \c gl_Position.
50 * - Each fragment shader executable must write to either \c gl_FragData or
51 * \c gl_FragColor.
52 *
53 * In the final stage individual shader executables are linked to create a
54 * complete exectuable.
55 *
56 * - Types of uniforms defined in multiple shader stages with the same name
57 * are verified to be the same.
58 * - Initializers for uniforms defined in multiple shader stages with the
59 * same name are verified to be the same.
60 * - Types and qualifiers of outputs defined in one stage are verified to
61 * be the same as the types and qualifiers of inputs defined with the same
62 * name in a later stage.
63 *
64 * \author Ian Romanick <ian.d.romanick@intel.com>
65 */
Ian Romanickf36460e2010-06-23 12:07:22 -070066
Chia-I Wubfd7c9a2010-08-23 17:51:42 +080067#include "main/core.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070068#include "glsl_symbol_table.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070069#include "ir.h"
70#include "program.h"
Aras Pranckevicius31747152010-07-29 12:40:49 +030071#include "program/hash_table.h"
Ian Romanick8fe8a812010-07-13 17:36:13 -070072#include "linker.h"
Ian Romanicka7ba9a72010-07-20 13:36:32 -070073#include "ir_optimization.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070074
Ian Romanick3322fba2010-10-14 13:28:42 -070075extern "C" {
76#include "main/shaderobj.h"
77}
78
Ian Romanick832dfa52010-06-17 15:04:20 -070079/**
80 * Visitor that determines whether or not a variable is ever written.
81 */
82class find_assignment_visitor : public ir_hierarchical_visitor {
83public:
84 find_assignment_visitor(const char *name)
85 : name(name), found(false)
86 {
87 /* empty */
88 }
89
90 virtual ir_visitor_status visit_enter(ir_assignment *ir)
91 {
92 ir_variable *const var = ir->lhs->variable_referenced();
93
94 if (strcmp(name, var->name) == 0) {
95 found = true;
96 return visit_stop;
97 }
98
99 return visit_continue_with_parent;
100 }
101
Eric Anholt18a60232010-08-23 11:29:25 -0700102 virtual ir_visitor_status visit_enter(ir_call *ir)
103 {
104 exec_list_iterator sig_iter = ir->get_callee()->parameters.iterator();
105 foreach_iter(exec_list_iterator, iter, *ir) {
106 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
107 ir_variable *sig_param = (ir_variable *)sig_iter.get();
108
109 if (sig_param->mode == ir_var_out ||
110 sig_param->mode == ir_var_inout) {
111 ir_variable *var = param_rval->variable_referenced();
112 if (var && strcmp(name, var->name) == 0) {
113 found = true;
114 return visit_stop;
115 }
116 }
117 sig_iter.next();
118 }
119
120 return visit_continue_with_parent;
121 }
122
Ian Romanick832dfa52010-06-17 15:04:20 -0700123 bool variable_found()
124 {
125 return found;
126 }
127
128private:
129 const char *name; /**< Find writes to a variable with this name. */
130 bool found; /**< Was a write to the variable found? */
131};
132
Ian Romanickc93b8f12010-06-17 15:20:22 -0700133
Ian Romanickc33e78f2010-08-13 12:30:41 -0700134/**
135 * Visitor that determines whether or not a variable is ever read.
136 */
137class find_deref_visitor : public ir_hierarchical_visitor {
138public:
139 find_deref_visitor(const char *name)
140 : name(name), found(false)
141 {
142 /* empty */
143 }
144
145 virtual ir_visitor_status visit(ir_dereference_variable *ir)
146 {
147 if (strcmp(this->name, ir->var->name) == 0) {
148 this->found = true;
149 return visit_stop;
150 }
151
152 return visit_continue;
153 }
154
155 bool variable_found() const
156 {
157 return this->found;
158 }
159
160private:
161 const char *name; /**< Find writes to a variable with this name. */
162 bool found; /**< Was a write to the variable found? */
163};
164
165
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700166void
Ian Romanick586e7412011-07-28 14:04:09 -0700167linker_error(gl_shader_program *prog, const char *fmt, ...)
Ian Romanickf36460e2010-06-23 12:07:22 -0700168{
169 va_list ap;
170
Kenneth Graunked3073f52011-01-21 14:32:31 -0800171 ralloc_strcat(&prog->InfoLog, "error: ");
Ian Romanickf36460e2010-06-23 12:07:22 -0700172 va_start(ap, fmt);
Kenneth Graunked3073f52011-01-21 14:32:31 -0800173 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
Ian Romanickf36460e2010-06-23 12:07:22 -0700174 va_end(ap);
Ian Romanick586e7412011-07-28 14:04:09 -0700175
176 prog->LinkStatus = false;
Ian Romanickf36460e2010-06-23 12:07:22 -0700177}
178
179
180void
Ian Romanick379a32f2011-07-28 14:09:06 -0700181linker_warning(gl_shader_program *prog, const char *fmt, ...)
182{
183 va_list ap;
184
185 ralloc_strcat(&prog->InfoLog, "error: ");
186 va_start(ap, fmt);
187 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
188 va_end(ap);
189
190}
191
192
193void
Ian Romanickf6ee7bc2011-10-11 16:15:47 -0700194link_invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
195 int generic_base)
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700196{
Eric Anholt16b68b12010-06-30 11:05:43 -0700197 foreach_list(node, sh->ir) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700198 ir_variable *const var = ((ir_instruction *) node)->as_variable();
199
200 if ((var == NULL) || (var->mode != (unsigned) mode))
201 continue;
202
203 /* Only assign locations for generic attributes / varyings / etc.
204 */
Ian Romanick68a4fc92010-10-07 17:21:22 -0700205 if ((var->location >= generic_base) && !var->explicit_location)
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700206 var->location = -1;
207 }
208}
209
210
Ian Romanickc93b8f12010-06-17 15:20:22 -0700211/**
Ian Romanick69846702010-06-22 17:29:19 -0700212 * Determine the number of attribute slots required for a particular type
213 *
214 * This code is here because it implements the language rules of a specific
215 * GLSL version. Since it's a property of the language and not a property of
216 * types in general, it doesn't really belong in glsl_type.
217 */
218unsigned
219count_attribute_slots(const glsl_type *t)
220{
221 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
222 *
223 * "A scalar input counts the same amount against this limit as a vec4,
224 * so applications may want to consider packing groups of four
225 * unrelated float inputs together into a vector to better utilize the
226 * capabilities of the underlying hardware. A matrix input will use up
227 * multiple locations. The number of locations used will equal the
228 * number of columns in the matrix."
229 *
230 * The spec does not explicitly say how arrays are counted. However, it
231 * should be safe to assume the total number of slots consumed by an array
232 * is the number of entries in the array multiplied by the number of slots
233 * consumed by a single element of the array.
234 */
235
236 if (t->is_array())
237 return t->array_size() * count_attribute_slots(t->element_type());
238
239 if (t->is_matrix())
240 return t->matrix_columns;
241
242 return 1;
243}
244
245
246/**
Paul Berry1ad54ae2011-09-17 09:42:02 -0700247 * Verify that a vertex shader executable meets all semantic requirements.
248 *
Paul Berry642e5b412012-01-04 13:57:52 -0800249 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
250 * as a side effect.
Ian Romanickc93b8f12010-06-17 15:20:22 -0700251 *
252 * \param shader Vertex shader executable to be verified
253 */
Ian Romanick832dfa52010-06-17 15:04:20 -0700254bool
Eric Anholt849e1812010-06-30 11:49:17 -0700255validate_vertex_shader_executable(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700256 struct gl_shader *shader)
Ian Romanick832dfa52010-06-17 15:04:20 -0700257{
258 if (shader == NULL)
259 return true;
260
Eric Anholtf1c1c9e2012-03-19 22:43:27 -0700261 /* From the GLSL 1.10 spec, page 48:
262 *
263 * "The variable gl_Position is available only in the vertex
264 * language and is intended for writing the homogeneous vertex
265 * position. All executions of a well-formed vertex shader
266 * executable must write a value into this variable. [...] The
267 * variable gl_Position is available only in the vertex
268 * language and is intended for writing the homogeneous vertex
269 * position. All executions of a well-formed vertex shader
270 * executable must write a value into this variable."
271 *
272 * while in GLSL 1.40 this text is changed to:
273 *
274 * "The variable gl_Position is available only in the vertex
275 * language and is intended for writing the homogeneous vertex
276 * position. It can be written at any time during shader
277 * execution. It may also be read back by a vertex shader
278 * after being written. This value will be used by primitive
279 * assembly, clipping, culling, and other fixed functionality
280 * operations, if present, that operate on primitives after
281 * vertex processing has occurred. Its value is undefined if
282 * the vertex shader executable does not write gl_Position."
283 */
284 if (prog->Version < 140) {
285 find_assignment_visitor find("gl_Position");
286 find.run(shader->ir);
287 if (!find.variable_found()) {
288 linker_error(prog, "vertex shader does not write to `gl_Position'\n");
289 return false;
290 }
Ian Romanick832dfa52010-06-17 15:04:20 -0700291 }
292
Paul Berry642e5b412012-01-04 13:57:52 -0800293 prog->Vert.ClipDistanceArraySize = 0;
294
Paul Berryb453ba22011-08-11 18:10:22 -0700295 if (prog->Version >= 130) {
296 /* From section 7.1 (Vertex Shader Special Variables) of the
297 * GLSL 1.30 spec:
298 *
299 * "It is an error for a shader to statically write both
300 * gl_ClipVertex and gl_ClipDistance."
301 */
302 find_assignment_visitor clip_vertex("gl_ClipVertex");
303 find_assignment_visitor clip_distance("gl_ClipDistance");
304
305 clip_vertex.run(shader->ir);
306 clip_distance.run(shader->ir);
307 if (clip_vertex.variable_found() && clip_distance.variable_found()) {
308 linker_error(prog, "vertex shader writes to both `gl_ClipVertex' "
309 "and `gl_ClipDistance'\n");
310 return false;
311 }
Paul Berry1ad54ae2011-09-17 09:42:02 -0700312 prog->Vert.UsesClipDistance = clip_distance.variable_found();
Paul Berry642e5b412012-01-04 13:57:52 -0800313 ir_variable *clip_distance_var =
314 shader->symbols->get_variable("gl_ClipDistance");
315 if (clip_distance_var)
316 prog->Vert.ClipDistanceArraySize = clip_distance_var->type->length;
Paul Berryb453ba22011-08-11 18:10:22 -0700317 }
318
Ian Romanick832dfa52010-06-17 15:04:20 -0700319 return true;
320}
321
322
Ian Romanickc93b8f12010-06-17 15:20:22 -0700323/**
324 * Verify that a fragment shader executable meets all semantic requirements
325 *
326 * \param shader Fragment shader executable to be verified
327 */
Ian Romanick832dfa52010-06-17 15:04:20 -0700328bool
Eric Anholt849e1812010-06-30 11:49:17 -0700329validate_fragment_shader_executable(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700330 struct gl_shader *shader)
Ian Romanick832dfa52010-06-17 15:04:20 -0700331{
332 if (shader == NULL)
333 return true;
334
Ian Romanick832dfa52010-06-17 15:04:20 -0700335 find_assignment_visitor frag_color("gl_FragColor");
336 find_assignment_visitor frag_data("gl_FragData");
337
Eric Anholt16b68b12010-06-30 11:05:43 -0700338 frag_color.run(shader->ir);
339 frag_data.run(shader->ir);
Ian Romanick832dfa52010-06-17 15:04:20 -0700340
Ian Romanick832dfa52010-06-17 15:04:20 -0700341 if (frag_color.variable_found() && frag_data.variable_found()) {
Ian Romanick586e7412011-07-28 14:04:09 -0700342 linker_error(prog, "fragment shader writes to both "
343 "`gl_FragColor' and `gl_FragData'\n");
Ian Romanick832dfa52010-06-17 15:04:20 -0700344 return false;
345 }
346
347 return true;
348}
349
350
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700351/**
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700352 * Generate a string describing the mode of a variable
353 */
354static const char *
355mode_string(const ir_variable *var)
356{
357 switch (var->mode) {
358 case ir_var_auto:
359 return (var->read_only) ? "global constant" : "global variable";
360
361 case ir_var_uniform: return "uniform";
362 case ir_var_in: return "shader input";
363 case ir_var_out: return "shader output";
364 case ir_var_inout: return "shader inout";
Ian Romanick7e2aa912010-07-19 17:12:42 -0700365
Kenneth Graunke819d57f2011-01-12 15:37:37 -0800366 case ir_var_const_in:
Ian Romanick7e2aa912010-07-19 17:12:42 -0700367 case ir_var_temporary:
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700368 default:
369 assert(!"Should not get here.");
370 return "invalid variable";
371 }
372}
373
374
375/**
376 * Perform validation of global variables used across multiple shaders
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700377 */
378bool
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700379cross_validate_globals(struct gl_shader_program *prog,
380 struct gl_shader **shader_list,
381 unsigned num_shaders,
382 bool uniforms_only)
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700383{
384 /* Examine all of the uniforms in all of the shaders and cross validate
385 * them.
386 */
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700387 glsl_symbol_table variables;
388 for (unsigned i = 0; i < num_shaders; i++) {
Ian Romanick3322fba2010-10-14 13:28:42 -0700389 if (shader_list[i] == NULL)
390 continue;
391
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700392 foreach_list(node, shader_list[i]->ir) {
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700393 ir_variable *const var = ((ir_instruction *) node)->as_variable();
394
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700395 if (var == NULL)
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700396 continue;
397
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700398 if (uniforms_only && (var->mode != ir_var_uniform))
399 continue;
400
Ian Romanick7e2aa912010-07-19 17:12:42 -0700401 /* Don't cross validate temporaries that are at global scope. These
402 * will eventually get pulled into the shaders 'main'.
403 */
404 if (var->mode == ir_var_temporary)
405 continue;
406
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700407 /* If a global with this name has already been seen, verify that the
408 * new instance has the same type. In addition, if the globals have
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700409 * initializers, the values of the initializers must be the same.
410 */
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700411 ir_variable *const existing = variables.get_variable(var->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700412 if (existing != NULL) {
413 if (var->type != existing->type) {
Ian Romanicka2711d62010-08-29 22:07:49 -0700414 /* Consider the types to be "the same" if both types are arrays
415 * of the same type and one of the arrays is implicitly sized.
416 * In addition, set the type of the linked variable to the
417 * explicitly sized array.
418 */
419 if (var->type->is_array()
420 && existing->type->is_array()
421 && (var->type->fields.array == existing->type->fields.array)
422 && ((var->type->length == 0)
423 || (existing->type->length == 0))) {
Ian Romanick0f4b2a02011-01-25 12:06:18 -0800424 if (var->type->length != 0) {
Ian Romanicka2711d62010-08-29 22:07:49 -0700425 existing->type = var->type;
Ian Romanick6f539212010-12-07 18:30:33 -0800426 }
Ian Romanicka2711d62010-08-29 22:07:49 -0700427 } else {
Ian Romanick586e7412011-07-28 14:04:09 -0700428 linker_error(prog, "%s `%s' declared as type "
429 "`%s' and type `%s'\n",
430 mode_string(var),
431 var->name, var->type->name,
432 existing->type->name);
Ian Romanicka2711d62010-08-29 22:07:49 -0700433 return false;
434 }
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700435 }
436
Ian Romanick68a4fc92010-10-07 17:21:22 -0700437 if (var->explicit_location) {
438 if (existing->explicit_location
439 && (var->location != existing->location)) {
Ian Romanick586e7412011-07-28 14:04:09 -0700440 linker_error(prog, "explicit locations for %s "
441 "`%s' have differing values\n",
442 mode_string(var), var->name);
Ian Romanick68a4fc92010-10-07 17:21:22 -0700443 return false;
444 }
445
446 existing->location = var->location;
447 existing->explicit_location = true;
448 }
449
Ian Romanick46173f92011-10-31 13:07:06 -0700450 /* Validate layout qualifiers for gl_FragDepth.
451 *
452 * From the AMD/ARB_conservative_depth specs:
453 *
454 * "If gl_FragDepth is redeclared in any fragment shader in a
455 * program, it must be redeclared in all fragment shaders in
456 * that program that have static assignments to
457 * gl_FragDepth. All redeclarations of gl_FragDepth in all
458 * fragment shaders in a single program must have the same set
459 * of qualifiers."
460 */
461 if (strcmp(var->name, "gl_FragDepth") == 0) {
462 bool layout_declared = var->depth_layout != ir_depth_layout_none;
463 bool layout_differs =
464 var->depth_layout != existing->depth_layout;
465
466 if (layout_declared && layout_differs) {
467 linker_error(prog,
468 "All redeclarations of gl_FragDepth in all "
469 "fragment shaders in a single program must have "
470 "the same set of qualifiers.");
471 }
472
473 if (var->used && layout_differs) {
474 linker_error(prog,
475 "If gl_FragDepth is redeclared with a layout "
476 "qualifier in any fragment shader, it must be "
477 "redeclared with the same layout qualifier in "
478 "all fragment shaders that have assignments to "
479 "gl_FragDepth");
480 }
481 }
Chad Versaceaddae332011-01-27 01:40:31 -0800482
Ian Romanickf37b1ad2011-10-31 14:31:07 -0700483 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
484 *
485 * "If a shared global has multiple initializers, the
486 * initializers must all be constant expressions, and they
487 * must all have the same value. Otherwise, a link error will
488 * result. (A shared global having only one initializer does
489 * not require that initializer to be a constant expression.)"
490 *
491 * Previous to 4.20 the GLSL spec simply said that initializers
492 * must have the same value. In this case of non-constant
493 * initializers, this was impossible to determine. As a result,
494 * no vendor actually implemented that behavior. The 4.20
495 * behavior matches the implemented behavior of at least one other
496 * vendor, so we'll implement that for all GLSL versions.
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700497 */
Ian Romanickf37b1ad2011-10-31 14:31:07 -0700498 if (var->constant_initializer != NULL) {
499 if (existing->constant_initializer != NULL) {
500 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
Ian Romanick586e7412011-07-28 14:04:09 -0700501 linker_error(prog, "initializers for %s "
502 "`%s' have differing values\n",
503 mode_string(var), var->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700504 return false;
505 }
Ian Romanickf37b1ad2011-10-31 14:31:07 -0700506 } else {
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700507 /* If the first-seen instance of a particular uniform did not
508 * have an initializer but a later instance does, copy the
509 * initializer to the version stored in the symbol table.
510 */
Ian Romanickde415b72010-07-14 13:22:12 -0700511 /* FINISHME: This is wrong. The constant_value field should
512 * FINISHME: not be modified! Imagine a case where a shader
513 * FINISHME: without an initializer is linked in two different
514 * FINISHME: programs with shaders that have differing
515 * FINISHME: initializers. Linking with the first will
516 * FINISHME: modify the shader, and linking with the second
517 * FINISHME: will fail.
518 */
Ian Romanickf37b1ad2011-10-31 14:31:07 -0700519 existing->constant_initializer =
520 var->constant_initializer->clone(ralloc_parent(existing),
521 NULL);
522 }
523 }
524
525 if (var->has_initializer) {
526 if (existing->has_initializer
527 && (var->constant_initializer == NULL
528 || existing->constant_initializer == NULL)) {
529 linker_error(prog,
530 "shared global variable `%s' has multiple "
531 "non-constant initializers.\n",
532 var->name);
533 return false;
534 }
535
536 /* Some instance had an initializer, so keep track of that. In
537 * this location, all sorts of initializers (constant or
538 * otherwise) will propagate the existence to the variable
539 * stored in the symbol table.
540 */
541 existing->has_initializer = true;
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700542 }
Chad Versace7528f142010-11-17 14:34:38 -0800543
544 if (existing->invariant != var->invariant) {
Ian Romanick586e7412011-07-28 14:04:09 -0700545 linker_error(prog, "declarations for %s `%s' have "
546 "mismatching invariant qualifiers\n",
547 mode_string(var), var->name);
Chad Versace7528f142010-11-17 14:34:38 -0800548 return false;
549 }
Chad Versace61428dd2011-01-10 15:29:30 -0800550 if (existing->centroid != var->centroid) {
Ian Romanick586e7412011-07-28 14:04:09 -0700551 linker_error(prog, "declarations for %s `%s' have "
552 "mismatching centroid qualifiers\n",
553 mode_string(var), var->name);
Chad Versace61428dd2011-01-10 15:29:30 -0800554 return false;
555 }
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700556 } else
Eric Anholt001eee52010-11-05 06:11:24 -0700557 variables.add_variable(var);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700558 }
559 }
560
561 return true;
562}
563
564
Ian Romanick37101922010-06-18 19:02:10 -0700565/**
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700566 * Perform validation of uniforms used across multiple shader stages
567 */
568bool
569cross_validate_uniforms(struct gl_shader_program *prog)
570{
571 return cross_validate_globals(prog, prog->_LinkedShaders,
Ian Romanick3322fba2010-10-14 13:28:42 -0700572 MESA_SHADER_TYPES, true);
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700573}
574
575
576/**
Ian Romanick37101922010-06-18 19:02:10 -0700577 * Validate that outputs from one stage match inputs of another
578 */
579bool
Eric Anholt849e1812010-06-30 11:49:17 -0700580cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700581 gl_shader *producer, gl_shader *consumer)
Ian Romanick37101922010-06-18 19:02:10 -0700582{
583 glsl_symbol_table parameters;
584 /* FINISHME: Figure these out dynamically. */
585 const char *const producer_stage = "vertex";
586 const char *const consumer_stage = "fragment";
587
588 /* Find all shader outputs in the "producer" stage.
589 */
Eric Anholt16b68b12010-06-30 11:05:43 -0700590 foreach_list(node, producer->ir) {
Ian Romanick37101922010-06-18 19:02:10 -0700591 ir_variable *const var = ((ir_instruction *) node)->as_variable();
592
593 /* FINISHME: For geometry shaders, this should also look for inout
594 * FINISHME: variables.
595 */
596 if ((var == NULL) || (var->mode != ir_var_out))
597 continue;
598
Eric Anholt001eee52010-11-05 06:11:24 -0700599 parameters.add_variable(var);
Ian Romanick37101922010-06-18 19:02:10 -0700600 }
601
602
603 /* Find all shader inputs in the "consumer" stage. Any variables that have
604 * matching outputs already in the symbol table must have the same type and
605 * qualifiers.
606 */
Eric Anholt16b68b12010-06-30 11:05:43 -0700607 foreach_list(node, consumer->ir) {
Ian Romanick37101922010-06-18 19:02:10 -0700608 ir_variable *const input = ((ir_instruction *) node)->as_variable();
609
610 /* FINISHME: For geometry shaders, this should also look for inout
611 * FINISHME: variables.
612 */
613 if ((input == NULL) || (input->mode != ir_var_in))
614 continue;
615
616 ir_variable *const output = parameters.get_variable(input->name);
617 if (output != NULL) {
618 /* Check that the types match between stages.
619 */
620 if (input->type != output->type) {
Ian Romanickcb2b5472010-12-13 15:16:39 -0800621 /* There is a bit of a special case for gl_TexCoord. This
Bryan Cainf18a0862011-04-23 19:29:15 -0500622 * built-in is unsized by default. Applications that variable
Ian Romanickcb2b5472010-12-13 15:16:39 -0800623 * access it must redeclare it with a size. There is some
624 * language in the GLSL spec that implies the fragment shader
625 * and vertex shader do not have to agree on this size. Other
626 * driver behave this way, and one or two applications seem to
627 * rely on it.
628 *
629 * Neither declaration needs to be modified here because the array
630 * sizes are fixed later when update_array_sizes is called.
631 *
632 * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
633 *
634 * "Unlike user-defined varying variables, the built-in
635 * varying variables don't have a strict one-to-one
636 * correspondence between the vertex language and the
637 * fragment language."
638 */
639 if (!output->type->is_array()
640 || (strncmp("gl_", output->name, 3) != 0)) {
Ian Romanick586e7412011-07-28 14:04:09 -0700641 linker_error(prog,
642 "%s shader output `%s' declared as type `%s', "
643 "but %s shader input declared as type `%s'\n",
644 producer_stage, output->name,
645 output->type->name,
646 consumer_stage, input->type->name);
Ian Romanickcb2b5472010-12-13 15:16:39 -0800647 return false;
648 }
Ian Romanick37101922010-06-18 19:02:10 -0700649 }
650
651 /* Check that all of the qualifiers match between stages.
652 */
653 if (input->centroid != output->centroid) {
Ian Romanick586e7412011-07-28 14:04:09 -0700654 linker_error(prog,
655 "%s shader output `%s' %s centroid qualifier, "
656 "but %s shader input %s centroid qualifier\n",
657 producer_stage,
658 output->name,
659 (output->centroid) ? "has" : "lacks",
660 consumer_stage,
661 (input->centroid) ? "has" : "lacks");
Ian Romanick37101922010-06-18 19:02:10 -0700662 return false;
663 }
664
665 if (input->invariant != output->invariant) {
Ian Romanick586e7412011-07-28 14:04:09 -0700666 linker_error(prog,
667 "%s shader output `%s' %s invariant qualifier, "
668 "but %s shader input %s invariant qualifier\n",
669 producer_stage,
670 output->name,
671 (output->invariant) ? "has" : "lacks",
672 consumer_stage,
673 (input->invariant) ? "has" : "lacks");
Ian Romanick37101922010-06-18 19:02:10 -0700674 return false;
675 }
676
677 if (input->interpolation != output->interpolation) {
Ian Romanick586e7412011-07-28 14:04:09 -0700678 linker_error(prog,
679 "%s shader output `%s' specifies %s "
680 "interpolation qualifier, "
681 "but %s shader input specifies %s "
682 "interpolation qualifier\n",
683 producer_stage,
684 output->name,
685 output->interpolation_string(),
686 consumer_stage,
687 input->interpolation_string());
Ian Romanick37101922010-06-18 19:02:10 -0700688 return false;
689 }
690 }
691 }
692
693 return true;
694}
695
696
Ian Romanick3fb87872010-07-09 14:09:34 -0700697/**
698 * Populates a shaders symbol table with all global declarations
699 */
700static void
701populate_symbol_table(gl_shader *sh)
702{
703 sh->symbols = new(sh) glsl_symbol_table;
704
705 foreach_list(node, sh->ir) {
706 ir_instruction *const inst = (ir_instruction *) node;
707 ir_variable *var;
708 ir_function *func;
709
710 if ((func = inst->as_function()) != NULL) {
Eric Anholte8f5ebf2010-11-05 06:08:45 -0700711 sh->symbols->add_function(func);
Ian Romanick3fb87872010-07-09 14:09:34 -0700712 } else if ((var = inst->as_variable()) != NULL) {
Eric Anholt001eee52010-11-05 06:11:24 -0700713 sh->symbols->add_variable(var);
Ian Romanick3fb87872010-07-09 14:09:34 -0700714 }
715 }
716}
717
718
719/**
Ian Romanick31a97862010-07-12 18:48:50 -0700720 * Remap variables referenced in an instruction tree
721 *
722 * This is used when instruction trees are cloned from one shader and placed in
723 * another. These trees will contain references to \c ir_variable nodes that
724 * do not exist in the target shader. This function finds these \c ir_variable
725 * references and replaces the references with matching variables in the target
726 * shader.
727 *
728 * If there is no matching variable in the target shader, a clone of the
729 * \c ir_variable is made and added to the target shader. The new variable is
730 * added to \b both the instruction stream and the symbol table.
731 *
732 * \param inst IR tree that is to be processed.
733 * \param symbols Symbol table containing global scope symbols in the
734 * linked shader.
735 * \param instructions Instruction stream where new variable declarations
736 * should be added.
737 */
738void
Eric Anholt8273bd42010-08-04 12:34:56 -0700739remap_variables(ir_instruction *inst, struct gl_shader *target,
740 hash_table *temps)
Ian Romanick31a97862010-07-12 18:48:50 -0700741{
742 class remap_visitor : public ir_hierarchical_visitor {
743 public:
Eric Anholt8273bd42010-08-04 12:34:56 -0700744 remap_visitor(struct gl_shader *target,
Ian Romanick7e2aa912010-07-19 17:12:42 -0700745 hash_table *temps)
Ian Romanick31a97862010-07-12 18:48:50 -0700746 {
Eric Anholt8273bd42010-08-04 12:34:56 -0700747 this->target = target;
748 this->symbols = target->symbols;
749 this->instructions = target->ir;
Ian Romanick7e2aa912010-07-19 17:12:42 -0700750 this->temps = temps;
Ian Romanick31a97862010-07-12 18:48:50 -0700751 }
752
753 virtual ir_visitor_status visit(ir_dereference_variable *ir)
754 {
Ian Romanick7e2aa912010-07-19 17:12:42 -0700755 if (ir->var->mode == ir_var_temporary) {
756 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
757
758 assert(var != NULL);
759 ir->var = var;
760 return visit_continue;
761 }
762
Ian Romanick31a97862010-07-12 18:48:50 -0700763 ir_variable *const existing =
764 this->symbols->get_variable(ir->var->name);
765 if (existing != NULL)
766 ir->var = existing;
767 else {
Eric Anholt8273bd42010-08-04 12:34:56 -0700768 ir_variable *copy = ir->var->clone(this->target, NULL);
Ian Romanick31a97862010-07-12 18:48:50 -0700769
Eric Anholt001eee52010-11-05 06:11:24 -0700770 this->symbols->add_variable(copy);
Ian Romanick31a97862010-07-12 18:48:50 -0700771 this->instructions->push_head(copy);
Ian Romanick7e2aa912010-07-19 17:12:42 -0700772 ir->var = copy;
Ian Romanick31a97862010-07-12 18:48:50 -0700773 }
774
775 return visit_continue;
776 }
777
778 private:
Eric Anholt8273bd42010-08-04 12:34:56 -0700779 struct gl_shader *target;
Ian Romanick31a97862010-07-12 18:48:50 -0700780 glsl_symbol_table *symbols;
781 exec_list *instructions;
Ian Romanick7e2aa912010-07-19 17:12:42 -0700782 hash_table *temps;
Ian Romanick31a97862010-07-12 18:48:50 -0700783 };
784
Eric Anholt8273bd42010-08-04 12:34:56 -0700785 remap_visitor v(target, temps);
Ian Romanick31a97862010-07-12 18:48:50 -0700786
787 inst->accept(&v);
788}
789
790
791/**
792 * Move non-declarations from one instruction stream to another
793 *
794 * The intended usage pattern of this function is to pass the pointer to the
Eric Anholt62c47632010-07-29 13:52:25 -0700795 * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
Ian Romanick31a97862010-07-12 18:48:50 -0700796 * pointer) for \c last and \c false for \c make_copies on the first
797 * call. Successive calls pass the return value of the previous call for
798 * \c last and \c true for \c make_copies.
799 *
800 * \param instructions Source instruction stream
801 * \param last Instruction after which new instructions should be
802 * inserted in the target instruction stream
803 * \param make_copies Flag selecting whether instructions in \c instructions
804 * should be copied (via \c ir_instruction::clone) into the
805 * target list or moved.
806 *
807 * \return
808 * The new "last" instruction in the target instruction stream. This pointer
809 * is suitable for use as the \c last parameter of a later call to this
810 * function.
811 */
812exec_node *
813move_non_declarations(exec_list *instructions, exec_node *last,
814 bool make_copies, gl_shader *target)
815{
Ian Romanick7e2aa912010-07-19 17:12:42 -0700816 hash_table *temps = NULL;
817
818 if (make_copies)
819 temps = hash_table_ctor(0, hash_table_pointer_hash,
820 hash_table_pointer_compare);
821
Ian Romanick303c99f2010-07-19 12:34:56 -0700822 foreach_list_safe(node, instructions) {
Ian Romanick31a97862010-07-12 18:48:50 -0700823 ir_instruction *inst = (ir_instruction *) node;
824
Ian Romanick7e2aa912010-07-19 17:12:42 -0700825 if (inst->as_function())
Ian Romanick31a97862010-07-12 18:48:50 -0700826 continue;
827
Ian Romanick7e2aa912010-07-19 17:12:42 -0700828 ir_variable *var = inst->as_variable();
829 if ((var != NULL) && (var->mode != ir_var_temporary))
830 continue;
831
832 assert(inst->as_assignment()
833 || ((var != NULL) && (var->mode == ir_var_temporary)));
Ian Romanick31a97862010-07-12 18:48:50 -0700834
835 if (make_copies) {
Eric Anholt8273bd42010-08-04 12:34:56 -0700836 inst = inst->clone(target, NULL);
Ian Romanick7e2aa912010-07-19 17:12:42 -0700837
838 if (var != NULL)
839 hash_table_insert(temps, inst, var);
840 else
Eric Anholt8273bd42010-08-04 12:34:56 -0700841 remap_variables(inst, target, temps);
Ian Romanick31a97862010-07-12 18:48:50 -0700842 } else {
843 inst->remove();
844 }
845
846 last->insert_after(inst);
847 last = inst;
848 }
849
Ian Romanick7e2aa912010-07-19 17:12:42 -0700850 if (make_copies)
851 hash_table_dtor(temps);
852
Ian Romanick31a97862010-07-12 18:48:50 -0700853 return last;
854}
855
856/**
Ian Romanick15ce87e2010-07-09 15:28:22 -0700857 * Get the function signature for main from a shader
858 */
859static ir_function_signature *
860get_main_function_signature(gl_shader *sh)
861{
862 ir_function *const f = sh->symbols->get_function("main");
863 if (f != NULL) {
864 exec_list void_parameters;
865
866 /* Look for the 'void main()' signature and ensure that it's defined.
867 * This keeps the linker from accidentally pick a shader that just
868 * contains a prototype for main.
869 *
870 * We don't have to check for multiple definitions of main (in multiple
871 * shaders) because that would have already been caught above.
872 */
873 ir_function_signature *sig = f->matching_signature(&void_parameters);
874 if ((sig != NULL) && sig->is_defined) {
875 return sig;
876 }
877 }
878
879 return NULL;
880}
881
882
883/**
Brian Paul84a12732012-02-02 20:10:40 -0700884 * This class is only used in link_intrastage_shaders() below but declaring
885 * it inside that function leads to compiler warnings with some versions of
886 * gcc.
887 */
888class array_sizing_visitor : public ir_hierarchical_visitor {
889public:
890 virtual ir_visitor_status visit(ir_variable *var)
891 {
892 if (var->type->is_array() && (var->type->length == 0)) {
893 const glsl_type *type =
894 glsl_type::get_array_instance(var->type->fields.array,
895 var->max_array_access + 1);
896 assert(type != NULL);
897 var->type = type;
898 }
899 return visit_continue;
900 }
901};
902
903
904/**
Ian Romanick3fb87872010-07-09 14:09:34 -0700905 * Combine a group of shaders for a single stage to generate a linked shader
906 *
907 * \note
908 * If this function is supplied a single shader, it is cloned, and the new
909 * shader is returned.
910 */
911static struct gl_shader *
Kenneth Graunke2da02e72010-11-17 11:03:57 -0800912link_intrastage_shaders(void *mem_ctx,
913 struct gl_context *ctx,
Eric Anholt5d0f4302010-08-18 12:02:35 -0700914 struct gl_shader_program *prog,
Ian Romanick3fb87872010-07-09 14:09:34 -0700915 struct gl_shader **shader_list,
916 unsigned num_shaders)
917{
Ian Romanick13f782c2010-06-29 18:53:38 -0700918 /* Check that global variables defined in multiple shaders are consistent.
919 */
920 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
921 return NULL;
922
923 /* Check that there is only a single definition of each function signature
924 * across all shaders.
925 */
926 for (unsigned i = 0; i < (num_shaders - 1); i++) {
927 foreach_list(node, shader_list[i]->ir) {
928 ir_function *const f = ((ir_instruction *) node)->as_function();
929
930 if (f == NULL)
931 continue;
932
933 for (unsigned j = i + 1; j < num_shaders; j++) {
934 ir_function *const other =
935 shader_list[j]->symbols->get_function(f->name);
936
937 /* If the other shader has no function (and therefore no function
938 * signatures) with the same name, skip to the next shader.
939 */
940 if (other == NULL)
941 continue;
942
943 foreach_iter (exec_list_iterator, iter, *f) {
944 ir_function_signature *sig =
945 (ir_function_signature *) iter.get();
946
Kenneth Graunkef412fac2010-09-05 01:48:11 -0700947 if (!sig->is_defined || sig->is_builtin)
Ian Romanick13f782c2010-06-29 18:53:38 -0700948 continue;
949
950 ir_function_signature *other_sig =
951 other->exact_matching_signature(& sig->parameters);
952
953 if ((other_sig != NULL) && other_sig->is_defined
Kenneth Graunkef412fac2010-09-05 01:48:11 -0700954 && !other_sig->is_builtin) {
Ian Romanick586e7412011-07-28 14:04:09 -0700955 linker_error(prog, "function `%s' is multiply defined",
956 f->name);
Ian Romanick13f782c2010-06-29 18:53:38 -0700957 return NULL;
958 }
959 }
960 }
961 }
962 }
963
964 /* Find the shader that defines main, and make a clone of it.
965 *
966 * Starting with the clone, search for undefined references. If one is
967 * found, find the shader that defines it. Clone the reference and add
968 * it to the shader. Repeat until there are no undefined references or
969 * until a reference cannot be resolved.
970 */
Ian Romanick15ce87e2010-07-09 15:28:22 -0700971 gl_shader *main = NULL;
972 for (unsigned i = 0; i < num_shaders; i++) {
973 if (get_main_function_signature(shader_list[i]) != NULL) {
974 main = shader_list[i];
975 break;
976 }
977 }
Ian Romanick13f782c2010-06-29 18:53:38 -0700978
Ian Romanick15ce87e2010-07-09 15:28:22 -0700979 if (main == NULL) {
Ian Romanick586e7412011-07-28 14:04:09 -0700980 linker_error(prog, "%s shader lacks `main'\n",
981 (shader_list[0]->Type == GL_VERTEX_SHADER)
982 ? "vertex" : "fragment");
Ian Romanick15ce87e2010-07-09 15:28:22 -0700983 return NULL;
984 }
985
Ian Romanick4a455952010-10-13 15:13:02 -0700986 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
Ian Romanick15ce87e2010-07-09 15:28:22 -0700987 linked->ir = new(linked) exec_list;
Kenneth Graunke2da02e72010-11-17 11:03:57 -0800988 clone_ir_list(mem_ctx, linked->ir, main->ir);
Ian Romanick15ce87e2010-07-09 15:28:22 -0700989
990 populate_symbol_table(linked);
Ian Romanick13f782c2010-06-29 18:53:38 -0700991
Ian Romanick31a97862010-07-12 18:48:50 -0700992 /* The a pointer to the main function in the final linked shader (i.e., the
993 * copy of the original shader that contained the main function).
994 */
995 ir_function_signature *const main_sig = get_main_function_signature(linked);
996
997 /* Move any instructions other than variable declarations or function
998 * declarations into main.
999 */
Ian Romanick9303e352010-07-19 12:33:54 -07001000 exec_node *insertion_point =
1001 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
1002 linked);
1003
Ian Romanick31a97862010-07-12 18:48:50 -07001004 for (unsigned i = 0; i < num_shaders; i++) {
Ian Romanick9303e352010-07-19 12:33:54 -07001005 if (shader_list[i] == main)
1006 continue;
1007
Ian Romanick31a97862010-07-12 18:48:50 -07001008 insertion_point = move_non_declarations(shader_list[i]->ir,
Ian Romanick9303e352010-07-19 12:33:54 -07001009 insertion_point, true, linked);
Ian Romanick31a97862010-07-12 18:48:50 -07001010 }
1011
Ian Romanick13f782c2010-06-29 18:53:38 -07001012 /* Resolve initializers for global variables in the linked shader.
1013 */
Ian Romanickd5be2ac2010-07-20 11:29:46 -07001014 unsigned num_linking_shaders = num_shaders;
1015 for (unsigned i = 0; i < num_shaders; i++)
1016 num_linking_shaders += shader_list[i]->num_builtins_to_link;
1017
1018 gl_shader **linking_shaders =
1019 (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
1020
1021 memcpy(linking_shaders, shader_list,
1022 sizeof(linking_shaders[0]) * num_shaders);
1023
1024 unsigned idx = num_shaders;
1025 for (unsigned i = 0; i < num_shaders; i++) {
1026 memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
1027 sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
1028 idx += shader_list[i]->num_builtins_to_link;
1029 }
1030
1031 assert(idx == num_linking_shaders);
1032
Ian Romanick4a455952010-10-13 15:13:02 -07001033 if (!link_function_calls(prog, linked, linking_shaders,
1034 num_linking_shaders)) {
1035 ctx->Driver.DeleteShader(ctx, linked);
1036 linked = NULL;
1037 }
Ian Romanickd5be2ac2010-07-20 11:29:46 -07001038
1039 free(linking_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07001040
Paul Berryc148ef62011-08-03 15:37:01 -07001041#ifdef DEBUG
1042 /* At this point linked should contain all of the linked IR, so
1043 * validate it to make sure nothing went wrong.
1044 */
1045 if (linked)
1046 validate_ir_tree(linked->ir);
1047#endif
1048
Ian Romanickc87e9ef2011-01-25 12:04:08 -08001049 /* Make a pass over all variable declarations to ensure that arrays with
Ian Romanick6f539212010-12-07 18:30:33 -08001050 * unspecified sizes have a size specified. The size is inferred from the
1051 * max_array_access field.
1052 */
Ian Romanick002cd2c2010-12-07 19:00:44 -08001053 if (linked != NULL) {
Brian Paul84a12732012-02-02 20:10:40 -07001054 array_sizing_visitor v;
Ian Romanick6f539212010-12-07 18:30:33 -08001055
Ian Romanickc87e9ef2011-01-25 12:04:08 -08001056 v.run(linked->ir);
Ian Romanick6f539212010-12-07 18:30:33 -08001057 }
1058
Ian Romanick3fb87872010-07-09 14:09:34 -07001059 return linked;
1060}
1061
Eric Anholta721abf2010-08-23 10:32:01 -07001062/**
1063 * Update the sizes of linked shader uniform arrays to the maximum
1064 * array index used.
1065 *
1066 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1067 *
1068 * If one or more elements of an array are active,
1069 * GetActiveUniform will return the name of the array in name,
1070 * subject to the restrictions listed above. The type of the array
1071 * is returned in type. The size parameter contains the highest
1072 * array element index used, plus one. The compiler or linker
1073 * determines the highest index used. There will be only one
1074 * active uniform reported by the GL per uniform array.
1075
1076 */
1077static void
Eric Anholt586b4b52010-09-28 14:32:16 -07001078update_array_sizes(struct gl_shader_program *prog)
Eric Anholta721abf2010-08-23 10:32:01 -07001079{
Ian Romanick3322fba2010-10-14 13:28:42 -07001080 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1081 if (prog->_LinkedShaders[i] == NULL)
1082 continue;
1083
Eric Anholta721abf2010-08-23 10:32:01 -07001084 foreach_list(node, prog->_LinkedShaders[i]->ir) {
1085 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1086
Eric Anholt586b4b52010-09-28 14:32:16 -07001087 if ((var == NULL) || (var->mode != ir_var_uniform &&
1088 var->mode != ir_var_in &&
1089 var->mode != ir_var_out) ||
Eric Anholta721abf2010-08-23 10:32:01 -07001090 !var->type->is_array())
1091 continue;
1092
1093 unsigned int size = var->max_array_access;
Ian Romanick3322fba2010-10-14 13:28:42 -07001094 for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
1095 if (prog->_LinkedShaders[j] == NULL)
1096 continue;
1097
Eric Anholta721abf2010-08-23 10:32:01 -07001098 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
1099 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
1100 if (!other_var)
1101 continue;
1102
1103 if (strcmp(var->name, other_var->name) == 0 &&
1104 other_var->max_array_access > size) {
1105 size = other_var->max_array_access;
1106 }
1107 }
1108 }
Eric Anholt586b4b52010-09-28 14:32:16 -07001109
Eric Anholta721abf2010-08-23 10:32:01 -07001110 if (size + 1 != var->type->fields.array->length) {
Ian Romanick89d81ab2011-01-25 10:41:20 -08001111 /* If this is a built-in uniform (i.e., it's backed by some
1112 * fixed-function state), adjust the number of state slots to
1113 * match the new array size. The number of slots per array entry
Bryan Cainf18a0862011-04-23 19:29:15 -05001114 * is not known. It seems safe to assume that the total number of
Ian Romanick89d81ab2011-01-25 10:41:20 -08001115 * slots is an integer multiple of the number of array elements.
1116 * Determine the number of slots per array element by dividing by
1117 * the old (total) size.
1118 */
1119 if (var->num_state_slots > 0) {
1120 var->num_state_slots = (size + 1)
1121 * (var->num_state_slots / var->type->length);
1122 }
1123
Eric Anholta721abf2010-08-23 10:32:01 -07001124 var->type = glsl_type::get_array_instance(var->type->fields.array,
1125 size + 1);
1126 /* FINISHME: We should update the types of array
1127 * dereferences of this variable now.
1128 */
1129 }
1130 }
1131 }
1132}
1133
Ian Romanick69846702010-06-22 17:29:19 -07001134/**
Bryan Cainf18a0862011-04-23 19:29:15 -05001135 * Find a contiguous set of available bits in a bitmask.
Ian Romanick69846702010-06-22 17:29:19 -07001136 *
1137 * \param used_mask Bits representing used (1) and unused (0) locations
1138 * \param needed_count Number of contiguous bits needed.
1139 *
1140 * \return
1141 * Base location of the available bits on success or -1 on failure.
1142 */
1143int
1144find_available_slots(unsigned used_mask, unsigned needed_count)
1145{
1146 unsigned needed_mask = (1 << needed_count) - 1;
1147 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1148
1149 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1150 * cannot optimize possibly infinite loops" for the loop below.
1151 */
1152 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1153 return -1;
1154
1155 for (int i = 0; i <= max_bit_to_test; i++) {
1156 if ((needed_mask & ~used_mask) == needed_mask)
1157 return i;
1158
1159 needed_mask <<= 1;
1160 }
1161
1162 return -1;
1163}
1164
1165
Ian Romanickd32d4f72011-06-27 17:59:58 -07001166/**
1167 * Assign locations for either VS inputs for FS outputs
1168 *
1169 * \param prog Shader program whose variables need locations assigned
1170 * \param target_index Selector for the program target to receive location
1171 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1172 * \c MESA_SHADER_FRAGMENT.
1173 * \param max_index Maximum number of generic locations. This corresponds
1174 * to either the maximum number of draw buffers or the
1175 * maximum number of generic attributes.
1176 *
1177 * \return
1178 * If locations are successfully assigned, true is returned. Otherwise an
1179 * error is emitted to the shader link log and false is returned.
Ian Romanickd32d4f72011-06-27 17:59:58 -07001180 */
Ian Romanick69846702010-06-22 17:29:19 -07001181bool
Ian Romanickd32d4f72011-06-27 17:59:58 -07001182assign_attribute_or_color_locations(gl_shader_program *prog,
1183 unsigned target_index,
1184 unsigned max_index)
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001185{
Ian Romanickd32d4f72011-06-27 17:59:58 -07001186 /* Mark invalid locations as being used.
Ian Romanick9342d262010-06-22 17:41:37 -07001187 */
Ian Romanickd32d4f72011-06-27 17:59:58 -07001188 unsigned used_locations = (max_index >= 32)
1189 ? ~0 : ~((1 << max_index) - 1);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001190
Ian Romanickd32d4f72011-06-27 17:59:58 -07001191 assert((target_index == MESA_SHADER_VERTEX)
1192 || (target_index == MESA_SHADER_FRAGMENT));
1193
1194 gl_shader *const sh = prog->_LinkedShaders[target_index];
1195 if (sh == NULL)
1196 return true;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001197
Ian Romanick69846702010-06-22 17:29:19 -07001198 /* Operate in a total of four passes.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001199 *
1200 * 1. Invalidate the location assignments for all vertex shader inputs.
1201 *
1202 * 2. Assign locations for inputs that have user-defined (via
Ian Romanickb12b5d92011-11-04 16:08:52 -07001203 * glBindVertexAttribLocation) locations and outputs that have
1204 * user-defined locations (via glBindFragDataLocation).
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001205 *
Ian Romanick69846702010-06-22 17:29:19 -07001206 * 3. Sort the attributes without assigned locations by number of slots
1207 * required in decreasing order. Fragmentation caused by attribute
1208 * locations assigned by the application may prevent large attributes
1209 * from having enough contiguous space.
1210 *
1211 * 4. Assign locations to any inputs without assigned locations.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001212 */
1213
Ian Romanickd32d4f72011-06-27 17:59:58 -07001214 const int generic_base = (target_index == MESA_SHADER_VERTEX)
Brian Paul7eb7d672011-07-07 16:47:59 -06001215 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001216
Ian Romanickd32d4f72011-06-27 17:59:58 -07001217 const enum ir_variable_mode direction =
1218 (target_index == MESA_SHADER_VERTEX) ? ir_var_in : ir_var_out;
1219
1220
Ian Romanickf6ee7bc2011-10-11 16:15:47 -07001221 link_invalidate_variable_locations(sh, direction, generic_base);
Ian Romanickd32d4f72011-06-27 17:59:58 -07001222
Ian Romanick69846702010-06-22 17:29:19 -07001223 /* Temporary storage for the set of attributes that need locations assigned.
1224 */
1225 struct temp_attr {
1226 unsigned slots;
1227 ir_variable *var;
1228
1229 /* Used below in the call to qsort. */
1230 static int compare(const void *a, const void *b)
1231 {
1232 const temp_attr *const l = (const temp_attr *) a;
1233 const temp_attr *const r = (const temp_attr *) b;
1234
1235 /* Reversed because we want a descending order sort below. */
1236 return r->slots - l->slots;
1237 }
1238 } to_assign[16];
1239
1240 unsigned num_attr = 0;
1241
Eric Anholt16b68b12010-06-30 11:05:43 -07001242 foreach_list(node, sh->ir) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001243 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1244
Brian Paul4470ff22011-07-19 21:10:25 -06001245 if ((var == NULL) || (var->mode != (unsigned) direction))
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001246 continue;
1247
Ian Romanick68a4fc92010-10-07 17:21:22 -07001248 if (var->explicit_location) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07001249 if ((var->location >= (int)(max_index + generic_base))
Ian Romanick68a4fc92010-10-07 17:21:22 -07001250 || (var->location < 0)) {
Ian Romanick586e7412011-07-28 14:04:09 -07001251 linker_error(prog,
1252 "invalid explicit location %d specified for `%s'\n",
Ian Romanick523b6112011-08-17 15:40:03 -07001253 (var->location < 0)
1254 ? var->location : var->location - generic_base,
Ian Romanick586e7412011-07-28 14:04:09 -07001255 var->name);
Ian Romanick68a4fc92010-10-07 17:21:22 -07001256 return false;
Ian Romanick523b6112011-08-17 15:40:03 -07001257 }
1258 } else if (target_index == MESA_SHADER_VERTEX) {
1259 unsigned binding;
1260
1261 if (prog->AttributeBindings->get(binding, var->name)) {
1262 assert(binding >= VERT_ATTRIB_GENERIC0);
1263 var->location = binding;
Ian Romanick68a4fc92010-10-07 17:21:22 -07001264 }
Ian Romanickb12b5d92011-11-04 16:08:52 -07001265 } else if (target_index == MESA_SHADER_FRAGMENT) {
1266 unsigned binding;
1267
1268 if (prog->FragDataBindings->get(binding, var->name)) {
1269 assert(binding >= FRAG_RESULT_DATA0);
1270 var->location = binding;
1271 }
Ian Romanick68a4fc92010-10-07 17:21:22 -07001272 }
1273
Ian Romanick9f0e98d2011-10-06 10:25:34 -07001274 /* If the variable is not a built-in and has a location statically
1275 * assigned in the shader (presumably via a layout qualifier), make sure
1276 * that it doesn't collide with other assigned locations. Otherwise,
1277 * add it to the list of variables that need linker-assigned locations.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001278 */
Ian Romanick523b6112011-08-17 15:40:03 -07001279 const unsigned slots = count_attribute_slots(var->type);
1280 if (var->location != -1) {
1281 if (var->location >= generic_base) {
1282 /* From page 61 of the OpenGL 4.0 spec:
1283 *
1284 * "LinkProgram will fail if the attribute bindings assigned
1285 * by BindAttribLocation do not leave not enough space to
1286 * assign a location for an active matrix attribute or an
1287 * active attribute array, both of which require multiple
1288 * contiguous generic attributes."
1289 *
1290 * Previous versions of the spec contain similar language but omit
1291 * the bit about attribute arrays.
1292 *
1293 * Page 61 of the OpenGL 4.0 spec also says:
1294 *
1295 * "It is possible for an application to bind more than one
1296 * attribute name to the same location. This is referred to as
1297 * aliasing. This will only work if only one of the aliased
1298 * attributes is active in the executable program, or if no
1299 * path through the shader consumes more than one attribute of
1300 * a set of attributes aliased to the same location. A link
1301 * error can occur if the linker determines that every path
1302 * through the shader consumes multiple aliased attributes,
1303 * but implementations are not required to generate an error
1304 * in this case."
1305 *
1306 * These two paragraphs are either somewhat contradictory, or I
1307 * don't fully understand one or both of them.
1308 */
1309 /* FINISHME: The code as currently written does not support
1310 * FINISHME: attribute location aliasing (see comment above).
1311 */
1312 /* Mask representing the contiguous slots that will be used by
1313 * this attribute.
1314 */
1315 const unsigned attr = var->location - generic_base;
1316 const unsigned use_mask = (1 << slots) - 1;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001317
Ian Romanick523b6112011-08-17 15:40:03 -07001318 /* Generate a link error if the set of bits requested for this
1319 * attribute overlaps any previously allocated bits.
1320 */
1321 if ((~(use_mask << attr) & used_locations) != used_locations) {
Dave Airlie7449ae42011-11-20 19:56:35 +00001322 const char *const string = (target_index == MESA_SHADER_VERTEX)
1323 ? "vertex shader input" : "fragment shader output";
Ian Romanick523b6112011-08-17 15:40:03 -07001324 linker_error(prog,
Dave Airlie7449ae42011-11-20 19:56:35 +00001325 "insufficient contiguous locations "
1326 "available for %s `%s'", string,
Ian Romanick523b6112011-08-17 15:40:03 -07001327 var->name);
1328 return false;
1329 }
1330
1331 used_locations |= (use_mask << attr);
1332 }
1333
1334 continue;
1335 }
1336
1337 to_assign[num_attr].slots = slots;
Ian Romanick69846702010-06-22 17:29:19 -07001338 to_assign[num_attr].var = var;
1339 num_attr++;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001340 }
Ian Romanick69846702010-06-22 17:29:19 -07001341
1342 /* If all of the attributes were assigned locations by the application (or
1343 * are built-in attributes with fixed locations), return early. This should
1344 * be the common case.
1345 */
1346 if (num_attr == 0)
1347 return true;
1348
1349 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1350
Ian Romanickd32d4f72011-06-27 17:59:58 -07001351 if (target_index == MESA_SHADER_VERTEX) {
1352 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1353 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1354 * reserved to prevent it from being automatically allocated below.
1355 */
1356 find_deref_visitor find("gl_Vertex");
1357 find.run(sh->ir);
1358 if (find.variable_found())
1359 used_locations |= (1 << 0);
1360 }
Ian Romanick982e3792010-06-29 18:58:20 -07001361
Ian Romanick69846702010-06-22 17:29:19 -07001362 for (unsigned i = 0; i < num_attr; i++) {
1363 /* Mask representing the contiguous slots that will be used by this
1364 * attribute.
1365 */
1366 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1367
1368 int location = find_available_slots(used_locations, to_assign[i].slots);
1369
1370 if (location < 0) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07001371 const char *const string = (target_index == MESA_SHADER_VERTEX)
1372 ? "vertex shader input" : "fragment shader output";
1373
Ian Romanick586e7412011-07-28 14:04:09 -07001374 linker_error(prog,
Dave Airlie7449ae42011-11-20 19:56:35 +00001375 "insufficient contiguous locations "
Ian Romanick586e7412011-07-28 14:04:09 -07001376 "available for %s `%s'",
1377 string, to_assign[i].var->name);
Ian Romanick69846702010-06-22 17:29:19 -07001378 return false;
1379 }
1380
Ian Romanickd32d4f72011-06-27 17:59:58 -07001381 to_assign[i].var->location = generic_base + location;
Ian Romanick69846702010-06-22 17:29:19 -07001382 used_locations |= (use_mask << location);
1383 }
1384
1385 return true;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001386}
1387
1388
Ian Romanick40e114b2010-08-17 14:55:50 -07001389/**
Ian Romanickcc90e622010-10-19 17:59:10 -07001390 * Demote shader inputs and outputs that are not used in other stages
Ian Romanick40e114b2010-08-17 14:55:50 -07001391 */
1392void
Ian Romanickcc90e622010-10-19 17:59:10 -07001393demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
Ian Romanick40e114b2010-08-17 14:55:50 -07001394{
1395 foreach_list(node, sh->ir) {
1396 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1397
Ian Romanickcc90e622010-10-19 17:59:10 -07001398 if ((var == NULL) || (var->mode != int(mode)))
Ian Romanick40e114b2010-08-17 14:55:50 -07001399 continue;
1400
Ian Romanickcc90e622010-10-19 17:59:10 -07001401 /* A shader 'in' or 'out' variable is only really an input or output if
1402 * its value is used by other shader stages. This will cause the variable
1403 * to have a location assigned.
Ian Romanick40e114b2010-08-17 14:55:50 -07001404 */
1405 if (var->location == -1) {
1406 var->mode = ir_var_auto;
1407 }
1408 }
1409}
1410
1411
Paul Berry871ddb92011-11-05 11:17:32 -07001412/**
1413 * Data structure tracking information about a transform feedback declaration
1414 * during linking.
1415 */
1416class tfeedback_decl
1417{
1418public:
Paul Berry456279b2011-12-26 19:39:25 -08001419 bool init(struct gl_context *ctx, struct gl_shader_program *prog,
1420 const void *mem_ctx, const char *input);
Paul Berry871ddb92011-11-05 11:17:32 -07001421 static bool is_same(const tfeedback_decl &x, const tfeedback_decl &y);
1422 bool assign_location(struct gl_context *ctx, struct gl_shader_program *prog,
1423 ir_variable *output_var);
Christoph Bumillerd540af52012-01-20 13:24:46 +01001424 bool accumulate_num_outputs(struct gl_shader_program *prog, unsigned *count);
Paul Berryd3150eb2012-01-09 11:25:14 -08001425 bool store(struct gl_context *ctx, struct gl_shader_program *prog,
Eric Anholt9d36c962012-01-02 17:08:13 -08001426 struct gl_transform_feedback_info *info, unsigned buffer,
Christoph Bumillerd540af52012-01-20 13:24:46 +01001427 unsigned varying, const unsigned max_outputs) const;
Paul Berry871ddb92011-11-05 11:17:32 -07001428
1429
1430 /**
1431 * True if assign_location() has been called for this object.
1432 */
1433 bool is_assigned() const
1434 {
1435 return this->location != -1;
1436 }
1437
1438 /**
1439 * Determine whether this object refers to the variable var.
1440 */
1441 bool matches_var(ir_variable *var) const
1442 {
Paul Berry642e5b412012-01-04 13:57:52 -08001443 if (this->is_clip_distance_mesa)
1444 return strcmp(var->name, "gl_ClipDistanceMESA") == 0;
1445 else
1446 return strcmp(var->name, this->var_name) == 0;
Paul Berry871ddb92011-11-05 11:17:32 -07001447 }
1448
1449 /**
1450 * The total number of varying components taken up by this variable. Only
1451 * valid if is_assigned() is true.
1452 */
1453 unsigned num_components() const
1454 {
Paul Berry642e5b412012-01-04 13:57:52 -08001455 if (this->is_clip_distance_mesa)
1456 return this->size;
Paul Berrybe4e9f72012-01-04 12:21:55 -08001457 else
Paul Berry642e5b412012-01-04 13:57:52 -08001458 return this->vector_elements * this->matrix_columns * this->size;
Paul Berry871ddb92011-11-05 11:17:32 -07001459 }
1460
1461private:
1462 /**
1463 * The name that was supplied to glTransformFeedbackVaryings. Used for
Eric Anholt9d36c962012-01-02 17:08:13 -08001464 * error reporting and glGetTransformFeedbackVarying().
Paul Berry871ddb92011-11-05 11:17:32 -07001465 */
1466 const char *orig_name;
1467
1468 /**
1469 * The name of the variable, parsed from orig_name.
1470 */
Paul Berry913a5c22011-12-27 08:24:57 -08001471 const char *var_name;
Paul Berry871ddb92011-11-05 11:17:32 -07001472
1473 /**
1474 * True if the declaration in orig_name represents an array.
1475 */
Paul Berry33fe0212012-01-03 20:41:34 -08001476 bool is_subscripted;
Paul Berry871ddb92011-11-05 11:17:32 -07001477
1478 /**
Paul Berry33fe0212012-01-03 20:41:34 -08001479 * If is_subscripted is true, the subscript that was specified in orig_name.
Paul Berry871ddb92011-11-05 11:17:32 -07001480 */
Paul Berry33fe0212012-01-03 20:41:34 -08001481 unsigned array_subscript;
Paul Berry871ddb92011-11-05 11:17:32 -07001482
1483 /**
Paul Berry642e5b412012-01-04 13:57:52 -08001484 * True if the variable is gl_ClipDistance and the driver lowers
1485 * gl_ClipDistance to gl_ClipDistanceMESA.
Paul Berry456279b2011-12-26 19:39:25 -08001486 */
Paul Berry642e5b412012-01-04 13:57:52 -08001487 bool is_clip_distance_mesa;
Paul Berry456279b2011-12-26 19:39:25 -08001488
1489 /**
Paul Berry871ddb92011-11-05 11:17:32 -07001490 * The vertex shader output location that the linker assigned for this
1491 * variable. -1 if a location hasn't been assigned yet.
1492 */
1493 int location;
1494
1495 /**
1496 * If location != -1, the number of vector elements in this variable, or 1
1497 * if this variable is a scalar.
1498 */
1499 unsigned vector_elements;
1500
1501 /**
1502 * If location != -1, the number of matrix columns in this variable, or 1
1503 * if this variable is not a matrix.
1504 */
1505 unsigned matrix_columns;
Eric Anholt9d36c962012-01-02 17:08:13 -08001506
1507 /** Type of the varying returned by glGetTransformFeedbackVarying() */
1508 GLenum type;
Paul Berry33fe0212012-01-03 20:41:34 -08001509
1510 /**
1511 * If location != -1, the size that should be returned by
1512 * glGetTransformFeedbackVarying().
1513 */
1514 unsigned size;
Paul Berry871ddb92011-11-05 11:17:32 -07001515};
1516
1517
1518/**
1519 * Initialize this object based on a string that was passed to
1520 * glTransformFeedbackVaryings. If there is a parse error, the error is
1521 * reported using linker_error(), and false is returned.
1522 */
1523bool
Paul Berry456279b2011-12-26 19:39:25 -08001524tfeedback_decl::init(struct gl_context *ctx, struct gl_shader_program *prog,
1525 const void *mem_ctx, const char *input)
Paul Berry871ddb92011-11-05 11:17:32 -07001526{
1527 /* We don't have to be pedantic about what is a valid GLSL variable name,
1528 * because any variable with an invalid name can't exist in the IR anyway.
1529 */
1530
1531 this->location = -1;
1532 this->orig_name = input;
Paul Berry642e5b412012-01-04 13:57:52 -08001533 this->is_clip_distance_mesa = false;
Paul Berry871ddb92011-11-05 11:17:32 -07001534
1535 const char *bracket = strrchr(input, '[');
1536
1537 if (bracket) {
1538 this->var_name = ralloc_strndup(mem_ctx, input, bracket - input);
Paul Berry33fe0212012-01-03 20:41:34 -08001539 if (sscanf(bracket, "[%u]", &this->array_subscript) != 1) {
Paul Berry456279b2011-12-26 19:39:25 -08001540 linker_error(prog, "Cannot parse transform feedback varying %s", input);
1541 return false;
Paul Berry871ddb92011-11-05 11:17:32 -07001542 }
Paul Berry33fe0212012-01-03 20:41:34 -08001543 this->is_subscripted = true;
Paul Berry871ddb92011-11-05 11:17:32 -07001544 } else {
1545 this->var_name = ralloc_strdup(mem_ctx, input);
Paul Berry33fe0212012-01-03 20:41:34 -08001546 this->is_subscripted = false;
Paul Berry871ddb92011-11-05 11:17:32 -07001547 }
1548
Paul Berry642e5b412012-01-04 13:57:52 -08001549 /* For drivers that lower gl_ClipDistance to gl_ClipDistanceMESA, this
1550 * class must behave specially to account for the fact that gl_ClipDistance
1551 * is converted from a float[8] to a vec4[2].
Paul Berry456279b2011-12-26 19:39:25 -08001552 */
1553 if (ctx->ShaderCompilerOptions[MESA_SHADER_VERTEX].LowerClipDistance &&
1554 strcmp(this->var_name, "gl_ClipDistance") == 0) {
Paul Berry642e5b412012-01-04 13:57:52 -08001555 this->is_clip_distance_mesa = true;
Paul Berry456279b2011-12-26 19:39:25 -08001556 }
1557
1558 return true;
Paul Berry871ddb92011-11-05 11:17:32 -07001559}
1560
1561
1562/**
1563 * Determine whether two tfeedback_decl objects refer to the same variable and
1564 * array index (if applicable).
1565 */
1566bool
1567tfeedback_decl::is_same(const tfeedback_decl &x, const tfeedback_decl &y)
1568{
1569 if (strcmp(x.var_name, y.var_name) != 0)
1570 return false;
Paul Berry33fe0212012-01-03 20:41:34 -08001571 if (x.is_subscripted != y.is_subscripted)
Paul Berry871ddb92011-11-05 11:17:32 -07001572 return false;
Paul Berry33fe0212012-01-03 20:41:34 -08001573 if (x.is_subscripted && x.array_subscript != y.array_subscript)
Paul Berry871ddb92011-11-05 11:17:32 -07001574 return false;
1575 return true;
1576}
1577
1578
1579/**
1580 * Assign a location for this tfeedback_decl object based on the location
1581 * assignment in output_var.
1582 *
1583 * If an error occurs, the error is reported through linker_error() and false
1584 * is returned.
1585 */
1586bool
1587tfeedback_decl::assign_location(struct gl_context *ctx,
1588 struct gl_shader_program *prog,
1589 ir_variable *output_var)
1590{
1591 if (output_var->type->is_array()) {
1592 /* Array variable */
Paul Berry871ddb92011-11-05 11:17:32 -07001593 const unsigned matrix_cols =
1594 output_var->type->fields.array->matrix_columns;
Paul Berry642e5b412012-01-04 13:57:52 -08001595 unsigned actual_array_size = this->is_clip_distance_mesa ?
1596 prog->Vert.ClipDistanceArraySize : output_var->type->array_size();
Paul Berry33fe0212012-01-03 20:41:34 -08001597
1598 if (this->is_subscripted) {
1599 /* Check array bounds. */
Paul Berry642e5b412012-01-04 13:57:52 -08001600 if (this->array_subscript >= actual_array_size) {
Paul Berry33fe0212012-01-03 20:41:34 -08001601 linker_error(prog, "Transform feedback varying %s has index "
Paul Berry642e5b412012-01-04 13:57:52 -08001602 "%i, but the array size is %u.",
Paul Berry33fe0212012-01-03 20:41:34 -08001603 this->orig_name, this->array_subscript,
Paul Berry642e5b412012-01-04 13:57:52 -08001604 actual_array_size);
Paul Berry33fe0212012-01-03 20:41:34 -08001605 return false;
1606 }
Paul Berry642e5b412012-01-04 13:57:52 -08001607 if (this->is_clip_distance_mesa) {
1608 this->location =
1609 output_var->location + this->array_subscript / 4;
1610 } else {
1611 this->location =
1612 output_var->location + this->array_subscript * matrix_cols;
1613 }
Paul Berry33fe0212012-01-03 20:41:34 -08001614 this->size = 1;
1615 } else {
1616 this->location = output_var->location;
Paul Berry642e5b412012-01-04 13:57:52 -08001617 this->size = actual_array_size;
Paul Berry33fe0212012-01-03 20:41:34 -08001618 }
Paul Berry871ddb92011-11-05 11:17:32 -07001619 this->vector_elements = output_var->type->fields.array->vector_elements;
1620 this->matrix_columns = matrix_cols;
Paul Berry642e5b412012-01-04 13:57:52 -08001621 if (this->is_clip_distance_mesa)
1622 this->type = GL_FLOAT;
1623 else
1624 this->type = output_var->type->fields.array->gl_type;
Paul Berry871ddb92011-11-05 11:17:32 -07001625 } else {
1626 /* Regular variable (scalar, vector, or matrix) */
Paul Berry33fe0212012-01-03 20:41:34 -08001627 if (this->is_subscripted) {
Paul Berry108cba22012-01-04 15:17:52 -08001628 linker_error(prog, "Transform feedback varying %s requested, "
1629 "but %s is not an array.",
1630 this->orig_name, this->var_name);
Paul Berry871ddb92011-11-05 11:17:32 -07001631 return false;
1632 }
1633 this->location = output_var->location;
Paul Berry33fe0212012-01-03 20:41:34 -08001634 this->size = 1;
Paul Berry871ddb92011-11-05 11:17:32 -07001635 this->vector_elements = output_var->type->vector_elements;
1636 this->matrix_columns = output_var->type->matrix_columns;
Eric Anholt9d36c962012-01-02 17:08:13 -08001637 this->type = output_var->type->gl_type;
Paul Berry871ddb92011-11-05 11:17:32 -07001638 }
Paul Berry642e5b412012-01-04 13:57:52 -08001639
Paul Berry871ddb92011-11-05 11:17:32 -07001640 /* From GL_EXT_transform_feedback:
1641 * A program will fail to link if:
1642 *
1643 * * the total number of components to capture in any varying
1644 * variable in <varyings> is greater than the constant
1645 * MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT and the
1646 * buffer mode is SEPARATE_ATTRIBS_EXT;
1647 */
1648 if (prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS &&
1649 this->num_components() >
1650 ctx->Const.MaxTransformFeedbackSeparateComponents) {
1651 linker_error(prog, "Transform feedback varying %s exceeds "
1652 "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS.",
1653 this->orig_name);
1654 return false;
1655 }
1656
1657 return true;
1658}
1659
1660
Paul Berry871ddb92011-11-05 11:17:32 -07001661bool
Christoph Bumillerd540af52012-01-20 13:24:46 +01001662tfeedback_decl::accumulate_num_outputs(struct gl_shader_program *prog,
1663 unsigned *count)
Paul Berry871ddb92011-11-05 11:17:32 -07001664{
1665 if (!this->is_assigned()) {
1666 /* From GL_EXT_transform_feedback:
1667 * A program will fail to link if:
1668 *
1669 * * any variable name specified in the <varyings> array is not
1670 * declared as an output in the geometry shader (if present) or
1671 * the vertex shader (if no geometry shader is present);
1672 */
1673 linker_error(prog, "Transform feedback varying %s undeclared.",
1674 this->orig_name);
1675 return false;
1676 }
Paul Berryd3150eb2012-01-09 11:25:14 -08001677
Christoph Bumillerd540af52012-01-20 13:24:46 +01001678 unsigned translated_size = this->size;
1679 if (this->is_clip_distance_mesa)
1680 translated_size = (translated_size + 3) / 4;
1681
1682 *count += translated_size * this->matrix_columns;
1683
1684 return true;
1685}
1686
1687
1688/**
1689 * Update gl_transform_feedback_info to reflect this tfeedback_decl.
1690 *
1691 * If an error occurs, the error is reported through linker_error() and false
1692 * is returned.
1693 */
1694bool
1695tfeedback_decl::store(struct gl_context *ctx, struct gl_shader_program *prog,
1696 struct gl_transform_feedback_info *info,
1697 unsigned buffer,
1698 unsigned varying, const unsigned max_outputs) const
1699{
Paul Berryd3150eb2012-01-09 11:25:14 -08001700 /* From GL_EXT_transform_feedback:
1701 * A program will fail to link if:
1702 *
1703 * * the total number of components to capture is greater than
1704 * the constant MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT
1705 * and the buffer mode is INTERLEAVED_ATTRIBS_EXT.
1706 */
1707 if (prog->TransformFeedback.BufferMode == GL_INTERLEAVED_ATTRIBS &&
1708 info->BufferStride[buffer] + this->num_components() >
1709 ctx->Const.MaxTransformFeedbackInterleavedComponents) {
1710 linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1711 "limit has been exceeded.");
1712 return false;
1713 }
1714
Paul Berry642e5b412012-01-04 13:57:52 -08001715 unsigned translated_size = this->size;
1716 if (this->is_clip_distance_mesa)
1717 translated_size = (translated_size + 3) / 4;
Paul Berrybe4e9f72012-01-04 12:21:55 -08001718 unsigned components_so_far = 0;
Paul Berry642e5b412012-01-04 13:57:52 -08001719 for (unsigned index = 0; index < translated_size; ++index) {
Paul Berry33fe0212012-01-03 20:41:34 -08001720 for (unsigned v = 0; v < this->matrix_columns; ++v) {
Paul Berry642e5b412012-01-04 13:57:52 -08001721 unsigned num_components = this->vector_elements;
Christoph Bumillerd540af52012-01-20 13:24:46 +01001722 assert(info->NumOutputs < max_outputs);
Paul Berry642e5b412012-01-04 13:57:52 -08001723 info->Outputs[info->NumOutputs].ComponentOffset = 0;
1724 if (this->is_clip_distance_mesa) {
1725 if (this->is_subscripted) {
1726 num_components = 1;
1727 info->Outputs[info->NumOutputs].ComponentOffset =
1728 this->array_subscript % 4;
1729 } else {
1730 num_components = MIN2(4, this->size - components_so_far);
1731 }
1732 }
Paul Berry33fe0212012-01-03 20:41:34 -08001733 info->Outputs[info->NumOutputs].OutputRegister =
1734 this->location + v + index * this->matrix_columns;
1735 info->Outputs[info->NumOutputs].NumComponents = num_components;
1736 info->Outputs[info->NumOutputs].OutputBuffer = buffer;
1737 info->Outputs[info->NumOutputs].DstOffset = info->BufferStride[buffer];
Paul Berry33fe0212012-01-03 20:41:34 -08001738 ++info->NumOutputs;
1739 info->BufferStride[buffer] += num_components;
Paul Berrybe4e9f72012-01-04 12:21:55 -08001740 components_so_far += num_components;
Paul Berry33fe0212012-01-03 20:41:34 -08001741 }
Paul Berry871ddb92011-11-05 11:17:32 -07001742 }
Paul Berrybe4e9f72012-01-04 12:21:55 -08001743 assert(components_so_far == this->num_components());
Eric Anholt9d36c962012-01-02 17:08:13 -08001744
1745 info->Varyings[varying].Name = ralloc_strdup(prog, this->orig_name);
1746 info->Varyings[varying].Type = this->type;
Paul Berry33fe0212012-01-03 20:41:34 -08001747 info->Varyings[varying].Size = this->size;
Eric Anholt9d36c962012-01-02 17:08:13 -08001748 info->NumVarying++;
1749
Paul Berry871ddb92011-11-05 11:17:32 -07001750 return true;
1751}
1752
1753
1754/**
1755 * Parse all the transform feedback declarations that were passed to
1756 * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
1757 *
1758 * If an error occurs, the error is reported through linker_error() and false
1759 * is returned.
1760 */
1761static bool
Paul Berry456279b2011-12-26 19:39:25 -08001762parse_tfeedback_decls(struct gl_context *ctx, struct gl_shader_program *prog,
1763 const void *mem_ctx, unsigned num_names,
1764 char **varying_names, tfeedback_decl *decls)
Paul Berry871ddb92011-11-05 11:17:32 -07001765{
1766 for (unsigned i = 0; i < num_names; ++i) {
Paul Berry456279b2011-12-26 19:39:25 -08001767 if (!decls[i].init(ctx, prog, mem_ctx, varying_names[i]))
Paul Berry871ddb92011-11-05 11:17:32 -07001768 return false;
1769 /* From GL_EXT_transform_feedback:
1770 * A program will fail to link if:
1771 *
1772 * * any two entries in the <varyings> array specify the same varying
1773 * variable;
1774 *
1775 * We interpret this to mean "any two entries in the <varyings> array
1776 * specify the same varying variable and array index", since transform
1777 * feedback of arrays would be useless otherwise.
1778 */
1779 for (unsigned j = 0; j < i; ++j) {
1780 if (tfeedback_decl::is_same(decls[i], decls[j])) {
1781 linker_error(prog, "Transform feedback varying %s specified "
1782 "more than once.", varying_names[i]);
1783 return false;
1784 }
1785 }
1786 }
1787 return true;
1788}
1789
1790
1791/**
1792 * Assign a location for a variable that is produced in one pipeline stage
1793 * (the "producer") and consumed in the next stage (the "consumer").
1794 *
1795 * \param input_var is the input variable declaration in the consumer.
1796 *
1797 * \param output_var is the output variable declaration in the producer.
1798 *
1799 * \param input_index is the counter that keeps track of assigned input
1800 * locations in the consumer.
1801 *
1802 * \param output_index is the counter that keeps track of assigned output
1803 * locations in the producer.
1804 *
1805 * It is permissible for \c input_var to be NULL (this happens if a variable
1806 * is output by the producer and consumed by transform feedback, but not
1807 * consumed by the consumer).
1808 *
1809 * If the variable has already been assigned a location, this function has no
1810 * effect.
1811 */
1812void
1813assign_varying_location(ir_variable *input_var, ir_variable *output_var,
1814 unsigned *input_index, unsigned *output_index)
1815{
1816 if (output_var->location != -1) {
1817 /* Location already assigned. */
1818 return;
1819 }
1820
1821 if (input_var) {
1822 assert(input_var->location == -1);
1823 input_var->location = *input_index;
1824 }
1825
1826 output_var->location = *output_index;
1827
1828 /* FINISHME: Support for "varying" records in GLSL 1.50. */
1829 assert(!output_var->type->is_record());
1830
1831 if (output_var->type->is_array()) {
1832 const unsigned slots = output_var->type->length
1833 * output_var->type->fields.array->matrix_columns;
1834
1835 *output_index += slots;
1836 *input_index += slots;
1837 } else {
1838 const unsigned slots = output_var->type->matrix_columns;
1839
1840 *output_index += slots;
1841 *input_index += slots;
1842 }
1843}
1844
1845
1846/**
1847 * Assign locations for all variables that are produced in one pipeline stage
1848 * (the "producer") and consumed in the next stage (the "consumer").
1849 *
1850 * Variables produced by the producer may also be consumed by transform
1851 * feedback.
1852 *
1853 * \param num_tfeedback_decls is the number of declarations indicating
1854 * variables that may be consumed by transform feedback.
1855 *
1856 * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
1857 * representing the result of parsing the strings passed to
1858 * glTransformFeedbackVaryings(). assign_location() will be called for
1859 * each of these objects that matches one of the outputs of the
1860 * producer.
1861 *
1862 * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
1863 * be NULL. In this case, varying locations are assigned solely based on the
1864 * requirements of transform feedback.
1865 */
Ian Romanickde773242011-06-09 13:31:32 -07001866bool
1867assign_varying_locations(struct gl_context *ctx,
1868 struct gl_shader_program *prog,
Paul Berry871ddb92011-11-05 11:17:32 -07001869 gl_shader *producer, gl_shader *consumer,
1870 unsigned num_tfeedback_decls,
1871 tfeedback_decl *tfeedback_decls)
Ian Romanick0e59b262010-06-23 11:23:01 -07001872{
1873 /* FINISHME: Set dynamically when geometry shader support is added. */
1874 unsigned output_index = VERT_RESULT_VAR0;
1875 unsigned input_index = FRAG_ATTRIB_VAR0;
1876
1877 /* Operate in a total of three passes.
1878 *
1879 * 1. Assign locations for any matching inputs and outputs.
1880 *
1881 * 2. Mark output variables in the producer that do not have locations as
1882 * not being outputs. This lets the optimizer eliminate them.
1883 *
1884 * 3. Mark input variables in the consumer that do not have locations as
1885 * not being inputs. This lets the optimizer eliminate them.
1886 */
1887
Ian Romanickf6ee7bc2011-10-11 16:15:47 -07001888 link_invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
Paul Berry871ddb92011-11-05 11:17:32 -07001889 if (consumer)
1890 link_invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
Ian Romanick0e59b262010-06-23 11:23:01 -07001891
Eric Anholt16b68b12010-06-30 11:05:43 -07001892 foreach_list(node, producer->ir) {
Ian Romanick0e59b262010-06-23 11:23:01 -07001893 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1894
Paul Berry871ddb92011-11-05 11:17:32 -07001895 if ((output_var == NULL) || (output_var->mode != ir_var_out))
Ian Romanick0e59b262010-06-23 11:23:01 -07001896 continue;
1897
Paul Berry871ddb92011-11-05 11:17:32 -07001898 ir_variable *input_var =
1899 consumer ? consumer->symbols->get_variable(output_var->name) : NULL;
Ian Romanick0e59b262010-06-23 11:23:01 -07001900
Paul Berry871ddb92011-11-05 11:17:32 -07001901 if (input_var && input_var->mode != ir_var_in)
1902 input_var = NULL;
Ian Romanick0e59b262010-06-23 11:23:01 -07001903
Paul Berry871ddb92011-11-05 11:17:32 -07001904 if (input_var) {
1905 assign_varying_location(input_var, output_var, &input_index,
1906 &output_index);
1907 }
Ian Romanick0e59b262010-06-23 11:23:01 -07001908
Paul Berry871ddb92011-11-05 11:17:32 -07001909 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1910 if (!tfeedback_decls[i].is_assigned() &&
1911 tfeedback_decls[i].matches_var(output_var)) {
1912 if (output_var->location == -1) {
1913 assign_varying_location(input_var, output_var, &input_index,
1914 &output_index);
1915 }
1916 if (!tfeedback_decls[i].assign_location(ctx, prog, output_var))
1917 return false;
1918 }
Ian Romanickdf869d92010-08-30 15:37:44 -07001919 }
Ian Romanick0e59b262010-06-23 11:23:01 -07001920 }
1921
Ian Romanickde773242011-06-09 13:31:32 -07001922 unsigned varying_vectors = 0;
1923
Paul Berry871ddb92011-11-05 11:17:32 -07001924 if (consumer) {
1925 foreach_list(node, consumer->ir) {
1926 ir_variable *const var = ((ir_instruction *) node)->as_variable();
Ian Romanick0e59b262010-06-23 11:23:01 -07001927
Paul Berry871ddb92011-11-05 11:17:32 -07001928 if ((var == NULL) || (var->mode != ir_var_in))
1929 continue;
Ian Romanick0e59b262010-06-23 11:23:01 -07001930
Paul Berry871ddb92011-11-05 11:17:32 -07001931 if (var->location == -1) {
1932 if (prog->Version <= 120) {
1933 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1934 *
1935 * Only those varying variables used (i.e. read) in
1936 * the fragment shader executable must be written to
1937 * by the vertex shader executable; declaring
1938 * superfluous varying variables in a vertex shader is
1939 * permissible.
1940 *
1941 * We interpret this text as meaning that the VS must
1942 * write the variable for the FS to read it. See
1943 * "glsl1-varying read but not written" in piglit.
1944 */
Eric Anholtb7062832010-07-28 13:52:23 -07001945
Paul Berry871ddb92011-11-05 11:17:32 -07001946 linker_error(prog, "fragment shader varying %s not written "
1947 "by vertex shader\n.", var->name);
1948 }
Eric Anholtb7062832010-07-28 13:52:23 -07001949
Paul Berry871ddb92011-11-05 11:17:32 -07001950 /* An 'in' variable is only really a shader input if its
1951 * value is written by the previous stage.
1952 */
1953 var->mode = ir_var_auto;
1954 } else {
1955 /* The packing rules are used for vertex shader inputs are also
1956 * used for fragment shader inputs.
1957 */
1958 varying_vectors += count_attribute_slots(var->type);
1959 }
Eric Anholtb7062832010-07-28 13:52:23 -07001960 }
Ian Romanick0e59b262010-06-23 11:23:01 -07001961 }
Ian Romanickde773242011-06-09 13:31:32 -07001962
1963 if (ctx->API == API_OPENGLES2 || prog->Version == 100) {
1964 if (varying_vectors > ctx->Const.MaxVarying) {
Marek Olšákdf809ae2011-12-10 04:14:46 +01001965 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
1966 linker_warning(prog, "shader uses too many varying vectors "
1967 "(%u > %u), but the driver will try to optimize "
1968 "them out; this is non-portable out-of-spec "
1969 "behavior\n",
1970 varying_vectors, ctx->Const.MaxVarying);
1971 } else {
1972 linker_error(prog, "shader uses too many varying vectors "
1973 "(%u > %u)\n",
1974 varying_vectors, ctx->Const.MaxVarying);
1975 return false;
1976 }
Ian Romanickde773242011-06-09 13:31:32 -07001977 }
1978 } else {
1979 const unsigned float_components = varying_vectors * 4;
1980 if (float_components > ctx->Const.MaxVarying * 4) {
Marek Olšákdf809ae2011-12-10 04:14:46 +01001981 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
1982 linker_warning(prog, "shader uses too many varying components "
1983 "(%u > %u), but the driver will try to optimize "
1984 "them out; this is non-portable out-of-spec "
1985 "behavior\n",
1986 float_components, ctx->Const.MaxVarying * 4);
1987 } else {
1988 linker_error(prog, "shader uses too many varying components "
1989 "(%u > %u)\n",
1990 float_components, ctx->Const.MaxVarying * 4);
1991 return false;
1992 }
Ian Romanickde773242011-06-09 13:31:32 -07001993 }
1994 }
1995
1996 return true;
Ian Romanick0e59b262010-06-23 11:23:01 -07001997}
1998
1999
Paul Berry871ddb92011-11-05 11:17:32 -07002000/**
2001 * Store transform feedback location assignments into
2002 * prog->LinkedTransformFeedback based on the data stored in tfeedback_decls.
2003 *
2004 * If an error occurs, the error is reported through linker_error() and false
2005 * is returned.
2006 */
2007static bool
2008store_tfeedback_info(struct gl_context *ctx, struct gl_shader_program *prog,
2009 unsigned num_tfeedback_decls,
2010 tfeedback_decl *tfeedback_decls)
2011{
Paul Berryebfad9f2011-12-29 15:55:01 -08002012 bool separate_attribs_mode =
2013 prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS;
Eric Anholt9d36c962012-01-02 17:08:13 -08002014
2015 ralloc_free(prog->LinkedTransformFeedback.Varyings);
Christoph Bumillerd540af52012-01-20 13:24:46 +01002016 ralloc_free(prog->LinkedTransformFeedback.Outputs);
Eric Anholt9d36c962012-01-02 17:08:13 -08002017
2018 memset(&prog->LinkedTransformFeedback, 0,
2019 sizeof(prog->LinkedTransformFeedback));
2020
Paul Berry1be0fd82012-01-05 13:06:36 -08002021 prog->LinkedTransformFeedback.NumBuffers =
2022 separate_attribs_mode ? num_tfeedback_decls : 1;
2023
Eric Anholt9d36c962012-01-02 17:08:13 -08002024 prog->LinkedTransformFeedback.Varyings =
Eric Anholt5a0f3952012-01-12 13:10:26 -08002025 rzalloc_array(prog,
Eric Anholt9d36c962012-01-02 17:08:13 -08002026 struct gl_transform_feedback_varying_info,
2027 num_tfeedback_decls);
2028
Christoph Bumillerd540af52012-01-20 13:24:46 +01002029 unsigned num_outputs = 0;
2030 for (unsigned i = 0; i < num_tfeedback_decls; ++i)
2031 if (!tfeedback_decls[i].accumulate_num_outputs(prog, &num_outputs))
2032 return false;
2033
2034 prog->LinkedTransformFeedback.Outputs =
2035 rzalloc_array(prog,
2036 struct gl_transform_feedback_output,
2037 num_outputs);
2038
Paul Berry871ddb92011-11-05 11:17:32 -07002039 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
Paul Berryebfad9f2011-12-29 15:55:01 -08002040 unsigned buffer = separate_attribs_mode ? i : 0;
Paul Berryd3150eb2012-01-09 11:25:14 -08002041 if (!tfeedback_decls[i].store(ctx, prog, &prog->LinkedTransformFeedback,
Christoph Bumillerd540af52012-01-20 13:24:46 +01002042 buffer, i, num_outputs))
Paul Berry871ddb92011-11-05 11:17:32 -07002043 return false;
Paul Berry871ddb92011-11-05 11:17:32 -07002044 }
Christoph Bumillerd540af52012-01-20 13:24:46 +01002045 assert(prog->LinkedTransformFeedback.NumOutputs == num_outputs);
Paul Berry871ddb92011-11-05 11:17:32 -07002046
2047 return true;
2048}
2049
Ian Romanick92f81592011-11-08 12:37:19 -08002050/**
Marek Olšákec174a42011-11-18 15:00:10 +01002051 * Store the gl_FragDepth layout in the gl_shader_program struct.
2052 */
2053static void
2054store_fragdepth_layout(struct gl_shader_program *prog)
2055{
2056 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2057 return;
2058 }
2059
2060 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2061
2062 /* We don't look up the gl_FragDepth symbol directly because if
2063 * gl_FragDepth is not used in the shader, it's removed from the IR.
2064 * However, the symbol won't be removed from the symbol table.
2065 *
2066 * We're only interested in the cases where the variable is NOT removed
2067 * from the IR.
2068 */
2069 foreach_list(node, ir) {
2070 ir_variable *const var = ((ir_instruction *) node)->as_variable();
2071
2072 if (var == NULL || var->mode != ir_var_out) {
2073 continue;
2074 }
2075
2076 if (strcmp(var->name, "gl_FragDepth") == 0) {
2077 switch (var->depth_layout) {
2078 case ir_depth_layout_none:
2079 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2080 return;
2081 case ir_depth_layout_any:
2082 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2083 return;
2084 case ir_depth_layout_greater:
2085 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2086 return;
2087 case ir_depth_layout_less:
2088 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2089 return;
2090 case ir_depth_layout_unchanged:
2091 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2092 return;
2093 default:
2094 assert(0);
2095 return;
2096 }
2097 }
2098 }
2099}
2100
2101/**
Ian Romanick92f81592011-11-08 12:37:19 -08002102 * Validate the resources used by a program versus the implementation limits
2103 */
2104static bool
2105check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2106{
2107 static const char *const shader_names[MESA_SHADER_TYPES] = {
2108 "vertex", "fragment", "geometry"
2109 };
2110
2111 const unsigned max_samplers[MESA_SHADER_TYPES] = {
2112 ctx->Const.MaxVertexTextureImageUnits,
2113 ctx->Const.MaxTextureImageUnits,
2114 ctx->Const.MaxGeometryTextureImageUnits
2115 };
2116
2117 const unsigned max_uniform_components[MESA_SHADER_TYPES] = {
2118 ctx->Const.VertexProgram.MaxUniformComponents,
2119 ctx->Const.FragmentProgram.MaxUniformComponents,
2120 0 /* FINISHME: Geometry shaders. */
2121 };
2122
2123 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2124 struct gl_shader *sh = prog->_LinkedShaders[i];
2125
2126 if (sh == NULL)
2127 continue;
2128
2129 if (sh->num_samplers > max_samplers[i]) {
2130 linker_error(prog, "Too many %s shader texture samplers",
2131 shader_names[i]);
2132 }
2133
2134 if (sh->num_uniform_components > max_uniform_components[i]) {
Marek Olšákdf809ae2011-12-10 04:14:46 +01002135 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2136 linker_warning(prog, "Too many %s shader uniform components, "
2137 "but the driver will try to optimize them out; "
2138 "this is non-portable out-of-spec behavior\n",
2139 shader_names[i]);
2140 } else {
2141 linker_error(prog, "Too many %s shader uniform components",
2142 shader_names[i]);
2143 }
Ian Romanick92f81592011-11-08 12:37:19 -08002144 }
2145 }
2146
2147 return prog->LinkStatus;
2148}
Paul Berry871ddb92011-11-05 11:17:32 -07002149
Ian Romanick0e59b262010-06-23 11:23:01 -07002150void
Kristian Høgsbergf9995b32010-10-12 12:26:10 -04002151link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
Ian Romanick832dfa52010-06-17 15:04:20 -07002152{
Paul Berry871ddb92011-11-05 11:17:32 -07002153 tfeedback_decl *tfeedback_decls = NULL;
2154 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
2155
Kenneth Graunked3073f52011-01-21 14:32:31 -08002156 void *mem_ctx = ralloc_context(NULL); // temporary linker context
Kenneth Graunke2da02e72010-11-17 11:03:57 -08002157
Ian Romanick832dfa52010-06-17 15:04:20 -07002158 prog->LinkStatus = false;
2159 prog->Validated = false;
2160 prog->_Used = false;
2161
Ian Romanickf36460e2010-06-23 12:07:22 -07002162 if (prog->InfoLog != NULL)
Kenneth Graunked3073f52011-01-21 14:32:31 -08002163 ralloc_free(prog->InfoLog);
Ian Romanickf36460e2010-06-23 12:07:22 -07002164
Kenneth Graunked3073f52011-01-21 14:32:31 -08002165 prog->InfoLog = ralloc_strdup(NULL, "");
Ian Romanickf36460e2010-06-23 12:07:22 -07002166
Ian Romanick832dfa52010-06-17 15:04:20 -07002167 /* Separate the shaders into groups based on their type.
2168 */
Eric Anholt16b68b12010-06-30 11:05:43 -07002169 struct gl_shader **vert_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -07002170 unsigned num_vert_shaders = 0;
Eric Anholt16b68b12010-06-30 11:05:43 -07002171 struct gl_shader **frag_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -07002172 unsigned num_frag_shaders = 0;
2173
Eric Anholt16b68b12010-06-30 11:05:43 -07002174 vert_shader_list = (struct gl_shader **)
2175 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
Ian Romanick832dfa52010-06-17 15:04:20 -07002176 frag_shader_list = &vert_shader_list[prog->NumShaders];
2177
Ian Romanick25f51d32010-07-16 15:51:50 -07002178 unsigned min_version = UINT_MAX;
2179 unsigned max_version = 0;
Ian Romanick832dfa52010-06-17 15:04:20 -07002180 for (unsigned i = 0; i < prog->NumShaders; i++) {
Ian Romanick25f51d32010-07-16 15:51:50 -07002181 min_version = MIN2(min_version, prog->Shaders[i]->Version);
2182 max_version = MAX2(max_version, prog->Shaders[i]->Version);
2183
Ian Romanick832dfa52010-06-17 15:04:20 -07002184 switch (prog->Shaders[i]->Type) {
2185 case GL_VERTEX_SHADER:
2186 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
2187 num_vert_shaders++;
2188 break;
2189 case GL_FRAGMENT_SHADER:
2190 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
2191 num_frag_shaders++;
2192 break;
2193 case GL_GEOMETRY_SHADER:
2194 /* FINISHME: Support geometry shaders. */
2195 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
2196 break;
2197 }
2198 }
2199
Ian Romanick25f51d32010-07-16 15:51:50 -07002200 /* Previous to GLSL version 1.30, different compilation units could mix and
2201 * match shading language versions. With GLSL 1.30 and later, the versions
2202 * of all shaders must match.
2203 */
Kenneth Graunke5a81d052010-08-31 09:33:58 -07002204 assert(min_version >= 100);
Eric Anholtc5ff9a82012-03-08 13:49:15 -08002205 assert(max_version <= 140);
Kenneth Graunke5a81d052010-08-31 09:33:58 -07002206 if ((max_version >= 130 || min_version == 100)
2207 && min_version != max_version) {
Ian Romanick586e7412011-07-28 14:04:09 -07002208 linker_error(prog, "all shaders must use same shading "
2209 "language version\n");
Ian Romanick25f51d32010-07-16 15:51:50 -07002210 goto done;
2211 }
2212
2213 prog->Version = max_version;
2214
Ian Romanick3322fba2010-10-14 13:28:42 -07002215 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
2216 if (prog->_LinkedShaders[i] != NULL)
2217 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
2218
2219 prog->_LinkedShaders[i] = NULL;
Eric Anholt5d0f4302010-08-18 12:02:35 -07002220 }
2221
Ian Romanickcd6764e2010-07-16 16:00:07 -07002222 /* Link all shaders for a particular stage and validate the result.
2223 */
Ian Romanickcc22c5a2010-06-18 17:13:42 -07002224 if (num_vert_shaders > 0) {
Ian Romanick3fb87872010-07-09 14:09:34 -07002225 gl_shader *const sh =
Kenneth Graunke2da02e72010-11-17 11:03:57 -08002226 link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
2227 num_vert_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07002228
2229 if (sh == NULL)
2230 goto done;
2231
2232 if (!validate_vertex_shader_executable(prog, sh))
Ian Romanickf29ff6e2010-10-14 17:55:17 -07002233 goto done;
Ian Romanick3fb87872010-07-09 14:09:34 -07002234
Ian Romanick3322fba2010-10-14 13:28:42 -07002235 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
2236 sh);
Ian Romanickcc22c5a2010-06-18 17:13:42 -07002237 }
2238
2239 if (num_frag_shaders > 0) {
Ian Romanick3fb87872010-07-09 14:09:34 -07002240 gl_shader *const sh =
Kenneth Graunke2da02e72010-11-17 11:03:57 -08002241 link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
2242 num_frag_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07002243
2244 if (sh == NULL)
2245 goto done;
2246
2247 if (!validate_fragment_shader_executable(prog, sh))
Ian Romanickf29ff6e2010-10-14 17:55:17 -07002248 goto done;
Ian Romanick3fb87872010-07-09 14:09:34 -07002249
Ian Romanick3322fba2010-10-14 13:28:42 -07002250 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
2251 sh);
Ian Romanickcc22c5a2010-06-18 17:13:42 -07002252 }
2253
Ian Romanick3ed850e2010-06-23 12:18:21 -07002254 /* Here begins the inter-stage linking phase. Some initial validation is
2255 * performed, then locations are assigned for uniforms, attributes, and
2256 * varyings.
2257 */
Ian Romanicked1fe3d2010-06-23 12:09:14 -07002258 if (cross_validate_uniforms(prog)) {
Ian Romanick3322fba2010-10-14 13:28:42 -07002259 unsigned prev;
2260
2261 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2262 if (prog->_LinkedShaders[prev] != NULL)
2263 break;
2264 }
2265
Bryan Cainf18a0862011-04-23 19:29:15 -05002266 /* Validate the inputs of each stage with the output of the preceding
Ian Romanick37101922010-06-18 19:02:10 -07002267 * stage.
2268 */
Ian Romanick3322fba2010-10-14 13:28:42 -07002269 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2270 if (prog->_LinkedShaders[i] == NULL)
2271 continue;
2272
Ian Romanickf36460e2010-06-23 12:07:22 -07002273 if (!cross_validate_outputs_to_inputs(prog,
Ian Romanick3322fba2010-10-14 13:28:42 -07002274 prog->_LinkedShaders[prev],
Ian Romanickabee16e2010-06-21 16:16:05 -07002275 prog->_LinkedShaders[i]))
Ian Romanick37101922010-06-18 19:02:10 -07002276 goto done;
Ian Romanick3322fba2010-10-14 13:28:42 -07002277
2278 prev = i;
Ian Romanick37101922010-06-18 19:02:10 -07002279 }
2280
Ian Romanickcc22c5a2010-06-18 17:13:42 -07002281 prog->LinkStatus = true;
Ian Romanick37101922010-06-18 19:02:10 -07002282 }
Ian Romanick832dfa52010-06-17 15:04:20 -07002283
Eric Anholt2f4fe152010-08-10 13:06:49 -07002284 /* Do common optimization before assigning storage for attributes,
2285 * uniforms, and varyings. Later optimization could possibly make
2286 * some of that unused.
2287 */
Ian Romanick3322fba2010-10-14 13:28:42 -07002288 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2289 if (prog->_LinkedShaders[i] == NULL)
2290 continue;
2291
Ian Romanick02c5ae12011-07-11 10:46:01 -07002292 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
2293 if (!prog->LinkStatus)
2294 goto done;
2295
Paul Berryc06e3252011-08-11 20:58:21 -07002296 if (ctx->ShaderCompilerOptions[i].LowerClipDistance)
2297 lower_clip_distance(prog->_LinkedShaders[i]->ir);
2298
Brian Paul7feabfe2012-03-20 17:43:12 -06002299 unsigned max_unroll = ctx->ShaderCompilerOptions[i].MaxUnrollIterations;
2300
2301 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false, max_unroll))
Eric Anholt2f4fe152010-08-10 13:06:49 -07002302 ;
Ian Romanicka7ba9a72010-07-20 13:36:32 -07002303 }
Ian Romanick13e10e42010-06-21 12:03:24 -07002304
Ian Romanickd32d4f72011-06-27 17:59:58 -07002305 /* FINISHME: The value of the max_attribute_index parameter is
2306 * FINISHME: implementation dependent based on the value of
2307 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
2308 * FINISHME: at least 16, so hardcode 16 for now.
2309 */
2310 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX, 16)) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07002311 goto done;
2312 }
2313
2314 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, ctx->Const.MaxDrawBuffers)) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07002315 goto done;
Ian Romanick40e114b2010-08-17 14:55:50 -07002316 }
2317
Ian Romanick3322fba2010-10-14 13:28:42 -07002318 unsigned prev;
2319 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2320 if (prog->_LinkedShaders[prev] != NULL)
2321 break;
2322 }
2323
Paul Berry871ddb92011-11-05 11:17:32 -07002324 if (num_tfeedback_decls != 0) {
2325 /* From GL_EXT_transform_feedback:
2326 * A program will fail to link if:
2327 *
2328 * * the <count> specified by TransformFeedbackVaryingsEXT is
2329 * non-zero, but the program object has no vertex or geometry
2330 * shader;
2331 */
2332 if (prev >= MESA_SHADER_FRAGMENT) {
2333 linker_error(prog, "Transform feedback varyings specified, but "
2334 "no vertex or geometry shader is present.");
2335 goto done;
2336 }
2337
2338 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
2339 prog->TransformFeedback.NumVarying);
Paul Berry456279b2011-12-26 19:39:25 -08002340 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
Paul Berry871ddb92011-11-05 11:17:32 -07002341 prog->TransformFeedback.VaryingNames,
2342 tfeedback_decls))
2343 goto done;
2344 }
2345
Ian Romanick3322fba2010-10-14 13:28:42 -07002346 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2347 if (prog->_LinkedShaders[i] == NULL)
2348 continue;
2349
Paul Berry871ddb92011-11-05 11:17:32 -07002350 if (!assign_varying_locations(
2351 ctx, prog, prog->_LinkedShaders[prev], prog->_LinkedShaders[i],
2352 i == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2353 tfeedback_decls))
Ian Romanickde773242011-06-09 13:31:32 -07002354 goto done;
Ian Romanickde773242011-06-09 13:31:32 -07002355
Ian Romanick3322fba2010-10-14 13:28:42 -07002356 prev = i;
2357 }
Ian Romanick13e10e42010-06-21 12:03:24 -07002358
Paul Berry871ddb92011-11-05 11:17:32 -07002359 if (prev != MESA_SHADER_FRAGMENT && num_tfeedback_decls != 0) {
2360 /* There was no fragment shader, but we still have to assign varying
2361 * locations for use by transform feedback.
2362 */
2363 if (!assign_varying_locations(
2364 ctx, prog, prog->_LinkedShaders[prev], NULL, num_tfeedback_decls,
2365 tfeedback_decls))
2366 goto done;
2367 }
2368
2369 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
2370 goto done;
2371
Ian Romanickcc90e622010-10-19 17:59:10 -07002372 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
2373 demote_shader_inputs_and_outputs(prog->_LinkedShaders[MESA_SHADER_VERTEX],
2374 ir_var_out);
Ian Romanick960d7222011-10-21 11:21:02 -07002375
2376 /* Eliminate code that is now dead due to unused vertex outputs being
2377 * demoted.
2378 */
2379 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_VERTEX]->ir, false))
2380 ;
Ian Romanickcc90e622010-10-19 17:59:10 -07002381 }
2382
2383 if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
2384 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
2385
2386 demote_shader_inputs_and_outputs(sh, ir_var_in);
2387 demote_shader_inputs_and_outputs(sh, ir_var_inout);
2388 demote_shader_inputs_and_outputs(sh, ir_var_out);
Ian Romanick960d7222011-10-21 11:21:02 -07002389
2390 /* Eliminate code that is now dead due to unused geometry outputs being
2391 * demoted.
2392 */
2393 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_GEOMETRY]->ir, false))
2394 ;
Ian Romanickcc90e622010-10-19 17:59:10 -07002395 }
2396
2397 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
2398 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2399
2400 demote_shader_inputs_and_outputs(sh, ir_var_in);
Ian Romanick960d7222011-10-21 11:21:02 -07002401
2402 /* Eliminate code that is now dead due to unused fragment inputs being
2403 * demoted. This shouldn't actually do anything other than remove
2404 * declarations of the (now unused) global variables.
2405 */
2406 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir, false))
2407 ;
Ian Romanickcc90e622010-10-19 17:59:10 -07002408 }
2409
Ian Romanick960d7222011-10-21 11:21:02 -07002410 update_array_sizes(prog);
Ian Romanick71990962011-10-18 16:01:49 -07002411 link_assign_uniform_locations(prog);
Marek Olšákec174a42011-11-18 15:00:10 +01002412 store_fragdepth_layout(prog);
Ian Romanick960d7222011-10-21 11:21:02 -07002413
Ian Romanick92f81592011-11-08 12:37:19 -08002414 if (!check_resources(ctx, prog))
2415 goto done;
2416
Ian Romanickce9171f2011-02-03 17:10:14 -08002417 /* OpenGL ES requires that a vertex shader and a fragment shader both be
2418 * present in a linked program. By checking for use of shading language
2419 * version 1.00, we also catch the GL_ARB_ES2_compatibility case.
2420 */
Eric Anholt57f79782011-07-22 12:57:47 -07002421 if (!prog->InternalSeparateShader &&
2422 (ctx->API == API_OPENGLES2 || prog->Version == 100)) {
Ian Romanickce9171f2011-02-03 17:10:14 -08002423 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
Ian Romanick586e7412011-07-28 14:04:09 -07002424 linker_error(prog, "program lacks a vertex shader\n");
Ian Romanickce9171f2011-02-03 17:10:14 -08002425 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
Ian Romanick586e7412011-07-28 14:04:09 -07002426 linker_error(prog, "program lacks a fragment shader\n");
Ian Romanickce9171f2011-02-03 17:10:14 -08002427 }
2428 }
2429
Ian Romanick13e10e42010-06-21 12:03:24 -07002430 /* FINISHME: Assign fragment shader output locations. */
2431
Ian Romanick832dfa52010-06-17 15:04:20 -07002432done:
2433 free(vert_shader_list);
Kenneth Graunke2da02e72010-11-17 11:03:57 -08002434
2435 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2436 if (prog->_LinkedShaders[i] == NULL)
2437 continue;
2438
2439 /* Retain any live IR, but trash the rest. */
2440 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
Ian Romanick7bbcc0b2011-09-30 14:21:10 -07002441
2442 /* The symbol table in the linked shaders may contain references to
2443 * variables that were removed (e.g., unused uniforms). Since it may
2444 * contain junk, there is no possible valid use. Delete it and set the
2445 * pointer to NULL.
2446 */
2447 delete prog->_LinkedShaders[i]->symbols;
2448 prog->_LinkedShaders[i]->symbols = NULL;
Kenneth Graunke2da02e72010-11-17 11:03:57 -08002449 }
2450
Kenneth Graunked3073f52011-01-21 14:32:31 -08002451 ralloc_free(mem_ctx);
Ian Romanick832dfa52010-06-17 15:04:20 -07002452}