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