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