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