ir_constant_visitor: Use 'union ir_constant_data' in expression handler
[mesa.git] / ast_function.cpp
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 <cstdio>
25 #include "glsl_symbol_table.h"
26 #include "ast.h"
27 #include "glsl_types.h"
28 #include "ir.h"
29
30 static unsigned
31 process_parameters(exec_list *instructions, exec_list *actual_parameters,
32 exec_list *parameters,
33 struct _mesa_glsl_parse_state *state)
34 {
35 unsigned count = 0;
36
37 foreach_list (n, parameters) {
38 ast_node *const ast = exec_node_data(ast_node, n, link);
39 ir_rvalue *result = ast->hir(instructions, state);
40
41 ir_constant *const constant = result->constant_expression_value();
42 if (constant != NULL)
43 result = constant;
44
45 actual_parameters->push_tail(result);
46 count++;
47 }
48
49 return count;
50 }
51
52
53 static ir_rvalue *
54 process_call(exec_list *instructions, ir_function *f,
55 YYLTYPE *loc, exec_list *actual_parameters,
56 struct _mesa_glsl_parse_state *state)
57 {
58 const ir_function_signature *sig =
59 f->matching_signature(actual_parameters);
60
61 /* The instructions param will be used when the FINISHMEs below are done */
62 (void) instructions;
63
64 if (sig != NULL) {
65 /* Verify that 'out' and 'inout' actual parameters are lvalues. This
66 * isn't done in ir_function::matching_signature because that function
67 * cannot generate the necessary diagnostics.
68 */
69 exec_list_iterator actual_iter = actual_parameters->iterator();
70 exec_list_iterator formal_iter = sig->parameters.iterator();
71
72 while (actual_iter.has_next()) {
73 ir_rvalue *actual = (ir_rvalue *) actual_iter.get();
74 ir_variable *formal = (ir_variable *) formal_iter.get();
75
76 assert(actual != NULL);
77 assert(formal != NULL);
78
79 if ((formal->mode == ir_var_out)
80 || (formal->mode == ir_var_inout)) {
81 if (! actual->is_lvalue()) {
82 /* FINISHME: Log a better diagnostic here. There is no way
83 * FINISHME: to tell the user which parameter is invalid.
84 */
85 _mesa_glsl_error(loc, state, "`%s' parameter is not lvalue",
86 (formal->mode == ir_var_out) ? "out" : "inout");
87 }
88 }
89
90 actual_iter.next();
91 formal_iter.next();
92 }
93
94 /* FINISHME: The list of actual parameters needs to be modified to
95 * FINISHME: include any necessary conversions.
96 */
97 return new ir_call(sig, actual_parameters);
98 } else {
99 /* FINISHME: Log a better error message here. G++ will show the types
100 * FINISHME: of the actual parameters and the set of candidate
101 * FINISHME: functions. A different error should also be logged when
102 * FINISHME: multiple functions match.
103 */
104 _mesa_glsl_error(loc, state, "no matching function for call to `%s'",
105 f->name);
106 return ir_call::get_error_instruction();
107 }
108 }
109
110
111 static ir_rvalue *
112 match_function_by_name(exec_list *instructions, const char *name,
113 YYLTYPE *loc, exec_list *actual_parameters,
114 struct _mesa_glsl_parse_state *state)
115 {
116 ir_function *f = state->symbols->get_function(name);
117
118 if (f == NULL) {
119 _mesa_glsl_error(loc, state, "function `%s' undeclared", name);
120 return ir_call::get_error_instruction();
121 }
122
123 /* Once we've determined that the function being called might exist, try
124 * to find an overload of the function that matches the parameters.
125 */
126 return process_call(instructions, f, loc, actual_parameters, state);
127 }
128
129
130 /**
131 * Perform automatic type conversion of constructor parameters
132 */
133 static ir_rvalue *
134 convert_component(ir_rvalue *src, const glsl_type *desired_type)
135 {
136 const unsigned a = desired_type->base_type;
137 const unsigned b = src->type->base_type;
138 ir_expression *result = NULL;
139
140 if (src->type->is_error())
141 return src;
142
143 assert(a <= GLSL_TYPE_BOOL);
144 assert(b <= GLSL_TYPE_BOOL);
145
146 if ((a == b) || (src->type->is_integer() && desired_type->is_integer()))
147 return src;
148
149 switch (a) {
150 case GLSL_TYPE_UINT:
151 case GLSL_TYPE_INT:
152 if (b == GLSL_TYPE_FLOAT)
153 result = new ir_expression(ir_unop_f2i, desired_type, src, NULL);
154 else {
155 assert(b == GLSL_TYPE_BOOL);
156 result = new ir_expression(ir_unop_b2i, desired_type, src, NULL);
157 }
158 break;
159 case GLSL_TYPE_FLOAT:
160 switch (b) {
161 case GLSL_TYPE_UINT:
162 result = new ir_expression(ir_unop_u2f, desired_type, src, NULL);
163 break;
164 case GLSL_TYPE_INT:
165 result = new ir_expression(ir_unop_i2f, desired_type, src, NULL);
166 break;
167 case GLSL_TYPE_BOOL:
168 result = new ir_expression(ir_unop_b2f, desired_type, src, NULL);
169 break;
170 }
171 break;
172 case GLSL_TYPE_BOOL: {
173 int z = 0;
174 ir_constant *const zero = new ir_constant(src->type, &z);
175
176 result = new ir_expression(ir_binop_nequal, desired_type, src, zero);
177 }
178 }
179
180 assert(result != NULL);
181
182 ir_constant *const constant = result->constant_expression_value();
183 return (constant != NULL) ? (ir_rvalue *) constant : (ir_rvalue *) result;
184 }
185
186
187 /**
188 * Dereference a specific component from a scalar, vector, or matrix
189 */
190 static ir_rvalue *
191 dereference_component(ir_rvalue *src, unsigned component)
192 {
193 assert(component < src->type->components());
194
195 /* If the source is a constant, just create a new constant instead of a
196 * dereference of the existing constant.
197 */
198 ir_constant *constant = src->as_constant();
199 if (constant)
200 return new ir_constant(constant, component);
201
202 if (src->type->is_scalar()) {
203 return src;
204 } else if (src->type->is_vector()) {
205 return new ir_swizzle(src, component, 0, 0, 0, 1);
206 } else {
207 assert(src->type->is_matrix());
208
209 /* Dereference a row of the matrix, then call this function again to get
210 * a specific element from that row.
211 */
212 const int c = component / src->type->column_type()->vector_elements;
213 const int r = component % src->type->column_type()->vector_elements;
214 ir_constant *const col_index = new ir_constant(glsl_type::int_type, &c);
215 ir_dereference *const col = new ir_dereference_array(src, col_index);
216
217 col->type = src->type->column_type();
218
219 return dereference_component(col, r);
220 }
221
222 assert(!"Should not get here.");
223 return NULL;
224 }
225
226
227 static ir_rvalue *
228 process_array_constructor(exec_list *instructions,
229 const glsl_type *constructor_type,
230 YYLTYPE *loc, exec_list *parameters,
231 struct _mesa_glsl_parse_state *state)
232 {
233 /* Array constructors come in two forms: sized and unsized. Sized array
234 * constructors look like 'vec4[2](a, b)', where 'a' and 'b' are vec4
235 * variables. In this case the number of parameters must exactly match the
236 * specified size of the array.
237 *
238 * Unsized array constructors look like 'vec4[](a, b)', where 'a' and 'b'
239 * are vec4 variables. In this case the size of the array being constructed
240 * is determined by the number of parameters.
241 *
242 * From page 52 (page 58 of the PDF) of the GLSL 1.50 spec:
243 *
244 * "There must be exactly the same number of arguments as the size of
245 * the array being constructed. If no size is present in the
246 * constructor, then the array is explicitly sized to the number of
247 * arguments provided. The arguments are assigned in order, starting at
248 * element 0, to the elements of the constructed array. Each argument
249 * must be the same type as the element type of the array, or be a type
250 * that can be converted to the element type of the array according to
251 * Section 4.1.10 "Implicit Conversions.""
252 */
253 exec_list actual_parameters;
254 const unsigned parameter_count =
255 process_parameters(instructions, &actual_parameters, parameters, state);
256
257 if ((parameter_count == 0)
258 || ((constructor_type->length != 0)
259 && (constructor_type->length != parameter_count))) {
260 const unsigned min_param = (constructor_type->length == 0)
261 ? 1 : constructor_type->length;
262
263 _mesa_glsl_error(loc, state, "array constructor must have %s %u "
264 "parameter%s",
265 (constructor_type->length != 0) ? "at least" : "exactly",
266 min_param, (min_param <= 1) ? "" : "s");
267 return ir_call::get_error_instruction();
268 }
269
270 if (constructor_type->length == 0) {
271 constructor_type =
272 glsl_type::get_array_instance(constructor_type->element_type(),
273 parameter_count);
274 assert(constructor_type != NULL);
275 assert(constructor_type->length == parameter_count);
276 }
277
278 ir_function *f = state->symbols->get_function(constructor_type->name);
279
280 /* If the constructor for this type of array does not exist, generate the
281 * prototype and add it to the symbol table.
282 */
283 if (f == NULL) {
284 f = constructor_type->generate_constructor(state->symbols);
285 }
286
287 ir_rvalue *const r =
288 process_call(instructions, f, loc, &actual_parameters, state);
289
290 assert(r != NULL);
291 assert(r->type->is_error() || (r->type == constructor_type));
292
293 return r;
294 }
295
296
297 /**
298 * Try to convert a record constructor to a constant expression
299 */
300 static ir_constant *
301 constant_record_constructor(const glsl_type *constructor_type,
302 YYLTYPE *loc, exec_list *parameters,
303 struct _mesa_glsl_parse_state *state)
304 {
305 bool all_parameters_are_constant = true;
306
307 exec_node *node = parameters->head;
308 for (unsigned i = 0; i < constructor_type->length; i++) {
309 ir_instruction *ir = (ir_instruction *) node;
310
311 if (node->is_tail_sentinal()) {
312 _mesa_glsl_error(loc, state,
313 "insufficient parameters to constructor for `%s'",
314 constructor_type->name);
315 return NULL;
316 }
317
318 if (ir->type != constructor_type->fields.structure[i].type) {
319 _mesa_glsl_error(loc, state,
320 "parameter type mismatch in constructor for `%s' "
321 " (%s vs %s)",
322 constructor_type->name,
323 ir->type->name,
324 constructor_type->fields.structure[i].type->name);
325 return NULL;
326 }
327
328 if (ir->as_constant() == NULL)
329 all_parameters_are_constant = false;
330
331 node = node->next;
332 }
333
334 if (!all_parameters_are_constant)
335 return NULL;
336
337 return new ir_constant(constructor_type, parameters);
338 }
339
340
341 /**
342 * Generate data for a constant matrix constructor w/a single scalar parameter
343 *
344 * Matrix constructors in GLSL can be passed a single scalar of the
345 * approriate type. In these cases, the resulting matrix is the identity
346 * matrix multipled by the specified scalar. This function generates data for
347 * that matrix.
348 *
349 * \param type Type of the desired matrix.
350 * \param initializer Scalar value used to initialize the matrix diagonal.
351 * \param data Location to store the resulting matrix.
352 */
353 void
354 generate_constructor_matrix(const glsl_type *type, ir_constant *initializer,
355 ir_constant_data *data)
356 {
357 switch (type->base_type) {
358 case GLSL_TYPE_UINT:
359 case GLSL_TYPE_INT:
360 for (unsigned i = 0; i < type->components(); i++)
361 data->u[i] = 0;
362
363 for (unsigned i = 0; i < type->matrix_columns; i++) {
364 /* The array offset of the ith row and column of the matrix.
365 */
366 const unsigned idx = (i * type->vector_elements) + i;
367
368 data->u[idx] = initializer->value.u[0];
369 }
370 break;
371
372 case GLSL_TYPE_FLOAT:
373 for (unsigned i = 0; i < type->components(); i++)
374 data->f[i] = 0;
375
376 for (unsigned i = 0; i < type->matrix_columns; i++) {
377 /* The array offset of the ith row and column of the matrix.
378 */
379 const unsigned idx = (i * type->vector_elements) + i;
380
381 data->f[idx] = initializer->value.f[0];
382 }
383
384 break;
385
386 default:
387 assert(!"Should not get here.");
388 break;
389 }
390 }
391
392
393 /**
394 * Generate data for a constant vector constructor w/a single scalar parameter
395 *
396 * Vector constructors in GLSL can be passed a single scalar of the
397 * approriate type. In these cases, the resulting vector contains the specified
398 * value in all components. This function generates data for that vector.
399 *
400 * \param type Type of the desired vector.
401 * \param initializer Scalar value used to initialize the vector.
402 * \param data Location to store the resulting vector data.
403 */
404 void
405 generate_constructor_vector(const glsl_type *type, ir_constant *initializer,
406 ir_constant_data *data)
407 {
408 switch (type->base_type) {
409 case GLSL_TYPE_UINT:
410 case GLSL_TYPE_INT:
411 for (unsigned i = 0; i < type->components(); i++)
412 data->u[i] = initializer->value.u[0];
413
414 break;
415
416 case GLSL_TYPE_FLOAT:
417 for (unsigned i = 0; i < type->components(); i++)
418 data->f[i] = initializer->value.f[0];
419
420 break;
421
422 case GLSL_TYPE_BOOL:
423 for (unsigned i = 0; i < type->components(); i++)
424 data->b[i] = initializer->value.b[0];
425
426 break;
427
428 default:
429 assert(!"Should not get here.");
430 break;
431 }
432 }
433
434
435 ir_rvalue *
436 ast_function_expression::hir(exec_list *instructions,
437 struct _mesa_glsl_parse_state *state)
438 {
439 /* There are three sorts of function calls.
440 *
441 * 1. contstructors - The first subexpression is an ast_type_specifier.
442 * 2. methods - Only the .length() method of array types.
443 * 3. functions - Calls to regular old functions.
444 *
445 * Method calls are actually detected when the ast_field_selection
446 * expression is handled.
447 */
448 if (is_constructor()) {
449 const ast_type_specifier *type = (ast_type_specifier *) subexpressions[0];
450 YYLTYPE loc = type->get_location();
451 const char *name;
452
453 const glsl_type *const constructor_type = type->glsl_type(& name, state);
454
455
456 /* Constructors for samplers are illegal.
457 */
458 if (constructor_type->is_sampler()) {
459 _mesa_glsl_error(& loc, state, "cannot construct sampler type `%s'",
460 constructor_type->name);
461 return ir_call::get_error_instruction();
462 }
463
464 if (constructor_type->is_array()) {
465 if (state->language_version <= 110) {
466 _mesa_glsl_error(& loc, state,
467 "array constructors forbidden in GLSL 1.10");
468 return ir_call::get_error_instruction();
469 }
470
471 return process_array_constructor(instructions, constructor_type,
472 & loc, &this->expressions, state);
473 }
474
475 /* There are two kinds of constructor call. Constructors for built-in
476 * language types, such as mat4 and vec2, are free form. The only
477 * requirement is that the parameters must provide enough values of the
478 * correct scalar type. Constructors for arrays and structures must
479 * have the exact number of parameters with matching types in the
480 * correct order. These constructors follow essentially the same type
481 * matching rules as functions.
482 */
483 if (constructor_type->is_numeric() || constructor_type->is_boolean()) {
484 /* Constructing a numeric type has a couple steps. First all values
485 * passed to the constructor are broken into individual parameters
486 * and type converted to the base type of the thing being constructed.
487 *
488 * At that point we have some number of values that match the base
489 * type of the thing being constructed. Now the constructor can be
490 * treated like a function call. Each numeric type has a small set
491 * of constructor functions. The set of new parameters will either
492 * match one of those functions or the original constructor is
493 * invalid.
494 */
495 const glsl_type *const base_type = constructor_type->get_base_type();
496
497 /* Total number of components of the type being constructed.
498 */
499 const unsigned type_components = constructor_type->components();
500
501 /* Number of components from parameters that have actually been
502 * consumed. This is used to perform several kinds of error checking.
503 */
504 unsigned components_used = 0;
505
506 unsigned matrix_parameters = 0;
507 unsigned nonmatrix_parameters = 0;
508 exec_list actual_parameters;
509
510 bool all_parameters_are_constant = true;
511
512 assert(!this->expressions.is_empty());
513
514 foreach_list (n, &this->expressions) {
515 ast_node *ast = exec_node_data(ast_node, n, link);
516 ir_rvalue *result =
517 ast->hir(instructions, state)->as_rvalue();
518
519 /* Attempt to convert the parameter to a constant valued expression.
520 * After doing so, track whether or not all the parameters to the
521 * constructor are trivially constant valued expressions.
522 */
523 ir_rvalue *const constant =
524 result->constant_expression_value();
525
526 if (constant != NULL)
527 result = constant;
528 else
529 all_parameters_are_constant = false;
530
531 /* From page 50 (page 56 of the PDF) of the GLSL 1.50 spec:
532 *
533 * "It is an error to provide extra arguments beyond this
534 * last used argument."
535 */
536 if (components_used >= type_components) {
537 _mesa_glsl_error(& loc, state, "too many parameters to `%s' "
538 "constructor",
539 constructor_type->name);
540 return ir_call::get_error_instruction();
541 }
542
543 if (!result->type->is_numeric() && !result->type->is_boolean()) {
544 _mesa_glsl_error(& loc, state, "cannot construct `%s' from a "
545 "non-numeric data type",
546 constructor_type->name);
547 return ir_call::get_error_instruction();
548 }
549
550 /* Count the number of matrix and nonmatrix parameters. This
551 * is used below to enforce some of the constructor rules.
552 */
553 if (result->type->is_matrix())
554 matrix_parameters++;
555 else
556 nonmatrix_parameters++;
557
558
559 /* Process each of the components of the parameter. Dereference
560 * each component individually, perform any type conversions, and
561 * add it to the parameter list for the constructor.
562 */
563 for (unsigned i = 0; i < result->type->components(); i++) {
564 if (components_used >= type_components)
565 break;
566
567 ir_rvalue *const component =
568 convert_component(dereference_component(result, i),
569 base_type);
570
571 /* All cases that could result in component->type being the
572 * error type should have already been caught above.
573 */
574 assert(component->type == base_type);
575
576 if (component->as_constant() == NULL)
577 all_parameters_are_constant = false;
578
579 /* Don't actually generate constructor calls for scalars.
580 * Instead, do the usual component selection and conversion,
581 * and return the single component.
582 */
583 if (constructor_type->is_scalar())
584 return component;
585
586 actual_parameters.push_tail(component);
587 components_used++;
588 }
589 }
590
591 /* From page 28 (page 34 of the PDF) of the GLSL 1.10 spec:
592 *
593 * "It is an error to construct matrices from other matrices. This
594 * is reserved for future use."
595 */
596 if ((state->language_version <= 110) && (matrix_parameters > 0)
597 && constructor_type->is_matrix()) {
598 _mesa_glsl_error(& loc, state, "cannot construct `%s' from a "
599 "matrix in GLSL 1.10",
600 constructor_type->name);
601 return ir_call::get_error_instruction();
602 }
603
604 /* From page 50 (page 56 of the PDF) of the GLSL 1.50 spec:
605 *
606 * "If a matrix argument is given to a matrix constructor, it is
607 * an error to have any other arguments."
608 */
609 if ((matrix_parameters > 0)
610 && ((matrix_parameters + nonmatrix_parameters) > 1)
611 && constructor_type->is_matrix()) {
612 _mesa_glsl_error(& loc, state, "for matrix `%s' constructor, "
613 "matrix must be only parameter",
614 constructor_type->name);
615 return ir_call::get_error_instruction();
616 }
617
618 /* From page 28 (page 34 of the PDF) of the GLSL 1.10 spec:
619 *
620 * "In these cases, there must be enough components provided in the
621 * arguments to provide an initializer for every component in the
622 * constructed value."
623 */
624 if ((components_used < type_components) && (components_used != 1)) {
625 _mesa_glsl_error(& loc, state, "too few components to construct "
626 "`%s'",
627 constructor_type->name);
628 return ir_call::get_error_instruction();
629 }
630
631 ir_function *f = state->symbols->get_function(constructor_type->name);
632 if (f == NULL) {
633 _mesa_glsl_error(& loc, state, "no constructor for type `%s'",
634 constructor_type->name);
635 return ir_call::get_error_instruction();
636 }
637
638 const ir_function_signature *sig =
639 f->matching_signature(& actual_parameters);
640 if (sig != NULL) {
641 /* If all of the parameters are trivially constant, create a
642 * constant representing the complete collection of parameters.
643 */
644 if (all_parameters_are_constant) {
645 if (components_used >= type_components)
646 return new ir_constant(sig->return_type, & actual_parameters);
647
648 assert(sig->return_type->is_vector()
649 || sig->return_type->is_matrix());
650
651 /* Constructors with exactly one component are special for
652 * vectors and matrices. For vectors it causes all elements of
653 * the vector to be filled with the value. For matrices it
654 * causes the matrix to be filled with 0 and the diagonal to be
655 * filled with the value.
656 */
657 ir_constant_data data;
658 ir_constant *const initializer =
659 (ir_constant *) actual_parameters.head;
660 if (sig->return_type->is_matrix())
661 generate_constructor_matrix(sig->return_type, initializer,
662 &data);
663 else
664 generate_constructor_vector(sig->return_type, initializer,
665 &data);
666
667 return new ir_constant(sig->return_type, &data);
668 } else
669 return new ir_call(sig, & actual_parameters);
670 } else {
671 /* FINISHME: Log a better error message here. G++ will show the
672 * FINSIHME: types of the actual parameters and the set of
673 * FINSIHME: candidate functions. A different error should also be
674 * FINSIHME: logged when multiple functions match.
675 */
676 _mesa_glsl_error(& loc, state, "no matching constructor for `%s'",
677 constructor_type->name);
678 return ir_call::get_error_instruction();
679 }
680 }
681
682 return ir_call::get_error_instruction();
683 } else {
684 const ast_expression *id = subexpressions[0];
685 YYLTYPE loc = id->get_location();
686 exec_list actual_parameters;
687
688 process_parameters(instructions, &actual_parameters, &this->expressions,
689 state);
690
691 const glsl_type *const type =
692 state->symbols->get_type(id->primary_expression.identifier);
693
694 if ((type != NULL) && type->is_record()) {
695 ir_constant *constant =
696 constant_record_constructor(type, &loc, &actual_parameters, state);
697
698 if (constant != NULL)
699 return constant;
700 }
701
702 return match_function_by_name(instructions,
703 id->primary_expression.identifier, & loc,
704 &actual_parameters, state);
705 }
706
707 return ir_call::get_error_instruction();
708 }