]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/generate.cpp
770fb460d657196cf7781fd0ea9b9553a2728b21
[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         for(Block *block=current_block; block; block=block->parent)
305         {
306                 map<string, InterfaceBlock *>::iterator i = stage->interface_blocks.find("_"+iface.name);
307                 if(i!=stage->interface_blocks.end())
308                 {
309                         iface.declaration = i->second;
310                         r_members = &i->second->members.variables;
311                         break;
312                 }
313         }
314 }
315
316 void VariableResolver::visit(MemberAccess &memacc)
317 {
318         r_members = 0;
319         r_iface_ref = 0;
320         memacc.left->visit(*this);
321
322         if(r_iface_ref)
323                 memacc.left = r_iface_ref;
324         r_iface_ref = 0;
325
326         memacc.declaration = 0;
327         if(r_members)
328         {
329                 map<string, VariableDeclaration *>::iterator i = r_members->find(memacc.member);
330                 if(i!=r_members->end())
331                 {
332                         memacc.declaration = i->second;
333                         if(StructDeclaration *strct = dynamic_cast<StructDeclaration *>(i->second->type_declaration))
334                                 r_members = &strct->members.variables;
335                 }
336                 else
337                         r_members = 0;
338         }
339 }
340
341 void VariableResolver::visit(UnaryExpression &unary)
342 {
343         TraversingVisitor::visit(unary);
344         r_members = 0;
345         r_iface_ref = 0;
346 }
347
348 void VariableResolver::visit(BinaryExpression &binary)
349 {
350         if(binary.oper->token[0]=='[')
351         {
352                 {
353                         /* The subscript expression is not a part of the primary assignment
354                         target. */
355                         SetFlag set(record_target, false);
356                         binary.right->visit(*this);
357                 }
358                 r_members = 0;
359                 r_iface_ref = 0;
360                 binary.left->visit(*this);
361                 if(r_iface_ref)
362                         binary.left = r_iface_ref;
363         }
364         else
365         {
366                 TraversingVisitor::visit(binary);
367                 r_members = 0;
368         }
369
370         r_iface_ref = 0;
371 }
372
373 void VariableResolver::visit(Assignment &assign)
374 {
375         {
376                 SetFlag set(record_target);
377                 r_assignment_target = 0;
378                 assign.left->visit(*this);
379                 assign.target_declaration = r_assignment_target;
380         }
381
382         r_self_referencing = false;
383         assign.right->visit(*this);
384         assign.self_referencing = (r_self_referencing || assign.oper->token[0]!='=');
385
386         r_members = 0;
387         r_iface_ref = 0;
388 }
389
390 void VariableResolver::visit(FunctionCall &call)
391 {
392         TraversingVisitor::visit(call);
393         r_members = 0;
394         r_iface_ref = 0;
395 }
396
397 void VariableResolver::visit(VariableDeclaration &var)
398 {
399         if(!block_interface.empty() && var.interface.empty())
400                 var.interface = block_interface;
401
402         TraversingVisitor::visit(var);
403         current_block->variables.insert(make_pair(var.name, &var));
404 }
405
406 void VariableResolver::visit(InterfaceBlock &iface)
407 {
408         /* Block names can be reused in different interfaces.  Prefix the name with
409         the first character of the interface to avoid conflicts. */
410         stage->interface_blocks.insert(make_pair(iface.interface+iface.name, &iface));
411         if(!iface.instance_name.empty())
412                 stage->interface_blocks.insert(make_pair("_"+iface.instance_name, &iface));
413
414         SetForScope<string> set_iface(block_interface, iface.interface);
415         TraversingVisitor::visit(iface);
416 }
417
418
419 bool ExpressionResolver::is_scalar(BasicTypeDeclaration &type)
420 {
421         return (type.kind==BasicTypeDeclaration::INT || type.kind==BasicTypeDeclaration::FLOAT);
422 }
423
424 bool ExpressionResolver::is_vector_or_matrix(BasicTypeDeclaration &type)
425 {
426         return (type.kind==BasicTypeDeclaration::VECTOR || type.kind==BasicTypeDeclaration::MATRIX);
427 }
428
429 BasicTypeDeclaration *ExpressionResolver::get_element_type(BasicTypeDeclaration &type)
430 {
431         if(is_vector_or_matrix(type) || type.kind==BasicTypeDeclaration::ARRAY)
432         {
433                 BasicTypeDeclaration *basic_base = dynamic_cast<BasicTypeDeclaration *>(type.base_type);
434                 return (basic_base ? get_element_type(*basic_base) : 0);
435         }
436         else
437                 return &type;
438 }
439
440 bool ExpressionResolver::can_convert(BasicTypeDeclaration &from, BasicTypeDeclaration &to)
441 {
442         if(from.kind==BasicTypeDeclaration::INT && to.kind==BasicTypeDeclaration::FLOAT)
443                 return from.size<=to.size;
444         else if(from.kind!=to.kind)
445                 return false;
446         else if((from.kind==BasicTypeDeclaration::VECTOR || from.kind==BasicTypeDeclaration::MATRIX) && from.size==to.size)
447         {
448                 BasicTypeDeclaration *from_base = dynamic_cast<BasicTypeDeclaration *>(from.base_type);
449                 BasicTypeDeclaration *to_base = dynamic_cast<BasicTypeDeclaration *>(to.base_type);
450                 return (from_base && to_base && can_convert(*from_base, *to_base));
451         }
452         else
453                 return false;
454 }
455
456 ExpressionResolver::Compatibility ExpressionResolver::get_compatibility(BasicTypeDeclaration &left, BasicTypeDeclaration &right)
457 {
458         if(&left==&right)
459                 return SAME_TYPE;
460         else if(can_convert(left, right))
461                 return LEFT_CONVERTIBLE;
462         else if(can_convert(right, left))
463                 return RIGHT_CONVERTIBLE;
464         else
465                 return NOT_COMPATIBLE;
466 }
467
468 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration::Kind kind, unsigned size)
469 {
470         for(vector<BasicTypeDeclaration *>::const_iterator i=basic_types.begin(); i!=basic_types.end(); ++i)
471                 if((*i)->kind==kind && (*i)->size==size)
472                         return *i;
473         return 0;
474 }
475
476 BasicTypeDeclaration *ExpressionResolver::find_type(BasicTypeDeclaration &elem_type, BasicTypeDeclaration::Kind kind, unsigned size)
477 {
478         for(vector<BasicTypeDeclaration *>::const_iterator i=basic_types.begin(); i!=basic_types.end(); ++i)
479                 if(get_element_type(**i)==&elem_type && (*i)->kind==kind && (*i)->size==size)
480                         return *i;
481         return 0;
482 }
483
484 void ExpressionResolver::convert_to(RefPtr<Expression> &expr, BasicTypeDeclaration &type)
485 {
486         RefPtr<FunctionCall> call = new FunctionCall;
487         call->name = type.name;
488         call->constructor = true;
489         call->arguments.push_back(0);
490         call->arguments.back() = expr;
491         call->type = &type;
492         expr = call;
493 }
494
495 bool ExpressionResolver::convert_to_element(RefPtr<Expression> &expr, BasicTypeDeclaration &elem_type)
496 {
497         if(BasicTypeDeclaration *expr_type = dynamic_cast<BasicTypeDeclaration *>(expr->type))
498         {
499                 BasicTypeDeclaration *to_type = &elem_type;
500                 if(is_vector_or_matrix(*expr_type))
501                         to_type = find_type(elem_type, expr_type->kind, expr_type->size);
502                 if(to_type)
503                 {
504                         convert_to(expr, *to_type);
505                         return true;
506                 }
507         }
508
509         return false;
510 }
511
512 void ExpressionResolver::visit(Literal &literal)
513 {
514         if(literal.value.check_type<bool>())
515                 literal.type = find_type(BasicTypeDeclaration::BOOL, 1);
516         else if(literal.value.check_type<int>())
517                 literal.type = find_type(BasicTypeDeclaration::INT, 32);
518         else if(literal.value.check_type<float>())
519                 literal.type = find_type(BasicTypeDeclaration::FLOAT, 32);
520 }
521
522 void ExpressionResolver::visit(ParenthesizedExpression &parexpr)
523 {
524         TraversingVisitor::visit(parexpr);
525
526         parexpr.type = parexpr.expression->type;
527         parexpr.lvalue = parexpr.expression->lvalue;
528 }
529
530 void ExpressionResolver::visit(VariableReference &var)
531 {
532         if(var.declaration)
533                 var.type = var.declaration->type_declaration;
534         var.lvalue = true;
535 }
536
537 void ExpressionResolver::visit(InterfaceBlockReference &iface)
538 {
539         iface.lvalue = true;
540 }
541
542 void ExpressionResolver::visit(MemberAccess &memacc)
543 {
544         TraversingVisitor::visit(memacc);
545
546         if(memacc.declaration)
547                 memacc.type = memacc.declaration->type_declaration;
548         memacc.lvalue = memacc.left->lvalue;
549 }
550
551 void ExpressionResolver::visit(UnaryExpression &unary)
552 {
553         TraversingVisitor::visit(unary);
554
555         BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(unary.expression->type);
556         if(!basic)
557                 return;
558
559         char oper = unary.oper->token[0];
560         if(oper=='!')
561         {
562                 if(basic->kind==BasicTypeDeclaration::BOOL)
563                         unary.type = basic;
564         }
565         else if(oper=='~')
566         {
567                 if(basic->kind==BasicTypeDeclaration::INT)
568                         unary.type = basic;
569         }
570         else if(oper=='+' || oper=='-')
571         {
572                 BasicTypeDeclaration *elem = get_element_type(*basic);
573                 if(elem && is_scalar(*elem))
574                         unary.type = basic;
575         }
576         unary.lvalue = unary.expression->lvalue;
577 }
578
579 void ExpressionResolver::visit(BinaryExpression &binary)
580 {
581         TraversingVisitor::visit(binary);
582
583         /* Binary operators are only defined for basic types (not for image or
584         structure types). */
585         BasicTypeDeclaration *basic_left = dynamic_cast<BasicTypeDeclaration *>(binary.left->type);
586         BasicTypeDeclaration *basic_right = dynamic_cast<BasicTypeDeclaration *>(binary.right->type);
587         if(!basic_left || !basic_right)
588                 return;
589
590         binary.lvalue = false;
591
592         char oper = binary.oper->token[0];
593         if(oper=='[')
594         {
595                 /* Subscripting operates on vectors, matrices and arrays, and the right
596                 operand must be an integer. */
597                 if((!is_vector_or_matrix(*basic_left) && basic_left->kind!=BasicTypeDeclaration::ARRAY) || basic_right->kind!=BasicTypeDeclaration::INT)
598                         return;
599
600                 binary.type = basic_left->base_type;
601                 binary.lvalue = binary.left->lvalue;
602                 return;
603         }
604         else if(basic_left->kind==BasicTypeDeclaration::ARRAY || basic_right->kind==BasicTypeDeclaration::ARRAY)
605                 // No other binary operator can be used with arrays.
606                 return;
607
608         BasicTypeDeclaration *elem_left = get_element_type(*basic_left);
609         BasicTypeDeclaration *elem_right = get_element_type(*basic_right);
610         if(!elem_left || !elem_right)
611                 return;
612
613         Compatibility compat = get_compatibility(*basic_left, *basic_right);
614         Compatibility elem_compat = get_compatibility(*elem_left, *elem_right);
615         if(elem_compat==NOT_COMPATIBLE)
616                 return;
617
618         char oper2 = binary.oper->token[1];
619         if((oper=='<' && oper2!='<') || (oper=='>' && oper2!='>'))
620         {
621                 /* Relational operators compare two scalar integer or floating-point
622                 values. */
623                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right) || compat==NOT_COMPATIBLE)
624                         return;
625
626                 binary.type = find_type(BasicTypeDeclaration::BOOL, 1);
627         }
628         else if((oper=='=' || oper=='!') && oper2=='=')
629         {
630                 // Equality comparison can be done on any compatible types.
631                 if(compat==NOT_COMPATIBLE)
632                         return;
633
634                 binary.type = find_type(BasicTypeDeclaration::BOOL, 1);
635         }
636         else if(oper2=='&' || oper2=='|' || oper2=='^')
637         {
638                 // Logical operators can only be applied to booleans.
639                 if(basic_left->kind!=BasicTypeDeclaration::BOOL || basic_right->kind!=BasicTypeDeclaration::BOOL)
640                         return;
641
642                 binary.type = basic_left;
643         }
644         else if((oper=='&' || oper=='|' || oper=='^' || oper=='%') && !oper2)
645         {
646                 // Bitwise operators and modulo can only be applied to integers.
647                 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
648                         return;
649
650                 binary.type = (compat==LEFT_CONVERTIBLE ? basic_right : basic_left);
651         }
652         else if((oper=='<' || oper=='>') && oper2==oper)
653         {
654                 // Shifts only apply to integers.
655                 if(basic_left->kind!=BasicTypeDeclaration::INT || basic_right->kind!=BasicTypeDeclaration::INT)
656                         return;
657
658                 binary.type = basic_left;
659         }
660         else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
661         {
662                 // Arithmetic operators require scalar elements.
663                 if(!is_scalar(*elem_left) || !is_scalar(*elem_right))
664                         return;
665
666                 if(oper=='*' && is_vector_or_matrix(*basic_left) && is_vector_or_matrix(*basic_right) &&
667                         (basic_left->kind==BasicTypeDeclaration::MATRIX || basic_right->kind==BasicTypeDeclaration::MATRIX))
668                 {
669                         /* Multiplication has special rules when at least one operand is a
670                         matrix and the other is a vector or a matrix. */
671                         unsigned left_columns = basic_left->size&0xFFFF;
672                         unsigned right_rows = basic_right->size;
673                         if(basic_right->kind==BasicTypeDeclaration::MATRIX)
674                                 right_rows >>= 16;
675                         if(left_columns!=right_rows)
676                                 return;
677
678                         BasicTypeDeclaration *elem_result = (elem_compat==LEFT_CONVERTIBLE ? elem_right : elem_left);
679
680                         if(basic_left->kind==BasicTypeDeclaration::VECTOR)
681                                 binary.type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_right->size&0xFFFF);
682                         else if(basic_right->kind==BasicTypeDeclaration::VECTOR)
683                                 binary.type = find_type(*elem_result, BasicTypeDeclaration::VECTOR, basic_left->size>>16);
684                         else
685                                 binary.type = find_type(*elem_result, BasicTypeDeclaration::MATRIX, (basic_left->size&0xFFFF0000)|(basic_right->size&0xFFFF));
686                 }
687                 else if(compat==NOT_COMPATIBLE)
688                 {
689                         // Arithmetic between scalars and matrices or vectors is supported.
690                         if(is_scalar(*basic_left) && is_vector_or_matrix(*basic_right))
691                                 binary.type = (elem_compat==RIGHT_CONVERTIBLE ? find_type(*elem_left, basic_right->kind, basic_right->size) : basic_right);
692                         else if(is_vector_or_matrix(*basic_left) && is_scalar(*basic_right))
693                                 binary.type = (elem_compat==LEFT_CONVERTIBLE ? find_type(*elem_right, basic_left->kind, basic_left->size) : basic_left);
694                         else
695                                 return;
696                 }
697                 else if(compat==LEFT_CONVERTIBLE)
698                         binary.type = basic_right;
699                 else
700                         binary.type = basic_left;
701         }
702         else
703                 return;
704
705         bool converted = true;
706         if(compat==LEFT_CONVERTIBLE)
707                 convert_to(binary.left, *basic_right);
708         else if(compat==RIGHT_CONVERTIBLE)
709                 convert_to(binary.right, *basic_left);
710         else if(elem_compat==LEFT_CONVERTIBLE)
711                 converted = convert_to_element(binary.left, *elem_right);
712         else if(elem_compat==RIGHT_CONVERTIBLE)
713                 converted = convert_to_element(binary.right, *elem_left);
714
715         if(!converted)
716                 binary.type = 0;
717 }
718
719 void ExpressionResolver::visit(Assignment &assign)
720 {
721         TraversingVisitor::visit(assign);
722         assign.type = assign.left->type;
723         assign.lvalue = true;
724 }
725
726 void ExpressionResolver::visit(FunctionCall &call)
727 {
728         TraversingVisitor::visit(call);
729
730         if(call.declaration)
731                 call.type = call.declaration->return_type_declaration;
732         else if(call.constructor)
733         {
734                 map<string, TypeDeclaration *>::const_iterator i=stage->types.find(call.name);
735                 call.type = (i!=stage->types.end() ? i->second : 0);
736         }
737         call.lvalue = false;
738 }
739
740 void ExpressionResolver::visit(BasicTypeDeclaration &type)
741 {
742         basic_types.push_back(&type);
743 }
744
745 void ExpressionResolver::visit(VariableDeclaration &var)
746 {
747         TraversingVisitor::visit(var);
748         if(!var.init_expression)
749                 return;
750
751         BasicTypeDeclaration *var_basic = dynamic_cast<BasicTypeDeclaration *>(var.type_declaration);
752         BasicTypeDeclaration *init_basic = dynamic_cast<BasicTypeDeclaration *>(var.init_expression->type);
753         if(!var_basic || !init_basic)
754                 return;
755
756         Compatibility compat = get_compatibility(*var_basic, *init_basic);
757         if(compat==RIGHT_CONVERTIBLE)
758                 convert_to(var.init_expression, *var_basic);
759 }
760
761
762 void FunctionResolver::apply(Stage &s)
763 {
764         stage = &s;
765         s.functions.clear();
766         s.content.visit(*this);
767 }
768
769 void FunctionResolver::visit(FunctionCall &call)
770 {
771         map<string, FunctionDeclaration *>::iterator i = stage->functions.find(call.name);
772         if(i!=stage->functions.end())
773                 call.declaration = i->second;
774
775         TraversingVisitor::visit(call);
776 }
777
778 void FunctionResolver::visit(FunctionDeclaration &func)
779 {
780         FunctionDeclaration *&stage_decl = stage->functions[func.name];
781         vector<FunctionDeclaration *> &decls = declarations[func.name];
782         if(func.definition==&func)
783         {
784                 stage_decl = &func;
785
786                 // Set all previous declarations to use this definition.
787                 for(vector<FunctionDeclaration *>::iterator i=decls.begin(); i!=decls.end(); ++i)
788                 {
789                         (*i)->definition = func.definition;
790                         (*i)->body.body.clear();
791                 }
792         }
793         else
794         {
795                 func.definition = 0;
796                 if(!stage_decl)
797                         stage_decl = &func;
798                 else
799                         func.definition = stage_decl->definition;
800         }
801         decls.push_back(&func);
802
803         TraversingVisitor::visit(func);
804 }
805
806
807 InterfaceGenerator::InterfaceGenerator():
808         stage(0),
809         function_scope(false),
810         iface_block(0),
811         copy_block(false),
812         iface_target_block(0)
813 { }
814
815 string InterfaceGenerator::get_out_prefix(Stage::Type type)
816 {
817         if(type==Stage::VERTEX)
818                 return "_vs_out_";
819         else if(type==Stage::GEOMETRY)
820                 return "_gs_out_";
821         else
822                 return string();
823 }
824
825 void InterfaceGenerator::apply(Stage &s)
826 {
827         stage = &s;
828         iface_target_block = &stage->content;
829         if(stage->previous)
830                 in_prefix = get_out_prefix(stage->previous->type);
831         out_prefix = get_out_prefix(stage->type);
832         s.content.visit(*this);
833         NodeRemover().apply(s, nodes_to_remove);
834 }
835
836 void InterfaceGenerator::visit(Block &block)
837 {
838         SetForScope<Block *> set_block(current_block, &block);
839         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
840         {
841                 assignment_insert_point = i;
842                 if(&block==&stage->content)
843                         iface_insert_point = i;
844
845                 (*i)->visit(*this);
846         }
847 }
848
849 string InterfaceGenerator::change_prefix(const string &name, const string &prefix) const
850 {
851         unsigned offset = (name.compare(0, in_prefix.size(), in_prefix) ? 0 : in_prefix.size());
852         return prefix+name.substr(offset);
853 }
854
855 VariableDeclaration *InterfaceGenerator::generate_interface(VariableDeclaration &var, const string &iface, const string &name)
856 {
857         if(stage->content.variables.count(name))
858                 return 0;
859
860         VariableDeclaration* iface_var = new VariableDeclaration;
861         iface_var->sampling = var.sampling;
862         iface_var->interface = iface;
863         iface_var->type = var.type;
864         iface_var->name = name;
865         /* Geometry shader inputs are always arrays.  But if we're bringing in an
866         entire block, the array is on the block and not individual variables. */
867         if(stage->type==Stage::GEOMETRY && !copy_block)
868                 iface_var->array = ((var.array && var.interface!="in") || iface=="in");
869         else
870                 iface_var->array = var.array;
871         if(iface_var->array)
872                 iface_var->array_size = var.array_size;
873         if(iface=="in")
874         {
875                 iface_var->layout = var.layout;
876                 iface_var->linked_declaration = &var;
877                 var.linked_declaration = iface_var;
878         }
879
880         iface_target_block->body.insert(iface_insert_point, iface_var);
881         iface_target_block->variables.insert(make_pair(name, iface_var));
882
883         return iface_var;
884 }
885
886 InterfaceBlock *InterfaceGenerator::generate_interface(InterfaceBlock &out_block)
887 {
888         if(stage->interface_blocks.count("in"+out_block.name))
889                 return 0;
890
891         InterfaceBlock *in_block = new InterfaceBlock;
892         in_block->interface = "in";
893         in_block->name = out_block.name;
894         in_block->instance_name = out_block.instance_name;
895         if(stage->type==Stage::GEOMETRY)
896                 in_block->array = true;
897         else
898                 in_block->array = out_block.array;
899         in_block->linked_block = &out_block;
900         out_block.linked_block = in_block;
901
902         {
903                 SetFlag set_copy(copy_block, true);
904                 SetForScope<Block *> set_target(iface_target_block, &in_block->members);
905                 SetForScope<NodeList<Statement>::iterator> set_ins_pt(iface_insert_point, in_block->members.body.end());
906                 out_block.members.visit(*this);
907         }
908
909         iface_target_block->body.insert(iface_insert_point, in_block);
910         stage->interface_blocks.insert(make_pair("in"+in_block->name, in_block));
911         if(!in_block->instance_name.empty())
912                 stage->interface_blocks.insert(make_pair("_"+in_block->instance_name, in_block));
913
914         SetFlag set_scope(function_scope, false);
915         SetForScope<Block *> set_block(current_block, &stage->content);
916         in_block->visit(*this);
917
918         return in_block;
919 }
920
921 ExpressionStatement &InterfaceGenerator::insert_assignment(const string &left, Expression *right)
922 {
923         Assignment *assign = new Assignment;
924         VariableReference *ref = new VariableReference;
925         ref->name = left;
926         assign->left = ref;
927         assign->oper = &Operator::get_operator("=", Operator::BINARY);
928         assign->right = right;
929
930         ExpressionStatement *stmt = new ExpressionStatement;
931         stmt->expression = assign;
932         current_block->body.insert(assignment_insert_point, stmt);
933         stmt->visit(*this);
934
935         return *stmt;
936 }
937
938 void InterfaceGenerator::visit(VariableReference &var)
939 {
940         if(var.declaration || !stage->previous)
941                 return;
942         /* Don't pull a variable from previous stage if we just generated an output
943         interface in this stage */
944         if(stage->content.variables.count(var.name))
945                 return;
946
947         const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
948         map<string, VariableDeclaration *>::const_iterator i = prev_vars.find(var.name);
949         if(i==prev_vars.end() || i->second->interface!="out")
950                 i = prev_vars.find(in_prefix+var.name);
951         if(i!=prev_vars.end() && i->second->interface=="out")
952         {
953                 generate_interface(*i->second, "in", i->second->name);
954                 var.name = i->second->name;
955                 return;
956         }
957
958         const map<string, InterfaceBlock *> &prev_blocks = stage->previous->interface_blocks;
959         map<string, InterfaceBlock *>::const_iterator j = prev_blocks.find("_"+var.name);
960         if(j!=prev_blocks.end() && j->second->interface=="out")
961         {
962                 generate_interface(*j->second);
963                 /* Let VariableResolver convert the variable reference into an interface
964                 block reference. */
965                 return;
966         }
967
968         for(j=prev_blocks.begin(); j!=prev_blocks.end(); ++j)
969                 if(j->second->instance_name.empty())
970                 {
971                         i = j->second->members.variables.find(var.name);
972                         if(i!=j->second->members.variables.end())
973                         {
974                                 generate_interface(*j->second);
975                                 return;
976                         }
977                 }
978 }
979
980 void InterfaceGenerator::visit(VariableDeclaration &var)
981 {
982         if(copy_block)
983         {
984                 generate_interface(var, "in", var.name);
985                 return;
986         }
987
988         if(iface_block)
989         {
990                 if(iface_block->linked_block)
991                 {
992                         // Link all variables to their counterparts in the linked block.
993                         const map<string, VariableDeclaration *> &linked_vars = iface_block->linked_block->members.variables;
994                         map<string, VariableDeclaration *>::const_iterator i = linked_vars.find(var.name);
995                         if(i!=linked_vars.end())
996                         {
997                                 var.linked_declaration = i->second;
998                                 var.linked_declaration->linked_declaration = &var;
999                         }
1000                 }
1001                 return;
1002         }
1003
1004         if(var.interface=="out")
1005         {
1006                 /* For output variables in function scope, generate a global interface
1007                 and replace the local declaration with an assignment. */
1008                 VariableDeclaration *out_var = 0;
1009                 if(function_scope && (out_var=generate_interface(var, "out", var.name)))
1010                 {
1011                         out_var->source = var.source;
1012                         out_var->line = var.line;
1013                         nodes_to_remove.insert(&var);
1014                         if(var.init_expression)
1015                         {
1016                                 ExpressionStatement &stmt = insert_assignment(var.name, var.init_expression->clone());
1017                                 stmt.source = var.source;
1018                                 stmt.line = var.line;
1019                                 return;
1020                         }
1021                 }
1022         }
1023         else if(var.interface=="in")
1024         {
1025                 /* Try to link input variables in global scope with output variables from
1026                 previous stage. */
1027                 if(current_block==&stage->content && !var.linked_declaration && stage->previous)
1028                 {
1029                         const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
1030                         map<string, VariableDeclaration *>::const_iterator i = prev_vars.find(var.name);
1031                         if(i!=prev_vars.end() && i->second->interface=="out")
1032                         {
1033                                 var.linked_declaration = i->second;
1034                                 i->second->linked_declaration = &var;
1035                         }
1036                 }
1037         }
1038
1039         TraversingVisitor::visit(var);
1040 }
1041
1042 void InterfaceGenerator::visit(InterfaceBlock &iface)
1043 {
1044         if(iface.interface=="in")
1045         {
1046                 /* Try to link input blocks with output blocks sharing the same block
1047                 name from previous stage. */
1048                 if(!iface.linked_block && stage->previous)
1049                 {
1050                         const map<string, InterfaceBlock *> &prev_blocks = stage->previous->interface_blocks;
1051                         map<string, InterfaceBlock *>::const_iterator i = prev_blocks.find("out"+iface.name);
1052                         if(i!=prev_blocks.end())
1053                         {
1054                                 iface.linked_block = i->second;
1055                                 i->second->linked_block = &iface;
1056                         }
1057                 }
1058         }
1059
1060         SetForScope<InterfaceBlock *> set_iface(iface_block, &iface);
1061         TraversingVisitor::visit(iface);
1062 }
1063
1064 void InterfaceGenerator::visit(FunctionDeclaration &func)
1065 {
1066         SetFlag set_scope(function_scope, true);
1067         // Skip parameters because they're not useful here
1068         func.body.visit(*this);
1069 }
1070
1071 void InterfaceGenerator::visit(Passthrough &pass)
1072 {
1073         vector<VariableDeclaration *> pass_vars;
1074
1075         // Pass through all input variables of this stage.
1076         for(map<string, VariableDeclaration *>::const_iterator i=stage->content.variables.begin(); i!=stage->content.variables.end(); ++i)
1077                 if(i->second->interface=="in")
1078                         pass_vars.push_back(i->second);
1079
1080         if(stage->previous)
1081         {
1082                 const map<string, VariableDeclaration *> &prev_vars = stage->previous->content.variables;
1083                 for(map<string, VariableDeclaration *>::const_iterator i=prev_vars.begin(); i!=prev_vars.end(); ++i)
1084                 {
1085                         if(i->second->interface!="out")
1086                                 continue;
1087
1088                         /* Pass through output variables from the previous stage, but only
1089                         those which are not already linked to an input here. */
1090                         if(!i->second->linked_declaration && generate_interface(*i->second, "in", i->second->name))
1091                                 pass_vars.push_back(i->second);
1092                 }
1093         }
1094
1095         if(stage->type==Stage::GEOMETRY)
1096         {
1097                 /* Special case for geometry shader: copy gl_Position from input to
1098                 output. */
1099                 InterfaceBlockReference *ref = new InterfaceBlockReference;
1100                 ref->name = "gl_in";
1101
1102                 BinaryExpression *subscript = new BinaryExpression;
1103                 subscript->left = ref;
1104                 subscript->oper = &Operator::get_operator("[", Operator::BINARY);
1105                 subscript->right = pass.subscript;
1106
1107                 MemberAccess *memacc = new MemberAccess;
1108                 memacc->left = subscript;
1109                 memacc->member = "gl_Position";
1110
1111                 insert_assignment("gl_Position", memacc);
1112         }
1113
1114         for(vector<VariableDeclaration *>::const_iterator i=pass_vars.begin(); i!=pass_vars.end(); ++i)
1115         {
1116                 string out_name = change_prefix((*i)->name, out_prefix);
1117                 generate_interface(**i, "out", out_name);
1118
1119                 VariableReference *ref = new VariableReference;
1120                 ref->name = (*i)->name;
1121                 if(pass.subscript)
1122                 {
1123                         BinaryExpression *subscript = new BinaryExpression;
1124                         subscript->left = ref;
1125                         subscript->oper = &Operator::get_operator("[", Operator::BINARY);
1126                         subscript->right = pass.subscript;
1127                         insert_assignment(out_name, subscript);
1128                 }
1129                 else
1130                         insert_assignment(out_name, ref);
1131         }
1132
1133         nodes_to_remove.insert(&pass);
1134 }
1135
1136 } // namespace SL
1137 } // namespace GL
1138 } // namespace Msp