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;
207 void FunctionInliner::visit(Block &block)
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)
218 void FunctionInliner::visit(UnaryExpression &unary)
220 visit_and_inline(unary.expression);
224 void FunctionInliner::visit(BinaryExpression &binary)
226 visit_and_inline(binary.left);
227 visit_and_inline(binary.right);
231 void FunctionInliner::visit(MemberAccess &memacc)
233 visit_and_inline(memacc.left);
237 void FunctionInliner::visit(FunctionCall &call)
239 for(NodeArray<Expression>::iterator i=call.arguments.begin(); i!=call.arguments.end(); ++i)
240 visit_and_inline(*i);
242 FunctionDeclaration *def = call.declaration;
244 def = def->definition;
246 if(def && inlineable.count(def))
248 string result_name = InlineContentInjector().apply(*stage, *current_function, *current_block, insert_point, *def);
250 // This will later get removed by UnusedVariableRemover.
251 if(result_name.empty())
252 result_name = "msp_unused_from_inline";
254 RefPtr<VariableReference> ref = new VariableReference;
255 ref->name = result_name;
256 r_inline_result = ref;
258 /* Inlined variables need to be resolved before this function can be
260 inlineable.erase(current_function);
266 void FunctionInliner::visit(ExpressionStatement &expr)
268 visit_and_inline(expr.expression);
271 void FunctionInliner::visit(VariableDeclaration &var)
273 if(var.init_expression)
274 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;
369 void ExpressionInliner::inline_expression(Expression &expr, RefPtr<Expression> &ptr, const Operator *outer_oper, const Operator *inner_oper, bool on_rhs)
371 unsigned outer_precedence = (outer_oper ? outer_oper->precedence : 20);
372 unsigned inner_precedence = (inner_oper ? inner_oper->precedence : 0);
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));
379 if(needs_parentheses)
381 RefPtr<ParenthesizedExpression> parexpr = new ParenthesizedExpression;
382 parexpr->expression = expr.clone();
388 r_any_inlined = true;
391 void ExpressionInliner::visit(Block &block)
393 TraversingVisitor::visit(block);
395 for(map<VariableDeclaration *, ExpressionInfo>::iterator i=expressions.begin(); i!=expressions.end(); )
397 map<string, VariableDeclaration *>::iterator j = block.variables.find(i->first->name);
398 if(j!=block.variables.end() && j->second==i->first)
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);
403 expressions.erase(i++);
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;
419 void ExpressionInliner::visit(VariableReference &var)
423 map<VariableDeclaration *, ExpressionInfo>::iterator i = expressions.find(var.declaration);
424 if(i!=expressions.end())
426 /* If a non-trivial expression is referenced multiple times, don't
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. */
433 i->second.expression = 0;
434 r_ref_info = &i->second;
439 void ExpressionInliner::visit(MemberAccess &memacc)
441 visit_and_record(memacc.left, memacc.oper, false);
443 r_oper = memacc.oper;
447 void ExpressionInliner::visit(UnaryExpression &unary)
449 SetFlag set_target(mutating, mutating || unary.oper->token[1]=='+' || unary.oper->token[1]=='-');
450 visit_and_record(unary.expression, unary.oper, false);
456 void ExpressionInliner::visit(BinaryExpression &binary)
458 visit_and_record(binary.left, binary.oper, false);
460 SetFlag clear_target(mutating, false);
461 visit_and_record(binary.right, binary.oper, true);
464 r_oper = binary.oper;
468 void ExpressionInliner::visit(Assignment &assign)
471 SetFlag set_target(mutating);
472 visit_and_record(assign.left, assign.oper, false);
475 visit_and_record(assign.right, assign.oper, true);
477 if(assign.target_declaration)
479 map<VariableDeclaration *, ExpressionInfo>::iterator i = expressions.find(assign.target_declaration);
480 if(i!=expressions.end())
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;
493 r_oper = assign.oper;
497 void ExpressionInliner::visit(FunctionCall &call)
499 for(NodeArray<Expression>::iterator i=call.arguments.begin(); i!=call.arguments.end(); ++i)
500 visit_and_record(*i, 0, false);
506 void ExpressionInliner::visit(VariableDeclaration &var)
510 if(var.init_expression)
511 visit_and_record(var.init_expression, 0, false);
513 bool constant = var.constant;
514 if(constant && var.layout)
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");
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())
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;
535 void ExpressionInliner::visit(Conditional &cond)
537 visit_and_record(cond.condition, 0, false);
538 cond.body.visit(*this);
541 void ExpressionInliner::visit(Iteration &iter)
543 SetForScope<Block *> set_block(current_block, &iter.body);
544 if(iter.init_statement)
546 SetFlag set_init(iteration_init);
547 iter.init_statement->visit(*this);
550 SetForScope<Block *> set_body(iteration_body, &iter.body);
552 iter.condition->visit(*this);
553 iter.body.visit(*this);
554 if(iter.loop_expression)
555 iter.loop_expression->visit(*this);
558 void ExpressionInliner::visit(Return &ret)
561 visit_and_record(ret.expression, 0, false);
565 void ConstantConditionEliminator::apply(Stage &stage)
567 stage.content.visit(*this);
568 NodeRemover().apply(stage, nodes_to_remove);
571 void ConstantConditionEliminator::visit(Block &block)
573 SetForScope<Block *> set_block(current_block, &block);
574 for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
581 void ConstantConditionEliminator::visit(Conditional &cond)
583 ExpressionEvaluator eval;
584 cond.condition->visit(eval);
585 if(eval.is_result_valid())
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);
593 TraversingVisitor::visit(cond);
596 void ConstantConditionEliminator::visit(Iteration &iter)
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())
609 nodes_to_remove.insert(&iter);
614 TraversingVisitor::visit(iter);
618 UnusedVariableRemover::VariableInfo::VariableInfo():
620 conditionally_assigned(false),
625 UnusedVariableRemover::UnusedVariableRemover():
628 assignment_target(false),
629 r_assign_to_subfield(false),
630 r_side_effects(false)
633 bool UnusedVariableRemover::apply(Stage &stage)
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)
640 /* Don't remove output variables which are used by the next stage or the
642 if(i->first->interface=="out" && (stage.type==Stage::FRAGMENT || i->first->linked_declaration || !i->first->name.compare(0, 3, "gl_")))
645 // Mark other unreferenced global variables as unused.
646 if(!i->second.referenced)
648 unused_nodes.insert(i->first);
649 clear_assignments(i->second, true);
652 variables.pop_back();
654 NodeRemover().apply(stage, unused_nodes);
656 return !unused_nodes.empty();
659 void UnusedVariableRemover::visit(VariableReference &var)
661 map<VariableDeclaration *, Node *>::iterator i = aggregates.find(var.declaration);
662 if(i!=aggregates.end())
663 unused_nodes.erase(i->second);
665 if(var.declaration && !assignment_target)
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;
674 void UnusedVariableRemover::visit(InterfaceBlockReference &iface)
676 unused_nodes.erase(iface.declaration);
679 void UnusedVariableRemover::visit(MemberAccess &memacc)
681 r_assign_to_subfield = true;
682 TraversingVisitor::visit(memacc);
683 unused_nodes.erase(memacc.declaration);
686 void UnusedVariableRemover::visit(UnaryExpression &unary)
688 TraversingVisitor::visit(unary);
689 if(unary.oper->token[1]=='+' || unary.oper->token[1]=='-')
690 r_side_effects = true;
693 void UnusedVariableRemover::visit(BinaryExpression &binary)
695 if(binary.oper->token[0]=='[')
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);
704 TraversingVisitor::visit(binary);
707 void UnusedVariableRemover::visit(Assignment &assign)
710 SetFlag set(assignment_target, !assign.self_referencing);
711 assign.left->visit(*this);
713 assign.right->visit(*this);
714 r_assignment = &assign;
715 r_side_effects = true;
718 void UnusedVariableRemover::visit(FunctionCall &call)
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;
726 void UnusedVariableRemover::record_assignment(VariableDeclaration &var, Node &node, bool chained)
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. */
732 clear_assignments(var_info, true);
733 var_info.assignments.push_back(&node);
734 var_info.conditionally_assigned = false;
737 void UnusedVariableRemover::clear_assignments(VariableInfo &var_info, bool mark_unused)
741 for(vector<Node *>::iterator i=var_info.assignments.begin(); i!=var_info.assignments.end(); ++i)
742 unused_nodes.insert(*i);
744 var_info.assignments.clear();
747 void UnusedVariableRemover::visit(ExpressionStatement &expr)
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));
756 unused_nodes.insert(&expr);
759 void UnusedVariableRemover::visit(StructDeclaration &strct)
761 SetForScope<Node *> set(aggregate, &strct);
762 unused_nodes.insert(&strct);
763 TraversingVisitor::visit(strct);
766 void UnusedVariableRemover::visit(VariableDeclaration &var)
769 aggregates[&var] = aggregate;
772 variables.back()[&var].local = true;
773 if(var.init_expression)
774 record_assignment(var, *var.init_expression, false);
776 unused_nodes.erase(var.type_declaration);
777 TraversingVisitor::visit(var);
780 void UnusedVariableRemover::visit(InterfaceBlock &iface)
782 SetForScope<Node *> set(aggregate, &iface);
783 unused_nodes.insert(&iface);
784 TraversingVisitor::visit(iface);
787 void UnusedVariableRemover::visit(FunctionDeclaration &func)
789 variables.push_back(BlockVariableMap());
791 for(NodeArray<VariableDeclaration>::iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
793 func.body.visit(*this);
795 BlockVariableMap &block_variables = variables.back();
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)
801 i->second.conditionally_assigned = true;
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;
808 merge_down_variables();
811 void UnusedVariableRemover::merge_down_variables()
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)
819 if(!i->second.referenced)
820 unused_nodes.insert(i->first);
821 /* Any unreferenced assignments when a variable runs out of scope
823 clear_assignments(i->second, true);
827 BlockVariableMap::iterator j = parent_variables.find(i->first);
828 if(j==parent_variables.end())
829 parent_variables.insert(*i);
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());
840 variables.pop_back();
843 void UnusedVariableRemover::visit(Conditional &cond)
845 cond.condition->visit(*this);
846 variables.push_back(BlockVariableMap());
847 cond.body.visit(*this);
849 BlockVariableMap if_variables;
850 swap(variables.back(), if_variables);
851 cond.else_body.visit(*this);
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)
857 BlockVariableMap::iterator j = if_variables.find(i->first);
858 if(j!=if_variables.end())
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);
866 // Mark variables found in only one branch as conditionally assigned.
867 i->second.conditionally_assigned = true;
870 /* Move variables which were only used in the if block into the combined
872 for(BlockVariableMap::iterator i=if_variables.begin(); i!=if_variables.end(); ++i)
874 i->second.conditionally_assigned = true;
875 else_variables.insert(*i);
878 merge_down_variables();
881 void UnusedVariableRemover::visit(Iteration &iter)
883 variables.push_back(BlockVariableMap());
884 TraversingVisitor::visit(iter);
885 merge_down_variables();
889 bool UnusedFunctionRemover::apply(Stage &stage)
891 stage.content.visit(*this);
892 NodeRemover().apply(stage, unused_nodes);
893 return !unused_nodes.empty();
896 void UnusedFunctionRemover::visit(FunctionCall &call)
898 TraversingVisitor::visit(call);
900 unused_nodes.erase(call.declaration);
901 if(call.declaration && call.declaration->definition!=call.declaration)
902 used_definitions.insert(call.declaration->definition);
905 void UnusedFunctionRemover::visit(FunctionDeclaration &func)
907 TraversingVisitor::visit(func);
909 if((func.name!="main" || func.body.body.empty()) && !used_definitions.count(&func))
910 unused_nodes.insert(&func);