Skip to content
Draft
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
2 changes: 2 additions & 0 deletions libyul/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ add_library(yul
optimiser/CircularReferencesPruner.h
optimiser/CommonSubexpressionEliminator.cpp
optimiser/CommonSubexpressionEliminator.h
optimiser/ConditionalBranchFlattener.cpp
optimiser/ConditionalBranchFlattener.h
optimiser/ConditionalSimplifier.cpp
optimiser/ConditionalSimplifier.h
optimiser/ConditionalUnsimplifier.cpp
Expand Down
154 changes: 154 additions & 0 deletions libyul/optimiser/ConditionalBranchFlattener.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/*
This file is part of solidity.

solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/optimiser/ConditionalBranchFlattener.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/NameDispenser.h>
#include <libyul/AST.h>
#include <libyul/Dialect.h>

#include <libsolutil/CommonData.h>

using namespace solidity;
using namespace solidity::yul;
using namespace solidity::util;

void ConditionalBranchFlattener::run(OptimiserStepContext& _context, Block& _ast)
{
ConditionalBranchFlattener{_context}(_ast);
}

void ConditionalBranchFlattener::operator()(Block& _block)
{
iterateReplacing(
_block.statements,
[&](Statement& _s) -> std::optional<std::vector<Statement>>
{
visit(_s);

if (!std::holds_alternative<If>(_s))
return {};

If& ifStatement = std::get<If>(_s);
std::vector<Statement>& bodyStatements = ifStatement.body.statements;

if (bodyStatements.size() != 1)
return {};

Statement& bodyStatement = bodyStatements.front();
if (!std::holds_alternative<Assignment>(bodyStatement))
return {};

Assignment& assignment = std::get<Assignment>(bodyStatement);
if (assignment.variableNames.size() != 1)
return {};

SideEffectsCollector sideEffectsCollector(m_context.dialect);
sideEffectsCollector.visit(*assignment.value);
if (!sideEffectsCollector.movable())
return {};

langutil::DebugData::ConstPtr debugData = ifStatement.debugData;
YulName conditionName = m_context.dispenser.newName({YulName("condition")});

auto normalizedCondition = std::make_unique<Expression>(
createBuiltinCall(
debugData,
"iszero",
make_vector<Expression>(
createBuiltinCall(
debugData,
"iszero",
make_vector<Expression>(std::move(*ifStatement.condition))
)
)
)
);

std::vector<Statement> transformed;
transformed.reserve(2);

transformed.push_back(VariableDeclaration{
debugData,
{NameWithDebugData{debugData, conditionName}},
std::move(normalizedCondition)
});

YulName targetName = assignment.variableNames[0].name;
std::unique_ptr<Expression> rhs = std::move(assignment.value);

Expression mask = createBuiltinCall(
debugData,
"sub",
make_vector<Expression>(
m_context.dialect.zeroLiteral(),
Identifier{debugData, conditionName}
)
);

Expression diff = createBuiltinCall(
debugData,
"xor",
make_vector<Expression>(
Identifier{debugData, targetName},
std::move(*rhs)
)
);

Expression maskedDiff = createBuiltinCall(
debugData,
"and",
make_vector<Expression>(
std::move(mask),
std::move(diff)
)
);

Expression finalExpr = createBuiltinCall(
debugData,
"xor",
make_vector<Expression>(
Identifier{debugData, targetName},
std::move(maskedDiff)
)
);

transformed.push_back(Assignment{
debugData,
assignment.variableNames,
std::make_unique<Expression>(std::move(finalExpr))
});

return transformed;
}
);
}

FunctionCall ConditionalBranchFlattener::createBuiltinCall(
langutil::DebugData::ConstPtr _debugData,
std::string const& _name,
std::vector<Expression> _arguments
)
{
auto handle = m_context.dialect.findBuiltin(_name);
yulAssert(handle.has_value(), "Builtin not found: " + _name);
return FunctionCall{
std::move(_debugData),
{BuiltinName{nullptr, *handle}},
std::move(_arguments)
};
}
69 changes: 69 additions & 0 deletions libyul/optimiser/ConditionalBranchFlattener.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
This file is part of solidity.

solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.
#pragma once

#include <libyul/optimiser/ASTWalker.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/AST.h>

namespace solidity::yul
{

/**
* Replaces conditional execution with branchless bitwise operations.
*
* Rewrites:
* if c { x := a }
* to:
* let condition := iszero(iszero(c))
* x := xor(x, and(sub(0, condition), xor(a, x)))
*
* This transformation is applied if:
* - The body of the `if` statement contains a single assignment.
* - All RHS expressions in the assignment are movable.
* - There are no control flow statements in the body.
*
* The logic `xor(x, and(sub(0, condition), xor(a, x)))` effectively implements
* `condition ? a : x` using bitwise operations, relying on `condition` being 0 or 1.
* `sub(0, condition)` generates a mask of all ones if condition is 1, and all zeros if condition
* is 0.
*
* Prerequisites: Disambiguator
*/
class ConditionalBranchFlattener: public ASTModifier
{
public:
static constexpr char const* name = "ConditionalBranchFlattener";
static void run(OptimiserStepContext& _context, Block& _ast);

using ASTModifier::operator();
void operator()(Block& _block) override;

private:
ConditionalBranchFlattener(OptimiserStepContext& _context): m_context(_context) {}

FunctionCall createBuiltinCall(
langutil::DebugData::ConstPtr _debugData,
std::string const& _name,
std::vector<Expression> _arguments
);

OptimiserStepContext& m_context;
};

}
3 changes: 3 additions & 0 deletions libyul/optimiser/Suite.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
#include <libyul/optimiser/BlockFlattener.h>
#include <libyul/optimiser/CallGraphGenerator.h>
#include <libyul/optimiser/CircularReferencesPruner.h>
#include <libyul/optimiser/ConditionalBranchFlattener.h>
#include <libyul/optimiser/ControlFlowSimplifier.h>
#include <libyul/optimiser/ConditionalSimplifier.h>
#include <libyul/optimiser/ConditionalUnsimplifier.h>
Expand Down Expand Up @@ -232,6 +233,7 @@ std::map<std::string, std::unique_ptr<OptimiserStep>> const& OptimiserSuite::all
BlockFlattener,
CircularReferencesPruner,
CommonSubexpressionEliminator,
ConditionalBranchFlattener,
ConditionalSimplifier,
ConditionalUnsimplifier,
ControlFlowSimplifier,
Expand Down Expand Up @@ -273,6 +275,7 @@ std::map<std::string, char> const& OptimiserSuite::stepNameToAbbreviationMap()
{BlockFlattener::name, 'f'},
{CircularReferencesPruner::name, 'l'},
{CommonSubexpressionEliminator::name, 'c'},
{ConditionalBranchFlattener::name, 'B'},
{ConditionalSimplifier::name, 'C'},
{ConditionalUnsimplifier::name, 'U'},
{ControlFlowSimplifier::name, 'n'},
Expand Down
7 changes: 7 additions & 0 deletions test/libyul/YulOptimizerTestCommon.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
#include <libyul/optimiser/DeadCodeEliminator.h>
#include <libyul/optimiser/Disambiguator.h>
#include <libyul/optimiser/CircularReferencesPruner.h>
#include <libyul/optimiser/ConditionalBranchFlattener.h>
#include <libyul/optimiser/ConditionalUnsimplifier.h>
#include <libyul/optimiser/ConditionalSimplifier.h>
#include <libyul/optimiser/CommonSubexpressionEliminator.h>
Expand Down Expand Up @@ -142,6 +143,12 @@ YulOptimizerTestCommon::YulOptimizerTestCommon(std::shared_ptr<Object const> _ob
CommonSubexpressionEliminator::run(*m_context, block);
return block;
}},
{"conditionalBranchFlattener", [&]() {
auto block = disambiguate();
updateContext(block);
ConditionalBranchFlattener::run(*m_context, block);
return block;
}},
{"conditionalUnsimplifier", [&]() {
auto block = disambiguate();
updateContext(block);
Expand Down
12 changes: 12 additions & 0 deletions test/libyul/yulOptimizerTests/conditionalBranchFlattener/basic.yul
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
let x := mload(0)
if slt(x, 0) { x := sub(0, x) }
}
// ----
// step: conditionalBranchFlattener
//
// {
// let x := mload(0)
// let condition := iszero(iszero(slt(x, 0)))
// x := xor(x, and(sub(0, condition), xor(x, sub(0, x))))
// }
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
let x := 10
let c := 1
if c { x := add(x, 1) }
}
// ----
// step: conditionalBranchFlattener
//
// {
// let x := 10
// let c := 1
// let condition := iszero(iszero(c))
// x := xor(x, and(sub(0, condition), xor(x, add(x, 1))))
// }
21 changes: 21 additions & 0 deletions test/libyul/yulOptimizerTests/conditionalBranchFlattener/multi.yul
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
let x := mload(0)
let y := mload(0)
if slt(x, 0) {
x := sub(0, x)
}
if slt(y, 0) {
y := add(y, 2)
}
}
// ----
// step: conditionalBranchFlattener
//
// {
// let x := mload(0)
// let y := mload(0)
// let condition := iszero(iszero(slt(x, 0)))
// x := xor(x, and(sub(0, condition), xor(x, sub(0, x))))
// let condition_1 := iszero(iszero(slt(y, 0)))
// y := xor(y, and(sub(0, condition_1), xor(y, add(y, 2))))
// }
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
let x := mload(0)
if slt(x, 0) { x := not(x) }
}
// ----
// step: conditionalBranchFlattener
//
// {
// let x := mload(0)
// let condition := iszero(iszero(slt(x, 0)))
// x := xor(x, and(sub(0, condition), xor(x, not(x))))
// }
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
let x := mload(0)
if slt(0, x) { x := sub(0, x) }
}
// ----
// step: conditionalBranchFlattener
//
// {
// let x := mload(0)
// let condition := iszero(iszero(slt(0, x)))
// x := xor(x, and(sub(0, condition), xor(x, sub(0, x))))
// }
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
let x := mload(0)
let y := mload(0)
if slt(x, 0) {
x := sub(0, x)
y := add(y, 2)
}
}
// ----
// step: conditionalBranchFlattener
//
// {
// let x := mload(0)
// let y := mload(0)
// if slt(x, 0)
// {
// x := sub(0, x)
// y := add(y, 2)
// }
// }
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
let x := 10
if x { sstore(0, 1) }
}
// ----
// step: conditionalBranchFlattener
//
// {
// let x := 10
// if x { sstore(0, 1) }
// }
Loading