Skip to content

Commit 065a303

Browse files
authored
Merge pull request #11817 from ethereum/extendKnowledgeBase
Extend knowledge base
2 parents cef0f1b + 2165c0d commit 065a303

File tree

7 files changed

+231
-21
lines changed

7 files changed

+231
-21
lines changed

libevmasm/RuleList.h

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,22 @@ std::vector<SimplificationRule<Pattern>> simplificationRuleListPart8(
681681
// X - (A + Y) -> (X - Y) + (-A)
682682
Builtins::SUB(X, Builtins::ADD(A, Y)),
683683
[=]() -> Pattern { return Builtins::ADD(Builtins::SUB(X, Y), 0 - A.d()); }
684+
}, {
685+
// (X - A) - Y -> (X - Y) - A
686+
Builtins::SUB(Builtins::SUB(X, A), Y),
687+
[=]() -> Pattern { return Builtins::SUB(Builtins::SUB(X, Y), A); }
688+
}, {
689+
// (A - X) - Y -> A - (X + Y)
690+
Builtins::SUB(Builtins::SUB(A, X), Y),
691+
[=]() -> Pattern { return Builtins::SUB(A, Builtins::ADD(X, Y)); }
692+
}, {
693+
// X - (Y - A) -> (X - Y) + A
694+
Builtins::SUB(X, Builtins::SUB(Y, A)),
695+
[=]() -> Pattern { return Builtins::ADD(Builtins::SUB(X, Y), A.d()); }
696+
}, {
697+
// X - (A - Y) -> (X + Y) + (-A)
698+
Builtins::SUB(X, Builtins::SUB(A, Y)),
699+
[=]() -> Pattern { return Builtins::ADD(Builtins::ADD(X, Y), 0 - A.d()); }
684700
}
685701
};
686702
return rules;

libyul/optimiser/KnowledgeBase.cpp

Lines changed: 37 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,8 @@ bool KnowledgeBase::knownToBeDifferent(YulString _a, YulString _b)
4040
// current values to turn `sub(_a, _b)` into a nonzero constant.
4141
// If that fails, try `eq(_a, _b)`.
4242

43-
Expression expr1 = simplify(FunctionCall{{}, {{}, "sub"_yulstring}, util::make_vector<Expression>(Identifier{{}, _a}, Identifier{{}, _b})});
44-
if (holds_alternative<Literal>(expr1))
45-
return valueOfLiteral(std::get<Literal>(expr1)) != 0;
43+
if (optional<u256> difference = differenceIfKnownConstant(_a, _b))
44+
return difference != 0;
4645

4746
Expression expr2 = simplify(FunctionCall{{}, {{}, "eq"_yulstring}, util::make_vector<Expression>(Identifier{{}, _a}, Identifier{{}, _b})});
4847
if (holds_alternative<Literal>(expr2))
@@ -51,39 +50,59 @@ bool KnowledgeBase::knownToBeDifferent(YulString _a, YulString _b)
5150
return false;
5251
}
5352

53+
optional<u256> KnowledgeBase::differenceIfKnownConstant(YulString _a, YulString _b)
54+
{
55+
// Try to use the simplification rules together with the
56+
// current values to turn `sub(_a, _b)` into a constant.
57+
58+
Expression expr1 = simplify(FunctionCall{{}, {{}, "sub"_yulstring}, util::make_vector<Expression>(Identifier{{}, _a}, Identifier{{}, _b})});
59+
if (Literal const* value = get_if<Literal>(&expr1))
60+
return valueOfLiteral(*value);
61+
62+
return {};
63+
}
64+
5465
bool KnowledgeBase::knownToBeDifferentByAtLeast32(YulString _a, YulString _b)
5566
{
5667
// Try to use the simplification rules together with the
5768
// current values to turn `sub(_a, _b)` into a constant whose absolute value is at least 32.
5869

59-
Expression expr1 = simplify(FunctionCall{{}, {{}, "sub"_yulstring}, util::make_vector<Expression>(Identifier{{}, _a}, Identifier{{}, _b})});
60-
if (holds_alternative<Literal>(expr1))
61-
{
62-
u256 val = valueOfLiteral(std::get<Literal>(expr1));
63-
return val >= 32 && val <= u256(0) - 32;
64-
}
70+
if (optional<u256> difference = differenceIfKnownConstant(_a, _b))
71+
return difference >= 32 && difference <= u256(0) - 32;
6572

6673
return false;
6774
}
6875

76+
bool KnowledgeBase::knownToBeZero(YulString _a)
77+
{
78+
return valueIfKnownConstant(_a) == u256{};
79+
}
80+
81+
optional<u256> KnowledgeBase::valueIfKnownConstant(YulString _a)
82+
{
83+
if (m_variableValues.count(_a))
84+
if (Literal const* literal = get_if<Literal>(m_variableValues.at(_a).value))
85+
return valueOfLiteral(*literal);
86+
return {};
87+
}
88+
6989
Expression KnowledgeBase::simplify(Expression _expression)
7090
{
71-
bool startedRecursion = (m_recursionCounter == 0);
72-
ScopeGuard{[&] { if (startedRecursion) m_recursionCounter = 0; }};
91+
m_counter = 0;
92+
return simplifyRecursively(move(_expression));
93+
}
7394

74-
if (startedRecursion)
75-
m_recursionCounter = 100;
76-
else if (m_recursionCounter == 1)
95+
Expression KnowledgeBase::simplifyRecursively(Expression _expression)
96+
{
97+
if (m_counter++ > 100)
7798
return _expression;
78-
else
79-
--m_recursionCounter;
8099

81100
if (holds_alternative<FunctionCall>(_expression))
82101
for (Expression& arg: std::get<FunctionCall>(_expression).arguments)
83-
arg = simplify(arg);
102+
arg = simplifyRecursively(arg);
84103

85104
if (auto match = SimplificationRules::findFirstMatch(_expression, m_dialect, m_variableValues))
86-
return simplify(match->action().toExpression(debugDataOf(_expression)));
105+
return simplifyRecursively(match->action().toExpression(debugDataOf(_expression)));
87106

88107
return _expression;
89108
}

libyul/optimiser/KnowledgeBase.h

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
#include <libyul/ASTForward.h>
2525
#include <libyul/YulString.h>
2626

27+
#include <libsolutil/Common.h>
28+
2729
#include <map>
2830

2931
namespace solidity::yul
@@ -46,15 +48,19 @@ class KnowledgeBase
4648
{}
4749

4850
bool knownToBeDifferent(YulString _a, YulString _b);
51+
std::optional<u256> differenceIfKnownConstant(YulString _a, YulString _b);
4952
bool knownToBeDifferentByAtLeast32(YulString _a, YulString _b);
5053
bool knownToBeEqual(YulString _a, YulString _b) const { return _a == _b; }
54+
bool knownToBeZero(YulString _a);
55+
std::optional<u256> valueIfKnownConstant(YulString _a);
5156

5257
private:
5358
Expression simplify(Expression _expression);
59+
Expression simplifyRecursively(Expression _expression);
5460

5561
Dialect const& m_dialect;
5662
std::map<YulString, AssignedValue> const& m_variableValues;
57-
size_t m_recursionCounter = 0;
63+
size_t m_counter = 0;
5864
};
5965

6066
}

test/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ set(libyul_sources
136136
libyul/FunctionSideEffects.cpp
137137
libyul/FunctionSideEffects.h
138138
libyul/Inliner.cpp
139+
libyul/KnowledgeBaseTest.cpp
139140
libyul/Metrics.cpp
140141
libyul/ObjectCompilerTest.cpp
141142
libyul/ObjectCompilerTest.h

test/formal/sub_sub.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from rule import Rule
2+
from opcodes import *
3+
4+
"""
5+
Rules:
6+
SUB(SUB(X, A), Y) -> SUB(SUB(X, Y), A)
7+
SUB(SUB(A, X), Y) -> SUB(A, ADD(X, Y))
8+
SUB(X, SUB(Y, A)) -> ADD(SUB(X, Y), A)
9+
SUB(X, SUB(A, Y)) -> ADD(ADD(X, Y), -A)
10+
"""
11+
12+
rule = Rule()
13+
14+
n_bits = 256
15+
16+
# Input vars
17+
X = BitVec('X', n_bits)
18+
Y = BitVec('Y', n_bits)
19+
A = BitVec('A', n_bits)
20+
21+
rule.check(
22+
SUB(SUB(X, A), Y),
23+
SUB(SUB(X, Y), A)
24+
)
25+
rule.check(
26+
SUB(SUB(A, X), Y),
27+
SUB(A, ADD(X, Y))
28+
)
29+
rule.check(
30+
SUB(X, SUB(Y, A)),
31+
ADD(SUB(X, Y), A)
32+
)
33+
rule.check(
34+
SUB(X, SUB(A, Y)),
35+
ADD(ADD(X, Y), SUB(0, A))
36+
)

test/libsolidity/semanticTests/array/copying/copy_byte_array_in_struct_to_storage.sol

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,11 @@ contract C {
3737
// compileViaYul: also
3838
// ----
3939
// f() -> 0x40, 0x80, 6, 0x6162636465660000000000000000000000000000000000000000000000000000, 0x49, 0x3132333435363738393031323334353637383930313233343536373839303120, 0x3132333435363738393031323334353637383930313233343536373839303120, 0x3132333435363738390000000000000000000000000000000000000000000000
40-
// gas irOptimized: 179963
40+
// gas irOptimized: 179947
4141
// gas legacy: 180694
4242
// gas legacyOptimized: 180088
4343
// g() -> 0x40, 0xc0, 0x49, 0x3132333435363738393031323334353637383930313233343536373839303120, 0x3132333435363738393031323334353637383930313233343536373839303120, 0x3132333435363738390000000000000000000000000000000000000000000000, 0x11, 0x3132333435363738393233343536373839000000000000000000000000000000
44-
// gas irOptimized: 107332
44+
// gas irOptimized: 107322
4545
// gas legacy: 107895
4646
// gas legacyOptimized: 107254
4747
// h() -> 0x40, 0x60, 0x00, 0x00

test/libyul/KnowledgeBaseTest.cpp

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
/*
2+
This file is part of solidity.
3+
4+
solidity is free software: you can redistribute it and/or modify
5+
it under the terms of the GNU General Public License as published by
6+
the Free Software Foundation, either version 3 of the License, or
7+
(at your option) any later version.
8+
9+
solidity is distributed in the hope that it will be useful,
10+
but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
GNU General Public License for more details.
13+
14+
You should have received a copy of the GNU General Public License
15+
along with solidity. If not, see <http://www.gnu.org/licenses/>.
16+
*/
17+
/**
18+
* Unit tests for KnowledgeBase
19+
*/
20+
21+
#include <test/Common.h>
22+
23+
#include <test/libyul/Common.h>
24+
25+
#include <libyul/Object.h>
26+
#include <libyul/optimiser/KnowledgeBase.h>
27+
#include <libyul/optimiser/SSAValueTracker.h>
28+
#include <libyul/optimiser/DataFlowAnalyzer.h>
29+
#include <libyul/optimiser/NameDispenser.h>
30+
#include <libyul/optimiser/CommonSubexpressionEliminator.h>
31+
#include <libyul/backends/evm/EVMDialect.h>
32+
33+
#include <liblangutil/ErrorReporter.h>
34+
35+
#include <boost/test/unit_test.hpp>
36+
37+
using namespace std;
38+
using namespace solidity::langutil;
39+
40+
namespace solidity::yul::test
41+
{
42+
43+
class KnowledgeBaseTest
44+
{
45+
protected:
46+
KnowledgeBase constructKnowledgeBase(string const& _source)
47+
{
48+
ErrorList errorList;
49+
shared_ptr<AsmAnalysisInfo> analysisInfo;
50+
std::tie(m_object, analysisInfo) = yul::test::parse(_source, m_dialect, errorList);
51+
BOOST_REQUIRE(m_object && errorList.empty() && m_object->code);
52+
53+
NameDispenser dispenser(m_dialect, *m_object->code);
54+
std::set<YulString> reserved;
55+
OptimiserStepContext context{m_dialect, dispenser, reserved, 0};
56+
CommonSubexpressionEliminator::run(context, *m_object->code);
57+
58+
m_ssaValues(*m_object->code);
59+
for (auto const& [name, expression]: m_ssaValues.values())
60+
m_values[name].value = expression;
61+
62+
return KnowledgeBase(m_dialect, m_values);
63+
}
64+
65+
EVMDialect m_dialect{EVMVersion{}, true};
66+
shared_ptr<Object> m_object;
67+
SSAValueTracker m_ssaValues;
68+
map<YulString, AssignedValue> m_values;
69+
};
70+
71+
BOOST_FIXTURE_TEST_SUITE(KnowledgeBase, KnowledgeBaseTest)
72+
73+
BOOST_AUTO_TEST_CASE(basic)
74+
{
75+
yul::KnowledgeBase kb = constructKnowledgeBase(R"({
76+
let a := calldataload(0)
77+
let b := calldataload(0)
78+
let zero := 0
79+
let c := add(b, 0)
80+
let d := mul(b, 0)
81+
let e := sub(a, b)
82+
})");
83+
84+
BOOST_CHECK(!kb.knownToBeDifferent("a"_yulstring, "b"_yulstring));
85+
// This only works if the variable names are the same.
86+
// It assumes that SSA+CSE+Simplifier actually replaces the variables.
87+
BOOST_CHECK(!kb.knownToBeEqual("a"_yulstring, "b"_yulstring));
88+
BOOST_CHECK(!kb.valueIfKnownConstant("a"_yulstring));
89+
BOOST_CHECK(kb.valueIfKnownConstant("zero"_yulstring) == u256(0));
90+
}
91+
92+
BOOST_AUTO_TEST_CASE(difference)
93+
{
94+
yul::KnowledgeBase kb = constructKnowledgeBase(R"({
95+
let a := calldataload(0)
96+
let b := add(a, 200)
97+
let c := add(a, 220)
98+
let d := add(c, 12)
99+
let e := sub(c, 12)
100+
})");
101+
102+
BOOST_CHECK(
103+
kb.differenceIfKnownConstant("c"_yulstring, "b"_yulstring) ==
104+
u256(20)
105+
);
106+
BOOST_CHECK(
107+
kb.differenceIfKnownConstant("b"_yulstring, "c"_yulstring) ==
108+
u256(-20)
109+
);
110+
BOOST_CHECK(!kb.knownToBeDifferentByAtLeast32("b"_yulstring, "c"_yulstring));
111+
BOOST_CHECK(kb.knownToBeDifferentByAtLeast32("b"_yulstring, "d"_yulstring));
112+
BOOST_CHECK(kb.knownToBeDifferentByAtLeast32("a"_yulstring, "b"_yulstring));
113+
BOOST_CHECK(kb.knownToBeDifferentByAtLeast32("b"_yulstring, "a"_yulstring));
114+
115+
BOOST_CHECK(
116+
kb.differenceIfKnownConstant("e"_yulstring, "a"_yulstring) == u256(208)
117+
);
118+
BOOST_CHECK(
119+
kb.differenceIfKnownConstant("e"_yulstring, "b"_yulstring) == u256(8)
120+
);
121+
BOOST_CHECK(
122+
kb.differenceIfKnownConstant("a"_yulstring, "e"_yulstring) == u256(-208)
123+
);
124+
BOOST_CHECK(
125+
kb.differenceIfKnownConstant("b"_yulstring, "e"_yulstring) == u256(-8)
126+
);
127+
}
128+
129+
130+
BOOST_AUTO_TEST_SUITE_END()
131+
132+
}

0 commit comments

Comments
 (0)