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