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