blob: d0445f160329e573f3794ec9eb5b51626ca0922e [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
Brian Paulddf4b2e2015-02-24 16:56:54 -070067#include <ctype.h>
Chia-I Wubfd7c9a2010-08-23 17:51:42 +080068#include "main/core.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070069#include "glsl_symbol_table.h"
Eric Anholtfaf3dba2013-06-12 16:57:11 -070070#include "glsl_parser_extras.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070071#include "ir.h"
72#include "program.h"
Aras Pranckevicius31747152010-07-29 12:40:49 +030073#include "program/hash_table.h"
Ian Romanick8fe8a812010-07-13 17:36:13 -070074#include "linker.h"
Paul Berry4b11b572012-12-17 14:20:35 -080075#include "link_varyings.h"
Ian Romanicka7ba9a72010-07-20 13:36:32 -070076#include "ir_optimization.h"
Bryan Cain25480922013-02-15 09:46:50 -060077#include "ir_rvalue_visitor.h"
Tapani Pällieca9d162014-04-08 08:45:36 +030078#include "ir_uniform.h"
Ian Romanick832dfa52010-06-17 15:04:20 -070079
Ian Romanick3322fba2010-10-14 13:28:42 -070080#include "main/shaderobj.h"
Eric Anholt6065a872013-06-12 18:12:40 -070081#include "main/enums.h"
Brian Paul241c5992014-12-15 16:41:58 -070082
Ian Romanick3322fba2010-10-14 13:28:42 -070083
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
Timothy Arcerid67515b2015-04-30 20:45:54 +1000227 var->type = glsl_type::get_array_instance(var->type->fields.array,
Paul Berry7cfefe62013-07-30 21:13:48 -0700228 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())
Timothy Arcerid67515b2015-04-30 20:45:54 +1000248 ir->type = vt->fields.array;
Paul Berry7cfefe62013-07-30 21:13:48 -0700249 return visit_continue;
250 }
251};
252
Chris Forbes7c758c52014-09-21 13:33:14 +1200253class tess_eval_array_resize_visitor : public ir_hierarchical_visitor {
254public:
255 unsigned num_vertices;
256 gl_shader_program *prog;
257
258 tess_eval_array_resize_visitor(unsigned num_vertices, gl_shader_program *prog)
259 {
260 this->num_vertices = num_vertices;
261 this->prog = prog;
262 }
263
264 virtual ~tess_eval_array_resize_visitor()
265 {
266 /* empty */
267 }
268
269 virtual ir_visitor_status visit(ir_variable *var)
270 {
271 if (!var->type->is_array() || var->data.mode != ir_var_shader_in || var->data.patch)
272 return visit_continue;
273
274 var->type = glsl_type::get_array_instance(var->type->fields.array,
275 this->num_vertices);
276 var->data.max_array_access = this->num_vertices - 1;
277
278 return visit_continue;
279 }
280
281 /* Dereferences of input variables need to be updated so that their type
282 * matches the newly assigned type of the variable they are accessing. */
283 virtual ir_visitor_status visit(ir_dereference_variable *ir)
284 {
285 ir->type = ir->var->type;
286 return visit_continue;
287 }
288
289 /* Dereferences of 2D input arrays need to be updated so that their type
290 * matches the newly assigned type of the array they are accessing. */
291 virtual ir_visitor_status visit_leave(ir_dereference_array *ir)
292 {
293 const glsl_type *const vt = ir->array->type;
294 if (vt->is_array())
295 ir->type = vt->fields.array;
296 return visit_continue;
297 }
298};
299
Chris Forbes8cf72972014-09-07 21:42:50 +1200300class barrier_use_visitor : public ir_hierarchical_visitor {
301public:
302 barrier_use_visitor(gl_shader_program *prog)
303 : prog(prog), in_main(false), after_return(false), control_flow(0)
304 {
305 }
306
307 virtual ~barrier_use_visitor()
308 {
309 /* empty */
310 }
311
312 virtual ir_visitor_status visit_enter(ir_function *ir)
313 {
314 if (strcmp(ir->name, "main") == 0)
315 in_main = true;
316
317 return visit_continue;
318 }
319
320 virtual ir_visitor_status visit_leave(ir_function *ir)
321 {
322 in_main = false;
323 after_return = false;
324 return visit_continue;
325 }
326
327 virtual ir_visitor_status visit_leave(ir_return *ir)
328 {
329 after_return = true;
330 return visit_continue;
331 }
332
333 virtual ir_visitor_status visit_enter(ir_if *ir)
334 {
335 ++control_flow;
336 return visit_continue;
337 }
338
339 virtual ir_visitor_status visit_leave(ir_if *ir)
340 {
341 --control_flow;
342 return visit_continue;
343 }
344
345 virtual ir_visitor_status visit_enter(ir_loop *ir)
346 {
347 ++control_flow;
348 return visit_continue;
349 }
350
351 virtual ir_visitor_status visit_leave(ir_loop *ir)
352 {
353 --control_flow;
354 return visit_continue;
355 }
356
357 /* FINISHME: `switch` is not expressed at the IR level -- it's already
358 * been lowered to a mess of `if`s. We'll correctly disallow any use of
359 * barrier() in a conditional path within the switch, but not in a path
360 * which is always hit.
361 */
362
363 virtual ir_visitor_status visit_enter(ir_call *ir)
364 {
365 if (ir->use_builtin && strcmp(ir->callee_name(), "barrier") == 0) {
366 /* Use of barrier(); determine if it is legal: */
367 if (!in_main) {
368 linker_error(prog, "Builtin barrier() may only be used in main");
369 return visit_stop;
370 }
371
372 if (after_return) {
373 linker_error(prog, "Builtin barrier() may not be used after return");
374 return visit_stop;
375 }
376
377 if (control_flow != 0) {
378 linker_error(prog, "Builtin barrier() may not be used inside control flow");
379 return visit_stop;
380 }
381 }
382 return visit_continue;
383 }
384
385private:
386 gl_shader_program *prog;
387 bool in_main, after_return;
388 int control_flow;
389};
390
Paul Berry1a33e022013-08-18 20:59:37 -0700391/**
Iago Toral Quiroga75896832014-06-16 16:09:53 +0200392 * Visitor that determines the highest stream id to which a (geometry) shader
393 * emits vertices. It also checks whether End{Stream}Primitive is ever called.
Paul Berry1a33e022013-08-18 20:59:37 -0700394 */
Iago Toral Quiroga75896832014-06-16 16:09:53 +0200395class find_emit_vertex_visitor : public ir_hierarchical_visitor {
Paul Berry1a33e022013-08-18 20:59:37 -0700396public:
Iago Toral Quiroga75896832014-06-16 16:09:53 +0200397 find_emit_vertex_visitor(int max_allowed)
398 : max_stream_allowed(max_allowed),
399 invalid_stream_id(0),
400 invalid_stream_id_from_emit_vertex(false),
401 end_primitive_found(false),
402 uses_non_zero_stream(false)
Paul Berry1a33e022013-08-18 20:59:37 -0700403 {
404 /* empty */
405 }
406
Iago Toral Quiroga75896832014-06-16 16:09:53 +0200407 virtual ir_visitor_status visit_leave(ir_emit_vertex *ir)
Paul Berry1a33e022013-08-18 20:59:37 -0700408 {
Iago Toral Quiroga75896832014-06-16 16:09:53 +0200409 int stream_id = ir->stream_id();
410
411 if (stream_id < 0) {
412 invalid_stream_id = stream_id;
413 invalid_stream_id_from_emit_vertex = true;
414 return visit_stop;
415 }
416
417 if (stream_id > max_stream_allowed) {
418 invalid_stream_id = stream_id;
419 invalid_stream_id_from_emit_vertex = true;
420 return visit_stop;
421 }
422
423 if (stream_id != 0)
424 uses_non_zero_stream = true;
425
426 return visit_continue;
Paul Berry1a33e022013-08-18 20:59:37 -0700427 }
428
Iago Toral Quiroga75896832014-06-16 16:09:53 +0200429 virtual ir_visitor_status visit_leave(ir_end_primitive *ir)
Paul Berry1a33e022013-08-18 20:59:37 -0700430 {
Iago Toral Quiroga75896832014-06-16 16:09:53 +0200431 end_primitive_found = true;
432
433 int stream_id = ir->stream_id();
434
435 if (stream_id < 0) {
436 invalid_stream_id = stream_id;
437 invalid_stream_id_from_emit_vertex = false;
438 return visit_stop;
439 }
440
441 if (stream_id > max_stream_allowed) {
442 invalid_stream_id = stream_id;
443 invalid_stream_id_from_emit_vertex = false;
444 return visit_stop;
445 }
446
447 if (stream_id != 0)
448 uses_non_zero_stream = true;
449
450 return visit_continue;
451 }
452
453 bool error()
454 {
455 return invalid_stream_id != 0;
456 }
457
458 const char *error_func()
459 {
460 return invalid_stream_id_from_emit_vertex ?
461 "EmitStreamVertex" : "EndStreamPrimitive";
462 }
463
464 int error_stream()
465 {
466 return invalid_stream_id;
467 }
468
469 bool uses_streams()
470 {
471 return uses_non_zero_stream;
472 }
473
474 bool uses_end_primitive()
475 {
476 return end_primitive_found;
Paul Berry1a33e022013-08-18 20:59:37 -0700477 }
478
479private:
Iago Toral Quiroga75896832014-06-16 16:09:53 +0200480 int max_stream_allowed;
481 int invalid_stream_id;
482 bool invalid_stream_id_from_emit_vertex;
483 bool end_primitive_found;
484 bool uses_non_zero_stream;
Paul Berry1a33e022013-08-18 20:59:37 -0700485};
486
Tapani Pälli9350ea62015-05-19 15:01:49 +0300487/* Class that finds array derefs and check if indexes are dynamic. */
488class dynamic_sampler_array_indexing_visitor : public ir_hierarchical_visitor
489{
490public:
491 dynamic_sampler_array_indexing_visitor() :
492 dynamic_sampler_array_indexing(false)
493 {
494 }
495
496 ir_visitor_status visit_enter(ir_dereference_array *ir)
497 {
498 if (!ir->variable_referenced())
499 return visit_continue;
500
501 if (!ir->variable_referenced()->type->contains_sampler())
502 return visit_continue;
503
504 if (!ir->array_index->constant_expression_value()) {
505 dynamic_sampler_array_indexing = true;
506 return visit_stop;
507 }
508 return visit_continue;
509 }
510
511 bool uses_dynamic_sampler_array_indexing()
512 {
513 return dynamic_sampler_array_indexing;
514 }
515
516private:
517 bool dynamic_sampler_array_indexing;
518};
519
Eric Anholt10ef9492013-09-20 11:03:44 -0700520} /* anonymous namespace */
Paul Berry1a33e022013-08-18 20:59:37 -0700521
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700522void
Ian Romanick586e7412011-07-28 14:04:09 -0700523linker_error(gl_shader_program *prog, const char *fmt, ...)
Ian Romanickf36460e2010-06-23 12:07:22 -0700524{
525 va_list ap;
526
Kenneth Graunked3073f52011-01-21 14:32:31 -0800527 ralloc_strcat(&prog->InfoLog, "error: ");
Ian Romanickf36460e2010-06-23 12:07:22 -0700528 va_start(ap, fmt);
Kenneth Graunked3073f52011-01-21 14:32:31 -0800529 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
Ian Romanickf36460e2010-06-23 12:07:22 -0700530 va_end(ap);
Ian Romanick586e7412011-07-28 14:04:09 -0700531
532 prog->LinkStatus = false;
Ian Romanickf36460e2010-06-23 12:07:22 -0700533}
534
535
536void
Ian Romanick379a32f2011-07-28 14:09:06 -0700537linker_warning(gl_shader_program *prog, const char *fmt, ...)
538{
539 va_list ap;
540
Anuj Phogat80b4a362014-03-07 16:48:35 -0800541 ralloc_strcat(&prog->InfoLog, "warning: ");
Ian Romanick379a32f2011-07-28 14:09:06 -0700542 va_start(ap, fmt);
543 ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
544 va_end(ap);
545
546}
547
548
Paul Berryb92900d2013-01-28 14:21:59 -0800549/**
550 * Given a string identifying a program resource, break it into a base name
551 * and an optional array index in square brackets.
552 *
553 * If an array index is present, \c out_base_name_end is set to point to the
554 * "[" that precedes the array index, and the array index itself is returned
555 * as a long.
556 *
557 * If no array index is present (or if the array index is negative or
558 * mal-formed), \c out_base_name_end, is set to point to the null terminator
559 * at the end of the input string, and -1 is returned.
560 *
561 * Only the final array index is parsed; if the string contains other array
562 * indices (or structure field accesses), they are left in the base name.
563 *
564 * No attempt is made to check that the base name is properly formed;
565 * typically the caller will look up the base name in a hash table, so
566 * ill-formed base names simply turn into hash table lookup failures.
567 */
568long
569parse_program_resource_name(const GLchar *name,
570 const GLchar **out_base_name_end)
571{
572 /* Section 7.3.1 ("Program Interfaces") of the OpenGL 4.3 spec says:
573 *
574 * "When an integer array element or block instance number is part of
575 * the name string, it will be specified in decimal form without a "+"
576 * or "-" sign or any extra leading zeroes. Additionally, the name
577 * string will not include white space anywhere in the string."
578 */
579
580 const size_t len = strlen(name);
581 *out_base_name_end = name + len;
582
583 if (len == 0 || name[len-1] != ']')
584 return -1;
585
586 /* Walk backwards over the string looking for a non-digit character. This
587 * had better be the opening bracket for an array index.
588 *
589 * Initially, i specifies the location of the ']'. Since the string may
590 * contain only the ']' charcater, walk backwards very carefully.
591 */
592 unsigned i;
593 for (i = len - 1; (i > 0) && isdigit(name[i-1]); --i)
594 /* empty */ ;
595
596 if ((i == 0) || name[i-1] != '[')
597 return -1;
598
599 long array_index = strtol(&name[i], NULL, 10);
600 if (array_index < 0)
601 return -1;
602
Timothy Arceri09c440c2015-07-03 08:45:30 +1000603 /* Check for leading zero */
604 if (name[i] == '0' && name[i+1] != ']')
605 return -1;
606
Paul Berryb92900d2013-01-28 14:21:59 -0800607 *out_base_name_end = name + (i - 1);
608 return array_index;
609}
610
611
Ian Romanick379a32f2011-07-28 14:09:06 -0700612void
Ian Romanick63974c02013-10-04 10:46:29 -0700613link_invalidate_variable_locations(exec_list *ir)
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700614{
Matt Turner4d784462014-06-24 21:34:05 -0700615 foreach_in_list(ir_instruction, node, ir) {
616 ir_variable *const var = node->as_variable();
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700617
Paul Berry50895d42012-12-05 07:17:07 -0800618 if (var == NULL)
619 continue;
620
Ian Romanick63974c02013-10-04 10:46:29 -0700621 /* Only assign locations for variables that lack an explicit location.
622 * Explicit locations are set for all built-in variables, generic vertex
623 * shader inputs (via layout(location=...)), and generic fragment shader
624 * outputs (also via layout(location=...)).
625 */
Tapani Pälli447bb902013-12-12 15:08:59 +0200626 if (!var->data.explicit_location) {
627 var->data.location = -1;
628 var->data.location_frac = 0;
Paul Berry50895d42012-12-05 07:17:07 -0800629 }
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700630
Ian Romanick63974c02013-10-04 10:46:29 -0700631 /* ir_variable::is_unmatched_generic_inout is used by the linker while
632 * connecting outputs from one stage to inputs of the next stage.
633 *
634 * There are two implicit assumptions here. First, we assume that any
635 * built-in variable (i.e., non-generic in or out) will have
636 * explicit_location set. Second, we assume that any generic in or out
637 * will not have explicit_location set.
638 *
639 * This second assumption will only be valid until
640 * GL_ARB_separate_shader_objects is supported. When that extension is
641 * implemented, this function will need some modifications.
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700642 */
Tapani Pälli447bb902013-12-12 15:08:59 +0200643 if (!var->data.explicit_location) {
644 var->data.is_unmatched_generic_inout = 1;
Paul Berry3e81c662012-12-05 10:47:55 -0800645 } else {
Tapani Pälli447bb902013-12-12 15:08:59 +0200646 var->data.is_unmatched_generic_inout = 0;
Paul Berry3e81c662012-12-05 10:47:55 -0800647 }
Ian Romanick0ad22cd2010-06-21 17:18:31 -0700648 }
649}
650
651
Ian Romanickc93b8f12010-06-17 15:20:22 -0700652/**
Paul Berry44e07de2013-06-11 14:11:05 -0700653 * Set UsesClipDistance and ClipDistanceArraySize based on the given shader.
654 *
655 * Also check for errors based on incorrect usage of gl_ClipVertex and
656 * gl_ClipDistance.
657 *
658 * Return false if an error was reported.
659 */
660static void
Paul Berryb30e25f2013-12-17 09:49:43 -0800661analyze_clip_usage(struct gl_shader_program *prog,
Paul Berry44e07de2013-06-11 14:11:05 -0700662 struct gl_shader *shader, GLboolean *UsesClipDistance,
663 GLuint *ClipDistanceArraySize)
664{
665 *ClipDistanceArraySize = 0;
666
667 if (!prog->IsES && prog->Version >= 130) {
668 /* From section 7.1 (Vertex Shader Special Variables) of the
669 * GLSL 1.30 spec:
670 *
671 * "It is an error for a shader to statically write both
672 * gl_ClipVertex and gl_ClipDistance."
673 *
674 * This does not apply to GLSL ES shaders, since GLSL ES defines neither
675 * gl_ClipVertex nor gl_ClipDistance.
676 */
677 find_assignment_visitor clip_vertex("gl_ClipVertex");
678 find_assignment_visitor clip_distance("gl_ClipDistance");
679
680 clip_vertex.run(shader->ir);
681 clip_distance.run(shader->ir);
682 if (clip_vertex.variable_found() && clip_distance.variable_found()) {
683 linker_error(prog, "%s shader writes to both `gl_ClipVertex' "
Paul Berryb30e25f2013-12-17 09:49:43 -0800684 "and `gl_ClipDistance'\n",
Paul Berrye3b86f02014-01-07 10:58:56 -0800685 _mesa_shader_stage_to_string(shader->Stage));
Paul Berry44e07de2013-06-11 14:11:05 -0700686 return;
687 }
688 *UsesClipDistance = clip_distance.variable_found();
689 ir_variable *clip_distance_var =
690 shader->symbols->get_variable("gl_ClipDistance");
691 if (clip_distance_var)
692 *ClipDistanceArraySize = clip_distance_var->type->length;
693 } else {
694 *UsesClipDistance = false;
695 }
696}
697
698
699/**
Paul Berry1ad54ae2011-09-17 09:42:02 -0700700 * Verify that a vertex shader executable meets all semantic requirements.
701 *
Paul Berry642e5b412012-01-04 13:57:52 -0800702 * Also sets prog->Vert.UsesClipDistance and prog->Vert.ClipDistanceArraySize
703 * as a side effect.
Ian Romanickc93b8f12010-06-17 15:20:22 -0700704 *
705 * \param shader Vertex shader executable to be verified
706 */
Paul Berryb95d2372013-07-27 11:08:31 -0700707void
Eric Anholt849e1812010-06-30 11:49:17 -0700708validate_vertex_shader_executable(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700709 struct gl_shader *shader)
Ian Romanick832dfa52010-06-17 15:04:20 -0700710{
711 if (shader == NULL)
Paul Berryb95d2372013-07-27 11:08:31 -0700712 return;
Ian Romanick832dfa52010-06-17 15:04:20 -0700713
Eric Anholtf1c1c9e2012-03-19 22:43:27 -0700714 /* From the GLSL 1.10 spec, page 48:
715 *
716 * "The variable gl_Position is available only in the vertex
717 * language and is intended for writing the homogeneous vertex
718 * position. All executions of a well-formed vertex shader
719 * executable must write a value into this variable. [...] The
720 * variable gl_Position is available only in the vertex
721 * language and is intended for writing the homogeneous vertex
722 * position. All executions of a well-formed vertex shader
723 * executable must write a value into this variable."
724 *
725 * while in GLSL 1.40 this text is changed to:
726 *
727 * "The variable gl_Position is available only in the vertex
728 * language and is intended for writing the homogeneous vertex
729 * position. It can be written at any time during shader
730 * execution. It may also be read back by a vertex shader
731 * after being written. This value will be used by primitive
732 * assembly, clipping, culling, and other fixed functionality
733 * operations, if present, that operate on primitives after
734 * vertex processing has occurred. Its value is undefined if
735 * the vertex shader executable does not write gl_Position."
Paul Berry15ba2a52012-08-02 17:51:02 -0700736 *
Kalyan Kondapally78c92012014-09-08 11:10:42 +0300737 * All GLSL ES Versions are similar to GLSL 1.40--failing to write to
738 * gl_Position is not an error.
Eric Anholtf1c1c9e2012-03-19 22:43:27 -0700739 */
Kalyan Kondapallydbc2d812014-09-10 20:20:23 -0700740 if (prog->Version < (prog->IsES ? 300 : 140)) {
Eric Anholtf1c1c9e2012-03-19 22:43:27 -0700741 find_assignment_visitor find("gl_Position");
742 find.run(shader->ir);
743 if (!find.variable_found()) {
Kalyan Kondapallydbc2d812014-09-10 20:20:23 -0700744 if (prog->IsES) {
745 linker_warning(prog,
746 "vertex shader does not write to `gl_Position'."
747 "It's value is undefined. \n");
748 } else {
749 linker_error(prog,
750 "vertex shader does not write to `gl_Position'. \n");
751 }
Paul Berryb95d2372013-07-27 11:08:31 -0700752 return;
Eric Anholtf1c1c9e2012-03-19 22:43:27 -0700753 }
Ian Romanick832dfa52010-06-17 15:04:20 -0700754 }
755
Paul Berryb30e25f2013-12-17 09:49:43 -0800756 analyze_clip_usage(prog, shader, &prog->Vert.UsesClipDistance,
Paul Berry44e07de2013-06-11 14:11:05 -0700757 &prog->Vert.ClipDistanceArraySize);
Ian Romanick832dfa52010-06-17 15:04:20 -0700758}
759
Chris Forbesdf16e0d2014-09-09 19:25:02 +1200760void
761validate_tess_eval_shader_executable(struct gl_shader_program *prog,
762 struct gl_shader *shader)
763{
764 if (shader == NULL)
765 return;
766
767 analyze_clip_usage(prog, shader, &prog->TessEval.UsesClipDistance,
768 &prog->TessEval.ClipDistanceArraySize);
769}
770
Ian Romanick832dfa52010-06-17 15:04:20 -0700771
Ian Romanickc93b8f12010-06-17 15:20:22 -0700772/**
773 * Verify that a fragment shader executable meets all semantic requirements
774 *
775 * \param shader Fragment shader executable to be verified
776 */
Paul Berryb95d2372013-07-27 11:08:31 -0700777void
Eric Anholt849e1812010-06-30 11:49:17 -0700778validate_fragment_shader_executable(struct gl_shader_program *prog,
Eric Anholt16b68b12010-06-30 11:05:43 -0700779 struct gl_shader *shader)
Ian Romanick832dfa52010-06-17 15:04:20 -0700780{
781 if (shader == NULL)
Paul Berryb95d2372013-07-27 11:08:31 -0700782 return;
Ian Romanick832dfa52010-06-17 15:04:20 -0700783
Ian Romanick832dfa52010-06-17 15:04:20 -0700784 find_assignment_visitor frag_color("gl_FragColor");
785 find_assignment_visitor frag_data("gl_FragData");
786
Eric Anholt16b68b12010-06-30 11:05:43 -0700787 frag_color.run(shader->ir);
788 frag_data.run(shader->ir);
Ian Romanick832dfa52010-06-17 15:04:20 -0700789
Ian Romanick832dfa52010-06-17 15:04:20 -0700790 if (frag_color.variable_found() && frag_data.variable_found()) {
Ian Romanick586e7412011-07-28 14:04:09 -0700791 linker_error(prog, "fragment shader writes to both "
792 "`gl_FragColor' and `gl_FragData'\n");
Ian Romanick832dfa52010-06-17 15:04:20 -0700793 }
Ian Romanick832dfa52010-06-17 15:04:20 -0700794}
795
Bryan Cain25480922013-02-15 09:46:50 -0600796/**
797 * Verify that a geometry shader executable meets all semantic requirements
798 *
Paul Berry44e07de2013-06-11 14:11:05 -0700799 * Also sets prog->Geom.VerticesIn, prog->Geom.UsesClipDistance, and
800 * prog->Geom.ClipDistanceArraySize as a side effect.
Bryan Cain25480922013-02-15 09:46:50 -0600801 *
802 * \param shader Geometry shader executable to be verified
803 */
804void
805validate_geometry_shader_executable(struct gl_shader_program *prog,
806 struct gl_shader *shader)
807{
808 if (shader == NULL)
809 return;
810
811 unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
812 prog->Geom.VerticesIn = num_vertices;
Paul Berry44e07de2013-06-11 14:11:05 -0700813
Paul Berryb30e25f2013-12-17 09:49:43 -0800814 analyze_clip_usage(prog, shader, &prog->Geom.UsesClipDistance,
Paul Berry44e07de2013-06-11 14:11:05 -0700815 &prog->Geom.ClipDistanceArraySize);
Iago Toral Quiroga75896832014-06-16 16:09:53 +0200816}
Paul Berry1a33e022013-08-18 20:59:37 -0700817
Iago Toral Quiroga75896832014-06-16 16:09:53 +0200818/**
819 * Check if geometry shaders emit to non-zero streams and do corresponding
820 * validations.
821 */
822static void
823validate_geometry_shader_emissions(struct gl_context *ctx,
824 struct gl_shader_program *prog)
825{
826 if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
827 find_emit_vertex_visitor emit_vertex(ctx->Const.MaxVertexStreams - 1);
828 emit_vertex.run(prog->_LinkedShaders[MESA_SHADER_GEOMETRY]->ir);
829 if (emit_vertex.error()) {
830 linker_error(prog, "Invalid call %s(%d). Accepted values for the "
Andres Gomezf9fc3ae2014-11-18 08:43:35 -0700831 "stream parameter are in the range [0, %d].\n",
Iago Toral Quiroga75896832014-06-16 16:09:53 +0200832 emit_vertex.error_func(),
833 emit_vertex.error_stream(),
834 ctx->Const.MaxVertexStreams - 1);
835 }
836 prog->Geom.UsesStreams = emit_vertex.uses_streams();
837 prog->Geom.UsesEndPrimitive = emit_vertex.uses_end_primitive();
838
839 /* From the ARB_gpu_shader5 spec:
840 *
841 * "Multiple vertex streams are supported only if the output primitive
842 * type is declared to be "points". A program will fail to link if it
843 * contains a geometry shader calling EmitStreamVertex() or
844 * EndStreamPrimitive() if its output primitive type is not "points".
845 *
846 * However, in the same spec:
847 *
848 * "The function EmitVertex() is equivalent to calling EmitStreamVertex()
849 * with <stream> set to zero."
850 *
851 * And:
852 *
853 * "The function EndPrimitive() is equivalent to calling
854 * EndStreamPrimitive() with <stream> set to zero."
855 *
856 * Since we can call EmitVertex() and EndPrimitive() when we output
857 * primitives other than points, calling EmitStreamVertex(0) or
858 * EmitEndPrimitive(0) should not produce errors. This it also what Nvidia
859 * does. Currently we only set prog->Geom.UsesStreams to TRUE when
860 * EmitStreamVertex() or EmitEndPrimitive() are called with a non-zero
861 * stream.
862 */
863 if (prog->Geom.UsesStreams && prog->Geom.OutputType != GL_POINTS) {
864 linker_error(prog, "EmitStreamVertex(n) and EndStreamPrimitive(n) "
Andres Gomezf9fc3ae2014-11-18 08:43:35 -0700865 "with n>0 requires point output\n");
Iago Toral Quiroga75896832014-06-16 16:09:53 +0200866 }
867 }
Bryan Cain25480922013-02-15 09:46:50 -0600868}
869
Timothy Arceri50859c62015-02-21 21:47:14 +1100870bool
871validate_intrastage_arrays(struct gl_shader_program *prog,
872 ir_variable *const var,
873 ir_variable *const existing)
874{
875 /* Consider the types to be "the same" if both types are arrays
876 * of the same type and one of the arrays is implicitly sized.
877 * In addition, set the type of the linked variable to the
878 * explicitly sized array.
879 */
880 if (var->type->is_array() && existing->type->is_array() &&
881 (var->type->fields.array == existing->type->fields.array) &&
882 ((var->type->length == 0)|| (existing->type->length == 0))) {
883 if (var->type->length != 0) {
884 if (var->type->length <= existing->data.max_array_access) {
885 linker_error(prog, "%s `%s' declared as type "
886 "`%s' but outermost dimension has an index"
887 " of `%i'\n",
888 mode_string(var),
889 var->name, var->type->name,
890 existing->data.max_array_access);
891 }
892 existing->type = var->type;
893 return true;
894 } else if (existing->type->length != 0) {
895 if(existing->type->length <= var->data.max_array_access) {
896 linker_error(prog, "%s `%s' declared as type "
897 "`%s' but outermost dimension has an index"
898 " of `%i'\n",
899 mode_string(var),
900 var->name, existing->type->name,
901 var->data.max_array_access);
902 }
903 return true;
904 }
905 }
906 return false;
907}
908
Ian Romanick832dfa52010-06-17 15:04:20 -0700909
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700910/**
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700911 * Perform validation of global variables used across multiple shaders
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700912 */
Paul Berryb95d2372013-07-27 11:08:31 -0700913void
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700914cross_validate_globals(struct gl_shader_program *prog,
915 struct gl_shader **shader_list,
916 unsigned num_shaders,
917 bool uniforms_only)
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700918{
919 /* Examine all of the uniforms in all of the shaders and cross validate
920 * them.
921 */
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700922 glsl_symbol_table variables;
923 for (unsigned i = 0; i < num_shaders; i++) {
Ian Romanick3322fba2010-10-14 13:28:42 -0700924 if (shader_list[i] == NULL)
925 continue;
926
Matt Turner4d784462014-06-24 21:34:05 -0700927 foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
928 ir_variable *const var = node->as_variable();
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700929
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700930 if (var == NULL)
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700931 continue;
932
Kristian Høgsberga78a5892015-05-13 11:17:23 +0200933 if (uniforms_only && (var->data.mode != ir_var_uniform && var->data.mode != ir_var_shader_storage))
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700934 continue;
935
Ian Romanick7e2aa912010-07-19 17:12:42 -0700936 /* Don't cross validate temporaries that are at global scope. These
937 * will eventually get pulled into the shaders 'main'.
938 */
Tapani Pälli33ee2c62013-12-12 13:51:01 +0200939 if (var->data.mode == ir_var_temporary)
Ian Romanick7e2aa912010-07-19 17:12:42 -0700940 continue;
941
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700942 /* If a global with this name has already been seen, verify that the
943 * new instance has the same type. In addition, if the globals have
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700944 * initializers, the values of the initializers must be the same.
945 */
Ian Romanicke2e5d0d2010-06-29 18:47:11 -0700946 ir_variable *const existing = variables.get_variable(var->name);
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700947 if (existing != NULL) {
Timothy Arceri50859c62015-02-21 21:47:14 +1100948 /* Check if types match. Interface blocks have some special
949 * rules so we handle those elsewhere.
950 */
Timothy Arceri1a96d9e2015-02-24 17:28:51 +1100951 if (var->type != existing->type &&
952 !var->is_interface_instance()) {
Timothy Arceri50859c62015-02-21 21:47:14 +1100953 if (!validate_intrastage_arrays(prog, var, existing)) {
954 if (var->type->is_record() && existing->type->is_record()
955 && existing->type->record_compare(var->type)) {
956 existing->type = var->type;
957 } else {
Timothy Arcerida4fb3e2014-11-25 23:04:23 +1100958 linker_error(prog, "%s `%s' declared as type "
Timothy Arceri50859c62015-02-21 21:47:14 +1100959 "`%s' and type `%s'\n",
Timothy Arcerida4fb3e2014-11-25 23:04:23 +1100960 mode_string(var),
Timothy Arceri50859c62015-02-21 21:47:14 +1100961 var->name, var->type->name,
962 existing->type->name);
Timothy Arcerida4fb3e2014-11-25 23:04:23 +1100963 return;
964 }
Ian Romanicka2711d62010-08-29 22:07:49 -0700965 }
Ian Romanickcc22c5a2010-06-18 17:13:42 -0700966 }
967
Tapani Pälli447bb902013-12-12 15:08:59 +0200968 if (var->data.explicit_location) {
969 if (existing->data.explicit_location
970 && (var->data.location != existing->data.location)) {
Ian Romanick586e7412011-07-28 14:04:09 -0700971 linker_error(prog, "explicit locations for %s "
972 "`%s' have differing values\n",
973 mode_string(var), var->name);
Paul Berryb95d2372013-07-27 11:08:31 -0700974 return;
Ian Romanick68a4fc92010-10-07 17:21:22 -0700975 }
976
Tapani Pälli447bb902013-12-12 15:08:59 +0200977 existing->data.location = var->data.location;
978 existing->data.explicit_location = true;
Ian Romanick68a4fc92010-10-07 17:21:22 -0700979 }
980
Kenneth Graunke9a9a8302013-07-16 12:18:57 -0700981 /* From the GLSL 4.20 specification:
982 * "A link error will result if two compilation units in a program
983 * specify different integer-constant bindings for the same
984 * opaque-uniform name. However, it is not an error to specify a
985 * binding on some but not all declarations for the same name"
986 */
Tapani Pälli447bb902013-12-12 15:08:59 +0200987 if (var->data.explicit_binding) {
988 if (existing->data.explicit_binding &&
989 var->data.binding != existing->data.binding) {
Kenneth Graunke9a9a8302013-07-16 12:18:57 -0700990 linker_error(prog, "explicit bindings for %s "
991 "`%s' have differing values\n",
992 mode_string(var), var->name);
Paul Berryb95d2372013-07-27 11:08:31 -0700993 return;
Kenneth Graunke9a9a8302013-07-16 12:18:57 -0700994 }
995
Tapani Pälli447bb902013-12-12 15:08:59 +0200996 existing->data.binding = var->data.binding;
997 existing->data.explicit_binding = true;
Kenneth Graunke9a9a8302013-07-16 12:18:57 -0700998 }
999
Francisco Jerez5c114932013-09-11 12:14:46 -07001000 if (var->type->contains_atomic() &&
Tapani Pälli447bb902013-12-12 15:08:59 +02001001 var->data.atomic.offset != existing->data.atomic.offset) {
Francisco Jerez5c114932013-09-11 12:14:46 -07001002 linker_error(prog, "offset specifications for %s "
1003 "`%s' have differing values\n",
1004 mode_string(var), var->name);
1005 return;
1006 }
1007
Ian Romanick46173f92011-10-31 13:07:06 -07001008 /* Validate layout qualifiers for gl_FragDepth.
1009 *
1010 * From the AMD/ARB_conservative_depth specs:
1011 *
1012 * "If gl_FragDepth is redeclared in any fragment shader in a
1013 * program, it must be redeclared in all fragment shaders in
1014 * that program that have static assignments to
1015 * gl_FragDepth. All redeclarations of gl_FragDepth in all
1016 * fragment shaders in a single program must have the same set
1017 * of qualifiers."
1018 */
1019 if (strcmp(var->name, "gl_FragDepth") == 0) {
Tapani Pälli447bb902013-12-12 15:08:59 +02001020 bool layout_declared = var->data.depth_layout != ir_depth_layout_none;
Ian Romanick46173f92011-10-31 13:07:06 -07001021 bool layout_differs =
Tapani Pälli447bb902013-12-12 15:08:59 +02001022 var->data.depth_layout != existing->data.depth_layout;
Ian Romanick46173f92011-10-31 13:07:06 -07001023
1024 if (layout_declared && layout_differs) {
1025 linker_error(prog,
1026 "All redeclarations of gl_FragDepth in all "
1027 "fragment shaders in a single program must have "
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07001028 "the same set of qualifiers.\n");
Ian Romanick46173f92011-10-31 13:07:06 -07001029 }
1030
Tapani Pälli33ee2c62013-12-12 13:51:01 +02001031 if (var->data.used && layout_differs) {
Ian Romanick46173f92011-10-31 13:07:06 -07001032 linker_error(prog,
1033 "If gl_FragDepth is redeclared with a layout "
1034 "qualifier in any fragment shader, it must be "
1035 "redeclared with the same layout qualifier in "
1036 "all fragment shaders that have assignments to "
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07001037 "gl_FragDepth\n");
Ian Romanick46173f92011-10-31 13:07:06 -07001038 }
1039 }
Chad Versaceaddae332011-01-27 01:40:31 -08001040
Ian Romanickf37b1ad2011-10-31 14:31:07 -07001041 /* Page 35 (page 41 of the PDF) of the GLSL 4.20 spec says:
1042 *
1043 * "If a shared global has multiple initializers, the
1044 * initializers must all be constant expressions, and they
1045 * must all have the same value. Otherwise, a link error will
1046 * result. (A shared global having only one initializer does
1047 * not require that initializer to be a constant expression.)"
1048 *
1049 * Previous to 4.20 the GLSL spec simply said that initializers
1050 * must have the same value. In this case of non-constant
1051 * initializers, this was impossible to determine. As a result,
1052 * no vendor actually implemented that behavior. The 4.20
1053 * behavior matches the implemented behavior of at least one other
1054 * vendor, so we'll implement that for all GLSL versions.
Ian Romanicke2e5d0d2010-06-29 18:47:11 -07001055 */
Ian Romanickf37b1ad2011-10-31 14:31:07 -07001056 if (var->constant_initializer != NULL) {
1057 if (existing->constant_initializer != NULL) {
1058 if (!var->constant_initializer->has_value(existing->constant_initializer)) {
Ian Romanick586e7412011-07-28 14:04:09 -07001059 linker_error(prog, "initializers for %s "
1060 "`%s' have differing values\n",
1061 mode_string(var), var->name);
Paul Berryb95d2372013-07-27 11:08:31 -07001062 return;
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001063 }
Ian Romanickf37b1ad2011-10-31 14:31:07 -07001064 } else {
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001065 /* If the first-seen instance of a particular uniform did not
1066 * have an initializer but a later instance does, copy the
1067 * initializer to the version stored in the symbol table.
1068 */
Ian Romanickde415b72010-07-14 13:22:12 -07001069 /* FINISHME: This is wrong. The constant_value field should
1070 * FINISHME: not be modified! Imagine a case where a shader
1071 * FINISHME: without an initializer is linked in two different
1072 * FINISHME: programs with shaders that have differing
1073 * FINISHME: initializers. Linking with the first will
1074 * FINISHME: modify the shader, and linking with the second
1075 * FINISHME: will fail.
1076 */
Ian Romanickf37b1ad2011-10-31 14:31:07 -07001077 existing->constant_initializer =
1078 var->constant_initializer->clone(ralloc_parent(existing),
1079 NULL);
1080 }
1081 }
1082
Tapani Pälli447bb902013-12-12 15:08:59 +02001083 if (var->data.has_initializer) {
1084 if (existing->data.has_initializer
Ian Romanickf37b1ad2011-10-31 14:31:07 -07001085 && (var->constant_initializer == NULL
1086 || existing->constant_initializer == NULL)) {
1087 linker_error(prog,
1088 "shared global variable `%s' has multiple "
1089 "non-constant initializers.\n",
1090 var->name);
Paul Berryb95d2372013-07-27 11:08:31 -07001091 return;
Ian Romanickf37b1ad2011-10-31 14:31:07 -07001092 }
1093
1094 /* Some instance had an initializer, so keep track of that. In
1095 * this location, all sorts of initializers (constant or
1096 * otherwise) will propagate the existence to the variable
1097 * stored in the symbol table.
1098 */
Tapani Pälli447bb902013-12-12 15:08:59 +02001099 existing->data.has_initializer = true;
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001100 }
Chad Versace7528f142010-11-17 14:34:38 -08001101
Tapani Pällic1d30802013-12-12 12:57:57 +02001102 if (existing->data.invariant != var->data.invariant) {
Ian Romanick586e7412011-07-28 14:04:09 -07001103 linker_error(prog, "declarations for %s `%s' have "
1104 "mismatching invariant qualifiers\n",
1105 mode_string(var), var->name);
Paul Berryb95d2372013-07-27 11:08:31 -07001106 return;
Chad Versace7528f142010-11-17 14:34:38 -08001107 }
Tapani Pällic1d30802013-12-12 12:57:57 +02001108 if (existing->data.centroid != var->data.centroid) {
Ian Romanick586e7412011-07-28 14:04:09 -07001109 linker_error(prog, "declarations for %s `%s' have "
1110 "mismatching centroid qualifiers\n",
1111 mode_string(var), var->name);
Paul Berryb95d2372013-07-27 11:08:31 -07001112 return;
Chad Versace61428dd2011-01-10 15:29:30 -08001113 }
Tapani Pällic1d30802013-12-12 12:57:57 +02001114 if (existing->data.sample != var->data.sample) {
Chris Forbes51c5fc82013-11-29 21:26:10 +13001115 linker_error(prog, "declarations for %s `%s` have "
1116 "mismatching sample qualifiers\n",
1117 mode_string(var), var->name);
1118 return;
1119 }
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001120 } else
Eric Anholt001eee52010-11-05 06:11:24 -07001121 variables.add_variable(var);
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001122 }
1123 }
Ian Romanickcc22c5a2010-06-18 17:13:42 -07001124}
1125
1126
Ian Romanick37101922010-06-18 19:02:10 -07001127/**
Ian Romanicke2e5d0d2010-06-29 18:47:11 -07001128 * Perform validation of uniforms used across multiple shader stages
1129 */
Paul Berryb95d2372013-07-27 11:08:31 -07001130void
Ian Romanicke2e5d0d2010-06-29 18:47:11 -07001131cross_validate_uniforms(struct gl_shader_program *prog)
1132{
Paul Berryb95d2372013-07-27 11:08:31 -07001133 cross_validate_globals(prog, prog->_LinkedShaders,
Paul Berry665b8d72014-01-07 10:11:39 -08001134 MESA_SHADER_STAGES, true);
Ian Romanicke2e5d0d2010-06-29 18:47:11 -07001135}
1136
Eric Anholtf609cf72012-04-27 13:52:56 -07001137/**
1138 * Accumulates the array of prog->UniformBlocks and checks that all
1139 * definitons of blocks agree on their contents.
1140 */
1141static bool
1142interstage_cross_validate_uniform_blocks(struct gl_shader_program *prog)
1143{
1144 unsigned max_num_uniform_blocks = 0;
Paul Berry665b8d72014-01-07 10:11:39 -08001145 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
Eric Anholtf609cf72012-04-27 13:52:56 -07001146 if (prog->_LinkedShaders[i])
1147 max_num_uniform_blocks += prog->_LinkedShaders[i]->NumUniformBlocks;
1148 }
1149
Paul Berry665b8d72014-01-07 10:11:39 -08001150 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
Eric Anholtf609cf72012-04-27 13:52:56 -07001151 struct gl_shader *sh = prog->_LinkedShaders[i];
1152
1153 prog->UniformBlockStageIndex[i] = ralloc_array(prog, int,
1154 max_num_uniform_blocks);
1155 for (unsigned int j = 0; j < max_num_uniform_blocks; j++)
1156 prog->UniformBlockStageIndex[i][j] = -1;
1157
1158 if (sh == NULL)
1159 continue;
1160
1161 for (unsigned int j = 0; j < sh->NumUniformBlocks; j++) {
1162 int index = link_cross_validate_uniform_block(prog,
1163 &prog->UniformBlocks,
1164 &prog->NumUniformBlocks,
1165 &sh->UniformBlocks[j]);
1166
1167 if (index == -1) {
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07001168 linker_error(prog, "uniform block `%s' has mismatching definitions\n",
Eric Anholtf609cf72012-04-27 13:52:56 -07001169 sh->UniformBlocks[j].Name);
1170 return false;
1171 }
1172
1173 prog->UniformBlockStageIndex[i][index] = j;
1174 }
1175 }
1176
1177 return true;
1178}
Ian Romanicke2e5d0d2010-06-29 18:47:11 -07001179
Ian Romanick37101922010-06-18 19:02:10 -07001180
Ian Romanick3fb87872010-07-09 14:09:34 -07001181/**
1182 * Populates a shaders symbol table with all global declarations
1183 */
1184static void
1185populate_symbol_table(gl_shader *sh)
1186{
1187 sh->symbols = new(sh) glsl_symbol_table;
1188
Matt Turner4d784462014-06-24 21:34:05 -07001189 foreach_in_list(ir_instruction, inst, sh->ir) {
Ian Romanick3fb87872010-07-09 14:09:34 -07001190 ir_variable *var;
1191 ir_function *func;
1192
1193 if ((func = inst->as_function()) != NULL) {
Eric Anholte8f5ebf2010-11-05 06:08:45 -07001194 sh->symbols->add_function(func);
Ian Romanick3fb87872010-07-09 14:09:34 -07001195 } else if ((var = inst->as_variable()) != NULL) {
Ian Romanicka9948242014-07-08 18:53:09 -07001196 if (var->data.mode != ir_var_temporary)
1197 sh->symbols->add_variable(var);
Ian Romanick3fb87872010-07-09 14:09:34 -07001198 }
1199 }
1200}
1201
1202
1203/**
Ian Romanick31a97862010-07-12 18:48:50 -07001204 * Remap variables referenced in an instruction tree
1205 *
1206 * This is used when instruction trees are cloned from one shader and placed in
1207 * another. These trees will contain references to \c ir_variable nodes that
1208 * do not exist in the target shader. This function finds these \c ir_variable
1209 * references and replaces the references with matching variables in the target
1210 * shader.
1211 *
1212 * If there is no matching variable in the target shader, a clone of the
1213 * \c ir_variable is made and added to the target shader. The new variable is
1214 * added to \b both the instruction stream and the symbol table.
1215 *
1216 * \param inst IR tree that is to be processed.
1217 * \param symbols Symbol table containing global scope symbols in the
1218 * linked shader.
1219 * \param instructions Instruction stream where new variable declarations
1220 * should be added.
1221 */
1222void
Eric Anholt8273bd42010-08-04 12:34:56 -07001223remap_variables(ir_instruction *inst, struct gl_shader *target,
1224 hash_table *temps)
Ian Romanick31a97862010-07-12 18:48:50 -07001225{
1226 class remap_visitor : public ir_hierarchical_visitor {
1227 public:
Eric Anholt8273bd42010-08-04 12:34:56 -07001228 remap_visitor(struct gl_shader *target,
Ian Romanick7e2aa912010-07-19 17:12:42 -07001229 hash_table *temps)
Ian Romanick31a97862010-07-12 18:48:50 -07001230 {
Eric Anholt8273bd42010-08-04 12:34:56 -07001231 this->target = target;
1232 this->symbols = target->symbols;
1233 this->instructions = target->ir;
Ian Romanick7e2aa912010-07-19 17:12:42 -07001234 this->temps = temps;
Ian Romanick31a97862010-07-12 18:48:50 -07001235 }
1236
1237 virtual ir_visitor_status visit(ir_dereference_variable *ir)
1238 {
Tapani Pälli33ee2c62013-12-12 13:51:01 +02001239 if (ir->var->data.mode == ir_var_temporary) {
Ian Romanick7e2aa912010-07-19 17:12:42 -07001240 ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
1241
1242 assert(var != NULL);
1243 ir->var = var;
1244 return visit_continue;
1245 }
1246
Ian Romanick31a97862010-07-12 18:48:50 -07001247 ir_variable *const existing =
1248 this->symbols->get_variable(ir->var->name);
1249 if (existing != NULL)
1250 ir->var = existing;
1251 else {
Eric Anholt8273bd42010-08-04 12:34:56 -07001252 ir_variable *copy = ir->var->clone(this->target, NULL);
Ian Romanick31a97862010-07-12 18:48:50 -07001253
Eric Anholt001eee52010-11-05 06:11:24 -07001254 this->symbols->add_variable(copy);
Ian Romanick31a97862010-07-12 18:48:50 -07001255 this->instructions->push_head(copy);
Ian Romanick7e2aa912010-07-19 17:12:42 -07001256 ir->var = copy;
Ian Romanick31a97862010-07-12 18:48:50 -07001257 }
1258
1259 return visit_continue;
1260 }
1261
1262 private:
Eric Anholt8273bd42010-08-04 12:34:56 -07001263 struct gl_shader *target;
Ian Romanick31a97862010-07-12 18:48:50 -07001264 glsl_symbol_table *symbols;
1265 exec_list *instructions;
Ian Romanick7e2aa912010-07-19 17:12:42 -07001266 hash_table *temps;
Ian Romanick31a97862010-07-12 18:48:50 -07001267 };
1268
Eric Anholt8273bd42010-08-04 12:34:56 -07001269 remap_visitor v(target, temps);
Ian Romanick31a97862010-07-12 18:48:50 -07001270
1271 inst->accept(&v);
1272}
1273
1274
1275/**
1276 * Move non-declarations from one instruction stream to another
1277 *
1278 * The intended usage pattern of this function is to pass the pointer to the
Eric Anholt62c47632010-07-29 13:52:25 -07001279 * 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 -07001280 * pointer) for \c last and \c false for \c make_copies on the first
1281 * call. Successive calls pass the return value of the previous call for
1282 * \c last and \c true for \c make_copies.
1283 *
1284 * \param instructions Source instruction stream
1285 * \param last Instruction after which new instructions should be
1286 * inserted in the target instruction stream
1287 * \param make_copies Flag selecting whether instructions in \c instructions
1288 * should be copied (via \c ir_instruction::clone) into the
1289 * target list or moved.
1290 *
1291 * \return
1292 * The new "last" instruction in the target instruction stream. This pointer
1293 * is suitable for use as the \c last parameter of a later call to this
1294 * function.
1295 */
1296exec_node *
1297move_non_declarations(exec_list *instructions, exec_node *last,
1298 bool make_copies, gl_shader *target)
1299{
Ian Romanick7e2aa912010-07-19 17:12:42 -07001300 hash_table *temps = NULL;
1301
1302 if (make_copies)
1303 temps = hash_table_ctor(0, hash_table_pointer_hash,
1304 hash_table_pointer_compare);
1305
Matt Turnerc6a16f62014-06-24 21:58:35 -07001306 foreach_in_list_safe(ir_instruction, inst, instructions) {
Ian Romanick7e2aa912010-07-19 17:12:42 -07001307 if (inst->as_function())
Ian Romanick31a97862010-07-12 18:48:50 -07001308 continue;
1309
Ian Romanick7e2aa912010-07-19 17:12:42 -07001310 ir_variable *var = inst->as_variable();
Tapani Pälli33ee2c62013-12-12 13:51:01 +02001311 if ((var != NULL) && (var->data.mode != ir_var_temporary))
Ian Romanick7e2aa912010-07-19 17:12:42 -07001312 continue;
1313
1314 assert(inst->as_assignment()
Kenneth Graunked884f602012-03-20 15:56:37 -07001315 || inst->as_call()
Kenneth Graunkeb45a68e2012-10-24 13:17:24 -07001316 || inst->as_if() /* for initializers with the ?: operator */
Tapani Pälli33ee2c62013-12-12 13:51:01 +02001317 || ((var != NULL) && (var->data.mode == ir_var_temporary)));
Ian Romanick31a97862010-07-12 18:48:50 -07001318
1319 if (make_copies) {
Eric Anholt8273bd42010-08-04 12:34:56 -07001320 inst = inst->clone(target, NULL);
Ian Romanick7e2aa912010-07-19 17:12:42 -07001321
1322 if (var != NULL)
1323 hash_table_insert(temps, inst, var);
1324 else
Eric Anholt8273bd42010-08-04 12:34:56 -07001325 remap_variables(inst, target, temps);
Ian Romanick31a97862010-07-12 18:48:50 -07001326 } else {
1327 inst->remove();
1328 }
1329
1330 last->insert_after(inst);
1331 last = inst;
1332 }
1333
Ian Romanick7e2aa912010-07-19 17:12:42 -07001334 if (make_copies)
1335 hash_table_dtor(temps);
1336
Ian Romanick31a97862010-07-12 18:48:50 -07001337 return last;
1338}
1339
1340/**
Ian Romanick15ce87e2010-07-09 15:28:22 -07001341 * Get the function signature for main from a shader
1342 */
Ian Romanick04d33232014-06-19 12:05:20 -07001343ir_function_signature *
1344link_get_main_function_signature(gl_shader *sh)
Ian Romanick15ce87e2010-07-09 15:28:22 -07001345{
1346 ir_function *const f = sh->symbols->get_function("main");
1347 if (f != NULL) {
1348 exec_list void_parameters;
1349
1350 /* Look for the 'void main()' signature and ensure that it's defined.
1351 * This keeps the linker from accidentally pick a shader that just
1352 * contains a prototype for main.
1353 *
1354 * We don't have to check for multiple definitions of main (in multiple
1355 * shaders) because that would have already been caught above.
1356 */
Kenneth Graunke21129d42014-07-24 14:05:40 -07001357 ir_function_signature *sig =
1358 f->matching_signature(NULL, &void_parameters, false);
Ian Romanick15ce87e2010-07-09 15:28:22 -07001359 if ((sig != NULL) && sig->is_defined) {
1360 return sig;
1361 }
1362 }
1363
1364 return NULL;
1365}
1366
1367
1368/**
Brian Paul84a12732012-02-02 20:10:40 -07001369 * This class is only used in link_intrastage_shaders() below but declaring
1370 * it inside that function leads to compiler warnings with some versions of
1371 * gcc.
1372 */
1373class array_sizing_visitor : public ir_hierarchical_visitor {
1374public:
Paul Berry15e05b92013-09-25 14:07:37 -07001375 array_sizing_visitor()
1376 : mem_ctx(ralloc_context(NULL)),
1377 unnamed_interfaces(hash_table_ctor(0, hash_table_pointer_hash,
1378 hash_table_pointer_compare))
1379 {
1380 }
1381
1382 ~array_sizing_visitor()
1383 {
1384 hash_table_dtor(this->unnamed_interfaces);
1385 ralloc_free(this->mem_ctx);
1386 }
1387
Brian Paul84a12732012-02-02 20:10:40 -07001388 virtual ir_visitor_status visit(ir_variable *var)
1389 {
Tapani Pälli447bb902013-12-12 15:08:59 +02001390 fixup_type(&var->type, var->data.max_array_access);
Paul Berrye2266692013-09-23 10:44:19 -07001391 if (var->type->is_interface()) {
1392 if (interface_contains_unsized_arrays(var->type)) {
1393 const glsl_type *new_type =
Ian Romanick21df0162014-05-23 18:57:36 -07001394 resize_interface_members(var->type,
1395 var->get_max_ifc_array_access());
Paul Berrye2266692013-09-23 10:44:19 -07001396 var->type = new_type;
1397 var->change_interface_type(new_type);
1398 }
1399 } else if (var->type->is_array() &&
1400 var->type->fields.array->is_interface()) {
1401 if (interface_contains_unsized_arrays(var->type->fields.array)) {
1402 const glsl_type *new_type =
1403 resize_interface_members(var->type->fields.array,
Ian Romanick21df0162014-05-23 18:57:36 -07001404 var->get_max_ifc_array_access());
Paul Berrye2266692013-09-23 10:44:19 -07001405 var->change_interface_type(new_type);
Timothy Arceri939dc282015-03-14 12:40:20 +11001406 var->type = update_interface_members_array(var->type, new_type);
Paul Berrye2266692013-09-23 10:44:19 -07001407 }
Paul Berry15e05b92013-09-25 14:07:37 -07001408 } else if (const glsl_type *ifc_type = var->get_interface_type()) {
1409 /* Store a pointer to the variable in the unnamed_interfaces
1410 * hashtable.
1411 */
1412 ir_variable **interface_vars = (ir_variable **)
1413 hash_table_find(this->unnamed_interfaces, ifc_type);
1414 if (interface_vars == NULL) {
1415 interface_vars = rzalloc_array(mem_ctx, ir_variable *,
1416 ifc_type->length);
1417 hash_table_insert(this->unnamed_interfaces, interface_vars,
1418 ifc_type);
1419 }
1420 unsigned index = ifc_type->field_index(var->name);
1421 assert(index < ifc_type->length);
1422 assert(interface_vars[index] == NULL);
1423 interface_vars[index] = var;
Brian Paul84a12732012-02-02 20:10:40 -07001424 }
1425 return visit_continue;
1426 }
Paul Berrye2266692013-09-23 10:44:19 -07001427
Paul Berry15e05b92013-09-25 14:07:37 -07001428 /**
1429 * For each unnamed interface block that was discovered while running the
1430 * visitor, adjust the interface type to reflect the newly assigned array
1431 * sizes, and fix up the ir_variable nodes to point to the new interface
1432 * type.
1433 */
1434 void fixup_unnamed_interface_types()
1435 {
1436 hash_table_call_foreach(this->unnamed_interfaces,
1437 fixup_unnamed_interface_type, NULL);
1438 }
1439
Paul Berrye2266692013-09-23 10:44:19 -07001440private:
1441 /**
1442 * If the type pointed to by \c type represents an unsized array, replace
1443 * it with a sized array whose size is determined by max_array_access.
1444 */
1445 static void fixup_type(const glsl_type **type, unsigned max_array_access)
1446 {
Timothy Arcerib59c5922013-10-23 21:31:27 +11001447 if ((*type)->is_unsized_array()) {
Paul Berrye2266692013-09-23 10:44:19 -07001448 *type = glsl_type::get_array_instance((*type)->fields.array,
1449 max_array_access + 1);
1450 assert(*type != NULL);
1451 }
1452 }
1453
Timothy Arceri939dc282015-03-14 12:40:20 +11001454 static const glsl_type *
1455 update_interface_members_array(const glsl_type *type,
1456 const glsl_type *new_interface_type)
1457 {
1458 const glsl_type *element_type = type->fields.array;
1459 if (element_type->is_array()) {
1460 const glsl_type *new_array_type =
1461 update_interface_members_array(element_type, new_interface_type);
1462 return glsl_type::get_array_instance(new_array_type, type->length);
1463 } else {
1464 return glsl_type::get_array_instance(new_interface_type,
1465 type->length);
1466 }
1467 }
1468
Paul Berrye2266692013-09-23 10:44:19 -07001469 /**
1470 * Determine whether the given interface type contains unsized arrays (if
1471 * it doesn't, array_sizing_visitor doesn't need to process it).
1472 */
1473 static bool interface_contains_unsized_arrays(const glsl_type *type)
1474 {
1475 for (unsigned i = 0; i < type->length; i++) {
1476 const glsl_type *elem_type = type->fields.structure[i].type;
Timothy Arcerib59c5922013-10-23 21:31:27 +11001477 if (elem_type->is_unsized_array())
Paul Berrye2266692013-09-23 10:44:19 -07001478 return true;
1479 }
1480 return false;
1481 }
1482
1483 /**
1484 * Create a new interface type based on the given type, with unsized arrays
1485 * replaced by sized arrays whose size is determined by
1486 * max_ifc_array_access.
1487 */
1488 static const glsl_type *
1489 resize_interface_members(const glsl_type *type,
1490 const unsigned *max_ifc_array_access)
1491 {
1492 unsigned num_fields = type->length;
1493 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1494 memcpy(fields, type->fields.structure,
1495 num_fields * sizeof(*fields));
1496 for (unsigned i = 0; i < num_fields; i++) {
1497 fixup_type(&fields[i].type, max_ifc_array_access[i]);
1498 }
1499 glsl_interface_packing packing =
1500 (glsl_interface_packing) type->interface_packing;
1501 const glsl_type *new_ifc_type =
1502 glsl_type::get_interface_instance(fields, num_fields,
1503 packing, type->name);
1504 delete [] fields;
1505 return new_ifc_type;
1506 }
Paul Berry15e05b92013-09-25 14:07:37 -07001507
1508 static void fixup_unnamed_interface_type(const void *key, void *data,
1509 void *)
1510 {
1511 const glsl_type *ifc_type = (const glsl_type *) key;
1512 ir_variable **interface_vars = (ir_variable **) data;
1513 unsigned num_fields = ifc_type->length;
1514 glsl_struct_field *fields = new glsl_struct_field[num_fields];
1515 memcpy(fields, ifc_type->fields.structure,
1516 num_fields * sizeof(*fields));
1517 bool interface_type_changed = false;
1518 for (unsigned i = 0; i < num_fields; i++) {
1519 if (interface_vars[i] != NULL &&
1520 fields[i].type != interface_vars[i]->type) {
1521 fields[i].type = interface_vars[i]->type;
1522 interface_type_changed = true;
1523 }
1524 }
1525 if (!interface_type_changed) {
1526 delete [] fields;
1527 return;
1528 }
1529 glsl_interface_packing packing =
1530 (glsl_interface_packing) ifc_type->interface_packing;
1531 const glsl_type *new_ifc_type =
1532 glsl_type::get_interface_instance(fields, num_fields, packing,
1533 ifc_type->name);
1534 delete [] fields;
1535 for (unsigned i = 0; i < num_fields; i++) {
1536 if (interface_vars[i] != NULL)
1537 interface_vars[i]->change_interface_type(new_ifc_type);
1538 }
1539 }
1540
1541 /**
1542 * Memory context used to allocate the data in \c unnamed_interfaces.
1543 */
1544 void *mem_ctx;
1545
1546 /**
1547 * Hash table from const glsl_type * to an array of ir_variable *'s
1548 * pointing to the ir_variables constituting each unnamed interface block.
1549 */
1550 hash_table *unnamed_interfaces;
Brian Paul84a12732012-02-02 20:10:40 -07001551};
1552
Chris Forbes7c758c52014-09-21 13:33:14 +12001553
1554/**
1555 * Performs the cross-validation of tessellation control shader vertices and
1556 * layout qualifiers for the attached tessellation control shaders,
1557 * and propagates them to the linked TCS and linked shader program.
1558 */
1559static void
1560link_tcs_out_layout_qualifiers(struct gl_shader_program *prog,
1561 struct gl_shader *linked_shader,
1562 struct gl_shader **shader_list,
1563 unsigned num_shaders)
1564{
1565 linked_shader->TessCtrl.VerticesOut = 0;
1566
1567 if (linked_shader->Stage != MESA_SHADER_TESS_CTRL)
1568 return;
1569
1570 /* From the GLSL 4.0 spec (chapter 4.3.8.2):
1571 *
1572 * "All tessellation control shader layout declarations in a program
1573 * must specify the same output patch vertex count. There must be at
1574 * least one layout qualifier specifying an output patch vertex count
1575 * in any program containing tessellation control shaders; however,
1576 * such a declaration is not required in all tessellation control
1577 * shaders."
1578 */
1579
1580 for (unsigned i = 0; i < num_shaders; i++) {
1581 struct gl_shader *shader = shader_list[i];
1582
1583 if (shader->TessCtrl.VerticesOut != 0) {
1584 if (linked_shader->TessCtrl.VerticesOut != 0 &&
1585 linked_shader->TessCtrl.VerticesOut != shader->TessCtrl.VerticesOut) {
1586 linker_error(prog, "tessellation control shader defined with "
1587 "conflicting output vertex count (%d and %d)\n",
1588 linked_shader->TessCtrl.VerticesOut,
1589 shader->TessCtrl.VerticesOut);
1590 return;
1591 }
1592 linked_shader->TessCtrl.VerticesOut = shader->TessCtrl.VerticesOut;
1593 }
1594 }
1595
1596 /* Just do the intrastage -> interstage propagation right now,
1597 * since we already know we're in the right type of shader program
1598 * for doing it.
1599 */
1600 if (linked_shader->TessCtrl.VerticesOut == 0) {
1601 linker_error(prog, "tessellation control shader didn't declare "
1602 "vertices out layout qualifier\n");
1603 return;
1604 }
1605 prog->TessCtrl.VerticesOut = linked_shader->TessCtrl.VerticesOut;
1606}
1607
1608
1609/**
1610 * Performs the cross-validation of tessellation evaluation shader
1611 * primitive type, vertex spacing, ordering and point_mode layout qualifiers
1612 * for the attached tessellation evaluation shaders, and propagates them
1613 * to the linked TES and linked shader program.
1614 */
1615static void
1616link_tes_in_layout_qualifiers(struct gl_shader_program *prog,
1617 struct gl_shader *linked_shader,
1618 struct gl_shader **shader_list,
1619 unsigned num_shaders)
1620{
1621 linked_shader->TessEval.PrimitiveMode = PRIM_UNKNOWN;
1622 linked_shader->TessEval.Spacing = 0;
1623 linked_shader->TessEval.VertexOrder = 0;
1624 linked_shader->TessEval.PointMode = -1;
1625
1626 if (linked_shader->Stage != MESA_SHADER_TESS_EVAL)
1627 return;
1628
1629 /* From the GLSL 4.0 spec (chapter 4.3.8.1):
1630 *
1631 * "At least one tessellation evaluation shader (compilation unit) in
1632 * a program must declare a primitive mode in its input layout.
1633 * Declaration vertex spacing, ordering, and point mode identifiers is
1634 * optional. It is not required that all tessellation evaluation
1635 * shaders in a program declare a primitive mode. If spacing or
1636 * vertex ordering declarations are omitted, the tessellation
1637 * primitive generator will use equal spacing or counter-clockwise
1638 * vertex ordering, respectively. If a point mode declaration is
1639 * omitted, the tessellation primitive generator will produce lines or
1640 * triangles according to the primitive mode."
1641 */
1642
1643 for (unsigned i = 0; i < num_shaders; i++) {
1644 struct gl_shader *shader = shader_list[i];
1645
1646 if (shader->TessEval.PrimitiveMode != PRIM_UNKNOWN) {
1647 if (linked_shader->TessEval.PrimitiveMode != PRIM_UNKNOWN &&
1648 linked_shader->TessEval.PrimitiveMode != shader->TessEval.PrimitiveMode) {
1649 linker_error(prog, "tessellation evaluation shader defined with "
1650 "conflicting input primitive modes.\n");
1651 return;
1652 }
1653 linked_shader->TessEval.PrimitiveMode = shader->TessEval.PrimitiveMode;
1654 }
1655
1656 if (shader->TessEval.Spacing != 0) {
1657 if (linked_shader->TessEval.Spacing != 0 &&
1658 linked_shader->TessEval.Spacing != shader->TessEval.Spacing) {
1659 linker_error(prog, "tessellation evaluation shader defined with "
1660 "conflicting vertex spacing.\n");
1661 return;
1662 }
1663 linked_shader->TessEval.Spacing = shader->TessEval.Spacing;
1664 }
1665
1666 if (shader->TessEval.VertexOrder != 0) {
1667 if (linked_shader->TessEval.VertexOrder != 0 &&
1668 linked_shader->TessEval.VertexOrder != shader->TessEval.VertexOrder) {
1669 linker_error(prog, "tessellation evaluation shader defined with "
1670 "conflicting ordering.\n");
1671 return;
1672 }
1673 linked_shader->TessEval.VertexOrder = shader->TessEval.VertexOrder;
1674 }
1675
1676 if (shader->TessEval.PointMode != -1) {
1677 if (linked_shader->TessEval.PointMode != -1 &&
1678 linked_shader->TessEval.PointMode != shader->TessEval.PointMode) {
1679 linker_error(prog, "tessellation evaluation shader defined with "
1680 "conflicting point modes.\n");
1681 return;
1682 }
1683 linked_shader->TessEval.PointMode = shader->TessEval.PointMode;
1684 }
1685
1686 }
1687
1688 /* Just do the intrastage -> interstage propagation right now,
1689 * since we already know we're in the right type of shader program
1690 * for doing it.
1691 */
1692 if (linked_shader->TessEval.PrimitiveMode == PRIM_UNKNOWN) {
1693 linker_error(prog,
1694 "tessellation evaluation shader didn't declare input "
1695 "primitive modes.\n");
1696 return;
1697 }
1698 prog->TessEval.PrimitiveMode = linked_shader->TessEval.PrimitiveMode;
1699
1700 if (linked_shader->TessEval.Spacing == 0)
1701 linked_shader->TessEval.Spacing = GL_EQUAL;
1702 prog->TessEval.Spacing = linked_shader->TessEval.Spacing;
1703
1704 if (linked_shader->TessEval.VertexOrder == 0)
1705 linked_shader->TessEval.VertexOrder = GL_CCW;
1706 prog->TessEval.VertexOrder = linked_shader->TessEval.VertexOrder;
1707
1708 if (linked_shader->TessEval.PointMode == -1)
1709 linked_shader->TessEval.PointMode = GL_FALSE;
1710 prog->TessEval.PointMode = linked_shader->TessEval.PointMode;
1711}
1712
1713
Brian Paul84a12732012-02-02 20:10:40 -07001714/**
Anuj Phogat35f11e82014-02-05 15:01:58 -08001715 * Performs the cross-validation of layout qualifiers specified in
1716 * redeclaration of gl_FragCoord for the attached fragment shaders,
1717 * and propagates them to the linked FS and linked shader program.
1718 */
1719static void
1720link_fs_input_layout_qualifiers(struct gl_shader_program *prog,
1721 struct gl_shader *linked_shader,
1722 struct gl_shader **shader_list,
1723 unsigned num_shaders)
1724{
1725 linked_shader->redeclares_gl_fragcoord = false;
1726 linked_shader->uses_gl_fragcoord = false;
1727 linked_shader->origin_upper_left = false;
1728 linked_shader->pixel_center_integer = false;
1729
Anuj Phogat9bcb0a82014-02-10 14:12:40 -08001730 if (linked_shader->Stage != MESA_SHADER_FRAGMENT ||
1731 (prog->Version < 150 && !prog->ARB_fragment_coord_conventions_enable))
Anuj Phogat35f11e82014-02-05 15:01:58 -08001732 return;
1733
1734 for (unsigned i = 0; i < num_shaders; i++) {
1735 struct gl_shader *shader = shader_list[i];
1736 /* From the GLSL 1.50 spec, page 39:
1737 *
1738 * "If gl_FragCoord is redeclared in any fragment shader in a program,
1739 * it must be redeclared in all the fragment shaders in that program
1740 * that have a static use gl_FragCoord."
Anuj Phogat35f11e82014-02-05 15:01:58 -08001741 */
1742 if ((linked_shader->redeclares_gl_fragcoord
1743 && !shader->redeclares_gl_fragcoord
Anuj Phogatd8208312015-03-05 11:07:52 -08001744 && shader->uses_gl_fragcoord)
Anuj Phogat35f11e82014-02-05 15:01:58 -08001745 || (shader->redeclares_gl_fragcoord
1746 && !linked_shader->redeclares_gl_fragcoord
Anuj Phogatd8208312015-03-05 11:07:52 -08001747 && linked_shader->uses_gl_fragcoord)) {
Anuj Phogat35f11e82014-02-05 15:01:58 -08001748 linker_error(prog, "fragment shader defined with conflicting "
1749 "layout qualifiers for gl_FragCoord\n");
1750 }
1751
1752 /* From the GLSL 1.50 spec, page 39:
1753 *
1754 * "All redeclarations of gl_FragCoord in all fragment shaders in a
1755 * single program must have the same set of qualifiers."
1756 */
1757 if (linked_shader->redeclares_gl_fragcoord && shader->redeclares_gl_fragcoord
1758 && (shader->origin_upper_left != linked_shader->origin_upper_left
1759 || shader->pixel_center_integer != linked_shader->pixel_center_integer)) {
1760 linker_error(prog, "fragment shader defined with conflicting "
1761 "layout qualifiers for gl_FragCoord\n");
1762 }
1763
Martin Peres87a4bc52015-05-21 15:51:09 +03001764 /* Update the linked shader state. Note that uses_gl_fragcoord should
1765 * accumulate the results. The other values should replace. If there
Anuj Phogat35f11e82014-02-05 15:01:58 -08001766 * are multiple redeclarations, all the fields except uses_gl_fragcoord
1767 * are already known to be the same.
1768 */
1769 if (shader->redeclares_gl_fragcoord || shader->uses_gl_fragcoord) {
1770 linked_shader->redeclares_gl_fragcoord =
1771 shader->redeclares_gl_fragcoord;
1772 linked_shader->uses_gl_fragcoord = linked_shader->uses_gl_fragcoord
1773 || shader->uses_gl_fragcoord;
1774 linked_shader->origin_upper_left = shader->origin_upper_left;
1775 linked_shader->pixel_center_integer = shader->pixel_center_integer;
1776 }
Francisco Jerezce0e1512015-01-28 17:42:37 +02001777
1778 linked_shader->EarlyFragmentTests |= shader->EarlyFragmentTests;
Anuj Phogat35f11e82014-02-05 15:01:58 -08001779 }
1780}
1781
1782/**
Eric Anholt6065a872013-06-12 18:12:40 -07001783 * Performs the cross-validation of geometry shader max_vertices and
1784 * primitive type layout qualifiers for the attached geometry shaders,
1785 * and propagates them to the linked GS and linked shader program.
1786 */
1787static void
1788link_gs_inout_layout_qualifiers(struct gl_shader_program *prog,
1789 struct gl_shader *linked_shader,
1790 struct gl_shader **shader_list,
1791 unsigned num_shaders)
1792{
1793 linked_shader->Geom.VerticesOut = 0;
Jordan Justen31340202014-01-25 02:17:21 -08001794 linked_shader->Geom.Invocations = 0;
Eric Anholt6065a872013-06-12 18:12:40 -07001795 linked_shader->Geom.InputType = PRIM_UNKNOWN;
1796 linked_shader->Geom.OutputType = PRIM_UNKNOWN;
1797
1798 /* No in/out qualifiers defined for anything but GLSL 1.50+
1799 * geometry shaders so far.
1800 */
Paul Berrye3b86f02014-01-07 10:58:56 -08001801 if (linked_shader->Stage != MESA_SHADER_GEOMETRY || prog->Version < 150)
Eric Anholt6065a872013-06-12 18:12:40 -07001802 return;
1803
1804 /* From the GLSL 1.50 spec, page 46:
1805 *
1806 * "All geometry shader output layout declarations in a program
1807 * must declare the same layout and same value for
1808 * max_vertices. There must be at least one geometry output
1809 * layout declaration somewhere in a program, but not all
1810 * geometry shaders (compilation units) are required to
1811 * declare it."
1812 */
1813
1814 for (unsigned i = 0; i < num_shaders; i++) {
1815 struct gl_shader *shader = shader_list[i];
1816
1817 if (shader->Geom.InputType != PRIM_UNKNOWN) {
1818 if (linked_shader->Geom.InputType != PRIM_UNKNOWN &&
1819 linked_shader->Geom.InputType != shader->Geom.InputType) {
1820 linker_error(prog, "geometry shader defined with conflicting "
1821 "input types\n");
1822 return;
1823 }
1824 linked_shader->Geom.InputType = shader->Geom.InputType;
1825 }
1826
1827 if (shader->Geom.OutputType != PRIM_UNKNOWN) {
1828 if (linked_shader->Geom.OutputType != PRIM_UNKNOWN &&
1829 linked_shader->Geom.OutputType != shader->Geom.OutputType) {
1830 linker_error(prog, "geometry shader defined with conflicting "
1831 "output types\n");
1832 return;
1833 }
1834 linked_shader->Geom.OutputType = shader->Geom.OutputType;
1835 }
1836
1837 if (shader->Geom.VerticesOut != 0) {
1838 if (linked_shader->Geom.VerticesOut != 0 &&
1839 linked_shader->Geom.VerticesOut != shader->Geom.VerticesOut) {
1840 linker_error(prog, "geometry shader defined with conflicting "
1841 "output vertex count (%d and %d)\n",
1842 linked_shader->Geom.VerticesOut,
1843 shader->Geom.VerticesOut);
1844 return;
1845 }
1846 linked_shader->Geom.VerticesOut = shader->Geom.VerticesOut;
1847 }
Jordan Justen31340202014-01-25 02:17:21 -08001848
1849 if (shader->Geom.Invocations != 0) {
1850 if (linked_shader->Geom.Invocations != 0 &&
1851 linked_shader->Geom.Invocations != shader->Geom.Invocations) {
1852 linker_error(prog, "geometry shader defined with conflicting "
1853 "invocation count (%d and %d)\n",
1854 linked_shader->Geom.Invocations,
1855 shader->Geom.Invocations);
1856 return;
1857 }
1858 linked_shader->Geom.Invocations = shader->Geom.Invocations;
1859 }
Eric Anholt6065a872013-06-12 18:12:40 -07001860 }
1861
1862 /* Just do the intrastage -> interstage propagation right now,
1863 * since we already know we're in the right type of shader program
1864 * for doing it.
1865 */
1866 if (linked_shader->Geom.InputType == PRIM_UNKNOWN) {
1867 linker_error(prog,
1868 "geometry shader didn't declare primitive input type\n");
1869 return;
1870 }
1871 prog->Geom.InputType = linked_shader->Geom.InputType;
1872
1873 if (linked_shader->Geom.OutputType == PRIM_UNKNOWN) {
1874 linker_error(prog,
1875 "geometry shader didn't declare primitive output type\n");
1876 return;
1877 }
1878 prog->Geom.OutputType = linked_shader->Geom.OutputType;
1879
1880 if (linked_shader->Geom.VerticesOut == 0) {
1881 linker_error(prog,
1882 "geometry shader didn't declare max_vertices\n");
1883 return;
1884 }
1885 prog->Geom.VerticesOut = linked_shader->Geom.VerticesOut;
Jordan Justen31340202014-01-25 02:17:21 -08001886
1887 if (linked_shader->Geom.Invocations == 0)
1888 linked_shader->Geom.Invocations = 1;
1889
1890 prog->Geom.Invocations = linked_shader->Geom.Invocations;
Eric Anholt6065a872013-06-12 18:12:40 -07001891}
1892
Paul Berry28ce6042014-01-08 11:59:28 -08001893
1894/**
1895 * Perform cross-validation of compute shader local_size_{x,y,z} layout
1896 * qualifiers for the attached compute shaders, and propagate them to the
1897 * linked CS and linked shader program.
1898 */
1899static void
1900link_cs_input_layout_qualifiers(struct gl_shader_program *prog,
1901 struct gl_shader *linked_shader,
1902 struct gl_shader **shader_list,
1903 unsigned num_shaders)
1904{
1905 for (int i = 0; i < 3; i++)
1906 linked_shader->Comp.LocalSize[i] = 0;
1907
1908 /* This function is called for all shader stages, but it only has an effect
1909 * for compute shaders.
1910 */
1911 if (linked_shader->Stage != MESA_SHADER_COMPUTE)
1912 return;
1913
1914 /* From the ARB_compute_shader spec, in the section describing local size
1915 * declarations:
1916 *
1917 * If multiple compute shaders attached to a single program object
1918 * declare local work-group size, the declarations must be identical;
1919 * otherwise a link-time error results. Furthermore, if a program
1920 * object contains any compute shaders, at least one must contain an
1921 * input layout qualifier specifying the local work sizes of the
1922 * program, or a link-time error will occur.
1923 */
1924 for (unsigned sh = 0; sh < num_shaders; sh++) {
1925 struct gl_shader *shader = shader_list[sh];
1926
1927 if (shader->Comp.LocalSize[0] != 0) {
1928 if (linked_shader->Comp.LocalSize[0] != 0) {
1929 for (int i = 0; i < 3; i++) {
1930 if (linked_shader->Comp.LocalSize[i] !=
1931 shader->Comp.LocalSize[i]) {
1932 linker_error(prog, "compute shader defined with conflicting "
1933 "local sizes\n");
1934 return;
1935 }
1936 }
1937 }
1938 for (int i = 0; i < 3; i++)
1939 linked_shader->Comp.LocalSize[i] = shader->Comp.LocalSize[i];
1940 }
1941 }
1942
1943 /* Just do the intrastage -> interstage propagation right now,
1944 * since we already know we're in the right type of shader program
1945 * for doing it.
1946 */
1947 if (linked_shader->Comp.LocalSize[0] == 0) {
1948 linker_error(prog, "compute shader didn't declare local size\n");
1949 return;
1950 }
1951 for (int i = 0; i < 3; i++)
1952 prog->Comp.LocalSize[i] = linked_shader->Comp.LocalSize[i];
1953}
1954
1955
Eric Anholt6065a872013-06-12 18:12:40 -07001956/**
Ian Romanick3fb87872010-07-09 14:09:34 -07001957 * Combine a group of shaders for a single stage to generate a linked shader
1958 *
1959 * \note
1960 * If this function is supplied a single shader, it is cloned, and the new
1961 * shader is returned.
1962 */
1963static struct gl_shader *
Kenneth Graunke2da02e72010-11-17 11:03:57 -08001964link_intrastage_shaders(void *mem_ctx,
1965 struct gl_context *ctx,
Eric Anholt5d0f4302010-08-18 12:02:35 -07001966 struct gl_shader_program *prog,
Ian Romanick3fb87872010-07-09 14:09:34 -07001967 struct gl_shader **shader_list,
1968 unsigned num_shaders)
1969{
Eric Anholtf609cf72012-04-27 13:52:56 -07001970 struct gl_uniform_block *uniform_blocks = NULL;
Eric Anholtf609cf72012-04-27 13:52:56 -07001971
Ian Romanick13f782c2010-06-29 18:53:38 -07001972 /* Check that global variables defined in multiple shaders are consistent.
1973 */
Paul Berryb95d2372013-07-27 11:08:31 -07001974 cross_validate_globals(prog, shader_list, num_shaders, false);
1975 if (!prog->LinkStatus)
Ian Romanick13f782c2010-06-29 18:53:38 -07001976 return NULL;
1977
Jordan Justen4a0bcd92013-05-20 23:42:49 -07001978 /* Check that interface blocks defined in multiple shaders are consistent.
1979 */
Paul Berryb95d2372013-07-27 11:08:31 -07001980 validate_intrastage_interface_blocks(prog, (const gl_shader **)shader_list,
1981 num_shaders);
1982 if (!prog->LinkStatus)
Jordan Justen4a0bcd92013-05-20 23:42:49 -07001983 return NULL;
1984
Paul Berry4682b9b2013-07-27 15:07:08 -07001985 /* Link up uniform blocks defined within this stage. */
1986 const unsigned num_uniform_blocks =
Ian Romanick514f8c72013-01-22 01:09:16 -05001987 link_uniform_blocks(mem_ctx, prog, shader_list, num_shaders,
1988 &uniform_blocks);
Juha-Pekka Heikkila088da372014-04-03 17:06:42 +03001989 if (!prog->LinkStatus)
1990 return NULL;
Eric Anholtf609cf72012-04-27 13:52:56 -07001991
Ian Romanick13f782c2010-06-29 18:53:38 -07001992 /* Check that there is only a single definition of each function signature
1993 * across all shaders.
1994 */
1995 for (unsigned i = 0; i < (num_shaders - 1); i++) {
Matt Turner4d784462014-06-24 21:34:05 -07001996 foreach_in_list(ir_instruction, node, shader_list[i]->ir) {
1997 ir_function *const f = node->as_function();
Ian Romanick13f782c2010-06-29 18:53:38 -07001998
1999 if (f == NULL)
2000 continue;
2001
2002 for (unsigned j = i + 1; j < num_shaders; j++) {
2003 ir_function *const other =
2004 shader_list[j]->symbols->get_function(f->name);
2005
2006 /* If the other shader has no function (and therefore no function
2007 * signatures) with the same name, skip to the next shader.
2008 */
2009 if (other == NULL)
2010 continue;
2011
Matt Turner4d784462014-06-24 21:34:05 -07002012 foreach_in_list(ir_function_signature, sig, &f->signatures) {
Kenneth Graunke4b0bac02013-08-30 16:12:55 -07002013 if (!sig->is_defined || sig->is_builtin())
Ian Romanick13f782c2010-06-29 18:53:38 -07002014 continue;
2015
2016 ir_function_signature *other_sig =
Kenneth Graunke3e820e32013-08-30 23:11:55 -07002017 other->exact_matching_signature(NULL, &sig->parameters);
Ian Romanick13f782c2010-06-29 18:53:38 -07002018
2019 if ((other_sig != NULL) && other_sig->is_defined
Kenneth Graunke4b0bac02013-08-30 16:12:55 -07002020 && !other_sig->is_builtin()) {
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07002021 linker_error(prog, "function `%s' is multiply defined\n",
Ian Romanick586e7412011-07-28 14:04:09 -07002022 f->name);
Ian Romanick13f782c2010-06-29 18:53:38 -07002023 return NULL;
2024 }
2025 }
2026 }
2027 }
2028 }
2029
2030 /* Find the shader that defines main, and make a clone of it.
2031 *
2032 * Starting with the clone, search for undefined references. If one is
2033 * found, find the shader that defines it. Clone the reference and add
2034 * it to the shader. Repeat until there are no undefined references or
2035 * until a reference cannot be resolved.
2036 */
Ian Romanick15ce87e2010-07-09 15:28:22 -07002037 gl_shader *main = NULL;
2038 for (unsigned i = 0; i < num_shaders; i++) {
Ian Romanick04d33232014-06-19 12:05:20 -07002039 if (link_get_main_function_signature(shader_list[i]) != NULL) {
Ian Romanick15ce87e2010-07-09 15:28:22 -07002040 main = shader_list[i];
2041 break;
2042 }
2043 }
Ian Romanick13f782c2010-06-29 18:53:38 -07002044
Ian Romanick15ce87e2010-07-09 15:28:22 -07002045 if (main == NULL) {
Ian Romanick586e7412011-07-28 14:04:09 -07002046 linker_error(prog, "%s shader lacks `main'\n",
Paul Berrye3b86f02014-01-07 10:58:56 -08002047 _mesa_shader_stage_to_string(shader_list[0]->Stage));
Ian Romanick15ce87e2010-07-09 15:28:22 -07002048 return NULL;
2049 }
2050
Ian Romanick4a455952010-10-13 15:13:02 -07002051 gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
Ian Romanick15ce87e2010-07-09 15:28:22 -07002052 linked->ir = new(linked) exec_list;
Kenneth Graunke2da02e72010-11-17 11:03:57 -08002053 clone_ir_list(mem_ctx, linked->ir, main->ir);
Ian Romanick15ce87e2010-07-09 15:28:22 -07002054
Eric Anholtf609cf72012-04-27 13:52:56 -07002055 linked->UniformBlocks = uniform_blocks;
2056 linked->NumUniformBlocks = num_uniform_blocks;
2057 ralloc_steal(linked, linked->UniformBlocks);
2058
Anuj Phogat35f11e82014-02-05 15:01:58 -08002059 link_fs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
Chris Forbes7c758c52014-09-21 13:33:14 +12002060 link_tcs_out_layout_qualifiers(prog, linked, shader_list, num_shaders);
2061 link_tes_in_layout_qualifiers(prog, linked, shader_list, num_shaders);
Eric Anholt6065a872013-06-12 18:12:40 -07002062 link_gs_inout_layout_qualifiers(prog, linked, shader_list, num_shaders);
Paul Berry28ce6042014-01-08 11:59:28 -08002063 link_cs_input_layout_qualifiers(prog, linked, shader_list, num_shaders);
Eric Anholt6065a872013-06-12 18:12:40 -07002064
Ian Romanick15ce87e2010-07-09 15:28:22 -07002065 populate_symbol_table(linked);
Ian Romanick13f782c2010-06-29 18:53:38 -07002066
Andres Gomezb0e0c262014-10-24 16:51:09 +03002067 /* The pointer to the main function in the final linked shader (i.e., the
Ian Romanick31a97862010-07-12 18:48:50 -07002068 * copy of the original shader that contained the main function).
2069 */
Ian Romanick04d33232014-06-19 12:05:20 -07002070 ir_function_signature *const main_sig =
2071 link_get_main_function_signature(linked);
Ian Romanick31a97862010-07-12 18:48:50 -07002072
2073 /* Move any instructions other than variable declarations or function
2074 * declarations into main.
2075 */
Ian Romanick9303e352010-07-19 12:33:54 -07002076 exec_node *insertion_point =
2077 move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
2078 linked);
2079
Ian Romanick31a97862010-07-12 18:48:50 -07002080 for (unsigned i = 0; i < num_shaders; i++) {
Ian Romanick9303e352010-07-19 12:33:54 -07002081 if (shader_list[i] == main)
2082 continue;
2083
Ian Romanick31a97862010-07-12 18:48:50 -07002084 insertion_point = move_non_declarations(shader_list[i]->ir,
Ian Romanick9303e352010-07-19 12:33:54 -07002085 insertion_point, true, linked);
Ian Romanick31a97862010-07-12 18:48:50 -07002086 }
2087
Kenneth Graunke5b331f62013-11-23 12:11:34 -08002088 /* Check if any shader needs built-in functions. */
2089 bool need_builtins = false;
Ian Romanickd5be2ac2010-07-20 11:29:46 -07002090 for (unsigned i = 0; i < num_shaders; i++) {
Kenneth Graunke5b331f62013-11-23 12:11:34 -08002091 if (shader_list[i]->uses_builtin_functions) {
2092 need_builtins = true;
2093 break;
2094 }
Ian Romanickd5be2ac2010-07-20 11:29:46 -07002095 }
2096
Kenneth Graunke5b331f62013-11-23 12:11:34 -08002097 bool ok;
2098 if (need_builtins) {
2099 /* Make a temporary array one larger than shader_list, which will hold
2100 * the built-in function shader as well.
2101 */
2102 gl_shader **linking_shaders = (gl_shader **)
2103 calloc(num_shaders + 1, sizeof(gl_shader *));
Ian Romanickd5be2ac2010-07-20 11:29:46 -07002104
Juha-Pekka Heikkilad2f04422014-05-07 16:20:12 +03002105 ok = linking_shaders != NULL;
Kenneth Graunke5b331f62013-11-23 12:11:34 -08002106
Juha-Pekka Heikkilad2f04422014-05-07 16:20:12 +03002107 if (ok) {
2108 memcpy(linking_shaders, shader_list, num_shaders * sizeof(gl_shader *));
2109 linking_shaders[num_shaders] = _mesa_glsl_get_builtin_function_shader();
2110
2111 ok = link_function_calls(prog, linked, linking_shaders, num_shaders + 1);
2112
2113 free(linking_shaders);
2114 } else {
2115 _mesa_error_no_memory(__func__);
2116 }
Kenneth Graunke5b331f62013-11-23 12:11:34 -08002117 } else {
2118 ok = link_function_calls(prog, linked, shader_list, num_shaders);
2119 }
2120
2121
2122 if (!ok) {
2123 ctx->Driver.DeleteShader(ctx, linked);
Kenneth Graunke7d2423a2013-08-02 00:35:05 -07002124 return NULL;
Ian Romanick4a455952010-10-13 15:13:02 -07002125 }
Ian Romanickd5be2ac2010-07-20 11:29:46 -07002126
Paul Berryc148ef62011-08-03 15:37:01 -07002127 /* At this point linked should contain all of the linked IR, so
2128 * validate it to make sure nothing went wrong.
2129 */
Kenneth Graunke7d2423a2013-08-02 00:35:05 -07002130 validate_ir_tree(linked->ir);
Paul Berryc148ef62011-08-03 15:37:01 -07002131
Paul Berry7cfefe62013-07-30 21:13:48 -07002132 /* Set the size of geometry shader input arrays */
Paul Berrye3b86f02014-01-07 10:58:56 -08002133 if (linked->Stage == MESA_SHADER_GEOMETRY) {
Paul Berry7cfefe62013-07-30 21:13:48 -07002134 unsigned num_vertices = vertices_per_prim(prog->Geom.InputType);
2135 geom_array_resize_visitor input_resize_visitor(num_vertices, prog);
Matt Turner4d784462014-06-24 21:34:05 -07002136 foreach_in_list(ir_instruction, ir, linked->ir) {
Paul Berry7cfefe62013-07-30 21:13:48 -07002137 ir->accept(&input_resize_visitor);
2138 }
2139 }
2140
Ian Romanickec08b5e2014-06-19 12:06:42 -07002141 if (ctx->Const.VertexID_is_zero_based)
2142 lower_vertex_id(linked);
2143
Chris Forbes8cf72972014-09-07 21:42:50 +12002144 /* Validate correct usage of barrier() in the tess control shader */
2145 if (linked->Stage == MESA_SHADER_TESS_CTRL) {
2146 barrier_use_visitor visitor(prog);
2147 foreach_in_list(ir_instruction, ir, linked->ir) {
2148 ir->accept(&visitor);
2149 }
2150 }
2151
Ian Romanickc87e9ef2011-01-25 12:04:08 -08002152 /* Make a pass over all variable declarations to ensure that arrays with
Ian Romanick6f539212010-12-07 18:30:33 -08002153 * unspecified sizes have a size specified. The size is inferred from the
2154 * max_array_access field.
2155 */
Kenneth Graunke7d2423a2013-08-02 00:35:05 -07002156 array_sizing_visitor v;
2157 v.run(linked->ir);
Paul Berry15e05b92013-09-25 14:07:37 -07002158 v.fixup_unnamed_interface_types();
Ian Romanick6f539212010-12-07 18:30:33 -08002159
Ian Romanick3fb87872010-07-09 14:09:34 -07002160 return linked;
2161}
2162
Eric Anholta721abf2010-08-23 10:32:01 -07002163/**
2164 * Update the sizes of linked shader uniform arrays to the maximum
2165 * array index used.
2166 *
2167 * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
2168 *
2169 * If one or more elements of an array are active,
2170 * GetActiveUniform will return the name of the array in name,
2171 * subject to the restrictions listed above. The type of the array
2172 * is returned in type. The size parameter contains the highest
2173 * array element index used, plus one. The compiler or linker
2174 * determines the highest index used. There will be only one
2175 * active uniform reported by the GL per uniform array.
2176
2177 */
2178static void
Eric Anholt586b4b52010-09-28 14:32:16 -07002179update_array_sizes(struct gl_shader_program *prog)
Eric Anholta721abf2010-08-23 10:32:01 -07002180{
Paul Berry665b8d72014-01-07 10:11:39 -08002181 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
Ian Romanick3322fba2010-10-14 13:28:42 -07002182 if (prog->_LinkedShaders[i] == NULL)
2183 continue;
2184
Matt Turner4d784462014-06-24 21:34:05 -07002185 foreach_in_list(ir_instruction, node, prog->_LinkedShaders[i]->ir) {
2186 ir_variable *const var = node->as_variable();
Eric Anholta721abf2010-08-23 10:32:01 -07002187
Tapani Pälli33ee2c62013-12-12 13:51:01 +02002188 if ((var == NULL) || (var->data.mode != ir_var_uniform) ||
Eric Anholta721abf2010-08-23 10:32:01 -07002189 !var->type->is_array())
2190 continue;
2191
Eric Anholt9feb4032012-05-01 14:43:31 -07002192 /* GL_ARB_uniform_buffer_object says that std140 uniforms
2193 * will not be eliminated. Since we always do std140, just
2194 * don't resize arrays in UBOs.
Francisco Jerez5c114932013-09-11 12:14:46 -07002195 *
2196 * Atomic counters are supposed to get deterministic
2197 * locations assigned based on the declaration ordering and
2198 * sizes, array compaction would mess that up.
Eric Anholt9feb4032012-05-01 14:43:31 -07002199 */
Iago Toral Quiroga11466962015-06-05 09:11:53 +02002200 if (var->is_in_buffer_block() || var->type->contains_atomic())
Eric Anholt9feb4032012-05-01 14:43:31 -07002201 continue;
2202
Tapani Pälli447bb902013-12-12 15:08:59 +02002203 unsigned int size = var->data.max_array_access;
Paul Berry665b8d72014-01-07 10:11:39 -08002204 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
Ian Romanick3322fba2010-10-14 13:28:42 -07002205 if (prog->_LinkedShaders[j] == NULL)
2206 continue;
2207
Matt Turner4d784462014-06-24 21:34:05 -07002208 foreach_in_list(ir_instruction, node2, prog->_LinkedShaders[j]->ir) {
2209 ir_variable *other_var = node2->as_variable();
Eric Anholta721abf2010-08-23 10:32:01 -07002210 if (!other_var)
2211 continue;
2212
2213 if (strcmp(var->name, other_var->name) == 0 &&
Tapani Pälli447bb902013-12-12 15:08:59 +02002214 other_var->data.max_array_access > size) {
2215 size = other_var->data.max_array_access;
Eric Anholta721abf2010-08-23 10:32:01 -07002216 }
2217 }
2218 }
Eric Anholt586b4b52010-09-28 14:32:16 -07002219
Fabian Bieler63684782013-06-14 13:37:07 +02002220 if (size + 1 != var->type->length) {
Ian Romanick89d81ab2011-01-25 10:41:20 -08002221 /* If this is a built-in uniform (i.e., it's backed by some
2222 * fixed-function state), adjust the number of state slots to
2223 * match the new array size. The number of slots per array entry
Bryan Cainf18a0862011-04-23 19:29:15 -05002224 * is not known. It seems safe to assume that the total number of
Ian Romanick89d81ab2011-01-25 10:41:20 -08002225 * slots is an integer multiple of the number of array elements.
2226 * Determine the number of slots per array element by dividing by
2227 * the old (total) size.
2228 */
Ian Romanick5aa8d812014-05-14 19:47:28 -07002229 const unsigned num_slots = var->get_num_state_slots();
2230 if (num_slots > 0) {
2231 var->set_num_state_slots((size + 1)
2232 * (num_slots / var->type->length));
Ian Romanick89d81ab2011-01-25 10:41:20 -08002233 }
2234
Eric Anholta721abf2010-08-23 10:32:01 -07002235 var->type = glsl_type::get_array_instance(var->type->fields.array,
2236 size + 1);
2237 /* FINISHME: We should update the types of array
2238 * dereferences of this variable now.
2239 */
2240 }
2241 }
2242 }
2243}
2244
Ian Romanick69846702010-06-22 17:29:19 -07002245/**
Chris Forbes7c758c52014-09-21 13:33:14 +12002246 * Resize tessellation evaluation per-vertex inputs to the size of
2247 * tessellation control per-vertex outputs.
2248 */
2249static void
2250resize_tes_inputs(struct gl_context *ctx,
2251 struct gl_shader_program *prog)
2252{
2253 if (prog->_LinkedShaders[MESA_SHADER_TESS_EVAL] == NULL)
2254 return;
2255
2256 gl_shader *const tcs = prog->_LinkedShaders[MESA_SHADER_TESS_CTRL];
2257 gl_shader *const tes = prog->_LinkedShaders[MESA_SHADER_TESS_EVAL];
2258
2259 /* If no control shader is present, then the TES inputs are statically
2260 * sized to MaxPatchVertices; the actual size of the arrays won't be
2261 * known until draw time.
2262 */
2263 const int num_vertices = tcs
2264 ? tcs->TessCtrl.VerticesOut
2265 : ctx->Const.MaxPatchVertices;
2266
2267 tess_eval_array_resize_visitor input_resize_visitor(num_vertices, prog);
2268 foreach_in_list(ir_instruction, ir, tes->ir) {
2269 ir->accept(&input_resize_visitor);
2270 }
2271}
2272
2273/**
Bryan Cainf18a0862011-04-23 19:29:15 -05002274 * Find a contiguous set of available bits in a bitmask.
Ian Romanick69846702010-06-22 17:29:19 -07002275 *
2276 * \param used_mask Bits representing used (1) and unused (0) locations
2277 * \param needed_count Number of contiguous bits needed.
2278 *
2279 * \return
2280 * Base location of the available bits on success or -1 on failure.
2281 */
2282int
2283find_available_slots(unsigned used_mask, unsigned needed_count)
2284{
2285 unsigned needed_mask = (1 << needed_count) - 1;
2286 const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
2287
2288 /* The comparison to 32 is redundant, but without it GCC emits "warning:
2289 * cannot optimize possibly infinite loops" for the loop below.
2290 */
2291 if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
2292 return -1;
2293
2294 for (int i = 0; i <= max_bit_to_test; i++) {
2295 if ((needed_mask & ~used_mask) == needed_mask)
2296 return i;
2297
2298 needed_mask <<= 1;
2299 }
2300
2301 return -1;
2302}
2303
2304
Ian Romanickd32d4f72011-06-27 17:59:58 -07002305/**
Andres Gomezb0e0c262014-10-24 16:51:09 +03002306 * Assign locations for either VS inputs or FS outputs
Ian Romanickd32d4f72011-06-27 17:59:58 -07002307 *
2308 * \param prog Shader program whose variables need locations assigned
2309 * \param target_index Selector for the program target to receive location
2310 * assignmnets. Must be either \c MESA_SHADER_VERTEX or
2311 * \c MESA_SHADER_FRAGMENT.
2312 * \param max_index Maximum number of generic locations. This corresponds
2313 * to either the maximum number of draw buffers or the
2314 * maximum number of generic attributes.
2315 *
2316 * \return
2317 * If locations are successfully assigned, true is returned. Otherwise an
2318 * error is emitted to the shader link log and false is returned.
Ian Romanickd32d4f72011-06-27 17:59:58 -07002319 */
Ian Romanick69846702010-06-22 17:29:19 -07002320bool
Ian Romanickd32d4f72011-06-27 17:59:58 -07002321assign_attribute_or_color_locations(gl_shader_program *prog,
2322 unsigned target_index,
2323 unsigned max_index)
Ian Romanick0ad22cd2010-06-21 17:18:31 -07002324{
Ian Romanickd32d4f72011-06-27 17:59:58 -07002325 /* Mark invalid locations as being used.
Ian Romanick9342d262010-06-22 17:41:37 -07002326 */
Ian Romanickd32d4f72011-06-27 17:59:58 -07002327 unsigned used_locations = (max_index >= 32)
2328 ? ~0 : ~((1 << max_index) - 1);
Ian Romanick0ad22cd2010-06-21 17:18:31 -07002329
Ian Romanickd32d4f72011-06-27 17:59:58 -07002330 assert((target_index == MESA_SHADER_VERTEX)
2331 || (target_index == MESA_SHADER_FRAGMENT));
2332
2333 gl_shader *const sh = prog->_LinkedShaders[target_index];
2334 if (sh == NULL)
2335 return true;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07002336
Ian Romanick69846702010-06-22 17:29:19 -07002337 /* Operate in a total of four passes.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07002338 *
2339 * 1. Invalidate the location assignments for all vertex shader inputs.
2340 *
2341 * 2. Assign locations for inputs that have user-defined (via
Ian Romanickb12b5d92011-11-04 16:08:52 -07002342 * glBindVertexAttribLocation) locations and outputs that have
2343 * user-defined locations (via glBindFragDataLocation).
Ian Romanick0ad22cd2010-06-21 17:18:31 -07002344 *
Ian Romanick69846702010-06-22 17:29:19 -07002345 * 3. Sort the attributes without assigned locations by number of slots
2346 * required in decreasing order. Fragmentation caused by attribute
2347 * locations assigned by the application may prevent large attributes
2348 * from having enough contiguous space.
2349 *
2350 * 4. Assign locations to any inputs without assigned locations.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07002351 */
2352
Ian Romanickd32d4f72011-06-27 17:59:58 -07002353 const int generic_base = (target_index == MESA_SHADER_VERTEX)
Brian Paul7eb7d672011-07-07 16:47:59 -06002354 ? (int) VERT_ATTRIB_GENERIC0 : (int) FRAG_RESULT_DATA0;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07002355
Ian Romanickd32d4f72011-06-27 17:59:58 -07002356 const enum ir_variable_mode direction =
Paul Berry42a29d82013-01-11 14:39:32 -08002357 (target_index == MESA_SHADER_VERTEX)
2358 ? ir_var_shader_in : ir_var_shader_out;
Ian Romanickd32d4f72011-06-27 17:59:58 -07002359
2360
Ian Romanick69846702010-06-22 17:29:19 -07002361 /* Temporary storage for the set of attributes that need locations assigned.
2362 */
2363 struct temp_attr {
2364 unsigned slots;
2365 ir_variable *var;
2366
2367 /* Used below in the call to qsort. */
2368 static int compare(const void *a, const void *b)
2369 {
2370 const temp_attr *const l = (const temp_attr *) a;
2371 const temp_attr *const r = (const temp_attr *) b;
2372
2373 /* Reversed because we want a descending order sort below. */
2374 return r->slots - l->slots;
2375 }
2376 } to_assign[16];
2377
2378 unsigned num_attr = 0;
Dave Airliead208d92015-04-30 10:42:06 +10002379 unsigned total_attribs_size = 0;
Ian Romanick69846702010-06-22 17:29:19 -07002380
Matt Turner4d784462014-06-24 21:34:05 -07002381 foreach_in_list(ir_instruction, node, sh->ir) {
2382 ir_variable *const var = node->as_variable();
Ian Romanick0ad22cd2010-06-21 17:18:31 -07002383
Tapani Pälli33ee2c62013-12-12 13:51:01 +02002384 if ((var == NULL) || (var->data.mode != (unsigned) direction))
Ian Romanick0ad22cd2010-06-21 17:18:31 -07002385 continue;
2386
Tapani Pälli447bb902013-12-12 15:08:59 +02002387 if (var->data.explicit_location) {
2388 if ((var->data.location >= (int)(max_index + generic_base))
2389 || (var->data.location < 0)) {
Ian Romanick586e7412011-07-28 14:04:09 -07002390 linker_error(prog,
2391 "invalid explicit location %d specified for `%s'\n",
Tapani Pälli447bb902013-12-12 15:08:59 +02002392 (var->data.location < 0)
2393 ? var->data.location
2394 : var->data.location - generic_base,
Ian Romanick586e7412011-07-28 14:04:09 -07002395 var->name);
Ian Romanick68a4fc92010-10-07 17:21:22 -07002396 return false;
Ian Romanick523b6112011-08-17 15:40:03 -07002397 }
2398 } else if (target_index == MESA_SHADER_VERTEX) {
2399 unsigned binding;
2400
2401 if (prog->AttributeBindings->get(binding, var->name)) {
2402 assert(binding >= VERT_ATTRIB_GENERIC0);
Tapani Pälli447bb902013-12-12 15:08:59 +02002403 var->data.location = binding;
2404 var->data.is_unmatched_generic_inout = 0;
Ian Romanick68a4fc92010-10-07 17:21:22 -07002405 }
Ian Romanickb12b5d92011-11-04 16:08:52 -07002406 } else if (target_index == MESA_SHADER_FRAGMENT) {
2407 unsigned binding;
Dave Airlie1256a5d2012-03-24 13:33:41 +00002408 unsigned index;
Ian Romanickb12b5d92011-11-04 16:08:52 -07002409
2410 if (prog->FragDataBindings->get(binding, var->name)) {
2411 assert(binding >= FRAG_RESULT_DATA0);
Tapani Pälli447bb902013-12-12 15:08:59 +02002412 var->data.location = binding;
2413 var->data.is_unmatched_generic_inout = 0;
Dave Airlie1256a5d2012-03-24 13:33:41 +00002414
2415 if (prog->FragDataIndexBindings->get(index, var->name)) {
Tapani Pälli447bb902013-12-12 15:08:59 +02002416 var->data.index = index;
Dave Airlie1256a5d2012-03-24 13:33:41 +00002417 }
Ian Romanickb12b5d92011-11-04 16:08:52 -07002418 }
Ian Romanick68a4fc92010-10-07 17:21:22 -07002419 }
2420
Dave Airliead208d92015-04-30 10:42:06 +10002421 const unsigned slots = var->type->count_attribute_slots();
2422
2423 /* From GL4.5 core spec, section 11.1.1 (Vertex Attributes):
2424 *
2425 * "A program with more than the value of MAX_VERTEX_ATTRIBS active
2426 * attribute variables may fail to link, unless device-dependent
2427 * optimizations are able to make the program fit within available
2428 * hardware resources. For the purposes of this test, attribute variables
2429 * of the type dvec3, dvec4, dmat2x3, dmat2x4, dmat3, dmat3x4, dmat4x3,
2430 * and dmat4 may count as consuming twice as many attributes as equivalent
2431 * single-precision types. While these types use the same number of
2432 * generic attributes as their single-precision equivalents,
2433 * implementations are permitted to consume two single-precision vectors
2434 * of internal storage for each three- or four-component double-precision
2435 * vector."
2436 * Until someone has a good reason in Mesa, enforce that now.
2437 */
2438 if (target_index == MESA_SHADER_VERTEX) {
2439 total_attribs_size += slots;
2440 if (var->type->without_array() == glsl_type::dvec3_type ||
2441 var->type->without_array() == glsl_type::dvec4_type ||
2442 var->type->without_array() == glsl_type::dmat2x3_type ||
2443 var->type->without_array() == glsl_type::dmat2x4_type ||
2444 var->type->without_array() == glsl_type::dmat3_type ||
2445 var->type->without_array() == glsl_type::dmat3x4_type ||
2446 var->type->without_array() == glsl_type::dmat4x3_type ||
2447 var->type->without_array() == glsl_type::dmat4_type)
2448 total_attribs_size += slots;
2449 }
2450
Ian Romanick9f0e98d2011-10-06 10:25:34 -07002451 /* If the variable is not a built-in and has a location statically
2452 * assigned in the shader (presumably via a layout qualifier), make sure
2453 * that it doesn't collide with other assigned locations. Otherwise,
2454 * add it to the list of variables that need linker-assigned locations.
Ian Romanick0ad22cd2010-06-21 17:18:31 -07002455 */
Tapani Pälli447bb902013-12-12 15:08:59 +02002456 if (var->data.location != -1) {
2457 if (var->data.location >= generic_base && var->data.index < 1) {
Ian Romanick523b6112011-08-17 15:40:03 -07002458 /* From page 61 of the OpenGL 4.0 spec:
2459 *
2460 * "LinkProgram will fail if the attribute bindings assigned
2461 * by BindAttribLocation do not leave not enough space to
2462 * assign a location for an active matrix attribute or an
2463 * active attribute array, both of which require multiple
2464 * contiguous generic attributes."
2465 *
Anuj Phogat8c61b6a2014-03-04 17:03:28 -08002466 * I think above text prohibits the aliasing of explicit and
2467 * automatic assignments. But, aliasing is allowed in manual
2468 * assignments of attribute locations. See below comments for
2469 * the details.
Ian Romanick523b6112011-08-17 15:40:03 -07002470 *
Anuj Phogat8c61b6a2014-03-04 17:03:28 -08002471 * From OpenGL 4.0 spec, page 61:
Ian Romanick523b6112011-08-17 15:40:03 -07002472 *
2473 * "It is possible for an application to bind more than one
2474 * attribute name to the same location. This is referred to as
2475 * aliasing. This will only work if only one of the aliased
2476 * attributes is active in the executable program, or if no
2477 * path through the shader consumes more than one attribute of
2478 * a set of attributes aliased to the same location. A link
2479 * error can occur if the linker determines that every path
2480 * through the shader consumes multiple aliased attributes,
2481 * but implementations are not required to generate an error
2482 * in this case."
2483 *
Anuj Phogat8c61b6a2014-03-04 17:03:28 -08002484 * From GLSL 4.30 spec, page 54:
2485 *
2486 * "A program will fail to link if any two non-vertex shader
2487 * input variables are assigned to the same location. For
2488 * vertex shaders, multiple input variables may be assigned
2489 * to the same location using either layout qualifiers or via
2490 * the OpenGL API. However, such aliasing is intended only to
2491 * support vertex shaders where each execution path accesses
2492 * at most one input per each location. Implementations are
2493 * permitted, but not required, to generate link-time errors
2494 * if they detect that every path through the vertex shader
2495 * executable accesses multiple inputs assigned to any single
2496 * location. For all shader types, a program will fail to link
2497 * if explicit location assignments leave the linker unable
2498 * to find space for other variables without explicit
2499 * assignments."
2500 *
2501 * From OpenGL ES 3.0 spec, page 56:
2502 *
2503 * "Binding more than one attribute name to the same location
2504 * is referred to as aliasing, and is not permitted in OpenGL
2505 * ES Shading Language 3.00 vertex shaders. LinkProgram will
2506 * fail when this condition exists. However, aliasing is
2507 * possible in OpenGL ES Shading Language 1.00 vertex shaders.
2508 * This will only work if only one of the aliased attributes
2509 * is active in the executable program, or if no path through
2510 * the shader consumes more than one attribute of a set of
2511 * attributes aliased to the same location. A link error can
2512 * occur if the linker determines that every path through the
2513 * shader consumes multiple aliased attributes, but implemen-
2514 * tations are not required to generate an error in this case."
2515 *
2516 * After looking at above references from OpenGL, OpenGL ES and
2517 * GLSL specifications, we allow aliasing of vertex input variables
2518 * in: OpenGL 2.0 (and above) and OpenGL ES 2.0.
2519 *
2520 * NOTE: This is not required by the spec but its worth mentioning
2521 * here that we're not doing anything to make sure that no path
2522 * through the vertex shader executable accesses multiple inputs
2523 * assigned to any single location.
Ian Romanick523b6112011-08-17 15:40:03 -07002524 */
Anuj Phogat8c61b6a2014-03-04 17:03:28 -08002525
Ian Romanick523b6112011-08-17 15:40:03 -07002526 /* Mask representing the contiguous slots that will be used by
2527 * this attribute.
2528 */
Tapani Pälli447bb902013-12-12 15:08:59 +02002529 const unsigned attr = var->data.location - generic_base;
Ian Romanick523b6112011-08-17 15:40:03 -07002530 const unsigned use_mask = (1 << slots) - 1;
Anuj Phogat8c61b6a2014-03-04 17:03:28 -08002531 const char *const string = (target_index == MESA_SHADER_VERTEX)
2532 ? "vertex shader input" : "fragment shader output";
2533
2534 /* Generate a link error if the requested locations for this
2535 * attribute exceed the maximum allowed attribute location.
2536 */
2537 if (attr + slots > max_index) {
2538 linker_error(prog,
2539 "insufficient contiguous locations "
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07002540 "available for %s `%s' %d %d %d\n", string,
Anuj Phogat8c61b6a2014-03-04 17:03:28 -08002541 var->name, used_locations, use_mask, attr);
2542 return false;
2543 }
Ian Romanick0ad22cd2010-06-21 17:18:31 -07002544
Ian Romanick523b6112011-08-17 15:40:03 -07002545 /* Generate a link error if the set of bits requested for this
2546 * attribute overlaps any previously allocated bits.
2547 */
2548 if ((~(use_mask << attr) & used_locations) != used_locations) {
Anuj Phogat8c61b6a2014-03-04 17:03:28 -08002549 if (target_index == MESA_SHADER_FRAGMENT ||
2550 (prog->IsES && prog->Version >= 300)) {
2551 linker_error(prog,
2552 "overlapping location is assigned "
2553 "to %s `%s' %d %d %d\n", string,
2554 var->name, used_locations, use_mask, attr);
2555 return false;
2556 } else {
2557 linker_warning(prog,
2558 "overlapping location is assigned "
2559 "to %s `%s' %d %d %d\n", string,
2560 var->name, used_locations, use_mask, attr);
2561 }
Ian Romanick523b6112011-08-17 15:40:03 -07002562 }
2563
2564 used_locations |= (use_mask << attr);
2565 }
2566
2567 continue;
2568 }
2569
2570 to_assign[num_attr].slots = slots;
Ian Romanick69846702010-06-22 17:29:19 -07002571 to_assign[num_attr].var = var;
2572 num_attr++;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07002573 }
Ian Romanick69846702010-06-22 17:29:19 -07002574
Dave Airliead208d92015-04-30 10:42:06 +10002575 if (target_index == MESA_SHADER_VERTEX) {
2576 if (total_attribs_size > max_index) {
2577 linker_error(prog,
2578 "attempt to use %d vertex attribute slots only %d available ",
2579 total_attribs_size, max_index);
2580 return false;
2581 }
2582 }
2583
Ian Romanick69846702010-06-22 17:29:19 -07002584 /* If all of the attributes were assigned locations by the application (or
2585 * are built-in attributes with fixed locations), return early. This should
2586 * be the common case.
2587 */
2588 if (num_attr == 0)
2589 return true;
2590
2591 qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
2592
Ian Romanickd32d4f72011-06-27 17:59:58 -07002593 if (target_index == MESA_SHADER_VERTEX) {
2594 /* VERT_ATTRIB_GENERIC0 is a pseudo-alias for VERT_ATTRIB_POS. It can
2595 * only be explicitly assigned by via glBindAttribLocation. Mark it as
2596 * reserved to prevent it from being automatically allocated below.
2597 */
2598 find_deref_visitor find("gl_Vertex");
2599 find.run(sh->ir);
2600 if (find.variable_found())
2601 used_locations |= (1 << 0);
2602 }
Ian Romanick982e3792010-06-29 18:58:20 -07002603
Ian Romanick69846702010-06-22 17:29:19 -07002604 for (unsigned i = 0; i < num_attr; i++) {
2605 /* Mask representing the contiguous slots that will be used by this
2606 * attribute.
2607 */
2608 const unsigned use_mask = (1 << to_assign[i].slots) - 1;
2609
2610 int location = find_available_slots(used_locations, to_assign[i].slots);
2611
2612 if (location < 0) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07002613 const char *const string = (target_index == MESA_SHADER_VERTEX)
2614 ? "vertex shader input" : "fragment shader output";
2615
Ian Romanick586e7412011-07-28 14:04:09 -07002616 linker_error(prog,
Dave Airlie7449ae42011-11-20 19:56:35 +00002617 "insufficient contiguous locations "
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07002618 "available for %s `%s'\n",
Ian Romanick586e7412011-07-28 14:04:09 -07002619 string, to_assign[i].var->name);
Ian Romanick69846702010-06-22 17:29:19 -07002620 return false;
2621 }
2622
Tapani Pälli447bb902013-12-12 15:08:59 +02002623 to_assign[i].var->data.location = generic_base + location;
2624 to_assign[i].var->data.is_unmatched_generic_inout = 0;
Ian Romanick69846702010-06-22 17:29:19 -07002625 used_locations |= (use_mask << location);
2626 }
2627
2628 return true;
Ian Romanick0ad22cd2010-06-21 17:18:31 -07002629}
2630
2631
Ian Romanick40e114b2010-08-17 14:55:50 -07002632/**
Ian Romanickcc90e622010-10-19 17:59:10 -07002633 * Demote shader inputs and outputs that are not used in other stages
Ian Romanick40e114b2010-08-17 14:55:50 -07002634 */
2635void
Ian Romanickcc90e622010-10-19 17:59:10 -07002636demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
Ian Romanick40e114b2010-08-17 14:55:50 -07002637{
Matt Turner4d784462014-06-24 21:34:05 -07002638 foreach_in_list(ir_instruction, node, sh->ir) {
2639 ir_variable *const var = node->as_variable();
Ian Romanick40e114b2010-08-17 14:55:50 -07002640
Tapani Pälli33ee2c62013-12-12 13:51:01 +02002641 if ((var == NULL) || (var->data.mode != int(mode)))
Ian Romanick40e114b2010-08-17 14:55:50 -07002642 continue;
2643
Ian Romanickcc90e622010-10-19 17:59:10 -07002644 /* A shader 'in' or 'out' variable is only really an input or output if
2645 * its value is used by other shader stages. This will cause the variable
2646 * to have a location assigned.
Ian Romanick40e114b2010-08-17 14:55:50 -07002647 */
Tapani Pälli447bb902013-12-12 15:08:59 +02002648 if (var->data.is_unmatched_generic_inout) {
Ian Romanicka9948242014-07-08 18:53:09 -07002649 assert(var->data.mode != ir_var_temporary);
Tapani Pälli33ee2c62013-12-12 13:51:01 +02002650 var->data.mode = ir_var_auto;
Ian Romanick40e114b2010-08-17 14:55:50 -07002651 }
2652 }
2653}
2654
2655
Paul Berry871ddb92011-11-05 11:17:32 -07002656/**
Marek Olšákec174a42011-11-18 15:00:10 +01002657 * Store the gl_FragDepth layout in the gl_shader_program struct.
2658 */
2659static void
2660store_fragdepth_layout(struct gl_shader_program *prog)
2661{
2662 if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
2663 return;
2664 }
2665
2666 struct exec_list *ir = prog->_LinkedShaders[MESA_SHADER_FRAGMENT]->ir;
2667
2668 /* We don't look up the gl_FragDepth symbol directly because if
2669 * gl_FragDepth is not used in the shader, it's removed from the IR.
2670 * However, the symbol won't be removed from the symbol table.
2671 *
2672 * We're only interested in the cases where the variable is NOT removed
2673 * from the IR.
2674 */
Matt Turner4d784462014-06-24 21:34:05 -07002675 foreach_in_list(ir_instruction, node, ir) {
2676 ir_variable *const var = node->as_variable();
Marek Olšákec174a42011-11-18 15:00:10 +01002677
Tapani Pälli33ee2c62013-12-12 13:51:01 +02002678 if (var == NULL || var->data.mode != ir_var_shader_out) {
Marek Olšákec174a42011-11-18 15:00:10 +01002679 continue;
2680 }
2681
2682 if (strcmp(var->name, "gl_FragDepth") == 0) {
Tapani Pälli447bb902013-12-12 15:08:59 +02002683 switch (var->data.depth_layout) {
Marek Olšákec174a42011-11-18 15:00:10 +01002684 case ir_depth_layout_none:
2685 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_NONE;
2686 return;
2687 case ir_depth_layout_any:
2688 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_ANY;
2689 return;
2690 case ir_depth_layout_greater:
2691 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_GREATER;
2692 return;
2693 case ir_depth_layout_less:
2694 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_LESS;
2695 return;
2696 case ir_depth_layout_unchanged:
2697 prog->FragDepthLayout = FRAG_DEPTH_LAYOUT_UNCHANGED;
2698 return;
2699 default:
2700 assert(0);
2701 return;
2702 }
2703 }
2704 }
2705}
2706
2707/**
Ian Romanick92f81592011-11-08 12:37:19 -08002708 * Validate the resources used by a program versus the implementation limits
2709 */
Paul Berryb95d2372013-07-27 11:08:31 -07002710static void
Ian Romanick92f81592011-11-08 12:37:19 -08002711check_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2712{
Paul Berry665b8d72014-01-07 10:11:39 -08002713 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
Ian Romanick92f81592011-11-08 12:37:19 -08002714 struct gl_shader *sh = prog->_LinkedShaders[i];
2715
2716 if (sh == NULL)
2717 continue;
2718
Paul Berrybce8bc02014-01-08 10:17:01 -08002719 if (sh->num_samplers > ctx->Const.Program[i].MaxTextureImageUnits) {
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07002720 linker_error(prog, "Too many %s shader texture samplers\n",
Paul Berry665b8d72014-01-07 10:11:39 -08002721 _mesa_shader_stage_to_string(i));
Ian Romanick92f81592011-11-08 12:37:19 -08002722 }
2723
Paul Berrybce8bc02014-01-08 10:17:01 -08002724 if (sh->num_uniform_components >
2725 ctx->Const.Program[i].MaxUniformComponents) {
Eric Anholt38e77e52013-05-23 11:10:15 -07002726 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2727 linker_warning(prog, "Too many %s shader default uniform block "
2728 "components, but the driver will try to optimize "
2729 "them out; this is non-portable out-of-spec "
2730 "behavior\n",
Paul Berry665b8d72014-01-07 10:11:39 -08002731 _mesa_shader_stage_to_string(i));
Eric Anholt38e77e52013-05-23 11:10:15 -07002732 } else {
2733 linker_error(prog, "Too many %s shader default uniform block "
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07002734 "components\n",
Paul Berry665b8d72014-01-07 10:11:39 -08002735 _mesa_shader_stage_to_string(i));
Eric Anholt38e77e52013-05-23 11:10:15 -07002736 }
2737 }
2738
2739 if (sh->num_combined_uniform_components >
Paul Berrybce8bc02014-01-08 10:17:01 -08002740 ctx->Const.Program[i].MaxCombinedUniformComponents) {
Marek Olšákdf809ae2011-12-10 04:14:46 +01002741 if (ctx->Const.GLSLSkipStrictMaxUniformLimitCheck) {
2742 linker_warning(prog, "Too many %s shader uniform components, "
2743 "but the driver will try to optimize them out; "
2744 "this is non-portable out-of-spec behavior\n",
Paul Berry665b8d72014-01-07 10:11:39 -08002745 _mesa_shader_stage_to_string(i));
Marek Olšákdf809ae2011-12-10 04:14:46 +01002746 } else {
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07002747 linker_error(prog, "Too many %s shader uniform components\n",
Paul Berry665b8d72014-01-07 10:11:39 -08002748 _mesa_shader_stage_to_string(i));
Marek Olšákdf809ae2011-12-10 04:14:46 +01002749 }
Ian Romanick92f81592011-11-08 12:37:19 -08002750 }
2751 }
2752
Paul Berry665b8d72014-01-07 10:11:39 -08002753 unsigned blocks[MESA_SHADER_STAGES] = {0};
Eric Anholt877a8972012-06-25 12:47:01 -07002754 unsigned total_uniform_blocks = 0;
2755
2756 for (unsigned i = 0; i < prog->NumUniformBlocks; i++) {
Jose Fonsecaf734d252015-06-15 18:29:02 +01002757 if (prog->UniformBlocks[i].UniformBufferSize > ctx->Const.MaxUniformBlockSize) {
2758 linker_error(prog, "Uniform block %s too big (%d/%d)\n",
2759 prog->UniformBlocks[i].Name,
2760 prog->UniformBlocks[i].UniformBufferSize,
2761 ctx->Const.MaxUniformBlockSize);
2762 }
2763
Paul Berry665b8d72014-01-07 10:11:39 -08002764 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
Eric Anholt877a8972012-06-25 12:47:01 -07002765 if (prog->UniformBlockStageIndex[j][i] != -1) {
2766 blocks[j]++;
2767 total_uniform_blocks++;
2768 }
2769 }
2770
2771 if (total_uniform_blocks > ctx->Const.MaxCombinedUniformBlocks) {
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07002772 linker_error(prog, "Too many combined uniform blocks (%d/%d)\n",
Eric Anholt877a8972012-06-25 12:47:01 -07002773 prog->NumUniformBlocks,
2774 ctx->Const.MaxCombinedUniformBlocks);
2775 } else {
Paul Berry665b8d72014-01-07 10:11:39 -08002776 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
Paul Berrybce8bc02014-01-08 10:17:01 -08002777 const unsigned max_uniform_blocks =
2778 ctx->Const.Program[i].MaxUniformBlocks;
2779 if (blocks[i] > max_uniform_blocks) {
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07002780 linker_error(prog, "Too many %s uniform blocks (%d/%d)\n",
Paul Berry665b8d72014-01-07 10:11:39 -08002781 _mesa_shader_stage_to_string(i),
Eric Anholt877a8972012-06-25 12:47:01 -07002782 blocks[i],
Paul Berrybce8bc02014-01-08 10:17:01 -08002783 max_uniform_blocks);
Eric Anholt877a8972012-06-25 12:47:01 -07002784 break;
2785 }
2786 }
2787 }
2788 }
Ian Romanick92f81592011-11-08 12:37:19 -08002789}
Paul Berry871ddb92011-11-05 11:17:32 -07002790
Francisco Jereze51158f2013-11-22 15:53:26 -08002791/**
2792 * Validate shader image resources.
2793 */
2794static void
2795check_image_resources(struct gl_context *ctx, struct gl_shader_program *prog)
2796{
2797 unsigned total_image_units = 0;
2798 unsigned fragment_outputs = 0;
2799
2800 if (!ctx->Extensions.ARB_shader_image_load_store)
2801 return;
2802
2803 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2804 struct gl_shader *sh = prog->_LinkedShaders[i];
2805
2806 if (sh) {
2807 if (sh->NumImages > ctx->Const.Program[i].MaxImageUniforms)
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07002808 linker_error(prog, "Too many %s shader image uniforms\n",
Francisco Jereze51158f2013-11-22 15:53:26 -08002809 _mesa_shader_stage_to_string(i));
2810
2811 total_image_units += sh->NumImages;
2812
2813 if (i == MESA_SHADER_FRAGMENT) {
Matt Turner4d784462014-06-24 21:34:05 -07002814 foreach_in_list(ir_instruction, node, sh->ir) {
2815 ir_variable *var = node->as_variable();
Francisco Jereze51158f2013-11-22 15:53:26 -08002816 if (var && var->data.mode == ir_var_shader_out)
2817 fragment_outputs += var->type->count_attribute_slots();
2818 }
2819 }
2820 }
2821 }
2822
2823 if (total_image_units > ctx->Const.MaxCombinedImageUniforms)
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07002824 linker_error(prog, "Too many combined image uniforms\n");
Francisco Jereze51158f2013-11-22 15:53:26 -08002825
2826 if (total_image_units + fragment_outputs >
2827 ctx->Const.MaxCombinedImageUnitsAndFragmentOutputs)
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07002828 linker_error(prog, "Too many combined image uniforms and fragment outputs\n");
Francisco Jereze51158f2013-11-22 15:53:26 -08002829}
2830
Tapani Pällieca9d162014-04-08 08:45:36 +03002831
2832/**
2833 * Initializes explicit location slots to INACTIVE_UNIFORM_EXPLICIT_LOCATION
2834 * for a variable, checks for overlaps between other uniforms using explicit
2835 * locations.
2836 */
2837static bool
2838reserve_explicit_locations(struct gl_shader_program *prog,
2839 string_to_uint_map *map, ir_variable *var)
2840{
2841 unsigned slots = var->type->uniform_locations();
2842 unsigned max_loc = var->data.location + slots - 1;
2843
2844 /* Resize remap table if locations do not fit in the current one. */
2845 if (max_loc + 1 > prog->NumUniformRemapTable) {
2846 prog->UniformRemapTable =
2847 reralloc(prog, prog->UniformRemapTable,
2848 gl_uniform_storage *,
2849 max_loc + 1);
2850
2851 if (!prog->UniformRemapTable) {
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07002852 linker_error(prog, "Out of memory during linking.\n");
Tapani Pällieca9d162014-04-08 08:45:36 +03002853 return false;
2854 }
2855
2856 /* Initialize allocated space. */
2857 for (unsigned i = prog->NumUniformRemapTable; i < max_loc + 1; i++)
2858 prog->UniformRemapTable[i] = NULL;
2859
2860 prog->NumUniformRemapTable = max_loc + 1;
2861 }
2862
2863 for (unsigned i = 0; i < slots; i++) {
2864 unsigned loc = var->data.location + i;
2865
2866 /* Check if location is already used. */
2867 if (prog->UniformRemapTable[loc] == INACTIVE_UNIFORM_EXPLICIT_LOCATION) {
2868
2869 /* Possibly same uniform from a different stage, this is ok. */
2870 unsigned hash_loc;
2871 if (map->get(hash_loc, var->name) && hash_loc == loc - i)
2872 continue;
2873
2874 /* ARB_explicit_uniform_location specification states:
2875 *
2876 * "No two default-block uniform variables in the program can have
2877 * the same location, even if they are unused, otherwise a compiler
2878 * or linker error will be generated."
2879 */
2880 linker_error(prog,
Neil Roberts352f8f22014-11-13 15:31:44 +00002881 "location qualifier for uniform %s overlaps "
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07002882 "previously used location\n",
Tapani Pällieca9d162014-04-08 08:45:36 +03002883 var->name);
2884 return false;
2885 }
2886
2887 /* Initialize location as inactive before optimization
2888 * rounds and location assignment.
2889 */
2890 prog->UniformRemapTable[loc] = INACTIVE_UNIFORM_EXPLICIT_LOCATION;
2891 }
2892
2893 /* Note, base location used for arrays. */
2894 map->put(var->data.location, var->name);
2895
2896 return true;
2897}
2898
2899/**
2900 * Check and reserve all explicit uniform locations, called before
2901 * any optimizations happen to handle also inactive uniforms and
2902 * inactive array elements that may get trimmed away.
2903 */
2904static void
2905check_explicit_uniform_locations(struct gl_context *ctx,
2906 struct gl_shader_program *prog)
2907{
2908 if (!ctx->Extensions.ARB_explicit_uniform_location)
2909 return;
2910
2911 /* This map is used to detect if overlapping explicit locations
2912 * occur with the same uniform (from different stage) or a different one.
2913 */
2914 string_to_uint_map *uniform_map = new string_to_uint_map;
2915
2916 if (!uniform_map) {
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07002917 linker_error(prog, "Out of memory during linking.\n");
Tapani Pällieca9d162014-04-08 08:45:36 +03002918 return;
2919 }
2920
2921 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2922 struct gl_shader *sh = prog->_LinkedShaders[i];
2923
2924 if (!sh)
2925 continue;
2926
Matt Turner4d784462014-06-24 21:34:05 -07002927 foreach_in_list(ir_instruction, node, sh->ir) {
2928 ir_variable *var = node->as_variable();
Kristian Høgsberga78a5892015-05-13 11:17:23 +02002929 if (var && (var->data.mode == ir_var_uniform || var->data.mode == ir_var_shader_storage) &&
Tapani Pällieca9d162014-04-08 08:45:36 +03002930 var->data.explicit_location) {
Dave Airlie2d5d1f52014-09-02 09:54:36 +10002931 if (!reserve_explicit_locations(prog, uniform_map, var)) {
2932 delete uniform_map;
Tapani Pällieca9d162014-04-08 08:45:36 +03002933 return;
Dave Airlie2d5d1f52014-09-02 09:54:36 +10002934 }
Tapani Pällieca9d162014-04-08 08:45:36 +03002935 }
2936 }
2937 }
2938
2939 delete uniform_map;
2940}
2941
Tapani Pällic796ce42015-03-06 09:14:49 +02002942static bool
2943add_program_resource(struct gl_shader_program *prog, GLenum type,
2944 const void *data, uint8_t stages)
2945{
2946 assert(data);
2947
2948 /* If resource already exists, do not add it again. */
2949 for (unsigned i = 0; i < prog->NumProgramResourceList; i++)
2950 if (prog->ProgramResourceList[i].Data == data)
2951 return true;
2952
2953 prog->ProgramResourceList =
2954 reralloc(prog,
2955 prog->ProgramResourceList,
2956 gl_program_resource,
2957 prog->NumProgramResourceList + 1);
2958
2959 if (!prog->ProgramResourceList) {
2960 linker_error(prog, "Out of memory during linking.\n");
2961 return false;
2962 }
2963
2964 struct gl_program_resource *res =
2965 &prog->ProgramResourceList[prog->NumProgramResourceList];
2966
2967 res->Type = type;
2968 res->Data = data;
2969 res->StageReferences = stages;
2970
2971 prog->NumProgramResourceList++;
2972
2973 return true;
2974}
2975
2976/**
2977 * Function builds a stage reference bitmask from variable name.
2978 */
2979static uint8_t
2980build_stageref(struct gl_shader_program *shProg, const char *name)
2981{
2982 uint8_t stages = 0;
2983
2984 /* Note, that we assume MAX 8 stages, if there will be more stages, type
2985 * used for reference mask in gl_program_resource will need to be changed.
2986 */
2987 assert(MESA_SHADER_STAGES < 8);
2988
2989 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
2990 struct gl_shader *sh = shProg->_LinkedShaders[i];
2991 if (!sh)
2992 continue;
Tapani Pälliccaf37f2015-06-29 14:19:00 +03002993
2994 /* Shader symbol table may contain variables that have
2995 * been optimized away. Search IR for the variable instead.
2996 */
2997 foreach_in_list(ir_instruction, node, sh->ir) {
2998 ir_variable *var = node->as_variable();
2999 if (var && strcmp(var->name, name) == 0) {
3000 stages |= (1 << i);
3001 break;
3002 }
3003 }
Tapani Pällic796ce42015-03-06 09:14:49 +02003004 }
3005 return stages;
3006}
3007
3008static bool
3009add_interface_variables(struct gl_shader_program *shProg,
Jose Fonseca037e0e72015-04-16 10:19:57 +01003010 struct gl_shader *sh, GLenum programInterface)
Tapani Pällic796ce42015-03-06 09:14:49 +02003011{
3012 foreach_in_list(ir_instruction, node, sh->ir) {
3013 ir_variable *var = node->as_variable();
Tapani Pälli3706e5d2015-04-30 09:27:00 +03003014 uint8_t mask = 0;
Tapani Pällic796ce42015-03-06 09:14:49 +02003015
3016 if (!var)
3017 continue;
3018
3019 switch (var->data.mode) {
3020 /* From GL 4.3 core spec, section 11.1.1 (Vertex Attributes):
3021 * "For GetActiveAttrib, all active vertex shader input variables
3022 * are enumerated, including the special built-in inputs gl_VertexID
3023 * and gl_InstanceID."
3024 */
3025 case ir_var_system_value:
3026 if (var->data.location != SYSTEM_VALUE_VERTEX_ID &&
3027 var->data.location != SYSTEM_VALUE_VERTEX_ID_ZERO_BASE &&
3028 var->data.location != SYSTEM_VALUE_INSTANCE_ID)
Tapani Pälli5917ca32015-04-21 08:25:16 +03003029 continue;
Tapani Pälli3706e5d2015-04-30 09:27:00 +03003030 /* Mark special built-in inputs referenced by the vertex stage so
3031 * that they are considered active by the shader queries.
3032 */
3033 mask = (1 << (MESA_SHADER_VERTEX));
Tapani Pällied10f9c2015-04-21 20:11:43 +03003034 /* FALLTHROUGH */
Tapani Pällic796ce42015-03-06 09:14:49 +02003035 case ir_var_shader_in:
Jose Fonseca037e0e72015-04-16 10:19:57 +01003036 if (programInterface != GL_PROGRAM_INPUT)
Tapani Pällic796ce42015-03-06 09:14:49 +02003037 continue;
3038 break;
3039 case ir_var_shader_out:
Jose Fonseca037e0e72015-04-16 10:19:57 +01003040 if (programInterface != GL_PROGRAM_OUTPUT)
Tapani Pällic796ce42015-03-06 09:14:49 +02003041 continue;
3042 break;
3043 default:
3044 continue;
3045 };
3046
Kenneth Graunke6218c682015-06-28 22:17:16 -07003047 if (!add_program_resource(shProg, programInterface, var,
Tapani Pälli3706e5d2015-04-30 09:27:00 +03003048 build_stageref(shProg, var->name) | mask))
Tapani Pällic796ce42015-03-06 09:14:49 +02003049 return false;
3050 }
3051 return true;
3052}
3053
3054/**
3055 * Builds up a list of program resources that point to existing
3056 * resource data.
3057 */
Tapani Pälli73afa312015-06-29 14:39:05 +03003058void
Tapani Pällic796ce42015-03-06 09:14:49 +02003059build_program_resource_list(struct gl_context *ctx,
3060 struct gl_shader_program *shProg)
3061{
3062 /* Rebuild resource list. */
3063 if (shProg->ProgramResourceList) {
3064 ralloc_free(shProg->ProgramResourceList);
3065 shProg->ProgramResourceList = NULL;
3066 shProg->NumProgramResourceList = 0;
3067 }
3068
3069 int input_stage = MESA_SHADER_STAGES, output_stage = 0;
3070
3071 /* Determine first input and final output stage. These are used to
3072 * detect which variables should be enumerated in the resource list
3073 * for GL_PROGRAM_INPUT and GL_PROGRAM_OUTPUT.
3074 */
3075 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3076 if (!shProg->_LinkedShaders[i])
3077 continue;
3078 if (input_stage == MESA_SHADER_STAGES)
3079 input_stage = i;
3080 output_stage = i;
3081 }
3082
3083 /* Empty shader, no resources. */
3084 if (input_stage == MESA_SHADER_STAGES && output_stage == 0)
3085 return;
3086
3087 /* Add inputs and outputs to the resource list. */
3088 if (!add_interface_variables(shProg, shProg->_LinkedShaders[input_stage],
3089 GL_PROGRAM_INPUT))
3090 return;
3091
3092 if (!add_interface_variables(shProg, shProg->_LinkedShaders[output_stage],
3093 GL_PROGRAM_OUTPUT))
3094 return;
3095
3096 /* Add transform feedback varyings. */
3097 if (shProg->LinkedTransformFeedback.NumVarying > 0) {
3098 for (int i = 0; i < shProg->LinkedTransformFeedback.NumVarying; i++) {
3099 uint8_t stageref =
3100 build_stageref(shProg,
3101 shProg->LinkedTransformFeedback.Varyings[i].Name);
3102 if (!add_program_resource(shProg, GL_TRANSFORM_FEEDBACK_VARYING,
3103 &shProg->LinkedTransformFeedback.Varyings[i],
3104 stageref))
3105 return;
3106 }
3107 }
3108
3109 /* Add uniforms from uniform storage. */
Martin Peres87a4bc52015-05-21 15:51:09 +03003110 for (unsigned i = 0; i < shProg->NumUniformStorage; i++) {
Tapani Pällic796ce42015-03-06 09:14:49 +02003111 /* Do not add uniforms internally used by Mesa. */
3112 if (shProg->UniformStorage[i].hidden)
3113 continue;
3114
3115 uint8_t stageref =
3116 build_stageref(shProg, shProg->UniformStorage[i].name);
Tapani Pälli9f4eaba2015-05-11 13:24:20 +03003117
3118 /* Add stagereferences for uniforms in a uniform block. */
3119 int block_index = shProg->UniformStorage[i].block_index;
3120 if (block_index != -1) {
3121 for (unsigned j = 0; j < MESA_SHADER_STAGES; j++) {
3122 if (shProg->UniformBlockStageIndex[j][block_index] != -1)
3123 stageref |= (1 << j);
3124 }
3125 }
3126
Tapani Pällic796ce42015-03-06 09:14:49 +02003127 if (!add_program_resource(shProg, GL_UNIFORM,
3128 &shProg->UniformStorage[i], stageref))
3129 return;
3130 }
3131
3132 /* Add program uniform blocks. */
3133 for (unsigned i = 0; i < shProg->NumUniformBlocks; i++) {
3134 if (!add_program_resource(shProg, GL_UNIFORM_BLOCK,
3135 &shProg->UniformBlocks[i], 0))
3136 return;
3137 }
3138
3139 /* Add atomic counter buffers. */
3140 for (unsigned i = 0; i < shProg->NumAtomicBuffers; i++) {
3141 if (!add_program_resource(shProg, GL_ATOMIC_COUNTER_BUFFER,
3142 &shProg->AtomicBuffers[i], 0))
3143 return;
3144 }
3145
3146 /* TODO - following extensions will require more resource types:
3147 *
3148 * GL_ARB_shader_storage_buffer_object
3149 * GL_ARB_shader_subroutine
3150 */
3151}
3152
Tapani Pälli9350ea62015-05-19 15:01:49 +03003153/**
3154 * This check is done to make sure we allow only constant expression
3155 * indexing and "constant-index-expression" (indexing with an expression
3156 * that includes loop induction variable).
3157 */
3158static bool
3159validate_sampler_array_indexing(struct gl_context *ctx,
3160 struct gl_shader_program *prog)
3161{
3162 dynamic_sampler_array_indexing_visitor v;
3163 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3164 if (prog->_LinkedShaders[i] == NULL)
3165 continue;
3166
3167 bool no_dynamic_indexing =
3168 ctx->Const.ShaderCompilerOptions[i].EmitNoIndirectSampler;
3169
3170 /* Search for array derefs in shader. */
3171 v.run(prog->_LinkedShaders[i]->ir);
3172 if (v.uses_dynamic_sampler_array_indexing()) {
3173 const char *msg = "sampler arrays indexed with non-constant "
3174 "expressions is forbidden in GLSL %s %u";
3175 /* Backend has indicated that it has no dynamic indexing support. */
3176 if (no_dynamic_indexing) {
3177 linker_error(prog, msg, prog->IsES ? "ES" : "", prog->Version);
3178 return false;
3179 } else {
3180 linker_warning(prog, msg, prog->IsES ? "ES" : "", prog->Version);
3181 }
3182 }
3183 }
3184 return true;
3185}
3186
Tapani Pällic796ce42015-03-06 09:14:49 +02003187
Ian Romanick0e59b262010-06-23 11:23:01 -07003188void
Kristian Høgsbergf9995b32010-10-12 12:26:10 -04003189link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
Ian Romanick832dfa52010-06-17 15:04:20 -07003190{
Paul Berry871ddb92011-11-05 11:17:32 -07003191 tfeedback_decl *tfeedback_decls = NULL;
3192 unsigned num_tfeedback_decls = prog->TransformFeedback.NumVarying;
3193
Kenneth Graunked3073f52011-01-21 14:32:31 -08003194 void *mem_ctx = ralloc_context(NULL); // temporary linker context
Kenneth Graunke2da02e72010-11-17 11:03:57 -08003195
Paul Berryb95d2372013-07-27 11:08:31 -07003196 prog->LinkStatus = true; /* All error paths will set this to false */
Ian Romanick832dfa52010-06-17 15:04:20 -07003197 prog->Validated = false;
3198 prog->_Used = false;
3199
Anuj Phogat9bcb0a82014-02-10 14:12:40 -08003200 prog->ARB_fragment_coord_conventions_enable = false;
Francisco Jerez5c114932013-09-11 12:14:46 -07003201
Ian Romanick832dfa52010-06-17 15:04:20 -07003202 /* Separate the shaders into groups based on their type.
3203 */
Paul Berrycd18ba12014-01-07 08:56:57 -08003204 struct gl_shader **shader_list[MESA_SHADER_STAGES];
3205 unsigned num_shaders[MESA_SHADER_STAGES];
Ian Romanick832dfa52010-06-17 15:04:20 -07003206
Paul Berrycd18ba12014-01-07 08:56:57 -08003207 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
3208 shader_list[i] = (struct gl_shader **)
3209 calloc(prog->NumShaders, sizeof(struct gl_shader *));
3210 num_shaders[i] = 0;
3211 }
Ian Romanick832dfa52010-06-17 15:04:20 -07003212
Ian Romanick25f51d32010-07-16 15:51:50 -07003213 unsigned min_version = UINT_MAX;
3214 unsigned max_version = 0;
Paul Berrya9f34dc2012-08-02 17:49:44 -07003215 const bool is_es_prog =
3216 (prog->NumShaders > 0 && prog->Shaders[0]->IsES) ? true : false;
Ian Romanick832dfa52010-06-17 15:04:20 -07003217 for (unsigned i = 0; i < prog->NumShaders; i++) {
Ian Romanick25f51d32010-07-16 15:51:50 -07003218 min_version = MIN2(min_version, prog->Shaders[i]->Version);
3219 max_version = MAX2(max_version, prog->Shaders[i]->Version);
3220
Paul Berrya9f34dc2012-08-02 17:49:44 -07003221 if (prog->Shaders[i]->IsES != is_es_prog) {
3222 linker_error(prog, "all shaders must use same shading "
3223 "language version\n");
3224 goto done;
3225 }
3226
Jose Fonsecad01a7cda2015-03-18 14:21:15 +00003227 if (prog->Shaders[i]->ARB_fragment_coord_conventions_enable) {
3228 prog->ARB_fragment_coord_conventions_enable = true;
3229 }
Anuj Phogat9bcb0a82014-02-10 14:12:40 -08003230
Paul Berrycd18ba12014-01-07 08:56:57 -08003231 gl_shader_stage shader_type = prog->Shaders[i]->Stage;
3232 shader_list[shader_type][num_shaders[shader_type]] = prog->Shaders[i];
3233 num_shaders[shader_type]++;
Ian Romanick832dfa52010-06-17 15:04:20 -07003234 }
3235
Paul Berry672fab02013-10-13 18:01:11 -07003236 /* In desktop GLSL, different shader versions may be linked together. In
3237 * GLSL ES, all shader versions must be the same.
Ian Romanick25f51d32010-07-16 15:51:50 -07003238 */
Paul Berry672fab02013-10-13 18:01:11 -07003239 if (is_es_prog && min_version != max_version) {
Ian Romanick586e7412011-07-28 14:04:09 -07003240 linker_error(prog, "all shaders must use same shading "
3241 "language version\n");
Ian Romanick25f51d32010-07-16 15:51:50 -07003242 goto done;
3243 }
3244
3245 prog->Version = max_version;
Paul Berry91c92bb2012-08-02 17:50:43 -07003246 prog->IsES = is_es_prog;
Ian Romanick25f51d32010-07-16 15:51:50 -07003247
Chris Forbes7c758c52014-09-21 13:33:14 +12003248 /* Some shaders have to be linked with some other shaders present.
Fabian Bielerbd85ba02013-05-24 23:26:54 +02003249 */
Paul Berrycd18ba12014-01-07 08:56:57 -08003250 if (num_shaders[MESA_SHADER_GEOMETRY] > 0 &&
Ian Romanickc557eb72014-01-23 18:26:29 -08003251 num_shaders[MESA_SHADER_VERTEX] == 0 &&
3252 !prog->SeparateShader) {
Fabian Bielerbd85ba02013-05-24 23:26:54 +02003253 linker_error(prog, "Geometry shader must be linked with "
3254 "vertex shader\n");
3255 goto done;
3256 }
Chris Forbes7c758c52014-09-21 13:33:14 +12003257 if (num_shaders[MESA_SHADER_TESS_EVAL] > 0 &&
3258 num_shaders[MESA_SHADER_VERTEX] == 0 &&
3259 !prog->SeparateShader) {
3260 linker_error(prog, "Tessellation evaluation shader must be linked with "
3261 "vertex shader\n");
3262 goto done;
3263 }
3264 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
3265 num_shaders[MESA_SHADER_VERTEX] == 0 &&
3266 !prog->SeparateShader) {
3267 linker_error(prog, "Tessellation control shader must be linked with "
3268 "vertex shader\n");
3269 goto done;
3270 }
3271
3272 /* The spec is self-contradictory here. It allows linking without a tess
3273 * eval shader, but that can only be used with transform feedback and
3274 * rasterization disabled. However, transform feedback isn't allowed
3275 * with GL_PATCHES, so it can't be used.
3276 *
3277 * More investigation showed that the idea of transform feedback after
3278 * a tess control shader was dropped, because some hw vendors couldn't
3279 * support tessellation without a tess eval shader, but the linker section
3280 * wasn't updated to reflect that.
3281 *
3282 * All specifications (ARB_tessellation_shader, GL 4.0-4.5) have this
3283 * spec bug.
3284 *
3285 * Do what's reasonable and always require a tess eval shader if a tess
3286 * control shader is present.
3287 */
3288 if (num_shaders[MESA_SHADER_TESS_CTRL] > 0 &&
3289 num_shaders[MESA_SHADER_TESS_EVAL] == 0 &&
3290 !prog->SeparateShader) {
3291 linker_error(prog, "Tessellation control shader must be linked with "
3292 "tessellation evaluation shader\n");
3293 goto done;
3294 }
Fabian Bielerbd85ba02013-05-24 23:26:54 +02003295
Paul Berry1fe274b2014-01-08 11:40:23 -08003296 /* Compute shaders have additional restrictions. */
3297 if (num_shaders[MESA_SHADER_COMPUTE] > 0 &&
3298 num_shaders[MESA_SHADER_COMPUTE] != prog->NumShaders) {
3299 linker_error(prog, "Compute shaders may not be linked with any other "
3300 "type of shader\n");
3301 }
3302
Paul Berry665b8d72014-01-07 10:11:39 -08003303 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
Ian Romanick3322fba2010-10-14 13:28:42 -07003304 if (prog->_LinkedShaders[i] != NULL)
3305 ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
3306
3307 prog->_LinkedShaders[i] = NULL;
Eric Anholt5d0f4302010-08-18 12:02:35 -07003308 }
3309
Ian Romanickcd6764e2010-07-16 16:00:07 -07003310 /* Link all shaders for a particular stage and validate the result.
3311 */
Paul Berrycd18ba12014-01-07 08:56:57 -08003312 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
3313 if (num_shaders[stage] > 0) {
3314 gl_shader *const sh =
3315 link_intrastage_shaders(mem_ctx, ctx, prog, shader_list[stage],
3316 num_shaders[stage]);
Ian Romanick3fb87872010-07-09 14:09:34 -07003317
Ilia Mirkin5646f0f2015-05-17 17:56:44 -04003318 if (!prog->LinkStatus) {
3319 if (sh)
3320 ctx->Driver.DeleteShader(ctx, sh);
Paul Berrycd18ba12014-01-07 08:56:57 -08003321 goto done;
Ilia Mirkin5646f0f2015-05-17 17:56:44 -04003322 }
Ian Romanick3fb87872010-07-09 14:09:34 -07003323
Paul Berrycd18ba12014-01-07 08:56:57 -08003324 switch (stage) {
3325 case MESA_SHADER_VERTEX:
3326 validate_vertex_shader_executable(prog, sh);
3327 break;
Chris Forbesdf16e0d2014-09-09 19:25:02 +12003328 case MESA_SHADER_TESS_CTRL:
3329 /* nothing to be done */
3330 break;
3331 case MESA_SHADER_TESS_EVAL:
3332 validate_tess_eval_shader_executable(prog, sh);
3333 break;
Paul Berrycd18ba12014-01-07 08:56:57 -08003334 case MESA_SHADER_GEOMETRY:
3335 validate_geometry_shader_executable(prog, sh);
3336 break;
3337 case MESA_SHADER_FRAGMENT:
3338 validate_fragment_shader_executable(prog, sh);
3339 break;
3340 }
Ilia Mirkin5646f0f2015-05-17 17:56:44 -04003341 if (!prog->LinkStatus) {
3342 if (sh)
3343 ctx->Driver.DeleteShader(ctx, sh);
Paul Berrycd18ba12014-01-07 08:56:57 -08003344 goto done;
Ilia Mirkin5646f0f2015-05-17 17:56:44 -04003345 }
Ian Romanick3fb87872010-07-09 14:09:34 -07003346
Paul Berrycd18ba12014-01-07 08:56:57 -08003347 _mesa_reference_shader(ctx, &prog->_LinkedShaders[stage], sh);
3348 }
Ian Romanickcc22c5a2010-06-18 17:13:42 -07003349 }
3350
Paul Berrycd18ba12014-01-07 08:56:57 -08003351 if (num_shaders[MESA_SHADER_GEOMETRY] > 0)
Paul Berry44b7ebe2013-10-23 12:55:24 -07003352 prog->LastClipDistanceArraySize = prog->Geom.ClipDistanceArraySize;
Chris Forbesdf16e0d2014-09-09 19:25:02 +12003353 else if (num_shaders[MESA_SHADER_TESS_EVAL] > 0)
3354 prog->LastClipDistanceArraySize = prog->TessEval.ClipDistanceArraySize;
Paul Berrycd18ba12014-01-07 08:56:57 -08003355 else if (num_shaders[MESA_SHADER_VERTEX] > 0)
3356 prog->LastClipDistanceArraySize = prog->Vert.ClipDistanceArraySize;
3357 else
3358 prog->LastClipDistanceArraySize = 0; /* Not used */
Bryan Cain25480922013-02-15 09:46:50 -06003359
Ian Romanick3ed850e2010-06-23 12:18:21 -07003360 /* Here begins the inter-stage linking phase. Some initial validation is
3361 * performed, then locations are assigned for uniforms, attributes, and
3362 * varyings.
3363 */
Paul Berryb95d2372013-07-27 11:08:31 -07003364 cross_validate_uniforms(prog);
3365 if (!prog->LinkStatus)
3366 goto done;
Ian Romanick3322fba2010-10-14 13:28:42 -07003367
Paul Berryb95d2372013-07-27 11:08:31 -07003368 unsigned prev;
Ian Romanick3322fba2010-10-14 13:28:42 -07003369
Paul Berry28e526d2014-01-06 19:47:25 -08003370 for (prev = 0; prev <= MESA_SHADER_FRAGMENT; prev++) {
Paul Berryb95d2372013-07-27 11:08:31 -07003371 if (prog->_LinkedShaders[prev] != NULL)
3372 break;
3373 }
Ian Romanick3322fba2010-10-14 13:28:42 -07003374
Tapani Pällieca9d162014-04-08 08:45:36 +03003375 check_explicit_uniform_locations(ctx, prog);
3376 if (!prog->LinkStatus)
3377 goto done;
3378
Chris Forbes7c758c52014-09-21 13:33:14 +12003379 resize_tes_inputs(ctx, prog);
3380
Paul Berryb95d2372013-07-27 11:08:31 -07003381 /* Validate the inputs of each stage with the output of the preceding
3382 * stage.
3383 */
Paul Berry28e526d2014-01-06 19:47:25 -08003384 for (unsigned i = prev + 1; i <= MESA_SHADER_FRAGMENT; i++) {
Paul Berryb95d2372013-07-27 11:08:31 -07003385 if (prog->_LinkedShaders[i] == NULL)
3386 continue;
Kenneth Graunke3ddfccb2013-05-20 23:46:16 -07003387
Paul Berry544e3122013-11-15 14:23:45 -08003388 validate_interstage_inout_blocks(prog, prog->_LinkedShaders[prev],
3389 prog->_LinkedShaders[i]);
Paul Berryb95d2372013-07-27 11:08:31 -07003390 if (!prog->LinkStatus)
3391 goto done;
Ian Romanick3322fba2010-10-14 13:28:42 -07003392
Paul Berryb95d2372013-07-27 11:08:31 -07003393 cross_validate_outputs_to_inputs(prog,
3394 prog->_LinkedShaders[prev],
3395 prog->_LinkedShaders[i]);
3396 if (!prog->LinkStatus)
3397 goto done;
Ian Romanick37101922010-06-18 19:02:10 -07003398
Paul Berryb95d2372013-07-27 11:08:31 -07003399 prev = i;
Ian Romanick37101922010-06-18 19:02:10 -07003400 }
Ian Romanick832dfa52010-06-17 15:04:20 -07003401
Paul Berry544e3122013-11-15 14:23:45 -08003402 /* Cross-validate uniform blocks between shader stages */
3403 validate_interstage_uniform_blocks(prog, prog->_LinkedShaders,
Paul Berry665b8d72014-01-07 10:11:39 -08003404 MESA_SHADER_STAGES);
Paul Berry544e3122013-11-15 14:23:45 -08003405 if (!prog->LinkStatus)
3406 goto done;
Jordan Justen5ebf5472013-03-10 03:20:03 -07003407
Paul Berry665b8d72014-01-07 10:11:39 -08003408 for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) {
Jordan Justen5ebf5472013-03-10 03:20:03 -07003409 if (prog->_LinkedShaders[i] != NULL)
3410 lower_named_interface_blocks(mem_ctx, prog->_LinkedShaders[i]);
3411 }
3412
Eric Anholt3de13952012-05-04 13:08:46 -07003413 /* Implement the GLSL 1.30+ rule for discard vs infinite loops Do
3414 * it before optimization because we want most of the checks to get
3415 * dropped thanks to constant propagation.
Paul Berry15ba2a52012-08-02 17:51:02 -07003416 *
3417 * This rule also applies to GLSL ES 3.00.
Eric Anholt3de13952012-05-04 13:08:46 -07003418 */
Paul Berry15ba2a52012-08-02 17:51:02 -07003419 if (max_version >= (is_es_prog ? 300 : 130)) {
Eric Anholt3de13952012-05-04 13:08:46 -07003420 struct gl_shader *sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
3421 if (sh) {
3422 lower_discard_flow(sh->ir);
3423 }
3424 }
3425
Eric Anholtf609cf72012-04-27 13:52:56 -07003426 if (!interstage_cross_validate_uniform_blocks(prog))
3427 goto done;
3428
Eric Anholt2f4fe152010-08-10 13:06:49 -07003429 /* Do common optimization before assigning storage for attributes,
3430 * uniforms, and varyings. Later optimization could possibly make
3431 * some of that unused.
3432 */
Paul Berry665b8d72014-01-07 10:11:39 -08003433 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
Ian Romanick3322fba2010-10-14 13:28:42 -07003434 if (prog->_LinkedShaders[i] == NULL)
3435 continue;
3436
Ian Romanick02c5ae12011-07-11 10:46:01 -07003437 detect_recursion_linked(prog, prog->_LinkedShaders[i]->ir);
3438 if (!prog->LinkStatus)
3439 goto done;
3440
Marek Olšák002211f2014-08-03 04:31:56 +02003441 if (ctx->Const.ShaderCompilerOptions[i].LowerClipDistance) {
Paul Berry18392442012-12-04 11:11:02 -08003442 lower_clip_distance(prog->_LinkedShaders[i]);
3443 }
Paul Berryc06e3252011-08-11 20:58:21 -07003444
Fabian Bieler73a9a152014-03-10 17:55:36 +01003445 if (ctx->Const.LowerTessLevel) {
3446 lower_tess_level(prog->_LinkedShaders[i]);
3447 }
3448
Kenneth Graunke169c6452014-04-06 23:25:00 -07003449 while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, false,
Marek Olšák002211f2014-08-03 04:31:56 +02003450 &ctx->Const.ShaderCompilerOptions[i],
Kenneth Graunke169c6452014-04-06 23:25:00 -07003451 ctx->Const.NativeIntegers))
Eric Anholt2f4fe152010-08-10 13:06:49 -07003452 ;
Kenneth Graunke4f22db52014-04-26 00:18:54 -07003453
3454 lower_const_arrays_to_uniforms(prog->_LinkedShaders[i]->ir);
Ian Romanicka7ba9a72010-07-20 13:36:32 -07003455 }
Ian Romanick13e10e42010-06-21 12:03:24 -07003456
Tapani Pälli9350ea62015-05-19 15:01:49 +03003457 /* Validation for special cases where we allow sampler array indexing
3458 * with loop induction variable. This check emits a warning or error
3459 * depending if backend can handle dynamic indexing.
3460 */
3461 if ((!prog->IsES && prog->Version < 130) ||
3462 (prog->IsES && prog->Version < 300)) {
3463 if (!validate_sampler_array_indexing(ctx, prog))
3464 goto done;
3465 }
3466
Iago Toral Quiroga75896832014-06-16 16:09:53 +02003467 /* Check and validate stream emissions in geometry shaders */
3468 validate_geometry_shader_emissions(ctx, prog);
3469
Paul Berry50895d42012-12-05 07:17:07 -08003470 /* Mark all generic shader inputs and outputs as unpaired. */
Ian Romanick6bdc1d92014-02-11 16:37:56 -08003471 for (unsigned i = MESA_SHADER_VERTEX; i <= MESA_SHADER_FRAGMENT; i++) {
3472 if (prog->_LinkedShaders[i] != NULL) {
3473 link_invalidate_variable_locations(prog->_LinkedShaders[i]->ir);
3474 }
Paul Berry50895d42012-12-05 07:17:07 -08003475 }
3476
Timothy Arceri87d2e152015-07-08 09:20:40 +10003477 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_VERTEX,
3478 ctx->Const.Program[MESA_SHADER_VERTEX].MaxAttribs)) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07003479 goto done;
3480 }
3481
Dave Airlie1256a5d2012-03-24 13:33:41 +00003482 if (!assign_attribute_or_color_locations(prog, MESA_SHADER_FRAGMENT, MAX2(ctx->Const.MaxDrawBuffers, ctx->Const.MaxDualSourceDrawBuffers))) {
Ian Romanickd32d4f72011-06-27 17:59:58 -07003483 goto done;
Ian Romanick40e114b2010-08-17 14:55:50 -07003484 }
3485
Tapani Pälli993b9b62015-03-17 13:58:57 +02003486 unsigned first, last;
3487
3488 first = MESA_SHADER_STAGES;
3489 last = 0;
3490
3491 /* Determine first and last stage. */
3492 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3493 if (!prog->_LinkedShaders[i])
3494 continue;
3495 if (first == MESA_SHADER_STAGES)
3496 first = i;
3497 last = i;
Ian Romanick3322fba2010-10-14 13:28:42 -07003498 }
3499
Paul Berry871ddb92011-11-05 11:17:32 -07003500 if (num_tfeedback_decls != 0) {
3501 /* From GL_EXT_transform_feedback:
3502 * A program will fail to link if:
3503 *
3504 * * the <count> specified by TransformFeedbackVaryingsEXT is
3505 * non-zero, but the program object has no vertex or geometry
3506 * shader;
3507 */
Bryan Cain25480922013-02-15 09:46:50 -06003508 if (first == MESA_SHADER_FRAGMENT) {
Paul Berry871ddb92011-11-05 11:17:32 -07003509 linker_error(prog, "Transform feedback varyings specified, but "
Andres Gomezf9fc3ae2014-11-18 08:43:35 -07003510 "no vertex or geometry shader is present.\n");
Paul Berry871ddb92011-11-05 11:17:32 -07003511 goto done;
3512 }
3513
3514 tfeedback_decls = ralloc_array(mem_ctx, tfeedback_decl,
3515 prog->TransformFeedback.NumVarying);
Paul Berry456279b2011-12-26 19:39:25 -08003516 if (!parse_tfeedback_decls(ctx, prog, mem_ctx, num_tfeedback_decls,
Paul Berry871ddb92011-11-05 11:17:32 -07003517 prog->TransformFeedback.VaryingNames,
3518 tfeedback_decls))
3519 goto done;
3520 }
3521
Marek Olšák284d9542013-06-12 02:18:09 +02003522 /* Linking the stages in the opposite order (from fragment to vertex)
3523 * ensures that inter-shader outputs written to in an earlier stage are
3524 * eliminated if they are (transitively) not used in a later stage.
3525 */
Tapani Pälli993b9b62015-03-17 13:58:57 +02003526 int next;
Ian Romanick13e10e42010-06-21 12:03:24 -07003527
Tapani Pälli993b9b62015-03-17 13:58:57 +02003528 if (first < MESA_SHADER_FRAGMENT) {
Marek Olšák284d9542013-06-12 02:18:09 +02003529 gl_shader *const sh = prog->_LinkedShaders[last];
3530
Ian Romanicka909b992014-12-01 14:07:30 -08003531 if (first == MESA_SHADER_GEOMETRY) {
3532 /* There was no vertex shader, but we still have to assign varying
3533 * locations for use by geometry shader inputs in SSO.
3534 *
3535 * If the shader is not separable (i.e., prog->SeparateShader is
3536 * false), linking will have already failed when first is
3537 * MESA_SHADER_GEOMETRY.
3538 */
3539 if (!assign_varying_locations(ctx, mem_ctx, prog,
Tapani Pälli993b9b62015-03-17 13:58:57 +02003540 NULL, prog->_LinkedShaders[first],
Chris Forbes0e94f352014-09-07 18:19:15 +12003541 num_tfeedback_decls, tfeedback_decls))
Ian Romanicka909b992014-12-01 14:07:30 -08003542 goto done;
3543 }
3544
Tapani Pälli993b9b62015-03-17 13:58:57 +02003545 if (last != MESA_SHADER_FRAGMENT &&
3546 (num_tfeedback_decls != 0 || prog->SeparateShader)) {
Marek Olšák284d9542013-06-12 02:18:09 +02003547 /* There was no fragment shader, but we still have to assign varying
3548 * locations for use by transform feedback.
3549 */
3550 if (!assign_varying_locations(ctx, mem_ctx, prog,
3551 sh, NULL,
Chris Forbes0e94f352014-09-07 18:19:15 +12003552 num_tfeedback_decls, tfeedback_decls))
Marek Olšák284d9542013-06-12 02:18:09 +02003553 goto done;
3554 }
3555
Marek Olšákd13003f2013-08-09 22:34:45 +02003556 do_dead_builtin_varyings(ctx, sh, NULL,
Marek Olšákb3d8b4c2013-06-12 13:23:48 +02003557 num_tfeedback_decls, tfeedback_decls);
3558
Ian Romanick1ff5a2b2014-02-14 12:10:27 -08003559 if (!prog->SeparateShader)
3560 demote_shader_inputs_and_outputs(sh, ir_var_shader_out);
Marek Olšák284d9542013-06-12 02:18:09 +02003561
3562 /* Eliminate code that is now dead due to unused outputs being demoted.
Paul Berry871ddb92011-11-05 11:17:32 -07003563 */
Marek Olšák284d9542013-06-12 02:18:09 +02003564 while (do_dead_code(sh->ir, false))
3565 ;
3566 }
3567 else if (first == MESA_SHADER_FRAGMENT) {
Marek Olšákb3d8b4c2013-06-12 13:23:48 +02003568 /* If the program only contains a fragment shader...
Marek Olšák284d9542013-06-12 02:18:09 +02003569 */
3570 gl_shader *const sh = prog->_LinkedShaders[first];
3571
Marek Olšákd13003f2013-08-09 22:34:45 +02003572 do_dead_builtin_varyings(ctx, NULL, sh,
Marek Olšákb3d8b4c2013-06-12 13:23:48 +02003573 num_tfeedback_decls, tfeedback_decls);
3574
Ian Romanick1ff5a2b2014-02-14 12:10:27 -08003575 if (prog->SeparateShader) {
3576 if (!assign_varying_locations(ctx, mem_ctx, prog,
3577 NULL /* producer */,
3578 sh /* consumer */,
3579 0 /* num_tfeedback_decls */,
Chris Forbes0e94f352014-09-07 18:19:15 +12003580 NULL /* tfeedback_decls */))
Ian Romanick1ff5a2b2014-02-14 12:10:27 -08003581 goto done;
3582 } else
3583 demote_shader_inputs_and_outputs(sh, ir_var_shader_in);
Marek Olšák284d9542013-06-12 02:18:09 +02003584
3585 while (do_dead_code(sh->ir, false))
3586 ;
3587 }
3588
3589 next = last;
3590 for (int i = next - 1; i >= 0; i--) {
3591 if (prog->_LinkedShaders[i] == NULL)
3592 continue;
3593
3594 gl_shader *const sh_i = prog->_LinkedShaders[i];
3595 gl_shader *const sh_next = prog->_LinkedShaders[next];
3596
3597 if (!assign_varying_locations(ctx, mem_ctx, prog, sh_i, sh_next,
3598 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
Chris Forbes0e94f352014-09-07 18:19:15 +12003599 tfeedback_decls))
Paul Berry871ddb92011-11-05 11:17:32 -07003600 goto done;
Marek Olšák284d9542013-06-12 02:18:09 +02003601
Marek Olšákd13003f2013-08-09 22:34:45 +02003602 do_dead_builtin_varyings(ctx, sh_i, sh_next,
Marek Olšákb3d8b4c2013-06-12 13:23:48 +02003603 next == MESA_SHADER_FRAGMENT ? num_tfeedback_decls : 0,
3604 tfeedback_decls);
3605
Marek Olšák284d9542013-06-12 02:18:09 +02003606 demote_shader_inputs_and_outputs(sh_i, ir_var_shader_out);
3607 demote_shader_inputs_and_outputs(sh_next, ir_var_shader_in);
3608
3609 /* Eliminate code that is now dead due to unused outputs being demoted.
3610 */
3611 while (do_dead_code(sh_i->ir, false))
3612 ;
3613 while (do_dead_code(sh_next->ir, false))
3614 ;
3615
Marek Olšák3c555822013-06-13 03:17:22 +02003616 /* This must be done after all dead varyings are eliminated. */
Ian Romanick42305fb2013-09-10 12:00:34 -05003617 if (!check_against_output_limit(ctx, prog, sh_i))
3618 goto done;
3619 if (!check_against_input_limit(ctx, prog, sh_next))
Marek Olšák3c555822013-06-13 03:17:22 +02003620 goto done;
3621
Marek Olšák284d9542013-06-12 02:18:09 +02003622 next = i;
Paul Berry871ddb92011-11-05 11:17:32 -07003623 }
3624
3625 if (!store_tfeedback_info(ctx, prog, num_tfeedback_decls, tfeedback_decls))
3626 goto done;
3627
Ian Romanick960d7222011-10-21 11:21:02 -07003628 update_array_sizes(prog);
Matt Turner9e2e7c72014-08-08 19:46:05 -07003629 link_assign_uniform_locations(prog, ctx->Const.UniformBooleanTrue);
Francisco Jerez5c114932013-09-11 12:14:46 -07003630 link_assign_atomic_counter_resources(ctx, prog);
Marek Olšákec174a42011-11-18 15:00:10 +01003631 store_fragdepth_layout(prog);
Ian Romanick960d7222011-10-21 11:21:02 -07003632
Paul Berryb95d2372013-07-27 11:08:31 -07003633 check_resources(ctx, prog);
Francisco Jereze51158f2013-11-22 15:53:26 -08003634 check_image_resources(ctx, prog);
Francisco Jerez5c114932013-09-11 12:14:46 -07003635 link_check_atomic_counter_resources(ctx, prog);
3636
Paul Berryb95d2372013-07-27 11:08:31 -07003637 if (!prog->LinkStatus)
Ian Romanick92f81592011-11-08 12:37:19 -08003638 goto done;
3639
Ian Romanickce9171f2011-02-03 17:10:14 -08003640 /* OpenGL ES requires that a vertex shader and a fragment shader both be
Anuj Phogat03597cf2013-12-19 14:17:19 -08003641 * present in a linked program. GL_ARB_ES2_compatibility doesn't say
3642 * anything about shader linking when one of the shaders (vertex or
3643 * fragment shader) is absent. So, the extension shouldn't change the
3644 * behavior specified in GLSL specification.
Ian Romanickce9171f2011-02-03 17:10:14 -08003645 */
Ian Romanickf64bfb22014-03-27 10:29:30 -07003646 if (!prog->SeparateShader && ctx->API == API_OPENGLES2) {
Ian Romanickce9171f2011-02-03 17:10:14 -08003647 if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
Ian Romanick586e7412011-07-28 14:04:09 -07003648 linker_error(prog, "program lacks a vertex shader\n");
Ian Romanickce9171f2011-02-03 17:10:14 -08003649 } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
Ian Romanick586e7412011-07-28 14:04:09 -07003650 linker_error(prog, "program lacks a fragment shader\n");
Ian Romanickce9171f2011-02-03 17:10:14 -08003651 }
3652 }
3653
Ian Romanick13e10e42010-06-21 12:03:24 -07003654 /* FINISHME: Assign fragment shader output locations. */
3655
Ian Romanick832dfa52010-06-17 15:04:20 -07003656done:
Paul Berry665b8d72014-01-07 10:11:39 -08003657 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
Paul Berrycd18ba12014-01-07 08:56:57 -08003658 free(shader_list[i]);
Kenneth Graunke2da02e72010-11-17 11:03:57 -08003659 if (prog->_LinkedShaders[i] == NULL)
3660 continue;
3661
Paul Berryd7fa9eb2013-11-22 12:37:22 -08003662 /* Do a final validation step to make sure that the IR wasn't
3663 * invalidated by any modifications performed after intrastage linking.
3664 */
3665 validate_ir_tree(prog->_LinkedShaders[i]->ir);
3666
Kenneth Graunke2da02e72010-11-17 11:03:57 -08003667 /* Retain any live IR, but trash the rest. */
3668 reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
Ian Romanick7bbcc0b2011-09-30 14:21:10 -07003669
3670 /* The symbol table in the linked shaders may contain references to
3671 * variables that were removed (e.g., unused uniforms). Since it may
3672 * contain junk, there is no possible valid use. Delete it and set the
3673 * pointer to NULL.
3674 */
3675 delete prog->_LinkedShaders[i]->symbols;
3676 prog->_LinkedShaders[i]->symbols = NULL;
Kenneth Graunke2da02e72010-11-17 11:03:57 -08003677 }
3678
Kenneth Graunked3073f52011-01-21 14:32:31 -08003679 ralloc_free(mem_ctx);
Ian Romanick832dfa52010-06-17 15:04:20 -07003680}