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