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