1 #include <msp/core/algorithm.h>
2 #include <msp/core/raii.h>
3 #include <msp/strings/regex.h>
4 #include <msp/strings/utils.h>
14 void BlockHierarchyResolver::enter(Block &block)
16 r_any_resolved |= (current_block!=block.parent);
17 block.parent = current_block;
21 bool TypeResolver::apply(Stage &s)
25 r_any_resolved = false;
26 s.content.visit(*this);
27 return r_any_resolved;
30 TypeDeclaration *TypeResolver::get_or_create_array_type(TypeDeclaration &type)
32 bool extended_alignment = iface_block;
33 auto key = make_pair(&type, extended_alignment);
34 auto i = array_types.find(key);
35 if(i!=array_types.end())
38 BasicTypeDeclaration *array = new BasicTypeDeclaration;
39 array->source = INTERNAL_SOURCE;
40 array->name = type.name+"[]";
41 array->kind = BasicTypeDeclaration::ARRAY;
42 array->extended_alignment = extended_alignment;
43 array->base = type.name;
44 array->base_type = &type;
45 stage->content.body.insert(type_insert_point, array);
46 array_types[key] = array;
50 TypeDeclaration *TypeResolver::get_or_create_image_type(ImageTypeDeclaration &type, const std::string &texel_format)
52 if(texel_format.empty())
55 auto key = make_pair(&type, texel_format);
56 auto i = image_types.find(key);
57 if(i!=image_types.end())
60 ImageTypeDeclaration *image = new ImageTypeDeclaration(type);
61 image->source = INTERNAL_SOURCE;
62 image->name = format("%s_%s", type.name, texel_format);
63 image->format = texel_format;
64 image->base_image = &type;
65 stage->content.body.insert(type_insert_point, image);
66 image_types[key] = image;
70 void TypeResolver::resolve_type(TypeDeclaration *&type, const string &name, bool array, const Layout *layout)
72 TypeDeclaration *resolved = 0;
73 auto i = stage->types.find(name);
74 if(i!=stage->types.end())
76 auto j = alias_map.find(i->second);
77 resolved = (j!=alias_map.end() ? j->second : i->second);
82 if(ImageTypeDeclaration *image = dynamic_cast<ImageTypeDeclaration *>(resolved))
85 static const Regex r_format("^(r|rg|rgba)(8|16|8_snorm|16_snorm|16f|32f)$");
86 for(const Layout::Qualifier &q: layout->qualifiers)
87 if(r_format.match(q.name))
89 resolved = get_or_create_image_type(*image, q.name);
95 resolved = get_or_create_array_type(*resolved);
98 r_any_resolved |= (resolved!=type);
102 void TypeResolver::visit(Block &block)
104 for(auto i=block.body.begin(); i!=block.body.end(); ++i)
107 type_insert_point = i;
112 void TypeResolver::visit(BasicTypeDeclaration &type)
114 resolve_type(type.base_type, type.base, false);
116 if(type.kind==BasicTypeDeclaration::VECTOR && type.base_type)
117 if(BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type))
118 if(basic_base->kind==BasicTypeDeclaration::VECTOR)
120 type.kind = BasicTypeDeclaration::MATRIX;
121 /* A matrix's base type is its column vector type. This will put
122 the column vector's size, i.e. the matrix's row count, in the high
124 type.size |= basic_base->size<<16;
127 if(type.kind==BasicTypeDeclaration::ALIAS && type.base_type)
128 alias_map[&type] = type.base_type;
129 else if(type.kind==BasicTypeDeclaration::ARRAY && type.base_type)
130 array_types[make_pair(type.base_type, type.extended_alignment)] = &type;
132 stage->types.insert(make_pair(type.name, &type));
135 void TypeResolver::visit(ImageTypeDeclaration &type)
137 resolve_type(type.base_type, type.base, false);
139 if(!type.format.empty() && type.base_image)
140 image_types[make_pair(type.base_image, type.format)] = &type;
142 stage->types.insert(make_pair(type.name, &type));
145 void TypeResolver::visit(StructDeclaration &strct)
147 stage->types.insert(make_pair(strct.name, &strct));
148 if(strct.block_name.empty())
150 SetForScope<VariableDeclaration *> set_iface(iface_block, strct.block_declaration);
151 TraversingVisitor::visit(strct);
154 block_member_type_ins_pt = type_insert_point;
157 void TypeResolver::visit(VariableDeclaration &var)
159 resolve_type(var.type_declaration, var.type, var.array, var.layout.get());
161 var.block_declaration = 0;
162 if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(get_ultimate_base_type(var.type_declaration)))
163 if(!strct->block_name.empty())
165 var.block_declaration = strct;
166 strct->block_declaration = &var;
167 strct->extended_alignment = true;
169 SetForScope<NodeList<Statement>::iterator> set_ins_pt(type_insert_point, block_member_type_ins_pt);
170 SetForScope<VariableDeclaration *> set_iface(iface_block, &var);
171 TraversingVisitor::visit(*strct);
176 if(var.interface==iface_block->interface)
177 var.interface.clear();
178 if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(var.type_declaration))
179 strct->extended_alignment = true;
183 void TypeResolver::visit(FunctionDeclaration &func)
185 resolve_type(func.return_type_declaration, func.return_type, false);
186 TraversingVisitor::visit(func);
190 bool VariableResolver::apply(Stage &s)
193 s.interface_blocks.clear();
194 r_any_resolved = false;
195 s.content.visit(*this);
196 for(Statement *b: redeclared_builtins)
197 b->source = GENERATED_SOURCE;
198 NodeRemover().apply(s, nodes_to_remove);
199 return r_any_resolved;
202 void VariableResolver::enter(Block &block)
204 block.variables.clear();
207 void VariableResolver::visit(RefPtr<Expression> &expr)
209 r_replacement_expr = 0;
211 if(r_replacement_expr)
213 expr = r_replacement_expr;
214 /* Don't record assignment target when doing a replacement, because chain
215 information won't be correct. */
216 r_assignment_target.declaration = 0;
217 r_any_resolved = true;
219 r_replacement_expr = 0;
222 void VariableResolver::check_assignment_target(VariableDeclaration *declaration)
226 if(r_assignment_target.declaration)
228 /* More than one reference found in assignment target. Unable to
229 determine what the primary target is. */
230 record_target = false;
231 r_assignment_target.declaration = 0;
234 r_assignment_target.declaration = declaration;
236 // TODO This check is overly broad and may prevent some optimizations.
237 else if(declaration && declaration==r_assignment_target.declaration)
238 r_self_referencing = true;
241 void VariableResolver::visit(VariableReference &var)
243 VariableDeclaration *declaration = 0;
245 /* Look for variable declarations in the block hierarchy first. Interface
246 blocks are always defined in the top level so we can't accidentally skip
248 for(Block *block=current_block; (!declaration && block); block=block->parent)
250 auto i = block->variables.find(var.name);
251 if(i!=block->variables.end())
252 declaration = i->second;
257 for(const auto &kvp: stage->interface_blocks)
258 if(kvp.second->name.find(' ')!=string::npos && kvp.second->block_declaration->members.variables.count(var.name))
260 /* The name refers a member of an anonymous interface block. Prepare
261 new syntax tree nodes accordingly. */
262 VariableReference *iface_ref = new VariableReference;
263 iface_ref->name = kvp.first;
264 iface_ref->source = var.source;
265 iface_ref->line = var.line;
266 iface_ref->declaration = kvp.second;
268 MemberAccess *memacc = new MemberAccess;
269 memacc->source = var.source;
270 memacc->line = var.line;
271 memacc->left = iface_ref;
272 memacc->member = var.name;
274 r_replacement_expr = memacc;
279 r_any_resolved |= (declaration!=var.declaration);
280 var.declaration = declaration;
282 check_assignment_target(var.declaration);
285 void VariableResolver::visit(MemberAccess &memacc)
287 TraversingVisitor::visit(memacc);
289 VariableDeclaration *declaration = 0;
291 if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(memacc.left->type))
293 auto i = strct->members.variables.find(memacc.member);
294 if(i!=strct->members.variables.end())
296 declaration = i->second;
298 for(auto j=strct->members.body.begin(); (j!=strct->members.body.end() && j->get()!=i->second); ++j)
302 add_to_chain(r_assignment_target, Assignment::Target::MEMBER, index);
305 else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(memacc.left->type))
307 bool scalar_swizzle = ((basic->kind==BasicTypeDeclaration::INT || basic->kind==BasicTypeDeclaration::FLOAT) && memacc.member.size()==1);
308 bool vector_swizzle = (basic->kind==BasicTypeDeclaration::VECTOR && memacc.member.size()<=4);
309 if(scalar_swizzle || vector_swizzle)
311 static const char component_names[] = { 'x', 'r', 's', 'y', 'g', 't', 'z', 'b', 'p', 'w', 'a', 'q' };
314 uint8_t components[4] = { };
315 for(unsigned i=0; (ok && i<memacc.member.size()); ++i)
316 ok = ((components[i] = (std::find(component_names, component_names+12, memacc.member[i])-component_names)/3) < 4);
320 Swizzle *swizzle = new Swizzle;
321 swizzle->source = memacc.source;
322 swizzle->line = memacc.line;
323 swizzle->oper = memacc.oper;
324 swizzle->left = memacc.left;
325 swizzle->component_group = memacc.member;
326 swizzle->count = memacc.member.size();
327 copy(components, components+memacc.member.size(), swizzle->components);
328 r_replacement_expr = swizzle;
333 r_any_resolved |= (declaration!=memacc.declaration || index!=memacc.index);
334 memacc.declaration = declaration;
335 memacc.index = index;
338 void VariableResolver::visit(Swizzle &swizzle)
340 TraversingVisitor::visit(swizzle);
345 for(unsigned i=0; i<swizzle.count; ++i)
346 mask |= 1<<swizzle.components[i];
347 add_to_chain(r_assignment_target, Assignment::Target::SWIZZLE, mask);
351 void VariableResolver::visit(BinaryExpression &binary)
353 if(binary.oper->token[0]=='[')
356 /* The subscript expression is not a part of the primary assignment
358 SetFlag set(record_target, false);
365 unsigned index = 0x3F;
366 if(Literal *literal_subscript = dynamic_cast<Literal *>(binary.right.get()))
367 if(literal_subscript->value.check_type<int>())
368 index = literal_subscript->value.value<int>();
369 add_to_chain(r_assignment_target, Assignment::Target::ARRAY, index);
373 TraversingVisitor::visit(binary);
376 void VariableResolver::visit(Assignment &assign)
379 SetFlag set(record_target);
380 r_assignment_target = Assignment::Target();
382 r_any_resolved |= (r_assignment_target<assign.target || assign.target<r_assignment_target);
383 assign.target = r_assignment_target;
386 r_self_referencing = false;
388 assign.self_referencing = (r_self_referencing || assign.oper->token[0]!='=');
391 void VariableResolver::merge_layouts(Layout &to_layout, const Layout &from_layout)
393 for(const Layout::Qualifier &q: from_layout.qualifiers)
395 auto i = find_member(to_layout.qualifiers, q.name, &Layout::Qualifier::name);
396 if(i!=to_layout.qualifiers.end())
398 i->has_value = q.value;
402 to_layout.qualifiers.push_back(q);
406 void VariableResolver::redeclare_builtin(VariableDeclaration &existing, VariableDeclaration &var)
411 merge_layouts(*existing.layout, *var.layout);
413 existing.layout = var.layout;
416 existing.array_size = var.array_size;
418 redeclared_builtins.push_back(&existing);
421 void VariableResolver::visit(VariableDeclaration &var)
423 TraversingVisitor::visit(var);
425 auto i = current_block->variables.find(var.name);
426 VariableDeclaration *existing = 0;
427 VariableDeclaration *block = 0;
428 if(i!=current_block->variables.end())
429 existing = i->second;
430 else if(!current_block->parent)
432 const map<string, VariableDeclaration *> &blocks = stage->interface_blocks;
433 for(auto j=blocks.begin(); j!=blocks.end(); ++j)
434 if(j->second->name.find(' ')!=string::npos)
436 const map<string, VariableDeclaration *> &block_vars = j->second->block_declaration->members.variables;
437 auto k = block_vars.find(var.name);
438 if(k!=block_vars.end())
440 existing = k->second;
449 current_block->variables.insert(make_pair(var.name, &var));
450 if(var.block_declaration)
452 stage->interface_blocks.insert(make_pair(format("%s %s", var.interface, var.block_declaration->block_name), &var));
453 if(var.name.find(' ')==string::npos)
454 stage->interface_blocks.insert(make_pair(var.name, &var));
457 else if(!current_block->parent && (block ? block->interface : existing->interface)==var.interface && existing->array==var.array)
459 if(existing->source==BUILTIN_SOURCE)
461 if(var.block_declaration && existing->block_declaration && var.block_declaration->block_name==existing->block_declaration->block_name)
463 const map<string, VariableDeclaration *> &vars = var.block_declaration->members.variables;
464 const map<string, VariableDeclaration *> &existing_vars = existing->block_declaration->members.variables;
466 bool found_all = true;
467 for(const auto &kvp: vars)
469 auto j = existing_vars.find(kvp.first);
470 if(j!=existing_vars.end() && j->second->type==kvp.second->type && j->second->array==kvp.second->array)
471 redeclare_builtin(*j->second, *kvp.second);
478 redeclared_builtins.push_back(existing);
479 nodes_to_remove.insert(&var);
480 // The block struct will be removed during unused type removal
481 //nodes_to_remove.insert(var.block_declaration);
484 else if(!var.block_declaration && !existing->block_declaration && var.type==existing->type)
486 redeclare_builtin(*existing, var);
490 /* Cause the block and its members to be marked as not builtin
491 so it will be emitted in output */
492 redeclared_builtins.push_back(block);
493 for(const auto &kvp: block->block_declaration->members.variables)
494 redeclared_builtins.push_back(kvp.second);
497 nodes_to_remove.insert(&var);
498 r_any_resolved = true;
501 else if(existing->array && !existing->array_size && var.type==existing->type && !var.layout && !var.init_expression)
503 existing->array_size = var.array_size;
504 nodes_to_remove.insert(&var);
505 r_any_resolved = true;
511 bool ExpressionResolver::apply(Stage &s)
514 r_any_resolved = false;
515 s.content.visit(*this);
516 return r_any_resolved;
519 ExpressionResolver::Compatibility ExpressionResolver::get_compatibility(BasicTypeDeclaration &left, BasicTypeDeclaration &right)
523 else if(can_convert(left, right))
524 return LEFT_CONVERTIBLE;
525 else if(can_convert(right, left))
526 return RIGHT_CONVERTIBLE;
528 return NOT_COMPATIBLE;
531 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration::Kind kind, unsigned size, bool sign)
533 auto i = find_if(basic_types,
534 [kind, size, sign](const BasicTypeDeclaration *t){ return t->kind==kind && t->size==size && t->sign==sign; });
535 return (i!=basic_types.end() ? *i : 0);
538 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration &elem_type, BasicTypeDeclaration::Kind kind, unsigned size)
540 auto i = find_if(basic_types,
541 [&elem_type, kind, size](BasicTypeDeclaration *t){ return get_element_type(*t)==&elem_type && t->kind==kind && t->size==size; });
542 return (i!=basic_types.end() ? *i : 0);
545 void ExpressionResolver::convert_to(RefPtr<Expression> &expr, BasicTypeDeclaration &type)
547 RefPtr<FunctionCall> call = new FunctionCall;
548 call->name = type.name;
549 call->constructor = true;
550 call->arguments.push_back_nocopy(expr);
555 bool ExpressionResolver::convert_to_element(RefPtr<Expression> &expr, BasicTypeDeclaration &elem_type)
557 if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
559 BasicTypeDeclaration *to_type = &elem_type;
560 if(is_vector_or_matrix(*expr_basic))
561 to_type = find_type(elem_type, expr_basic->kind, expr_basic->size);
564 convert_to(expr, *to_type);
572 bool ExpressionResolver::truncate_vector(RefPtr<Expression> &expr, unsigned size)
574 if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
575 if(BasicTypeDeclaration *expr_elem = get_element_type(*expr_basic))
577 RefPtr<Swizzle> swizzle = new Swizzle;
578 swizzle->left = expr;
579 swizzle->oper = &Operator::get_operator(".", Operator::POSTFIX);
580 swizzle->component_group = string("xyzw", size);
581 swizzle->count = size;
582 for(unsigned i=0; i<size; ++i)
583 swizzle->components[i] = i;
585 swizzle->type = expr_elem;
587 swizzle->type = find_type(*expr_elem, BasicTypeDeclaration::VECTOR, size);
596 void ExpressionResolver::resolve(Expression &expr, TypeDeclaration *type, bool lvalue)
598 r_any_resolved |= (type!=expr.type || lvalue!=expr.lvalue);
600 expr.lvalue = lvalue;
603 void ExpressionResolver::visit(Block &block)
605 SetForScope<Block *> set_block(current_block, &block);
606 for(auto i=block.body.begin(); i!=block.body.end(); ++i)
613 void ExpressionResolver::visit(Literal &literal)
615 if(literal.value.check_type<bool>())
616 resolve(literal, find_type(BasicTypeDeclaration::BOOL, 1), false);
617 else if(literal.value.check_type<int>())
618 resolve(literal, find_type(BasicTypeDeclaration::INT, 32, true), false);
619 else if(literal.value.check_type<unsigned>())
620 resolve(literal, find_type(BasicTypeDeclaration::INT, 32, false), false);
621 else if(literal.value.check_type<float>())
622 resolve(literal, find_type(BasicTypeDeclaration::FLOAT, 32), false);
625 void ExpressionResolver::visit(VariableReference &var)
628 resolve(var, var.declaration->type_declaration, true);
631 void ExpressionResolver::visit(MemberAccess &memacc)
633 TraversingVisitor::visit(memacc);
635 if(memacc.declaration)
636 resolve(memacc, memacc.declaration->type_declaration, memacc.left->lvalue);
639 void ExpressionResolver::visit(Swizzle &swizzle)
641 TraversingVisitor::visit(swizzle);
643 if(BasicTypeDeclaration *left_basic = dynamic_cast<BasicTypeDeclaration *>(swizzle.left->type))
645 BasicTypeDeclaration *left_elem = get_element_type(*left_basic);
647 resolve(swizzle, left_elem, swizzle.left->lvalue);
648 else if(left_basic->kind==BasicTypeDeclaration::VECTOR && left_elem)
649 resolve(swizzle, find_type(*left_elem, left_basic->kind, swizzle.count), swizzle.left->lvalue);
653 void ExpressionResolver::visit(UnaryExpression &unary)
655 TraversingVisitor::visit(unary);
657 BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(unary.expression->type);
661 char oper = unary.oper->token[0];
664 if(basic->kind!=BasicTypeDeclaration::BOOL)
669 if(basic->kind!=BasicTypeDeclaration::INT)
672 else if(oper=='+' || oper=='-')
674 BasicTypeDeclaration *elem = get_element_type(*basic);
675 if(!elem || !is_scalar(*elem))
678 resolve(unary, basic, unary.expression->lvalue);
681 void ExpressionResolver::visit(BinaryExpression &binary, bool assign)
683 /* Binary operators are only defined for basic types (not for image or
685 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(binary.left->type);
686 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(binary.right->type);
687 if(!basic_left || !basic_right)
690 char oper = binary.oper->token[0];
693 /* Subscripting operates on vectors, matrices and arrays, and the right
694 operand must be an integer. */
695 if((!is_vector_or_matrix(*basic_left) && basic_left->kind!=BasicTypeDeclaration::ARRAY) || basic_right->kind!=BasicTypeDeclaration::INT)
698 resolve(binary, basic_left->base_type, binary.left->lvalue);
701 else if(basic_left->kind==BasicTypeDeclaration::ARRAY || basic_right->kind==BasicTypeDeclaration::ARRAY)
702 // No other binary operator can be used with arrays.
705 BasicTypeDeclaration *elem_left = get_element_type(*basic_left);
706 BasicTypeDeclaration *elem_right = get_element_type(*basic_right);
707 if(!elem_left || !elem_right)
710 Compatibility compat = get_compatibility(*basic_left, *basic_right);
711 Compatibility elem_compat = get_compatibility(*elem_left, *elem_right);
712 if(elem_compat==NOT_COMPATIBLE)
714 if(assign && (compat==LEFT_CONVERTIBLE || elem_compat==LEFT_CONVERTIBLE))
717 TypeDeclaration *type = 0;
718 char oper2 = binary.oper->token[1];
719 if((oper=='<' && oper2!='<') || (oper=='>' && oper2!='>'))
721 /* Relational operators compare two scalar integer or floating-point
723 if(!is_scalar(*elem_left) || !is_scalar(*elem_right) || compat==NOT_COMPATIBLE)
726 type = find_type(BasicTypeDeclaration::BOOL, 1);
728 else if((oper=='=' || oper=='!') && oper2=='=')
730 // Equality comparison can be done on any compatible types.
731 if(compat==NOT_COMPATIBLE)
734 type = find_type(BasicTypeDeclaration::BOOL, 1);
736 else if(oper2=='&' || oper2=='|' || oper2=='^')
738 // Logical operators can only be applied to booleans.
739 if(basic_left->kind!=BasicTypeDeclaration::BOOL || basic_right->kind!=BasicTypeDeclaration::BOOL)
744 else if((oper=='&' || oper=='|' || oper=='^' || oper=='%') && !oper2)
746 // Bitwise operators and modulo can only be applied to integers.
747 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
750 type = (compat==LEFT_CONVERTIBLE ? basic_right : basic_left);
752 else if((oper=='<' || oper=='>') && oper2==oper)
754 // Shifts apply to integer scalars and vectors, with some restrictions.
755 if(elem_left->kind!=BasicTypeDeclaration::INT || elem_right->kind!=BasicTypeDeclaration::INT)
757 unsigned left_size = (basic_left->kind==BasicTypeDeclaration::INT ? 1 : basic_left->kind==BasicTypeDeclaration::VECTOR ? basic_left->size : 0);
758 unsigned right_size = (basic_right->kind==BasicTypeDeclaration::INT ? 1 : basic_right->kind==BasicTypeDeclaration::VECTOR ? basic_right->size : 0);
759 if(!left_size || (left_size==1 && right_size!=1) || (left_size>1 && right_size!=1 && right_size!=left_size))
762 /* If the left operand is a vector and right is scalar, convert the right
763 operand to a vector too. */
764 if(left_size>1 && right_size==1)
766 BasicTypeDeclaration *vec_right = find_type(*elem_right, basic_left->kind, basic_left->size);
770 convert_to(binary.right, *vec_right);
774 // Don't perform conversion even if the operands are of different sizes.
777 else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
779 // Arithmetic operators require scalar elements.
780 if(!is_scalar(*elem_left) || !is_scalar(*elem_right))
783 if(oper=='*' && is_vector_or_matrix(*basic_left) && is_vector_or_matrix(*basic_right) &&
784 (basic_left->kind==BasicTypeDeclaration::MATRIX || basic_right->kind==BasicTypeDeclaration::MATRIX))
786 /* Multiplication has special rules when at least one operand is a
787 matrix and the other is a vector or a matrix. */
788 unsigned left_columns = basic_left->size&0xFFFF;
789 unsigned right_rows = basic_right->size;
790 if(basic_right->kind==BasicTypeDeclaration::MATRIX)
792 if(left_columns!=right_rows)
795 BasicTypeDeclaration *elem_result = (elem_compat==LEFT_CONVERTIBLE ? elem_right : elem_left);
797 if(basic_left->kind==BasicTypeDeclaration::VECTOR)
798 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_right->size&0xFFFF);
799 else if(basic_right->kind==BasicTypeDeclaration::VECTOR)
800 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_left->size>>16);
802 type = find_type(*elem_result, BasicTypeDeclaration::MATRIX, (basic_left->size&0xFFFF0000)|(basic_right->size&0xFFFF));
804 else if(compat==NOT_COMPATIBLE)
806 // Arithmetic between scalars and matrices or vectors is supported.
807 if(is_scalar(*basic_left) && is_vector_or_matrix(*basic_right))
808 type = (elem_compat==RIGHT_CONVERTIBLE ? find_type(*elem_left, basic_right->kind, basic_right->size) : basic_right);
809 else if(is_vector_or_matrix(*basic_left) && is_scalar(*basic_right))
810 type = (elem_compat==LEFT_CONVERTIBLE ? find_type(*elem_right, basic_left->kind, basic_left->size) : basic_left);
814 else if(compat==LEFT_CONVERTIBLE)
822 if(assign && type!=basic_left)
825 bool converted = true;
826 if(compat==LEFT_CONVERTIBLE)
827 convert_to(binary.left, *basic_right);
828 else if(compat==RIGHT_CONVERTIBLE)
829 convert_to(binary.right, *basic_left);
830 else if(elem_compat==LEFT_CONVERTIBLE)
831 converted = convert_to_element(binary.left, *elem_right);
832 else if(elem_compat==RIGHT_CONVERTIBLE)
833 converted = convert_to_element(binary.right, *elem_left);
838 resolve(binary, type, assign);
841 void ExpressionResolver::visit(BinaryExpression &binary)
843 TraversingVisitor::visit(binary);
844 visit(binary, false);
847 void ExpressionResolver::visit(Assignment &assign)
849 TraversingVisitor::visit(assign);
851 if(assign.oper->token[0]!='=')
852 return visit(assign, true);
853 else if(assign.left->type!=assign.right->type)
855 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(assign.left->type);
856 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(assign.right->type);
857 if(!basic_left || !basic_right)
860 Compatibility compat = get_compatibility(*basic_left, *basic_right);
861 if(compat==RIGHT_CONVERTIBLE)
862 convert_to(assign.right, *basic_left);
863 else if(compat!=SAME_TYPE)
867 resolve(assign, assign.left->type, true);
870 void ExpressionResolver::visit(TernaryExpression &ternary)
872 TraversingVisitor::visit(ternary);
874 BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(ternary.condition->type);
875 if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
878 TypeDeclaration *type = 0;
879 if(ternary.true_expr->type==ternary.false_expr->type)
880 type = ternary.true_expr->type;
883 BasicTypeDeclaration *basic_true = dynamic_cast<BasicTypeDeclaration *>(ternary.true_expr->type);
884 BasicTypeDeclaration *basic_false = dynamic_cast<BasicTypeDeclaration *>(ternary.false_expr->type);
885 if(!basic_true || !basic_false)
888 Compatibility compat = get_compatibility(*basic_true, *basic_false);
889 if(compat==NOT_COMPATIBLE)
892 type = (compat==LEFT_CONVERTIBLE ? basic_true : basic_false);
894 if(compat==LEFT_CONVERTIBLE)
895 convert_to(ternary.true_expr, *basic_false);
896 else if(compat==RIGHT_CONVERTIBLE)
897 convert_to(ternary.false_expr, *basic_true);
900 resolve(ternary, type, false);
903 void ExpressionResolver::visit_constructor(FunctionCall &call)
905 if(call.arguments.empty())
908 auto i = stage->types.find(call.name);
909 if(i==stage->types.end())
911 else if(call.arguments.size()==1 && i->second==call.arguments[0]->type)
913 else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(i->second))
915 BasicTypeDeclaration *elem = get_element_type(*basic);
919 vector<ArgumentInfo> args;
920 args.reserve(call.arguments.size());
921 unsigned arg_component_total = 0;
922 bool has_matrices = false;
923 for(const RefPtr<Expression> &a: call.arguments)
926 if(!(info.type=dynamic_cast<BasicTypeDeclaration *>(a->type)))
928 if(is_scalar(*info.type) || info.type->kind==BasicTypeDeclaration::BOOL)
929 info.component_count = 1;
930 else if(info.type->kind==BasicTypeDeclaration::VECTOR)
931 info.component_count = info.type->size;
932 else if(info.type->kind==BasicTypeDeclaration::MATRIX)
934 info.component_count = (info.type->size>>16)*(info.type->size&0xFFFF);
939 arg_component_total += info.component_count;
940 args.push_back(info);
943 bool convert_args = false;
944 if((is_scalar(*basic) || basic->kind==BasicTypeDeclaration::BOOL) && call.arguments.size()==1 && !has_matrices)
946 if(arg_component_total>1)
947 truncate_vector(call.arguments.front(), 1);
949 /* Single-element type constructors never need to convert their
950 arguments because the constructor *is* the conversion. */
952 else if(basic->kind==BasicTypeDeclaration::VECTOR && !has_matrices)
954 /* Vector constructors need either a single scalar argument or
955 enough components to fill out the vector. */
956 if(arg_component_total!=1 && arg_component_total<basic->size)
959 /* A vector of same size can be converted directly. For other
960 combinations the individual arguments need to be converted. */
961 if(call.arguments.size()==1)
963 if(arg_component_total==1)
965 else if(arg_component_total>basic->size)
966 truncate_vector(call.arguments.front(), basic->size);
968 else if(arg_component_total==basic->size)
973 else if(basic->kind==BasicTypeDeclaration::MATRIX)
975 unsigned column_count = basic->size&0xFFFF;
976 unsigned row_count = basic->size>>16;
978 vector<RefPtr<Expression> > columns;
979 columns.reserve(column_count);
980 bool changed_columns = false;
982 if(call.arguments.size()==1)
984 /* A matrix can be constructed from a single element or another
985 matrix of sufficient size. */
986 if(arg_component_total==1)
988 else if(args.front().type->kind==BasicTypeDeclaration::MATRIX)
990 unsigned arg_columns = args.front().type->size&0xFFFF;
991 unsigned arg_rows = args.front().type->size>>16;
992 if(arg_columns<column_count || arg_rows<row_count)
995 /* Always generate a temporary here and let the optimization
996 stage inline it if that's reasonable. */
997 RefPtr<VariableDeclaration> temporary = new VariableDeclaration;
998 temporary->type = args.front().type->name;
999 temporary->name = get_unused_variable_name(*current_block, "_temp");
1000 temporary->init_expression = call.arguments.front();
1001 current_block->body.insert(insert_point, temporary);
1003 // Create expressions to build each column.
1004 for(unsigned j=0; j<column_count; ++j)
1006 RefPtr<VariableReference> ref = new VariableReference;
1007 ref->name = temporary->name;
1009 RefPtr<Literal> index = new Literal;
1010 index->token = lexical_cast<string>(j);
1011 index->value = static_cast<int>(j);
1013 RefPtr<BinaryExpression> subscript = new BinaryExpression;
1014 subscript->left = ref;
1015 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
1016 subscript->right = index;
1017 subscript->type = args.front().type->base_type;
1019 columns.push_back(subscript);
1020 if(arg_rows>row_count)
1021 truncate_vector(columns.back(), row_count);
1024 changed_columns = true;
1029 else if(arg_component_total==column_count*row_count && !has_matrices)
1031 /* Construct a matrix from individual components in column-major
1032 order. Arguments must align at column boundaries. */
1033 vector<RefPtr<Expression> > column_args;
1034 column_args.reserve(row_count);
1035 unsigned column_component_count = 0;
1037 for(unsigned j=0; j<call.arguments.size(); ++j)
1039 const ArgumentInfo &info = args[j];
1040 if(!column_component_count && info.type->kind==BasicTypeDeclaration::VECTOR && info.component_count==row_count)
1041 // A vector filling the entire column can be used as is.
1042 columns.push_back(call.arguments[j]);
1045 column_args.push_back(call.arguments[j]);
1046 column_component_count += info.component_count;
1047 if(column_component_count==row_count)
1049 /* The column has filled up. Create a vector constructor
1051 RefPtr<FunctionCall> column_call = new FunctionCall;
1052 column_call->name = basic->base_type->name;
1053 column_call->constructor = true;
1054 column_call->arguments.resize(column_args.size());
1055 copy(column_args.begin(), column_args.end(), column_call->arguments.begin());
1056 column_call->type = basic->base_type;
1057 visit_constructor(*column_call);
1058 columns.push_back(column_call);
1060 column_args.clear();
1061 column_component_count = 0;
1063 else if(column_component_count>row_count)
1064 // Argument alignment mismatch.
1067 changed_columns = true;
1076 call.arguments.resize(column_count);
1077 copy(columns.begin(), columns.end(), call.arguments.begin());
1079 /* Let VariableResolver process the new nodes and finish
1080 resolving the constructor on the next pass. */
1081 r_any_resolved = true;
1090 // The argument list may have changed so can't rely on args.
1091 for(RefPtr<Expression> &a: call.arguments)
1092 if(BasicTypeDeclaration *basic_arg = dynamic_cast<BasicTypeDeclaration *>(a->type))
1094 BasicTypeDeclaration *elem_arg = get_element_type(*basic_arg);
1096 convert_to_element(a, *elem);
1100 else if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(i->second))
1102 if(call.arguments.size()!=strct->members.body.size())
1105 auto j = call.arguments.begin();
1106 for(const RefPtr<Statement> &s: strct->members.body)
1108 if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(s.get()))
1110 if(!(*j)->type || (*j)->type!=var->type_declaration)
1119 resolve(call, i->second, false);
1122 void ExpressionResolver::visit(FunctionCall &call)
1124 TraversingVisitor::visit(call);
1126 if(call.declaration)
1128 for(unsigned i=0; i<call.arguments.size(); ++i)
1130 TypeDeclaration *arg_type = call.arguments[i]->type;
1131 TypeDeclaration *param_type = call.declaration->parameters[i]->type_declaration;
1132 if(arg_type==param_type)
1134 else if(!arg_type || !param_type)
1137 BasicTypeDeclaration *arg_basic = dynamic_cast<BasicTypeDeclaration *>(arg_type);
1138 BasicTypeDeclaration *param_basic = dynamic_cast<BasicTypeDeclaration *>(param_type);
1139 if(arg_basic && param_basic)
1141 Compatibility compat = get_compatibility(*param_basic, *arg_basic);
1142 if(compat==RIGHT_CONVERTIBLE)
1143 convert_to(call.arguments[i], *param_basic);
1144 else if(compat!=SAME_TYPE)
1149 ImageTypeDeclaration *arg_image = dynamic_cast<ImageTypeDeclaration *>(arg_type);
1150 ImageTypeDeclaration *param_image = dynamic_cast<ImageTypeDeclaration *>(param_type);
1151 if(!arg_image || !param_image || arg_image->base_image!=param_image)
1155 resolve(call, call.declaration->return_type_declaration, false);
1157 else if(call.constructor)
1158 visit_constructor(call);
1161 void ExpressionResolver::visit(BasicTypeDeclaration &type)
1163 basic_types.push_back(&type);
1166 void ExpressionResolver::visit(VariableDeclaration &var)
1168 TraversingVisitor::visit(var);
1169 if(!var.init_expression)
1172 BasicTypeDeclaration *var_basic = dynamic_cast<BasicTypeDeclaration *>(var.type_declaration);
1173 BasicTypeDeclaration *init_basic = dynamic_cast<BasicTypeDeclaration *>(var.init_expression->type);
1174 if(!var_basic || !init_basic)
1177 Compatibility compat = get_compatibility(*var_basic, *init_basic);
1178 if(compat==RIGHT_CONVERTIBLE)
1179 convert_to(var.init_expression, *var_basic);
1182 void ExpressionResolver::visit(FunctionDeclaration &func)
1184 SetForScope<const FunctionDeclaration *> set_func(current_function, &func);
1185 TraversingVisitor::visit(func);
1188 void ExpressionResolver::visit(Return &ret)
1190 TraversingVisitor::visit(ret);
1191 if(!current_function || !ret.expression)
1194 BasicTypeDeclaration *ret_basic = dynamic_cast<BasicTypeDeclaration *>(current_function->return_type_declaration);
1195 BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(ret.expression->type);
1196 if(!ret_basic || !expr_basic)
1199 Compatibility compat = get_compatibility(*ret_basic, *expr_basic);
1200 if(compat==RIGHT_CONVERTIBLE)
1201 convert_to(ret.expression, *ret_basic);
1205 bool FunctionResolver::apply(Stage &s)
1208 s.functions.clear();
1209 r_any_resolved = false;
1210 s.content.visit(*this);
1211 return r_any_resolved;
1214 bool FunctionResolver::can_convert_arguments(const FunctionCall &call, const FunctionDeclaration &decl)
1216 if(decl.parameters.size()!=call.arguments.size())
1219 for(unsigned j=0; j<call.arguments.size(); ++j)
1221 const TypeDeclaration *arg_type = call.arguments[j]->type;
1222 const TypeDeclaration *param_type = decl.parameters[j]->type_declaration;
1223 if(arg_type==param_type)
1226 const BasicTypeDeclaration *arg_basic = dynamic_cast<const BasicTypeDeclaration *>(arg_type);
1227 const BasicTypeDeclaration *param_basic = dynamic_cast<const BasicTypeDeclaration *>(param_type);
1228 if(arg_basic && param_basic && can_convert(*arg_basic, *param_basic))
1237 void FunctionResolver::visit(FunctionCall &call)
1239 FunctionDeclaration *declaration = 0;
1240 if(stage->types.count(call.name))
1241 call.constructor = true;
1245 bool has_signature = true;
1246 for(auto i=call.arguments.begin(); (has_signature && i!=call.arguments.end()); ++i)
1248 if(const TypeDeclaration *type = (*i)->type)
1250 if(const ImageTypeDeclaration *image = dynamic_cast<const ImageTypeDeclaration *>(type))
1251 if(image->base_image)
1252 type = image->base_image;
1253 append(arg_types, ",", type->name);
1256 has_signature = false;
1261 auto i = stage->functions.find(format("%s(%s)", call.name, arg_types));
1262 declaration = (i!=stage->functions.end() ? i->second : 0);
1266 for(i=stage->functions.lower_bound(call.name+"("); (i!=stage->functions.end() && i->second->name==call.name); ++i)
1267 if(can_convert_arguments(call, *i->second))
1275 declaration = i->second;
1281 r_any_resolved |= (declaration!=call.declaration);
1282 call.declaration = declaration;
1284 TraversingVisitor::visit(call);
1287 void FunctionResolver::visit(FunctionDeclaration &func)
1289 if(func.signature.empty())
1292 for(const RefPtr<VariableDeclaration> &p: func.parameters)
1294 if(p->type_declaration)
1295 append(param_types, ",", p->type_declaration->name);
1299 func.signature = format("(%s)", param_types);
1300 r_any_resolved = true;
1303 string key = func.name+func.signature;
1304 FunctionDeclaration *&stage_decl = stage->functions[key];
1305 vector<FunctionDeclaration *> &decls = declarations[key];
1306 if(func.definition==&func)
1308 if(stage_decl && stage_decl->definition)
1311 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1312 format("Overriding function '%s' without the override keyword is deprecated", key)));
1313 if(!stage_decl->definition->virtua)
1314 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1315 format("Overriding function '%s' not declared as virtual is deprecated", key)));
1319 // Set all previous declarations to use this definition.
1320 for(FunctionDeclaration *f: decls)
1322 r_any_resolved |= (func.definition!=f->definition);
1323 f->definition = func.definition;
1324 f->body.body.clear();
1329 FunctionDeclaration *definition = (stage_decl ? stage_decl->definition : 0);
1330 r_any_resolved |= (definition!=func.definition);
1331 func.definition = definition;
1336 decls.push_back(&func);
1338 TraversingVisitor::visit(func);