Have the stack optimization in the code transform only reuse slots that are reachable and fix argument slot reuse on functions without return variables.

This commit is contained in:
Daniel Kirchner
2021-06-28 18:11:57 +02:00
committed by hrkrshnn
parent dfce7b667d
commit bc288aacf5
3 changed files with 53 additions and 10 deletions
+20 -10
View File
@@ -182,16 +182,24 @@ void CodeTransform::operator()(VariableDeclaration const& _varDecl)
else
m_variablesScheduledForDeletion.insert(&var);
}
else if (m_unusedStackSlots.empty())
atTopOfStack = false;
else
{
auto slot = static_cast<size_t>(*m_unusedStackSlots.begin());
m_unusedStackSlots.erase(m_unusedStackSlots.begin());
m_context->variableStackHeights[&var] = slot;
if (size_t heightDiff = variableHeightDiff(var, varName, true))
m_assembly.appendInstruction(evmasm::swapInstruction(static_cast<unsigned>(heightDiff - 1)));
m_assembly.appendInstruction(evmasm::Instruction::POP);
bool foundUnusedSlot = false;
for (auto it = m_unusedStackSlots.begin(); it != m_unusedStackSlots.end(); ++it)
{
if (m_assembly.stackHeight() - *it > 17)
continue;
foundUnusedSlot = true;
auto slot = static_cast<size_t>(*it);
m_unusedStackSlots.erase(it);
m_context->variableStackHeights[&var] = slot;
if (size_t heightDiff = variableHeightDiff(var, varName, true))
m_assembly.appendInstruction(evmasm::swapInstruction(static_cast<unsigned>(heightDiff - 1)));
m_assembly.appendInstruction(evmasm::Instruction::POP);
break;
}
if (!foundUnusedSlot)
atTopOfStack = false;
}
}
}
@@ -404,7 +412,7 @@ void CodeTransform::operator()(FunctionDefinition const& _function)
subTransform.deleteVariable(var);
}
if (!m_allowStackOpt || _function.returnVariables.empty())
if (!m_allowStackOpt)
subTransform.setupReturnVariablesAndFunctionExit();
subTransform(_function.body);
@@ -594,6 +602,7 @@ void CodeTransform::visitExpression(Expression const& _expression)
void CodeTransform::setupReturnVariablesAndFunctionExit()
{
yulAssert(isInsideFunction(), "");
yulAssert(!returnVariablesAndFunctionExitAreSetup(), "");
yulAssert(m_scope, "");
@@ -656,7 +665,8 @@ void CodeTransform::visitStatements(vector<Statement> const& _statements)
{
freeUnusedVariables();
if (
!m_delayedReturnVariables.empty() &&
isInsideFunction() &&
!returnVariablesAndFunctionExitAreSetup() &&
statementNeedsReturnVariableSetup(statement, m_delayedReturnVariables)
)
setupReturnVariablesAndFunctionExit();