]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/resolve.cpp
Fix a name conflict in certain inlining scenarios
[libs/gl.git] / source / glsl / resolve.cpp
1 #include <msp/core/algorithm.h>
2 #include <msp/core/raii.h>
3 #include <msp/strings/utils.h>
4 #include "reflect.h"
5 #include "resolve.h"
6
7 using namespace std;
8
9 namespace Msp {
10 namespace GL {
11 namespace SL {
12
13 void BlockHierarchyResolver::enter(Block &block)
14 {
15         r_any_resolved |= (current_block!=block.parent);
16         block.parent = current_block;
17 }
18
19
20 bool TypeResolver::apply(Stage &s)
21 {
22         stage = &s;
23         s.types.clear();
24         r_any_resolved = false;
25         s.content.visit(*this);
26         return r_any_resolved;
27 }
28
29 TypeDeclaration *TypeResolver::get_or_create_array_type(TypeDeclaration &type)
30 {
31         auto i = array_types.find(&type);
32         if(i!=array_types.end())
33                 return i->second;
34
35         BasicTypeDeclaration *array = new BasicTypeDeclaration;
36         array->source = INTERNAL_SOURCE;
37         array->name = type.name+"[]";
38         array->kind = BasicTypeDeclaration::ARRAY;
39         array->base = type.name;
40         array->base_type = &type;
41         stage->content.body.insert(type_insert_point, array);
42         array_types[&type] = array;
43         return array;
44 }
45
46 void TypeResolver::resolve_type(TypeDeclaration *&type, const string &name, bool array)
47 {
48         TypeDeclaration *resolved = 0;
49         auto i = stage->types.find(name);
50         if(i!=stage->types.end())
51         {
52                 auto j = alias_map.find(i->second);
53                 resolved = (j!=alias_map.end() ? j->second : i->second);
54         }
55
56         if(resolved && array)
57                 resolved = get_or_create_array_type(*resolved);
58
59         r_any_resolved |= (resolved!=type);
60         type=resolved;
61 }
62
63 void TypeResolver::visit(Block &block)
64 {
65         for(auto i=block.body.begin(); i!=block.body.end(); ++i)
66         {
67                 if(!block.parent)
68                         type_insert_point = i;
69                 (*i)->visit(*this);
70         }
71 }
72
73 void TypeResolver::visit(BasicTypeDeclaration &type)
74 {
75         resolve_type(type.base_type, type.base, false);
76
77         if(type.kind==BasicTypeDeclaration::VECTOR && type.base_type)
78                 if(BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type))
79                         if(basic_base->kind==BasicTypeDeclaration::VECTOR)
80                         {
81                                 type.kind = BasicTypeDeclaration::MATRIX;
82                                 /* A matrix's base type is its column vector type.  This will put
83                                 the column vector's size, i.e. the matrix's row count, in the high
84                                 half of the size. */
85                                 type.size |= basic_base->size<<16;
86                         }
87
88         if(type.kind==BasicTypeDeclaration::ALIAS && type.base_type)
89                 alias_map[&type] = type.base_type;
90         else if(type.kind==BasicTypeDeclaration::ARRAY && type.base_type)
91                 array_types[type.base_type] = &type;
92
93         stage->types.insert(make_pair(type.name, &type));
94 }
95
96 void TypeResolver::visit(ImageTypeDeclaration &type)
97 {
98         resolve_type(type.base_type, type.base, false);
99         stage->types.insert(make_pair(type.name, &type));
100 }
101
102 void TypeResolver::visit(StructDeclaration &strct)
103 {
104         stage->types.insert(make_pair(strct.name, &strct));
105         TraversingVisitor::visit(strct);
106 }
107
108 void TypeResolver::visit(VariableDeclaration &var)
109 {
110         resolve_type(var.type_declaration, var.type, var.array);
111         if(iface_block && var.interface==iface_block->interface)
112                 var.interface.clear();
113 }
114
115 void TypeResolver::visit(InterfaceBlock &iface)
116 {
117         if(iface.members)
118         {
119                 SetForScope<InterfaceBlock *> set_iface(iface_block, &iface);
120                 iface.members->visit(*this);
121
122                 StructDeclaration *strct = new StructDeclaration;
123                 strct->source = INTERNAL_SOURCE;
124                 strct->name = format("_%s_%s", iface.interface, iface.block_name);
125                 strct->members.body.splice(strct->members.body.begin(), iface.members->body);
126                 stage->content.body.insert(type_insert_point, strct);
127                 stage->types.insert(make_pair(strct->name, strct));
128
129                 iface.members = 0;
130                 strct->interface_block = &iface;
131                 iface.struct_declaration = strct;
132         }
133
134         TypeDeclaration *type = iface.struct_declaration;
135         if(type && iface.array)
136                 type = get_or_create_array_type(*type);
137         r_any_resolved = (type!=iface.type_declaration);
138         iface.type_declaration = type;
139 }
140
141 void TypeResolver::visit(FunctionDeclaration &func)
142 {
143         resolve_type(func.return_type_declaration, func.return_type, false);
144         TraversingVisitor::visit(func);
145 }
146
147
148 bool VariableResolver::apply(Stage &s)
149 {
150         stage = &s;
151         s.interface_blocks.clear();
152         r_any_resolved = false;
153         s.content.visit(*this);
154         for(Statement *b: redeclared_builtins)
155                 b->source = GENERATED_SOURCE;
156         NodeRemover().apply(s, nodes_to_remove);
157         return r_any_resolved;
158 }
159
160 void VariableResolver::enter(Block &block)
161 {
162         block.variables.clear();
163 }
164
165 void VariableResolver::visit(RefPtr<Expression> &expr)
166 {
167         r_replacement_expr = 0;
168         expr->visit(*this);
169         if(r_replacement_expr)
170         {
171                 expr = r_replacement_expr;
172                 /* Don't record assignment target when doing a replacement, because chain
173                 information won't be correct. */
174                 r_assignment_target.declaration = 0;
175                 r_any_resolved = true;
176         }
177         r_replacement_expr = 0;
178 }
179
180 void VariableResolver::check_assignment_target(Statement *declaration)
181 {
182         if(record_target)
183         {
184                 if(r_assignment_target.declaration)
185                 {
186                         /* More than one reference found in assignment target.  Unable to
187                         determine what the primary target is. */
188                         record_target = false;
189                         r_assignment_target.declaration = 0;
190                 }
191                 else
192                         r_assignment_target.declaration = declaration;
193         }
194         // TODO This check is overly broad and may prevent some optimizations.
195         else if(declaration && declaration==r_assignment_target.declaration)
196                 r_self_referencing = true;
197 }
198
199 void VariableResolver::visit(VariableReference &var)
200 {
201         VariableDeclaration *declaration = 0;
202
203         /* Look for variable declarations in the block hierarchy first.  Interface
204         blocks are always defined in the top level so we can't accidentally skip
205         one. */
206         for(Block *block=current_block; (!declaration && block); block=block->parent)
207         {
208                 auto i = block->variables.find(var.name);
209                 if(i!=block->variables.end())
210                         declaration = i->second;
211         }
212
213         if(!declaration)
214         {
215                 const map<string, InterfaceBlock *> &blocks = stage->interface_blocks;
216                 auto i = blocks.find(var.name);
217                 if(i==blocks.end())
218                 {
219                         // Look for the variable in anonymous interface blocks.
220                         for(i=blocks.begin(); i!=blocks.end(); ++i)
221                                 if(i->second->instance_name.empty() && i->second->struct_declaration)
222                                         if(i->second->struct_declaration->members.variables.count(var.name))
223                                                 break;
224                 }
225
226                 if(i!=blocks.end())
227                 {
228                         /* The name refers to either an interface block with an instance name
229                         or a variable declared inside an anonymous interface block.  Prepare
230                         new syntax tree nodes accordingly. */
231                         InterfaceBlockReference *iface_ref = new InterfaceBlockReference;
232                         iface_ref->source = var.source;
233                         iface_ref->line = var.line;
234                         iface_ref->declaration = i->second;
235
236                         if(i->second->instance_name.empty())
237                         {
238                                 iface_ref->name = format("%s %s", i->second->interface, i->second->block_name);
239
240                                 MemberAccess *memacc = new MemberAccess;
241                                 memacc->source = var.source;
242                                 memacc->line = var.line;
243                                 memacc->left = iface_ref;
244                                 memacc->member = var.name;
245
246                                 r_replacement_expr = memacc;
247                         }
248                         else
249                         {
250                                 iface_ref->name = var.name;
251                                 r_replacement_expr = iface_ref;
252                         }
253                 }
254         }
255
256         r_any_resolved |= (declaration!=var.declaration);
257         var.declaration = declaration;
258
259         check_assignment_target(var.declaration);
260 }
261
262 void VariableResolver::visit(InterfaceBlockReference &iface)
263 {
264         auto i = stage->interface_blocks.find(iface.name);
265         InterfaceBlock *declaration = (i!=stage->interface_blocks.end() ? i->second : 0);
266         r_any_resolved |= (declaration!=iface.declaration);
267         iface.declaration = declaration;
268
269         check_assignment_target(iface.declaration);
270 }
271
272 void VariableResolver::visit(MemberAccess &memacc)
273 {
274         TraversingVisitor::visit(memacc);
275
276         VariableDeclaration *declaration = 0;
277         int index = -1;
278         if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(memacc.left->type))
279         {
280                 auto i = strct->members.variables.find(memacc.member);
281                 if(i!=strct->members.variables.end())
282                 {
283                         declaration = i->second;
284                         index = 0;
285                         for(auto j=strct->members.body.begin(); (j!=strct->members.body.end() && j->get()!=i->second); ++j)
286                                 ++index;
287
288                         if(record_target)
289                                 add_to_chain(r_assignment_target, Assignment::Target::MEMBER, index);
290                 }
291         }
292         else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(memacc.left->type))
293         {
294                 bool scalar_swizzle = ((basic->kind==BasicTypeDeclaration::INT || basic->kind==BasicTypeDeclaration::FLOAT) && memacc.member.size()==1);
295                 bool vector_swizzle = (basic->kind==BasicTypeDeclaration::VECTOR && memacc.member.size()<=4);
296                 if(scalar_swizzle || vector_swizzle)
297                 {
298                         static const char component_names[] = { 'x', 'r', 's', 'y', 'g', 't', 'z', 'b', 'p', 'w', 'a', 'q' };
299
300                         bool ok = true;
301                         uint8_t components[4] = { };
302                         for(unsigned i=0; (ok && i<memacc.member.size()); ++i)
303                                 ok = ((components[i] = (std::find(component_names, component_names+12, memacc.member[i])-component_names)/3) < 4);
304
305                         if(ok)
306                         {
307                                 Swizzle *swizzle = new Swizzle;
308                                 swizzle->source = memacc.source;
309                                 swizzle->line = memacc.line;
310                                 swizzle->oper = memacc.oper;
311                                 swizzle->left = memacc.left;
312                                 swizzle->component_group = memacc.member;
313                                 swizzle->count = memacc.member.size();
314                                 copy(components, components+memacc.member.size(), swizzle->components);
315                                 r_replacement_expr = swizzle;
316                         }
317                 }
318         }
319
320         r_any_resolved |= (declaration!=memacc.declaration || index!=memacc.index);
321         memacc.declaration = declaration;
322         memacc.index = index;
323 }
324
325 void VariableResolver::visit(Swizzle &swizzle)
326 {
327         TraversingVisitor::visit(swizzle);
328
329         if(record_target)
330         {
331                 unsigned mask = 0;
332                 for(unsigned i=0; i<swizzle.count; ++i)
333                         mask |= 1<<swizzle.components[i];
334                 add_to_chain(r_assignment_target, Assignment::Target::SWIZZLE, mask);
335         }
336 }
337
338 void VariableResolver::visit(BinaryExpression &binary)
339 {
340         if(binary.oper->token[0]=='[')
341         {
342                 {
343                         /* The subscript expression is not a part of the primary assignment
344                         target. */
345                         SetFlag set(record_target, false);
346                         visit(binary.right);
347                 }
348                 visit(binary.left);
349
350                 if(record_target)
351                 {
352                         unsigned index = 0x3F;
353                         if(Literal *literal_subscript = dynamic_cast<Literal *>(binary.right.get()))
354                                 if(literal_subscript->value.check_type<int>())
355                                         index = literal_subscript->value.value<int>();
356                         add_to_chain(r_assignment_target, Assignment::Target::ARRAY, index);
357                 }
358         }
359         else
360                 TraversingVisitor::visit(binary);
361 }
362
363 void VariableResolver::visit(Assignment &assign)
364 {
365         {
366                 SetFlag set(record_target);
367                 r_assignment_target = Assignment::Target();
368                 visit(assign.left);
369                 r_any_resolved |= (r_assignment_target<assign.target || assign.target<r_assignment_target);
370                 assign.target = r_assignment_target;
371         }
372
373         r_self_referencing = false;
374         visit(assign.right);
375         assign.self_referencing = (r_self_referencing || assign.oper->token[0]!='=');
376 }
377
378 void VariableResolver::merge_layouts(Layout &to_layout, const Layout &from_layout)
379 {
380         for(const Layout::Qualifier &q: from_layout.qualifiers)
381         {
382                 auto i = find_member(to_layout.qualifiers, q.name, &Layout::Qualifier::name);
383                 if(i!=to_layout.qualifiers.end())
384                 {
385                         i->has_value = q.value;
386                         i->value = q.value;
387                 }
388                 else
389                         to_layout.qualifiers.push_back(q);
390         }
391 }
392
393 void VariableResolver::redeclare_builtin(VariableDeclaration &existing, VariableDeclaration &var)
394 {
395         if(var.layout)
396         {
397                 if(existing.layout)
398                         merge_layouts(*existing.layout, *var.layout);
399                 else
400                         existing.layout = var.layout;
401         }
402         if(var.array_size)
403                 existing.array_size = var.array_size;
404
405         redeclared_builtins.push_back(&existing);
406 }
407
408 void VariableResolver::visit(VariableDeclaration &var)
409 {
410         TraversingVisitor::visit(var);
411
412         auto i = current_block->variables.find(var.name);
413         VariableDeclaration *existing = 0;
414         InterfaceBlock *block = 0;
415         if(i!=current_block->variables.end())
416                 existing = i->second;
417         else if(!current_block->parent)
418         {
419                 const map<string, InterfaceBlock *> &blocks = stage->interface_blocks;
420                 for(auto j=blocks.begin(); j!=blocks.end(); ++j)
421                         if(j->second->instance_name.empty() && j->second->struct_declaration)
422                         {
423                                 map<string, VariableDeclaration *> &block_vars = j->second->struct_declaration->members.variables;
424                                 i = block_vars.find(var.name);
425                                 if(i!=block_vars.end())
426                                 {
427                                         existing = i->second;
428                                         block = j->second;
429                                         break;
430                                 }
431                         }
432         }
433
434         if(!existing)
435                 current_block->variables.insert(make_pair(var.name, &var));
436         else if(!current_block->parent && (block ? block->interface : existing->interface)==var.interface && existing->type==var.type && existing->array==var.array)
437         {
438                 if(existing->source==BUILTIN_SOURCE)
439                 {
440                         redeclare_builtin(*existing, var);
441
442                         if(block)
443                         {
444                                 redeclared_builtins.push_back(block);
445                                 for(const auto &kvp: block->struct_declaration->members.variables)
446                                         redeclared_builtins.push_back(kvp.second);
447                         }
448
449                         nodes_to_remove.insert(&var);
450                         r_any_resolved = true;
451                 }
452                 else if(existing->array && !existing->array_size && !var.layout && !var.init_expression)
453                 {
454                         existing->array_size = var.array_size;
455                         nodes_to_remove.insert(&var);
456                         r_any_resolved = true;
457                 }
458         }
459 }
460
461 void VariableResolver::visit(InterfaceBlock &iface)
462 {
463         string key = format("%s %s", iface.interface, iface.block_name);
464         auto i = stage->interface_blocks.find(key);
465         if(i!=stage->interface_blocks.end())
466         {
467                 if(i->second->source==BUILTIN_SOURCE && iface.struct_declaration && i->second->struct_declaration)
468                 {
469                         const map<string, VariableDeclaration *> &vars = iface.struct_declaration->members.variables;
470                         const map<string, VariableDeclaration *> &existing_vars = i->second->struct_declaration->members.variables;
471
472                         bool found_all = true;
473                         for(const auto &kvp: vars)
474                         {
475                                 auto j = existing_vars.find(kvp.first);
476                                 if(j!=existing_vars.end() && j->second->type==kvp.second->type && j->second->array==kvp.second->array)
477                                         redeclare_builtin(*j->second, *kvp.second);
478                                 else
479                                         found_all = false;
480                         }
481
482                         if(found_all)
483                         {
484                                 redeclared_builtins.push_back(i->second);
485                                 nodes_to_remove.insert(&iface);
486                                 nodes_to_remove.insert(iface.struct_declaration);
487                         }
488                 }
489         }
490         else
491         {
492                 /* Block names can be reused in different interfaces.  Prepend the interface
493                 to the name to avoid conflicts. */
494                 stage->interface_blocks.insert(make_pair(key, &iface));
495                 if(!iface.instance_name.empty())
496                         stage->interface_blocks.insert(make_pair(iface.instance_name, &iface));
497         }
498
499         TraversingVisitor::visit(iface);
500 }
501
502
503 bool ExpressionResolver::apply(Stage &s)
504 {
505         stage = &s;
506         r_any_resolved = false;
507         s.content.visit(*this);
508         return r_any_resolved;
509 }
510
511 ExpressionResolver::Compatibility ExpressionResolver::get_compatibility(BasicTypeDeclaration &left, BasicTypeDeclaration &right)
512 {
513         if(&left==&right)
514                 return SAME_TYPE;
515         else if(can_convert(left, right))
516                 return LEFT_CONVERTIBLE;
517         else if(can_convert(right, left))
518                 return RIGHT_CONVERTIBLE;
519         else
520                 return NOT_COMPATIBLE;
521 }
522
523 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration::Kind kind, unsigned size, bool sign)
524 {
525         auto i = find_if(basic_types,
526                 [kind, size, sign](const BasicTypeDeclaration *t){ return t->kind==kind && t->size==size && t->sign==sign; });
527         return (i!=basic_types.end() ? *i : 0);
528 }
529
530 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration &elem_type, BasicTypeDeclaration::Kind kind, unsigned size)
531 {
532         auto i = find_if(basic_types,
533                 [&elem_type, kind, size](BasicTypeDeclaration *t){ return get_element_type(*t)==&elem_type && t->kind==kind && t->size==size; });
534         return (i!=basic_types.end() ? *i : 0);
535 }
536
537 void ExpressionResolver::convert_to(RefPtr<Expression> &expr, BasicTypeDeclaration &type)
538 {
539         RefPtr<FunctionCall> call = new FunctionCall;
540         call->name = type.name;
541         call->constructor = true;
542         call->arguments.push_back_nocopy(expr);
543         call->type = &type;
544         expr = call;
545 }
546
547 bool ExpressionResolver::convert_to_element(RefPtr<Expression> &expr, BasicTypeDeclaration &elem_type)
548 {
549         if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
550         {
551                 BasicTypeDeclaration *to_type = &elem_type;
552                 if(is_vector_or_matrix(*expr_basic))
553                         to_type = find_type(elem_type, expr_basic->kind, expr_basic->size);
554                 if(to_type)
555                 {
556                         convert_to(expr, *to_type);
557                         return true;
558                 }
559         }
560
561         return false;
562 }
563
564 bool ExpressionResolver::truncate_vector(RefPtr<Expression> &expr, unsigned size)
565 {
566         if(BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(expr->type))
567                 if(BasicTypeDeclaration *expr_elem = get_element_type(*expr_basic))
568                 {
569                         RefPtr<Swizzle> swizzle = new Swizzle;
570                         swizzle->left = expr;
571                         swizzle->oper = &Operator::get_operator(".", Operator::POSTFIX);
572                         swizzle->component_group = string("xyzw", size);
573                         swizzle->count = size;
574                         for(unsigned i=0; i<size; ++i)
575                                 swizzle->components[i] = i;
576                         if(size==1)
577                                 swizzle->type = expr_elem;
578                         else
579                                 swizzle->type = find_type(*expr_elem, BasicTypeDeclaration::VECTOR, size);
580                         expr = swizzle;
581
582                         return true;
583                 }
584
585         return false;
586 }
587
588 void ExpressionResolver::resolve(Expression &expr, TypeDeclaration *type, bool lvalue)
589 {
590         r_any_resolved |= (type!=expr.type || lvalue!=expr.lvalue);
591         expr.type = type;
592         expr.lvalue = lvalue;
593 }
594
595 void ExpressionResolver::visit(Block &block)
596 {
597         SetForScope<Block *> set_block(current_block, &block);
598         for(auto i=block.body.begin(); i!=block.body.end(); ++i)
599         {
600                 insert_point = i;
601                 (*i)->visit(*this);
602         }
603 }
604
605 void ExpressionResolver::visit(Literal &literal)
606 {
607         if(literal.value.check_type<bool>())
608                 resolve(literal, find_type(BasicTypeDeclaration::BOOL, 1), false);
609         else if(literal.value.check_type<int>())
610                 resolve(literal, find_type(BasicTypeDeclaration::INT, 32, true), false);
611         else if(literal.value.check_type<unsigned>())
612                 resolve(literal, find_type(BasicTypeDeclaration::INT, 32, false), false);
613         else if(literal.value.check_type<float>())
614                 resolve(literal, find_type(BasicTypeDeclaration::FLOAT, 32), false);
615 }
616
617 void ExpressionResolver::visit(VariableReference &var)
618 {
619         if(var.declaration)
620                 resolve(var, var.declaration->type_declaration, true);
621 }
622
623 void ExpressionResolver::visit(InterfaceBlockReference &iface)
624 {
625         if(iface.declaration)
626                 resolve(iface, iface.declaration->type_declaration, true);
627 }
628
629 void ExpressionResolver::visit(MemberAccess &memacc)
630 {
631         TraversingVisitor::visit(memacc);
632
633         if(memacc.declaration)
634                 resolve(memacc, memacc.declaration->type_declaration, memacc.left->lvalue);
635 }
636
637 void ExpressionResolver::visit(Swizzle &swizzle)
638 {
639         TraversingVisitor::visit(swizzle);
640
641         if(BasicTypeDeclaration *left_basic = dynamic_cast<BasicTypeDeclaration *>(swizzle.left->type))
642         {
643                 BasicTypeDeclaration *left_elem = get_element_type(*left_basic);
644                 if(swizzle.count==1)
645                         resolve(swizzle, left_elem, swizzle.left->lvalue);
646                 else if(left_basic->kind==BasicTypeDeclaration::VECTOR && left_elem)
647                         resolve(swizzle, find_type(*left_elem, left_basic->kind, swizzle.count), swizzle.left->lvalue);
648         }
649 }
650
651 void ExpressionResolver::visit(UnaryExpression &unary)
652 {
653         TraversingVisitor::visit(unary);
654
655         BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(unary.expression->type);
656         if(!basic)
657                 return;
658
659         char oper = unary.oper->token[0];
660         if(oper=='!')
661         {
662                 if(basic->kind!=BasicTypeDeclaration::BOOL)
663                         return;
664         }
665         else if(oper=='~')
666         {
667                 if(basic->kind!=BasicTypeDeclaration::INT)
668                         return;
669         }
670         else if(oper=='+' || oper=='-')
671         {
672                 BasicTypeDeclaration *elem = get_element_type(*basic);
673                 if(!elem || !is_scalar(*elem))
674                         return;
675         }
676         resolve(unary, basic, unary.expression->lvalue);
677 }
678
679 void ExpressionResolver::visit(BinaryExpression &binary, bool assign)
680 {
681         /* Binary operators are only defined for basic types (not for image or
682         structure types). */
683         BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(binary.left->type);
684         BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(binary.right->type);
685         if(!basic_left || !basic_right)
686                 return;
687
688         char oper = binary.oper->token[0];
689         if(oper=='[')
690         {
691                 /* Subscripting operates on vectors, matrices and arrays, and the right
692                 operand must be an integer. */
693                 if((!is_vector_or_matrix(*basic_left) && basic_left->kind!=BasicTypeDeclaration::ARRAY) || basic_right->kind!=BasicTypeDeclaration::INT)
694                         return;
695
696                 resolve(binary, basic_left->base_type, binary.left->lvalue);
697                 return;
698         }
699         else if(basic_left->kind==BasicTypeDeclaration::ARRAY || basic_right->kind==BasicTypeDeclaration::ARRAY)
700                 // No other binary operator can be used with arrays.
701                 return;
702
703         BasicTypeDeclaration *elem_left = get_element_type(*basic_left);
704         BasicTypeDeclaration *elem_right = get_element_type(*basic_right);
705         if(!elem_left || !elem_right)
706                 return;
707
708         Compatibility compat = get_compatibility(*basic_left, *basic_right);
709         Compatibility elem_compat = get_compatibility(*elem_left, *elem_right);
710         if(elem_compat==NOT_COMPATIBLE)
711                 return;
712         if(assign && (compat==LEFT_CONVERTIBLE || elem_compat==LEFT_CONVERTIBLE))
713                 return;
714
715         TypeDeclaration *type = 0;
716         char oper2 = binary.oper->token[1];
717         if((oper=='<' && oper2!='<') || (oper=='>' && oper2!='>'))
718         {
719                 /* Relational operators compare two scalar integer or floating-point
720                 values. */
721                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right) || compat==NOT_COMPATIBLE)
722                         return;
723
724                 type = find_type(BasicTypeDeclaration::BOOL, 1);
725         }
726         else if((oper=='=' || oper=='!') && oper2=='=')
727         {
728                 // Equality comparison can be done on any compatible types.
729                 if(compat==NOT_COMPATIBLE)
730                         return;
731
732                 type = find_type(BasicTypeDeclaration::BOOL, 1);
733         }
734         else if(oper2=='&' || oper2=='|' || oper2=='^')
735         {
736                 // Logical operators can only be applied to booleans.
737                 if(basic_left->kind!=BasicTypeDeclaration::BOOL || basic_right->kind!=BasicTypeDeclaration::BOOL)
738                         return;
739
740                 type = basic_left;
741         }
742         else if((oper=='&' || oper=='|' || oper=='^' || oper=='%') && !oper2)
743         {
744                 // Bitwise operators and modulo can only be applied to integers.
745                 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
746                         return;
747
748                 type = (compat==LEFT_CONVERTIBLE ? basic_right : basic_left);
749         }
750         else if((oper=='<' || oper=='>') && oper2==oper)
751         {
752                 // Shifts apply to integer scalars and vectors, with some restrictions.
753                 if(elem_left->kind!=BasicTypeDeclaration::INT || elem_right->kind!=BasicTypeDeclaration::INT)
754                         return;
755                 unsigned left_size = (basic_left->kind==BasicTypeDeclaration::INT ? 1 : basic_left->kind==BasicTypeDeclaration::VECTOR ? basic_left->size : 0);
756                 unsigned right_size = (basic_right->kind==BasicTypeDeclaration::INT ? 1 : basic_right->kind==BasicTypeDeclaration::VECTOR ? basic_right->size : 0);
757                 if(!left_size || (left_size==1 && right_size!=1) || (left_size>1 && right_size!=1 && right_size!=left_size))
758                         return;
759
760                 /* If the left operand is a vector and right is scalar, convert the right
761                 operand to a vector too. */
762                 if(left_size>1 && right_size==1)
763                 {
764                         BasicTypeDeclaration *vec_right = find_type(*elem_right, basic_left->kind, basic_left->size);
765                         if(!vec_right)
766                                 return;
767
768                         convert_to(binary.right, *vec_right);
769                 }
770
771                 type = basic_left;
772                 // Don't perform conversion even if the operands are of different sizes.
773                 compat = SAME_TYPE;
774         }
775         else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
776         {
777                 // Arithmetic operators require scalar elements.
778                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right))
779                         return;
780
781                 if(oper=='*' && is_vector_or_matrix(*basic_left) && is_vector_or_matrix(*basic_right) &&
782                         (basic_left->kind==BasicTypeDeclaration::MATRIX || basic_right->kind==BasicTypeDeclaration::MATRIX))
783                 {
784                         /* Multiplication has special rules when at least one operand is a
785                         matrix and the other is a vector or a matrix. */
786                         unsigned left_columns = basic_left->size&0xFFFF;
787                         unsigned right_rows = basic_right->size;
788                         if(basic_right->kind==BasicTypeDeclaration::MATRIX)
789                                 right_rows >>= 16;
790                         if(left_columns!=right_rows)
791                                 return;
792
793                         BasicTypeDeclaration *elem_result = (elem_compat==LEFT_CONVERTIBLE ? elem_right : elem_left);
794
795                         if(basic_left->kind==BasicTypeDeclaration::VECTOR)
796                                 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_right->size&0xFFFF);
797                         else if(basic_right->kind==BasicTypeDeclaration::VECTOR)
798                                 type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_left->size>>16);
799                         else
800                                 type = find_type(*elem_result, BasicTypeDeclaration::MATRIX, (basic_left->size&0xFFFF0000)|(basic_right->size&0xFFFF));
801                 }
802                 else if(compat==NOT_COMPATIBLE)
803                 {
804                         // Arithmetic between scalars and matrices or vectors is supported.
805                         if(is_scalar(*basic_left) && is_vector_or_matrix(*basic_right))
806                                 type = (elem_compat==RIGHT_CONVERTIBLE ? find_type(*elem_left, basic_right->kind, basic_right->size) : basic_right);
807                         else if(is_vector_or_matrix(*basic_left) && is_scalar(*basic_right))
808                                 type = (elem_compat==LEFT_CONVERTIBLE ? find_type(*elem_right, basic_left->kind, basic_left->size) : basic_left);
809                         else
810                                 return;
811                 }
812                 else if(compat==LEFT_CONVERTIBLE)
813                         type = basic_right;
814                 else
815                         type = basic_left;
816         }
817         else
818                 return;
819
820         if(assign && type!=basic_left)
821                 return;
822
823         bool converted = true;
824         if(compat==LEFT_CONVERTIBLE)
825                 convert_to(binary.left, *basic_right);
826         else if(compat==RIGHT_CONVERTIBLE)
827                 convert_to(binary.right, *basic_left);
828         else if(elem_compat==LEFT_CONVERTIBLE)
829                 converted = convert_to_element(binary.left, *elem_right);
830         else if(elem_compat==RIGHT_CONVERTIBLE)
831                 converted = convert_to_element(binary.right, *elem_left);
832
833         if(!converted)
834                 type = 0;
835
836         resolve(binary, type, assign);
837 }
838
839 void ExpressionResolver::visit(BinaryExpression &binary)
840 {
841         TraversingVisitor::visit(binary);
842         visit(binary, false);
843 }
844
845 void ExpressionResolver::visit(Assignment &assign)
846 {
847         TraversingVisitor::visit(assign);
848
849         if(assign.oper->token[0]!='=')
850                 return visit(assign, true);
851         else if(assign.left->type!=assign.right->type)
852         {
853                 BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(assign.left->type);
854                 BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(assign.right->type);
855                 if(!basic_left || !basic_right)
856                         return;
857
858                 Compatibility compat = get_compatibility(*basic_left, *basic_right);
859                 if(compat==RIGHT_CONVERTIBLE)
860                         convert_to(assign.right, *basic_left);
861                 else if(compat!=SAME_TYPE)
862                         return;
863         }
864
865         resolve(assign, assign.left->type, true);
866 }
867
868 void ExpressionResolver::visit(TernaryExpression &ternary)
869 {
870         TraversingVisitor::visit(ternary);
871
872         BasicTypeDeclaration *basic_cond = dynamic_cast<BasicTypeDeclaration *>(ternary.condition->type);
873         if(!basic_cond || basic_cond->kind!=BasicTypeDeclaration::BOOL)
874                 return;
875
876         TypeDeclaration *type = 0;
877         if(ternary.true_expr->type==ternary.false_expr->type)
878                 type = ternary.true_expr->type;
879         else
880         {
881                 BasicTypeDeclaration *basic_true = dynamic_cast<BasicTypeDeclaration *>(ternary.true_expr->type);
882                 BasicTypeDeclaration *basic_false = dynamic_cast<BasicTypeDeclaration *>(ternary.false_expr->type);
883                 if(!basic_true || !basic_false)
884                         return;
885
886                 Compatibility compat = get_compatibility(*basic_true, *basic_false);
887                 if(compat==NOT_COMPATIBLE)
888                         return;
889
890                 type = (compat==LEFT_CONVERTIBLE ? basic_true : basic_false);
891
892                 if(compat==LEFT_CONVERTIBLE)
893                         convert_to(ternary.true_expr, *basic_false);
894                 else if(compat==RIGHT_CONVERTIBLE)
895                         convert_to(ternary.false_expr, *basic_true);
896         }
897
898         resolve(ternary, type, false);
899 }
900
901 void ExpressionResolver::visit_constructor(FunctionCall &call)
902 {
903         if(call.arguments.empty())
904                 return;
905
906         auto i = stage->types.find(call.name);
907         if(i==stage->types.end())
908                 return;
909         else if(call.arguments.size()==1 && i->second==call.arguments[0]->type)
910                 ;
911         else if(BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(i->second))
912         {
913                 BasicTypeDeclaration *elem = get_element_type(*basic);
914                 if(!elem)
915                         return;
916
917                 vector<ArgumentInfo> args;
918                 args.reserve(call.arguments.size());
919                 unsigned arg_component_total = 0;
920                 bool has_matrices = false;
921                 for(const RefPtr<Expression> &a: call.arguments)
922                 {
923                         ArgumentInfo info;
924                         if(!(info.type=dynamic_cast<BasicTypeDeclaration *>(a->type)))
925                                 return;
926                         if(is_scalar(*info.type) || info.type->kind==BasicTypeDeclaration::BOOL)
927                                 info.component_count = 1;
928                         else if(info.type->kind==BasicTypeDeclaration::VECTOR)
929                                 info.component_count = info.type->size;
930                         else if(info.type->kind==BasicTypeDeclaration::MATRIX)
931                         {
932                                 info.component_count = (info.type->size>>16)*(info.type->size&0xFFFF);
933                                 has_matrices = true;
934                         }
935                         else
936                                 return;
937                         arg_component_total += info.component_count;
938                         args.push_back(info);
939                 }
940
941                 bool convert_args = false;
942                 if((is_scalar(*basic) || basic->kind==BasicTypeDeclaration::BOOL) && call.arguments.size()==1 && !has_matrices)
943                 {
944                         if(arg_component_total>1)
945                                 truncate_vector(call.arguments.front(), 1);
946
947                         /* Single-element type constructors never need to convert their
948                         arguments because the constructor *is* the conversion. */
949                 }
950                 else if(basic->kind==BasicTypeDeclaration::VECTOR && !has_matrices)
951                 {
952                         /* Vector constructors need either a single scalar argument or
953                         enough components to fill out the vector. */
954                         if(arg_component_total!=1 && arg_component_total<basic->size)
955                                 return;
956
957                         /* A vector of same size can be converted directly.  For other
958                         combinations the individual arguments need to be converted. */
959                         if(call.arguments.size()==1)
960                         {
961                                 if(arg_component_total==1)
962                                         convert_args = true;
963                                 else if(arg_component_total>basic->size)
964                                         truncate_vector(call.arguments.front(), basic->size);
965                         }
966                         else if(arg_component_total==basic->size)
967                                 convert_args = true;
968                         else
969                                 return;
970                 }
971                 else if(basic->kind==BasicTypeDeclaration::MATRIX)
972                 {
973                         unsigned column_count = basic->size&0xFFFF;
974                         unsigned row_count = basic->size>>16;
975
976                         vector<RefPtr<Expression> > columns;
977                         columns.reserve(column_count);
978                         bool changed_columns = false;
979
980                         if(call.arguments.size()==1)
981                         {
982                                 /* A matrix can be constructed from a single element or another
983                                 matrix of sufficient size. */
984                                 if(arg_component_total==1)
985                                         convert_args = true;
986                                 else if(args.front().type->kind==BasicTypeDeclaration::MATRIX)
987                                 {
988                                         unsigned arg_columns = args.front().type->size&0xFFFF;
989                                         unsigned arg_rows = args.front().type->size>>16;
990                                         if(arg_columns<column_count || arg_rows<row_count)
991                                                 return;
992
993                                         /* Always generate a temporary here and let the optimization
994                                         stage inline it if that's reasonable. */
995                                         RefPtr<VariableDeclaration> temporary = new VariableDeclaration;
996                                         temporary->type = args.front().type->name;
997                                         temporary->name = get_unused_variable_name(*current_block, "_temp");
998                                         temporary->init_expression = call.arguments.front();
999                                         current_block->body.insert(insert_point, temporary);
1000
1001                                         // Create expressions to build each column.
1002                                         for(unsigned j=0; j<column_count; ++j)
1003                                         {
1004                                                 RefPtr<VariableReference> ref = new VariableReference;
1005                                                 ref->name = temporary->name;
1006
1007                                                 RefPtr<Literal> index = new Literal;
1008                                                 index->token = lexical_cast<string>(j);
1009                                                 index->value = static_cast<int>(j);
1010
1011                                                 RefPtr<BinaryExpression> subscript = new BinaryExpression;
1012                                                 subscript->left = ref;
1013                                                 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
1014                                                 subscript->right = index;
1015                                                 subscript->type = args.front().type->base_type;
1016
1017                                                 columns.push_back(subscript);
1018                                                 if(arg_rows>row_count)
1019                                                         truncate_vector(columns.back(), row_count);
1020                                         }
1021
1022                                         changed_columns = true;
1023                                 }
1024                                 else
1025                                         return;
1026                         }
1027                         else if(arg_component_total==column_count*row_count && !has_matrices)
1028                         {
1029                                 /* Construct a matrix from individual components in column-major
1030                                 order.  Arguments must align at column boundaries. */
1031                                 vector<RefPtr<Expression> > column_args;
1032                                 column_args.reserve(row_count);
1033                                 unsigned column_component_count = 0;
1034
1035                                 for(unsigned j=0; j<call.arguments.size(); ++j)
1036                                 {
1037                                         const ArgumentInfo &info = args[j];
1038                                         if(!column_component_count && info.type->kind==BasicTypeDeclaration::VECTOR && info.component_count==row_count)
1039                                                 // A vector filling the entire column can be used as is.
1040                                                 columns.push_back(call.arguments[j]);
1041                                         else
1042                                         {
1043                                                 column_args.push_back(call.arguments[j]);
1044                                                 column_component_count += info.component_count;
1045                                                 if(column_component_count==row_count)
1046                                                 {
1047                                                         /* The column has filled up.  Create a vector constructor
1048                                                         for it.*/
1049                                                         RefPtr<FunctionCall> column_call = new FunctionCall;
1050                                                         column_call->name = basic->base_type->name;
1051                                                         column_call->constructor = true;
1052                                                         column_call->arguments.resize(column_args.size());
1053                                                         copy(column_args.begin(), column_args.end(), column_call->arguments.begin());
1054                                                         column_call->type = basic->base_type;
1055                                                         visit_constructor(*column_call);
1056                                                         columns.push_back(column_call);
1057
1058                                                         column_args.clear();
1059                                                         column_component_count = 0;
1060                                                 }
1061                                                 else if(column_component_count>row_count)
1062                                                         // Argument alignment mismatch.
1063                                                         return;
1064
1065                                                 changed_columns = true;
1066                                         }
1067                                 }
1068                         }
1069                         else
1070                                 return;
1071
1072                         if(changed_columns)
1073                         {
1074                                 call.arguments.resize(column_count);
1075                                 copy(columns.begin(), columns.end(), call.arguments.begin());
1076
1077                                 /* Let VariableResolver process the new nodes and finish
1078                                 resolving the constructor on the next pass. */
1079                                 r_any_resolved = true;
1080                                 return;
1081                         }
1082                 }
1083                 else
1084                         return;
1085
1086                 if(convert_args)
1087                 {
1088                         // The argument list may have changed so can't rely on args.
1089                         for(RefPtr<Expression> &a: call.arguments)
1090                                 if(BasicTypeDeclaration *basic_arg = dynamic_cast<BasicTypeDeclaration *>(a->type))
1091                                 {
1092                                         BasicTypeDeclaration *elem_arg = get_element_type(*basic_arg);
1093                                         if(elem_arg!=elem)
1094                                                 convert_to_element(a, *elem);
1095                                 }
1096                 }
1097         }
1098         else if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(i->second))
1099         {
1100                 if(call.arguments.size()!=strct->members.body.size())
1101                         return;
1102
1103                 auto j = call.arguments.begin();
1104                 for(const RefPtr<Statement> &s: strct->members.body)
1105                 {
1106                         if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(s.get()))
1107                         {
1108                                 if(!(*j)->type || (*j)->type!=var->type_declaration)
1109                                         return;
1110                         }
1111                         else
1112                                 return;
1113                         ++j;
1114                 }
1115         }
1116
1117         resolve(call, i->second, false);
1118 }
1119
1120 void ExpressionResolver::visit(FunctionCall &call)
1121 {
1122         TraversingVisitor::visit(call);
1123
1124         if(call.declaration)
1125                 resolve(call, call.declaration->return_type_declaration, false);
1126         else if(call.constructor)
1127                 visit_constructor(call);
1128 }
1129
1130 void ExpressionResolver::visit(BasicTypeDeclaration &type)
1131 {
1132         basic_types.push_back(&type);
1133 }
1134
1135 void ExpressionResolver::visit(VariableDeclaration &var)
1136 {
1137         TraversingVisitor::visit(var);
1138         if(!var.init_expression)
1139                 return;
1140
1141         BasicTypeDeclaration *var_basic = dynamic_cast<BasicTypeDeclaration *>(var.type_declaration);
1142         BasicTypeDeclaration *init_basic = dynamic_cast<BasicTypeDeclaration *>(var.init_expression->type);
1143         if(!var_basic || !init_basic)
1144                 return;
1145
1146         Compatibility compat = get_compatibility(*var_basic, *init_basic);
1147         if(compat==RIGHT_CONVERTIBLE)
1148                 convert_to(var.init_expression, *var_basic);
1149 }
1150
1151 void ExpressionResolver::visit(FunctionDeclaration &func)
1152 {
1153         SetForScope<const FunctionDeclaration *> set_func(current_function, &func);
1154         TraversingVisitor::visit(func);
1155 }
1156
1157 void ExpressionResolver::visit(Return &ret)
1158 {
1159         TraversingVisitor::visit(ret);
1160         if(!current_function || !ret.expression)
1161                 return;
1162
1163         BasicTypeDeclaration *ret_basic = dynamic_cast<BasicTypeDeclaration *>(current_function->return_type_declaration);
1164         BasicTypeDeclaration *expr_basic = dynamic_cast<BasicTypeDeclaration *>(ret.expression->type);
1165         if(!ret_basic || !expr_basic)
1166                 return;
1167
1168         Compatibility compat = get_compatibility(*ret_basic, *expr_basic);
1169         if(compat==RIGHT_CONVERTIBLE)
1170                 convert_to(ret.expression, *ret_basic);
1171 }
1172
1173
1174 bool FunctionResolver::apply(Stage &s)
1175 {
1176         stage = &s;
1177         s.functions.clear();
1178         r_any_resolved = false;
1179         s.content.visit(*this);
1180         return r_any_resolved;
1181 }
1182
1183 bool FunctionResolver::can_convert_arguments(const FunctionCall &call, const FunctionDeclaration &decl)
1184 {
1185         if(decl.parameters.size()!=call.arguments.size())
1186                 return false;
1187
1188         for(unsigned j=0; j<call.arguments.size(); ++j)
1189         {
1190                 const TypeDeclaration *arg_type = call.arguments[j]->type;
1191                 const TypeDeclaration *param_type = decl.parameters[j]->type_declaration;
1192                 if(arg_type==param_type)
1193                         continue;
1194
1195                 const BasicTypeDeclaration *arg_basic = dynamic_cast<const BasicTypeDeclaration *>(arg_type);
1196                 const BasicTypeDeclaration *param_basic = dynamic_cast<const BasicTypeDeclaration *>(param_type);
1197                 if(arg_basic && param_basic && can_convert(*arg_basic, *param_basic))
1198                         continue;
1199
1200                 return false;
1201         }
1202
1203         return true;
1204 }
1205
1206 void FunctionResolver::visit(FunctionCall &call)
1207 {
1208         FunctionDeclaration *declaration = 0;
1209         if(stage->types.count(call.name))
1210                 call.constructor = true;
1211         else
1212         {
1213                 string arg_types;
1214                 bool has_signature = true;
1215                 for(auto i=call.arguments.begin(); (has_signature && i!=call.arguments.end()); ++i)
1216                 {
1217                         if((*i)->type)
1218                                 append(arg_types, ",", (*i)->type->name);
1219                         else
1220                                 has_signature = false;
1221                 }
1222
1223                 if(has_signature)
1224                 {
1225                         auto i = stage->functions.find(format("%s(%s)", call.name, arg_types));
1226                         declaration = (i!=stage->functions.end() ? i->second : 0);
1227
1228                         if(!declaration)
1229                         {
1230                                 for(i=stage->functions.lower_bound(call.name+"("); (i!=stage->functions.end() && i->second->name==call.name); ++i)
1231                                         if(can_convert_arguments(call, *i->second))
1232                                         {
1233                                                 if(declaration)
1234                                                 {
1235                                                         declaration = 0;
1236                                                         break;
1237                                                 }
1238                                                 else
1239                                                         declaration = i->second;
1240                                         }
1241                         }
1242                 }
1243         }
1244
1245         r_any_resolved |= (declaration!=call.declaration);
1246         call.declaration = declaration;
1247
1248         TraversingVisitor::visit(call);
1249 }
1250
1251 void FunctionResolver::visit(FunctionDeclaration &func)
1252 {
1253         if(func.signature.empty())
1254         {
1255                 string param_types;
1256                 for(const RefPtr<VariableDeclaration> &p: func.parameters)
1257                 {
1258                         if(p->type_declaration)
1259                                 append(param_types, ",", p->type_declaration->name);
1260                         else
1261                                 return;
1262                 }
1263                 func.signature = format("(%s)", param_types);
1264                 r_any_resolved = true;
1265         }
1266
1267         string key = func.name+func.signature;
1268         FunctionDeclaration *&stage_decl = stage->functions[key];
1269         vector<FunctionDeclaration *> &decls = declarations[key];
1270         if(func.definition==&func)
1271         {
1272                 if(stage_decl && stage_decl->definition)
1273                 {
1274                         if(!func.overrd)
1275                                 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1276                                         format("Overriding function '%s' without the override keyword is deprecated", key)));
1277                         if(!stage_decl->definition->virtua)
1278                                 stage->diagnostics.push_back(Diagnostic(Diagnostic::WARN, func.source, func.line,
1279                                         format("Overriding function '%s' not declared as virtual is deprecated", key)));
1280                 }
1281                 stage_decl = &func;
1282
1283                 // Set all previous declarations to use this definition.
1284                 for(FunctionDeclaration *f: decls)
1285                 {
1286                         r_any_resolved |= (func.definition!=f->definition);
1287                         f->definition = func.definition;
1288                         f->body.body.clear();
1289                 }
1290         }
1291         else
1292         {
1293                 FunctionDeclaration *definition = (stage_decl ? stage_decl->definition : 0);
1294                 r_any_resolved |= (definition!=func.definition);
1295                 func.definition = definition;
1296
1297                 if(!stage_decl)
1298                         stage_decl = &func;
1299         }
1300         decls.push_back(&func);
1301
1302         TraversingVisitor::visit(func);
1303 }
1304
1305 } // namespace SL
1306 } // namespace GL
1307 } // namespace Msp