Skip to content

Commit

Permalink
Prune unreferenced functions from CFG
Browse files Browse the repository at this point in the history
  • Loading branch information
rodiazet committed Nov 27, 2024
1 parent 8ea8efd commit 199e229
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions libyul/backends/evm/ControlFlowGraphBuilder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,26 @@ namespace
/// Removes edges to blocks that are not reachable.
void cleanUnreachable(CFG& _cfg)
{
// If operation is a function call it adds the callee entry as child
auto const addFunctionsEntries = [&_cfg](CFG::BasicBlock* _node, auto&& _addChild)
{
for (auto const& operation: _node->operations)
{
if (auto const* functionCall = std::get_if<CFG::FunctionCall>(&operation.operation); functionCall != nullptr)
{
auto const functionInfo = _cfg.functionInfo.at(&(functionCall->function.get()));
_addChild(functionInfo.entry);
}
}
};

// Determine which blocks are reachable from the entry.
util::BreadthFirstSearch<CFG::BasicBlock*> reachabilityCheck{{_cfg.entry}};
for (auto const& functionInfo: _cfg.functionInfo | ranges::views::values)
reachabilityCheck.verticesToTraverse.emplace_back(functionInfo.entry);

reachabilityCheck.run([&](CFG::BasicBlock* _node, auto&& _addChild) {
addFunctionsEntries(_node, _addChild);
visit(util::GenericVisitor{
[&](CFG::BasicBlock::Jump const& _jump) {
_addChild(_jump.target);
Expand All @@ -76,6 +90,16 @@ void cleanUnreachable(CFG& _cfg)
cxx20::erase_if(node->entries, [&](CFG::BasicBlock* entry) -> bool {
return !reachabilityCheck.visited.count(entry);
});

// Remove functions which are never referenced.
_cfg.functions.erase(std::remove_if(_cfg.functions.begin(), _cfg.functions.end(), [&](auto const& item) {
return !reachabilityCheck.visited.count(_cfg.functionInfo.at(item).entry);
}), _cfg.functions.end());

// Remove functionInfos which are never referenced.
cxx20::erase_if(_cfg.functionInfo, [&](auto const& entry) -> bool {
return !reachabilityCheck.visited.count(entry.second.entry);
});
}

/// Sets the ``recursive`` member to ``true`` for all recursive function calls.
Expand Down

0 comments on commit 199e229

Please sign in to comment.