Skip to content

Add option to treat literal assignments as operations in SSACFGs #16041

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions libyul/YulControlFlowGraphExporter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -177,12 +177,20 @@ Json YulControlFlowGraphExporter::toJson(SSACFG const& _cfg, SSACFG::BlockId _bl
Json YulControlFlowGraphExporter::toJson(Json& _ret, SSACFG const& _cfg, SSACFG::Operation const& _operation)
{
Json opJson = Json::object();
std::visit(util::GenericVisitor{
[&](SSACFG::Call const& _call) {
std::visit(GenericVisitor{
[&](SSACFG::Call const& _call)
{
_ret["type"] = "FunctionCall";
opJson["op"] = _call.function.get().name.str();
},
[&](SSACFG::BuiltinCall const& _call) {
[&](SSACFG::LiteralAssignment const&)
{
yulAssert(_operation.inputs.size() == 1);
yulAssert(_cfg.isLiteralValue(_operation.inputs.back()));
_ret["type"] = "LiteralAssignment";
},
[&](SSACFG::BuiltinCall const& _call)
{
_ret["type"] = "BuiltinCall";
Json builtinArgsJson = Json::array();
auto const& builtin = _call.builtin.get();
Expand Down
8 changes: 6 additions & 2 deletions libyul/YulStack.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -394,11 +394,15 @@ Json YulStack::cfgJson() const
yulAssert(m_parserResult->analysisInfo, "");
// FIXME: we should not regenerate the cfg, but for now this is sufficient for testing purposes
auto exportCFGFromObject = [&](Object const& _object) -> Json {
// with this set to `true`, assignments of the type `let x := 42` are preserved and added as assignment
// operations to the control flow graphs
bool constexpr keepLiteralAssignments = true;
// NOTE: The block Ids are reset for each object
std::unique_ptr<ControlFlow> controlFlow = SSAControlFlowGraphBuilder::build(
*_object.analysisInfo.get(),
*_object.analysisInfo,
languageToDialect(m_language, m_evmVersion, m_eofVersion),
_object.code()->root()
_object.code()->root(),
keepLiteralAssignments
);
std::unique_ptr<ControlFlowLiveness> liveness = std::make_unique<ControlFlowLiveness>(*controlFlow);
YulControlFlowGraphExporter exporter(*controlFlow, liveness.get());
Expand Down
21 changes: 16 additions & 5 deletions libyul/backends/evm/SSAControlFlowGraph.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -168,17 +168,28 @@ class SSACFGPrinter
[&](SSACFG::BuiltinCall const& _call) {
return _call.builtin.get().name;
},
[&](SSACFG::LiteralAssignment const&)
{
yulAssert(operation.inputs.size() == 1);
return varToString(m_cfg, operation.inputs.back());
}
}, operation.kind);
if (!operation.outputs.empty())
m_result << fmt::format(
"{} := ",
fmt::join(operation.outputs | ranges::views::transform(valueToString), ", ")
);
m_result << fmt::format(
"{}({})\\l\\\n",
escape(label),
fmt::join(operation.inputs | ranges::views::transform(valueToString), ", ")
);
if (std::holds_alternative<SSACFG::LiteralAssignment>(operation.kind))
m_result << fmt::format(
"{}\\l\\\n",
escape(label)
);
else
m_result << fmt::format(
"{}({})\\l\\\n",
escape(label),
fmt::join(operation.inputs | ranges::views::transform(valueToString), ", ")
);
}
m_result << "\"];\n";
std::visit(GenericVisitor{
Expand Down
8 changes: 6 additions & 2 deletions libyul/backends/evm/SSAControlFlowGraph.h
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,14 @@ class SSACFG
std::reference_wrapper<FunctionCall const> call;
bool canContinue;
};
struct LiteralAssignment
{
langutil::DebugData::ConstPtr debugData;
};

struct Operation {
std::vector<ValueId> outputs{};
std::variant<BuiltinCall, Call> kind;
std::variant<BuiltinCall, Call, LiteralAssignment> kind;
std::vector<ValueId> inputs{};
};
struct BasicBlock
Expand Down Expand Up @@ -199,7 +203,7 @@ class SSACFG
}
ValueId newLiteral(langutil::DebugData::ConstPtr _debugData, u256 _value)
{
auto [it, inserted] = m_literals.emplace(_value, SSACFG::ValueId{m_valueInfos.size()});
auto [it, inserted] = m_literals.emplace(_value, ValueId{m_valueInfos.size()});
if (inserted)
m_valueInfos.emplace_back(LiteralValue{std::move(_debugData), _value});
else
Expand Down
65 changes: 41 additions & 24 deletions libyul/backends/evm/SSAControlFlowGraphBuilder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,18 @@
*/

#include <libyul/backends/evm/SSAControlFlowGraphBuilder.h>
#include <libyul/AST.h>
#include <libyul/Exceptions.h>

#include <libyul/backends/evm/ControlFlow.h>
#include <libyul/AST.h>
#include <libyul/ControlFlowSideEffectsCollector.h>
#include <libyul/Exceptions.h>
#include <libyul/Utilities.h>

#include <libsolutil/Algorithms.h>
#include <libsolutil/StringUtils.h>
#include <libsolutil/Visitor.h>

#include <range/v3/algorithm/replace.hpp>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/drop_last.hpp>
#include <range/v3/view/enumerate.hpp>
Expand All @@ -49,26 +51,29 @@ SSAControlFlowGraphBuilder::SSAControlFlowGraphBuilder(
SSACFG& _graph,
AsmAnalysisInfo const& _analysisInfo,
ControlFlowSideEffectsCollector const& _sideEffects,
Dialect const& _dialect
Dialect const& _dialect,
bool _keepLiteralAssignments
):
m_controlFlow(_controlFlow),
m_graph(_graph),
m_info(_analysisInfo),
m_sideEffects(_sideEffects),
m_dialect(_dialect)
m_dialect(_dialect),
m_keepLiteralAssignments(_keepLiteralAssignments)
{
}

std::unique_ptr<ControlFlow> SSAControlFlowGraphBuilder::build(
AsmAnalysisInfo const& _analysisInfo,
Dialect const& _dialect,
Block const& _block
Block const& _block,
bool _keepLiteralAssignments
)
{
ControlFlowSideEffectsCollector sideEffects(_dialect, _block);

auto controlFlow = std::make_unique<ControlFlow>();
SSAControlFlowGraphBuilder builder(*controlFlow, *controlFlow->mainGraph, _analysisInfo, sideEffects, _dialect);
SSAControlFlowGraphBuilder builder(*controlFlow, *controlFlow->mainGraph, _analysisInfo, sideEffects, _dialect, _keepLiteralAssignments);
builder.m_currentBlock = controlFlow->mainGraph->makeBlock(debugDataOf(_block));
builder.sealBlock(builder.m_currentBlock);
builder(_block);
Expand Down Expand Up @@ -147,8 +152,8 @@ SSACFG::ValueId SSAControlFlowGraphBuilder::tryRemoveTrivialPhi(SSACFG::ValueId
[](SSACFG::BasicBlock::Terminated&) {}
}, block.exit);
}
for (auto& [_, currentVariableDefs]: m_currentDef)
std::replace(currentVariableDefs.begin(), currentVariableDefs.end(), _phi, same);
for (auto& currentVariableDefs: m_currentDef | ranges::views::values)
ranges::replace(currentVariableDefs, _phi, same);

for (auto phiUse: phiUses)
tryRemoveTrivialPhi(phiUse);
Expand Down Expand Up @@ -178,11 +183,6 @@ void SSAControlFlowGraphBuilder::cleanUnreachable()
}, block.exit);
});

auto isUnreachableValue = [&](SSACFG::ValueId const& _value) -> bool {
auto* valueInfo = std::get_if<SSACFG::UnreachableValue>(&m_graph.valueInfo(_value));
return (valueInfo) ? true : false;
};

// Remove all entries from unreachable nodes from the graph.
for (SSACFG::BlockId blockId: reachabilityCheck.visited)
{
Expand All @@ -197,7 +197,7 @@ void SSAControlFlowGraphBuilder::cleanUnreachable()
for (auto phi: block.phis)
if (auto* phiInfo = std::get_if<SSACFG::PhiValue>(&m_graph.valueInfo(phi)))
std::erase_if(phiInfo->arguments, [&](SSACFG::ValueId _arg) {
if (isUnreachableValue(_arg))
if (std::holds_alternative<SSACFG::UnreachableValue>(m_graph.valueInfo(_arg)))
{
maybeTrivialPhi.insert(phi);
return true;
Expand Down Expand Up @@ -240,7 +240,7 @@ void SSAControlFlowGraphBuilder::buildFunctionGraph(
cfg.arguments = arguments;
cfg.returns = returns;

SSAControlFlowGraphBuilder builder(m_controlFlow, cfg, m_info, m_sideEffects, m_dialect);
SSAControlFlowGraphBuilder builder(m_controlFlow, cfg, m_info, m_sideEffects, m_dialect, m_keepLiteralAssignments);
builder.m_currentBlock = cfg.entry;
builder.m_functionDefinitions = m_functionDefinitions;
for (auto&& [var, varId]: cfg.arguments)
Expand Down Expand Up @@ -273,6 +273,11 @@ void SSAControlFlowGraphBuilder::operator()(Assignment const& _assignment)

void SSAControlFlowGraphBuilder::operator()(VariableDeclaration const& _variableDeclaration)
{
// if we have no value (like in `let a` without right-hand side), we can just skip this. the variable(s) will be
// added when first needed
if (!_variableDeclaration.value)
return;

assign(
_variableDeclaration.variables | ranges::views::transform([&](auto& _var) { return std::ref(lookupVariable(_var.name)); }) | ranges::to<std::vector>,
_variableDeclaration.value.get()
Expand Down Expand Up @@ -533,15 +538,27 @@ void SSAControlFlowGraphBuilder::assign(std::vector<std::reference_wrapper<Scope
auto rhs = [&]() -> std::vector<SSACFG::ValueId> {
if (auto const* functionCall = std::get_if<FunctionCall>(_expression))
return visitFunctionCall(*functionCall);
else if (_expression)
if (_expression)
return {std::visit(*this, *_expression)};
else
return {_variables.size(), zero()};
return {_variables.size(), zero()};
}();
yulAssert(rhs.size() == _variables.size());

for (auto const& [var, value]: ranges::zip_view(_variables, rhs))
writeVariable(var, m_currentBlock, value);
{
if (m_keepLiteralAssignments && m_graph.isLiteralValue(value))
{
SSACFG::Operation assignment{
.outputs = {m_graph.newVariable(m_currentBlock)},
.kind = SSACFG::LiteralAssignment{},
.inputs = {value}
};
currentBlock().operations.emplace_back(assignment);
writeVariable(var, m_currentBlock, assignment.outputs.back());
}
else
writeVariable(var, m_currentBlock, value);
}

}

Expand Down Expand Up @@ -610,7 +627,7 @@ SSACFG::ValueId SSAControlFlowGraphBuilder::readVariableRecursive(Scope::Variabl
// incomplete block
val = m_graph.newPhi(_block);
block.phis.insert(val);
info.incompletePhis.emplace_back(val, std::ref(_variable));
info.incompletePhis.emplace_back(val, _variable);
}
else if (block.entries.size() == 1)
// one predecessor: no phi needed
Expand All @@ -633,7 +650,7 @@ SSACFG::ValueId SSAControlFlowGraphBuilder::addPhiOperands(Scope::Variable const
{
yulAssert(std::holds_alternative<SSACFG::PhiValue>(m_graph.valueInfo(_phi)));
auto& phi = std::get<SSACFG::PhiValue>(m_graph.valueInfo(_phi));
for (auto pred: m_graph.block(phi.block).entries)
for (auto const& pred: m_graph.block(phi.block).entries)
phi.arguments.emplace_back(readVariable(_variable, pred));
// we call tryRemoveTrivialPhi explicitly to avoid removing trivial phis in unsealed blocks
return _phi;
Expand All @@ -660,14 +677,14 @@ Scope::Variable const& SSAControlFlowGraphBuilder::lookupVariable(YulName _name)
yulAssert(m_scope, "");
Scope::Variable const* var = nullptr;
if (m_scope->lookup(_name, util::GenericVisitor{
[&](Scope::Variable& _var) { var = &_var; },
[](Scope::Function&)
[&](Scope::Variable const& _var) { var = &_var; },
[](Scope::Function const&)
{
yulAssert(false, "Function not removed during desugaring.");
}
}))
{
yulAssert(var, "");
yulAssert(var);
return *var;
};
yulAssert(false, "External identifier access unimplemented.");
Expand Down
7 changes: 5 additions & 2 deletions libyul/backends/evm/SSAControlFlowGraphBuilder.h
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,17 @@ class SSAControlFlowGraphBuilder
SSACFG& _graph,
AsmAnalysisInfo const& _analysisInfo,
ControlFlowSideEffectsCollector const& _sideEffects,
Dialect const& _dialect
Dialect const& _dialect,
bool _keepLiteralAssignments
);
public:
SSAControlFlowGraphBuilder(SSAControlFlowGraphBuilder const&) = delete;
SSAControlFlowGraphBuilder& operator=(SSAControlFlowGraphBuilder const&) = delete;
static std::unique_ptr<ControlFlow> build(
AsmAnalysisInfo const& _analysisInfo,
Dialect const& _dialect,
Block const& _block
Block const& _block,
bool _keepLiteralAssignments
);

void operator()(ExpressionStatement const& _statement);
Expand Down Expand Up @@ -92,6 +94,7 @@ class SSAControlFlowGraphBuilder
AsmAnalysisInfo const& m_info;
ControlFlowSideEffectsCollector const& m_sideEffects;
Dialect const& m_dialect;
bool const m_keepLiteralAssignments;
std::vector<std::tuple<Scope::Function const*, FunctionDefinition const*>> m_functionDefinitions;
SSACFG::BlockId m_currentBlock;
SSACFG::BasicBlock& currentBlock() { return m_graph.block(m_currentBlock); }
Expand Down
Loading