+bool AggregateDismantler::apply(Stage &stage)
+{
+ stage.content.visit(*this);
+
+ bool any_dismantled = false;
+ for(const auto &kvp: aggregates)
+ {
+ if(kvp.second.referenced || !kvp.second.members_referenced)
+ continue;
+
+ for(const AggregateMember &m: kvp.second.members)
+ {
+ string name;
+ if(m.declaration)
+ name = format("%s_%s", kvp.second.declaration->name, m.declaration->name);
+ else
+ name = format("%s_%d", kvp.second.declaration->name, m.index);
+
+ VariableDeclaration *var = new VariableDeclaration;
+ var->source = kvp.first->source;
+ var->line = kvp.first->line;
+ var->name = get_unused_variable_name(*kvp.second.decl_scope, name);
+ /* XXX This is kind of brittle and depends on the array declaration's
+ textual type not having brackets in it. */
+ var->type = (m.declaration ? m.declaration : kvp.second.declaration)->type;
+ if(m.initializer)
+ var->init_expression = m.initializer->clone();
+
+ kvp.second.decl_scope->body.insert(kvp.second.insert_point, var);
+
+ for(RefPtr<Expression> *r: m.references)
+ {
+ VariableReference *ref = new VariableReference;
+ ref->name = var->name;
+ *r = ref;
+ }
+
+ any_dismantled = true;
+ }
+ }
+
+ return any_dismantled;
+}
+
+void AggregateDismantler::visit(Block &block)
+{
+ SetForScope<Block *> set_block(current_block, &block);
+ for(auto i=block.body.begin(); i!=block.body.end(); ++i)
+ {
+ insert_point = i;
+ (*i)->visit(*this);
+ }
+}
+
+void AggregateDismantler::visit(RefPtr<Expression> &expr)
+{
+ r_aggregate_ref = 0;
+ expr->visit(*this);
+ if(r_aggregate_ref && r_reference.chain_len==1)
+ {
+ if((r_reference.chain[0]&0x3F)!=0x3F)
+ {
+ r_aggregate_ref->members[r_reference.chain[0]&0x3F].references.push_back(&expr);
+ r_aggregate_ref->members_referenced = true;
+ }
+ else
+ /* If the accessed member is not known, mark the entire aggregate as
+ referenced. */
+ r_aggregate_ref->referenced = true;
+ }
+ r_aggregate_ref = 0;
+}
+
+void AggregateDismantler::visit(VariableReference &var)
+{
+ if(composite_reference)
+ r_reference.declaration = var.declaration;
+ else
+ {
+ /* If an aggregate variable is referenced as a whole, it should not be
+ dismantled. */
+ auto i = aggregates.find(var.declaration);
+ if(i!=aggregates.end())
+ i->second.referenced = true;
+ }
+}
+
+void AggregateDismantler::visit_composite(RefPtr<Expression> &expr)
+{
+ if(!composite_reference)
+ r_reference = Assignment::Target();
+
+ SetFlag set_composite(composite_reference);
+ visit(expr);
+}
+
+void AggregateDismantler::visit(MemberAccess &memacc)
+{
+ visit_composite(memacc.left);
+
+ add_to_chain(r_reference, Assignment::Target::MEMBER, memacc.index);
+
+ if(r_reference.declaration && r_reference.chain_len==1)
+ {
+ auto i = aggregates.find(r_reference.declaration);
+ r_aggregate_ref = (i!=aggregates.end() ? &i->second : 0);
+ }
+ else
+ r_aggregate_ref = 0;
+}
+
+void AggregateDismantler::visit(BinaryExpression &binary)
+{
+ if(binary.oper->token[0]=='[')
+ {
+ visit_composite(binary.left);
+ {
+ SetFlag clear_composite(composite_reference, false);
+ visit(binary.right);
+ }
+
+ unsigned index = 0x3F;
+ if(Literal *literal_subscript = dynamic_cast<Literal *>(binary.right.get()))
+ if(literal_subscript->value.check_type<int>())
+ index = literal_subscript->value.value<int>();
+ add_to_chain(r_reference, Assignment::Target::ARRAY, index);
+
+ if(r_reference.declaration && r_reference.chain_len==1)
+ {
+ auto i = aggregates.find(r_reference.declaration);
+ r_aggregate_ref = (i!=aggregates.end() ? &i->second : 0);
+ }
+ else
+ r_aggregate_ref = 0;
+ }
+ else
+ {
+ SetFlag clear_composite(composite_reference, false);
+ TraversingVisitor::visit(binary);
+ }
+}
+
+void AggregateDismantler::visit(VariableDeclaration &var)
+{
+ TraversingVisitor::visit(var);
+
+ if(var.interface.empty())
+ {
+ if(const StructDeclaration *strct = dynamic_cast<const StructDeclaration *>(var.type_declaration))
+ {
+ const FunctionCall *init_call = dynamic_cast<const FunctionCall *>(var.init_expression.get());
+ if((init_call && init_call->constructor) || !var.init_expression)
+ {
+
+ Aggregate &aggre = aggregates[&var];
+ aggre.declaration = &var;
+ aggre.decl_scope = current_block;
+ aggre.insert_point = insert_point;
+
+ unsigned i = 0;
+ for(const RefPtr<Statement> &s: strct->members.body)
+ {
+ if(const VariableDeclaration *mem_decl = dynamic_cast<const VariableDeclaration *>(s.get()))
+ {
+ AggregateMember member;
+ member.declaration = mem_decl;
+ member.index = i;
+ if(init_call)
+ member.initializer = init_call->arguments[i];
+ aggre.members.push_back(member);
+ }
+ ++i;
+ }
+ }
+ }
+ else if(const Literal *literal_size = dynamic_cast<const Literal *>(var.array_size.get()))
+ {
+ if(literal_size->value.check_type<int>())
+ {
+ Aggregate &aggre = aggregates[&var];
+ aggre.declaration = &var;
+ aggre.decl_scope = current_block;
+ aggre.insert_point = insert_point;
+
+ int size = literal_size->value.value<int>();
+ for(int i=0; i<size; ++i)
+ {
+ AggregateMember member;
+ member.index = i;
+ // Array initializers are not supported yet
+ aggre.members.push_back(member);
+ }
+ }
+ }
+ }
+}
+
+void AggregateDismantler::visit(FunctionDeclaration &func)
+{
+ func.body.visit(*this);
+}
+
+
+template<typename T>
+T ConstantFolder::evaluate_logical(char oper, T left, T right)
+{
+ switch(oper)
+ {
+ case '&': return left&right;
+ case '|': return left|right;
+ case '^': return left^right;
+ default: return T();
+ }
+}
+
+template<typename T>
+bool ConstantFolder::evaluate_relation(const char *oper, T left, T right)
+{
+ switch(oper[0]|oper[1])
+ {
+ case '<': return left<right;
+ case '<'|'=': return left<=right;
+ case '>': return left>right;
+ case '>'|'=': return left>=right;
+ default: return false;
+ }
+}
+
+template<typename T>
+T ConstantFolder::evaluate_arithmetic(char oper, T left, T right)
+{
+ switch(oper)
+ {
+ case '+': return left+right;
+ case '-': return left-right;
+ case '*': return left*right;
+ case '/': return left/right;
+ default: return T();
+ }
+}
+
+template<typename T>
+T ConstantFolder::evaluate_int_special_op(char oper, T left, T right)
+{
+ switch(oper)
+ {
+ case '%': return left%right;
+ case '<': return left<<right;
+ case '>': return left>>right;
+ default: return T();
+ }
+}
+
+template<typename T>
+void ConstantFolder::convert_to_result(const Variant &value)
+{
+ if(value.check_type<bool>())
+ set_result(static_cast<T>(value.value<bool>()));
+ else if(value.check_type<int>())
+ set_result(static_cast<T>(value.value<int>()));
+ else if(value.check_type<unsigned>())
+ set_result(static_cast<T>(value.value<unsigned>()));
+ else if(value.check_type<float>())
+ set_result(static_cast<T>(value.value<float>()));
+}
+
+void ConstantFolder::set_result(const Variant &value, bool literal)
+{
+ r_constant_value = value;
+ r_constant = true;
+ r_literal = literal;
+}
+
+void ConstantFolder::visit(RefPtr<Expression> &expr)
+{
+ r_constant_value = Variant();
+ r_constant = false;
+ r_literal = false;
+ r_uses_iter_var = false;
+ expr->visit(*this);
+ /* Don't replace literals since they'd only be replaced with an identical
+ literal. Also skip anything that uses an iteration variable, but pass on
+ the result so the Iteration visiting function can handle it. */
+ if(!r_constant || r_literal || r_uses_iter_var)
+ return;
+
+ RefPtr<Literal> literal = new Literal;
+ if(r_constant_value.check_type<bool>())
+ literal->token = (r_constant_value.value<bool>() ? "true" : "false");
+ else if(r_constant_value.check_type<int>())
+ literal->token = lexical_cast<string>(r_constant_value.value<int>());
+ else if(r_constant_value.check_type<unsigned>())
+ literal->token = lexical_cast<string>(r_constant_value.value<unsigned>())+"u";
+ else if(r_constant_value.check_type<float>())
+ {
+ literal->token = lexical_cast<string>(r_constant_value.value<float>(), Fmt().precision(8));
+ if(literal->token.find('.')==string::npos && literal->token.find('e')==string::npos)
+ literal->token += ".0";
+ }
+ else
+ {
+ r_constant = false;
+ return;
+ }
+ literal->value = r_constant_value;
+ expr = literal;
+ r_any_folded = true;
+}
+
+void ConstantFolder::visit(Literal &literal)
+{
+ set_result(literal.value, true);
+}
+
+void ConstantFolder::visit(VariableReference &var)
+{
+ /* If an iteration variable is initialized with a constant value, return
+ that value here for the purpose of evaluating the loop condition for the
+ first iteration. */
+ if(var.declaration==iteration_var)
+ {
+ set_result(iter_init_value);
+ r_uses_iter_var = true;
+ }
+}
+
+void ConstantFolder::visit(MemberAccess &memacc)
+{
+ TraversingVisitor::visit(memacc);
+ r_constant = false;
+}
+
+void ConstantFolder::visit(Swizzle &swizzle)
+{
+ TraversingVisitor::visit(swizzle);
+ r_constant = false;
+}
+
+void ConstantFolder::visit(UnaryExpression &unary)
+{
+ TraversingVisitor::visit(unary);
+ bool can_fold = r_constant;
+ r_constant = false;
+ if(!can_fold)
+ return;
+
+ char oper = unary.oper->token[0];
+ char oper2 = unary.oper->token[1];
+ if(oper=='!')
+ {
+ if(r_constant_value.check_type<bool>())
+ set_result(!r_constant_value.value<bool>());
+ }
+ else if(oper=='~')
+ {
+ if(r_constant_value.check_type<int>())
+ set_result(~r_constant_value.value<int>());
+ else if(r_constant_value.check_type<unsigned>())
+ set_result(~r_constant_value.value<unsigned>());
+ }
+ else if(oper=='-' && !oper2)
+ {
+ if(r_constant_value.check_type<int>())
+ set_result(-r_constant_value.value<int>());
+ else if(r_constant_value.check_type<unsigned>())
+ set_result(-r_constant_value.value<unsigned>());
+ else if(r_constant_value.check_type<float>())
+ set_result(-r_constant_value.value<float>());
+ }
+}
+
+void ConstantFolder::visit(BinaryExpression &binary)
+{
+ visit(binary.left);
+ bool left_constant = r_constant;
+ bool left_iter_var = r_uses_iter_var;
+ Variant left_value = r_constant_value;
+ visit(binary.right);
+ if(left_iter_var)
+ r_uses_iter_var = true;
+
+ bool can_fold = (left_constant && r_constant);
+ r_constant = false;
+ if(!can_fold)
+ return;
+
+ // Currently only expressions with both sides of equal types are handled.
+ if(!left_value.check_same_type(r_constant_value))
+ return;
+
+ char oper = binary.oper->token[0];
+ char oper2 = binary.oper->token[1];
+ if(oper=='&' || oper=='|' || oper=='^')
+ {
+ if(oper2==oper && left_value.check_type<bool>())
+ set_result(evaluate_logical(oper, left_value.value<bool>(), r_constant_value.value<bool>()));
+ else if(!oper2 && left_value.check_type<int>())
+ set_result(evaluate_logical(oper, left_value.value<int>(), r_constant_value.value<int>()));
+ else if(!oper2 && left_value.check_type<unsigned>())
+ set_result(evaluate_logical(oper, left_value.value<unsigned>(), r_constant_value.value<unsigned>()));
+ }
+ else if((oper=='<' || oper=='>') && oper2!=oper)
+ {
+ if(left_value.check_type<int>())
+ set_result(evaluate_relation(binary.oper->token, left_value.value<int>(), r_constant_value.value<int>()));
+ else if(left_value.check_type<unsigned>())
+ set_result(evaluate_relation(binary.oper->token, left_value.value<unsigned>(), r_constant_value.value<unsigned>()));
+ else if(left_value.check_type<float>())
+ set_result(evaluate_relation(binary.oper->token, left_value.value<float>(), r_constant_value.value<float>()));
+ }
+ else if((oper=='=' || oper=='!') && oper2=='=')
+ {
+ if(left_value.check_type<int>())
+ set_result((left_value.value<int>()==r_constant_value.value<int>()) == (oper=='='));
+ else if(left_value.check_type<unsigned>())
+ set_result((left_value.value<unsigned>()==r_constant_value.value<unsigned>()) == (oper=='='));
+ else if(left_value.check_type<float>())
+ set_result((left_value.value<float>()==r_constant_value.value<float>()) == (oper=='='));
+ }
+ else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
+ {
+ if(left_value.check_type<int>())
+ set_result(evaluate_arithmetic(oper, left_value.value<int>(), r_constant_value.value<int>()));
+ else if(left_value.check_type<unsigned>())
+ set_result(evaluate_arithmetic(oper, left_value.value<unsigned>(), r_constant_value.value<unsigned>()));
+ else if(left_value.check_type<float>())
+ set_result(evaluate_arithmetic(oper, left_value.value<float>(), r_constant_value.value<float>()));
+ }
+ else if(oper=='%' || ((oper=='<' || oper=='>') && oper2==oper))
+ {
+ if(left_value.check_type<int>())
+ set_result(evaluate_int_special_op(oper, left_value.value<int>(), r_constant_value.value<int>()));
+ else if(left_value.check_type<unsigned>())
+ set_result(evaluate_int_special_op(oper, left_value.value<unsigned>(), r_constant_value.value<unsigned>()));
+ }
+}
+
+void ConstantFolder::visit(Assignment &assign)
+{
+ TraversingVisitor::visit(assign);
+ r_constant = false;
+}
+
+void ConstantFolder::visit(TernaryExpression &ternary)
+{
+ TraversingVisitor::visit(ternary);
+ r_constant = false;
+}
+
+void ConstantFolder::visit(FunctionCall &call)
+{
+ if(call.constructor && call.type && call.arguments.size()==1)
+ {
+ const BasicTypeDeclaration *basic = dynamic_cast<const BasicTypeDeclaration *>(call.type);
+ if(basic)
+ {
+ visit(call.arguments[0]);
+ bool can_fold = r_constant;
+ r_constant = false;
+ if(!can_fold)
+ return;
+
+ if(basic->kind==BasicTypeDeclaration::BOOL)
+ convert_to_result<bool>(r_constant_value);
+ else if(basic->kind==BasicTypeDeclaration::INT && basic->size==32 && basic->sign)
+ convert_to_result<int>(r_constant_value);
+ else if(basic->kind==BasicTypeDeclaration::INT && basic->size==32 && !basic->sign)
+ convert_to_result<unsigned>(r_constant_value);
+ else if(basic->kind==BasicTypeDeclaration::FLOAT && basic->size==32)
+ convert_to_result<float>(r_constant_value);
+
+ return;
+ }
+ }
+
+ TraversingVisitor::visit(call);
+ r_constant = false;
+}
+
+void ConstantFolder::visit(VariableDeclaration &var)
+{
+ if(iteration_init && var.init_expression)
+ {
+ visit(var.init_expression);
+ if(r_constant)
+ {
+ /* Record the value of a constant initialization expression of an
+ iteration, so it can be used to evaluate the loop condition. */
+ iteration_var = &var;
+ iter_init_value = r_constant_value;
+ }
+ }
+ else
+ TraversingVisitor::visit(var);
+}
+
+void ConstantFolder::visit(Iteration &iter)
+{
+ SetForScope<Block *> set_block(current_block, &iter.body);
+
+ /* The iteration variable is not normally inlined into expressions, so we
+ process it specially here. If the initial value causes the loop condition
+ to evaluate to false, then the expression can be folded. */
+ iteration_var = 0;
+ if(iter.init_statement)
+ {
+ SetFlag set_init(iteration_init);
+ iter.init_statement->visit(*this);
+ }
+
+ if(iter.condition)
+ {
+ visit(iter.condition);
+ if(r_constant && r_constant_value.check_type<bool>() && !r_constant_value.value<bool>())
+ {
+ RefPtr<Literal> literal = new Literal;
+ literal->token = "false";
+ literal->value = r_constant_value;
+ iter.condition = literal;
+ }
+ }
+ iteration_var = 0;
+
+ iter.body.visit(*this);
+ if(iter.loop_expression)
+ visit(iter.loop_expression);
+}
+
+
+bool ConstantConditionEliminator::apply(Stage &stage)