blob: 247c828d3d695a78d9f0de0daf0a293fd84f963b [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"
Eric Anholtfaf3dba2013-06-12 16:57:11 -070069#include "glsl_parser_extras.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070070#include "ir.h"
71#include "program.h"
Aras Pranckevicius31747152010-07-29 12:40:49 +030072#include "program/hash_table.h"
Ian Romanick8fe8a812010-07-13 17:36:13 -070073#include "linker.h"
Paul Berry4b11b572012-12-17 14:20:35 -080074#include "link_varyings.h"
Ian Romanicka7ba9a72010-07-20 13:36:32 -070075#include "ir_optimization.h"
Bryan Cain25480922013-02-15 09:46:50 -060076#include "ir_rvalue_visitor.h"
Tapani Pällieca9d162014-04-08 08:45:36 +030077#include "ir_uniform.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070078
Ian Romanick3322fba2010-10-14 13:28:42 -070079extern "C" {
80#include "main/shaderobj.h"
Eric Anholt6065a872013-06-12 18:12:40 -070081#include "main/enums.h"
Ian Romanick3322fba2010-10-14 13:28:42 -070082}
83
Bryan Cain25480922013-02-15 09:46:50 -060084void linker_error(gl_shader_program *, const char *, ...);
85
Eric Anholt10ef9492013-09-20 11:03:44 -070086namespace {
87
Ian Romanick832dfa52010-06-17 15:04:20 -070088/**
89 * Visitor that determines whether or not a variable is ever written.
90 */
91class find_assignment_visitor : public ir_hierarchical_visitor {
92public:
93 find_assignment_visitor(const char *name)
94 : name(name), found(false)
95 {
96 /* empty */
97 }
98
99 virtual ir_visitor_status visit_enter(ir_assignment *ir)
100 {
101 ir_variable *const var = ir->lhs->variable_referenced();
102
103 if (strcmp(name, var->name) == 0) {
104 found = true;
105 return visit_stop;
106 }
107
108 return visit_continue_with_parent;
109 }
110
Eric Anholt18a60232010-08-23 11:29:25 -0700111 virtual ir_visitor_status visit_enter(ir_call *ir)
112 {
Kenneth Graunke48d0faa2014-01-10 16:39:17 -0800113 foreach_two_lists(formal_node, &ir->callee->parameters,
114 actual_node, &ir->actual_parameters) {
115 ir_rvalue *param_rval = (ir_rvalue *) actual_node;
116 ir_variable *sig_param = (ir_variable *) formal_node;
Eric Anholt18a60232010-08-23 11:29:25 -0700117
Tapani Pälli33ee2c62013-12-12 13:51:01 +0200118 if (sig_param->data.mode == ir_var_function_out ||
119 sig_param->data.mode == ir_var_function_inout) {
Eric Anholt18a60232010-08-23 11:29:25 -0700120 ir_variable *var = param_rval->variable_referenced();
121 if (var && strcmp(name, var->name) == 0) {
122 found = true;
123 return visit_stop;
124 }
125 }
Eric Anholt18a60232010-08-23 11:29:25 -0700126 }
127
Kenneth Graunked884f602012-03-20 15:56:37 -0700128 if (ir->return_deref != NULL) {
129 ir_variable *const var = ir->return_deref->variable_referenced();
130
131 if (strcmp(name, var->name) == 0) {
132 found = true;
133 return visit_stop;
134 }
135 }
136
Eric Anholt18a60232010-08-23 11:29:25 -0700137 return visit_continue_with_parent;
138 }
139
Ian Romanick832dfa52010-06-17 15:04:20 -0700140 bool variable_found()
141 {
142 return found;
143 }
144
145private:
146 const char *name; /**< Find writes to a variable with this name. */
147 bool found; /**< Was a write to the variable found? */
148};
149
Ian Romanickc93b8f12010-06-17 15:20:22 -0700150
Ian Romanickc33e78f2010-08-13 12:30:41 -0700151/**
152 * Visitor that determines whether or not a variable is ever read.
153 */
154class find_deref_visitor : public ir_hierarchical_visitor {
155public:
156 find_deref_visitor(const char *name)
157 : name(name), found(false)
158 {
159 /* empty */
160 }
161
162 virtual ir_visitor_status visit(ir_dereference_variable *ir)
163 {
164 if (strcmp(this->name, ir->var->name) == 0) {
165 this->found = true;
166 return visit_stop;
167 }
168
169 return visit_continue;
170 }
171
172 bool variable_found() const
173 {
174 return this->found;
175 }
176
177private:
178 const char *name; /**< Find writes to a variable with this name. */
179 bool found; /**< Was a write to the variable found? */
180};
181
182
Paul Berry7cfefe62013-07-30 21:13:48 -0700183class geom_array_resize_visitor : public ir_hierarchical_visitor {
184public:
185 unsigned num_vertices;
186 gl_shader_program *prog;
187
188 geom_array_resize_visitor(unsigned num_vertices, gl_shader_program *prog)
189 {
190 this->num_vertices = num_vertices;
191 this->prog = prog;
192 }
193
194 virtual ~geom_array_resize_visitor()
195 {
196 /* empty */
197 }
198
199 virtual ir_visitor_status visit(ir_variable *var)
200 {
Tapani Pälli33ee2c62013-12-12 13:51:01 +0200201 if (!var->type->is_array() || var->data.mode != ir_var_shader_in)
Paul Berry7cfefe62013-07-30 21:13:48 -0700202 return visit_continue;
203
204 unsigned size = var->type->length;
205
206 /* Generate a link error if the shader has declared this array with an
207 * incorrect size.
208 */
209 if (size && size != this->num_vertices) {
210 linker_error(this->prog, "size of array %s declared as %u, "
211 "but number of input vertices is %u\n",
212 var->name, size, this->num_vertices);
213 return visit_continue;
214 }
215
216 /* Generate a link error if the shader attempts to access an input
217 * array using an index too large for its actual size assigned at link
218 * time.
219 */
Tapani Pälli447bb902013-12-12 15:08:59 +0200220 if (var->data.max_array_access >= this->num_vertices) {
Paul Berry7cfefe62013-07-30 21:13:48 -0700221 linker_error(this->prog, "geometry shader accesses element %i of "
222 "%s, but only %i input vertices\n",
Tapani Pälli447bb902013-12-12 15:08:59 +0200223 var->data.max_array_access, var->name, this->num_vertices);
Paul Berry7cfefe62013-07-30 21:13:48 -0700224 return visit_continue;
225 }
226
227 var->type = glsl_type::get_array_instance(var->type->element_type(),
228 this->num_vertices);
Tapani Pälli447bb902013-12-12 15:08:59 +0200229 var->data.max_array_access = this->num_vertices - 1;
Paul Berry7cfefe62013-07-30 21:13:48 -0700230
231 return visit_continue;
232 }
233
234 /* Dereferences of input variables need to be updated so that their type
235 * matches the newly assigned type of the variable they are accessing. */
236 virtual ir_visitor_status visit(ir_dereference_variable *ir)
237 {
238 ir->type = ir->var->type;
239 return visit_continue;
240 }
241
242 /* Dereferences of 2D input arrays need to be updated so that their type
243 * matches the newly assigned type of the array they are accessing. */
244 virtual ir_visitor_status visit_leave(ir_dereference_array *ir)
245 {
246 const glsl_type *const vt = ir->array->type;
247 if (vt->is_array())
248 ir->type = vt->element_type();
249 return visit_continue;
250 }
251};
252
253
Paul Berry1a33e022013-08-18 20:59:37 -0700254/**
255 * Visitor that determines whether or not a shader uses ir_end_primitive.
256 */
257class find_end_primitive_visitor : public ir_hierarchical_visitor {
258public:
259 find_end_primitive_visitor()
260 : found(false)
261 {
262 /* empty */
263 }
264
265 virtual ir_visitor_status visit(ir_end_primitive *)
266 {
267 found = true;
268 return visit_stop;
269 }
270
271 bool end_primitive_found()
272 {
273 return found;
274 }
275
276private:
277 bool found;
278};
279
Eric Anholt10ef9492013-09-20 11:03:44 -0700280} /* anonymous namespace */
Paul Berry1a33e022013-08-18 20:59:37 -0700281
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700282void
Ian Romanick586e7412011-07-28 14:04:09 -0700283linker_error(gl_shader_program *prog, const char *fmt, ...)
Ian Romanickf36460e2010-06-23 12:07:22 -0700284{
285 va_list ap;
286
Kenneth Graunked3073f52011-01-21 14:32:31 -0800287 ralloc_strcat(&prog->InfoLog, "error: ");
Ian Romanickf36460e2010-06-23 12:07:22 -0700288 va_start(ap, fmt);
Kenneth Graunked3073f52011-01-21 14:32:31 -0800289 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
Ian Romanickf36460e2010-06-23 12:07:22 -0700290 va_end(ap);
Ian Romanick586e7412011-07-28 14:04:09 -0700291
292 prog->LinkStatus = false;
Ian Romanickf36460e2010-06-23 12:07:22 -0700293}
294
295
296void
Ian Romanick379a32f2011-07-28 14:09:06 -0700297linker_warning(gl_shader_program *prog, const char *fmt, ...)
298{
299 va_list ap;
300
Anuj Phogat80b4a362014-03-07 16:48:35 -0800301 ralloc_strcat(&prog->InfoLog, "warning: ");
Ian Romanick379a32f2011-07-28 14:09:06 -0700302 va_start(ap, fmt);
303 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
304 va_end(ap);
305
306}
307
308
Paul Berryb92900d2013-01-28 14:21:59 -0800309/**
310 * Given a string identifying a program resource, break it into a base name
311 * and an optional array index in square brackets.
312 *
313 * If an array index is present, \c out_base_name_end is set to point to the
314 * "[" that precedes the array index, and the array index itself is returned
315 * as a long.
316 *
317 * If no array index is present (or if the array index is negative or
318 * mal-formed), \c out_base_name_end, is set to point to the null terminator
319 * at the end of the input string, and -1 is returned.
320 *
321 * Only the final array index is parsed; if the string contains other array
322 * indices (or structure field accesses), they are left in the base name.
323 *
324 * No attempt is made to check that the base name is properly formed;
325 * typically the caller will look up the base name in a hash table, so
326 * ill-formed base names simply turn into hash table lookup failures.
327 */
328long
329parse_program_resource_name(const GLchar *name,
330 const GLchar **out_base_name_end)
331{
332 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
333 *
334 * "When an integer array element or block instance number is part of
335 * the name string, it will be specified in decimal form without a "+"
336 * or "-" sign or any extra leading zeroes. Additionally, the name
337 * string will not include white space anywhere in the string."
338 */
339
340 const size_t len = strlen(name);
341 *out_base_name_end = name + len;
342
343 if (len == 0 || name[len-1] != ']')
344 return -1;
345
346 /* Walk backwards over the string looking for a non-digit character. This
347 * had better be the opening bracket for an array index.
348 *
349 * Initially, i specifies the location of the ']'. Since the string may
350 * contain only the ']' charcater, walk backwards very carefully.
351 */
352 unsigned i;
353 for (i = len - 1; (i > 0) && isdigit(name[i-1]); --i)
354 /* empty */ ;
355
356 if ((i == 0) || name[i-1] != '[')
357 return -1;
358
359 long array_index = strtol(&name[i], NULL, 10);
360 if (array_index < 0)
361 return -1;
362
363 *out_base_name_end = name + (i - 1);
364 return array_index;
365}
366
367
Ian Romanick379a32f2011-07-28 14:09:06 -0700368void
Ian Romanick63974c02013-10-04 10:46:29 -0700369link_invalidate_variable_locations(exec_list *ir)
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700370{
Ian Romanickcf8b14c2013-10-22 15:07:00 -0700371 foreach_list(node, ir) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700372 ir_variable *const var = ((ir_instruction *) node)->as_variable();
373
Paul Berry50895d42012-12-05 07:17:07 -0800374 if (var == NULL)
375 continue;
376
Ian Romanick63974c02013-10-04 10:46:29 -0700377 /* Only assign locations for variables that lack an explicit location.
378 * Explicit locations are set for all built-in variables, generic vertex
379 * shader inputs (via layout(location=...)), and generic fragment shader
380 * outputs (also via layout(location=...)).
381 */
Tapani Pälli447bb902013-12-12 15:08:59 +0200382 if (!var->data.explicit_location) {
383 var->data.location = -1;
384 var->data.location_frac = 0;
Paul Berry50895d42012-12-05 07:17:07 -0800385 }
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700386
Ian Romanick63974c02013-10-04 10:46:29 -0700387 /* ir_variable::is_unmatched_generic_inout is used by the linker while
388 * connecting outputs from one stage to inputs of the next stage.
389 *
390 * There are two implicit assumptions here. First, we assume that any
391 * built-in variable (i.e., non-generic in or out) will have
392 * explicit_location set. Second, we assume that any generic in or out
393 * will not have explicit_location set.
394 *
395 * This second assumption will only be valid until
396 * GL_ARB_separate_shader_objects is supported. When that extension is
397 * implemented, this function will need some modifications.
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700398 */
Tapani Pälli447bb902013-12-12 15:08:59 +0200399 if (!var->data.explicit_location) {
400 var->data.is_unmatched_generic_inout = 1;
Paul Berry3e81c662012-12-05 10:47:55 -0800401 } else {
Tapani Pälli447bb902013-12-12 15:08:59 +0200402 var->data.is_unmatched_generic_inout = 0;
Paul Berry3e81c662012-12-05 10:47:55 -0800403 }
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700404 }
405}
406
407
Ian Romanickc93b8f12010-06-17 15:20:22 -0700408/**
Paul Berry44e07de2013-06-11 14:11:05 -0700409 * Set UsesClipDistance and ClipDistanceArraySize based on the given shader.
410 *
411 * Also check for errors based on incorrect usage of gl_ClipVertex and
412 * gl_ClipDistance.
413 *
414 * Return false if an error was reported.
415 */
416static void
Paul Berryb30e25f2013-12-17 09:49:43 -0800417analyze_clip_usage(struct gl_shader_program *prog,
Paul Berry44e07de2013-06-11 14:11:05 -0700418 struct gl_shader *shader, GLboolean *UsesClipDistance,
419 GLuint *ClipDistanceArraySize)
420{
421 *ClipDistanceArraySize = 0;
422
423 if (!prog->IsES && prog->Version >= 130) {
424 /* From section 7.1 (Vertex Shader Special Variables) of the
425 * GLSL 1.30 spec:
426 *
427 * "It is an error for a shader to statically write both
428 * gl_ClipVertex and gl_ClipDistance."
429 *
430 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
431 * gl_ClipVertex nor gl_ClipDistance.
432 */
433 find_assignment_visitor clip_vertex("gl_ClipVertex");
434 find_assignment_visitor clip_distance("gl_ClipDistance");
435
436 clip_vertex.run(shader->ir);
437 clip_distance.run(shader->ir);
438 if (clip_vertex.variable_found() && clip_distance.variable_found()) {
439 linker_error(prog, "%s shader writes to both `gl_ClipVertex' "
Paul Berryb30e25f2013-12-17 09:49:43 -0800440 "and `gl_ClipDistance'\n",
Paul Berrye3b86f02014-01-07 10:58:56 -0800441 _mesa_shader_stage_to_string(shader->Stage));
Paul Berry44e07de2013-06-11 14:11:05 -0700442 return;
443 }
444 *UsesClipDistance = clip_distance.variable_found();
445 ir_variable *clip_distance_var =
446 shader->symbols->get_variable("gl_ClipDistance");
447 if (clip_distance_var)
448 *ClipDistanceArraySize = clip_distance_var->type->length;
449 } else {
450 *UsesClipDistance = false;
451 }
452}
453
454
455/**
Paul Berry1ad54ae2011-09-17 09:42:02 -0700456 * Verify that a vertex shader executable meets all semantic requirements.
457 *
Paul Berry642e5b412012-01-04 13:57:52 -0800458 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
459 * as a side effect.
Ian Romanickc93b8f12010-06-17 15:20:22 -0700460 *
461 * \param shader Vertex shader executable to be verified
462 */
Paul Berryb95d2372013-07-27 11:08:31 -0700463void
Eric Anholt849e1812010-06-30 11:49:17 -0700464validate_vertex_shader_executable(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700465 struct gl_shader *shader)
Ian Romanick832dfa52010-06-17 15:04:20 -0700466{
467 if (shader == NULL)
Paul Berryb95d2372013-07-27 11:08:31 -0700468 return;
Ian Romanick832dfa52010-06-17 15:04:20 -0700469
Eric Anholtf1c1c9e2012-03-19 22:43:27 -0700470 /* From the GLSL 1.10 spec, page 48:
471 *
472 * "The variable gl_Position is available only in the vertex
473 * language and is intended for writing the homogeneous vertex
474 * position. All executions of a well-formed vertex shader
475 * executable must write a value into this variable. [...] The
476 * variable gl_Position is available only in the vertex
477 * language and is intended for writing the homogeneous vertex
478 * position. All executions of a well-formed vertex shader
479 * executable must write a value into this variable."
480 *
481 * while in GLSL 1.40 this text is changed to:
482 *
483 * "The variable gl_Position is available only in the vertex
484 * language and is intended for writing the homogeneous vertex
485 * position. It can be written at any time during shader
486 * execution. It may also be read back by a vertex shader
487 * after being written. This value will be used by primitive
488 * assembly, clipping, culling, and other fixed functionality
489 * operations, if present, that operate on primitives after
490 * vertex processing has occurred. Its value is undefined if
491 * the vertex shader executable does not write gl_Position."
Paul Berry15ba2a52012-08-02 17:51:02 -0700492 *
493 * GLSL ES 3.00 is similar to GLSL 1.40--failing to write to gl_Position is
494 * not an error.
Eric Anholtf1c1c9e2012-03-19 22:43:27 -0700495 */
Paul Berry15ba2a52012-08-02 17:51:02 -0700496 if (prog->Version < (prog->IsES ? 300 : 140)) {
Eric Anholtf1c1c9e2012-03-19 22:43:27 -0700497 find_assignment_visitor find("gl_Position");
498 find.run(shader->ir);
499 if (!find.variable_found()) {
500 linker_error(prog, "vertex shader does not write to `gl_Position'\n");
Paul Berryb95d2372013-07-27 11:08:31 -0700501 return;
Eric Anholtf1c1c9e2012-03-19 22:43:27 -0700502 }
Ian Romanick832dfa52010-06-17 15:04:20 -0700503 }
504
Paul Berryb30e25f2013-12-17 09:49:43 -0800505 analyze_clip_usage(prog, shader, &prog->Vert.UsesClipDistance,
Paul Berry44e07de2013-06-11 14:11:05 -0700506 &prog->Vert.ClipDistanceArraySize);
Ian Romanick832dfa52010-06-17 15:04:20 -0700507}
508
509
Ian Romanickc93b8f12010-06-17 15:20:22 -0700510/**
511 * Verify that a fragment shader executable meets all semantic requirements
512 *
513 * \param shader Fragment shader executable to be verified
514 */
Paul Berryb95d2372013-07-27 11:08:31 -0700515void
Eric Anholt849e1812010-06-30 11:49:17 -0700516validate_fragment_shader_executable(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700517 struct gl_shader *shader)
Ian Romanick832dfa52010-06-17 15:04:20 -0700518{
519 if (shader == NULL)
Paul Berryb95d2372013-07-27 11:08:31 -0700520 return;
Ian Romanick832dfa52010-06-17 15:04:20 -0700521
Ian Romanick832dfa52010-06-17 15:04:20 -0700522 find_assignment_visitor frag_color("gl_FragColor");
523 find_assignment_visitor frag_data("gl_FragData");
524
Eric Anholt16b68b12010-06-30 11:05:43 -0700525 frag_color.run(shader->ir);
526 frag_data.run(shader->ir);
Ian Romanick832dfa52010-06-17 15:04:20 -0700527
Ian Romanick832dfa52010-06-17 15:04:20 -0700528 if (frag_color.variable_found() && frag_data.variable_found()) {
Ian Romanick586e7412011-07-28 14:04:09 -0700529 linker_error(prog, "fragment shader writes to both "
530 "`gl_FragColor' and `gl_FragData'\n");
Ian Romanick832dfa52010-06-17 15:04:20 -0700531 }
Ian Romanick832dfa52010-06-17 15:04:20 -0700532}
533
Bryan Cain25480922013-02-15 09:46:50 -0600534/**
535 * Verify that a geometry shader executable meets all semantic requirements
536 *
Paul Berry44e07de2013-06-11 14:11:05 -0700537 * Also sets prog->Geom.VerticesIn, prog->Geom.UsesClipDistance, and
538 * prog->Geom.ClipDistanceArraySize as a side effect.
Bryan Cain25480922013-02-15 09:46:50 -0600539 *
540 * \param shader Geometry shader executable to be verified
541 */
542void
543validate_geometry_shader_executable(struct gl_shader_program *prog,
544 struct gl_shader *shader)
545{
546 if (shader == NULL)
547 return;
548
549 unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
550 prog->Geom.VerticesIn = num_vertices;
Paul Berry44e07de2013-06-11 14:11:05 -0700551
Paul Berryb30e25f2013-12-17 09:49:43 -0800552 analyze_clip_usage(prog, shader, &prog->Geom.UsesClipDistance,
Paul Berry44e07de2013-06-11 14:11:05 -0700553 &prog->Geom.ClipDistanceArraySize);
Paul Berry1a33e022013-08-18 20:59:37 -0700554
555 find_end_primitive_visitor end_primitive;
556 end_primitive.run(shader->ir);
557 prog->Geom.UsesEndPrimitive = end_primitive.end_primitive_found();
Bryan Cain25480922013-02-15 09:46:50 -0600558}
559
Ian Romanick832dfa52010-06-17 15:04:20 -0700560
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700561/**
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700562 * Perform validation of global variables used across multiple shaders
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700563 */
Paul Berryb95d2372013-07-27 11:08:31 -0700564void
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700565cross_validate_globals(struct gl_shader_program *prog,
566 struct gl_shader **shader_list,
567 unsigned num_shaders,
568 bool uniforms_only)
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700569{
570 /* Examine all of the uniforms in all of the shaders and cross validate
571 * them.
572 */
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700573 glsl_symbol_table variables;
574 for (unsigned i = 0; i < num_shaders; i++) {
Ian Romanick3322fba2010-10-14 13:28:42 -0700575 if (shader_list[i] == NULL)
576 continue;
577
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700578 foreach_list(node, shader_list[i]->ir) {
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700579 ir_variable *const var = ((ir_instruction *) node)->as_variable();
580
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700581 if (var == NULL)
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700582 continue;
583
Tapani Pälli33ee2c62013-12-12 13:51:01 +0200584 if (uniforms_only && (var->data.mode != ir_var_uniform))
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700585 continue;
586
Ian Romanick7e2aa912010-07-19 17:12:42 -0700587 /* Don't cross validate temporaries that are at global scope. These
588 * will eventually get pulled into the shaders 'main'.
589 */
Tapani Pälli33ee2c62013-12-12 13:51:01 +0200590 if (var->data.mode == ir_var_temporary)
Ian Romanick7e2aa912010-07-19 17:12:42 -0700591 continue;
592
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700593 /* If a global with this name has already been seen, verify that the
594 * new instance has the same type. In addition, if the globals have
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700595 * initializers, the values of the initializers must be the same.
596 */
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700597 ir_variable *const existing = variables.get_variable(var->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700598 if (existing != NULL) {
599 if (var->type != existing->type) {
Ian Romanicka2711d62010-08-29 22:07:49 -0700600 /* Consider the types to be "the same" if both types are arrays
601 * of the same type and one of the arrays is implicitly sized.
602 * In addition, set the type of the linked variable to the
603 * explicitly sized array.
604 */
605 if (var->type->is_array()
606 && existing->type->is_array()
607 && (var->type->fields.array == existing->type->fields.array)
608 && ((var->type->length == 0)
609 || (existing->type->length == 0))) {
Ian Romanick0f4b2a02011-01-25 12:06:18 -0800610 if (var->type->length != 0) {
Ian Romanicka2711d62010-08-29 22:07:49 -0700611 existing->type = var->type;
Ian Romanick6f539212010-12-07 18:30:33 -0800612 }
Grigori Goronzy955c93d2013-11-27 00:15:06 +0100613 } else if (var->type->is_record()
614 && existing->type->is_record()
615 && existing->type->record_compare(var->type)) {
616 existing->type = var->type;
Ian Romanicka2711d62010-08-29 22:07:49 -0700617 } else {
Ian Romanick586e7412011-07-28 14:04:09 -0700618 linker_error(prog, "%s `%s' declared as type "
619 "`%s' and type `%s'\n",
620 mode_string(var),
621 var->name, var->type->name,
622 existing->type->name);
Paul Berryb95d2372013-07-27 11:08:31 -0700623 return;
Ian Romanicka2711d62010-08-29 22:07:49 -0700624 }
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700625 }
626
Tapani Pälli447bb902013-12-12 15:08:59 +0200627 if (var->data.explicit_location) {
628 if (existing->data.explicit_location
629 && (var->data.location != existing->data.location)) {
Ian Romanick586e7412011-07-28 14:04:09 -0700630 linker_error(prog, "explicit locations for %s "
631 "`%s' have differing values\n",
632 mode_string(var), var->name);
Paul Berryb95d2372013-07-27 11:08:31 -0700633 return;
Ian Romanick68a4fc92010-10-07 17:21:22 -0700634 }
635
Tapani Pälli447bb902013-12-12 15:08:59 +0200636 existing->data.location = var->data.location;
637 existing->data.explicit_location = true;
Ian Romanick68a4fc92010-10-07 17:21:22 -0700638 }
639
Kenneth Graunke9a9a8302013-07-16 12:18:57 -0700640 /* From the GLSL 4.20 specification:
641 * "A link error will result if two compilation units in a program
642 * specify different integer-constant bindings for the same
643 * opaque-uniform name. However, it is not an error to specify a
644 * binding on some but not all declarations for the same name"
645 */
Tapani Pälli447bb902013-12-12 15:08:59 +0200646 if (var->data.explicit_binding) {
647 if (existing->data.explicit_binding &&
648 var->data.binding != existing->data.binding) {
Kenneth Graunke9a9a8302013-07-16 12:18:57 -0700649 linker_error(prog, "explicit bindings for %s "
650 "`%s' have differing values\n",
651 mode_string(var), var->name);
Paul Berryb95d2372013-07-27 11:08:31 -0700652 return;
Kenneth Graunke9a9a8302013-07-16 12:18:57 -0700653 }
654
Tapani Pälli447bb902013-12-12 15:08:59 +0200655 existing->data.binding = var->data.binding;
656 existing->data.explicit_binding = true;
Kenneth Graunke9a9a8302013-07-16 12:18:57 -0700657 }
658
Francisco Jerez5c114932013-09-11 12:14:46 -0700659 if (var->type->contains_atomic() &&
Tapani Pälli447bb902013-12-12 15:08:59 +0200660 var->data.atomic.offset != existing->data.atomic.offset) {
Francisco Jerez5c114932013-09-11 12:14:46 -0700661 linker_error(prog, "offset specifications for %s "
662 "`%s' have differing values\n",
663 mode_string(var), var->name);
664 return;
665 }
666
Ian Romanick46173f92011-10-31 13:07:06 -0700667 /* Validate layout qualifiers for gl_FragDepth.
668 *
669 * From the AMD/ARB_conservative_depth specs:
670 *
671 * "If gl_FragDepth is redeclared in any fragment shader in a
672 * program, it must be redeclared in all fragment shaders in
673 * that program that have static assignments to
674 * gl_FragDepth. All redeclarations of gl_FragDepth in all
675 * fragment shaders in a single program must have the same set
676 * of qualifiers."
677 */
678 if (strcmp(var->name, "gl_FragDepth") == 0) {
Tapani Pälli447bb902013-12-12 15:08:59 +0200679 bool layout_declared = var->data.depth_layout != ir_depth_layout_none;
Ian Romanick46173f92011-10-31 13:07:06 -0700680 bool layout_differs =
Tapani Pälli447bb902013-12-12 15:08:59 +0200681 var->data.depth_layout != existing->data.depth_layout;
Ian Romanick46173f92011-10-31 13:07:06 -0700682
683 if (layout_declared && layout_differs) {
684 linker_error(prog,
685 "All redeclarations of gl_FragDepth in all "
686 "fragment shaders in a single program must have "
687 "the same set of qualifiers.");
688 }
689
Tapani Pälli33ee2c62013-12-12 13:51:01 +0200690 if (var->data.used && layout_differs) {
Ian Romanick46173f92011-10-31 13:07:06 -0700691 linker_error(prog,
692 "If gl_FragDepth is redeclared with a layout "
693 "qualifier in any fragment shader, it must be "
694 "redeclared with the same layout qualifier in "
695 "all fragment shaders that have assignments to "
696 "gl_FragDepth");
697 }
698 }
Chad Versaceaddae332011-01-27 01:40:31 -0800699
Ian Romanickf37b1ad2011-10-31 14:31:07 -0700700 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
701 *
702 * "If a shared global has multiple initializers, the
703 * initializers must all be constant expressions, and they
704 * must all have the same value. Otherwise, a link error will
705 * result. (A shared global having only one initializer does
706 * not require that initializer to be a constant expression.)"
707 *
708 * Previous to 4.20 the GLSL spec simply said that initializers
709 * must have the same value. In this case of non-constant
710 * initializers, this was impossible to determine. As a result,
711 * no vendor actually implemented that behavior. The 4.20
712 * behavior matches the implemented behavior of at least one other
713 * vendor, so we'll implement that for all GLSL versions.
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700714 */
Ian Romanickf37b1ad2011-10-31 14:31:07 -0700715 if (var->constant_initializer != NULL) {
716 if (existing->constant_initializer != NULL) {
717 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
Ian Romanick586e7412011-07-28 14:04:09 -0700718 linker_error(prog, "initializers for %s "
719 "`%s' have differing values\n",
720 mode_string(var), var->name);
Paul Berryb95d2372013-07-27 11:08:31 -0700721 return;
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700722 }
Ian Romanickf37b1ad2011-10-31 14:31:07 -0700723 } else {
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700724 /* If the first-seen instance of a particular uniform did not
725 * have an initializer but a later instance does, copy the
726 * initializer to the version stored in the symbol table.
727 */
Ian Romanickde415b72010-07-14 13:22:12 -0700728 /* FINISHME: This is wrong. The constant_value field should
729 * FINISHME: not be modified! Imagine a case where a shader
730 * FINISHME: without an initializer is linked in two different
731 * FINISHME: programs with shaders that have differing
732 * FINISHME: initializers. Linking with the first will
733 * FINISHME: modify the shader, and linking with the second
734 * FINISHME: will fail.
735 */
Ian Romanickf37b1ad2011-10-31 14:31:07 -0700736 existing->constant_initializer =
737 var->constant_initializer->clone(ralloc_parent(existing),
738 NULL);
739 }
740 }
741
Tapani Pälli447bb902013-12-12 15:08:59 +0200742 if (var->data.has_initializer) {
743 if (existing->data.has_initializer
Ian Romanickf37b1ad2011-10-31 14:31:07 -0700744 && (var->constant_initializer == NULL
745 || existing->constant_initializer == NULL)) {
746 linker_error(prog,
747 "shared global variable `%s' has multiple "
748 "non-constant initializers.\n",
749 var->name);
Paul Berryb95d2372013-07-27 11:08:31 -0700750 return;
Ian Romanickf37b1ad2011-10-31 14:31:07 -0700751 }
752
753 /* Some instance had an initializer, so keep track of that. In
754 * this location, all sorts of initializers (constant or
755 * otherwise) will propagate the existence to the variable
756 * stored in the symbol table.
757 */
Tapani Pälli447bb902013-12-12 15:08:59 +0200758 existing->data.has_initializer = true;
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700759 }
Chad Versace7528f142010-11-17 14:34:38 -0800760
Tapani Pällic1d30802013-12-12 12:57:57 +0200761 if (existing->data.invariant != var->data.invariant) {
Ian Romanick586e7412011-07-28 14:04:09 -0700762 linker_error(prog, "declarations for %s `%s' have "
763 "mismatching invariant qualifiers\n",
764 mode_string(var), var->name);
Paul Berryb95d2372013-07-27 11:08:31 -0700765 return;
Chad Versace7528f142010-11-17 14:34:38 -0800766 }
Tapani Pällic1d30802013-12-12 12:57:57 +0200767 if (existing->data.centroid != var->data.centroid) {
Ian Romanick586e7412011-07-28 14:04:09 -0700768 linker_error(prog, "declarations for %s `%s' have "
769 "mismatching centroid qualifiers\n",
770 mode_string(var), var->name);
Paul Berryb95d2372013-07-27 11:08:31 -0700771 return;
Chad Versace61428dd2011-01-10 15:29:30 -0800772 }
Tapani Pällic1d30802013-12-12 12:57:57 +0200773 if (existing->data.sample != var->data.sample) {
Chris Forbes51c5fc82013-11-29 21:26:10 +1300774 linker_error(prog, "declarations for %s `%s` have "
775 "mismatching sample qualifiers\n",
776 mode_string(var), var->name);
777 return;
778 }
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700779 } else
Eric Anholt001eee52010-11-05 06:11:24 -0700780 variables.add_variable(var);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700781 }
782 }
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700783}
784
785
Ian Romanick37101922010-06-18 19:02:10 -0700786/**
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700787 * Perform validation of uniforms used across multiple shader stages
788 */
Paul Berryb95d2372013-07-27 11:08:31 -0700789void
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700790cross_validate_uniforms(struct gl_shader_program *prog)
791{
Paul Berryb95d2372013-07-27 11:08:31 -0700792 cross_validate_globals(prog, prog->_LinkedShaders,
Paul Berry665b8d72014-01-07 10:11:39 -0800793 MESA_SHADER_STAGES, true);
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700794}
795
Eric Anholtf609cf72012-04-27 13:52:56 -0700796/**
797 * Accumulates the array of prog->UniformBlocks and checks that all
798 * definitons of blocks agree on their contents.
799 */
800static bool
801interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog)
802{
803 unsigned max_num_uniform_blocks = 0;
Paul Berry665b8d72014-01-07 10:11:39 -0800804 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
Eric Anholtf609cf72012-04-27 13:52:56 -0700805 if (prog->_LinkedShaders[i])
806 max_num_uniform_blocks += prog->_LinkedShaders[i]->NumUniformBlocks;
807 }
808
Paul Berry665b8d72014-01-07 10:11:39 -0800809 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
Eric Anholtf609cf72012-04-27 13:52:56 -0700810 struct gl_shader *sh = prog->_LinkedShaders[i];
811
812 prog->UniformBlockStageIndex[i] = ralloc_array(prog, int,
813 max_num_uniform_blocks);
814 for (unsigned int j = 0; j < max_num_uniform_blocks; j++)
815 prog->UniformBlockStageIndex[i][j] = -1;
816
817 if (sh == NULL)
818 continue;
819
820 for (unsigned int j = 0; j < sh->NumUniformBlocks; j++) {
821 int index = link_cross_validate_uniform_block(prog,
822 &prog->UniformBlocks,
823 &prog->NumUniformBlocks,
824 &sh->UniformBlocks[j]);
825
826 if (index == -1) {
827 linker_error(prog, "uniform block `%s' has mismatching definitions",
828 sh->UniformBlocks[j].Name);
829 return false;
830 }
831
832 prog->UniformBlockStageIndex[i][index] = j;
833 }
834 }
835
836 return true;
837}
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700838
Ian Romanick37101922010-06-18 19:02:10 -0700839
Ian Romanick3fb87872010-07-09 14:09:34 -0700840/**
841 * Populates a shaders symbol table with all global declarations
842 */
843static void
844populate_symbol_table(gl_shader *sh)
845{
846 sh->symbols = new(sh) glsl_symbol_table;
847
848 foreach_list(node, sh->ir) {
849 ir_instruction *const inst = (ir_instruction *) node;
850 ir_variable *var;
851 ir_function *func;
852
853 if ((func = inst->as_function()) != NULL) {
Eric Anholte8f5ebf2010-11-05 06:08:45 -0700854 sh->symbols->add_function(func);
Ian Romanick3fb87872010-07-09 14:09:34 -0700855 } else if ((var = inst->as_variable()) != NULL) {
Eric Anholt001eee52010-11-05 06:11:24 -0700856 sh->symbols->add_variable(var);
Ian Romanick3fb87872010-07-09 14:09:34 -0700857 }
858 }
859}
860
861
862/**
Ian Romanick31a97862010-07-12 18:48:50 -0700863 * Remap variables referenced in an instruction tree
864 *
865 * This is used when instruction trees are cloned from one shader and placed in
866 * another. These trees will contain references to \c ir_variable nodes that
867 * do not exist in the target shader. This function finds these \c ir_variable
868 * references and replaces the references with matching variables in the target
869 * shader.
870 *
871 * If there is no matching variable in the target shader, a clone of the
872 * \c ir_variable is made and added to the target shader. The new variable is
873 * added to \b both the instruction stream and the symbol table.
874 *
875 * \param inst IR tree that is to be processed.
876 * \param symbols Symbol table containing global scope symbols in the
877 * linked shader.
878 * \param instructions Instruction stream where new variable declarations
879 * should be added.
880 */
881void
Eric Anholt8273bd42010-08-04 12:34:56 -0700882remap_variables(ir_instruction *inst, struct gl_shader *target,
883 hash_table *temps)
Ian Romanick31a97862010-07-12 18:48:50 -0700884{
885 class remap_visitor : public ir_hierarchical_visitor {
886 public:
Eric Anholt8273bd42010-08-04 12:34:56 -0700887 remap_visitor(struct gl_shader *target,
Ian Romanick7e2aa912010-07-19 17:12:42 -0700888 hash_table *temps)
Ian Romanick31a97862010-07-12 18:48:50 -0700889 {
Eric Anholt8273bd42010-08-04 12:34:56 -0700890 this->target = target;
891 this->symbols = target->symbols;
892 this->instructions = target->ir;
Ian Romanick7e2aa912010-07-19 17:12:42 -0700893 this->temps = temps;
Ian Romanick31a97862010-07-12 18:48:50 -0700894 }
895
896 virtual ir_visitor_status visit(ir_dereference_variable *ir)
897 {
Tapani Pälli33ee2c62013-12-12 13:51:01 +0200898 if (ir->var->data.mode == ir_var_temporary) {
Ian Romanick7e2aa912010-07-19 17:12:42 -0700899 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
900
901 assert(var != NULL);
902 ir->var = var;
903 return visit_continue;
904 }
905
Ian Romanick31a97862010-07-12 18:48:50 -0700906 ir_variable *const existing =
907 this->symbols->get_variable(ir->var->name);
908 if (existing != NULL)
909 ir->var = existing;
910 else {
Eric Anholt8273bd42010-08-04 12:34:56 -0700911 ir_variable *copy = ir->var->clone(this->target, NULL);
Ian Romanick31a97862010-07-12 18:48:50 -0700912
Eric Anholt001eee52010-11-05 06:11:24 -0700913 this->symbols->add_variable(copy);
Ian Romanick31a97862010-07-12 18:48:50 -0700914 this->instructions->push_head(copy);
Ian Romanick7e2aa912010-07-19 17:12:42 -0700915 ir->var = copy;
Ian Romanick31a97862010-07-12 18:48:50 -0700916 }
917
918 return visit_continue;
919 }
920
921 private:
Eric Anholt8273bd42010-08-04 12:34:56 -0700922 struct gl_shader *target;
Ian Romanick31a97862010-07-12 18:48:50 -0700923 glsl_symbol_table *symbols;
924 exec_list *instructions;
Ian Romanick7e2aa912010-07-19 17:12:42 -0700925 hash_table *temps;
Ian Romanick31a97862010-07-12 18:48:50 -0700926 };
927
Eric Anholt8273bd42010-08-04 12:34:56 -0700928 remap_visitor v(target, temps);
Ian Romanick31a97862010-07-12 18:48:50 -0700929
930 inst->accept(&v);
931}
932
933
934/**
935 * Move non-declarations from one instruction stream to another
936 *
937 * The intended usage pattern of this function is to pass the pointer to the
Eric Anholt62c47632010-07-29 13:52:25 -0700938 * 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 -0700939 * pointer) for \c last and \c false for \c make_copies on the first
940 * call. Successive calls pass the return value of the previous call for
941 * \c last and \c true for \c make_copies.
942 *
943 * \param instructions Source instruction stream
944 * \param last Instruction after which new instructions should be
945 * inserted in the target instruction stream
946 * \param make_copies Flag selecting whether instructions in \c instructions
947 * should be copied (via \c ir_instruction::clone) into the
948 * target list or moved.
949 *
950 * \return
951 * The new "last" instruction in the target instruction stream. This pointer
952 * is suitable for use as the \c last parameter of a later call to this
953 * function.
954 */
955exec_node *
956move_non_declarations(exec_list *instructions, exec_node *last,
957 bool make_copies, gl_shader *target)
958{
Ian Romanick7e2aa912010-07-19 17:12:42 -0700959 hash_table *temps = NULL;
960
961 if (make_copies)
962 temps = hash_table_ctor(0, hash_table_pointer_hash,
963 hash_table_pointer_compare);
964
Ian Romanick303c99f2010-07-19 12:34:56 -0700965 foreach_list_safe(node, instructions) {
Ian Romanick31a97862010-07-12 18:48:50 -0700966 ir_instruction *inst = (ir_instruction *) node;
967
Ian Romanick7e2aa912010-07-19 17:12:42 -0700968 if (inst->as_function())
Ian Romanick31a97862010-07-12 18:48:50 -0700969 continue;
970
Ian Romanick7e2aa912010-07-19 17:12:42 -0700971 ir_variable *var = inst->as_variable();
Tapani Pälli33ee2c62013-12-12 13:51:01 +0200972 if ((var != NULL) && (var->data.mode != ir_var_temporary))
Ian Romanick7e2aa912010-07-19 17:12:42 -0700973 continue;
974
975 assert(inst->as_assignment()
Kenneth Graunked884f602012-03-20 15:56:37 -0700976 || inst->as_call()
Kenneth Graunkeb45a68e2012-10-24 13:17:24 -0700977 || inst->as_if() /* for initializers with the ?: operator */
Tapani Pälli33ee2c62013-12-12 13:51:01 +0200978 || ((var != NULL) && (var->data.mode == ir_var_temporary)));
Ian Romanick31a97862010-07-12 18:48:50 -0700979
980 if (make_copies) {
Eric Anholt8273bd42010-08-04 12:34:56 -0700981 inst = inst->clone(target, NULL);
Ian Romanick7e2aa912010-07-19 17:12:42 -0700982
983 if (var != NULL)
984 hash_table_insert(temps, inst, var);
985 else
Eric Anholt8273bd42010-08-04 12:34:56 -0700986 remap_variables(inst, target, temps);
Ian Romanick31a97862010-07-12 18:48:50 -0700987 } else {
988 inst->remove();
989 }
990
991 last->insert_after(inst);
992 last = inst;
993 }
994
Ian Romanick7e2aa912010-07-19 17:12:42 -0700995 if (make_copies)
996 hash_table_dtor(temps);
997
Ian Romanick31a97862010-07-12 18:48:50 -0700998 return last;
999}
1000
1001/**
Ian Romanick15ce87e2010-07-09 15:28:22 -07001002 * Get the function signature for main from a shader
1003 */
1004static ir_function_signature *
1005get_main_function_signature(gl_shader *sh)
1006{
1007 ir_function *const f = sh->symbols->get_function("main");
1008 if (f != NULL) {
1009 exec_list void_parameters;
1010
1011 /* Look for the 'void main()' signature and ensure that it's defined.
1012 * This keeps the linker from accidentally pick a shader that just
1013 * contains a prototype for main.
1014 *
1015 * We don't have to check for multiple definitions of main (in multiple
1016 * shaders) because that would have already been caught above.
1017 */
Kenneth Graunke3e820e32013-08-30 23:11:55 -07001018 ir_function_signature *sig = f->matching_signature(NULL, &void_parameters);
Ian Romanick15ce87e2010-07-09 15:28:22 -07001019 if ((sig != NULL) && sig->is_defined) {
1020 return sig;
1021 }
1022 }
1023
1024 return NULL;
1025}
1026
1027
1028/**
Brian Paul84a12732012-02-02 20:10:40 -07001029 * This class is only used in link_intrastage_shaders() below but declaring
1030 * it inside that function leads to compiler warnings with some versions of
1031 * gcc.
1032 */
1033class array_sizing_visitor : public ir_hierarchical_visitor {
1034public:
Paul Berry15e05b92013-09-25 14:07:37 -07001035 array_sizing_visitor()
1036 : mem_ctx(ralloc_context(NULL)),
1037 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash,
1038 hash_table_pointer_compare))
1039 {
1040 }
1041
1042 ~array_sizing_visitor()
1043 {
1044 hash_table_dtor(this->unnamed_interfaces);
1045 ralloc_free(this->mem_ctx);
1046 }
1047
Brian Paul84a12732012-02-02 20:10:40 -07001048 virtual ir_visitor_status visit(ir_variable *var)
1049 {
Tapani Pälli447bb902013-12-12 15:08:59 +02001050 fixup_type(&var->type, var->data.max_array_access);
Paul Berrye2266692013-09-23 10:44:19 -07001051 if (var->type->is_interface()) {
1052 if (interface_contains_unsized_arrays(var->type)) {
1053 const glsl_type *new_type =
1054 resize_interface_members(var->type, var->max_ifc_array_access);
1055 var->type = new_type;
1056 var->change_interface_type(new_type);
1057 }
1058 } else if (var->type->is_array() &&
1059 var->type->fields.array->is_interface()) {
1060 if (interface_contains_unsized_arrays(var->type->fields.array)) {
1061 const glsl_type *new_type =
1062 resize_interface_members(var->type->fields.array,
1063 var->max_ifc_array_access);
1064 var->change_interface_type(new_type);
1065 var->type =
1066 glsl_type::get_array_instance(new_type, var->type->length);
1067 }
Paul Berry15e05b92013-09-25 14:07:37 -07001068 } else if (const glsl_type *ifc_type = var->get_interface_type()) {
1069 /* Store a pointer to the variable in the unnamed_interfaces
1070 * hashtable.
1071 */
1072 ir_variable **interface_vars = (ir_variable **)
1073 hash_table_find(this->unnamed_interfaces, ifc_type);
1074 if (interface_vars == NULL) {
1075 interface_vars = rzalloc_array(mem_ctx, ir_variable *,
1076 ifc_type->length);
1077 hash_table_insert(this->unnamed_interfaces, interface_vars,
1078 ifc_type);
1079 }
1080 unsigned index = ifc_type->field_index(var->name);
1081 assert(index < ifc_type->length);
1082 assert(interface_vars[index] == NULL);
1083 interface_vars[index] = var;
Brian Paul84a12732012-02-02 20:10:40 -07001084 }
1085 return visit_continue;
1086 }
Paul Berrye2266692013-09-23 10:44:19 -07001087
Paul Berry15e05b92013-09-25 14:07:37 -07001088 /**
1089 * For each unnamed interface block that was discovered while running the
1090 * visitor, adjust the interface type to reflect the newly assigned array
1091 * sizes, and fix up the ir_variable nodes to point to the new interface
1092 * type.
1093 */
1094 void fixup_unnamed_interface_types()
1095 {
1096 hash_table_call_foreach(this->unnamed_interfaces,
1097 fixup_unnamed_interface_type, NULL);
1098 }
1099
Paul Berrye2266692013-09-23 10:44:19 -07001100private:
1101 /**
1102 * If the type pointed to by \c type represents an unsized array, replace
1103 * it with a sized array whose size is determined by max_array_access.
1104 */
1105 static void fixup_type(const glsl_type **type, unsigned max_array_access)
1106 {
Timothy Arcerib59c5922013-10-23 21:31:27 +11001107 if ((*type)->is_unsized_array()) {
Paul Berrye2266692013-09-23 10:44:19 -07001108 *type = glsl_type::get_array_instance((*type)->fields.array,
1109 max_array_access + 1);
1110 assert(*type != NULL);
1111 }
1112 }
1113
1114 /**
1115 * Determine whether the given interface type contains unsized arrays (if
1116 * it doesn't, array_sizing_visitor doesn't need to process it).
1117 */
1118 static bool interface_contains_unsized_arrays(const glsl_type *type)
1119 {
1120 for (unsigned i = 0; i < type->length; i++) {
1121 const glsl_type *elem_type = type->fields.structure[i].type;
Timothy Arcerib59c5922013-10-23 21:31:27 +11001122 if (elem_type->is_unsized_array())
Paul Berrye2266692013-09-23 10:44:19 -07001123 return true;
1124 }
1125 return false;
1126 }
1127
1128 /**
1129 * Create a new interface type based on the given type, with unsized arrays
1130 * replaced by sized arrays whose size is determined by
1131 * max_ifc_array_access.
1132 */
1133 static const glsl_type *
1134 resize_interface_members(const glsl_type *type,
1135 const unsigned *max_ifc_array_access)
1136 {
1137 unsigned num_fields = type->length;
1138 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1139 memcpy(fields, type->fields.structure,
1140 num_fields * sizeof(*fields));
1141 for (unsigned i = 0; i < num_fields; i++) {
1142 fixup_type(&fields[i].type, max_ifc_array_access[i]);
1143 }
1144 glsl_interface_packing packing =
1145 (glsl_interface_packing) type->interface_packing;
1146 const glsl_type *new_ifc_type =
1147 glsl_type::get_interface_instance(fields, num_fields,
1148 packing, type->name);
1149 delete [] fields;
1150 return new_ifc_type;
1151 }
Paul Berry15e05b92013-09-25 14:07:37 -07001152
1153 static void fixup_unnamed_interface_type(const void *key, void *data,
1154 void *)
1155 {
1156 const glsl_type *ifc_type = (const glsl_type *) key;
1157 ir_variable **interface_vars = (ir_variable **) data;
1158 unsigned num_fields = ifc_type->length;
1159 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1160 memcpy(fields, ifc_type->fields.structure,
1161 num_fields * sizeof(*fields));
1162 bool interface_type_changed = false;
1163 for (unsigned i = 0; i < num_fields; i++) {
1164 if (interface_vars[i] != NULL &&
1165 fields[i].type != interface_vars[i]->type) {
1166 fields[i].type = interface_vars[i]->type;
1167 interface_type_changed = true;
1168 }
1169 }
1170 if (!interface_type_changed) {
1171 delete [] fields;
1172 return;
1173 }
1174 glsl_interface_packing packing =
1175 (glsl_interface_packing) ifc_type->interface_packing;
1176 const glsl_type *new_ifc_type =
1177 glsl_type::get_interface_instance(fields, num_fields, packing,
1178 ifc_type->name);
1179 delete [] fields;
1180 for (unsigned i = 0; i < num_fields; i++) {
1181 if (interface_vars[i] != NULL)
1182 interface_vars[i]->change_interface_type(new_ifc_type);
1183 }
1184 }
1185
1186 /**
1187 * Memory context used to allocate the data in \c unnamed_interfaces.
1188 */
1189 void *mem_ctx;
1190
1191 /**
1192 * Hash table from const glsl_type * to an array of ir_variable *'s
1193 * pointing to the ir_variables constituting each unnamed interface block.
1194 */
1195 hash_table *unnamed_interfaces;
Brian Paul84a12732012-02-02 20:10:40 -07001196};
1197
Brian Paul84a12732012-02-02 20:10:40 -07001198/**
Anuj Phogat35f11e82014-02-05 15:01:58 -08001199 * Performs the cross-validation of layout qualifiers specified in
1200 * redeclaration of gl_FragCoord for the attached fragment shaders,
1201 * and propagates them to the linked FS and linked shader program.
1202 */
1203static void
1204link_fs_input_layout_qualifiers(struct gl_shader_program *prog,
1205 struct gl_shader *linked_shader,
1206 struct gl_shader **shader_list,
1207 unsigned num_shaders)
1208{
1209 linked_shader->redeclares_gl_fragcoord = false;
1210 linked_shader->uses_gl_fragcoord = false;
1211 linked_shader->origin_upper_left = false;
1212 linked_shader->pixel_center_integer = false;
1213
Anuj Phogat9bcb0a82014-02-10 14:12:40 -08001214 if (linked_shader->Stage != MESA_SHADER_FRAGMENT ||
1215 (prog->Version < 150 && !prog->ARB_fragment_coord_conventions_enable))
Anuj Phogat35f11e82014-02-05 15:01:58 -08001216 return;
1217
1218 for (unsigned i = 0; i < num_shaders; i++) {
1219 struct gl_shader *shader = shader_list[i];
1220 /* From the GLSL 1.50 spec, page 39:
1221 *
1222 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1223 * it must be redeclared in all the fragment shaders in that program
1224 * that have a static use gl_FragCoord."
1225 *
1226 * Exclude the case when one of the 'linked_shader' or 'shader' redeclares
1227 * gl_FragCoord with no layout qualifiers but the other one doesn't
1228 * redeclare it. If we strictly follow GLSL 1.50 spec's language, it
1229 * should be a link error. But, generating link error for this case will
1230 * be a wrong behaviour which spec didn't intend to do and it could also
1231 * break some applications.
1232 */
1233 if ((linked_shader->redeclares_gl_fragcoord
1234 && !shader->redeclares_gl_fragcoord
1235 && shader->uses_gl_fragcoord
1236 && (linked_shader->origin_upper_left
1237 || linked_shader->pixel_center_integer))
1238 || (shader->redeclares_gl_fragcoord
1239 && !linked_shader->redeclares_gl_fragcoord
1240 && linked_shader->uses_gl_fragcoord
1241 && (shader->origin_upper_left
1242 || shader->pixel_center_integer))) {
1243 linker_error(prog, "fragment shader defined with conflicting "
1244 "layout qualifiers for gl_FragCoord\n");
1245 }
1246
1247 /* From the GLSL 1.50 spec, page 39:
1248 *
1249 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1250 * single program must have the same set of qualifiers."
1251 */
1252 if (linked_shader->redeclares_gl_fragcoord && shader->redeclares_gl_fragcoord
1253 && (shader->origin_upper_left != linked_shader->origin_upper_left
1254 || shader->pixel_center_integer != linked_shader->pixel_center_integer)) {
1255 linker_error(prog, "fragment shader defined with conflicting "
1256 "layout qualifiers for gl_FragCoord\n");
1257 }
1258
1259 /* Update the linked shader state.  Note that uses_gl_fragcoord should
1260 * accumulate the results.  The other values should replace.  If there
1261 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1262 * are already known to be the same.
1263 */
1264 if (shader->redeclares_gl_fragcoord || shader->uses_gl_fragcoord) {
1265 linked_shader->redeclares_gl_fragcoord =
1266 shader->redeclares_gl_fragcoord;
1267 linked_shader->uses_gl_fragcoord = linked_shader->uses_gl_fragcoord
1268 || shader->uses_gl_fragcoord;
1269 linked_shader->origin_upper_left = shader->origin_upper_left;
1270 linked_shader->pixel_center_integer = shader->pixel_center_integer;
1271 }
1272 }
1273}
1274
1275/**
Eric Anholt6065a872013-06-12 18:12:40 -07001276 * Performs the cross-validation of geometry shader max_vertices and
1277 * primitive type layout qualifiers for the attached geometry shaders,
1278 * and propagates them to the linked GS and linked shader program.
1279 */
1280static void
1281link_gs_inout_layout_qualifiers(struct gl_shader_program *prog,
1282 struct gl_shader *linked_shader,
1283 struct gl_shader **shader_list,
1284 unsigned num_shaders)
1285{
1286 linked_shader->Geom.VerticesOut = 0;
Jordan Justen31340202014-01-25 02:17:21 -08001287 linked_shader->Geom.Invocations = 0;
Eric Anholt6065a872013-06-12 18:12:40 -07001288 linked_shader->Geom.InputType = PRIM_UNKNOWN;
1289 linked_shader->Geom.OutputType = PRIM_UNKNOWN;
1290
1291 /* No in/out qualifiers defined for anything but GLSL 1.50+
1292 * geometry shaders so far.
1293 */
Paul Berrye3b86f02014-01-07 10:58:56 -08001294 if (linked_shader->Stage != MESA_SHADER_GEOMETRY || prog->Version < 150)
Eric Anholt6065a872013-06-12 18:12:40 -07001295 return;
1296
1297 /* From the GLSL 1.50 spec, page 46:
1298 *
1299 * "All geometry shader output layout declarations in a program
1300 * must declare the same layout and same value for
1301 * max_vertices. There must be at least one geometry output
1302 * layout declaration somewhere in a program, but not all
1303 * geometry shaders (compilation units) are required to
1304 * declare it."
1305 */
1306
1307 for (unsigned i = 0; i < num_shaders; i++) {
1308 struct gl_shader *shader = shader_list[i];
1309
1310 if (shader->Geom.InputType != PRIM_UNKNOWN) {
1311 if (linked_shader->Geom.InputType != PRIM_UNKNOWN &&
1312 linked_shader->Geom.InputType != shader->Geom.InputType) {
1313 linker_error(prog, "geometry shader defined with conflicting "
1314 "input types\n");
1315 return;
1316 }
1317 linked_shader->Geom.InputType = shader->Geom.InputType;
1318 }
1319
1320 if (shader->Geom.OutputType != PRIM_UNKNOWN) {
1321 if (linked_shader->Geom.OutputType != PRIM_UNKNOWN &&
1322 linked_shader->Geom.OutputType != shader->Geom.OutputType) {
1323 linker_error(prog, "geometry shader defined with conflicting "
1324 "output types\n");
1325 return;
1326 }
1327 linked_shader->Geom.OutputType = shader->Geom.OutputType;
1328 }
1329
1330 if (shader->Geom.VerticesOut != 0) {
1331 if (linked_shader->Geom.VerticesOut != 0 &&
1332 linked_shader->Geom.VerticesOut != shader->Geom.VerticesOut) {
1333 linker_error(prog, "geometry shader defined with conflicting "
1334 "output vertex count (%d and %d)\n",
1335 linked_shader->Geom.VerticesOut,
1336 shader->Geom.VerticesOut);
1337 return;
1338 }
1339 linked_shader->Geom.VerticesOut = shader->Geom.VerticesOut;
1340 }
Jordan Justen31340202014-01-25 02:17:21 -08001341
1342 if (shader->Geom.Invocations != 0) {
1343 if (linked_shader->Geom.Invocations != 0 &&
1344 linked_shader->Geom.Invocations != shader->Geom.Invocations) {
1345 linker_error(prog, "geometry shader defined with conflicting "
1346 "invocation count (%d and %d)\n",
1347 linked_shader->Geom.Invocations,
1348 shader->Geom.Invocations);
1349 return;
1350 }
1351 linked_shader->Geom.Invocations = shader->Geom.Invocations;
1352 }
Eric Anholt6065a872013-06-12 18:12:40 -07001353 }
1354
1355 /* Just do the intrastage -> interstage propagation right now,
1356 * since we already know we're in the right type of shader program
1357 * for doing it.
1358 */
1359 if (linked_shader->Geom.InputType == PRIM_UNKNOWN) {
1360 linker_error(prog,
1361 "geometry shader didn't declare primitive input type\n");
1362 return;
1363 }
1364 prog->Geom.InputType = linked_shader->Geom.InputType;
1365
1366 if (linked_shader->Geom.OutputType == PRIM_UNKNOWN) {
1367 linker_error(prog,
1368 "geometry shader didn't declare primitive output type\n");
1369 return;
1370 }
1371 prog->Geom.OutputType = linked_shader->Geom.OutputType;
1372
1373 if (linked_shader->Geom.VerticesOut == 0) {
1374 linker_error(prog,
1375 "geometry shader didn't declare max_vertices\n");
1376 return;
1377 }
1378 prog->Geom.VerticesOut = linked_shader->Geom.VerticesOut;
Jordan Justen31340202014-01-25 02:17:21 -08001379
1380 if (linked_shader->Geom.Invocations == 0)
1381 linked_shader->Geom.Invocations = 1;
1382
1383 prog->Geom.Invocations = linked_shader->Geom.Invocations;
Eric Anholt6065a872013-06-12 18:12:40 -07001384}
1385
Paul Berry28ce6042014-01-08 11:59:28 -08001386
1387/**
1388 * Perform cross-validation of compute shader local_size_{x,y,z} layout
1389 * qualifiers for the attached compute shaders, and propagate them to the
1390 * linked CS and linked shader program.
1391 */
1392static void
1393link_cs_input_layout_qualifiers(struct gl_shader_program *prog,
1394 struct gl_shader *linked_shader,
1395 struct gl_shader **shader_list,
1396 unsigned num_shaders)
1397{
1398 for (int i = 0; i < 3; i++)
1399 linked_shader->Comp.LocalSize[i] = 0;
1400
1401 /* This function is called for all shader stages, but it only has an effect
1402 * for compute shaders.
1403 */
1404 if (linked_shader->Stage != MESA_SHADER_COMPUTE)
1405 return;
1406
1407 /* From the ARB_compute_shader spec, in the section describing local size
1408 * declarations:
1409 *
1410 * If multiple compute shaders attached to a single program object
1411 * declare local work-group size, the declarations must be identical;
1412 * otherwise a link-time error results. Furthermore, if a program
1413 * object contains any compute shaders, at least one must contain an
1414 * input layout qualifier specifying the local work sizes of the
1415 * program, or a link-time error will occur.
1416 */
1417 for (unsigned sh = 0; sh < num_shaders; sh++) {
1418 struct gl_shader *shader = shader_list[sh];
1419
1420 if (shader->Comp.LocalSize[0] != 0) {
1421 if (linked_shader->Comp.LocalSize[0] != 0) {
1422 for (int i = 0; i < 3; i++) {
1423 if (linked_shader->Comp.LocalSize[i] !=
1424 shader->Comp.LocalSize[i]) {
1425 linker_error(prog, "compute shader defined with conflicting "
1426 "local sizes\n");
1427 return;
1428 }
1429 }
1430 }
1431 for (int i = 0; i < 3; i++)
1432 linked_shader->Comp.LocalSize[i] = shader->Comp.LocalSize[i];
1433 }
1434 }
1435
1436 /* Just do the intrastage -> interstage propagation right now,
1437 * since we already know we're in the right type of shader program
1438 * for doing it.
1439 */
1440 if (linked_shader->Comp.LocalSize[0] == 0) {
1441 linker_error(prog, "compute shader didn't declare local size\n");
1442 return;
1443 }
1444 for (int i = 0; i < 3; i++)
1445 prog->Comp.LocalSize[i] = linked_shader->Comp.LocalSize[i];
1446}
1447
1448
Eric Anholt6065a872013-06-12 18:12:40 -07001449/**
Ian Romanick3fb87872010-07-09 14:09:34 -07001450 * Combine a group of shaders for a single stage to generate a linked shader
1451 *
1452 * \note
1453 * If this function is supplied a single shader, it is cloned, and the new
1454 * shader is returned.
1455 */
1456static struct gl_shader *
Kenneth Graunke2da02e72010-11-17 11:03:57 -08001457link_intrastage_shaders(void *mem_ctx,
1458 struct gl_context *ctx,
Eric Anholt5d0f4302010-08-18 12:02:35 -07001459 struct gl_shader_program *prog,
Ian Romanick3fb87872010-07-09 14:09:34 -07001460 struct gl_shader **shader_list,
1461 unsigned num_shaders)
1462{
Eric Anholtf609cf72012-04-27 13:52:56 -07001463 struct gl_uniform_block *uniform_blocks = NULL;
Eric Anholtf609cf72012-04-27 13:52:56 -07001464
Ian Romanick13f782c2010-06-29 18:53:38 -07001465 /* Check that global variables defined in multiple shaders are consistent.
1466 */
Paul Berryb95d2372013-07-27 11:08:31 -07001467 cross_validate_globals(prog, shader_list, num_shaders, false);
1468 if (!prog->LinkStatus)
Ian Romanick13f782c2010-06-29 18:53:38 -07001469 return NULL;
1470
Jordan Justen4a0bcd92013-05-20 23:42:49 -07001471 /* Check that interface blocks defined in multiple shaders are consistent.
1472 */
Paul Berryb95d2372013-07-27 11:08:31 -07001473 validate_intrastage_interface_blocks(prog, (const gl_shader **)shader_list,
1474 num_shaders);
1475 if (!prog->LinkStatus)
Jordan Justen4a0bcd92013-05-20 23:42:49 -07001476 return NULL;
1477
Paul Berry4682b9b2013-07-27 15:07:08 -07001478 /* Link up uniform blocks defined within this stage. */
1479 const unsigned num_uniform_blocks =
Ian Romanick514f8c72013-01-22 01:09:16 -05001480 link_uniform_blocks(mem_ctx, prog, shader_list, num_shaders,
1481 &uniform_blocks);
Juha-Pekka Heikkila088da372014-04-03 17:06:42 +03001482 if (!prog->LinkStatus)
1483 return NULL;
Eric Anholtf609cf72012-04-27 13:52:56 -07001484
Ian Romanick13f782c2010-06-29 18:53:38 -07001485 /* Check that there is only a single definition of each function signature
1486 * across all shaders.
1487 */
1488 for (unsigned i = 0; i < (num_shaders - 1); i++) {
1489 foreach_list(node, shader_list[i]->ir) {
1490 ir_function *const f = ((ir_instruction *) node)->as_function();
1491
1492 if (f == NULL)
1493 continue;
1494
1495 for (unsigned j = i + 1; j < num_shaders; j++) {
1496 ir_function *const other =
1497 shader_list[j]->symbols->get_function(f->name);
1498
1499 /* If the other shader has no function (and therefore no function
1500 * signatures) with the same name, skip to the next shader.
1501 */
1502 if (other == NULL)
1503 continue;
1504
Kenneth Graunke5f7e7782013-11-22 01:25:42 -08001505 foreach_list(n, &f->signatures) {
1506 ir_function_signature *sig = (ir_function_signature *) n;
Ian Romanick13f782c2010-06-29 18:53:38 -07001507
Kenneth Graunke4b0bac02013-08-30 16:12:55 -07001508 if (!sig->is_defined || sig->is_builtin())
Ian Romanick13f782c2010-06-29 18:53:38 -07001509 continue;
1510
1511 ir_function_signature *other_sig =
Kenneth Graunke3e820e32013-08-30 23:11:55 -07001512 other->exact_matching_signature(NULL, &sig->parameters);
Ian Romanick13f782c2010-06-29 18:53:38 -07001513
1514 if ((other_sig != NULL) && other_sig->is_defined
Kenneth Graunke4b0bac02013-08-30 16:12:55 -07001515 && !other_sig->is_builtin()) {
Ian Romanick586e7412011-07-28 14:04:09 -07001516 linker_error(prog, "function `%s' is multiply defined",
1517 f->name);
Ian Romanick13f782c2010-06-29 18:53:38 -07001518 return NULL;
1519 }
1520 }
1521 }
1522 }
1523 }
1524
1525 /* Find the shader that defines main, and make a clone of it.
1526 *
1527 * Starting with the clone, search for undefined references. If one is
1528 * found, find the shader that defines it. Clone the reference and add
1529 * it to the shader. Repeat until there are no undefined references or
1530 * until a reference cannot be resolved.
1531 */
Ian Romanick15ce87e2010-07-09 15:28:22 -07001532 gl_shader *main = NULL;
1533 for (unsigned i = 0; i < num_shaders; i++) {
1534 if (get_main_function_signature(shader_list[i]) != NULL) {
1535 main = shader_list[i];
1536 break;
1537 }
1538 }
Ian Romanick13f782c2010-06-29 18:53:38 -07001539
Ian Romanick15ce87e2010-07-09 15:28:22 -07001540 if (main == NULL) {
Ian Romanick586e7412011-07-28 14:04:09 -07001541 linker_error(prog, "%s shader lacks `main'\n",
Paul Berrye3b86f02014-01-07 10:58:56 -08001542 _mesa_shader_stage_to_string(shader_list[0]->Stage));
Ian Romanick15ce87e2010-07-09 15:28:22 -07001543 return NULL;
1544 }
1545
Ian Romanick4a455952010-10-13 15:13:02 -07001546 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
Ian Romanick15ce87e2010-07-09 15:28:22 -07001547 linked->ir = new(linked) exec_list;
Kenneth Graunke2da02e72010-11-17 11:03:57 -08001548 clone_ir_list(mem_ctx, linked->ir, main->ir);
Ian Romanick15ce87e2010-07-09 15:28:22 -07001549
Eric Anholtf609cf72012-04-27 13:52:56 -07001550 linked->UniformBlocks = uniform_blocks;
1551 linked->NumUniformBlocks = num_uniform_blocks;
1552 ralloc_steal(linked, linked->UniformBlocks);
1553
Anuj Phogat35f11e82014-02-05 15:01:58 -08001554 link_fs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
Eric Anholt6065a872013-06-12 18:12:40 -07001555 link_gs_inout_layout_qualifiers(prog, linked, shader_list, num_shaders);
Paul Berry28ce6042014-01-08 11:59:28 -08001556 link_cs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
Eric Anholt6065a872013-06-12 18:12:40 -07001557
Ian Romanick15ce87e2010-07-09 15:28:22 -07001558 populate_symbol_table(linked);
Ian Romanick13f782c2010-06-29 18:53:38 -07001559
Ian Romanick31a97862010-07-12 18:48:50 -07001560 /* The a pointer to the main function in the final linked shader (i.e., the
1561 * copy of the original shader that contained the main function).
1562 */
1563 ir_function_signature *const main_sig = get_main_function_signature(linked);
1564
1565 /* Move any instructions other than variable declarations or function
1566 * declarations into main.
1567 */
Ian Romanick9303e352010-07-19 12:33:54 -07001568 exec_node *insertion_point =
1569 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
1570 linked);
1571
Ian Romanick31a97862010-07-12 18:48:50 -07001572 for (unsigned i = 0; i < num_shaders; i++) {
Ian Romanick9303e352010-07-19 12:33:54 -07001573 if (shader_list[i] == main)
1574 continue;
1575
Ian Romanick31a97862010-07-12 18:48:50 -07001576 insertion_point = move_non_declarations(shader_list[i]->ir,
Ian Romanick9303e352010-07-19 12:33:54 -07001577 insertion_point, true, linked);
Ian Romanick31a97862010-07-12 18:48:50 -07001578 }
1579
Kenneth Graunke5b331f62013-11-23 12:11:34 -08001580 /* Check if any shader needs built-in functions. */
1581 bool need_builtins = false;
Ian Romanickd5be2ac2010-07-20 11:29:46 -07001582 for (unsigned i = 0; i < num_shaders; i++) {
Kenneth Graunke5b331f62013-11-23 12:11:34 -08001583 if (shader_list[i]->uses_builtin_functions) {
1584 need_builtins = true;
1585 break;
1586 }
Ian Romanickd5be2ac2010-07-20 11:29:46 -07001587 }
1588
Kenneth Graunke5b331f62013-11-23 12:11:34 -08001589 bool ok;
1590 if (need_builtins) {
1591 /* Make a temporary array one larger than shader_list, which will hold
1592 * the built-in function shader as well.
1593 */
1594 gl_shader **linking_shaders = (gl_shader **)
1595 calloc(num_shaders + 1, sizeof(gl_shader *));
1596 memcpy(linking_shaders, shader_list, num_shaders * sizeof(gl_shader *));
1597 linking_shaders[num_shaders] = _mesa_glsl_get_builtin_function_shader();
Ian Romanickd5be2ac2010-07-20 11:29:46 -07001598
Kenneth Graunke5b331f62013-11-23 12:11:34 -08001599 ok = link_function_calls(prog, linked, linking_shaders, num_shaders + 1);
1600
Kenneth Graunke7d2423a2013-08-02 00:35:05 -07001601 free(linking_shaders);
Kenneth Graunke5b331f62013-11-23 12:11:34 -08001602 } else {
1603 ok = link_function_calls(prog, linked, shader_list, num_shaders);
1604 }
1605
1606
1607 if (!ok) {
1608 ctx->Driver.DeleteShader(ctx, linked);
Kenneth Graunke7d2423a2013-08-02 00:35:05 -07001609 return NULL;
Ian Romanick4a455952010-10-13 15:13:02 -07001610 }
Ian Romanickd5be2ac2010-07-20 11:29:46 -07001611
Paul Berryc148ef62011-08-03 15:37:01 -07001612 /* At this point linked should contain all of the linked IR, so
1613 * validate it to make sure nothing went wrong.
1614 */
Kenneth Graunke7d2423a2013-08-02 00:35:05 -07001615 validate_ir_tree(linked->ir);
Paul Berryc148ef62011-08-03 15:37:01 -07001616
Paul Berry7cfefe62013-07-30 21:13:48 -07001617 /* Set the size of geometry shader input arrays */
Paul Berrye3b86f02014-01-07 10:58:56 -08001618 if (linked->Stage == MESA_SHADER_GEOMETRY) {
Paul Berry7cfefe62013-07-30 21:13:48 -07001619 unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
1620 geom_array_resize_visitor input_resize_visitor(num_vertices, prog);
Kenneth Graunke5f7e7782013-11-22 01:25:42 -08001621 foreach_list(n, linked->ir) {
1622 ir_instruction *ir = (ir_instruction *) n;
Paul Berry7cfefe62013-07-30 21:13:48 -07001623 ir->accept(&input_resize_visitor);
1624 }
1625 }
1626
Ian Romanickc87e9ef2011-01-25 12:04:08 -08001627 /* Make a pass over all variable declarations to ensure that arrays with
Ian Romanick6f539212010-12-07 18:30:33 -08001628 * unspecified sizes have a size specified. The size is inferred from the
1629 * max_array_access field.
1630 */
Kenneth Graunke7d2423a2013-08-02 00:35:05 -07001631 array_sizing_visitor v;
1632 v.run(linked->ir);
Paul Berry15e05b92013-09-25 14:07:37 -07001633 v.fixup_unnamed_interface_types();
Ian Romanick6f539212010-12-07 18:30:33 -08001634
Ian Romanick3fb87872010-07-09 14:09:34 -07001635 return linked;
1636}
1637
Eric Anholta721abf2010-08-23 10:32:01 -07001638/**
1639 * Update the sizes of linked shader uniform arrays to the maximum
1640 * array index used.
1641 *
1642 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
1643 *
1644 * If one or more elements of an array are active,
1645 * GetActiveUniform will return the name of the array in name,
1646 * subject to the restrictions listed above. The type of the array
1647 * is returned in type. The size parameter contains the highest
1648 * array element index used, plus one. The compiler or linker
1649 * determines the highest index used. There will be only one
1650 * active uniform reported by the GL per uniform array.
1651
1652 */
1653static void
Eric Anholt586b4b52010-09-28 14:32:16 -07001654update_array_sizes(struct gl_shader_program *prog)
Eric Anholta721abf2010-08-23 10:32:01 -07001655{
Paul Berry665b8d72014-01-07 10:11:39 -08001656 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
Ian Romanick3322fba2010-10-14 13:28:42 -07001657 if (prog->_LinkedShaders[i] == NULL)
1658 continue;
1659
Eric Anholta721abf2010-08-23 10:32:01 -07001660 foreach_list(node, prog->_LinkedShaders[i]->ir) {
1661 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1662
Tapani Pälli33ee2c62013-12-12 13:51:01 +02001663 if ((var == NULL) || (var->data.mode != ir_var_uniform) ||
Eric Anholta721abf2010-08-23 10:32:01 -07001664 !var->type->is_array())
1665 continue;
1666
Eric Anholt9feb4032012-05-01 14:43:31 -07001667 /* GL_ARB_uniform_buffer_object says that std140 uniforms
1668 * will not be eliminated. Since we always do std140, just
1669 * don't resize arrays in UBOs.
Francisco Jerez5c114932013-09-11 12:14:46 -07001670 *
1671 * Atomic counters are supposed to get deterministic
1672 * locations assigned based on the declaration ordering and
1673 * sizes, array compaction would mess that up.
Eric Anholt9feb4032012-05-01 14:43:31 -07001674 */
Francisco Jerez5c114932013-09-11 12:14:46 -07001675 if (var->is_in_uniform_block() || var->type->contains_atomic())
Eric Anholt9feb4032012-05-01 14:43:31 -07001676 continue;
1677
Tapani Pälli447bb902013-12-12 15:08:59 +02001678 unsigned int size = var->data.max_array_access;
Paul Berry665b8d72014-01-07 10:11:39 -08001679 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
Ian Romanick3322fba2010-10-14 13:28:42 -07001680 if (prog->_LinkedShaders[j] == NULL)
1681 continue;
1682
Eric Anholta721abf2010-08-23 10:32:01 -07001683 foreach_list(node2, prog->_LinkedShaders[j]->ir) {
1684 ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
1685 if (!other_var)
1686 continue;
1687
1688 if (strcmp(var->name, other_var->name) == 0 &&
Tapani Pälli447bb902013-12-12 15:08:59 +02001689 other_var->data.max_array_access > size) {
1690 size = other_var->data.max_array_access;
Eric Anholta721abf2010-08-23 10:32:01 -07001691 }
1692 }
1693 }
Eric Anholt586b4b52010-09-28 14:32:16 -07001694
Fabian Bieler63684782013-06-14 13:37:07 +02001695 if (size + 1 != var->type->length) {
Ian Romanick89d81ab2011-01-25 10:41:20 -08001696 /* If this is a built-in uniform (i.e., it's backed by some
1697 * fixed-function state), adjust the number of state slots to
1698 * match the new array size. The number of slots per array entry
Bryan Cainf18a0862011-04-23 19:29:15 -05001699 * is not known. It seems safe to assume that the total number of
Ian Romanick89d81ab2011-01-25 10:41:20 -08001700 * slots is an integer multiple of the number of array elements.
1701 * Determine the number of slots per array element by dividing by
1702 * the old (total) size.
1703 */
1704 if (var->num_state_slots > 0) {
1705 var->num_state_slots = (size + 1)
1706 * (var->num_state_slots / var->type->length);
1707 }
1708
Eric Anholta721abf2010-08-23 10:32:01 -07001709 var->type = glsl_type::get_array_instance(var->type->fields.array,
1710 size + 1);
1711 /* FINISHME: We should update the types of array
1712 * dereferences of this variable now.
1713 */
1714 }
1715 }
1716 }
1717}
1718
Ian Romanick69846702010-06-22 17:29:19 -07001719/**
Bryan Cainf18a0862011-04-23 19:29:15 -05001720 * Find a contiguous set of available bits in a bitmask.
Ian Romanick69846702010-06-22 17:29:19 -07001721 *
1722 * \param used_mask Bits representing used (1) and unused (0) locations
1723 * \param needed_count Number of contiguous bits needed.
1724 *
1725 * \return
1726 * Base location of the available bits on success or -1 on failure.
1727 */
1728int
1729find_available_slots(unsigned used_mask, unsigned needed_count)
1730{
1731 unsigned needed_mask = (1 << needed_count) - 1;
1732 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
1733
1734 /* The comparison to 32 is redundant, but without it GCC emits "warning:
1735 * cannot optimize possibly infinite loops" for the loop below.
1736 */
1737 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
1738 return -1;
1739
1740 for (int i = 0; i <= max_bit_to_test; i++) {
1741 if ((needed_mask & ~used_mask) == needed_mask)
1742 return i;
1743
1744 needed_mask <<= 1;
1745 }
1746
1747 return -1;
1748}
1749
1750
Ian Romanickd32d4f72011-06-27 17:59:58 -07001751/**
1752 * Assign locations for either VS inputs for FS outputs
1753 *
1754 * \param prog Shader program whose variables need locations assigned
1755 * \param target_index Selector for the program target to receive location
1756 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
1757 * \c MESA_SHADER_FRAGMENT.
1758 * \param max_index Maximum number of generic locations. This corresponds
1759 * to either the maximum number of draw buffers or the
1760 * maximum number of generic attributes.
1761 *
1762 * \return
1763 * If locations are successfully assigned, true is returned. Otherwise an
1764 * error is emitted to the shader link log and false is returned.
Ian Romanickd32d4f72011-06-27 17:59:58 -07001765 */
Ian Romanick69846702010-06-22 17:29:19 -07001766bool
Ian Romanickd32d4f72011-06-27 17:59:58 -07001767assign_attribute_or_color_locations(gl_shader_program *prog,
1768 unsigned target_index,
1769 unsigned max_index)
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001770{
Ian Romanickd32d4f72011-06-27 17:59:58 -07001771 /* Mark invalid locations as being used.
Ian Romanick9342d262010-06-22 17:41:37 -07001772 */
Ian Romanickd32d4f72011-06-27 17:59:58 -07001773 unsigned used_locations = (max_index >= 32)
1774 ? ~0 : ~((1 << max_index) - 1);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001775
Ian Romanickd32d4f72011-06-27 17:59:58 -07001776 assert((target_index == MESA_SHADER_VERTEX)
1777 || (target_index == MESA_SHADER_FRAGMENT));
1778
1779 gl_shader *const sh = prog->_LinkedShaders[target_index];
1780 if (sh == NULL)
1781 return true;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001782
Ian Romanick69846702010-06-22 17:29:19 -07001783 /* Operate in a total of four passes.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001784 *
1785 * 1. Invalidate the location assignments for all vertex shader inputs.
1786 *
1787 * 2. Assign locations for inputs that have user-defined (via
Ian Romanickb12b5d92011-11-04 16:08:52 -07001788 * glBindVertexAttribLocation) locations and outputs that have
1789 * user-defined locations (via glBindFragDataLocation).
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001790 *
Ian Romanick69846702010-06-22 17:29:19 -07001791 * 3. Sort the attributes without assigned locations by number of slots
1792 * required in decreasing order. Fragmentation caused by attribute
1793 * locations assigned by the application may prevent large attributes
1794 * from having enough contiguous space.
1795 *
1796 * 4. Assign locations to any inputs without assigned locations.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001797 */
1798
Ian Romanickd32d4f72011-06-27 17:59:58 -07001799 const int generic_base = (target_index == MESA_SHADER_VERTEX)
Brian Paul7eb7d672011-07-07 16:47:59 -06001800 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001801
Ian Romanickd32d4f72011-06-27 17:59:58 -07001802 const enum ir_variable_mode direction =
Paul Berry42a29d82013-01-11 14:39:32 -08001803 (target_index == MESA_SHADER_VERTEX)
1804 ? ir_var_shader_in : ir_var_shader_out;
Ian Romanickd32d4f72011-06-27 17:59:58 -07001805
1806
Ian Romanick69846702010-06-22 17:29:19 -07001807 /* Temporary storage for the set of attributes that need locations assigned.
1808 */
1809 struct temp_attr {
1810 unsigned slots;
1811 ir_variable *var;
1812
1813 /* Used below in the call to qsort. */
1814 static int compare(const void *a, const void *b)
1815 {
1816 const temp_attr *const l = (const temp_attr *) a;
1817 const temp_attr *const r = (const temp_attr *) b;
1818
1819 /* Reversed because we want a descending order sort below. */
1820 return r->slots - l->slots;
1821 }
1822 } to_assign[16];
1823
1824 unsigned num_attr = 0;
1825
Eric Anholt16b68b12010-06-30 11:05:43 -07001826 foreach_list(node, sh->ir) {
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001827 ir_variable *const var = ((ir_instruction *) node)->as_variable();
1828
Tapani Pälli33ee2c62013-12-12 13:51:01 +02001829 if ((var == NULL) || (var->data.mode != (unsigned) direction))
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001830 continue;
1831
Tapani Pälli447bb902013-12-12 15:08:59 +02001832 if (var->data.explicit_location) {
1833 if ((var->data.location >= (int)(max_index + generic_base))
1834 || (var->data.location < 0)) {
Ian Romanick586e7412011-07-28 14:04:09 -07001835 linker_error(prog,
1836 "invalid explicit location %d specified for `%s'\n",
Tapani Pälli447bb902013-12-12 15:08:59 +02001837 (var->data.location < 0)
1838 ? var->data.location
1839 : var->data.location - generic_base,
Ian Romanick586e7412011-07-28 14:04:09 -07001840 var->name);
Ian Romanick68a4fc92010-10-07 17:21:22 -07001841 return false;
Ian Romanick523b6112011-08-17 15:40:03 -07001842 }
1843 } else if (target_index == MESA_SHADER_VERTEX) {
1844 unsigned binding;
1845
1846 if (prog->AttributeBindings->get(binding, var->name)) {
1847 assert(binding >= VERT_ATTRIB_GENERIC0);
Tapani Pälli447bb902013-12-12 15:08:59 +02001848 var->data.location = binding;
1849 var->data.is_unmatched_generic_inout = 0;
Ian Romanick68a4fc92010-10-07 17:21:22 -07001850 }
Ian Romanickb12b5d92011-11-04 16:08:52 -07001851 } else if (target_index == MESA_SHADER_FRAGMENT) {
1852 unsigned binding;
Dave Airlie1256a5d2012-03-24 13:33:41 +00001853 unsigned index;
Ian Romanickb12b5d92011-11-04 16:08:52 -07001854
1855 if (prog->FragDataBindings->get(binding, var->name)) {
1856 assert(binding >= FRAG_RESULT_DATA0);
Tapani Pälli447bb902013-12-12 15:08:59 +02001857 var->data.location = binding;
1858 var->data.is_unmatched_generic_inout = 0;
Dave Airlie1256a5d2012-03-24 13:33:41 +00001859
1860 if (prog->FragDataIndexBindings->get(index, var->name)) {
Tapani Pälli447bb902013-12-12 15:08:59 +02001861 var->data.index = index;
Dave Airlie1256a5d2012-03-24 13:33:41 +00001862 }
Ian Romanickb12b5d92011-11-04 16:08:52 -07001863 }
Ian Romanick68a4fc92010-10-07 17:21:22 -07001864 }
1865
Ian Romanick9f0e98d2011-10-06 10:25:34 -07001866 /* If the variable is not a built-in and has a location statically
1867 * assigned in the shader (presumably via a layout qualifier), make sure
1868 * that it doesn't collide with other assigned locations. Otherwise,
1869 * add it to the list of variables that need linker-assigned locations.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001870 */
Paul Berry0026ad42013-07-31 08:15:08 -07001871 const unsigned slots = var->type->count_attribute_slots();
Tapani Pälli447bb902013-12-12 15:08:59 +02001872 if (var->data.location != -1) {
1873 if (var->data.location >= generic_base && var->data.index < 1) {
Ian Romanick523b6112011-08-17 15:40:03 -07001874 /* From page 61 of the OpenGL 4.0 spec:
1875 *
1876 * "LinkProgram will fail if the attribute bindings assigned
1877 * by BindAttribLocation do not leave not enough space to
1878 * assign a location for an active matrix attribute or an
1879 * active attribute array, both of which require multiple
1880 * contiguous generic attributes."
1881 *
Anuj Phogat8c61b6a2014-03-04 17:03:28 -08001882 * I think above text prohibits the aliasing of explicit and
1883 * automatic assignments. But, aliasing is allowed in manual
1884 * assignments of attribute locations. See below comments for
1885 * the details.
Ian Romanick523b6112011-08-17 15:40:03 -07001886 *
Anuj Phogat8c61b6a2014-03-04 17:03:28 -08001887 * From OpenGL 4.0 spec, page 61:
Ian Romanick523b6112011-08-17 15:40:03 -07001888 *
1889 * "It is possible for an application to bind more than one
1890 * attribute name to the same location. This is referred to as
1891 * aliasing. This will only work if only one of the aliased
1892 * attributes is active in the executable program, or if no
1893 * path through the shader consumes more than one attribute of
1894 * a set of attributes aliased to the same location. A link
1895 * error can occur if the linker determines that every path
1896 * through the shader consumes multiple aliased attributes,
1897 * but implementations are not required to generate an error
1898 * in this case."
1899 *
Anuj Phogat8c61b6a2014-03-04 17:03:28 -08001900 * From GLSL 4.30 spec, page 54:
1901 *
1902 * "A program will fail to link if any two non-vertex shader
1903 * input variables are assigned to the same location. For
1904 * vertex shaders, multiple input variables may be assigned
1905 * to the same location using either layout qualifiers or via
1906 * the OpenGL API. However, such aliasing is intended only to
1907 * support vertex shaders where each execution path accesses
1908 * at most one input per each location. Implementations are
1909 * permitted, but not required, to generate link-time errors
1910 * if they detect that every path through the vertex shader
1911 * executable accesses multiple inputs assigned to any single
1912 * location. For all shader types, a program will fail to link
1913 * if explicit location assignments leave the linker unable
1914 * to find space for other variables without explicit
1915 * assignments."
1916 *
1917 * From OpenGL ES 3.0 spec, page 56:
1918 *
1919 * "Binding more than one attribute name to the same location
1920 * is referred to as aliasing, and is not permitted in OpenGL
1921 * ES Shading Language 3.00 vertex shaders. LinkProgram will
1922 * fail when this condition exists. However, aliasing is
1923 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
1924 * This will only work if only one of the aliased attributes
1925 * is active in the executable program, or if no path through
1926 * the shader consumes more than one attribute of a set of
1927 * attributes aliased to the same location. A link error can
1928 * occur if the linker determines that every path through the
1929 * shader consumes multiple aliased attributes, but implemen-
1930 * tations are not required to generate an error in this case."
1931 *
1932 * After looking at above references from OpenGL, OpenGL ES and
1933 * GLSL specifications, we allow aliasing of vertex input variables
1934 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
1935 *
1936 * NOTE: This is not required by the spec but its worth mentioning
1937 * here that we're not doing anything to make sure that no path
1938 * through the vertex shader executable accesses multiple inputs
1939 * assigned to any single location.
Ian Romanick523b6112011-08-17 15:40:03 -07001940 */
Anuj Phogat8c61b6a2014-03-04 17:03:28 -08001941
Ian Romanick523b6112011-08-17 15:40:03 -07001942 /* Mask representing the contiguous slots that will be used by
1943 * this attribute.
1944 */
Tapani Pälli447bb902013-12-12 15:08:59 +02001945 const unsigned attr = var->data.location - generic_base;
Ian Romanick523b6112011-08-17 15:40:03 -07001946 const unsigned use_mask = (1 << slots) - 1;
Anuj Phogat8c61b6a2014-03-04 17:03:28 -08001947 const char *const string = (target_index == MESA_SHADER_VERTEX)
1948 ? "vertex shader input" : "fragment shader output";
1949
1950 /* Generate a link error if the requested locations for this
1951 * attribute exceed the maximum allowed attribute location.
1952 */
1953 if (attr + slots > max_index) {
1954 linker_error(prog,
1955 "insufficient contiguous locations "
1956 "available for %s `%s' %d %d %d", string,
1957 var->name, used_locations, use_mask, attr);
1958 return false;
1959 }
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001960
Ian Romanick523b6112011-08-17 15:40:03 -07001961 /* Generate a link error if the set of bits requested for this
1962 * attribute overlaps any previously allocated bits.
1963 */
1964 if ((~(use_mask << attr) & used_locations) != used_locations) {
Anuj Phogat8c61b6a2014-03-04 17:03:28 -08001965 if (target_index == MESA_SHADER_FRAGMENT ||
1966 (prog->IsES && prog->Version >= 300)) {
1967 linker_error(prog,
1968 "overlapping location is assigned "
1969 "to %s `%s' %d %d %d\n", string,
1970 var->name, used_locations, use_mask, attr);
1971 return false;
1972 } else {
1973 linker_warning(prog,
1974 "overlapping location is assigned "
1975 "to %s `%s' %d %d %d\n", string,
1976 var->name, used_locations, use_mask, attr);
1977 }
Ian Romanick523b6112011-08-17 15:40:03 -07001978 }
1979
1980 used_locations |= (use_mask << attr);
1981 }
1982
1983 continue;
1984 }
1985
1986 to_assign[num_attr].slots = slots;
Ian Romanick69846702010-06-22 17:29:19 -07001987 to_assign[num_attr].var = var;
1988 num_attr++;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07001989 }
Ian Romanick69846702010-06-22 17:29:19 -07001990
1991 /* If all of the attributes were assigned locations by the application (or
1992 * are built-in attributes with fixed locations), return early. This should
1993 * be the common case.
1994 */
1995 if (num_attr == 0)
1996 return true;
1997
1998 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
1999
Ian Romanickd32d4f72011-06-27 17:59:58 -07002000 if (target_index == MESA_SHADER_VERTEX) {
2001 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2002 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2003 * reserved to prevent it from being automatically allocated below.
2004 */
2005 find_deref_visitor find("gl_Vertex");
2006 find.run(sh->ir);
2007 if (find.variable_found())
2008 used_locations |= (1 << 0);
2009 }
Ian Romanick982e3792010-06-29 18:58:20 -07002010
Ian Romanick69846702010-06-22 17:29:19 -07002011 for (unsigned i = 0; i < num_attr; i++) {
2012 /* Mask representing the contiguous slots that will be used by this
2013 * attribute.
2014 */
2015 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
2016
2017 int location = find_available_slots(used_locations, to_assign[i].slots);
2018
2019 if (location < 0) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07002020 const char *const string = (target_index == MESA_SHADER_VERTEX)
2021 ? "vertex shader input" : "fragment shader output";
2022
Ian Romanick586e7412011-07-28 14:04:09 -07002023 linker_error(prog,
Dave Airlie7449ae42011-11-20 19:56:35 +00002024 "insufficient contiguous locations "
Ian Romanick586e7412011-07-28 14:04:09 -07002025 "available for %s `%s'",
2026 string, to_assign[i].var->name);
Ian Romanick69846702010-06-22 17:29:19 -07002027 return false;
2028 }
2029
Tapani Pälli447bb902013-12-12 15:08:59 +02002030 to_assign[i].var->data.location = generic_base + location;
2031 to_assign[i].var->data.is_unmatched_generic_inout = 0;
Ian Romanick69846702010-06-22 17:29:19 -07002032 used_locations |= (use_mask << location);
2033 }
2034
2035 return true;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07002036}
2037
2038
Ian Romanick40e114b2010-08-17 14:55:50 -07002039/**
Ian Romanickcc90e622010-10-19 17:59:10 -07002040 * Demote shader inputs and outputs that are not used in other stages
Ian Romanick40e114b2010-08-17 14:55:50 -07002041 */
2042void
Ian Romanickcc90e622010-10-19 17:59:10 -07002043demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
Ian Romanick40e114b2010-08-17 14:55:50 -07002044{
2045 foreach_list(node, sh->ir) {
2046 ir_variable *const var = ((ir_instruction *) node)->as_variable();
2047
Tapani Pälli33ee2c62013-12-12 13:51:01 +02002048 if ((var == NULL) || (var->data.mode != int(mode)))
Ian Romanick40e114b2010-08-17 14:55:50 -07002049 continue;
2050
Ian Romanickcc90e622010-10-19 17:59:10 -07002051 /* A shader 'in' or 'out' variable is only really an input or output if
2052 * its value is used by other shader stages. This will cause the variable
2053 * to have a location assigned.
Ian Romanick40e114b2010-08-17 14:55:50 -07002054 */
Tapani Pälli447bb902013-12-12 15:08:59 +02002055 if (var->data.is_unmatched_generic_inout) {
Tapani Pälli33ee2c62013-12-12 13:51:01 +02002056 var->data.mode = ir_var_auto;
Ian Romanick40e114b2010-08-17 14:55:50 -07002057 }
2058 }
2059}
2060
2061
Paul Berry871ddb92011-11-05 11:17:32 -07002062/**
Marek Olšákec174a42011-11-18 15:00:10 +01002063 * Store the gl_FragDepth layout in the gl_shader_program struct.
2064 */
2065static void
2066store_fragdepth_layout(struct gl_shader_program *prog)
2067{
2068 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2069 return;
2070 }
2071
2072 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2073
2074 /* We don't look up the gl_FragDepth symbol directly because if
2075 * gl_FragDepth is not used in the shader, it's removed from the IR.
2076 * However, the symbol won't be removed from the symbol table.
2077 *
2078 * We're only interested in the cases where the variable is NOT removed
2079 * from the IR.
2080 */
2081 foreach_list(node, ir) {
2082 ir_variable *const var = ((ir_instruction *) node)->as_variable();
2083
Tapani Pälli33ee2c62013-12-12 13:51:01 +02002084 if (var == NULL || var->data.mode != ir_var_shader_out) {
Marek Olšákec174a42011-11-18 15:00:10 +01002085 continue;
2086 }
2087
2088 if (strcmp(var->name, "gl_FragDepth") == 0) {
Tapani Pälli447bb902013-12-12 15:08:59 +02002089 switch (var->data.depth_layout) {
Marek Olšákec174a42011-11-18 15:00:10 +01002090 case ir_depth_layout_none:
2091 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2092 return;
2093 case ir_depth_layout_any:
2094 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2095 return;
2096 case ir_depth_layout_greater:
2097 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2098 return;
2099 case ir_depth_layout_less:
2100 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2101 return;
2102 case ir_depth_layout_unchanged:
2103 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2104 return;
2105 default:
2106 assert(0);
2107 return;
2108 }
2109 }
2110 }
2111}
2112
2113/**
Ian Romanick92f81592011-11-08 12:37:19 -08002114 * Validate the resources used by a program versus the implementation limits
2115 */
Paul Berryb95d2372013-07-27 11:08:31 -07002116static void
Ian Romanick92f81592011-11-08 12:37:19 -08002117check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2118{
Paul Berry665b8d72014-01-07 10:11:39 -08002119 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
Ian Romanick92f81592011-11-08 12:37:19 -08002120 struct gl_shader *sh = prog->_LinkedShaders[i];
2121
2122 if (sh == NULL)
2123 continue;
2124
Paul Berrybce8bc02014-01-08 10:17:01 -08002125 if (sh->num_samplers > ctx->Const.Program[i].MaxTextureImageUnits) {
Ian Romanick92f81592011-11-08 12:37:19 -08002126 linker_error(prog, "Too many %s shader texture samplers",
Paul Berry665b8d72014-01-07 10:11:39 -08002127 _mesa_shader_stage_to_string(i));
Ian Romanick92f81592011-11-08 12:37:19 -08002128 }
2129
Paul Berrybce8bc02014-01-08 10:17:01 -08002130 if (sh->num_uniform_components >
2131 ctx->Const.Program[i].MaxUniformComponents) {
Eric Anholt38e77e52013-05-23 11:10:15 -07002132 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2133 linker_warning(prog, "Too many %s shader default uniform block "
2134 "components, but the driver will try to optimize "
2135 "them out; this is non-portable out-of-spec "
2136 "behavior\n",
Paul Berry665b8d72014-01-07 10:11:39 -08002137 _mesa_shader_stage_to_string(i));
Eric Anholt38e77e52013-05-23 11:10:15 -07002138 } else {
2139 linker_error(prog, "Too many %s shader default uniform block "
2140 "components",
Paul Berry665b8d72014-01-07 10:11:39 -08002141 _mesa_shader_stage_to_string(i));
Eric Anholt38e77e52013-05-23 11:10:15 -07002142 }
2143 }
2144
2145 if (sh->num_combined_uniform_components >
Paul Berrybce8bc02014-01-08 10:17:01 -08002146 ctx->Const.Program[i].MaxCombinedUniformComponents) {
Marek Olšákdf809ae2011-12-10 04:14:46 +01002147 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2148 linker_warning(prog, "Too many %s shader uniform components, "
2149 "but the driver will try to optimize them out; "
2150 "this is non-portable out-of-spec behavior\n",
Paul Berry665b8d72014-01-07 10:11:39 -08002151 _mesa_shader_stage_to_string(i));
Marek Olšákdf809ae2011-12-10 04:14:46 +01002152 } else {
2153 linker_error(prog, "Too many %s shader uniform components",
Paul Berry665b8d72014-01-07 10:11:39 -08002154 _mesa_shader_stage_to_string(i));
Marek Olšákdf809ae2011-12-10 04:14:46 +01002155 }
Ian Romanick92f81592011-11-08 12:37:19 -08002156 }
2157 }
2158
Paul Berry665b8d72014-01-07 10:11:39 -08002159 unsigned blocks[MESA_SHADER_STAGES] = {0};
Eric Anholt877a8972012-06-25 12:47:01 -07002160 unsigned total_uniform_blocks = 0;
2161
2162 for (unsigned i = 0; i < prog->NumUniformBlocks; i++) {
Paul Berry665b8d72014-01-07 10:11:39 -08002163 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
Eric Anholt877a8972012-06-25 12:47:01 -07002164 if (prog->UniformBlockStageIndex[j][i] != -1) {
2165 blocks[j]++;
2166 total_uniform_blocks++;
2167 }
2168 }
2169
2170 if (total_uniform_blocks > ctx->Const.MaxCombinedUniformBlocks) {
2171 linker_error(prog, "Too many combined uniform blocks (%d/%d)",
2172 prog->NumUniformBlocks,
2173 ctx->Const.MaxCombinedUniformBlocks);
2174 } else {
Paul Berry665b8d72014-01-07 10:11:39 -08002175 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
Paul Berrybce8bc02014-01-08 10:17:01 -08002176 const unsigned max_uniform_blocks =
2177 ctx->Const.Program[i].MaxUniformBlocks;
2178 if (blocks[i] > max_uniform_blocks) {
Eric Anholt877a8972012-06-25 12:47:01 -07002179 linker_error(prog, "Too many %s uniform blocks (%d/%d)",
Paul Berry665b8d72014-01-07 10:11:39 -08002180 _mesa_shader_stage_to_string(i),
Eric Anholt877a8972012-06-25 12:47:01 -07002181 blocks[i],
Paul Berrybce8bc02014-01-08 10:17:01 -08002182 max_uniform_blocks);
Eric Anholt877a8972012-06-25 12:47:01 -07002183 break;
2184 }
2185 }
2186 }
2187 }
Ian Romanick92f81592011-11-08 12:37:19 -08002188}
Paul Berry871ddb92011-11-05 11:17:32 -07002189
Francisco Jereze51158f2013-11-22 15:53:26 -08002190/**
2191 * Validate shader image resources.
2192 */
2193static void
2194check_image_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2195{
2196 unsigned total_image_units = 0;
2197 unsigned fragment_outputs = 0;
2198
2199 if (!ctx->Extensions.ARB_shader_image_load_store)
2200 return;
2201
2202 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2203 struct gl_shader *sh = prog->_LinkedShaders[i];
2204
2205 if (sh) {
2206 if (sh->NumImages > ctx->Const.Program[i].MaxImageUniforms)
2207 linker_error(prog, "Too many %s shader image uniforms",
2208 _mesa_shader_stage_to_string(i));
2209
2210 total_image_units += sh->NumImages;
2211
2212 if (i == MESA_SHADER_FRAGMENT) {
2213 foreach_list(node, sh->ir) {
2214 ir_variable *var = ((ir_instruction *)node)->as_variable();
2215 if (var && var->data.mode == ir_var_shader_out)
2216 fragment_outputs += var->type->count_attribute_slots();
2217 }
2218 }
2219 }
2220 }
2221
2222 if (total_image_units > ctx->Const.MaxCombinedImageUniforms)
2223 linker_error(prog, "Too many combined image uniforms");
2224
2225 if (total_image_units + fragment_outputs >
2226 ctx->Const.MaxCombinedImageUnitsAndFragmentOutputs)
2227 linker_error(prog, "Too many combined image uniforms and fragment outputs");
2228}
2229
Tapani Pällieca9d162014-04-08 08:45:36 +03002230
2231/**
2232 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
2233 * for a variable, checks for overlaps between other uniforms using explicit
2234 * locations.
2235 */
2236static bool
2237reserve_explicit_locations(struct gl_shader_program *prog,
2238 string_to_uint_map *map, ir_variable *var)
2239{
2240 unsigned slots = var->type->uniform_locations();
2241 unsigned max_loc = var->data.location + slots - 1;
2242
2243 /* Resize remap table if locations do not fit in the current one. */
2244 if (max_loc + 1 > prog->NumUniformRemapTable) {
2245 prog->UniformRemapTable =
2246 reralloc(prog, prog->UniformRemapTable,
2247 gl_uniform_storage *,
2248 max_loc + 1);
2249
2250 if (!prog->UniformRemapTable) {
2251 linker_error(prog, "Out of memory during linking.");
2252 return false;
2253 }
2254
2255 /* Initialize allocated space. */
2256 for (unsigned i = prog->NumUniformRemapTable; i < max_loc + 1; i++)
2257 prog->UniformRemapTable[i] = NULL;
2258
2259 prog->NumUniformRemapTable = max_loc + 1;
2260 }
2261
2262 for (unsigned i = 0; i < slots; i++) {
2263 unsigned loc = var->data.location + i;
2264
2265 /* Check if location is already used. */
2266 if (prog->UniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
2267
2268 /* Possibly same uniform from a different stage, this is ok. */
2269 unsigned hash_loc;
2270 if (map->get(hash_loc, var->name) && hash_loc == loc - i)
2271 continue;
2272
2273 /* ARB_explicit_uniform_location specification states:
2274 *
2275 * "No two default-block uniform variables in the program can have
2276 * the same location, even if they are unused, otherwise a compiler
2277 * or linker error will be generated."
2278 */
2279 linker_error(prog,
2280 "location qualifier for uniform %s overlaps"
2281 "previously used location",
2282 var->name);
2283 return false;
2284 }
2285
2286 /* Initialize location as inactive before optimization
2287 * rounds and location assignment.
2288 */
2289 prog->UniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
2290 }
2291
2292 /* Note, base location used for arrays. */
2293 map->put(var->data.location, var->name);
2294
2295 return true;
2296}
2297
2298/**
2299 * Check and reserve all explicit uniform locations, called before
2300 * any optimizations happen to handle also inactive uniforms and
2301 * inactive array elements that may get trimmed away.
2302 */
2303static void
2304check_explicit_uniform_locations(struct gl_context *ctx,
2305 struct gl_shader_program *prog)
2306{
2307 if (!ctx->Extensions.ARB_explicit_uniform_location)
2308 return;
2309
2310 /* This map is used to detect if overlapping explicit locations
2311 * occur with the same uniform (from different stage) or a different one.
2312 */
2313 string_to_uint_map *uniform_map = new string_to_uint_map;
2314
2315 if (!uniform_map) {
2316 linker_error(prog, "Out of memory during linking.");
2317 return;
2318 }
2319
2320 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2321 struct gl_shader *sh = prog->_LinkedShaders[i];
2322
2323 if (!sh)
2324 continue;
2325
2326 foreach_list(node, sh->ir) {
2327 ir_variable *var = ((ir_instruction *)node)->as_variable();
2328 if ((var && var->data.mode == ir_var_uniform) &&
2329 var->data.explicit_location) {
2330 if (!reserve_explicit_locations(prog, uniform_map, var))
2331 return;
2332 }
2333 }
2334 }
2335
2336 delete uniform_map;
2337}
2338
Ian Romanick0e59b262010-06-23 11:23:01 -07002339void
Kristian Høgsbergf9995b32010-10-12 12:26:10 -04002340link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
Ian Romanick832dfa52010-06-17 15:04:20 -07002341{
Paul Berry871ddb92011-11-05 11:17:32 -07002342 tfeedback_decl *tfeedback_decls = NULL;
2343 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
2344
Kenneth Graunked3073f52011-01-21 14:32:31 -08002345 void *mem_ctx = ralloc_context(NULL); // temporary linker context
Kenneth Graunke2da02e72010-11-17 11:03:57 -08002346
Paul Berryb95d2372013-07-27 11:08:31 -07002347 prog->LinkStatus = true; /* All error paths will set this to false */
Ian Romanick832dfa52010-06-17 15:04:20 -07002348 prog->Validated = false;
2349 prog->_Used = false;
2350
Eric Anholtf609cf72012-04-27 13:52:56 -07002351 ralloc_free(prog->InfoLog);
Kenneth Graunked3073f52011-01-21 14:32:31 -08002352 prog->InfoLog = ralloc_strdup(NULL, "");
Ian Romanickf36460e2010-06-23 12:07:22 -07002353
Eric Anholtf609cf72012-04-27 13:52:56 -07002354 ralloc_free(prog->UniformBlocks);
2355 prog->UniformBlocks = NULL;
2356 prog->NumUniformBlocks = 0;
Paul Berry665b8d72014-01-07 10:11:39 -08002357 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
Eric Anholtf609cf72012-04-27 13:52:56 -07002358 ralloc_free(prog->UniformBlockStageIndex[i]);
2359 prog->UniformBlockStageIndex[i] = NULL;
2360 }
2361
Francisco Jerez5c114932013-09-11 12:14:46 -07002362 ralloc_free(prog->AtomicBuffers);
2363 prog->AtomicBuffers = NULL;
2364 prog->NumAtomicBuffers = 0;
Anuj Phogat9bcb0a82014-02-10 14:12:40 -08002365 prog->ARB_fragment_coord_conventions_enable = false;
Francisco Jerez5c114932013-09-11 12:14:46 -07002366
Ian Romanick832dfa52010-06-17 15:04:20 -07002367 /* Separate the shaders into groups based on their type.
2368 */
Paul Berrycd18ba12014-01-07 08:56:57 -08002369 struct gl_shader **shader_list[MESA_SHADER_STAGES];
2370 unsigned num_shaders[MESA_SHADER_STAGES];
Ian Romanick832dfa52010-06-17 15:04:20 -07002371
Paul Berrycd18ba12014-01-07 08:56:57 -08002372 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
2373 shader_list[i] = (struct gl_shader **)
2374 calloc(prog->NumShaders, sizeof(struct gl_shader *));
2375 num_shaders[i] = 0;
2376 }
Ian Romanick832dfa52010-06-17 15:04:20 -07002377
Ian Romanick25f51d32010-07-16 15:51:50 -07002378 unsigned min_version = UINT_MAX;
2379 unsigned max_version = 0;
Paul Berrya9f34dc2012-08-02 17:49:44 -07002380 const bool is_es_prog =
2381 (prog->NumShaders > 0 && prog->Shaders[0]->IsES) ? true : false;
Ian Romanick832dfa52010-06-17 15:04:20 -07002382 for (unsigned i = 0; i < prog->NumShaders; i++) {
Ian Romanick25f51d32010-07-16 15:51:50 -07002383 min_version = MIN2(min_version, prog->Shaders[i]->Version);
2384 max_version = MAX2(max_version, prog->Shaders[i]->Version);
2385
Paul Berrya9f34dc2012-08-02 17:49:44 -07002386 if (prog->Shaders[i]->IsES != is_es_prog) {
2387 linker_error(prog, "all shaders must use same shading "
2388 "language version\n");
2389 goto done;
2390 }
2391
Anuj Phogat9bcb0a82014-02-10 14:12:40 -08002392 prog->ARB_fragment_coord_conventions_enable |=
2393 prog->Shaders[i]->ARB_fragment_coord_conventions_enable;
2394
Paul Berrycd18ba12014-01-07 08:56:57 -08002395 gl_shader_stage shader_type = prog->Shaders[i]->Stage;
2396 shader_list[shader_type][num_shaders[shader_type]] = prog->Shaders[i];
2397 num_shaders[shader_type]++;
Ian Romanick832dfa52010-06-17 15:04:20 -07002398 }
2399
Paul Berry672fab02013-10-13 18:01:11 -07002400 /* In desktop GLSL, different shader versions may be linked together. In
2401 * GLSL ES, all shader versions must be the same.
Ian Romanick25f51d32010-07-16 15:51:50 -07002402 */
Paul Berry672fab02013-10-13 18:01:11 -07002403 if (is_es_prog && min_version != max_version) {
Ian Romanick586e7412011-07-28 14:04:09 -07002404 linker_error(prog, "all shaders must use same shading "
2405 "language version\n");
Ian Romanick25f51d32010-07-16 15:51:50 -07002406 goto done;
2407 }
2408
2409 prog->Version = max_version;
Paul Berry91c92bb2012-08-02 17:50:43 -07002410 prog->IsES = is_es_prog;
Ian Romanick25f51d32010-07-16 15:51:50 -07002411
Fabian Bielerbd85ba02013-05-24 23:26:54 +02002412 /* Geometry shaders have to be linked with vertex shaders.
2413 */
Paul Berrycd18ba12014-01-07 08:56:57 -08002414 if (num_shaders[MESA_SHADER_GEOMETRY] > 0 &&
Ian Romanickc557eb72014-01-23 18:26:29 -08002415 num_shaders[MESA_SHADER_VERTEX] == 0 &&
2416 !prog->SeparateShader) {
Fabian Bielerbd85ba02013-05-24 23:26:54 +02002417 linker_error(prog, "Geometry shader must be linked with "
2418 "vertex shader\n");
2419 goto done;
2420 }
2421
Paul Berry1fe274b2014-01-08 11:40:23 -08002422 /* Compute shaders have additional restrictions. */
2423 if (num_shaders[MESA_SHADER_COMPUTE] > 0 &&
2424 num_shaders[MESA_SHADER_COMPUTE] != prog->NumShaders) {
2425 linker_error(prog, "Compute shaders may not be linked with any other "
2426 "type of shader\n");
2427 }
2428
Paul Berry665b8d72014-01-07 10:11:39 -08002429 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
Ian Romanick3322fba2010-10-14 13:28:42 -07002430 if (prog->_LinkedShaders[i] != NULL)
2431 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
2432
2433 prog->_LinkedShaders[i] = NULL;
Eric Anholt5d0f4302010-08-18 12:02:35 -07002434 }
2435
Ian Romanickcd6764e2010-07-16 16:00:07 -07002436 /* Link all shaders for a particular stage and validate the result.
2437 */
Paul Berrycd18ba12014-01-07 08:56:57 -08002438 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
2439 if (num_shaders[stage] > 0) {
2440 gl_shader *const sh =
2441 link_intrastage_shaders(mem_ctx, ctx, prog, shader_list[stage],
2442 num_shaders[stage]);
Ian Romanick3fb87872010-07-09 14:09:34 -07002443
Paul Berrycd18ba12014-01-07 08:56:57 -08002444 if (!prog->LinkStatus)
2445 goto done;
Ian Romanick3fb87872010-07-09 14:09:34 -07002446
Paul Berrycd18ba12014-01-07 08:56:57 -08002447 switch (stage) {
2448 case MESA_SHADER_VERTEX:
2449 validate_vertex_shader_executable(prog, sh);
2450 break;
2451 case MESA_SHADER_GEOMETRY:
2452 validate_geometry_shader_executable(prog, sh);
2453 break;
2454 case MESA_SHADER_FRAGMENT:
2455 validate_fragment_shader_executable(prog, sh);
2456 break;
2457 }
2458 if (!prog->LinkStatus)
2459 goto done;
Ian Romanick3fb87872010-07-09 14:09:34 -07002460
Paul Berrycd18ba12014-01-07 08:56:57 -08002461 _mesa_reference_shader(ctx, &prog->_LinkedShaders[stage], sh);
2462 }
Ian Romanickcc22c5a2010-06-18 17:13:42 -07002463 }
2464
Paul Berrycd18ba12014-01-07 08:56:57 -08002465 if (num_shaders[MESA_SHADER_GEOMETRY] > 0)
Paul Berry44b7ebe2013-10-23 12:55:24 -07002466 prog->LastClipDistanceArraySize = prog->Geom.ClipDistanceArraySize;
Paul Berrycd18ba12014-01-07 08:56:57 -08002467 else if (num_shaders[MESA_SHADER_VERTEX] > 0)
2468 prog->LastClipDistanceArraySize = prog->Vert.ClipDistanceArraySize;
2469 else
2470 prog->LastClipDistanceArraySize = 0; /* Not used */
Bryan Cain25480922013-02-15 09:46:50 -06002471
Ian Romanick3ed850e2010-06-23 12:18:21 -07002472 /* Here begins the inter-stage linking phase. Some initial validation is
2473 * performed, then locations are assigned for uniforms, attributes, and
2474 * varyings.
2475 */
Paul Berryb95d2372013-07-27 11:08:31 -07002476 cross_validate_uniforms(prog);
2477 if (!prog->LinkStatus)
2478 goto done;
Ian Romanick3322fba2010-10-14 13:28:42 -07002479
Paul Berryb95d2372013-07-27 11:08:31 -07002480 unsigned prev;
Ian Romanick3322fba2010-10-14 13:28:42 -07002481
Paul Berry28e526d2014-01-06 19:47:25 -08002482 for (prev = 0; prev <= MESA_SHADER_FRAGMENT; prev++) {
Paul Berryb95d2372013-07-27 11:08:31 -07002483 if (prog->_LinkedShaders[prev] != NULL)
2484 break;
2485 }
Ian Romanick3322fba2010-10-14 13:28:42 -07002486
Tapani Pällieca9d162014-04-08 08:45:36 +03002487 check_explicit_uniform_locations(ctx, prog);
2488 if (!prog->LinkStatus)
2489 goto done;
2490
Paul Berryb95d2372013-07-27 11:08:31 -07002491 /* Validate the inputs of each stage with the output of the preceding
2492 * stage.
2493 */
Paul Berry28e526d2014-01-06 19:47:25 -08002494 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
Paul Berryb95d2372013-07-27 11:08:31 -07002495 if (prog->_LinkedShaders[i] == NULL)
2496 continue;
Kenneth Graunke3ddfccb2013-05-20 23:46:16 -07002497
Paul Berry544e3122013-11-15 14:23:45 -08002498 validate_interstage_inout_blocks(prog, prog->_LinkedShaders[prev],
2499 prog->_LinkedShaders[i]);
Paul Berryb95d2372013-07-27 11:08:31 -07002500 if (!prog->LinkStatus)
2501 goto done;
Ian Romanick3322fba2010-10-14 13:28:42 -07002502
Paul Berryb95d2372013-07-27 11:08:31 -07002503 cross_validate_outputs_to_inputs(prog,
2504 prog->_LinkedShaders[prev],
2505 prog->_LinkedShaders[i]);
2506 if (!prog->LinkStatus)
2507 goto done;
Ian Romanick37101922010-06-18 19:02:10 -07002508
Paul Berryb95d2372013-07-27 11:08:31 -07002509 prev = i;
Ian Romanick37101922010-06-18 19:02:10 -07002510 }
Ian Romanick832dfa52010-06-17 15:04:20 -07002511
Paul Berry544e3122013-11-15 14:23:45 -08002512 /* Cross-validate uniform blocks between shader stages */
2513 validate_interstage_uniform_blocks(prog, prog->_LinkedShaders,
Paul Berry665b8d72014-01-07 10:11:39 -08002514 MESA_SHADER_STAGES);
Paul Berry544e3122013-11-15 14:23:45 -08002515 if (!prog->LinkStatus)
2516 goto done;
Jordan Justen5ebf5472013-03-10 03:20:03 -07002517
Paul Berry665b8d72014-01-07 10:11:39 -08002518 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
Jordan Justen5ebf5472013-03-10 03:20:03 -07002519 if (prog->_LinkedShaders[i] != NULL)
2520 lower_named_interface_blocks(mem_ctx, prog->_LinkedShaders[i]);
2521 }
2522
Eric Anholt3de13952012-05-04 13:08:46 -07002523 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
2524 * it before optimization because we want most of the checks to get
2525 * dropped thanks to constant propagation.
Paul Berry15ba2a52012-08-02 17:51:02 -07002526 *
2527 * This rule also applies to GLSL ES 3.00.
Eric Anholt3de13952012-05-04 13:08:46 -07002528 */
Paul Berry15ba2a52012-08-02 17:51:02 -07002529 if (max_version >= (is_es_prog ? 300 : 130)) {
Eric Anholt3de13952012-05-04 13:08:46 -07002530 struct gl_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
2531 if (sh) {
2532 lower_discard_flow(sh->ir);
2533 }
2534 }
2535
Eric Anholtf609cf72012-04-27 13:52:56 -07002536 if (!interstage_cross_validate_uniform_blocks(prog))
2537 goto done;
2538
Eric Anholt2f4fe152010-08-10 13:06:49 -07002539 /* Do common optimization before assigning storage for attributes,
2540 * uniforms, and varyings. Later optimization could possibly make
2541 * some of that unused.
2542 */
Paul Berry665b8d72014-01-07 10:11:39 -08002543 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
Ian Romanick3322fba2010-10-14 13:28:42 -07002544 if (prog->_LinkedShaders[i] == NULL)
2545 continue;
2546
Ian Romanick02c5ae12011-07-11 10:46:01 -07002547 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
2548 if (!prog->LinkStatus)
2549 goto done;
2550
Paul Berry18392442012-12-04 11:11:02 -08002551 if (ctx->ShaderCompilerOptions[i].LowerClipDistance) {
2552 lower_clip_distance(prog->_LinkedShaders[i]);
2553 }
Paul Berryc06e3252011-08-11 20:58:21 -07002554
Kenneth Graunke169c6452014-04-06 23:25:00 -07002555 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false,
Kenneth Graunkeda222212014-04-08 15:43:46 -07002556 &ctx->ShaderCompilerOptions[i],
Kenneth Graunke169c6452014-04-06 23:25:00 -07002557 ctx->Const.NativeIntegers))
Eric Anholt2f4fe152010-08-10 13:06:49 -07002558 ;
Ian Romanicka7ba9a72010-07-20 13:36:32 -07002559 }
Ian Romanick13e10e42010-06-21 12:03:24 -07002560
Paul Berry50895d42012-12-05 07:17:07 -08002561 /* Mark all generic shader inputs and outputs as unpaired. */
Ian Romanick6bdc1d92014-02-11 16:37:56 -08002562 for (unsigned i = MESA_SHADER_VERTEX; i <= MESA_SHADER_FRAGMENT; i++) {
2563 if (prog->_LinkedShaders[i] != NULL) {
2564 link_invalidate_variable_locations(prog->_LinkedShaders[i]->ir);
2565 }
Paul Berry50895d42012-12-05 07:17:07 -08002566 }
2567
Ian Romanickd32d4f72011-06-27 17:59:58 -07002568 /* FINISHME: The value of the max_attribute_index parameter is
2569 * FINISHME: implementation dependent based on the value of
2570 * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
2571 * FINISHME: at least 16, so hardcode 16 for now.
2572 */
2573 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX, 16)) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07002574 goto done;
2575 }
2576
Dave Airlie1256a5d2012-03-24 13:33:41 +00002577 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, MAX2(ctx->Const.MaxDrawBuffers, ctx->Const.MaxDualSourceDrawBuffers))) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07002578 goto done;
Ian Romanick40e114b2010-08-17 14:55:50 -07002579 }
2580
Marek Olšák284d9542013-06-12 02:18:09 +02002581 unsigned first;
Paul Berry28e526d2014-01-06 19:47:25 -08002582 for (first = 0; first <= MESA_SHADER_FRAGMENT; first++) {
Marek Olšák284d9542013-06-12 02:18:09 +02002583 if (prog->_LinkedShaders[first] != NULL)
Ian Romanick3322fba2010-10-14 13:28:42 -07002584 break;
2585 }
2586
Paul Berry871ddb92011-11-05 11:17:32 -07002587 if (num_tfeedback_decls != 0) {
2588 /* From GL_EXT_transform_feedback:
2589 * A program will fail to link if:
2590 *
2591 * * the <count> specified by TransformFeedbackVaryingsEXT is
2592 * non-zero, but the program object has no vertex or geometry
2593 * shader;
2594 */
Bryan Cain25480922013-02-15 09:46:50 -06002595 if (first == MESA_SHADER_FRAGMENT) {
Paul Berry871ddb92011-11-05 11:17:32 -07002596 linker_error(prog, "Transform feedback varyings specified, but "
2597 "no vertex or geometry shader is present.");
2598 goto done;
2599 }
2600
2601 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
2602 prog->TransformFeedback.NumVarying);
Paul Berry456279b2011-12-26 19:39:25 -08002603 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
Paul Berry871ddb92011-11-05 11:17:32 -07002604 prog->TransformFeedback.VaryingNames,
2605 tfeedback_decls))
2606 goto done;
2607 }
2608
Marek Olšák284d9542013-06-12 02:18:09 +02002609 /* Linking the stages in the opposite order (from fragment to vertex)
2610 * ensures that inter-shader outputs written to in an earlier stage are
2611 * eliminated if they are (transitively) not used in a later stage.
2612 */
2613 int last, next;
Paul Berry28e526d2014-01-06 19:47:25 -08002614 for (last = MESA_SHADER_FRAGMENT; last >= 0; last--) {
Marek Olšák284d9542013-06-12 02:18:09 +02002615 if (prog->_LinkedShaders[last] != NULL)
2616 break;
Ian Romanick3322fba2010-10-14 13:28:42 -07002617 }
Ian Romanick13e10e42010-06-21 12:03:24 -07002618
Marek Olšák284d9542013-06-12 02:18:09 +02002619 if (last >= 0 && last < MESA_SHADER_FRAGMENT) {
2620 gl_shader *const sh = prog->_LinkedShaders[last];
2621
Ian Romanick1ff5a2b2014-02-14 12:10:27 -08002622 if (num_tfeedback_decls != 0 || prog->SeparateShader) {
Marek Olšák284d9542013-06-12 02:18:09 +02002623 /* There was no fragment shader, but we still have to assign varying
2624 * locations for use by transform feedback.
2625 */
2626 if (!assign_varying_locations(ctx, mem_ctx, prog,
2627 sh, NULL,
Paul Berry3b0cf702013-04-10 06:48:42 -07002628 num_tfeedback_decls, tfeedback_decls,
2629 0))
Marek Olšák284d9542013-06-12 02:18:09 +02002630 goto done;
2631 }
2632
Marek Olšákd13003f2013-08-09 22:34:45 +02002633 do_dead_builtin_varyings(ctx, sh, NULL,
Marek Olšákb3d8b4c2013-06-12 13:23:48 +02002634 num_tfeedback_decls, tfeedback_decls);
2635
Ian Romanick1ff5a2b2014-02-14 12:10:27 -08002636 if (!prog->SeparateShader)
2637 demote_shader_inputs_and_outputs(sh, ir_var_shader_out);
Marek Olšák284d9542013-06-12 02:18:09 +02002638
2639 /* Eliminate code that is now dead due to unused outputs being demoted.
Paul Berry871ddb92011-11-05 11:17:32 -07002640 */
Marek Olšák284d9542013-06-12 02:18:09 +02002641 while (do_dead_code(sh->ir, false))
2642 ;
2643 }
2644 else if (first == MESA_SHADER_FRAGMENT) {
Marek Olšákb3d8b4c2013-06-12 13:23:48 +02002645 /* If the program only contains a fragment shader...
Marek Olšák284d9542013-06-12 02:18:09 +02002646 */
2647 gl_shader *const sh = prog->_LinkedShaders[first];
2648
Marek Olšákd13003f2013-08-09 22:34:45 +02002649 do_dead_builtin_varyings(ctx, NULL, sh,
Marek Olšákb3d8b4c2013-06-12 13:23:48 +02002650 num_tfeedback_decls, tfeedback_decls);
2651
Ian Romanick1ff5a2b2014-02-14 12:10:27 -08002652 if (prog->SeparateShader) {
2653 if (!assign_varying_locations(ctx, mem_ctx, prog,
2654 NULL /* producer */,
2655 sh /* consumer */,
2656 0 /* num_tfeedback_decls */,
2657 NULL /* tfeedback_decls */,
2658 0 /* gs_input_vertices */))
2659 goto done;
2660 } else
2661 demote_shader_inputs_and_outputs(sh, ir_var_shader_in);
Marek Olšák284d9542013-06-12 02:18:09 +02002662
2663 while (do_dead_code(sh->ir, false))
2664 ;
2665 }
2666
2667 next = last;
2668 for (int i = next - 1; i >= 0; i--) {
2669 if (prog->_LinkedShaders[i] == NULL)
2670 continue;
2671
2672 gl_shader *const sh_i = prog->_LinkedShaders[i];
2673 gl_shader *const sh_next = prog->_LinkedShaders[next];
Paul Berry3b0cf702013-04-10 06:48:42 -07002674 unsigned gs_input_vertices =
2675 next == MESA_SHADER_GEOMETRY ? prog->Geom.VerticesIn : 0;
Marek Olšák284d9542013-06-12 02:18:09 +02002676
2677 if (!assign_varying_locations(ctx, mem_ctx, prog, sh_i, sh_next,
2678 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
Paul Berry3b0cf702013-04-10 06:48:42 -07002679 tfeedback_decls, gs_input_vertices))
Paul Berry871ddb92011-11-05 11:17:32 -07002680 goto done;
Marek Olšák284d9542013-06-12 02:18:09 +02002681
Marek Olšákd13003f2013-08-09 22:34:45 +02002682 do_dead_builtin_varyings(ctx, sh_i, sh_next,
Marek Olšákb3d8b4c2013-06-12 13:23:48 +02002683 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
2684 tfeedback_decls);
2685
Marek Olšák284d9542013-06-12 02:18:09 +02002686 demote_shader_inputs_and_outputs(sh_i, ir_var_shader_out);
2687 demote_shader_inputs_and_outputs(sh_next, ir_var_shader_in);
2688
2689 /* Eliminate code that is now dead due to unused outputs being demoted.
2690 */
2691 while (do_dead_code(sh_i->ir, false))
2692 ;
2693 while (do_dead_code(sh_next->ir, false))
2694 ;
2695
Marek Olšák3c555822013-06-13 03:17:22 +02002696 /* This must be done after all dead varyings are eliminated. */
Ian Romanick42305fb2013-09-10 12:00:34 -05002697 if (!check_against_output_limit(ctx, prog, sh_i))
2698 goto done;
2699 if (!check_against_input_limit(ctx, prog, sh_next))
Marek Olšák3c555822013-06-13 03:17:22 +02002700 goto done;
2701
Marek Olšák284d9542013-06-12 02:18:09 +02002702 next = i;
Paul Berry871ddb92011-11-05 11:17:32 -07002703 }
2704
2705 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
2706 goto done;
2707
Ian Romanick960d7222011-10-21 11:21:02 -07002708 update_array_sizes(prog);
Ian Romanick71990962011-10-18 16:01:49 -07002709 link_assign_uniform_locations(prog);
Francisco Jerez5c114932013-09-11 12:14:46 -07002710 link_assign_atomic_counter_resources(ctx, prog);
Marek Olšákec174a42011-11-18 15:00:10 +01002711 store_fragdepth_layout(prog);
Ian Romanick960d7222011-10-21 11:21:02 -07002712
Paul Berryb95d2372013-07-27 11:08:31 -07002713 check_resources(ctx, prog);
Francisco Jereze51158f2013-11-22 15:53:26 -08002714 check_image_resources(ctx, prog);
Francisco Jerez5c114932013-09-11 12:14:46 -07002715 link_check_atomic_counter_resources(ctx, prog);
2716
Paul Berryb95d2372013-07-27 11:08:31 -07002717 if (!prog->LinkStatus)
Ian Romanick92f81592011-11-08 12:37:19 -08002718 goto done;
2719
Ian Romanickce9171f2011-02-03 17:10:14 -08002720 /* OpenGL ES requires that a vertex shader and a fragment shader both be
Anuj Phogat03597cf2013-12-19 14:17:19 -08002721 * present in a linked program. GL_ARB_ES2_compatibility doesn't say
2722 * anything about shader linking when one of the shaders (vertex or
2723 * fragment shader) is absent. So, the extension shouldn't change the
2724 * behavior specified in GLSL specification.
Ian Romanickce9171f2011-02-03 17:10:14 -08002725 */
Ian Romanickf64bfb22014-03-27 10:29:30 -07002726 if (!prog->SeparateShader && ctx->API == API_OPENGLES2) {
Ian Romanickce9171f2011-02-03 17:10:14 -08002727 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
Ian Romanick586e7412011-07-28 14:04:09 -07002728 linker_error(prog, "program lacks a vertex shader\n");
Ian Romanickce9171f2011-02-03 17:10:14 -08002729 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
Ian Romanick586e7412011-07-28 14:04:09 -07002730 linker_error(prog, "program lacks a fragment shader\n");
Ian Romanickce9171f2011-02-03 17:10:14 -08002731 }
2732 }
2733
Ian Romanick13e10e42010-06-21 12:03:24 -07002734 /* FINISHME: Assign fragment shader output locations. */
2735
Ian Romanick832dfa52010-06-17 15:04:20 -07002736done:
Paul Berry665b8d72014-01-07 10:11:39 -08002737 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
Paul Berrycd18ba12014-01-07 08:56:57 -08002738 free(shader_list[i]);
Kenneth Graunke2da02e72010-11-17 11:03:57 -08002739 if (prog->_LinkedShaders[i] == NULL)
2740 continue;
2741
Paul Berryd7fa9eb2013-11-22 12:37:22 -08002742 /* Do a final validation step to make sure that the IR wasn't
2743 * invalidated by any modifications performed after intrastage linking.
2744 */
2745 validate_ir_tree(prog->_LinkedShaders[i]->ir);
2746
Kenneth Graunke2da02e72010-11-17 11:03:57 -08002747 /* Retain any live IR, but trash the rest. */
2748 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
Ian Romanick7bbcc0b2011-09-30 14:21:10 -07002749
2750 /* The symbol table in the linked shaders may contain references to
2751 * variables that were removed (e.g., unused uniforms). Since it may
2752 * contain junk, there is no possible valid use. Delete it and set the
2753 * pointer to NULL.
2754 */
2755 delete prog->_LinkedShaders[i]->symbols;
2756 prog->_LinkedShaders[i]->symbols = NULL;
Kenneth Graunke2da02e72010-11-17 11:03:57 -08002757 }
2758
Kenneth Graunked3073f52011-01-21 14:32:31 -08002759 ralloc_free(mem_ctx);
Ian Romanick832dfa52010-06-17 15:04:20 -07002760}