#include <libyul/optimiser/ExpressionJoiner.h>
#include <libyul/optimiser/FunctionGrouper.h>
#include <libyul/optimiser/NameCollector.h>
#include <libyul/optimiser/OptimizerUtilities.h>
#include <libyul/Exceptions.h>
#include <libyul/AST.h>
#include <libsolutil/CommonData.h>
#include <range/v3/view/reverse.hpp>
#include <limits>
using namespace std;
using namespace solidity;
using namespace solidity::yul;
void ExpressionJoiner::run(OptimiserStepContext& _context, Block& _ast)
{
ExpressionJoiner{_ast}(_ast);
FunctionGrouper::run(_context, _ast);
}
void ExpressionJoiner::operator()(FunctionCall& _funCall)
{
handleArguments(_funCall.arguments);
}
void ExpressionJoiner::operator()(Block& _block)
{
resetLatestStatementPointer();
for (size_t i = 0; i < _block.statements.size(); ++i)
{
visit(_block.statements[i]);
m_currentBlock = &_block;
m_latestStatementInBlock = i;
}
removeEmptyBlocks(_block);
resetLatestStatementPointer();
}
void ExpressionJoiner::visit(Expression& _e)
{
if (holds_alternative<Identifier>(_e))
{
Identifier const& identifier = std::get<Identifier>(_e);
if (isLatestStatementVarDeclJoinable(identifier))
{
VariableDeclaration& varDecl = std::get<VariableDeclaration>(*latestStatement());
_e = std::move(*varDecl.value);
*latestStatement() = Block();
decrementLatestStatementPointer();
}
}
else
ASTModifier::visit(_e);
}
ExpressionJoiner::ExpressionJoiner(Block& _ast)
{
m_references = ReferencesCounter::countReferences(_ast);
}
void ExpressionJoiner::handleArguments(vector<Expression>& _arguments)
{
size_t i = _arguments.size();
for (Expression const& arg: _arguments | ranges::views::reverse)
{
--i;
if (!holds_alternative<Identifier>(arg) && !holds_alternative<Literal>(arg))
break;
}
for (; i < _arguments.size(); ++i)
visit(_arguments.at(i));
}
void ExpressionJoiner::decrementLatestStatementPointer()
{
if (!m_currentBlock)
return;
if (m_latestStatementInBlock > 0)
--m_latestStatementInBlock;
else
resetLatestStatementPointer();
}
void ExpressionJoiner::resetLatestStatementPointer()
{
m_currentBlock = nullptr;
m_latestStatementInBlock = numeric_limits<size_t>::max();
}
Statement* ExpressionJoiner::latestStatement()
{
if (!m_currentBlock)
return nullptr;
else
return &m_currentBlock->statements.at(m_latestStatementInBlock);
}
bool ExpressionJoiner::isLatestStatementVarDeclJoinable(Identifier const& _identifier)
{
Statement const* statement = latestStatement();
if (!statement || !holds_alternative<VariableDeclaration>(*statement))
return false;
VariableDeclaration const& varDecl = std::get<VariableDeclaration>(*statement);
if (varDecl.variables.size() != 1 || !varDecl.value)
return false;
assertThrow(varDecl.variables.size() == 1, OptimizerException, "");
assertThrow(varDecl.value, OptimizerException, "");
return varDecl.variables.at(0).name == _identifier.name && m_references[_identifier.name] == 1;
}