• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2010 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  */
23 
24 #include "glsl_symbol_table.h"
25 #include "ast.h"
26 #include "compiler/glsl_types.h"
27 #include "ir.h"
28 #include "linker_util.h"
29 #include "main/shader_types.h"
30 #include "main/consts_exts.h"
31 #include "main/shaderobj.h"
32 #include "builtin_functions.h"
33 
34 static ir_rvalue *
35 convert_component(ir_rvalue *src, const glsl_type *desired_type);
36 
37 static unsigned
process_parameters(exec_list * instructions,exec_list * actual_parameters,exec_list * parameters,struct _mesa_glsl_parse_state * state)38 process_parameters(exec_list *instructions, exec_list *actual_parameters,
39                    exec_list *parameters,
40                    struct _mesa_glsl_parse_state *state)
41 {
42    void *mem_ctx = state;
43    unsigned count = 0;
44 
45    foreach_list_typed(ast_node, ast, link, parameters) {
46       /* We need to process the parameters first in order to know if we can
47        * raise or not a unitialized warning. Calling set_is_lhs silence the
48        * warning for now. Raising the warning or not will be checked at
49        * verify_parameter_modes.
50        */
51       ast->set_is_lhs(true);
52       ir_rvalue *result = ast->hir(instructions, state);
53 
54       /* Error happened processing function parameter */
55       if (!result) {
56          actual_parameters->push_tail(ir_rvalue::error_value(mem_ctx));
57          count++;
58          continue;
59       }
60 
61       ir_constant *const constant =
62          result->constant_expression_value(mem_ctx);
63 
64       if (constant != NULL)
65          result = constant;
66 
67       actual_parameters->push_tail(result);
68       count++;
69    }
70 
71    return count;
72 }
73 
74 
75 /**
76  * Generate a source prototype for a function signature
77  *
78  * \param return_type Return type of the function.  May be \c NULL.
79  * \param name        Name of the function.
80  * \param parameters  List of \c ir_instruction nodes representing the
81  *                    parameter list for the function.  This may be either a
82  *                    formal (\c ir_variable) or actual (\c ir_rvalue)
83  *                    parameter list.  Only the type is used.
84  *
85  * \return
86  * A ralloced string representing the prototype of the function.
87  */
88 char *
prototype_string(const glsl_type * return_type,const char * name,exec_list * parameters)89 prototype_string(const glsl_type *return_type, const char *name,
90                  exec_list *parameters)
91 {
92    char *str = NULL;
93 
94    if (return_type != NULL)
95       str = ralloc_asprintf(NULL, "%s ", glsl_get_type_name(return_type));
96 
97    ralloc_asprintf_append(&str, "%s(", name);
98 
99    const char *comma = "";
100    foreach_in_list(const ir_variable, param, parameters) {
101       ralloc_asprintf_append(&str, "%s%s", comma, glsl_get_type_name(param->type));
102       comma = ", ";
103    }
104 
105    ralloc_strcat(&str, ")");
106    return str;
107 }
108 
109 static bool
verify_image_parameter(YYLTYPE * loc,_mesa_glsl_parse_state * state,const ir_variable * formal,const ir_variable * actual)110 verify_image_parameter(YYLTYPE *loc, _mesa_glsl_parse_state *state,
111                        const ir_variable *formal, const ir_variable *actual)
112 {
113    /**
114     * From the ARB_shader_image_load_store specification:
115     *
116     * "The values of image variables qualified with coherent,
117     *  volatile, restrict, readonly, or writeonly may not be passed
118     *  to functions whose formal parameters lack such
119     *  qualifiers. [...] It is legal to have additional qualifiers
120     *  on a formal parameter, but not to have fewer."
121     */
122    if (actual->data.memory_coherent && !formal->data.memory_coherent) {
123       _mesa_glsl_error(loc, state,
124                        "function call parameter `%s' drops "
125                        "`coherent' qualifier", formal->name);
126       return false;
127    }
128 
129    if (actual->data.memory_volatile && !formal->data.memory_volatile) {
130       _mesa_glsl_error(loc, state,
131                        "function call parameter `%s' drops "
132                        "`volatile' qualifier", formal->name);
133       return false;
134    }
135 
136    if (actual->data.memory_restrict && !formal->data.memory_restrict) {
137       _mesa_glsl_error(loc, state,
138                        "function call parameter `%s' drops "
139                        "`restrict' qualifier", formal->name);
140       return false;
141    }
142 
143    if (actual->data.memory_read_only && !formal->data.memory_read_only) {
144       _mesa_glsl_error(loc, state,
145                        "function call parameter `%s' drops "
146                        "`readonly' qualifier", formal->name);
147       return false;
148    }
149 
150    if (actual->data.memory_write_only && !formal->data.memory_write_only) {
151       _mesa_glsl_error(loc, state,
152                        "function call parameter `%s' drops "
153                        "`writeonly' qualifier", formal->name);
154       return false;
155    }
156 
157    return true;
158 }
159 
160 static bool
verify_first_atomic_parameter(YYLTYPE * loc,_mesa_glsl_parse_state * state,ir_variable * var)161 verify_first_atomic_parameter(YYLTYPE *loc, _mesa_glsl_parse_state *state,
162                               ir_variable *var)
163 {
164    if (!var ||
165        (!var->is_in_shader_storage_block() &&
166         var->data.mode != ir_var_shader_shared)) {
167       _mesa_glsl_error(loc, state, "First argument to atomic function "
168                        "must be a buffer or shared variable");
169       return false;
170    }
171    return true;
172 }
173 
174 static bool
is_atomic_function(const char * func_name)175 is_atomic_function(const char *func_name)
176 {
177    return !strcmp(func_name, "atomicAdd") ||
178           !strcmp(func_name, "atomicMin") ||
179           !strcmp(func_name, "atomicMax") ||
180           !strcmp(func_name, "atomicAnd") ||
181           !strcmp(func_name, "atomicOr") ||
182           !strcmp(func_name, "atomicXor") ||
183           !strcmp(func_name, "atomicExchange") ||
184           !strcmp(func_name, "atomicCompSwap");
185 }
186 
187 static bool
verify_atomic_image_parameter_qualifier(YYLTYPE * loc,_mesa_glsl_parse_state * state,ir_variable * var)188 verify_atomic_image_parameter_qualifier(YYLTYPE *loc, _mesa_glsl_parse_state *state,
189                                         ir_variable *var)
190 {
191    if (!var ||
192        (var->data.image_format != PIPE_FORMAT_R32_UINT &&
193         var->data.image_format != PIPE_FORMAT_R32_SINT &&
194         var->data.image_format != PIPE_FORMAT_R32_FLOAT)) {
195       _mesa_glsl_error(loc, state, "Image atomic functions should use r32i/r32ui "
196                        "format qualifier");
197       return false;
198    }
199    return true;
200 }
201 
202 static bool
is_atomic_image_function(const char * func_name)203 is_atomic_image_function(const char *func_name)
204 {
205    return !strcmp(func_name, "imageAtomicAdd") ||
206           !strcmp(func_name, "imageAtomicMin") ||
207           !strcmp(func_name, "imageAtomicMax") ||
208           !strcmp(func_name, "imageAtomicAnd") ||
209           !strcmp(func_name, "imageAtomicOr") ||
210           !strcmp(func_name, "imageAtomicXor") ||
211           !strcmp(func_name, "imageAtomicExchange") ||
212           !strcmp(func_name, "imageAtomicCompSwap") ||
213           !strcmp(func_name, "imageAtomicIncWrap") ||
214           !strcmp(func_name, "imageAtomicDecWrap");
215 }
216 
217 
218 /**
219  * Verify that 'out' and 'inout' actual parameters are lvalues.  Also, verify
220  * that 'const_in' formal parameters (an extension in our IR) correspond to
221  * ir_constant actual parameters.
222  */
223 static bool
verify_parameter_modes(_mesa_glsl_parse_state * state,ir_function_signature * sig,exec_list & actual_ir_parameters,exec_list & actual_ast_parameters)224 verify_parameter_modes(_mesa_glsl_parse_state *state,
225                        ir_function_signature *sig,
226                        exec_list &actual_ir_parameters,
227                        exec_list &actual_ast_parameters)
228 {
229    exec_node *actual_ir_node  = actual_ir_parameters.get_head_raw();
230    exec_node *actual_ast_node = actual_ast_parameters.get_head_raw();
231 
232    foreach_in_list(const ir_variable, formal, &sig->parameters) {
233       /* The lists must be the same length. */
234       assert(!actual_ir_node->is_tail_sentinel());
235       assert(!actual_ast_node->is_tail_sentinel());
236 
237       const ir_rvalue *const actual = (ir_rvalue *) actual_ir_node;
238       const ast_expression *const actual_ast =
239          exec_node_data(ast_expression, actual_ast_node, link);
240 
241       YYLTYPE loc = actual_ast->get_location();
242 
243       /* Verify that 'const_in' parameters are ir_constants. */
244       if (formal->data.mode == ir_var_const_in &&
245           actual->ir_type != ir_type_constant) {
246          _mesa_glsl_error(&loc, state,
247                           "parameter `in %s' must be a constant expression",
248                           formal->name);
249          return false;
250       }
251 
252       /* Verify that shader_in parameters are shader inputs */
253       if (formal->data.must_be_shader_input) {
254          const ir_rvalue *val = actual;
255 
256          /* GLSL 4.40 allows swizzles, while earlier GLSL versions do not. */
257          if (val->ir_type == ir_type_swizzle) {
258             if (!state->is_version(440, 0)) {
259                _mesa_glsl_error(&loc, state,
260                                 "parameter `%s` must not be swizzled",
261                                 formal->name);
262                return false;
263             }
264             val = ((ir_swizzle *)val)->val;
265          }
266 
267          for (;;) {
268             if (val->ir_type == ir_type_dereference_array) {
269                val = ((ir_dereference_array *)val)->array;
270             } else if (val->ir_type == ir_type_dereference_record &&
271                        !state->es_shader) {
272                val = ((ir_dereference_record *)val)->record;
273             } else
274                break;
275          }
276 
277          ir_variable *var = NULL;
278          if (const ir_dereference_variable *deref_var = val->as_dereference_variable())
279             var = deref_var->variable_referenced();
280 
281          if (!var || var->data.mode != ir_var_shader_in) {
282             _mesa_glsl_error(&loc, state,
283                              "parameter `%s` must be a shader input",
284                              formal->name);
285             return false;
286          }
287 
288          var->data.must_be_shader_input = 1;
289       }
290 
291       /* Verify that 'out' and 'inout' actual parameters are lvalues. */
292       if (formal->data.mode == ir_var_function_out
293           || formal->data.mode == ir_var_function_inout) {
294          const char *mode = NULL;
295          switch (formal->data.mode) {
296          case ir_var_function_out:   mode = "out";   break;
297          case ir_var_function_inout: mode = "inout"; break;
298          default:                    assert(false);  break;
299          }
300 
301          /* This AST-based check catches errors like f(i++).  The IR-based
302           * is_lvalue() is insufficient because the actual parameter at the
303           * IR-level is just a temporary value, which is an l-value.
304           */
305          if (actual_ast->non_lvalue_description != NULL) {
306             _mesa_glsl_error(&loc, state,
307                              "function parameter '%s %s' references a %s",
308                              mode, formal->name,
309                              actual_ast->non_lvalue_description);
310             return false;
311          }
312 
313          ir_variable *var = actual->variable_referenced();
314 
315          if (var && formal->data.mode == ir_var_function_inout) {
316             if ((var->data.mode == ir_var_auto ||
317                  var->data.mode == ir_var_shader_out) &&
318                 !var->data.assigned &&
319                 !is_gl_identifier(var->name)) {
320                _mesa_glsl_warning(&loc, state, "`%s' used uninitialized",
321                                   var->name);
322             }
323          }
324 
325          if (var)
326             var->data.assigned = true;
327 
328          if (var && var->data.read_only) {
329             _mesa_glsl_error(&loc, state,
330                              "function parameter '%s %s' references the "
331                              "read-only variable '%s'",
332                              mode, formal->name,
333                              actual->variable_referenced()->name);
334             return false;
335          } else if (!actual->is_lvalue(state)) {
336             _mesa_glsl_error(&loc, state,
337                              "function parameter '%s %s' is not an lvalue",
338                              mode, formal->name);
339             return false;
340          }
341       } else {
342          assert(formal->data.mode == ir_var_function_in ||
343                 formal->data.mode == ir_var_const_in);
344          ir_variable *var = actual->variable_referenced();
345          if (var) {
346             if ((var->data.mode == ir_var_auto ||
347                  var->data.mode == ir_var_shader_out) &&
348                 !var->data.assigned &&
349                 !is_gl_identifier(var->name)) {
350                _mesa_glsl_warning(&loc, state, "`%s' used uninitialized",
351                                   var->name);
352             }
353          }
354       }
355 
356       if (glsl_type_is_image(formal->type) &&
357           actual->variable_referenced()) {
358          if (!verify_image_parameter(&loc, state, formal,
359                                      actual->variable_referenced()))
360             return false;
361       }
362 
363       actual_ir_node  = actual_ir_node->next;
364       actual_ast_node = actual_ast_node->next;
365    }
366 
367    /* The first parameter of atomic functions must be a buffer variable */
368    const char *func_name = sig->function_name();
369    bool is_atomic = is_atomic_function(func_name);
370    if (is_atomic) {
371       const ir_rvalue *const actual =
372          (ir_rvalue *) actual_ir_parameters.get_head_raw();
373 
374       const ast_expression *const actual_ast =
375          exec_node_data(ast_expression,
376                         actual_ast_parameters.get_head_raw(), link);
377       YYLTYPE loc = actual_ast->get_location();
378 
379       if (!verify_first_atomic_parameter(&loc, state,
380                                          actual->variable_referenced())) {
381          return false;
382       }
383    } else if (is_atomic_image_function(func_name)) {
384       const ir_rvalue *const actual =
385          (ir_rvalue *) actual_ir_parameters.get_head_raw();
386 
387       const ast_expression *const actual_ast =
388          exec_node_data(ast_expression,
389                         actual_ast_parameters.get_head_raw(), link);
390       YYLTYPE loc = actual_ast->get_location();
391 
392       if (!verify_atomic_image_parameter_qualifier(&loc, state,
393                                          actual->variable_referenced())) {
394          return false;
395       }
396    }
397 
398    return true;
399 }
400 
401 struct copy_index_deref_data {
402    void *mem_ctx;
403    exec_list *before_instructions;
404 };
405 
406 static void
copy_index_derefs_to_temps(ir_instruction * ir,void * data)407 copy_index_derefs_to_temps(ir_instruction *ir, void *data)
408 {
409    struct copy_index_deref_data *d = (struct copy_index_deref_data *)data;
410 
411    if (ir->ir_type == ir_type_dereference_array) {
412       ir_dereference_array *a = (ir_dereference_array *) ir;
413       ir = a->array->as_dereference();
414 
415       ir_rvalue *idx = a->array_index;
416       ir_variable *var = idx->variable_referenced();
417 
418       /* If the index is read only it cannot change so there is no need
419        * to copy it.
420        */
421       if (!var || var->data.read_only || var->data.memory_read_only)
422          return;
423 
424       ir_variable *tmp = new(d->mem_ctx) ir_variable(idx->type, "idx_tmp",
425                                                       ir_var_temporary);
426       d->before_instructions->push_tail(tmp);
427 
428       ir_dereference_variable *const deref_tmp_1 =
429          new(d->mem_ctx) ir_dereference_variable(tmp);
430       ir_assignment *const assignment =
431          new(d->mem_ctx) ir_assignment(deref_tmp_1,
432                                        idx->clone(d->mem_ctx, NULL));
433       d->before_instructions->push_tail(assignment);
434 
435       /* Replace the array index with a dereference of the new temporary */
436       ir_dereference_variable *const deref_tmp_2 =
437          new(d->mem_ctx) ir_dereference_variable(tmp);
438       a->array_index = deref_tmp_2;
439    }
440 }
441 
442 static void
fix_parameter(void * mem_ctx,ir_rvalue * actual,const glsl_type * formal_type,exec_list * before_instructions,exec_list * after_instructions,bool parameter_is_inout)443 fix_parameter(void *mem_ctx, ir_rvalue *actual, const glsl_type *formal_type,
444               exec_list *before_instructions, exec_list *after_instructions,
445               bool parameter_is_inout)
446 {
447    ir_expression *const expr = actual->as_expression();
448 
449    /* If the types match exactly and the parameter is not a vector-extract,
450     * nothing needs to be done to fix the parameter.
451     */
452    if (formal_type == actual->type
453        && (expr == NULL || expr->operation != ir_binop_vector_extract)
454        && actual->as_dereference_variable())
455       return;
456 
457    /* An array index could also be an out variable so we need to make a copy
458     * of them before the function is called.
459     */
460    if (!actual->as_dereference_variable()) {
461       struct copy_index_deref_data data;
462       data.mem_ctx = mem_ctx;
463       data.before_instructions = before_instructions;
464 
465       visit_tree(actual, copy_index_derefs_to_temps, &data);
466    }
467 
468    /* To convert an out parameter, we need to create a temporary variable to
469     * hold the value before conversion, and then perform the conversion after
470     * the function call returns.
471     *
472     * This has the effect of transforming code like this:
473     *
474     *   void f(out int x);
475     *   float value;
476     *   f(value);
477     *
478     * Into IR that's equivalent to this:
479     *
480     *   void f(out int x);
481     *   float value;
482     *   int out_parameter_conversion;
483     *   f(out_parameter_conversion);
484     *   value = float(out_parameter_conversion);
485     *
486     * If the parameter is an ir_expression of ir_binop_vector_extract,
487     * additional conversion is needed in the post-call re-write.
488     */
489    ir_variable *tmp =
490       new(mem_ctx) ir_variable(formal_type, "inout_tmp", ir_var_temporary);
491 
492    before_instructions->push_tail(tmp);
493 
494    /* If the parameter is an inout parameter, copy the value of the actual
495     * parameter to the new temporary.  Note that no type conversion is allowed
496     * here because inout parameters must match types exactly.
497     */
498    if (parameter_is_inout) {
499       /* Inout parameters should never require conversion, since that would
500        * require an implicit conversion to exist both to and from the formal
501        * parameter type, and there are no bidirectional implicit conversions.
502        */
503       assert (actual->type == formal_type);
504 
505       ir_dereference_variable *const deref_tmp_1 =
506          new(mem_ctx) ir_dereference_variable(tmp);
507       ir_assignment *const assignment =
508          new(mem_ctx) ir_assignment(deref_tmp_1, actual->clone(mem_ctx, NULL));
509       before_instructions->push_tail(assignment);
510    }
511 
512    /* Replace the parameter in the call with a dereference of the new
513     * temporary.
514     */
515    ir_dereference_variable *const deref_tmp_2 =
516       new(mem_ctx) ir_dereference_variable(tmp);
517    actual->replace_with(deref_tmp_2);
518 
519 
520    /* Copy the temporary variable to the actual parameter with optional
521     * type conversion applied.
522     */
523    ir_rvalue *rhs = new(mem_ctx) ir_dereference_variable(tmp);
524    if (actual->type != formal_type)
525       rhs = convert_component(rhs, actual->type);
526 
527    ir_rvalue *lhs = actual;
528    if (expr != NULL && expr->operation == ir_binop_vector_extract) {
529       lhs = new(mem_ctx) ir_dereference_array(expr->operands[0]->clone(mem_ctx,
530                                                                        NULL),
531                                               expr->operands[1]->clone(mem_ctx,
532                                                                        NULL));
533    }
534 
535    ir_assignment *const assignment_2 = new(mem_ctx) ir_assignment(lhs, rhs);
536    after_instructions->push_tail(assignment_2);
537 }
538 
539 /**
540  * Generate a function call.
541  *
542  * For non-void functions, this returns a dereference of the temporary
543  * variable which stores the return value for the call.  For void functions,
544  * this returns NULL.
545  */
546 static ir_rvalue *
generate_call(exec_list * instructions,ir_function_signature * sig,exec_list * actual_parameters,ir_variable * sub_var,ir_rvalue * array_idx,struct _mesa_glsl_parse_state * state)547 generate_call(exec_list *instructions, ir_function_signature *sig,
548               exec_list *actual_parameters,
549               ir_variable *sub_var,
550               ir_rvalue *array_idx,
551               struct _mesa_glsl_parse_state *state)
552 {
553    void *ctx = state;
554    exec_list post_call_conversions;
555 
556    /* Perform implicit conversion of arguments.  For out parameters, we need
557     * to place them in a temporary variable and do the conversion after the
558     * call takes place.  Since we haven't emitted the call yet, we'll place
559     * the post-call conversions in a temporary exec_list, and emit them later.
560     */
561    foreach_two_lists(formal_node, &sig->parameters,
562                      actual_node, actual_parameters) {
563       ir_rvalue *actual = (ir_rvalue *) actual_node;
564       ir_variable *formal = (ir_variable *) formal_node;
565 
566       if (glsl_type_is_numeric(formal->type) || glsl_type_is_boolean(formal->type)) {
567          switch (formal->data.mode) {
568          case ir_var_const_in:
569          case ir_var_function_in: {
570             ir_rvalue *converted
571                = convert_component(actual, formal->type);
572             actual->replace_with(converted);
573             break;
574          }
575          case ir_var_function_out:
576          case ir_var_function_inout:
577             fix_parameter(ctx, actual, formal->type,
578                           instructions, &post_call_conversions,
579                           formal->data.mode == ir_var_function_inout);
580             break;
581          default:
582             assert (!"Illegal formal parameter mode");
583             break;
584          }
585       }
586    }
587 
588    /* Section 4.3.2 (Const) of the GLSL 1.10.59 spec says:
589     *
590     *     "Initializers for const declarations must be formed from literal
591     *     values, other const variables (not including function call
592     *     paramaters), or expressions of these.
593     *
594     *     Constructors may be used in such expressions, but function calls may
595     *     not."
596     *
597     * Section 4.3.3 (Constant Expressions) of the GLSL 1.20.8 spec says:
598     *
599     *     "A constant expression is one of
600     *
601     *         ...
602     *
603     *         - a built-in function call whose arguments are all constant
604     *           expressions, with the exception of the texture lookup
605     *           functions, the noise functions, and ftransform. The built-in
606     *           functions dFdx, dFdy, and fwidth must return 0 when evaluated
607     *           inside an initializer with an argument that is a constant
608     *           expression."
609     *
610     * Section 5.10 (Constant Expressions) of the GLSL ES 1.00.17 spec says:
611     *
612     *     "A constant expression is one of
613     *
614     *         ...
615     *
616     *         - a built-in function call whose arguments are all constant
617     *           expressions, with the exception of the texture lookup
618     *           functions."
619     *
620     * Section 4.3.3 (Constant Expressions) of the GLSL ES 3.00.4 spec says:
621     *
622     *     "A constant expression is one of
623     *
624     *         ...
625     *
626     *         - a built-in function call whose arguments are all constant
627     *           expressions, with the exception of the texture lookup
628     *           functions.  The built-in functions dFdx, dFdy, and fwidth must
629     *           return 0 when evaluated inside an initializer with an argument
630     *           that is a constant expression."
631     *
632     * If the function call is a constant expression, don't generate any
633     * instructions; just generate an ir_constant.
634     */
635    if (state->is_version(120, 100) ||
636        state->consts->AllowGLSLBuiltinConstantExpression) {
637       ir_constant *value = sig->constant_expression_value(ctx,
638                                                           actual_parameters,
639                                                           NULL);
640       if (value != NULL) {
641          return value;
642       }
643    }
644 
645    ir_dereference_variable *deref = NULL;
646    if (!glsl_type_is_void(sig->return_type)) {
647       /* Create a new temporary to hold the return value. */
648       char *const name = ir_variable::temporaries_allocate_names
649          ? ralloc_asprintf(ctx, "%s_retval", sig->function_name())
650          : NULL;
651 
652       ir_variable *var;
653 
654       var = new(ctx) ir_variable(sig->return_type, name, ir_var_temporary);
655       var->data.precision = sig->return_precision;
656       instructions->push_tail(var);
657 
658       ralloc_free(name);
659 
660       deref = new(ctx) ir_dereference_variable(var);
661    }
662 
663    ir_call *call = new(ctx) ir_call(sig, deref,
664                                     actual_parameters, sub_var, array_idx);
665    instructions->push_tail(call);
666 
667    /* Also emit any necessary out-parameter conversions. */
668    instructions->append_list(&post_call_conversions);
669 
670    return deref ? deref->clone(ctx, NULL) : NULL;
671 }
672 
673 /**
674  * Given a function name and parameter list, find the matching signature.
675  */
676 static ir_function_signature *
match_function_by_name(const char * name,exec_list * actual_parameters,struct _mesa_glsl_parse_state * state)677 match_function_by_name(const char *name,
678                        exec_list *actual_parameters,
679                        struct _mesa_glsl_parse_state *state)
680 {
681    ir_function *f = state->symbols->get_function(name);
682    ir_function_signature *local_sig = NULL;
683    ir_function_signature *sig = NULL;
684 
685    /* Is the function hidden by a record type constructor? */
686    if (state->symbols->get_type(name))
687       return sig; /* no match */
688 
689    /* Is the function hidden by a variable (impossible in 1.10)? */
690    if (!state->symbols->separate_function_namespace
691        && state->symbols->get_variable(name))
692       return sig; /* no match */
693 
694    if (f != NULL) {
695       /* In desktop GL, the presence of a user-defined signature hides any
696        * built-in signatures, so we must ignore them.  In contrast, in ES2
697        * user-defined signatures add new overloads, so we must consider them.
698        */
699       bool allow_builtins = state->es_shader || !f->has_user_signature();
700 
701       /* Look for a match in the local shader.  If exact, we're done. */
702       bool is_exact = false;
703       sig = local_sig = f->matching_signature(state, actual_parameters,
704                                               allow_builtins, &is_exact);
705       if (is_exact)
706          return sig;
707 
708       if (!allow_builtins)
709          return sig;
710    }
711 
712    /* Local shader has no exact candidates; check the built-ins. */
713    sig = _mesa_glsl_find_builtin_function(state, name, actual_parameters);
714 
715    /* if _mesa_glsl_find_builtin_function failed, fall back to the result
716     * of choose_best_inexact_overload() instead. This should only affect
717     * GLES.
718     */
719    return sig ? sig : local_sig;
720 }
721 
722 static ir_function_signature *
match_subroutine_by_name(const char * name,exec_list * actual_parameters,struct _mesa_glsl_parse_state * state,ir_variable ** var_r)723 match_subroutine_by_name(const char *name,
724                          exec_list *actual_parameters,
725                          struct _mesa_glsl_parse_state *state,
726                          ir_variable **var_r)
727 {
728    void *ctx = state;
729    ir_function_signature *sig = NULL;
730    ir_function *f, *found = NULL;
731    const char *new_name;
732    ir_variable *var;
733    bool is_exact = false;
734 
735    new_name =
736       ralloc_asprintf(ctx, "%s_%s",
737                       _mesa_shader_stage_to_subroutine_prefix(state->stage),
738                       name);
739    var = state->symbols->get_variable(new_name);
740    if (!var)
741       return NULL;
742 
743    for (int i = 0; i < state->num_subroutine_types; i++) {
744       f = state->subroutine_types[i];
745       if (strcmp(f->name, glsl_get_type_name(glsl_without_array(var->type))))
746          continue;
747       found = f;
748       break;
749    }
750 
751    if (!found)
752       return NULL;
753    *var_r = var;
754    sig = found->matching_signature(state, actual_parameters,
755                                    false, &is_exact);
756    return sig;
757 }
758 
759 static ir_rvalue *
generate_array_index(void * mem_ctx,exec_list * instructions,struct _mesa_glsl_parse_state * state,YYLTYPE loc,const ast_expression * array,ast_expression * idx,const char ** function_name,exec_list * actual_parameters)760 generate_array_index(void *mem_ctx, exec_list *instructions,
761                      struct _mesa_glsl_parse_state *state, YYLTYPE loc,
762                      const ast_expression *array, ast_expression *idx,
763                      const char **function_name, exec_list *actual_parameters)
764 {
765    if (array->oper == ast_array_index) {
766       /* This handles arrays of arrays */
767       ir_rvalue *outer_array = generate_array_index(mem_ctx, instructions,
768                                                     state, loc,
769                                                     array->subexpressions[0],
770                                                     array->subexpressions[1],
771                                                     function_name,
772                                                     actual_parameters);
773       ir_rvalue *outer_array_idx = idx->hir(instructions, state);
774 
775       YYLTYPE index_loc = idx->get_location();
776       return _mesa_ast_array_index_to_hir(mem_ctx, state, outer_array,
777                                           outer_array_idx, loc,
778                                           index_loc);
779    } else {
780       ir_variable *sub_var = NULL;
781       *function_name = array->primary_expression.identifier;
782 
783       if (!match_subroutine_by_name(*function_name, actual_parameters,
784                                     state, &sub_var)) {
785          _mesa_glsl_error(&loc, state, "Unknown subroutine `%s'",
786                           *function_name);
787          *function_name = NULL; /* indicate error condition to caller */
788          return NULL;
789       }
790 
791       ir_rvalue *outer_array_idx = idx->hir(instructions, state);
792       return new(mem_ctx) ir_dereference_array(sub_var, outer_array_idx);
793    }
794 }
795 
796 static bool
function_exists(_mesa_glsl_parse_state * state,struct glsl_symbol_table * symbols,const char * name)797 function_exists(_mesa_glsl_parse_state *state,
798                 struct glsl_symbol_table *symbols, const char *name)
799 {
800    ir_function *f = symbols->get_function(name);
801    if (f != NULL) {
802       foreach_in_list(ir_function_signature, sig, &f->signatures) {
803          if (sig->is_builtin() && !sig->is_builtin_available(state))
804             continue;
805          return true;
806       }
807    }
808    return false;
809 }
810 
811 static void
print_function_prototypes(_mesa_glsl_parse_state * state,YYLTYPE * loc,ir_function * f)812 print_function_prototypes(_mesa_glsl_parse_state *state, YYLTYPE *loc,
813                           ir_function *f)
814 {
815    if (f == NULL)
816       return;
817 
818    foreach_in_list(ir_function_signature, sig, &f->signatures) {
819       if (sig->is_builtin() && !sig->is_builtin_available(state))
820          continue;
821 
822       char *str = prototype_string(sig->return_type, f->name,
823                                    &sig->parameters);
824       _mesa_glsl_error(loc, state, "   %s", str);
825       ralloc_free(str);
826    }
827 }
828 
829 /**
830  * Raise a "no matching function" error, listing all possible overloads the
831  * compiler considered so developers can figure out what went wrong.
832  */
833 static void
no_matching_function_error(const char * name,YYLTYPE * loc,exec_list * actual_parameters,_mesa_glsl_parse_state * state)834 no_matching_function_error(const char *name,
835                            YYLTYPE *loc,
836                            exec_list *actual_parameters,
837                            _mesa_glsl_parse_state *state)
838 {
839    gl_shader *sh = _mesa_glsl_get_builtin_function_shader();
840 
841    if (!function_exists(state, state->symbols, name)
842        && (!state->uses_builtin_functions
843            || !function_exists(state, sh->symbols, name))) {
844       _mesa_glsl_error(loc, state, "no function with name '%s'", name);
845    } else {
846       char *str = prototype_string(NULL, name, actual_parameters);
847       _mesa_glsl_error(loc, state,
848                        "no matching function for call to `%s';"
849                        " candidates are:",
850                        str);
851       ralloc_free(str);
852 
853       print_function_prototypes(state, loc,
854                                 state->symbols->get_function(name));
855 
856       if (state->uses_builtin_functions) {
857          print_function_prototypes(state, loc,
858                                    sh->symbols->get_function(name));
859       }
860    }
861 }
862 
863 /**
864  * Perform automatic type conversion of constructor parameters
865  *
866  * This implements the rules in the "Conversion and Scalar Constructors"
867  * section (GLSL 1.10 section 5.4.1), not the "Implicit Conversions" rules.
868  */
869 static ir_rvalue *
convert_component(ir_rvalue * src,const glsl_type * desired_type)870 convert_component(ir_rvalue *src, const glsl_type *desired_type)
871 {
872    void *ctx = ralloc_parent(src);
873    const unsigned a = desired_type->base_type;
874    const unsigned b = src->type->base_type;
875    ir_expression *result = NULL;
876 
877    if (glsl_type_is_error(src->type))
878       return src;
879 
880    assert(a <= GLSL_TYPE_IMAGE);
881    assert(b <= GLSL_TYPE_IMAGE);
882 
883    if (a == b)
884       return src;
885 
886    switch (a) {
887    case GLSL_TYPE_UINT:
888       switch (b) {
889       case GLSL_TYPE_INT:
890          result = new(ctx) ir_expression(ir_unop_i2u, src);
891          break;
892       case GLSL_TYPE_FLOAT16:
893          result = new(ctx) ir_expression(ir_unop_f162u, src);
894          break;
895       case GLSL_TYPE_FLOAT:
896          result = new(ctx) ir_expression(ir_unop_f2u, src);
897          break;
898       case GLSL_TYPE_BOOL:
899          result = new(ctx) ir_expression(ir_unop_i2u,
900                                          new(ctx) ir_expression(ir_unop_b2i,
901                                                                 src));
902          break;
903       case GLSL_TYPE_DOUBLE:
904          result = new(ctx) ir_expression(ir_unop_d2u, src);
905          break;
906       case GLSL_TYPE_UINT64:
907          result = new(ctx) ir_expression(ir_unop_u642u, src);
908          break;
909       case GLSL_TYPE_INT64:
910          result = new(ctx) ir_expression(ir_unop_i642u, src);
911          break;
912       case GLSL_TYPE_SAMPLER:
913          result = new(ctx) ir_expression(ir_unop_unpack_sampler_2x32, src);
914          break;
915       case GLSL_TYPE_IMAGE:
916          result = new(ctx) ir_expression(ir_unop_unpack_image_2x32, src);
917          break;
918       }
919       break;
920    case GLSL_TYPE_INT:
921       switch (b) {
922       case GLSL_TYPE_UINT:
923          result = new(ctx) ir_expression(ir_unop_u2i, src);
924          break;
925       case GLSL_TYPE_FLOAT16:
926          result = new(ctx) ir_expression(ir_unop_f162i, src);
927          break;
928       case GLSL_TYPE_FLOAT:
929          result = new(ctx) ir_expression(ir_unop_f2i, src);
930          break;
931       case GLSL_TYPE_BOOL:
932          result = new(ctx) ir_expression(ir_unop_b2i, src);
933          break;
934       case GLSL_TYPE_DOUBLE:
935          result = new(ctx) ir_expression(ir_unop_d2i, src);
936          break;
937       case GLSL_TYPE_UINT64:
938          result = new(ctx) ir_expression(ir_unop_u642i, src);
939          break;
940       case GLSL_TYPE_INT64:
941          result = new(ctx) ir_expression(ir_unop_i642i, src);
942          break;
943       }
944       break;
945    case GLSL_TYPE_FLOAT16:
946       switch (b) {
947       case GLSL_TYPE_UINT:
948          result = new(ctx) ir_expression(ir_unop_u2f16, desired_type, src, NULL);
949          break;
950       case GLSL_TYPE_INT:
951          result = new(ctx) ir_expression(ir_unop_i2f16, desired_type, src, NULL);
952          break;
953       case GLSL_TYPE_BOOL:
954          result = new(ctx) ir_expression(ir_unop_b2f16, desired_type, src, NULL);
955          break;
956       case GLSL_TYPE_FLOAT:
957          result = new(ctx) ir_expression(ir_unop_f2f16, desired_type, src, NULL);
958          break;
959       case GLSL_TYPE_DOUBLE:
960          result = new(ctx) ir_expression(ir_unop_d2f16, desired_type, src, NULL);
961          break;
962       case GLSL_TYPE_UINT64:
963          result = new(ctx) ir_expression(ir_unop_u642f16, desired_type, src, NULL);
964          break;
965       case GLSL_TYPE_INT64:
966          result = new(ctx) ir_expression(ir_unop_i642f16, desired_type, src, NULL);
967          break;
968       }
969       break;
970    case GLSL_TYPE_FLOAT:
971       switch (b) {
972       case GLSL_TYPE_UINT:
973          result = new(ctx) ir_expression(ir_unop_u2f, desired_type, src, NULL);
974          break;
975       case GLSL_TYPE_INT:
976          result = new(ctx) ir_expression(ir_unop_i2f, desired_type, src, NULL);
977          break;
978       case GLSL_TYPE_BOOL:
979          result = new(ctx) ir_expression(ir_unop_b2f, desired_type, src, NULL);
980          break;
981       case GLSL_TYPE_FLOAT16:
982          result = new(ctx) ir_expression(ir_unop_f162f, desired_type, src, NULL);
983          break;
984       case GLSL_TYPE_DOUBLE:
985          result = new(ctx) ir_expression(ir_unop_d2f, desired_type, src, NULL);
986          break;
987       case GLSL_TYPE_UINT64:
988          result = new(ctx) ir_expression(ir_unop_u642f, desired_type, src, NULL);
989          break;
990       case GLSL_TYPE_INT64:
991          result = new(ctx) ir_expression(ir_unop_i642f, desired_type, src, NULL);
992          break;
993       }
994       break;
995    case GLSL_TYPE_BOOL:
996       switch (b) {
997       case GLSL_TYPE_UINT:
998          result = new(ctx) ir_expression(ir_unop_i2b,
999                                          new(ctx) ir_expression(ir_unop_u2i,
1000                                                                 src));
1001          break;
1002       case GLSL_TYPE_INT:
1003          result = new(ctx) ir_expression(ir_unop_i2b, desired_type, src, NULL);
1004          break;
1005       case GLSL_TYPE_FLOAT16:
1006          result = new(ctx) ir_expression(ir_unop_f162b, desired_type, src, NULL);
1007          break;
1008       case GLSL_TYPE_FLOAT:
1009          result = new(ctx) ir_expression(ir_unop_f2b, desired_type, src, NULL);
1010          break;
1011       case GLSL_TYPE_DOUBLE:
1012          result = new(ctx) ir_expression(ir_unop_d2b, desired_type, src, NULL);
1013          break;
1014       case GLSL_TYPE_UINT64:
1015          result = new(ctx) ir_expression(ir_unop_i642b,
1016                                          new(ctx) ir_expression(ir_unop_u642i64,
1017                                                                 src));
1018          break;
1019       case GLSL_TYPE_INT64:
1020          result = new(ctx) ir_expression(ir_unop_i642b, desired_type, src, NULL);
1021          break;
1022       }
1023       break;
1024    case GLSL_TYPE_DOUBLE:
1025       switch (b) {
1026       case GLSL_TYPE_INT:
1027          result = new(ctx) ir_expression(ir_unop_i2d, src);
1028          break;
1029       case GLSL_TYPE_UINT:
1030          result = new(ctx) ir_expression(ir_unop_u2d, src);
1031          break;
1032       case GLSL_TYPE_BOOL:
1033          result = new(ctx) ir_expression(ir_unop_f2d,
1034                                          new(ctx) ir_expression(ir_unop_b2f,
1035                                                                 src));
1036          break;
1037       case GLSL_TYPE_FLOAT16:
1038          result = new(ctx) ir_expression(ir_unop_f162d, desired_type, src, NULL);
1039          break;
1040       case GLSL_TYPE_FLOAT:
1041          result = new(ctx) ir_expression(ir_unop_f2d, desired_type, src, NULL);
1042          break;
1043       case GLSL_TYPE_UINT64:
1044          result = new(ctx) ir_expression(ir_unop_u642d, desired_type, src, NULL);
1045          break;
1046       case GLSL_TYPE_INT64:
1047          result = new(ctx) ir_expression(ir_unop_i642d, desired_type, src, NULL);
1048          break;
1049       }
1050       break;
1051    case GLSL_TYPE_UINT64:
1052       switch (b) {
1053       case GLSL_TYPE_INT:
1054          result = new(ctx) ir_expression(ir_unop_i2u64, src);
1055          break;
1056       case GLSL_TYPE_UINT:
1057          result = new(ctx) ir_expression(ir_unop_u2u64, src);
1058          break;
1059       case GLSL_TYPE_BOOL:
1060          result = new(ctx) ir_expression(ir_unop_i642u64,
1061                                          new(ctx) ir_expression(ir_unop_b2i64,
1062                                                                 src));
1063          break;
1064       case GLSL_TYPE_FLOAT16:
1065          result = new(ctx) ir_expression(ir_unop_f162u64, src);
1066          break;
1067       case GLSL_TYPE_FLOAT:
1068          result = new(ctx) ir_expression(ir_unop_f2u64, src);
1069          break;
1070       case GLSL_TYPE_DOUBLE:
1071          result = new(ctx) ir_expression(ir_unop_d2u64, src);
1072          break;
1073       case GLSL_TYPE_INT64:
1074          result = new(ctx) ir_expression(ir_unop_i642u64, src);
1075          break;
1076       }
1077       break;
1078    case GLSL_TYPE_INT64:
1079       switch (b) {
1080       case GLSL_TYPE_INT:
1081          result = new(ctx) ir_expression(ir_unop_i2i64, src);
1082          break;
1083       case GLSL_TYPE_UINT:
1084          result = new(ctx) ir_expression(ir_unop_u2i64, src);
1085          break;
1086       case GLSL_TYPE_BOOL:
1087          result = new(ctx) ir_expression(ir_unop_b2i64, src);
1088          break;
1089       case GLSL_TYPE_FLOAT16:
1090          result = new(ctx) ir_expression(ir_unop_f162i64, src);
1091          break;
1092       case GLSL_TYPE_FLOAT:
1093          result = new(ctx) ir_expression(ir_unop_f2i64, src);
1094          break;
1095       case GLSL_TYPE_DOUBLE:
1096          result = new(ctx) ir_expression(ir_unop_d2i64, src);
1097          break;
1098       case GLSL_TYPE_UINT64:
1099          result = new(ctx) ir_expression(ir_unop_u642i64, src);
1100          break;
1101       }
1102       break;
1103    case GLSL_TYPE_SAMPLER:
1104       switch (b) {
1105       case GLSL_TYPE_UINT:
1106          result = new(ctx)
1107             ir_expression(ir_unop_pack_sampler_2x32, desired_type, src);
1108          break;
1109       }
1110       break;
1111    case GLSL_TYPE_IMAGE:
1112       switch (b) {
1113       case GLSL_TYPE_UINT:
1114          result = new(ctx)
1115             ir_expression(ir_unop_pack_image_2x32, desired_type, src);
1116          break;
1117       }
1118       break;
1119    }
1120 
1121    assert(result != NULL);
1122    assert(result->type == desired_type);
1123 
1124    /* Try constant folding; it may fold in the conversion we just added. */
1125    ir_constant *const constant = result->constant_expression_value(ctx);
1126    return (constant != NULL) ? (ir_rvalue *) constant : (ir_rvalue *) result;
1127 }
1128 
1129 
1130 /**
1131  * Perform automatic type and constant conversion of constructor parameters
1132  *
1133  * This implements the rules in the "Implicit Conversions" rules, not the
1134  * "Conversion and Scalar Constructors".
1135  *
1136  * After attempting the implicit conversion, an attempt to convert into a
1137  * constant valued expression is also done.
1138  *
1139  * The \c from \c ir_rvalue is converted "in place".
1140  *
1141  * \param from   Operand that is being converted
1142  * \param to     Base type the operand will be converted to
1143  * \param state  GLSL compiler state
1144  *
1145  * \return
1146  * If the attempt to convert into a constant expression succeeds, \c true is
1147  * returned. Otherwise \c false is returned.
1148  */
1149 static bool
implicitly_convert_component(ir_rvalue * & from,const glsl_base_type to,struct _mesa_glsl_parse_state * state)1150 implicitly_convert_component(ir_rvalue * &from, const glsl_base_type to,
1151                              struct _mesa_glsl_parse_state *state)
1152 {
1153    void *mem_ctx = state;
1154    ir_rvalue *result = from;
1155 
1156    if (to != from->type->base_type) {
1157       const glsl_type *desired_type =
1158          glsl_simple_type(to,
1159                           from->type->vector_elements,
1160                           from->type->matrix_columns);
1161 
1162       if (_mesa_glsl_can_implicitly_convert(from->type, desired_type, state)) {
1163          /* Even though convert_component() implements the constructor
1164           * conversion rules (not the implicit conversion rules), its safe
1165           * to use it here because we already checked that the implicit
1166           * conversion is legal.
1167           */
1168          result = convert_component(from, desired_type);
1169       }
1170    }
1171 
1172    ir_rvalue *const constant = result->constant_expression_value(mem_ctx);
1173 
1174    if (constant != NULL)
1175       result = constant;
1176 
1177    if (from != result) {
1178       from->replace_with(result);
1179       from = result;
1180    }
1181 
1182    return constant != NULL;
1183 }
1184 
1185 
1186 /**
1187  * Dereference a specific component from a scalar, vector, or matrix
1188  */
1189 static ir_rvalue *
dereference_component(ir_rvalue * src,unsigned component)1190 dereference_component(ir_rvalue *src, unsigned component)
1191 {
1192    void *ctx = ralloc_parent(src);
1193    assert(component < glsl_get_components(src->type));
1194 
1195    /* If the source is a constant, just create a new constant instead of a
1196     * dereference of the existing constant.
1197     */
1198    ir_constant *constant = src->as_constant();
1199    if (constant)
1200       return new(ctx) ir_constant(constant, component);
1201 
1202    if (glsl_type_is_scalar(src->type)) {
1203       return src;
1204    } else if (glsl_type_is_vector(src->type)) {
1205       return new(ctx) ir_swizzle(src, component, 0, 0, 0, 1);
1206    } else {
1207       assert(glsl_type_is_matrix(src->type));
1208 
1209       /* Dereference a row of the matrix, then call this function again to get
1210        * a specific element from that row.
1211        */
1212       const int c = component / glsl_get_column_type(src->type)->vector_elements;
1213       const int r = component % glsl_get_column_type(src->type)->vector_elements;
1214       ir_constant *const col_index = new(ctx) ir_constant(c);
1215       ir_dereference *const col = new(ctx) ir_dereference_array(src,
1216                                                                 col_index);
1217 
1218       col->type = glsl_get_column_type(src->type);
1219 
1220       return dereference_component(col, r);
1221    }
1222 
1223    assert(!"Should not get here.");
1224    return NULL;
1225 }
1226 
1227 
1228 static ir_rvalue *
process_vec_mat_constructor(exec_list * instructions,const glsl_type * constructor_type,YYLTYPE * loc,exec_list * parameters,struct _mesa_glsl_parse_state * state)1229 process_vec_mat_constructor(exec_list *instructions,
1230                             const glsl_type *constructor_type,
1231                             YYLTYPE *loc, exec_list *parameters,
1232                             struct _mesa_glsl_parse_state *state)
1233 {
1234    void *ctx = state;
1235 
1236    /* The ARB_shading_language_420pack spec says:
1237     *
1238     * "If an initializer is a list of initializers enclosed in curly braces,
1239     *  the variable being declared must be a vector, a matrix, an array, or a
1240     *  structure.
1241     *
1242     *      int i = { 1 }; // illegal, i is not an aggregate"
1243     */
1244    if (constructor_type->vector_elements <= 1) {
1245       _mesa_glsl_error(loc, state, "aggregates can only initialize vectors, "
1246                        "matrices, arrays, and structs");
1247       return ir_rvalue::error_value(ctx);
1248    }
1249 
1250    exec_list actual_parameters;
1251    const unsigned parameter_count =
1252       process_parameters(instructions, &actual_parameters, parameters, state);
1253 
1254    if (parameter_count == 0
1255        || (glsl_type_is_vector(constructor_type) &&
1256            constructor_type->vector_elements != parameter_count)
1257        || (glsl_type_is_matrix(constructor_type) &&
1258            constructor_type->matrix_columns != parameter_count)) {
1259       _mesa_glsl_error(loc, state, "%s constructor must have %u parameters",
1260                        glsl_type_is_vector(constructor_type) ? "vector" : "matrix",
1261                        constructor_type->vector_elements);
1262       return ir_rvalue::error_value(ctx);
1263    }
1264 
1265    bool all_parameters_are_constant = true;
1266 
1267    /* Type cast each parameter and, if possible, fold constants. */
1268    foreach_in_list_safe(ir_rvalue, ir, &actual_parameters) {
1269       /* Apply implicit conversions (not the scalar constructor rules, see the
1270        * spec quote above!) and attempt to convert the parameter to a constant
1271        * valued expression. After doing so, track whether or not all the
1272        * parameters to the constructor are trivially constant valued
1273        * expressions.
1274        */
1275       all_parameters_are_constant &=
1276          implicitly_convert_component(ir, constructor_type->base_type, state);
1277 
1278       if (glsl_type_is_matrix(constructor_type)) {
1279          if (ir->type != glsl_get_column_type(constructor_type)) {
1280             _mesa_glsl_error(loc, state, "type error in matrix constructor: "
1281                              "expected: %s, found %s",
1282                              glsl_get_type_name(glsl_get_column_type(constructor_type)),
1283                              glsl_get_type_name(ir->type));
1284             return ir_rvalue::error_value(ctx);
1285          }
1286       } else if (ir->type != glsl_get_scalar_type(constructor_type)) {
1287          _mesa_glsl_error(loc, state, "type error in vector constructor: "
1288                           "expected: %s, found %s",
1289                           glsl_get_type_name(glsl_get_scalar_type(constructor_type)),
1290                           glsl_get_type_name(ir->type));
1291          return ir_rvalue::error_value(ctx);
1292       }
1293    }
1294 
1295    if (all_parameters_are_constant)
1296       return new(ctx) ir_constant(constructor_type, &actual_parameters);
1297 
1298    ir_variable *var = new(ctx) ir_variable(constructor_type, "vec_mat_ctor",
1299                                            ir_var_temporary);
1300    instructions->push_tail(var);
1301 
1302    int i = 0;
1303 
1304    foreach_in_list(ir_rvalue, rhs, &actual_parameters) {
1305       ir_instruction *assignment = NULL;
1306 
1307       if (glsl_type_is_matrix(var->type)) {
1308          ir_rvalue *lhs =
1309             new(ctx) ir_dereference_array(var, new(ctx) ir_constant(i));
1310          assignment = new(ctx) ir_assignment(lhs, rhs);
1311       } else {
1312          /* use writemask rather than index for vector */
1313          assert(glsl_type_is_vector(var->type));
1314          assert(i < 4);
1315          ir_dereference *lhs = new(ctx) ir_dereference_variable(var);
1316          assignment = new(ctx) ir_assignment(lhs, rhs, 1u << i);
1317       }
1318 
1319       instructions->push_tail(assignment);
1320 
1321       i++;
1322    }
1323 
1324    return new(ctx) ir_dereference_variable(var);
1325 }
1326 
1327 
1328 static ir_rvalue *
process_array_constructor(exec_list * instructions,const glsl_type * constructor_type,YYLTYPE * loc,exec_list * parameters,struct _mesa_glsl_parse_state * state)1329 process_array_constructor(exec_list *instructions,
1330                           const glsl_type *constructor_type,
1331                           YYLTYPE *loc, exec_list *parameters,
1332                           struct _mesa_glsl_parse_state *state)
1333 {
1334    void *ctx = state;
1335    /* Array constructors come in two forms: sized and unsized.  Sized array
1336     * constructors look like 'vec4[2](a, b)', where 'a' and 'b' are vec4
1337     * variables.  In this case the number of parameters must exactly match the
1338     * specified size of the array.
1339     *
1340     * Unsized array constructors look like 'vec4[](a, b)', where 'a' and 'b'
1341     * are vec4 variables.  In this case the size of the array being constructed
1342     * is determined by the number of parameters.
1343     *
1344     * From page 52 (page 58 of the PDF) of the GLSL 1.50 spec:
1345     *
1346     *    "There must be exactly the same number of arguments as the size of
1347     *    the array being constructed. If no size is present in the
1348     *    constructor, then the array is explicitly sized to the number of
1349     *    arguments provided. The arguments are assigned in order, starting at
1350     *    element 0, to the elements of the constructed array. Each argument
1351     *    must be the same type as the element type of the array, or be a type
1352     *    that can be converted to the element type of the array according to
1353     *    Section 4.1.10 "Implicit Conversions.""
1354     */
1355    exec_list actual_parameters;
1356    const unsigned parameter_count =
1357       process_parameters(instructions, &actual_parameters, parameters, state);
1358    bool is_unsized_array = glsl_type_is_unsized_array(constructor_type);
1359 
1360    if ((parameter_count == 0) ||
1361        (!is_unsized_array && (constructor_type->length != parameter_count))) {
1362       const unsigned min_param = is_unsized_array
1363          ? 1 : constructor_type->length;
1364 
1365       _mesa_glsl_error(loc, state, "array constructor must have %s %u "
1366                        "parameter%s",
1367                        is_unsized_array ? "at least" : "exactly",
1368                        min_param, (min_param <= 1) ? "" : "s");
1369       return ir_rvalue::error_value(ctx);
1370    }
1371 
1372    if (is_unsized_array) {
1373       constructor_type =
1374          glsl_array_type(constructor_type->fields.array,
1375                          parameter_count, 0);
1376       assert(constructor_type != NULL);
1377       assert(constructor_type->length == parameter_count);
1378    }
1379 
1380    bool all_parameters_are_constant = true;
1381    const glsl_type *element_type = constructor_type->fields.array;
1382 
1383    /* Type cast each parameter and, if possible, fold constants. */
1384    foreach_in_list_safe(ir_rvalue, ir, &actual_parameters) {
1385       /* Apply implicit conversions (not the scalar constructor rules, see the
1386        * spec quote above!) and attempt to convert the parameter to a constant
1387        * valued expression. After doing so, track whether or not all the
1388        * parameters to the constructor are trivially constant valued
1389        * expressions.
1390        */
1391       all_parameters_are_constant &=
1392          implicitly_convert_component(ir, element_type->base_type, state);
1393 
1394       if (glsl_type_is_unsized_array(constructor_type->fields.array)) {
1395          /* As the inner parameters of the constructor are created without
1396           * knowledge of each other we need to check to make sure unsized
1397           * parameters of unsized constructors all end up with the same size.
1398           *
1399           * e.g we make sure to fail for a constructor like this:
1400           * vec4[][] a = vec4[][](vec4[](vec4(0.0), vec4(1.0)),
1401           *                       vec4[](vec4(0.0), vec4(1.0), vec4(1.0)),
1402           *                       vec4[](vec4(0.0), vec4(1.0)));
1403           */
1404          if (glsl_type_is_unsized_array(element_type)) {
1405             /* This is the first parameter so just get the type */
1406             element_type = ir->type;
1407          } else if (element_type != ir->type) {
1408             _mesa_glsl_error(loc, state, "type error in array constructor: "
1409                              "expected: %s, found %s",
1410                              glsl_get_type_name(element_type),
1411                              glsl_get_type_name(ir->type));
1412             return ir_rvalue::error_value(ctx);
1413          }
1414       } else if (ir->type != constructor_type->fields.array) {
1415          _mesa_glsl_error(loc, state, "type error in array constructor: "
1416                           "expected: %s, found %s",
1417                           glsl_get_type_name(constructor_type->fields.array),
1418                           glsl_get_type_name(ir->type));
1419          return ir_rvalue::error_value(ctx);
1420       } else {
1421          element_type = ir->type;
1422       }
1423    }
1424 
1425    if (glsl_type_is_unsized_array(constructor_type->fields.array)) {
1426       constructor_type =
1427          glsl_array_type(element_type, parameter_count, 0);
1428       assert(constructor_type != NULL);
1429       assert(constructor_type->length == parameter_count);
1430    }
1431 
1432    if (all_parameters_are_constant)
1433       return new(ctx) ir_constant(constructor_type, &actual_parameters);
1434 
1435    ir_variable *var = new(ctx) ir_variable(constructor_type, "array_ctor",
1436                                            ir_var_temporary);
1437    instructions->push_tail(var);
1438 
1439    int i = 0;
1440    foreach_in_list(ir_rvalue, rhs, &actual_parameters) {
1441       ir_rvalue *lhs = new(ctx) ir_dereference_array(var,
1442                                                      new(ctx) ir_constant(i));
1443 
1444       ir_instruction *assignment = new(ctx) ir_assignment(lhs, rhs);
1445       instructions->push_tail(assignment);
1446 
1447       i++;
1448    }
1449 
1450    return new(ctx) ir_dereference_variable(var);
1451 }
1452 
1453 
1454 /**
1455  * Determine if a list consists of a single scalar r-value
1456  */
1457 static bool
single_scalar_parameter(exec_list * parameters)1458 single_scalar_parameter(exec_list *parameters)
1459 {
1460    const ir_rvalue *const p = (ir_rvalue *) parameters->get_head_raw();
1461    assert(((ir_rvalue *)p)->as_rvalue() != NULL);
1462 
1463    return (glsl_type_is_scalar(p->type) && p->next->is_tail_sentinel());
1464 }
1465 
1466 
1467 /**
1468  * Generate inline code for a vector constructor
1469  *
1470  * The generated constructor code will consist of a temporary variable
1471  * declaration of the same type as the constructor.  A sequence of assignments
1472  * from constructor parameters to the temporary will follow.
1473  *
1474  * \return
1475  * An \c ir_dereference_variable of the temprorary generated in the constructor
1476  * body.
1477  */
1478 static ir_rvalue *
emit_inline_vector_constructor(const glsl_type * type,exec_list * instructions,exec_list * parameters,void * ctx)1479 emit_inline_vector_constructor(const glsl_type *type,
1480                                exec_list *instructions,
1481                                exec_list *parameters,
1482                                void *ctx)
1483 {
1484    assert(!parameters->is_empty());
1485 
1486    ir_variable *var = new(ctx) ir_variable(type, "vec_ctor", ir_var_temporary);
1487    instructions->push_tail(var);
1488 
1489    /* There are three kinds of vector constructors.
1490     *
1491     *  - Construct a vector from a single scalar by replicating that scalar to
1492     *    all components of the vector.
1493     *
1494     *  - Construct a vector from at least a matrix. This case should already
1495     *    have been taken care of in ast_function_expression::hir by breaking
1496     *    down the matrix into a series of column vectors.
1497     *
1498     *  - Construct a vector from an arbirary combination of vectors and
1499     *    scalars.  The components of the constructor parameters are assigned
1500     *    to the vector in order until the vector is full.
1501     */
1502    const unsigned lhs_components = glsl_get_components(type);
1503    if (single_scalar_parameter(parameters)) {
1504       ir_rvalue *first_param = (ir_rvalue *)parameters->get_head_raw();
1505       return new(ctx) ir_swizzle(first_param, 0, 0, 0, 0, lhs_components);
1506    } else {
1507       unsigned base_component = 0;
1508       unsigned base_lhs_component = 0;
1509       ir_constant_data data;
1510       unsigned constant_mask = 0, constant_components = 0;
1511 
1512       memset(&data, 0, sizeof(data));
1513 
1514       foreach_in_list(ir_rvalue, param, parameters) {
1515          unsigned rhs_components = glsl_get_components(param->type);
1516 
1517          /* Do not try to assign more components to the vector than it has! */
1518          if ((rhs_components + base_lhs_component) > lhs_components) {
1519             rhs_components = lhs_components - base_lhs_component;
1520          }
1521 
1522          const ir_constant *const c = param->as_constant();
1523          if (c != NULL) {
1524             for (unsigned i = 0; i < rhs_components; i++) {
1525                switch (c->type->base_type) {
1526                case GLSL_TYPE_UINT:
1527                   data.u[i + base_component] = c->get_uint_component(i);
1528                   break;
1529                case GLSL_TYPE_INT:
1530                   data.i[i + base_component] = c->get_int_component(i);
1531                   break;
1532                case GLSL_TYPE_FLOAT:
1533                   data.f[i + base_component] = c->get_float_component(i);
1534                   break;
1535                case GLSL_TYPE_DOUBLE:
1536                   data.d[i + base_component] = c->get_double_component(i);
1537                   break;
1538                case GLSL_TYPE_BOOL:
1539                   data.b[i + base_component] = c->get_bool_component(i);
1540                   break;
1541                case GLSL_TYPE_UINT64:
1542                   data.u64[i + base_component] = c->get_uint64_component(i);
1543                   break;
1544                case GLSL_TYPE_INT64:
1545                   data.i64[i + base_component] = c->get_int64_component(i);
1546                   break;
1547                default:
1548                   assert(!"Should not get here.");
1549                   break;
1550                }
1551             }
1552 
1553             /* Mask of fields to be written in the assignment. */
1554             constant_mask |= ((1U << rhs_components) - 1) << base_lhs_component;
1555             constant_components += rhs_components;
1556 
1557             base_component += rhs_components;
1558          }
1559          /* Advance the component index by the number of components
1560           * that were just assigned.
1561           */
1562          base_lhs_component += rhs_components;
1563       }
1564 
1565       if (constant_mask != 0) {
1566          ir_dereference *lhs = new(ctx) ir_dereference_variable(var);
1567          const glsl_type *rhs_type =
1568             glsl_simple_type(var->type->base_type, constant_components, 1);
1569          ir_rvalue *rhs = new(ctx) ir_constant(rhs_type, &data);
1570 
1571          ir_instruction *inst =
1572             new(ctx) ir_assignment(lhs, rhs, constant_mask);
1573          instructions->push_tail(inst);
1574       }
1575 
1576       base_component = 0;
1577       foreach_in_list(ir_rvalue, param, parameters) {
1578          unsigned rhs_components = glsl_get_components(param->type);
1579 
1580          /* Do not try to assign more components to the vector than it has! */
1581          if ((rhs_components + base_component) > lhs_components) {
1582             rhs_components = lhs_components - base_component;
1583          }
1584 
1585          /* If we do not have any components left to copy, break out of the
1586           * loop. This can happen when initializing a vec4 with a mat3 as the
1587           * mat3 would have been broken into a series of column vectors.
1588           */
1589          if (rhs_components == 0) {
1590             break;
1591          }
1592 
1593          const ir_constant *const c = param->as_constant();
1594          if (c == NULL) {
1595             /* Mask of fields to be written in the assignment. */
1596             const unsigned write_mask = ((1U << rhs_components) - 1)
1597                << base_component;
1598 
1599             ir_dereference *lhs = new(ctx) ir_dereference_variable(var);
1600 
1601             /* Generate a swizzle so that LHS and RHS sizes match. */
1602             ir_rvalue *rhs =
1603                new(ctx) ir_swizzle(param, 0, 1, 2, 3, rhs_components);
1604 
1605             ir_instruction *inst =
1606                new(ctx) ir_assignment(lhs, rhs, write_mask);
1607             instructions->push_tail(inst);
1608          }
1609 
1610          /* Advance the component index by the number of components that were
1611           * just assigned.
1612           */
1613          base_component += rhs_components;
1614       }
1615    }
1616    return new(ctx) ir_dereference_variable(var);
1617 }
1618 
1619 
1620 /**
1621  * Generate assignment of a portion of a vector to a portion of a matrix column
1622  *
1623  * \param src_base  First component of the source to be used in assignment
1624  * \param column    Column of destination to be assiged
1625  * \param row_base  First component of the destination column to be assigned
1626  * \param count     Number of components to be assigned
1627  *
1628  * \note
1629  * \c src_base + \c count must be less than or equal to the number of
1630  * components in the source vector.
1631  */
1632 static ir_instruction *
assign_to_matrix_column(ir_variable * var,unsigned column,unsigned row_base,ir_rvalue * src,unsigned src_base,unsigned count,void * mem_ctx)1633 assign_to_matrix_column(ir_variable *var, unsigned column, unsigned row_base,
1634                         ir_rvalue *src, unsigned src_base, unsigned count,
1635                         void *mem_ctx)
1636 {
1637    ir_constant *col_idx = new(mem_ctx) ir_constant(column);
1638    ir_dereference *column_ref = new(mem_ctx) ir_dereference_array(var,
1639                                                                   col_idx);
1640 
1641    assert(glsl_get_components(column_ref->type) >= (row_base + count));
1642    assert(glsl_get_components(src->type) >= (src_base + count));
1643 
1644    /* Generate a swizzle that extracts the number of components from the source
1645     * that are to be assigned to the column of the matrix.
1646     */
1647    if (count < src->type->vector_elements) {
1648       src = new(mem_ctx) ir_swizzle(src,
1649                                     src_base + 0, src_base + 1,
1650                                     src_base + 2, src_base + 3,
1651                                     count);
1652    }
1653 
1654    /* Mask of fields to be written in the assignment. */
1655    const unsigned write_mask = ((1U << count) - 1) << row_base;
1656 
1657    return new(mem_ctx) ir_assignment(column_ref, src, write_mask);
1658 }
1659 
1660 
1661 /**
1662  * Generate inline code for a matrix constructor
1663  *
1664  * The generated constructor code will consist of a temporary variable
1665  * declaration of the same type as the constructor.  A sequence of assignments
1666  * from constructor parameters to the temporary will follow.
1667  *
1668  * \return
1669  * An \c ir_dereference_variable of the temprorary generated in the constructor
1670  * body.
1671  */
1672 static ir_rvalue *
emit_inline_matrix_constructor(const glsl_type * type,exec_list * instructions,exec_list * parameters,void * ctx)1673 emit_inline_matrix_constructor(const glsl_type *type,
1674                                exec_list *instructions,
1675                                exec_list *parameters,
1676                                void *ctx)
1677 {
1678    assert(!parameters->is_empty());
1679 
1680    ir_variable *var = new(ctx) ir_variable(type, "mat_ctor", ir_var_temporary);
1681    instructions->push_tail(var);
1682 
1683    /* There are three kinds of matrix constructors.
1684     *
1685     *  - Construct a matrix from a single scalar by replicating that scalar to
1686     *    along the diagonal of the matrix and setting all other components to
1687     *    zero.
1688     *
1689     *  - Construct a matrix from an arbirary combination of vectors and
1690     *    scalars.  The components of the constructor parameters are assigned
1691     *    to the matrix in column-major order until the matrix is full.
1692     *
1693     *  - Construct a matrix from a single matrix.  The source matrix is copied
1694     *    to the upper left portion of the constructed matrix, and the remaining
1695     *    elements take values from the identity matrix.
1696     */
1697    ir_rvalue *const first_param = (ir_rvalue *) parameters->get_head_raw();
1698    if (single_scalar_parameter(parameters)) {
1699       /* Assign the scalar to the X component of a vec4, and fill the remaining
1700        * components with zero.
1701        */
1702       glsl_base_type param_base_type = first_param->type->base_type;
1703       assert(glsl_type_is_float_16_32_64(first_param->type));
1704       ir_variable *rhs_var =
1705          new(ctx) ir_variable(glsl_simple_type(param_base_type, 4, 1),
1706                               "mat_ctor_vec",
1707                               ir_var_temporary);
1708       instructions->push_tail(rhs_var);
1709 
1710       ir_constant_data zero;
1711       for (unsigned i = 0; i < 4; i++)
1712          if (glsl_type_is_float(first_param->type))
1713             zero.f[i] = 0.0;
1714          else
1715             zero.d[i] = 0.0;
1716 
1717       ir_instruction *inst =
1718          new(ctx) ir_assignment(new(ctx) ir_dereference_variable(rhs_var),
1719                                 new(ctx) ir_constant(rhs_var->type, &zero));
1720       instructions->push_tail(inst);
1721 
1722       ir_dereference *const rhs_ref =
1723          new(ctx) ir_dereference_variable(rhs_var);
1724 
1725       inst = new(ctx) ir_assignment(rhs_ref, first_param, 0x01);
1726       instructions->push_tail(inst);
1727 
1728       /* Assign the temporary vector to each column of the destination matrix
1729        * with a swizzle that puts the X component on the diagonal of the
1730        * matrix.  In some cases this may mean that the X component does not
1731        * get assigned into the column at all (i.e., when the matrix has more
1732        * columns than rows).
1733        */
1734       static const unsigned rhs_swiz[4][4] = {
1735          { 0, 1, 1, 1 },
1736          { 1, 0, 1, 1 },
1737          { 1, 1, 0, 1 },
1738          { 1, 1, 1, 0 }
1739       };
1740 
1741       const unsigned cols_to_init = MIN2(type->matrix_columns,
1742                                          type->vector_elements);
1743       for (unsigned i = 0; i < cols_to_init; i++) {
1744          ir_constant *const col_idx = new(ctx) ir_constant(i);
1745          ir_rvalue *const col_ref = new(ctx) ir_dereference_array(var,
1746                                                                   col_idx);
1747 
1748          ir_rvalue *const rhs_ref = new(ctx) ir_dereference_variable(rhs_var);
1749          ir_rvalue *const rhs = new(ctx) ir_swizzle(rhs_ref, rhs_swiz[i],
1750                                                     type->vector_elements);
1751 
1752          inst = new(ctx) ir_assignment(col_ref, rhs);
1753          instructions->push_tail(inst);
1754       }
1755 
1756       for (unsigned i = cols_to_init; i < type->matrix_columns; i++) {
1757          ir_constant *const col_idx = new(ctx) ir_constant(i);
1758          ir_rvalue *const col_ref = new(ctx) ir_dereference_array(var,
1759                                                                   col_idx);
1760 
1761          ir_rvalue *const rhs_ref = new(ctx) ir_dereference_variable(rhs_var);
1762          ir_rvalue *const rhs = new(ctx) ir_swizzle(rhs_ref, 1, 1, 1, 1,
1763                                                     type->vector_elements);
1764 
1765          inst = new(ctx) ir_assignment(col_ref, rhs);
1766          instructions->push_tail(inst);
1767       }
1768    } else if (glsl_type_is_matrix(first_param->type)) {
1769       /* From page 50 (56 of the PDF) of the GLSL 1.50 spec:
1770        *
1771        *     "If a matrix is constructed from a matrix, then each component
1772        *     (column i, row j) in the result that has a corresponding
1773        *     component (column i, row j) in the argument will be initialized
1774        *     from there. All other components will be initialized to the
1775        *     identity matrix. If a matrix argument is given to a matrix
1776        *     constructor, it is an error to have any other arguments."
1777        */
1778       assert(first_param->next->is_tail_sentinel());
1779       ir_rvalue *const src_matrix = first_param;
1780 
1781       /* If the source matrix is smaller, pre-initialize the relavent parts of
1782        * the destination matrix to the identity matrix.
1783        */
1784       if ((src_matrix->type->matrix_columns < var->type->matrix_columns) ||
1785           (src_matrix->type->vector_elements < var->type->vector_elements)) {
1786 
1787          /* If the source matrix has fewer rows, every column of the
1788           * destination must be initialized.  Otherwise only the columns in
1789           * the destination that do not exist in the source must be
1790           * initialized.
1791           */
1792          unsigned col =
1793             (src_matrix->type->vector_elements < var->type->vector_elements)
1794             ? 0 : src_matrix->type->matrix_columns;
1795 
1796          const glsl_type *const col_type = glsl_get_column_type(var->type);
1797          for (/* empty */; col < var->type->matrix_columns; col++) {
1798             ir_constant_data ident;
1799 
1800             if (!glsl_type_is_double(col_type)) {
1801                ident.f[0] = 0.0f;
1802                ident.f[1] = 0.0f;
1803                ident.f[2] = 0.0f;
1804                ident.f[3] = 0.0f;
1805                ident.f[col] = 1.0f;
1806             } else {
1807                ident.d[0] = 0.0;
1808                ident.d[1] = 0.0;
1809                ident.d[2] = 0.0;
1810                ident.d[3] = 0.0;
1811                ident.d[col] = 1.0;
1812             }
1813 
1814             ir_rvalue *const rhs = new(ctx) ir_constant(col_type, &ident);
1815 
1816             ir_rvalue *const lhs =
1817                new(ctx) ir_dereference_array(var, new(ctx) ir_constant(col));
1818 
1819             ir_instruction *inst = new(ctx) ir_assignment(lhs, rhs);
1820             instructions->push_tail(inst);
1821          }
1822       }
1823 
1824       /* Assign columns from the source matrix to the destination matrix.
1825        *
1826        * Since the parameter will be used in the RHS of multiple assignments,
1827        * generate a temporary and copy the paramter there.
1828        */
1829       ir_variable *const rhs_var =
1830          new(ctx) ir_variable(first_param->type, "mat_ctor_mat",
1831                               ir_var_temporary);
1832       instructions->push_tail(rhs_var);
1833 
1834       ir_dereference *const rhs_var_ref =
1835          new(ctx) ir_dereference_variable(rhs_var);
1836       ir_instruction *const inst =
1837          new(ctx) ir_assignment(rhs_var_ref, first_param);
1838       instructions->push_tail(inst);
1839 
1840       const unsigned last_row = MIN2(src_matrix->type->vector_elements,
1841                                      var->type->vector_elements);
1842       const unsigned last_col = MIN2(src_matrix->type->matrix_columns,
1843                                      var->type->matrix_columns);
1844 
1845       unsigned swiz[4] = { 0, 0, 0, 0 };
1846       for (unsigned i = 1; i < last_row; i++)
1847          swiz[i] = i;
1848 
1849       const unsigned write_mask = (1U << last_row) - 1;
1850 
1851       for (unsigned i = 0; i < last_col; i++) {
1852          ir_dereference *const lhs =
1853             new(ctx) ir_dereference_array(var, new(ctx) ir_constant(i));
1854          ir_rvalue *const rhs_col =
1855             new(ctx) ir_dereference_array(rhs_var, new(ctx) ir_constant(i));
1856 
1857          /* If one matrix has columns that are smaller than the columns of the
1858           * other matrix, wrap the column access of the larger with a swizzle
1859           * so that the LHS and RHS of the assignment have the same size (and
1860           * therefore have the same type).
1861           *
1862           * It would be perfectly valid to unconditionally generate the
1863           * swizzles, this this will typically result in a more compact IR
1864           * tree.
1865           */
1866          ir_rvalue *rhs;
1867          if (lhs->type->vector_elements != rhs_col->type->vector_elements) {
1868             rhs = new(ctx) ir_swizzle(rhs_col, swiz, last_row);
1869          } else {
1870             rhs = rhs_col;
1871          }
1872 
1873          ir_instruction *inst =
1874             new(ctx) ir_assignment(lhs, rhs, write_mask);
1875          instructions->push_tail(inst);
1876       }
1877    } else {
1878       const unsigned cols = type->matrix_columns;
1879       const unsigned rows = type->vector_elements;
1880       unsigned remaining_slots = rows * cols;
1881       unsigned col_idx = 0;
1882       unsigned row_idx = 0;
1883 
1884       foreach_in_list(ir_rvalue, rhs, parameters) {
1885          unsigned rhs_components = glsl_get_components(rhs->type);
1886          unsigned rhs_base = 0;
1887 
1888          if (remaining_slots == 0)
1889             break;
1890 
1891          /* Since the parameter might be used in the RHS of two assignments,
1892           * generate a temporary and copy the paramter there.
1893           */
1894          ir_variable *rhs_var =
1895             new(ctx) ir_variable(rhs->type, "mat_ctor_vec", ir_var_temporary);
1896          instructions->push_tail(rhs_var);
1897 
1898          ir_dereference *rhs_var_ref =
1899             new(ctx) ir_dereference_variable(rhs_var);
1900          ir_instruction *inst = new(ctx) ir_assignment(rhs_var_ref, rhs);
1901          instructions->push_tail(inst);
1902 
1903          do {
1904             /* Assign the current parameter to as many components of the matrix
1905              * as it will fill.
1906              *
1907              * NOTE: A single vector parameter can span two matrix columns.  A
1908              * single vec4, for example, can completely fill a mat2.
1909              */
1910             unsigned count = MIN2(rows - row_idx,
1911                                   rhs_components - rhs_base);
1912 
1913             rhs_var_ref = new(ctx) ir_dereference_variable(rhs_var);
1914             ir_instruction *inst = assign_to_matrix_column(var, col_idx,
1915                                                            row_idx,
1916                                                            rhs_var_ref,
1917                                                            rhs_base,
1918                                                            count, ctx);
1919             instructions->push_tail(inst);
1920             rhs_base += count;
1921             row_idx += count;
1922             remaining_slots -= count;
1923 
1924             /* Sometimes, there is still data left in the parameters and
1925              * components left to be set in the destination but in other
1926              * column.
1927              */
1928             if (row_idx >= rows) {
1929                row_idx = 0;
1930                col_idx++;
1931             }
1932          } while(remaining_slots > 0 && rhs_base < rhs_components);
1933       }
1934    }
1935 
1936    return new(ctx) ir_dereference_variable(var);
1937 }
1938 
1939 
1940 static ir_rvalue *
emit_inline_record_constructor(const glsl_type * type,exec_list * instructions,exec_list * parameters,void * mem_ctx)1941 emit_inline_record_constructor(const glsl_type *type,
1942                                exec_list *instructions,
1943                                exec_list *parameters,
1944                                void *mem_ctx)
1945 {
1946    ir_variable *const var =
1947       new(mem_ctx) ir_variable(type, "record_ctor", ir_var_temporary);
1948    ir_dereference_variable *const d =
1949       new(mem_ctx) ir_dereference_variable(var);
1950 
1951    instructions->push_tail(var);
1952 
1953    exec_node *node = parameters->get_head_raw();
1954    for (unsigned i = 0; i < type->length; i++) {
1955       assert(!node->is_tail_sentinel());
1956 
1957       ir_dereference *const lhs =
1958          new(mem_ctx) ir_dereference_record(d->clone(mem_ctx, NULL),
1959                                             type->fields.structure[i].name);
1960 
1961       ir_rvalue *const rhs = ((ir_instruction *) node)->as_rvalue();
1962       assert(rhs != NULL);
1963 
1964       ir_instruction *const assign = new(mem_ctx) ir_assignment(lhs, rhs);
1965 
1966       instructions->push_tail(assign);
1967       node = node->next;
1968    }
1969 
1970    return d;
1971 }
1972 
1973 
1974 static ir_rvalue *
process_record_constructor(exec_list * instructions,const glsl_type * constructor_type,YYLTYPE * loc,exec_list * parameters,struct _mesa_glsl_parse_state * state)1975 process_record_constructor(exec_list *instructions,
1976                            const glsl_type *constructor_type,
1977                            YYLTYPE *loc, exec_list *parameters,
1978                            struct _mesa_glsl_parse_state *state)
1979 {
1980    void *ctx = state;
1981    /* From page 32 (page 38 of the PDF) of the GLSL 1.20 spec:
1982     *
1983     *    "The arguments to the constructor will be used to set the structure's
1984     *     fields, in order, using one argument per field. Each argument must
1985     *     be the same type as the field it sets, or be a type that can be
1986     *     converted to the field's type according to Section 4.1.10 “Implicit
1987     *     Conversions.”"
1988     *
1989     * From page 35 (page 41 of the PDF) of the GLSL 4.20 spec:
1990     *
1991     *    "In all cases, the innermost initializer (i.e., not a list of
1992     *     initializers enclosed in curly braces) applied to an object must
1993     *     have the same type as the object being initialized or be a type that
1994     *     can be converted to the object's type according to section 4.1.10
1995     *     "Implicit Conversions". In the latter case, an implicit conversion
1996     *     will be done on the initializer before the assignment is done."
1997     */
1998    exec_list actual_parameters;
1999 
2000    const unsigned parameter_count =
2001          process_parameters(instructions, &actual_parameters, parameters,
2002                             state);
2003 
2004    if (parameter_count != constructor_type->length) {
2005       _mesa_glsl_error(loc, state,
2006                        "%s parameters in constructor for `%s'",
2007                        parameter_count > constructor_type->length
2008                        ? "too many": "insufficient",
2009                        glsl_get_type_name(constructor_type));
2010       return ir_rvalue::error_value(ctx);
2011    }
2012 
2013    bool all_parameters_are_constant = true;
2014 
2015    int i = 0;
2016    /* Type cast each parameter and, if possible, fold constants. */
2017    foreach_in_list_safe(ir_rvalue, ir, &actual_parameters) {
2018 
2019       const glsl_struct_field *struct_field =
2020          &constructor_type->fields.structure[i];
2021 
2022       /* Apply implicit conversions (not the scalar constructor rules, see the
2023        * spec quote above!) and attempt to convert the parameter to a constant
2024        * valued expression. After doing so, track whether or not all the
2025        * parameters to the constructor are trivially constant valued
2026        * expressions.
2027        */
2028       all_parameters_are_constant &=
2029          implicitly_convert_component(ir, struct_field->type->base_type,
2030                                       state);
2031 
2032       if (ir->type != struct_field->type) {
2033          _mesa_glsl_error(loc, state,
2034                           "parameter type mismatch in constructor for `%s.%s' "
2035                           "(%s vs %s)",
2036                           glsl_get_type_name(constructor_type),
2037                           struct_field->name,
2038                           glsl_get_type_name(ir->type),
2039                           glsl_get_type_name(struct_field->type));
2040          return ir_rvalue::error_value(ctx);
2041       }
2042 
2043       i++;
2044    }
2045 
2046    if (all_parameters_are_constant) {
2047       return new(ctx) ir_constant(constructor_type, &actual_parameters);
2048    } else {
2049       return emit_inline_record_constructor(constructor_type, instructions,
2050                                             &actual_parameters, state);
2051    }
2052 }
2053 
2054 ir_rvalue *
handle_method(exec_list * instructions,struct _mesa_glsl_parse_state * state)2055 ast_function_expression::handle_method(exec_list *instructions,
2056                                        struct _mesa_glsl_parse_state *state)
2057 {
2058    const ast_expression *field = subexpressions[0];
2059    ir_rvalue *op;
2060    ir_rvalue *result;
2061    void *ctx = state;
2062    /* Handle "method calls" in GLSL 1.20 - namely, array.length() */
2063    YYLTYPE loc = get_location();
2064    state->check_version(120, 300, &loc, "methods not supported");
2065 
2066    const char *method;
2067    method = field->primary_expression.identifier;
2068 
2069    /* This would prevent to raise "uninitialized variable" warnings when
2070     * calling array.length.
2071     */
2072    field->subexpressions[0]->set_is_lhs(true);
2073    op = field->subexpressions[0]->hir(instructions, state);
2074    if (strcmp(method, "length") == 0) {
2075       if (!this->expressions.is_empty()) {
2076          _mesa_glsl_error(&loc, state, "length method takes no arguments");
2077          goto fail;
2078       }
2079 
2080       if (glsl_type_is_array(op->type)) {
2081          if (glsl_type_is_unsized_array(op->type)) {
2082             if (!state->has_shader_storage_buffer_objects()) {
2083                _mesa_glsl_error(&loc, state,
2084                                 "length called on unsized array"
2085                                 " only available with"
2086                                 " ARB_shader_storage_buffer_object");
2087                goto fail;
2088             } else if (op->variable_referenced()->is_in_shader_storage_block()) {
2089                /* Calculate length of an unsized array in run-time */
2090                result = new(ctx)
2091                   ir_expression(ir_unop_ssbo_unsized_array_length, op);
2092             } else {
2093                /* When actual size is known at link-time, this will be
2094                 * replaced with a constant expression.
2095                 */
2096                result = new (ctx)
2097                   ir_expression(ir_unop_implicitly_sized_array_length, op);
2098             }
2099          } else {
2100             result = new(ctx) ir_constant(glsl_array_size(op->type));
2101          }
2102       } else if (glsl_type_is_vector(op->type)) {
2103          if (state->has_420pack()) {
2104             /* .length() returns int. */
2105             result = new(ctx) ir_constant((int) op->type->vector_elements);
2106          } else {
2107             _mesa_glsl_error(&loc, state, "length method on matrix only"
2108                              " available with ARB_shading_language_420pack");
2109             goto fail;
2110          }
2111       } else if (glsl_type_is_matrix(op->type)) {
2112          if (state->has_420pack()) {
2113             /* .length() returns int. */
2114             result = new(ctx) ir_constant((int) op->type->matrix_columns);
2115          } else {
2116             _mesa_glsl_error(&loc, state, "length method on matrix only"
2117                              " available with ARB_shading_language_420pack");
2118             goto fail;
2119          }
2120       } else {
2121          _mesa_glsl_error(&loc, state, "length called on scalar.");
2122          goto fail;
2123       }
2124    } else {
2125       _mesa_glsl_error(&loc, state, "unknown method: `%s'", method);
2126       goto fail;
2127    }
2128    return result;
2129  fail:
2130    return ir_rvalue::error_value(ctx);
2131 }
2132 
is_valid_constructor(const glsl_type * type,struct _mesa_glsl_parse_state * state)2133 static inline bool is_valid_constructor(const glsl_type *type,
2134                                         struct _mesa_glsl_parse_state *state)
2135 {
2136    return glsl_type_is_numeric(type) || glsl_type_is_boolean(type) ||
2137           (state->has_bindless() && (glsl_type_is_sampler(type) || glsl_type_is_image(type)));
2138 }
2139 
2140 ir_rvalue *
hir(exec_list * instructions,struct _mesa_glsl_parse_state * state)2141 ast_function_expression::hir(exec_list *instructions,
2142                              struct _mesa_glsl_parse_state *state)
2143 {
2144    void *ctx = state;
2145    /* There are three sorts of function calls.
2146     *
2147     * 1. constructors - The first subexpression is an ast_type_specifier.
2148     * 2. methods - Only the .length() method of array types.
2149     * 3. functions - Calls to regular old functions.
2150     *
2151     */
2152    if (is_constructor()) {
2153       const ast_type_specifier *type =
2154          (ast_type_specifier *) subexpressions[0];
2155       YYLTYPE loc = type->get_location();
2156       const char *name;
2157 
2158       const glsl_type *const constructor_type = type->glsl_type(& name, state);
2159 
2160       /* constructor_type can be NULL if a variable with the same name as the
2161        * structure has come into scope.
2162        */
2163       if (constructor_type == NULL) {
2164          _mesa_glsl_error(& loc, state, "unknown type `%s' (structure name "
2165                           "may be shadowed by a variable with the same name)",
2166                           type->type_name);
2167          return ir_rvalue::error_value(ctx);
2168       }
2169 
2170 
2171       /* Constructors for opaque types are illegal.
2172        *
2173        * From section 4.1.7 of the ARB_bindless_texture spec:
2174        *
2175        * "Samplers are represented using 64-bit integer handles, and may be "
2176        *  converted to and from 64-bit integers using constructors."
2177        *
2178        * From section 4.1.X of the ARB_bindless_texture spec:
2179        *
2180        * "Images are represented using 64-bit integer handles, and may be
2181        *  converted to and from 64-bit integers using constructors."
2182        */
2183       if (glsl_contains_atomic(constructor_type) ||
2184           (!state->has_bindless() && glsl_contains_opaque(constructor_type))) {
2185          _mesa_glsl_error(& loc, state, "cannot construct %s type `%s'",
2186                           state->has_bindless() ? "atomic" : "opaque",
2187                           glsl_get_type_name(constructor_type));
2188          return ir_rvalue::error_value(ctx);
2189       }
2190 
2191       if (glsl_type_is_subroutine(constructor_type)) {
2192          _mesa_glsl_error(& loc, state,
2193                           "subroutine name cannot be a constructor `%s'",
2194                           glsl_get_type_name(constructor_type));
2195          return ir_rvalue::error_value(ctx);
2196       }
2197 
2198       if (glsl_type_is_array(constructor_type)) {
2199          if (!state->check_version(state->allow_glsl_120_subset_in_110 ? 110 : 120,
2200                                    300, &loc, "array constructors forbidden")) {
2201             return ir_rvalue::error_value(ctx);
2202          }
2203 
2204          return process_array_constructor(instructions, constructor_type,
2205                                           & loc, &this->expressions, state);
2206       }
2207 
2208 
2209       /* There are two kinds of constructor calls.  Constructors for arrays and
2210        * structures must have the exact number of arguments with matching types
2211        * in the correct order.  These constructors follow essentially the same
2212        * type matching rules as functions.
2213        *
2214        * Constructors for built-in language types, such as mat4 and vec2, are
2215        * free form.  The only requirements are that the parameters must provide
2216        * enough values of the correct scalar type and that no arguments are
2217        * given past the last used argument.
2218        *
2219        * When using the C-style initializer syntax from GLSL 4.20, constructors
2220        * must have the exact number of arguments with matching types in the
2221        * correct order.
2222        */
2223       if (glsl_type_is_struct(constructor_type)) {
2224          return process_record_constructor(instructions, constructor_type,
2225                                            &loc, &this->expressions,
2226                                            state);
2227       }
2228 
2229       if (!is_valid_constructor(constructor_type, state))
2230          return ir_rvalue::error_value(ctx);
2231 
2232       /* Total number of components of the type being constructed. */
2233       const unsigned type_components = glsl_get_components(constructor_type);
2234 
2235       /* Number of components from parameters that have actually been
2236        * consumed.  This is used to perform several kinds of error checking.
2237        */
2238       unsigned components_used = 0;
2239 
2240       unsigned matrix_parameters = 0;
2241       unsigned nonmatrix_parameters = 0;
2242       exec_list actual_parameters;
2243 
2244       foreach_list_typed(ast_node, ast, link, &this->expressions) {
2245          ir_rvalue *result = ast->hir(instructions, state);
2246 
2247          /* From page 50 (page 56 of the PDF) of the GLSL 1.50 spec:
2248           *
2249           *    "It is an error to provide extra arguments beyond this
2250           *    last used argument."
2251           */
2252          if (components_used >= type_components) {
2253             _mesa_glsl_error(& loc, state, "too many parameters to `%s' "
2254                              "constructor",
2255                              glsl_get_type_name(constructor_type));
2256             return ir_rvalue::error_value(ctx);
2257          }
2258 
2259          if (!is_valid_constructor(result->type, state)) {
2260             _mesa_glsl_error(& loc, state, "cannot construct `%s' from a "
2261                              "non-numeric data type",
2262                              glsl_get_type_name(constructor_type));
2263             return ir_rvalue::error_value(ctx);
2264          }
2265 
2266          /* Count the number of matrix and nonmatrix parameters.  This
2267           * is used below to enforce some of the constructor rules.
2268           */
2269          if (glsl_type_is_matrix(result->type))
2270             matrix_parameters++;
2271          else
2272             nonmatrix_parameters++;
2273 
2274          actual_parameters.push_tail(result);
2275          components_used += glsl_get_components(result->type);
2276       }
2277 
2278       /* From page 28 (page 34 of the PDF) of the GLSL 1.10 spec:
2279        *
2280        *    "It is an error to construct matrices from other matrices. This
2281        *    is reserved for future use."
2282        */
2283       if (matrix_parameters > 0
2284           && glsl_type_is_matrix(constructor_type)
2285           && !state->check_version(120, 100, &loc,
2286                                    "cannot construct `%s' from a matrix",
2287                                    glsl_get_type_name(constructor_type))) {
2288          return ir_rvalue::error_value(ctx);
2289       }
2290 
2291       /* From page 50 (page 56 of the PDF) of the GLSL 1.50 spec:
2292        *
2293        *    "If a matrix argument is given to a matrix constructor, it is
2294        *    an error to have any other arguments."
2295        */
2296       if ((matrix_parameters > 0)
2297           && ((matrix_parameters + nonmatrix_parameters) > 1)
2298           && glsl_type_is_matrix(constructor_type)) {
2299          _mesa_glsl_error(& loc, state, "for matrix `%s' constructor, "
2300                           "matrix must be only parameter",
2301                           glsl_get_type_name(constructor_type));
2302          return ir_rvalue::error_value(ctx);
2303       }
2304 
2305       /* From page 28 (page 34 of the PDF) of the GLSL 1.10 spec:
2306        *
2307        *    "In these cases, there must be enough components provided in the
2308        *    arguments to provide an initializer for every component in the
2309        *    constructed value."
2310        */
2311       if (components_used < type_components && components_used != 1
2312           && matrix_parameters == 0) {
2313          _mesa_glsl_error(& loc, state, "too few components to construct "
2314                           "`%s'",
2315                           glsl_get_type_name(constructor_type));
2316          return ir_rvalue::error_value(ctx);
2317       }
2318 
2319       /* Matrices can never be consumed as is by any constructor but matrix
2320        * constructors. If the constructor type is not matrix, always break the
2321        * matrix up into a series of column vectors.
2322        */
2323       if (!glsl_type_is_matrix(constructor_type)) {
2324          foreach_in_list_safe(ir_rvalue, matrix, &actual_parameters) {
2325             if (!glsl_type_is_matrix(matrix->type))
2326                continue;
2327 
2328             /* Create a temporary containing the matrix. */
2329             ir_variable *var = new(ctx) ir_variable(matrix->type, "matrix_tmp",
2330                                                     ir_var_temporary);
2331             instructions->push_tail(var);
2332             instructions->push_tail(
2333                new(ctx) ir_assignment(new(ctx) ir_dereference_variable(var),
2334                                       matrix));
2335             var->constant_value = matrix->constant_expression_value(ctx);
2336 
2337             /* Replace the matrix with dereferences of its columns. */
2338             for (int i = 0; i < matrix->type->matrix_columns; i++) {
2339                matrix->insert_before(
2340                   new (ctx) ir_dereference_array(var,
2341                                                  new(ctx) ir_constant(i)));
2342             }
2343             matrix->remove();
2344          }
2345       }
2346 
2347       bool all_parameters_are_constant = true;
2348 
2349       /* Type cast each parameter and, if possible, fold constants.*/
2350       foreach_in_list_safe(ir_rvalue, ir, &actual_parameters) {
2351          const glsl_type *desired_type;
2352 
2353          /* From section 5.4.1 of the ARB_bindless_texture spec:
2354           *
2355           * "In the following four constructors, the low 32 bits of the sampler
2356           *  type correspond to the .x component of the uvec2 and the high 32
2357           *  bits correspond to the .y component."
2358           *
2359           *  uvec2(any sampler type)     // Converts a sampler type to a
2360           *                              //   pair of 32-bit unsigned integers
2361           *  any sampler type(uvec2)     // Converts a pair of 32-bit unsigned integers to
2362           *                              //   a sampler type
2363           *  uvec2(any image type)       // Converts an image type to a
2364           *                              //   pair of 32-bit unsigned integers
2365           *  any image type(uvec2)       // Converts a pair of 32-bit unsigned integers to
2366           *                              //   an image type
2367           */
2368          if (glsl_type_is_sampler(ir->type) || glsl_type_is_image(ir->type)) {
2369             /* Convert a sampler/image type to a pair of 32-bit unsigned
2370              * integers as defined by ARB_bindless_texture.
2371              */
2372             if (constructor_type != &glsl_type_builtin_uvec2) {
2373                _mesa_glsl_error(&loc, state, "sampler and image types can only "
2374                                 "be converted to a pair of 32-bit unsigned "
2375                                 "integers");
2376             }
2377             desired_type = &glsl_type_builtin_uvec2;
2378          } else if (glsl_type_is_sampler(constructor_type) ||
2379                     glsl_type_is_image(constructor_type)) {
2380             /* Convert a pair of 32-bit unsigned integers to a sampler or image
2381              * type as defined by ARB_bindless_texture.
2382              */
2383             if (ir->type != &glsl_type_builtin_uvec2) {
2384                _mesa_glsl_error(&loc, state, "sampler and image types can only "
2385                                 "be converted from a pair of 32-bit unsigned "
2386                                 "integers");
2387             }
2388             desired_type = constructor_type;
2389          } else {
2390             desired_type =
2391                glsl_simple_type(constructor_type->base_type,
2392                                 ir->type->vector_elements,
2393                                 ir->type->matrix_columns);
2394          }
2395 
2396          ir_rvalue *result = convert_component(ir, desired_type);
2397 
2398          /* Attempt to convert the parameter to a constant valued expression.
2399           * After doing so, track whether or not all the parameters to the
2400           * constructor are trivially constant valued expressions.
2401           */
2402          ir_rvalue *const constant = result->constant_expression_value(ctx);
2403 
2404          if (constant != NULL)
2405             result = constant;
2406          else
2407             all_parameters_are_constant = false;
2408 
2409          if (result != ir) {
2410             ir->replace_with(result);
2411          }
2412       }
2413 
2414       /* If all of the parameters are trivially constant, create a
2415        * constant representing the complete collection of parameters.
2416        */
2417       if (all_parameters_are_constant) {
2418          return new(ctx) ir_constant(constructor_type, &actual_parameters);
2419       } else if (glsl_type_is_scalar(constructor_type)) {
2420          return dereference_component((ir_rvalue *)
2421                                       actual_parameters.get_head_raw(),
2422                                       0);
2423       } else if (glsl_type_is_vector(constructor_type)) {
2424          return emit_inline_vector_constructor(constructor_type,
2425                                                instructions,
2426                                                &actual_parameters,
2427                                                ctx);
2428       } else {
2429          assert(glsl_type_is_matrix(constructor_type));
2430          return emit_inline_matrix_constructor(constructor_type,
2431                                                instructions,
2432                                                &actual_parameters,
2433                                                ctx);
2434       }
2435    } else if (subexpressions[0]->oper == ast_field_selection) {
2436       return handle_method(instructions, state);
2437    } else {
2438       const ast_expression *id = subexpressions[0];
2439       const char *func_name = NULL;
2440       YYLTYPE loc = get_location();
2441       exec_list actual_parameters;
2442       ir_variable *sub_var = NULL;
2443       ir_rvalue *array_idx = NULL;
2444 
2445       process_parameters(instructions, &actual_parameters, &this->expressions,
2446                          state);
2447 
2448       if (id->oper == ast_array_index) {
2449          array_idx = generate_array_index(ctx, instructions, state, loc,
2450                                           id->subexpressions[0],
2451                                           id->subexpressions[1], &func_name,
2452                                           &actual_parameters);
2453       } else if (id->oper == ast_identifier) {
2454          func_name = id->primary_expression.identifier;
2455       } else {
2456          _mesa_glsl_error(&loc, state, "function name is not an identifier");
2457       }
2458 
2459       /* an error was emitted earlier */
2460       if (!func_name)
2461          return ir_rvalue::error_value(ctx);
2462 
2463       ir_function_signature *sig =
2464          match_function_by_name(func_name, &actual_parameters, state);
2465 
2466       ir_rvalue *value = NULL;
2467       if (sig == NULL) {
2468          sig = match_subroutine_by_name(func_name, &actual_parameters,
2469                                         state, &sub_var);
2470       }
2471 
2472       if (sig == NULL) {
2473          no_matching_function_error(func_name, &loc,
2474                                     &actual_parameters, state);
2475          value = ir_rvalue::error_value(ctx);
2476       } else if (!verify_parameter_modes(state, sig,
2477                                          actual_parameters,
2478                                          this->expressions)) {
2479          /* an error has already been emitted */
2480          value = ir_rvalue::error_value(ctx);
2481       } else if (sig->is_builtin() && strcmp(func_name, "ftransform") == 0) {
2482          /* ftransform refers to global variables, and we don't have any code
2483           * for remapping the variable references in the built-in shader.
2484           */
2485          ir_variable *mvp =
2486             state->symbols->get_variable("gl_ModelViewProjectionMatrix");
2487          ir_variable *vtx = state->symbols->get_variable("gl_Vertex");
2488          value = new(ctx) ir_expression(ir_binop_mul, &glsl_type_builtin_vec4,
2489                                         new(ctx) ir_dereference_variable(mvp),
2490                                         new(ctx) ir_dereference_variable(vtx));
2491       } else {
2492          bool is_begin_interlock = false;
2493          bool is_end_interlock = false;
2494          if (sig->is_builtin() &&
2495              state->stage == MESA_SHADER_FRAGMENT &&
2496              state->ARB_fragment_shader_interlock_enable) {
2497             is_begin_interlock = strcmp(func_name, "beginInvocationInterlockARB") == 0;
2498             is_end_interlock = strcmp(func_name, "endInvocationInterlockARB") == 0;
2499          }
2500 
2501          if (sig->is_builtin() &&
2502              ((state->stage == MESA_SHADER_TESS_CTRL &&
2503                strcmp(func_name, "barrier") == 0) ||
2504               is_begin_interlock || is_end_interlock)) {
2505             if (state->current_function == NULL ||
2506                 strcmp(state->current_function->function_name(), "main") != 0) {
2507                _mesa_glsl_error(&loc, state,
2508                                 "%s() may only be used in main()", func_name);
2509             }
2510 
2511             if (state->found_return) {
2512                _mesa_glsl_error(&loc, state,
2513                                 "%s() may not be used after return", func_name);
2514             }
2515 
2516             if (instructions != &state->current_function->body) {
2517                _mesa_glsl_error(&loc, state,
2518                                 "%s() may not be used in control flow", func_name);
2519             }
2520          }
2521 
2522          /* There can be only one begin/end interlock pair in the function. */
2523          if (is_begin_interlock) {
2524             if (state->found_begin_interlock)
2525                _mesa_glsl_error(&loc, state,
2526                                 "beginInvocationInterlockARB may not be used twice");
2527             state->found_begin_interlock = true;
2528          } else if (is_end_interlock) {
2529             if (!state->found_begin_interlock)
2530                _mesa_glsl_error(&loc, state,
2531                                 "endInvocationInterlockARB may not be used "
2532                                 "before beginInvocationInterlockARB");
2533             if (state->found_end_interlock)
2534                _mesa_glsl_error(&loc, state,
2535                                 "endInvocationInterlockARB may not be used twice");
2536             state->found_end_interlock = true;
2537          }
2538 
2539          value = generate_call(instructions, sig, &actual_parameters, sub_var,
2540                                array_idx, state);
2541          if (!value) {
2542             ir_variable *const tmp = new(ctx) ir_variable(&glsl_type_builtin_void,
2543                                                           "void_var",
2544                                                           ir_var_temporary);
2545             instructions->push_tail(tmp);
2546             value = new(ctx) ir_dereference_variable(tmp);
2547          }
2548       }
2549 
2550       return value;
2551    }
2552 
2553    unreachable("not reached");
2554 }
2555 
2556 bool
has_sequence_subexpression() const2557 ast_function_expression::has_sequence_subexpression() const
2558 {
2559    foreach_list_typed(const ast_node, ast, link, &this->expressions) {
2560       if (ast->has_sequence_subexpression())
2561          return true;
2562    }
2563 
2564    return false;
2565 }
2566 
2567 ir_rvalue *
hir(exec_list * instructions,struct _mesa_glsl_parse_state * state)2568 ast_aggregate_initializer::hir(exec_list *instructions,
2569                                struct _mesa_glsl_parse_state *state)
2570 {
2571    void *ctx = state;
2572    YYLTYPE loc = this->get_location();
2573 
2574    if (!this->constructor_type) {
2575       _mesa_glsl_error(&loc, state, "type of C-style initializer unknown");
2576       return ir_rvalue::error_value(ctx);
2577    }
2578    const glsl_type *const constructor_type = this->constructor_type;
2579 
2580    if (!state->has_420pack()) {
2581       _mesa_glsl_error(&loc, state, "C-style initialization requires the "
2582                        "GL_ARB_shading_language_420pack extension");
2583       return ir_rvalue::error_value(ctx);
2584    }
2585 
2586    if (glsl_type_is_array(constructor_type)) {
2587       return process_array_constructor(instructions, constructor_type, &loc,
2588                                        &this->expressions, state);
2589    }
2590 
2591    if (glsl_type_is_struct(constructor_type)) {
2592       return process_record_constructor(instructions, constructor_type, &loc,
2593                                         &this->expressions, state);
2594    }
2595 
2596    return process_vec_mat_constructor(instructions, constructor_type, &loc,
2597                                       &this->expressions, state);
2598 }
2599