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