]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/optimize.cpp
Copy the location when moving output declarations out of functions
[libs/gl.git] / source / glsl / optimize.cpp
1 #include <msp/core/raii.h>
2 #include <msp/strings/format.h>
3 #include "optimize.h"
4
5 using namespace std;
6
7 namespace Msp {
8 namespace GL {
9 namespace SL {
10
11 InlineableFunctionLocator::InlineableFunctionLocator():
12         current_function(0),
13         return_count(0)
14 { }
15
16 void InlineableFunctionLocator::visit(FunctionCall &call)
17 {
18         FunctionDeclaration *def = call.declaration;
19         if(def)
20                 def = def->definition;
21
22         if(def)
23         {
24                 unsigned &count = refcounts[def];
25                 ++count;
26                 /* Don't inline functions which are called more than once or are called
27                 recursively. */
28                 if(count>1 || def==current_function)
29                         inlineable.erase(def);
30         }
31
32         TraversingVisitor::visit(call);
33 }
34
35 void InlineableFunctionLocator::visit(FunctionDeclaration &func)
36 {
37         unsigned &count = refcounts[func.definition];
38         if(count<=1 && func.parameters.empty())
39                 inlineable.insert(func.definition);
40
41         SetForScope<FunctionDeclaration *> set(current_function, &func);
42         return_count = 0;
43         TraversingVisitor::visit(func);
44 }
45
46 void InlineableFunctionLocator::visit(Conditional &cond)
47 {
48         TraversingVisitor::visit(cond);
49         inlineable.erase(current_function);
50 }
51
52 void InlineableFunctionLocator::visit(Iteration &iter)
53 {
54         TraversingVisitor::visit(iter);
55         inlineable.erase(current_function);
56 }
57
58 void InlineableFunctionLocator::visit(Return &ret)
59 {
60         TraversingVisitor::visit(ret);
61         if(return_count)
62                 inlineable.erase(current_function);
63         ++return_count;
64 }
65
66
67 InlineContentInjector::InlineContentInjector():
68         source_func(0),
69         remap_names(false),
70         deps_only(false)
71 { }
72
73 const string &InlineContentInjector::apply(Stage &stage, FunctionDeclaration &target_func, Block &tgt_blk, const NodeList<Statement>::iterator &ins_pt, FunctionDeclaration &src)
74 {
75         target_block = &tgt_blk;
76         source_func = &src;
77         for(NodeList<Statement>::iterator i=src.body.body.begin(); i!=src.body.body.end(); ++i)
78         {
79                 r_inlined_statement = 0;
80                 (*i)->visit(*this);
81                 if(!r_inlined_statement)
82                         r_inlined_statement = (*i)->clone();
83
84                 SetFlag set_remap(remap_names);
85                 r_inlined_statement->visit(*this);
86                 tgt_blk.body.insert(ins_pt, r_inlined_statement);
87         }
88
89         NodeReorderer().apply(stage, target_func, dependencies);
90
91         return r_result_name;
92 }
93
94 string InlineContentInjector::create_unused_name(const string &base, bool always_prefix)
95 {
96         string result = base;
97         if(always_prefix || target_block->variables.count(result))
98                 result = format("_%s_%s", source_func->name, base);
99         unsigned initial_size = result.size();
100         for(unsigned i=1; target_block->variables.count(result); ++i)
101         {
102                 result.erase(initial_size);
103                 result += format("_%d", i);
104         }
105         return result;
106 }
107
108 void InlineContentInjector::visit(VariableReference &var)
109 {
110         if(remap_names)
111         {
112                 map<string, VariableDeclaration *>::const_iterator i = variable_map.find(var.name);
113                 if(i!=variable_map.end())
114                         var.name = i->second->name;
115         }
116         else if(var.declaration)
117         {
118                 SetFlag set_deps(deps_only);
119                 dependencies.insert(var.declaration);
120                 var.declaration->visit(*this);
121         }
122 }
123
124 void InlineContentInjector::visit(InterfaceBlockReference &iface)
125 {
126         if(!remap_names && iface.declaration)
127         {
128                 SetFlag set_deps(deps_only);
129                 dependencies.insert(iface.declaration);
130                 iface.declaration->visit(*this);
131         }
132 }
133
134 void InlineContentInjector::visit(FunctionCall &call)
135 {
136         if(!remap_names && call.declaration)
137                 dependencies.insert(call.declaration);
138         TraversingVisitor::visit(call);
139 }
140
141 void InlineContentInjector::visit(VariableDeclaration &var)
142 {
143         TraversingVisitor::visit(var);
144
145         if(var.type_declaration)
146         {
147                 SetFlag set_deps(deps_only);
148                 dependencies.insert(var.type_declaration);
149                 var.type_declaration->visit(*this);
150         }
151
152         if(!remap_names && !deps_only)
153         {
154                 RefPtr<VariableDeclaration> inlined_var = var.clone();
155                 inlined_var->name = create_unused_name(var.name, false);
156                 r_inlined_statement = inlined_var;
157
158                 variable_map[var.name] = inlined_var.get();
159         }
160 }
161
162 void InlineContentInjector::visit(Return &ret)
163 {
164         TraversingVisitor::visit(ret);
165
166         if(ret.expression)
167         {
168                 /* Create a new variable to hold the return value of the inlined
169                 function. */
170                 r_result_name = create_unused_name("return", true);
171                 RefPtr<VariableDeclaration> var = new VariableDeclaration;
172                 var->source = ret.source;
173                 var->line = ret.line;
174                 var->type = source_func->return_type;
175                 var->name = r_result_name;
176                 var->init_expression = ret.expression->clone();
177                 r_inlined_statement = var;
178         }
179 }
180
181
182 FunctionInliner::FunctionInliner():
183         current_function(0),
184         r_any_inlined(false)
185 { }
186
187 bool FunctionInliner::apply(Stage &s)
188 {
189         stage = &s;
190         inlineable = InlineableFunctionLocator().apply(s);
191         r_any_inlined = false;
192         s.content.visit(*this);
193         return r_any_inlined;
194 }
195
196 void FunctionInliner::visit_and_inline(RefPtr<Expression> &ptr)
197 {
198         r_inline_result = 0;
199         ptr->visit(*this);
200         if(r_inline_result)
201         {
202                 ptr = r_inline_result;
203                 r_any_inlined = true;
204         }
205 }
206
207 void FunctionInliner::visit(Block &block)
208 {
209         SetForScope<Block *> set_block(current_block, &block);
210         SetForScope<NodeList<Statement>::iterator> save_insert_point(insert_point, block.body.begin());
211         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
212         {
213                 insert_point = i;
214                 (*i)->visit(*this);
215         }
216 }
217
218 void FunctionInliner::visit(UnaryExpression &unary)
219 {
220         visit_and_inline(unary.expression);
221         r_inline_result = 0;
222 }
223
224 void FunctionInliner::visit(BinaryExpression &binary)
225 {
226         visit_and_inline(binary.left);
227         visit_and_inline(binary.right);
228         r_inline_result = 0;
229 }
230
231 void FunctionInliner::visit(MemberAccess &memacc)
232 {
233         visit_and_inline(memacc.left);
234         r_inline_result = 0;
235 }
236
237 void FunctionInliner::visit(FunctionCall &call)
238 {
239         for(NodeArray<Expression>::iterator i=call.arguments.begin(); i!=call.arguments.end(); ++i)
240                 visit_and_inline(*i);
241
242         FunctionDeclaration *def = call.declaration;
243         if(def)
244                 def = def->definition;
245
246         if(def && inlineable.count(def))
247         {
248                 string result_name = InlineContentInjector().apply(*stage, *current_function, *current_block, insert_point, *def);
249
250                 // This will later get removed by UnusedVariableRemover.
251                 if(result_name.empty())
252                         result_name = "msp_unused_from_inline";
253
254                 RefPtr<VariableReference> ref = new VariableReference;
255                 ref->name = result_name;
256                 r_inline_result = ref;
257
258                 /* Inlined variables need to be resolved before this function can be
259                 inlined further. */
260                 inlineable.erase(current_function);
261         }
262         else
263                 r_inline_result = 0;
264 }
265
266 void FunctionInliner::visit(ExpressionStatement &expr)
267 {
268         visit_and_inline(expr.expression);
269 }
270
271 void FunctionInliner::visit(VariableDeclaration &var)
272 {
273         if(var.init_expression)
274                 visit_and_inline(var.init_expression);
275         r_inline_result = 0;
276 }
277
278 void FunctionInliner::visit(FunctionDeclaration &func)
279 {
280         SetForScope<FunctionDeclaration *> set_func(current_function, &func);
281         TraversingVisitor::visit(func);
282 }
283
284 void FunctionInliner::visit(Conditional &cond)
285 {
286         visit_and_inline(cond.condition);
287         cond.body.visit(*this);
288 }
289
290 void FunctionInliner::visit(Iteration &iter)
291 {
292         /* Visit the initialization statement before entering the loop body so the
293         inlined statements get inserted outside. */
294         if(iter.init_statement)
295                 iter.init_statement->visit(*this);
296
297         SetForScope<Block *> set_block(current_block, &iter.body);
298         /* Skip the condition and loop expression parts because they're not properly
299         inside the body block.  Inlining anything into them will require a more
300         comprehensive transformation. */
301         iter.body.visit(*this);
302 }
303
304 void FunctionInliner::visit(Return &ret)
305 {
306         if(ret.expression)
307                 visit_and_inline(ret.expression);
308 }
309
310
311 ExpressionInliner::ExpressionInfo::ExpressionInfo():
312         expression(0),
313         assign_scope(0),
314         inline_point(0),
315         inner_oper(0),
316         outer_oper(0),
317         inline_on_rhs(false),
318         trivial(false),
319         available(true)
320 { }
321
322
323 ExpressionInliner::ExpressionInliner():
324         r_ref_info(0),
325         r_any_inlined(false),
326         r_trivial(false),
327         mutating(false),
328         iteration_init(false),
329         iteration_body(0),
330         r_oper(0)
331 { }
332
333 bool ExpressionInliner::apply(Stage &s)
334 {
335         s.content.visit(*this);
336         return r_any_inlined;
337 }
338
339 void ExpressionInliner::visit_and_record(RefPtr<Expression> &ptr, const Operator *outer_oper, bool on_rhs)
340 {
341         r_ref_info = 0;
342         ptr->visit(*this);
343         if(r_ref_info && r_ref_info->expression && r_ref_info->available)
344         {
345                 if(iteration_body && !r_ref_info->trivial)
346                 {
347                         /* Don't inline non-trivial expressions which were assigned outside
348                         an iteration statement.  The iteration may run multiple times, which
349                         would cause the expression to also be evaluated multiple times. */
350                         Block *i = r_ref_info->assign_scope;
351                         for(; (i && i!=iteration_body); i=i->parent) ;
352                         if(!i)
353                                 return;
354                 }
355
356                 r_ref_info->outer_oper = outer_oper;
357                 if(r_ref_info->trivial)
358                         inline_expression(*r_ref_info->expression, ptr, outer_oper, r_ref_info->inner_oper, on_rhs);
359                 else
360                 {
361                         /* Record the inline point for a non-trivial expression but don't
362                         inline it yet.  It might turn out it shouldn't be inlined after all. */
363                         r_ref_info->inline_point = &ptr;
364                         r_ref_info->inline_on_rhs = on_rhs;
365                 }
366         }
367 }
368
369 void ExpressionInliner::inline_expression(Expression &expr, RefPtr<Expression> &ptr, const Operator *outer_oper, const Operator *inner_oper, bool on_rhs)
370 {
371         unsigned outer_precedence = (outer_oper ? outer_oper->precedence : 20);
372         unsigned inner_precedence = (inner_oper ? inner_oper->precedence : 0);
373
374         bool needs_parentheses = (inner_precedence>=outer_precedence);
375         if(inner_oper && inner_oper==outer_oper)
376                 // Omit parentheses if the operator's natural grouping works out.
377                 needs_parentheses = (inner_oper->assoc!=Operator::ASSOCIATIVE && on_rhs!=(inner_oper->assoc==Operator::RIGHT_TO_LEFT));
378
379         if(needs_parentheses)
380         {
381                 RefPtr<ParenthesizedExpression> parexpr = new ParenthesizedExpression;
382                 parexpr->expression = expr.clone();
383                 ptr = parexpr;
384         }
385         else
386                 ptr = expr.clone();
387
388         r_any_inlined = true;
389 }
390
391 void ExpressionInliner::visit(Block &block)
392 {
393         TraversingVisitor::visit(block);
394
395         for(map<VariableDeclaration *, ExpressionInfo>::iterator i=expressions.begin(); i!=expressions.end(); )
396         {
397                 map<string, VariableDeclaration *>::iterator j = block.variables.find(i->first->name);
398                 if(j!=block.variables.end() && j->second==i->first)
399                 {
400                         if(i->second.expression && i->second.inline_point)
401                                 inline_expression(*i->second.expression, *i->second.inline_point, i->second.outer_oper, i->second.inner_oper, i->second.inline_on_rhs);
402
403                         expressions.erase(i++);
404                 }
405                 else
406                 {
407                         /* The expression was assigned in this block and may depend on local
408                         variables of the block.  If this is a conditionally executed block,
409                         the assignment might not always happen.  Mark the expression as not
410                         available to any outer blocks. */
411                         if(i->second.assign_scope==&block)
412                                 i->second.available = false;
413
414                         ++i;
415                 }
416         }
417 }
418
419 void ExpressionInliner::visit(VariableReference &var)
420 {
421         if(var.declaration)
422         {
423                 map<VariableDeclaration *, ExpressionInfo>::iterator i = expressions.find(var.declaration);
424                 if(i!=expressions.end())
425                 {
426                         /* If a non-trivial expression is referenced multiple times, don't
427                         inline it. */
428                         if(i->second.inline_point && !i->second.trivial)
429                                 i->second.expression = 0;
430                         /* Mutating expressions are analogous to self-referencing assignments
431                         and prevent inlining. */
432                         if(mutating)
433                                 i->second.expression = 0;
434                         r_ref_info = &i->second;
435                 }
436         }
437 }
438
439 void ExpressionInliner::visit(MemberAccess &memacc)
440 {
441         visit_and_record(memacc.left, memacc.oper, false);
442         r_ref_info = 0;
443         r_oper = memacc.oper;
444         r_trivial = false;
445 }
446
447 void ExpressionInliner::visit(UnaryExpression &unary)
448 {
449         SetFlag set_target(mutating, mutating || unary.oper->token[1]=='+' || unary.oper->token[1]=='-');
450         visit_and_record(unary.expression, unary.oper, false);
451         r_ref_info = 0;
452         r_oper = unary.oper;
453         r_trivial = false;
454 }
455
456 void ExpressionInliner::visit(BinaryExpression &binary)
457 {
458         visit_and_record(binary.left, binary.oper, false);
459         {
460                 SetFlag clear_target(mutating, false);
461                 visit_and_record(binary.right, binary.oper, true);
462         }
463         r_ref_info = 0;
464         r_oper = binary.oper;
465         r_trivial = false;
466 }
467
468 void ExpressionInliner::visit(Assignment &assign)
469 {
470         {
471                 SetFlag set_target(mutating);
472                 visit_and_record(assign.left, assign.oper, false);
473         }
474         r_oper = 0;
475         visit_and_record(assign.right, assign.oper, true);
476
477         if(assign.target_declaration)
478         {
479                 map<VariableDeclaration *, ExpressionInfo>::iterator i = expressions.find(assign.target_declaration);
480                 if(i!=expressions.end())
481                 {
482                         /* Self-referencing assignments can't be inlined without additional
483                         work.  Just clear any previous expression. */
484                         i->second.expression = (assign.self_referencing ? 0 : assign.right.get());
485                         i->second.assign_scope = current_block;
486                         i->second.inline_point = 0;
487                         i->second.inner_oper = r_oper;
488                         i->second.available = true;
489                 }
490         }
491
492         r_ref_info = 0;
493         r_oper = assign.oper;
494         r_trivial = false;
495 }
496
497 void ExpressionInliner::visit(FunctionCall &call)
498 {
499         for(NodeArray<Expression>::iterator i=call.arguments.begin(); i!=call.arguments.end(); ++i)
500                 visit_and_record(*i, 0, false);
501         r_ref_info = 0;
502         r_oper = 0;
503         r_trivial = false;
504 }
505
506 void ExpressionInliner::visit(VariableDeclaration &var)
507 {
508         r_oper = 0;
509         r_trivial = true;
510         if(var.init_expression)
511                 visit_and_record(var.init_expression, 0, false);
512
513         bool constant = var.constant;
514         if(constant && var.layout)
515         {
516                 for(vector<Layout::Qualifier>::const_iterator i=var.layout->qualifiers.begin(); (constant && i!=var.layout->qualifiers.end()); ++i)
517                         constant = (i->name!="constant_id");
518         }
519
520         /* Only inline global variables if they're constant and have trivial
521         initializers.  Non-constant variables could change in ways which are hard to
522         analyze and non-trivial expressions could be expensive to inline.  */
523         if((current_block->parent || (constant && r_trivial)) && var.interface.empty())
524         {
525                 ExpressionInfo &info = expressions[&var];
526                 /* Assume variables declared in an iteration initialization statement
527                 will have their values change throughout the iteration. */
528                 info.expression = (iteration_init ? 0 : var.init_expression.get());
529                 info.assign_scope = current_block;
530                 info.inner_oper = r_oper;
531                 info.trivial = r_trivial;
532         }
533 }
534
535 void ExpressionInliner::visit(Conditional &cond)
536 {
537         visit_and_record(cond.condition, 0, false);
538         cond.body.visit(*this);
539 }
540
541 void ExpressionInliner::visit(Iteration &iter)
542 {
543         SetForScope<Block *> set_block(current_block, &iter.body);
544         if(iter.init_statement)
545         {
546                 SetFlag set_init(iteration_init);
547                 iter.init_statement->visit(*this);
548         }
549
550         SetForScope<Block *> set_body(iteration_body, &iter.body);
551         if(iter.condition)
552                 iter.condition->visit(*this);
553         iter.body.visit(*this);
554         if(iter.loop_expression)
555                 iter.loop_expression->visit(*this);
556 }
557
558 void ExpressionInliner::visit(Return &ret)
559 {
560         if(ret.expression)
561                 visit_and_record(ret.expression, 0, false);
562 }
563
564
565 void ConstantConditionEliminator::apply(Stage &stage)
566 {
567         stage.content.visit(*this);
568         NodeRemover().apply(stage, nodes_to_remove);
569 }
570
571 void ConstantConditionEliminator::visit(Block &block)
572 {
573         SetForScope<Block *> set_block(current_block, &block);
574         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
575         {
576                 insert_point = i;
577                 (*i)->visit(*this);
578         }
579 }
580
581 void ConstantConditionEliminator::visit(Conditional &cond)
582 {
583         ExpressionEvaluator eval;
584         cond.condition->visit(eval);
585         if(eval.is_result_valid())
586         {
587                 Block &block = (eval.get_result() ? cond.body : cond.else_body);
588                 current_block->body.splice(insert_point, block.body);
589                 nodes_to_remove.insert(&cond);
590                 return;
591         }
592
593         TraversingVisitor::visit(cond);
594 }
595
596 void ConstantConditionEliminator::visit(Iteration &iter)
597 {
598         if(iter.condition)
599         {
600                 /* If the loop condition is always false on the first iteration, the
601                 entire loop can be removed */
602                 ExpressionEvaluator::ValueMap values;
603                 if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(iter.init_statement.get()))
604                         values[var] = var->init_expression.get();
605                 ExpressionEvaluator eval(values);
606                 iter.condition->visit(eval);
607                 if(eval.is_result_valid() && !eval.get_result())
608                 {
609                         nodes_to_remove.insert(&iter);
610                         return;
611                 }
612         }
613
614         TraversingVisitor::visit(iter);
615 }
616
617
618 UnusedVariableRemover::VariableInfo::VariableInfo():
619         local(false),
620         conditionally_assigned(false),
621         referenced(false)
622 { }
623
624
625 UnusedVariableRemover::UnusedVariableRemover():
626         aggregate(0),
627         r_assignment(0),
628         assignment_target(false),
629         r_assign_to_subfield(false),
630         r_side_effects(false)
631 { }
632
633 bool UnusedVariableRemover::apply(Stage &stage)
634 {
635         variables.push_back(BlockVariableMap());
636         stage.content.visit(*this);
637         BlockVariableMap &global_variables = variables.back();
638         for(BlockVariableMap::iterator i=global_variables.begin(); i!=global_variables.end(); ++i)
639         {
640                 /* Don't remove output variables which are used by the next stage or the
641                 graphics API. */
642                 if(i->first->interface=="out" && (stage.type==Stage::FRAGMENT || i->first->linked_declaration || !i->first->name.compare(0, 3, "gl_")))
643                         continue;
644
645                 // Mark other unreferenced global variables as unused.
646                 if(!i->second.referenced)
647                 {
648                         unused_nodes.insert(i->first);
649                         clear_assignments(i->second, true);
650                 }
651         }
652         variables.pop_back();
653
654         NodeRemover().apply(stage, unused_nodes);
655
656         return !unused_nodes.empty();
657 }
658
659 void UnusedVariableRemover::visit(VariableReference &var)
660 {
661         map<VariableDeclaration *, Node *>::iterator i = aggregates.find(var.declaration);
662         if(i!=aggregates.end())
663                 unused_nodes.erase(i->second);
664
665         if(var.declaration && !assignment_target)
666         {
667                 VariableInfo &var_info = variables.back()[var.declaration];
668                 // Previous assignments are used by this reference.
669                 clear_assignments(var_info, false);
670                 var_info.referenced = true;
671         }
672 }
673
674 void UnusedVariableRemover::visit(InterfaceBlockReference &iface)
675 {
676         unused_nodes.erase(iface.declaration);
677 }
678
679 void UnusedVariableRemover::visit(MemberAccess &memacc)
680 {
681         r_assign_to_subfield = true;
682         TraversingVisitor::visit(memacc);
683         unused_nodes.erase(memacc.declaration);
684 }
685
686 void UnusedVariableRemover::visit(UnaryExpression &unary)
687 {
688         TraversingVisitor::visit(unary);
689         if(unary.oper->token[1]=='+' || unary.oper->token[1]=='-')
690                 r_side_effects = true;
691 }
692
693 void UnusedVariableRemover::visit(BinaryExpression &binary)
694 {
695         if(binary.oper->token[0]=='[')
696         {
697                 if(assignment_target)
698                         r_assign_to_subfield = true;
699                 binary.left->visit(*this);
700                 SetFlag set(assignment_target, false);
701                 binary.right->visit(*this);
702         }
703         else
704                 TraversingVisitor::visit(binary);
705 }
706
707 void UnusedVariableRemover::visit(Assignment &assign)
708 {
709         {
710                 SetFlag set(assignment_target, !assign.self_referencing);
711                 assign.left->visit(*this);
712         }
713         assign.right->visit(*this);
714         r_assignment = &assign;
715         r_side_effects = true;
716 }
717
718 void UnusedVariableRemover::visit(FunctionCall &call)
719 {
720         TraversingVisitor::visit(call);
721         /* Treat function calls as having side effects so expression statements
722         consisting of nothing but a function call won't be optimized away. */
723         r_side_effects = true;
724 }
725
726 void UnusedVariableRemover::record_assignment(VariableDeclaration &var, Node &node, bool chained)
727 {
728         VariableInfo &var_info = variables.back()[&var];
729         /* An assignment which completely replaces the value of the variable causes
730         any previous unreferenced assignments to be unused. */
731         if(!chained)
732                 clear_assignments(var_info, true);
733         var_info.assignments.push_back(&node);
734         var_info.conditionally_assigned = false;
735 }
736
737 void UnusedVariableRemover::clear_assignments(VariableInfo &var_info, bool mark_unused)
738 {
739         if(mark_unused)
740         {
741                 for(vector<Node *>::iterator i=var_info.assignments.begin(); i!=var_info.assignments.end(); ++i)
742                         unused_nodes.insert(*i);
743         }
744         var_info.assignments.clear();
745 }
746
747 void UnusedVariableRemover::visit(ExpressionStatement &expr)
748 {
749         r_assignment = 0;
750         r_assign_to_subfield = false;
751         r_side_effects = false;
752         TraversingVisitor::visit(expr);
753         if(r_assignment && r_assignment->target_declaration)
754                 record_assignment(*r_assignment->target_declaration, expr, (r_assignment->self_referencing || r_assign_to_subfield));
755         if(!r_side_effects)
756                 unused_nodes.insert(&expr);
757 }
758
759 void UnusedVariableRemover::visit(StructDeclaration &strct)
760 {
761         SetForScope<Node *> set(aggregate, &strct);
762         unused_nodes.insert(&strct);
763         TraversingVisitor::visit(strct);
764 }
765
766 void UnusedVariableRemover::visit(VariableDeclaration &var)
767 {
768         if(aggregate)
769                 aggregates[&var] = aggregate;
770         else
771         {
772                 variables.back()[&var].local = true;
773                 if(var.init_expression)
774                         record_assignment(var, *var.init_expression, false);
775         }
776         unused_nodes.erase(var.type_declaration);
777         TraversingVisitor::visit(var);
778 }
779
780 void UnusedVariableRemover::visit(InterfaceBlock &iface)
781 {
782         SetForScope<Node *> set(aggregate, &iface);
783         unused_nodes.insert(&iface);
784         TraversingVisitor::visit(iface);
785 }
786
787 void UnusedVariableRemover::visit(FunctionDeclaration &func)
788 {
789         variables.push_back(BlockVariableMap());
790
791         for(NodeArray<VariableDeclaration>::iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
792                 (*i)->visit(*this);
793         func.body.visit(*this);
794
795         BlockVariableMap &block_variables = variables.back();
796
797         /* Mark global variables as conditionally assigned so assignments in other
798         functions won't be removed. */
799         for(BlockVariableMap::iterator i=block_variables.begin(); i!=block_variables.end(); ++i)
800                 if(!i->second.local)
801                         i->second.conditionally_assigned = true;
802
803         /* Always treat function parameters as referenced.  Removing unused
804         parameters is not currently supported. */
805         for(NodeArray<VariableDeclaration>::iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
806                 block_variables[i->get()].referenced = true;
807
808         merge_down_variables();
809 }
810
811 void UnusedVariableRemover::merge_down_variables()
812 {
813         BlockVariableMap &parent_variables = variables[variables.size()-2];
814         BlockVariableMap &block_variables = variables.back();
815         for(BlockVariableMap::iterator i=block_variables.begin(); i!=block_variables.end(); ++i)
816         {
817                 if(i->second.local)
818                 {
819                         if(!i->second.referenced)
820                                 unused_nodes.insert(i->first);
821                         /* Any unreferenced assignments when a variable runs out of scope
822                         become unused. */
823                         clear_assignments(i->second, true);
824                         continue;
825                 }
826
827                 BlockVariableMap::iterator j = parent_variables.find(i->first);
828                 if(j==parent_variables.end())
829                         parent_variables.insert(*i);
830                 else
831                 {
832                         // Merge a non-local variable's state into the parent scope.
833                         if(i->second.referenced || !i->second.conditionally_assigned)
834                                 clear_assignments(j->second, !i->second.referenced);
835                         j->second.conditionally_assigned = i->second.conditionally_assigned;
836                         j->second.referenced |= i->second.referenced;
837                         j->second.assignments.insert(j->second.assignments.end(), i->second.assignments.begin(), i->second.assignments.end());
838                 }
839         }
840         variables.pop_back();
841 }
842
843 void UnusedVariableRemover::visit(Conditional &cond)
844 {
845         cond.condition->visit(*this);
846         variables.push_back(BlockVariableMap());
847         cond.body.visit(*this);
848
849         BlockVariableMap if_variables;
850         swap(variables.back(), if_variables);
851         cond.else_body.visit(*this);
852
853         // Combine variables from both branches.
854         BlockVariableMap &else_variables = variables.back();
855         for(BlockVariableMap::iterator i=else_variables.begin(); i!=else_variables.end(); ++i)
856         {
857                 BlockVariableMap::iterator j = if_variables.find(i->first);
858                 if(j!=if_variables.end())
859                 {
860                         // The variable was found in both branches.
861                         i->second.assignments.insert(i->second.assignments.end(), j->second.assignments.begin(), j->second.assignments.end());
862                         i->second.conditionally_assigned |= j->second.conditionally_assigned;
863                         if_variables.erase(j);
864                 }
865                 else
866                         // Mark variables found in only one branch as conditionally assigned.
867                         i->second.conditionally_assigned = true;
868         }
869
870         /* Move variables which were only used in the if block into the combined
871         block. */
872         for(BlockVariableMap::iterator i=if_variables.begin(); i!=if_variables.end(); ++i)
873         {
874                 i->second.conditionally_assigned = true;
875                 else_variables.insert(*i);
876         }
877
878         merge_down_variables();
879 }
880
881 void UnusedVariableRemover::visit(Iteration &iter)
882 {
883         variables.push_back(BlockVariableMap());
884         TraversingVisitor::visit(iter);
885         merge_down_variables();
886 }
887
888
889 bool UnusedFunctionRemover::apply(Stage &stage)
890 {
891         stage.content.visit(*this);
892         NodeRemover().apply(stage, unused_nodes);
893         return !unused_nodes.empty();
894 }
895
896 void UnusedFunctionRemover::visit(FunctionCall &call)
897 {
898         TraversingVisitor::visit(call);
899
900         unused_nodes.erase(call.declaration);
901         if(call.declaration && call.declaration->definition!=call.declaration)
902                 used_definitions.insert(call.declaration->definition);
903 }
904
905 void UnusedFunctionRemover::visit(FunctionDeclaration &func)
906 {
907         TraversingVisitor::visit(func);
908
909         if((func.name!="main" || func.body.body.empty()) && !used_definitions.count(&func))
910                 unused_nodes.insert(&func);
911 }
912
913 } // namespace SL
914 } // namespace GL
915 } // namespace Msp