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