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