blob: 8278e43adb804bb5394f40dc7f41b6121f508dfb [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) {
1322 linker_error(prog,
1323 "insufficient contiguous attribute locations "
1324 "available for vertex shader input `%s'",
1325 var->name);
1326 return false;
1327 }
1328
1329 used_locations |= (use_mask << attr);
1330 }
1331
1332 continue;
1333 }
1334
1335 to_assign[num_attr].slots = slots;
Ian Romanick69846702010-06-22 17:29:19 -07001336 to_assign[num_attr].var = var;
1337 num_attr++;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001338 }
Ian Romanick69846702010-06-22 17:29:19 -07001339
1340 /* If all of the attributes were assigned locations by the application (or
1341 * are built-in attributes with fixed locations), return early. This should
1342 * be the common case.
1343 */
1344 if (num_attr == 0)
1345 return true;
1346
1347 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1348
Ian Romanickd32d4f72011-06-27 17:59:58 -07001349 if (target_index == MESA_SHADER_VERTEX) {
1350 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1351 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1352 * reserved to prevent it from being automatically allocated below.
1353 */
1354 find_deref_visitor find("gl_Vertex");
1355 find.run(sh->ir);
1356 if (find.variable_found())
1357 used_locations |= (1 << 0);
1358 }
Ian Romanick982e3792010-06-29 18:58:20 -07001359
Ian Romanick69846702010-06-22 17:29:19 -07001360 for (unsigned i = 0; i < num_attr; i++) {
1361 /* Mask representing the contiguous slots that will be used by this
1362 * attribute.
1363 */
1364 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1365
1366 int location = find_available_slots(used_locations, to_assign[i].slots);
1367
1368 if (location < 0) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07001369 const char *const string = (target_index == MESA_SHADER_VERTEX)
1370 ? "vertex shader input" : "fragment shader output";
1371
Ian Romanick586e7412011-07-28 14:04:09 -07001372 linker_error(prog,
1373 "insufficient contiguous attribute locations "
1374 "available for %s `%s'",
1375 string, to_assign[i].var->name);
Ian Romanick69846702010-06-22 17:29:19 -07001376 return false;
1377 }
1378
Ian Romanickd32d4f72011-06-27 17:59:58 -07001379 to_assign[i].var->location = generic_base + location;
Ian Romanick69846702010-06-22 17:29:19 -07001380 used_locations |= (use_mask << location);
1381 }
1382
1383 return true;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001384}
1385
1386
Ian Romanick40e114b2010-08-17 14:55:50 -07001387/**
Ian Romanickcc90e622010-10-19 17:59:10 -07001388 * Demote shader inputs and outputs that are not used in other stages
Ian Romanick40e114b2010-08-17 14:55:50 -07001389 */
1390void
Ian Romanickcc90e622010-10-19 17:59:10 -07001391demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
Ian Romanick40e114b2010-08-17 14:55:50 -07001392{
1393 foreach_list(node, sh->ir) {
1394 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1395
Ian Romanickcc90e622010-10-19 17:59:10 -07001396 if ((var == NULL) || (var->mode != int(mode)))
Ian Romanick40e114b2010-08-17 14:55:50 -07001397 continue;
1398
Ian Romanickcc90e622010-10-19 17:59:10 -07001399 /* A shader 'in' or 'out' variable is only really an input or output if
1400 * its value is used by other shader stages. This will cause the variable
1401 * to have a location assigned.
Ian Romanick40e114b2010-08-17 14:55:50 -07001402 */
1403 if (var->location == -1) {
1404 var->mode = ir_var_auto;
1405 }
1406 }
1407}
1408
1409
Paul Berry871ddb92011-11-05 11:17:32 -07001410/**
1411 * Data structure tracking information about a transform feedback declaration
1412 * during linking.
1413 */
1414class tfeedback_decl
1415{
1416public:
Paul Berry456279b2011-12-26 19:39:25 -08001417 bool init(struct gl_context *ctx, struct gl_shader_program *prog,
1418 const void *mem_ctx, const char *input);
Paul Berry871ddb92011-11-05 11:17:32 -07001419 static bool is_same(const tfeedback_decl &x, const tfeedback_decl &y);
1420 bool assign_location(struct gl_context *ctx, struct gl_shader_program *prog,
1421 ir_variable *output_var);
Christoph Bumillerd540af52012-01-20 13:24:46 +01001422 bool accumulate_num_outputs(struct gl_shader_program *prog, unsigned *count);
Paul Berryd3150eb2012-01-09 11:25:14 -08001423 bool store(struct gl_context *ctx, struct gl_shader_program *prog,
Eric Anholt9d36c962012-01-02 17:08:13 -08001424 struct gl_transform_feedback_info *info, unsigned buffer,
Christoph Bumillerd540af52012-01-20 13:24:46 +01001425 unsigned varying, const unsigned max_outputs) const;
Paul Berry871ddb92011-11-05 11:17:32 -07001426
1427
1428 /**
1429 * True if assign_location() has been called for this object.
1430 */
1431 bool is_assigned() const
1432 {
1433 return this->location != -1;
1434 }
1435
1436 /**
1437 * Determine whether this object refers to the variable var.
1438 */
1439 bool matches_var(ir_variable *var) const
1440 {
Paul Berry642e5b412012-01-04 13:57:52 -08001441 if (this->is_clip_distance_mesa)
1442 return strcmp(var->name, "gl_ClipDistanceMESA") == 0;
1443 else
1444 return strcmp(var->name, this->var_name) == 0;
Paul Berry871ddb92011-11-05 11:17:32 -07001445 }
1446
1447 /**
1448 * The total number of varying components taken up by this variable. Only
1449 * valid if is_assigned() is true.
1450 */
1451 unsigned num_components() const
1452 {
Paul Berry642e5b412012-01-04 13:57:52 -08001453 if (this->is_clip_distance_mesa)
1454 return this->size;
Paul Berrybe4e9f72012-01-04 12:21:55 -08001455 else
Paul Berry642e5b412012-01-04 13:57:52 -08001456 return this->vector_elements * this->matrix_columns * this->size;
Paul Berry871ddb92011-11-05 11:17:32 -07001457 }
1458
1459private:
1460 /**
1461 * The name that was supplied to glTransformFeedbackVaryings. Used for
Eric Anholt9d36c962012-01-02 17:08:13 -08001462 * error reporting and glGetTransformFeedbackVarying().
Paul Berry871ddb92011-11-05 11:17:32 -07001463 */
1464 const char *orig_name;
1465
1466 /**
1467 * The name of the variable, parsed from orig_name.
1468 */
Paul Berry913a5c22011-12-27 08:24:57 -08001469 const char *var_name;
Paul Berry871ddb92011-11-05 11:17:32 -07001470
1471 /**
1472 * True if the declaration in orig_name represents an array.
1473 */
Paul Berry33fe0212012-01-03 20:41:34 -08001474 bool is_subscripted;
Paul Berry871ddb92011-11-05 11:17:32 -07001475
1476 /**
Paul Berry33fe0212012-01-03 20:41:34 -08001477 * If is_subscripted is true, the subscript that was specified in orig_name.
Paul Berry871ddb92011-11-05 11:17:32 -07001478 */
Paul Berry33fe0212012-01-03 20:41:34 -08001479 unsigned array_subscript;
Paul Berry871ddb92011-11-05 11:17:32 -07001480
1481 /**
Paul Berry642e5b412012-01-04 13:57:52 -08001482 * True if the variable is gl_ClipDistance and the driver lowers
1483 * gl_ClipDistance to gl_ClipDistanceMESA.
Paul Berry456279b2011-12-26 19:39:25 -08001484 */
Paul Berry642e5b412012-01-04 13:57:52 -08001485 bool is_clip_distance_mesa;
Paul Berry456279b2011-12-26 19:39:25 -08001486
1487 /**
Paul Berry871ddb92011-11-05 11:17:32 -07001488 * The vertex shader output location that the linker assigned for this
1489 * variable. -1 if a location hasn't been assigned yet.
1490 */
1491 int location;
1492
1493 /**
1494 * If location != -1, the number of vector elements in this variable, or 1
1495 * if this variable is a scalar.
1496 */
1497 unsigned vector_elements;
1498
1499 /**
1500 * If location != -1, the number of matrix columns in this variable, or 1
1501 * if this variable is not a matrix.
1502 */
1503 unsigned matrix_columns;
Eric Anholt9d36c962012-01-02 17:08:13 -08001504
1505 /** Type of the varying returned by glGetTransformFeedbackVarying() */
1506 GLenum type;
Paul Berry33fe0212012-01-03 20:41:34 -08001507
1508 /**
1509 * If location != -1, the size that should be returned by
1510 * glGetTransformFeedbackVarying().
1511 */
1512 unsigned size;
Paul Berry871ddb92011-11-05 11:17:32 -07001513};
1514
1515
1516/**
1517 * Initialize this object based on a string that was passed to
1518 * glTransformFeedbackVaryings. If there is a parse error, the error is
1519 * reported using linker_error(), and false is returned.
1520 */
1521bool
Paul Berry456279b2011-12-26 19:39:25 -08001522tfeedback_decl::init(struct gl_context *ctx, struct gl_shader_program *prog,
1523 const void *mem_ctx, const char *input)
Paul Berry871ddb92011-11-05 11:17:32 -07001524{
1525 /* We don't have to be pedantic about what is a valid GLSL variable name,
1526 * because any variable with an invalid name can't exist in the IR anyway.
1527 */
1528
1529 this->location = -1;
1530 this->orig_name = input;
Paul Berry642e5b412012-01-04 13:57:52 -08001531 this->is_clip_distance_mesa = false;
Paul Berry871ddb92011-11-05 11:17:32 -07001532
1533 const char *bracket = strrchr(input, '[');
1534
1535 if (bracket) {
1536 this->var_name = ralloc_strndup(mem_ctx, input, bracket - input);
Paul Berry33fe0212012-01-03 20:41:34 -08001537 if (sscanf(bracket, "[%u]", &this->array_subscript) != 1) {
Paul Berry456279b2011-12-26 19:39:25 -08001538 linker_error(prog, "Cannot parse transform feedback varying %s", input);
1539 return false;
Paul Berry871ddb92011-11-05 11:17:32 -07001540 }
Paul Berry33fe0212012-01-03 20:41:34 -08001541 this->is_subscripted = true;
Paul Berry871ddb92011-11-05 11:17:32 -07001542 } else {
1543 this->var_name = ralloc_strdup(mem_ctx, input);
Paul Berry33fe0212012-01-03 20:41:34 -08001544 this->is_subscripted = false;
Paul Berry871ddb92011-11-05 11:17:32 -07001545 }
1546
Paul Berry642e5b412012-01-04 13:57:52 -08001547 /* For drivers that lower gl_ClipDistance to gl_ClipDistanceMESA, this
1548 * class must behave specially to account for the fact that gl_ClipDistance
1549 * is converted from a float[8] to a vec4[2].
Paul Berry456279b2011-12-26 19:39:25 -08001550 */
1551 if (ctx->ShaderCompilerOptions[MESA_SHADER_VERTEX].LowerClipDistance &&
1552 strcmp(this->var_name, "gl_ClipDistance") == 0) {
Paul Berry642e5b412012-01-04 13:57:52 -08001553 this->is_clip_distance_mesa = true;
Paul Berry456279b2011-12-26 19:39:25 -08001554 }
1555
1556 return true;
Paul Berry871ddb92011-11-05 11:17:32 -07001557}
1558
1559
1560/**
1561 * Determine whether two tfeedback_decl objects refer to the same variable and
1562 * array index (if applicable).
1563 */
1564bool
1565tfeedback_decl::is_same(const tfeedback_decl &x, const tfeedback_decl &y)
1566{
1567 if (strcmp(x.var_name, y.var_name) != 0)
1568 return false;
Paul Berry33fe0212012-01-03 20:41:34 -08001569 if (x.is_subscripted != y.is_subscripted)
Paul Berry871ddb92011-11-05 11:17:32 -07001570 return false;
Paul Berry33fe0212012-01-03 20:41:34 -08001571 if (x.is_subscripted && x.array_subscript != y.array_subscript)
Paul Berry871ddb92011-11-05 11:17:32 -07001572 return false;
1573 return true;
1574}
1575
1576
1577/**
1578 * Assign a location for this tfeedback_decl object based on the location
1579 * assignment in output_var.
1580 *
1581 * If an error occurs, the error is reported through linker_error() and false
1582 * is returned.
1583 */
1584bool
1585tfeedback_decl::assign_location(struct gl_context *ctx,
1586 struct gl_shader_program *prog,
1587 ir_variable *output_var)
1588{
1589 if (output_var->type->is_array()) {
1590 /* Array variable */
Paul Berry871ddb92011-11-05 11:17:32 -07001591 const unsigned matrix_cols =
1592 output_var->type->fields.array->matrix_columns;
Paul Berry642e5b412012-01-04 13:57:52 -08001593 unsigned actual_array_size = this->is_clip_distance_mesa ?
1594 prog->Vert.ClipDistanceArraySize : output_var->type->array_size();
Paul Berry33fe0212012-01-03 20:41:34 -08001595
1596 if (this->is_subscripted) {
1597 /* Check array bounds. */
Paul Berry642e5b412012-01-04 13:57:52 -08001598 if (this->array_subscript >= actual_array_size) {
Paul Berry33fe0212012-01-03 20:41:34 -08001599 linker_error(prog, "Transform feedback varying %s has index "
Paul Berry642e5b412012-01-04 13:57:52 -08001600 "%i, but the array size is %u.",
Paul Berry33fe0212012-01-03 20:41:34 -08001601 this->orig_name, this->array_subscript,
Paul Berry642e5b412012-01-04 13:57:52 -08001602 actual_array_size);
Paul Berry33fe0212012-01-03 20:41:34 -08001603 return false;
1604 }
Paul Berry642e5b412012-01-04 13:57:52 -08001605 if (this->is_clip_distance_mesa) {
1606 this->location =
1607 output_var->location + this->array_subscript / 4;
1608 } else {
1609 this->location =
1610 output_var->location + this->array_subscript * matrix_cols;
1611 }
Paul Berry33fe0212012-01-03 20:41:34 -08001612 this->size = 1;
1613 } else {
1614 this->location = output_var->location;
Paul Berry642e5b412012-01-04 13:57:52 -08001615 this->size = actual_array_size;
Paul Berry33fe0212012-01-03 20:41:34 -08001616 }
Paul Berry871ddb92011-11-05 11:17:32 -07001617 this->vector_elements = output_var->type->fields.array->vector_elements;
1618 this->matrix_columns = matrix_cols;
Paul Berry642e5b412012-01-04 13:57:52 -08001619 if (this->is_clip_distance_mesa)
1620 this->type = GL_FLOAT;
1621 else
1622 this->type = output_var->type->fields.array->gl_type;
Paul Berry871ddb92011-11-05 11:17:32 -07001623 } else {
1624 /* Regular variable (scalar, vector, or matrix) */
Paul Berry33fe0212012-01-03 20:41:34 -08001625 if (this->is_subscripted) {
Paul Berry108cba22012-01-04 15:17:52 -08001626 linker_error(prog, "Transform feedback varying %s requested, "
1627 "but %s is not an array.",
1628 this->orig_name, this->var_name);
Paul Berry871ddb92011-11-05 11:17:32 -07001629 return false;
1630 }
1631 this->location = output_var->location;
Paul Berry33fe0212012-01-03 20:41:34 -08001632 this->size = 1;
Paul Berry871ddb92011-11-05 11:17:32 -07001633 this->vector_elements = output_var->type->vector_elements;
1634 this->matrix_columns = output_var->type->matrix_columns;
Eric Anholt9d36c962012-01-02 17:08:13 -08001635 this->type = output_var->type->gl_type;
Paul Berry871ddb92011-11-05 11:17:32 -07001636 }
Paul Berry642e5b412012-01-04 13:57:52 -08001637
Paul Berry871ddb92011-11-05 11:17:32 -07001638 /* From GL_EXT_transform_feedback:
1639 * A program will fail to link if:
1640 *
1641 * * the total number of components to capture in any varying
1642 * variable in <varyings> is greater than the constant
1643 * MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT and the
1644 * buffer mode is SEPARATE_ATTRIBS_EXT;
1645 */
1646 if (prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS &&
1647 this->num_components() >
1648 ctx->Const.MaxTransformFeedbackSeparateComponents) {
1649 linker_error(prog, "Transform feedback varying %s exceeds "
1650 "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS.",
1651 this->orig_name);
1652 return false;
1653 }
1654
1655 return true;
1656}
1657
1658
Paul Berry871ddb92011-11-05 11:17:32 -07001659bool
Christoph Bumillerd540af52012-01-20 13:24:46 +01001660tfeedback_decl::accumulate_num_outputs(struct gl_shader_program *prog,
1661 unsigned *count)
Paul Berry871ddb92011-11-05 11:17:32 -07001662{
1663 if (!this->is_assigned()) {
1664 /* From GL_EXT_transform_feedback:
1665 * A program will fail to link if:
1666 *
1667 * * any variable name specified in the <varyings> array is not
1668 * declared as an output in the geometry shader (if present) or
1669 * the vertex shader (if no geometry shader is present);
1670 */
1671 linker_error(prog, "Transform feedback varying %s undeclared.",
1672 this->orig_name);
1673 return false;
1674 }
Paul Berryd3150eb2012-01-09 11:25:14 -08001675
Christoph Bumillerd540af52012-01-20 13:24:46 +01001676 unsigned translated_size = this->size;
1677 if (this->is_clip_distance_mesa)
1678 translated_size = (translated_size + 3) / 4;
1679
1680 *count += translated_size * this->matrix_columns;
1681
1682 return true;
1683}
1684
1685
1686/**
1687 * Update gl_transform_feedback_info to reflect this tfeedback_decl.
1688 *
1689 * If an error occurs, the error is reported through linker_error() and false
1690 * is returned.
1691 */
1692bool
1693tfeedback_decl::store(struct gl_context *ctx, struct gl_shader_program *prog,
1694 struct gl_transform_feedback_info *info,
1695 unsigned buffer,
1696 unsigned varying, const unsigned max_outputs) const
1697{
Paul Berryd3150eb2012-01-09 11:25:14 -08001698 /* From GL_EXT_transform_feedback:
1699 * A program will fail to link if:
1700 *
1701 * * the total number of components to capture is greater than
1702 * the constant MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT
1703 * and the buffer mode is INTERLEAVED_ATTRIBS_EXT.
1704 */
1705 if (prog->TransformFeedback.BufferMode == GL_INTERLEAVED_ATTRIBS &&
1706 info->BufferStride[buffer] + this->num_components() >
1707 ctx->Const.MaxTransformFeedbackInterleavedComponents) {
1708 linker_error(prog, "The MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS "
1709 "limit has been exceeded.");
1710 return false;
1711 }
1712
Paul Berry642e5b412012-01-04 13:57:52 -08001713 unsigned translated_size = this->size;
1714 if (this->is_clip_distance_mesa)
1715 translated_size = (translated_size + 3) / 4;
Paul Berrybe4e9f72012-01-04 12:21:55 -08001716 unsigned components_so_far = 0;
Paul Berry642e5b412012-01-04 13:57:52 -08001717 for (unsigned index = 0; index < translated_size; ++index) {
Paul Berry33fe0212012-01-03 20:41:34 -08001718 for (unsigned v = 0; v < this->matrix_columns; ++v) {
Paul Berry642e5b412012-01-04 13:57:52 -08001719 unsigned num_components = this->vector_elements;
Christoph Bumillerd540af52012-01-20 13:24:46 +01001720 assert(info->NumOutputs < max_outputs);
Paul Berry642e5b412012-01-04 13:57:52 -08001721 info->Outputs[info->NumOutputs].ComponentOffset = 0;
1722 if (this->is_clip_distance_mesa) {
1723 if (this->is_subscripted) {
1724 num_components = 1;
1725 info->Outputs[info->NumOutputs].ComponentOffset =
1726 this->array_subscript % 4;
1727 } else {
1728 num_components = MIN2(4, this->size - components_so_far);
1729 }
1730 }
Paul Berry33fe0212012-01-03 20:41:34 -08001731 info->Outputs[info->NumOutputs].OutputRegister =
1732 this->location + v + index * this->matrix_columns;
1733 info->Outputs[info->NumOutputs].NumComponents = num_components;
1734 info->Outputs[info->NumOutputs].OutputBuffer = buffer;
1735 info->Outputs[info->NumOutputs].DstOffset = info->BufferStride[buffer];
Paul Berry33fe0212012-01-03 20:41:34 -08001736 ++info->NumOutputs;
1737 info->BufferStride[buffer] += num_components;
Paul Berrybe4e9f72012-01-04 12:21:55 -08001738 components_so_far += num_components;
Paul Berry33fe0212012-01-03 20:41:34 -08001739 }
Paul Berry871ddb92011-11-05 11:17:32 -07001740 }
Paul Berrybe4e9f72012-01-04 12:21:55 -08001741 assert(components_so_far == this->num_components());
Eric Anholt9d36c962012-01-02 17:08:13 -08001742
1743 info->Varyings[varying].Name = ralloc_strdup(prog, this->orig_name);
1744 info->Varyings[varying].Type = this->type;
Paul Berry33fe0212012-01-03 20:41:34 -08001745 info->Varyings[varying].Size = this->size;
Eric Anholt9d36c962012-01-02 17:08:13 -08001746 info->NumVarying++;
1747
Paul Berry871ddb92011-11-05 11:17:32 -07001748 return true;
1749}
1750
1751
1752/**
1753 * Parse all the transform feedback declarations that were passed to
1754 * glTransformFeedbackVaryings() and store them in tfeedback_decl objects.
1755 *
1756 * If an error occurs, the error is reported through linker_error() and false
1757 * is returned.
1758 */
1759static bool
Paul Berry456279b2011-12-26 19:39:25 -08001760parse_tfeedback_decls(struct gl_context *ctx, struct gl_shader_program *prog,
1761 const void *mem_ctx, unsigned num_names,
1762 char **varying_names, tfeedback_decl *decls)
Paul Berry871ddb92011-11-05 11:17:32 -07001763{
1764 for (unsigned i = 0; i < num_names; ++i) {
Paul Berry456279b2011-12-26 19:39:25 -08001765 if (!decls[i].init(ctx, prog, mem_ctx, varying_names[i]))
Paul Berry871ddb92011-11-05 11:17:32 -07001766 return false;
1767 /* From GL_EXT_transform_feedback:
1768 * A program will fail to link if:
1769 *
1770 * * any two entries in the <varyings> array specify the same varying
1771 * variable;
1772 *
1773 * We interpret this to mean "any two entries in the <varyings> array
1774 * specify the same varying variable and array index", since transform
1775 * feedback of arrays would be useless otherwise.
1776 */
1777 for (unsigned j = 0; j < i; ++j) {
1778 if (tfeedback_decl::is_same(decls[i], decls[j])) {
1779 linker_error(prog, "Transform feedback varying %s specified "
1780 "more than once.", varying_names[i]);
1781 return false;
1782 }
1783 }
1784 }
1785 return true;
1786}
1787
1788
1789/**
1790 * Assign a location for a variable that is produced in one pipeline stage
1791 * (the "producer") and consumed in the next stage (the "consumer").
1792 *
1793 * \param input_var is the input variable declaration in the consumer.
1794 *
1795 * \param output_var is the output variable declaration in the producer.
1796 *
1797 * \param input_index is the counter that keeps track of assigned input
1798 * locations in the consumer.
1799 *
1800 * \param output_index is the counter that keeps track of assigned output
1801 * locations in the producer.
1802 *
1803 * It is permissible for \c input_var to be NULL (this happens if a variable
1804 * is output by the producer and consumed by transform feedback, but not
1805 * consumed by the consumer).
1806 *
1807 * If the variable has already been assigned a location, this function has no
1808 * effect.
1809 */
1810void
1811assign_varying_location(ir_variable *input_var, ir_variable *output_var,
1812 unsigned *input_index, unsigned *output_index)
1813{
1814 if (output_var->location != -1) {
1815 /* Location already assigned. */
1816 return;
1817 }
1818
1819 if (input_var) {
1820 assert(input_var->location == -1);
1821 input_var->location = *input_index;
1822 }
1823
1824 output_var->location = *output_index;
1825
1826 /* FINISHME: Support for "varying" records in GLSL 1.50. */
1827 assert(!output_var->type->is_record());
1828
1829 if (output_var->type->is_array()) {
1830 const unsigned slots = output_var->type->length
1831 * output_var->type->fields.array->matrix_columns;
1832
1833 *output_index += slots;
1834 *input_index += slots;
1835 } else {
1836 const unsigned slots = output_var->type->matrix_columns;
1837
1838 *output_index += slots;
1839 *input_index += slots;
1840 }
1841}
1842
1843
1844/**
1845 * Assign locations for all variables that are produced in one pipeline stage
1846 * (the "producer") and consumed in the next stage (the "consumer").
1847 *
1848 * Variables produced by the producer may also be consumed by transform
1849 * feedback.
1850 *
1851 * \param num_tfeedback_decls is the number of declarations indicating
1852 * variables that may be consumed by transform feedback.
1853 *
1854 * \param tfeedback_decls is a pointer to an array of tfeedback_decl objects
1855 * representing the result of parsing the strings passed to
1856 * glTransformFeedbackVaryings(). assign_location() will be called for
1857 * each of these objects that matches one of the outputs of the
1858 * producer.
1859 *
1860 * When num_tfeedback_decls is nonzero, it is permissible for the consumer to
1861 * be NULL. In this case, varying locations are assigned solely based on the
1862 * requirements of transform feedback.
1863 */
Ian Romanickde773242011-06-09 13:31:32 -07001864bool
1865assign_varying_locations(struct gl_context *ctx,
1866 struct gl_shader_program *prog,
Paul Berry871ddb92011-11-05 11:17:32 -07001867 gl_shader *producer, gl_shader *consumer,
1868 unsigned num_tfeedback_decls,
1869 tfeedback_decl *tfeedback_decls)
Ian Romanick0e59b262010-06-23 11:23:01 -07001870{
1871 /* FINISHME: Set dynamically when geometry shader support is added. */
1872 unsigned output_index = VERT_RESULT_VAR0;
1873 unsigned input_index = FRAG_ATTRIB_VAR0;
1874
1875 /* Operate in a total of three passes.
1876 *
1877 * 1. Assign locations for any matching inputs and outputs.
1878 *
1879 * 2. Mark output variables in the producer that do not have locations as
1880 * not being outputs. This lets the optimizer eliminate them.
1881 *
1882 * 3. Mark input variables in the consumer that do not have locations as
1883 * not being inputs. This lets the optimizer eliminate them.
1884 */
1885
Ian Romanickf6ee7bc2011-10-11 16:15:47 -07001886 link_invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
Paul Berry871ddb92011-11-05 11:17:32 -07001887 if (consumer)
1888 link_invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
Ian Romanick0e59b262010-06-23 11:23:01 -07001889
Eric Anholt16b68b12010-06-30 11:05:43 -07001890 foreach_list(node, producer->ir) {
Ian Romanick0e59b262010-06-23 11:23:01 -07001891 ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
1892
Paul Berry871ddb92011-11-05 11:17:32 -07001893 if ((output_var == NULL) || (output_var->mode != ir_var_out))
Ian Romanick0e59b262010-06-23 11:23:01 -07001894 continue;
1895
Paul Berry871ddb92011-11-05 11:17:32 -07001896 ir_variable *input_var =
1897 consumer ? consumer->symbols->get_variable(output_var->name) : NULL;
Ian Romanick0e59b262010-06-23 11:23:01 -07001898
Paul Berry871ddb92011-11-05 11:17:32 -07001899 if (input_var && input_var->mode != ir_var_in)
1900 input_var = NULL;
Ian Romanick0e59b262010-06-23 11:23:01 -07001901
Paul Berry871ddb92011-11-05 11:17:32 -07001902 if (input_var) {
1903 assign_varying_location(input_var, output_var, &input_index,
1904 &output_index);
1905 }
Ian Romanick0e59b262010-06-23 11:23:01 -07001906
Paul Berry871ddb92011-11-05 11:17:32 -07001907 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
1908 if (!tfeedback_decls[i].is_assigned() &&
1909 tfeedback_decls[i].matches_var(output_var)) {
1910 if (output_var->location == -1) {
1911 assign_varying_location(input_var, output_var, &input_index,
1912 &output_index);
1913 }
1914 if (!tfeedback_decls[i].assign_location(ctx, prog, output_var))
1915 return false;
1916 }
Ian Romanickdf869d92010-08-30 15:37:44 -07001917 }
Ian Romanick0e59b262010-06-23 11:23:01 -07001918 }
1919
Ian Romanickde773242011-06-09 13:31:32 -07001920 unsigned varying_vectors = 0;
1921
Paul Berry871ddb92011-11-05 11:17:32 -07001922 if (consumer) {
1923 foreach_list(node, consumer->ir) {
1924 ir_variable *const var = ((ir_instruction *) node)->as_variable();
Ian Romanick0e59b262010-06-23 11:23:01 -07001925
Paul Berry871ddb92011-11-05 11:17:32 -07001926 if ((var == NULL) || (var->mode != ir_var_in))
1927 continue;
Ian Romanick0e59b262010-06-23 11:23:01 -07001928
Paul Berry871ddb92011-11-05 11:17:32 -07001929 if (var->location == -1) {
1930 if (prog->Version <= 120) {
1931 /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
1932 *
1933 * Only those varying variables used (i.e. read) in
1934 * the fragment shader executable must be written to
1935 * by the vertex shader executable; declaring
1936 * superfluous varying variables in a vertex shader is
1937 * permissible.
1938 *
1939 * We interpret this text as meaning that the VS must
1940 * write the variable for the FS to read it. See
1941 * "glsl1-varying read but not written" in piglit.
1942 */
Eric Anholtb7062832010-07-28 13:52:23 -07001943
Paul Berry871ddb92011-11-05 11:17:32 -07001944 linker_error(prog, "fragment shader varying %s not written "
1945 "by vertex shader\n.", var->name);
1946 }
Eric Anholtb7062832010-07-28 13:52:23 -07001947
Paul Berry871ddb92011-11-05 11:17:32 -07001948 /* An 'in' variable is only really a shader input if its
1949 * value is written by the previous stage.
1950 */
1951 var->mode = ir_var_auto;
1952 } else {
1953 /* The packing rules are used for vertex shader inputs are also
1954 * used for fragment shader inputs.
1955 */
1956 varying_vectors += count_attribute_slots(var->type);
1957 }
Eric Anholtb7062832010-07-28 13:52:23 -07001958 }
Ian Romanick0e59b262010-06-23 11:23:01 -07001959 }
Ian Romanickde773242011-06-09 13:31:32 -07001960
1961 if (ctx->API == API_OPENGLES2 || prog->Version == 100) {
1962 if (varying_vectors > ctx->Const.MaxVarying) {
Marek Olšákdf809ae2011-12-10 04:14:46 +01001963 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
1964 linker_warning(prog, "shader uses too many varying vectors "
1965 "(%u > %u), but the driver will try to optimize "
1966 "them out; this is non-portable out-of-spec "
1967 "behavior\n",
1968 varying_vectors, ctx->Const.MaxVarying);
1969 } else {
1970 linker_error(prog, "shader uses too many varying vectors "
1971 "(%u > %u)\n",
1972 varying_vectors, ctx->Const.MaxVarying);
1973 return false;
1974 }
Ian Romanickde773242011-06-09 13:31:32 -07001975 }
1976 } else {
1977 const unsigned float_components = varying_vectors * 4;
1978 if (float_components > ctx->Const.MaxVarying * 4) {
Marek Olšákdf809ae2011-12-10 04:14:46 +01001979 if (ctx->Const.GLSLSkipStrictMaxVaryingLimitCheck) {
1980 linker_warning(prog, "shader uses too many varying components "
1981 "(%u > %u), but the driver will try to optimize "
1982 "them out; this is non-portable out-of-spec "
1983 "behavior\n",
1984 float_components, ctx->Const.MaxVarying * 4);
1985 } else {
1986 linker_error(prog, "shader uses too many varying components "
1987 "(%u > %u)\n",
1988 float_components, ctx->Const.MaxVarying * 4);
1989 return false;
1990 }
Ian Romanickde773242011-06-09 13:31:32 -07001991 }
1992 }
1993
1994 return true;
Ian Romanick0e59b262010-06-23 11:23:01 -07001995}
1996
1997
Paul Berry871ddb92011-11-05 11:17:32 -07001998/**
1999 * Store transform feedback location assignments into
2000 * prog->LinkedTransformFeedback based on the data stored in tfeedback_decls.
2001 *
2002 * If an error occurs, the error is reported through linker_error() and false
2003 * is returned.
2004 */
2005static bool
2006store_tfeedback_info(struct gl_context *ctx, struct gl_shader_program *prog,
2007 unsigned num_tfeedback_decls,
2008 tfeedback_decl *tfeedback_decls)
2009{
Paul Berryebfad9f2011-12-29 15:55:01 -08002010 bool separate_attribs_mode =
2011 prog->TransformFeedback.BufferMode == GL_SEPARATE_ATTRIBS;
Eric Anholt9d36c962012-01-02 17:08:13 -08002012
2013 ralloc_free(prog->LinkedTransformFeedback.Varyings);
Christoph Bumillerd540af52012-01-20 13:24:46 +01002014 ralloc_free(prog->LinkedTransformFeedback.Outputs);
Eric Anholt9d36c962012-01-02 17:08:13 -08002015
2016 memset(&prog->LinkedTransformFeedback, 0,
2017 sizeof(prog->LinkedTransformFeedback));
2018
Paul Berry1be0fd82012-01-05 13:06:36 -08002019 prog->LinkedTransformFeedback.NumBuffers =
2020 separate_attribs_mode ? num_tfeedback_decls : 1;
2021
Eric Anholt9d36c962012-01-02 17:08:13 -08002022 prog->LinkedTransformFeedback.Varyings =
Eric Anholt5a0f3952012-01-12 13:10:26 -08002023 rzalloc_array(prog,
Eric Anholt9d36c962012-01-02 17:08:13 -08002024 struct gl_transform_feedback_varying_info,
2025 num_tfeedback_decls);
2026
Christoph Bumillerd540af52012-01-20 13:24:46 +01002027 unsigned num_outputs = 0;
2028 for (unsigned i = 0; i < num_tfeedback_decls; ++i)
2029 if (!tfeedback_decls[i].accumulate_num_outputs(prog, &num_outputs))
2030 return false;
2031
2032 prog->LinkedTransformFeedback.Outputs =
2033 rzalloc_array(prog,
2034 struct gl_transform_feedback_output,
2035 num_outputs);
2036
Paul Berry871ddb92011-11-05 11:17:32 -07002037 for (unsigned i = 0; i < num_tfeedback_decls; ++i) {
Paul Berryebfad9f2011-12-29 15:55:01 -08002038 unsigned buffer = separate_attribs_mode ? i : 0;
Paul Berryd3150eb2012-01-09 11:25:14 -08002039 if (!tfeedback_decls[i].store(ctx, prog, &prog->LinkedTransformFeedback,
Christoph Bumillerd540af52012-01-20 13:24:46 +01002040 buffer, i, num_outputs))
Paul Berry871ddb92011-11-05 11:17:32 -07002041 return false;
Paul Berry871ddb92011-11-05 11:17:32 -07002042 }
Christoph Bumillerd540af52012-01-20 13:24:46 +01002043 assert(prog->LinkedTransformFeedback.NumOutputs == num_outputs);
Paul Berry871ddb92011-11-05 11:17:32 -07002044
2045 return true;
2046}
2047
Ian Romanick92f81592011-11-08 12:37:19 -08002048/**
Marek Olšákec174a42011-11-18 15:00:10 +01002049 * Store the gl_FragDepth layout in the gl_shader_program struct.
2050 */
2051static void
2052store_fragdepth_layout(struct gl_shader_program *prog)
2053{
2054 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2055 return;
2056 }
2057
2058 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2059
2060 /* We don't look up the gl_FragDepth symbol directly because if
2061 * gl_FragDepth is not used in the shader, it's removed from the IR.
2062 * However, the symbol won't be removed from the symbol table.
2063 *
2064 * We're only interested in the cases where the variable is NOT removed
2065 * from the IR.
2066 */
2067 foreach_list(node, ir) {
2068 ir_variable *const var = ((ir_instruction *) node)->as_variable();
2069
2070 if (var == NULL || var->mode != ir_var_out) {
2071 continue;
2072 }
2073
2074 if (strcmp(var->name, "gl_FragDepth") == 0) {
2075 switch (var->depth_layout) {
2076 case ir_depth_layout_none:
2077 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2078 return;
2079 case ir_depth_layout_any:
2080 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2081 return;
2082 case ir_depth_layout_greater:
2083 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2084 return;
2085 case ir_depth_layout_less:
2086 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2087 return;
2088 case ir_depth_layout_unchanged:
2089 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2090 return;
2091 default:
2092 assert(0);
2093 return;
2094 }
2095 }
2096 }
2097}
2098
2099/**
Ian Romanick92f81592011-11-08 12:37:19 -08002100 * Validate the resources used by a program versus the implementation limits
2101 */
2102static bool
2103check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2104{
2105 static const char *const shader_names[MESA_SHADER_TYPES] = {
2106 "vertex", "fragment", "geometry"
2107 };
2108
2109 const unsigned max_samplers[MESA_SHADER_TYPES] = {
2110 ctx->Const.MaxVertexTextureImageUnits,
2111 ctx->Const.MaxTextureImageUnits,
2112 ctx->Const.MaxGeometryTextureImageUnits
2113 };
2114
2115 const unsigned max_uniform_components[MESA_SHADER_TYPES] = {
2116 ctx->Const.VertexProgram.MaxUniformComponents,
2117 ctx->Const.FragmentProgram.MaxUniformComponents,
2118 0 /* FINISHME: Geometry shaders. */
2119 };
2120
2121 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2122 struct gl_shader *sh = prog->_LinkedShaders[i];
2123
2124 if (sh == NULL)
2125 continue;
2126
2127 if (sh->num_samplers > max_samplers[i]) {
2128 linker_error(prog, "Too many %s shader texture samplers",
2129 shader_names[i]);
2130 }
2131
2132 if (sh->num_uniform_components > max_uniform_components[i]) {
Marek Olšákdf809ae2011-12-10 04:14:46 +01002133 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2134 linker_warning(prog, "Too many %s shader uniform components, "
2135 "but the driver will try to optimize them out; "
2136 "this is non-portable out-of-spec behavior\n",
2137 shader_names[i]);
2138 } else {
2139 linker_error(prog, "Too many %s shader uniform components",
2140 shader_names[i]);
2141 }
Ian Romanick92f81592011-11-08 12:37:19 -08002142 }
2143 }
2144
2145 return prog->LinkStatus;
2146}
Paul Berry871ddb92011-11-05 11:17:32 -07002147
Ian Romanick0e59b262010-06-23 11:23:01 -07002148void
Kristian Høgsbergf9995b32010-10-12 12:26:10 -04002149link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
Ian Romanick832dfa52010-06-17 15:04:20 -07002150{
Paul Berry871ddb92011-11-05 11:17:32 -07002151 tfeedback_decl *tfeedback_decls = NULL;
2152 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
2153
Kenneth Graunked3073f52011-01-21 14:32:31 -08002154 void *mem_ctx = ralloc_context(NULL); // temporary linker context
Kenneth Graunke2da02e72010-11-17 11:03:57 -08002155
Ian Romanick832dfa52010-06-17 15:04:20 -07002156 prog->LinkStatus = false;
2157 prog->Validated = false;
2158 prog->_Used = false;
2159
Ian Romanickf36460e2010-06-23 12:07:22 -07002160 if (prog->InfoLog != NULL)
Kenneth Graunked3073f52011-01-21 14:32:31 -08002161 ralloc_free(prog->InfoLog);
Ian Romanickf36460e2010-06-23 12:07:22 -07002162
Kenneth Graunked3073f52011-01-21 14:32:31 -08002163 prog->InfoLog = ralloc_strdup(NULL, "");
Ian Romanickf36460e2010-06-23 12:07:22 -07002164
Ian Romanick832dfa52010-06-17 15:04:20 -07002165 /* Separate the shaders into groups based on their type.
2166 */
Eric Anholt16b68b12010-06-30 11:05:43 -07002167 struct gl_shader **vert_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -07002168 unsigned num_vert_shaders = 0;
Eric Anholt16b68b12010-06-30 11:05:43 -07002169 struct gl_shader **frag_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -07002170 unsigned num_frag_shaders = 0;
2171
Eric Anholt16b68b12010-06-30 11:05:43 -07002172 vert_shader_list = (struct gl_shader **)
2173 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
Ian Romanick832dfa52010-06-17 15:04:20 -07002174 frag_shader_list = &vert_shader_list[prog->NumShaders];
2175
Ian Romanick25f51d32010-07-16 15:51:50 -07002176 unsigned min_version = UINT_MAX;
2177 unsigned max_version = 0;
Ian Romanick832dfa52010-06-17 15:04:20 -07002178 for (unsigned i = 0; i < prog->NumShaders; i++) {
Ian Romanick25f51d32010-07-16 15:51:50 -07002179 min_version = MIN2(min_version, prog->Shaders[i]->Version);
2180 max_version = MAX2(max_version, prog->Shaders[i]->Version);
2181
Ian Romanick832dfa52010-06-17 15:04:20 -07002182 switch (prog->Shaders[i]->Type) {
2183 case GL_VERTEX_SHADER:
2184 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
2185 num_vert_shaders++;
2186 break;
2187 case GL_FRAGMENT_SHADER:
2188 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
2189 num_frag_shaders++;
2190 break;
2191 case GL_GEOMETRY_SHADER:
2192 /* FINISHME: Support geometry shaders. */
2193 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
2194 break;
2195 }
2196 }
2197
Ian Romanick25f51d32010-07-16 15:51:50 -07002198 /* Previous to GLSL version 1.30, different compilation units could mix and
2199 * match shading language versions. With GLSL 1.30 and later, the versions
2200 * of all shaders must match.
2201 */
Kenneth Graunke5a81d052010-08-31 09:33:58 -07002202 assert(min_version >= 100);
Eric Anholtc5ff9a82012-03-08 13:49:15 -08002203 assert(max_version <= 140);
Kenneth Graunke5a81d052010-08-31 09:33:58 -07002204 if ((max_version >= 130 || min_version == 100)
2205 && min_version != max_version) {
Ian Romanick586e7412011-07-28 14:04:09 -07002206 linker_error(prog, "all shaders must use same shading "
2207 "language version\n");
Ian Romanick25f51d32010-07-16 15:51:50 -07002208 goto done;
2209 }
2210
2211 prog->Version = max_version;
2212
Ian Romanick3322fba2010-10-14 13:28:42 -07002213 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
2214 if (prog->_LinkedShaders[i] != NULL)
2215 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
2216
2217 prog->_LinkedShaders[i] = NULL;
Eric Anholt5d0f4302010-08-18 12:02:35 -07002218 }
2219
Ian Romanickcd6764e2010-07-16 16:00:07 -07002220 /* Link all shaders for a particular stage and validate the result.
2221 */
Ian Romanickcc22c5a2010-06-18 17:13:42 -07002222 if (num_vert_shaders > 0) {
Ian Romanick3fb87872010-07-09 14:09:34 -07002223 gl_shader *const sh =
Kenneth Graunke2da02e72010-11-17 11:03:57 -08002224 link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
2225 num_vert_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07002226
2227 if (sh == NULL)
2228 goto done;
2229
2230 if (!validate_vertex_shader_executable(prog, sh))
Ian Romanickf29ff6e2010-10-14 17:55:17 -07002231 goto done;
Ian Romanick3fb87872010-07-09 14:09:34 -07002232
Ian Romanick3322fba2010-10-14 13:28:42 -07002233 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
2234 sh);
Ian Romanickcc22c5a2010-06-18 17:13:42 -07002235 }
2236
2237 if (num_frag_shaders > 0) {
Ian Romanick3fb87872010-07-09 14:09:34 -07002238 gl_shader *const sh =
Kenneth Graunke2da02e72010-11-17 11:03:57 -08002239 link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
2240 num_frag_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07002241
2242 if (sh == NULL)
2243 goto done;
2244
2245 if (!validate_fragment_shader_executable(prog, sh))
Ian Romanickf29ff6e2010-10-14 17:55:17 -07002246 goto done;
Ian Romanick3fb87872010-07-09 14:09:34 -07002247
Ian Romanick3322fba2010-10-14 13:28:42 -07002248 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
2249 sh);
Ian Romanickcc22c5a2010-06-18 17:13:42 -07002250 }
2251
Ian Romanick3ed850e2010-06-23 12:18:21 -07002252 /* Here begins the inter-stage linking phase. Some initial validation is
2253 * performed, then locations are assigned for uniforms, attributes, and
2254 * varyings.
2255 */
Ian Romanicked1fe3d2010-06-23 12:09:14 -07002256 if (cross_validate_uniforms(prog)) {
Ian Romanick3322fba2010-10-14 13:28:42 -07002257 unsigned prev;
2258
2259 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2260 if (prog->_LinkedShaders[prev] != NULL)
2261 break;
2262 }
2263
Bryan Cainf18a0862011-04-23 19:29:15 -05002264 /* Validate the inputs of each stage with the output of the preceding
Ian Romanick37101922010-06-18 19:02:10 -07002265 * stage.
2266 */
Ian Romanick3322fba2010-10-14 13:28:42 -07002267 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2268 if (prog->_LinkedShaders[i] == NULL)
2269 continue;
2270
Ian Romanickf36460e2010-06-23 12:07:22 -07002271 if (!cross_validate_outputs_to_inputs(prog,
Ian Romanick3322fba2010-10-14 13:28:42 -07002272 prog->_LinkedShaders[prev],
Ian Romanickabee16e2010-06-21 16:16:05 -07002273 prog->_LinkedShaders[i]))
Ian Romanick37101922010-06-18 19:02:10 -07002274 goto done;
Ian Romanick3322fba2010-10-14 13:28:42 -07002275
2276 prev = i;
Ian Romanick37101922010-06-18 19:02:10 -07002277 }
2278
Ian Romanickcc22c5a2010-06-18 17:13:42 -07002279 prog->LinkStatus = true;
Ian Romanick37101922010-06-18 19:02:10 -07002280 }
Ian Romanick832dfa52010-06-17 15:04:20 -07002281
Eric Anholt2f4fe152010-08-10 13:06:49 -07002282 /* Do common optimization before assigning storage for attributes,
2283 * uniforms, and varyings. Later optimization could possibly make
2284 * some of that unused.
2285 */
Ian Romanick3322fba2010-10-14 13:28:42 -07002286 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2287 if (prog->_LinkedShaders[i] == NULL)
2288 continue;
2289
Ian Romanick02c5ae12011-07-11 10:46:01 -07002290 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
2291 if (!prog->LinkStatus)
2292 goto done;
2293
Paul Berryc06e3252011-08-11 20:58:21 -07002294 if (ctx->ShaderCompilerOptions[i].LowerClipDistance)
2295 lower_clip_distance(prog->_LinkedShaders[i]->ir);
2296
Brian Paul7feabfe2012-03-20 17:43:12 -06002297 unsigned max_unroll = ctx->ShaderCompilerOptions[i].MaxUnrollIterations;
2298
2299 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false, max_unroll))
Eric Anholt2f4fe152010-08-10 13:06:49 -07002300 ;
Ian Romanicka7ba9a72010-07-20 13:36:32 -07002301 }
Ian Romanick13e10e42010-06-21 12:03:24 -07002302
Ian Romanickd32d4f72011-06-27 17:59:58 -07002303 /* FINISHME: The value of the max_attribute_index parameter is
2304 * FINISHME: implementation dependent based on the value of
2305 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
2306 * FINISHME: at least 16, so hardcode 16 for now.
2307 */
2308 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX, 16)) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07002309 goto done;
2310 }
2311
2312 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, ctx->Const.MaxDrawBuffers)) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07002313 goto done;
Ian Romanick40e114b2010-08-17 14:55:50 -07002314 }
2315
Ian Romanick3322fba2010-10-14 13:28:42 -07002316 unsigned prev;
2317 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
2318 if (prog->_LinkedShaders[prev] != NULL)
2319 break;
2320 }
2321
Paul Berry871ddb92011-11-05 11:17:32 -07002322 if (num_tfeedback_decls != 0) {
2323 /* From GL_EXT_transform_feedback:
2324 * A program will fail to link if:
2325 *
2326 * * the <count> specified by TransformFeedbackVaryingsEXT is
2327 * non-zero, but the program object has no vertex or geometry
2328 * shader;
2329 */
2330 if (prev >= MESA_SHADER_FRAGMENT) {
2331 linker_error(prog, "Transform feedback varyings specified, but "
2332 "no vertex or geometry shader is present.");
2333 goto done;
2334 }
2335
2336 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
2337 prog->TransformFeedback.NumVarying);
Paul Berry456279b2011-12-26 19:39:25 -08002338 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
Paul Berry871ddb92011-11-05 11:17:32 -07002339 prog->TransformFeedback.VaryingNames,
2340 tfeedback_decls))
2341 goto done;
2342 }
2343
Ian Romanick3322fba2010-10-14 13:28:42 -07002344 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
2345 if (prog->_LinkedShaders[i] == NULL)
2346 continue;
2347
Paul Berry871ddb92011-11-05 11:17:32 -07002348 if (!assign_varying_locations(
2349 ctx, prog, prog->_LinkedShaders[prev], prog->_LinkedShaders[i],
2350 i == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2351 tfeedback_decls))
Ian Romanickde773242011-06-09 13:31:32 -07002352 goto done;
Ian Romanickde773242011-06-09 13:31:32 -07002353
Ian Romanick3322fba2010-10-14 13:28:42 -07002354 prev = i;
2355 }
Ian Romanick13e10e42010-06-21 12:03:24 -07002356
Paul Berry871ddb92011-11-05 11:17:32 -07002357 if (prev != MESA_SHADER_FRAGMENT && num_tfeedback_decls != 0) {
2358 /* There was no fragment shader, but we still have to assign varying
2359 * locations for use by transform feedback.
2360 */
2361 if (!assign_varying_locations(
2362 ctx, prog, prog->_LinkedShaders[prev], NULL, num_tfeedback_decls,
2363 tfeedback_decls))
2364 goto done;
2365 }
2366
2367 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
2368 goto done;
2369
Ian Romanickcc90e622010-10-19 17:59:10 -07002370 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
2371 demote_shader_inputs_and_outputs(prog->_LinkedShaders[MESA_SHADER_VERTEX],
2372 ir_var_out);
Ian Romanick960d7222011-10-21 11:21:02 -07002373
2374 /* Eliminate code that is now dead due to unused vertex outputs being
2375 * demoted.
2376 */
2377 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_VERTEX]->ir, false))
2378 ;
Ian Romanickcc90e622010-10-19 17:59:10 -07002379 }
2380
2381 if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
2382 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
2383
2384 demote_shader_inputs_and_outputs(sh, ir_var_in);
2385 demote_shader_inputs_and_outputs(sh, ir_var_inout);
2386 demote_shader_inputs_and_outputs(sh, ir_var_out);
Ian Romanick960d7222011-10-21 11:21:02 -07002387
2388 /* Eliminate code that is now dead due to unused geometry outputs being
2389 * demoted.
2390 */
2391 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_GEOMETRY]->ir, false))
2392 ;
Ian Romanickcc90e622010-10-19 17:59:10 -07002393 }
2394
2395 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
2396 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2397
2398 demote_shader_inputs_and_outputs(sh, ir_var_in);
Ian Romanick960d7222011-10-21 11:21:02 -07002399
2400 /* Eliminate code that is now dead due to unused fragment inputs being
2401 * demoted. This shouldn't actually do anything other than remove
2402 * declarations of the (now unused) global variables.
2403 */
2404 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir, false))
2405 ;
Ian Romanickcc90e622010-10-19 17:59:10 -07002406 }
2407
Ian Romanick960d7222011-10-21 11:21:02 -07002408 update_array_sizes(prog);
Ian Romanick71990962011-10-18 16:01:49 -07002409 link_assign_uniform_locations(prog);
Marek Olšákec174a42011-11-18 15:00:10 +01002410 store_fragdepth_layout(prog);
Ian Romanick960d7222011-10-21 11:21:02 -07002411
Ian Romanick92f81592011-11-08 12:37:19 -08002412 if (!check_resources(ctx, prog))
2413 goto done;
2414
Ian Romanickce9171f2011-02-03 17:10:14 -08002415 /* OpenGL ES requires that a vertex shader and a fragment shader both be
2416 * present in a linked program. By checking for use of shading language
2417 * version 1.00, we also catch the GL_ARB_ES2_compatibility case.
2418 */
Eric Anholt57f79782011-07-22 12:57:47 -07002419 if (!prog->InternalSeparateShader &&
2420 (ctx->API == API_OPENGLES2 || prog->Version == 100)) {
Ian Romanickce9171f2011-02-03 17:10:14 -08002421 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
Ian Romanick586e7412011-07-28 14:04:09 -07002422 linker_error(prog, "program lacks a vertex shader\n");
Ian Romanickce9171f2011-02-03 17:10:14 -08002423 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
Ian Romanick586e7412011-07-28 14:04:09 -07002424 linker_error(prog, "program lacks a fragment shader\n");
Ian Romanickce9171f2011-02-03 17:10:14 -08002425 }
2426 }
2427
Ian Romanick13e10e42010-06-21 12:03:24 -07002428 /* FINISHME: Assign fragment shader output locations. */
2429
Ian Romanick832dfa52010-06-17 15:04:20 -07002430done:
2431 free(vert_shader_list);
Kenneth Graunke2da02e72010-11-17 11:03:57 -08002432
2433 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
2434 if (prog->_LinkedShaders[i] == NULL)
2435 continue;
2436
2437 /* Retain any live IR, but trash the rest. */
2438 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
Ian Romanick7bbcc0b2011-09-30 14:21:10 -07002439
2440 /* The symbol table in the linked shaders may contain references to
2441 * variables that were removed (e.g., unused uniforms). Since it may
2442 * contain junk, there is no possible valid use. Delete it and set the
2443 * pointer to NULL.
2444 */
2445 delete prog->_LinkedShaders[i]->symbols;
2446 prog->_LinkedShaders[i]->symbols = NULL;
Kenneth Graunke2da02e72010-11-17 11:03:57 -08002447 }
2448
Kenneth Graunked3073f52011-01-21 14:32:31 -08002449 ralloc_free(mem_ctx);
Ian Romanick832dfa52010-06-17 15:04:20 -07002450}