1 #include <msp/core/raii.h>
2 #include <msp/strings/format.h>
11 InlineableFunctionLocator::InlineableFunctionLocator():
16 void InlineableFunctionLocator::visit(FunctionCall &call)
18 FunctionDeclaration *def = call.declaration;
20 def = def->definition;
24 unsigned &count = refcounts[def];
26 /* Don't inline functions which are called more than once or are called
28 if(count>1 || def==current_function)
29 inlineable.erase(def);
32 TraversingVisitor::visit(call);
35 void InlineableFunctionLocator::visit(FunctionDeclaration &func)
37 unsigned &count = refcounts[func.definition];
38 if(count<=1 && func.parameters.empty())
39 inlineable.insert(func.definition);
41 SetForScope<FunctionDeclaration *> set(current_function, &func);
43 TraversingVisitor::visit(func);
46 void InlineableFunctionLocator::visit(Conditional &cond)
48 TraversingVisitor::visit(cond);
49 inlineable.erase(current_function);
52 void InlineableFunctionLocator::visit(Iteration &iter)
54 TraversingVisitor::visit(iter);
55 inlineable.erase(current_function);
58 void InlineableFunctionLocator::visit(Return &ret)
60 TraversingVisitor::visit(ret);
62 inlineable.erase(current_function);
67 InlineContentInjector::InlineContentInjector():
73 const string &InlineContentInjector::apply(Stage &stage, FunctionDeclaration &target_func, Block &tgt_blk, const NodeList<Statement>::iterator &ins_pt, FunctionDeclaration &src)
75 target_block = &tgt_blk;
77 for(NodeList<Statement>::iterator i=src.body.body.begin(); i!=src.body.body.end(); ++i)
79 r_inlined_statement = 0;
81 if(!r_inlined_statement)
82 r_inlined_statement = (*i)->clone();
84 SetFlag set_remap(remap_names);
85 r_inlined_statement->visit(*this);
86 tgt_blk.body.insert(ins_pt, r_inlined_statement);
89 NodeReorderer().apply(stage, target_func, dependencies);
94 string InlineContentInjector::create_unused_name(const string &base, bool always_prefix)
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)
102 result.erase(initial_size);
103 result += format("_%d", i);
108 void InlineContentInjector::visit(VariableReference &var)
112 map<string, VariableDeclaration *>::const_iterator i = variable_map.find(var.name);
113 if(i!=variable_map.end())
114 var.name = i->second->name;
116 else if(var.declaration)
118 SetFlag set_deps(deps_only);
119 dependencies.insert(var.declaration);
120 var.declaration->visit(*this);
124 void InlineContentInjector::visit(InterfaceBlockReference &iface)
126 if(!remap_names && iface.declaration)
128 SetFlag set_deps(deps_only);
129 dependencies.insert(iface.declaration);
130 iface.declaration->visit(*this);
134 void InlineContentInjector::visit(FunctionCall &call)
136 if(!remap_names && call.declaration)
137 dependencies.insert(call.declaration);
138 TraversingVisitor::visit(call);
141 void InlineContentInjector::visit(VariableDeclaration &var)
143 TraversingVisitor::visit(var);
145 if(var.type_declaration)
147 SetFlag set_deps(deps_only);
148 dependencies.insert(var.type_declaration);
149 var.type_declaration->visit(*this);
152 if(!remap_names && !deps_only)
154 RefPtr<VariableDeclaration> inlined_var = var.clone();
155 inlined_var->name = create_unused_name(var.name, false);
156 r_inlined_statement = inlined_var;
158 variable_map[var.name] = inlined_var.get();
162 void InlineContentInjector::visit(Return &ret)
164 TraversingVisitor::visit(ret);
168 /* Create a new variable to hold the return value of the inlined
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;
182 FunctionInliner::FunctionInliner():
187 bool FunctionInliner::apply(Stage &s)
190 inlineable = InlineableFunctionLocator().apply(s);
191 r_any_inlined = false;
192 s.content.visit(*this);
193 return r_any_inlined;
196 void FunctionInliner::visit_and_inline(RefPtr<Expression> &ptr)
202 ptr = r_inline_result;
203 r_any_inlined = true;
208 void FunctionInliner::visit(Block &block)
210 SetForScope<Block *> set_block(current_block, &block);
211 SetForScope<NodeList<Statement>::iterator> save_insert_point(insert_point, block.body.begin());
212 for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
219 void FunctionInliner::visit(UnaryExpression &unary)
221 visit_and_inline(unary.expression);
224 void FunctionInliner::visit(BinaryExpression &binary)
226 visit_and_inline(binary.left);
227 visit_and_inline(binary.right);
230 void FunctionInliner::visit(MemberAccess &memacc)
232 visit_and_inline(memacc.left);
235 void FunctionInliner::visit(Swizzle &swizzle)
237 visit_and_inline(swizzle.left);
240 void FunctionInliner::visit(FunctionCall &call)
242 for(NodeArray<Expression>::iterator i=call.arguments.begin(); i!=call.arguments.end(); ++i)
243 visit_and_inline(*i);
245 FunctionDeclaration *def = call.declaration;
247 def = def->definition;
249 if(def && inlineable.count(def))
251 string result_name = InlineContentInjector().apply(*stage, *current_function, *current_block, insert_point, *def);
253 // This will later get removed by UnusedVariableRemover.
254 if(result_name.empty())
255 result_name = "msp_unused_from_inline";
257 RefPtr<VariableReference> ref = new VariableReference;
258 ref->name = result_name;
259 r_inline_result = ref;
261 /* Inlined variables need to be resolved before this function can be
263 inlineable.erase(current_function);
267 void FunctionInliner::visit(ExpressionStatement &expr)
269 visit_and_inline(expr.expression);
272 void FunctionInliner::visit(VariableDeclaration &var)
274 if(var.init_expression)
275 visit_and_inline(var.init_expression);
278 void FunctionInliner::visit(FunctionDeclaration &func)
280 SetForScope<FunctionDeclaration *> set_func(current_function, &func);
281 TraversingVisitor::visit(func);
284 void FunctionInliner::visit(Conditional &cond)
286 visit_and_inline(cond.condition);
287 cond.body.visit(*this);
290 void FunctionInliner::visit(Iteration &iter)
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);
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);
304 void FunctionInliner::visit(Return &ret)
307 visit_and_inline(ret.expression);
311 ExpressionInliner::ExpressionInfo::ExpressionInfo():
317 inline_on_rhs(false),
323 ExpressionInliner::ExpressionInliner():
325 r_any_inlined(false),
328 iteration_init(false),
333 bool ExpressionInliner::apply(Stage &s)
335 s.content.visit(*this);
336 return r_any_inlined;
339 void ExpressionInliner::visit_and_record(RefPtr<Expression> &ptr, const Operator *outer_oper, bool on_rhs)
343 if(r_ref_info && r_ref_info->expression && r_ref_info->available)
345 if(iteration_body && !r_ref_info->trivial)
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) ;
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);
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;
370 void ExpressionInliner::inline_expression(Expression &expr, RefPtr<Expression> &ptr, const Operator *outer_oper, const Operator *inner_oper, bool on_rhs)
372 unsigned outer_precedence = (outer_oper ? outer_oper->precedence : 20);
373 unsigned inner_precedence = (inner_oper ? inner_oper->precedence : 0);
375 bool needs_parentheses = (inner_precedence>=outer_precedence);
376 if(inner_oper && inner_oper==outer_oper)
377 // Omit parentheses if the operator's natural grouping works out.
378 needs_parentheses = (inner_oper->assoc!=Operator::ASSOCIATIVE && on_rhs!=(inner_oper->assoc==Operator::RIGHT_TO_LEFT));
380 if(needs_parentheses)
382 RefPtr<ParenthesizedExpression> parexpr = new ParenthesizedExpression;
383 parexpr->expression = expr.clone();
389 r_any_inlined = true;
392 void ExpressionInliner::visit(Block &block)
394 TraversingVisitor::visit(block);
396 for(map<string, VariableDeclaration *>::iterator i=block.variables.begin(); i!=block.variables.end(); ++i)
398 map<Assignment::Target, ExpressionInfo>::iterator j = expressions.lower_bound(i->second);
399 for(; (j!=expressions.end() && j->first.declaration==i->second); )
401 if(j->second.expression && j->second.inline_point)
402 inline_expression(*j->second.expression, *j->second.inline_point, j->second.outer_oper, j->second.inner_oper, j->second.inline_on_rhs);
404 expressions.erase(j++);
408 /* Expressions assigned in this block may depend on local variables of the
409 block. If this is a conditionally executed block, the assignments might not
410 always happen. Mark the expressions as not available to any outer blocks. */
411 for(map<Assignment::Target, ExpressionInfo>::iterator i=expressions.begin(); i!=expressions.end(); ++i)
412 if(i->second.assign_scope==&block)
413 i->second.available = false;
416 void ExpressionInliner::visit(VariableReference &var)
420 map<Assignment::Target, ExpressionInfo>::iterator i = expressions.find(var.declaration);
421 if(i!=expressions.end())
423 /* If a non-trivial expression is referenced multiple times, don't
425 if(i->second.inline_point && !i->second.trivial)
426 i->second.expression = 0;
427 /* Mutating expressions are analogous to self-referencing assignments
428 and prevent inlining. */
430 i->second.expression = 0;
431 r_ref_info = &i->second;
436 void ExpressionInliner::visit(MemberAccess &memacc)
438 visit_and_record(memacc.left, memacc.oper, false);
439 r_oper = memacc.oper;
443 void ExpressionInliner::visit(Swizzle &swizzle)
445 visit_and_record(swizzle.left, swizzle.oper, false);
446 r_oper = swizzle.oper;
450 void ExpressionInliner::visit(UnaryExpression &unary)
452 SetFlag set_target(mutating, mutating || unary.oper->token[1]=='+' || unary.oper->token[1]=='-');
453 visit_and_record(unary.expression, unary.oper, false);
458 void ExpressionInliner::visit(BinaryExpression &binary)
460 visit_and_record(binary.left, binary.oper, false);
462 SetFlag clear_target(mutating, false);
463 visit_and_record(binary.right, binary.oper, true);
465 r_oper = binary.oper;
469 void ExpressionInliner::visit(Assignment &assign)
472 SetFlag set_target(mutating);
473 visit_and_record(assign.left, assign.oper, false);
476 visit_and_record(assign.right, assign.oper, true);
478 map<Assignment::Target, ExpressionInfo>::iterator i = expressions.find(assign.target);
479 if(i!=expressions.end())
481 /* Self-referencing assignments can't be inlined without additional
482 work. Just clear any previous expression. */
483 i->second.expression = (assign.self_referencing ? 0 : assign.right.get());
484 i->second.assign_scope = current_block;
485 i->second.inline_point = 0;
486 i->second.inner_oper = r_oper;
487 i->second.available = true;
490 r_oper = assign.oper;
494 void ExpressionInliner::visit(FunctionCall &call)
496 for(NodeArray<Expression>::iterator i=call.arguments.begin(); i!=call.arguments.end(); ++i)
497 visit_and_record(*i, 0, false);
502 void ExpressionInliner::visit(VariableDeclaration &var)
506 if(var.init_expression)
507 visit_and_record(var.init_expression, 0, false);
509 bool constant = var.constant;
510 if(constant && var.layout)
512 for(vector<Layout::Qualifier>::const_iterator i=var.layout->qualifiers.begin(); (constant && i!=var.layout->qualifiers.end()); ++i)
513 constant = (i->name!="constant_id");
516 /* Only inline global variables if they're constant and have trivial
517 initializers. Non-constant variables could change in ways which are hard to
518 analyze and non-trivial expressions could be expensive to inline. */
519 if((current_block->parent || (constant && r_trivial)) && var.interface.empty())
521 ExpressionInfo &info = expressions[&var];
522 /* Assume variables declared in an iteration initialization statement
523 will have their values change throughout the iteration. */
524 info.expression = (iteration_init ? 0 : var.init_expression.get());
525 info.assign_scope = current_block;
526 info.inner_oper = r_oper;
527 info.trivial = r_trivial;
531 void ExpressionInliner::visit(Conditional &cond)
533 visit_and_record(cond.condition, 0, false);
534 cond.body.visit(*this);
537 void ExpressionInliner::visit(Iteration &iter)
539 SetForScope<Block *> set_block(current_block, &iter.body);
540 if(iter.init_statement)
542 SetFlag set_init(iteration_init);
543 iter.init_statement->visit(*this);
546 SetForScope<Block *> set_body(iteration_body, &iter.body);
548 iter.condition->visit(*this);
549 iter.body.visit(*this);
550 if(iter.loop_expression)
551 iter.loop_expression->visit(*this);
554 void ExpressionInliner::visit(Return &ret)
557 visit_and_record(ret.expression, 0, false);
561 void ConstantConditionEliminator::apply(Stage &stage)
563 stage.content.visit(*this);
564 NodeRemover().apply(stage, nodes_to_remove);
567 void ConstantConditionEliminator::visit(Block &block)
569 SetForScope<Block *> set_block(current_block, &block);
570 for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
577 void ConstantConditionEliminator::visit(Conditional &cond)
579 ExpressionEvaluator eval;
580 cond.condition->visit(eval);
581 if(eval.is_result_valid())
583 Block &block = (eval.get_result() ? cond.body : cond.else_body);
584 current_block->body.splice(insert_point, block.body);
585 nodes_to_remove.insert(&cond);
589 TraversingVisitor::visit(cond);
592 void ConstantConditionEliminator::visit(Iteration &iter)
596 /* If the loop condition is always false on the first iteration, the
597 entire loop can be removed */
598 ExpressionEvaluator::ValueMap values;
599 if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(iter.init_statement.get()))
600 values[var] = var->init_expression.get();
601 ExpressionEvaluator eval(values);
602 iter.condition->visit(eval);
603 if(eval.is_result_valid() && !eval.get_result())
605 nodes_to_remove.insert(&iter);
610 TraversingVisitor::visit(iter);
614 UnusedVariableRemover::VariableInfo::VariableInfo():
617 conditionally_assigned(false),
623 bool UnusedTypeRemover::apply(Stage &stage)
625 stage.content.visit(*this);
626 NodeRemover().apply(stage, unused_nodes);
627 return !unused_nodes.empty();
630 void UnusedTypeRemover::visit(Literal &literal)
632 unused_nodes.erase(literal.type);
635 void UnusedTypeRemover::visit(UnaryExpression &unary)
637 unused_nodes.erase(unary.type);
638 TraversingVisitor::visit(unary);
641 void UnusedTypeRemover::visit(BinaryExpression &binary)
643 unused_nodes.erase(binary.type);
644 TraversingVisitor::visit(binary);
647 void UnusedTypeRemover::visit(FunctionCall &call)
649 unused_nodes.erase(call.type);
650 TraversingVisitor::visit(call);
653 void UnusedTypeRemover::visit(BasicTypeDeclaration &type)
656 unused_nodes.erase(type.base_type);
657 unused_nodes.insert(&type);
660 void UnusedTypeRemover::visit(ImageTypeDeclaration &type)
663 unused_nodes.erase(type.base_type);
664 unused_nodes.insert(&type);
667 void UnusedTypeRemover::visit(StructDeclaration &strct)
669 unused_nodes.insert(&strct);
670 TraversingVisitor::visit(strct);
673 void UnusedTypeRemover::visit(VariableDeclaration &var)
675 unused_nodes.erase(var.type_declaration);
678 void UnusedTypeRemover::visit(InterfaceBlock &iface)
680 unused_nodes.erase(iface.type_declaration);
683 void UnusedTypeRemover::visit(FunctionDeclaration &func)
685 unused_nodes.erase(func.return_type_declaration);
686 TraversingVisitor::visit(func);
690 UnusedVariableRemover::UnusedVariableRemover():
694 assignment_target(false),
695 r_side_effects(false)
698 bool UnusedVariableRemover::apply(Stage &s)
701 variables.push_back(BlockVariableMap());
702 s.content.visit(*this);
704 BlockVariableMap &global_variables = variables.back();
705 set<InterfaceBlock *> used_interface_blocks;
706 Statement *prev_decl = 0;
708 for(BlockVariableMap::iterator i=global_variables.begin(); i!=global_variables.end(); ++i)
710 if(i->first.declaration!=prev_decl)
712 prev_decl = i->first.declaration;
713 output = i->second.output;
717 if(!i->second.assignments.empty() && i->second.interface_block)
718 used_interface_blocks.insert(i->second.interface_block);
722 // Mark other unreferenced global variables as unused.
723 if(!i->second.referenced)
725 if(!i->second.interface_block && !i->first.chain_len)
726 unused_nodes.insert(i->first.declaration);
727 clear_assignments(i->second, true);
729 else if(i->second.interface_block)
730 used_interface_blocks.insert(i->second.interface_block);
732 variables.pop_back();
734 for(map<string, InterfaceBlock *>::const_iterator i=s.interface_blocks.begin(); i!=s.interface_blocks.end(); ++i)
735 if(i->second->instance_name.empty() && !used_interface_blocks.count(i->second))
736 unused_nodes.insert(i->second);
738 NodeRemover().apply(s, unused_nodes);
740 return !unused_nodes.empty();
743 void UnusedVariableRemover::reference_used(Statement &declaration)
745 BlockVariableMap &block_vars = variables.back();
746 /* Previous assignments of all subfields of this variable are used by
748 for(BlockVariableMap::iterator i=block_vars.lower_bound(&declaration); (i!=block_vars.end() && i->first.declaration==&declaration); ++i)
750 clear_assignments(i->second, false);
751 i->second.referenced = true;
754 // Always record a reference to the primary declaration, even if it didn't exist before
755 block_vars[&declaration].referenced = true;
758 void UnusedVariableRemover::visit(VariableReference &var)
760 if(var.declaration && !assignment_target)
761 reference_used(*var.declaration);
764 void UnusedVariableRemover::visit(InterfaceBlockReference &iface)
766 if(iface.declaration && !assignment_target)
767 reference_used(*iface.declaration);
770 void UnusedVariableRemover::visit(UnaryExpression &unary)
772 TraversingVisitor::visit(unary);
773 if(unary.oper->token[1]=='+' || unary.oper->token[1]=='-')
774 r_side_effects = true;
777 void UnusedVariableRemover::visit(BinaryExpression &binary)
779 if(binary.oper->token[0]=='[')
781 binary.left->visit(*this);
782 SetFlag set(assignment_target, false);
783 binary.right->visit(*this);
786 TraversingVisitor::visit(binary);
789 void UnusedVariableRemover::visit(Assignment &assign)
792 SetFlag set(assignment_target, !assign.self_referencing);
793 assign.left->visit(*this);
795 assign.right->visit(*this);
796 r_assignment = &assign;
797 r_side_effects = true;
800 void UnusedVariableRemover::visit(FunctionCall &call)
802 TraversingVisitor::visit(call);
803 /* Treat function calls as having side effects so expression statements
804 consisting of nothing but a function call won't be optimized away. */
805 r_side_effects = true;
808 void UnusedVariableRemover::record_assignment(const Assignment::Target &target, Node &node, bool chained)
810 BlockVariableMap &block_vars = variables.back();
811 for(BlockVariableMap::iterator i=block_vars.lower_bound(target); (i!=block_vars.end() && i->first.declaration==target.declaration); ++i)
813 bool subfield = (i->first.chain_len>=target.chain_len);
814 for(unsigned j=0; (subfield && j<target.chain_len); ++j)
815 subfield = (i->first.chain[j]==target.chain[j]);
819 /* An assignment to the target causes any previous unreferenced
820 assignments to the same target or its subfields to be unused. */
822 clear_assignments(i->second, true);
825 VariableInfo &var_info = variables.back()[target];
826 var_info.assignments.push_back(&node);
827 var_info.conditionally_assigned = false;
830 void UnusedVariableRemover::clear_assignments(VariableInfo &var_info, bool mark_unused)
834 for(vector<Node *>::iterator i=var_info.assignments.begin(); i!=var_info.assignments.end(); ++i)
835 unused_nodes.insert(*i);
837 var_info.assignments.clear();
840 void UnusedVariableRemover::visit(ExpressionStatement &expr)
843 r_side_effects = false;
844 TraversingVisitor::visit(expr);
845 if(r_assignment && r_assignment->target.declaration)
846 record_assignment(r_assignment->target, expr, r_assignment->self_referencing);
848 unused_nodes.insert(&expr);
851 void UnusedVariableRemover::visit(VariableDeclaration &var)
853 VariableInfo &var_info = variables.back()[&var];
854 var_info.local = true;
855 var_info.interface_block = interface_block;
857 /* Mark variables as output if they're used by the next stage or the
860 var_info.output = (interface_block->interface=="out" && (interface_block->linked_block || !interface_block->name.compare(0, 3, "gl_")));
862 var_info.output = (var.interface=="out" && (stage->type==Stage::FRAGMENT || var.linked_declaration || !var.name.compare(0, 3, "gl_")));
864 if(var.init_expression)
865 record_assignment(&var, *var.init_expression, false);
866 TraversingVisitor::visit(var);
869 void UnusedVariableRemover::visit(InterfaceBlock &iface)
871 if(iface.instance_name.empty())
873 SetForScope<InterfaceBlock *> set_block(interface_block, &iface);
874 iface.struct_declaration->members.visit(*this);
878 VariableInfo &var_info = variables.back()[&iface];
879 var_info.local = true;
880 var_info.output = (iface.interface=="out" && (iface.linked_block || !iface.name.compare(0, 3, "gl_")));
884 void UnusedVariableRemover::visit(FunctionDeclaration &func)
886 variables.push_back(BlockVariableMap());
888 for(NodeArray<VariableDeclaration>::iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
890 func.body.visit(*this);
892 BlockVariableMap &block_variables = variables.back();
894 /* Mark global variables as conditionally assigned so assignments in other
895 functions won't be removed. */
896 for(BlockVariableMap::iterator i=block_variables.begin(); i!=block_variables.end(); ++i)
898 i->second.conditionally_assigned = true;
900 /* Always treat function parameters as referenced. Removing unused
901 parameters is not currently supported. */
902 for(NodeArray<VariableDeclaration>::iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
903 block_variables[i->get()].referenced = true;
905 merge_down_variables();
908 void UnusedVariableRemover::merge_down_variables()
910 BlockVariableMap &parent_variables = variables[variables.size()-2];
911 BlockVariableMap &block_variables = variables.back();
912 for(BlockVariableMap::iterator i=block_variables.begin(); i!=block_variables.end(); ++i)
916 if(!i->second.referenced && !i->first.chain_len)
917 unused_nodes.insert(i->first.declaration);
918 /* Any unreferenced assignments when a variable runs out of scope
920 clear_assignments(i->second, true);
924 BlockVariableMap::iterator j = parent_variables.find(i->first);
925 if(j==parent_variables.end())
926 parent_variables.insert(*i);
929 // Merge a non-local variable's state into the parent scope.
930 if(i->second.referenced || !i->second.conditionally_assigned)
931 clear_assignments(j->second, !i->second.referenced);
932 j->second.conditionally_assigned = i->second.conditionally_assigned;
933 j->second.referenced |= i->second.referenced;
934 j->second.assignments.insert(j->second.assignments.end(), i->second.assignments.begin(), i->second.assignments.end());
937 variables.pop_back();
940 void UnusedVariableRemover::visit(Conditional &cond)
942 cond.condition->visit(*this);
943 variables.push_back(BlockVariableMap());
944 cond.body.visit(*this);
946 BlockVariableMap if_variables;
947 swap(variables.back(), if_variables);
948 cond.else_body.visit(*this);
950 // Combine variables from both branches.
951 BlockVariableMap &else_variables = variables.back();
952 for(BlockVariableMap::iterator i=else_variables.begin(); i!=else_variables.end(); ++i)
954 BlockVariableMap::iterator j = if_variables.find(i->first);
955 if(j!=if_variables.end())
957 // The variable was found in both branches.
958 i->second.assignments.insert(i->second.assignments.end(), j->second.assignments.begin(), j->second.assignments.end());
959 i->second.conditionally_assigned |= j->second.conditionally_assigned;
960 if_variables.erase(j);
963 // Mark variables found in only one branch as conditionally assigned.
964 i->second.conditionally_assigned = true;
967 /* Move variables which were only used in the if block into the combined
969 for(BlockVariableMap::iterator i=if_variables.begin(); i!=if_variables.end(); ++i)
971 i->second.conditionally_assigned = true;
972 else_variables.insert(*i);
975 merge_down_variables();
978 void UnusedVariableRemover::visit(Iteration &iter)
980 variables.push_back(BlockVariableMap());
981 TraversingVisitor::visit(iter);
982 merge_down_variables();
986 bool UnusedFunctionRemover::apply(Stage &stage)
988 stage.content.visit(*this);
989 NodeRemover().apply(stage, unused_nodes);
990 return !unused_nodes.empty();
993 void UnusedFunctionRemover::visit(FunctionCall &call)
995 TraversingVisitor::visit(call);
997 unused_nodes.erase(call.declaration);
998 if(call.declaration && call.declaration->definition!=call.declaration)
999 used_definitions.insert(call.declaration->definition);
1002 void UnusedFunctionRemover::visit(FunctionDeclaration &func)
1004 TraversingVisitor::visit(func);
1006 if((func.name!="main" || func.body.body.empty()) && !used_definitions.count(&func))
1007 unused_nodes.insert(&func);