blob: 63ce178f44c48c53ac7f528c8ef404ed8a0b2954 [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"
Paul Berry4b11b572012-12-17 14:20:35 -080073#include "link_varyings.h"
Ian Romanicka7ba9a72010-07-20 13:36:32 -070074#include "ir_optimization.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070075
Ian Romanick3322fba2010-10-14 13:28:42 -070076extern "C" {
77#include "main/shaderobj.h"
78}
79
Ian Romanick832dfa52010-06-17 15:04:20 -070080/**
81 * Visitor that determines whether or not a variable is ever written.
82 */
83class find_assignment_visitor : public ir_hierarchical_visitor {
84public:
85 find_assignment_visitor(const char *name)
86 : name(name), found(false)
87 {
88 /* empty */
89 }
90
91 virtual ir_visitor_status visit_enter(ir_assignment *ir)
92 {
93 ir_variable *const var = ir->lhs->variable_referenced();
94
95 if (strcmp(name, var->name) == 0) {
96 found = true;
97 return visit_stop;
98 }
99
100 return visit_continue_with_parent;
101 }
102
Eric Anholt18a60232010-08-23 11:29:25 -0700103 virtual ir_visitor_status visit_enter(ir_call *ir)
104 {
Kenneth Graunke82065fa2011-09-20 18:08:11 -0700105 exec_list_iterator sig_iter = ir->callee->parameters.iterator();
Eric Anholt18a60232010-08-23 11:29:25 -0700106 foreach_iter(exec_list_iterator, iter, *ir) {
107 ir_rvalue *param_rval = (ir_rvalue *)iter.get();
108 ir_variable *sig_param = (ir_variable *)sig_iter.get();
109
Paul Berry42a29d82013-01-11 14:39:32 -0800110 if (sig_param->mode == ir_var_function_out ||
111 sig_param->mode == ir_var_function_inout) {
Eric Anholt18a60232010-08-23 11:29:25 -0700112 ir_variable *var = param_rval->variable_referenced();
113 if (var && strcmp(name, var->name) == 0) {
114 found = true;
115 return visit_stop;
116 }
117 }
118 sig_iter.next();
119 }
120
Kenneth Graunked884f602012-03-20 15:56:37 -0700121 if (ir->return_deref != NULL) {
122 ir_variable *const var = ir->return_deref->variable_referenced();
123
124 if (strcmp(name, var->name) == 0) {
125 found = true;
126 return visit_stop;
127 }
128 }
129
Eric Anholt18a60232010-08-23 11:29:25 -0700130 return visit_continue_with_parent;
131 }
132
Ian Romanick832dfa52010-06-17 15:04:20 -0700133 bool variable_found()
134 {
135 return found;
136 }
137
138private:
139 const char *name; /**< Find writes to a variable with this name. */
140 bool found; /**< Was a write to the variable found? */
141};
142
Ian Romanickc93b8f12010-06-17 15:20:22 -0700143
Ian Romanickc33e78f2010-08-13 12:30:41 -0700144/**
145 * Visitor that determines whether or not a variable is ever read.
146 */
147class find_deref_visitor : public ir_hierarchical_visitor {
148public:
149 find_deref_visitor(const char *name)
150 : name(name), found(false)
151 {
152 /* empty */
153 }
154
155 virtual ir_visitor_status visit(ir_dereference_variable *ir)
156 {
157 if (strcmp(this->name, ir->var->name) == 0) {
158 this->found = true;
159 return visit_stop;
160 }
161
162 return visit_continue;
163 }
164
165 bool variable_found() const
166 {
167 return this->found;
168 }
169
170private:
171 const char *name; /**< Find writes to a variable with this name. */
172 bool found; /**< Was a write to the variable found? */
173};
174
175
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700176void
Ian Romanick586e7412011-07-28 14:04:09 -0700177linker_error(gl_shader_program *prog, const char *fmt, ...)
Ian Romanickf36460e2010-06-23 12:07:22 -0700178{
179 va_list ap;
180
Kenneth Graunked3073f52011-01-21 14:32:31 -0800181 ralloc_strcat(&prog->InfoLog, "error: ");
Ian Romanickf36460e2010-06-23 12:07:22 -0700182 va_start(ap, fmt);
Kenneth Graunked3073f52011-01-21 14:32:31 -0800183 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
Ian Romanickf36460e2010-06-23 12:07:22 -0700184 va_end(ap);
Ian Romanick586e7412011-07-28 14:04:09 -0700185
186 prog->LinkStatus = false;
Ian Romanickf36460e2010-06-23 12:07:22 -0700187}
188
189
190void
Ian Romanick379a32f2011-07-28 14:09:06 -0700191linker_warning(gl_shader_program *prog, const char *fmt, ...)
192{
193 va_list ap;
194
195 ralloc_strcat(&prog->InfoLog, "error: ");
196 va_start(ap, fmt);
197 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
198 va_end(ap);
199
200}
201
202
203void
Paul Berry50895d42012-12-05 07:17:07 -0800204link_invalidate_variable_locations(gl_shader *sh, int input_base,
205 int output_base)
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700206{
Eric Anholt16b68b12010-06-30 11:05:43 -0700207 foreach_list(node, sh->ir) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700208 ir_variable *const var = ((ir_instruction *) node)->as_variable();
209
Paul Berry50895d42012-12-05 07:17:07 -0800210 if (var == NULL)
211 continue;
212
213 int base;
214 switch (var->mode) {
Paul Berry42a29d82013-01-11 14:39:32 -0800215 case ir_var_shader_in:
Paul Berry50895d42012-12-05 07:17:07 -0800216 base = input_base;
217 break;
Paul Berry42a29d82013-01-11 14:39:32 -0800218 case ir_var_shader_out:
Paul Berry50895d42012-12-05 07:17:07 -0800219 base = output_base;
220 break;
221 default:
222 continue;
223 }
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700224
225 /* Only assign locations for generic attributes / varyings / etc.
226 */
Paul Berry50895d42012-12-05 07:17:07 -0800227 if ((var->location >= base) && !var->explicit_location)
228 var->location = -1;
Paul Berry3c9c17d2012-12-04 15:17:01 -0800229
Paul Berry3e81c662012-12-05 10:47:55 -0800230 if ((var->location == -1) && !var->explicit_location) {
Paul Berry3c9c17d2012-12-04 15:17:01 -0800231 var->is_unmatched_generic_inout = 1;
Paul Berry3e81c662012-12-05 10:47:55 -0800232 var->location_frac = 0;
233 } else {
Paul Berry3c9c17d2012-12-04 15:17:01 -0800234 var->is_unmatched_generic_inout = 0;
Paul Berry3e81c662012-12-05 10:47:55 -0800235 }
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700236 }
237}
238
239
Ian Romanickc93b8f12010-06-17 15:20:22 -0700240/**
Ian Romanick69846702010-06-22 17:29:19 -0700241 * Determine the number of attribute slots required for a particular type
242 *
243 * This code is here because it implements the language rules of a specific
244 * GLSL version. Since it's a property of the language and not a property of
245 * types in general, it doesn't really belong in glsl_type.
246 */
247unsigned
248count_attribute_slots(const glsl_type *t)
249{
250 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
251 *
252 * "A scalar input counts the same amount against this limit as a vec4,
253 * so applications may want to consider packing groups of four
254 * unrelated float inputs together into a vector to better utilize the
255 * capabilities of the underlying hardware. A matrix input will use up
256 * multiple locations. The number of locations used will equal the
257 * number of columns in the matrix."
258 *
259 * The spec does not explicitly say how arrays are counted. However, it
260 * should be safe to assume the total number of slots consumed by an array
261 * is the number of entries in the array multiplied by the number of slots
262 * consumed by a single element of the array.
263 */
264
265 if (t->is_array())
266 return t->array_size() * count_attribute_slots(t->element_type());
267
268 if (t->is_matrix())
269 return t->matrix_columns;
270
271 return 1;
272}
273
274
275/**
Paul Berry1ad54ae2011-09-17 09:42:02 -0700276 * Verify that a vertex shader executable meets all semantic requirements.
277 *
Paul Berry642e5b412012-01-04 13:57:52 -0800278 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
279 * as a side effect.
Ian Romanickc93b8f12010-06-17 15:20:22 -0700280 *
281 * \param shader Vertex shader executable to be verified
282 */
Ian Romanick832dfa52010-06-17 15:04:20 -0700283bool
Eric Anholt849e1812010-06-30 11:49:17 -0700284validate_vertex_shader_executable(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700285 struct gl_shader *shader)
Ian Romanick832dfa52010-06-17 15:04:20 -0700286{
287 if (shader == NULL)
288 return true;
289
Eric Anholtf1c1c9e2012-03-19 22:43:27 -0700290 /* From the GLSL 1.10 spec, page 48:
291 *
292 * "The variable gl_Position is available only in the vertex
293 * language and is intended for writing the homogeneous vertex
294 * position. All executions of a well-formed vertex shader
295 * executable must write a value into this variable. [...] The
296 * variable gl_Position is available only in the vertex
297 * language and is intended for writing the homogeneous vertex
298 * position. All executions of a well-formed vertex shader
299 * executable must write a value into this variable."
300 *
301 * while in GLSL 1.40 this text is changed to:
302 *
303 * "The variable gl_Position is available only in the vertex
304 * language and is intended for writing the homogeneous vertex
305 * position. It can be written at any time during shader
306 * execution. It may also be read back by a vertex shader
307 * after being written. This value will be used by primitive
308 * assembly, clipping, culling, and other fixed functionality
309 * operations, if present, that operate on primitives after
310 * vertex processing has occurred. Its value is undefined if
311 * the vertex shader executable does not write gl_Position."
Paul Berry15ba2a52012-08-02 17:51:02 -0700312 *
313 * GLSL ES 3.00 is similar to GLSL 1.40--failing to write to gl_Position is
314 * not an error.
Eric Anholtf1c1c9e2012-03-19 22:43:27 -0700315 */
Paul Berry15ba2a52012-08-02 17:51:02 -0700316 if (prog->Version < (prog->IsES ? 300 : 140)) {
Eric Anholtf1c1c9e2012-03-19 22:43:27 -0700317 find_assignment_visitor find("gl_Position");
318 find.run(shader->ir);
319 if (!find.variable_found()) {
320 linker_error(prog, "vertex shader does not write to `gl_Position'\n");
321 return false;
322 }
Ian Romanick832dfa52010-06-17 15:04:20 -0700323 }
324
Paul Berry642e5b412012-01-04 13:57:52 -0800325 prog->Vert.ClipDistanceArraySize = 0;
326
Paul Berry15ba2a52012-08-02 17:51:02 -0700327 if (!prog->IsES && prog->Version >= 130) {
Paul Berryb453ba22011-08-11 18:10:22 -0700328 /* From section 7.1 (Vertex Shader Special Variables) of the
329 * GLSL 1.30 spec:
330 *
331 * "It is an error for a shader to statically write both
332 * gl_ClipVertex and gl_ClipDistance."
Paul Berry15ba2a52012-08-02 17:51:02 -0700333 *
334 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
335 * gl_ClipVertex nor gl_ClipDistance.
Paul Berryb453ba22011-08-11 18:10:22 -0700336 */
337 find_assignment_visitor clip_vertex("gl_ClipVertex");
338 find_assignment_visitor clip_distance("gl_ClipDistance");
339
340 clip_vertex.run(shader->ir);
341 clip_distance.run(shader->ir);
342 if (clip_vertex.variable_found() && clip_distance.variable_found()) {
343 linker_error(prog, "vertex shader writes to both `gl_ClipVertex' "
344 "and `gl_ClipDistance'\n");
345 return false;
346 }
Paul Berry1ad54ae2011-09-17 09:42:02 -0700347 prog->Vert.UsesClipDistance = clip_distance.variable_found();
Paul Berry642e5b412012-01-04 13:57:52 -0800348 ir_variable *clip_distance_var =
349 shader->symbols->get_variable("gl_ClipDistance");
350 if (clip_distance_var)
351 prog->Vert.ClipDistanceArraySize = clip_distance_var->type->length;
Paul Berryb453ba22011-08-11 18:10:22 -0700352 }
353
Ian Romanick832dfa52010-06-17 15:04:20 -0700354 return true;
355}
356
357
Ian Romanickc93b8f12010-06-17 15:20:22 -0700358/**
359 * Verify that a fragment shader executable meets all semantic requirements
360 *
361 * \param shader Fragment shader executable to be verified
362 */
Ian Romanick832dfa52010-06-17 15:04:20 -0700363bool
Eric Anholt849e1812010-06-30 11:49:17 -0700364validate_fragment_shader_executable(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700365 struct gl_shader *shader)
Ian Romanick832dfa52010-06-17 15:04:20 -0700366{
367 if (shader == NULL)
368 return true;
369
Ian Romanick832dfa52010-06-17 15:04:20 -0700370 find_assignment_visitor frag_color("gl_FragColor");
371 find_assignment_visitor frag_data("gl_FragData");
372
Eric Anholt16b68b12010-06-30 11:05:43 -0700373 frag_color.run(shader->ir);
374 frag_data.run(shader->ir);
Ian Romanick832dfa52010-06-17 15:04:20 -0700375
Ian Romanick832dfa52010-06-17 15:04:20 -0700376 if (frag_color.variable_found() && frag_data.variable_found()) {
Ian Romanick586e7412011-07-28 14:04:09 -0700377 linker_error(prog, "fragment shader writes to both "
378 "`gl_FragColor' and `gl_FragData'\n");
Ian Romanick832dfa52010-06-17 15:04:20 -0700379 return false;
380 }
381
382 return true;
383}
384
385
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700386/**
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700387 * Generate a string describing the mode of a variable
388 */
389static const char *
390mode_string(const ir_variable *var)
391{
392 switch (var->mode) {
393 case ir_var_auto:
394 return (var->read_only) ? "global constant" : "global variable";
395
Paul Berry42a29d82013-01-11 14:39:32 -0800396 case ir_var_uniform: return "uniform";
397 case ir_var_shader_in: return "shader input";
398 case ir_var_shader_out: return "shader output";
Ian Romanick7e2aa912010-07-19 17:12:42 -0700399
Kenneth Graunke819d57f2011-01-12 15:37:37 -0800400 case ir_var_const_in:
Ian Romanick7e2aa912010-07-19 17:12:42 -0700401 case ir_var_temporary:
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700402 default:
403 assert(!"Should not get here.");
404 return "invalid variable";
405 }
406}
407
408
409/**
410 * Perform validation of global variables used across multiple shaders
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700411 */
412bool
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700413cross_validate_globals(struct gl_shader_program *prog,
414 struct gl_shader **shader_list,
415 unsigned num_shaders,
416 bool uniforms_only)
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700417{
418 /* Examine all of the uniforms in all of the shaders and cross validate
419 * them.
420 */
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700421 glsl_symbol_table variables;
422 for (unsigned i = 0; i < num_shaders; i++) {
Ian Romanick3322fba2010-10-14 13:28:42 -0700423 if (shader_list[i] == NULL)
424 continue;
425
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700426 foreach_list(node, shader_list[i]->ir) {
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700427 ir_variable *const var = ((ir_instruction *) node)->as_variable();
428
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700429 if (var == NULL)
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700430 continue;
431
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700432 if (uniforms_only && (var->mode != ir_var_uniform))
433 continue;
434
Ian Romanick7e2aa912010-07-19 17:12:42 -0700435 /* Don't cross validate temporaries that are at global scope. These
436 * will eventually get pulled into the shaders 'main'.
437 */
438 if (var->mode == ir_var_temporary)
439 continue;
440
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700441 /* If a global with this name has already been seen, verify that the
442 * new instance has the same type. In addition, if the globals have
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700443 * initializers, the values of the initializers must be the same.
444 */
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700445 ir_variable *const existing = variables.get_variable(var->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700446 if (existing != NULL) {
447 if (var->type != existing->type) {
Ian Romanicka2711d62010-08-29 22:07:49 -0700448 /* Consider the types to be "the same" if both types are arrays
449 * of the same type and one of the arrays is implicitly sized.
450 * In addition, set the type of the linked variable to the
451 * explicitly sized array.
452 */
453 if (var->type->is_array()
454 && existing->type->is_array()
455 && (var->type->fields.array == existing->type->fields.array)
456 && ((var->type->length == 0)
457 || (existing->type->length == 0))) {
Ian Romanick0f4b2a02011-01-25 12:06:18 -0800458 if (var->type->length != 0) {
Ian Romanicka2711d62010-08-29 22:07:49 -0700459 existing->type = var->type;
Ian Romanick6f539212010-12-07 18:30:33 -0800460 }
Ian Romanicka2711d62010-08-29 22:07:49 -0700461 } else {
Ian Romanick586e7412011-07-28 14:04:09 -0700462 linker_error(prog, "%s `%s' declared as type "
463 "`%s' and type `%s'\n",
464 mode_string(var),
465 var->name, var->type->name,
466 existing->type->name);
Ian Romanicka2711d62010-08-29 22:07:49 -0700467 return false;
468 }
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700469 }
470
Ian Romanick68a4fc92010-10-07 17:21:22 -0700471 if (var->explicit_location) {
472 if (existing->explicit_location
473 && (var->location != existing->location)) {
Ian Romanick586e7412011-07-28 14:04:09 -0700474 linker_error(prog, "explicit locations for %s "
475 "`%s' have differing values\n",
476 mode_string(var), var->name);
Ian Romanick68a4fc92010-10-07 17:21:22 -0700477 return false;
478 }
479
480 existing->location = var->location;
481 existing->explicit_location = true;
482 }
483
Ian Romanick46173f92011-10-31 13:07:06 -0700484 /* Validate layout qualifiers for gl_FragDepth.
485 *
486 * From the AMD/ARB_conservative_depth specs:
487 *
488 * "If gl_FragDepth is redeclared in any fragment shader in a
489 * program, it must be redeclared in all fragment shaders in
490 * that program that have static assignments to
491 * gl_FragDepth. All redeclarations of gl_FragDepth in all
492 * fragment shaders in a single program must have the same set
493 * of qualifiers."
494 */
495 if (strcmp(var->name, "gl_FragDepth") == 0) {
496 bool layout_declared = var->depth_layout != ir_depth_layout_none;
497 bool layout_differs =
498 var->depth_layout != existing->depth_layout;
499
500 if (layout_declared && layout_differs) {
501 linker_error(prog,
502 "All redeclarations of gl_FragDepth in all "
503 "fragment shaders in a single program must have "
504 "the same set of qualifiers.");
505 }
506
507 if (var->used && layout_differs) {
508 linker_error(prog,
509 "If gl_FragDepth is redeclared with a layout "
510 "qualifier in any fragment shader, it must be "
511 "redeclared with the same layout qualifier in "
512 "all fragment shaders that have assignments to "
513 "gl_FragDepth");
514 }
515 }
Chad Versaceaddae332011-01-27 01:40:31 -0800516
Ian Romanickf37b1ad2011-10-31 14:31:07 -0700517 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
518 *
519 * "If a shared global has multiple initializers, the
520 * initializers must all be constant expressions, and they
521 * must all have the same value. Otherwise, a link error will
522 * result. (A shared global having only one initializer does
523 * not require that initializer to be a constant expression.)"
524 *
525 * Previous to 4.20 the GLSL spec simply said that initializers
526 * must have the same value. In this case of non-constant
527 * initializers, this was impossible to determine. As a result,
528 * no vendor actually implemented that behavior. The 4.20
529 * behavior matches the implemented behavior of at least one other
530 * vendor, so we'll implement that for all GLSL versions.
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700531 */
Ian Romanickf37b1ad2011-10-31 14:31:07 -0700532 if (var->constant_initializer != NULL) {
533 if (existing->constant_initializer != NULL) {
534 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
Ian Romanick586e7412011-07-28 14:04:09 -0700535 linker_error(prog, "initializers for %s "
536 "`%s' have differing values\n",
537 mode_string(var), var->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700538 return false;
539 }
Ian Romanickf37b1ad2011-10-31 14:31:07 -0700540 } else {
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700541 /* If the first-seen instance of a particular uniform did not
542 * have an initializer but a later instance does, copy the
543 * initializer to the version stored in the symbol table.
544 */
Ian Romanickde415b72010-07-14 13:22:12 -0700545 /* FINISHME: This is wrong. The constant_value field should
546 * FINISHME: not be modified! Imagine a case where a shader
547 * FINISHME: without an initializer is linked in two different
548 * FINISHME: programs with shaders that have differing
549 * FINISHME: initializers. Linking with the first will
550 * FINISHME: modify the shader, and linking with the second
551 * FINISHME: will fail.
552 */
Ian Romanickf37b1ad2011-10-31 14:31:07 -0700553 existing->constant_initializer =
554 var->constant_initializer->clone(ralloc_parent(existing),
555 NULL);
556 }
557 }
558
559 if (var->has_initializer) {
560 if (existing->has_initializer
561 && (var->constant_initializer == NULL
562 || existing->constant_initializer == NULL)) {
563 linker_error(prog,
564 "shared global variable `%s' has multiple "
565 "non-constant initializers.\n",
566 var->name);
567 return false;
568 }
569
570 /* Some instance had an initializer, so keep track of that. In
571 * this location, all sorts of initializers (constant or
572 * otherwise) will propagate the existence to the variable
573 * stored in the symbol table.
574 */
575 existing->has_initializer = true;
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700576 }
Chad Versace7528f142010-11-17 14:34:38 -0800577
578 if (existing->invariant != var->invariant) {
Ian Romanick586e7412011-07-28 14:04:09 -0700579 linker_error(prog, "declarations for %s `%s' have "
580 "mismatching invariant qualifiers\n",
581 mode_string(var), var->name);
Chad Versace7528f142010-11-17 14:34:38 -0800582 return false;
583 }
Chad Versace61428dd2011-01-10 15:29:30 -0800584 if (existing->centroid != var->centroid) {
Ian Romanick586e7412011-07-28 14:04:09 -0700585 linker_error(prog, "declarations for %s `%s' have "
586 "mismatching centroid qualifiers\n",
587 mode_string(var), var->name);
Chad Versace61428dd2011-01-10 15:29:30 -0800588 return false;
589 }
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700590 } else
Eric Anholt001eee52010-11-05 06:11:24 -0700591 variables.add_variable(var);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700592 }
593 }
594
595 return true;
596}
597
598
Ian Romanick37101922010-06-18 19:02:10 -0700599/**
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700600 * Perform validation of uniforms used across multiple shader stages
601 */
602bool
603cross_validate_uniforms(struct gl_shader_program *prog)
604{
605 return cross_validate_globals(prog, prog->_LinkedShaders,
Ian Romanick3322fba2010-10-14 13:28:42 -0700606 MESA_SHADER_TYPES, true);
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700607}
608
Eric Anholtf609cf72012-04-27 13:52:56 -0700609/**
610 * Accumulates the array of prog->UniformBlocks and checks that all
611 * definitons of blocks agree on their contents.
612 */
613static bool
614interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog)
615{
616 unsigned max_num_uniform_blocks = 0;
617 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
618 if (prog->_LinkedShaders[i])
619 max_num_uniform_blocks += prog->_LinkedShaders[i]->NumUniformBlocks;
620 }
621
622 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
623 struct gl_shader *sh = prog->_LinkedShaders[i];
624
625 prog->UniformBlockStageIndex[i] = ralloc_array(prog, int,
626 max_num_uniform_blocks);
627 for (unsigned int j = 0; j < max_num_uniform_blocks; j++)
628 prog->UniformBlockStageIndex[i][j] = -1;
629
630 if (sh == NULL)
631 continue;
632
633 for (unsigned int j = 0; j < sh->NumUniformBlocks; j++) {
634 int index = link_cross_validate_uniform_block(prog,
635 &prog->UniformBlocks,
636 &prog->NumUniformBlocks,
637 &sh->UniformBlocks[j]);
638
639 if (index == -1) {
640 linker_error(prog, "uniform block `%s' has mismatching definitions",
641 sh->UniformBlocks[j].Name);
642 return false;
643 }
644
645 prog->UniformBlockStageIndex[i][index] = j;
646 }
647 }
648
649 return true;
650}
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700651
Ian Romanick37101922010-06-18 19:02:10 -0700652
Ian Romanick3fb87872010-07-09 14:09:34 -0700653/**
654 * Populates a shaders symbol table with all global declarations
655 */
656static void
657populate_symbol_table(gl_shader *sh)
658{
659 sh->symbols = new(sh) glsl_symbol_table;
660
661 foreach_list(node, sh->ir) {
662 ir_instruction *const inst = (ir_instruction *) node;
663 ir_variable *var;
664 ir_function *func;
665
666 if ((func = inst->as_function()) != NULL) {
Eric Anholte8f5ebf2010-11-05 06:08:45 -0700667 sh->symbols->add_function(func);
Ian Romanick3fb87872010-07-09 14:09:34 -0700668 } else if ((var = inst->as_variable()) != NULL) {
Eric Anholt001eee52010-11-05 06:11:24 -0700669 sh->symbols->add_variable(var);
Ian Romanick3fb87872010-07-09 14:09:34 -0700670 }
671 }
672}
673
674
675/**
Ian Romanick31a97862010-07-12 18:48:50 -0700676 * Remap variables referenced in an instruction tree
677 *
678 * This is used when instruction trees are cloned from one shader and placed in
679 * another. These trees will contain references to \c ir_variable nodes that
680 * do not exist in the target shader. This function finds these \c ir_variable
681 * references and replaces the references with matching variables in the target
682 * shader.
683 *
684 * If there is no matching variable in the target shader, a clone of the
685 * \c ir_variable is made and added to the target shader. The new variable is
686 * added to \b both the instruction stream and the symbol table.
687 *
688 * \param inst IR tree that is to be processed.
689 * \param symbols Symbol table containing global scope symbols in the
690 * linked shader.
691 * \param instructions Instruction stream where new variable declarations
692 * should be added.
693 */
694void
Eric Anholt8273bd42010-08-04 12:34:56 -0700695remap_variables(ir_instruction *inst, struct gl_shader *target,
696 hash_table *temps)
Ian Romanick31a97862010-07-12 18:48:50 -0700697{
698 class remap_visitor : public ir_hierarchical_visitor {
699 public:
Eric Anholt8273bd42010-08-04 12:34:56 -0700700 remap_visitor(struct gl_shader *target,
Ian Romanick7e2aa912010-07-19 17:12:42 -0700701 hash_table *temps)
Ian Romanick31a97862010-07-12 18:48:50 -0700702 {
Eric Anholt8273bd42010-08-04 12:34:56 -0700703 this->target = target;
704 this->symbols = target->symbols;
705 this->instructions = target->ir;
Ian Romanick7e2aa912010-07-19 17:12:42 -0700706 this->temps = temps;
Ian Romanick31a97862010-07-12 18:48:50 -0700707 }
708
709 virtual ir_visitor_status visit(ir_dereference_variable *ir)
710 {
Ian Romanick7e2aa912010-07-19 17:12:42 -0700711 if (ir->var->mode == ir_var_temporary) {
712 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
713
714 assert(var != NULL);
715 ir->var = var;
716 return visit_continue;
717 }
718
Ian Romanick31a97862010-07-12 18:48:50 -0700719 ir_variable *const existing =
720 this->symbols->get_variable(ir->var->name);
721 if (existing != NULL)
722 ir->var = existing;
723 else {
Eric Anholt8273bd42010-08-04 12:34:56 -0700724 ir_variable *copy = ir->var->clone(this->target, NULL);
Ian Romanick31a97862010-07-12 18:48:50 -0700725
Eric Anholt001eee52010-11-05 06:11:24 -0700726 this->symbols->add_variable(copy);
Ian Romanick31a97862010-07-12 18:48:50 -0700727 this->instructions->push_head(copy);
Ian Romanick7e2aa912010-07-19 17:12:42 -0700728 ir->var = copy;
Ian Romanick31a97862010-07-12 18:48:50 -0700729 }
730
731 return visit_continue;
732 }
733
734 private:
Eric Anholt8273bd42010-08-04 12:34:56 -0700735 struct gl_shader *target;
Ian Romanick31a97862010-07-12 18:48:50 -0700736 glsl_symbol_table *symbols;
737 exec_list *instructions;
Ian Romanick7e2aa912010-07-19 17:12:42 -0700738 hash_table *temps;
Ian Romanick31a97862010-07-12 18:48:50 -0700739 };
740
Eric Anholt8273bd42010-08-04 12:34:56 -0700741 remap_visitor v(target, temps);
Ian Romanick31a97862010-07-12 18:48:50 -0700742
743 inst->accept(&v);
744}
745
746
747/**
748 * Move non-declarations from one instruction stream to another
749 *
750 * The intended usage pattern of this function is to pass the pointer to the
Eric Anholt62c47632010-07-29 13:52:25 -0700751 * 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 -0700752 * pointer) for \c last and \c false for \c make_copies on the first
753 * call. Successive calls pass the return value of the previous call for
754 * \c last and \c true for \c make_copies.
755 *
756 * \param instructions Source instruction stream
757 * \param last Instruction after which new instructions should be
758 * inserted in the target instruction stream
759 * \param make_copies Flag selecting whether instructions in \c instructions
760 * should be copied (via \c ir_instruction::clone) into the
761 * target list or moved.
762 *
763 * \return
764 * The new "last" instruction in the target instruction stream. This pointer
765 * is suitable for use as the \c last parameter of a later call to this
766 * function.
767 */
768exec_node *
769move_non_declarations(exec_list *instructions, exec_node *last,
770 bool make_copies, gl_shader *target)
771{
Ian Romanick7e2aa912010-07-19 17:12:42 -0700772 hash_table *temps = NULL;
773
774 if (make_copies)
775 temps = hash_table_ctor(0, hash_table_pointer_hash,
776 hash_table_pointer_compare);
777
Ian Romanick303c99f2010-07-19 12:34:56 -0700778 foreach_list_safe(node, instructions) {
Ian Romanick31a97862010-07-12 18:48:50 -0700779 ir_instruction *inst = (ir_instruction *) node;
780
Ian Romanick7e2aa912010-07-19 17:12:42 -0700781 if (inst->as_function())
Ian Romanick31a97862010-07-12 18:48:50 -0700782 continue;
783
Ian Romanick7e2aa912010-07-19 17:12:42 -0700784 ir_variable *var = inst->as_variable();
785 if ((var != NULL) && (var->mode != ir_var_temporary))
786 continue;
787
788 assert(inst->as_assignment()
Kenneth Graunked884f602012-03-20 15:56:37 -0700789 || inst->as_call()
Kenneth Graunkeb45a68e2012-10-24 13:17:24 -0700790 || inst->as_if() /* for initializers with the ?: operator */
Ian Romanick7e2aa912010-07-19 17:12:42 -0700791 || ((var != NULL) && (var->mode == ir_var_temporary)));
Ian Romanick31a97862010-07-12 18:48:50 -0700792
793 if (make_copies) {
Eric Anholt8273bd42010-08-04 12:34:56 -0700794 inst = inst->clone(target, NULL);
Ian Romanick7e2aa912010-07-19 17:12:42 -0700795
796 if (var != NULL)
797 hash_table_insert(temps, inst, var);
798 else
Eric Anholt8273bd42010-08-04 12:34:56 -0700799 remap_variables(inst, target, temps);
Ian Romanick31a97862010-07-12 18:48:50 -0700800 } else {
801 inst->remove();
802 }
803
804 last->insert_after(inst);
805 last = inst;
806 }
807
Ian Romanick7e2aa912010-07-19 17:12:42 -0700808 if (make_copies)
809 hash_table_dtor(temps);
810
Ian Romanick31a97862010-07-12 18:48:50 -0700811 return last;
812}
813
814/**
Ian Romanick15ce87e2010-07-09 15:28:22 -0700815 * Get the function signature for main from a shader
816 */
817static ir_function_signature *
818get_main_function_signature(gl_shader *sh)
819{
820 ir_function *const f = sh->symbols->get_function("main");
821 if (f != NULL) {
822 exec_list void_parameters;
823
824 /* Look for the 'void main()' signature and ensure that it's defined.
825 * This keeps the linker from accidentally pick a shader that just
826 * contains a prototype for main.
827 *
828 * We don't have to check for multiple definitions of main (in multiple
829 * shaders) because that would have already been caught above.
830 */
831 ir_function_signature *sig = f->matching_signature(&void_parameters);
832 if ((sig != NULL) && sig->is_defined) {
833 return sig;
834 }
835 }
836
837 return NULL;
838}
839
840
841/**
Brian Paul84a12732012-02-02 20:10:40 -0700842 * This class is only used in link_intrastage_shaders() below but declaring
843 * it inside that function leads to compiler warnings with some versions of
844 * gcc.
845 */
846class array_sizing_visitor : public ir_hierarchical_visitor {
847public:
848 virtual ir_visitor_status visit(ir_variable *var)
849 {
850 if (var->type->is_array() && (var->type->length == 0)) {
851 const glsl_type *type =
852 glsl_type::get_array_instance(var->type->fields.array,
853 var->max_array_access + 1);
854 assert(type != NULL);
855 var->type = type;
856 }
857 return visit_continue;
858 }
859};
860
Brian Paul84a12732012-02-02 20:10:40 -0700861/**
Ian Romanick3fb87872010-07-09 14:09:34 -0700862 * Combine a group of shaders for a single stage to generate a linked shader
863 *
864 * \note
865 * If this function is supplied a single shader, it is cloned, and the new
866 * shader is returned.
867 */
868static struct gl_shader *
Kenneth Graunke2da02e72010-11-17 11:03:57 -0800869link_intrastage_shaders(void *mem_ctx,
870 struct gl_context *ctx,
Eric Anholt5d0f4302010-08-18 12:02:35 -0700871 struct gl_shader_program *prog,
Ian Romanick3fb87872010-07-09 14:09:34 -0700872 struct gl_shader **shader_list,
873 unsigned num_shaders)
874{
Eric Anholtf609cf72012-04-27 13:52:56 -0700875 struct gl_uniform_block *uniform_blocks = NULL;
Eric Anholtf609cf72012-04-27 13:52:56 -0700876
Ian Romanick13f782c2010-06-29 18:53:38 -0700877 /* Check that global variables defined in multiple shaders are consistent.
878 */
879 if (!cross_validate_globals(prog, shader_list, num_shaders, false))
880 return NULL;
881
Eric Anholtf609cf72012-04-27 13:52:56 -0700882 /* Check that uniform blocks between shaders for a stage agree. */
Ian Romanick514f8c72013-01-22 01:09:16 -0500883 const int num_uniform_blocks =
884 link_uniform_blocks(mem_ctx, prog, shader_list, num_shaders,
885 &uniform_blocks);
886 if (num_uniform_blocks < 0)
887 return NULL;
Eric Anholtf609cf72012-04-27 13:52:56 -0700888
Ian Romanick13f782c2010-06-29 18:53:38 -0700889 /* Check that there is only a single definition of each function signature
890 * across all shaders.
891 */
892 for (unsigned i = 0; i < (num_shaders - 1); i++) {
893 foreach_list(node, shader_list[i]->ir) {
894 ir_function *const f = ((ir_instruction *) node)->as_function();
895
896 if (f == NULL)
897 continue;
898
899 for (unsigned j = i + 1; j < num_shaders; j++) {
900 ir_function *const other =
901 shader_list[j]->symbols->get_function(f->name);
902
903 /* If the other shader has no function (and therefore no function
904 * signatures) with the same name, skip to the next shader.
905 */
906 if (other == NULL)
907 continue;
908
909 foreach_iter (exec_list_iterator, iter, *f) {
910 ir_function_signature *sig =
911 (ir_function_signature *) iter.get();
912
Kenneth Graunkef412fac2010-09-05 01:48:11 -0700913 if (!sig->is_defined || sig->is_builtin)
Ian Romanick13f782c2010-06-29 18:53:38 -0700914 continue;
915
916 ir_function_signature *other_sig =
917 other->exact_matching_signature(& sig->parameters);
918
919 if ((other_sig != NULL) && other_sig->is_defined
Kenneth Graunkef412fac2010-09-05 01:48:11 -0700920 && !other_sig->is_builtin) {
Ian Romanick586e7412011-07-28 14:04:09 -0700921 linker_error(prog, "function `%s' is multiply defined",
922 f->name);
Ian Romanick13f782c2010-06-29 18:53:38 -0700923 return NULL;
924 }
925 }
926 }
927 }
928 }
929
930 /* Find the shader that defines main, and make a clone of it.
931 *
932 * Starting with the clone, search for undefined references. If one is
933 * found, find the shader that defines it. Clone the reference and add
934 * it to the shader. Repeat until there are no undefined references or
935 * until a reference cannot be resolved.
936 */
Ian Romanick15ce87e2010-07-09 15:28:22 -0700937 gl_shader *main = NULL;
938 for (unsigned i = 0; i < num_shaders; i++) {
939 if (get_main_function_signature(shader_list[i]) != NULL) {
940 main = shader_list[i];
941 break;
942 }
943 }
Ian Romanick13f782c2010-06-29 18:53:38 -0700944
Ian Romanick15ce87e2010-07-09 15:28:22 -0700945 if (main == NULL) {
Ian Romanick586e7412011-07-28 14:04:09 -0700946 linker_error(prog, "%s shader lacks `main'\n",
947 (shader_list[0]->Type == GL_VERTEX_SHADER)
948 ? "vertex" : "fragment");
Ian Romanick15ce87e2010-07-09 15:28:22 -0700949 return NULL;
950 }
951
Ian Romanick4a455952010-10-13 15:13:02 -0700952 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
Ian Romanick15ce87e2010-07-09 15:28:22 -0700953 linked->ir = new(linked) exec_list;
Kenneth Graunke2da02e72010-11-17 11:03:57 -0800954 clone_ir_list(mem_ctx, linked->ir, main->ir);
Ian Romanick15ce87e2010-07-09 15:28:22 -0700955
Eric Anholtf609cf72012-04-27 13:52:56 -0700956 linked->UniformBlocks = uniform_blocks;
957 linked->NumUniformBlocks = num_uniform_blocks;
958 ralloc_steal(linked, linked->UniformBlocks);
959
Ian Romanick15ce87e2010-07-09 15:28:22 -0700960 populate_symbol_table(linked);
Ian Romanick13f782c2010-06-29 18:53:38 -0700961
Ian Romanick31a97862010-07-12 18:48:50 -0700962 /* The a pointer to the main function in the final linked shader (i.e., the
963 * copy of the original shader that contained the main function).
964 */
965 ir_function_signature *const main_sig = get_main_function_signature(linked);
966
967 /* Move any instructions other than variable declarations or function
968 * declarations into main.
969 */
Ian Romanick9303e352010-07-19 12:33:54 -0700970 exec_node *insertion_point =
971 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
972 linked);
973
Ian Romanick31a97862010-07-12 18:48:50 -0700974 for (unsigned i = 0; i < num_shaders; i++) {
Ian Romanick9303e352010-07-19 12:33:54 -0700975 if (shader_list[i] == main)
976 continue;
977
Ian Romanick31a97862010-07-12 18:48:50 -0700978 insertion_point = move_non_declarations(shader_list[i]->ir,
Ian Romanick9303e352010-07-19 12:33:54 -0700979 insertion_point, true, linked);
Ian Romanick31a97862010-07-12 18:48:50 -0700980 }
981
Ian Romanick13f782c2010-06-29 18:53:38 -0700982 /* Resolve initializers for global variables in the linked shader.
983 */
Ian Romanickd5be2ac2010-07-20 11:29:46 -0700984 unsigned num_linking_shaders = num_shaders;
985 for (unsigned i = 0; i < num_shaders; i++)
986 num_linking_shaders += shader_list[i]->num_builtins_to_link;
987
988 gl_shader **linking_shaders =
989 (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
990
991 memcpy(linking_shaders, shader_list,
992 sizeof(linking_shaders[0]) * num_shaders);
993
994 unsigned idx = num_shaders;
995 for (unsigned i = 0; i < num_shaders; i++) {
996 memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
997 sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
998 idx += shader_list[i]->num_builtins_to_link;
999 }
1000
1001 assert(idx == num_linking_shaders);
1002
Ian Romanick4a455952010-10-13 15:13:02 -07001003 if (!link_function_calls(prog, linked, linking_shaders,
1004 num_linking_shaders)) {
1005 ctx->Driver.DeleteShader(ctx, linked);
1006 linked = NULL;
1007 }
Ian Romanickd5be2ac2010-07-20 11:29:46 -07001008
1009 free(linking_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07001010
Paul Berryc148ef62011-08-03 15:37:01 -07001011#ifdef DEBUG
1012 /* At this point linked should contain all of the linked IR, so
1013 * validate it to make sure nothing went wrong.
1014 */
1015 if (linked)
1016 validate_ir_tree(linked->ir);
1017#endif
1018
Ian Romanickc87e9ef2011-01-25 12:04:08 -08001019 /* Make a pass over all variable declarations to ensure that arrays with
Ian Romanick6f539212010-12-07 18:30:33 -08001020 * unspecified sizes have a size specified. The size is inferred from the
1021 * max_array_access field.
1022 */
Ian Romanick002cd2c2010-12-07 19:00:44 -08001023 if (linked != NULL) {
Brian Paul84a12732012-02-02 20:10:40 -07001024 array_sizing_visitor v;
Ian Romanick6f539212010-12-07 18:30:33 -08001025
Ian Romanickc87e9ef2011-01-25 12:04:08 -08001026 v.run(linked->ir);
Ian Romanick6f539212010-12-07 18:30:33 -08001027 }
1028
Ian Romanick3fb87872010-07-09 14:09:34 -07001029 return linked;
1030}
1031
Eric Anholta721abf2010-08-23 10:32:01 -07001032/**
1033 * Update the sizes of linked shader uniform arrays to the maximum
1034 * array index used.
1035 *
1036 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1037 *
1038 * If one or more elements of an array are active,
1039 * GetActiveUniform will return the name of the array in name,
1040 * subject to the restrictions listed above. The type of the array
1041 * is returned in type. The size parameter contains the highest
1042 * array element index used, plus one. The compiler or linker
1043 * determines the highest index used. There will be only one
1044 * active uniform reported by the GL per uniform array.
1045
1046 */
1047static void
Eric Anholt586b4b52010-09-28 14:32:16 -07001048update_array_sizes(struct gl_shader_program *prog)
Eric Anholta721abf2010-08-23 10:32:01 -07001049{
Ian Romanick3322fba2010-10-14 13:28:42 -07001050 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1051 if (prog->_LinkedShaders[i] == NULL)
1052 continue;
1053
Eric Anholta721abf2010-08-23 10:32:01 -07001054 foreach_list(node, prog->_LinkedShaders[i]->ir) {
1055 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1056
Eric Anholt586b4b52010-09-28 14:32:16 -07001057 if ((var == NULL) || (var->mode != ir_var_uniform &&
Paul Berry42a29d82013-01-11 14:39:32 -08001058 var->mode != ir_var_shader_in &&
1059 var->mode != ir_var_shader_out) ||
Eric Anholta721abf2010-08-23 10:32:01 -07001060 !var->type->is_array())
1061 continue;
1062
Eric Anholt9feb4032012-05-01 14:43:31 -07001063 /* GL_ARB_uniform_buffer_object says that std140 uniforms
1064 * will not be eliminated. Since we always do std140, just
1065 * don't resize arrays in UBOs.
1066 */
Ian Romanick13be1f42012-12-14 12:00:14 -08001067 if (var->is_in_uniform_block())
Eric Anholt9feb4032012-05-01 14:43:31 -07001068 continue;
1069
Eric Anholta721abf2010-08-23 10:32:01 -07001070 unsigned int size = var->max_array_access;
Ian Romanick3322fba2010-10-14 13:28:42 -07001071 for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
1072 if (prog->_LinkedShaders[j] == NULL)
1073 continue;
1074
Eric Anholta721abf2010-08-23 10:32:01 -07001075 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
1076 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
1077 if (!other_var)
1078 continue;
1079
1080 if (strcmp(var->name, other_var->name) == 0 &&
1081 other_var->max_array_access > size) {
1082 size = other_var->max_array_access;
1083 }
1084 }
1085 }
Eric Anholt586b4b52010-09-28 14:32:16 -07001086
Eric Anholta721abf2010-08-23 10:32:01 -07001087 if (size + 1 != var->type->fields.array->length) {
Ian Romanick89d81ab2011-01-25 10:41:20 -08001088 /* If this is a built-in uniform (i.e., it's backed by some
1089 * fixed-function state), adjust the number of state slots to
1090 * match the new array size. The number of slots per array entry
Bryan Cainf18a0862011-04-23 19:29:15 -05001091 * is not known. It seems safe to assume that the total number of
Ian Romanick89d81ab2011-01-25 10:41:20 -08001092 * slots is an integer multiple of the number of array elements.
1093 * Determine the number of slots per array element by dividing by
1094 * the old (total) size.
1095 */
1096 if (var->num_state_slots > 0) {
1097 var->num_state_slots = (size + 1)
1098 * (var->num_state_slots / var->type->length);
1099 }
1100
Eric Anholta721abf2010-08-23 10:32:01 -07001101 var->type = glsl_type::get_array_instance(var->type->fields.array,
1102 size + 1);
1103 /* FINISHME: We should update the types of array
1104 * dereferences of this variable now.
1105 */
1106 }
1107 }
1108 }
1109}
1110
Ian Romanick69846702010-06-22 17:29:19 -07001111/**
Bryan Cainf18a0862011-04-23 19:29:15 -05001112 * Find a contiguous set of available bits in a bitmask.
Ian Romanick69846702010-06-22 17:29:19 -07001113 *
1114 * \param used_mask Bits representing used (1) and unused (0) locations
1115 * \param needed_count Number of contiguous bits needed.
1116 *
1117 * \return
1118 * Base location of the available bits on success or -1 on failure.
1119 */
1120int
1121find_available_slots(unsigned used_mask, unsigned needed_count)
1122{
1123 unsigned needed_mask = (1 << needed_count) - 1;
1124 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1125
1126 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1127 * cannot optimize possibly infinite loops" for the loop below.
1128 */
1129 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1130 return -1;
1131
1132 for (int i = 0; i <= max_bit_to_test; i++) {
1133 if ((needed_mask & ~used_mask) == needed_mask)
1134 return i;
1135
1136 needed_mask <<= 1;
1137 }
1138
1139 return -1;
1140}
1141
1142
Ian Romanickd32d4f72011-06-27 17:59:58 -07001143/**
1144 * Assign locations for either VS inputs for FS outputs
1145 *
1146 * \param prog Shader program whose variables need locations assigned
1147 * \param target_index Selector for the program target to receive location
1148 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1149 * \c MESA_SHADER_FRAGMENT.
1150 * \param max_index Maximum number of generic locations. This corresponds
1151 * to either the maximum number of draw buffers or the
1152 * maximum number of generic attributes.
1153 *
1154 * \return
1155 * If locations are successfully assigned, true is returned. Otherwise an
1156 * error is emitted to the shader link log and false is returned.
Ian Romanickd32d4f72011-06-27 17:59:58 -07001157 */
Ian Romanick69846702010-06-22 17:29:19 -07001158bool
Ian Romanickd32d4f72011-06-27 17:59:58 -07001159assign_attribute_or_color_locations(gl_shader_program *prog,
1160 unsigned target_index,
1161 unsigned max_index)
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001162{
Ian Romanickd32d4f72011-06-27 17:59:58 -07001163 /* Mark invalid locations as being used.
Ian Romanick9342d262010-06-22 17:41:37 -07001164 */
Ian Romanickd32d4f72011-06-27 17:59:58 -07001165 unsigned used_locations = (max_index >= 32)
1166 ? ~0 : ~((1 << max_index) - 1);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001167
Ian Romanickd32d4f72011-06-27 17:59:58 -07001168 assert((target_index == MESA_SHADER_VERTEX)
1169 || (target_index == MESA_SHADER_FRAGMENT));
1170
1171 gl_shader *const sh = prog->_LinkedShaders[target_index];
1172 if (sh == NULL)
1173 return true;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001174
Ian Romanick69846702010-06-22 17:29:19 -07001175 /* Operate in a total of four passes.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001176 *
1177 * 1. Invalidate the location assignments for all vertex shader inputs.
1178 *
1179 * 2. Assign locations for inputs that have user-defined (via
Ian Romanickb12b5d92011-11-04 16:08:52 -07001180 * glBindVertexAttribLocation) locations and outputs that have
1181 * user-defined locations (via glBindFragDataLocation).
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001182 *
Ian Romanick69846702010-06-22 17:29:19 -07001183 * 3. Sort the attributes without assigned locations by number of slots
1184 * required in decreasing order. Fragmentation caused by attribute
1185 * locations assigned by the application may prevent large attributes
1186 * from having enough contiguous space.
1187 *
1188 * 4. Assign locations to any inputs without assigned locations.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001189 */
1190
Ian Romanickd32d4f72011-06-27 17:59:58 -07001191 const int generic_base = (target_index == MESA_SHADER_VERTEX)
Brian Paul7eb7d672011-07-07 16:47:59 -06001192 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001193
Ian Romanickd32d4f72011-06-27 17:59:58 -07001194 const enum ir_variable_mode direction =
Paul Berry42a29d82013-01-11 14:39:32 -08001195 (target_index == MESA_SHADER_VERTEX)
1196 ? ir_var_shader_in : ir_var_shader_out;
Ian Romanickd32d4f72011-06-27 17:59:58 -07001197
1198
Ian Romanick69846702010-06-22 17:29:19 -07001199 /* Temporary storage for the set of attributes that need locations assigned.
1200 */
1201 struct temp_attr {
1202 unsigned slots;
1203 ir_variable *var;
1204
1205 /* Used below in the call to qsort. */
1206 static int compare(const void *a, const void *b)
1207 {
1208 const temp_attr *const l = (const temp_attr *) a;
1209 const temp_attr *const r = (const temp_attr *) b;
1210
1211 /* Reversed because we want a descending order sort below. */
1212 return r->slots - l->slots;
1213 }
1214 } to_assign[16];
1215
1216 unsigned num_attr = 0;
1217
Eric Anholt16b68b12010-06-30 11:05:43 -07001218 foreach_list(node, sh->ir) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001219 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1220
Brian Paul4470ff22011-07-19 21:10:25 -06001221 if ((var == NULL) || (var->mode != (unsigned) direction))
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001222 continue;
1223
Ian Romanick68a4fc92010-10-07 17:21:22 -07001224 if (var->explicit_location) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07001225 if ((var->location >= (int)(max_index + generic_base))
Ian Romanick68a4fc92010-10-07 17:21:22 -07001226 || (var->location < 0)) {
Ian Romanick586e7412011-07-28 14:04:09 -07001227 linker_error(prog,
1228 "invalid explicit location %d specified for `%s'\n",
Ian Romanick523b6112011-08-17 15:40:03 -07001229 (var->location < 0)
1230 ? var->location : var->location - generic_base,
Ian Romanick586e7412011-07-28 14:04:09 -07001231 var->name);
Ian Romanick68a4fc92010-10-07 17:21:22 -07001232 return false;
Ian Romanick523b6112011-08-17 15:40:03 -07001233 }
1234 } else if (target_index == MESA_SHADER_VERTEX) {
1235 unsigned binding;
1236
1237 if (prog->AttributeBindings->get(binding, var->name)) {
1238 assert(binding >= VERT_ATTRIB_GENERIC0);
1239 var->location = binding;
Paul Berry3c9c17d2012-12-04 15:17:01 -08001240 var->is_unmatched_generic_inout = 0;
Ian Romanick68a4fc92010-10-07 17:21:22 -07001241 }
Ian Romanickb12b5d92011-11-04 16:08:52 -07001242 } else if (target_index == MESA_SHADER_FRAGMENT) {
1243 unsigned binding;
Dave Airlie1256a5d2012-03-24 13:33:41 +00001244 unsigned index;
Ian Romanickb12b5d92011-11-04 16:08:52 -07001245
1246 if (prog->FragDataBindings->get(binding, var->name)) {
1247 assert(binding >= FRAG_RESULT_DATA0);
1248 var->location = binding;
Paul Berry3c9c17d2012-12-04 15:17:01 -08001249 var->is_unmatched_generic_inout = 0;
Dave Airlie1256a5d2012-03-24 13:33:41 +00001250
1251 if (prog->FragDataIndexBindings->get(index, var->name)) {
1252 var->index = index;
1253 }
Ian Romanickb12b5d92011-11-04 16:08:52 -07001254 }
Ian Romanick68a4fc92010-10-07 17:21:22 -07001255 }
1256
Ian Romanick9f0e98d2011-10-06 10:25:34 -07001257 /* If the variable is not a built-in and has a location statically
1258 * assigned in the shader (presumably via a layout qualifier), make sure
1259 * that it doesn't collide with other assigned locations. Otherwise,
1260 * add it to the list of variables that need linker-assigned locations.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001261 */
Ian Romanick523b6112011-08-17 15:40:03 -07001262 const unsigned slots = count_attribute_slots(var->type);
1263 if (var->location != -1) {
Dave Airlie1256a5d2012-03-24 13:33:41 +00001264 if (var->location >= generic_base && var->index < 1) {
Ian Romanick523b6112011-08-17 15:40:03 -07001265 /* From page 61 of the OpenGL 4.0 spec:
1266 *
1267 * "LinkProgram will fail if the attribute bindings assigned
1268 * by BindAttribLocation do not leave not enough space to
1269 * assign a location for an active matrix attribute or an
1270 * active attribute array, both of which require multiple
1271 * contiguous generic attributes."
1272 *
1273 * Previous versions of the spec contain similar language but omit
1274 * the bit about attribute arrays.
1275 *
1276 * Page 61 of the OpenGL 4.0 spec also says:
1277 *
1278 * "It is possible for an application to bind more than one
1279 * attribute name to the same location. This is referred to as
1280 * aliasing. This will only work if only one of the aliased
1281 * attributes is active in the executable program, or if no
1282 * path through the shader consumes more than one attribute of
1283 * a set of attributes aliased to the same location. A link
1284 * error can occur if the linker determines that every path
1285 * through the shader consumes multiple aliased attributes,
1286 * but implementations are not required to generate an error
1287 * in this case."
1288 *
1289 * These two paragraphs are either somewhat contradictory, or I
1290 * don't fully understand one or both of them.
1291 */
1292 /* FINISHME: The code as currently written does not support
1293 * FINISHME: attribute location aliasing (see comment above).
1294 */
1295 /* Mask representing the contiguous slots that will be used by
1296 * this attribute.
1297 */
1298 const unsigned attr = var->location - generic_base;
1299 const unsigned use_mask = (1 << slots) - 1;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001300
Ian Romanick523b6112011-08-17 15:40:03 -07001301 /* Generate a link error if the set of bits requested for this
1302 * attribute overlaps any previously allocated bits.
1303 */
1304 if ((~(use_mask << attr) & used_locations) != used_locations) {
Dave Airlie7449ae42011-11-20 19:56:35 +00001305 const char *const string = (target_index == MESA_SHADER_VERTEX)
1306 ? "vertex shader input" : "fragment shader output";
Ian Romanick523b6112011-08-17 15:40:03 -07001307 linker_error(prog,
Dave Airlie7449ae42011-11-20 19:56:35 +00001308 "insufficient contiguous locations "
Dave Airlie1256a5d2012-03-24 13:33:41 +00001309 "available for %s `%s' %d %d %d", string,
1310 var->name, used_locations, use_mask, attr);
Ian Romanick523b6112011-08-17 15:40:03 -07001311 return false;
1312 }
1313
1314 used_locations |= (use_mask << attr);
1315 }
1316
1317 continue;
1318 }
1319
1320 to_assign[num_attr].slots = slots;
Ian Romanick69846702010-06-22 17:29:19 -07001321 to_assign[num_attr].var = var;
1322 num_attr++;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001323 }
Ian Romanick69846702010-06-22 17:29:19 -07001324
1325 /* If all of the attributes were assigned locations by the application (or
1326 * are built-in attributes with fixed locations), return early. This should
1327 * be the common case.
1328 */
1329 if (num_attr == 0)
1330 return true;
1331
1332 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1333
Ian Romanickd32d4f72011-06-27 17:59:58 -07001334 if (target_index == MESA_SHADER_VERTEX) {
1335 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
1336 * only be explicitly assigned by via glBindAttribLocation. Mark it as
1337 * reserved to prevent it from being automatically allocated below.
1338 */
1339 find_deref_visitor find("gl_Vertex");
1340 find.run(sh->ir);
1341 if (find.variable_found())
1342 used_locations |= (1 << 0);
1343 }
Ian Romanick982e3792010-06-29 18:58:20 -07001344
Ian Romanick69846702010-06-22 17:29:19 -07001345 for (unsigned i = 0; i < num_attr; i++) {
1346 /* Mask representing the contiguous slots that will be used by this
1347 * attribute.
1348 */
1349 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
1350
1351 int location = find_available_slots(used_locations, to_assign[i].slots);
1352
1353 if (location < 0) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07001354 const char *const string = (target_index == MESA_SHADER_VERTEX)
1355 ? "vertex shader input" : "fragment shader output";
1356
Ian Romanick586e7412011-07-28 14:04:09 -07001357 linker_error(prog,
Dave Airlie7449ae42011-11-20 19:56:35 +00001358 "insufficient contiguous locations "
Ian Romanick586e7412011-07-28 14:04:09 -07001359 "available for %s `%s'",
1360 string, to_assign[i].var->name);
Ian Romanick69846702010-06-22 17:29:19 -07001361 return false;
1362 }
1363
Ian Romanickd32d4f72011-06-27 17:59:58 -07001364 to_assign[i].var->location = generic_base + location;
Paul Berry3c9c17d2012-12-04 15:17:01 -08001365 to_assign[i].var->is_unmatched_generic_inout = 0;
Ian Romanick69846702010-06-22 17:29:19 -07001366 used_locations |= (use_mask << location);
1367 }
1368
1369 return true;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001370}
1371
1372
Ian Romanick40e114b2010-08-17 14:55:50 -07001373/**
Ian Romanickcc90e622010-10-19 17:59:10 -07001374 * Demote shader inputs and outputs that are not used in other stages
Ian Romanick40e114b2010-08-17 14:55:50 -07001375 */
1376void
Ian Romanickcc90e622010-10-19 17:59:10 -07001377demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
Ian Romanick40e114b2010-08-17 14:55:50 -07001378{
1379 foreach_list(node, sh->ir) {
1380 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1381
Ian Romanickcc90e622010-10-19 17:59:10 -07001382 if ((var == NULL) || (var->mode != int(mode)))
Ian Romanick40e114b2010-08-17 14:55:50 -07001383 continue;
1384
Ian Romanickcc90e622010-10-19 17:59:10 -07001385 /* A shader 'in' or 'out' variable is only really an input or output if
1386 * its value is used by other shader stages. This will cause the variable
1387 * to have a location assigned.
Ian Romanick40e114b2010-08-17 14:55:50 -07001388 */
Paul Berry3c9c17d2012-12-04 15:17:01 -08001389 if (var->is_unmatched_generic_inout) {
Ian Romanick40e114b2010-08-17 14:55:50 -07001390 var->mode = ir_var_auto;
1391 }
1392 }
1393}
1394
1395
Paul Berry871ddb92011-11-05 11:17:32 -07001396/**
Marek Olšákec174a42011-11-18 15:00:10 +01001397 * Store the gl_FragDepth layout in the gl_shader_program struct.
1398 */
1399static void
1400store_fragdepth_layout(struct gl_shader_program *prog)
1401{
1402 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
1403 return;
1404 }
1405
1406 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
1407
1408 /* We don't look up the gl_FragDepth symbol directly because if
1409 * gl_FragDepth is not used in the shader, it's removed from the IR.
1410 * However, the symbol won't be removed from the symbol table.
1411 *
1412 * We're only interested in the cases where the variable is NOT removed
1413 * from the IR.
1414 */
1415 foreach_list(node, ir) {
1416 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1417
Paul Berry42a29d82013-01-11 14:39:32 -08001418 if (var == NULL || var->mode != ir_var_shader_out) {
Marek Olšákec174a42011-11-18 15:00:10 +01001419 continue;
1420 }
1421
1422 if (strcmp(var->name, "gl_FragDepth") == 0) {
1423 switch (var->depth_layout) {
1424 case ir_depth_layout_none:
1425 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
1426 return;
1427 case ir_depth_layout_any:
1428 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
1429 return;
1430 case ir_depth_layout_greater:
1431 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
1432 return;
1433 case ir_depth_layout_less:
1434 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
1435 return;
1436 case ir_depth_layout_unchanged:
1437 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
1438 return;
1439 default:
1440 assert(0);
1441 return;
1442 }
1443 }
1444 }
1445}
1446
1447/**
Ian Romanick92f81592011-11-08 12:37:19 -08001448 * Validate the resources used by a program versus the implementation limits
1449 */
1450static bool
1451check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
1452{
1453 static const char *const shader_names[MESA_SHADER_TYPES] = {
1454 "vertex", "fragment", "geometry"
1455 };
1456
1457 const unsigned max_samplers[MESA_SHADER_TYPES] = {
1458 ctx->Const.MaxVertexTextureImageUnits,
1459 ctx->Const.MaxTextureImageUnits,
1460 ctx->Const.MaxGeometryTextureImageUnits
1461 };
1462
1463 const unsigned max_uniform_components[MESA_SHADER_TYPES] = {
1464 ctx->Const.VertexProgram.MaxUniformComponents,
1465 ctx->Const.FragmentProgram.MaxUniformComponents,
1466 0 /* FINISHME: Geometry shaders. */
1467 };
1468
Eric Anholt877a8972012-06-25 12:47:01 -07001469 const unsigned max_uniform_blocks[MESA_SHADER_TYPES] = {
1470 ctx->Const.VertexProgram.MaxUniformBlocks,
1471 ctx->Const.FragmentProgram.MaxUniformBlocks,
1472 ctx->Const.GeometryProgram.MaxUniformBlocks,
1473 };
1474
Ian Romanick92f81592011-11-08 12:37:19 -08001475 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1476 struct gl_shader *sh = prog->_LinkedShaders[i];
1477
1478 if (sh == NULL)
1479 continue;
1480
1481 if (sh->num_samplers > max_samplers[i]) {
1482 linker_error(prog, "Too many %s shader texture samplers",
1483 shader_names[i]);
1484 }
1485
1486 if (sh->num_uniform_components > max_uniform_components[i]) {
Marek Olšákdf809ae2011-12-10 04:14:46 +01001487 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
1488 linker_warning(prog, "Too many %s shader uniform components, "
1489 "but the driver will try to optimize them out; "
1490 "this is non-portable out-of-spec behavior\n",
1491 shader_names[i]);
1492 } else {
1493 linker_error(prog, "Too many %s shader uniform components",
1494 shader_names[i]);
1495 }
Ian Romanick92f81592011-11-08 12:37:19 -08001496 }
1497 }
1498
Eric Anholt877a8972012-06-25 12:47:01 -07001499 unsigned blocks[MESA_SHADER_TYPES] = {0};
1500 unsigned total_uniform_blocks = 0;
1501
1502 for (unsigned i = 0; i < prog->NumUniformBlocks; i++) {
1503 for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
1504 if (prog->UniformBlockStageIndex[j][i] != -1) {
1505 blocks[j]++;
1506 total_uniform_blocks++;
1507 }
1508 }
1509
1510 if (total_uniform_blocks > ctx->Const.MaxCombinedUniformBlocks) {
1511 linker_error(prog, "Too many combined uniform blocks (%d/%d)",
1512 prog->NumUniformBlocks,
1513 ctx->Const.MaxCombinedUniformBlocks);
1514 } else {
1515 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1516 if (blocks[i] > max_uniform_blocks[i]) {
1517 linker_error(prog, "Too many %s uniform blocks (%d/%d)",
1518 shader_names[i],
1519 blocks[i],
1520 max_uniform_blocks[i]);
1521 break;
1522 }
1523 }
1524 }
1525 }
1526
Ian Romanick92f81592011-11-08 12:37:19 -08001527 return prog->LinkStatus;
1528}
Paul Berry871ddb92011-11-05 11:17:32 -07001529
Ian Romanick0e59b262010-06-23 11:23:01 -07001530void
Kristian Høgsbergf9995b32010-10-12 12:26:10 -04001531link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
Ian Romanick832dfa52010-06-17 15:04:20 -07001532{
Paul Berry871ddb92011-11-05 11:17:32 -07001533 tfeedback_decl *tfeedback_decls = NULL;
1534 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
1535
Kenneth Graunked3073f52011-01-21 14:32:31 -08001536 void *mem_ctx = ralloc_context(NULL); // temporary linker context
Kenneth Graunke2da02e72010-11-17 11:03:57 -08001537
Ian Romanick832dfa52010-06-17 15:04:20 -07001538 prog->LinkStatus = false;
1539 prog->Validated = false;
1540 prog->_Used = false;
1541
Eric Anholtf609cf72012-04-27 13:52:56 -07001542 ralloc_free(prog->InfoLog);
Kenneth Graunked3073f52011-01-21 14:32:31 -08001543 prog->InfoLog = ralloc_strdup(NULL, "");
Ian Romanickf36460e2010-06-23 12:07:22 -07001544
Eric Anholtf609cf72012-04-27 13:52:56 -07001545 ralloc_free(prog->UniformBlocks);
1546 prog->UniformBlocks = NULL;
1547 prog->NumUniformBlocks = 0;
1548 for (int i = 0; i < MESA_SHADER_TYPES; i++) {
1549 ralloc_free(prog->UniformBlockStageIndex[i]);
1550 prog->UniformBlockStageIndex[i] = NULL;
1551 }
1552
Ian Romanick832dfa52010-06-17 15:04:20 -07001553 /* Separate the shaders into groups based on their type.
1554 */
Eric Anholt16b68b12010-06-30 11:05:43 -07001555 struct gl_shader **vert_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -07001556 unsigned num_vert_shaders = 0;
Eric Anholt16b68b12010-06-30 11:05:43 -07001557 struct gl_shader **frag_shader_list;
Ian Romanick832dfa52010-06-17 15:04:20 -07001558 unsigned num_frag_shaders = 0;
1559
Eric Anholt16b68b12010-06-30 11:05:43 -07001560 vert_shader_list = (struct gl_shader **)
1561 calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
Ian Romanick832dfa52010-06-17 15:04:20 -07001562 frag_shader_list = &vert_shader_list[prog->NumShaders];
1563
Ian Romanick25f51d32010-07-16 15:51:50 -07001564 unsigned min_version = UINT_MAX;
1565 unsigned max_version = 0;
Paul Berrya9f34dc2012-08-02 17:49:44 -07001566 const bool is_es_prog =
1567 (prog->NumShaders > 0 && prog->Shaders[0]->IsES) ? true : false;
Ian Romanick832dfa52010-06-17 15:04:20 -07001568 for (unsigned i = 0; i < prog->NumShaders; i++) {
Ian Romanick25f51d32010-07-16 15:51:50 -07001569 min_version = MIN2(min_version, prog->Shaders[i]->Version);
1570 max_version = MAX2(max_version, prog->Shaders[i]->Version);
1571
Paul Berrya9f34dc2012-08-02 17:49:44 -07001572 if (prog->Shaders[i]->IsES != is_es_prog) {
1573 linker_error(prog, "all shaders must use same shading "
1574 "language version\n");
1575 goto done;
1576 }
1577
Ian Romanick832dfa52010-06-17 15:04:20 -07001578 switch (prog->Shaders[i]->Type) {
1579 case GL_VERTEX_SHADER:
1580 vert_shader_list[num_vert_shaders] = prog->Shaders[i];
1581 num_vert_shaders++;
1582 break;
1583 case GL_FRAGMENT_SHADER:
1584 frag_shader_list[num_frag_shaders] = prog->Shaders[i];
1585 num_frag_shaders++;
1586 break;
1587 case GL_GEOMETRY_SHADER:
1588 /* FINISHME: Support geometry shaders. */
1589 assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
1590 break;
1591 }
1592 }
1593
Ian Romanick25f51d32010-07-16 15:51:50 -07001594 /* Previous to GLSL version 1.30, different compilation units could mix and
1595 * match shading language versions. With GLSL 1.30 and later, the versions
1596 * of all shaders must match.
Paul Berrya9f34dc2012-08-02 17:49:44 -07001597 *
1598 * GLSL ES has never allowed mixing of shading language versions.
Ian Romanick25f51d32010-07-16 15:51:50 -07001599 */
Paul Berrya9f34dc2012-08-02 17:49:44 -07001600 if ((is_es_prog || max_version >= 130)
Kenneth Graunke5a81d052010-08-31 09:33:58 -07001601 && min_version != max_version) {
Ian Romanick586e7412011-07-28 14:04:09 -07001602 linker_error(prog, "all shaders must use same shading "
1603 "language version\n");
Ian Romanick25f51d32010-07-16 15:51:50 -07001604 goto done;
1605 }
1606
1607 prog->Version = max_version;
Paul Berry91c92bb2012-08-02 17:50:43 -07001608 prog->IsES = is_es_prog;
Ian Romanick25f51d32010-07-16 15:51:50 -07001609
Ian Romanick3322fba2010-10-14 13:28:42 -07001610 for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
1611 if (prog->_LinkedShaders[i] != NULL)
1612 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
1613
1614 prog->_LinkedShaders[i] = NULL;
Eric Anholt5d0f4302010-08-18 12:02:35 -07001615 }
1616
Ian Romanickcd6764e2010-07-16 16:00:07 -07001617 /* Link all shaders for a particular stage and validate the result.
1618 */
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001619 if (num_vert_shaders > 0) {
Ian Romanick3fb87872010-07-09 14:09:34 -07001620 gl_shader *const sh =
Kenneth Graunke2da02e72010-11-17 11:03:57 -08001621 link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
1622 num_vert_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07001623
1624 if (sh == NULL)
1625 goto done;
1626
1627 if (!validate_vertex_shader_executable(prog, sh))
Ian Romanickf29ff6e2010-10-14 17:55:17 -07001628 goto done;
Ian Romanick3fb87872010-07-09 14:09:34 -07001629
Ian Romanick3322fba2010-10-14 13:28:42 -07001630 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
1631 sh);
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001632 }
1633
1634 if (num_frag_shaders > 0) {
Ian Romanick3fb87872010-07-09 14:09:34 -07001635 gl_shader *const sh =
Kenneth Graunke2da02e72010-11-17 11:03:57 -08001636 link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
1637 num_frag_shaders);
Ian Romanick3fb87872010-07-09 14:09:34 -07001638
1639 if (sh == NULL)
1640 goto done;
1641
1642 if (!validate_fragment_shader_executable(prog, sh))
Ian Romanickf29ff6e2010-10-14 17:55:17 -07001643 goto done;
Ian Romanick3fb87872010-07-09 14:09:34 -07001644
Ian Romanick3322fba2010-10-14 13:28:42 -07001645 _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
1646 sh);
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001647 }
1648
Ian Romanick3ed850e2010-06-23 12:18:21 -07001649 /* Here begins the inter-stage linking phase. Some initial validation is
1650 * performed, then locations are assigned for uniforms, attributes, and
1651 * varyings.
1652 */
Ian Romanicked1fe3d2010-06-23 12:09:14 -07001653 if (cross_validate_uniforms(prog)) {
Ian Romanick3322fba2010-10-14 13:28:42 -07001654 unsigned prev;
1655
1656 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
1657 if (prog->_LinkedShaders[prev] != NULL)
1658 break;
1659 }
1660
Bryan Cainf18a0862011-04-23 19:29:15 -05001661 /* Validate the inputs of each stage with the output of the preceding
Ian Romanick37101922010-06-18 19:02:10 -07001662 * stage.
1663 */
Ian Romanick3322fba2010-10-14 13:28:42 -07001664 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
1665 if (prog->_LinkedShaders[i] == NULL)
1666 continue;
1667
Ian Romanickf36460e2010-06-23 12:07:22 -07001668 if (!cross_validate_outputs_to_inputs(prog,
Ian Romanick3322fba2010-10-14 13:28:42 -07001669 prog->_LinkedShaders[prev],
Ian Romanickabee16e2010-06-21 16:16:05 -07001670 prog->_LinkedShaders[i]))
Ian Romanick37101922010-06-18 19:02:10 -07001671 goto done;
Ian Romanick3322fba2010-10-14 13:28:42 -07001672
1673 prev = i;
Ian Romanick37101922010-06-18 19:02:10 -07001674 }
1675
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001676 prog->LinkStatus = true;
Ian Romanick37101922010-06-18 19:02:10 -07001677 }
Ian Romanick832dfa52010-06-17 15:04:20 -07001678
Eric Anholt3de13952012-05-04 13:08:46 -07001679 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
1680 * it before optimization because we want most of the checks to get
1681 * dropped thanks to constant propagation.
Paul Berry15ba2a52012-08-02 17:51:02 -07001682 *
1683 * This rule also applies to GLSL ES 3.00.
Eric Anholt3de13952012-05-04 13:08:46 -07001684 */
Paul Berry15ba2a52012-08-02 17:51:02 -07001685 if (max_version >= (is_es_prog ? 300 : 130)) {
Eric Anholt3de13952012-05-04 13:08:46 -07001686 struct gl_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
1687 if (sh) {
1688 lower_discard_flow(sh->ir);
1689 }
1690 }
1691
Eric Anholtf609cf72012-04-27 13:52:56 -07001692 if (!interstage_cross_validate_uniform_blocks(prog))
1693 goto done;
1694
Eric Anholt2f4fe152010-08-10 13:06:49 -07001695 /* Do common optimization before assigning storage for attributes,
1696 * uniforms, and varyings. Later optimization could possibly make
1697 * some of that unused.
1698 */
Ian Romanick3322fba2010-10-14 13:28:42 -07001699 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1700 if (prog->_LinkedShaders[i] == NULL)
1701 continue;
1702
Ian Romanick02c5ae12011-07-11 10:46:01 -07001703 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
1704 if (!prog->LinkStatus)
1705 goto done;
1706
Paul Berry18392442012-12-04 11:11:02 -08001707 if (ctx->ShaderCompilerOptions[i].LowerClipDistance) {
1708 lower_clip_distance(prog->_LinkedShaders[i]);
1709 }
Paul Berryc06e3252011-08-11 20:58:21 -07001710
Brian Paul7feabfe2012-03-20 17:43:12 -06001711 unsigned max_unroll = ctx->ShaderCompilerOptions[i].MaxUnrollIterations;
1712
1713 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false, max_unroll))
Eric Anholt2f4fe152010-08-10 13:06:49 -07001714 ;
Ian Romanicka7ba9a72010-07-20 13:36:32 -07001715 }
Ian Romanick13e10e42010-06-21 12:03:24 -07001716
Paul Berry50895d42012-12-05 07:17:07 -08001717 /* Mark all generic shader inputs and outputs as unpaired. */
1718 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
1719 link_invalidate_variable_locations(
1720 prog->_LinkedShaders[MESA_SHADER_VERTEX],
1721 VERT_ATTRIB_GENERIC0, VERT_RESULT_VAR0);
1722 }
1723 /* FINISHME: Geometry shaders not implemented yet */
1724 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
1725 link_invalidate_variable_locations(
1726 prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
1727 FRAG_ATTRIB_VAR0, FRAG_RESULT_DATA0);
1728 }
1729
Ian Romanickd32d4f72011-06-27 17:59:58 -07001730 /* FINISHME: The value of the max_attribute_index parameter is
1731 * FINISHME: implementation dependent based on the value of
1732 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
1733 * FINISHME: at least 16, so hardcode 16 for now.
1734 */
1735 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX, 16)) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07001736 goto done;
1737 }
1738
Dave Airlie1256a5d2012-03-24 13:33:41 +00001739 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, MAX2(ctx->Const.MaxDrawBuffers, ctx->Const.MaxDualSourceDrawBuffers))) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07001740 goto done;
Ian Romanick40e114b2010-08-17 14:55:50 -07001741 }
1742
Ian Romanick3322fba2010-10-14 13:28:42 -07001743 unsigned prev;
1744 for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
1745 if (prog->_LinkedShaders[prev] != NULL)
1746 break;
1747 }
1748
Paul Berry871ddb92011-11-05 11:17:32 -07001749 if (num_tfeedback_decls != 0) {
1750 /* From GL_EXT_transform_feedback:
1751 * A program will fail to link if:
1752 *
1753 * * the <count> specified by TransformFeedbackVaryingsEXT is
1754 * non-zero, but the program object has no vertex or geometry
1755 * shader;
1756 */
1757 if (prev >= MESA_SHADER_FRAGMENT) {
1758 linker_error(prog, "Transform feedback varyings specified, but "
1759 "no vertex or geometry shader is present.");
1760 goto done;
1761 }
1762
1763 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
1764 prog->TransformFeedback.NumVarying);
Paul Berry456279b2011-12-26 19:39:25 -08001765 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
Paul Berry871ddb92011-11-05 11:17:32 -07001766 prog->TransformFeedback.VaryingNames,
1767 tfeedback_decls))
1768 goto done;
1769 }
1770
Ian Romanick3322fba2010-10-14 13:28:42 -07001771 for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
1772 if (prog->_LinkedShaders[i] == NULL)
1773 continue;
1774
Paul Berry871ddb92011-11-05 11:17:32 -07001775 if (!assign_varying_locations(
Dave Airlie7d7a5492012-12-15 13:24:52 +10001776 ctx, mem_ctx, prog, prog->_LinkedShaders[prev], prog->_LinkedShaders[i],
Paul Berry871ddb92011-11-05 11:17:32 -07001777 i == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
1778 tfeedback_decls))
Ian Romanickde773242011-06-09 13:31:32 -07001779 goto done;
Ian Romanickde773242011-06-09 13:31:32 -07001780
Ian Romanick3322fba2010-10-14 13:28:42 -07001781 prev = i;
1782 }
Ian Romanick13e10e42010-06-21 12:03:24 -07001783
Paul Berry871ddb92011-11-05 11:17:32 -07001784 if (prev != MESA_SHADER_FRAGMENT && num_tfeedback_decls != 0) {
1785 /* There was no fragment shader, but we still have to assign varying
1786 * locations for use by transform feedback.
1787 */
1788 if (!assign_varying_locations(
Dave Airlie7d7a5492012-12-15 13:24:52 +10001789 ctx, mem_ctx, prog, prog->_LinkedShaders[prev], NULL, num_tfeedback_decls,
Paul Berry871ddb92011-11-05 11:17:32 -07001790 tfeedback_decls))
1791 goto done;
1792 }
1793
1794 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
1795 goto done;
1796
Ian Romanickcc90e622010-10-19 17:59:10 -07001797 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
1798 demote_shader_inputs_and_outputs(prog->_LinkedShaders[MESA_SHADER_VERTEX],
Paul Berry42a29d82013-01-11 14:39:32 -08001799 ir_var_shader_out);
Ian Romanick960d7222011-10-21 11:21:02 -07001800
1801 /* Eliminate code that is now dead due to unused vertex outputs being
1802 * demoted.
1803 */
1804 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_VERTEX]->ir, false))
1805 ;
Ian Romanickcc90e622010-10-19 17:59:10 -07001806 }
1807
1808 if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
1809 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
1810
Paul Berry42a29d82013-01-11 14:39:32 -08001811 demote_shader_inputs_and_outputs(sh, ir_var_shader_in);
1812 demote_shader_inputs_and_outputs(sh, ir_var_shader_out);
Ian Romanick960d7222011-10-21 11:21:02 -07001813
1814 /* Eliminate code that is now dead due to unused geometry outputs being
1815 * demoted.
1816 */
1817 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_GEOMETRY]->ir, false))
1818 ;
Ian Romanickcc90e622010-10-19 17:59:10 -07001819 }
1820
1821 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
1822 gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
1823
Paul Berry42a29d82013-01-11 14:39:32 -08001824 demote_shader_inputs_and_outputs(sh, ir_var_shader_in);
Ian Romanick960d7222011-10-21 11:21:02 -07001825
1826 /* Eliminate code that is now dead due to unused fragment inputs being
1827 * demoted. This shouldn't actually do anything other than remove
1828 * declarations of the (now unused) global variables.
1829 */
1830 while (do_dead_code(prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir, false))
1831 ;
Ian Romanickcc90e622010-10-19 17:59:10 -07001832 }
1833
Ian Romanick960d7222011-10-21 11:21:02 -07001834 update_array_sizes(prog);
Ian Romanick71990962011-10-18 16:01:49 -07001835 link_assign_uniform_locations(prog);
Marek Olšákec174a42011-11-18 15:00:10 +01001836 store_fragdepth_layout(prog);
Ian Romanick960d7222011-10-21 11:21:02 -07001837
Ian Romanick92f81592011-11-08 12:37:19 -08001838 if (!check_resources(ctx, prog))
1839 goto done;
1840
Ian Romanickce9171f2011-02-03 17:10:14 -08001841 /* OpenGL ES requires that a vertex shader and a fragment shader both be
Paul Berry15ba2a52012-08-02 17:51:02 -07001842 * present in a linked program. By checking prog->IsES, we also
1843 * catch the GL_ARB_ES2_compatibility case.
Ian Romanickce9171f2011-02-03 17:10:14 -08001844 */
Eric Anholt57f79782011-07-22 12:57:47 -07001845 if (!prog->InternalSeparateShader &&
Paul Berry15ba2a52012-08-02 17:51:02 -07001846 (ctx->API == API_OPENGLES2 || prog->IsES)) {
Ian Romanickce9171f2011-02-03 17:10:14 -08001847 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
Ian Romanick586e7412011-07-28 14:04:09 -07001848 linker_error(prog, "program lacks a vertex shader\n");
Ian Romanickce9171f2011-02-03 17:10:14 -08001849 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
Ian Romanick586e7412011-07-28 14:04:09 -07001850 linker_error(prog, "program lacks a fragment shader\n");
Ian Romanickce9171f2011-02-03 17:10:14 -08001851 }
1852 }
1853
Ian Romanick13e10e42010-06-21 12:03:24 -07001854 /* FINISHME: Assign fragment shader output locations. */
1855
Ian Romanick832dfa52010-06-17 15:04:20 -07001856done:
1857 free(vert_shader_list);
Kenneth Graunke2da02e72010-11-17 11:03:57 -08001858
1859 for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
1860 if (prog->_LinkedShaders[i] == NULL)
1861 continue;
1862
1863 /* Retain any live IR, but trash the rest. */
1864 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
Ian Romanick7bbcc0b2011-09-30 14:21:10 -07001865
1866 /* The symbol table in the linked shaders may contain references to
1867 * variables that were removed (e.g., unused uniforms). Since it may
1868 * contain junk, there is no possible valid use. Delete it and set the
1869 * pointer to NULL.
1870 */
1871 delete prog->_LinkedShaders[i]->symbols;
1872 prog->_LinkedShaders[i]->symbols = NULL;
Kenneth Graunke2da02e72010-11-17 11:03:57 -08001873 }
1874
Kenneth Graunked3073f52011-01-21 14:32:31 -08001875 ralloc_free(mem_ctx);
Ian Romanick832dfa52010-06-17 15:04:20 -07001876}