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