ast_to_hir.cpp revision e1d71850faba23d1bea3858a8c2e05a45fd21143
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 "main/imports.h"
53#include "glsl_symbol_table.h"
54#include "glsl_parser_extras.h"
55#include "ast.h"
56#include "glsl_types.h"
57#include "ir.h"
58
59void
60_mesa_ast_to_hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)
61{
62   _mesa_glsl_initialize_variables(instructions, state);
63   _mesa_glsl_initialize_functions(instructions, state);
64
65   state->current_function = NULL;
66
67   foreach_list_typed (ast_node, ast, link, & state->translation_unit)
68      ast->hir(instructions, state);
69}
70
71
72/**
73 * If a conversion is available, convert one operand to a different type
74 *
75 * The \c from \c ir_rvalue is converted "in place".
76 *
77 * \param to     Type that the operand it to be converted to
78 * \param from   Operand that is being converted
79 * \param state  GLSL compiler state
80 *
81 * \return
82 * If a conversion is possible (or unnecessary), \c true is returned.
83 * Otherwise \c false is returned.
84 */
85static bool
86apply_implicit_conversion(const glsl_type *to, ir_rvalue * &from,
87			  struct _mesa_glsl_parse_state *state)
88{
89   void *ctx = state;
90   if (to->base_type == from->type->base_type)
91      return true;
92
93   /* This conversion was added in GLSL 1.20.  If the compilation mode is
94    * GLSL 1.10, the conversion is skipped.
95    */
96   if (state->language_version < 120)
97      return false;
98
99   /* From page 27 (page 33 of the PDF) of the GLSL 1.50 spec:
100    *
101    *    "There are no implicit array or structure conversions. For
102    *    example, an array of int cannot be implicitly converted to an
103    *    array of float. There are no implicit conversions between
104    *    signed and unsigned integers."
105    */
106   /* FINISHME: The above comment is partially a lie.  There is int/uint
107    * FINISHME: conversion for immediate constants.
108    */
109   if (!to->is_float() || !from->type->is_numeric())
110      return false;
111
112   /* Convert to a floating point type with the same number of components
113    * as the original type - i.e. int to float, not int to vec4.
114    */
115   to = glsl_type::get_instance(GLSL_TYPE_FLOAT, from->type->vector_elements,
116			        from->type->matrix_columns);
117
118   switch (from->type->base_type) {
119   case GLSL_TYPE_INT:
120      from = new(ctx) ir_expression(ir_unop_i2f, to, from, NULL);
121      break;
122   case GLSL_TYPE_UINT:
123      from = new(ctx) ir_expression(ir_unop_u2f, to, from, NULL);
124      break;
125   case GLSL_TYPE_BOOL:
126      from = new(ctx) ir_expression(ir_unop_b2f, to, from, NULL);
127      break;
128   default:
129      assert(0);
130   }
131
132   return true;
133}
134
135
136static const struct glsl_type *
137arithmetic_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
138		       bool multiply,
139		       struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
140{
141   const glsl_type *type_a = value_a->type;
142   const glsl_type *type_b = value_b->type;
143
144   /* From GLSL 1.50 spec, page 56:
145    *
146    *    "The arithmetic binary operators add (+), subtract (-),
147    *    multiply (*), and divide (/) operate on integer and
148    *    floating-point scalars, vectors, and matrices."
149    */
150   if (!type_a->is_numeric() || !type_b->is_numeric()) {
151      _mesa_glsl_error(loc, state,
152		       "Operands to arithmetic operators must be numeric");
153      return glsl_type::error_type;
154   }
155
156
157   /*    "If one operand is floating-point based and the other is
158    *    not, then the conversions from Section 4.1.10 "Implicit
159    *    Conversions" are applied to the non-floating-point-based operand."
160    */
161   if (!apply_implicit_conversion(type_a, value_b, state)
162       && !apply_implicit_conversion(type_b, value_a, state)) {
163      _mesa_glsl_error(loc, state,
164		       "Could not implicitly convert operands to "
165		       "arithmetic operator");
166      return glsl_type::error_type;
167   }
168   type_a = value_a->type;
169   type_b = value_b->type;
170
171   /*    "If the operands are integer types, they must both be signed or
172    *    both be unsigned."
173    *
174    * From this rule and the preceeding conversion it can be inferred that
175    * both types must be GLSL_TYPE_FLOAT, or GLSL_TYPE_UINT, or GLSL_TYPE_INT.
176    * The is_numeric check above already filtered out the case where either
177    * type is not one of these, so now the base types need only be tested for
178    * equality.
179    */
180   if (type_a->base_type != type_b->base_type) {
181      _mesa_glsl_error(loc, state,
182		       "base type mismatch for arithmetic operator");
183      return glsl_type::error_type;
184   }
185
186   /*    "All arithmetic binary operators result in the same fundamental type
187    *    (signed integer, unsigned integer, or floating-point) as the
188    *    operands they operate on, after operand type conversion. After
189    *    conversion, the following cases are valid
190    *
191    *    * The two operands are scalars. In this case the operation is
192    *      applied, resulting in a scalar."
193    */
194   if (type_a->is_scalar() && type_b->is_scalar())
195      return type_a;
196
197   /*   "* One operand is a scalar, and the other is a vector or matrix.
198    *      In this case, the scalar operation is applied independently to each
199    *      component of the vector or matrix, resulting in the same size
200    *      vector or matrix."
201    */
202   if (type_a->is_scalar()) {
203      if (!type_b->is_scalar())
204	 return type_b;
205   } else if (type_b->is_scalar()) {
206      return type_a;
207   }
208
209   /* All of the combinations of <scalar, scalar>, <vector, scalar>,
210    * <scalar, vector>, <scalar, matrix>, and <matrix, scalar> have been
211    * handled.
212    */
213   assert(!type_a->is_scalar());
214   assert(!type_b->is_scalar());
215
216   /*   "* The two operands are vectors of the same size. In this case, the
217    *      operation is done component-wise resulting in the same size
218    *      vector."
219    */
220   if (type_a->is_vector() && type_b->is_vector()) {
221      if (type_a == type_b) {
222	 return type_a;
223      } else {
224	 _mesa_glsl_error(loc, state,
225			  "vector size mismatch for arithmetic operator");
226	 return glsl_type::error_type;
227      }
228   }
229
230   /* All of the combinations of <scalar, scalar>, <vector, scalar>,
231    * <scalar, vector>, <scalar, matrix>, <matrix, scalar>, and
232    * <vector, vector> have been handled.  At least one of the operands must
233    * be matrix.  Further, since there are no integer matrix types, the base
234    * type of both operands must be float.
235    */
236   assert(type_a->is_matrix() || type_b->is_matrix());
237   assert(type_a->base_type == GLSL_TYPE_FLOAT);
238   assert(type_b->base_type == GLSL_TYPE_FLOAT);
239
240   /*   "* The operator is add (+), subtract (-), or divide (/), and the
241    *      operands are matrices with the same number of rows and the same
242    *      number of columns. In this case, the operation is done component-
243    *      wise resulting in the same size matrix."
244    *    * The operator is multiply (*), where both operands are matrices or
245    *      one operand is a vector and the other a matrix. A right vector
246    *      operand is treated as a column vector and a left vector operand as a
247    *      row vector. In all these cases, it is required that the number of
248    *      columns of the left operand is equal to the number of rows of the
249    *      right operand. Then, the multiply (*) operation does a linear
250    *      algebraic multiply, yielding an object that has the same number of
251    *      rows as the left operand and the same number of columns as the right
252    *      operand. Section 5.10 "Vector and Matrix Operations" explains in
253    *      more detail how vectors and matrices are operated on."
254    */
255   if (! multiply) {
256      if (type_a == type_b)
257	 return type_a;
258   } else {
259      if (type_a->is_matrix() && type_b->is_matrix()) {
260	 /* Matrix multiply.  The columns of A must match the rows of B.  Given
261	  * the other previously tested constraints, this means the vector type
262	  * of a row from A must be the same as the vector type of a column from
263	  * B.
264	  */
265	 if (type_a->row_type() == type_b->column_type()) {
266	    /* The resulting matrix has the number of columns of matrix B and
267	     * the number of rows of matrix A.  We get the row count of A by
268	     * looking at the size of a vector that makes up a column.  The
269	     * transpose (size of a row) is done for B.
270	     */
271	    const glsl_type *const type =
272	       glsl_type::get_instance(type_a->base_type,
273				       type_a->column_type()->vector_elements,
274				       type_b->row_type()->vector_elements);
275	    assert(type != glsl_type::error_type);
276
277	    return type;
278	 }
279      } else if (type_a->is_matrix()) {
280	 /* A is a matrix and B is a column vector.  Columns of A must match
281	  * rows of B.  Given the other previously tested constraints, this
282	  * means the vector type of a row from A must be the same as the
283	  * vector the type of B.
284	  */
285	 if (type_a->row_type() == type_b)
286	    return type_b;
287      } else {
288	 assert(type_b->is_matrix());
289
290	 /* A is a row vector and B is a matrix.  Columns of A must match rows
291	  * of B.  Given the other previously tested constraints, this means
292	  * the type of A must be the same as the vector type of a column from
293	  * B.
294	  */
295	 if (type_a == type_b->column_type())
296	    return type_a;
297      }
298
299      _mesa_glsl_error(loc, state, "size mismatch for matrix multiplication");
300      return glsl_type::error_type;
301   }
302
303
304   /*    "All other cases are illegal."
305    */
306   _mesa_glsl_error(loc, state, "type mismatch");
307   return glsl_type::error_type;
308}
309
310
311static const struct glsl_type *
312unary_arithmetic_result_type(const struct glsl_type *type,
313			     struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
314{
315   /* From GLSL 1.50 spec, page 57:
316    *
317    *    "The arithmetic unary operators negate (-), post- and pre-increment
318    *     and decrement (-- and ++) operate on integer or floating-point
319    *     values (including vectors and matrices). All unary operators work
320    *     component-wise on their operands. These result with the same type
321    *     they operated on."
322    */
323   if (!type->is_numeric()) {
324      _mesa_glsl_error(loc, state,
325		       "Operands to arithmetic operators must be numeric");
326      return glsl_type::error_type;
327   }
328
329   return type;
330}
331
332
333static const struct glsl_type *
334modulus_result_type(const struct glsl_type *type_a,
335		    const struct glsl_type *type_b,
336		    struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
337{
338   /* From GLSL 1.50 spec, page 56:
339    *    "The operator modulus (%) operates on signed or unsigned integers or
340    *    integer vectors. The operand types must both be signed or both be
341    *    unsigned."
342    */
343   if (!type_a->is_integer() || !type_b->is_integer()
344       || (type_a->base_type != type_b->base_type)) {
345      _mesa_glsl_error(loc, state, "type mismatch");
346      return glsl_type::error_type;
347   }
348
349   /*    "The operands cannot be vectors of differing size. If one operand is
350    *    a scalar and the other vector, then the scalar is applied component-
351    *    wise to the vector, resulting in the same type as the vector. If both
352    *    are vectors of the same size, the result is computed component-wise."
353    */
354   if (type_a->is_vector()) {
355      if (!type_b->is_vector()
356	  || (type_a->vector_elements == type_b->vector_elements))
357	 return type_a;
358   } else
359      return type_b;
360
361   /*    "The operator modulus (%) is not defined for any other data types
362    *    (non-integer types)."
363    */
364   _mesa_glsl_error(loc, state, "type mismatch");
365   return glsl_type::error_type;
366}
367
368
369static const struct glsl_type *
370relational_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
371		       struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
372{
373   const glsl_type *type_a = value_a->type;
374   const glsl_type *type_b = value_b->type;
375
376   /* From GLSL 1.50 spec, page 56:
377    *    "The relational operators greater than (>), less than (<), greater
378    *    than or equal (>=), and less than or equal (<=) operate only on
379    *    scalar integer and scalar floating-point expressions."
380    */
381   if (!type_a->is_numeric()
382       || !type_b->is_numeric()
383       || !type_a->is_scalar()
384       || !type_b->is_scalar()) {
385      _mesa_glsl_error(loc, state,
386		       "Operands to relational operators must be scalar and "
387		       "numeric");
388      return glsl_type::error_type;
389   }
390
391   /*    "Either the operands' types must match, or the conversions from
392    *    Section 4.1.10 "Implicit Conversions" will be applied to the integer
393    *    operand, after which the types must match."
394    */
395   if (!apply_implicit_conversion(type_a, value_b, state)
396       && !apply_implicit_conversion(type_b, value_a, state)) {
397      _mesa_glsl_error(loc, state,
398		       "Could not implicitly convert operands to "
399		       "relational operator");
400      return glsl_type::error_type;
401   }
402   type_a = value_a->type;
403   type_b = value_b->type;
404
405   if (type_a->base_type != type_b->base_type) {
406      _mesa_glsl_error(loc, state, "base type mismatch");
407      return glsl_type::error_type;
408   }
409
410   /*    "The result is scalar Boolean."
411    */
412   return glsl_type::bool_type;
413}
414
415
416/**
417 * Validates that a value can be assigned to a location with a specified type
418 *
419 * Validates that \c rhs can be assigned to some location.  If the types are
420 * not an exact match but an automatic conversion is possible, \c rhs will be
421 * converted.
422 *
423 * \return
424 * \c NULL if \c rhs cannot be assigned to a location with type \c lhs_type.
425 * Otherwise the actual RHS to be assigned will be returned.  This may be
426 * \c rhs, or it may be \c rhs after some type conversion.
427 *
428 * \note
429 * In addition to being used for assignments, this function is used to
430 * type-check return values.
431 */
432ir_rvalue *
433validate_assignment(struct _mesa_glsl_parse_state *state,
434		    const glsl_type *lhs_type, ir_rvalue *rhs)
435{
436   const glsl_type *rhs_type = rhs->type;
437
438   /* If there is already some error in the RHS, just return it.  Anything
439    * else will lead to an avalanche of error message back to the user.
440    */
441   if (rhs_type->is_error())
442      return rhs;
443
444   /* If the types are identical, the assignment can trivially proceed.
445    */
446   if (rhs_type == lhs_type)
447      return rhs;
448
449   /* If the array element types are the same and the size of the LHS is zero,
450    * the assignment is okay.
451    *
452    * Note: Whole-array assignments are not permitted in GLSL 1.10, but this
453    * is handled by ir_dereference::is_lvalue.
454    */
455   if (lhs_type->is_array() && rhs->type->is_array()
456       && (lhs_type->element_type() == rhs->type->element_type())
457       && (lhs_type->array_size() == 0)) {
458      return rhs;
459   }
460
461   /* Check for implicit conversion in GLSL 1.20 */
462   if (apply_implicit_conversion(lhs_type, rhs, state)) {
463      rhs_type = rhs->type;
464      if (rhs_type == lhs_type)
465	 return rhs;
466   }
467
468   return NULL;
469}
470
471ir_rvalue *
472do_assignment(exec_list *instructions, struct _mesa_glsl_parse_state *state,
473	      ir_rvalue *lhs, ir_rvalue *rhs,
474	      YYLTYPE lhs_loc)
475{
476   void *ctx = state;
477   bool error_emitted = (lhs->type->is_error() || rhs->type->is_error());
478
479   if (!error_emitted) {
480      /* FINISHME: This does not handle 'foo.bar.a.b.c[5].d = 5' */
481      if (!lhs->is_lvalue()) {
482	 _mesa_glsl_error(& lhs_loc, state, "non-lvalue in assignment");
483	 error_emitted = true;
484      }
485   }
486
487   ir_rvalue *new_rhs = validate_assignment(state, lhs->type, rhs);
488   if (new_rhs == NULL) {
489      _mesa_glsl_error(& lhs_loc, state, "type mismatch");
490   } else {
491      rhs = new_rhs;
492
493      /* If the LHS array was not declared with a size, it takes it size from
494       * the RHS.  If the LHS is an l-value and a whole array, it must be a
495       * dereference of a variable.  Any other case would require that the LHS
496       * is either not an l-value or not a whole array.
497       */
498      if (lhs->type->array_size() == 0) {
499	 ir_dereference *const d = lhs->as_dereference();
500
501	 assert(d != NULL);
502
503	 ir_variable *const var = d->variable_referenced();
504
505	 assert(var != NULL);
506
507	 if (var->max_array_access >= unsigned(rhs->type->array_size())) {
508	    /* FINISHME: This should actually log the location of the RHS. */
509	    _mesa_glsl_error(& lhs_loc, state, "array size must be > %u due to "
510			     "previous access",
511			     var->max_array_access);
512	 }
513
514	 var->type = glsl_type::get_array_instance(lhs->type->element_type(),
515						   rhs->type->array_size());
516      }
517   }
518
519   /* Most callers of do_assignment (assign, add_assign, pre_inc/dec,
520    * but not post_inc) need the converted assigned value as an rvalue
521    * to handle things like:
522    *
523    * i = j += 1;
524    *
525    * So we always just store the computed value being assigned to a
526    * temporary and return a deref of that temporary.  If the rvalue
527    * ends up not being used, the temp will get copy-propagated out.
528    */
529   ir_variable *var = new(ctx) ir_variable(rhs->type, "assignment_tmp",
530					   ir_var_temporary);
531   ir_dereference_variable *deref_var = new(ctx) ir_dereference_variable(var);
532   instructions->push_tail(var);
533   instructions->push_tail(new(ctx) ir_assignment(deref_var,
534						  rhs,
535						  NULL));
536   deref_var = new(ctx) ir_dereference_variable(var);
537
538   instructions->push_tail(new(ctx) ir_assignment(lhs,
539						  deref_var,
540						  NULL));
541
542   return new(ctx) ir_dereference_variable(var);
543}
544
545static ir_rvalue *
546get_lvalue_copy(exec_list *instructions, ir_rvalue *lvalue)
547{
548   void *ctx = talloc_parent(lvalue);
549   ir_variable *var;
550
551   /* FINISHME: Give unique names to the temporaries. */
552   var = new(ctx) ir_variable(lvalue->type, "_post_incdec_tmp",
553			      ir_var_temporary);
554   instructions->push_tail(var);
555   var->mode = ir_var_auto;
556
557   instructions->push_tail(new(ctx) ir_assignment(new(ctx) ir_dereference_variable(var),
558						  lvalue, NULL));
559
560   /* Once we've created this temporary, mark it read only so it's no
561    * longer considered an lvalue.
562    */
563   var->read_only = true;
564
565   return new(ctx) ir_dereference_variable(var);
566}
567
568
569ir_rvalue *
570ast_node::hir(exec_list *instructions,
571	      struct _mesa_glsl_parse_state *state)
572{
573   (void) instructions;
574   (void) state;
575
576   return NULL;
577}
578
579
580ir_rvalue *
581ast_expression::hir(exec_list *instructions,
582		    struct _mesa_glsl_parse_state *state)
583{
584   void *ctx = state;
585   static const int operations[AST_NUM_OPERATORS] = {
586      -1,               /* ast_assign doesn't convert to ir_expression. */
587      -1,               /* ast_plus doesn't convert to ir_expression. */
588      ir_unop_neg,
589      ir_binop_add,
590      ir_binop_sub,
591      ir_binop_mul,
592      ir_binop_div,
593      ir_binop_mod,
594      ir_binop_lshift,
595      ir_binop_rshift,
596      ir_binop_less,
597      ir_binop_greater,
598      ir_binop_lequal,
599      ir_binop_gequal,
600      ir_binop_equal,
601      ir_binop_nequal,
602      ir_binop_bit_and,
603      ir_binop_bit_xor,
604      ir_binop_bit_or,
605      ir_unop_bit_not,
606      ir_binop_logic_and,
607      ir_binop_logic_xor,
608      ir_binop_logic_or,
609      ir_unop_logic_not,
610
611      /* Note: The following block of expression types actually convert
612       * to multiple IR instructions.
613       */
614      ir_binop_mul,     /* ast_mul_assign */
615      ir_binop_div,     /* ast_div_assign */
616      ir_binop_mod,     /* ast_mod_assign */
617      ir_binop_add,     /* ast_add_assign */
618      ir_binop_sub,     /* ast_sub_assign */
619      ir_binop_lshift,  /* ast_ls_assign */
620      ir_binop_rshift,  /* ast_rs_assign */
621      ir_binop_bit_and, /* ast_and_assign */
622      ir_binop_bit_xor, /* ast_xor_assign */
623      ir_binop_bit_or,  /* ast_or_assign */
624
625      -1,               /* ast_conditional doesn't convert to ir_expression. */
626      ir_binop_add,     /* ast_pre_inc. */
627      ir_binop_sub,     /* ast_pre_dec. */
628      ir_binop_add,     /* ast_post_inc. */
629      ir_binop_sub,     /* ast_post_dec. */
630      -1,               /* ast_field_selection doesn't conv to ir_expression. */
631      -1,               /* ast_array_index doesn't convert to ir_expression. */
632      -1,               /* ast_function_call doesn't conv to ir_expression. */
633      -1,               /* ast_identifier doesn't convert to ir_expression. */
634      -1,               /* ast_int_constant doesn't convert to ir_expression. */
635      -1,               /* ast_uint_constant doesn't conv to ir_expression. */
636      -1,               /* ast_float_constant doesn't conv to ir_expression. */
637      -1,               /* ast_bool_constant doesn't conv to ir_expression. */
638      -1,               /* ast_sequence doesn't convert to ir_expression. */
639   };
640   ir_rvalue *result = NULL;
641   ir_rvalue *op[2];
642   const struct glsl_type *type = glsl_type::error_type;
643   bool error_emitted = false;
644   YYLTYPE loc;
645
646   loc = this->get_location();
647
648   switch (this->oper) {
649   case ast_assign: {
650      op[0] = this->subexpressions[0]->hir(instructions, state);
651      op[1] = this->subexpressions[1]->hir(instructions, state);
652
653      result = do_assignment(instructions, state, op[0], op[1],
654			     this->subexpressions[0]->get_location());
655      error_emitted = result->type->is_error();
656      type = result->type;
657      break;
658   }
659
660   case ast_plus:
661      op[0] = this->subexpressions[0]->hir(instructions, state);
662
663      type = unary_arithmetic_result_type(op[0]->type, state, & loc);
664
665      error_emitted = type->is_error();
666
667      result = op[0];
668      break;
669
670   case ast_neg:
671      op[0] = this->subexpressions[0]->hir(instructions, state);
672
673      type = unary_arithmetic_result_type(op[0]->type, state, & loc);
674
675      error_emitted = type->is_error();
676
677      result = new(ctx) ir_expression(operations[this->oper], type,
678				      op[0], NULL);
679      break;
680
681   case ast_add:
682   case ast_sub:
683   case ast_mul:
684   case ast_div:
685      op[0] = this->subexpressions[0]->hir(instructions, state);
686      op[1] = this->subexpressions[1]->hir(instructions, state);
687
688      type = arithmetic_result_type(op[0], op[1],
689				    (this->oper == ast_mul),
690				    state, & loc);
691      error_emitted = type->is_error();
692
693      result = new(ctx) ir_expression(operations[this->oper], type,
694				      op[0], op[1]);
695      break;
696
697   case ast_mod:
698      op[0] = this->subexpressions[0]->hir(instructions, state);
699      op[1] = this->subexpressions[1]->hir(instructions, state);
700
701      type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
702
703      assert(operations[this->oper] == ir_binop_mod);
704
705      result = new(ctx) ir_expression(operations[this->oper], type,
706				      op[0], op[1]);
707      error_emitted = type->is_error();
708      break;
709
710   case ast_lshift:
711   case ast_rshift:
712      _mesa_glsl_error(& loc, state, "FINISHME: implement bit-shift operators");
713      error_emitted = true;
714      break;
715
716   case ast_less:
717   case ast_greater:
718   case ast_lequal:
719   case ast_gequal:
720      op[0] = this->subexpressions[0]->hir(instructions, state);
721      op[1] = this->subexpressions[1]->hir(instructions, state);
722
723      type = relational_result_type(op[0], op[1], state, & loc);
724
725      /* The relational operators must either generate an error or result
726       * in a scalar boolean.  See page 57 of the GLSL 1.50 spec.
727       */
728      assert(type->is_error()
729	     || ((type->base_type == GLSL_TYPE_BOOL)
730		 && type->is_scalar()));
731
732      result = new(ctx) ir_expression(operations[this->oper], type,
733				      op[0], op[1]);
734      error_emitted = type->is_error();
735      break;
736
737   case ast_nequal:
738   case ast_equal:
739      op[0] = this->subexpressions[0]->hir(instructions, state);
740      op[1] = this->subexpressions[1]->hir(instructions, state);
741
742      /* From page 58 (page 64 of the PDF) of the GLSL 1.50 spec:
743       *
744       *    "The equality operators equal (==), and not equal (!=)
745       *    operate on all types. They result in a scalar Boolean. If
746       *    the operand types do not match, then there must be a
747       *    conversion from Section 4.1.10 "Implicit Conversions"
748       *    applied to one operand that can make them match, in which
749       *    case this conversion is done."
750       */
751      if ((!apply_implicit_conversion(op[0]->type, op[1], state)
752	   && !apply_implicit_conversion(op[1]->type, op[0], state))
753	  || (op[0]->type != op[1]->type)) {
754	 _mesa_glsl_error(& loc, state, "operands of `%s' must have the same "
755			  "type", (this->oper == ast_equal) ? "==" : "!=");
756	 error_emitted = true;
757      } else if ((state->language_version <= 110)
758		 && (op[0]->type->is_array() || op[1]->type->is_array())) {
759	 _mesa_glsl_error(& loc, state, "array comparisons forbidden in "
760			  "GLSL 1.10");
761	 error_emitted = true;
762      }
763
764      result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
765				      op[0], op[1]);
766      type = glsl_type::bool_type;
767
768      assert(result->type == glsl_type::bool_type);
769      break;
770
771   case ast_bit_and:
772   case ast_bit_xor:
773   case ast_bit_or:
774   case ast_bit_not:
775      _mesa_glsl_error(& loc, state, "FINISHME: implement bit-wise operators");
776      error_emitted = true;
777      break;
778
779   case ast_logic_and: {
780      op[0] = this->subexpressions[0]->hir(instructions, state);
781
782      if (!op[0]->type->is_boolean() || !op[0]->type->is_scalar()) {
783	 YYLTYPE loc = this->subexpressions[0]->get_location();
784
785	 _mesa_glsl_error(& loc, state, "LHS of `%s' must be scalar boolean",
786			  operator_string(this->oper));
787	 error_emitted = true;
788      }
789
790      ir_constant *op0_const = op[0]->constant_expression_value();
791      if (op0_const) {
792	 if (op0_const->value.b[0]) {
793	    op[1] = this->subexpressions[1]->hir(instructions, state);
794
795	    if (!op[1]->type->is_boolean() || !op[1]->type->is_scalar()) {
796	       YYLTYPE loc = this->subexpressions[1]->get_location();
797
798	       _mesa_glsl_error(& loc, state,
799				"RHS of `%s' must be scalar boolean",
800				operator_string(this->oper));
801	       error_emitted = true;
802	    }
803	    result = op[1];
804	 } else {
805	    result = op0_const;
806	 }
807	 type = glsl_type::bool_type;
808      } else {
809	 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
810						       "and_tmp",
811						       ir_var_temporary);
812	 instructions->push_tail(tmp);
813
814	 ir_if *const stmt = new(ctx) ir_if(op[0]);
815	 instructions->push_tail(stmt);
816
817	 op[1] = this->subexpressions[1]->hir(&stmt->then_instructions, state);
818
819	 if (!op[1]->type->is_boolean() || !op[1]->type->is_scalar()) {
820	    YYLTYPE loc = this->subexpressions[1]->get_location();
821
822	    _mesa_glsl_error(& loc, state,
823			     "RHS of `%s' must be scalar boolean",
824			     operator_string(this->oper));
825	    error_emitted = true;
826	 }
827
828	 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
829	 ir_assignment *const then_assign =
830	    new(ctx) ir_assignment(then_deref, op[1], NULL);
831	 stmt->then_instructions.push_tail(then_assign);
832
833	 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
834	 ir_assignment *const else_assign =
835	    new(ctx) ir_assignment(else_deref, new(ctx) ir_constant(false), NULL);
836	 stmt->else_instructions.push_tail(else_assign);
837
838	 result = new(ctx) ir_dereference_variable(tmp);
839	 type = tmp->type;
840      }
841      break;
842   }
843
844   case ast_logic_or: {
845      op[0] = this->subexpressions[0]->hir(instructions, state);
846
847      if (!op[0]->type->is_boolean() || !op[0]->type->is_scalar()) {
848	 YYLTYPE loc = this->subexpressions[0]->get_location();
849
850	 _mesa_glsl_error(& loc, state, "LHS of `%s' must be scalar boolean",
851			  operator_string(this->oper));
852	 error_emitted = true;
853      }
854
855      ir_constant *op0_const = op[0]->constant_expression_value();
856      if (op0_const) {
857	 if (op0_const->value.b[0]) {
858	    result = op0_const;
859	 } else {
860	    op[1] = this->subexpressions[1]->hir(instructions, state);
861
862	    if (!op[1]->type->is_boolean() || !op[1]->type->is_scalar()) {
863	       YYLTYPE loc = this->subexpressions[1]->get_location();
864
865	       _mesa_glsl_error(& loc, state,
866				"RHS of `%s' must be scalar boolean",
867				operator_string(this->oper));
868	       error_emitted = true;
869	    }
870	    result = op[1];
871	 }
872	 type = glsl_type::bool_type;
873      } else {
874	 ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
875						       "or_tmp",
876						       ir_var_temporary);
877	 instructions->push_tail(tmp);
878
879	 ir_if *const stmt = new(ctx) ir_if(op[0]);
880	 instructions->push_tail(stmt);
881
882	 op[1] = this->subexpressions[1]->hir(&stmt->then_instructions, state);
883
884	 if (!op[1]->type->is_boolean() || !op[1]->type->is_scalar()) {
885	    YYLTYPE loc = this->subexpressions[1]->get_location();
886
887	    _mesa_glsl_error(& loc, state, "RHS of `%s' must be scalar boolean",
888			     operator_string(this->oper));
889	    error_emitted = true;
890	 }
891
892	 ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
893	 ir_assignment *const then_assign =
894	    new(ctx) ir_assignment(then_deref, new(ctx) ir_constant(true), NULL);
895	 stmt->then_instructions.push_tail(then_assign);
896
897	 ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
898	 ir_assignment *const else_assign =
899	    new(ctx) ir_assignment(else_deref, op[1], NULL);
900	 stmt->else_instructions.push_tail(else_assign);
901
902	 result = new(ctx) ir_dereference_variable(tmp);
903	 type = tmp->type;
904      }
905      break;
906   }
907
908   case ast_logic_xor:
909      op[0] = this->subexpressions[0]->hir(instructions, state);
910      op[1] = this->subexpressions[1]->hir(instructions, state);
911
912
913      result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
914				      op[0], op[1]);
915      type = glsl_type::bool_type;
916      break;
917
918   case ast_logic_not:
919      op[0] = this->subexpressions[0]->hir(instructions, state);
920
921      if (!op[0]->type->is_boolean() || !op[0]->type->is_scalar()) {
922	 YYLTYPE loc = this->subexpressions[0]->get_location();
923
924	 _mesa_glsl_error(& loc, state,
925			  "operand of `!' must be scalar boolean");
926	 error_emitted = true;
927      }
928
929      result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
930				      op[0], NULL);
931      type = glsl_type::bool_type;
932      break;
933
934   case ast_mul_assign:
935   case ast_div_assign:
936   case ast_add_assign:
937   case ast_sub_assign: {
938      op[0] = this->subexpressions[0]->hir(instructions, state);
939      op[1] = this->subexpressions[1]->hir(instructions, state);
940
941      type = arithmetic_result_type(op[0], op[1],
942				    (this->oper == ast_mul_assign),
943				    state, & loc);
944
945      ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
946						   op[0], op[1]);
947
948      result = do_assignment(instructions, state,
949			     op[0]->clone(NULL), temp_rhs,
950			     this->subexpressions[0]->get_location());
951      type = result->type;
952      error_emitted = (op[0]->type->is_error());
953
954      /* GLSL 1.10 does not allow array assignment.  However, we don't have to
955       * explicitly test for this because none of the binary expression
956       * operators allow array operands either.
957       */
958
959      break;
960   }
961
962   case ast_mod_assign: {
963      op[0] = this->subexpressions[0]->hir(instructions, state);
964      op[1] = this->subexpressions[1]->hir(instructions, state);
965
966      type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
967
968      assert(operations[this->oper] == ir_binop_mod);
969
970      struct ir_rvalue *temp_rhs;
971      temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
972					op[0], op[1]);
973
974      result = do_assignment(instructions, state,
975			     op[0]->clone(NULL), temp_rhs,
976			     this->subexpressions[0]->get_location());
977      type = result->type;
978      error_emitted = type->is_error();
979      break;
980   }
981
982   case ast_ls_assign:
983   case ast_rs_assign:
984      _mesa_glsl_error(& loc, state,
985		       "FINISHME: implement bit-shift assignment operators");
986      error_emitted = true;
987      break;
988
989   case ast_and_assign:
990   case ast_xor_assign:
991   case ast_or_assign:
992      _mesa_glsl_error(& loc, state,
993		       "FINISHME: implement logic assignment operators");
994      error_emitted = true;
995      break;
996
997   case ast_conditional: {
998      op[0] = this->subexpressions[0]->hir(instructions, state);
999
1000      /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1001       *
1002       *    "The ternary selection operator (?:). It operates on three
1003       *    expressions (exp1 ? exp2 : exp3). This operator evaluates the
1004       *    first expression, which must result in a scalar Boolean."
1005       */
1006      if (!op[0]->type->is_boolean() || !op[0]->type->is_scalar()) {
1007	 YYLTYPE loc = this->subexpressions[0]->get_location();
1008
1009	 _mesa_glsl_error(& loc, state, "?: condition must be scalar boolean");
1010	 error_emitted = true;
1011      }
1012
1013      /* The :? operator is implemented by generating an anonymous temporary
1014       * followed by an if-statement.  The last instruction in each branch of
1015       * the if-statement assigns a value to the anonymous temporary.  This
1016       * temporary is the r-value of the expression.
1017       */
1018      exec_list then_instructions;
1019      exec_list else_instructions;
1020
1021      op[1] = this->subexpressions[1]->hir(&then_instructions, state);
1022      op[2] = this->subexpressions[2]->hir(&else_instructions, state);
1023
1024      /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
1025       *
1026       *     "The second and third expressions can be any type, as
1027       *     long their types match, or there is a conversion in
1028       *     Section 4.1.10 "Implicit Conversions" that can be applied
1029       *     to one of the expressions to make their types match. This
1030       *     resulting matching type is the type of the entire
1031       *     expression."
1032       */
1033      if ((!apply_implicit_conversion(op[1]->type, op[2], state)
1034	   && !apply_implicit_conversion(op[2]->type, op[1], state))
1035	  || (op[1]->type != op[2]->type)) {
1036	 YYLTYPE loc = this->subexpressions[1]->get_location();
1037
1038	 _mesa_glsl_error(& loc, state, "Second and third operands of ?: "
1039			  "operator must have matching types.");
1040	 error_emitted = true;
1041	 type = glsl_type::error_type;
1042      } else {
1043	 type = op[1]->type;
1044      }
1045
1046      ir_constant *cond_val = op[0]->constant_expression_value();
1047      ir_constant *then_val = op[1]->constant_expression_value();
1048      ir_constant *else_val = op[2]->constant_expression_value();
1049
1050      if (then_instructions.is_empty()
1051	  && else_instructions.is_empty()
1052	  && (cond_val != NULL) && (then_val != NULL) && (else_val != NULL)) {
1053	 result = (cond_val->value.b[0]) ? then_val : else_val;
1054      } else {
1055	 ir_variable *const tmp =
1056	    new(ctx) ir_variable(type, "conditional_tmp", ir_var_temporary);
1057	 instructions->push_tail(tmp);
1058
1059	 ir_if *const stmt = new(ctx) ir_if(op[0]);
1060	 instructions->push_tail(stmt);
1061
1062	 then_instructions.move_nodes_to(& stmt->then_instructions);
1063	 ir_dereference *const then_deref =
1064	    new(ctx) ir_dereference_variable(tmp);
1065	 ir_assignment *const then_assign =
1066	    new(ctx) ir_assignment(then_deref, op[1], NULL);
1067	 stmt->then_instructions.push_tail(then_assign);
1068
1069	 else_instructions.move_nodes_to(& stmt->else_instructions);
1070	 ir_dereference *const else_deref =
1071	    new(ctx) ir_dereference_variable(tmp);
1072	 ir_assignment *const else_assign =
1073	    new(ctx) ir_assignment(else_deref, op[2], NULL);
1074	 stmt->else_instructions.push_tail(else_assign);
1075
1076	 result = new(ctx) ir_dereference_variable(tmp);
1077      }
1078      break;
1079   }
1080
1081   case ast_pre_inc:
1082   case ast_pre_dec: {
1083      op[0] = this->subexpressions[0]->hir(instructions, state);
1084      if (op[0]->type->base_type == GLSL_TYPE_FLOAT)
1085	 op[1] = new(ctx) ir_constant(1.0f);
1086      else
1087	 op[1] = new(ctx) ir_constant(1);
1088
1089      type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1090
1091      struct ir_rvalue *temp_rhs;
1092      temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1093					op[0], op[1]);
1094
1095      result = do_assignment(instructions, state,
1096			     op[0]->clone(NULL), temp_rhs,
1097			     this->subexpressions[0]->get_location());
1098      type = result->type;
1099      error_emitted = op[0]->type->is_error();
1100      break;
1101   }
1102
1103   case ast_post_inc:
1104   case ast_post_dec: {
1105      op[0] = this->subexpressions[0]->hir(instructions, state);
1106      if (op[0]->type->base_type == GLSL_TYPE_FLOAT)
1107	 op[1] = new(ctx) ir_constant(1.0f);
1108      else
1109	 op[1] = new(ctx) ir_constant(1);
1110
1111      error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1112
1113      type = arithmetic_result_type(op[0], op[1], false, state, & loc);
1114
1115      struct ir_rvalue *temp_rhs;
1116      temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
1117					op[0], op[1]);
1118
1119      /* Get a temporary of a copy of the lvalue before it's modified.
1120       * This may get thrown away later.
1121       */
1122      result = get_lvalue_copy(instructions, op[0]->clone(NULL));
1123
1124      (void)do_assignment(instructions, state,
1125			  op[0]->clone(NULL), temp_rhs,
1126			  this->subexpressions[0]->get_location());
1127
1128      type = result->type;
1129      error_emitted = op[0]->type->is_error();
1130      break;
1131   }
1132
1133   case ast_field_selection:
1134      result = _mesa_ast_field_selection_to_hir(this, instructions, state);
1135      type = result->type;
1136      break;
1137
1138   case ast_array_index: {
1139      YYLTYPE index_loc = subexpressions[1]->get_location();
1140
1141      op[0] = subexpressions[0]->hir(instructions, state);
1142      op[1] = subexpressions[1]->hir(instructions, state);
1143
1144      error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
1145
1146      ir_rvalue *const array = op[0];
1147
1148      result = new(ctx) ir_dereference_array(op[0], op[1]);
1149
1150      /* Do not use op[0] after this point.  Use array.
1151       */
1152      op[0] = NULL;
1153
1154
1155      if (error_emitted)
1156	 break;
1157
1158      if (!array->type->is_array()
1159	  && !array->type->is_matrix()
1160	  && !array->type->is_vector()) {
1161	 _mesa_glsl_error(& index_loc, state,
1162			  "cannot dereference non-array / non-matrix / "
1163			  "non-vector");
1164	 error_emitted = true;
1165      }
1166
1167      if (!op[1]->type->is_integer()) {
1168	 _mesa_glsl_error(& index_loc, state,
1169			  "array index must be integer type");
1170	 error_emitted = true;
1171      } else if (!op[1]->type->is_scalar()) {
1172	 _mesa_glsl_error(& index_loc, state,
1173			  "array index must be scalar");
1174	 error_emitted = true;
1175      }
1176
1177      /* If the array index is a constant expression and the array has a
1178       * declared size, ensure that the access is in-bounds.  If the array
1179       * index is not a constant expression, ensure that the array has a
1180       * declared size.
1181       */
1182      ir_constant *const const_index = op[1]->constant_expression_value();
1183      if (const_index != NULL) {
1184	 const int idx = const_index->value.i[0];
1185	 const char *type_name;
1186	 unsigned bound = 0;
1187
1188	 if (array->type->is_matrix()) {
1189	    type_name = "matrix";
1190	 } else if (array->type->is_vector()) {
1191	    type_name = "vector";
1192	 } else {
1193	    type_name = "array";
1194	 }
1195
1196	 /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
1197	  *
1198	  *    "It is illegal to declare an array with a size, and then
1199	  *    later (in the same shader) index the same array with an
1200	  *    integral constant expression greater than or equal to the
1201	  *    declared size. It is also illegal to index an array with a
1202	  *    negative constant expression."
1203	  */
1204	 if (array->type->is_matrix()) {
1205	    if (array->type->row_type()->vector_elements <= idx) {
1206	       bound = array->type->row_type()->vector_elements;
1207	    }
1208	 } else if (array->type->is_vector()) {
1209	    if (array->type->vector_elements <= idx) {
1210	       bound = array->type->vector_elements;
1211	    }
1212	 } else {
1213	    if ((array->type->array_size() > 0)
1214		&& (array->type->array_size() <= idx)) {
1215	       bound = array->type->array_size();
1216	    }
1217	 }
1218
1219	 if (bound > 0) {
1220	    _mesa_glsl_error(& loc, state, "%s index must be < %u",
1221			     type_name, bound);
1222	    error_emitted = true;
1223	 } else if (idx < 0) {
1224	    _mesa_glsl_error(& loc, state, "%s index must be >= 0",
1225			     type_name);
1226	    error_emitted = true;
1227	 }
1228
1229	 if (array->type->is_array()) {
1230	    /* If the array is a variable dereference, it dereferences the
1231	     * whole array, by definition.  Use this to get the variable.
1232	     *
1233	     * FINISHME: Should some methods for getting / setting / testing
1234	     * FINISHME: array access limits be added to ir_dereference?
1235	     */
1236	    ir_variable *const v = array->whole_variable_referenced();
1237	    if ((v != NULL) && (unsigned(idx) > v->max_array_access))
1238	       v->max_array_access = idx;
1239	 }
1240      } else if (array->type->array_size() == 0) {
1241	 _mesa_glsl_error(&loc, state, "unsized array index must be constant");
1242      }
1243
1244      if (error_emitted)
1245	 result->type = glsl_type::error_type;
1246
1247      type = result->type;
1248      break;
1249   }
1250
1251   case ast_function_call:
1252      /* Should *NEVER* get here.  ast_function_call should always be handled
1253       * by ast_function_expression::hir.
1254       */
1255      assert(0);
1256      break;
1257
1258   case ast_identifier: {
1259      /* ast_identifier can appear several places in a full abstract syntax
1260       * tree.  This particular use must be at location specified in the grammar
1261       * as 'variable_identifier'.
1262       */
1263      ir_variable *var =
1264	 state->symbols->get_variable(this->primary_expression.identifier);
1265
1266      result = new(ctx) ir_dereference_variable(var);
1267
1268      if (var != NULL) {
1269	 type = result->type;
1270      } else {
1271	 _mesa_glsl_error(& loc, state, "`%s' undeclared",
1272			  this->primary_expression.identifier);
1273
1274	 error_emitted = true;
1275      }
1276      break;
1277   }
1278
1279   case ast_int_constant:
1280      type = glsl_type::int_type;
1281      result = new(ctx) ir_constant(this->primary_expression.int_constant);
1282      break;
1283
1284   case ast_uint_constant:
1285      type = glsl_type::uint_type;
1286      result = new(ctx) ir_constant(this->primary_expression.uint_constant);
1287      break;
1288
1289   case ast_float_constant:
1290      type = glsl_type::float_type;
1291      result = new(ctx) ir_constant(this->primary_expression.float_constant);
1292      break;
1293
1294   case ast_bool_constant:
1295      type = glsl_type::bool_type;
1296      result = new(ctx) ir_constant(bool(this->primary_expression.bool_constant));
1297      break;
1298
1299   case ast_sequence: {
1300      /* It should not be possible to generate a sequence in the AST without
1301       * any expressions in it.
1302       */
1303      assert(!this->expressions.is_empty());
1304
1305      /* The r-value of a sequence is the last expression in the sequence.  If
1306       * the other expressions in the sequence do not have side-effects (and
1307       * therefore add instructions to the instruction list), they get dropped
1308       * on the floor.
1309       */
1310      foreach_list_typed (ast_node, ast, link, &this->expressions)
1311	 result = ast->hir(instructions, state);
1312
1313      type = result->type;
1314
1315      /* Any errors should have already been emitted in the loop above.
1316       */
1317      error_emitted = true;
1318      break;
1319   }
1320   }
1321
1322   if (type->is_error() && !error_emitted)
1323      _mesa_glsl_error(& loc, state, "type mismatch");
1324
1325   return result;
1326}
1327
1328
1329ir_rvalue *
1330ast_expression_statement::hir(exec_list *instructions,
1331			      struct _mesa_glsl_parse_state *state)
1332{
1333   /* It is possible to have expression statements that don't have an
1334    * expression.  This is the solitary semicolon:
1335    *
1336    * for (i = 0; i < 5; i++)
1337    *     ;
1338    *
1339    * In this case the expression will be NULL.  Test for NULL and don't do
1340    * anything in that case.
1341    */
1342   if (expression != NULL)
1343      expression->hir(instructions, state);
1344
1345   /* Statements do not have r-values.
1346    */
1347   return NULL;
1348}
1349
1350
1351ir_rvalue *
1352ast_compound_statement::hir(exec_list *instructions,
1353			    struct _mesa_glsl_parse_state *state)
1354{
1355   if (new_scope)
1356      state->symbols->push_scope();
1357
1358   foreach_list_typed (ast_node, ast, link, &this->statements)
1359      ast->hir(instructions, state);
1360
1361   if (new_scope)
1362      state->symbols->pop_scope();
1363
1364   /* Compound statements do not have r-values.
1365    */
1366   return NULL;
1367}
1368
1369
1370static const glsl_type *
1371process_array_type(const glsl_type *base, ast_node *array_size,
1372		   struct _mesa_glsl_parse_state *state)
1373{
1374   unsigned length = 0;
1375
1376   /* FINISHME: Reject delcarations of multidimensional arrays. */
1377
1378   if (array_size != NULL) {
1379      exec_list dummy_instructions;
1380      ir_rvalue *const ir = array_size->hir(& dummy_instructions, state);
1381      YYLTYPE loc = array_size->get_location();
1382
1383      /* FINISHME: Verify that the grammar forbids side-effects in array
1384       * FINISHME: sizes.   i.e., 'vec4 [x = 12] data'
1385       */
1386      assert(dummy_instructions.is_empty());
1387
1388      if (ir != NULL) {
1389	 if (!ir->type->is_integer()) {
1390	    _mesa_glsl_error(& loc, state, "array size must be integer type");
1391	 } else if (!ir->type->is_scalar()) {
1392	    _mesa_glsl_error(& loc, state, "array size must be scalar type");
1393	 } else {
1394	    ir_constant *const size = ir->constant_expression_value();
1395
1396	    if (size == NULL) {
1397	       _mesa_glsl_error(& loc, state, "array size must be a "
1398				"constant valued expression");
1399	    } else if (size->value.i[0] <= 0) {
1400	       _mesa_glsl_error(& loc, state, "array size must be > 0");
1401	    } else {
1402	       assert(size->type == ir->type);
1403	       length = size->value.u[0];
1404	    }
1405	 }
1406      }
1407   }
1408
1409   return glsl_type::get_array_instance(base, length);
1410}
1411
1412
1413const glsl_type *
1414ast_type_specifier::glsl_type(const char **name,
1415			      struct _mesa_glsl_parse_state *state) const
1416{
1417   const struct glsl_type *type;
1418
1419   if ((this->type_specifier == ast_struct) && (this->type_name == NULL)) {
1420      /* FINISHME: Handle annonymous structures. */
1421      type = NULL;
1422   } else {
1423      type = state->symbols->get_type(this->type_name);
1424      *name = this->type_name;
1425
1426      if (this->is_array) {
1427	 type = process_array_type(type, this->array_size, state);
1428      }
1429   }
1430
1431   return type;
1432}
1433
1434
1435static void
1436apply_type_qualifier_to_variable(const struct ast_type_qualifier *qual,
1437				 struct ir_variable *var,
1438				 struct _mesa_glsl_parse_state *state,
1439				 YYLTYPE *loc)
1440{
1441   if (qual->invariant)
1442      var->invariant = 1;
1443
1444   /* FINISHME: Mark 'in' variables at global scope as read-only. */
1445   if (qual->constant || qual->attribute || qual->uniform
1446       || (qual->varying && (state->target == fragment_shader)))
1447      var->read_only = 1;
1448
1449   if (qual->centroid)
1450      var->centroid = 1;
1451
1452   if (qual->attribute && state->target != vertex_shader) {
1453      var->type = glsl_type::error_type;
1454      _mesa_glsl_error(loc, state,
1455		       "`attribute' variables may not be declared in the "
1456		       "%s shader",
1457		       _mesa_glsl_shader_target_name(state->target));
1458   }
1459
1460   /* From page 25 (page 31 of the PDF) of the GLSL 1.10 spec:
1461    *
1462    *     "The varying qualifier can be used only with the data types
1463    *     float, vec2, vec3, vec4, mat2, mat3, and mat4, or arrays of
1464    *     these."
1465    */
1466   if (qual->varying) {
1467      const glsl_type *non_array_type;
1468
1469      if (var->type && var->type->is_array())
1470	 non_array_type = var->type->fields.array;
1471      else
1472	 non_array_type = var->type;
1473
1474      if (non_array_type && non_array_type->base_type != GLSL_TYPE_FLOAT) {
1475	 var->type = glsl_type::error_type;
1476	 _mesa_glsl_error(loc, state,
1477			  "varying variables must be of base type float");
1478      }
1479   }
1480
1481   /* If there is no qualifier that changes the mode of the variable, leave
1482    * the setting alone.
1483    */
1484   if (qual->in && qual->out)
1485      var->mode = ir_var_inout;
1486   else if (qual->attribute || qual->in
1487	    || (qual->varying && (state->target == fragment_shader)))
1488      var->mode = ir_var_in;
1489   else if (qual->out || (qual->varying && (state->target == vertex_shader)))
1490      var->mode = ir_var_out;
1491   else if (qual->uniform)
1492      var->mode = ir_var_uniform;
1493
1494   if (qual->uniform)
1495      var->shader_in = true;
1496
1497   /* Any 'in' or 'inout' variables at global scope must be marked as being
1498    * shader inputs.  Likewise, any 'out' or 'inout' variables at global scope
1499    * must be marked as being shader outputs.
1500    */
1501   if (state->current_function == NULL) {
1502      switch (var->mode) {
1503      case ir_var_in:
1504      case ir_var_uniform:
1505	 var->shader_in = true;
1506	 break;
1507      case ir_var_out:
1508	 var->shader_out = true;
1509	 break;
1510      case ir_var_inout:
1511	 var->shader_in = true;
1512	 var->shader_out = true;
1513	 break;
1514      default:
1515	 break;
1516      }
1517   }
1518
1519   if (qual->flat)
1520      var->interpolation = ir_var_flat;
1521   else if (qual->noperspective)
1522      var->interpolation = ir_var_noperspective;
1523   else
1524      var->interpolation = ir_var_smooth;
1525
1526   if (var->type->is_array() && (state->language_version >= 120)) {
1527      var->array_lvalue = true;
1528   }
1529}
1530
1531
1532ir_rvalue *
1533ast_declarator_list::hir(exec_list *instructions,
1534			 struct _mesa_glsl_parse_state *state)
1535{
1536   void *ctx = state;
1537   const struct glsl_type *decl_type;
1538   const char *type_name = NULL;
1539   ir_rvalue *result = NULL;
1540   YYLTYPE loc = this->get_location();
1541
1542   /* From page 46 (page 52 of the PDF) of the GLSL 1.50 spec:
1543    *
1544    *     "To ensure that a particular output variable is invariant, it is
1545    *     necessary to use the invariant qualifier. It can either be used to
1546    *     qualify a previously declared variable as being invariant
1547    *
1548    *         invariant gl_Position; // make existing gl_Position be invariant"
1549    *
1550    * In these cases the parser will set the 'invariant' flag in the declarator
1551    * list, and the type will be NULL.
1552    */
1553   if (this->invariant) {
1554      assert(this->type == NULL);
1555
1556      if (state->current_function != NULL) {
1557	 _mesa_glsl_error(& loc, state,
1558			  "All uses of `invariant' keyword must be at global "
1559			  "scope\n");
1560      }
1561
1562      foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
1563	 assert(!decl->is_array);
1564	 assert(decl->array_size == NULL);
1565	 assert(decl->initializer == NULL);
1566
1567	 ir_variable *const earlier =
1568	    state->symbols->get_variable(decl->identifier);
1569	 if (earlier == NULL) {
1570	    _mesa_glsl_error(& loc, state,
1571			     "Undeclared variable `%s' cannot be marked "
1572			     "invariant\n", decl->identifier);
1573	 } else if ((state->target == vertex_shader)
1574	       && (earlier->mode != ir_var_out)) {
1575	    _mesa_glsl_error(& loc, state,
1576			     "`%s' cannot be marked invariant, vertex shader "
1577			     "outputs only\n", decl->identifier);
1578	 } else if ((state->target == fragment_shader)
1579	       && (earlier->mode != ir_var_in)) {
1580	    _mesa_glsl_error(& loc, state,
1581			     "`%s' cannot be marked invariant, fragment shader "
1582			     "inputs only\n", decl->identifier);
1583	 } else {
1584	    earlier->invariant = true;
1585	 }
1586      }
1587
1588      /* Invariant redeclarations do not have r-values.
1589       */
1590      return NULL;
1591   }
1592
1593   assert(this->type != NULL);
1594   assert(!this->invariant);
1595
1596   /* The type specifier may contain a structure definition.  Process that
1597    * before any of the variable declarations.
1598    */
1599   (void) this->type->specifier->hir(instructions, state);
1600
1601   decl_type = this->type->specifier->glsl_type(& type_name, state);
1602   if (this->declarations.is_empty()) {
1603      /* The only valid case where the declaration list can be empty is when
1604       * the declaration is setting the default precision of a built-in type
1605       * (e.g., 'precision highp vec4;').
1606       */
1607
1608      if (decl_type != NULL) {
1609      } else {
1610	    _mesa_glsl_error(& loc, state, "incomplete declaration");
1611      }
1612   }
1613
1614   foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
1615      const struct glsl_type *var_type;
1616      struct ir_variable *var;
1617
1618      /* FINISHME: Emit a warning if a variable declaration shadows a
1619       * FINISHME: declaration at a higher scope.
1620       */
1621
1622      if ((decl_type == NULL) || decl_type->is_void()) {
1623	 if (type_name != NULL) {
1624	    _mesa_glsl_error(& loc, state,
1625			     "invalid type `%s' in declaration of `%s'",
1626			     type_name, decl->identifier);
1627	 } else {
1628	    _mesa_glsl_error(& loc, state,
1629			     "invalid type in declaration of `%s'",
1630			     decl->identifier);
1631	 }
1632	 continue;
1633      }
1634
1635      if (decl->is_array) {
1636	 var_type = process_array_type(decl_type, decl->array_size, state);
1637      } else {
1638	 var_type = decl_type;
1639      }
1640
1641      var = new(ctx) ir_variable(var_type, decl->identifier, ir_var_auto);
1642
1643      /* From page 22 (page 28 of the PDF) of the GLSL 1.10 specification;
1644       *
1645       *     "Global variables can only use the qualifiers const,
1646       *     attribute, uni form, or varying. Only one may be
1647       *     specified.
1648       *
1649       *     Local variables can only use the qualifier const."
1650       *
1651       * This is relaxed in GLSL 1.30.
1652       */
1653      if (state->language_version < 120) {
1654	 if (this->type->qualifier.out) {
1655	    _mesa_glsl_error(& loc, state,
1656			     "`out' qualifier in declaration of `%s' "
1657			     "only valid for function parameters in GLSL 1.10.",
1658			     decl->identifier);
1659	 }
1660	 if (this->type->qualifier.in) {
1661	    _mesa_glsl_error(& loc, state,
1662			     "`in' qualifier in declaration of `%s' "
1663			     "only valid for function parameters in GLSL 1.10.",
1664			     decl->identifier);
1665	 }
1666	 /* FINISHME: Test for other invalid qualifiers. */
1667      }
1668
1669      apply_type_qualifier_to_variable(& this->type->qualifier, var, state,
1670				       & loc);
1671
1672      if (this->type->qualifier.invariant) {
1673	 if ((state->target == vertex_shader) && !var->shader_out) {
1674	    _mesa_glsl_error(& loc, state,
1675			     "`%s' cannot be marked invariant, vertex shader "
1676			     "outputs only\n", var->name);
1677	 } else if ((state->target == fragment_shader) && !var->shader_in) {
1678	    _mesa_glsl_error(& loc, state,
1679			     "`%s' cannot be marked invariant, fragment shader "
1680			     "inputs only\n", var->name);
1681	 }
1682      }
1683
1684      if (state->current_function != NULL) {
1685	 const char *mode = NULL;
1686	 const char *extra = "";
1687
1688	 /* There is no need to check for 'inout' here because the parser will
1689	  * only allow that in function parameter lists.
1690	  */
1691	 if (this->type->qualifier.attribute) {
1692	    mode = "attribute";
1693	 } else if (this->type->qualifier.uniform) {
1694	    mode = "uniform";
1695	 } else if (this->type->qualifier.varying) {
1696	    mode = "varying";
1697	 } else if (this->type->qualifier.in) {
1698	    mode = "in";
1699	    extra = " or in function parameter list";
1700	 } else if (this->type->qualifier.out) {
1701	    mode = "out";
1702	    extra = " or in function parameter list";
1703	 }
1704
1705	 if (mode) {
1706	    _mesa_glsl_error(& loc, state,
1707			     "%s variable `%s' must be declared at "
1708			     "global scope%s",
1709			     mode, var->name, extra);
1710	 }
1711      } else if (var->mode == ir_var_in) {
1712	 if (state->target == vertex_shader) {
1713	    bool error_emitted = false;
1714
1715	    /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
1716	     *
1717	     *    "Vertex shader inputs can only be float, floating-point
1718	     *    vectors, matrices, signed and unsigned integers and integer
1719	     *    vectors. Vertex shader inputs can also form arrays of these
1720	     *    types, but not structures."
1721	     *
1722	     * From page 31 (page 27 of the PDF) of the GLSL 1.30 spec:
1723	     *
1724	     *    "Vertex shader inputs can only be float, floating-point
1725	     *    vectors, matrices, signed and unsigned integers and integer
1726	     *    vectors. They cannot be arrays or structures."
1727	     *
1728	     * From page 23 (page 29 of the PDF) of the GLSL 1.20 spec:
1729	     *
1730	     *    "The attribute qualifier can be used only with float,
1731	     *    floating-point vectors, and matrices. Attribute variables
1732	     *    cannot be declared as arrays or structures."
1733	     */
1734	    const glsl_type *check_type = var->type->is_array()
1735	       ? var->type->fields.array : var->type;
1736
1737	    switch (check_type->base_type) {
1738	    case GLSL_TYPE_FLOAT:
1739	       break;
1740	    case GLSL_TYPE_UINT:
1741	    case GLSL_TYPE_INT:
1742	       if (state->language_version > 120)
1743		  break;
1744	       /* FALLTHROUGH */
1745	    default:
1746	       _mesa_glsl_error(& loc, state,
1747				"vertex shader input / attribute cannot have "
1748				"type %s`%s'",
1749				var->type->is_array() ? "array of " : "",
1750				check_type->name);
1751	       error_emitted = true;
1752	    }
1753
1754	    if (!error_emitted && (state->language_version <= 130)
1755		&& var->type->is_array()) {
1756	       _mesa_glsl_error(& loc, state,
1757				"vertex shader input / attribute cannot have "
1758				"array type");
1759	       error_emitted = true;
1760	    }
1761	 }
1762      }
1763
1764      /* Process the initializer and add its instructions to a temporary
1765       * list.  This list will be added to the instruction stream (below) after
1766       * the declaration is added.  This is done because in some cases (such as
1767       * redeclarations) the declaration may not actually be added to the
1768       * instruction stream.
1769       */
1770      exec_list intializer_instructions;
1771      if (decl->initializer != NULL) {
1772	 YYLTYPE initializer_loc = decl->initializer->get_location();
1773
1774	 /* From page 24 (page 30 of the PDF) of the GLSL 1.10 spec:
1775	  *
1776	  *    "All uniform variables are read-only and are initialized either
1777	  *    directly by an application via API commands, or indirectly by
1778	  *    OpenGL."
1779	  */
1780	 if ((state->language_version <= 110)
1781	     && (var->mode == ir_var_uniform)) {
1782	    _mesa_glsl_error(& initializer_loc, state,
1783			     "cannot initialize uniforms in GLSL 1.10");
1784	 }
1785
1786	 if (var->type->is_sampler()) {
1787	    _mesa_glsl_error(& initializer_loc, state,
1788			     "cannot initialize samplers");
1789	 }
1790
1791	 if ((var->mode == ir_var_in) && (state->current_function == NULL)) {
1792	    _mesa_glsl_error(& initializer_loc, state,
1793			     "cannot initialize %s shader input / %s",
1794			     _mesa_glsl_shader_target_name(state->target),
1795			     (state->target == vertex_shader)
1796			     ? "attribute" : "varying");
1797	 }
1798
1799	 ir_dereference *const lhs = new(ctx) ir_dereference_variable(var);
1800	 ir_rvalue *rhs = decl->initializer->hir(&intializer_instructions,
1801						 state);
1802
1803	 /* Calculate the constant value if this is a const or uniform
1804	  * declaration.
1805	  */
1806	 if (this->type->qualifier.constant || this->type->qualifier.uniform) {
1807	    ir_rvalue *new_rhs = validate_assignment(state, var->type, rhs);
1808	    if (new_rhs != NULL) {
1809	       rhs = new_rhs;
1810	    } else {
1811	       _mesa_glsl_error(&initializer_loc, state,
1812			        "initializer of type %s cannot be assigned to "
1813				"variable of type %s",
1814				rhs->type->name, var->type->name);
1815	    }
1816
1817	    ir_constant *constant_value = rhs->constant_expression_value();
1818	    if (!constant_value) {
1819	       _mesa_glsl_error(& initializer_loc, state,
1820				"initializer of %s variable `%s' must be a "
1821				"constant expression",
1822				(this->type->qualifier.constant)
1823				? "const" : "uniform",
1824				decl->identifier);
1825	    } else {
1826	       rhs = constant_value;
1827	       var->constant_value = constant_value;
1828	    }
1829	 }
1830
1831	 if (rhs && !rhs->type->is_error()) {
1832	    bool temp = var->read_only;
1833	    if (this->type->qualifier.constant)
1834	       var->read_only = false;
1835
1836	    /* Never emit code to initialize a uniform.
1837	     */
1838	    if (!this->type->qualifier.uniform)
1839	       result = do_assignment(&intializer_instructions, state, lhs, rhs,
1840				      this->get_location());
1841	    var->read_only = temp;
1842	 }
1843      }
1844
1845      /* From page 23 (page 29 of the PDF) of the GLSL 1.10 spec:
1846       *
1847       *     "It is an error to write to a const variable outside of
1848       *      its declaration, so they must be initialized when
1849       *      declared."
1850       */
1851      if (this->type->qualifier.constant && decl->initializer == NULL) {
1852	 _mesa_glsl_error(& loc, state,
1853			  "const declaration of `%s' must be initialized");
1854      }
1855
1856      /* Attempt to add the variable to the symbol table.  If this fails, it
1857       * means the variable has already been declared at this scope.  Arrays
1858       * fudge this rule a little bit.
1859       *
1860       * From page 24 (page 30 of the PDF) of the GLSL 1.50 spec,
1861       *
1862       *    "It is legal to declare an array without a size and then
1863       *    later re-declare the same name as an array of the same
1864       *    type and specify a size."
1865       */
1866      if (state->symbols->name_declared_this_scope(decl->identifier)) {
1867	 ir_variable *const earlier =
1868	    state->symbols->get_variable(decl->identifier);
1869
1870	 if ((earlier != NULL)
1871	     && (earlier->type->array_size() == 0)
1872	     && var->type->is_array()
1873	     && (var->type->element_type() == earlier->type->element_type())) {
1874	    /* FINISHME: This doesn't match the qualifiers on the two
1875	     * FINISHME: declarations.  It's not 100% clear whether this is
1876	     * FINISHME: required or not.
1877	     */
1878
1879	    /* From page 54 (page 60 of the PDF) of the GLSL 1.20 spec:
1880	     *
1881	     *     "The size [of gl_TexCoord] can be at most
1882	     *     gl_MaxTextureCoords."
1883	     */
1884	    const unsigned size = unsigned(var->type->array_size());
1885	    if ((strcmp("gl_TexCoord", var->name) == 0)
1886		&& (size > state->Const.MaxTextureCoords)) {
1887	       YYLTYPE loc = this->get_location();
1888
1889	       _mesa_glsl_error(& loc, state, "`gl_TexCoord' array size cannot "
1890				"be larger than gl_MaxTextureCoords (%u)\n",
1891				state->Const.MaxTextureCoords);
1892	    } else if ((size > 0) && (size <= earlier->max_array_access)) {
1893	       YYLTYPE loc = this->get_location();
1894
1895	       _mesa_glsl_error(& loc, state, "array size must be > %u due to "
1896				"previous access",
1897				earlier->max_array_access);
1898	    }
1899
1900	    earlier->type = var->type;
1901	    delete var;
1902	    var = NULL;
1903	 } else {
1904	    YYLTYPE loc = this->get_location();
1905
1906	    _mesa_glsl_error(& loc, state, "`%s' redeclared",
1907			     decl->identifier);
1908	 }
1909
1910	 continue;
1911      }
1912
1913      /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
1914       *
1915       *   "Identifiers starting with "gl_" are reserved for use by
1916       *   OpenGL, and may not be declared in a shader as either a
1917       *   variable or a function."
1918       */
1919      if (strncmp(decl->identifier, "gl_", 3) == 0) {
1920	 /* FINISHME: This should only trigger if we're not redefining
1921	  * FINISHME: a builtin (to add a qualifier, for example).
1922	  */
1923	 _mesa_glsl_error(& loc, state,
1924			  "identifier `%s' uses reserved `gl_' prefix",
1925			  decl->identifier);
1926      }
1927
1928      instructions->push_tail(var);
1929      instructions->append_list(&intializer_instructions);
1930
1931      /* Add the variable to the symbol table after processing the initializer.
1932       * This differs from most C-like languages, but it follows the GLSL
1933       * specification.  From page 28 (page 34 of the PDF) of the GLSL 1.50
1934       * spec:
1935       *
1936       *     "Within a declaration, the scope of a name starts immediately
1937       *     after the initializer if present or immediately after the name
1938       *     being declared if not."
1939       */
1940      const bool added_variable =
1941	 state->symbols->add_variable(var->name, var);
1942      assert(added_variable);
1943   }
1944
1945
1946   /* Generally, variable declarations do not have r-values.  However,
1947    * one is used for the declaration in
1948    *
1949    * while (bool b = some_condition()) {
1950    *   ...
1951    * }
1952    *
1953    * so we return the rvalue from the last seen declaration here.
1954    */
1955   return result;
1956}
1957
1958
1959ir_rvalue *
1960ast_parameter_declarator::hir(exec_list *instructions,
1961			      struct _mesa_glsl_parse_state *state)
1962{
1963   void *ctx = state;
1964   const struct glsl_type *type;
1965   const char *name = NULL;
1966   YYLTYPE loc = this->get_location();
1967
1968   type = this->type->specifier->glsl_type(& name, state);
1969
1970   if (type == NULL) {
1971      if (name != NULL) {
1972	 _mesa_glsl_error(& loc, state,
1973			  "invalid type `%s' in declaration of `%s'",
1974			  name, this->identifier);
1975      } else {
1976	 _mesa_glsl_error(& loc, state,
1977			  "invalid type in declaration of `%s'",
1978			  this->identifier);
1979      }
1980
1981      type = glsl_type::error_type;
1982   }
1983
1984   /* From page 62 (page 68 of the PDF) of the GLSL 1.50 spec:
1985    *
1986    *    "Functions that accept no input arguments need not use void in the
1987    *    argument list because prototypes (or definitions) are required and
1988    *    therefore there is no ambiguity when an empty argument list "( )" is
1989    *    declared. The idiom "(void)" as a parameter list is provided for
1990    *    convenience."
1991    *
1992    * Placing this check here prevents a void parameter being set up
1993    * for a function, which avoids tripping up checks for main taking
1994    * parameters and lookups of an unnamed symbol.
1995    */
1996   if (type->is_void()) {
1997      if (this->identifier != NULL)
1998	 _mesa_glsl_error(& loc, state,
1999			  "named parameter cannot have type `void'");
2000
2001      is_void = true;
2002      return NULL;
2003   }
2004
2005   if (formal_parameter && (this->identifier == NULL)) {
2006      _mesa_glsl_error(& loc, state, "formal parameter lacks a name");
2007      return NULL;
2008   }
2009
2010   is_void = false;
2011   ir_variable *var = new(ctx) ir_variable(type, this->identifier, ir_var_in);
2012
2013   /* FINISHME: Handle array declarations.  Note that this requires
2014    * FINISHME: complete handling of constant expressions.
2015    */
2016
2017   /* Apply any specified qualifiers to the parameter declaration.  Note that
2018    * for function parameters the default mode is 'in'.
2019    */
2020   apply_type_qualifier_to_variable(& this->type->qualifier, var, state, & loc);
2021
2022   instructions->push_tail(var);
2023
2024   /* Parameter declarations do not have r-values.
2025    */
2026   return NULL;
2027}
2028
2029
2030void
2031ast_parameter_declarator::parameters_to_hir(exec_list *ast_parameters,
2032					    bool formal,
2033					    exec_list *ir_parameters,
2034					    _mesa_glsl_parse_state *state)
2035{
2036   ast_parameter_declarator *void_param = NULL;
2037   unsigned count = 0;
2038
2039   foreach_list_typed (ast_parameter_declarator, param, link, ast_parameters) {
2040      param->formal_parameter = formal;
2041      param->hir(ir_parameters, state);
2042
2043      if (param->is_void)
2044	 void_param = param;
2045
2046      count++;
2047   }
2048
2049   if ((void_param != NULL) && (count > 1)) {
2050      YYLTYPE loc = void_param->get_location();
2051
2052      _mesa_glsl_error(& loc, state,
2053		       "`void' parameter must be only parameter");
2054   }
2055}
2056
2057
2058ir_rvalue *
2059ast_function::hir(exec_list *instructions,
2060		  struct _mesa_glsl_parse_state *state)
2061{
2062   void *ctx = state;
2063   ir_function *f = NULL;
2064   ir_function_signature *sig = NULL;
2065   exec_list hir_parameters;
2066
2067   const char *const name = identifier;
2068
2069   /* Convert the list of function parameters to HIR now so that they can be
2070    * used below to compare this function's signature with previously seen
2071    * signatures for functions with the same name.
2072    */
2073   ast_parameter_declarator::parameters_to_hir(& this->parameters,
2074					       is_definition,
2075					       & hir_parameters, state);
2076
2077   const char *return_type_name;
2078   const glsl_type *return_type =
2079      this->return_type->specifier->glsl_type(& return_type_name, state);
2080
2081   assert(return_type != NULL);
2082
2083   /* From page 56 (page 62 of the PDF) of the GLSL 1.30 spec:
2084    * "No qualifier is allowed on the return type of a function."
2085    */
2086   if (this->return_type->has_qualifiers()) {
2087      YYLTYPE loc = this->get_location();
2088      _mesa_glsl_error(& loc, state,
2089		       "function `%s' return type has qualifiers", name);
2090   }
2091
2092   /* Verify that this function's signature either doesn't match a previously
2093    * seen signature for a function with the same name, or, if a match is found,
2094    * that the previously seen signature does not have an associated definition.
2095    */
2096   f = state->symbols->get_function(name);
2097   if (f != NULL) {
2098      ir_function_signature *sig = f->exact_matching_signature(&hir_parameters);
2099      if (sig != NULL) {
2100	 const char *badvar = sig->qualifiers_match(&hir_parameters);
2101	 if (badvar != NULL) {
2102	    YYLTYPE loc = this->get_location();
2103
2104	    _mesa_glsl_error(&loc, state, "function `%s' parameter `%s' "
2105			     "qualifiers don't match prototype", name, badvar);
2106	 }
2107
2108	 if (sig->return_type != return_type) {
2109	    YYLTYPE loc = this->get_location();
2110
2111	    _mesa_glsl_error(&loc, state, "function `%s' return type doesn't "
2112			     "match prototype", name);
2113	 }
2114
2115	 if (is_definition && sig->is_defined) {
2116	    YYLTYPE loc = this->get_location();
2117
2118	    _mesa_glsl_error(& loc, state, "function `%s' redefined", name);
2119	    sig = NULL;
2120	 }
2121      }
2122   } else if (state->symbols->name_declared_this_scope(name)) {
2123      /* This function name shadows a non-function use of the same name.
2124       */
2125      YYLTYPE loc = this->get_location();
2126
2127      _mesa_glsl_error(& loc, state, "function name `%s' conflicts with "
2128		       "non-function", name);
2129      sig = NULL;
2130   } else {
2131      f = new(ctx) ir_function(name);
2132      state->symbols->add_function(f->name, f);
2133
2134      /* Emit the new function header */
2135      instructions->push_tail(f);
2136   }
2137
2138   /* Verify the return type of main() */
2139   if (strcmp(name, "main") == 0) {
2140      if (! return_type->is_void()) {
2141	 YYLTYPE loc = this->get_location();
2142
2143	 _mesa_glsl_error(& loc, state, "main() must return void");
2144      }
2145
2146      if (!hir_parameters.is_empty()) {
2147	 YYLTYPE loc = this->get_location();
2148
2149	 _mesa_glsl_error(& loc, state, "main() must not take any parameters");
2150      }
2151   }
2152
2153   /* Finish storing the information about this new function in its signature.
2154    */
2155   if (sig == NULL) {
2156      sig = new(ctx) ir_function_signature(return_type);
2157      f->add_signature(sig);
2158   }
2159
2160   sig->replace_parameters(&hir_parameters);
2161   signature = sig;
2162
2163   /* Function declarations (prototypes) do not have r-values.
2164    */
2165   return NULL;
2166}
2167
2168
2169ir_rvalue *
2170ast_function_definition::hir(exec_list *instructions,
2171			     struct _mesa_glsl_parse_state *state)
2172{
2173   prototype->is_definition = true;
2174   prototype->hir(instructions, state);
2175
2176   ir_function_signature *signature = prototype->signature;
2177
2178   assert(state->current_function == NULL);
2179   state->current_function = signature;
2180   state->found_return = false;
2181
2182   /* Duplicate parameters declared in the prototype as concrete variables.
2183    * Add these to the symbol table.
2184    */
2185   state->symbols->push_scope();
2186   foreach_iter(exec_list_iterator, iter, signature->parameters) {
2187      ir_variable *const var = ((ir_instruction *) iter.get())->as_variable();
2188
2189      assert(var != NULL);
2190
2191      /* The only way a parameter would "exist" is if two parameters have
2192       * the same name.
2193       */
2194      if (state->symbols->name_declared_this_scope(var->name)) {
2195	 YYLTYPE loc = this->get_location();
2196
2197	 _mesa_glsl_error(& loc, state, "parameter `%s' redeclared", var->name);
2198      } else {
2199	 state->symbols->add_variable(var->name, var);
2200      }
2201   }
2202
2203   /* Convert the body of the function to HIR. */
2204   this->body->hir(&signature->body, state);
2205   signature->is_defined = true;
2206
2207   state->symbols->pop_scope();
2208
2209   assert(state->current_function == signature);
2210   state->current_function = NULL;
2211
2212   if (!signature->return_type->is_void() && !state->found_return) {
2213      YYLTYPE loc = this->get_location();
2214      _mesa_glsl_error(& loc, state, "function `%s' has non-void return type "
2215		       "%s, but no return statement",
2216		       signature->function_name(),
2217		       signature->return_type->name);
2218   }
2219
2220   /* Function definitions do not have r-values.
2221    */
2222   return NULL;
2223}
2224
2225
2226ir_rvalue *
2227ast_jump_statement::hir(exec_list *instructions,
2228			struct _mesa_glsl_parse_state *state)
2229{
2230   void *ctx = state;
2231
2232   switch (mode) {
2233   case ast_return: {
2234      ir_return *inst;
2235      assert(state->current_function);
2236
2237      if (opt_return_value) {
2238	 if (state->current_function->return_type->base_type ==
2239	     GLSL_TYPE_VOID) {
2240	    YYLTYPE loc = this->get_location();
2241
2242	    _mesa_glsl_error(& loc, state,
2243			     "`return` with a value, in function `%s' "
2244			     "returning void",
2245			     state->current_function->function_name());
2246	 }
2247
2248	 ir_expression *const ret = (ir_expression *)
2249	    opt_return_value->hir(instructions, state);
2250	 assert(ret != NULL);
2251
2252	 /* Implicit conversions are not allowed for return values. */
2253	 if (state->current_function->return_type != ret->type) {
2254	    YYLTYPE loc = this->get_location();
2255
2256	    _mesa_glsl_error(& loc, state,
2257			     "`return' with wrong type %s, in function `%s' "
2258			     "returning %s",
2259			     ret->type->name,
2260			     state->current_function->function_name(),
2261			     state->current_function->return_type->name);
2262	 }
2263
2264	 inst = new(ctx) ir_return(ret);
2265      } else {
2266	 if (state->current_function->return_type->base_type !=
2267	     GLSL_TYPE_VOID) {
2268	    YYLTYPE loc = this->get_location();
2269
2270	    _mesa_glsl_error(& loc, state,
2271			     "`return' with no value, in function %s returning "
2272			     "non-void",
2273			     state->current_function->function_name());
2274	 }
2275	 inst = new(ctx) ir_return;
2276      }
2277
2278      state->found_return = true;
2279      instructions->push_tail(inst);
2280      break;
2281   }
2282
2283   case ast_discard:
2284      if (state->target != fragment_shader) {
2285	 YYLTYPE loc = this->get_location();
2286
2287	 _mesa_glsl_error(& loc, state,
2288			  "`discard' may only appear in a fragment shader");
2289      }
2290      instructions->push_tail(new(ctx) ir_discard);
2291      break;
2292
2293   case ast_break:
2294   case ast_continue:
2295      /* FINISHME: Handle switch-statements.  They cannot contain 'continue',
2296       * FINISHME: and they use a different IR instruction for 'break'.
2297       */
2298      /* FINISHME: Correctly handle the nesting.  If a switch-statement is
2299       * FINISHME: inside a loop, a 'continue' is valid and will bind to the
2300       * FINISHME: loop.
2301       */
2302      if (state->loop_or_switch_nesting == NULL) {
2303	 YYLTYPE loc = this->get_location();
2304
2305	 _mesa_glsl_error(& loc, state,
2306			  "`%s' may only appear in a loop",
2307			  (mode == ast_break) ? "break" : "continue");
2308      } else {
2309	 ir_loop *const loop = state->loop_or_switch_nesting->as_loop();
2310
2311	 if (loop != NULL) {
2312	    ir_loop_jump *const jump =
2313	       new(ctx) ir_loop_jump((mode == ast_break)
2314				     ? ir_loop_jump::jump_break
2315				     : ir_loop_jump::jump_continue);
2316	    instructions->push_tail(jump);
2317	 }
2318      }
2319
2320      break;
2321   }
2322
2323   /* Jump instructions do not have r-values.
2324    */
2325   return NULL;
2326}
2327
2328
2329ir_rvalue *
2330ast_selection_statement::hir(exec_list *instructions,
2331			     struct _mesa_glsl_parse_state *state)
2332{
2333   void *ctx = state;
2334
2335   ir_rvalue *const condition = this->condition->hir(instructions, state);
2336
2337   /* From page 66 (page 72 of the PDF) of the GLSL 1.50 spec:
2338    *
2339    *    "Any expression whose type evaluates to a Boolean can be used as the
2340    *    conditional expression bool-expression. Vector types are not accepted
2341    *    as the expression to if."
2342    *
2343    * The checks are separated so that higher quality diagnostics can be
2344    * generated for cases where both rules are violated.
2345    */
2346   if (!condition->type->is_boolean() || !condition->type->is_scalar()) {
2347      YYLTYPE loc = this->condition->get_location();
2348
2349      _mesa_glsl_error(& loc, state, "if-statement condition must be scalar "
2350		       "boolean");
2351   }
2352
2353   ir_if *const stmt = new(ctx) ir_if(condition);
2354
2355   if (then_statement != NULL)
2356      then_statement->hir(& stmt->then_instructions, state);
2357
2358   if (else_statement != NULL)
2359      else_statement->hir(& stmt->else_instructions, state);
2360
2361   instructions->push_tail(stmt);
2362
2363   /* if-statements do not have r-values.
2364    */
2365   return NULL;
2366}
2367
2368
2369void
2370ast_iteration_statement::condition_to_hir(ir_loop *stmt,
2371					  struct _mesa_glsl_parse_state *state)
2372{
2373   void *ctx = state;
2374
2375   if (condition != NULL) {
2376      ir_rvalue *const cond =
2377	 condition->hir(& stmt->body_instructions, state);
2378
2379      if ((cond == NULL)
2380	  || !cond->type->is_boolean() || !cond->type->is_scalar()) {
2381	 YYLTYPE loc = condition->get_location();
2382
2383	 _mesa_glsl_error(& loc, state,
2384			  "loop condition must be scalar boolean");
2385      } else {
2386	 /* As the first code in the loop body, generate a block that looks
2387	  * like 'if (!condition) break;' as the loop termination condition.
2388	  */
2389	 ir_rvalue *const not_cond =
2390	    new(ctx) ir_expression(ir_unop_logic_not, glsl_type::bool_type, cond,
2391				   NULL);
2392
2393	 ir_if *const if_stmt = new(ctx) ir_if(not_cond);
2394
2395	 ir_jump *const break_stmt =
2396	    new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
2397
2398	 if_stmt->then_instructions.push_tail(break_stmt);
2399	 stmt->body_instructions.push_tail(if_stmt);
2400      }
2401   }
2402}
2403
2404
2405ir_rvalue *
2406ast_iteration_statement::hir(exec_list *instructions,
2407			     struct _mesa_glsl_parse_state *state)
2408{
2409   void *ctx = state;
2410
2411   /* For-loops and while-loops start a new scope, but do-while loops do not.
2412    */
2413   if (mode != ast_do_while)
2414      state->symbols->push_scope();
2415
2416   if (init_statement != NULL)
2417      init_statement->hir(instructions, state);
2418
2419   ir_loop *const stmt = new(ctx) ir_loop();
2420   instructions->push_tail(stmt);
2421
2422   /* Track the current loop and / or switch-statement nesting.
2423    */
2424   ir_instruction *const nesting = state->loop_or_switch_nesting;
2425   state->loop_or_switch_nesting = stmt;
2426
2427   if (mode != ast_do_while)
2428      condition_to_hir(stmt, state);
2429
2430   if (body != NULL)
2431      body->hir(& stmt->body_instructions, state);
2432
2433   if (rest_expression != NULL)
2434      rest_expression->hir(& stmt->body_instructions, state);
2435
2436   if (mode == ast_do_while)
2437      condition_to_hir(stmt, state);
2438
2439   if (mode != ast_do_while)
2440      state->symbols->pop_scope();
2441
2442   /* Restore previous nesting before returning.
2443    */
2444   state->loop_or_switch_nesting = nesting;
2445
2446   /* Loops do not have r-values.
2447    */
2448   return NULL;
2449}
2450
2451
2452ir_rvalue *
2453ast_type_specifier::hir(exec_list *instructions,
2454			  struct _mesa_glsl_parse_state *state)
2455{
2456   if (this->structure != NULL)
2457      return this->structure->hir(instructions, state);
2458
2459   return NULL;
2460}
2461
2462
2463ir_rvalue *
2464ast_struct_specifier::hir(exec_list *instructions,
2465			  struct _mesa_glsl_parse_state *state)
2466{
2467   unsigned decl_count = 0;
2468
2469   /* Make an initial pass over the list of structure fields to determine how
2470    * many there are.  Each element in this list is an ast_declarator_list.
2471    * This means that we actually need to count the number of elements in the
2472    * 'declarations' list in each of the elements.
2473    */
2474   foreach_list_typed (ast_declarator_list, decl_list, link,
2475		       &this->declarations) {
2476      foreach_list_const (decl_ptr, & decl_list->declarations) {
2477	 decl_count++;
2478      }
2479   }
2480
2481
2482   /* Allocate storage for the structure fields and process the field
2483    * declarations.  As the declarations are processed, try to also convert
2484    * the types to HIR.  This ensures that structure definitions embedded in
2485    * other structure definitions are processed.
2486    */
2487   glsl_struct_field *const fields = talloc_array(state, glsl_struct_field,
2488						  decl_count);
2489
2490   unsigned i = 0;
2491   foreach_list_typed (ast_declarator_list, decl_list, link,
2492		       &this->declarations) {
2493      const char *type_name;
2494
2495      decl_list->type->specifier->hir(instructions, state);
2496
2497      const glsl_type *decl_type =
2498	 decl_list->type->specifier->glsl_type(& type_name, state);
2499
2500      foreach_list_typed (ast_declaration, decl, link,
2501			  &decl_list->declarations) {
2502	 const struct glsl_type *const field_type =
2503	    (decl->is_array)
2504	    ? process_array_type(decl_type, decl->array_size, state)
2505	    : decl_type;
2506
2507	 fields[i].type = (field_type != NULL)
2508	    ? field_type : glsl_type::error_type;
2509	 fields[i].name = decl->identifier;
2510	 i++;
2511      }
2512   }
2513
2514   assert(i == decl_count);
2515
2516   const char *name;
2517   if (this->name == NULL) {
2518      static unsigned anon_count = 1;
2519      char buf[32];
2520
2521      snprintf(buf, sizeof(buf), "#anon_struct_%04x", anon_count);
2522      anon_count++;
2523
2524      name = strdup(buf);
2525   } else {
2526      name = this->name;
2527   }
2528
2529   const glsl_type *t =
2530      glsl_type::get_record_instance(fields, decl_count, name);
2531
2532   YYLTYPE loc = this->get_location();
2533   if (!state->symbols->add_type(name, t)) {
2534      _mesa_glsl_error(& loc, state, "struct `%s' previously defined", name);
2535   } else {
2536      /* This logic is a bit tricky.  It is an error to declare a structure at
2537       * global scope if there is also a function with the same name.
2538       */
2539      if ((state->current_function == NULL)
2540	  && (state->symbols->get_function(name) != NULL)) {
2541	 _mesa_glsl_error(& loc, state, "name `%s' previously defined", name);
2542      } else {
2543	 t->generate_constructor(state->symbols);
2544      }
2545
2546      const glsl_type **s = (const glsl_type **)
2547	 realloc(state->user_structures,
2548		 sizeof(state->user_structures[0]) *
2549		 (state->num_user_structures + 1));
2550      if (s != NULL) {
2551	 s[state->num_user_structures] = t;
2552	 state->user_structures = s;
2553	 state->num_user_structures++;
2554      }
2555   }
2556
2557   /* Structure type definitions do not have r-values.
2558    */
2559   return NULL;
2560}
2561