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