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