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