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