]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/generate.cpp
Remove an unnecessary loop over block hierarchy
[libs/gl.git] / source / glsl / generate.cpp
1 #include <msp/core/hash.h>
2 #include <msp/core/raii.h>
3 #include <msp/strings/lexicalcast.h>
4 #include "builtin.h"
5 #include "generate.h"
6
7 using namespace std;
8
9 namespace Msp {
10 namespace GL {
11 namespace SL {
12
13 void DeclarationCombiner::apply(Stage &stage)
14 {
15         stage.content.visit(*this);
16         NodeRemover().apply(stage, nodes_to_remove);
17 }
18
19 void DeclarationCombiner::visit(Block &block)
20 {
21         if(current_block)
22                 return;
23
24         TraversingVisitor::visit(block);
25 }
26
27 void DeclarationCombiner::visit(VariableDeclaration &var)
28 {
29         VariableDeclaration *&ptr = variables[var.name];
30         if(ptr)
31         {
32                 ptr->type = var.type;
33                 if(var.init_expression)
34                         ptr->init_expression = var.init_expression;
35                 if(var.layout)
36                 {
37                         if(ptr->layout)
38                         {
39                                 for(vector<Layout::Qualifier>::iterator i=var.layout->qualifiers.begin(); i!=var.layout->qualifiers.end(); ++i)
40                                 {
41                                         bool found = false;
42                                         for(vector<Layout::Qualifier>::iterator j=ptr->layout->qualifiers.begin(); (!found && j!=ptr->layout->qualifiers.end()); ++j)
43                                                 if(j->name==i->name)
44                                                 {
45                                                         j->has_value = i->value;
46                                                         j->value = i->value;
47                                                         found = true;
48                                                 }
49
50                                         if(!found)
51                                                 ptr->layout->qualifiers.push_back(*i);
52                                 }
53                         }
54                         else
55                                 ptr->layout = var.layout;
56                 }
57                 nodes_to_remove.insert(&var);
58         }
59         else
60                 ptr = &var;
61 }
62
63
64 ConstantSpecializer::ConstantSpecializer():
65         values(0)
66 { }
67
68 void ConstantSpecializer::apply(Stage &stage, const map<string, int> *v)
69 {
70         values = v;
71         stage.content.visit(*this);
72 }
73
74 void ConstantSpecializer::visit(VariableDeclaration &var)
75 {
76         bool specializable = false;
77         if(var.layout)
78         {
79                 vector<Layout::Qualifier> &qualifiers = var.layout->qualifiers;
80                 for(vector<Layout::Qualifier>::iterator i=qualifiers.begin(); i!=qualifiers.end(); ++i)
81                         if(i->name=="constant_id")
82                         {
83                                 specializable = true;
84                                 if(values)
85                                         qualifiers.erase(i);
86                                 else if(i->value==-1)
87                                         i->value = hash32(var.name)&0x7FFFFFFF;
88                                 break;
89                         }
90
91                 if(qualifiers.empty())
92                         var.layout = 0;
93         }
94
95         if(specializable && values)
96         {
97                 map<string, int>::const_iterator i = values->find(var.name);
98                 if(i!=values->end())
99                 {
100                         RefPtr<Literal> literal = new Literal;
101                         if(var.type=="bool")
102                         {
103                                 literal->token = (i->second ? "true" : "false");
104                                 literal->value = static_cast<bool>(i->second);
105                         }
106                         else if(var.type=="int")
107                         {
108                                 literal->token = lexical_cast<string>(i->second);
109                                 literal->value = i->second;
110                         }
111                         var.init_expression = literal;
112                 }
113         }
114 }
115
116
117 void BlockHierarchyResolver::enter(Block &block)
118 {
119         block.parent = current_block;
120 }
121
122
123 TypeResolver::TypeResolver():
124         stage(0)
125 { }
126
127 void TypeResolver::apply(Stage &s)
128 {
129         stage = &s;
130         s.types.clear();
131         s.content.visit(*this);
132 }
133
134 TypeDeclaration *TypeResolver::resolve_type(const string &name)
135 {
136         map<string, TypeDeclaration *>::iterator i = stage->types.find(name);
137         if(i!=stage->types.end())
138         {
139                 map<TypeDeclaration *, TypeDeclaration *>::iterator j = alias_map.find(i->second);
140                 return (j!=alias_map.end() ? j->second : i->second);
141         }
142         else
143                 return 0;
144 }
145
146 void TypeResolver::visit(Block &block)
147 {
148         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
149         {
150                 if(!block.parent)
151                         type_insert_point = i;
152                 (*i)->visit(*this);
153         }
154 }
155
156 void TypeResolver::visit(BasicTypeDeclaration &type)
157 {
158         type.base_type = resolve_type(type.base);
159
160         if(type.kind==BasicTypeDeclaration::VECTOR && type.base_type)
161                 if(BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type))
162                         if(basic_base->kind==BasicTypeDeclaration::VECTOR)
163                         {
164                                 type.kind = BasicTypeDeclaration::MATRIX;
165                                 type.size |= basic_base->size<<16;
166                         }
167
168         if(type.kind==BasicTypeDeclaration::ALIAS && type.base_type)
169                 alias_map[&type] = type.base_type;
170         else if(type.kind==BasicTypeDeclaration::ARRAY && type.base_type)
171                 array_types[type.base_type] = &type;
172
173         stage->types.insert(make_pair(type.name, &type));
174 }
175
176 void TypeResolver::visit(ImageTypeDeclaration &type)
177 {
178         type.base_type = resolve_type(type.base);
179         stage->types.insert(make_pair(type.name, &type));
180 }
181
182 void TypeResolver::visit(StructDeclaration &strct)
183 {
184         stage->types.insert(make_pair(strct.name, &strct));
185         TraversingVisitor::visit(strct);
186 }
187
188 void TypeResolver::visit(VariableDeclaration &var)
189 {
190         TypeDeclaration *type = resolve_type(var.type);
191         if(var.array && type)
192         {
193                 map<TypeDeclaration *, TypeDeclaration *>::iterator i = array_types.find(type);
194                 if(i==array_types.end())
195                 {
196                         BasicTypeDeclaration *array = new BasicTypeDeclaration;
197                         array->source = BUILTIN_SOURCE;
198                         array->name = type->name+"[]";
199                         array->kind = BasicTypeDeclaration::ARRAY;
200                         array->base = type->name;
201                         array->base_type = type;
202                         stage->content.body.insert(type_insert_point, array);
203                         array->visit(*this);
204                         type = array;
205                 }
206                 else
207                         type = i->second;
208         }
209         var.type_declaration = type;
210 }
211
212 void TypeResolver::visit(FunctionDeclaration &func)
213 {
214         func.return_type_declaration = resolve_type(func.return_type);
215         TraversingVisitor::visit(func);
216 }
217
218
219 VariableResolver::VariableResolver():
220         stage(0),
221         r_members(0),
222         record_target(false),
223         r_self_referencing(false),
224         r_assignment_target(0)
225 { }
226
227 void VariableResolver::apply(Stage &s)
228 {
229         stage = &s;
230         s.interface_blocks.clear();
231         s.content.visit(*this);
232 }
233
234 void VariableResolver::enter(Block &block)
235 {
236         block.variables.clear();
237 }
238
239 void VariableResolver::visit(VariableReference &var)
240 {
241         var.declaration = 0;
242         r_members = 0;
243         /* Look for variable declarations in the block hierarchy first.  Interface
244         blocks are always defined in the top level so we can't accidentally skip
245         one. */
246         for(Block *block=current_block; (!var.declaration && block); block=block->parent)
247         {
248                 map<string, VariableDeclaration *>::iterator i = block->variables.find(var.name);
249                 if(i!=block->variables.end())
250                         var.declaration = i->second;
251         }
252
253         if(!var.declaration)
254         {
255                 const map<string, InterfaceBlock *> &blocks = stage->interface_blocks;
256                 map<string, InterfaceBlock *>::const_iterator i = blocks.find("_"+var.name);
257                 if(i!=blocks.end())
258                 {
259                         /* The name refers to an interface block with an instance name rather
260                         than a variable.  Prepare a new syntax tree node accordingly. */
261                         r_iface_ref = new InterfaceBlockReference;
262                         r_iface_ref->source = var.source;
263                         r_iface_ref->line = var.line;
264                         r_iface_ref->name = var.name;
265                         r_iface_ref->declaration = i->second;
266                         r_members = &i->second->members.variables;
267                 }
268                 else
269                 {
270                         // Look for the variable in anonymous interface blocks.
271                         for(i=blocks.begin(); (!var.declaration && i!=blocks.end()); ++i)
272                                 if(i->second->instance_name.empty())
273                                 {
274                                         map<string, VariableDeclaration *>::iterator j = i->second->members.variables.find(var.name);
275                                         if(j!=i->second->members.variables.end())
276                                                 var.declaration = j->second;
277                                 }
278                 }
279         }
280
281         if(var.declaration)
282                 if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(var.declaration->type_declaration))
283                         r_members = &strct->members.variables;
284
285         if(record_target)
286         {
287                 if(r_assignment_target)
288                 {
289                         /* More than one variable reference found in assignment target.
290                         Unable to determine what the primary target is. */
291                         record_target = false;
292                         r_assignment_target = 0;
293                 }
294                 else
295                         r_assignment_target = var.declaration;
296         }
297         else if(var.declaration && var.declaration==r_assignment_target)
298                 r_self_referencing = true;
299 }
300
301 void VariableResolver::visit(InterfaceBlockReference &iface)
302 {
303         iface.declaration = 0;
304         map<string, InterfaceBlock *>::iterator i = stage->interface_blocks.find("_"+iface.name);
305         if(i!=stage->interface_blocks.end())
306         {
307                 iface.declaration = i->second;
308                 r_members = &i->second->members.variables;
309         }
310 }
311
312 void VariableResolver::visit(MemberAccess &memacc)
313 {
314         r_members = 0;
315         r_iface_ref = 0;
316         memacc.left->visit(*this);
317
318         if(r_iface_ref)
319                 memacc.left = r_iface_ref;
320         r_iface_ref = 0;
321
322         memacc.declaration = 0;
323         if(r_members)
324         {
325                 map<string, VariableDeclaration *>::iterator i = r_members->find(memacc.member);
326                 if(i!=r_members->end())
327                 {
328                         memacc.declaration = i->second;
329                         if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(i->second->type_declaration))
330                                 r_members = &strct->members.variables;
331                 }
332                 else
333                         r_members = 0;
334         }
335 }
336
337 void VariableResolver::visit(UnaryExpression &unary)
338 {
339         TraversingVisitor::visit(unary);
340         r_members = 0;
341         r_iface_ref = 0;
342 }
343
344 void VariableResolver::visit(BinaryExpression &binary)
345 {
346         if(binary.oper->token[0]=='[')
347         {
348                 {
349                         /* The subscript expression is not a part of the primary assignment
350                         target. */
351                         SetFlag set(record_target, false);
352                         binary.right->visit(*this);
353                 }
354                 r_members = 0;
355                 r_iface_ref = 0;
356                 binary.left->visit(*this);
357                 if(r_iface_ref)
358                         binary.left = r_iface_ref;
359         }
360         else
361         {
362                 TraversingVisitor::visit(binary);
363                 r_members = 0;
364         }
365
366         r_iface_ref = 0;
367 }
368
369 void VariableResolver::visit(Assignment &assign)
370 {
371         {
372                 SetFlag set(record_target);
373                 r_assignment_target = 0;
374                 assign.left->visit(*this);
375                 assign.target_declaration = r_assignment_target;
376         }
377
378         r_self_referencing = false;
379         assign.right->visit(*this);
380         assign.self_referencing = (r_self_referencing || assign.oper->token[0]!='=');
381
382         r_members = 0;
383         r_iface_ref = 0;
384 }
385
386 void VariableResolver::visit(FunctionCall &call)
387 {
388         TraversingVisitor::visit(call);
389         r_members = 0;
390         r_iface_ref = 0;
391 }
392
393 void VariableResolver::visit(VariableDeclaration &var)
394 {
395         if(!block_interface.empty() && var.interface.empty())
396                 var.interface = block_interface;
397
398         TraversingVisitor::visit(var);
399         current_block->variables.insert(make_pair(var.name, &var));
400 }
401
402 void VariableResolver::visit(InterfaceBlock &iface)
403 {
404         /* Block names can be reused in different interfaces.  Prefix the name with
405         the first character of the interface to avoid conflicts. */
406         stage->interface_blocks.insert(make_pair(iface.interface+iface.name, &iface));
407         if(!iface.instance_name.empty())
408                 stage->interface_blocks.insert(make_pair("_"+iface.instance_name, &iface));
409
410         SetForScope<string> set_iface(block_interface, iface.interface);
411         TraversingVisitor::visit(iface);
412 }
413
414
415 bool ExpressionResolver::is_scalar(BasicTypeDeclaration &type)
416 {
417         return (type.kind==BasicTypeDeclaration::INT || type.kind==BasicTypeDeclaration::FLOAT);
418 }
419
420 bool ExpressionResolver::is_vector_or_matrix(BasicTypeDeclaration &type)
421 {
422         return (type.kind==BasicTypeDeclaration::VECTOR || type.kind==BasicTypeDeclaration::MATRIX);
423 }
424
425 BasicTypeDeclaration *ExpressionResolver::get_element_type(BasicTypeDeclaration &type)
426 {
427         if(is_vector_or_matrix(type) || type.kind==BasicTypeDeclaration::ARRAY)
428         {
429                 BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type);
430                 return (basic_base ? get_element_type(*basic_base) : 0);
431         }
432         else
433                 return &type;
434 }
435
436 bool ExpressionResolver::can_convert(BasicTypeDeclaration &from, BasicTypeDeclaration &to)
437 {
438         if(from.kind==BasicTypeDeclaration::INT && to.kind==BasicTypeDeclaration::FLOAT)
439                 return from.size<=to.size;
440         else if(from.kind!=to.kind)
441                 return false;
442         else if((from.kind==BasicTypeDeclaration::VECTOR || from.kind==BasicTypeDeclaration::MATRIX) && from.size==to.size)
443         {
444                 BasicTypeDeclaration *from_base = dynamic_cast<BasicTypeDeclaration *>(from.base_type);
445                 BasicTypeDeclaration *to_base = dynamic_cast<BasicTypeDeclaration *>(to.base_type);
446                 return (from_base && to_base && can_convert(*from_base, *to_base));
447         }
448         else
449                 return false;
450 }
451
452 ExpressionResolver::Compatibility ExpressionResolver::get_compatibility(BasicTypeDeclaration &left, BasicTypeDeclaration &right)
453 {
454         if(&left==&right)
455                 return SAME_TYPE;
456         else if(can_convert(left, right))
457                 return LEFT_CONVERTIBLE;
458         else if(can_convert(right, left))
459                 return RIGHT_CONVERTIBLE;
460         else
461                 return NOT_COMPATIBLE;
462 }
463
464 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration::Kind kind, unsigned size)
465 {
466         for(vector<BasicTypeDeclaration *>::const_iterator i=basic_types.begin(); i!=basic_types.end(); ++i)
467                 if((*i)->kind==kind && (*i)->size==size)
468                         return *i;
469         return 0;
470 }
471
472 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration &elem_type, BasicTypeDeclaration::Kind kind, unsigned size)
473 {
474         for(vector<BasicTypeDeclaration *>::const_iterator i=basic_types.begin(); i!=basic_types.end(); ++i)
475                 if(get_element_type(**i)==&elem_type && (*i)->kind==kind && (*i)->size==size)
476                         return *i;
477         return 0;
478 }
479
480 void ExpressionResolver::convert_to(RefPtr<Expression> &expr, BasicTypeDeclaration &type)
481 {
482         RefPtr<FunctionCall> call = new FunctionCall;
483         call->name = type.name;
484         call->constructor = true;
485         call->arguments.push_back(0);
486         call->arguments.back() = expr;
487         call->type = &type;
488         expr = call;
489 }
490
491 bool ExpressionResolver::convert_to_element(RefPtr<Expression> &expr, BasicTypeDeclaration &elem_type)
492 {
493         if(BasicTypeDeclaration *expr_type = dynamic_cast<BasicTypeDeclaration *>(expr->type))
494         {
495                 BasicTypeDeclaration *to_type = &elem_type;
496                 if(is_vector_or_matrix(*expr_type))
497                         to_type = find_type(elem_type, expr_type->kind, expr_type->size);
498                 if(to_type)
499                 {
500                         convert_to(expr, *to_type);
501                         return true;
502                 }
503         }
504
505         return false;
506 }
507
508 void ExpressionResolver::visit(Literal &literal)
509 {
510         if(literal.value.check_type<bool>())
511                 literal.type = find_type(BasicTypeDeclaration::BOOL, 1);
512         else if(literal.value.check_type<int>())
513                 literal.type = find_type(BasicTypeDeclaration::INT, 32);
514         else if(literal.value.check_type<float>())
515                 literal.type = find_type(BasicTypeDeclaration::FLOAT, 32);
516 }
517
518 void ExpressionResolver::visit(ParenthesizedExpression &parexpr)
519 {
520         TraversingVisitor::visit(parexpr);
521
522         parexpr.type = parexpr.expression->type;
523         parexpr.lvalue = parexpr.expression->lvalue;
524 }
525
526 void ExpressionResolver::visit(VariableReference &var)
527 {
528         if(var.declaration)
529                 var.type = var.declaration->type_declaration;
530         var.lvalue = true;
531 }
532
533 void ExpressionResolver::visit(InterfaceBlockReference &iface)
534 {
535         iface.lvalue = true;
536 }
537
538 void ExpressionResolver::visit(MemberAccess &memacc)
539 {
540         TraversingVisitor::visit(memacc);
541
542         if(memacc.declaration)
543                 memacc.type = memacc.declaration->type_declaration;
544         memacc.lvalue = memacc.left->lvalue;
545 }
546
547 void ExpressionResolver::visit(UnaryExpression &unary)
548 {
549         TraversingVisitor::visit(unary);
550
551         BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(unary.expression->type);
552         if(!basic)
553                 return;
554
555         char oper = unary.oper->token[0];
556         if(oper=='!')
557         {
558                 if(basic->kind==BasicTypeDeclaration::BOOL)
559                         unary.type = basic;
560         }
561         else if(oper=='~')
562         {
563                 if(basic->kind==BasicTypeDeclaration::INT)
564                         unary.type = basic;
565         }
566         else if(oper=='+' || oper=='-')
567         {
568                 BasicTypeDeclaration *elem = get_element_type(*basic);
569                 if(elem && is_scalar(*elem))
570                         unary.type = basic;
571         }
572         unary.lvalue = unary.expression->lvalue;
573 }
574
575 void ExpressionResolver::visit(BinaryExpression &binary)
576 {
577         TraversingVisitor::visit(binary);
578
579         /* Binary operators are only defined for basic types (not for image or
580         structure types). */
581         BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(binary.left->type);
582         BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(binary.right->type);
583         if(!basic_left || !basic_right)
584                 return;
585
586         binary.lvalue = false;
587
588         char oper = binary.oper->token[0];
589         if(oper=='[')
590         {
591                 /* Subscripting operates on vectors, matrices and arrays, and the right
592                 operand must be an integer. */
593                 if((!is_vector_or_matrix(*basic_left) && basic_left->kind!=BasicTypeDeclaration::ARRAY) || basic_right->kind!=BasicTypeDeclaration::INT)
594                         return;
595
596                 binary.type = basic_left->base_type;
597                 binary.lvalue = binary.left->lvalue;
598                 return;
599         }
600         else if(basic_left->kind==BasicTypeDeclaration::ARRAY || basic_right->kind==BasicTypeDeclaration::ARRAY)
601                 // No other binary operator can be used with arrays.
602                 return;
603
604         BasicTypeDeclaration *elem_left = get_element_type(*basic_left);
605         BasicTypeDeclaration *elem_right = get_element_type(*basic_right);
606         if(!elem_left || !elem_right)
607                 return;
608
609         Compatibility compat = get_compatibility(*basic_left, *basic_right);
610         Compatibility elem_compat = get_compatibility(*elem_left, *elem_right);
611         if(elem_compat==NOT_COMPATIBLE)
612                 return;
613
614         char oper2 = binary.oper->token[1];
615         if((oper=='<' && oper2!='<') || (oper=='>' && oper2!='>'))
616         {
617                 /* Relational operators compare two scalar integer or floating-point
618                 values. */
619                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right) || compat==NOT_COMPATIBLE)
620                         return;
621
622                 binary.type = find_type(BasicTypeDeclaration::BOOL, 1);
623         }
624         else if((oper=='=' || oper=='!') && oper2=='=')
625         {
626                 // Equality comparison can be done on any compatible types.
627                 if(compat==NOT_COMPATIBLE)
628                         return;
629
630                 binary.type = find_type(BasicTypeDeclaration::BOOL, 1);
631         }
632         else if(oper2=='&' || oper2=='|' || oper2=='^')
633         {
634                 // Logical operators can only be applied to booleans.
635                 if(basic_left->kind!=BasicTypeDeclaration::BOOL || basic_right->kind!=BasicTypeDeclaration::BOOL)
636                         return;
637
638                 binary.type = basic_left;
639         }
640         else if((oper=='&' || oper=='|' || oper=='^' || oper=='%') && !oper2)
641         {
642                 // Bitwise operators and modulo can only be applied to integers.
643                 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
644                         return;
645
646                 binary.type = (compat==LEFT_CONVERTIBLE ? basic_right : basic_left);
647         }
648         else if((oper=='<' || oper=='>') && oper2==oper)
649         {
650                 // Shifts only apply to integers.
651                 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
652                         return;
653
654                 binary.type = basic_left;
655         }
656         else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
657         {
658                 // Arithmetic operators require scalar elements.
659                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right))
660                         return;
661
662                 if(oper=='*' && is_vector_or_matrix(*basic_left) && is_vector_or_matrix(*basic_right) &&
663                         (basic_left->kind==BasicTypeDeclaration::MATRIX || basic_right->kind==BasicTypeDeclaration::MATRIX))
664                 {
665                         /* Multiplication has special rules when at least one operand is a
666                         matrix and the other is a vector or a matrix. */
667                         unsigned left_columns = basic_left->size&0xFFFF;
668                         unsigned right_rows = basic_right->size;
669                         if(basic_right->kind==BasicTypeDeclaration::MATRIX)
670                                 right_rows >>= 16;
671                         if(left_columns!=right_rows)
672                                 return;
673
674                         BasicTypeDeclaration *elem_result = (elem_compat==LEFT_CONVERTIBLE ? elem_right : elem_left);
675
676                         if(basic_left->kind==BasicTypeDeclaration::VECTOR)
677                                 binary.type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_right->size&0xFFFF);
678                         else if(basic_right->kind==BasicTypeDeclaration::VECTOR)
679                                 binary.type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_left->size>>16);
680                         else
681                                 binary.type = find_type(*elem_result, BasicTypeDeclaration::MATRIX, (basic_left->size&0xFFFF0000)|(basic_right->size&0xFFFF));
682                 }
683                 else if(compat==NOT_COMPATIBLE)
684                 {
685                         // Arithmetic between scalars and matrices or vectors is supported.
686                         if(is_scalar(*basic_left) && is_vector_or_matrix(*basic_right))
687                                 binary.type = (elem_compat==RIGHT_CONVERTIBLE ? find_type(*elem_left, basic_right->kind, basic_right->size) : basic_right);
688                         else if(is_vector_or_matrix(*basic_left) && is_scalar(*basic_right))
689                                 binary.type = (elem_compat==LEFT_CONVERTIBLE ? find_type(*elem_right, basic_left->kind, basic_left->size) : basic_left);
690                         else
691                                 return;
692                 }
693                 else if(compat==LEFT_CONVERTIBLE)
694                         binary.type = basic_right;
695                 else
696                         binary.type = basic_left;
697         }
698         else
699                 return;
700
701         bool converted = true;
702         if(compat==LEFT_CONVERTIBLE)
703                 convert_to(binary.left, *basic_right);
704         else if(compat==RIGHT_CONVERTIBLE)
705                 convert_to(binary.right, *basic_left);
706         else if(elem_compat==LEFT_CONVERTIBLE)
707                 converted = convert_to_element(binary.left, *elem_right);
708         else if(elem_compat==RIGHT_CONVERTIBLE)
709                 converted = convert_to_element(binary.right, *elem_left);
710
711         if(!converted)
712                 binary.type = 0;
713 }
714
715 void ExpressionResolver::visit(Assignment &assign)
716 {
717         TraversingVisitor::visit(assign);
718         assign.type = assign.left->type;
719         assign.lvalue = true;
720 }
721
722 void ExpressionResolver::visit(FunctionCall &call)
723 {
724         TraversingVisitor::visit(call);
725
726         if(call.declaration)
727                 call.type = call.declaration->return_type_declaration;
728         else if(call.constructor)
729         {
730                 map<string, TypeDeclaration *>::const_iterator i=stage->types.find(call.name);
731                 call.type = (i!=stage->types.end() ? i->second : 0);
732         }
733         call.lvalue = false;
734 }
735
736 void ExpressionResolver::visit(BasicTypeDeclaration &type)
737 {
738         basic_types.push_back(&type);
739 }
740
741 void ExpressionResolver::visit(VariableDeclaration &var)
742 {
743         TraversingVisitor::visit(var);
744         if(!var.init_expression)
745                 return;
746
747         BasicTypeDeclaration *var_basic = dynamic_cast<BasicTypeDeclaration *>(var.type_declaration);
748         BasicTypeDeclaration *init_basic = dynamic_cast<BasicTypeDeclaration *>(var.init_expression->type);
749         if(!var_basic || !init_basic)
750                 return;
751
752         Compatibility compat = get_compatibility(*var_basic, *init_basic);
753         if(compat==RIGHT_CONVERTIBLE)
754                 convert_to(var.init_expression, *var_basic);
755 }
756
757
758 void FunctionResolver::apply(Stage &s)
759 {
760         stage = &s;
761         s.functions.clear();
762         s.content.visit(*this);
763 }
764
765 void FunctionResolver::visit(FunctionCall &call)
766 {
767         map<string, FunctionDeclaration *>::iterator i = stage->functions.find(call.name);
768         if(i!=stage->functions.end())
769                 call.declaration = i->second;
770
771         TraversingVisitor::visit(call);
772 }
773
774 void FunctionResolver::visit(FunctionDeclaration &func)
775 {
776         FunctionDeclaration *&stage_decl = stage->functions[func.name];
777         vector<FunctionDeclaration *> &decls = declarations[func.name];
778         if(func.definition==&func)
779         {
780                 stage_decl = &func;
781
782                 // Set all previous declarations to use this definition.
783                 for(vector<FunctionDeclaration *>::iterator i=decls.begin(); i!=decls.end(); ++i)
784                 {
785                         (*i)->definition = func.definition;
786                         (*i)->body.body.clear();
787                 }
788         }
789         else
790         {
791                 func.definition = 0;
792                 if(!stage_decl)
793                         stage_decl = &func;
794                 else
795                         func.definition = stage_decl->definition;
796         }
797         decls.push_back(&func);
798
799         TraversingVisitor::visit(func);
800 }
801
802
803 InterfaceGenerator::InterfaceGenerator():
804         stage(0),
805         function_scope(false),
806         iface_block(0),
807         copy_block(false),
808         iface_target_block(0)
809 { }
810
811 string InterfaceGenerator::get_out_prefix(Stage::Type type)
812 {
813         if(type==Stage::VERTEX)
814                 return "_vs_out_";
815         else if(type==Stage::GEOMETRY)
816                 return "_gs_out_";
817         else
818                 return string();
819 }
820
821 void InterfaceGenerator::apply(Stage &s)
822 {
823         stage = &s;
824         iface_target_block = &stage->content;
825         if(stage->previous)
826                 in_prefix = get_out_prefix(stage->previous->type);
827         out_prefix = get_out_prefix(stage->type);
828         s.content.visit(*this);
829         NodeRemover().apply(s, nodes_to_remove);
830 }
831
832 void InterfaceGenerator::visit(Block &block)
833 {
834         SetForScope<Block *> set_block(current_block, &block);
835         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
836         {
837                 assignment_insert_point = i;
838                 if(&block==&stage->content)
839                         iface_insert_point = i;
840
841                 (*i)->visit(*this);
842         }
843 }
844
845 string InterfaceGenerator::change_prefix(const string &name, const string &prefix) const
846 {
847         unsigned offset = (name.compare(0, in_prefix.size(), in_prefix) ? 0 : in_prefix.size());
848         return prefix+name.substr(offset);
849 }
850
851 VariableDeclaration *InterfaceGenerator::generate_interface(VariableDeclaration &var, const string &iface, const string &name)
852 {
853         if(stage->content.variables.count(name))
854                 return 0;
855
856         VariableDeclaration* iface_var = new VariableDeclaration;
857         iface_var->sampling = var.sampling;
858         iface_var->interface = iface;
859         iface_var->type = var.type;
860         iface_var->name = name;
861         /* Geometry shader inputs are always arrays.  But if we're bringing in an
862         entire block, the array is on the block and not individual variables. */
863         if(stage->type==Stage::GEOMETRY && !copy_block)
864                 iface_var->array = ((var.array && var.interface!="in") || iface=="in");
865         else
866                 iface_var->array = var.array;
867         if(iface_var->array)
868                 iface_var->array_size = var.array_size;
869         if(iface=="in")
870         {
871                 iface_var->layout = var.layout;
872                 iface_var->linked_declaration = &var;
873                 var.linked_declaration = iface_var;
874         }
875
876         iface_target_block->body.insert(iface_insert_point, iface_var);
877         iface_target_block->variables.insert(make_pair(name, iface_var));
878
879         return iface_var;
880 }
881
882 InterfaceBlock *InterfaceGenerator::generate_interface(InterfaceBlock &out_block)
883 {
884         if(stage->interface_blocks.count("in"+out_block.name))
885                 return 0;
886
887         InterfaceBlock *in_block = new InterfaceBlock;
888         in_block->interface = "in";
889         in_block->name = out_block.name;
890         in_block->instance_name = out_block.instance_name;
891         if(stage->type==Stage::GEOMETRY)
892                 in_block->array = true;
893         else
894                 in_block->array = out_block.array;
895         in_block->linked_block = &out_block;
896         out_block.linked_block = in_block;
897
898         {
899                 SetFlag set_copy(copy_block, true);
900                 SetForScope<Block *> set_target(iface_target_block, &in_block->members);
901                 SetForScope<NodeList<Statement>::iterator> set_ins_pt(iface_insert_point, in_block->members.body.end());
902                 out_block.members.visit(*this);
903         }
904
905         iface_target_block->body.insert(iface_insert_point, in_block);
906         stage->interface_blocks.insert(make_pair("in"+in_block->name, in_block));
907         if(!in_block->instance_name.empty())
908                 stage->interface_blocks.insert(make_pair("_"+in_block->instance_name, in_block));
909
910         SetFlag set_scope(function_scope, false);
911         SetForScope<Block *> set_block(current_block, &stage->content);
912         in_block->visit(*this);
913
914         return in_block;
915 }
916
917 ExpressionStatement &InterfaceGenerator::insert_assignment(const string &left, Expression *right)
918 {
919         Assignment *assign = new Assignment;
920         VariableReference *ref = new VariableReference;
921         ref->name = left;
922         assign->left = ref;
923         assign->oper = &Operator::get_operator("=", Operator::BINARY);
924         assign->right = right;
925
926         ExpressionStatement *stmt = new ExpressionStatement;
927         stmt->expression = assign;
928         current_block->body.insert(assignment_insert_point, stmt);
929         stmt->visit(*this);
930
931         return *stmt;
932 }
933
934 void InterfaceGenerator::visit(VariableReference &var)
935 {
936         if(var.declaration || !stage->previous)
937                 return;
938         /* Don't pull a variable from previous stage if we just generated an output
939         interface in this stage */
940         if(stage->content.variables.count(var.name))
941                 return;
942
943         const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
944         map<string, VariableDeclaration *>::const_iterator i = prev_vars.find(var.name);
945         if(i==prev_vars.end() || i->second->interface!="out")
946                 i = prev_vars.find(in_prefix+var.name);
947         if(i!=prev_vars.end() && i->second->interface=="out")
948         {
949                 generate_interface(*i->second, "in", i->second->name);
950                 var.name = i->second->name;
951                 return;
952         }
953
954         const map<string, InterfaceBlock *> &prev_blocks = stage->previous->interface_blocks;
955         map<string, InterfaceBlock *>::const_iterator j = prev_blocks.find("_"+var.name);
956         if(j!=prev_blocks.end() && j->second->interface=="out")
957         {
958                 generate_interface(*j->second);
959                 /* Let VariableResolver convert the variable reference into an interface
960                 block reference. */
961                 return;
962         }
963
964         for(j=prev_blocks.begin(); j!=prev_blocks.end(); ++j)
965                 if(j->second->instance_name.empty())
966                 {
967                         i = j->second->members.variables.find(var.name);
968                         if(i!=j->second->members.variables.end())
969                         {
970                                 generate_interface(*j->second);
971                                 return;
972                         }
973                 }
974 }
975
976 void InterfaceGenerator::visit(VariableDeclaration &var)
977 {
978         if(copy_block)
979         {
980                 generate_interface(var, "in", var.name);
981                 return;
982         }
983
984         if(iface_block)
985         {
986                 if(iface_block->linked_block)
987                 {
988                         // Link all variables to their counterparts in the linked block.
989                         const map<string, VariableDeclaration *> &linked_vars = iface_block->linked_block->members.variables;
990                         map<string, VariableDeclaration *>::const_iterator i = linked_vars.find(var.name);
991                         if(i!=linked_vars.end())
992                         {
993                                 var.linked_declaration = i->second;
994                                 var.linked_declaration->linked_declaration = &var;
995                         }
996                 }
997                 return;
998         }
999
1000         if(var.interface=="out")
1001         {
1002                 /* For output variables in function scope, generate a global interface
1003                 and replace the local declaration with an assignment. */
1004                 VariableDeclaration *out_var = 0;
1005                 if(function_scope && (out_var=generate_interface(var, "out", var.name)))
1006                 {
1007                         out_var->source = var.source;
1008                         out_var->line = var.line;
1009                         nodes_to_remove.insert(&var);
1010                         if(var.init_expression)
1011                         {
1012                                 ExpressionStatement &stmt = insert_assignment(var.name, var.init_expression->clone());
1013                                 stmt.source = var.source;
1014                                 stmt.line = var.line;
1015                                 return;
1016                         }
1017                 }
1018         }
1019         else if(var.interface=="in")
1020         {
1021                 /* Try to link input variables in global scope with output variables from
1022                 previous stage. */
1023                 if(current_block==&stage->content && !var.linked_declaration && stage->previous)
1024                 {
1025                         const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
1026                         map<string, VariableDeclaration *>::const_iterator i = prev_vars.find(var.name);
1027                         if(i!=prev_vars.end() && i->second->interface=="out")
1028                         {
1029                                 var.linked_declaration = i->second;
1030                                 i->second->linked_declaration = &var;
1031                         }
1032                 }
1033         }
1034
1035         TraversingVisitor::visit(var);
1036 }
1037
1038 void InterfaceGenerator::visit(InterfaceBlock &iface)
1039 {
1040         if(iface.interface=="in")
1041         {
1042                 /* Try to link input blocks with output blocks sharing the same block
1043                 name from previous stage. */
1044                 if(!iface.linked_block && stage->previous)
1045                 {
1046                         const map<string, InterfaceBlock *> &prev_blocks = stage->previous->interface_blocks;
1047                         map<string, InterfaceBlock *>::const_iterator i = prev_blocks.find("out"+iface.name);
1048                         if(i!=prev_blocks.end())
1049                         {
1050                                 iface.linked_block = i->second;
1051                                 i->second->linked_block = &iface;
1052                         }
1053                 }
1054         }
1055
1056         SetForScope<InterfaceBlock *> set_iface(iface_block, &iface);
1057         TraversingVisitor::visit(iface);
1058 }
1059
1060 void InterfaceGenerator::visit(FunctionDeclaration &func)
1061 {
1062         SetFlag set_scope(function_scope, true);
1063         // Skip parameters because they're not useful here
1064         func.body.visit(*this);
1065 }
1066
1067 void InterfaceGenerator::visit(Passthrough &pass)
1068 {
1069         vector<VariableDeclaration *> pass_vars;
1070
1071         // Pass through all input variables of this stage.
1072         for(map<string, VariableDeclaration *>::const_iterator i=stage->content.variables.begin(); i!=stage->content.variables.end(); ++i)
1073                 if(i->second->interface=="in")
1074                         pass_vars.push_back(i->second);
1075
1076         if(stage->previous)
1077         {
1078                 const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
1079                 for(map<string, VariableDeclaration *>::const_iterator i=prev_vars.begin(); i!=prev_vars.end(); ++i)
1080                 {
1081                         if(i->second->interface!="out")
1082                                 continue;
1083
1084                         /* Pass through output variables from the previous stage, but only
1085                         those which are not already linked to an input here. */
1086                         if(!i->second->linked_declaration && generate_interface(*i->second, "in", i->second->name))
1087                                 pass_vars.push_back(i->second);
1088                 }
1089         }
1090
1091         if(stage->type==Stage::GEOMETRY)
1092         {
1093                 /* Special case for geometry shader: copy gl_Position from input to
1094                 output. */
1095                 InterfaceBlockReference *ref = new InterfaceBlockReference;
1096                 ref->name = "gl_in";
1097
1098                 BinaryExpression *subscript = new BinaryExpression;
1099                 subscript->left = ref;
1100                 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
1101                 subscript->right = pass.subscript;
1102
1103                 MemberAccess *memacc = new MemberAccess;
1104                 memacc->left = subscript;
1105                 memacc->member = "gl_Position";
1106
1107                 insert_assignment("gl_Position", memacc);
1108         }
1109
1110         for(vector<VariableDeclaration *>::const_iterator i=pass_vars.begin(); i!=pass_vars.end(); ++i)
1111         {
1112                 string out_name = change_prefix((*i)->name, out_prefix);
1113                 generate_interface(**i, "out", out_name);
1114
1115                 VariableReference *ref = new VariableReference;
1116                 ref->name = (*i)->name;
1117                 if(pass.subscript)
1118                 {
1119                         BinaryExpression *subscript = new BinaryExpression;
1120                         subscript->left = ref;
1121                         subscript->oper = &Operator::get_operator("[", Operator::BINARY);
1122                         subscript->right = pass.subscript;
1123                         insert_assignment(out_name, subscript);
1124                 }
1125                 else
1126                         insert_assignment(out_name, ref);
1127         }
1128
1129         nodes_to_remove.insert(&pass);
1130 }
1131
1132 } // namespace SL
1133 } // namespace GL
1134 } // namespace Msp