1 #include <msp/core/algorithm.h>
2 #include <msp/core/raii.h>
3 #include <msp/strings/utils.h>
13 void BlockHierarchyResolver::enter(Block &block)
15 r_any_resolved |= (current_block!=block.parent);
16 block.parent = current_block;
20 bool TypeResolver::apply(Stage &s)
24 r_any_resolved = false;
25 s.content.visit(*this);
26 return r_any_resolved;
29 TypeDeclaration *TypeResolver::get_or_create_array_type(TypeDeclaration &type)
31 bool extended_alignment = iface_block;
32 auto key = make_pair(&type, extended_alignment);
33 auto i = array_types.find(key);
34 if(i!=array_types.end())
37 BasicTypeDeclaration *array = new BasicTypeDeclaration;
38 array->source = INTERNAL_SOURCE;
39 array->name = type.name+"[]";
40 array->kind = BasicTypeDeclaration::ARRAY;
41 array->extended_alignment = extended_alignment;
42 array->base = type.name;
43 array->base_type = &type;
44 stage->content.body.insert(type_insert_point, array);
45 array_types[key] = array;
49 void TypeResolver::resolve_type(TypeDeclaration *&type, const string &name, bool array)
51 TypeDeclaration *resolved = 0;
52 auto i = stage->types.find(name);
53 if(i!=stage->types.end())
55 auto j = alias_map.find(i->second);
56 resolved = (j!=alias_map.end() ? j->second : i->second);
60 resolved = get_or_create_array_type(*resolved);
62 r_any_resolved |= (resolved!=type);
66 void TypeResolver::visit(Block &block)
68 for(auto i=block.body.begin(); i!=block.body.end(); ++i)
71 type_insert_point = i;
76 void TypeResolver::visit(BasicTypeDeclaration &type)
78 resolve_type(type.base_type, type.base, false);
80 if(type.kind==BasicTypeDeclaration::VECTOR && type.base_type)
81 if(BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type))
82 if(basic_base->kind==BasicTypeDeclaration::VECTOR)
84 type.kind = BasicTypeDeclaration::MATRIX;
85 /* A matrix's base type is its column vector type. This will put
86 the column vector's size, i.e. the matrix's row count, in the high
88 type.size |= basic_base->size<<16;
91 if(type.kind==BasicTypeDeclaration::ALIAS && type.base_type)
92 alias_map[&type] = type.base_type;
93 else if(type.kind==BasicTypeDeclaration::ARRAY && type.base_type)
94 array_types[make_pair(type.base_type, type.extended_alignment)] = &type;
96 stage->types.insert(make_pair(type.name, &type));
99 void TypeResolver::visit(ImageTypeDeclaration &type)
101 resolve_type(type.base_type, type.base, false);
102 stage->types.insert(make_pair(type.name, &type));
105 void TypeResolver::visit(StructDeclaration &strct)
107 stage->types.insert(make_pair(strct.name, &strct));
108 SetForScope<InterfaceBlock *> set_iface(iface_block, strct.interface_block);
109 TraversingVisitor::visit(strct);
112 void TypeResolver::visit(VariableDeclaration &var)
114 resolve_type(var.type_declaration, var.type, var.array);
117 if(var.interface==iface_block->interface)
118 var.interface.clear();
119 if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(var.type_declaration))
120 strct->extended_alignment = true;
124 void TypeResolver::visit(InterfaceBlock &iface)
128 SetForScope<InterfaceBlock *> set_iface(iface_block, &iface);
129 iface.members->visit(*this);
131 StructDeclaration *strct = new StructDeclaration;
132 strct->source = INTERNAL_SOURCE;
133 strct->name = format("_%s_%s", iface.interface, iface.block_name);
134 strct->members.body.splice(strct->members.body.begin(), iface.members->body);
135 strct->extended_alignment = true;
136 stage->content.body.insert(type_insert_point, strct);
137 stage->types.insert(make_pair(strct->name, strct));
140 strct->interface_block = &iface;
141 iface.struct_declaration = strct;
144 TypeDeclaration *type = iface.struct_declaration;
145 if(type && iface.array)
146 type = get_or_create_array_type(*type);
147 r_any_resolved = (type!=iface.type_declaration);
148 iface.type_declaration = type;
151 void TypeResolver::visit(FunctionDeclaration &func)
153 resolve_type(func.return_type_declaration, func.return_type, false);
154 TraversingVisitor::visit(func);
158 bool VariableResolver::apply(Stage &s)
161 s.interface_blocks.clear();
162 r_any_resolved = false;
163 s.content.visit(*this);
164 for(Statement *b: redeclared_builtins)
165 b->source = GENERATED_SOURCE;
166 NodeRemover().apply(s, nodes_to_remove);
167 return r_any_resolved;
170 void VariableResolver::enter(Block &block)
172 block.variables.clear();
175 void VariableResolver::visit(RefPtr<Expression> &expr)
177 r_replacement_expr = 0;
179 if(r_replacement_expr)
181 expr = r_replacement_expr;
182 /* Don't record assignment target when doing a replacement, because chain
183 information won't be correct. */
184 r_assignment_target.declaration = 0;
185 r_any_resolved = true;
187 r_replacement_expr = 0;
190 void VariableResolver::check_assignment_target(Statement *declaration)
194 if(r_assignment_target.declaration)
196 /* More than one reference found in assignment target. Unable to
197 determine what the primary target is. */
198 record_target = false;
199 r_assignment_target.declaration = 0;
202 r_assignment_target.declaration = declaration;
204 // TODO This check is overly broad and may prevent some optimizations.
205 else if(declaration && declaration==r_assignment_target.declaration)
206 r_self_referencing = true;
209 void VariableResolver::visit(VariableReference &var)
211 VariableDeclaration *declaration = 0;
213 /* Look for variable declarations in the block hierarchy first. Interface
214 blocks are always defined in the top level so we can't accidentally skip
216 for(Block *block=current_block; (!declaration && block); block=block->parent)
218 auto i = block->variables.find(var.name);
219 if(i!=block->variables.end())
220 declaration = i->second;
225 const map<string, InterfaceBlock *> &blocks = stage->interface_blocks;
226 auto i = blocks.find(var.name);
229 // Look for the variable in anonymous interface blocks.
230 for(i=blocks.begin(); i!=blocks.end(); ++i)
231 if(i->second->instance_name.empty() && i->second->struct_declaration)
232 if(i->second->struct_declaration->members.variables.count(var.name))
238 /* The name refers to either an interface block with an instance name
239 or a variable declared inside an anonymous interface block. Prepare
240 new syntax tree nodes accordingly. */
241 InterfaceBlockReference *iface_ref = new InterfaceBlockReference;
242 iface_ref->source = var.source;
243 iface_ref->line = var.line;
244 iface_ref->declaration = i->second;
246 if(i->second->instance_name.empty())
248 iface_ref->name = format("%s %s", i->second->interface, i->second->block_name);
250 MemberAccess *memacc = new MemberAccess;
251 memacc->source = var.source;
252 memacc->line = var.line;
253 memacc->left = iface_ref;
254 memacc->member = var.name;
256 r_replacement_expr = memacc;
260 iface_ref->name = var.name;
261 r_replacement_expr = iface_ref;
266 r_any_resolved |= (declaration!=var.declaration);
267 var.declaration = declaration;
269 check_assignment_target(var.declaration);
272 void VariableResolver::visit(InterfaceBlockReference &iface)
274 auto i = stage->interface_blocks.find(iface.name);
275 InterfaceBlock *declaration = (i!=stage->interface_blocks.end() ? i->second : 0);
276 r_any_resolved |= (declaration!=iface.declaration);
277 iface.declaration = declaration;
279 check_assignment_target(iface.declaration);
282 void VariableResolver::visit(MemberAccess &memacc)
284 TraversingVisitor::visit(memacc);
286 VariableDeclaration *declaration = 0;
288 if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(memacc.left->type))
290 auto i = strct->members.variables.find(memacc.member);
291 if(i!=strct->members.variables.end())
293 declaration = i->second;
295 for(auto j=strct->members.body.begin(); (j!=strct->members.body.end() && j->get()!=i->second); ++j)
299 add_to_chain(r_assignment_target, Assignment::Target::MEMBER, index);
302 else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(memacc.left->type))
304 bool scalar_swizzle = ((basic->kind==BasicTypeDeclaration::INT || basic->kind==BasicTypeDeclaration::FLOAT) && memacc.member.size()==1);
305 bool vector_swizzle = (basic->kind==BasicTypeDeclaration::VECTOR && memacc.member.size()<=4);
306 if(scalar_swizzle || vector_swizzle)
308 static const char component_names[] = { 'x', 'r', 's', 'y', 'g', 't', 'z', 'b', 'p', 'w', 'a', 'q' };
311 uint8_t components[4] = { };
312 for(unsigned i=0; (ok && i<memacc.member.size()); ++i)
313 ok = ((components[i] = (std::find(component_names, component_names+12, memacc.member[i])-component_names)/3) < 4);
317 Swizzle *swizzle = new Swizzle;
318 swizzle->source = memacc.source;
319 swizzle->line = memacc.line;
320 swizzle->oper = memacc.oper;
321 swizzle->left = memacc.left;
322 swizzle->component_group = memacc.member;
323 swizzle->count = memacc.member.size();
324 copy(components, components+memacc.member.size(), swizzle->components);
325 r_replacement_expr = swizzle;
330 r_any_resolved |= (declaration!=memacc.declaration || index!=memacc.index);
331 memacc.declaration = declaration;
332 memacc.index = index;
335 void VariableResolver::visit(Swizzle &swizzle)
337 TraversingVisitor::visit(swizzle);
342 for(unsigned i=0; i<swizzle.count; ++i)
343 mask |= 1<<swizzle.components[i];
344 add_to_chain(r_assignment_target, Assignment::Target::SWIZZLE, mask);
348 void VariableResolver::visit(BinaryExpression &binary)
350 if(binary.oper->token[0]=='[')
353 /* The subscript expression is not a part of the primary assignment
355 SetFlag set(record_target, false);
362 unsigned index = 0x3F;
363 if(Literal *literal_subscript = dynamic_cast<Literal *>(binary.right.get()))
364 if(literal_subscript->value.check_type<int>())
365 index = literal_subscript->value.value<int>();
366 add_to_chain(r_assignment_target, Assignment::Target::ARRAY, index);
370 TraversingVisitor::visit(binary);
373 void VariableResolver::visit(Assignment &assign)
376 SetFlag set(record_target);
377 r_assignment_target = Assignment::Target();
379 r_any_resolved |= (r_assignment_target<assign.target || assign.target<r_assignment_target);
380 assign.target = r_assignment_target;
383 r_self_referencing = false;
385 assign.self_referencing = (r_self_referencing || assign.oper->token[0]!='=');
388 void VariableResolver::merge_layouts(Layout &to_layout, const Layout &from_layout)
390 for(const Layout::Qualifier &q: from_layout.qualifiers)
392 auto i = find_member(to_layout.qualifiers, q.name, &Layout::Qualifier::name);
393 if(i!=to_layout.qualifiers.end())
395 i->has_value = q.value;
399 to_layout.qualifiers.push_back(q);
403 void VariableResolver::redeclare_builtin(VariableDeclaration &existing, VariableDeclaration &var)
408 merge_layouts(*existing.layout, *var.layout);
410 existing.layout = var.layout;
413 existing.array_size = var.array_size;
415 redeclared_builtins.push_back(&existing);
418 void VariableResolver::visit(VariableDeclaration &var)
420 TraversingVisitor::visit(var);
422 auto i = current_block->variables.find(var.name);
423 VariableDeclaration *existing = 0;
424 InterfaceBlock *block = 0;
425 if(i!=current_block->variables.end())
426 existing = i->second;
427 else if(!current_block->parent)
429 const map<string, InterfaceBlock *> &blocks = stage->interface_blocks;
430 for(auto j=blocks.begin(); j!=blocks.end(); ++j)
431 if(j->second->instance_name.empty() && j->second->struct_declaration)
433 map<string, VariableDeclaration *> &block_vars = j->second->struct_declaration->members.variables;
434 i = block_vars.find(var.name);
435 if(i!=block_vars.end())
437 existing = i->second;
445 current_block->variables.insert(make_pair(var.name, &var));
446 else if(!current_block->parent && (block ? block->interface : existing->interface)==var.interface && existing->type==var.type && existing->array==var.array)
448 if(existing->source==BUILTIN_SOURCE)
450 redeclare_builtin(*existing, var);
454 redeclared_builtins.push_back(block);
455 for(const auto &kvp: block->struct_declaration->members.variables)
456 redeclared_builtins.push_back(kvp.second);
459 nodes_to_remove.insert(&var);
460 r_any_resolved = true;
462 else if(existing->array && !existing->array_size && !var.layout && !var.init_expression)
464 existing->array_size = var.array_size;
465 nodes_to_remove.insert(&var);
466 r_any_resolved = true;
471 void VariableResolver::visit(InterfaceBlock &iface)
473 string key = format("%s %s", iface.interface, iface.block_name);
474 auto i = stage->interface_blocks.find(key);
475 if(i!=stage->interface_blocks.end())
477 if(i->second->source==BUILTIN_SOURCE && iface.struct_declaration && i->second->struct_declaration)
479 const map<string, VariableDeclaration *> &vars = iface.struct_declaration->members.variables;
480 const map<string, VariableDeclaration *> &existing_vars = i->second->struct_declaration->members.variables;
482 bool found_all = true;
483 for(const auto &kvp: vars)
485 auto j = existing_vars.find(kvp.first);
486 if(j!=existing_vars.end() && j->second->type==kvp.second->type && j->second->array==kvp.second->array)
487 redeclare_builtin(*j->second, *kvp.second);
494 redeclared_builtins.push_back(i->second);
495 nodes_to_remove.insert(&iface);
496 nodes_to_remove.insert(iface.struct_declaration);
502 /* Block names can be reused in different interfaces. Prepend the interface
503 to the name to avoid conflicts. */
504 stage->interface_blocks.insert(make_pair(key, &iface));
505 if(!iface.instance_name.empty())
506 stage->interface_blocks.insert(make_pair(iface.instance_name, &iface));
509 TraversingVisitor::visit(iface);
513 bool ExpressionResolver::apply(Stage &s)
516 r_any_resolved = false;
517 s.content.visit(*this);
518 return r_any_resolved;
521 ExpressionResolver::Compatibility ExpressionResolver::get_compatibility(BasicTypeDeclaration &left, BasicTypeDeclaration &right)
525 else if(can_convert(left, right))
526 return LEFT_CONVERTIBLE;
527 else if(can_convert(right, left))
528 return RIGHT_CONVERTIBLE;
530 return NOT_COMPATIBLE;
533 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration::Kind kind, unsigned size, bool sign)
535 auto i = find_if(basic_types,
536 [kind, size, sign](const BasicTypeDeclaration *t){ return t->kind==kind && t->size==size && t->sign==sign; });
537 return (i!=basic_types.end() ? *i : 0);
540 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration &elem_type, BasicTypeDeclaration::Kind kind, unsigned size)
542 auto i = find_if(basic_types,
543 [&elem_type, kind, size](BasicTypeDeclaration *t){ return get_element_type(*t)==&elem_type && t->kind==kind && t->size==size; });
544 return (i!=basic_types.end() ? *i : 0);
547 void ExpressionResolver::convert_to(RefPtr<Expression> &expr, BasicTypeDeclaration &type)
549 RefPtr<FunctionCall> call = new FunctionCall;
550 call->name = type.name;
551 call->constructor = true;
552 call->arguments.push_back_nocopy(expr);
557 bool ExpressionResolver::convert_to_element(RefPtr<Expression> &expr, BasicTypeDeclaration &elem_type)
559 if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
561 BasicTypeDeclaration *to_type = &elem_type;
562 if(is_vector_or_matrix(*expr_basic))
563 to_type = find_type(elem_type, expr_basic->kind, expr_basic->size);
566 convert_to(expr, *to_type);
574 bool ExpressionResolver::truncate_vector(RefPtr<Expression> &expr, unsigned size)
576 if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
577 if(BasicTypeDeclaration *expr_elem = get_element_type(*expr_basic))
579 RefPtr<Swizzle> swizzle = new Swizzle;
580 swizzle->left = expr;
581 swizzle->oper = &Operator::get_operator(".", Operator::POSTFIX);
582 swizzle->component_group = string("xyzw", size);
583 swizzle->count = size;
584 for(unsigned i=0; i<size; ++i)
585 swizzle->components[i] = i;
587 swizzle->type = expr_elem;
589 swizzle->type = find_type(*expr_elem, BasicTypeDeclaration::VECTOR, size);
598 void ExpressionResolver::resolve(Expression &expr, TypeDeclaration *type, bool lvalue)
600 r_any_resolved |= (type!=expr.type || lvalue!=expr.lvalue);
602 expr.lvalue = lvalue;
605 void ExpressionResolver::visit(Block &block)
607 SetForScope<Block *> set_block(current_block, &block);
608 for(auto i=block.body.begin(); i!=block.body.end(); ++i)
615 void ExpressionResolver::visit(Literal &literal)
617 if(literal.value.check_type<bool>())
618 resolve(literal, find_type(BasicTypeDeclaration::BOOL, 1), false);
619 else if(literal.value.check_type<int>())
620 resolve(literal, find_type(BasicTypeDeclaration::INT, 32, true), false);
621 else if(literal.value.check_type<unsigned>())
622 resolve(literal, find_type(BasicTypeDeclaration::INT, 32, false), false);
623 else if(literal.value.check_type<float>())
624 resolve(literal, find_type(BasicTypeDeclaration::FLOAT, 32), false);
627 void ExpressionResolver::visit(VariableReference &var)
630 resolve(var, var.declaration->type_declaration, true);
633 void ExpressionResolver::visit(InterfaceBlockReference &iface)
635 if(iface.declaration)
636 resolve(iface, iface.declaration->type_declaration, true);
639 void ExpressionResolver::visit(MemberAccess &memacc)
641 TraversingVisitor::visit(memacc);
643 if(memacc.declaration)
644 resolve(memacc, memacc.declaration->type_declaration, memacc.left->lvalue);
647 void ExpressionResolver::visit(Swizzle &swizzle)
649 TraversingVisitor::visit(swizzle);
651 if(BasicTypeDeclaration *left_basic = dynamic_cast<BasicTypeDeclaration *>(swizzle.left->type))
653 BasicTypeDeclaration *left_elem = get_element_type(*left_basic);
655 resolve(swizzle, left_elem, swizzle.left->lvalue);
656 else if(left_basic->kind==BasicTypeDeclaration::VECTOR && left_elem)
657 resolve(swizzle, find_type(*left_elem, left_basic->kind, swizzle.count), swizzle.left->lvalue);
661 void ExpressionResolver::visit(UnaryExpression &unary)
663 TraversingVisitor::visit(unary);
665 BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(unary.expression->type);
669 char oper = unary.oper->token[0];
672 if(basic->kind!=BasicTypeDeclaration::BOOL)
677 if(basic->kind!=BasicTypeDeclaration::INT)
680 else if(oper=='+' || oper=='-')
682 BasicTypeDeclaration *elem = get_element_type(*basic);
683 if(!elem || !is_scalar(*elem))
686 resolve(unary, basic, unary.expression->lvalue);
689 void ExpressionResolver::visit(BinaryExpression &binary, bool assign)
691 /* Binary operators are only defined for basic types (not for image or
693 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(binary.left->type);
694 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(binary.right->type);
695 if(!basic_left || !basic_right)
698 char oper = binary.oper->token[0];
701 /* Subscripting operates on vectors, matrices and arrays, and the right
702 operand must be an integer. */
703 if((!is_vector_or_matrix(*basic_left) && basic_left->kind!=BasicTypeDeclaration::ARRAY) || basic_right->kind!=BasicTypeDeclaration::INT)
706 resolve(binary, basic_left->base_type, binary.left->lvalue);
709 else if(basic_left->kind==BasicTypeDeclaration::ARRAY || basic_right->kind==BasicTypeDeclaration::ARRAY)
710 // No other binary operator can be used with arrays.
713 BasicTypeDeclaration *elem_left = get_element_type(*basic_left);
714 BasicTypeDeclaration *elem_right = get_element_type(*basic_right);
715 if(!elem_left || !elem_right)
718 Compatibility compat = get_compatibility(*basic_left, *basic_right);
719 Compatibility elem_compat = get_compatibility(*elem_left, *elem_right);
720 if(elem_compat==NOT_COMPATIBLE)
722 if(assign && (compat==LEFT_CONVERTIBLE || elem_compat==LEFT_CONVERTIBLE))
725 TypeDeclaration *type = 0;
726 char oper2 = binary.oper->token[1];
727 if((oper=='<' && oper2!='<') || (oper=='>' && oper2!='>'))
729 /* Relational operators compare two scalar integer or floating-point
731 if(!is_scalar(*elem_left) || !is_scalar(*elem_right) || compat==NOT_COMPATIBLE)
734 type = find_type(BasicTypeDeclaration::BOOL, 1);
736 else if((oper=='=' || oper=='!') && oper2=='=')
738 // Equality comparison can be done on any compatible types.
739 if(compat==NOT_COMPATIBLE)
742 type = find_type(BasicTypeDeclaration::BOOL, 1);
744 else if(oper2=='&' || oper2=='|' || oper2=='^')
746 // Logical operators can only be applied to booleans.
747 if(basic_left->kind!=BasicTypeDeclaration::BOOL || basic_right->kind!=BasicTypeDeclaration::BOOL)
752 else if((oper=='&' || oper=='|' || oper=='^' || oper=='%') && !oper2)
754 // Bitwise operators and modulo can only be applied to integers.
755 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
758 type = (compat==LEFT_CONVERTIBLE ? basic_right : basic_left);
760 else if((oper=='<' || oper=='>') && oper2==oper)
762 // Shifts apply to integer scalars and vectors, with some restrictions.
763 if(elem_left->kind!=BasicTypeDeclaration::INT || elem_right->kind!=BasicTypeDeclaration::INT)
765 unsigned left_size = (basic_left->kind==BasicTypeDeclaration::INT ? 1 : basic_left->kind==BasicTypeDeclaration::VECTOR ? basic_left->size : 0);
766 unsigned right_size = (basic_right->kind==BasicTypeDeclaration::INT ? 1 : basic_right->kind==BasicTypeDeclaration::VECTOR ? basic_right->size : 0);
767 if(!left_size || (left_size==1 && right_size!=1) || (left_size>1 && right_size!=1 && right_size!=left_size))
770 /* If the left operand is a vector and right is scalar, convert the right
771 operand to a vector too. */
772 if(left_size>1 && right_size==1)
774 BasicTypeDeclaration *vec_right = find_type(*elem_right, basic_left->kind, basic_left->size);
778 convert_to(binary.right, *vec_right);
782 // Don't perform conversion even if the operands are of different sizes.
785 else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
787 // Arithmetic operators require scalar elements.
788 if(!is_scalar(*elem_left) || !is_scalar(*elem_right))
791 if(oper=='*' && is_vector_or_matrix(*basic_left) && is_vector_or_matrix(*basic_right) &&
792 (basic_left->kind==BasicTypeDeclaration::MATRIX || basic_right->kind==BasicTypeDeclaration::MATRIX))
794 /* Multiplication has special rules when at least one operand is a
795 matrix and the other is a vector or a matrix. */
796 unsigned left_columns = basic_left->size&0xFFFF;
797 unsigned right_rows = basic_right->size;
798 if(basic_right->kind==BasicTypeDeclaration::MATRIX)
800 if(left_columns!=right_rows)
803 BasicTypeDeclaration *elem_result = (elem_compat==LEFT_CONVERTIBLE ? elem_right : elem_left);
805 if(basic_left->kind==BasicTypeDeclaration::VECTOR)
806 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_right->size&0xFFFF);
807 else if(basic_right->kind==BasicTypeDeclaration::VECTOR)
808 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_left->size>>16);
810 type = find_type(*elem_result, BasicTypeDeclaration::MATRIX, (basic_left->size&0xFFFF0000)|(basic_right->size&0xFFFF));
812 else if(compat==NOT_COMPATIBLE)
814 // Arithmetic between scalars and matrices or vectors is supported.
815 if(is_scalar(*basic_left) && is_vector_or_matrix(*basic_right))
816 type = (elem_compat==RIGHT_CONVERTIBLE ? find_type(*elem_left, basic_right->kind, basic_right->size) : basic_right);
817 else if(is_vector_or_matrix(*basic_left) && is_scalar(*basic_right))
818 type = (elem_compat==LEFT_CONVERTIBLE ? find_type(*elem_right, basic_left->kind, basic_left->size) : basic_left);
822 else if(compat==LEFT_CONVERTIBLE)
830 if(assign && type!=basic_left)
833 bool converted = true;
834 if(compat==LEFT_CONVERTIBLE)
835 convert_to(binary.left, *basic_right);
836 else if(compat==RIGHT_CONVERTIBLE)
837 convert_to(binary.right, *basic_left);
838 else if(elem_compat==LEFT_CONVERTIBLE)
839 converted = convert_to_element(binary.left, *elem_right);
840 else if(elem_compat==RIGHT_CONVERTIBLE)
841 converted = convert_to_element(binary.right, *elem_left);
846 resolve(binary, type, assign);
849 void ExpressionResolver::visit(BinaryExpression &binary)
851 TraversingVisitor::visit(binary);
852 visit(binary, false);
855 void ExpressionResolver::visit(Assignment &assign)
857 TraversingVisitor::visit(assign);
859 if(assign.oper->token[0]!='=')
860 return visit(assign, true);
861 else if(assign.left->type!=assign.right->type)
863 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(assign.left->type);
864 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(assign.right->type);
865 if(!basic_left || !basic_right)
868 Compatibility compat = get_compatibility(*basic_left, *basic_right);
869 if(compat==RIGHT_CONVERTIBLE)
870 convert_to(assign.right, *basic_left);
871 else if(compat!=SAME_TYPE)
875 resolve(assign, assign.left->type, true);
878 void ExpressionResolver::visit(TernaryExpression &ternary)
880 TraversingVisitor::visit(ternary);
882 BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(ternary.condition->type);
883 if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
886 TypeDeclaration *type = 0;
887 if(ternary.true_expr->type==ternary.false_expr->type)
888 type = ternary.true_expr->type;
891 BasicTypeDeclaration *basic_true = dynamic_cast<BasicTypeDeclaration *>(ternary.true_expr->type);
892 BasicTypeDeclaration *basic_false = dynamic_cast<BasicTypeDeclaration *>(ternary.false_expr->type);
893 if(!basic_true || !basic_false)
896 Compatibility compat = get_compatibility(*basic_true, *basic_false);
897 if(compat==NOT_COMPATIBLE)
900 type = (compat==LEFT_CONVERTIBLE ? basic_true : basic_false);
902 if(compat==LEFT_CONVERTIBLE)
903 convert_to(ternary.true_expr, *basic_false);
904 else if(compat==RIGHT_CONVERTIBLE)
905 convert_to(ternary.false_expr, *basic_true);
908 resolve(ternary, type, false);
911 void ExpressionResolver::visit_constructor(FunctionCall &call)
913 if(call.arguments.empty())
916 auto i = stage->types.find(call.name);
917 if(i==stage->types.end())
919 else if(call.arguments.size()==1 && i->second==call.arguments[0]->type)
921 else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(i->second))
923 BasicTypeDeclaration *elem = get_element_type(*basic);
927 vector<ArgumentInfo> args;
928 args.reserve(call.arguments.size());
929 unsigned arg_component_total = 0;
930 bool has_matrices = false;
931 for(const RefPtr<Expression> &a: call.arguments)
934 if(!(info.type=dynamic_cast<BasicTypeDeclaration *>(a->type)))
936 if(is_scalar(*info.type) || info.type->kind==BasicTypeDeclaration::BOOL)
937 info.component_count = 1;
938 else if(info.type->kind==BasicTypeDeclaration::VECTOR)
939 info.component_count = info.type->size;
940 else if(info.type->kind==BasicTypeDeclaration::MATRIX)
942 info.component_count = (info.type->size>>16)*(info.type->size&0xFFFF);
947 arg_component_total += info.component_count;
948 args.push_back(info);
951 bool convert_args = false;
952 if((is_scalar(*basic) || basic->kind==BasicTypeDeclaration::BOOL) && call.arguments.size()==1 && !has_matrices)
954 if(arg_component_total>1)
955 truncate_vector(call.arguments.front(), 1);
957 /* Single-element type constructors never need to convert their
958 arguments because the constructor *is* the conversion. */
960 else if(basic->kind==BasicTypeDeclaration::VECTOR && !has_matrices)
962 /* Vector constructors need either a single scalar argument or
963 enough components to fill out the vector. */
964 if(arg_component_total!=1 && arg_component_total<basic->size)
967 /* A vector of same size can be converted directly. For other
968 combinations the individual arguments need to be converted. */
969 if(call.arguments.size()==1)
971 if(arg_component_total==1)
973 else if(arg_component_total>basic->size)
974 truncate_vector(call.arguments.front(), basic->size);
976 else if(arg_component_total==basic->size)
981 else if(basic->kind==BasicTypeDeclaration::MATRIX)
983 unsigned column_count = basic->size&0xFFFF;
984 unsigned row_count = basic->size>>16;
986 vector<RefPtr<Expression> > columns;
987 columns.reserve(column_count);
988 bool changed_columns = false;
990 if(call.arguments.size()==1)
992 /* A matrix can be constructed from a single element or another
993 matrix of sufficient size. */
994 if(arg_component_total==1)
996 else if(args.front().type->kind==BasicTypeDeclaration::MATRIX)
998 unsigned arg_columns = args.front().type->size&0xFFFF;
999 unsigned arg_rows = args.front().type->size>>16;
1000 if(arg_columns<column_count || arg_rows<row_count)
1003 /* Always generate a temporary here and let the optimization
1004 stage inline it if that's reasonable. */
1005 RefPtr<VariableDeclaration> temporary = new VariableDeclaration;
1006 temporary->type = args.front().type->name;
1007 temporary->name = get_unused_variable_name(*current_block, "_temp");
1008 temporary->init_expression = call.arguments.front();
1009 current_block->body.insert(insert_point, temporary);
1011 // Create expressions to build each column.
1012 for(unsigned j=0; j<column_count; ++j)
1014 RefPtr<VariableReference> ref = new VariableReference;
1015 ref->name = temporary->name;
1017 RefPtr<Literal> index = new Literal;
1018 index->token = lexical_cast<string>(j);
1019 index->value = static_cast<int>(j);
1021 RefPtr<BinaryExpression> subscript = new BinaryExpression;
1022 subscript->left = ref;
1023 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
1024 subscript->right = index;
1025 subscript->type = args.front().type->base_type;
1027 columns.push_back(subscript);
1028 if(arg_rows>row_count)
1029 truncate_vector(columns.back(), row_count);
1032 changed_columns = true;
1037 else if(arg_component_total==column_count*row_count && !has_matrices)
1039 /* Construct a matrix from individual components in column-major
1040 order. Arguments must align at column boundaries. */
1041 vector<RefPtr<Expression> > column_args;
1042 column_args.reserve(row_count);
1043 unsigned column_component_count = 0;
1045 for(unsigned j=0; j<call.arguments.size(); ++j)
1047 const ArgumentInfo &info = args[j];
1048 if(!column_component_count && info.type->kind==BasicTypeDeclaration::VECTOR && info.component_count==row_count)
1049 // A vector filling the entire column can be used as is.
1050 columns.push_back(call.arguments[j]);
1053 column_args.push_back(call.arguments[j]);
1054 column_component_count += info.component_count;
1055 if(column_component_count==row_count)
1057 /* The column has filled up. Create a vector constructor
1059 RefPtr<FunctionCall> column_call = new FunctionCall;
1060 column_call->name = basic->base_type->name;
1061 column_call->constructor = true;
1062 column_call->arguments.resize(column_args.size());
1063 copy(column_args.begin(), column_args.end(), column_call->arguments.begin());
1064 column_call->type = basic->base_type;
1065 visit_constructor(*column_call);
1066 columns.push_back(column_call);
1068 column_args.clear();
1069 column_component_count = 0;
1071 else if(column_component_count>row_count)
1072 // Argument alignment mismatch.
1075 changed_columns = true;
1084 call.arguments.resize(column_count);
1085 copy(columns.begin(), columns.end(), call.arguments.begin());
1087 /* Let VariableResolver process the new nodes and finish
1088 resolving the constructor on the next pass. */
1089 r_any_resolved = true;
1098 // The argument list may have changed so can't rely on args.
1099 for(RefPtr<Expression> &a: call.arguments)
1100 if(BasicTypeDeclaration *basic_arg = dynamic_cast<BasicTypeDeclaration *>(a->type))
1102 BasicTypeDeclaration *elem_arg = get_element_type(*basic_arg);
1104 convert_to_element(a, *elem);
1108 else if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(i->second))
1110 if(call.arguments.size()!=strct->members.body.size())
1113 auto j = call.arguments.begin();
1114 for(const RefPtr<Statement> &s: strct->members.body)
1116 if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(s.get()))
1118 if(!(*j)->type || (*j)->type!=var->type_declaration)
1127 resolve(call, i->second, false);
1130 void ExpressionResolver::visit(FunctionCall &call)
1132 TraversingVisitor::visit(call);
1134 if(call.declaration)
1135 resolve(call, call.declaration->return_type_declaration, false);
1136 else if(call.constructor)
1137 visit_constructor(call);
1140 void ExpressionResolver::visit(BasicTypeDeclaration &type)
1142 basic_types.push_back(&type);
1145 void ExpressionResolver::visit(VariableDeclaration &var)
1147 TraversingVisitor::visit(var);
1148 if(!var.init_expression)
1151 BasicTypeDeclaration *var_basic = dynamic_cast<BasicTypeDeclaration *>(var.type_declaration);
1152 BasicTypeDeclaration *init_basic = dynamic_cast<BasicTypeDeclaration *>(var.init_expression->type);
1153 if(!var_basic || !init_basic)
1156 Compatibility compat = get_compatibility(*var_basic, *init_basic);
1157 if(compat==RIGHT_CONVERTIBLE)
1158 convert_to(var.init_expression, *var_basic);
1161 void ExpressionResolver::visit(FunctionDeclaration &func)
1163 SetForScope<const FunctionDeclaration *> set_func(current_function, &func);
1164 TraversingVisitor::visit(func);
1167 void ExpressionResolver::visit(Return &ret)
1169 TraversingVisitor::visit(ret);
1170 if(!current_function || !ret.expression)
1173 BasicTypeDeclaration *ret_basic = dynamic_cast<BasicTypeDeclaration *>(current_function->return_type_declaration);
1174 BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(ret.expression->type);
1175 if(!ret_basic || !expr_basic)
1178 Compatibility compat = get_compatibility(*ret_basic, *expr_basic);
1179 if(compat==RIGHT_CONVERTIBLE)
1180 convert_to(ret.expression, *ret_basic);
1184 bool FunctionResolver::apply(Stage &s)
1187 s.functions.clear();
1188 r_any_resolved = false;
1189 s.content.visit(*this);
1190 return r_any_resolved;
1193 bool FunctionResolver::can_convert_arguments(const FunctionCall &call, const FunctionDeclaration &decl)
1195 if(decl.parameters.size()!=call.arguments.size())
1198 for(unsigned j=0; j<call.arguments.size(); ++j)
1200 const TypeDeclaration *arg_type = call.arguments[j]->type;
1201 const TypeDeclaration *param_type = decl.parameters[j]->type_declaration;
1202 if(arg_type==param_type)
1205 const BasicTypeDeclaration *arg_basic = dynamic_cast<const BasicTypeDeclaration *>(arg_type);
1206 const BasicTypeDeclaration *param_basic = dynamic_cast<const BasicTypeDeclaration *>(param_type);
1207 if(arg_basic && param_basic && can_convert(*arg_basic, *param_basic))
1216 void FunctionResolver::visit(FunctionCall &call)
1218 FunctionDeclaration *declaration = 0;
1219 if(stage->types.count(call.name))
1220 call.constructor = true;
1224 bool has_signature = true;
1225 for(auto i=call.arguments.begin(); (has_signature && i!=call.arguments.end()); ++i)
1228 append(arg_types, ",", (*i)->type->name);
1230 has_signature = false;
1235 auto i = stage->functions.find(format("%s(%s)", call.name, arg_types));
1236 declaration = (i!=stage->functions.end() ? i->second : 0);
1240 for(i=stage->functions.lower_bound(call.name+"("); (i!=stage->functions.end() && i->second->name==call.name); ++i)
1241 if(can_convert_arguments(call, *i->second))
1249 declaration = i->second;
1255 r_any_resolved |= (declaration!=call.declaration);
1256 call.declaration = declaration;
1258 TraversingVisitor::visit(call);
1261 void FunctionResolver::visit(FunctionDeclaration &func)
1263 if(func.signature.empty())
1266 for(const RefPtr<VariableDeclaration> &p: func.parameters)
1268 if(p->type_declaration)
1269 append(param_types, ",", p->type_declaration->name);
1273 func.signature = format("(%s)", param_types);
1274 r_any_resolved = true;
1277 string key = func.name+func.signature;
1278 FunctionDeclaration *&stage_decl = stage->functions[key];
1279 vector<FunctionDeclaration *> &decls = declarations[key];
1280 if(func.definition==&func)
1282 if(stage_decl && stage_decl->definition)
1285 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1286 format("Overriding function '%s' without the override keyword is deprecated", key)));
1287 if(!stage_decl->definition->virtua)
1288 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1289 format("Overriding function '%s' not declared as virtual is deprecated", key)));
1293 // Set all previous declarations to use this definition.
1294 for(FunctionDeclaration *f: decls)
1296 r_any_resolved |= (func.definition!=f->definition);
1297 f->definition = func.definition;
1298 f->body.body.clear();
1303 FunctionDeclaration *definition = (stage_decl ? stage_decl->definition : 0);
1304 r_any_resolved |= (definition!=func.definition);
1305 func.definition = definition;
1310 decls.push_back(&func);
1312 TraversingVisitor::visit(func);