Merge remote-tracking branch 'mesa-public/master' 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->fields.array == rhs->type->fields.array)) {
682 if (is_initializer) {
683 return rhs;
684 } else {
685 _mesa_glsl_error(&loc, state,
686 "implicitly sized arrays cannot be assigned");
687 return NULL;
688 }
689 }
690
691 /* Check for implicit conversion in GLSL 1.20 */
692 if (apply_implicit_conversion(lhs_type, rhs, state)) {
693 if (rhs->type == lhs_type)
694 return rhs;
695 }
696
697 _mesa_glsl_error(&loc, state,
698 "%s of type %s cannot be assigned to "
699 "variable of type %s",
700 is_initializer ? "initializer" : "value",
701 rhs->type->name, lhs_type->name);
702
703 return NULL;
704 }
705
706 static void
707 mark_whole_array_access(ir_rvalue *access)
708 {
709 ir_dereference_variable *deref = access->as_dereference_variable();
710
711 if (deref && deref->var) {
712 deref->var->data.max_array_access = deref->type->length - 1;
713 }
714 }
715
716 static bool
717 do_assignment(exec_list *instructions, struct _mesa_glsl_parse_state *state,
718 const char *non_lvalue_description,
719 ir_rvalue *lhs, ir_rvalue *rhs,
720 ir_rvalue **out_rvalue, bool needs_rvalue,
721 bool is_initializer,
722 YYLTYPE lhs_loc)
723 {
724 void *ctx = state;
725 bool error_emitted = (lhs->type->is_error() || rhs->type->is_error());
726 ir_rvalue *extract_channel = NULL;
727
728 /* If the assignment LHS comes back as an ir_binop_vector_extract
729 * expression, move it to the RHS as an ir_triop_vector_insert.
730 */
731 if (lhs->ir_type == ir_type_expression) {
732 ir_expression *const lhs_expr = lhs->as_expression();
733
734 if (unlikely(lhs_expr->operation == ir_binop_vector_extract)) {
735 ir_rvalue *new_rhs =
736 validate_assignment(state, lhs_loc, lhs->type,
737 rhs, is_initializer);
738
739 if (new_rhs == NULL) {
740 return lhs;
741 } else {
742 /* This converts:
743 * - LHS: (expression float vector_extract <vec> <channel>)
744 * - RHS: <scalar>
745 * into:
746 * - LHS: <vec>
747 * - RHS: (expression vec2 vector_insert <vec> <channel> <scalar>)
748 *
749 * The LHS type is now a vector instead of a scalar. Since GLSL
750 * allows assignments to be used as rvalues, we need to re-extract
751 * the channel from assignment_temp when returning the rvalue.
752 */
753 extract_channel = lhs_expr->operands[1];
754 rhs = new(ctx) ir_expression(ir_triop_vector_insert,
755 lhs_expr->operands[0]->type,
756 lhs_expr->operands[0],
757 new_rhs,
758 extract_channel);
759 lhs = lhs_expr->operands[0]->clone(ctx, NULL);
760 }
761 }
762 }
763
764 ir_variable *lhs_var = lhs->variable_referenced();
765 if (lhs_var)
766 lhs_var->data.assigned = true;
767
768 if (!error_emitted) {
769 if (non_lvalue_description != NULL) {
770 _mesa_glsl_error(&lhs_loc, state,
771 "assignment to %s",
772 non_lvalue_description);
773 error_emitted = true;
774 } else if (lhs_var != NULL && lhs_var->data.read_only) {
775 _mesa_glsl_error(&lhs_loc, state,
776 "assignment to read-only variable '%s'",
777 lhs_var->name);
778 error_emitted = true;
779 } else if (lhs->type->is_array() &&
780 !state->check_version(120, 300, &lhs_loc,
781 "whole array assignment forbidden")) {
782 /* From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
783 *
784 * "Other binary or unary expressions, non-dereferenced
785 * arrays, function names, swizzles with repeated fields,
786 * and constants cannot be l-values."
787 *
788 * The restriction on arrays is lifted in GLSL 1.20 and GLSL ES 3.00.
789 */
790 error_emitted = true;
791 } else if (!lhs->is_lvalue()) {
792 _mesa_glsl_error(& lhs_loc, state, "non-lvalue in assignment");
793 error_emitted = true;
794 }
795 }
796
797 ir_rvalue *new_rhs =
798 validate_assignment(state, lhs_loc, lhs->type, rhs, is_initializer);
799 if (new_rhs != NULL) {
800 rhs = new_rhs;
801
802 /* If the LHS array was not declared with a size, it takes it size from
803 * the RHS. If the LHS is an l-value and a whole array, it must be a
804 * dereference of a variable. Any other case would require that the LHS
805 * is either not an l-value or not a whole array.
806 */
807 if (lhs->type->is_unsized_array()) {
808 ir_dereference *const d = lhs->as_dereference();
809
810 assert(d != NULL);
811
812 ir_variable *const var = d->variable_referenced();
813
814 assert(var != NULL);
815
816 if (var->data.max_array_access >= unsigned(rhs->type->array_size())) {
817 /* FINISHME: This should actually log the location of the RHS. */
818 _mesa_glsl_error(& lhs_loc, state, "array size must be > %u due to "
819 "previous access",
820 var->data.max_array_access);
821 }
822
823 var->type = glsl_type::get_array_instance(lhs->type->fields.array,
824 rhs->type->array_size());
825 d->type = var->type;
826 }
827 if (lhs->type->is_array()) {
828 mark_whole_array_access(rhs);
829 mark_whole_array_access(lhs);
830 }
831 }
832
833 /* Most callers of do_assignment (assign, add_assign, pre_inc/dec,
834 * but not post_inc) need the converted assigned value as an rvalue
835 * to handle things like:
836 *
837 * i = j += 1;
838 */
839 if (needs_rvalue) {
840 ir_variable *var = new(ctx) ir_variable(rhs->type, "assignment_tmp",
841 ir_var_temporary);
842 instructions->push_tail(var);
843 instructions->push_tail(assign(var, rhs));
844
845 if (!error_emitted) {
846 ir_dereference_variable *deref_var = new(ctx) ir_dereference_variable(var);
847 instructions->push_tail(new(ctx) ir_assignment(lhs, deref_var));
848 }
849 ir_rvalue *rvalue = new(ctx) ir_dereference_variable(var);
850
851 if (extract_channel) {
852 rvalue = new(ctx) ir_expression(ir_binop_vector_extract,
853 rvalue,
854 extract_channel->clone(ctx, NULL));
855 }
856
857 *out_rvalue = rvalue;
858 } else {
859 if (!error_emitted)
860 instructions->push_tail(new(ctx) ir_assignment(lhs, rhs));
861 *out_rvalue = NULL;
862 }
863
864 return error_emitted;
865 }
866
867 static ir_rvalue *
868 get_lvalue_copy(exec_list *instructions, ir_rvalue *lvalue)
869 {
870 void *ctx = ralloc_parent(lvalue);
871 ir_variable *var;
872
873 var = new(ctx) ir_variable(lvalue->type, "_post_incdec_tmp",
874 ir_var_temporary);
875 instructions->push_tail(var);
876
877 instructions->push_tail(new(ctx) ir_assignment(new(ctx) ir_dereference_variable(var),
878 lvalue));
879
880 return new(ctx) ir_dereference_variable(var);
881 }
882
883
884 ir_rvalue *
885 ast_node::hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)
886 {
887 (void) instructions;
888 (void) state;
889
890 return NULL;
891 }
892
893 void
894 ast_function_expression::hir_no_rvalue(exec_list *instructions,
895 struct _mesa_glsl_parse_state *state)
896 {
897 (void)hir(instructions, state);
898 }
899
900 void
901 ast_aggregate_initializer::hir_no_rvalue(exec_list *instructions,
902 struct _mesa_glsl_parse_state *state)
903 {
904 (void)hir(instructions, state);
905 }
906
907 static ir_rvalue *
908 do_comparison(void *mem_ctx, int operation, ir_rvalue *op0, ir_rvalue *op1)
909 {
910 int join_op;
911 ir_rvalue *cmp = NULL;
912
913 if (operation == ir_binop_all_equal)
914 join_op = ir_binop_logic_and;
915 else
916 join_op = ir_binop_logic_or;
917
918 switch (op0->type->base_type) {
919 case GLSL_TYPE_FLOAT:
920 case GLSL_TYPE_UINT:
921 case GLSL_TYPE_INT:
922 case GLSL_TYPE_BOOL:
923 case GLSL_TYPE_DOUBLE:
924 return new(mem_ctx) ir_expression(operation, op0, op1);
925
926 case GLSL_TYPE_ARRAY: {
927 for (unsigned int i = 0; i < op0->type->length; i++) {
928 ir_rvalue *e0, *e1, *result;
929
930 e0 = new(mem_ctx) ir_dereference_array(op0->clone(mem_ctx, NULL),
931 new(mem_ctx) ir_constant(i));
932 e1 = new(mem_ctx) ir_dereference_array(op1->clone(mem_ctx, NULL),
933 new(mem_ctx) ir_constant(i));
934 result = do_comparison(mem_ctx, operation, e0, e1);
935
936 if (cmp) {
937 cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
938 } else {
939 cmp = result;
940 }
941 }
942
943 mark_whole_array_access(op0);
944 mark_whole_array_access(op1);
945 break;
946 }
947
948 case GLSL_TYPE_STRUCT: {
949 for (unsigned int i = 0; i < op0->type->length; i++) {
950 ir_rvalue *e0, *e1, *result;
951 const char *field_name = op0->type->fields.structure[i].name;
952
953 e0 = new(mem_ctx) ir_dereference_record(op0->clone(mem_ctx, NULL),
954 field_name);
955 e1 = new(mem_ctx) ir_dereference_record(op1->clone(mem_ctx, NULL),
956 field_name);
957 result = do_comparison(mem_ctx, operation, e0, e1);
958
959 if (cmp) {
960 cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
961 } else {
962 cmp = result;
963 }
964 }
965 break;
966 }
967
968 case GLSL_TYPE_ERROR:
969 case GLSL_TYPE_VOID:
970 case GLSL_TYPE_SAMPLER:
971 case GLSL_TYPE_IMAGE:
972 case GLSL_TYPE_INTERFACE:
973 case GLSL_TYPE_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.MaxCombinedTextureImageUnits;
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 = var->type->without_array();
2335
2336 if (base_type->is_image()) {
2337 if (var->data.mode != ir_var_uniform &&
2338 var->data.mode != ir_var_function_in) {
2339 _mesa_glsl_error(loc, state, "image variables may only be declared as "
2340 "function parameters or uniform-qualified "
2341 "global variables");
2342 }
2343
2344 var->data.image_read_only |= qual->flags.q.read_only;
2345 var->data.image_write_only |= qual->flags.q.write_only;
2346 var->data.image_coherent |= qual->flags.q.coherent;
2347 var->data.image_volatile |= qual->flags.q._volatile;
2348 var->data.image_restrict |= qual->flags.q.restrict_flag;
2349 var->data.read_only = true;
2350
2351 if (qual->flags.q.explicit_image_format) {
2352 if (var->data.mode == ir_var_function_in) {
2353 _mesa_glsl_error(loc, state, "format qualifiers cannot be "
2354 "used on image function parameters");
2355 }
2356
2357 if (qual->image_base_type != base_type->sampler_type) {
2358 _mesa_glsl_error(loc, state, "format qualifier doesn't match the "
2359 "base data type of the image");
2360 }
2361
2362 var->data.image_format = qual->image_format;
2363 } else {
2364 if (var->data.mode == ir_var_uniform && !qual->flags.q.write_only) {
2365 _mesa_glsl_error(loc, state, "uniforms not qualified with "
2366 "`writeonly' must have a format layout "
2367 "qualifier");
2368 }
2369
2370 var->data.image_format = GL_NONE;
2371 }
2372 } else if (qual->flags.q.read_only ||
2373 qual->flags.q.write_only ||
2374 qual->flags.q.coherent ||
2375 qual->flags.q._volatile ||
2376 qual->flags.q.restrict_flag ||
2377 qual->flags.q.explicit_image_format) {
2378 _mesa_glsl_error(loc, state, "memory qualifiers may only be applied to "
2379 "images");
2380 }
2381 }
2382
2383 static inline const char*
2384 get_layout_qualifier_string(bool origin_upper_left, bool pixel_center_integer)
2385 {
2386 if (origin_upper_left && pixel_center_integer)
2387 return "origin_upper_left, pixel_center_integer";
2388 else if (origin_upper_left)
2389 return "origin_upper_left";
2390 else if (pixel_center_integer)
2391 return "pixel_center_integer";
2392 else
2393 return " ";
2394 }
2395
2396 static inline bool
2397 is_conflicting_fragcoord_redeclaration(struct _mesa_glsl_parse_state *state,
2398 const struct ast_type_qualifier *qual)
2399 {
2400 /* If gl_FragCoord was previously declared, and the qualifiers were
2401 * different in any way, return true.
2402 */
2403 if (state->fs_redeclares_gl_fragcoord) {
2404 return (state->fs_pixel_center_integer != qual->flags.q.pixel_center_integer
2405 || state->fs_origin_upper_left != qual->flags.q.origin_upper_left);
2406 }
2407
2408 return false;
2409 }
2410
2411 static void
2412 apply_type_qualifier_to_variable(const struct ast_type_qualifier *qual,
2413 ir_variable *var,
2414 struct _mesa_glsl_parse_state *state,
2415 YYLTYPE *loc,
2416 bool is_parameter)
2417 {
2418 STATIC_ASSERT(sizeof(qual->flags.q) <= sizeof(qual->flags.i));
2419
2420 if (qual->flags.q.invariant) {
2421 if (var->data.used) {
2422 _mesa_glsl_error(loc, state,
2423 "variable `%s' may not be redeclared "
2424 "`invariant' after being used",
2425 var->name);
2426 } else {
2427 var->data.invariant = 1;
2428 }
2429 }
2430
2431 if (qual->flags.q.precise) {
2432 if (var->data.used) {
2433 _mesa_glsl_error(loc, state,
2434 "variable `%s' may not be redeclared "
2435 "`precise' after being used",
2436 var->name);
2437 } else {
2438 var->data.precise = 1;
2439 }
2440 }
2441
2442 if (qual->flags.q.constant || qual->flags.q.attribute
2443 || qual->flags.q.uniform
2444 || (qual->flags.q.varying && (state->stage == MESA_SHADER_FRAGMENT)))
2445 var->data.read_only = 1;
2446
2447 if (qual->flags.q.centroid)
2448 var->data.centroid = 1;
2449
2450 if (qual->flags.q.sample)
2451 var->data.sample = 1;
2452
2453 if (state->stage == MESA_SHADER_GEOMETRY &&
2454 qual->flags.q.out && qual->flags.q.stream) {
2455 var->data.stream = qual->stream;
2456 }
2457
2458 if (qual->flags.q.attribute && state->stage != MESA_SHADER_VERTEX) {
2459 var->type = glsl_type::error_type;
2460 _mesa_glsl_error(loc, state,
2461 "`attribute' variables may not be declared in the "
2462 "%s shader",
2463 _mesa_shader_stage_to_string(state->stage));
2464 }
2465
2466 /* Disallow layout qualifiers which may only appear on layout declarations. */
2467 if (qual->flags.q.prim_type) {
2468 _mesa_glsl_error(loc, state,
2469 "Primitive type may only be specified on GS input or output "
2470 "layout declaration, not on variables.");
2471 }
2472
2473 /* Section 6.1.1 (Function Calling Conventions) of the GLSL 1.10 spec says:
2474 *
2475 * "However, the const qualifier cannot be used with out or inout."
2476 *
2477 * The same section of the GLSL 4.40 spec further clarifies this saying:
2478 *
2479 * "The const qualifier cannot be used with out or inout, or a
2480 * compile-time error results."
2481 */
2482 if (is_parameter && qual->flags.q.constant && qual->flags.q.out) {
2483 _mesa_glsl_error(loc, state,
2484 "`const' may not be applied to `out' or `inout' "
2485 "function parameters");
2486 }
2487
2488 /* If there is no qualifier that changes the mode of the variable, leave
2489 * the setting alone.
2490 */
2491 assert(var->data.mode != ir_var_temporary);
2492 if (qual->flags.q.in && qual->flags.q.out)
2493 var->data.mode = ir_var_function_inout;
2494 else if (qual->flags.q.in)
2495 var->data.mode = is_parameter ? ir_var_function_in : ir_var_shader_in;
2496 else if (qual->flags.q.attribute
2497 || (qual->flags.q.varying && (state->stage == MESA_SHADER_FRAGMENT)))
2498 var->data.mode = ir_var_shader_in;
2499 else if (qual->flags.q.out)
2500 var->data.mode = is_parameter ? ir_var_function_out : ir_var_shader_out;
2501 else if (qual->flags.q.varying && (state->stage == MESA_SHADER_VERTEX))
2502 var->data.mode = ir_var_shader_out;
2503 else if (qual->flags.q.uniform)
2504 var->data.mode = ir_var_uniform;
2505
2506 if (!is_parameter && is_varying_var(var, state->stage)) {
2507 /* User-defined ins/outs are not permitted in compute shaders. */
2508 if (state->stage == MESA_SHADER_COMPUTE) {
2509 _mesa_glsl_error(loc, state,
2510 "user-defined input and output variables are not "
2511 "permitted in compute shaders");
2512 }
2513
2514 /* This variable is being used to link data between shader stages (in
2515 * pre-glsl-1.30 parlance, it's a "varying"). Check that it has a type
2516 * that is allowed for such purposes.
2517 *
2518 * From page 25 (page 31 of the PDF) of the GLSL 1.10 spec:
2519 *
2520 * "The varying qualifier can be used only with the data types
2521 * float, vec2, vec3, vec4, mat2, mat3, and mat4, or arrays of
2522 * these."
2523 *
2524 * This was relaxed in GLSL version 1.30 and GLSL ES version 3.00. From
2525 * page 31 (page 37 of the PDF) of the GLSL 1.30 spec:
2526 *
2527 * "Fragment inputs can only be signed and unsigned integers and
2528 * integer vectors, float, floating-point vectors, matrices, or
2529 * arrays of these. Structures cannot be input.
2530 *
2531 * Similar text exists in the section on vertex shader outputs.
2532 *
2533 * Similar text exists in the GLSL ES 3.00 spec, except that the GLSL ES
2534 * 3.00 spec allows structs as well. Varying structs are also allowed
2535 * in GLSL 1.50.
2536 */
2537 switch (var->type->get_scalar_type()->base_type) {
2538 case GLSL_TYPE_FLOAT:
2539 /* Ok in all GLSL versions */
2540 break;
2541 case GLSL_TYPE_UINT:
2542 case GLSL_TYPE_INT:
2543 if (state->is_version(130, 300))
2544 break;
2545 _mesa_glsl_error(loc, state,
2546 "varying variables must be of base type float in %s",
2547 state->get_version_string());
2548 break;
2549 case GLSL_TYPE_STRUCT:
2550 if (state->is_version(150, 300))
2551 break;
2552 _mesa_glsl_error(loc, state,
2553 "varying variables may not be of type struct");
2554 break;
2555 case GLSL_TYPE_DOUBLE:
2556 break;
2557 default:
2558 _mesa_glsl_error(loc, state, "illegal type for a varying variable");
2559 break;
2560 }
2561 }
2562
2563 if (state->all_invariant && (state->current_function == NULL)) {
2564 switch (state->stage) {
2565 case MESA_SHADER_VERTEX:
2566 if (var->data.mode == ir_var_shader_out)
2567 var->data.invariant = true;
2568 break;
2569 case MESA_SHADER_GEOMETRY:
2570 if ((var->data.mode == ir_var_shader_in)
2571 || (var->data.mode == ir_var_shader_out))
2572 var->data.invariant = true;
2573 break;
2574 case MESA_SHADER_FRAGMENT:
2575 if (var->data.mode == ir_var_shader_in)
2576 var->data.invariant = true;
2577 break;
2578 case MESA_SHADER_COMPUTE:
2579 /* Invariance isn't meaningful in compute shaders. */
2580 break;
2581 }
2582 }
2583
2584 var->data.interpolation =
2585 interpret_interpolation_qualifier(qual, (ir_variable_mode) var->data.mode,
2586 state, loc);
2587
2588 var->data.pixel_center_integer = qual->flags.q.pixel_center_integer;
2589 var->data.origin_upper_left = qual->flags.q.origin_upper_left;
2590 if ((qual->flags.q.origin_upper_left || qual->flags.q.pixel_center_integer)
2591 && (strcmp(var->name, "gl_FragCoord") != 0)) {
2592 const char *const qual_string = (qual->flags.q.origin_upper_left)
2593 ? "origin_upper_left" : "pixel_center_integer";
2594
2595 _mesa_glsl_error(loc, state,
2596 "layout qualifier `%s' can only be applied to "
2597 "fragment shader input `gl_FragCoord'",
2598 qual_string);
2599 }
2600
2601 if (var->name != NULL && strcmp(var->name, "gl_FragCoord") == 0) {
2602
2603 /* Section 4.3.8.1, page 39 of GLSL 1.50 spec says:
2604 *
2605 * "Within any shader, the first redeclarations of gl_FragCoord
2606 * must appear before any use of gl_FragCoord."
2607 *
2608 * Generate a compiler error if above condition is not met by the
2609 * fragment shader.
2610 */
2611 ir_variable *earlier = state->symbols->get_variable("gl_FragCoord");
2612 if (earlier != NULL &&
2613 earlier->data.used &&
2614 !state->fs_redeclares_gl_fragcoord) {
2615 _mesa_glsl_error(loc, state,
2616 "gl_FragCoord used before its first redeclaration "
2617 "in fragment shader");
2618 }
2619
2620 /* Make sure all gl_FragCoord redeclarations specify the same layout
2621 * qualifiers.
2622 */
2623 if (is_conflicting_fragcoord_redeclaration(state, qual)) {
2624 const char *const qual_string =
2625 get_layout_qualifier_string(qual->flags.q.origin_upper_left,
2626 qual->flags.q.pixel_center_integer);
2627
2628 const char *const state_string =
2629 get_layout_qualifier_string(state->fs_origin_upper_left,
2630 state->fs_pixel_center_integer);
2631
2632 _mesa_glsl_error(loc, state,
2633 "gl_FragCoord redeclared with different layout "
2634 "qualifiers (%s) and (%s) ",
2635 state_string,
2636 qual_string);
2637 }
2638 state->fs_origin_upper_left = qual->flags.q.origin_upper_left;
2639 state->fs_pixel_center_integer = qual->flags.q.pixel_center_integer;
2640 state->fs_redeclares_gl_fragcoord_with_no_layout_qualifiers =
2641 !qual->flags.q.origin_upper_left && !qual->flags.q.pixel_center_integer;
2642 state->fs_redeclares_gl_fragcoord =
2643 state->fs_origin_upper_left ||
2644 state->fs_pixel_center_integer ||
2645 state->fs_redeclares_gl_fragcoord_with_no_layout_qualifiers;
2646 }
2647
2648 if (qual->flags.q.vk_set) {
2649 if (!qual->flags.q.explicit_binding)
2650 _mesa_glsl_error(loc, state,
2651 "Vulkan descriptor set layout requires both set "
2652 "and binding qualifiers");
2653
2654 var->data.vk_set = true;
2655 var->data.set = qual->set;
2656 var->data.binding = qual->binding;
2657 } else if (qual->flags.q.explicit_location) {
2658 validate_explicit_location(qual, var, state, loc);
2659 } else if (qual->flags.q.explicit_index) {
2660 _mesa_glsl_error(loc, state, "explicit index requires explicit location");
2661 }
2662
2663 if (qual->flags.q.explicit_binding &&
2664 validate_binding_qualifier(state, loc, var, qual)) {
2665 var->data.explicit_binding = true;
2666 var->data.binding = qual->binding;
2667 }
2668
2669 if (var->type->contains_atomic()) {
2670 if (var->data.mode == ir_var_uniform) {
2671 if (var->data.explicit_binding) {
2672 unsigned *offset =
2673 &state->atomic_counter_offsets[var->data.binding];
2674
2675 if (*offset % ATOMIC_COUNTER_SIZE)
2676 _mesa_glsl_error(loc, state,
2677 "misaligned atomic counter offset");
2678
2679 var->data.atomic.offset = *offset;
2680 *offset += var->type->atomic_size();
2681
2682 } else {
2683 _mesa_glsl_error(loc, state,
2684 "atomic counters require explicit binding point");
2685 }
2686 } else if (var->data.mode != ir_var_function_in) {
2687 _mesa_glsl_error(loc, state, "atomic counters may only be declared as "
2688 "function parameters or uniform-qualified "
2689 "global variables");
2690 }
2691 }
2692
2693 /* Does the declaration use the deprecated 'attribute' or 'varying'
2694 * keywords?
2695 */
2696 const bool uses_deprecated_qualifier = qual->flags.q.attribute
2697 || qual->flags.q.varying;
2698
2699
2700 /* Validate auxiliary storage qualifiers */
2701
2702 /* From section 4.3.4 of the GLSL 1.30 spec:
2703 * "It is an error to use centroid in in a vertex shader."
2704 *
2705 * From section 4.3.4 of the GLSL ES 3.00 spec:
2706 * "It is an error to use centroid in or interpolation qualifiers in
2707 * a vertex shader input."
2708 */
2709
2710 /* Section 4.3.6 of the GLSL 1.30 specification states:
2711 * "It is an error to use centroid out in a fragment shader."
2712 *
2713 * The GL_ARB_shading_language_420pack extension specification states:
2714 * "It is an error to use auxiliary storage qualifiers or interpolation
2715 * qualifiers on an output in a fragment shader."
2716 */
2717 if (qual->flags.q.sample && (!is_varying_var(var, state->stage) || uses_deprecated_qualifier)) {
2718 _mesa_glsl_error(loc, state,
2719 "sample qualifier may only be used on `in` or `out` "
2720 "variables between shader stages");
2721 }
2722 if (qual->flags.q.centroid && !is_varying_var(var, state->stage)) {
2723 _mesa_glsl_error(loc, state,
2724 "centroid qualifier may only be used with `in', "
2725 "`out' or `varying' variables between shader stages");
2726 }
2727
2728
2729 /* Is the 'layout' keyword used with parameters that allow relaxed checking.
2730 * Many implementations of GL_ARB_fragment_coord_conventions_enable and some
2731 * implementations (only Mesa?) GL_ARB_explicit_attrib_location_enable
2732 * allowed the layout qualifier to be used with 'varying' and 'attribute'.
2733 * These extensions and all following extensions that add the 'layout'
2734 * keyword have been modified to require the use of 'in' or 'out'.
2735 *
2736 * The following extension do not allow the deprecated keywords:
2737 *
2738 * GL_AMD_conservative_depth
2739 * GL_ARB_conservative_depth
2740 * GL_ARB_gpu_shader5
2741 * GL_ARB_separate_shader_objects
2742 * GL_ARB_tessellation_shader
2743 * GL_ARB_transform_feedback3
2744 * GL_ARB_uniform_buffer_object
2745 *
2746 * It is unknown whether GL_EXT_shader_image_load_store or GL_NV_gpu_shader5
2747 * allow layout with the deprecated keywords.
2748 */
2749 const bool relaxed_layout_qualifier_checking =
2750 state->ARB_fragment_coord_conventions_enable;
2751
2752 if (qual->has_layout() && uses_deprecated_qualifier) {
2753 if (relaxed_layout_qualifier_checking) {
2754 _mesa_glsl_warning(loc, state,
2755 "`layout' qualifier may not be used with "
2756 "`attribute' or `varying'");
2757 } else {
2758 _mesa_glsl_error(loc, state,
2759 "`layout' qualifier may not be used with "
2760 "`attribute' or `varying'");
2761 }
2762 }
2763
2764 /* Layout qualifiers for gl_FragDepth, which are enabled by extension
2765 * AMD_conservative_depth.
2766 */
2767 int depth_layout_count = qual->flags.q.depth_any
2768 + qual->flags.q.depth_greater
2769 + qual->flags.q.depth_less
2770 + qual->flags.q.depth_unchanged;
2771 if (depth_layout_count > 0
2772 && !state->AMD_conservative_depth_enable
2773 && !state->ARB_conservative_depth_enable) {
2774 _mesa_glsl_error(loc, state,
2775 "extension GL_AMD_conservative_depth or "
2776 "GL_ARB_conservative_depth must be enabled "
2777 "to use depth layout qualifiers");
2778 } else if (depth_layout_count > 0
2779 && strcmp(var->name, "gl_FragDepth") != 0) {
2780 _mesa_glsl_error(loc, state,
2781 "depth layout qualifiers can be applied only to "
2782 "gl_FragDepth");
2783 } else if (depth_layout_count > 1
2784 && strcmp(var->name, "gl_FragDepth") == 0) {
2785 _mesa_glsl_error(loc, state,
2786 "at most one depth layout qualifier can be applied to "
2787 "gl_FragDepth");
2788 }
2789 if (qual->flags.q.depth_any)
2790 var->data.depth_layout = ir_depth_layout_any;
2791 else if (qual->flags.q.depth_greater)
2792 var->data.depth_layout = ir_depth_layout_greater;
2793 else if (qual->flags.q.depth_less)
2794 var->data.depth_layout = ir_depth_layout_less;
2795 else if (qual->flags.q.depth_unchanged)
2796 var->data.depth_layout = ir_depth_layout_unchanged;
2797 else
2798 var->data.depth_layout = ir_depth_layout_none;
2799
2800 if (qual->flags.q.std140 ||
2801 qual->flags.q.packed ||
2802 qual->flags.q.shared) {
2803 _mesa_glsl_error(loc, state,
2804 "uniform block layout qualifiers std140, packed, and "
2805 "shared can only be applied to uniform blocks, not "
2806 "members");
2807 }
2808
2809 if (qual->flags.q.row_major || qual->flags.q.column_major) {
2810 validate_matrix_layout_for_type(state, loc, var->type, var);
2811 }
2812
2813 apply_image_qualifier_to_variable(qual, var, state, loc);
2814
2815 /* From section 4.4.1.3 of the GLSL 4.50 specification (Fragment Shader
2816 * Inputs):
2817 *
2818 * "Fragment shaders also allow the following layout qualifier on in only
2819 * (not with variable declarations)
2820 * layout-qualifier-id
2821 * early_fragment_tests
2822 * [...]"
2823 */
2824 if (qual->flags.q.early_fragment_tests) {
2825 _mesa_glsl_error(loc, state, "early_fragment_tests layout qualifier only "
2826 "valid in fragment shader input layout declaration.");
2827 }
2828 }
2829
2830 /**
2831 * Get the variable that is being redeclared by this declaration
2832 *
2833 * Semantic checks to verify the validity of the redeclaration are also
2834 * performed. If semantic checks fail, compilation error will be emitted via
2835 * \c _mesa_glsl_error, but a non-\c NULL pointer will still be returned.
2836 *
2837 * \returns
2838 * A pointer to an existing variable in the current scope if the declaration
2839 * is a redeclaration, \c NULL otherwise.
2840 */
2841 static ir_variable *
2842 get_variable_being_redeclared(ir_variable *var, YYLTYPE loc,
2843 struct _mesa_glsl_parse_state *state,
2844 bool allow_all_redeclarations)
2845 {
2846 /* Check if this declaration is actually a re-declaration, either to
2847 * resize an array or add qualifiers to an existing variable.
2848 *
2849 * This is allowed for variables in the current scope, or when at
2850 * global scope (for built-ins in the implicit outer scope).
2851 */
2852 ir_variable *earlier = state->symbols->get_variable(var->name);
2853 if (earlier == NULL ||
2854 (state->current_function != NULL &&
2855 !state->symbols->name_declared_this_scope(var->name))) {
2856 return NULL;
2857 }
2858
2859
2860 /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec,
2861 *
2862 * "It is legal to declare an array without a size and then
2863 * later re-declare the same name as an array of the same
2864 * type and specify a size."
2865 */
2866 if (earlier->type->is_unsized_array() && var->type->is_array()
2867 && (var->type->fields.array == earlier->type->fields.array)) {
2868 /* FINISHME: This doesn't match the qualifiers on the two
2869 * FINISHME: declarations. It's not 100% clear whether this is
2870 * FINISHME: required or not.
2871 */
2872
2873 const unsigned size = unsigned(var->type->array_size());
2874 check_builtin_array_max_size(var->name, size, loc, state);
2875 if ((size > 0) && (size <= earlier->data.max_array_access)) {
2876 _mesa_glsl_error(& loc, state, "array size must be > %u due to "
2877 "previous access",
2878 earlier->data.max_array_access);
2879 }
2880
2881 earlier->type = var->type;
2882 delete var;
2883 var = NULL;
2884 } else if ((state->ARB_fragment_coord_conventions_enable ||
2885 state->is_version(150, 0))
2886 && strcmp(var->name, "gl_FragCoord") == 0
2887 && earlier->type == var->type
2888 && earlier->data.mode == var->data.mode) {
2889 /* Allow redeclaration of gl_FragCoord for ARB_fcc layout
2890 * qualifiers.
2891 */
2892 earlier->data.origin_upper_left = var->data.origin_upper_left;
2893 earlier->data.pixel_center_integer = var->data.pixel_center_integer;
2894
2895 /* According to section 4.3.7 of the GLSL 1.30 spec,
2896 * the following built-in varaibles can be redeclared with an
2897 * interpolation qualifier:
2898 * * gl_FrontColor
2899 * * gl_BackColor
2900 * * gl_FrontSecondaryColor
2901 * * gl_BackSecondaryColor
2902 * * gl_Color
2903 * * gl_SecondaryColor
2904 */
2905 } else if (state->is_version(130, 0)
2906 && (strcmp(var->name, "gl_FrontColor") == 0
2907 || strcmp(var->name, "gl_BackColor") == 0
2908 || strcmp(var->name, "gl_FrontSecondaryColor") == 0
2909 || strcmp(var->name, "gl_BackSecondaryColor") == 0
2910 || strcmp(var->name, "gl_Color") == 0
2911 || strcmp(var->name, "gl_SecondaryColor") == 0)
2912 && earlier->type == var->type
2913 && earlier->data.mode == var->data.mode) {
2914 earlier->data.interpolation = var->data.interpolation;
2915
2916 /* Layout qualifiers for gl_FragDepth. */
2917 } else if ((state->AMD_conservative_depth_enable ||
2918 state->ARB_conservative_depth_enable)
2919 && strcmp(var->name, "gl_FragDepth") == 0
2920 && earlier->type == var->type
2921 && earlier->data.mode == var->data.mode) {
2922
2923 /** From the AMD_conservative_depth spec:
2924 * Within any shader, the first redeclarations of gl_FragDepth
2925 * must appear before any use of gl_FragDepth.
2926 */
2927 if (earlier->data.used) {
2928 _mesa_glsl_error(&loc, state,
2929 "the first redeclaration of gl_FragDepth "
2930 "must appear before any use of gl_FragDepth");
2931 }
2932
2933 /* Prevent inconsistent redeclaration of depth layout qualifier. */
2934 if (earlier->data.depth_layout != ir_depth_layout_none
2935 && earlier->data.depth_layout != var->data.depth_layout) {
2936 _mesa_glsl_error(&loc, state,
2937 "gl_FragDepth: depth layout is declared here "
2938 "as '%s, but it was previously declared as "
2939 "'%s'",
2940 depth_layout_string(var->data.depth_layout),
2941 depth_layout_string(earlier->data.depth_layout));
2942 }
2943
2944 earlier->data.depth_layout = var->data.depth_layout;
2945
2946 } else if (allow_all_redeclarations) {
2947 if (earlier->data.mode != var->data.mode) {
2948 _mesa_glsl_error(&loc, state,
2949 "redeclaration of `%s' with incorrect qualifiers",
2950 var->name);
2951 } else if (earlier->type != var->type) {
2952 _mesa_glsl_error(&loc, state,
2953 "redeclaration of `%s' has incorrect type",
2954 var->name);
2955 }
2956 } else {
2957 _mesa_glsl_error(&loc, state, "`%s' redeclared", var->name);
2958 }
2959
2960 return earlier;
2961 }
2962
2963 /**
2964 * Generate the IR for an initializer in a variable declaration
2965 */
2966 ir_rvalue *
2967 process_initializer(ir_variable *var, ast_declaration *decl,
2968 ast_fully_specified_type *type,
2969 exec_list *initializer_instructions,
2970 struct _mesa_glsl_parse_state *state)
2971 {
2972 ir_rvalue *result = NULL;
2973
2974 YYLTYPE initializer_loc = decl->initializer->get_location();
2975
2976 /* From page 24 (page 30 of the PDF) of the GLSL 1.10 spec:
2977 *
2978 * "All uniform variables are read-only and are initialized either
2979 * directly by an application via API commands, or indirectly by
2980 * OpenGL."
2981 */
2982 if (var->data.mode == ir_var_uniform) {
2983 state->check_version(120, 0, &initializer_loc,
2984 "cannot initialize uniforms");
2985 }
2986
2987 /* From section 4.1.7 of the GLSL 4.40 spec:
2988 *
2989 * "Opaque variables [...] are initialized only through the
2990 * OpenGL API; they cannot be declared with an initializer in a
2991 * shader."
2992 */
2993 if (var->type->contains_opaque()) {
2994 _mesa_glsl_error(& initializer_loc, state,
2995 "cannot initialize opaque variable");
2996 }
2997
2998 if ((var->data.mode == ir_var_shader_in) && (state->current_function == NULL)) {
2999 _mesa_glsl_error(& initializer_loc, state,
3000 "cannot initialize %s shader input / %s",
3001 _mesa_shader_stage_to_string(state->stage),
3002 (state->stage == MESA_SHADER_VERTEX)
3003 ? "attribute" : "varying");
3004 }
3005
3006 /* If the initializer is an ast_aggregate_initializer, recursively store
3007 * type information from the LHS into it, so that its hir() function can do
3008 * type checking.
3009 */
3010 if (decl->initializer->oper == ast_aggregate)
3011 _mesa_ast_set_aggregate_type(var->type, decl->initializer);
3012
3013 ir_dereference *const lhs = new(state) ir_dereference_variable(var);
3014 ir_rvalue *rhs = decl->initializer->hir(initializer_instructions, state);
3015
3016 /* Calculate the constant value if this is a const or uniform
3017 * declaration.
3018 */
3019 if (type->qualifier.flags.q.constant
3020 || type->qualifier.flags.q.uniform) {
3021 ir_rvalue *new_rhs = validate_assignment(state, initializer_loc,
3022 var->type, rhs, true);
3023 if (new_rhs != NULL) {
3024 rhs = new_rhs;
3025
3026 ir_constant *constant_value = rhs->constant_expression_value();
3027 if (!constant_value) {
3028 /* If ARB_shading_language_420pack is enabled, initializers of
3029 * const-qualified local variables do not have to be constant
3030 * expressions. Const-qualified global variables must still be
3031 * initialized with constant expressions.
3032 */
3033 if (!state->ARB_shading_language_420pack_enable
3034 || state->current_function == NULL) {
3035 _mesa_glsl_error(& initializer_loc, state,
3036 "initializer of %s variable `%s' must be a "
3037 "constant expression",
3038 (type->qualifier.flags.q.constant)
3039 ? "const" : "uniform",
3040 decl->identifier);
3041 if (var->type->is_numeric()) {
3042 /* Reduce cascading errors. */
3043 var->constant_value = ir_constant::zero(state, var->type);
3044 }
3045 }
3046 } else {
3047 rhs = constant_value;
3048 var->constant_value = constant_value;
3049 }
3050 } else {
3051 if (var->type->is_numeric()) {
3052 /* Reduce cascading errors. */
3053 var->constant_value = ir_constant::zero(state, var->type);
3054 }
3055 }
3056 }
3057
3058 if (rhs && !rhs->type->is_error()) {
3059 bool temp = var->data.read_only;
3060 if (type->qualifier.flags.q.constant)
3061 var->data.read_only = false;
3062
3063 /* Never emit code to initialize a uniform.
3064 */
3065 const glsl_type *initializer_type;
3066 if (!type->qualifier.flags.q.uniform) {
3067 do_assignment(initializer_instructions, state,
3068 NULL,
3069 lhs, rhs,
3070 &result, true,
3071 true,
3072 type->get_location());
3073 initializer_type = result->type;
3074 } else
3075 initializer_type = rhs->type;
3076
3077 var->constant_initializer = rhs->constant_expression_value();
3078 var->data.has_initializer = true;
3079
3080 /* If the declared variable is an unsized array, it must inherrit
3081 * its full type from the initializer. A declaration such as
3082 *
3083 * uniform float a[] = float[](1.0, 2.0, 3.0, 3.0);
3084 *
3085 * becomes
3086 *
3087 * uniform float a[4] = float[](1.0, 2.0, 3.0, 3.0);
3088 *
3089 * The assignment generated in the if-statement (below) will also
3090 * automatically handle this case for non-uniforms.
3091 *
3092 * If the declared variable is not an array, the types must
3093 * already match exactly. As a result, the type assignment
3094 * here can be done unconditionally. For non-uniforms the call
3095 * to do_assignment can change the type of the initializer (via
3096 * the implicit conversion rules). For uniforms the initializer
3097 * must be a constant expression, and the type of that expression
3098 * was validated above.
3099 */
3100 var->type = initializer_type;
3101
3102 var->data.read_only = temp;
3103 }
3104
3105 return result;
3106 }
3107
3108
3109 /**
3110 * Do additional processing necessary for geometry shader input declarations
3111 * (this covers both interface blocks arrays and bare input variables).
3112 */
3113 static void
3114 handle_geometry_shader_input_decl(struct _mesa_glsl_parse_state *state,
3115 YYLTYPE loc, ir_variable *var)
3116 {
3117 unsigned num_vertices = 0;
3118 if (state->gs_input_prim_type_specified) {
3119 num_vertices = vertices_per_prim(state->in_qualifier->prim_type);
3120 }
3121
3122 /* Geometry shader input variables must be arrays. Caller should have
3123 * reported an error for this.
3124 */
3125 if (!var->type->is_array()) {
3126 assert(state->error);
3127
3128 /* To avoid cascading failures, short circuit the checks below. */
3129 return;
3130 }
3131
3132 if (var->type->is_unsized_array()) {
3133 /* Section 4.3.8.1 (Input Layout Qualifiers) of the GLSL 1.50 spec says:
3134 *
3135 * All geometry shader input unsized array declarations will be
3136 * sized by an earlier input layout qualifier, when present, as per
3137 * the following table.
3138 *
3139 * Followed by a table mapping each allowed input layout qualifier to
3140 * the corresponding input length.
3141 */
3142 if (num_vertices != 0)
3143 var->type = glsl_type::get_array_instance(var->type->fields.array,
3144 num_vertices);
3145 } else {
3146 /* Section 4.3.8.1 (Input Layout Qualifiers) of the GLSL 1.50 spec
3147 * includes the following examples of compile-time errors:
3148 *
3149 * // code sequence within one shader...
3150 * in vec4 Color1[]; // size unknown
3151 * ...Color1.length()...// illegal, length() unknown
3152 * in vec4 Color2[2]; // size is 2
3153 * ...Color1.length()...// illegal, Color1 still has no size
3154 * in vec4 Color3[3]; // illegal, input sizes are inconsistent
3155 * layout(lines) in; // legal, input size is 2, matching
3156 * in vec4 Color4[3]; // illegal, contradicts layout
3157 * ...
3158 *
3159 * To detect the case illustrated by Color3, we verify that the size of
3160 * an explicitly-sized array matches the size of any previously declared
3161 * explicitly-sized array. To detect the case illustrated by Color4, we
3162 * verify that the size of an explicitly-sized array is consistent with
3163 * any previously declared input layout.
3164 */
3165 if (num_vertices != 0 && var->type->length != num_vertices) {
3166 _mesa_glsl_error(&loc, state,
3167 "geometry shader input size contradicts previously"
3168 " declared layout (size is %u, but layout requires a"
3169 " size of %u)", var->type->length, num_vertices);
3170 } else if (state->gs_input_size != 0 &&
3171 var->type->length != state->gs_input_size) {
3172 _mesa_glsl_error(&loc, state,
3173 "geometry shader input sizes are "
3174 "inconsistent (size is %u, but a previous "
3175 "declaration has size %u)",
3176 var->type->length, state->gs_input_size);
3177 } else {
3178 state->gs_input_size = var->type->length;
3179 }
3180 }
3181 }
3182
3183
3184 void
3185 validate_identifier(const char *identifier, YYLTYPE loc,
3186 struct _mesa_glsl_parse_state *state)
3187 {
3188 /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
3189 *
3190 * "Identifiers starting with "gl_" are reserved for use by
3191 * OpenGL, and may not be declared in a shader as either a
3192 * variable or a function."
3193 */
3194 if (is_gl_identifier(identifier)) {
3195 _mesa_glsl_error(&loc, state,
3196 "identifier `%s' uses reserved `gl_' prefix",
3197 identifier);
3198 } else if (strstr(identifier, "__")) {
3199 /* From page 14 (page 20 of the PDF) of the GLSL 1.10
3200 * spec:
3201 *
3202 * "In addition, all identifiers containing two
3203 * consecutive underscores (__) are reserved as
3204 * possible future keywords."
3205 *
3206 * The intention is that names containing __ are reserved for internal
3207 * use by the implementation, and names prefixed with GL_ are reserved
3208 * for use by Khronos. Names simply containing __ are dangerous to use,
3209 * but should be allowed.
3210 *
3211 * A future version of the GLSL specification will clarify this.
3212 */
3213 _mesa_glsl_warning(&loc, state,
3214 "identifier `%s' uses reserved `__' string",
3215 identifier);
3216 }
3217 }
3218
3219 static bool
3220 precision_qualifier_allowed(const glsl_type *type)
3221 {
3222 /* Precision qualifiers apply to floating point, integer and sampler
3223 * types.
3224 *
3225 * Section 4.5.2 (Precision Qualifiers) of the GLSL 1.30 spec says:
3226 * "Any floating point or any integer declaration can have the type
3227 * preceded by one of these precision qualifiers [...] Literal
3228 * constants do not have precision qualifiers. Neither do Boolean
3229 * variables.
3230 *
3231 * Section 4.5 (Precision and Precision Qualifiers) of the GLSL 1.30
3232 * spec also says:
3233 *
3234 * "Precision qualifiers are added for code portability with OpenGL
3235 * ES, not for functionality. They have the same syntax as in OpenGL
3236 * ES."
3237 *
3238 * Section 8 (Built-In Functions) of the GLSL ES 1.00 spec says:
3239 *
3240 * "uniform lowp sampler2D sampler;
3241 * highp vec2 coord;
3242 * ...
3243 * lowp vec4 col = texture2D (sampler, coord);
3244 * // texture2D returns lowp"
3245 *
3246 * From this, we infer that GLSL 1.30 (and later) should allow precision
3247 * qualifiers on sampler types just like float and integer types.
3248 */
3249 return type->is_float()
3250 || type->is_integer()
3251 || type->is_record()
3252 || type->is_sampler();
3253 }
3254
3255 ir_rvalue *
3256 ast_declarator_list::hir(exec_list *instructions,
3257 struct _mesa_glsl_parse_state *state)
3258 {
3259 void *ctx = state;
3260 const struct glsl_type *decl_type;
3261 const char *type_name = NULL;
3262 ir_rvalue *result = NULL;
3263 YYLTYPE loc = this->get_location();
3264
3265 /* From page 46 (page 52 of the PDF) of the GLSL 1.50 spec:
3266 *
3267 * "To ensure that a particular output variable is invariant, it is
3268 * necessary to use the invariant qualifier. It can either be used to
3269 * qualify a previously declared variable as being invariant
3270 *
3271 * invariant gl_Position; // make existing gl_Position be invariant"
3272 *
3273 * In these cases the parser will set the 'invariant' flag in the declarator
3274 * list, and the type will be NULL.
3275 */
3276 if (this->invariant) {
3277 assert(this->type == NULL);
3278
3279 if (state->current_function != NULL) {
3280 _mesa_glsl_error(& loc, state,
3281 "all uses of `invariant' keyword must be at global "
3282 "scope");
3283 }
3284
3285 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
3286 assert(decl->array_specifier == NULL);
3287 assert(decl->initializer == NULL);
3288
3289 ir_variable *const earlier =
3290 state->symbols->get_variable(decl->identifier);
3291 if (earlier == NULL) {
3292 _mesa_glsl_error(& loc, state,
3293 "undeclared variable `%s' cannot be marked "
3294 "invariant", decl->identifier);
3295 } else if (!is_varying_var(earlier, state->stage)) {
3296 _mesa_glsl_error(&loc, state,
3297 "`%s' cannot be marked invariant; interfaces between "
3298 "shader stages only.", decl->identifier);
3299 } else if (earlier->data.used) {
3300 _mesa_glsl_error(& loc, state,
3301 "variable `%s' may not be redeclared "
3302 "`invariant' after being used",
3303 earlier->name);
3304 } else {
3305 earlier->data.invariant = true;
3306 }
3307 }
3308
3309 /* Invariant redeclarations do not have r-values.
3310 */
3311 return NULL;
3312 }
3313
3314 if (this->precise) {
3315 assert(this->type == NULL);
3316
3317 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
3318 assert(decl->array_specifier == NULL);
3319 assert(decl->initializer == NULL);
3320
3321 ir_variable *const earlier =
3322 state->symbols->get_variable(decl->identifier);
3323 if (earlier == NULL) {
3324 _mesa_glsl_error(& loc, state,
3325 "undeclared variable `%s' cannot be marked "
3326 "precise", decl->identifier);
3327 } else if (state->current_function != NULL &&
3328 !state->symbols->name_declared_this_scope(decl->identifier)) {
3329 /* Note: we have to check if we're in a function, since
3330 * builtins are treated as having come from another scope.
3331 */
3332 _mesa_glsl_error(& loc, state,
3333 "variable `%s' from an outer scope may not be "
3334 "redeclared `precise' in this scope",
3335 earlier->name);
3336 } else if (earlier->data.used) {
3337 _mesa_glsl_error(& loc, state,
3338 "variable `%s' may not be redeclared "
3339 "`precise' after being used",
3340 earlier->name);
3341 } else {
3342 earlier->data.precise = true;
3343 }
3344 }
3345
3346 /* Precise redeclarations do not have r-values either. */
3347 return NULL;
3348 }
3349
3350 assert(this->type != NULL);
3351 assert(!this->invariant);
3352 assert(!this->precise);
3353
3354 /* The type specifier may contain a structure definition. Process that
3355 * before any of the variable declarations.
3356 */
3357 (void) this->type->specifier->hir(instructions, state);
3358
3359 decl_type = this->type->glsl_type(& type_name, state);
3360
3361 /* An offset-qualified atomic counter declaration sets the default
3362 * offset for the next declaration within the same atomic counter
3363 * buffer.
3364 */
3365 if (decl_type && decl_type->contains_atomic()) {
3366 if (type->qualifier.flags.q.explicit_binding &&
3367 type->qualifier.flags.q.explicit_offset)
3368 state->atomic_counter_offsets[type->qualifier.binding] =
3369 type->qualifier.offset;
3370 }
3371
3372 if (this->declarations.is_empty()) {
3373 /* If there is no structure involved in the program text, there are two
3374 * possible scenarios:
3375 *
3376 * - The program text contained something like 'vec4;'. This is an
3377 * empty declaration. It is valid but weird. Emit a warning.
3378 *
3379 * - The program text contained something like 'S;' and 'S' is not the
3380 * name of a known structure type. This is both invalid and weird.
3381 * Emit an error.
3382 *
3383 * - The program text contained something like 'mediump float;'
3384 * when the programmer probably meant 'precision mediump
3385 * float;' Emit a warning with a description of what they
3386 * probably meant to do.
3387 *
3388 * Note that if decl_type is NULL and there is a structure involved,
3389 * there must have been some sort of error with the structure. In this
3390 * case we assume that an error was already generated on this line of
3391 * code for the structure. There is no need to generate an additional,
3392 * confusing error.
3393 */
3394 assert(this->type->specifier->structure == NULL || decl_type != NULL
3395 || state->error);
3396
3397 if (decl_type == NULL) {
3398 _mesa_glsl_error(&loc, state,
3399 "invalid type `%s' in empty declaration",
3400 type_name);
3401 } else if (decl_type->base_type == GLSL_TYPE_ATOMIC_UINT) {
3402 /* Empty atomic counter declarations are allowed and useful
3403 * to set the default offset qualifier.
3404 */
3405 return NULL;
3406 } else if (this->type->qualifier.precision != ast_precision_none) {
3407 if (this->type->specifier->structure != NULL) {
3408 _mesa_glsl_error(&loc, state,
3409 "precision qualifiers can't be applied "
3410 "to structures");
3411 } else {
3412 static const char *const precision_names[] = {
3413 "highp",
3414 "highp",
3415 "mediump",
3416 "lowp"
3417 };
3418
3419 _mesa_glsl_warning(&loc, state,
3420 "empty declaration with precision qualifier, "
3421 "to set the default precision, use "
3422 "`precision %s %s;'",
3423 precision_names[this->type->qualifier.precision],
3424 type_name);
3425 }
3426 } else if (this->type->specifier->structure == NULL) {
3427 _mesa_glsl_warning(&loc, state, "empty declaration");
3428 }
3429 }
3430
3431 foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
3432 const struct glsl_type *var_type;
3433 ir_variable *var;
3434
3435 /* FINISHME: Emit a warning if a variable declaration shadows a
3436 * FINISHME: declaration at a higher scope.
3437 */
3438
3439 if ((decl_type == NULL) || decl_type->is_void()) {
3440 if (type_name != NULL) {
3441 _mesa_glsl_error(& loc, state,
3442 "invalid type `%s' in declaration of `%s'",
3443 type_name, decl->identifier);
3444 } else {
3445 _mesa_glsl_error(& loc, state,
3446 "invalid type in declaration of `%s'",
3447 decl->identifier);
3448 }
3449 continue;
3450 }
3451
3452 var_type = process_array_type(&loc, decl_type, decl->array_specifier,
3453 state);
3454
3455 var = new(ctx) ir_variable(var_type, decl->identifier, ir_var_auto);
3456
3457 /* The 'varying in' and 'varying out' qualifiers can only be used with
3458 * ARB_geometry_shader4 and EXT_geometry_shader4, which we don't support
3459 * yet.
3460 */
3461 if (this->type->qualifier.flags.q.varying) {
3462 if (this->type->qualifier.flags.q.in) {
3463 _mesa_glsl_error(& loc, state,
3464 "`varying in' qualifier in declaration of "
3465 "`%s' only valid for geometry shaders using "
3466 "ARB_geometry_shader4 or EXT_geometry_shader4",
3467 decl->identifier);
3468 } else if (this->type->qualifier.flags.q.out) {
3469 _mesa_glsl_error(& loc, state,
3470 "`varying out' qualifier in declaration of "
3471 "`%s' only valid for geometry shaders using "
3472 "ARB_geometry_shader4 or EXT_geometry_shader4",
3473 decl->identifier);
3474 }
3475 }
3476
3477 /* From page 22 (page 28 of the PDF) of the GLSL 1.10 specification;
3478 *
3479 * "Global variables can only use the qualifiers const,
3480 * attribute, uniform, or varying. Only one may be
3481 * specified.
3482 *
3483 * Local variables can only use the qualifier const."
3484 *
3485 * This is relaxed in GLSL 1.30 and GLSL ES 3.00. It is also relaxed by
3486 * any extension that adds the 'layout' keyword.
3487 */
3488 if (!state->is_version(130, 300)
3489 && !state->has_explicit_attrib_location()
3490 && !state->has_separate_shader_objects()
3491 && !state->ARB_fragment_coord_conventions_enable) {
3492 if (this->type->qualifier.flags.q.out) {
3493 _mesa_glsl_error(& loc, state,
3494 "`out' qualifier in declaration of `%s' "
3495 "only valid for function parameters in %s",
3496 decl->identifier, state->get_version_string());
3497 }
3498 if (this->type->qualifier.flags.q.in) {
3499 _mesa_glsl_error(& loc, state,
3500 "`in' qualifier in declaration of `%s' "
3501 "only valid for function parameters in %s",
3502 decl->identifier, state->get_version_string());
3503 }
3504 /* FINISHME: Test for other invalid qualifiers. */
3505 }
3506
3507 apply_type_qualifier_to_variable(& this->type->qualifier, var, state,
3508 & loc, false);
3509
3510 if (this->type->qualifier.flags.q.invariant) {
3511 if (!is_varying_var(var, state->stage)) {
3512 _mesa_glsl_error(&loc, state,
3513 "`%s' cannot be marked invariant; interfaces between "
3514 "shader stages only", var->name);
3515 }
3516 }
3517
3518 if (state->current_function != NULL) {
3519 const char *mode = NULL;
3520 const char *extra = "";
3521
3522 /* There is no need to check for 'inout' here because the parser will
3523 * only allow that in function parameter lists.
3524 */
3525 if (this->type->qualifier.flags.q.attribute) {
3526 mode = "attribute";
3527 } else if (this->type->qualifier.flags.q.uniform) {
3528 mode = "uniform";
3529 } else if (this->type->qualifier.flags.q.varying) {
3530 mode = "varying";
3531 } else if (this->type->qualifier.flags.q.in) {
3532 mode = "in";
3533 extra = " or in function parameter list";
3534 } else if (this->type->qualifier.flags.q.out) {
3535 mode = "out";
3536 extra = " or in function parameter list";
3537 }
3538
3539 if (mode) {
3540 _mesa_glsl_error(& loc, state,
3541 "%s variable `%s' must be declared at "
3542 "global scope%s",
3543 mode, var->name, extra);
3544 }
3545 } else if (var->data.mode == ir_var_shader_in) {
3546 var->data.read_only = true;
3547
3548 if (state->stage == MESA_SHADER_VERTEX) {
3549 bool error_emitted = false;
3550
3551 /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
3552 *
3553 * "Vertex shader inputs can only be float, floating-point
3554 * vectors, matrices, signed and unsigned integers and integer
3555 * vectors. Vertex shader inputs can also form arrays of these
3556 * types, but not structures."
3557 *
3558 * From page 31 (page 27 of the PDF) of the GLSL 1.30 spec:
3559 *
3560 * "Vertex shader inputs can only be float, floating-point
3561 * vectors, matrices, signed and unsigned integers and integer
3562 * vectors. They cannot be arrays or structures."
3563 *
3564 * From page 23 (page 29 of the PDF) of the GLSL 1.20 spec:
3565 *
3566 * "The attribute qualifier can be used only with float,
3567 * floating-point vectors, and matrices. Attribute variables
3568 * cannot be declared as arrays or structures."
3569 *
3570 * From page 33 (page 39 of the PDF) of the GLSL ES 3.00 spec:
3571 *
3572 * "Vertex shader inputs can only be float, floating-point
3573 * vectors, matrices, signed and unsigned integers and integer
3574 * vectors. Vertex shader inputs cannot be arrays or
3575 * structures."
3576 */
3577 const glsl_type *check_type = var->type->without_array();
3578
3579 switch (check_type->base_type) {
3580 case GLSL_TYPE_FLOAT:
3581 break;
3582 case GLSL_TYPE_UINT:
3583 case GLSL_TYPE_INT:
3584 if (state->is_version(120, 300))
3585 break;
3586 case GLSL_TYPE_DOUBLE:
3587 if (check_type->base_type == GLSL_TYPE_DOUBLE && (state->is_version(410, 0) || state->ARB_vertex_attrib_64bit_enable))
3588 break;
3589 /* FALLTHROUGH */
3590 default:
3591 _mesa_glsl_error(& loc, state,
3592 "vertex shader input / attribute cannot have "
3593 "type %s`%s'",
3594 var->type->is_array() ? "array of " : "",
3595 check_type->name);
3596 error_emitted = true;
3597 }
3598
3599 if (!error_emitted && var->type->is_array() &&
3600 !state->check_version(150, 0, &loc,
3601 "vertex shader input / attribute "
3602 "cannot have array type")) {
3603 error_emitted = true;
3604 }
3605 } else if (state->stage == MESA_SHADER_GEOMETRY) {
3606 /* From section 4.3.4 (Inputs) of the GLSL 1.50 spec:
3607 *
3608 * Geometry shader input variables get the per-vertex values
3609 * written out by vertex shader output variables of the same
3610 * names. Since a geometry shader operates on a set of
3611 * vertices, each input varying variable (or input block, see
3612 * interface blocks below) needs to be declared as an array.
3613 */
3614 if (!var->type->is_array()) {
3615 _mesa_glsl_error(&loc, state,
3616 "geometry shader inputs must be arrays");
3617 }
3618
3619 handle_geometry_shader_input_decl(state, loc, var);
3620 } else if (state->stage == MESA_SHADER_FRAGMENT) {
3621 /* From section 4.3.4 (Input Variables) of the GLSL ES 3.10 spec:
3622 *
3623 * It is a compile-time error to declare a fragment shader
3624 * input with, or that contains, any of the following types:
3625 *
3626 * * A boolean type
3627 * * An opaque type
3628 * * An array of arrays
3629 * * An array of structures
3630 * * A structure containing an array
3631 * * A structure containing a structure
3632 */
3633 if (state->es_shader) {
3634 const glsl_type *check_type = var->type->without_array();
3635 if (check_type->is_boolean() ||
3636 check_type->contains_opaque()) {
3637 _mesa_glsl_error(&loc, state,
3638 "fragment shader input cannot have type %s",
3639 check_type->name);
3640 }
3641 if (var->type->is_array() &&
3642 var->type->fields.array->is_array()) {
3643 _mesa_glsl_error(&loc, state,
3644 "%s shader output "
3645 "cannot have an array of arrays",
3646 _mesa_shader_stage_to_string(state->stage));
3647 }
3648 if (var->type->is_array() &&
3649 var->type->fields.array->is_record()) {
3650 _mesa_glsl_error(&loc, state,
3651 "fragment shader input "
3652 "cannot have an array of structs");
3653 }
3654 if (var->type->is_record()) {
3655 for (unsigned i = 0; i < var->type->length; i++) {
3656 if (var->type->fields.structure[i].type->is_array() ||
3657 var->type->fields.structure[i].type->is_record())
3658 _mesa_glsl_error(&loc, state,
3659 "fragement shader input cannot have "
3660 "a struct that contains an "
3661 "array or struct");
3662 }
3663 }
3664 }
3665 }
3666 } else if (var->data.mode == ir_var_shader_out) {
3667 const glsl_type *check_type = var->type->without_array();
3668
3669 /* From section 4.3.6 (Output variables) of the GLSL 4.40 spec:
3670 *
3671 * It is a compile-time error to declare a vertex, tessellation
3672 * evaluation, tessellation control, or geometry shader output
3673 * that contains any of the following:
3674 *
3675 * * A Boolean type (bool, bvec2 ...)
3676 * * An opaque type
3677 */
3678 if (check_type->is_boolean() || check_type->contains_opaque())
3679 _mesa_glsl_error(&loc, state,
3680 "%s shader output cannot have type %s",
3681 _mesa_shader_stage_to_string(state->stage),
3682 check_type->name);
3683
3684 /* From section 4.3.6 (Output variables) of the GLSL 4.40 spec:
3685 *
3686 * It is a compile-time error to declare a fragment shader output
3687 * that contains any of the following:
3688 *
3689 * * A Boolean type (bool, bvec2 ...)
3690 * * A double-precision scalar or vector (double, dvec2 ...)
3691 * * An opaque type
3692 * * Any matrix type
3693 * * A structure
3694 */
3695 if (state->stage == MESA_SHADER_FRAGMENT) {
3696 if (check_type->is_record() || check_type->is_matrix())
3697 _mesa_glsl_error(&loc, state,
3698 "fragment shader output "
3699 "cannot have struct or matrix type");
3700 switch (check_type->base_type) {
3701 case GLSL_TYPE_UINT:
3702 case GLSL_TYPE_INT:
3703 case GLSL_TYPE_FLOAT:
3704 break;
3705 default:
3706 _mesa_glsl_error(&loc, state,
3707 "fragment shader output cannot have "
3708 "type %s", check_type->name);
3709 }
3710 }
3711
3712 /* From section 4.3.6 (Output Variables) of the GLSL ES 3.10 spec:
3713 *
3714 * It is a compile-time error to declare a vertex shader output
3715 * with, or that contains, any of the following types:
3716 *
3717 * * A boolean type
3718 * * An opaque type
3719 * * An array of arrays
3720 * * An array of structures
3721 * * A structure containing an array
3722 * * A structure containing a structure
3723 *
3724 * It is a compile-time error to declare a fragment shader output
3725 * with, or that contains, any of the following types:
3726 *
3727 * * A boolean type
3728 * * An opaque type
3729 * * A matrix
3730 * * A structure
3731 * * An array of array
3732 */
3733 if (state->es_shader) {
3734 if (var->type->is_array() &&
3735 var->type->fields.array->is_array()) {
3736 _mesa_glsl_error(&loc, state,
3737 "%s shader output "
3738 "cannot have an array of arrays",
3739 _mesa_shader_stage_to_string(state->stage));
3740 }
3741 if (state->stage == MESA_SHADER_VERTEX) {
3742 if (var->type->is_array() &&
3743 var->type->fields.array->is_record()) {
3744 _mesa_glsl_error(&loc, state,
3745 "vertex shader output "
3746 "cannot have an array of structs");
3747 }
3748 if (var->type->is_record()) {
3749 for (unsigned i = 0; i < var->type->length; i++) {
3750 if (var->type->fields.structure[i].type->is_array() ||
3751 var->type->fields.structure[i].type->is_record())
3752 _mesa_glsl_error(&loc, state,
3753 "vertex shader output cannot have a "
3754 "struct that contains an "
3755 "array or struct");
3756 }
3757 }
3758 }
3759 }
3760 }
3761
3762 /* Integer fragment inputs must be qualified with 'flat'. In GLSL ES,
3763 * so must integer vertex outputs.
3764 *
3765 * From section 4.3.4 ("Inputs") of the GLSL 1.50 spec:
3766 * "Fragment shader inputs that are signed or unsigned integers or
3767 * integer vectors must be qualified with the interpolation qualifier
3768 * flat."
3769 *
3770 * From section 4.3.4 ("Input Variables") of the GLSL 3.00 ES spec:
3771 * "Fragment shader inputs that are, or contain, signed or unsigned
3772 * integers or integer vectors must be qualified with the
3773 * interpolation qualifier flat."
3774 *
3775 * From section 4.3.6 ("Output Variables") of the GLSL 3.00 ES spec:
3776 * "Vertex shader outputs that are, or contain, signed or unsigned
3777 * integers or integer vectors must be qualified with the
3778 * interpolation qualifier flat."
3779 *
3780 * Note that prior to GLSL 1.50, this requirement applied to vertex
3781 * outputs rather than fragment inputs. That creates problems in the
3782 * presence of geometry shaders, so we adopt the GLSL 1.50 rule for all
3783 * desktop GL shaders. For GLSL ES shaders, we follow the spec and
3784 * apply the restriction to both vertex outputs and fragment inputs.
3785 *
3786 * Note also that the desktop GLSL specs are missing the text "or
3787 * contain"; this is presumably an oversight, since there is no
3788 * reasonable way to interpolate a fragment shader input that contains
3789 * an integer.
3790 */
3791 if (state->is_version(130, 300) &&
3792 var->type->contains_integer() &&
3793 var->data.interpolation != INTERP_QUALIFIER_FLAT &&
3794 ((state->stage == MESA_SHADER_FRAGMENT && var->data.mode == ir_var_shader_in)
3795 || (state->stage == MESA_SHADER_VERTEX && var->data.mode == ir_var_shader_out
3796 && state->es_shader))) {
3797 const char *var_type = (state->stage == MESA_SHADER_VERTEX) ?
3798 "vertex output" : "fragment input";
3799 _mesa_glsl_error(&loc, state, "if a %s is (or contains) "
3800 "an integer, then it must be qualified with 'flat'",
3801 var_type);
3802 }
3803
3804 /* Double fragment inputs must be qualified with 'flat'. */
3805 if (var->type->contains_double() &&
3806 var->data.interpolation != INTERP_QUALIFIER_FLAT &&
3807 state->stage == MESA_SHADER_FRAGMENT &&
3808 var->data.mode == ir_var_shader_in) {
3809 _mesa_glsl_error(&loc, state, "if a fragment input is (or contains) "
3810 "a double, then it must be qualified with 'flat'",
3811 var_type);
3812 }
3813
3814 /* Interpolation qualifiers cannot be applied to 'centroid' and
3815 * 'centroid varying'.
3816 *
3817 * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
3818 * "interpolation qualifiers may only precede the qualifiers in,
3819 * centroid in, out, or centroid out in a declaration. They do not apply
3820 * to the deprecated storage qualifiers varying or centroid varying."
3821 *
3822 * These deprecated storage qualifiers do not exist in GLSL ES 3.00.
3823 */
3824 if (state->is_version(130, 0)
3825 && this->type->qualifier.has_interpolation()
3826 && this->type->qualifier.flags.q.varying) {
3827
3828 const char *i = this->type->qualifier.interpolation_string();
3829 assert(i != NULL);
3830 const char *s;
3831 if (this->type->qualifier.flags.q.centroid)
3832 s = "centroid varying";
3833 else
3834 s = "varying";
3835
3836 _mesa_glsl_error(&loc, state,
3837 "qualifier '%s' cannot be applied to the "
3838 "deprecated storage qualifier '%s'", i, s);
3839 }
3840
3841
3842 /* Interpolation qualifiers can only apply to vertex shader outputs and
3843 * fragment shader inputs.
3844 *
3845 * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
3846 * "Outputs from a vertex shader (out) and inputs to a fragment
3847 * shader (in) can be further qualified with one or more of these
3848 * interpolation qualifiers"
3849 *
3850 * From page 31 (page 37 of the PDF) of the GLSL ES 3.00 spec:
3851 * "These interpolation qualifiers may only precede the qualifiers
3852 * in, centroid in, out, or centroid out in a declaration. They do
3853 * not apply to inputs into a vertex shader or outputs from a
3854 * fragment shader."
3855 */
3856 if (state->is_version(130, 300)
3857 && this->type->qualifier.has_interpolation()) {
3858
3859 const char *i = this->type->qualifier.interpolation_string();
3860 assert(i != NULL);
3861
3862 switch (state->stage) {
3863 case MESA_SHADER_VERTEX:
3864 if (this->type->qualifier.flags.q.in) {
3865 _mesa_glsl_error(&loc, state,
3866 "qualifier '%s' cannot be applied to vertex "
3867 "shader inputs", i);
3868 }
3869 break;
3870 case MESA_SHADER_FRAGMENT:
3871 if (this->type->qualifier.flags.q.out) {
3872 _mesa_glsl_error(&loc, state,
3873 "qualifier '%s' cannot be applied to fragment "
3874 "shader outputs", i);
3875 }
3876 break;
3877 default:
3878 break;
3879 }
3880 }
3881
3882
3883 /* Precision qualifiers exists only in GLSL versions 1.00 and >= 1.30.
3884 */
3885 if (this->type->qualifier.precision != ast_precision_none) {
3886 state->check_precision_qualifiers_allowed(&loc);
3887 }
3888
3889
3890 /* If a precision qualifier is allowed on a type, it is allowed on
3891 * an array of that type.
3892 */
3893 if (!(this->type->qualifier.precision == ast_precision_none
3894 || precision_qualifier_allowed(var->type)
3895 || (var->type->is_array()
3896 && precision_qualifier_allowed(var->type->fields.array)))) {
3897
3898 _mesa_glsl_error(&loc, state,
3899 "precision qualifiers apply only to floating point"
3900 ", integer and sampler types");
3901 }
3902
3903 /* From section 4.1.7 of the GLSL 4.40 spec:
3904 *
3905 * "[Opaque types] can only be declared as function
3906 * parameters or uniform-qualified variables."
3907 */
3908 if (var_type->contains_opaque() &&
3909 !this->type->qualifier.flags.q.uniform) {
3910 _mesa_glsl_error(&loc, state,
3911 "opaque variables must be declared uniform");
3912 }
3913
3914 /* Process the initializer and add its instructions to a temporary
3915 * list. This list will be added to the instruction stream (below) after
3916 * the declaration is added. This is done because in some cases (such as
3917 * redeclarations) the declaration may not actually be added to the
3918 * instruction stream.
3919 */
3920 exec_list initializer_instructions;
3921
3922 /* Examine var name here since var may get deleted in the next call */
3923 bool var_is_gl_id = is_gl_identifier(var->name);
3924
3925 ir_variable *earlier =
3926 get_variable_being_redeclared(var, decl->get_location(), state,
3927 false /* allow_all_redeclarations */);
3928 if (earlier != NULL) {
3929 if (var_is_gl_id &&
3930 earlier->data.how_declared == ir_var_declared_in_block) {
3931 _mesa_glsl_error(&loc, state,
3932 "`%s' has already been redeclared using "
3933 "gl_PerVertex", earlier->name);
3934 }
3935 earlier->data.how_declared = ir_var_declared_normally;
3936 }
3937
3938 if (decl->initializer != NULL) {
3939 result = process_initializer((earlier == NULL) ? var : earlier,
3940 decl, this->type,
3941 &initializer_instructions, state);
3942 }
3943
3944 /* From page 23 (page 29 of the PDF) of the GLSL 1.10 spec:
3945 *
3946 * "It is an error to write to a const variable outside of
3947 * its declaration, so they must be initialized when
3948 * declared."
3949 */
3950 if (this->type->qualifier.flags.q.constant && decl->initializer == NULL) {
3951 _mesa_glsl_error(& loc, state,
3952 "const declaration of `%s' must be initialized",
3953 decl->identifier);
3954 }
3955
3956 if (state->es_shader) {
3957 const glsl_type *const t = (earlier == NULL)
3958 ? var->type : earlier->type;
3959
3960 if (t->is_unsized_array())
3961 /* Section 10.17 of the GLSL ES 1.00 specification states that
3962 * unsized array declarations have been removed from the language.
3963 * Arrays that are sized using an initializer are still explicitly
3964 * sized. However, GLSL ES 1.00 does not allow array
3965 * initializers. That is only allowed in GLSL ES 3.00.
3966 *
3967 * Section 4.1.9 (Arrays) of the GLSL ES 3.00 spec says:
3968 *
3969 * "An array type can also be formed without specifying a size
3970 * if the definition includes an initializer:
3971 *
3972 * float x[] = float[2] (1.0, 2.0); // declares an array of size 2
3973 * float y[] = float[] (1.0, 2.0, 3.0); // declares an array of size 3
3974 *
3975 * float a[5];
3976 * float b[] = a;"
3977 */
3978 _mesa_glsl_error(& loc, state,
3979 "unsized array declarations are not allowed in "
3980 "GLSL ES");
3981 }
3982
3983 /* If the declaration is not a redeclaration, there are a few additional
3984 * semantic checks that must be applied. In addition, variable that was
3985 * created for the declaration should be added to the IR stream.
3986 */
3987 if (earlier == NULL) {
3988 validate_identifier(decl->identifier, loc, state);
3989
3990 /* Add the variable to the symbol table. Note that the initializer's
3991 * IR was already processed earlier (though it hasn't been emitted
3992 * yet), without the variable in scope.
3993 *
3994 * This differs from most C-like languages, but it follows the GLSL
3995 * specification. From page 28 (page 34 of the PDF) of the GLSL 1.50
3996 * spec:
3997 *
3998 * "Within a declaration, the scope of a name starts immediately
3999 * after the initializer if present or immediately after the name
4000 * being declared if not."
4001 */
4002 if (!state->symbols->add_variable(var)) {
4003 YYLTYPE loc = this->get_location();
4004 _mesa_glsl_error(&loc, state, "name `%s' already taken in the "
4005 "current scope", decl->identifier);
4006 continue;
4007 }
4008
4009 /* Push the variable declaration to the top. It means that all the
4010 * variable declarations will appear in a funny last-to-first order,
4011 * but otherwise we run into trouble if a function is prototyped, a
4012 * global var is decled, then the function is defined with usage of
4013 * the global var. See glslparsertest's CorrectModule.frag.
4014 */
4015 instructions->push_head(var);
4016 }
4017
4018 instructions->append_list(&initializer_instructions);
4019 }
4020
4021
4022 /* Generally, variable declarations do not have r-values. However,
4023 * one is used for the declaration in
4024 *
4025 * while (bool b = some_condition()) {
4026 * ...
4027 * }
4028 *
4029 * so we return the rvalue from the last seen declaration here.
4030 */
4031 return result;
4032 }
4033
4034
4035 ir_rvalue *
4036 ast_parameter_declarator::hir(exec_list *instructions,
4037 struct _mesa_glsl_parse_state *state)
4038 {
4039 void *ctx = state;
4040 const struct glsl_type *type;
4041 const char *name = NULL;
4042 YYLTYPE loc = this->get_location();
4043
4044 type = this->type->glsl_type(& name, state);
4045
4046 if (type == NULL) {
4047 if (name != NULL) {
4048 _mesa_glsl_error(& loc, state,
4049 "invalid type `%s' in declaration of `%s'",
4050 name, this->identifier);
4051 } else {
4052 _mesa_glsl_error(& loc, state,
4053 "invalid type in declaration of `%s'",
4054 this->identifier);
4055 }
4056
4057 type = glsl_type::error_type;
4058 }
4059
4060 /* From page 62 (page 68 of the PDF) of the GLSL 1.50 spec:
4061 *
4062 * "Functions that accept no input arguments need not use void in the
4063 * argument list because prototypes (or definitions) are required and
4064 * therefore there is no ambiguity when an empty argument list "( )" is
4065 * declared. The idiom "(void)" as a parameter list is provided for
4066 * convenience."
4067 *
4068 * Placing this check here prevents a void parameter being set up
4069 * for a function, which avoids tripping up checks for main taking
4070 * parameters and lookups of an unnamed symbol.
4071 */
4072 if (type->is_void()) {
4073 if (this->identifier != NULL)
4074 _mesa_glsl_error(& loc, state,
4075 "named parameter cannot have type `void'");
4076
4077 is_void = true;
4078 return NULL;
4079 }
4080
4081 if (formal_parameter && (this->identifier == NULL)) {
4082 _mesa_glsl_error(& loc, state, "formal parameter lacks a name");
4083 return NULL;
4084 }
4085
4086 /* This only handles "vec4 foo[..]". The earlier specifier->glsl_type(...)
4087 * call already handled the "vec4[..] foo" case.
4088 */
4089 type = process_array_type(&loc, type, this->array_specifier, state);
4090
4091 if (!type->is_error() && type->is_unsized_array()) {
4092 _mesa_glsl_error(&loc, state, "arrays passed as parameters must have "
4093 "a declared size");
4094 type = glsl_type::error_type;
4095 }
4096
4097 is_void = false;
4098 ir_variable *var = new(ctx)
4099 ir_variable(type, this->identifier, ir_var_function_in);
4100
4101 /* Apply any specified qualifiers to the parameter declaration. Note that
4102 * for function parameters the default mode is 'in'.
4103 */
4104 apply_type_qualifier_to_variable(& this->type->qualifier, var, state, & loc,
4105 true);
4106
4107 /* From section 4.1.7 of the GLSL 4.40 spec:
4108 *
4109 * "Opaque variables cannot be treated as l-values; hence cannot
4110 * be used as out or inout function parameters, nor can they be
4111 * assigned into."
4112 */
4113 if ((var->data.mode == ir_var_function_inout || var->data.mode == ir_var_function_out)
4114 && type->contains_opaque()) {
4115 _mesa_glsl_error(&loc, state, "out and inout parameters cannot "
4116 "contain opaque variables");
4117 type = glsl_type::error_type;
4118 }
4119
4120 /* From page 39 (page 45 of the PDF) of the GLSL 1.10 spec:
4121 *
4122 * "When calling a function, expressions that do not evaluate to
4123 * l-values cannot be passed to parameters declared as out or inout."
4124 *
4125 * From page 32 (page 38 of the PDF) of the GLSL 1.10 spec:
4126 *
4127 * "Other binary or unary expressions, non-dereferenced arrays,
4128 * function names, swizzles with repeated fields, and constants
4129 * cannot be l-values."
4130 *
4131 * So for GLSL 1.10, passing an array as an out or inout parameter is not
4132 * allowed. This restriction is removed in GLSL 1.20, and in GLSL ES.
4133 */
4134 if ((var->data.mode == ir_var_function_inout || var->data.mode == ir_var_function_out)
4135 && type->is_array()
4136 && !state->check_version(120, 100, &loc,
4137 "arrays cannot be out or inout parameters")) {
4138 type = glsl_type::error_type;
4139 }
4140
4141 instructions->push_tail(var);
4142
4143 /* Parameter declarations do not have r-values.
4144 */
4145 return NULL;
4146 }
4147
4148
4149 void
4150 ast_parameter_declarator::parameters_to_hir(exec_list *ast_parameters,
4151 bool formal,
4152 exec_list *ir_parameters,
4153 _mesa_glsl_parse_state *state)
4154 {
4155 ast_parameter_declarator *void_param = NULL;
4156 unsigned count = 0;
4157
4158 foreach_list_typed (ast_parameter_declarator, param, link, ast_parameters) {
4159 param->formal_parameter = formal;
4160 param->hir(ir_parameters, state);
4161
4162 if (param->is_void)
4163 void_param = param;
4164
4165 count++;
4166 }
4167
4168 if ((void_param != NULL) && (count > 1)) {
4169 YYLTYPE loc = void_param->get_location();
4170
4171 _mesa_glsl_error(& loc, state,
4172 "`void' parameter must be only parameter");
4173 }
4174 }
4175
4176
4177 void
4178 emit_function(_mesa_glsl_parse_state *state, ir_function *f)
4179 {
4180 /* IR invariants disallow function declarations or definitions
4181 * nested within other function definitions. But there is no
4182 * requirement about the relative order of function declarations
4183 * and definitions with respect to one another. So simply insert
4184 * the new ir_function block at the end of the toplevel instruction
4185 * list.
4186 */
4187 state->toplevel_ir->push_tail(f);
4188 }
4189
4190
4191 ir_rvalue *
4192 ast_function::hir(exec_list *instructions,
4193 struct _mesa_glsl_parse_state *state)
4194 {
4195 void *ctx = state;
4196 ir_function *f = NULL;
4197 ir_function_signature *sig = NULL;
4198 exec_list hir_parameters;
4199
4200 const char *const name = identifier;
4201
4202 /* New functions are always added to the top-level IR instruction stream,
4203 * so this instruction list pointer is ignored. See also emit_function
4204 * (called below).
4205 */
4206 (void) instructions;
4207
4208 /* From page 21 (page 27 of the PDF) of the GLSL 1.20 spec,
4209 *
4210 * "Function declarations (prototypes) cannot occur inside of functions;
4211 * they must be at global scope, or for the built-in functions, outside
4212 * the global scope."
4213 *
4214 * From page 27 (page 33 of the PDF) of the GLSL ES 1.00.16 spec,
4215 *
4216 * "User defined functions may only be defined within the global scope."
4217 *
4218 * Note that this language does not appear in GLSL 1.10.
4219 */
4220 if ((state->current_function != NULL) &&
4221 state->is_version(120, 100)) {
4222 YYLTYPE loc = this->get_location();
4223 _mesa_glsl_error(&loc, state,
4224 "declaration of function `%s' not allowed within "
4225 "function body", name);
4226 }
4227
4228 validate_identifier(name, this->get_location(), state);
4229
4230 /* Convert the list of function parameters to HIR now so that they can be
4231 * used below to compare this function's signature with previously seen
4232 * signatures for functions with the same name.
4233 */
4234 ast_parameter_declarator::parameters_to_hir(& this->parameters,
4235 is_definition,
4236 & hir_parameters, state);
4237
4238 const char *return_type_name;
4239 const glsl_type *return_type =
4240 this->return_type->glsl_type(& return_type_name, state);
4241
4242 if (!return_type) {
4243 YYLTYPE loc = this->get_location();
4244 _mesa_glsl_error(&loc, state,
4245 "function `%s' has undeclared return type `%s'",
4246 name, return_type_name);
4247 return_type = glsl_type::error_type;
4248 }
4249
4250 /* From page 56 (page 62 of the PDF) of the GLSL 1.30 spec:
4251 * "No qualifier is allowed on the return type of a function."
4252 */
4253 if (this->return_type->has_qualifiers()) {
4254 YYLTYPE loc = this->get_location();
4255 _mesa_glsl_error(& loc, state,
4256 "function `%s' return type has qualifiers", name);
4257 }
4258
4259 /* Section 6.1 (Function Definitions) of the GLSL 1.20 spec says:
4260 *
4261 * "Arrays are allowed as arguments and as the return type. In both
4262 * cases, the array must be explicitly sized."
4263 */
4264 if (return_type->is_unsized_array()) {
4265 YYLTYPE loc = this->get_location();
4266 _mesa_glsl_error(& loc, state,
4267 "function `%s' return type array must be explicitly "
4268 "sized", name);
4269 }
4270
4271 /* From section 4.1.7 of the GLSL 4.40 spec:
4272 *
4273 * "[Opaque types] can only be declared as function parameters
4274 * or uniform-qualified variables."
4275 */
4276 if (return_type->contains_opaque()) {
4277 YYLTYPE loc = this->get_location();
4278 _mesa_glsl_error(&loc, state,
4279 "function `%s' return type can't contain an opaque type",
4280 name);
4281 }
4282
4283 /* Create an ir_function if one doesn't already exist. */
4284 f = state->symbols->get_function(name);
4285 if (f == NULL) {
4286 f = new(ctx) ir_function(name);
4287 if (!state->symbols->add_function(f)) {
4288 /* This function name shadows a non-function use of the same name. */
4289 YYLTYPE loc = this->get_location();
4290
4291 _mesa_glsl_error(&loc, state, "function name `%s' conflicts with "
4292 "non-function", name);
4293 return NULL;
4294 }
4295
4296 emit_function(state, f);
4297 }
4298
4299 /* From GLSL ES 3.0 spec, chapter 6.1 "Function Definitions", page 71:
4300 *
4301 * "A shader cannot redefine or overload built-in functions."
4302 *
4303 * While in GLSL ES 1.0 specification, chapter 8 "Built-in Functions":
4304 *
4305 * "User code can overload the built-in functions but cannot redefine
4306 * them."
4307 */
4308 if (state->es_shader && state->language_version >= 300) {
4309 /* Local shader has no exact candidates; check the built-ins. */
4310 _mesa_glsl_initialize_builtin_functions();
4311 if (_mesa_glsl_find_builtin_function_by_name(state, name)) {
4312 YYLTYPE loc = this->get_location();
4313 _mesa_glsl_error(& loc, state,
4314 "A shader cannot redefine or overload built-in "
4315 "function `%s' in GLSL ES 3.00", name);
4316 return NULL;
4317 }
4318 }
4319
4320 /* Verify that this function's signature either doesn't match a previously
4321 * seen signature for a function with the same name, or, if a match is found,
4322 * that the previously seen signature does not have an associated definition.
4323 */
4324 if (state->es_shader || f->has_user_signature()) {
4325 sig = f->exact_matching_signature(state, &hir_parameters);
4326 if (sig != NULL) {
4327 const char *badvar = sig->qualifiers_match(&hir_parameters);
4328 if (badvar != NULL) {
4329 YYLTYPE loc = this->get_location();
4330
4331 _mesa_glsl_error(&loc, state, "function `%s' parameter `%s' "
4332 "qualifiers don't match prototype", name, badvar);
4333 }
4334
4335 if (sig->return_type != return_type) {
4336 YYLTYPE loc = this->get_location();
4337
4338 _mesa_glsl_error(&loc, state, "function `%s' return type doesn't "
4339 "match prototype", name);
4340 }
4341
4342 if (sig->is_defined) {
4343 if (is_definition) {
4344 YYLTYPE loc = this->get_location();
4345 _mesa_glsl_error(& loc, state, "function `%s' redefined", name);
4346 } else {
4347 /* We just encountered a prototype that exactly matches a
4348 * function that's already been defined. This is redundant,
4349 * and we should ignore it.
4350 */
4351 return NULL;
4352 }
4353 }
4354 }
4355 }
4356
4357 /* Verify the return type of main() */
4358 if (strcmp(name, "main") == 0) {
4359 if (! return_type->is_void()) {
4360 YYLTYPE loc = this->get_location();
4361
4362 _mesa_glsl_error(& loc, state, "main() must return void");
4363 }
4364
4365 if (!hir_parameters.is_empty()) {
4366 YYLTYPE loc = this->get_location();
4367
4368 _mesa_glsl_error(& loc, state, "main() must not take any parameters");
4369 }
4370 }
4371
4372 /* Finish storing the information about this new function in its signature.
4373 */
4374 if (sig == NULL) {
4375 sig = new(ctx) ir_function_signature(return_type);
4376 f->add_signature(sig);
4377 }
4378
4379 sig->replace_parameters(&hir_parameters);
4380 signature = sig;
4381
4382 /* Function declarations (prototypes) do not have r-values.
4383 */
4384 return NULL;
4385 }
4386
4387
4388 ir_rvalue *
4389 ast_function_definition::hir(exec_list *instructions,
4390 struct _mesa_glsl_parse_state *state)
4391 {
4392 prototype->is_definition = true;
4393 prototype->hir(instructions, state);
4394
4395 ir_function_signature *signature = prototype->signature;
4396 if (signature == NULL)
4397 return NULL;
4398
4399 assert(state->current_function == NULL);
4400 state->current_function = signature;
4401 state->found_return = false;
4402
4403 /* Duplicate parameters declared in the prototype as concrete variables.
4404 * Add these to the symbol table.
4405 */
4406 state->symbols->push_scope();
4407 foreach_in_list(ir_variable, var, &signature->parameters) {
4408 assert(var->as_variable() != NULL);
4409
4410 /* The only way a parameter would "exist" is if two parameters have
4411 * the same name.
4412 */
4413 if (state->symbols->name_declared_this_scope(var->name)) {
4414 YYLTYPE loc = this->get_location();
4415
4416 _mesa_glsl_error(& loc, state, "parameter `%s' redeclared", var->name);
4417 } else {
4418 state->symbols->add_variable(var);
4419 }
4420 }
4421
4422 /* Convert the body of the function to HIR. */
4423 this->body->hir(&signature->body, state);
4424 signature->is_defined = true;
4425
4426 state->symbols->pop_scope();
4427
4428 assert(state->current_function == signature);
4429 state->current_function = NULL;
4430
4431 if (!signature->return_type->is_void() && !state->found_return) {
4432 YYLTYPE loc = this->get_location();
4433 _mesa_glsl_error(& loc, state, "function `%s' has non-void return type "
4434 "%s, but no return statement",
4435 signature->function_name(),
4436 signature->return_type->name);
4437 }
4438
4439 /* Function definitions do not have r-values.
4440 */
4441 return NULL;
4442 }
4443
4444
4445 ir_rvalue *
4446 ast_jump_statement::hir(exec_list *instructions,
4447 struct _mesa_glsl_parse_state *state)
4448 {
4449 void *ctx = state;
4450
4451 switch (mode) {
4452 case ast_return: {
4453 ir_return *inst;
4454 assert(state->current_function);
4455
4456 if (opt_return_value) {
4457 ir_rvalue *ret = opt_return_value->hir(instructions, state);
4458
4459 /* The value of the return type can be NULL if the shader says
4460 * 'return foo();' and foo() is a function that returns void.
4461 *
4462 * NOTE: The GLSL spec doesn't say that this is an error. The type
4463 * of the return value is void. If the return type of the function is
4464 * also void, then this should compile without error. Seriously.
4465 */
4466 const glsl_type *const ret_type =
4467 (ret == NULL) ? glsl_type::void_type : ret->type;
4468
4469 /* Implicit conversions are not allowed for return values prior to
4470 * ARB_shading_language_420pack.
4471 */
4472 if (state->current_function->return_type != ret_type) {
4473 YYLTYPE loc = this->get_location();
4474
4475 if (state->ARB_shading_language_420pack_enable) {
4476 if (!apply_implicit_conversion(state->current_function->return_type,
4477 ret, state)) {
4478 _mesa_glsl_error(& loc, state,
4479 "could not implicitly convert return value "
4480 "to %s, in function `%s'",
4481 state->current_function->return_type->name,
4482 state->current_function->function_name());
4483 }
4484 } else {
4485 _mesa_glsl_error(& loc, state,
4486 "`return' with wrong type %s, in function `%s' "
4487 "returning %s",
4488 ret_type->name,
4489 state->current_function->function_name(),
4490 state->current_function->return_type->name);
4491 }
4492 } else if (state->current_function->return_type->base_type ==
4493 GLSL_TYPE_VOID) {
4494 YYLTYPE loc = this->get_location();
4495
4496 /* The ARB_shading_language_420pack, GLSL ES 3.0, and GLSL 4.20
4497 * specs add a clarification:
4498 *
4499 * "A void function can only use return without a return argument, even if
4500 * the return argument has void type. Return statements only accept values:
4501 *
4502 * void func1() { }
4503 * void func2() { return func1(); } // illegal return statement"
4504 */
4505 _mesa_glsl_error(& loc, state,
4506 "void functions can only use `return' without a "
4507 "return argument");
4508 }
4509
4510 inst = new(ctx) ir_return(ret);
4511 } else {
4512 if (state->current_function->return_type->base_type !=
4513 GLSL_TYPE_VOID) {
4514 YYLTYPE loc = this->get_location();
4515
4516 _mesa_glsl_error(& loc, state,
4517 "`return' with no value, in function %s returning "
4518 "non-void",
4519 state->current_function->function_name());
4520 }
4521 inst = new(ctx) ir_return;
4522 }
4523
4524 state->found_return = true;
4525 instructions->push_tail(inst);
4526 break;
4527 }
4528
4529 case ast_discard:
4530 if (state->stage != MESA_SHADER_FRAGMENT) {
4531 YYLTYPE loc = this->get_location();
4532
4533 _mesa_glsl_error(& loc, state,
4534 "`discard' may only appear in a fragment shader");
4535 }
4536 instructions->push_tail(new(ctx) ir_discard);
4537 break;
4538
4539 case ast_break:
4540 case ast_continue:
4541 if (mode == ast_continue &&
4542 state->loop_nesting_ast == NULL) {
4543 YYLTYPE loc = this->get_location();
4544
4545 _mesa_glsl_error(& loc, state, "continue may only appear in a loop");
4546 } else if (mode == ast_break &&
4547 state->loop_nesting_ast == NULL &&
4548 state->switch_state.switch_nesting_ast == NULL) {
4549 YYLTYPE loc = this->get_location();
4550
4551 _mesa_glsl_error(& loc, state,
4552 "break may only appear in a loop or a switch");
4553 } else {
4554 /* For a loop, inline the for loop expression again, since we don't
4555 * know where near the end of the loop body the normal copy of it is
4556 * going to be placed. Same goes for the condition for a do-while
4557 * loop.
4558 */
4559 if (state->loop_nesting_ast != NULL &&
4560 mode == ast_continue && !state->switch_state.is_switch_innermost) {
4561 if (state->loop_nesting_ast->rest_expression) {
4562 state->loop_nesting_ast->rest_expression->hir(instructions,
4563 state);
4564 }
4565 if (state->loop_nesting_ast->mode ==
4566 ast_iteration_statement::ast_do_while) {
4567 state->loop_nesting_ast->condition_to_hir(instructions, state);
4568 }
4569 }
4570
4571 if (state->switch_state.is_switch_innermost &&
4572 mode == ast_continue) {
4573 /* Set 'continue_inside' to true. */
4574 ir_rvalue *const true_val = new (ctx) ir_constant(true);
4575 ir_dereference_variable *deref_continue_inside_var =
4576 new(ctx) ir_dereference_variable(state->switch_state.continue_inside);
4577 instructions->push_tail(new(ctx) ir_assignment(deref_continue_inside_var,
4578 true_val));
4579
4580 /* Break out from the switch, continue for the loop will
4581 * be called right after switch. */
4582 ir_loop_jump *const jump =
4583 new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
4584 instructions->push_tail(jump);
4585
4586 } else if (state->switch_state.is_switch_innermost &&
4587 mode == ast_break) {
4588 /* Force break out of switch by inserting a break. */
4589 ir_loop_jump *const jump =
4590 new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
4591 instructions->push_tail(jump);
4592 } else {
4593 ir_loop_jump *const jump =
4594 new(ctx) ir_loop_jump((mode == ast_break)
4595 ? ir_loop_jump::jump_break
4596 : ir_loop_jump::jump_continue);
4597 instructions->push_tail(jump);
4598 }
4599 }
4600
4601 break;
4602 }
4603
4604 /* Jump instructions do not have r-values.
4605 */
4606 return NULL;
4607 }
4608
4609
4610 ir_rvalue *
4611 ast_selection_statement::hir(exec_list *instructions,
4612 struct _mesa_glsl_parse_state *state)
4613 {
4614 void *ctx = state;
4615
4616 ir_rvalue *const condition = this->condition->hir(instructions, state);
4617
4618 /* From page 66 (page 72 of the PDF) of the GLSL 1.50 spec:
4619 *
4620 * "Any expression whose type evaluates to a Boolean can be used as the
4621 * conditional expression bool-expression. Vector types are not accepted
4622 * as the expression to if."
4623 *
4624 * The checks are separated so that higher quality diagnostics can be
4625 * generated for cases where both rules are violated.
4626 */
4627 if (!condition->type->is_boolean() || !condition->type->is_scalar()) {
4628 YYLTYPE loc = this->condition->get_location();
4629
4630 _mesa_glsl_error(& loc, state, "if-statement condition must be scalar "
4631 "boolean");
4632 }
4633
4634 ir_if *const stmt = new(ctx) ir_if(condition);
4635
4636 if (then_statement != NULL) {
4637 state->symbols->push_scope();
4638 then_statement->hir(& stmt->then_instructions, state);
4639 state->symbols->pop_scope();
4640 }
4641
4642 if (else_statement != NULL) {
4643 state->symbols->push_scope();
4644 else_statement->hir(& stmt->else_instructions, state);
4645 state->symbols->pop_scope();
4646 }
4647
4648 instructions->push_tail(stmt);
4649
4650 /* if-statements do not have r-values.
4651 */
4652 return NULL;
4653 }
4654
4655
4656 ir_rvalue *
4657 ast_switch_statement::hir(exec_list *instructions,
4658 struct _mesa_glsl_parse_state *state)
4659 {
4660 void *ctx = state;
4661
4662 ir_rvalue *const test_expression =
4663 this->test_expression->hir(instructions, state);
4664
4665 /* From page 66 (page 55 of the PDF) of the GLSL 1.50 spec:
4666 *
4667 * "The type of init-expression in a switch statement must be a
4668 * scalar integer."
4669 */
4670 if (!test_expression->type->is_scalar() ||
4671 !test_expression->type->is_integer()) {
4672 YYLTYPE loc = this->test_expression->get_location();
4673
4674 _mesa_glsl_error(& loc,
4675 state,
4676 "switch-statement expression must be scalar "
4677 "integer");
4678 }
4679
4680 /* Track the switch-statement nesting in a stack-like manner.
4681 */
4682 struct glsl_switch_state saved = state->switch_state;
4683
4684 state->switch_state.is_switch_innermost = true;
4685 state->switch_state.switch_nesting_ast = this;
4686 state->switch_state.labels_ht = hash_table_ctor(0, hash_table_pointer_hash,
4687 hash_table_pointer_compare);
4688 state->switch_state.previous_default = NULL;
4689
4690 /* Initalize is_fallthru state to false.
4691 */
4692 ir_rvalue *const is_fallthru_val = new (ctx) ir_constant(false);
4693 state->switch_state.is_fallthru_var =
4694 new(ctx) ir_variable(glsl_type::bool_type,
4695 "switch_is_fallthru_tmp",
4696 ir_var_temporary);
4697 instructions->push_tail(state->switch_state.is_fallthru_var);
4698
4699 ir_dereference_variable *deref_is_fallthru_var =
4700 new(ctx) ir_dereference_variable(state->switch_state.is_fallthru_var);
4701 instructions->push_tail(new(ctx) ir_assignment(deref_is_fallthru_var,
4702 is_fallthru_val));
4703
4704 /* Initialize continue_inside state to false.
4705 */
4706 state->switch_state.continue_inside =
4707 new(ctx) ir_variable(glsl_type::bool_type,
4708 "continue_inside_tmp",
4709 ir_var_temporary);
4710 instructions->push_tail(state->switch_state.continue_inside);
4711
4712 ir_rvalue *const false_val = new (ctx) ir_constant(false);
4713 ir_dereference_variable *deref_continue_inside_var =
4714 new(ctx) ir_dereference_variable(state->switch_state.continue_inside);
4715 instructions->push_tail(new(ctx) ir_assignment(deref_continue_inside_var,
4716 false_val));
4717
4718 state->switch_state.run_default =
4719 new(ctx) ir_variable(glsl_type::bool_type,
4720 "run_default_tmp",
4721 ir_var_temporary);
4722 instructions->push_tail(state->switch_state.run_default);
4723
4724 /* Loop around the switch is used for flow control. */
4725 ir_loop * loop = new(ctx) ir_loop();
4726 instructions->push_tail(loop);
4727
4728 /* Cache test expression.
4729 */
4730 test_to_hir(&loop->body_instructions, state);
4731
4732 /* Emit code for body of switch stmt.
4733 */
4734 body->hir(&loop->body_instructions, state);
4735
4736 /* Insert a break at the end to exit loop. */
4737 ir_loop_jump *jump = new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
4738 loop->body_instructions.push_tail(jump);
4739
4740 /* If we are inside loop, check if continue got called inside switch. */
4741 if (state->loop_nesting_ast != NULL) {
4742 ir_dereference_variable *deref_continue_inside =
4743 new(ctx) ir_dereference_variable(state->switch_state.continue_inside);
4744 ir_if *irif = new(ctx) ir_if(deref_continue_inside);
4745 ir_loop_jump *jump = new(ctx) ir_loop_jump(ir_loop_jump::jump_continue);
4746
4747 if (state->loop_nesting_ast != NULL) {
4748 if (state->loop_nesting_ast->rest_expression) {
4749 state->loop_nesting_ast->rest_expression->hir(&irif->then_instructions,
4750 state);
4751 }
4752 if (state->loop_nesting_ast->mode ==
4753 ast_iteration_statement::ast_do_while) {
4754 state->loop_nesting_ast->condition_to_hir(&irif->then_instructions, state);
4755 }
4756 }
4757 irif->then_instructions.push_tail(jump);
4758 instructions->push_tail(irif);
4759 }
4760
4761 hash_table_dtor(state->switch_state.labels_ht);
4762
4763 state->switch_state = saved;
4764
4765 /* Switch statements do not have r-values. */
4766 return NULL;
4767 }
4768
4769
4770 void
4771 ast_switch_statement::test_to_hir(exec_list *instructions,
4772 struct _mesa_glsl_parse_state *state)
4773 {
4774 void *ctx = state;
4775
4776 /* Cache value of test expression. */
4777 ir_rvalue *const test_val =
4778 test_expression->hir(instructions,
4779 state);
4780
4781 state->switch_state.test_var = new(ctx) ir_variable(test_val->type,
4782 "switch_test_tmp",
4783 ir_var_temporary);
4784 ir_dereference_variable *deref_test_var =
4785 new(ctx) ir_dereference_variable(state->switch_state.test_var);
4786
4787 instructions->push_tail(state->switch_state.test_var);
4788 instructions->push_tail(new(ctx) ir_assignment(deref_test_var, test_val));
4789 }
4790
4791
4792 ir_rvalue *
4793 ast_switch_body::hir(exec_list *instructions,
4794 struct _mesa_glsl_parse_state *state)
4795 {
4796 if (stmts != NULL)
4797 stmts->hir(instructions, state);
4798
4799 /* Switch bodies do not have r-values. */
4800 return NULL;
4801 }
4802
4803 ir_rvalue *
4804 ast_case_statement_list::hir(exec_list *instructions,
4805 struct _mesa_glsl_parse_state *state)
4806 {
4807 exec_list default_case, after_default, tmp;
4808
4809 foreach_list_typed (ast_case_statement, case_stmt, link, & this->cases) {
4810 case_stmt->hir(&tmp, state);
4811
4812 /* Default case. */
4813 if (state->switch_state.previous_default && default_case.is_empty()) {
4814 default_case.append_list(&tmp);
4815 continue;
4816 }
4817
4818 /* If default case found, append 'after_default' list. */
4819 if (!default_case.is_empty())
4820 after_default.append_list(&tmp);
4821 else
4822 instructions->append_list(&tmp);
4823 }
4824
4825 /* Handle the default case. This is done here because default might not be
4826 * the last case. We need to add checks against following cases first to see
4827 * if default should be chosen or not.
4828 */
4829 if (!default_case.is_empty()) {
4830
4831 ir_rvalue *const true_val = new (state) ir_constant(true);
4832 ir_dereference_variable *deref_run_default_var =
4833 new(state) ir_dereference_variable(state->switch_state.run_default);
4834
4835 /* Choose to run default case initially, following conditional
4836 * assignments might change this.
4837 */
4838 ir_assignment *const init_var =
4839 new(state) ir_assignment(deref_run_default_var, true_val);
4840 instructions->push_tail(init_var);
4841
4842 /* Default case was the last one, no checks required. */
4843 if (after_default.is_empty()) {
4844 instructions->append_list(&default_case);
4845 return NULL;
4846 }
4847
4848 foreach_in_list(ir_instruction, ir, &after_default) {
4849 ir_assignment *assign = ir->as_assignment();
4850
4851 if (!assign)
4852 continue;
4853
4854 /* Clone the check between case label and init expression. */
4855 ir_expression *exp = (ir_expression*) assign->condition;
4856 ir_expression *clone = exp->clone(state, NULL);
4857
4858 ir_dereference_variable *deref_var =
4859 new(state) ir_dereference_variable(state->switch_state.run_default);
4860 ir_rvalue *const false_val = new (state) ir_constant(false);
4861
4862 ir_assignment *const set_false =
4863 new(state) ir_assignment(deref_var, false_val, clone);
4864
4865 instructions->push_tail(set_false);
4866 }
4867
4868 /* Append default case and all cases after it. */
4869 instructions->append_list(&default_case);
4870 instructions->append_list(&after_default);
4871 }
4872
4873 /* Case statements do not have r-values. */
4874 return NULL;
4875 }
4876
4877 ir_rvalue *
4878 ast_case_statement::hir(exec_list *instructions,
4879 struct _mesa_glsl_parse_state *state)
4880 {
4881 labels->hir(instructions, state);
4882
4883 /* Guard case statements depending on fallthru state. */
4884 ir_dereference_variable *const deref_fallthru_guard =
4885 new(state) ir_dereference_variable(state->switch_state.is_fallthru_var);
4886 ir_if *const test_fallthru = new(state) ir_if(deref_fallthru_guard);
4887
4888 foreach_list_typed (ast_node, stmt, link, & this->stmts)
4889 stmt->hir(& test_fallthru->then_instructions, state);
4890
4891 instructions->push_tail(test_fallthru);
4892
4893 /* Case statements do not have r-values. */
4894 return NULL;
4895 }
4896
4897
4898 ir_rvalue *
4899 ast_case_label_list::hir(exec_list *instructions,
4900 struct _mesa_glsl_parse_state *state)
4901 {
4902 foreach_list_typed (ast_case_label, label, link, & this->labels)
4903 label->hir(instructions, state);
4904
4905 /* Case labels do not have r-values. */
4906 return NULL;
4907 }
4908
4909 ir_rvalue *
4910 ast_case_label::hir(exec_list *instructions,
4911 struct _mesa_glsl_parse_state *state)
4912 {
4913 void *ctx = state;
4914
4915 ir_dereference_variable *deref_fallthru_var =
4916 new(ctx) ir_dereference_variable(state->switch_state.is_fallthru_var);
4917
4918 ir_rvalue *const true_val = new(ctx) ir_constant(true);
4919
4920 /* If not default case, ... */
4921 if (this->test_value != NULL) {
4922 /* Conditionally set fallthru state based on
4923 * comparison of cached test expression value to case label.
4924 */
4925 ir_rvalue *const label_rval = this->test_value->hir(instructions, state);
4926 ir_constant *label_const = label_rval->constant_expression_value();
4927
4928 if (!label_const) {
4929 YYLTYPE loc = this->test_value->get_location();
4930
4931 _mesa_glsl_error(& loc, state,
4932 "switch statement case label must be a "
4933 "constant expression");
4934
4935 /* Stuff a dummy value in to allow processing to continue. */
4936 label_const = new(ctx) ir_constant(0);
4937 } else {
4938 ast_expression *previous_label = (ast_expression *)
4939 hash_table_find(state->switch_state.labels_ht,
4940 (void *)(uintptr_t)label_const->value.u[0]);
4941
4942 if (previous_label) {
4943 YYLTYPE loc = this->test_value->get_location();
4944 _mesa_glsl_error(& loc, state, "duplicate case value");
4945
4946 loc = previous_label->get_location();
4947 _mesa_glsl_error(& loc, state, "this is the previous case label");
4948 } else {
4949 hash_table_insert(state->switch_state.labels_ht,
4950 this->test_value,
4951 (void *)(uintptr_t)label_const->value.u[0]);
4952 }
4953 }
4954
4955 ir_dereference_variable *deref_test_var =
4956 new(ctx) ir_dereference_variable(state->switch_state.test_var);
4957
4958 ir_expression *test_cond = new(ctx) ir_expression(ir_binop_all_equal,
4959 label_const,
4960 deref_test_var);
4961
4962 /*
4963 * From GLSL 4.40 specification section 6.2 ("Selection"):
4964 *
4965 * "The type of the init-expression value in a switch statement must
4966 * be a scalar int or uint. The type of the constant-expression value
4967 * in a case label also must be a scalar int or uint. When any pair
4968 * of these values is tested for "equal value" and the types do not
4969 * match, an implicit conversion will be done to convert the int to a
4970 * uint (see section 4.1.10 “Implicit Conversions”) before the compare
4971 * is done."
4972 */
4973 if (label_const->type != state->switch_state.test_var->type) {
4974 YYLTYPE loc = this->test_value->get_location();
4975
4976 const glsl_type *type_a = label_const->type;
4977 const glsl_type *type_b = state->switch_state.test_var->type;
4978
4979 /* Check if int->uint implicit conversion is supported. */
4980 bool integer_conversion_supported =
4981 glsl_type::int_type->can_implicitly_convert_to(glsl_type::uint_type,
4982 state);
4983
4984 if ((!type_a->is_integer() || !type_b->is_integer()) ||
4985 !integer_conversion_supported) {
4986 _mesa_glsl_error(&loc, state, "type mismatch with switch "
4987 "init-expression and case label (%s != %s)",
4988 type_a->name, type_b->name);
4989 } else {
4990 /* Conversion of the case label. */
4991 if (type_a->base_type == GLSL_TYPE_INT) {
4992 if (!apply_implicit_conversion(glsl_type::uint_type,
4993 test_cond->operands[0], state))
4994 _mesa_glsl_error(&loc, state, "implicit type conversion error");
4995 } else {
4996 /* Conversion of the init-expression value. */
4997 if (!apply_implicit_conversion(glsl_type::uint_type,
4998 test_cond->operands[1], state))
4999 _mesa_glsl_error(&loc, state, "implicit type conversion error");
5000 }
5001 }
5002 }
5003
5004 ir_assignment *set_fallthru_on_test =
5005 new(ctx) ir_assignment(deref_fallthru_var, true_val, test_cond);
5006
5007 instructions->push_tail(set_fallthru_on_test);
5008 } else { /* default case */
5009 if (state->switch_state.previous_default) {
5010 YYLTYPE loc = this->get_location();
5011 _mesa_glsl_error(& loc, state,
5012 "multiple default labels in one switch");
5013
5014 loc = state->switch_state.previous_default->get_location();
5015 _mesa_glsl_error(& loc, state, "this is the first default label");
5016 }
5017 state->switch_state.previous_default = this;
5018
5019 /* Set fallthru condition on 'run_default' bool. */
5020 ir_dereference_variable *deref_run_default =
5021 new(ctx) ir_dereference_variable(state->switch_state.run_default);
5022 ir_rvalue *const cond_true = new(ctx) ir_constant(true);
5023 ir_expression *test_cond = new(ctx) ir_expression(ir_binop_all_equal,
5024 cond_true,
5025 deref_run_default);
5026
5027 /* Set falltrhu state. */
5028 ir_assignment *set_fallthru =
5029 new(ctx) ir_assignment(deref_fallthru_var, true_val, test_cond);
5030
5031 instructions->push_tail(set_fallthru);
5032 }
5033
5034 /* Case statements do not have r-values. */
5035 return NULL;
5036 }
5037
5038 void
5039 ast_iteration_statement::condition_to_hir(exec_list *instructions,
5040 struct _mesa_glsl_parse_state *state)
5041 {
5042 void *ctx = state;
5043
5044 if (condition != NULL) {
5045 ir_rvalue *const cond =
5046 condition->hir(instructions, state);
5047
5048 if ((cond == NULL)
5049 || !cond->type->is_boolean() || !cond->type->is_scalar()) {
5050 YYLTYPE loc = condition->get_location();
5051
5052 _mesa_glsl_error(& loc, state,
5053 "loop condition must be scalar boolean");
5054 } else {
5055 /* As the first code in the loop body, generate a block that looks
5056 * like 'if (!condition) break;' as the loop termination condition.
5057 */
5058 ir_rvalue *const not_cond =
5059 new(ctx) ir_expression(ir_unop_logic_not, cond);
5060
5061 ir_if *const if_stmt = new(ctx) ir_if(not_cond);
5062
5063 ir_jump *const break_stmt =
5064 new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
5065
5066 if_stmt->then_instructions.push_tail(break_stmt);
5067 instructions->push_tail(if_stmt);
5068 }
5069 }
5070 }
5071
5072
5073 ir_rvalue *
5074 ast_iteration_statement::hir(exec_list *instructions,
5075 struct _mesa_glsl_parse_state *state)
5076 {
5077 void *ctx = state;
5078
5079 /* For-loops and while-loops start a new scope, but do-while loops do not.
5080 */
5081 if (mode != ast_do_while)
5082 state->symbols->push_scope();
5083
5084 if (init_statement != NULL)
5085 init_statement->hir(instructions, state);
5086
5087 ir_loop *const stmt = new(ctx) ir_loop();
5088 instructions->push_tail(stmt);
5089
5090 /* Track the current loop nesting. */
5091 ast_iteration_statement *nesting_ast = state->loop_nesting_ast;
5092
5093 state->loop_nesting_ast = this;
5094
5095 /* Likewise, indicate that following code is closest to a loop,
5096 * NOT closest to a switch.
5097 */
5098 bool saved_is_switch_innermost = state->switch_state.is_switch_innermost;
5099 state->switch_state.is_switch_innermost = false;
5100
5101 if (mode != ast_do_while)
5102 condition_to_hir(&stmt->body_instructions, state);
5103
5104 if (body != NULL)
5105 body->hir(& stmt->body_instructions, state);
5106
5107 if (rest_expression != NULL)
5108 rest_expression->hir(& stmt->body_instructions, state);
5109
5110 if (mode == ast_do_while)
5111 condition_to_hir(&stmt->body_instructions, state);
5112
5113 if (mode != ast_do_while)
5114 state->symbols->pop_scope();
5115
5116 /* Restore previous nesting before returning. */
5117 state->loop_nesting_ast = nesting_ast;
5118 state->switch_state.is_switch_innermost = saved_is_switch_innermost;
5119
5120 /* Loops do not have r-values.
5121 */
5122 return NULL;
5123 }
5124
5125
5126 /**
5127 * Determine if the given type is valid for establishing a default precision
5128 * qualifier.
5129 *
5130 * From GLSL ES 3.00 section 4.5.4 ("Default Precision Qualifiers"):
5131 *
5132 * "The precision statement
5133 *
5134 * precision precision-qualifier type;
5135 *
5136 * can be used to establish a default precision qualifier. The type field
5137 * can be either int or float or any of the sampler types, and the
5138 * precision-qualifier can be lowp, mediump, or highp."
5139 *
5140 * GLSL ES 1.00 has similar language. GLSL 1.30 doesn't allow precision
5141 * qualifiers on sampler types, but this seems like an oversight (since the
5142 * intention of including these in GLSL 1.30 is to allow compatibility with ES
5143 * shaders). So we allow int, float, and all sampler types regardless of GLSL
5144 * version.
5145 */
5146 static bool
5147 is_valid_default_precision_type(const struct glsl_type *const type)
5148 {
5149 if (type == NULL)
5150 return false;
5151
5152 switch (type->base_type) {
5153 case GLSL_TYPE_INT:
5154 case GLSL_TYPE_FLOAT:
5155 /* "int" and "float" are valid, but vectors and matrices are not. */
5156 return type->vector_elements == 1 && type->matrix_columns == 1;
5157 case GLSL_TYPE_SAMPLER:
5158 return true;
5159 default:
5160 return false;
5161 }
5162 }
5163
5164
5165 ir_rvalue *
5166 ast_type_specifier::hir(exec_list *instructions,
5167 struct _mesa_glsl_parse_state *state)
5168 {
5169 if (this->default_precision == ast_precision_none && this->structure == NULL)
5170 return NULL;
5171
5172 YYLTYPE loc = this->get_location();
5173
5174 /* If this is a precision statement, check that the type to which it is
5175 * applied is either float or int.
5176 *
5177 * From section 4.5.3 of the GLSL 1.30 spec:
5178 * "The precision statement
5179 * precision precision-qualifier type;
5180 * can be used to establish a default precision qualifier. The type
5181 * field can be either int or float [...]. Any other types or
5182 * qualifiers will result in an error.
5183 */
5184 if (this->default_precision != ast_precision_none) {
5185 if (!state->check_precision_qualifiers_allowed(&loc))
5186 return NULL;
5187
5188 if (this->structure != NULL) {
5189 _mesa_glsl_error(&loc, state,
5190 "precision qualifiers do not apply to structures");
5191 return NULL;
5192 }
5193
5194 if (this->array_specifier != NULL) {
5195 _mesa_glsl_error(&loc, state,
5196 "default precision statements do not apply to "
5197 "arrays");
5198 return NULL;
5199 }
5200
5201 const struct glsl_type *const type =
5202 state->symbols->get_type(this->type_name);
5203 if (!is_valid_default_precision_type(type)) {
5204 _mesa_glsl_error(&loc, state,
5205 "default precision statements apply only to "
5206 "float, int, and sampler types");
5207 return NULL;
5208 }
5209
5210 if (type->base_type == GLSL_TYPE_FLOAT
5211 && state->es_shader
5212 && state->stage == MESA_SHADER_FRAGMENT) {
5213 /* Section 4.5.3 (Default Precision Qualifiers) of the GLSL ES 1.00
5214 * spec says:
5215 *
5216 * "The fragment language has no default precision qualifier for
5217 * floating point types."
5218 *
5219 * As a result, we have to track whether or not default precision has
5220 * been specified for float in GLSL ES fragment shaders.
5221 *
5222 * Earlier in that same section, the spec says:
5223 *
5224 * "Non-precision qualified declarations will use the precision
5225 * qualifier specified in the most recent precision statement
5226 * that is still in scope. The precision statement has the same
5227 * scoping rules as variable declarations. If it is declared
5228 * inside a compound statement, its effect stops at the end of
5229 * the innermost statement it was declared in. Precision
5230 * statements in nested scopes override precision statements in
5231 * outer scopes. Multiple precision statements for the same basic
5232 * type can appear inside the same scope, with later statements
5233 * overriding earlier statements within that scope."
5234 *
5235 * Default precision specifications follow the same scope rules as
5236 * variables. So, we can track the state of the default float
5237 * precision in the symbol table, and the rules will just work. This
5238 * is a slight abuse of the symbol table, but it has the semantics
5239 * that we want.
5240 */
5241 ir_variable *const junk =
5242 new(state) ir_variable(type, "#default precision",
5243 ir_var_auto);
5244
5245 state->symbols->add_variable(junk);
5246 }
5247
5248 /* FINISHME: Translate precision statements into IR. */
5249 return NULL;
5250 }
5251
5252 /* _mesa_ast_set_aggregate_type() sets the <structure> field so that
5253 * process_record_constructor() can do type-checking on C-style initializer
5254 * expressions of structs, but ast_struct_specifier should only be translated
5255 * to HIR if it is declaring the type of a structure.
5256 *
5257 * The ->is_declaration field is false for initializers of variables
5258 * declared separately from the struct's type definition.
5259 *
5260 * struct S { ... }; (is_declaration = true)
5261 * struct T { ... } t = { ... }; (is_declaration = true)
5262 * S s = { ... }; (is_declaration = false)
5263 */
5264 if (this->structure != NULL && this->structure->is_declaration)
5265 return this->structure->hir(instructions, state);
5266
5267 return NULL;
5268 }
5269
5270
5271 /**
5272 * Process a structure or interface block tree into an array of structure fields
5273 *
5274 * After parsing, where there are some syntax differnces, structures and
5275 * interface blocks are almost identical. They are similar enough that the
5276 * AST for each can be processed the same way into a set of
5277 * \c glsl_struct_field to describe the members.
5278 *
5279 * If we're processing an interface block, var_mode should be the type of the
5280 * interface block (ir_var_shader_in, ir_var_shader_out, or ir_var_uniform).
5281 * If we're processing a structure, var_mode should be ir_var_auto.
5282 *
5283 * \return
5284 * The number of fields processed. A pointer to the array structure fields is
5285 * stored in \c *fields_ret.
5286 */
5287 unsigned
5288 ast_process_structure_or_interface_block(exec_list *instructions,
5289 struct _mesa_glsl_parse_state *state,
5290 exec_list *declarations,
5291 YYLTYPE &loc,
5292 glsl_struct_field **fields_ret,
5293 bool is_interface,
5294 enum glsl_matrix_layout matrix_layout,
5295 bool allow_reserved_names,
5296 ir_variable_mode var_mode)
5297 {
5298 unsigned decl_count = 0;
5299
5300 /* Make an initial pass over the list of fields to determine how
5301 * many there are. Each element in this list is an ast_declarator_list.
5302 * This means that we actually need to count the number of elements in the
5303 * 'declarations' list in each of the elements.
5304 */
5305 foreach_list_typed (ast_declarator_list, decl_list, link, declarations) {
5306 decl_count += decl_list->declarations.length();
5307 }
5308
5309 /* Allocate storage for the fields and process the field
5310 * declarations. As the declarations are processed, try to also convert
5311 * the types to HIR. This ensures that structure definitions embedded in
5312 * other structure definitions or in interface blocks are processed.
5313 */
5314 glsl_struct_field *const fields = ralloc_array(state, glsl_struct_field,
5315 decl_count);
5316
5317 unsigned i = 0;
5318 foreach_list_typed (ast_declarator_list, decl_list, link, declarations) {
5319 const char *type_name;
5320
5321 decl_list->type->specifier->hir(instructions, state);
5322
5323 /* Section 10.9 of the GLSL ES 1.00 specification states that
5324 * embedded structure definitions have been removed from the language.
5325 */
5326 if (state->es_shader && decl_list->type->specifier->structure != NULL) {
5327 _mesa_glsl_error(&loc, state, "embedded structure definitions are "
5328 "not allowed in GLSL ES 1.00");
5329 }
5330
5331 const glsl_type *decl_type =
5332 decl_list->type->glsl_type(& type_name, state);
5333
5334 foreach_list_typed (ast_declaration, decl, link,
5335 &decl_list->declarations) {
5336 if (!allow_reserved_names)
5337 validate_identifier(decl->identifier, loc, state);
5338
5339 /* From section 4.3.9 of the GLSL 4.40 spec:
5340 *
5341 * "[In interface blocks] opaque types are not allowed."
5342 *
5343 * It should be impossible for decl_type to be NULL here. Cases that
5344 * might naturally lead to decl_type being NULL, especially for the
5345 * is_interface case, will have resulted in compilation having
5346 * already halted due to a syntax error.
5347 */
5348 const struct glsl_type *field_type =
5349 decl_type != NULL ? decl_type : glsl_type::error_type;
5350
5351 if (is_interface && field_type->contains_opaque()) {
5352 YYLTYPE loc = decl_list->get_location();
5353 _mesa_glsl_error(&loc, state,
5354 "uniform in non-default uniform block contains "
5355 "opaque variable");
5356 }
5357
5358 if (field_type->contains_atomic()) {
5359 /* FINISHME: Add a spec quotation here once updated spec
5360 * FINISHME: language is available. See Khronos bug #10903
5361 * FINISHME: on whether atomic counters are allowed in
5362 * FINISHME: structures.
5363 */
5364 YYLTYPE loc = decl_list->get_location();
5365 _mesa_glsl_error(&loc, state, "atomic counter in structure or "
5366 "uniform block");
5367 }
5368
5369 if (field_type->contains_image()) {
5370 /* FINISHME: Same problem as with atomic counters.
5371 * FINISHME: Request clarification from Khronos and add
5372 * FINISHME: spec quotation here.
5373 */
5374 YYLTYPE loc = decl_list->get_location();
5375 _mesa_glsl_error(&loc, state,
5376 "image in structure or uniform block");
5377 }
5378
5379 const struct ast_type_qualifier *const qual =
5380 & decl_list->type->qualifier;
5381 if (qual->flags.q.std140 ||
5382 qual->flags.q.packed ||
5383 qual->flags.q.shared) {
5384 _mesa_glsl_error(&loc, state,
5385 "uniform block layout qualifiers std140, packed, and "
5386 "shared can only be applied to uniform blocks, not "
5387 "members");
5388 }
5389
5390 if (qual->flags.q.constant) {
5391 YYLTYPE loc = decl_list->get_location();
5392 _mesa_glsl_error(&loc, state,
5393 "const storage qualifier cannot be applied "
5394 "to struct or interface block members");
5395 }
5396
5397 field_type = process_array_type(&loc, decl_type,
5398 decl->array_specifier, state);
5399 fields[i].type = field_type;
5400 fields[i].name = decl->identifier;
5401 fields[i].location = -1;
5402 fields[i].interpolation =
5403 interpret_interpolation_qualifier(qual, var_mode, state, &loc);
5404 fields[i].centroid = qual->flags.q.centroid ? 1 : 0;
5405 fields[i].sample = qual->flags.q.sample ? 1 : 0;
5406
5407 /* Only save explicitly defined streams in block's field */
5408 fields[i].stream = qual->flags.q.explicit_stream ? qual->stream : -1;
5409
5410 if (qual->flags.q.row_major || qual->flags.q.column_major) {
5411 if (!qual->flags.q.uniform) {
5412 _mesa_glsl_error(&loc, state,
5413 "row_major and column_major can only be "
5414 "applied to uniform interface blocks");
5415 } else
5416 validate_matrix_layout_for_type(state, &loc, field_type, NULL);
5417 }
5418
5419 if (qual->flags.q.uniform && qual->has_interpolation()) {
5420 _mesa_glsl_error(&loc, state,
5421 "interpolation qualifiers cannot be used "
5422 "with uniform interface blocks");
5423 }
5424
5425 if ((qual->flags.q.uniform || !is_interface) &&
5426 qual->has_auxiliary_storage()) {
5427 _mesa_glsl_error(&loc, state,
5428 "auxiliary storage qualifiers cannot be used "
5429 "in uniform blocks or structures.");
5430 }
5431
5432 /* Propogate row- / column-major information down the fields of the
5433 * structure or interface block. Structures need this data because
5434 * the structure may contain a structure that contains ... a matrix
5435 * that need the proper layout.
5436 */
5437 if (field_type->without_array()->is_matrix()
5438 || field_type->without_array()->is_record()) {
5439 /* If no layout is specified for the field, inherit the layout
5440 * from the block.
5441 */
5442 fields[i].matrix_layout = matrix_layout;
5443
5444 if (qual->flags.q.row_major)
5445 fields[i].matrix_layout = GLSL_MATRIX_LAYOUT_ROW_MAJOR;
5446 else if (qual->flags.q.column_major)
5447 fields[i].matrix_layout = GLSL_MATRIX_LAYOUT_COLUMN_MAJOR;
5448
5449 /* If we're processing an interface block, the matrix layout must
5450 * be decided by this point.
5451 */
5452 assert(!is_interface
5453 || fields[i].matrix_layout == GLSL_MATRIX_LAYOUT_ROW_MAJOR
5454 || fields[i].matrix_layout == GLSL_MATRIX_LAYOUT_COLUMN_MAJOR);
5455 }
5456
5457 i++;
5458 }
5459 }
5460
5461 assert(i == decl_count);
5462
5463 *fields_ret = fields;
5464 return decl_count;
5465 }
5466
5467
5468 ir_rvalue *
5469 ast_struct_specifier::hir(exec_list *instructions,
5470 struct _mesa_glsl_parse_state *state)
5471 {
5472 YYLTYPE loc = this->get_location();
5473
5474 /* Section 4.1.8 (Structures) of the GLSL 1.10 spec says:
5475 *
5476 * "Anonymous structures are not supported; so embedded structures must
5477 * have a declarator. A name given to an embedded struct is scoped at
5478 * the same level as the struct it is embedded in."
5479 *
5480 * The same section of the GLSL 1.20 spec says:
5481 *
5482 * "Anonymous structures are not supported. Embedded structures are not
5483 * supported.
5484 *
5485 * struct S { float f; };
5486 * struct T {
5487 * S; // Error: anonymous structures disallowed
5488 * struct { ... }; // Error: embedded structures disallowed
5489 * S s; // Okay: nested structures with name are allowed
5490 * };"
5491 *
5492 * The GLSL ES 1.00 and 3.00 specs have similar langauge and examples. So,
5493 * we allow embedded structures in 1.10 only.
5494 */
5495 if (state->language_version != 110 && state->struct_specifier_depth != 0)
5496 _mesa_glsl_error(&loc, state,
5497 "embedded structure declarations are not allowed");
5498
5499 state->struct_specifier_depth++;
5500
5501 glsl_struct_field *fields;
5502 unsigned decl_count =
5503 ast_process_structure_or_interface_block(instructions,
5504 state,
5505 &this->declarations,
5506 loc,
5507 &fields,
5508 false,
5509 GLSL_MATRIX_LAYOUT_INHERITED,
5510 false /* allow_reserved_names */,
5511 ir_var_auto);
5512
5513 validate_identifier(this->name, loc, state);
5514
5515 const glsl_type *t =
5516 glsl_type::get_record_instance(fields, decl_count, this->name);
5517
5518 if (!state->symbols->add_type(name, t)) {
5519 _mesa_glsl_error(& loc, state, "struct `%s' previously defined", name);
5520 } else {
5521 const glsl_type **s = reralloc(state, state->user_structures,
5522 const glsl_type *,
5523 state->num_user_structures + 1);
5524 if (s != NULL) {
5525 s[state->num_user_structures] = t;
5526 state->user_structures = s;
5527 state->num_user_structures++;
5528 }
5529 }
5530
5531 state->struct_specifier_depth--;
5532
5533 /* Structure type definitions do not have r-values.
5534 */
5535 return NULL;
5536 }
5537
5538
5539 /**
5540 * Visitor class which detects whether a given interface block has been used.
5541 */
5542 class interface_block_usage_visitor : public ir_hierarchical_visitor
5543 {
5544 public:
5545 interface_block_usage_visitor(ir_variable_mode mode, const glsl_type *block)
5546 : mode(mode), block(block), found(false)
5547 {
5548 }
5549
5550 virtual ir_visitor_status visit(ir_dereference_variable *ir)
5551 {
5552 if (ir->var->data.mode == mode && ir->var->get_interface_type() == block) {
5553 found = true;
5554 return visit_stop;
5555 }
5556 return visit_continue;
5557 }
5558
5559 bool usage_found() const
5560 {
5561 return this->found;
5562 }
5563
5564 private:
5565 ir_variable_mode mode;
5566 const glsl_type *block;
5567 bool found;
5568 };
5569
5570
5571 ir_rvalue *
5572 ast_interface_block::hir(exec_list *instructions,
5573 struct _mesa_glsl_parse_state *state)
5574 {
5575 YYLTYPE loc = this->get_location();
5576
5577 /* Interface blocks must be declared at global scope */
5578 if (state->current_function != NULL) {
5579 _mesa_glsl_error(&loc, state,
5580 "Interface block `%s' must be declared "
5581 "at global scope",
5582 this->block_name);
5583 }
5584
5585 /* The ast_interface_block has a list of ast_declarator_lists. We
5586 * need to turn those into ir_variables with an association
5587 * with this uniform block.
5588 */
5589 enum glsl_interface_packing packing;
5590 if (this->layout.flags.q.shared) {
5591 packing = GLSL_INTERFACE_PACKING_SHARED;
5592 } else if (this->layout.flags.q.packed) {
5593 packing = GLSL_INTERFACE_PACKING_PACKED;
5594 } else {
5595 /* The default layout is std140.
5596 */
5597 packing = GLSL_INTERFACE_PACKING_STD140;
5598 }
5599
5600 ir_variable_mode var_mode;
5601 const char *iface_type_name;
5602 if (this->layout.flags.q.in) {
5603 var_mode = ir_var_shader_in;
5604 iface_type_name = "in";
5605 } else if (this->layout.flags.q.out) {
5606 var_mode = ir_var_shader_out;
5607 iface_type_name = "out";
5608 } else if (this->layout.flags.q.uniform) {
5609 var_mode = ir_var_uniform;
5610 iface_type_name = "uniform";
5611 } else {
5612 var_mode = ir_var_auto;
5613 iface_type_name = "UNKNOWN";
5614 assert(!"interface block layout qualifier not found!");
5615 }
5616
5617 enum glsl_matrix_layout matrix_layout = GLSL_MATRIX_LAYOUT_INHERITED;
5618 if (this->layout.flags.q.row_major)
5619 matrix_layout = GLSL_MATRIX_LAYOUT_ROW_MAJOR;
5620 else if (this->layout.flags.q.column_major)
5621 matrix_layout = GLSL_MATRIX_LAYOUT_COLUMN_MAJOR;
5622
5623 bool redeclaring_per_vertex = strcmp(this->block_name, "gl_PerVertex") == 0;
5624 exec_list declared_variables;
5625 glsl_struct_field *fields;
5626
5627 /* Treat an interface block as one level of nesting, so that embedded struct
5628 * specifiers will be disallowed.
5629 */
5630 state->struct_specifier_depth++;
5631
5632 unsigned int num_variables =
5633 ast_process_structure_or_interface_block(&declared_variables,
5634 state,
5635 &this->declarations,
5636 loc,
5637 &fields,
5638 true,
5639 matrix_layout,
5640 redeclaring_per_vertex,
5641 var_mode);
5642
5643 state->struct_specifier_depth--;
5644
5645 if (!redeclaring_per_vertex) {
5646 validate_identifier(this->block_name, loc, state);
5647
5648 /* From section 4.3.9 ("Interface Blocks") of the GLSL 4.50 spec:
5649 *
5650 * "Block names have no other use within a shader beyond interface
5651 * matching; it is a compile-time error to use a block name at global
5652 * scope for anything other than as a block name."
5653 */
5654 ir_variable *var = state->symbols->get_variable(this->block_name);
5655 if (var && !var->type->is_interface()) {
5656 _mesa_glsl_error(&loc, state, "Block name `%s' is "
5657 "already used in the scope.",
5658 this->block_name);
5659 }
5660 }
5661
5662 const glsl_type *earlier_per_vertex = NULL;
5663 if (redeclaring_per_vertex) {
5664 /* Find the previous declaration of gl_PerVertex. If we're redeclaring
5665 * the named interface block gl_in, we can find it by looking at the
5666 * previous declaration of gl_in. Otherwise we can find it by looking
5667 * at the previous decalartion of any of the built-in outputs,
5668 * e.g. gl_Position.
5669 *
5670 * Also check that the instance name and array-ness of the redeclaration
5671 * are correct.
5672 */
5673 switch (var_mode) {
5674 case ir_var_shader_in:
5675 if (ir_variable *earlier_gl_in =
5676 state->symbols->get_variable("gl_in")) {
5677 earlier_per_vertex = earlier_gl_in->get_interface_type();
5678 } else {
5679 _mesa_glsl_error(&loc, state,
5680 "redeclaration of gl_PerVertex input not allowed "
5681 "in the %s shader",
5682 _mesa_shader_stage_to_string(state->stage));
5683 }
5684 if (this->instance_name == NULL ||
5685 strcmp(this->instance_name, "gl_in") != 0 || this->array_specifier == NULL) {
5686 _mesa_glsl_error(&loc, state,
5687 "gl_PerVertex input must be redeclared as "
5688 "gl_in[]");
5689 }
5690 break;
5691 case ir_var_shader_out:
5692 if (ir_variable *earlier_gl_Position =
5693 state->symbols->get_variable("gl_Position")) {
5694 earlier_per_vertex = earlier_gl_Position->get_interface_type();
5695 } else {
5696 _mesa_glsl_error(&loc, state,
5697 "redeclaration of gl_PerVertex output not "
5698 "allowed in the %s shader",
5699 _mesa_shader_stage_to_string(state->stage));
5700 }
5701 if (this->instance_name != NULL) {
5702 _mesa_glsl_error(&loc, state,
5703 "gl_PerVertex output may not be redeclared with "
5704 "an instance name");
5705 }
5706 break;
5707 default:
5708 _mesa_glsl_error(&loc, state,
5709 "gl_PerVertex must be declared as an input or an "
5710 "output");
5711 break;
5712 }
5713
5714 if (earlier_per_vertex == NULL) {
5715 /* An error has already been reported. Bail out to avoid null
5716 * dereferences later in this function.
5717 */
5718 return NULL;
5719 }
5720
5721 /* Copy locations from the old gl_PerVertex interface block. */
5722 for (unsigned i = 0; i < num_variables; i++) {
5723 int j = earlier_per_vertex->field_index(fields[i].name);
5724 if (j == -1) {
5725 _mesa_glsl_error(&loc, state,
5726 "redeclaration of gl_PerVertex must be a subset "
5727 "of the built-in members of gl_PerVertex");
5728 } else {
5729 fields[i].location =
5730 earlier_per_vertex->fields.structure[j].location;
5731 fields[i].interpolation =
5732 earlier_per_vertex->fields.structure[j].interpolation;
5733 fields[i].centroid =
5734 earlier_per_vertex->fields.structure[j].centroid;
5735 fields[i].sample =
5736 earlier_per_vertex->fields.structure[j].sample;
5737 }
5738 }
5739
5740 /* From section 7.1 ("Built-in Language Variables") of the GLSL 4.10
5741 * spec:
5742 *
5743 * If a built-in interface block is redeclared, it must appear in
5744 * the shader before any use of any member included in the built-in
5745 * declaration, or a compilation error will result.
5746 *
5747 * This appears to be a clarification to the behaviour established for
5748 * gl_PerVertex by GLSL 1.50, therefore we implement this behaviour
5749 * regardless of GLSL version.
5750 */
5751 interface_block_usage_visitor v(var_mode, earlier_per_vertex);
5752 v.run(instructions);
5753 if (v.usage_found()) {
5754 _mesa_glsl_error(&loc, state,
5755 "redeclaration of a built-in interface block must "
5756 "appear before any use of any member of the "
5757 "interface block");
5758 }
5759 }
5760
5761 const glsl_type *block_type =
5762 glsl_type::get_interface_instance(fields,
5763 num_variables,
5764 packing,
5765 this->block_name);
5766
5767 if (!state->symbols->add_interface(block_type->name, block_type, var_mode)) {
5768 YYLTYPE loc = this->get_location();
5769 _mesa_glsl_error(&loc, state, "interface block `%s' with type `%s' "
5770 "already taken in the current scope",
5771 this->block_name, iface_type_name);
5772 }
5773
5774 /* Since interface blocks cannot contain statements, it should be
5775 * impossible for the block to generate any instructions.
5776 */
5777 assert(declared_variables.is_empty());
5778
5779 /* From section 4.3.4 (Inputs) of the GLSL 1.50 spec:
5780 *
5781 * Geometry shader input variables get the per-vertex values written
5782 * out by vertex shader output variables of the same names. Since a
5783 * geometry shader operates on a set of vertices, each input varying
5784 * variable (or input block, see interface blocks below) needs to be
5785 * declared as an array.
5786 */
5787 if (state->stage == MESA_SHADER_GEOMETRY && this->array_specifier == NULL &&
5788 var_mode == ir_var_shader_in) {
5789 _mesa_glsl_error(&loc, state, "geometry shader inputs must be arrays");
5790 }
5791
5792 /* Page 39 (page 45 of the PDF) of section 4.3.7 in the GLSL ES 3.00 spec
5793 * says:
5794 *
5795 * "If an instance name (instance-name) is used, then it puts all the
5796 * members inside a scope within its own name space, accessed with the
5797 * field selector ( . ) operator (analogously to structures)."
5798 */
5799 if (this->instance_name) {
5800 if (redeclaring_per_vertex) {
5801 /* When a built-in in an unnamed interface block is redeclared,
5802 * get_variable_being_redeclared() calls
5803 * check_builtin_array_max_size() to make sure that built-in array
5804 * variables aren't redeclared to illegal sizes. But we're looking
5805 * at a redeclaration of a named built-in interface block. So we
5806 * have to manually call check_builtin_array_max_size() for all parts
5807 * of the interface that are arrays.
5808 */
5809 for (unsigned i = 0; i < num_variables; i++) {
5810 if (fields[i].type->is_array()) {
5811 const unsigned size = fields[i].type->array_size();
5812 check_builtin_array_max_size(fields[i].name, size, loc, state);
5813 }
5814 }
5815 } else {
5816 validate_identifier(this->instance_name, loc, state);
5817 }
5818
5819 ir_variable *var;
5820
5821 if (this->array_specifier != NULL) {
5822 /* Section 4.3.7 (Interface Blocks) of the GLSL 1.50 spec says:
5823 *
5824 * For uniform blocks declared an array, each individual array
5825 * element corresponds to a separate buffer object backing one
5826 * instance of the block. As the array size indicates the number
5827 * of buffer objects needed, uniform block array declarations
5828 * must specify an array size.
5829 *
5830 * And a few paragraphs later:
5831 *
5832 * Geometry shader input blocks must be declared as arrays and
5833 * follow the array declaration and linking rules for all
5834 * geometry shader inputs. All other input and output block
5835 * arrays must specify an array size.
5836 *
5837 * The upshot of this is that the only circumstance where an
5838 * interface array size *doesn't* need to be specified is on a
5839 * geometry shader input.
5840 */
5841 if (this->array_specifier->is_unsized_array &&
5842 (state->stage != MESA_SHADER_GEOMETRY || !this->layout.flags.q.in)) {
5843 _mesa_glsl_error(&loc, state,
5844 "only geometry shader inputs may be unsized "
5845 "instance block arrays");
5846
5847 }
5848
5849 const glsl_type *block_array_type =
5850 process_array_type(&loc, block_type, this->array_specifier, state);
5851
5852 /* From section 4.3.9 (Interface Blocks) of the GLSL ES 3.10 spec:
5853 *
5854 * * Arrays of arrays of blocks are not allowed
5855 */
5856 if (state->es_shader && block_array_type->is_array() &&
5857 block_array_type->fields.array->is_array()) {
5858 _mesa_glsl_error(&loc, state,
5859 "arrays of arrays interface blocks are "
5860 "not allowed");
5861 }
5862
5863 var = new(state) ir_variable(block_array_type,
5864 this->instance_name,
5865 var_mode);
5866 } else {
5867 var = new(state) ir_variable(block_type,
5868 this->instance_name,
5869 var_mode);
5870 }
5871
5872 var->data.matrix_layout = matrix_layout == GLSL_MATRIX_LAYOUT_INHERITED
5873 ? GLSL_MATRIX_LAYOUT_COLUMN_MAJOR : matrix_layout;
5874
5875 if (var_mode == ir_var_shader_in || var_mode == ir_var_uniform)
5876 var->data.read_only = true;
5877
5878 if (state->stage == MESA_SHADER_GEOMETRY && var_mode == ir_var_shader_in)
5879 handle_geometry_shader_input_decl(state, loc, var);
5880
5881 if (ir_variable *earlier =
5882 state->symbols->get_variable(this->instance_name)) {
5883 if (!redeclaring_per_vertex) {
5884 _mesa_glsl_error(&loc, state, "`%s' redeclared",
5885 this->instance_name);
5886 }
5887 earlier->data.how_declared = ir_var_declared_normally;
5888 earlier->type = var->type;
5889 earlier->reinit_interface_type(block_type);
5890 delete var;
5891 } else {
5892 /* Propagate the "binding" keyword into this UBO's fields;
5893 * the UBO declaration itself doesn't get an ir_variable unless it
5894 * has an instance name. This is ugly.
5895 */
5896 var->data.explicit_binding = this->layout.flags.q.explicit_binding;
5897 var->data.binding = this->layout.binding;
5898
5899 var->data.vk_set = this->layout.flags.q.vk_set;
5900 var->data.set = this->layout.set;
5901 var->data.binding = this->layout.binding;
5902
5903 state->symbols->add_variable(var);
5904 instructions->push_tail(var);
5905 }
5906 } else {
5907 /* In order to have an array size, the block must also be declared with
5908 * an instance name.
5909 */
5910 assert(this->array_specifier == NULL);
5911
5912 for (unsigned i = 0; i < num_variables; i++) {
5913 ir_variable *var =
5914 new(state) ir_variable(fields[i].type,
5915 ralloc_strdup(state, fields[i].name),
5916 var_mode);
5917 var->data.interpolation = fields[i].interpolation;
5918 var->data.centroid = fields[i].centroid;
5919 var->data.sample = fields[i].sample;
5920 var->init_interface_type(block_type);
5921
5922 if (var_mode == ir_var_shader_in || var_mode == ir_var_uniform)
5923 var->data.read_only = true;
5924
5925 if (fields[i].matrix_layout == GLSL_MATRIX_LAYOUT_INHERITED) {
5926 var->data.matrix_layout = matrix_layout == GLSL_MATRIX_LAYOUT_INHERITED
5927 ? GLSL_MATRIX_LAYOUT_COLUMN_MAJOR : matrix_layout;
5928 } else {
5929 var->data.matrix_layout = fields[i].matrix_layout;
5930 }
5931
5932 if (fields[i].stream != -1 &&
5933 ((unsigned)fields[i].stream) != this->layout.stream) {
5934 _mesa_glsl_error(&loc, state,
5935 "stream layout qualifier on "
5936 "interface block member `%s' does not match "
5937 "the interface block (%d vs %d)",
5938 var->name, fields[i].stream, this->layout.stream);
5939 }
5940
5941 var->data.stream = this->layout.stream;
5942
5943 /* Examine var name here since var may get deleted in the next call */
5944 bool var_is_gl_id = is_gl_identifier(var->name);
5945
5946 if (redeclaring_per_vertex) {
5947 ir_variable *earlier =
5948 get_variable_being_redeclared(var, loc, state,
5949 true /* allow_all_redeclarations */);
5950 if (!var_is_gl_id || earlier == NULL) {
5951 _mesa_glsl_error(&loc, state,
5952 "redeclaration of gl_PerVertex can only "
5953 "include built-in variables");
5954 } else if (earlier->data.how_declared == ir_var_declared_normally) {
5955 _mesa_glsl_error(&loc, state,
5956 "`%s' has already been redeclared",
5957 earlier->name);
5958 } else {
5959 earlier->data.how_declared = ir_var_declared_in_block;
5960 earlier->reinit_interface_type(block_type);
5961 }
5962 continue;
5963 }
5964
5965 if (state->symbols->get_variable(var->name) != NULL)
5966 _mesa_glsl_error(&loc, state, "`%s' redeclared", var->name);
5967
5968 /* Propagate the "binding" keyword into this UBO's fields;
5969 * the UBO declaration itself doesn't get an ir_variable unless it
5970 * has an instance name. This is ugly.
5971 */
5972 var->data.explicit_binding = this->layout.flags.q.explicit_binding;
5973 var->data.binding = this->layout.binding;
5974
5975 var->data.vk_set = this->layout.flags.q.vk_set;
5976 var->data.set = this->layout.set;
5977 var->data.binding = this->layout.binding;
5978
5979 state->symbols->add_variable(var);
5980 instructions->push_tail(var);
5981 }
5982
5983 if (redeclaring_per_vertex && block_type != earlier_per_vertex) {
5984 /* From section 7.1 ("Built-in Language Variables") of the GLSL 4.10 spec:
5985 *
5986 * It is also a compilation error ... to redeclare a built-in
5987 * block and then use a member from that built-in block that was
5988 * not included in the redeclaration.
5989 *
5990 * This appears to be a clarification to the behaviour established
5991 * for gl_PerVertex by GLSL 1.50, therefore we implement this
5992 * behaviour regardless of GLSL version.
5993 *
5994 * To prevent the shader from using a member that was not included in
5995 * the redeclaration, we disable any ir_variables that are still
5996 * associated with the old declaration of gl_PerVertex (since we've
5997 * already updated all of the variables contained in the new
5998 * gl_PerVertex to point to it).
5999 *
6000 * As a side effect this will prevent
6001 * validate_intrastage_interface_blocks() from getting confused and
6002 * thinking there are conflicting definitions of gl_PerVertex in the
6003 * shader.
6004 */
6005 foreach_in_list_safe(ir_instruction, node, instructions) {
6006 ir_variable *const var = node->as_variable();
6007 if (var != NULL &&
6008 var->get_interface_type() == earlier_per_vertex &&
6009 var->data.mode == var_mode) {
6010 if (var->data.how_declared == ir_var_declared_normally) {
6011 _mesa_glsl_error(&loc, state,
6012 "redeclaration of gl_PerVertex cannot "
6013 "follow a redeclaration of `%s'",
6014 var->name);
6015 }
6016 state->symbols->disable_variable(var->name);
6017 var->remove();
6018 }
6019 }
6020 }
6021 }
6022
6023 return NULL;
6024 }
6025
6026
6027 ir_rvalue *
6028 ast_gs_input_layout::hir(exec_list *instructions,
6029 struct _mesa_glsl_parse_state *state)
6030 {
6031 YYLTYPE loc = this->get_location();
6032
6033 /* If any geometry input layout declaration preceded this one, make sure it
6034 * was consistent with this one.
6035 */
6036 if (state->gs_input_prim_type_specified &&
6037 state->in_qualifier->prim_type != this->prim_type) {
6038 _mesa_glsl_error(&loc, state,
6039 "geometry shader input layout does not match"
6040 " previous declaration");
6041 return NULL;
6042 }
6043
6044 /* If any shader inputs occurred before this declaration and specified an
6045 * array size, make sure the size they specified is consistent with the
6046 * primitive type.
6047 */
6048 unsigned num_vertices = vertices_per_prim(this->prim_type);
6049 if (state->gs_input_size != 0 && state->gs_input_size != num_vertices) {
6050 _mesa_glsl_error(&loc, state,
6051 "this geometry shader input layout implies %u vertices"
6052 " per primitive, but a previous input is declared"
6053 " with size %u", num_vertices, state->gs_input_size);
6054 return NULL;
6055 }
6056
6057 state->gs_input_prim_type_specified = true;
6058
6059 /* If any shader inputs occurred before this declaration and did not
6060 * specify an array size, their size is determined now.
6061 */
6062 foreach_in_list(ir_instruction, node, instructions) {
6063 ir_variable *var = node->as_variable();
6064 if (var == NULL || var->data.mode != ir_var_shader_in)
6065 continue;
6066
6067 /* Note: gl_PrimitiveIDIn has mode ir_var_shader_in, but it's not an
6068 * array; skip it.
6069 */
6070
6071 if (var->type->is_unsized_array()) {
6072 if (var->data.max_array_access >= num_vertices) {
6073 _mesa_glsl_error(&loc, state,
6074 "this geometry shader input layout implies %u"
6075 " vertices, but an access to element %u of input"
6076 " `%s' already exists", num_vertices,
6077 var->data.max_array_access, var->name);
6078 } else {
6079 var->type = glsl_type::get_array_instance(var->type->fields.array,
6080 num_vertices);
6081 }
6082 }
6083 }
6084
6085 return NULL;
6086 }
6087
6088
6089 ir_rvalue *
6090 ast_cs_input_layout::hir(exec_list *instructions,
6091 struct _mesa_glsl_parse_state *state)
6092 {
6093 YYLTYPE loc = this->get_location();
6094
6095 /* If any compute input layout declaration preceded this one, make sure it
6096 * was consistent with this one.
6097 */
6098 if (state->cs_input_local_size_specified) {
6099 for (int i = 0; i < 3; i++) {
6100 if (state->cs_input_local_size[i] != this->local_size[i]) {
6101 _mesa_glsl_error(&loc, state,
6102 "compute shader input layout does not match"
6103 " previous declaration");
6104 return NULL;
6105 }
6106 }
6107 }
6108
6109 /* From the ARB_compute_shader specification:
6110 *
6111 * If the local size of the shader in any dimension is greater
6112 * than the maximum size supported by the implementation for that
6113 * dimension, a compile-time error results.
6114 *
6115 * It is not clear from the spec how the error should be reported if
6116 * the total size of the work group exceeds
6117 * MAX_COMPUTE_WORK_GROUP_INVOCATIONS, but it seems reasonable to
6118 * report it at compile time as well.
6119 */
6120 GLuint64 total_invocations = 1;
6121 for (int i = 0; i < 3; i++) {
6122 if (this->local_size[i] > state->ctx->Const.MaxComputeWorkGroupSize[i]) {
6123 _mesa_glsl_error(&loc, state,
6124 "local_size_%c exceeds MAX_COMPUTE_WORK_GROUP_SIZE"
6125 " (%d)", 'x' + i,
6126 state->ctx->Const.MaxComputeWorkGroupSize[i]);
6127 break;
6128 }
6129 total_invocations *= this->local_size[i];
6130 if (total_invocations >
6131 state->ctx->Const.MaxComputeWorkGroupInvocations) {
6132 _mesa_glsl_error(&loc, state,
6133 "product of local_sizes exceeds "
6134 "MAX_COMPUTE_WORK_GROUP_INVOCATIONS (%d)",
6135 state->ctx->Const.MaxComputeWorkGroupInvocations);
6136 break;
6137 }
6138 }
6139
6140 state->cs_input_local_size_specified = true;
6141 for (int i = 0; i < 3; i++)
6142 state->cs_input_local_size[i] = this->local_size[i];
6143
6144 /* We may now declare the built-in constant gl_WorkGroupSize (see
6145 * builtin_variable_generator::generate_constants() for why we didn't
6146 * declare it earlier).
6147 */
6148 ir_variable *var = new(state->symbols)
6149 ir_variable(glsl_type::uvec3_type, "gl_WorkGroupSize", ir_var_auto);
6150 var->data.how_declared = ir_var_declared_implicitly;
6151 var->data.read_only = true;
6152 instructions->push_tail(var);
6153 state->symbols->add_variable(var);
6154 ir_constant_data data;
6155 memset(&data, 0, sizeof(data));
6156 for (int i = 0; i < 3; i++)
6157 data.u[i] = this->local_size[i];
6158 var->constant_value = new(var) ir_constant(glsl_type::uvec3_type, &data);
6159 var->constant_initializer =
6160 new(var) ir_constant(glsl_type::uvec3_type, &data);
6161 var->data.has_initializer = true;
6162
6163 return NULL;
6164 }
6165
6166
6167 static void
6168 detect_conflicting_assignments(struct _mesa_glsl_parse_state *state,
6169 exec_list *instructions)
6170 {
6171 bool gl_FragColor_assigned = false;
6172 bool gl_FragData_assigned = false;
6173 bool user_defined_fs_output_assigned = false;
6174 ir_variable *user_defined_fs_output = NULL;
6175
6176 /* It would be nice to have proper location information. */
6177 YYLTYPE loc;
6178 memset(&loc, 0, sizeof(loc));
6179
6180 foreach_in_list(ir_instruction, node, instructions) {
6181 ir_variable *var = node->as_variable();
6182
6183 if (!var || !var->data.assigned)
6184 continue;
6185
6186 if (strcmp(var->name, "gl_FragColor") == 0)
6187 gl_FragColor_assigned = true;
6188 else if (strcmp(var->name, "gl_FragData") == 0)
6189 gl_FragData_assigned = true;
6190 else if (!is_gl_identifier(var->name)) {
6191 if (state->stage == MESA_SHADER_FRAGMENT &&
6192 var->data.mode == ir_var_shader_out) {
6193 user_defined_fs_output_assigned = true;
6194 user_defined_fs_output = var;
6195 }
6196 }
6197 }
6198
6199 /* From the GLSL 1.30 spec:
6200 *
6201 * "If a shader statically assigns a value to gl_FragColor, it
6202 * may not assign a value to any element of gl_FragData. If a
6203 * shader statically writes a value to any element of
6204 * gl_FragData, it may not assign a value to
6205 * gl_FragColor. That is, a shader may assign values to either
6206 * gl_FragColor or gl_FragData, but not both. Multiple shaders
6207 * linked together must also consistently write just one of
6208 * these variables. Similarly, if user declared output
6209 * variables are in use (statically assigned to), then the
6210 * built-in variables gl_FragColor and gl_FragData may not be
6211 * assigned to. These incorrect usages all generate compile
6212 * time errors."
6213 */
6214 if (gl_FragColor_assigned && gl_FragData_assigned) {
6215 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
6216 "`gl_FragColor' and `gl_FragData'");
6217 } else if (gl_FragColor_assigned && user_defined_fs_output_assigned) {
6218 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
6219 "`gl_FragColor' and `%s'",
6220 user_defined_fs_output->name);
6221 } else if (gl_FragData_assigned && user_defined_fs_output_assigned) {
6222 _mesa_glsl_error(&loc, state, "fragment shader writes to both "
6223 "`gl_FragData' and `%s'",
6224 user_defined_fs_output->name);
6225 }
6226 }
6227
6228
6229 static void
6230 remove_per_vertex_blocks(exec_list *instructions,
6231 _mesa_glsl_parse_state *state, ir_variable_mode mode)
6232 {
6233 /* Find the gl_PerVertex interface block of the appropriate (in/out) mode,
6234 * if it exists in this shader type.
6235 */
6236 const glsl_type *per_vertex = NULL;
6237 switch (mode) {
6238 case ir_var_shader_in:
6239 if (ir_variable *gl_in = state->symbols->get_variable("gl_in"))
6240 per_vertex = gl_in->get_interface_type();
6241 break;
6242 case ir_var_shader_out:
6243 if (ir_variable *gl_Position =
6244 state->symbols->get_variable("gl_Position")) {
6245 per_vertex = gl_Position->get_interface_type();
6246 }
6247 break;
6248 default:
6249 assert(!"Unexpected mode");
6250 break;
6251 }
6252
6253 /* If we didn't find a built-in gl_PerVertex interface block, then we don't
6254 * need to do anything.
6255 */
6256 if (per_vertex == NULL)
6257 return;
6258
6259 /* If the interface block is used by the shader, then we don't need to do
6260 * anything.
6261 */
6262 interface_block_usage_visitor v(mode, per_vertex);
6263 v.run(instructions);
6264 if (v.usage_found())
6265 return;
6266
6267 /* Remove any ir_variable declarations that refer to the interface block
6268 * we're removing.
6269 */
6270 foreach_in_list_safe(ir_instruction, node, instructions) {
6271 ir_variable *const var = node->as_variable();
6272 if (var != NULL && var->get_interface_type() == per_vertex &&
6273 var->data.mode == mode) {
6274 state->symbols->disable_variable(var->name);
6275 var->remove();
6276 }
6277 }
6278 }