glsl: Fix chained assignments of vector channels.
[mesa.git] / src / glsl / ast_to_hir.cpp
1 /*
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 ast_to_hir.c
26 * Convert abstract syntax to to high-level intermediate reprensentation (HIR).
27 *
28 * During the conversion to HIR, the majority of the symantic checking is
29 * preformed on the program. This includes:
30 *
31 * * Symbol table management
32 * * Type checking
33 * * Function binding
34 *
35 * The majority of this work could be done during parsing, and the parser could
36 * probably generate HIR directly. However, this results in frequent changes
37 * to the parser code. Since we do not assume that every system this complier
38 * is built on will have Flex and Bison installed, we have to store the code
39 * generated by these tools in our version control system. In other parts of
40 * the system we've seen problems where a parser was changed but the generated
41 * code was not committed, merge conflicts where created because two developers
42 * had slightly different versions of Bison installed, etc.
43 *
44 * I have also noticed that running Bison generated parsers in GDB is very
45 * irritating. When you get a segfault on '$$ = $1->foo', you can't very
46 * well 'print $1' in GDB.
47 *
48 * As a result, my preference is to put as little C code as possible in the
49 * parser (and lexer) sources.
50 */
51
52 #include "main/core.h" /* for struct gl_extensions */
53 #include "glsl_symbol_table.h"
54 #include "glsl_parser_extras.h"
55 #include "ast.h"
56 #include "glsl_types.h"
57 #include "program/hash_table.h"
58 #include "ir.h"
59
60 static void
61 detect_conflicting_assignments(struct _mesa_glsl_parse_state *state,
62 exec_list *instructions);
63 static void
64 remove_per_vertex_blocks(exec_list *instructions,
65 _mesa_glsl_parse_state *state, ir_variable_mode mode);
66
67
68 void
69 _mesa_ast_to_hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)
70 {
71 _mesa_glsl_initialize_variables(instructions, state);
72
73 state->symbols->separate_function_namespace = state->language_version == 110;
74
75 state->current_function = NULL;
76
77 state->toplevel_ir = instructions;
78
79 state->gs_input_prim_type_specified = false;
80
81 /* Section 4.2 of the GLSL 1.20 specification states:
82 * "The built-in functions are scoped in a scope outside the global scope
83 * users declare global variables in. That is, a shader's global scope,
84 * available for user-defined functions and global variables, is nested
85 * inside the scope containing the built-in functions."
86 *
87 * Since built-in functions like ftransform() access built-in variables,
88 * it follows that those must be in the outer scope as well.
89 *
90 * We push scope here to create this nesting effect...but don't pop.
91 * This way, a shader's globals are still in the symbol table for use
92 * by the linker.
93 */
94 state->symbols->push_scope();
95
96 foreach_list_typed (ast_node, ast, link, & state->translation_unit)
97 ast->hir(instructions, state);
98
99 detect_recursion_unlinked(state, instructions);
100 detect_conflicting_assignments(state, instructions);
101
102 state->toplevel_ir = NULL;
103
104 /* Move all of the variable declarations to the front of the IR list, and
105 * reverse the order. This has the (intended!) side effect that vertex
106 * shader inputs and fragment shader outputs will appear in the IR in the
107 * same order that they appeared in the shader code. This results in the
108 * locations being assigned in the declared order. Many (arguably buggy)
109 * applications depend on this behavior, and it matches what nearly all
110 * other drivers do.
111 */
112 foreach_list_safe(node, instructions) {
113 ir_variable *const var = ((ir_instruction *) node)->as_variable();
114
115 if (var == NULL)
116 continue;
117
118 var->remove();
119 instructions->push_head(var);
120 }
121
122 /* From section 7.1 (Built-In Language Variables) of the GLSL 4.10 spec:
123 *
124 * If multiple shaders using members of a built-in block belonging to
125 * the same interface are linked together in the same program, they
126 * must all redeclare the built-in block in the same way, as described
127 * in section 4.3.7 "Interface Blocks" for interface block matching, or
128 * a link error will result.
129 *
130 * The phrase "using members of a built-in block" implies that if two
131 * shaders are linked together and one of them *does not use* any members
132 * of the built-in block, then that shader does not need to have a matching
133 * redeclaration of the built-in block.
134 *
135 * This appears to be a clarification to the behaviour established for
136 * gl_PerVertex by GLSL 1.50, therefore implement it regardless of GLSL
137 * version.
138 *
139 * The definition of "interface" in section 4.3.7 that applies here is as
140 * follows:
141 *
142 * The boundary between adjacent programmable pipeline stages: This
143 * spans all the outputs in all compilation units of the first stage
144 * and all the inputs in all compilation units of the second stage.
145 *
146 * Therefore this rule applies to both inter- and intra-stage linking.
147 *
148 * The easiest way to implement this is to check whether the shader uses
149 * gl_PerVertex right after ast-to-ir conversion, and if it doesn't, simply
150 * remove all the relevant variable declaration from the IR, so that the
151 * linker won't see them and complain about mismatches.
152 */
153 remove_per_vertex_blocks(instructions, state, ir_var_shader_in);
154 remove_per_vertex_blocks(instructions, state, ir_var_shader_out);
155 }
156
157
158 /**
159 * If a conversion is available, convert one operand to a different type
160 *
161 * The \c from \c ir_rvalue is converted "in place".
162 *
163 * \param to Type that the operand it to be converted to
164 * \param from Operand that is being converted
165 * \param state GLSL compiler state
166 *
167 * \return
168 * If a conversion is possible (or unnecessary), \c true is returned.
169 * Otherwise \c false is returned.
170 */
171 bool
172 apply_implicit_conversion(const glsl_type *to, ir_rvalue * &from,
173 struct _mesa_glsl_parse_state *state)
174 {
175 void *ctx = state;
176 if (to->base_type == from->type->base_type)
177 return true;
178
179 /* This conversion was added in GLSL 1.20. If the compilation mode is
180 * GLSL 1.10, the conversion is skipped.
181 */
182 if (!state->is_version(120, 0))
183 return false;
184
185 /* From page 27 (page 33 of the PDF) of the GLSL 1.50 spec:
186 *
187 * "There are no implicit array or structure conversions. For
188 * example, an array of int cannot be implicitly converted to an
189 * array of float. There are no implicit conversions between
190 * signed and unsigned integers."
191 */
192 /* FINISHME: The above comment is partially a lie. There is int/uint
193 * FINISHME: conversion for immediate constants.
194 */
195 if (!to->is_float() || !from->type->is_numeric())
196 return false;
197
198 /* Convert to a floating point type with the same number of components
199 * as the original type - i.e. int to float, not int to vec4.
200 */
201 to = glsl_type::get_instance(GLSL_TYPE_FLOAT, from->type->vector_elements,
202 from->type->matrix_columns);
203
204 switch (from->type->base_type) {
205 case GLSL_TYPE_INT:
206 from = new(ctx) ir_expression(ir_unop_i2f, to, from, NULL);
207 break;
208 case GLSL_TYPE_UINT:
209 from = new(ctx) ir_expression(ir_unop_u2f, to, from, NULL);
210 break;
211 case GLSL_TYPE_BOOL:
212 from = new(ctx) ir_expression(ir_unop_b2f, to, from, NULL);
213 break;
214 default:
215 assert(0);
216 }
217
218 return true;
219 }
220
221
222 static const struct glsl_type *
223 arithmetic_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
224 bool multiply,
225 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
226 {
227 const glsl_type *type_a = value_a->type;
228 const glsl_type *type_b = value_b->type;
229
230 /* From GLSL 1.50 spec, page 56:
231 *
232 * "The arithmetic binary operators add (+), subtract (-),
233 * multiply (*), and divide (/) operate on integer and
234 * floating-point scalars, vectors, and matrices."
235 */
236 if (!type_a->is_numeric() || !type_b->is_numeric()) {
237 _mesa_glsl_error(loc, state,
238 "operands to arithmetic operators must be numeric");
239 return glsl_type::error_type;
240 }
241
242
243 /* "If one operand is floating-point based and the other is
244 * not, then the conversions from Section 4.1.10 "Implicit
245 * Conversions" are applied to the non-floating-point-based operand."
246 */
247 if (!apply_implicit_conversion(type_a, value_b, state)
248 && !apply_implicit_conversion(type_b, value_a, state)) {
249 _mesa_glsl_error(loc, state,
250 "could not implicitly convert operands to "
251 "arithmetic operator");
252 return glsl_type::error_type;
253 }
254 type_a = value_a->type;
255 type_b = value_b->type;
256
257 /* "If the operands are integer types, they must both be signed or
258 * both be unsigned."
259 *
260 * From this rule and the preceeding conversion it can be inferred that
261 * both types must be GLSL_TYPE_FLOAT, or GLSL_TYPE_UINT, or GLSL_TYPE_INT.
262 * The is_numeric check above already filtered out the case where either
263 * type is not one of these, so now the base types need only be tested for
264 * equality.
265 */
266 if (type_a->base_type != type_b->base_type) {
267 _mesa_glsl_error(loc, state,
268 "base type mismatch for arithmetic operator");
269 return glsl_type::error_type;
270 }
271
272 /* "All arithmetic binary operators result in the same fundamental type
273 * (signed integer, unsigned integer, or floating-point) as the
274 * operands they operate on, after operand type conversion. After
275 * conversion, the following cases are valid
276 *
277 * * The two operands are scalars. In this case the operation is
278 * applied, resulting in a scalar."
279 */
280 if (type_a->is_scalar() && type_b->is_scalar())
281 return type_a;
282
283 /* "* One operand is a scalar, and the other is a vector or matrix.
284 * In this case, the scalar operation is applied independently to each
285 * component of the vector or matrix, resulting in the same size
286 * vector or matrix."
287 */
288 if (type_a->is_scalar()) {
289 if (!type_b->is_scalar())
290 return type_b;
291 } else if (type_b->is_scalar()) {
292 return type_a;
293 }
294
295 /* All of the combinations of <scalar, scalar>, <vector, scalar>,
296 * <scalar, vector>, <scalar, matrix>, and <matrix, scalar> have been
297 * handled.
298 */
299 assert(!type_a->is_scalar());
300 assert(!type_b->is_scalar());
301
302 /* "* The two operands are vectors of the same size. In this case, the
303 * operation is done component-wise resulting in the same size
304 * vector."
305 */
306 if (type_a->is_vector() && type_b->is_vector()) {
307 if (type_a == type_b) {
308 return type_a;
309 } else {
310 _mesa_glsl_error(loc, state,
311 "vector size mismatch for arithmetic operator");
312 return glsl_type::error_type;
313 }
314 }
315
316 /* All of the combinations of <scalar, scalar>, <vector, scalar>,
317 * <scalar, vector>, <scalar, matrix>, <matrix, scalar>, and
318 * <vector, vector> have been handled. At least one of the operands must
319 * be matrix. Further, since there are no integer matrix types, the base
320 * type of both operands must be float.
321 */
322 assert(type_a->is_matrix() || type_b->is_matrix());
323 assert(type_a->base_type == GLSL_TYPE_FLOAT);
324 assert(type_b->base_type == GLSL_TYPE_FLOAT);
325
326 /* "* The operator is add (+), subtract (-), or divide (/), and the
327 * operands are matrices with the same number of rows and the same
328 * number of columns. In this case, the operation is done component-
329 * wise resulting in the same size matrix."
330 * * The operator is multiply (*), where both operands are matrices or
331 * one operand is a vector and the other a matrix. A right vector
332 * operand is treated as a column vector and a left vector operand as a
333 * row vector. In all these cases, it is required that the number of
334 * columns of the left operand is equal to the number of rows of the
335 * right operand. Then, the multiply (*) operation does a linear
336 * algebraic multiply, yielding an object that has the same number of
337 * rows as the left operand and the same number of columns as the right
338 * operand. Section 5.10 "Vector and Matrix Operations" explains in
339 * more detail how vectors and matrices are operated on."
340 */
341 if (! multiply) {
342 if (type_a == type_b)
343 return type_a;
344 } else {
345 if (type_a->is_matrix() && type_b->is_matrix()) {
346 /* Matrix multiply. The columns of A must match the rows of B. Given
347 * the other previously tested constraints, this means the vector type
348 * of a row from A must be the same as the vector type of a column from
349 * B.
350 */
351 if (type_a->row_type() == type_b->column_type()) {
352 /* The resulting matrix has the number of columns of matrix B and
353 * the number of rows of matrix A. We get the row count of A by
354 * looking at the size of a vector that makes up a column. The
355 * transpose (size of a row) is done for B.
356 */
357 const glsl_type *const type =
358 glsl_type::get_instance(type_a->base_type,
359 type_a->column_type()->vector_elements,
360 type_b->row_type()->vector_elements);
361 assert(type != glsl_type::error_type);
362
363 return type;
364 }
365 } else if (type_a->is_matrix()) {
366 /* A is a matrix and B is a column vector. Columns of A must match
367 * rows of B. Given the other previously tested constraints, this
368 * means the vector type of a row from A must be the same as the
369 * vector the type of B.
370 */
371 if (type_a->row_type() == type_b) {
372 /* The resulting vector has a number of elements equal to
373 * the number of rows of matrix A. */
374 const glsl_type *const type =
375 glsl_type::get_instance(type_a->base_type,
376 type_a->column_type()->vector_elements,
377 1);
378 assert(type != glsl_type::error_type);
379
380 return type;
381 }
382 } else {
383 assert(type_b->is_matrix());
384
385 /* A is a row vector and B is a matrix. Columns of A must match rows
386 * of B. Given the other previously tested constraints, this means
387 * the type of A must be the same as the vector type of a column from
388 * B.
389 */
390 if (type_a == type_b->column_type()) {
391 /* The resulting vector has a number of elements equal to
392 * the number of columns of matrix B. */
393 const glsl_type *const type =
394 glsl_type::get_instance(type_a->base_type,
395 type_b->row_type()->vector_elements,
396 1);
397 assert(type != glsl_type::error_type);
398
399 return type;
400 }
401 }
402
403 _mesa_glsl_error(loc, state, "size mismatch for matrix multiplication");
404 return glsl_type::error_type;
405 }
406
407
408 /* "All other cases are illegal."
409 */
410 _mesa_glsl_error(loc, state, "type mismatch");
411 return glsl_type::error_type;
412 }
413
414
415 static const struct glsl_type *
416 unary_arithmetic_result_type(const struct glsl_type *type,
417 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
418 {
419 /* From GLSL 1.50 spec, page 57:
420 *
421 * "The arithmetic unary operators negate (-), post- and pre-increment
422 * and decrement (-- and ++) operate on integer or floating-point
423 * values (including vectors and matrices). All unary operators work
424 * component-wise on their operands. These result with the same type
425 * they operated on."
426 */
427 if (!type->is_numeric()) {
428 _mesa_glsl_error(loc, state,
429 "operands to arithmetic operators must be numeric");
430 return glsl_type::error_type;
431 }
432
433 return type;
434 }
435
436 /**
437 * \brief Return the result type of a bit-logic operation.
438 *
439 * If the given types to the bit-logic operator are invalid, return
440 * glsl_type::error_type.
441 *
442 * \param type_a Type of LHS of bit-logic op
443 * \param type_b Type of RHS of bit-logic op
444 */
445 static const struct glsl_type *
446 bit_logic_result_type(const struct glsl_type *type_a,
447 const struct glsl_type *type_b,
448 ast_operators op,
449 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
450 {
451 if (!state->check_bitwise_operations_allowed(loc)) {
452 return glsl_type::error_type;
453 }
454
455 /* From page 50 (page 56 of PDF) of GLSL 1.30 spec:
456 *
457 * "The bitwise operators and (&), exclusive-or (^), and inclusive-or
458 * (|). The operands must be of type signed or unsigned integers or
459 * integer vectors."
460 */
461 if (!type_a->is_integer()) {
462 _mesa_glsl_error(loc, state, "LHS of `%s' must be an integer",
463 ast_expression::operator_string(op));
464 return glsl_type::error_type;
465 }
466 if (!type_b->is_integer()) {
467 _mesa_glsl_error(loc, state, "RHS of `%s' must be an integer",
468 ast_expression::operator_string(op));
469 return glsl_type::error_type;
470 }
471
472 /* "The fundamental types of the operands (signed or unsigned) must
473 * match,"
474 */
475 if (type_a->base_type != type_b->base_type) {
476 _mesa_glsl_error(loc, state, "operands of `%s' must have the same "
477 "base type", ast_expression::operator_string(op));
478 return glsl_type::error_type;
479 }
480
481 /* "The operands cannot be vectors of differing size." */
482 if (type_a->is_vector() &&
483 type_b->is_vector() &&
484 type_a->vector_elements != type_b->vector_elements) {
485 _mesa_glsl_error(loc, state, "operands of `%s' cannot be vectors of "
486 "different sizes", ast_expression::operator_string(op));
487 return glsl_type::error_type;
488 }
489
490 /* "If one operand is a scalar and the other a vector, the scalar is
491 * applied component-wise to the vector, resulting in the same type as
492 * the vector. The fundamental types of the operands [...] will be the
493 * resulting fundamental type."
494 */
495 if (type_a->is_scalar())
496 return type_b;
497 else
498 return type_a;
499 }
500
501 static const struct glsl_type *
502 modulus_result_type(const struct glsl_type *type_a,
503 const struct glsl_type *type_b,
504 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
505 {
506 if (!state->check_version(130, 300, loc, "operator '%%' is reserved")) {
507 return glsl_type::error_type;
508 }
509
510 /* From GLSL 1.50 spec, page 56:
511 * "The operator modulus (%) operates on signed or unsigned integers or
512 * integer vectors. The operand types must both be signed or both be
513 * unsigned."
514 */
515 if (!type_a->is_integer()) {
516 _mesa_glsl_error(loc, state, "LHS of operator %% must be an integer");
517 return glsl_type::error_type;
518 }
519 if (!type_b->is_integer()) {
520 _mesa_glsl_error(loc, state, "RHS of operator %% must be an integer");
521 return glsl_type::error_type;
522 }
523 if (type_a->base_type != type_b->base_type) {
524 _mesa_glsl_error(loc, state,
525 "operands of %% must have the same base type");
526 return glsl_type::error_type;
527 }
528
529 /* "The operands cannot be vectors of differing size. If one operand is
530 * a scalar and the other vector, then the scalar is applied component-
531 * wise to the vector, resulting in the same type as the vector. If both
532 * are vectors of the same size, the result is computed component-wise."
533 */
534 if (type_a->is_vector()) {
535 if (!type_b->is_vector()
536 || (type_a->vector_elements == type_b->vector_elements))
537 return type_a;
538 } else
539 return type_b;
540
541 /* "The operator modulus (%) is not defined for any other data types
542 * (non-integer types)."
543 */
544 _mesa_glsl_error(loc, state, "type mismatch");
545 return glsl_type::error_type;
546 }
547
548
549 static const struct glsl_type *
550 relational_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
551 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
552 {
553 const glsl_type *type_a = value_a->type;
554 const glsl_type *type_b = value_b->type;
555
556 /* From GLSL 1.50 spec, page 56:
557 * "The relational operators greater than (>), less than (<), greater
558 * than or equal (>=), and less than or equal (<=) operate only on
559 * scalar integer and scalar floating-point expressions."
560 */
561 if (!type_a->is_numeric()
562 || !type_b->is_numeric()
563 || !type_a->is_scalar()
564 || !type_b->is_scalar()) {
565 _mesa_glsl_error(loc, state,
566 "operands to relational operators must be scalar and "
567 "numeric");
568 return glsl_type::error_type;
569 }
570
571 /* "Either the operands' types must match, or the conversions from
572 * Section 4.1.10 "Implicit Conversions" will be applied to the integer
573 * operand, after which the types must match."
574 */
575 if (!apply_implicit_conversion(type_a, value_b, state)
576 && !apply_implicit_conversion(type_b, value_a, state)) {
577 _mesa_glsl_error(loc, state,
578 "could not implicitly convert operands to "
579 "relational operator");
580 return glsl_type::error_type;
581 }
582 type_a = value_a->type;
583 type_b = value_b->type;
584
585 if (type_a->base_type != type_b->base_type) {
586 _mesa_glsl_error(loc, state, "base type mismatch");
587 return glsl_type::error_type;
588 }
589
590 /* "The result is scalar Boolean."
591 */
592 return glsl_type::bool_type;
593 }
594
595 /**
596 * \brief Return the result type of a bit-shift operation.
597 *
598 * If the given types to the bit-shift operator are invalid, return
599 * glsl_type::error_type.
600 *
601 * \param type_a Type of LHS of bit-shift op
602 * \param type_b Type of RHS of bit-shift op
603 */
604 static const struct glsl_type *
605 shift_result_type(const struct glsl_type *type_a,
606 const struct glsl_type *type_b,
607 ast_operators op,
608 struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
609 {
610 if (!state->check_bitwise_operations_allowed(loc)) {
611 return glsl_type::error_type;
612 }
613
614 /* From page 50 (page 56 of the PDF) of the GLSL 1.30 spec:
615 *
616 * "The shift operators (<<) and (>>). For both operators, the operands
617 * must be signed or unsigned integers or integer vectors. One operand
618 * can be signed while the other is unsigned."
619 */
620 if (!type_a->is_integer()) {
621 _mesa_glsl_error(loc, state, "LHS of operator %s must be an integer or "
622 "integer vector", ast_expression::operator_string(op));
623 return glsl_type::error_type;
624
625 }
626 if (!type_b->is_integer()) {
627 _mesa_glsl_error(loc, state, "RHS of operator %s must be an integer or "
628 "integer vector", ast_expression::operator_string(op));
629 return glsl_type::error_type;
630 }
631
632 /* "If the first operand is a scalar, the second operand has to be
633 * a scalar as well."
634 */
635 if (type_a->is_scalar() && !type_b->is_scalar()) {
636 _mesa_glsl_error(loc, state, "if the first operand of %s is scalar, the "
637 "second must be scalar as well",
638 ast_expression::operator_string(op));
639 return glsl_type::error_type;
640 }
641
642 /* If both operands are vectors, check that they have same number of
643 * elements.
644 */
645 if (type_a->is_vector() &&
646 type_b->is_vector() &&
647 type_a->vector_elements != type_b->vector_elements) {
648 _mesa_glsl_error(loc, state, "vector operands to operator %s must "
649 "have same number of elements",
650 ast_expression::operator_string(op));
651 return glsl_type::error_type;
652 }
653
654 /* "In all cases, the resulting type will be the same type as the left
655 * operand."
656 */
657 return type_a;
658 }
659
660 /**
661 * Validates that a value can be assigned to a location with a specified type
662 *
663 * Validates that \c rhs can be assigned to some location. If the types are
664 * not an exact match but an automatic conversion is possible, \c rhs will be
665 * converted.
666 *
667 * \return
668 * \c NULL if \c rhs cannot be assigned to a location with type \c lhs_type.
669 * Otherwise the actual RHS to be assigned will be returned. This may be
670 * \c rhs, or it may be \c rhs after some type conversion.
671 *
672 * \note
673 * In addition to being used for assignments, this function is used to
674 * type-check return values.
675 */
676 ir_rvalue *
677 validate_assignment(struct _mesa_glsl_parse_state *state,
678 YYLTYPE loc, const glsl_type *lhs_type,
679 ir_rvalue *rhs, bool is_initializer)
680 {
681 /* If there is already some error in the RHS, just return it. Anything
682 * else will lead to an avalanche of error message back to the user.
683 */
684 if (rhs->type->is_error())
685 return rhs;
686
687 /* If the types are identical, the assignment can trivially proceed.
688 */
689 if (rhs->type == lhs_type)
690 return rhs;
691
692 /* If the array element types are the same and the LHS is unsized,
693 * the assignment is okay for initializers embedded in variable
694 * declarations.
695 *
696 * Note: Whole-array assignments are not permitted in GLSL 1.10, but this
697 * is handled by ir_dereference::is_lvalue.
698 */
699 if (lhs_type->is_unsized_array() && rhs->type->is_array()
700 && (lhs_type->element_type() == rhs->type->element_type())) {
701 if (is_initializer) {
702 return rhs;
703 } else {
704 _mesa_glsl_error(&loc, state,
705 "implicitly sized arrays cannot be assigned");
706 return NULL;
707 }
708 }
709
710 /* Check for implicit conversion in GLSL 1.20 */
711 if (apply_implicit_conversion(lhs_type, rhs, state)) {
712 if (rhs->type == lhs_type)
713 return rhs;
714 }
715
716 _mesa_glsl_error(&loc, state,
717 "%s of type %s cannot be assigned to "
718 "variable of type %s",
719 is_initializer ? "initializer" : "value",
720 rhs->type->name, lhs_type->name);
721
722 return NULL;
723 }
724
725 static void
726 mark_whole_array_access(ir_rvalue *access)
727 {
728 ir_dereference_variable *deref = access->as_dereference_variable();
729
730 if (deref && deref->var) {
731 deref->var->data.max_array_access = deref->type->length - 1;
732 }
733 }
734
735 ir_rvalue *
736 do_assignment(exec_list *instructions, struct _mesa_glsl_parse_state *state,
737 const char *non_lvalue_description,
738 ir_rvalue *lhs, ir_rvalue *rhs, bool is_initializer,
739 YYLTYPE lhs_loc)
740 {
741 void *ctx = state;
742 bool error_emitted = (lhs->type->is_error() || rhs->type->is_error());
743 ir_rvalue *extract_channel = NULL;
744
745 /* If the assignment LHS comes back as an ir_binop_vector_extract
746 * expression, move it to the RHS as an ir_triop_vector_insert.
747 */
748 if (lhs->ir_type == ir_type_expression) {
749 ir_expression *const lhs_expr = lhs->as_expression();
750
751 if (unlikely(lhs_expr->operation == ir_binop_vector_extract)) {
752 ir_rvalue *new_rhs =
753 validate_assignment(state, lhs_loc, lhs->type,
754 rhs, is_initializer);
755
756 if (new_rhs == NULL) {
757 return lhs;
758 } else {
759 /* This converts:
760 * - LHS: (expression float vector_extract <vec> <channel>)
761 * - RHS: <scalar>
762 * into:
763 * - LHS: <vec>
764 * - RHS: (expression vec2 vector_insert <vec> <channel> <scalar>)
765 *
766 * The LHS type is now a vector instead of a scalar. Since GLSL
767 * allows assignments to be used as rvalues, we need to re-extract
768 * the channel from assignment_temp when returning the rvalue.
769 */
770 extract_channel = lhs_expr->operands[1];
771 rhs = new(ctx) ir_expression(ir_triop_vector_insert,
772 lhs_expr->operands[0]->type,
773 lhs_expr->operands[0],
774 new_rhs,
775 extract_channel);
776 lhs = lhs_expr->operands[0]->clone(ctx, NULL);
777 }
778 }
779 }
780
781 ir_variable *lhs_var = lhs->variable_referenced();
782 if (lhs_var)
783 lhs_var->data.assigned = true;
784
785 if (!error_emitted) {
786 if (non_lvalue_description != NULL) {
787 _mesa_glsl_error(&lhs_loc, state,
788 "assignment to %s",
789 non_lvalue_description);
790 error_emitted = true;
791 } else if (lhs->variable_referenced() != NULL
792 && lhs->variable_referenced()->data.read_only) {
793 _mesa_glsl_error(&lhs_loc, state,
794 "assignment to read-only variable '%s'",
795 lhs->variable_referenced()->name);
796 error_emitted = true;
797
798 } else if (lhs->type->is_array() &&
799 !state->check_version(120, 300, &lhs_loc,
800 "whole array assignment forbidden")) {
801 /* From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
802 *
803 * "Other binary or unary expressions, non-dereferenced
804 * arrays, function names, swizzles with repeated fields,
805 * and constants cannot be l-values."
806 *
807 * The restriction on arrays is lifted in GLSL 1.20 and GLSL ES 3.00.
808 */
809 error_emitted = true;
810 } else if (!lhs->is_lvalue()) {
811 _mesa_glsl_error(& lhs_loc, state, "non-lvalue in assignment");
812 error_emitted = true;
813 }
814 }
815
816 ir_rvalue *new_rhs =
817 validate_assignment(state, lhs_loc, lhs->type, rhs, is_initializer);
818 if (new_rhs != NULL) {
819 rhs = new_rhs;
820
821 /* If the LHS array was not declared with a size, it takes it size from
822 * the RHS. If the LHS is an l-value and a whole array, it must be a
823 * dereference of a variable. Any other case would require that the LHS
824 * is either not an l-value or not a whole array.
825 */
826 if (lhs->type->is_unsized_array()) {
827 ir_dereference *const d = lhs->as_dereference();
828
829 assert(d != NULL);
830
831 ir_variable *const var = d->variable_referenced();
832
833 assert(var != NULL);
834
835 if (var->data.max_array_access >= unsigned(rhs->type->array_size())) {
836 /* FINISHME: This should actually log the location of the RHS. */
837 _mesa_glsl_error(& lhs_loc, state, "array size must be > %u due to "
838 "previous access",
839 var->data.max_array_access);
840 }
841
842 var->type = glsl_type::get_array_instance(lhs->type->element_type(),
843 rhs->type->array_size());
844 d->type = var->type;
845 }
846 if (lhs->type->is_array()) {
847 mark_whole_array_access(rhs);
848 mark_whole_array_access(lhs);
849 }
850 }
851
852 /* Most callers of do_assignment (assign, add_assign, pre_inc/dec,
853 * but not post_inc) need the converted assigned value as an rvalue
854 * to handle things like:
855 *
856 * i = j += 1;
857 *
858 * So we always just store the computed value being assigned to a
859 * temporary and return a deref of that temporary. If the rvalue
860 * ends up not being used, the temp will get copy-propagated out.
861 */
862 ir_variable *var = new(ctx) ir_variable(rhs->type, "assignment_tmp",
863 ir_var_temporary);
864 ir_dereference_variable *deref_var = new(ctx) ir_dereference_variable(var);
865 instructions->push_tail(var);
866 instructions->push_tail(new(ctx) ir_assignment(deref_var, rhs));
867 deref_var = new(ctx) ir_dereference_variable(var);
868
869 if (!error_emitted)
870 instructions->push_tail(new(ctx) ir_assignment(lhs, deref_var));
871
872 if (extract_channel) {
873 return new(ctx) ir_expression(ir_binop_vector_extract,
874 new(ctx) ir_dereference_variable(var),
875 extract_channel->clone(ctx, NULL));
876 }
877 return new(ctx) ir_dereference_variable(var);
878 }
879
880 static ir_rvalue *
881 get_lvalue_copy(exec_list *instructions, ir_rvalue *lvalue)
882 {
883 void *ctx = ralloc_parent(lvalue);
884 ir_variable *var;
885
886 var = new(ctx) ir_variable(lvalue->type, "_post_incdec_tmp",
887 ir_var_temporary);
888 instructions->push_tail(var);
889 var->data.mode = ir_var_auto;
890
891 instructions->push_tail(new(ctx) ir_assignment(new(ctx) ir_dereference_variable(var),
892 lvalue));
893
894 return new(ctx) ir_dereference_variable(var);
895 }
896
897
898 ir_rvalue *
899 ast_node::hir(exec_list *instructions,
900 struct _mesa_glsl_parse_state *state)
901 {
902 (void) instructions;
903 (void) state;
904
905 return NULL;
906 }
907
908 static ir_rvalue *
909 do_comparison(void *mem_ctx, int operation, ir_rvalue *op0, ir_rvalue *op1)
910 {
911 int join_op;
912 ir_rvalue *cmp = NULL;
913
914 if (operation == ir_binop_all_equal)
915 join_op = ir_binop_logic_and;
916 else
917 join_op = ir_binop_logic_or;
918
919 switch (op0->type->base_type) {
920 case GLSL_TYPE_FLOAT:
921 case GLSL_TYPE_UINT:
922 case GLSL_TYPE_INT:
923 case GLSL_TYPE_BOOL:
924 return new(mem_ctx) ir_expression(operation, op0, op1);
925
926 case GLSL_TYPE_ARRAY: {
927 for (unsigned int i = 0; i < op0->type->length; i++) {
928 ir_rvalue *e0, *e1, *result;
929
930 e0 = new(mem_ctx) ir_dereference_array(op0->clone(mem_ctx, NULL),
931 new(mem_ctx) ir_constant(i));
932 e1 = new(mem_ctx) ir_dereference_array(op1->clone(mem_ctx, NULL),
933 new(mem_ctx) ir_constant(i));
934 result = do_comparison(mem_ctx, operation, e0, e1);
935
936 if (cmp) {
937 cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
938 } else {
939 cmp = result;
940 }
941 }
942
943 mark_whole_array_access(op0);
944 mark_whole_array_access(op1);
945 break;
946 }
947
948 case GLSL_TYPE_STRUCT: {
949 for (unsigned int i = 0; i < op0->type->length; i++) {
950 ir_rvalue *e0, *e1, *result;
951 const char *field_name = op0->type->fields.structure[i].name;
952
953 e0 = new(mem_ctx) ir_dereference_record(op0->clone(mem_ctx, NULL),
954 field_name);
955 e1 = new(mem_ctx) ir_dereference_record(op1->clone(mem_ctx, NULL),
956 field_name);
957 result = do_comparison(mem_ctx, operation, e0, e1);
958
959 if (cmp) {
960 cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
961 } else {
962 cmp = result;
963 }
964 }
965 break;
966 }
967
968 case GLSL_TYPE_ERROR:
969 case GLSL_TYPE_VOID:
970 case GLSL_TYPE_SAMPLER:
971 case GLSL_TYPE_INTERFACE:
972 case GLSL_TYPE_ATOMIC_UINT:
973 /* I assume a comparison of a struct containing a sampler just
974 * ignores the sampler present in the type.
975 */
976 break;
977 }
978
979 if (cmp == NULL)
980 cmp = new(mem_ctx) ir_constant(true);
981
982 return cmp;
983 }
984
985 /* For logical operations, we want to ensure that the operands are
986 * scalar booleans. If it isn't, emit an error and return a constant
987 * boolean to avoid triggering cascading error messages.
988 */
989 ir_rvalue *
990 get_scalar_boolean_operand(exec_list *instructions,
991 struct _mesa_glsl_parse_state *state,
992 ast_expression *parent_expr,
993 int operand,
994 const char *operand_name,
995 bool *error_emitted)
996 {
997 ast_expression *expr = parent_expr->subexpressions[operand];
998 void *ctx = state;
999 ir_rvalue *val = expr->hir(instructions, state);
1000
1001 if (val->type->is_boolean() && val->type->is_scalar())
1002 return val;
1003
1004 if (!*error_emitted) {
1005 YYLTYPE loc = expr->get_location();
1006 _mesa_glsl_error(&loc, state, "%s of `%s' must be scalar boolean",
1007 operand_name,
1008 parent_expr->operator_string(parent_expr->oper));
1009 *error_emitted = true;
1010 }
1011
1012 return new(ctx) ir_constant(true);
1013 }
1014
1015 /**
1016 * If name refers to a builtin array whose maximum allowed size is less than
1017 * size, report an error and return true. Otherwise return false.
1018 */
1019 void
1020 check_builtin_array_max_size(const char *name, unsigned size,
1021 YYLTYPE loc, struct _mesa_glsl_parse_state *state)
1022 {
1023 if ((strcmp("gl_TexCoord", name) == 0)
1024 && (size > state->Const.MaxTextureCoords)) {
1025 /* From page 54 (page 60 of the PDF) of the GLSL 1.20 spec:
1026 *
1027 * "The size [of gl_TexCoord] can be at most
1028 * gl_MaxTextureCoords."
1029 */
1030 _mesa_glsl_error(&loc, state, "`gl_TexCoord' array size cannot "
1031 "be larger than gl_MaxTextureCoords (%u)",
1032 state->Const.MaxTextureCoords);
1033 } else if (strcmp("gl_ClipDistance", name) == 0
1034 && size > state->Const.MaxClipPlanes) {
1035 /* From section 7.1 (Vertex Shader Special Variables) of the
1036 * GLSL 1.30 spec:
1037 *
1038 * "The gl_ClipDistance array is predeclared as unsized and
1039 * must be sized by the shader either redeclaring it with a
1040 * size or indexing it only with integral constant
1041 * expressions. ... The size can be at most
1042 * gl_MaxClipDistances."
1043 */
1044 _mesa_glsl_error(&loc, state, "`gl_ClipDistance' array size cannot "
1045 "be larger than gl_MaxClipDistances (%u)",
1046 state->Const.MaxClipPlanes);
1047 }
1048 }
1049
1050 /**
1051 * Create the constant 1, of a which is appropriate for incrementing and
1052 * decrementing values of the given GLSL type. For example, if type is vec4,
1053 * this creates a constant value of 1.0 having type float.
1054 *
1055 * If the given type is invalid for increment and decrement operators, return
1056 * a floating point 1--the error will be detected later.
1057 */
1058 static ir_rvalue *
1059 constant_one_for_inc_dec(void *ctx, const glsl_type *type)
1060 {
1061 switch (type->base_type) {
1062 case GLSL_TYPE_UINT:
1063 return new(ctx) ir_constant((unsigned) 1);
1064 case GLSL_TYPE_INT:
1065 return new(ctx) ir_constant(1);
1066 default:
1067 case GLSL_TYPE_FLOAT:
1068 return new(ctx) ir_constant(1.0f);
1069 }
1070 }
1071
1072 ir_rvalue *
1073 ast_expression::hir(exec_list *instructions,
1074 struct _mesa_glsl_parse_state *state)
1075 {
1076 void *ctx = state;
1077 static const int operations[AST_NUM_OPERATORS] = {
1078 -1, /* ast_assign doesn't convert to ir_expression. */
1079 -1, /* ast_plus doesn't convert to ir_expression. */
1080 ir_unop_neg,
1081 ir_binop_add,
1082 ir_binop_sub,
1083 ir_binop_mul,
1084 ir_binop_div,
1085 ir_binop_mod,
1086 ir_binop_lshift,
1087 ir_binop_rshift,
1088 ir_binop_less,
1089 ir_binop_greater,
1090 ir_binop_lequal,
1091 ir_binop_gequal,
1092 ir_binop_all_equal,
1093 ir_binop_any_nequal,
1094 ir_binop_bit_and,
1095 ir_binop_bit_xor,
1096 ir_binop_bit_or,
1097 ir_unop_bit_not,
1098 ir_binop_logic_and,
1099 ir_binop_logic_xor,
1100 ir_binop_logic_or,
1101 ir_unop_logic_not,
1102
1103 /* Note: The following block of expression types actually convert
1104 * to multiple IR instructions.
1105 */
1106 ir_binop_mul, /* ast_mul_assign */
1107 ir_binop_div, /* ast_div_assign */
1108 ir_binop_mod, /* ast_mod_assign */
1109 ir_binop_add, /* ast_add_assign */
1110 ir_binop_sub, /* ast_sub_assign */
1111 ir_binop_lshift, /* ast_ls_assign */
1112 ir_binop_rshift, /* ast_rs_assign */
1113 ir_binop_bit_and, /* ast_and_assign */
1114 ir_binop_bit_xor, /* ast_xor_assign */
1115 ir_binop_bit_or, /* ast_or_assign */
1116
1117 -1, /* ast_conditional doesn't convert to ir_expression. */
1118 ir_binop_add, /* ast_pre_inc. */
1119 ir_binop_sub, /* ast_pre_dec. */
1120 ir_binop_add, /* ast_post_inc. */
1121 ir_binop_sub, /* ast_post_dec. */
1122 -1, /* ast_field_selection doesn't conv to ir_expression. */
1123 -1, /* ast_array_index doesn't convert to ir_expression. */
1124 -1, /* ast_function_call doesn't conv to ir_expression. */
1125 -1, /* ast_identifier doesn't convert to ir_expression. */
1126 -1, /* ast_int_constant doesn't convert to ir_expression. */
1127 -1, /* ast_uint_constant doesn't conv to ir_expression. */
1128 -1, /* ast_float_constant doesn't conv to ir_expression. */
1129 -1, /* ast_bool_constant doesn't conv to ir_expression. */
1130 -1, /* ast_sequence doesn't convert to ir_expression. */
1131 };
1132 ir_rvalue *result = NULL;
1133 ir_rvalue *op[3];
1134 const struct glsl_type *type; /* a temporary variable for switch cases */
1135 bool error_emitted = false;
1136 YYLTYPE loc;
1137
1138 loc = this->get_location();
1139
1140 switch (this->oper) {
1141 case ast_aggregate:
1142 assert(!"ast_aggregate: Should never get here.");
1143 break;
1144
1145 case ast_assign: {
1146 op[0] = this->subexpressions[0]->hir(instructions, state);
1147 op[1] = this->subexpressions[1]->hir(instructions, state);
1148
1149 result = do_assignment(instructions, state,
1150 this->subexpressions[0]->non_lvalue_description,
1151 op[0], op[1], false,
1152 this->subexpressions[0]->get_location());
1153 error_emitted = result->type->is_error();
1154 break;
1155 }
1156
1157 case ast_plus:
1158 op[0] = this->subexpressions[0]->hir(instructions, state);
1159
1160 type = unary_arithmetic_result_type(op[0]->type, state, & loc);
1161
1162 error_emitted = type->is_error();
1163
1164 result = op[0];
1165 break;
1166
1167 case ast_neg:
1168 op[0] = this->subexpressions[0]->hir(instructions, state);
1169
1170 type = unary_arithmetic_result_type(op[0]->type, state, & loc);
1171
1172 error_emitted = type->is_error();
1173
1174 result = new(ctx) ir_expression(operations[this->oper], type,
1175 op[0], NULL);
1176 break;
1177
1178 case ast_add:
1179 case ast_sub:
1180 case ast_mul:
1181 case ast_div:
1182 op[0] = this->subexpressions[0]->hir(instructions, state);
1183 op[1] = this->subexpressions[1]->hir(instructions, state);
1184
1185 type = arithmetic_result_type(op[0], op[1],
1186 (this->oper == ast_mul),
1187 state, & loc);
1188 error_emitted = type->is_error();
1189
1190 result = new(ctx) ir_expression(operations[this->oper], type,
1191 op[0], op[1]);
1192 break;
1193
1194 case ast_mod:
1195 op[0] = this->subexpressions[0]->hir(instructions, state);
1196 op[1] = this->subexpressions[1]->hir(instructions, state);
1197
1198 type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
1199
1200 assert(operations[this->oper] == ir_binop_mod);
1201
1202 result = new(ctx) ir_expression(operations[this->oper], type,
1203 op[0], op[1]);
1204 error_emitted = type->is_error();
1205 break;
1206
1207 case ast_lshift:
1208 case ast_rshift:
1209 if (!state->check_bitwise_operations_allowed(&loc)) {
1210 error_emitted = true;
1211 }
1212
1213 op[0] = this->subexpressions[0]->hir(instructions, state);
1214 op[1] = this->subexpressions[1]->hir(instructions, state);
1215 type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1216 &loc);
1217 result = new(ctx) ir_expression(operations[this->oper], type,
1218 op[0], op[1]);
1219 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1220 break;
1221
1222 case ast_less:
1223 case ast_greater:
1224 case ast_lequal:
1225 case ast_gequal:
1226 op[0] = this->subexpressions[0]->hir(instructions, state);
1227 op[1] = this->subexpressions[1]->hir(instructions, state);
1228
1229 type = relational_result_type(op[0], op[1], state, & loc);
1230
1231 /* The relational operators must either generate an error or result
1232 * in a scalar boolean. See page 57 of the GLSL 1.50 spec.
1233 */
1234 assert(type->is_error()
1235 || ((type->base_type == GLSL_TYPE_BOOL)
1236 && type->is_scalar()));
1237
1238 result = new(ctx) ir_expression(operations[this->oper], type,
1239 op[0], op[1]);
1240 error_emitted = type->is_error();
1241 break;
1242
1243 case ast_nequal:
1244 case ast_equal:
1245 op[0] = this->subexpressions[0]->hir(instructions, state);
1246 op[1] = this->subexpressions[1]->hir(instructions, state);
1247
1248 /* From page 58 (page 64 of the PDF) of the GLSL 1.50 spec:
1249 *
1250 * "The equality operators equal (==), and not equal (!=)
1251 * operate on all types. They result in a scalar Boolean. If
1252 * the operand types do not match, then there must be a
1253 * conversion from Section 4.1.10 "Implicit Conversions"
1254 * applied to one operand that can make them match, in which
1255 * case this conversion is done."
1256 */
1257 if ((!apply_implicit_conversion(op[0]->type, op[1], state)
1258 && !apply_implicit_conversion(op[1]->type, op[0], state))
1259 || (op[0]->type != op[1]->type)) {
1260 _mesa_glsl_error(& loc, state, "operands of `%s' must have the same "
1261 "type", (this->oper == ast_equal) ? "==" : "!=");
1262 error_emitted = true;
1263 } else if ((op[0]->type->is_array() || op[1]->type->is_array()) &&
1264 !state->check_version(120, 300, &loc,
1265 "array comparisons forbidden")) {
1266 error_emitted = true;
1267 } else if ((op[0]->type->contains_opaque() ||
1268 op[1]->type->contains_opaque())) {
1269 _mesa_glsl_error(&loc, state, "opaque type comparisons forbidden");
1270 error_emitted = true;
1271 }
1272
1273 if (error_emitted) {
1274 result = new(ctx) ir_constant(false);
1275 } else {
1276 result = do_comparison(ctx, operations[this->oper], op[0], op[1]);
1277 assert(result->type == glsl_type::bool_type);
1278 }
1279 break;
1280
1281 case ast_bit_and:
1282 case ast_bit_xor:
1283 case ast_bit_or:
1284 op[0] = this->subexpressions[0]->hir(instructions, state);
1285 op[1] = this->subexpressions[1]->hir(instructions, state);
1286 type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
1287 state, &loc);
1288 result = new(ctx) ir_expression(operations[this->oper], type,
1289 op[0], op[1]);
1290 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1291 break;
1292
1293 case ast_bit_not:
1294 op[0] = this->subexpressions[0]->hir(instructions, state);
1295
1296 if (!state->check_bitwise_operations_allowed(&loc)) {
1297 error_emitted = true;
1298 }
1299
1300 if (!op[0]->type->is_integer()) {
1301 _mesa_glsl_error(&loc, state, "operand of `~' must be an integer");
1302 error_emitted = true;
1303 }
1304
1305 type = error_emitted ? glsl_type::error_type : op[0]->type;
1306 result = new(ctx) ir_expression(ir_unop_bit_not, type, op[0], NULL);
1307 break;
1308
1309 case ast_logic_and: {
1310 exec_list rhs_instructions;
1311 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1312 "LHS", &error_emitted);
1313 op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1314 "RHS", &error_emitted);
1315
1316 if (rhs_instructions.is_empty()) {
1317 result = new(ctx) ir_expression(ir_binop_logic_and, op[0], op[1]);
1318 type = result->type;
1319 } else {
1320 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1321 "and_tmp",
1322 ir_var_temporary);
1323 instructions->push_tail(tmp);
1324
1325 ir_if *const stmt = new(ctx) ir_if(op[0]);
1326 instructions->push_tail(stmt);
1327
1328 stmt->then_instructions.append_list(&rhs_instructions);
1329 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1330 ir_assignment *const then_assign =
1331 new(ctx) ir_assignment(then_deref, op[1]);
1332 stmt->then_instructions.push_tail(then_assign);
1333
1334 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1335 ir_assignment *const else_assign =
1336 new(ctx) ir_assignment(else_deref, new(ctx) ir_constant(false));
1337 stmt->else_instructions.push_tail(else_assign);
1338
1339 result = new(ctx) ir_dereference_variable(tmp);
1340 type = tmp->type;
1341 }
1342 break;
1343 }
1344
1345 case ast_logic_or: {
1346 exec_list rhs_instructions;
1347 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1348 "LHS", &error_emitted);
1349 op[1] = get_scalar_boolean_operand(&rhs_instructions, state, this, 1,
1350 "RHS", &error_emitted);
1351
1352 if (rhs_instructions.is_empty()) {
1353 result = new(ctx) ir_expression(ir_binop_logic_or, op[0], op[1]);
1354 type = result->type;
1355 } else {
1356 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
1357 "or_tmp",
1358 ir_var_temporary);
1359 instructions->push_tail(tmp);
1360
1361 ir_if *const stmt = new(ctx) ir_if(op[0]);
1362 instructions->push_tail(stmt);
1363
1364 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
1365 ir_assignment *const then_assign =
1366 new(ctx) ir_assignment(then_deref, new(ctx) ir_constant(true));
1367 stmt->then_instructions.push_tail(then_assign);
1368
1369 stmt->else_instructions.append_list(&rhs_instructions);
1370 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
1371 ir_assignment *const else_assign =
1372 new(ctx) ir_assignment(else_deref, op[1]);
1373 stmt->else_instructions.push_tail(else_assign);
1374
1375 result = new(ctx) ir_dereference_variable(tmp);
1376 type = tmp->type;
1377 }
1378 break;
1379 }
1380
1381 case ast_logic_xor:
1382 /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1383 *
1384 * "The logical binary operators and (&&), or ( | | ), and
1385 * exclusive or (^^). They operate only on two Boolean
1386 * expressions and result in a Boolean expression."
1387 */
1388 op[0] = get_scalar_boolean_operand(instructions, state, this, 0, "LHS",
1389 &error_emitted);
1390 op[1] = get_scalar_boolean_operand(instructions, state, this, 1, "RHS",
1391 &error_emitted);
1392
1393 result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1394 op[0], op[1]);
1395 break;
1396
1397 case ast_logic_not:
1398 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1399 "operand", &error_emitted);
1400
1401 result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
1402 op[0], NULL);
1403 break;
1404
1405 case ast_mul_assign:
1406 case ast_div_assign:
1407 case ast_add_assign:
1408 case ast_sub_assign: {
1409 op[0] = this->subexpressions[0]->hir(instructions, state);
1410 op[1] = this->subexpressions[1]->hir(instructions, state);
1411
1412 type = arithmetic_result_type(op[0], op[1],
1413 (this->oper == ast_mul_assign),
1414 state, & loc);
1415
1416 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1417 op[0], op[1]);
1418
1419 result = do_assignment(instructions, state,
1420 this->subexpressions[0]->non_lvalue_description,
1421 op[0]->clone(ctx, NULL), temp_rhs, false,
1422 this->subexpressions[0]->get_location());
1423 error_emitted = (op[0]->type->is_error());
1424
1425 /* GLSL 1.10 does not allow array assignment. However, we don't have to
1426 * explicitly test for this because none of the binary expression
1427 * operators allow array operands either.
1428 */
1429
1430 break;
1431 }
1432
1433 case ast_mod_assign: {
1434 op[0] = this->subexpressions[0]->hir(instructions, state);
1435 op[1] = this->subexpressions[1]->hir(instructions, state);
1436
1437 type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
1438
1439 assert(operations[this->oper] == ir_binop_mod);
1440
1441 ir_rvalue *temp_rhs;
1442 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1443 op[0], op[1]);
1444
1445 result = do_assignment(instructions, state,
1446 this->subexpressions[0]->non_lvalue_description,
1447 op[0]->clone(ctx, NULL), temp_rhs, false,
1448 this->subexpressions[0]->get_location());
1449 error_emitted = type->is_error();
1450 break;
1451 }
1452
1453 case ast_ls_assign:
1454 case ast_rs_assign: {
1455 op[0] = this->subexpressions[0]->hir(instructions, state);
1456 op[1] = this->subexpressions[1]->hir(instructions, state);
1457 type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
1458 &loc);
1459 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1460 type, op[0], op[1]);
1461 result = do_assignment(instructions, state,
1462 this->subexpressions[0]->non_lvalue_description,
1463 op[0]->clone(ctx, NULL), temp_rhs, false,
1464 this->subexpressions[0]->get_location());
1465 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1466 break;
1467 }
1468
1469 case ast_and_assign:
1470 case ast_xor_assign:
1471 case ast_or_assign: {
1472 op[0] = this->subexpressions[0]->hir(instructions, state);
1473 op[1] = this->subexpressions[1]->hir(instructions, state);
1474 type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
1475 state, &loc);
1476 ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
1477 type, op[0], op[1]);
1478 result = do_assignment(instructions, state,
1479 this->subexpressions[0]->non_lvalue_description,
1480 op[0]->clone(ctx, NULL), temp_rhs, false,
1481 this->subexpressions[0]->get_location());
1482 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1483 break;
1484 }
1485
1486 case ast_conditional: {
1487 /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1488 *
1489 * "The ternary selection operator (?:). It operates on three
1490 * expressions (exp1 ? exp2 : exp3). This operator evaluates the
1491 * first expression, which must result in a scalar Boolean."
1492 */
1493 op[0] = get_scalar_boolean_operand(instructions, state, this, 0,
1494 "condition", &error_emitted);
1495
1496 /* The :? operator is implemented by generating an anonymous temporary
1497 * followed by an if-statement. The last instruction in each branch of
1498 * the if-statement assigns a value to the anonymous temporary. This
1499 * temporary is the r-value of the expression.
1500 */
1501 exec_list then_instructions;
1502 exec_list else_instructions;
1503
1504 op[1] = this->subexpressions[1]->hir(&then_instructions, state);
1505 op[2] = this->subexpressions[2]->hir(&else_instructions, state);
1506
1507 /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1508 *
1509 * "The second and third expressions can be any type, as
1510 * long their types match, or there is a conversion in
1511 * Section 4.1.10 "Implicit Conversions" that can be applied
1512 * to one of the expressions to make their types match. This
1513 * resulting matching type is the type of the entire
1514 * expression."
1515 */
1516 if ((!apply_implicit_conversion(op[1]->type, op[2], state)
1517 && !apply_implicit_conversion(op[2]->type, op[1], state))
1518 || (op[1]->type != op[2]->type)) {
1519 YYLTYPE loc = this->subexpressions[1]->get_location();
1520
1521 _mesa_glsl_error(& loc, state, "second and third operands of ?: "
1522 "operator must have matching types");
1523 error_emitted = true;
1524 type = glsl_type::error_type;
1525 } else {
1526 type = op[1]->type;
1527 }
1528
1529 /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
1530 *
1531 * "The second and third expressions must be the same type, but can
1532 * be of any type other than an array."
1533 */
1534 if (type->is_array() &&
1535 !state->check_version(120, 300, &loc,
1536 "second and third operands of ?: operator "
1537 "cannot be arrays")) {
1538 error_emitted = true;
1539 }
1540
1541 ir_constant *cond_val = op[0]->constant_expression_value();
1542 ir_constant *then_val = op[1]->constant_expression_value();
1543 ir_constant *else_val = op[2]->constant_expression_value();
1544
1545 if (then_instructions.is_empty()
1546 && else_instructions.is_empty()
1547 && (cond_val != NULL) && (then_val != NULL) && (else_val != NULL)) {
1548 result = (cond_val->value.b[0]) ? then_val : else_val;
1549 } else {
1550 ir_variable *const tmp =
1551 new(ctx) ir_variable(type, "conditional_tmp", ir_var_temporary);
1552 instructions->push_tail(tmp);
1553
1554 ir_if *const stmt = new(ctx) ir_if(op[0]);
1555 instructions->push_tail(stmt);
1556
1557 then_instructions.move_nodes_to(& stmt->then_instructions);
1558 ir_dereference *const then_deref =
1559 new(ctx) ir_dereference_variable(tmp);
1560 ir_assignment *const then_assign =
1561 new(ctx) ir_assignment(then_deref, op[1]);
1562 stmt->then_instructions.push_tail(then_assign);
1563
1564 else_instructions.move_nodes_to(& stmt->else_instructions);
1565 ir_dereference *const else_deref =
1566 new(ctx) ir_dereference_variable(tmp);
1567 ir_assignment *const else_assign =
1568 new(ctx) ir_assignment(else_deref, op[2]);
1569 stmt->else_instructions.push_tail(else_assign);
1570
1571 result = new(ctx) ir_dereference_variable(tmp);
1572 }
1573 break;
1574 }
1575
1576 case ast_pre_inc:
1577 case ast_pre_dec: {
1578 this->non_lvalue_description = (this->oper == ast_pre_inc)
1579 ? "pre-increment operation" : "pre-decrement operation";
1580
1581 op[0] = this->subexpressions[0]->hir(instructions, state);
1582 op[1] = constant_one_for_inc_dec(ctx, op[0]->type);
1583
1584 type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1585
1586 ir_rvalue *temp_rhs;
1587 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1588 op[0], op[1]);
1589
1590 result = do_assignment(instructions, state,
1591 this->subexpressions[0]->non_lvalue_description,
1592 op[0]->clone(ctx, NULL), temp_rhs, false,
1593 this->subexpressions[0]->get_location());
1594 error_emitted = op[0]->type->is_error();
1595 break;
1596 }
1597
1598 case ast_post_inc:
1599 case ast_post_dec: {
1600 this->non_lvalue_description = (this->oper == ast_post_inc)
1601 ? "post-increment operation" : "post-decrement operation";
1602 op[0] = this->subexpressions[0]->hir(instructions, state);
1603 op[1] = constant_one_for_inc_dec(ctx, op[0]->type);
1604
1605 error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1606
1607 type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1608
1609 ir_rvalue *temp_rhs;
1610 temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1611 op[0], op[1]);
1612
1613 /* Get a temporary of a copy of the lvalue before it's modified.
1614 * This may get thrown away later.
1615 */
1616 result = get_lvalue_copy(instructions, op[0]->clone(ctx, NULL));
1617
1618 (void)do_assignment(instructions, state,
1619 this->subexpressions[0]->non_lvalue_description,
1620 op[0]->clone(ctx, NULL), temp_rhs, false,
1621 this->subexpressions[0]->get_location());
1622
1623 error_emitted = op[0]->type->is_error();
1624 break;
1625 }
1626
1627 case ast_field_selection:
1628 result = _mesa_ast_field_selection_to_hir(this, instructions, state);
1629 break;
1630
1631 case ast_array_index: {
1632 YYLTYPE index_loc = subexpressions[1]->get_location();
1633
1634 op[0] = subexpressions[0]->hir(instructions, state);
1635 op[1] = subexpressions[1]->hir(instructions, state);
1636
1637 result = _mesa_ast_array_index_to_hir(ctx, state, op[0], op[1],
1638 loc, index_loc);
1639
1640 if (result->type->is_error())
1641 error_emitted = true;
1642
1643 break;
1644 }
1645
1646 case ast_function_call:
1647 /* Should *NEVER* get here. ast_function_call should always be handled
1648 * by ast_function_expression::hir.
1649 */
1650 assert(0);
1651 break;
1652
1653 case ast_identifier: {
1654 /* ast_identifier can appear several places in a full abstract syntax
1655 * tree. This particular use must be at location specified in the grammar
1656 * as 'variable_identifier'.
1657 */
1658 ir_variable *var =
1659 state->symbols->get_variable(this->primary_expression.identifier);
1660
1661 if (var != NULL) {
1662 var->data.used = true;
1663 result = new(ctx) ir_dereference_variable(var);
1664 } else {
1665 _mesa_glsl_error(& loc, state, "`%s' undeclared",
1666 this->primary_expression.identifier);
1667
1668 result = ir_rvalue::error_value(ctx);
1669 error_emitted = true;
1670 }
1671 break;
1672 }
1673
1674 case ast_int_constant:
1675 result = new(ctx) ir_constant(this->primary_expression.int_constant);
1676 break;
1677
1678 case ast_uint_constant:
1679 result = new(ctx) ir_constant(this->primary_expression.uint_constant);
1680 break;
1681
1682 case ast_float_constant:
1683 result = new(ctx) ir_constant(this->primary_expression.float_constant);
1684 break;
1685
1686 case ast_bool_constant:
1687 result = new(ctx) ir_constant(bool(this->primary_expression.bool_constant));
1688 break;
1689
1690 case ast_sequence: {
1691 /* It should not be possible to generate a sequence in the AST without
1692 * any expressions in it.
1693 */
1694 assert(!this->expressions.is_empty());
1695
1696 /* The r-value of a sequence is the last expression in the sequence. If
1697 * the other expressions in the sequence do not have side-effects (and
1698 * therefore add instructions to the instruction list), they get dropped
1699 * on the floor.
1700 */
1701 exec_node *previous_tail_pred = NULL;
1702 YYLTYPE previous_operand_loc = loc;
1703
1704 foreach_list_typed (ast_node, ast, link, &this->expressions) {
1705 /* If one of the operands of comma operator does not generate any
1706 * code, we want to emit a warning. At each pass through the loop
1707 * previous_tail_pred will point to the last instruction in the
1708 * stream *before* processing the previous operand. Naturally,
1709 * instructions->tail_pred will point to the last instruction in the
1710 * stream *after* processing the previous operand. If the two
1711 * pointers match, then the previous operand had no effect.
1712 *
1713 * The warning behavior here differs slightly from GCC. GCC will
1714 * only emit a warning if none of the left-hand operands have an
1715 * effect. However, it will emit a warning for each. I believe that
1716 * there are some cases in C (especially with GCC extensions) where
1717 * it is useful to have an intermediate step in a sequence have no
1718 * effect, but I don't think these cases exist in GLSL. Either way,
1719 * it would be a giant hassle to replicate that behavior.
1720 */
1721 if (previous_tail_pred == instructions->tail_pred) {
1722 _mesa_glsl_warning(&previous_operand_loc, state,
1723 "left-hand operand of comma expression has "
1724 "no effect");
1725 }
1726
1727 /* tail_pred is directly accessed instead of using the get_tail()
1728 * method for performance reasons. get_tail() has extra code to
1729 * return NULL when the list is empty. We don't care about that
1730 * here, so using tail_pred directly is fine.
1731 */
1732 previous_tail_pred = instructions->tail_pred;
1733 previous_operand_loc = ast->get_location();
1734
1735 result = ast->hir(instructions, state);
1736 }
1737
1738 /* Any errors should have already been emitted in the loop above.
1739 */
1740 error_emitted = true;
1741 break;
1742 }
1743 }
1744 type = NULL; /* use result->type, not type. */
1745 assert(result != NULL);
1746
1747 if (result->type->is_error() && !error_emitted)
1748 _mesa_glsl_error(& loc, state, "type mismatch");
1749
1750 return result;
1751 }
1752
1753
1754 ir_rvalue *
1755 ast_expression_statement::hir(exec_list *instructions,
1756 struct _mesa_glsl_parse_state *state)
1757 {
1758 /* It is possible to have expression statements that don't have an
1759 * expression. This is the solitary semicolon:
1760 *
1761 * for (i = 0; i < 5; i++)
1762 * ;
1763 *
1764 * In this case the expression will be NULL. Test for NULL and don't do
1765 * anything in that case.
1766 */
1767 if (expression != NULL)
1768 expression->hir(instructions, state);
1769
1770 /* Statements do not have r-values.
1771 */
1772 return NULL;
1773 }
1774
1775
1776 ir_rvalue *
1777 ast_compound_statement::hir(exec_list *instructions,
1778 struct _mesa_glsl_parse_state *state)
1779 {
1780 if (new_scope)
1781 state->symbols->push_scope();
1782
1783 foreach_list_typed (ast_node, ast, link, &this->statements)
1784 ast->hir(instructions, state);
1785
1786 if (new_scope)
1787 state->symbols->pop_scope();
1788
1789 /* Compound statements do not have r-values.
1790 */
1791 return NULL;
1792 }
1793
1794 /**
1795 * Evaluate the given exec_node (which should be an ast_node representing
1796 * a single array dimension) and return its integer value.
1797 */
1798 static const unsigned
1799 process_array_size(exec_node *node,
1800 struct _mesa_glsl_parse_state *state)
1801 {
1802 exec_list dummy_instructions;
1803
1804 ast_node *array_size = exec_node_data(ast_node, node, link);
1805 ir_rvalue *const ir = array_size->hir(& dummy_instructions,
1806 state);
1807 YYLTYPE loc = array_size->get_location();
1808
1809 if (ir == NULL) {
1810 _mesa_glsl_error(& loc, state,
1811 "array size could not be resolved");
1812 return 0;
1813 }
1814
1815 if (!ir->type->is_integer()) {
1816 _mesa_glsl_error(& loc, state,
1817 "array size must be integer type");
1818 return 0;
1819 }
1820
1821 if (!ir->type->is_scalar()) {
1822 _mesa_glsl_error(& loc, state,
1823 "array size must be scalar type");
1824 return 0;
1825 }
1826
1827 ir_constant *const size = ir->constant_expression_value();
1828 if (size == NULL) {
1829 _mesa_glsl_error(& loc, state, "array size must be a "
1830 "constant valued expression");
1831 return 0;
1832 }
1833
1834 if (size->value.i[0] <= 0) {
1835 _mesa_glsl_error(& loc, state, "array size must be > 0");
1836 return 0;
1837 }
1838
1839 assert(size->type == ir->type);
1840
1841 /* If the array size is const (and we've verified that
1842 * it is) then no instructions should have been emitted
1843 * when we converted it to HIR. If they were emitted,
1844 * then either the array size isn't const after all, or
1845 * we are emitting unnecessary instructions.
1846 */
1847 assert(dummy_instructions.is_empty());
1848
1849 return size->value.u[0];
1850 }
1851
1852 static const glsl_type *
1853 process_array_type(YYLTYPE *loc, const glsl_type *base,
1854 ast_array_specifier *array_specifier,
1855 struct _mesa_glsl_parse_state *state)
1856 {
1857 const glsl_type *array_type = base;
1858
1859 if (array_specifier != NULL) {
1860 if (base->is_array()) {
1861
1862 /* From page 19 (page 25) of the GLSL 1.20 spec:
1863 *
1864 * "Only one-dimensional arrays may be declared."
1865 */
1866 if (!state->ARB_arrays_of_arrays_enable) {
1867 _mesa_glsl_error(loc, state,
1868 "invalid array of `%s'"
1869 "GL_ARB_arrays_of_arrays "
1870 "required for defining arrays of arrays",
1871 base->name);
1872 return glsl_type::error_type;
1873 }
1874
1875 if (base->length == 0) {
1876 _mesa_glsl_error(loc, state,
1877 "only the outermost array dimension can "
1878 "be unsized",
1879 base->name);
1880 return glsl_type::error_type;
1881 }
1882 }
1883
1884 for (exec_node *node = array_specifier->array_dimensions.tail_pred;
1885 !node->is_head_sentinel(); node = node->prev) {
1886 unsigned array_size = process_array_size(node, state);
1887 array_type = glsl_type::get_array_instance(array_type,
1888 array_size);
1889 }
1890
1891 if (array_specifier->is_unsized_array)
1892 array_type = glsl_type::get_array_instance(array_type, 0);
1893 }
1894
1895 return array_type;
1896 }
1897
1898
1899 const glsl_type *
1900 ast_type_specifier::glsl_type(const char **name,
1901 struct _mesa_glsl_parse_state *state) const
1902 {
1903 const struct glsl_type *type;
1904
1905 type = state->symbols->get_type(this->type_name);
1906 *name = this->type_name;
1907
1908 YYLTYPE loc = this->get_location();
1909 type = process_array_type(&loc, type, this->array_specifier, state);
1910
1911 return type;
1912 }
1913
1914 const glsl_type *
1915 ast_fully_specified_type::glsl_type(const char **name,
1916 struct _mesa_glsl_parse_state *state) const
1917 {
1918 const struct glsl_type *type = this->specifier->glsl_type(name, state);
1919
1920 if (type == NULL)
1921 return NULL;
1922
1923 if (type->base_type == GLSL_TYPE_FLOAT
1924 && state->es_shader
1925 && state->stage == MESA_SHADER_FRAGMENT
1926 && this->qualifier.precision == ast_precision_none
1927 && state->symbols->get_variable("#default precision") == NULL) {
1928 YYLTYPE loc = this->get_location();
1929 _mesa_glsl_error(&loc, state,
1930 "no precision specified this scope for type `%s'",
1931 type->name);
1932 }
1933
1934 return type;
1935 }
1936
1937 /**
1938 * Determine whether a toplevel variable declaration declares a varying. This
1939 * function operates by examining the variable's mode and the shader target,
1940 * so it correctly identifies linkage variables regardless of whether they are
1941 * declared using the deprecated "varying" syntax or the new "in/out" syntax.
1942 *
1943 * Passing a non-toplevel variable declaration (e.g. a function parameter) to
1944 * this function will produce undefined results.
1945 */
1946 static bool
1947 is_varying_var(ir_variable *var, gl_shader_stage target)
1948 {
1949 switch (target) {
1950 case MESA_SHADER_VERTEX:
1951 return var->data.mode == ir_var_shader_out;
1952 case MESA_SHADER_FRAGMENT:
1953 return var->data.mode == ir_var_shader_in;
1954 default:
1955 return var->data.mode == ir_var_shader_out || var->data.mode == ir_var_shader_in;
1956 }
1957 }
1958
1959
1960 /**
1961 * Matrix layout qualifiers are only allowed on certain types
1962 */
1963 static void
1964 validate_matrix_layout_for_type(struct _mesa_glsl_parse_state *state,
1965 YYLTYPE *loc,
1966 const glsl_type *type,
1967 ir_variable *var)
1968 {
1969 if (var && !var->is_in_uniform_block()) {
1970 /* Layout qualifiers may only apply to interface blocks and fields in
1971 * them.
1972 */
1973 _mesa_glsl_error(loc, state,
1974 "uniform block layout qualifiers row_major and "
1975 "column_major may not be applied to variables "
1976 "outside of uniform blocks");
1977 } else if (!type->is_matrix()) {
1978 /* The OpenGL ES 3.0 conformance tests did not originally allow
1979 * matrix layout qualifiers on non-matrices. However, the OpenGL
1980 * 4.4 and OpenGL ES 3.0 (revision TBD) specifications were
1981 * amended to specifically allow these layouts on all types. Emit
1982 * a warning so that people know their code may not be portable.
1983 */
1984 _mesa_glsl_warning(loc, state,
1985 "uniform block layout qualifiers row_major and "
1986 "column_major applied to non-matrix types may "
1987 "be rejected by older compilers");
1988 } else if (type->is_record()) {
1989 /* We allow 'layout(row_major)' on structure types because it's the only
1990 * way to get row-major layouts on matrices contained in structures.
1991 */
1992 _mesa_glsl_warning(loc, state,
1993 "uniform block layout qualifiers row_major and "
1994 "column_major applied to structure types is not "
1995 "strictly conformant and may be rejected by other "
1996 "compilers");
1997 }
1998 }
1999
2000 static bool
2001 validate_binding_qualifier(struct _mesa_glsl_parse_state *state,
2002 YYLTYPE *loc,
2003 ir_variable *var,
2004 const ast_type_qualifier *qual)
2005 {
2006 if (var->data.mode != ir_var_uniform) {
2007 _mesa_glsl_error(loc, state,
2008 "the \"binding\" qualifier only applies to uniforms");
2009 return false;
2010 }
2011
2012 if (qual->binding < 0) {
2013 _mesa_glsl_error(loc, state, "binding values must be >= 0");
2014 return false;
2015 }
2016
2017 const struct gl_context *const ctx = state->ctx;
2018 unsigned elements = var->type->is_array() ? var->type->length : 1;
2019 unsigned max_index = qual->binding + elements - 1;
2020
2021 if (var->type->is_interface()) {
2022 /* UBOs. From page 60 of the GLSL 4.20 specification:
2023 * "If the binding point for any uniform block instance is less than zero,
2024 * or greater than or equal to the implementation-dependent maximum
2025 * number of uniform buffer bindings, a compilation error will occur.
2026 * When the binding identifier is used with a uniform block instanced as
2027 * an array of size N, all elements of the array from binding through
2028 * binding + N – 1 must be within this range."
2029 *
2030 * The implementation-dependent maximum is GL_MAX_UNIFORM_BUFFER_BINDINGS.
2031 */
2032 if (max_index >= ctx->Const.MaxUniformBufferBindings) {
2033 _mesa_glsl_error(loc, state, "layout(binding = %d) for %d UBOs exceeds "
2034 "the maximum number of UBO binding points (%d)",
2035 qual->binding, elements,
2036 ctx->Const.MaxUniformBufferBindings);
2037 return false;
2038 }
2039 } else if (var->type->is_sampler() ||
2040 (var->type->is_array() && var->type->fields.array->is_sampler())) {
2041 /* Samplers. From page 63 of the GLSL 4.20 specification:
2042 * "If the binding is less than zero, or greater than or equal to the
2043 * implementation-dependent maximum supported number of units, a
2044 * compilation error will occur. When the binding identifier is used
2045 * with an array of size N, all elements of the array from binding
2046 * through binding + N - 1 must be within this range."
2047 */
2048 unsigned limit = ctx->Const.Program[state->stage].MaxTextureImageUnits;
2049
2050 if (max_index >= limit) {
2051 _mesa_glsl_error(loc, state, "layout(binding = %d) for %d samplers "
2052 "exceeds the maximum number of texture image units "
2053 "(%d)", qual->binding, elements, limit);
2054
2055 return false;
2056 }
2057 } else if (var->type->contains_atomic()) {
2058 assert(ctx->Const.MaxAtomicBufferBindings <= MAX_COMBINED_ATOMIC_BUFFERS);
2059 if (unsigned(qual->binding) >= ctx->Const.MaxAtomicBufferBindings) {
2060 _mesa_glsl_error(loc, state, "layout(binding = %d) exceeds the "
2061 " maximum number of atomic counter buffer bindings"
2062 "(%d)", qual->binding,
2063 ctx->Const.MaxAtomicBufferBindings);
2064
2065 return false;
2066 }
2067 } else {
2068 _mesa_glsl_error(loc, state,
2069 "the \"binding\" qualifier only applies to uniform "
2070 "blocks, samplers, atomic counters, or arrays thereof");
2071 return false;
2072 }
2073
2074 return true;
2075 }
2076
2077
2078 static glsl_interp_qualifier
2079 interpret_interpolation_qualifier(const struct ast_type_qualifier *qual,
2080 ir_variable_mode mode,
2081 struct _mesa_glsl_parse_state *state,
2082 YYLTYPE *loc)
2083 {
2084 glsl_interp_qualifier interpolation;
2085 if (qual->flags.q.flat)
2086 interpolation = INTERP_QUALIFIER_FLAT;
2087 else if (qual->flags.q.noperspective)
2088 interpolation = INTERP_QUALIFIER_NOPERSPECTIVE;
2089 else if (qual->flags.q.smooth)
2090 interpolation = INTERP_QUALIFIER_SMOOTH;
2091 else
2092 interpolation = INTERP_QUALIFIER_NONE;
2093
2094 if (interpolation != INTERP_QUALIFIER_NONE) {
2095 if (mode != ir_var_shader_in && mode != ir_var_shader_out) {
2096 _mesa_glsl_error(loc, state,
2097 "interpolation qualifier `%s' can only be applied to "
2098 "shader inputs or outputs.",
2099 interpolation_string(interpolation));
2100
2101 }
2102
2103 if ((state->stage == MESA_SHADER_VERTEX && mode == ir_var_shader_in) ||
2104 (state->stage == MESA_SHADER_FRAGMENT && mode == ir_var_shader_out)) {
2105 _mesa_glsl_error(loc, state,
2106 "interpolation qualifier `%s' cannot be applied to "
2107 "vertex shader inputs or fragment shader outputs",
2108 interpolation_string(interpolation));
2109 }
2110 }
2111
2112 return interpolation;
2113 }
2114
2115
2116 static void
2117 validate_explicit_location(const struct ast_type_qualifier *qual,
2118 ir_variable *var,
2119 struct _mesa_glsl_parse_state *state,
2120 YYLTYPE *loc)
2121 {
2122 bool fail = false;
2123
2124 /* In the vertex shader only shader inputs can be given explicit
2125 * locations.
2126 *
2127 * In the fragment shader only shader outputs can be given explicit
2128 * locations.
2129 */
2130 switch (state->stage) {
2131 case MESA_SHADER_VERTEX:
2132 if (var->data.mode == ir_var_shader_in) {
2133 if (!state->check_explicit_attrib_location_allowed(loc, var))
2134 return;
2135
2136 break;
2137 }
2138
2139 fail = true;
2140 break;
2141
2142 case MESA_SHADER_GEOMETRY:
2143 _mesa_glsl_error(loc, state,
2144 "geometry shader variables cannot be given "
2145 "explicit locations");
2146 return;
2147
2148 case MESA_SHADER_FRAGMENT:
2149 if (var->data.mode == ir_var_shader_out) {
2150 if (!state->check_explicit_attrib_location_allowed(loc, var))
2151 return;
2152
2153 break;
2154 }
2155
2156 fail = true;
2157 break;
2158 };
2159
2160 if (fail) {
2161 _mesa_glsl_error(loc, state,
2162 "%s cannot be given an explicit location in %s shader",
2163 mode_string(var),
2164 _mesa_shader_stage_to_string(state->stage));
2165 } else {
2166 var->data.explicit_location = true;
2167
2168 /* This bit of silliness is needed because invalid explicit locations
2169 * are supposed to be flagged during linking. Small negative values
2170 * biased by VERT_ATTRIB_GENERIC0 or FRAG_RESULT_DATA0 could alias
2171 * built-in values (e.g., -16+VERT_ATTRIB_GENERIC0 = VERT_ATTRIB_POS).
2172 * The linker needs to be able to differentiate these cases. This
2173 * ensures that negative values stay negative.
2174 */
2175 if (qual->location >= 0) {
2176 var->data.location = (state->stage == MESA_SHADER_VERTEX)
2177 ? (qual->location + VERT_ATTRIB_GENERIC0)
2178 : (qual->location + FRAG_RESULT_DATA0);
2179 } else {
2180 var->data.location = qual->location;
2181 }
2182
2183 if (qual->flags.q.explicit_index) {
2184 /* From the GLSL 4.30 specification, section 4.4.2 (Output
2185 * Layout Qualifiers):
2186 *
2187 * "It is also a compile-time error if a fragment shader
2188 * sets a layout index to less than 0 or greater than 1."
2189 *
2190 * Older specifications don't mandate a behavior; we take
2191 * this as a clarification and always generate the error.
2192 */
2193 if (qual->index < 0 || qual->index > 1) {
2194 _mesa_glsl_error(loc, state,
2195 "explicit index may only be 0 or 1");
2196 } else {
2197 var->data.explicit_index = true;
2198 var->data.index = qual->index;
2199 }
2200 }
2201 }
2202
2203 return;
2204 }
2205
2206 static void
2207 apply_type_qualifier_to_variable(const struct ast_type_qualifier *qual,
2208 ir_variable *var,
2209 struct _mesa_glsl_parse_state *state,
2210 YYLTYPE *loc,
2211 bool is_parameter)
2212 {
2213 STATIC_ASSERT(sizeof(qual->flags.q) <= sizeof(qual->flags.i));
2214
2215 if (qual->flags.q.invariant) {
2216 if (var->data.used) {
2217 _mesa_glsl_error(loc, state,
2218 "variable `%s' may not be redeclared "
2219 "`invariant' after being used",
2220 var->name);
2221 } else {
2222 var->data.invariant = 1;
2223 }
2224 }
2225
2226 if (qual->flags.q.constant || qual->flags.q.attribute
2227 || qual->flags.q.uniform
2228 || (qual->flags.q.varying && (state->stage == MESA_SHADER_FRAGMENT)))
2229 var->data.read_only = 1;
2230
2231 if (qual->flags.q.centroid)
2232 var->data.centroid = 1;
2233
2234 if (qual->flags.q.sample)
2235 var->data.sample = 1;
2236
2237 if (qual->flags.q.attribute && state->stage != MESA_SHADER_VERTEX) {
2238 var->type = glsl_type::error_type;
2239 _mesa_glsl_error(loc, state,
2240 "`attribute' variables may not be declared in the "
2241 "%s shader",
2242 _mesa_shader_stage_to_string(state->stage));
2243 }
2244
2245 /* Section 6.1.1 (Function Calling Conventions) of the GLSL 1.10 spec says:
2246 *
2247 * "However, the const qualifier cannot be used with out or inout."
2248 *
2249 * The same section of the GLSL 4.40 spec further clarifies this saying:
2250 *
2251 * "The const qualifier cannot be used with out or inout, or a
2252 * compile-time error results."
2253 */
2254 if (is_parameter && qual->flags.q.constant && qual->flags.q.out) {
2255 _mesa_glsl_error(loc, state,
2256 "`const' may not be applied to `out' or `inout' "
2257 "function parameters");
2258 }
2259
2260 /* If there is no qualifier that changes the mode of the variable, leave
2261 * the setting alone.
2262 */
2263 if (qual->flags.q.in && qual->flags.q.out)
2264 var->data.mode = ir_var_function_inout;
2265 else if (qual->flags.q.in)
2266 var->data.mode = is_parameter ? ir_var_function_in : ir_var_shader_in;
2267 else if (qual->flags.q.attribute
2268 || (qual->flags.q.varying && (state->stage == MESA_SHADER_FRAGMENT)))
2269 var->data.mode = ir_var_shader_in;
2270 else if (qual->flags.q.out)
2271 var->data.mode = is_parameter ? ir_var_function_out : ir_var_shader_out;
2272 else if (qual->flags.q.varying && (state->stage == MESA_SHADER_VERTEX))
2273 var->data.mode = ir_var_shader_out;
2274 else if (qual->flags.q.uniform)
2275 var->data.mode = ir_var_uniform;
2276
2277 if (!is_parameter && is_varying_var(var, state->stage)) {
2278 /* This variable is being used to link data between shader stages (in
2279 * pre-glsl-1.30 parlance, it's a "varying"). Check that it has a type
2280 * that is allowed for such purposes.
2281 *
2282 * From page 25 (page 31 of the PDF) of the GLSL 1.10 spec:
2283 *
2284 * "The varying qualifier can be used only with the data types
2285 * float, vec2, vec3, vec4, mat2, mat3, and mat4, or arrays of
2286 * these."
2287 *
2288 * This was relaxed in GLSL version 1.30 and GLSL ES version 3.00. From
2289 * page 31 (page 37 of the PDF) of the GLSL 1.30 spec:
2290 *
2291 * "Fragment inputs can only be signed and unsigned integers and
2292 * integer vectors, float, floating-point vectors, matrices, or
2293 * arrays of these. Structures cannot be input.
2294 *
2295 * Similar text exists in the section on vertex shader outputs.
2296 *
2297 * Similar text exists in the GLSL ES 3.00 spec, except that the GLSL ES
2298 * 3.00 spec allows structs as well. Varying structs are also allowed
2299 * in GLSL 1.50.
2300 */
2301 switch (var->type->get_scalar_type()->base_type) {
2302 case GLSL_TYPE_FLOAT:
2303 /* Ok in all GLSL versions */
2304 break;
2305 case GLSL_TYPE_UINT:
2306 case GLSL_TYPE_INT:
2307 if (state->is_version(130, 300))
2308 break;
2309 _mesa_glsl_error(loc, state,
2310 "varying variables must be of base type float in %s",
2311 state->get_version_string());
2312 break;
2313 case GLSL_TYPE_STRUCT:
2314 if (state->is_version(150, 300))
2315 break;
2316 _mesa_glsl_error(loc, state,
2317 "varying variables may not be of type struct");
2318 break;
2319 default:
2320 _mesa_glsl_error(loc, state, "illegal type for a varying variable");
2321 break;
2322 }
2323 }
2324
2325 if (state->all_invariant && (state->current_function == NULL)) {
2326 switch (state->stage) {
2327 case MESA_SHADER_VERTEX:
2328 if (var->data.mode == ir_var_shader_out)
2329 var->data.invariant = true;
2330 break;
2331 case MESA_SHADER_GEOMETRY:
2332 if ((var->data.mode == ir_var_shader_in)
2333 || (var->data.mode == ir_var_shader_out))
2334 var->data.invariant = true;
2335 break;
2336 case MESA_SHADER_FRAGMENT:
2337 if (var->data.mode == ir_var_shader_in)
2338 var->data.invariant = true;
2339 break;
2340 }
2341 }
2342
2343 var->data.interpolation =
2344 interpret_interpolation_qualifier(qual, (ir_variable_mode) var->data.mode,
2345 state, loc);
2346
2347 var->data.pixel_center_integer = qual->flags.q.pixel_center_integer;
2348 var->data.origin_upper_left = qual->flags.q.origin_upper_left;
2349 if ((qual->flags.q.origin_upper_left || qual->flags.q.pixel_center_integer)
2350 && (strcmp(var->name, "gl_FragCoord") != 0)) {
2351 const char *const qual_string = (qual->flags.q.origin_upper_left)
2352 ? "origin_upper_left" : "pixel_center_integer";
2353
2354 _mesa_glsl_error(loc, state,
2355 "layout qualifier `%s' can only be applied to "
2356 "fragment shader input `gl_FragCoord'",
2357 qual_string);
2358 }
2359
2360 if (qual->flags.q.explicit_location) {
2361 validate_explicit_location(qual, var, state, loc);
2362 } else if (qual->flags.q.explicit_index) {
2363 _mesa_glsl_error(loc, state,
2364 "explicit index requires explicit location");
2365 }
2366
2367 if (qual->flags.q.explicit_binding &&
2368 validate_binding_qualifier(state, loc, var, qual)) {
2369 var->data.explicit_binding = true;
2370 var->data.binding = qual->binding;
2371 }
2372
2373 if (var->type->contains_atomic()) {
2374 if (var->data.mode == ir_var_uniform) {
2375 if (var->data.explicit_binding) {
2376 unsigned *offset =
2377 &state->atomic_counter_offsets[var->data.binding];
2378
2379 if (*offset % ATOMIC_COUNTER_SIZE)
2380 _mesa_glsl_error(loc, state,
2381 "misaligned atomic counter offset");
2382
2383 var->data.atomic.offset = *offset;
2384 *offset += var->type->atomic_size();
2385
2386 } else {
2387 _mesa_glsl_error(loc, state,
2388 "atomic counters require explicit binding point");
2389 }
2390 } else if (var->data.mode != ir_var_function_in) {
2391 _mesa_glsl_error(loc, state, "atomic counters may only be declared as "
2392 "function parameters or uniform-qualified "
2393 "global variables");
2394 }
2395 }
2396
2397 /* Does the declaration use the deprecated 'attribute' or 'varying'
2398 * keywords?
2399 */
2400 const bool uses_deprecated_qualifier = qual->flags.q.attribute
2401 || qual->flags.q.varying;
2402
2403 /* Is the 'layout' keyword used with parameters that allow relaxed checking.
2404 * Many implementations of GL_ARB_fragment_coord_conventions_enable and some
2405 * implementations (only Mesa?) GL_ARB_explicit_attrib_location_enable
2406 * allowed the layout qualifier to be used with 'varying' and 'attribute'.
2407 * These extensions and all following extensions that add the 'layout'
2408 * keyword have been modified to require the use of 'in' or 'out'.
2409 *
2410 * The following extension do not allow the deprecated keywords:
2411 *
2412 * GL_AMD_conservative_depth
2413 * GL_ARB_conservative_depth
2414 * GL_ARB_gpu_shader5
2415 * GL_ARB_separate_shader_objects
2416 * GL_ARB_tesselation_shader
2417 * GL_ARB_transform_feedback3
2418 * GL_ARB_uniform_buffer_object
2419 *
2420 * It is unknown whether GL_EXT_shader_image_load_store or GL_NV_gpu_shader5
2421 * allow layout with the deprecated keywords.
2422 */
2423 const bool relaxed_layout_qualifier_checking =
2424 state->ARB_fragment_coord_conventions_enable;
2425
2426 if (qual->has_layout() && uses_deprecated_qualifier) {
2427 if (relaxed_layout_qualifier_checking) {
2428 _mesa_glsl_warning(loc, state,
2429 "`layout' qualifier may not be used with "
2430 "`attribute' or `varying'");
2431 } else {
2432 _mesa_glsl_error(loc, state,
2433 "`layout' qualifier may not be used with "
2434 "`attribute' or `varying'");
2435 }
2436 }
2437
2438 /* Layout qualifiers for gl_FragDepth, which are enabled by extension
2439 * AMD_conservative_depth.
2440 */
2441 int depth_layout_count = qual->flags.q.depth_any
2442 + qual->flags.q.depth_greater
2443 + qual->flags.q.depth_less
2444 + qual->flags.q.depth_unchanged;
2445 if (depth_layout_count > 0
2446 && !state->AMD_conservative_depth_enable
2447 && !state->ARB_conservative_depth_enable) {
2448 _mesa_glsl_error(loc, state,
2449 "extension GL_AMD_conservative_depth or "
2450 "GL_ARB_conservative_depth must be enabled "
2451 "to use depth layout qualifiers");
2452 } else if (depth_layout_count > 0
2453 && strcmp(var->name, "gl_FragDepth") != 0) {
2454 _mesa_glsl_error(loc, state,
2455 "depth layout qualifiers can be applied only to "
2456 "gl_FragDepth");
2457 } else if (depth_layout_count > 1
2458 && strcmp(var->name, "gl_FragDepth") == 0) {
2459 _mesa_glsl_error(loc, state,
2460 "at most one depth layout qualifier can be applied to "
2461 "gl_FragDepth");
2462 }
2463 if (qual->flags.q.depth_any)
2464 var->data.depth_layout = ir_depth_layout_any;
2465 else if (qual->flags.q.depth_greater)
2466 var->data.depth_layout = ir_depth_layout_greater;
2467 else if (qual->flags.q.depth_less)
2468 var->data.depth_layout = ir_depth_layout_less;
2469 else if (qual->flags.q.depth_unchanged)
2470 var->data.depth_layout = ir_depth_layout_unchanged;
2471 else
2472 var->data.depth_layout = ir_depth_layout_none;
2473
2474 if (qual->flags.q.std140 ||
2475 qual->flags.q.packed ||
2476 qual->flags.q.shared) {
2477 _mesa_glsl_error(loc, state,
2478 "uniform block layout qualifiers std140, packed, and "
2479 "shared can only be applied to uniform blocks, not "
2480 "members");
2481 }
2482
2483 if (qual->flags.q.row_major || qual->flags.q.column_major) {
2484 validate_matrix_layout_for_type(state, loc, var->type, var);
2485 }
2486 }
2487
2488 /**
2489 * Get the variable that is being redeclared by this declaration
2490 *
2491 * Semantic checks to verify the validity of the redeclaration are also
2492 * performed. If semantic checks fail, compilation error will be emitted via
2493 * \c _mesa_glsl_error, but a non-\c NULL pointer will still be returned.
2494 *
2495 * \returns
2496 * A pointer to an existing variable in the current scope if the declaration
2497 * is a redeclaration, \c NULL otherwise.
2498 */
2499 static ir_variable *
2500 get_variable_being_redeclared(ir_variable *var, YYLTYPE loc,
2501 struct _mesa_glsl_parse_state *state,
2502 bool allow_all_redeclarations)
2503 {
2504 /* Check if this declaration is actually a re-declaration, either to
2505 * resize an array or add qualifiers to an existing variable.
2506 *
2507 * This is allowed for variables in the current scope, or when at
2508 * global scope (for built-ins in the implicit outer scope).
2509 */
2510 ir_variable *earlier = state->symbols->get_variable(var->name);
2511 if (earlier == NULL ||
2512 (state->current_function != NULL &&
2513 !state->symbols->name_declared_this_scope(var->name))) {
2514 return NULL;
2515 }
2516
2517
2518 /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec,
2519 *
2520 * "It is legal to declare an array without a size and then
2521 * later re-declare the same name as an array of the same
2522 * type and specify a size."
2523 */
2524 if (earlier->type->is_unsized_array() && var->type->is_array()
2525 && (var->type->element_type() == earlier->type->element_type())) {
2526 /* FINISHME: This doesn't match the qualifiers on the two
2527 * FINISHME: declarations. It's not 100% clear whether this is
2528 * FINISHME: required or not.
2529 */
2530
2531 const unsigned size = unsigned(var->type->array_size());
2532 check_builtin_array_max_size(var->name, size, loc, state);
2533 if ((size > 0) && (size <= earlier->data.max_array_access)) {
2534 _mesa_glsl_error(& loc, state, "array size must be > %u due to "
2535 "previous access",
2536 earlier->data.max_array_access);
2537 }
2538
2539 earlier->type = var->type;
2540 delete var;
2541 var = NULL;
2542 } else if ((state->ARB_fragment_coord_conventions_enable ||
2543 state->is_version(150, 0))
2544 && strcmp(var->name, "gl_FragCoord") == 0
2545 && earlier->type == var->type
2546 && earlier->data.mode == var->data.mode) {
2547 /* Allow redeclaration of gl_FragCoord for ARB_fcc layout
2548 * qualifiers.
2549 */
2550 earlier->data.origin_upper_left = var->data.origin_upper_left;
2551 earlier->data.pixel_center_integer = var->data.pixel_center_integer;
2552
2553 /* According to section 4.3.7 of the GLSL 1.30 spec,
2554 * the following built-in varaibles can be redeclared with an
2555 * interpolation qualifier:
2556 * * gl_FrontColor
2557 * * gl_BackColor
2558 * * gl_FrontSecondaryColor
2559 * * gl_BackSecondaryColor
2560 * * gl_Color
2561 * * gl_SecondaryColor
2562 */
2563 } else if (state->is_version(130, 0)
2564 && (strcmp(var->name, "gl_FrontColor") == 0
2565 || strcmp(var->name, "gl_BackColor") == 0
2566 || strcmp(var->name, "gl_FrontSecondaryColor") == 0
2567 || strcmp(var->name, "gl_BackSecondaryColor") == 0
2568 || strcmp(var->name, "gl_Color") == 0
2569 || strcmp(var->name, "gl_SecondaryColor") == 0)
2570 && earlier->type == var->type
2571 && earlier->data.mode == var->data.mode) {
2572 earlier->data.interpolation = var->data.interpolation;
2573
2574 /* Layout qualifiers for gl_FragDepth. */
2575 } else if ((state->AMD_conservative_depth_enable ||
2576 state->ARB_conservative_depth_enable)
2577 && strcmp(var->name, "gl_FragDepth") == 0
2578 && earlier->type == var->type
2579 && earlier->data.mode == var->data.mode) {
2580
2581 /** From the AMD_conservative_depth spec:
2582 * Within any shader, the first redeclarations of gl_FragDepth
2583 * must appear before any use of gl_FragDepth.
2584 */
2585 if (earlier->data.used) {
2586 _mesa_glsl_error(&loc, state,
2587 "the first redeclaration of gl_FragDepth "
2588 "must appear before any use of gl_FragDepth");
2589 }
2590
2591 /* Prevent inconsistent redeclaration of depth layout qualifier. */
2592 if (earlier->data.depth_layout != ir_depth_layout_none
2593 && earlier->data.depth_layout != var->data.depth_layout) {
2594 _mesa_glsl_error(&loc, state,
2595 "gl_FragDepth: depth layout is declared here "
2596 "as '%s, but it was previously declared as "
2597 "'%s'",
2598 depth_layout_string(var->data.depth_layout),
2599 depth_layout_string(earlier->data.depth_layout));
2600 }
2601
2602 earlier->data.depth_layout = var->data.depth_layout;
2603
2604 } else if (allow_all_redeclarations) {
2605 if (earlier->data.mode != var->data.mode) {
2606 _mesa_glsl_error(&loc, state,
2607 "redeclaration of `%s' with incorrect qualifiers",
2608 var->name);
2609 } else if (earlier->type != var->type) {
2610 _mesa_glsl_error(&loc, state,
2611 "redeclaration of `%s' has incorrect type",
2612 var->name);
2613 }
2614 } else {
2615 _mesa_glsl_error(&loc, state, "`%s' redeclared", var->name);
2616 }
2617
2618 return earlier;
2619 }
2620
2621 /**
2622 * Generate the IR for an initializer in a variable declaration
2623 */
2624 ir_rvalue *
2625 process_initializer(ir_variable *var, ast_declaration *decl,
2626 ast_fully_specified_type *type,
2627 exec_list *initializer_instructions,
2628 struct _mesa_glsl_parse_state *state)
2629 {
2630 ir_rvalue *result = NULL;
2631
2632 YYLTYPE initializer_loc = decl->initializer->get_location();
2633
2634 /* From page 24 (page 30 of the PDF) of the GLSL 1.10 spec:
2635 *
2636 * "All uniform variables are read-only and are initialized either
2637 * directly by an application via API commands, or indirectly by
2638 * OpenGL."
2639 */
2640 if (var->data.mode == ir_var_uniform) {
2641 state->check_version(120, 0, &initializer_loc,
2642 "cannot initialize uniforms");
2643 }
2644
2645 if (var->type->is_sampler()) {
2646 _mesa_glsl_error(& initializer_loc, state,
2647 "cannot initialize samplers");
2648 }
2649
2650 if ((var->data.mode == ir_var_shader_in) && (state->current_function == NULL)) {
2651 _mesa_glsl_error(& initializer_loc, state,
2652 "cannot initialize %s shader input / %s",
2653 _mesa_shader_stage_to_string(state->stage),
2654 (state->stage == MESA_SHADER_VERTEX)
2655 ? "attribute" : "varying");
2656 }
2657
2658 /* If the initializer is an ast_aggregate_initializer, recursively store
2659 * type information from the LHS into it, so that its hir() function can do
2660 * type checking.
2661 */
2662 if (decl->initializer->oper == ast_aggregate)
2663 _mesa_ast_set_aggregate_type(var->type, decl->initializer);
2664
2665 ir_dereference *const lhs = new(state) ir_dereference_variable(var);
2666 ir_rvalue *rhs = decl->initializer->hir(initializer_instructions,
2667 state);
2668
2669 /* Calculate the constant value if this is a const or uniform
2670 * declaration.
2671 */
2672 if (type->qualifier.flags.q.constant
2673 || type->qualifier.flags.q.uniform) {
2674 ir_rvalue *new_rhs = validate_assignment(state, initializer_loc,
2675 var->type, rhs, true);
2676 if (new_rhs != NULL) {
2677 rhs = new_rhs;
2678
2679 ir_constant *constant_value = rhs->constant_expression_value();
2680 if (!constant_value) {
2681 /* If ARB_shading_language_420pack is enabled, initializers of
2682 * const-qualified local variables do not have to be constant
2683 * expressions. Const-qualified global variables must still be
2684 * initialized with constant expressions.
2685 */
2686 if (!state->ARB_shading_language_420pack_enable
2687 || state->current_function == NULL) {
2688 _mesa_glsl_error(& initializer_loc, state,
2689 "initializer of %s variable `%s' must be a "
2690 "constant expression",
2691 (type->qualifier.flags.q.constant)
2692 ? "const" : "uniform",
2693 decl->identifier);
2694 if (var->type->is_numeric()) {
2695 /* Reduce cascading errors. */
2696 var->constant_value = ir_constant::zero(state, var->type);
2697 }
2698 }
2699 } else {
2700 rhs = constant_value;
2701 var->constant_value = constant_value;
2702 }
2703 } else {
2704 if (var->type->is_numeric()) {
2705 /* Reduce cascading errors. */
2706 var->constant_value = ir_constant::zero(state, var->type);
2707 }
2708 }
2709 }
2710
2711 if (rhs && !rhs->type->is_error()) {
2712 bool temp = var->data.read_only;
2713 if (type->qualifier.flags.q.constant)
2714 var->data.read_only = false;
2715
2716 /* Never emit code to initialize a uniform.
2717 */
2718 const glsl_type *initializer_type;
2719 if (!type->qualifier.flags.q.uniform) {
2720 result = do_assignment(initializer_instructions, state,
2721 NULL,
2722 lhs, rhs, true,
2723 type->get_location());
2724 initializer_type = result->type;
2725 } else
2726 initializer_type = rhs->type;
2727
2728 var->constant_initializer = rhs->constant_expression_value();
2729 var->data.has_initializer = true;
2730
2731 /* If the declared variable is an unsized array, it must inherrit
2732 * its full type from the initializer. A declaration such as
2733 *
2734 * uniform float a[] = float[](1.0, 2.0, 3.0, 3.0);
2735 *
2736 * becomes
2737 *
2738 * uniform float a[4] = float[](1.0, 2.0, 3.0, 3.0);
2739 *
2740 * The assignment generated in the if-statement (below) will also
2741 * automatically handle this case for non-uniforms.
2742 *
2743 * If the declared variable is not an array, the types must
2744 * already match exactly. As a result, the type assignment
2745 * here can be done unconditionally. For non-uniforms the call
2746 * to do_assignment can change the type of the initializer (via
2747 * the implicit conversion rules). For uniforms the initializer
2748 * must be a constant expression, and the type of that expression
2749 * was validated above.
2750 */
2751 var->type = initializer_type;
2752
2753 var->data.read_only = temp;
2754 }
2755
2756 return result;
2757 }
2758
2759
2760 /**
2761 * Do additional processing necessary for geometry shader input declarations
2762 * (this covers both interface blocks arrays and bare input variables).
2763 */
2764 static void
2765 handle_geometry_shader_input_decl(struct _mesa_glsl_parse_state *state,
2766 YYLTYPE loc, ir_variable *var)
2767 {
2768 unsigned num_vertices = 0;
2769 if (state->gs_input_prim_type_specified) {
2770 num_vertices = vertices_per_prim(state->gs_input_prim_type);
2771 }
2772
2773 /* Geometry shader input variables must be arrays. Caller should have
2774 * reported an error for this.
2775 */
2776 if (!var->type->is_array()) {
2777 assert(state->error);
2778
2779 /* To avoid cascading failures, short circuit the checks below. */
2780 return;
2781 }
2782
2783 if (var->type->is_unsized_array()) {
2784 /* Section 4.3.8.1 (Input Layout Qualifiers) of the GLSL 1.50 spec says:
2785 *
2786 * All geometry shader input unsized array declarations will be
2787 * sized by an earlier input layout qualifier, when present, as per
2788 * the following table.
2789 *
2790 * Followed by a table mapping each allowed input layout qualifier to
2791 * the corresponding input length.
2792 */
2793 if (num_vertices != 0)
2794 var->type = glsl_type::get_array_instance(var->type->fields.array,
2795 num_vertices);
2796 } else {
2797 /* Section 4.3.8.1 (Input Layout Qualifiers) of the GLSL 1.50 spec
2798 * includes the following examples of compile-time errors:
2799 *
2800 * // code sequence within one shader...
2801 * in vec4 Color1[]; // size unknown
2802 * ...Color1.length()...// illegal, length() unknown
2803 * in vec4 Color2[2]; // size is 2
2804 * ...Color1.length()...// illegal, Color1 still has no size
2805 * in vec4 Color3[3]; // illegal, input sizes are inconsistent
2806 * layout(lines) in; // legal, input size is 2, matching
2807 * in vec4 Color4[3]; // illegal, contradicts layout
2808 * ...
2809 *
2810 * To detect the case illustrated by Color3, we verify that the size of
2811 * an explicitly-sized array matches the size of any previously declared
2812 * explicitly-sized array. To detect the case illustrated by Color4, we
2813 * verify that the size of an explicitly-sized array is consistent with
2814 * any previously declared input layout.
2815 */
2816 if (num_vertices != 0 && var->type->length != num_vertices) {
2817 _mesa_glsl_error(&loc, state,
2818 "geometry shader input size contradicts previously"
2819 " declared layout (size is %u, but layout requires a"
2820 " size of %u)", var->type->length, num_vertices);
2821 } else if (state->gs_input_size != 0 &&
2822 var->type->length != state->gs_input_size) {
2823 _mesa_glsl_error(&loc, state,
2824 "geometry shader input sizes are "
2825 "inconsistent (size is %u, but a previous "
2826 "declaration has size %u)",
2827 var->type->length, state->gs_input_size);
2828 } else {
2829 state->gs_input_size = var->type->length;
2830 }
2831 }
2832 }
2833
2834
2835 void
2836 validate_identifier(const char *identifier, YYLTYPE loc,
2837 struct _mesa_glsl_parse_state *state)
2838 {
2839 /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
2840 *
2841 * "Identifiers starting with "gl_" are reserved for use by
2842 * OpenGL, and may not be declared in a shader as either a
2843 * variable or a function."
2844 */
2845 if (strncmp(identifier, "gl_", 3) == 0) {
2846 _mesa_glsl_error(&loc, state,
2847 "identifier `%s' uses reserved `gl_' prefix",
2848 identifier);
2849 } else if (strstr(identifier, "__")) {
2850 /* From page 14 (page 20 of the PDF) of the GLSL 1.10
2851 * spec:
2852 *
2853 * "In addition, all identifiers containing two
2854 * consecutive underscores (__) are reserved as
2855 * possible future keywords."
2856 */
2857 _mesa_glsl_error(&loc, state,
2858 "identifier `%s' uses reserved `__' string",
2859 identifier);
2860 }
2861 }
2862
2863
2864 ir_rvalue *
2865 ast_declarator_list::hir(exec_list *instructions,
2866 struct _mesa_glsl_parse_state *state)
2867 {
2868 void *ctx = state;
2869 const struct glsl_type *decl_type;
2870 const char *type_name = NULL;
2871 ir_rvalue *result = NULL;
2872 YYLTYPE loc = this->get_location();
2873
2874 /* From page 46 (page 52 of the PDF) of the GLSL 1.50 spec:
2875 *
2876 * "To ensure that a particular output variable is invariant, it is
2877 * necessary to use the invariant qualifier. It can either be used to
2878 * qualify a previously declared variable as being invariant
2879 *
2880 * invariant gl_Position; // make existing gl_Position be invariant"
2881 *
2882 * In these cases the parser will set the 'invariant' flag in the declarator
2883 * list, and the type will be NULL.
2884 */
2885 if (this->invariant) {
2886 assert(this->type == NULL);
2887
2888 if (state->current_function != NULL) {
2889 _mesa_glsl_error(& loc, state,
2890 "all uses of `invariant' keyword must be at global "
2891 "scope");
2892 }
2893
2894 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
2895 assert(decl->array_specifier == NULL);
2896 assert(decl->initializer == NULL);
2897
2898 ir_variable *const earlier =
2899 state->symbols->get_variable(decl->identifier);
2900 if (earlier == NULL) {
2901 _mesa_glsl_error(& loc, state,
2902 "undeclared variable `%s' cannot be marked "
2903 "invariant", decl->identifier);
2904 } else if ((state->stage == MESA_SHADER_VERTEX)
2905 && (earlier->data.mode != ir_var_shader_out)) {
2906 _mesa_glsl_error(& loc, state,
2907 "`%s' cannot be marked invariant, vertex shader "
2908 "outputs only", decl->identifier);
2909 } else if ((state->stage == MESA_SHADER_FRAGMENT)
2910 && (earlier->data.mode != ir_var_shader_in)) {
2911 _mesa_glsl_error(& loc, state,
2912 "`%s' cannot be marked invariant, fragment shader "
2913 "inputs only", decl->identifier);
2914 } else if (earlier->data.used) {
2915 _mesa_glsl_error(& loc, state,
2916 "variable `%s' may not be redeclared "
2917 "`invariant' after being used",
2918 earlier->name);
2919 } else {
2920 earlier->data.invariant = true;
2921 }
2922 }
2923
2924 /* Invariant redeclarations do not have r-values.
2925 */
2926 return NULL;
2927 }
2928
2929 assert(this->type != NULL);
2930 assert(!this->invariant);
2931
2932 /* The type specifier may contain a structure definition. Process that
2933 * before any of the variable declarations.
2934 */
2935 (void) this->type->specifier->hir(instructions, state);
2936
2937 decl_type = this->type->glsl_type(& type_name, state);
2938
2939 /* An offset-qualified atomic counter declaration sets the default
2940 * offset for the next declaration within the same atomic counter
2941 * buffer.
2942 */
2943 if (decl_type && decl_type->contains_atomic()) {
2944 if (type->qualifier.flags.q.explicit_binding &&
2945 type->qualifier.flags.q.explicit_offset)
2946 state->atomic_counter_offsets[type->qualifier.binding] =
2947 type->qualifier.offset;
2948 }
2949
2950 if (this->declarations.is_empty()) {
2951 /* If there is no structure involved in the program text, there are two
2952 * possible scenarios:
2953 *
2954 * - The program text contained something like 'vec4;'. This is an
2955 * empty declaration. It is valid but weird. Emit a warning.
2956 *
2957 * - The program text contained something like 'S;' and 'S' is not the
2958 * name of a known structure type. This is both invalid and weird.
2959 * Emit an error.
2960 *
2961 * - The program text contained something like 'mediump float;'
2962 * when the programmer probably meant 'precision mediump
2963 * float;' Emit a warning with a description of what they
2964 * probably meant to do.
2965 *
2966 * Note that if decl_type is NULL and there is a structure involved,
2967 * there must have been some sort of error with the structure. In this
2968 * case we assume that an error was already generated on this line of
2969 * code for the structure. There is no need to generate an additional,
2970 * confusing error.
2971 */
2972 assert(this->type->specifier->structure == NULL || decl_type != NULL
2973 || state->error);
2974
2975 if (decl_type == NULL) {
2976 _mesa_glsl_error(&loc, state,
2977 "invalid type `%s' in empty declaration",
2978 type_name);
2979 } else if (decl_type->base_type == GLSL_TYPE_ATOMIC_UINT) {
2980 /* Empty atomic counter declarations are allowed and useful
2981 * to set the default offset qualifier.
2982 */
2983 return NULL;
2984 } else if (this->type->qualifier.precision != ast_precision_none) {
2985 if (this->type->specifier->structure != NULL) {
2986 _mesa_glsl_error(&loc, state,
2987 "precision qualifiers can't be applied "
2988 "to structures");
2989 } else {
2990 static const char *const precision_names[] = {
2991 "highp",
2992 "highp",
2993 "mediump",
2994 "lowp"
2995 };
2996
2997 _mesa_glsl_warning(&loc, state,
2998 "empty declaration with precision qualifier, "
2999 "to set the default precision, use "
3000 "`precision %s %s;'",
3001 precision_names[this->type->qualifier.precision],
3002 type_name);
3003 }
3004 } else if (this->type->specifier->structure == NULL) {
3005 _mesa_glsl_warning(&loc, state, "empty declaration");
3006 }
3007 }
3008
3009 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
3010 const struct glsl_type *var_type;
3011 ir_variable *var;
3012
3013 /* FINISHME: Emit a warning if a variable declaration shadows a
3014 * FINISHME: declaration at a higher scope.
3015 */
3016
3017 if ((decl_type == NULL) || decl_type->is_void()) {
3018 if (type_name != NULL) {
3019 _mesa_glsl_error(& loc, state,
3020 "invalid type `%s' in declaration of `%s'",
3021 type_name, decl->identifier);
3022 } else {
3023 _mesa_glsl_error(& loc, state,
3024 "invalid type in declaration of `%s'",
3025 decl->identifier);
3026 }
3027 continue;
3028 }
3029
3030 var_type = process_array_type(&loc, decl_type, decl->array_specifier,
3031 state);
3032
3033 var = new(ctx) ir_variable(var_type, decl->identifier, ir_var_auto);
3034
3035 /* The 'varying in' and 'varying out' qualifiers can only be used with
3036 * ARB_geometry_shader4 and EXT_geometry_shader4, which we don't support
3037 * yet.
3038 */
3039 if (this->type->qualifier.flags.q.varying) {
3040 if (this->type->qualifier.flags.q.in) {
3041 _mesa_glsl_error(& loc, state,
3042 "`varying in' qualifier in declaration of "
3043 "`%s' only valid for geometry shaders using "
3044 "ARB_geometry_shader4 or EXT_geometry_shader4",
3045 decl->identifier);
3046 } else if (this->type->qualifier.flags.q.out) {
3047 _mesa_glsl_error(& loc, state,
3048 "`varying out' qualifier in declaration of "
3049 "`%s' only valid for geometry shaders using "
3050 "ARB_geometry_shader4 or EXT_geometry_shader4",
3051 decl->identifier);
3052 }
3053 }
3054
3055 /* From page 22 (page 28 of the PDF) of the GLSL 1.10 specification;
3056 *
3057 * "Global variables can only use the qualifiers const,
3058 * attribute, uni form, or varying. Only one may be
3059 * specified.
3060 *
3061 * Local variables can only use the qualifier const."
3062 *
3063 * This is relaxed in GLSL 1.30 and GLSL ES 3.00. It is also relaxed by
3064 * any extension that adds the 'layout' keyword.
3065 */
3066 if (!state->is_version(130, 300)
3067 && !state->has_explicit_attrib_location()
3068 && !state->ARB_fragment_coord_conventions_enable) {
3069 if (this->type->qualifier.flags.q.out) {
3070 _mesa_glsl_error(& loc, state,
3071 "`out' qualifier in declaration of `%s' "
3072 "only valid for function parameters in %s",
3073 decl->identifier, state->get_version_string());
3074 }
3075 if (this->type->qualifier.flags.q.in) {
3076 _mesa_glsl_error(& loc, state,
3077 "`in' qualifier in declaration of `%s' "
3078 "only valid for function parameters in %s",
3079 decl->identifier, state->get_version_string());
3080 }
3081 /* FINISHME: Test for other invalid qualifiers. */
3082 }
3083
3084 apply_type_qualifier_to_variable(& this->type->qualifier, var, state,
3085 & loc, false);
3086
3087 if (this->type->qualifier.flags.q.invariant) {
3088 if ((state->stage == MESA_SHADER_VERTEX) &&
3089 var->data.mode != ir_var_shader_out) {
3090 _mesa_glsl_error(& loc, state,
3091 "`%s' cannot be marked invariant, vertex shader "
3092 "outputs only", var->name);
3093 } else if ((state->stage == MESA_SHADER_FRAGMENT) &&
3094 var->data.mode != ir_var_shader_in) {
3095 /* FINISHME: Note that this doesn't work for invariant on
3096 * a function signature inval
3097 */
3098 _mesa_glsl_error(& loc, state,
3099 "`%s' cannot be marked invariant, fragment shader "
3100 "inputs only", var->name);
3101 }
3102 }
3103
3104 if (state->current_function != NULL) {
3105 const char *mode = NULL;
3106 const char *extra = "";
3107
3108 /* There is no need to check for 'inout' here because the parser will
3109 * only allow that in function parameter lists.
3110 */
3111 if (this->type->qualifier.flags.q.attribute) {
3112 mode = "attribute";
3113 } else if (this->type->qualifier.flags.q.uniform) {
3114 mode = "uniform";
3115 } else if (this->type->qualifier.flags.q.varying) {
3116 mode = "varying";
3117 } else if (this->type->qualifier.flags.q.in) {
3118 mode = "in";
3119 extra = " or in function parameter list";
3120 } else if (this->type->qualifier.flags.q.out) {
3121 mode = "out";
3122 extra = " or in function parameter list";
3123 }
3124
3125 if (mode) {
3126 _mesa_glsl_error(& loc, state,
3127 "%s variable `%s' must be declared at "
3128 "global scope%s",
3129 mode, var->name, extra);
3130 }
3131 } else if (var->data.mode == ir_var_shader_in) {
3132 var->data.read_only = true;
3133
3134 if (state->stage == MESA_SHADER_VERTEX) {
3135 bool error_emitted = false;
3136
3137 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
3138 *
3139 * "Vertex shader inputs can only be float, floating-point
3140 * vectors, matrices, signed and unsigned integers and integer
3141 * vectors. Vertex shader inputs can also form arrays of these
3142 * types, but not structures."
3143 *
3144 * From page 31 (page 27 of the PDF) of the GLSL 1.30 spec:
3145 *
3146 * "Vertex shader inputs can only be float, floating-point
3147 * vectors, matrices, signed and unsigned integers and integer
3148 * vectors. They cannot be arrays or structures."
3149 *
3150 * From page 23 (page 29 of the PDF) of the GLSL 1.20 spec:
3151 *
3152 * "The attribute qualifier can be used only with float,
3153 * floating-point vectors, and matrices. Attribute variables
3154 * cannot be declared as arrays or structures."
3155 *
3156 * From page 33 (page 39 of the PDF) of the GLSL ES 3.00 spec:
3157 *
3158 * "Vertex shader inputs can only be float, floating-point
3159 * vectors, matrices, signed and unsigned integers and integer
3160 * vectors. Vertex shader inputs cannot be arrays or
3161 * structures."
3162 */
3163 const glsl_type *check_type = var->type;
3164 while (check_type->is_array())
3165 check_type = check_type->element_type();
3166
3167 switch (check_type->base_type) {
3168 case GLSL_TYPE_FLOAT:
3169 break;
3170 case GLSL_TYPE_UINT:
3171 case GLSL_TYPE_INT:
3172 if (state->is_version(120, 300))
3173 break;
3174 /* FALLTHROUGH */
3175 default:
3176 _mesa_glsl_error(& loc, state,
3177 "vertex shader input / attribute cannot have "
3178 "type %s`%s'",
3179 var->type->is_array() ? "array of " : "",
3180 check_type->name);
3181 error_emitted = true;
3182 }
3183
3184 if (!error_emitted && var->type->is_array() &&
3185 !state->check_version(150, 0, &loc,
3186 "vertex shader input / attribute "
3187 "cannot have array type")) {
3188 error_emitted = true;
3189 }
3190 } else if (state->stage == MESA_SHADER_GEOMETRY) {
3191 /* From section 4.3.4 (Inputs) of the GLSL 1.50 spec:
3192 *
3193 * Geometry shader input variables get the per-vertex values
3194 * written out by vertex shader output variables of the same
3195 * names. Since a geometry shader operates on a set of
3196 * vertices, each input varying variable (or input block, see
3197 * interface blocks below) needs to be declared as an array.
3198 */
3199 if (!var->type->is_array()) {
3200 _mesa_glsl_error(&loc, state,
3201 "geometry shader inputs must be arrays");
3202 }
3203
3204 handle_geometry_shader_input_decl(state, loc, var);
3205 }
3206 }
3207
3208 /* Integer fragment inputs must be qualified with 'flat'. In GLSL ES,
3209 * so must integer vertex outputs.
3210 *
3211 * From section 4.3.4 ("Inputs") of the GLSL 1.50 spec:
3212 * "Fragment shader inputs that are signed or unsigned integers or
3213 * integer vectors must be qualified with the interpolation qualifier
3214 * flat."
3215 *
3216 * From section 4.3.4 ("Input Variables") of the GLSL 3.00 ES spec:
3217 * "Fragment shader inputs that are, or contain, signed or unsigned
3218 * integers or integer vectors must be qualified with the
3219 * interpolation qualifier flat."
3220 *
3221 * From section 4.3.6 ("Output Variables") of the GLSL 3.00 ES spec:
3222 * "Vertex shader outputs that are, or contain, signed or unsigned
3223 * integers or integer vectors must be qualified with the
3224 * interpolation qualifier flat."
3225 *
3226 * Note that prior to GLSL 1.50, this requirement applied to vertex
3227 * outputs rather than fragment inputs. That creates problems in the
3228 * presence of geometry shaders, so we adopt the GLSL 1.50 rule for all
3229 * desktop GL shaders. For GLSL ES shaders, we follow the spec and
3230 * apply the restriction to both vertex outputs and fragment inputs.
3231 *
3232 * Note also that the desktop GLSL specs are missing the text "or
3233 * contain"; this is presumably an oversight, since there is no
3234 * reasonable way to interpolate a fragment shader input that contains
3235 * an integer.
3236 */
3237 if (state->is_version(130, 300) &&
3238 var->type->contains_integer() &&
3239 var->data.interpolation != INTERP_QUALIFIER_FLAT &&
3240 ((state->stage == MESA_SHADER_FRAGMENT && var->data.mode == ir_var_shader_in)
3241 || (state->stage == MESA_SHADER_VERTEX && var->data.mode == ir_var_shader_out
3242 && state->es_shader))) {
3243 const char *var_type = (state->stage == MESA_SHADER_VERTEX) ?
3244 "vertex output" : "fragment input";
3245 _mesa_glsl_error(&loc, state, "if a %s is (or contains) "
3246 "an integer, then it must be qualified with 'flat'",
3247 var_type);
3248 }
3249
3250
3251 /* Interpolation qualifiers cannot be applied to 'centroid' and
3252 * 'centroid varying'.
3253 *
3254 * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
3255 * "interpolation qualifiers may only precede the qualifiers in,
3256 * centroid in, out, or centroid out in a declaration. They do not apply
3257 * to the deprecated storage qualifiers varying or centroid varying."
3258 *
3259 * These deprecated storage qualifiers do not exist in GLSL ES 3.00.
3260 */
3261 if (state->is_version(130, 0)
3262 && this->type->qualifier.has_interpolation()
3263 && this->type->qualifier.flags.q.varying) {
3264
3265 const char *i = this->type->qualifier.interpolation_string();
3266 assert(i != NULL);
3267 const char *s;
3268 if (this->type->qualifier.flags.q.centroid)
3269 s = "centroid varying";
3270 else
3271 s = "varying";
3272
3273 _mesa_glsl_error(&loc, state,
3274 "qualifier '%s' cannot be applied to the "
3275 "deprecated storage qualifier '%s'", i, s);
3276 }
3277
3278
3279 /* Interpolation qualifiers can only apply to vertex shader outputs and
3280 * fragment shader inputs.
3281 *
3282 * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
3283 * "Outputs from a vertex shader (out) and inputs to a fragment
3284 * shader (in) can be further qualified with one or more of these
3285 * interpolation qualifiers"
3286 *
3287 * From page 31 (page 37 of the PDF) of the GLSL ES 3.00 spec:
3288 * "These interpolation qualifiers may only precede the qualifiers
3289 * in, centroid in, out, or centroid out in a declaration. They do
3290 * not apply to inputs into a vertex shader or outputs from a
3291 * fragment shader."
3292 */
3293 if (state->is_version(130, 300)
3294 && this->type->qualifier.has_interpolation()) {
3295
3296 const char *i = this->type->qualifier.interpolation_string();
3297 assert(i != NULL);
3298
3299 switch (state->stage) {
3300 case MESA_SHADER_VERTEX:
3301 if (this->type->qualifier.flags.q.in) {
3302 _mesa_glsl_error(&loc, state,
3303 "qualifier '%s' cannot be applied to vertex "
3304 "shader inputs", i);
3305 }
3306 break;
3307 case MESA_SHADER_FRAGMENT:
3308 if (this->type->qualifier.flags.q.out) {
3309 _mesa_glsl_error(&loc, state,
3310 "qualifier '%s' cannot be applied to fragment "
3311 "shader outputs", i);
3312 }
3313 break;
3314 default:
3315 break;
3316 }
3317 }
3318
3319
3320 /* From section 4.3.4 of the GLSL 1.30 spec:
3321 * "It is an error to use centroid in in a vertex shader."
3322 *
3323 * From section 4.3.4 of the GLSL ES 3.00 spec:
3324 * "It is an error to use centroid in or interpolation qualifiers in
3325 * a vertex shader input."
3326 */
3327 if (state->is_version(130, 300)
3328 && this->type->qualifier.flags.q.centroid
3329 && this->type->qualifier.flags.q.in
3330 && state->stage == MESA_SHADER_VERTEX) {
3331
3332 _mesa_glsl_error(&loc, state,
3333 "'centroid in' cannot be used in a vertex shader");
3334 }
3335
3336 if (state->stage == MESA_SHADER_VERTEX
3337 && this->type->qualifier.flags.q.sample
3338 && this->type->qualifier.flags.q.in) {
3339
3340 _mesa_glsl_error(&loc, state,
3341 "'sample in' cannot be used in a vertex shader");
3342 }
3343
3344 /* Section 4.3.6 of the GLSL 1.30 specification states:
3345 * "It is an error to use centroid out in a fragment shader."
3346 *
3347 * The GL_ARB_shading_language_420pack extension specification states:
3348 * "It is an error to use auxiliary storage qualifiers or interpolation
3349 * qualifiers on an output in a fragment shader."
3350 */
3351 if (state->stage == MESA_SHADER_FRAGMENT &&
3352 this->type->qualifier.flags.q.out &&
3353 this->type->qualifier.has_auxiliary_storage()) {
3354 _mesa_glsl_error(&loc, state,
3355 "auxiliary storage qualifiers cannot be used on "
3356 "fragment shader outputs");
3357 }
3358
3359 /* Precision qualifiers exists only in GLSL versions 1.00 and >= 1.30.
3360 */
3361 if (this->type->qualifier.precision != ast_precision_none) {
3362 state->check_precision_qualifiers_allowed(&loc);
3363 }
3364
3365
3366 /* Precision qualifiers apply to floating point, integer and sampler
3367 * types.
3368 *
3369 * Section 4.5.2 (Precision Qualifiers) of the GLSL 1.30 spec says:
3370 * "Any floating point or any integer declaration can have the type
3371 * preceded by one of these precision qualifiers [...] Literal
3372 * constants do not have precision qualifiers. Neither do Boolean
3373 * variables.
3374 *
3375 * Section 4.5 (Precision and Precision Qualifiers) of the GLSL 1.30
3376 * spec also says:
3377 *
3378 * "Precision qualifiers are added for code portability with OpenGL
3379 * ES, not for functionality. They have the same syntax as in OpenGL
3380 * ES."
3381 *
3382 * Section 8 (Built-In Functions) of the GLSL ES 1.00 spec says:
3383 *
3384 * "uniform lowp sampler2D sampler;
3385 * highp vec2 coord;
3386 * ...
3387 * lowp vec4 col = texture2D (sampler, coord);
3388 * // texture2D returns lowp"
3389 *
3390 * From this, we infer that GLSL 1.30 (and later) should allow precision
3391 * qualifiers on sampler types just like float and integer types.
3392 */
3393 if (this->type->qualifier.precision != ast_precision_none
3394 && !var->type->is_float()
3395 && !var->type->is_integer()
3396 && !var->type->is_record()
3397 && !var->type->is_sampler()
3398 && !(var->type->is_array()
3399 && (var->type->fields.array->is_float()
3400 || var->type->fields.array->is_integer()))) {
3401
3402 _mesa_glsl_error(&loc, state,
3403 "precision qualifiers apply only to floating point"
3404 ", integer and sampler types");
3405 }
3406
3407 /* From page 17 (page 23 of the PDF) of the GLSL 1.20 spec:
3408 *
3409 * "[Sampler types] can only be declared as function
3410 * parameters or uniform variables (see Section 4.3.5
3411 * "Uniform")".
3412 */
3413 if (var_type->contains_sampler() &&
3414 !this->type->qualifier.flags.q.uniform) {
3415 _mesa_glsl_error(&loc, state, "samplers must be declared uniform");
3416 }
3417
3418 /* Process the initializer and add its instructions to a temporary
3419 * list. This list will be added to the instruction stream (below) after
3420 * the declaration is added. This is done because in some cases (such as
3421 * redeclarations) the declaration may not actually be added to the
3422 * instruction stream.
3423 */
3424 exec_list initializer_instructions;
3425 ir_variable *earlier =
3426 get_variable_being_redeclared(var, decl->get_location(), state,
3427 false /* allow_all_redeclarations */);
3428 if (earlier != NULL) {
3429 if (strncmp(var->name, "gl_", 3) == 0 &&
3430 earlier->data.how_declared == ir_var_declared_in_block) {
3431 _mesa_glsl_error(&loc, state,
3432 "`%s' has already been redeclared using "
3433 "gl_PerVertex", var->name);
3434 }
3435 earlier->data.how_declared = ir_var_declared_normally;
3436 }
3437
3438 if (decl->initializer != NULL) {
3439 result = process_initializer((earlier == NULL) ? var : earlier,
3440 decl, this->type,
3441 &initializer_instructions, state);
3442 }
3443
3444 /* From page 23 (page 29 of the PDF) of the GLSL 1.10 spec:
3445 *
3446 * "It is an error to write to a const variable outside of
3447 * its declaration, so they must be initialized when
3448 * declared."
3449 */
3450 if (this->type->qualifier.flags.q.constant && decl->initializer == NULL) {
3451 _mesa_glsl_error(& loc, state,
3452 "const declaration of `%s' must be initialized",
3453 decl->identifier);
3454 }
3455
3456 if (state->es_shader) {
3457 const glsl_type *const t = (earlier == NULL)
3458 ? var->type : earlier->type;
3459
3460 if (t->is_unsized_array())
3461 /* Section 10.17 of the GLSL ES 1.00 specification states that
3462 * unsized array declarations have been removed from the language.
3463 * Arrays that are sized using an initializer are still explicitly
3464 * sized. However, GLSL ES 1.00 does not allow array
3465 * initializers. That is only allowed in GLSL ES 3.00.
3466 *
3467 * Section 4.1.9 (Arrays) of the GLSL ES 3.00 spec says:
3468 *
3469 * "An array type can also be formed without specifying a size
3470 * if the definition includes an initializer:
3471 *
3472 * float x[] = float[2] (1.0, 2.0); // declares an array of size 2
3473 * float y[] = float[] (1.0, 2.0, 3.0); // declares an array of size 3
3474 *
3475 * float a[5];
3476 * float b[] = a;"
3477 */
3478 _mesa_glsl_error(& loc, state,
3479 "unsized array declarations are not allowed in "
3480 "GLSL ES");
3481 }
3482
3483 /* If the declaration is not a redeclaration, there are a few additional
3484 * semantic checks that must be applied. In addition, variable that was
3485 * created for the declaration should be added to the IR stream.
3486 */
3487 if (earlier == NULL) {
3488 validate_identifier(decl->identifier, loc, state);
3489
3490 /* Add the variable to the symbol table. Note that the initializer's
3491 * IR was already processed earlier (though it hasn't been emitted
3492 * yet), without the variable in scope.
3493 *
3494 * This differs from most C-like languages, but it follows the GLSL
3495 * specification. From page 28 (page 34 of the PDF) of the GLSL 1.50
3496 * spec:
3497 *
3498 * "Within a declaration, the scope of a name starts immediately
3499 * after the initializer if present or immediately after the name
3500 * being declared if not."
3501 */
3502 if (!state->symbols->add_variable(var)) {
3503 YYLTYPE loc = this->get_location();
3504 _mesa_glsl_error(&loc, state, "name `%s' already taken in the "
3505 "current scope", decl->identifier);
3506 continue;
3507 }
3508
3509 /* Push the variable declaration to the top. It means that all the
3510 * variable declarations will appear in a funny last-to-first order,
3511 * but otherwise we run into trouble if a function is prototyped, a
3512 * global var is decled, then the function is defined with usage of
3513 * the global var. See glslparsertest's CorrectModule.frag.
3514 */
3515 instructions->push_head(var);
3516 }
3517
3518 instructions->append_list(&initializer_instructions);
3519 }
3520
3521
3522 /* Generally, variable declarations do not have r-values. However,
3523 * one is used for the declaration in
3524 *
3525 * while (bool b = some_condition()) {
3526 * ...
3527 * }
3528 *
3529 * so we return the rvalue from the last seen declaration here.
3530 */
3531 return result;
3532 }
3533
3534
3535 ir_rvalue *
3536 ast_parameter_declarator::hir(exec_list *instructions,
3537 struct _mesa_glsl_parse_state *state)
3538 {
3539 void *ctx = state;
3540 const struct glsl_type *type;
3541 const char *name = NULL;
3542 YYLTYPE loc = this->get_location();
3543
3544 type = this->type->glsl_type(& name, state);
3545
3546 if (type == NULL) {
3547 if (name != NULL) {
3548 _mesa_glsl_error(& loc, state,
3549 "invalid type `%s' in declaration of `%s'",
3550 name, this->identifier);
3551 } else {
3552 _mesa_glsl_error(& loc, state,
3553 "invalid type in declaration of `%s'",
3554 this->identifier);
3555 }
3556
3557 type = glsl_type::error_type;
3558 }
3559
3560 /* From page 62 (page 68 of the PDF) of the GLSL 1.50 spec:
3561 *
3562 * "Functions that accept no input arguments need not use void in the
3563 * argument list because prototypes (or definitions) are required and
3564 * therefore there is no ambiguity when an empty argument list "( )" is
3565 * declared. The idiom "(void)" as a parameter list is provided for
3566 * convenience."
3567 *
3568 * Placing this check here prevents a void parameter being set up
3569 * for a function, which avoids tripping up checks for main taking
3570 * parameters and lookups of an unnamed symbol.
3571 */
3572 if (type->is_void()) {
3573 if (this->identifier != NULL)
3574 _mesa_glsl_error(& loc, state,
3575 "named parameter cannot have type `void'");
3576
3577 is_void = true;
3578 return NULL;
3579 }
3580
3581 if (formal_parameter && (this->identifier == NULL)) {
3582 _mesa_glsl_error(& loc, state, "formal parameter lacks a name");
3583 return NULL;
3584 }
3585
3586 /* This only handles "vec4 foo[..]". The earlier specifier->glsl_type(...)
3587 * call already handled the "vec4[..] foo" case.
3588 */
3589 type = process_array_type(&loc, type, this->array_specifier, state);
3590
3591 if (!type->is_error() && type->is_unsized_array()) {
3592 _mesa_glsl_error(&loc, state, "arrays passed as parameters must have "
3593 "a declared size");
3594 type = glsl_type::error_type;
3595 }
3596
3597 is_void = false;
3598 ir_variable *var = new(ctx)
3599 ir_variable(type, this->identifier, ir_var_function_in);
3600
3601 /* Apply any specified qualifiers to the parameter declaration. Note that
3602 * for function parameters the default mode is 'in'.
3603 */
3604 apply_type_qualifier_to_variable(& this->type->qualifier, var, state, & loc,
3605 true);
3606
3607 /* From page 17 (page 23 of the PDF) of the GLSL 1.20 spec:
3608 *
3609 * "Samplers cannot be treated as l-values; hence cannot be used
3610 * as out or inout function parameters, nor can they be assigned
3611 * into."
3612 */
3613 if ((var->data.mode == ir_var_function_inout || var->data.mode == ir_var_function_out)
3614 && type->contains_sampler()) {
3615 _mesa_glsl_error(&loc, state, "out and inout parameters cannot contain samplers");
3616 type = glsl_type::error_type;
3617 }
3618
3619 /* From page 39 (page 45 of the PDF) of the GLSL 1.10 spec:
3620 *
3621 * "When calling a function, expressions that do not evaluate to
3622 * l-values cannot be passed to parameters declared as out or inout."
3623 *
3624 * From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
3625 *
3626 * "Other binary or unary expressions, non-dereferenced arrays,
3627 * function names, swizzles with repeated fields, and constants
3628 * cannot be l-values."
3629 *
3630 * So for GLSL 1.10, passing an array as an out or inout parameter is not
3631 * allowed. This restriction is removed in GLSL 1.20, and in GLSL ES.
3632 */
3633 if ((var->data.mode == ir_var_function_inout || var->data.mode == ir_var_function_out)
3634 && type->is_array()
3635 && !state->check_version(120, 100, &loc,
3636 "arrays cannot be out or inout parameters")) {
3637 type = glsl_type::error_type;
3638 }
3639
3640 instructions->push_tail(var);
3641
3642 /* Parameter declarations do not have r-values.
3643 */
3644 return NULL;
3645 }
3646
3647
3648 void
3649 ast_parameter_declarator::parameters_to_hir(exec_list *ast_parameters,
3650 bool formal,
3651 exec_list *ir_parameters,
3652 _mesa_glsl_parse_state *state)
3653 {
3654 ast_parameter_declarator *void_param = NULL;
3655 unsigned count = 0;
3656
3657 foreach_list_typed (ast_parameter_declarator, param, link, ast_parameters) {
3658 param->formal_parameter = formal;
3659 param->hir(ir_parameters, state);
3660
3661 if (param->is_void)
3662 void_param = param;
3663
3664 count++;
3665 }
3666
3667 if ((void_param != NULL) && (count > 1)) {
3668 YYLTYPE loc = void_param->get_location();
3669
3670 _mesa_glsl_error(& loc, state,
3671 "`void' parameter must be only parameter");
3672 }
3673 }
3674
3675
3676 void
3677 emit_function(_mesa_glsl_parse_state *state, ir_function *f)
3678 {
3679 /* IR invariants disallow function declarations or definitions
3680 * nested within other function definitions. But there is no
3681 * requirement about the relative order of function declarations
3682 * and definitions with respect to one another. So simply insert
3683 * the new ir_function block at the end of the toplevel instruction
3684 * list.
3685 */
3686 state->toplevel_ir->push_tail(f);
3687 }
3688
3689
3690 ir_rvalue *
3691 ast_function::hir(exec_list *instructions,
3692 struct _mesa_glsl_parse_state *state)
3693 {
3694 void *ctx = state;
3695 ir_function *f = NULL;
3696 ir_function_signature *sig = NULL;
3697 exec_list hir_parameters;
3698
3699 const char *const name = identifier;
3700
3701 /* New functions are always added to the top-level IR instruction stream,
3702 * so this instruction list pointer is ignored. See also emit_function
3703 * (called below).
3704 */
3705 (void) instructions;
3706
3707 /* From page 21 (page 27 of the PDF) of the GLSL 1.20 spec,
3708 *
3709 * "Function declarations (prototypes) cannot occur inside of functions;
3710 * they must be at global scope, or for the built-in functions, outside
3711 * the global scope."
3712 *
3713 * From page 27 (page 33 of the PDF) of the GLSL ES 1.00.16 spec,
3714 *
3715 * "User defined functions may only be defined within the global scope."
3716 *
3717 * Note that this language does not appear in GLSL 1.10.
3718 */
3719 if ((state->current_function != NULL) &&
3720 state->is_version(120, 100)) {
3721 YYLTYPE loc = this->get_location();
3722 _mesa_glsl_error(&loc, state,
3723 "declaration of function `%s' not allowed within "
3724 "function body", name);
3725 }
3726
3727 validate_identifier(name, this->get_location(), state);
3728
3729 /* Convert the list of function parameters to HIR now so that they can be
3730 * used below to compare this function's signature with previously seen
3731 * signatures for functions with the same name.
3732 */
3733 ast_parameter_declarator::parameters_to_hir(& this->parameters,
3734 is_definition,
3735 & hir_parameters, state);
3736
3737 const char *return_type_name;
3738 const glsl_type *return_type =
3739 this->return_type->glsl_type(& return_type_name, state);
3740
3741 if (!return_type) {
3742 YYLTYPE loc = this->get_location();
3743 _mesa_glsl_error(&loc, state,
3744 "function `%s' has undeclared return type `%s'",
3745 name, return_type_name);
3746 return_type = glsl_type::error_type;
3747 }
3748
3749 /* From page 56 (page 62 of the PDF) of the GLSL 1.30 spec:
3750 * "No qualifier is allowed on the return type of a function."
3751 */
3752 if (this->return_type->has_qualifiers()) {
3753 YYLTYPE loc = this->get_location();
3754 _mesa_glsl_error(& loc, state,
3755 "function `%s' return type has qualifiers", name);
3756 }
3757
3758 /* Section 6.1 (Function Definitions) of the GLSL 1.20 spec says:
3759 *
3760 * "Arrays are allowed as arguments and as the return type. In both
3761 * cases, the array must be explicitly sized."
3762 */
3763 if (return_type->is_unsized_array()) {
3764 YYLTYPE loc = this->get_location();
3765 _mesa_glsl_error(& loc, state,
3766 "function `%s' return type array must be explicitly "
3767 "sized", name);
3768 }
3769
3770 /* From page 17 (page 23 of the PDF) of the GLSL 1.20 spec:
3771 *
3772 * "[Sampler types] can only be declared as function parameters
3773 * or uniform variables (see Section 4.3.5 "Uniform")".
3774 */
3775 if (return_type->contains_sampler()) {
3776 YYLTYPE loc = this->get_location();
3777 _mesa_glsl_error(&loc, state,
3778 "function `%s' return type can't contain a sampler",
3779 name);
3780 }
3781
3782 /* Verify that this function's signature either doesn't match a previously
3783 * seen signature for a function with the same name, or, if a match is found,
3784 * that the previously seen signature does not have an associated definition.
3785 */
3786 f = state->symbols->get_function(name);
3787 if (f != NULL && (state->es_shader || f->has_user_signature())) {
3788 sig = f->exact_matching_signature(state, &hir_parameters);
3789 if (sig != NULL) {
3790 const char *badvar = sig->qualifiers_match(&hir_parameters);
3791 if (badvar != NULL) {
3792 YYLTYPE loc = this->get_location();
3793
3794 _mesa_glsl_error(&loc, state, "function `%s' parameter `%s' "
3795 "qualifiers don't match prototype", name, badvar);
3796 }
3797
3798 if (sig->return_type != return_type) {
3799 YYLTYPE loc = this->get_location();
3800
3801 _mesa_glsl_error(&loc, state, "function `%s' return type doesn't "
3802 "match prototype", name);
3803 }
3804
3805 if (sig->is_defined) {
3806 if (is_definition) {
3807 YYLTYPE loc = this->get_location();
3808 _mesa_glsl_error(& loc, state, "function `%s' redefined", name);
3809 } else {
3810 /* We just encountered a prototype that exactly matches a
3811 * function that's already been defined. This is redundant,
3812 * and we should ignore it.
3813 */
3814 return NULL;
3815 }
3816 }
3817 }
3818 } else {
3819 f = new(ctx) ir_function(name);
3820 if (!state->symbols->add_function(f)) {
3821 /* This function name shadows a non-function use of the same name. */
3822 YYLTYPE loc = this->get_location();
3823
3824 _mesa_glsl_error(&loc, state, "function name `%s' conflicts with "
3825 "non-function", name);
3826 return NULL;
3827 }
3828
3829 emit_function(state, f);
3830 }
3831
3832 /* Verify the return type of main() */
3833 if (strcmp(name, "main") == 0) {
3834 if (! return_type->is_void()) {
3835 YYLTYPE loc = this->get_location();
3836
3837 _mesa_glsl_error(& loc, state, "main() must return void");
3838 }
3839
3840 if (!hir_parameters.is_empty()) {
3841 YYLTYPE loc = this->get_location();
3842
3843 _mesa_glsl_error(& loc, state, "main() must not take any parameters");
3844 }
3845 }
3846
3847 /* Finish storing the information about this new function in its signature.
3848 */
3849 if (sig == NULL) {
3850 sig = new(ctx) ir_function_signature(return_type);
3851 f->add_signature(sig);
3852 }
3853
3854 sig->replace_parameters(&hir_parameters);
3855 signature = sig;
3856
3857 /* Function declarations (prototypes) do not have r-values.
3858 */
3859 return NULL;
3860 }
3861
3862
3863 ir_rvalue *
3864 ast_function_definition::hir(exec_list *instructions,
3865 struct _mesa_glsl_parse_state *state)
3866 {
3867 prototype->is_definition = true;
3868 prototype->hir(instructions, state);
3869
3870 ir_function_signature *signature = prototype->signature;
3871 if (signature == NULL)
3872 return NULL;
3873
3874 assert(state->current_function == NULL);
3875 state->current_function = signature;
3876 state->found_return = false;
3877
3878 /* Duplicate parameters declared in the prototype as concrete variables.
3879 * Add these to the symbol table.
3880 */
3881 state->symbols->push_scope();
3882 foreach_list(n, &signature->parameters) {
3883 ir_variable *const var = ((ir_instruction *) n)->as_variable();
3884
3885 assert(var != NULL);
3886
3887 /* The only way a parameter would "exist" is if two parameters have
3888 * the same name.
3889 */
3890 if (state->symbols->name_declared_this_scope(var->name)) {
3891 YYLTYPE loc = this->get_location();
3892
3893 _mesa_glsl_error(& loc, state, "parameter `%s' redeclared", var->name);
3894 } else {
3895 state->symbols->add_variable(var);
3896 }
3897 }
3898
3899 /* Convert the body of the function to HIR. */
3900 this->body->hir(&signature->body, state);
3901 signature->is_defined = true;
3902
3903 state->symbols->pop_scope();
3904
3905 assert(state->current_function == signature);
3906 state->current_function = NULL;
3907
3908 if (!signature->return_type->is_void() && !state->found_return) {
3909 YYLTYPE loc = this->get_location();
3910 _mesa_glsl_error(& loc, state, "function `%s' has non-void return type "
3911 "%s, but no return statement",
3912 signature->function_name(),
3913 signature->return_type->name);
3914 }
3915
3916 /* Function definitions do not have r-values.
3917 */
3918 return NULL;
3919 }
3920
3921
3922 ir_rvalue *
3923 ast_jump_statement::hir(exec_list *instructions,
3924 struct _mesa_glsl_parse_state *state)
3925 {
3926 void *ctx = state;
3927
3928 switch (mode) {
3929 case ast_return: {
3930 ir_return *inst;
3931 assert(state->current_function);
3932
3933 if (opt_return_value) {
3934 ir_rvalue *ret = opt_return_value->hir(instructions, state);
3935
3936 /* The value of the return type can be NULL if the shader says
3937 * 'return foo();' and foo() is a function that returns void.
3938 *
3939 * NOTE: The GLSL spec doesn't say that this is an error. The type
3940 * of the return value is void. If the return type of the function is
3941 * also void, then this should compile without error. Seriously.
3942 */
3943 const glsl_type *const ret_type =
3944 (ret == NULL) ? glsl_type::void_type : ret->type;
3945
3946 /* Implicit conversions are not allowed for return values prior to
3947 * ARB_shading_language_420pack.
3948 */
3949 if (state->current_function->return_type != ret_type) {
3950 YYLTYPE loc = this->get_location();
3951
3952 if (state->ARB_shading_language_420pack_enable) {
3953 if (!apply_implicit_conversion(state->current_function->return_type,
3954 ret, state)) {
3955 _mesa_glsl_error(& loc, state,
3956 "could not implicitly convert return value "
3957 "to %s, in function `%s'",
3958 state->current_function->return_type->name,
3959 state->current_function->function_name());
3960 }
3961 } else {
3962 _mesa_glsl_error(& loc, state,
3963 "`return' with wrong type %s, in function `%s' "
3964 "returning %s",
3965 ret_type->name,
3966 state->current_function->function_name(),
3967 state->current_function->return_type->name);
3968 }
3969 } else if (state->current_function->return_type->base_type ==
3970 GLSL_TYPE_VOID) {
3971 YYLTYPE loc = this->get_location();
3972
3973 /* The ARB_shading_language_420pack, GLSL ES 3.0, and GLSL 4.20
3974 * specs add a clarification:
3975 *
3976 * "A void function can only use return without a return argument, even if
3977 * the return argument has void type. Return statements only accept values:
3978 *
3979 * void func1() { }
3980 * void func2() { return func1(); } // illegal return statement"
3981 */
3982 _mesa_glsl_error(& loc, state,
3983 "void functions can only use `return' without a "
3984 "return argument");
3985 }
3986
3987 inst = new(ctx) ir_return(ret);
3988 } else {
3989 if (state->current_function->return_type->base_type !=
3990 GLSL_TYPE_VOID) {
3991 YYLTYPE loc = this->get_location();
3992
3993 _mesa_glsl_error(& loc, state,
3994 "`return' with no value, in function %s returning "
3995 "non-void",
3996 state->current_function->function_name());
3997 }
3998 inst = new(ctx) ir_return;
3999 }
4000
4001 state->found_return = true;
4002 instructions->push_tail(inst);
4003 break;
4004 }
4005
4006 case ast_discard:
4007 if (state->stage != MESA_SHADER_FRAGMENT) {
4008 YYLTYPE loc = this->get_location();
4009
4010 _mesa_glsl_error(& loc, state,
4011 "`discard' may only appear in a fragment shader");
4012 }
4013 instructions->push_tail(new(ctx) ir_discard);
4014 break;
4015
4016 case ast_break:
4017 case ast_continue:
4018 if (mode == ast_continue &&
4019 state->loop_nesting_ast == NULL) {
4020 YYLTYPE loc = this->get_location();
4021
4022 _mesa_glsl_error(& loc, state,
4023 "continue may only appear in a loop");
4024 } else if (mode == ast_break &&
4025 state->loop_nesting_ast == NULL &&
4026 state->switch_state.switch_nesting_ast == NULL) {
4027 YYLTYPE loc = this->get_location();
4028
4029 _mesa_glsl_error(& loc, state,
4030 "break may only appear in a loop or a switch");
4031 } else {
4032 /* For a loop, inline the for loop expression again,
4033 * since we don't know where near the end of
4034 * the loop body the normal copy of it
4035 * is going to be placed.
4036 */
4037 if (state->loop_nesting_ast != NULL &&
4038 mode == ast_continue &&
4039 state->loop_nesting_ast->rest_expression) {
4040 state->loop_nesting_ast->rest_expression->hir(instructions,
4041 state);
4042 }
4043
4044 if (state->switch_state.is_switch_innermost &&
4045 mode == ast_break) {
4046 /* Force break out of switch by setting is_break switch state.
4047 */
4048 ir_variable *const is_break_var = state->switch_state.is_break_var;
4049 ir_dereference_variable *const deref_is_break_var =
4050 new(ctx) ir_dereference_variable(is_break_var);
4051 ir_constant *const true_val = new(ctx) ir_constant(true);
4052 ir_assignment *const set_break_var =
4053 new(ctx) ir_assignment(deref_is_break_var, true_val);
4054
4055 instructions->push_tail(set_break_var);
4056 }
4057 else {
4058 ir_loop_jump *const jump =
4059 new(ctx) ir_loop_jump((mode == ast_break)
4060 ? ir_loop_jump::jump_break
4061 : ir_loop_jump::jump_continue);
4062 instructions->push_tail(jump);
4063 }
4064 }
4065
4066 break;
4067 }
4068
4069 /* Jump instructions do not have r-values.
4070 */
4071 return NULL;
4072 }
4073
4074
4075 ir_rvalue *
4076 ast_selection_statement::hir(exec_list *instructions,
4077 struct _mesa_glsl_parse_state *state)
4078 {
4079 void *ctx = state;
4080
4081 ir_rvalue *const condition = this->condition->hir(instructions, state);
4082
4083 /* From page 66 (page 72 of the PDF) of the GLSL 1.50 spec:
4084 *
4085 * "Any expression whose type evaluates to a Boolean can be used as the
4086 * conditional expression bool-expression. Vector types are not accepted
4087 * as the expression to if."
4088 *
4089 * The checks are separated so that higher quality diagnostics can be
4090 * generated for cases where both rules are violated.
4091 */
4092 if (!condition->type->is_boolean() || !condition->type->is_scalar()) {
4093 YYLTYPE loc = this->condition->get_location();
4094
4095 _mesa_glsl_error(& loc, state, "if-statement condition must be scalar "
4096 "boolean");
4097 }
4098
4099 ir_if *const stmt = new(ctx) ir_if(condition);
4100
4101 if (then_statement != NULL) {
4102 state->symbols->push_scope();
4103 then_statement->hir(& stmt->then_instructions, state);
4104 state->symbols->pop_scope();
4105 }
4106
4107 if (else_statement != NULL) {
4108 state->symbols->push_scope();
4109 else_statement->hir(& stmt->else_instructions, state);
4110 state->symbols->pop_scope();
4111 }
4112
4113 instructions->push_tail(stmt);
4114
4115 /* if-statements do not have r-values.
4116 */
4117 return NULL;
4118 }
4119
4120
4121 ir_rvalue *
4122 ast_switch_statement::hir(exec_list *instructions,
4123 struct _mesa_glsl_parse_state *state)
4124 {
4125 void *ctx = state;
4126
4127 ir_rvalue *const test_expression =
4128 this->test_expression->hir(instructions, state);
4129
4130 /* From page 66 (page 55 of the PDF) of the GLSL 1.50 spec:
4131 *
4132 * "The type of init-expression in a switch statement must be a
4133 * scalar integer."
4134 */
4135 if (!test_expression->type->is_scalar() ||
4136 !test_expression->type->is_integer()) {
4137 YYLTYPE loc = this->test_expression->get_location();
4138
4139 _mesa_glsl_error(& loc,
4140 state,
4141 "switch-statement expression must be scalar "
4142 "integer");
4143 }
4144
4145 /* Track the switch-statement nesting in a stack-like manner.
4146 */
4147 struct glsl_switch_state saved = state->switch_state;
4148
4149 state->switch_state.is_switch_innermost = true;
4150 state->switch_state.switch_nesting_ast = this;
4151 state->switch_state.labels_ht = hash_table_ctor(0, hash_table_pointer_hash,
4152 hash_table_pointer_compare);
4153 state->switch_state.previous_default = NULL;
4154
4155 /* Initalize is_fallthru state to false.
4156 */
4157 ir_rvalue *const is_fallthru_val = new (ctx) ir_constant(false);
4158 state->switch_state.is_fallthru_var =
4159 new(ctx) ir_variable(glsl_type::bool_type,
4160 "switch_is_fallthru_tmp",
4161 ir_var_temporary);
4162 instructions->push_tail(state->switch_state.is_fallthru_var);
4163
4164 ir_dereference_variable *deref_is_fallthru_var =
4165 new(ctx) ir_dereference_variable(state->switch_state.is_fallthru_var);
4166 instructions->push_tail(new(ctx) ir_assignment(deref_is_fallthru_var,
4167 is_fallthru_val));
4168
4169 /* Initalize is_break state to false.
4170 */
4171 ir_rvalue *const is_break_val = new (ctx) ir_constant(false);
4172 state->switch_state.is_break_var = new(ctx) ir_variable(glsl_type::bool_type,
4173 "switch_is_break_tmp",
4174 ir_var_temporary);
4175 instructions->push_tail(state->switch_state.is_break_var);
4176
4177 ir_dereference_variable *deref_is_break_var =
4178 new(ctx) ir_dereference_variable(state->switch_state.is_break_var);
4179 instructions->push_tail(new(ctx) ir_assignment(deref_is_break_var,
4180 is_break_val));
4181
4182 /* Cache test expression.
4183 */
4184 test_to_hir(instructions, state);
4185
4186 /* Emit code for body of switch stmt.
4187 */
4188 body->hir(instructions, state);
4189
4190 hash_table_dtor(state->switch_state.labels_ht);
4191
4192 state->switch_state = saved;
4193
4194 /* Switch statements do not have r-values. */
4195 return NULL;
4196 }
4197
4198
4199 void
4200 ast_switch_statement::test_to_hir(exec_list *instructions,
4201 struct _mesa_glsl_parse_state *state)
4202 {
4203 void *ctx = state;
4204
4205 /* Cache value of test expression. */
4206 ir_rvalue *const test_val =
4207 test_expression->hir(instructions,
4208 state);
4209
4210 state->switch_state.test_var = new(ctx) ir_variable(test_val->type,
4211 "switch_test_tmp",
4212 ir_var_temporary);
4213 ir_dereference_variable *deref_test_var =
4214 new(ctx) ir_dereference_variable(state->switch_state.test_var);
4215
4216 instructions->push_tail(state->switch_state.test_var);
4217 instructions->push_tail(new(ctx) ir_assignment(deref_test_var, test_val));
4218 }
4219
4220
4221 ir_rvalue *
4222 ast_switch_body::hir(exec_list *instructions,
4223 struct _mesa_glsl_parse_state *state)
4224 {
4225 if (stmts != NULL)
4226 stmts->hir(instructions, state);
4227
4228 /* Switch bodies do not have r-values. */
4229 return NULL;
4230 }
4231
4232 ir_rvalue *
4233 ast_case_statement_list::hir(exec_list *instructions,
4234 struct _mesa_glsl_parse_state *state)
4235 {
4236 foreach_list_typed (ast_case_statement, case_stmt, link, & this->cases)
4237 case_stmt->hir(instructions, state);
4238
4239 /* Case statements do not have r-values. */
4240 return NULL;
4241 }
4242
4243 ir_rvalue *
4244 ast_case_statement::hir(exec_list *instructions,
4245 struct _mesa_glsl_parse_state *state)
4246 {
4247 labels->hir(instructions, state);
4248
4249 /* Conditionally set fallthru state based on break state. */
4250 ir_constant *const false_val = new(state) ir_constant(false);
4251 ir_dereference_variable *const deref_is_fallthru_var =
4252 new(state) ir_dereference_variable(state->switch_state.is_fallthru_var);
4253 ir_dereference_variable *const deref_is_break_var =
4254 new(state) ir_dereference_variable(state->switch_state.is_break_var);
4255 ir_assignment *const reset_fallthru_on_break =
4256 new(state) ir_assignment(deref_is_fallthru_var,
4257 false_val,
4258 deref_is_break_var);
4259 instructions->push_tail(reset_fallthru_on_break);
4260
4261 /* Guard case statements depending on fallthru state. */
4262 ir_dereference_variable *const deref_fallthru_guard =
4263 new(state) ir_dereference_variable(state->switch_state.is_fallthru_var);
4264 ir_if *const test_fallthru = new(state) ir_if(deref_fallthru_guard);
4265
4266 foreach_list_typed (ast_node, stmt, link, & this->stmts)
4267 stmt->hir(& test_fallthru->then_instructions, state);
4268
4269 instructions->push_tail(test_fallthru);
4270
4271 /* Case statements do not have r-values. */
4272 return NULL;
4273 }
4274
4275
4276 ir_rvalue *
4277 ast_case_label_list::hir(exec_list *instructions,
4278 struct _mesa_glsl_parse_state *state)
4279 {
4280 foreach_list_typed (ast_case_label, label, link, & this->labels)
4281 label->hir(instructions, state);
4282
4283 /* Case labels do not have r-values. */
4284 return NULL;
4285 }
4286
4287 ir_rvalue *
4288 ast_case_label::hir(exec_list *instructions,
4289 struct _mesa_glsl_parse_state *state)
4290 {
4291 void *ctx = state;
4292
4293 ir_dereference_variable *deref_fallthru_var =
4294 new(ctx) ir_dereference_variable(state->switch_state.is_fallthru_var);
4295
4296 ir_rvalue *const true_val = new(ctx) ir_constant(true);
4297
4298 /* If not default case, ... */
4299 if (this->test_value != NULL) {
4300 /* Conditionally set fallthru state based on
4301 * comparison of cached test expression value to case label.
4302 */
4303 ir_rvalue *const label_rval = this->test_value->hir(instructions, state);
4304 ir_constant *label_const = label_rval->constant_expression_value();
4305
4306 if (!label_const) {
4307 YYLTYPE loc = this->test_value->get_location();
4308
4309 _mesa_glsl_error(& loc, state,
4310 "switch statement case label must be a "
4311 "constant expression");
4312
4313 /* Stuff a dummy value in to allow processing to continue. */
4314 label_const = new(ctx) ir_constant(0);
4315 } else {
4316 ast_expression *previous_label = (ast_expression *)
4317 hash_table_find(state->switch_state.labels_ht,
4318 (void *)(uintptr_t)label_const->value.u[0]);
4319
4320 if (previous_label) {
4321 YYLTYPE loc = this->test_value->get_location();
4322 _mesa_glsl_error(& loc, state,
4323 "duplicate case value");
4324
4325 loc = previous_label->get_location();
4326 _mesa_glsl_error(& loc, state,
4327 "this is the previous case label");
4328 } else {
4329 hash_table_insert(state->switch_state.labels_ht,
4330 this->test_value,
4331 (void *)(uintptr_t)label_const->value.u[0]);
4332 }
4333 }
4334
4335 ir_dereference_variable *deref_test_var =
4336 new(ctx) ir_dereference_variable(state->switch_state.test_var);
4337
4338 ir_rvalue *const test_cond = new(ctx) ir_expression(ir_binop_all_equal,
4339 label_const,
4340 deref_test_var);
4341
4342 ir_assignment *set_fallthru_on_test =
4343 new(ctx) ir_assignment(deref_fallthru_var,
4344 true_val,
4345 test_cond);
4346
4347 instructions->push_tail(set_fallthru_on_test);
4348 } else { /* default case */
4349 if (state->switch_state.previous_default) {
4350 YYLTYPE loc = this->get_location();
4351 _mesa_glsl_error(& loc, state,
4352 "multiple default labels in one switch");
4353
4354 loc = state->switch_state.previous_default->get_location();
4355 _mesa_glsl_error(& loc, state,
4356 "this is the first default label");
4357 }
4358 state->switch_state.previous_default = this;
4359
4360 /* Set falltrhu state. */
4361 ir_assignment *set_fallthru =
4362 new(ctx) ir_assignment(deref_fallthru_var, true_val);
4363
4364 instructions->push_tail(set_fallthru);
4365 }
4366
4367 /* Case statements do not have r-values. */
4368 return NULL;
4369 }
4370
4371 void
4372 ast_iteration_statement::condition_to_hir(ir_loop *stmt,
4373 struct _mesa_glsl_parse_state *state)
4374 {
4375 void *ctx = state;
4376
4377 if (condition != NULL) {
4378 ir_rvalue *const cond =
4379 condition->hir(& stmt->body_instructions, state);
4380
4381 if ((cond == NULL)
4382 || !cond->type->is_boolean() || !cond->type->is_scalar()) {
4383 YYLTYPE loc = condition->get_location();
4384
4385 _mesa_glsl_error(& loc, state,
4386 "loop condition must be scalar boolean");
4387 } else {
4388 /* As the first code in the loop body, generate a block that looks
4389 * like 'if (!condition) break;' as the loop termination condition.
4390 */
4391 ir_rvalue *const not_cond =
4392 new(ctx) ir_expression(ir_unop_logic_not, cond);
4393
4394 ir_if *const if_stmt = new(ctx) ir_if(not_cond);
4395
4396 ir_jump *const break_stmt =
4397 new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
4398
4399 if_stmt->then_instructions.push_tail(break_stmt);
4400 stmt->body_instructions.push_tail(if_stmt);
4401 }
4402 }
4403 }
4404
4405
4406 ir_rvalue *
4407 ast_iteration_statement::hir(exec_list *instructions,
4408 struct _mesa_glsl_parse_state *state)
4409 {
4410 void *ctx = state;
4411
4412 /* For-loops and while-loops start a new scope, but do-while loops do not.
4413 */
4414 if (mode != ast_do_while)
4415 state->symbols->push_scope();
4416
4417 if (init_statement != NULL)
4418 init_statement->hir(instructions, state);
4419
4420 ir_loop *const stmt = new(ctx) ir_loop();
4421 instructions->push_tail(stmt);
4422
4423 /* Track the current loop nesting. */
4424 ast_iteration_statement *nesting_ast = state->loop_nesting_ast;
4425
4426 state->loop_nesting_ast = this;
4427
4428 /* Likewise, indicate that following code is closest to a loop,
4429 * NOT closest to a switch.
4430 */
4431 bool saved_is_switch_innermost = state->switch_state.is_switch_innermost;
4432 state->switch_state.is_switch_innermost = false;
4433
4434 if (mode != ast_do_while)
4435 condition_to_hir(stmt, state);
4436
4437 if (body != NULL)
4438 body->hir(& stmt->body_instructions, state);
4439
4440 if (rest_expression != NULL)
4441 rest_expression->hir(& stmt->body_instructions, state);
4442
4443 if (mode == ast_do_while)
4444 condition_to_hir(stmt, state);
4445
4446 if (mode != ast_do_while)
4447 state->symbols->pop_scope();
4448
4449 /* Restore previous nesting before returning. */
4450 state->loop_nesting_ast = nesting_ast;
4451 state->switch_state.is_switch_innermost = saved_is_switch_innermost;
4452
4453 /* Loops do not have r-values.
4454 */
4455 return NULL;
4456 }
4457
4458
4459 /**
4460 * Determine if the given type is valid for establishing a default precision
4461 * qualifier.
4462 *
4463 * From GLSL ES 3.00 section 4.5.4 ("Default Precision Qualifiers"):
4464 *
4465 * "The precision statement
4466 *
4467 * precision precision-qualifier type;
4468 *
4469 * can be used to establish a default precision qualifier. The type field
4470 * can be either int or float or any of the sampler types, and the
4471 * precision-qualifier can be lowp, mediump, or highp."
4472 *
4473 * GLSL ES 1.00 has similar language. GLSL 1.30 doesn't allow precision
4474 * qualifiers on sampler types, but this seems like an oversight (since the
4475 * intention of including these in GLSL 1.30 is to allow compatibility with ES
4476 * shaders). So we allow int, float, and all sampler types regardless of GLSL
4477 * version.
4478 */
4479 static bool
4480 is_valid_default_precision_type(const struct glsl_type *const type)
4481 {
4482 if (type == NULL)
4483 return false;
4484
4485 switch (type->base_type) {
4486 case GLSL_TYPE_INT:
4487 case GLSL_TYPE_FLOAT:
4488 /* "int" and "float" are valid, but vectors and matrices are not. */
4489 return type->vector_elements == 1 && type->matrix_columns == 1;
4490 case GLSL_TYPE_SAMPLER:
4491 return true;
4492 default:
4493 return false;
4494 }
4495 }
4496
4497
4498 ir_rvalue *
4499 ast_type_specifier::hir(exec_list *instructions,
4500 struct _mesa_glsl_parse_state *state)
4501 {
4502 if (this->default_precision == ast_precision_none && this->structure == NULL)
4503 return NULL;
4504
4505 YYLTYPE loc = this->get_location();
4506
4507 /* If this is a precision statement, check that the type to which it is
4508 * applied is either float or int.
4509 *
4510 * From section 4.5.3 of the GLSL 1.30 spec:
4511 * "The precision statement
4512 * precision precision-qualifier type;
4513 * can be used to establish a default precision qualifier. The type
4514 * field can be either int or float [...]. Any other types or
4515 * qualifiers will result in an error.
4516 */
4517 if (this->default_precision != ast_precision_none) {
4518 if (!state->check_precision_qualifiers_allowed(&loc))
4519 return NULL;
4520
4521 if (this->structure != NULL) {
4522 _mesa_glsl_error(&loc, state,
4523 "precision qualifiers do not apply to structures");
4524 return NULL;
4525 }
4526
4527 if (this->array_specifier != NULL) {
4528 _mesa_glsl_error(&loc, state,
4529 "default precision statements do not apply to "
4530 "arrays");
4531 return NULL;
4532 }
4533
4534 const struct glsl_type *const type =
4535 state->symbols->get_type(this->type_name);
4536 if (!is_valid_default_precision_type(type)) {
4537 _mesa_glsl_error(&loc, state,
4538 "default precision statements apply only to "
4539 "float, int, and sampler types");
4540 return NULL;
4541 }
4542
4543 if (type->base_type == GLSL_TYPE_FLOAT
4544 && state->es_shader
4545 && state->stage == MESA_SHADER_FRAGMENT) {
4546 /* Section 4.5.3 (Default Precision Qualifiers) of the GLSL ES 1.00
4547 * spec says:
4548 *
4549 * "The fragment language has no default precision qualifier for
4550 * floating point types."
4551 *
4552 * As a result, we have to track whether or not default precision has
4553 * been specified for float in GLSL ES fragment shaders.
4554 *
4555 * Earlier in that same section, the spec says:
4556 *
4557 * "Non-precision qualified declarations will use the precision
4558 * qualifier specified in the most recent precision statement
4559 * that is still in scope. The precision statement has the same
4560 * scoping rules as variable declarations. If it is declared
4561 * inside a compound statement, its effect stops at the end of
4562 * the innermost statement it was declared in. Precision
4563 * statements in nested scopes override precision statements in
4564 * outer scopes. Multiple precision statements for the same basic
4565 * type can appear inside the same scope, with later statements
4566 * overriding earlier statements within that scope."
4567 *
4568 * Default precision specifications follow the same scope rules as
4569 * variables. So, we can track the state of the default float
4570 * precision in the symbol table, and the rules will just work. This
4571 * is a slight abuse of the symbol table, but it has the semantics
4572 * that we want.
4573 */
4574 ir_variable *const junk =
4575 new(state) ir_variable(type, "#default precision",
4576 ir_var_temporary);
4577
4578 state->symbols->add_variable(junk);
4579 }
4580
4581 /* FINISHME: Translate precision statements into IR. */
4582 return NULL;
4583 }
4584
4585 /* _mesa_ast_set_aggregate_type() sets the <structure> field so that
4586 * process_record_constructor() can do type-checking on C-style initializer
4587 * expressions of structs, but ast_struct_specifier should only be translated
4588 * to HIR if it is declaring the type of a structure.
4589 *
4590 * The ->is_declaration field is false for initializers of variables
4591 * declared separately from the struct's type definition.
4592 *
4593 * struct S { ... }; (is_declaration = true)
4594 * struct T { ... } t = { ... }; (is_declaration = true)
4595 * S s = { ... }; (is_declaration = false)
4596 */
4597 if (this->structure != NULL && this->structure->is_declaration)
4598 return this->structure->hir(instructions, state);
4599
4600 return NULL;
4601 }
4602
4603
4604 /**
4605 * Process a structure or interface block tree into an array of structure fields
4606 *
4607 * After parsing, where there are some syntax differnces, structures and
4608 * interface blocks are almost identical. They are similar enough that the
4609 * AST for each can be processed the same way into a set of
4610 * \c glsl_struct_field to describe the members.
4611 *
4612 * If we're processing an interface block, var_mode should be the type of the
4613 * interface block (ir_var_shader_in, ir_var_shader_out, or ir_var_uniform).
4614 * If we're processing a structure, var_mode should be ir_var_auto.
4615 *
4616 * \return
4617 * The number of fields processed. A pointer to the array structure fields is
4618 * stored in \c *fields_ret.
4619 */
4620 unsigned
4621 ast_process_structure_or_interface_block(exec_list *instructions,
4622 struct _mesa_glsl_parse_state *state,
4623 exec_list *declarations,
4624 YYLTYPE &loc,
4625 glsl_struct_field **fields_ret,
4626 bool is_interface,
4627 bool block_row_major,
4628 bool allow_reserved_names,
4629 ir_variable_mode var_mode)
4630 {
4631 unsigned decl_count = 0;
4632
4633 /* Make an initial pass over the list of fields to determine how
4634 * many there are. Each element in this list is an ast_declarator_list.
4635 * This means that we actually need to count the number of elements in the
4636 * 'declarations' list in each of the elements.
4637 */
4638 foreach_list_typed (ast_declarator_list, decl_list, link, declarations) {
4639 foreach_list_const (decl_ptr, & decl_list->declarations) {
4640 decl_count++;
4641 }
4642 }
4643
4644 /* Allocate storage for the fields and process the field
4645 * declarations. As the declarations are processed, try to also convert
4646 * the types to HIR. This ensures that structure definitions embedded in
4647 * other structure definitions or in interface blocks are processed.
4648 */
4649 glsl_struct_field *const fields = ralloc_array(state, glsl_struct_field,
4650 decl_count);
4651
4652 unsigned i = 0;
4653 foreach_list_typed (ast_declarator_list, decl_list, link, declarations) {
4654 const char *type_name;
4655
4656 decl_list->type->specifier->hir(instructions, state);
4657
4658 /* Section 10.9 of the GLSL ES 1.00 specification states that
4659 * embedded structure definitions have been removed from the language.
4660 */
4661 if (state->es_shader && decl_list->type->specifier->structure != NULL) {
4662 _mesa_glsl_error(&loc, state, "embedded structure definitions are "
4663 "not allowed in GLSL ES 1.00");
4664 }
4665
4666 const glsl_type *decl_type =
4667 decl_list->type->glsl_type(& type_name, state);
4668
4669 foreach_list_typed (ast_declaration, decl, link,
4670 &decl_list->declarations) {
4671 if (!allow_reserved_names)
4672 validate_identifier(decl->identifier, loc, state);
4673
4674 /* From the GL_ARB_uniform_buffer_object spec:
4675 *
4676 * "Sampler types are not allowed inside of uniform
4677 * blocks. All other types, arrays, and structures
4678 * allowed for uniforms are allowed within a uniform
4679 * block."
4680 *
4681 * It should be impossible for decl_type to be NULL here. Cases that
4682 * might naturally lead to decl_type being NULL, especially for the
4683 * is_interface case, will have resulted in compilation having
4684 * already halted due to a syntax error.
4685 */
4686 const struct glsl_type *field_type =
4687 decl_type != NULL ? decl_type : glsl_type::error_type;
4688
4689 if (is_interface && field_type->contains_sampler()) {
4690 YYLTYPE loc = decl_list->get_location();
4691 _mesa_glsl_error(&loc, state,
4692 "uniform in non-default uniform block contains sampler");
4693 }
4694
4695 if (field_type->contains_atomic()) {
4696 /* FINISHME: Add a spec quotation here once updated spec
4697 * FINISHME: language is available. See Khronos bug #10903
4698 * FINISHME: on whether atomic counters are allowed in
4699 * FINISHME: structures.
4700 */
4701 YYLTYPE loc = decl_list->get_location();
4702 _mesa_glsl_error(&loc, state, "atomic counter in structure or "
4703 "uniform block");
4704 }
4705
4706 const struct ast_type_qualifier *const qual =
4707 & decl_list->type->qualifier;
4708 if (qual->flags.q.std140 ||
4709 qual->flags.q.packed ||
4710 qual->flags.q.shared) {
4711 _mesa_glsl_error(&loc, state,
4712 "uniform block layout qualifiers std140, packed, and "
4713 "shared can only be applied to uniform blocks, not "
4714 "members");
4715 }
4716
4717 field_type = process_array_type(&loc, decl_type,
4718 decl->array_specifier, state);
4719 fields[i].type = field_type;
4720 fields[i].name = decl->identifier;
4721 fields[i].location = -1;
4722 fields[i].interpolation =
4723 interpret_interpolation_qualifier(qual, var_mode, state, &loc);
4724 fields[i].centroid = qual->flags.q.centroid ? 1 : 0;
4725 fields[i].sample = qual->flags.q.sample ? 1 : 0;
4726
4727 if (qual->flags.q.row_major || qual->flags.q.column_major) {
4728 if (!qual->flags.q.uniform) {
4729 _mesa_glsl_error(&loc, state,
4730 "row_major and column_major can only be "
4731 "applied to uniform interface blocks");
4732 } else
4733 validate_matrix_layout_for_type(state, &loc, field_type, NULL);
4734 }
4735
4736 if (qual->flags.q.uniform && qual->has_interpolation()) {
4737 _mesa_glsl_error(&loc, state,
4738 "interpolation qualifiers cannot be used "
4739 "with uniform interface blocks");
4740 }
4741
4742 if (field_type->is_matrix() ||
4743 (field_type->is_array() && field_type->fields.array->is_matrix())) {
4744 fields[i].row_major = block_row_major;
4745 if (qual->flags.q.row_major)
4746 fields[i].row_major = true;
4747 else if (qual->flags.q.column_major)
4748 fields[i].row_major = false;
4749 }
4750
4751 i++;
4752 }
4753 }
4754
4755 assert(i == decl_count);
4756
4757 *fields_ret = fields;
4758 return decl_count;
4759 }
4760
4761
4762 ir_rvalue *
4763 ast_struct_specifier::hir(exec_list *instructions,
4764 struct _mesa_glsl_parse_state *state)
4765 {
4766 YYLTYPE loc = this->get_location();
4767
4768 /* Section 4.1.8 (Structures) of the GLSL 1.10 spec says:
4769 *
4770 * "Anonymous structures are not supported; so embedded structures must
4771 * have a declarator. A name given to an embedded struct is scoped at
4772 * the same level as the struct it is embedded in."
4773 *
4774 * The same section of the GLSL 1.20 spec says:
4775 *
4776 * "Anonymous structures are not supported. Embedded structures are not
4777 * supported.
4778 *
4779 * struct S { float f; };
4780 * struct T {
4781 * S; // Error: anonymous structures disallowed
4782 * struct { ... }; // Error: embedded structures disallowed
4783 * S s; // Okay: nested structures with name are allowed
4784 * };"
4785 *
4786 * The GLSL ES 1.00 and 3.00 specs have similar langauge and examples. So,
4787 * we allow embedded structures in 1.10 only.
4788 */
4789 if (state->language_version != 110 && state->struct_specifier_depth != 0)
4790 _mesa_glsl_error(&loc, state,
4791 "embedded structure declartions are not allowed");
4792
4793 state->struct_specifier_depth++;
4794
4795 glsl_struct_field *fields;
4796 unsigned decl_count =
4797 ast_process_structure_or_interface_block(instructions,
4798 state,
4799 &this->declarations,
4800 loc,
4801 &fields,
4802 false,
4803 false,
4804 false /* allow_reserved_names */,
4805 ir_var_auto);
4806
4807 validate_identifier(this->name, loc, state);
4808
4809 const glsl_type *t =
4810 glsl_type::get_record_instance(fields, decl_count, this->name);
4811
4812 if (!state->symbols->add_type(name, t)) {
4813 _mesa_glsl_error(& loc, state, "struct `%s' previously defined", name);
4814 } else {
4815 const glsl_type **s = reralloc(state, state->user_structures,
4816 const glsl_type *,
4817 state->num_user_structures + 1);
4818 if (s != NULL) {
4819 s[state->num_user_structures] = t;
4820 state->user_structures = s;
4821 state->num_user_structures++;
4822 }
4823 }
4824
4825 state->struct_specifier_depth--;
4826
4827 /* Structure type definitions do not have r-values.
4828 */
4829 return NULL;
4830 }
4831
4832
4833 /**
4834 * Visitor class which detects whether a given interface block has been used.
4835 */
4836 class interface_block_usage_visitor : public ir_hierarchical_visitor
4837 {
4838 public:
4839 interface_block_usage_visitor(ir_variable_mode mode, const glsl_type *block)
4840 : mode(mode), block(block), found(false)
4841 {
4842 }
4843
4844 virtual ir_visitor_status visit(ir_dereference_variable *ir)
4845 {
4846 if (ir->var->data.mode == mode && ir->var->get_interface_type() == block) {
4847 found = true;
4848 return visit_stop;
4849 }
4850 return visit_continue;
4851 }
4852
4853 bool usage_found() const
4854 {
4855 return this->found;
4856 }
4857
4858 private:
4859 ir_variable_mode mode;
4860 const glsl_type *block;
4861 bool found;
4862 };
4863
4864
4865 ir_rvalue *
4866 ast_interface_block::hir(exec_list *instructions,
4867 struct _mesa_glsl_parse_state *state)
4868 {
4869 YYLTYPE loc = this->get_location();
4870
4871 /* The ast_interface_block has a list of ast_declarator_lists. We
4872 * need to turn those into ir_variables with an association
4873 * with this uniform block.
4874 */
4875 enum glsl_interface_packing packing;
4876 if (this->layout.flags.q.shared) {
4877 packing = GLSL_INTERFACE_PACKING_SHARED;
4878 } else if (this->layout.flags.q.packed) {
4879 packing = GLSL_INTERFACE_PACKING_PACKED;
4880 } else {
4881 /* The default layout is std140.
4882 */
4883 packing = GLSL_INTERFACE_PACKING_STD140;
4884 }
4885
4886 ir_variable_mode var_mode;
4887 const char *iface_type_name;
4888 if (this->layout.flags.q.in) {
4889 var_mode = ir_var_shader_in;
4890 iface_type_name = "in";
4891 } else if (this->layout.flags.q.out) {
4892 var_mode = ir_var_shader_out;
4893 iface_type_name = "out";
4894 } else if (this->layout.flags.q.uniform) {
4895 var_mode = ir_var_uniform;
4896 iface_type_name = "uniform";
4897 } else {
4898 var_mode = ir_var_auto;
4899 iface_type_name = "UNKNOWN";
4900 assert(!"interface block layout qualifier not found!");
4901 }
4902
4903 bool redeclaring_per_vertex = strcmp(this->block_name, "gl_PerVertex") == 0;
4904 bool block_row_major = this->layout.flags.q.row_major;
4905 exec_list declared_variables;
4906 glsl_struct_field *fields;
4907 unsigned int num_variables =
4908 ast_process_structure_or_interface_block(&declared_variables,
4909 state,
4910 &this->declarations,
4911 loc,
4912 &fields,
4913 true,
4914 block_row_major,
4915 redeclaring_per_vertex,
4916 var_mode);
4917
4918 if (!redeclaring_per_vertex)
4919 validate_identifier(this->block_name, loc, state);
4920
4921 const glsl_type *earlier_per_vertex = NULL;
4922 if (redeclaring_per_vertex) {
4923 /* Find the previous declaration of gl_PerVertex. If we're redeclaring
4924 * the named interface block gl_in, we can find it by looking at the
4925 * previous declaration of gl_in. Otherwise we can find it by looking
4926 * at the previous decalartion of any of the built-in outputs,
4927 * e.g. gl_Position.
4928 *
4929 * Also check that the instance name and array-ness of the redeclaration
4930 * are correct.
4931 */
4932 switch (var_mode) {
4933 case ir_var_shader_in:
4934 if (ir_variable *earlier_gl_in =
4935 state->symbols->get_variable("gl_in")) {
4936 earlier_per_vertex = earlier_gl_in->get_interface_type();
4937 } else {
4938 _mesa_glsl_error(&loc, state,
4939 "redeclaration of gl_PerVertex input not allowed "
4940 "in the %s shader",
4941 _mesa_shader_stage_to_string(state->stage));
4942 }
4943 if (this->instance_name == NULL ||
4944 strcmp(this->instance_name, "gl_in") != 0 || this->array_specifier == NULL) {
4945 _mesa_glsl_error(&loc, state,
4946 "gl_PerVertex input must be redeclared as "
4947 "gl_in[]");
4948 }
4949 break;
4950 case ir_var_shader_out:
4951 if (ir_variable *earlier_gl_Position =
4952 state->symbols->get_variable("gl_Position")) {
4953 earlier_per_vertex = earlier_gl_Position->get_interface_type();
4954 } else {
4955 _mesa_glsl_error(&loc, state,
4956 "redeclaration of gl_PerVertex output not "
4957 "allowed in the %s shader",
4958 _mesa_shader_stage_to_string(state->stage));
4959 }
4960 if (this->instance_name != NULL) {
4961 _mesa_glsl_error(&loc, state,
4962 "gl_PerVertex input may not be redeclared with "
4963 "an instance name");
4964 }
4965 break;
4966 default:
4967 _mesa_glsl_error(&loc, state,
4968 "gl_PerVertex must be declared as an input or an "
4969 "output");
4970 break;
4971 }
4972
4973 if (earlier_per_vertex == NULL) {
4974 /* An error has already been reported. Bail out to avoid null
4975 * dereferences later in this function.
4976 */
4977 return NULL;
4978 }
4979
4980 /* Copy locations from the old gl_PerVertex interface block. */
4981 for (unsigned i = 0; i < num_variables; i++) {
4982 int j = earlier_per_vertex->field_index(fields[i].name);
4983 if (j == -1) {
4984 _mesa_glsl_error(&loc, state,
4985 "redeclaration of gl_PerVertex must be a subset "
4986 "of the built-in members of gl_PerVertex");
4987 } else {
4988 fields[i].location =
4989 earlier_per_vertex->fields.structure[j].location;
4990 fields[i].interpolation =
4991 earlier_per_vertex->fields.structure[j].interpolation;
4992 fields[i].centroid =
4993 earlier_per_vertex->fields.structure[j].centroid;
4994 fields[i].sample =
4995 earlier_per_vertex->fields.structure[j].sample;
4996 }
4997 }
4998
4999 /* From section 7.1 ("Built-in Language Variables") of the GLSL 4.10
5000 * spec:
5001 *
5002 * If a built-in interface block is redeclared, it must appear in
5003 * the shader before any use of any member included in the built-in
5004 * declaration, or a compilation error will result.
5005 *
5006 * This appears to be a clarification to the behaviour established for
5007 * gl_PerVertex by GLSL 1.50, therefore we implement this behaviour
5008 * regardless of GLSL version.
5009 */
5010 interface_block_usage_visitor v(var_mode, earlier_per_vertex);
5011 v.run(instructions);
5012 if (v.usage_found()) {
5013 _mesa_glsl_error(&loc, state,
5014 "redeclaration of a built-in interface block must "
5015 "appear before any use of any member of the "
5016 "interface block");
5017 }
5018 }
5019
5020 const glsl_type *block_type =
5021 glsl_type::get_interface_instance(fields,
5022 num_variables,
5023 packing,
5024 this->block_name);
5025
5026 if (!state->symbols->add_interface(block_type->name, block_type, var_mode)) {
5027 YYLTYPE loc = this->get_location();
5028 _mesa_glsl_error(&loc, state, "interface block `%s' with type `%s' "
5029 "already taken in the current scope",
5030 this->block_name, iface_type_name);
5031 }
5032
5033 /* Since interface blocks cannot contain statements, it should be
5034 * impossible for the block to generate any instructions.
5035 */
5036 assert(declared_variables.is_empty());
5037
5038 /* From section 4.3.4 (Inputs) of the GLSL 1.50 spec:
5039 *
5040 * Geometry shader input variables get the per-vertex values written
5041 * out by vertex shader output variables of the same names. Since a
5042 * geometry shader operates on a set of vertices, each input varying
5043 * variable (or input block, see interface blocks below) needs to be
5044 * declared as an array.
5045 */
5046 if (state->stage == MESA_SHADER_GEOMETRY && this->array_specifier == NULL &&
5047 var_mode == ir_var_shader_in) {
5048 _mesa_glsl_error(&loc, state, "geometry shader inputs must be arrays");
5049 }
5050
5051 /* Page 39 (page 45 of the PDF) of section 4.3.7 in the GLSL ES 3.00 spec
5052 * says:
5053 *
5054 * "If an instance name (instance-name) is used, then it puts all the
5055 * members inside a scope within its own name space, accessed with the
5056 * field selector ( . ) operator (analogously to structures)."
5057 */
5058 if (this->instance_name) {
5059 if (redeclaring_per_vertex) {
5060 /* When a built-in in an unnamed interface block is redeclared,
5061 * get_variable_being_redeclared() calls
5062 * check_builtin_array_max_size() to make sure that built-in array
5063 * variables aren't redeclared to illegal sizes. But we're looking
5064 * at a redeclaration of a named built-in interface block. So we
5065 * have to manually call check_builtin_array_max_size() for all parts
5066 * of the interface that are arrays.
5067 */
5068 for (unsigned i = 0; i < num_variables; i++) {
5069 if (fields[i].type->is_array()) {
5070 const unsigned size = fields[i].type->array_size();
5071 check_builtin_array_max_size(fields[i].name, size, loc, state);
5072 }
5073 }
5074 } else {
5075 validate_identifier(this->instance_name, loc, state);
5076 }
5077
5078 ir_variable *var;
5079
5080 if (this->array_specifier != NULL) {
5081 /* Section 4.3.7 (Interface Blocks) of the GLSL 1.50 spec says:
5082 *
5083 * For uniform blocks declared an array, each individual array
5084 * element corresponds to a separate buffer object backing one
5085 * instance of the block. As the array size indicates the number
5086 * of buffer objects needed, uniform block array declarations
5087 * must specify an array size.
5088 *
5089 * And a few paragraphs later:
5090 *
5091 * Geometry shader input blocks must be declared as arrays and
5092 * follow the array declaration and linking rules for all
5093 * geometry shader inputs. All other input and output block
5094 * arrays must specify an array size.
5095 *
5096 * The upshot of this is that the only circumstance where an
5097 * interface array size *doesn't* need to be specified is on a
5098 * geometry shader input.
5099 */
5100 if (this->array_specifier->is_unsized_array &&
5101 (state->stage != MESA_SHADER_GEOMETRY || !this->layout.flags.q.in)) {
5102 _mesa_glsl_error(&loc, state,
5103 "only geometry shader inputs may be unsized "
5104 "instance block arrays");
5105
5106 }
5107
5108 const glsl_type *block_array_type =
5109 process_array_type(&loc, block_type, this->array_specifier, state);
5110
5111 var = new(state) ir_variable(block_array_type,
5112 this->instance_name,
5113 var_mode);
5114 } else {
5115 var = new(state) ir_variable(block_type,
5116 this->instance_name,
5117 var_mode);
5118 }
5119
5120 if (state->stage == MESA_SHADER_GEOMETRY && var_mode == ir_var_shader_in)
5121 handle_geometry_shader_input_decl(state, loc, var);
5122
5123 if (ir_variable *earlier =
5124 state->symbols->get_variable(this->instance_name)) {
5125 if (!redeclaring_per_vertex) {
5126 _mesa_glsl_error(&loc, state, "`%s' redeclared",
5127 this->instance_name);
5128 }
5129 earlier->data.how_declared = ir_var_declared_normally;
5130 earlier->type = var->type;
5131 earlier->reinit_interface_type(block_type);
5132 delete var;
5133 } else {
5134 state->symbols->add_variable(var);
5135 instructions->push_tail(var);
5136 }
5137 } else {
5138 /* In order to have an array size, the block must also be declared with
5139 * an instane name.
5140 */
5141 assert(this->array_specifier == NULL);
5142
5143 for (unsigned i = 0; i < num_variables; i++) {
5144 ir_variable *var =
5145 new(state) ir_variable(fields[i].type,
5146 ralloc_strdup(state, fields[i].name),
5147 var_mode);
5148 var->data.interpolation = fields[i].interpolation;
5149 var->data.centroid = fields[i].centroid;
5150 var->data.sample = fields[i].sample;
5151 var->init_interface_type(block_type);
5152
5153 if (redeclaring_per_vertex) {
5154 ir_variable *earlier =
5155 get_variable_being_redeclared(var, loc, state,
5156 true /* allow_all_redeclarations */);
5157 if (strncmp(var->name, "gl_", 3) != 0 || earlier == NULL) {
5158 _mesa_glsl_error(&loc, state,
5159 "redeclaration of gl_PerVertex can only "
5160 "include built-in variables");
5161 } else if (earlier->data.how_declared == ir_var_declared_normally) {
5162 _mesa_glsl_error(&loc, state,
5163 "`%s' has already been redeclared", var->name);
5164 } else {
5165 earlier->data.how_declared = ir_var_declared_in_block;
5166 earlier->reinit_interface_type(block_type);
5167 }
5168 continue;
5169 }
5170
5171 if (state->symbols->get_variable(var->name) != NULL)
5172 _mesa_glsl_error(&loc, state, "`%s' redeclared", var->name);
5173
5174 /* Propagate the "binding" keyword into this UBO's fields;
5175 * the UBO declaration itself doesn't get an ir_variable unless it
5176 * has an instance name. This is ugly.
5177 */
5178 var->data.explicit_binding = this->layout.flags.q.explicit_binding;
5179 var->data.binding = this->layout.binding;
5180
5181 state->symbols->add_variable(var);
5182 instructions->push_tail(var);
5183 }
5184
5185 if (redeclaring_per_vertex && block_type != earlier_per_vertex) {
5186 /* From section 7.1 ("Built-in Language Variables") of the GLSL 4.10 spec:
5187 *
5188 * It is also a compilation error ... to redeclare a built-in
5189 * block and then use a member from that built-in block that was
5190 * not included in the redeclaration.
5191 *
5192 * This appears to be a clarification to the behaviour established
5193 * for gl_PerVertex by GLSL 1.50, therefore we implement this
5194 * behaviour regardless of GLSL version.
5195 *
5196 * To prevent the shader from using a member that was not included in
5197 * the redeclaration, we disable any ir_variables that are still
5198 * associated with the old declaration of gl_PerVertex (since we've
5199 * already updated all of the variables contained in the new
5200 * gl_PerVertex to point to it).
5201 *
5202 * As a side effect this will prevent
5203 * validate_intrastage_interface_blocks() from getting confused and
5204 * thinking there are conflicting definitions of gl_PerVertex in the
5205 * shader.
5206 */
5207 foreach_list_safe(node, instructions) {
5208 ir_variable *const var = ((ir_instruction *) node)->as_variable();
5209 if (var != NULL &&
5210 var->get_interface_type() == earlier_per_vertex &&
5211 var->data.mode == var_mode) {
5212 if (var->data.how_declared == ir_var_declared_normally) {
5213 _mesa_glsl_error(&loc, state,
5214 "redeclaration of gl_PerVertex cannot "
5215 "follow a redeclaration of `%s'",
5216 var->name);
5217 }
5218 state->symbols->disable_variable(var->name);
5219 var->remove();
5220 }
5221 }
5222 }
5223 }
5224
5225 return NULL;
5226 }
5227
5228
5229 ir_rvalue *
5230 ast_gs_input_layout::hir(exec_list *instructions,
5231 struct _mesa_glsl_parse_state *state)
5232 {
5233 YYLTYPE loc = this->get_location();
5234
5235 /* If any geometry input layout declaration preceded this one, make sure it
5236 * was consistent with this one.
5237 */
5238 if (state->gs_input_prim_type_specified &&
5239 state->gs_input_prim_type != this->prim_type) {
5240 _mesa_glsl_error(&loc, state,
5241 "geometry shader input layout does not match"
5242 " previous declaration");
5243 return NULL;
5244 }
5245
5246 /* If any shader inputs occurred before this declaration and specified an
5247 * array size, make sure the size they specified is consistent with the
5248 * primitive type.
5249 */
5250 unsigned num_vertices = vertices_per_prim(this->prim_type);
5251 if (state->gs_input_size != 0 && state->gs_input_size != num_vertices) {
5252 _mesa_glsl_error(&loc, state,
5253 "this geometry shader input layout implies %u vertices"
5254 " per primitive, but a previous input is declared"
5255 " with size %u", num_vertices, state->gs_input_size);
5256 return NULL;
5257 }
5258
5259 state->gs_input_prim_type_specified = true;
5260 state->gs_input_prim_type = this->prim_type;
5261
5262 /* If any shader inputs occurred before this declaration and did not
5263 * specify an array size, their size is determined now.
5264 */
5265 foreach_list (node, instructions) {
5266 ir_variable *var = ((ir_instruction *) node)->as_variable();
5267 if (var == NULL || var->data.mode != ir_var_shader_in)
5268 continue;
5269
5270 /* Note: gl_PrimitiveIDIn has mode ir_var_shader_in, but it's not an
5271 * array; skip it.
5272 */
5273
5274 if (var->type->is_unsized_array()) {
5275 if (var->data.max_array_access >= num_vertices) {
5276 _mesa_glsl_error(&loc, state,
5277 "this geometry shader input layout implies %u"
5278 " vertices, but an access to element %u of input"
5279 " `%s' already exists", num_vertices,
5280 var->data.max_array_access, var->name);
5281 } else {
5282 var->type = glsl_type::get_array_instance(var->type->fields.array,
5283 num_vertices);
5284 }
5285 }
5286 }
5287
5288 return NULL;
5289 }
5290
5291
5292 static void
5293 detect_conflicting_assignments(struct _mesa_glsl_parse_state *state,
5294 exec_list *instructions)
5295 {
5296 bool gl_FragColor_assigned = false;
5297 bool gl_FragData_assigned = false;
5298 bool user_defined_fs_output_assigned = false;
5299 ir_variable *user_defined_fs_output = NULL;
5300
5301 /* It would be nice to have proper location information. */
5302 YYLTYPE loc;
5303 memset(&loc, 0, sizeof(loc));
5304
5305 foreach_list(node, instructions) {
5306 ir_variable *var = ((ir_instruction *)node)->as_variable();
5307
5308 if (!var || !var->data.assigned)
5309 continue;
5310
5311 if (strcmp(var->name, "gl_FragColor") == 0)
5312 gl_FragColor_assigned = true;
5313 else if (strcmp(var->name, "gl_FragData") == 0)
5314 gl_FragData_assigned = true;
5315 else if (strncmp(var->name, "gl_", 3) != 0) {
5316 if (state->stage == MESA_SHADER_FRAGMENT &&
5317 var->data.mode == ir_var_shader_out) {
5318 user_defined_fs_output_assigned = true;
5319 user_defined_fs_output = var;
5320 }
5321 }
5322 }
5323
5324 /* From the GLSL 1.30 spec:
5325 *
5326 * "If a shader statically assigns a value to gl_FragColor, it
5327 * may not assign a value to any element of gl_FragData. If a
5328 * shader statically writes a value to any element of
5329 * gl_FragData, it may not assign a value to
5330 * gl_FragColor. That is, a shader may assign values to either
5331 * gl_FragColor or gl_FragData, but not both. Multiple shaders
5332 * linked together must also consistently write just one of
5333 * these variables. Similarly, if user declared output
5334 * variables are in use (statically assigned to), then the
5335 * built-in variables gl_FragColor and gl_FragData may not be
5336 * assigned to. These incorrect usages all generate compile
5337 * time errors."
5338 */
5339 if (gl_FragColor_assigned && gl_FragData_assigned) {
5340 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
5341 "`gl_FragColor' and `gl_FragData'");
5342 } else if (gl_FragColor_assigned && user_defined_fs_output_assigned) {
5343 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
5344 "`gl_FragColor' and `%s'",
5345 user_defined_fs_output->name);
5346 } else if (gl_FragData_assigned && user_defined_fs_output_assigned) {
5347 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
5348 "`gl_FragData' and `%s'",
5349 user_defined_fs_output->name);
5350 }
5351 }
5352
5353
5354 static void
5355 remove_per_vertex_blocks(exec_list *instructions,
5356 _mesa_glsl_parse_state *state, ir_variable_mode mode)
5357 {
5358 /* Find the gl_PerVertex interface block of the appropriate (in/out) mode,
5359 * if it exists in this shader type.
5360 */
5361 const glsl_type *per_vertex = NULL;
5362 switch (mode) {
5363 case ir_var_shader_in:
5364 if (ir_variable *gl_in = state->symbols->get_variable("gl_in"))
5365 per_vertex = gl_in->get_interface_type();
5366 break;
5367 case ir_var_shader_out:
5368 if (ir_variable *gl_Position =
5369 state->symbols->get_variable("gl_Position")) {
5370 per_vertex = gl_Position->get_interface_type();
5371 }
5372 break;
5373 default:
5374 assert(!"Unexpected mode");
5375 break;
5376 }
5377
5378 /* If we didn't find a built-in gl_PerVertex interface block, then we don't
5379 * need to do anything.
5380 */
5381 if (per_vertex == NULL)
5382 return;
5383
5384 /* If the interface block is used by the shader, then we don't need to do
5385 * anything.
5386 */
5387 interface_block_usage_visitor v(mode, per_vertex);
5388 v.run(instructions);
5389 if (v.usage_found())
5390 return;
5391
5392 /* Remove any ir_variable declarations that refer to the interface block
5393 * we're removing.
5394 */
5395 foreach_list_safe(node, instructions) {
5396 ir_variable *const var = ((ir_instruction *) node)->as_variable();
5397 if (var != NULL && var->get_interface_type() == per_vertex &&
5398 var->data.mode == mode) {
5399 state->symbols->disable_variable(var->name);
5400 var->remove();
5401 }
5402 }
5403 }