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