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