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