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