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