Skip to content

Commit 2b979cb

Browse files
committed
Also optimize memory.
1 parent 8572600 commit 2b979cb

24 files changed

+331
-63
lines changed

libyul/CMakeLists.txt

+2-2
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,8 @@ add_library(yul
9696
optimiser/InlinableExpressionFunctionFinder.h
9797
optimiser/KnowledgeBase.cpp
9898
optimiser/KnowledgeBase.h
99+
optimiser/LoadResolver.cpp
100+
optimiser/LoadResolver.h
99101
optimiser/MainFunction.cpp
100102
optimiser/MainFunction.h
101103
optimiser/Metrics.cpp
@@ -111,8 +113,6 @@ add_library(yul
111113
optimiser/RedundantAssignEliminator.cpp
112114
optimiser/RedundantAssignEliminator.h
113115
optimiser/Rematerialiser.cpp
114-
optimiser/SLoadResolver.cpp
115-
optimiser/SLoadResolver.h
116116
optimiser/Rematerialiser.h
117117
optimiser/SSAReverser.cpp
118118
optimiser/SSAReverser.h

libyul/Dialect.h

+3
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,9 @@ struct BuiltinFunction
6060
/// If false, storage of the current contract before and after the function is the same
6161
/// under every circumstance. If the function does not return, this can be false.
6262
bool invalidatesStorage = true;
63+
/// If false, memory before and after the function is the same under every circumstance.
64+
/// If the function does not return, this can be false.
65+
bool invalidatesMemory = true;
6366
/// If true, can only accept literals as arguments and they cannot be moved to variables.
6467
bool literalArguments = false;
6568
};

libyul/backends/evm/EVMDialect.cpp

+6-3
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ pair<YulString, BuiltinFunctionForEVM> createEVMFunction(
5555
f.sideEffectFreeIfNoMSize = eth::SemanticInformation::sideEffectFreeIfNoMSize(_instruction);
5656
f.isMSize = _instruction == dev::eth::Instruction::MSIZE;
5757
f.invalidatesStorage = eth::SemanticInformation::invalidatesStorage(_instruction);
58+
f.invalidatesMemory = eth::SemanticInformation::invalidatesMemory(_instruction);
5859
f.literalArguments = false;
5960
f.instruction = _instruction;
6061
f.generateCode = [_instruction](
@@ -78,6 +79,7 @@ pair<YulString, BuiltinFunctionForEVM> createFunction(
7879
bool _sideEffectFree,
7980
bool _sideEffectFreeIfNoMSize,
8081
bool _invalidatesStorage,
82+
bool _invalidatesMemory,
8183
bool _literalArguments,
8284
std::function<void(FunctionCall const&, AbstractAssembly&, BuiltinContext&, std::function<void()>)> _generateCode
8385
)
@@ -93,6 +95,7 @@ pair<YulString, BuiltinFunctionForEVM> createFunction(
9395
f.sideEffectFreeIfNoMSize = _sideEffectFreeIfNoMSize;
9496
f.isMSize = false;
9597
f.invalidatesStorage = _invalidatesStorage;
98+
f.invalidatesMemory = _invalidatesMemory;
9699
f.instruction = {};
97100
f.generateCode = std::move(_generateCode);
98101
return {name, f};
@@ -113,7 +116,7 @@ map<YulString, BuiltinFunctionForEVM> createBuiltins(langutil::EVMVersion _evmVe
113116

114117
if (_objectAccess)
115118
{
116-
builtins.emplace(createFunction("datasize", 1, 1, true, true, true, false, true, [](
119+
builtins.emplace(createFunction("datasize", 1, 1, true, true, true, false, false, true, [](
117120
FunctionCall const& _call,
118121
AbstractAssembly& _assembly,
119122
BuiltinContext& _context,
@@ -134,7 +137,7 @@ map<YulString, BuiltinFunctionForEVM> createBuiltins(langutil::EVMVersion _evmVe
134137
_assembly.appendDataSize(_context.subIDs.at(dataName));
135138
}
136139
}));
137-
builtins.emplace(createFunction("dataoffset", 1, 1, true, true, true, false, true, [](
140+
builtins.emplace(createFunction("dataoffset", 1, 1, true, true, true, false, false, true, [](
138141
FunctionCall const& _call,
139142
AbstractAssembly& _assembly,
140143
BuiltinContext& _context,
@@ -155,7 +158,7 @@ map<YulString, BuiltinFunctionForEVM> createBuiltins(langutil::EVMVersion _evmVe
155158
_assembly.appendDataOffset(_context.subIDs.at(dataName));
156159
}
157160
}));
158-
builtins.emplace(createFunction("datacopy", 3, 0, false, false, false, false, false, [](
161+
builtins.emplace(createFunction("datacopy", 3, 0, false, false, false, false, true, false, [](
159162
FunctionCall const&,
160163
AbstractAssembly& _assembly,
161164
BuiltinContext&,

libyul/backends/wasm/WasmDialect.cpp

+1
Original file line numberDiff line numberDiff line change
@@ -84,5 +84,6 @@ void WasmDialect::addFunction(string _name, size_t _params, size_t _returns)
8484
f.sideEffectFreeIfNoMSize = false;
8585
f.isMSize = false;
8686
f.invalidatesStorage = true;
87+
f.invalidatesMemory = true;
8788
f.literalArguments = false;
8889
}

libyul/optimiser/DataFlowAnalyzer.cpp

+82-28
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ using namespace yul;
4040

4141
void DataFlowAnalyzer::operator()(ExpressionStatement& _statement)
4242
{
43-
if (boost::optional<pair<YulString, YulString>> vars = isSimpleSStore(_statement))
43+
if (auto vars = isSimpleStore(dev::eth::Instruction::SSTORE, _statement))
4444
{
4545
ASTModifier::operator()(_statement);
4646
m_storage.set(vars->first, vars->second);
@@ -54,9 +54,22 @@ void DataFlowAnalyzer::operator()(ExpressionStatement& _statement)
5454
for (YulString const& key: keysToErase)
5555
m_storage.eraseKey(key);
5656
}
57+
else if (auto vars = isSimpleStore(dev::eth::Instruction::MSTORE, _statement))
58+
{
59+
ASTModifier::operator()(_statement);
60+
set<YulString> keysToErase;
61+
for (auto const& item: m_memory.values)
62+
if (!m_knowledgeBase.knownToBeDifferentByAtLeast32(vars->first, item.first))
63+
keysToErase.insert(item.first);
64+
// TODO is it fine to do that here?
65+
// can we also move the storage above?
66+
m_memory.set(vars->first, vars->second);
67+
for (YulString const& key: keysToErase)
68+
m_memory.eraseKey(key);
69+
}
5770
else
5871
{
59-
clearStorageKnowledgeIfInvalidated(_statement.expression);
72+
clearKnowledgeIfInvalidated(_statement.expression);
6073
ASTModifier::operator()(_statement);
6174
}
6275
}
@@ -67,7 +80,7 @@ void DataFlowAnalyzer::operator()(Assignment& _assignment)
6780
for (auto const& var: _assignment.variableNames)
6881
names.emplace(var.name);
6982
assertThrow(_assignment.value, OptimizerException, "");
70-
clearStorageKnowledgeIfInvalidated(*_assignment.value);
83+
clearKnowledgeIfInvalidated(*_assignment.value);
7184
visit(*_assignment.value);
7285
handleAssignment(names, _assignment.value.get());
7386
}
@@ -81,7 +94,7 @@ void DataFlowAnalyzer::operator()(VariableDeclaration& _varDecl)
8194

8295
if (_varDecl.value)
8396
{
84-
clearStorageKnowledgeIfInvalidated(*_varDecl.value);
97+
clearKnowledgeIfInvalidated(*_varDecl.value);
8598
visit(*_varDecl.value);
8699
}
87100

@@ -90,12 +103,13 @@ void DataFlowAnalyzer::operator()(VariableDeclaration& _varDecl)
90103

91104
void DataFlowAnalyzer::operator()(If& _if)
92105
{
93-
clearStorageKnowledgeIfInvalidated(*_if.condition);
106+
clearKnowledgeIfInvalidated(*_if.condition);
94107
InvertibleMap<YulString, YulString> storage = m_storage;
108+
InvertibleMap<YulString, YulString> memory = m_memory;
95109

96110
ASTModifier::operator()(_if);
97111

98-
joinStorageKnowledge(storage);
112+
joinKnowledge(storage, memory);
99113

100114
Assignments assignments;
101115
assignments(_if.body);
@@ -104,24 +118,25 @@ void DataFlowAnalyzer::operator()(If& _if)
104118

105119
void DataFlowAnalyzer::operator()(Switch& _switch)
106120
{
107-
clearStorageKnowledgeIfInvalidated(*_switch.expression);
121+
clearKnowledgeIfInvalidated(*_switch.expression);
108122
visit(*_switch.expression);
109123
set<YulString> assignedVariables;
110124
for (auto& _case: _switch.cases)
111125
{
112126
InvertibleMap<YulString, YulString> storage = m_storage;
127+
InvertibleMap<YulString, YulString> memory = m_memory;
113128
(*this)(_case.body);
114-
joinStorageKnowledge(storage);
129+
joinKnowledge(storage, memory);
115130

116131
Assignments assignments;
117132
assignments(_case.body);
118133
assignedVariables += assignments.names();
119134
// This is a little too destructive, we could retain the old values.
120135
clearValues(assignments.names());
121-
clearStorageKnowledgeIfInvalidated(_case.body);
136+
clearKnowledgeIfInvalidated(_case.body);
122137
}
123138
for (auto& _case: _switch.cases)
124-
clearStorageKnowledgeIfInvalidated(_case.body);
139+
clearKnowledgeIfInvalidated(_case.body);
125140
clearValues(assignedVariables);
126141
}
127142

@@ -132,9 +147,11 @@ void DataFlowAnalyzer::operator()(FunctionDefinition& _fun)
132147
map<YulString, Expression const*> value;
133148
InvertibleRelation<YulString> references;
134149
InvertibleMap<YulString, YulString> storage;
150+
InvertibleMap<YulString, YulString> memory;
135151
m_value.swap(value);
136152
swap(m_references, references);
137153
swap(m_storage, storage);
154+
swap(m_memory, memory);
138155
pushScope(true);
139156

140157
for (auto const& parameter: _fun.parameters)
@@ -150,6 +167,7 @@ void DataFlowAnalyzer::operator()(FunctionDefinition& _fun)
150167
m_value.swap(value);
151168
swap(m_references, references);
152169
swap(m_storage, storage);
170+
swap(m_memory, memory);
153171
}
154172

155173
void DataFlowAnalyzer::operator()(ForLoop& _for)
@@ -167,19 +185,19 @@ void DataFlowAnalyzer::operator()(ForLoop& _for)
167185
clearValues(assignments.names());
168186

169187
// break/continue are tricky for storage and thus we almost always clear here.
170-
clearStorageKnowledgeIfInvalidated(*_for.condition);
171-
clearStorageKnowledgeIfInvalidated(_for.post);
172-
clearStorageKnowledgeIfInvalidated(_for.body);
188+
clearKnowledgeIfInvalidated(*_for.condition);
189+
clearKnowledgeIfInvalidated(_for.post);
190+
clearKnowledgeIfInvalidated(_for.body);
173191

174192
visit(*_for.condition);
175193
(*this)(_for.body);
176194
clearValues(assignmentsSinceCont.names());
177-
clearStorageKnowledgeIfInvalidated(_for.body);
195+
clearKnowledgeIfInvalidated(_for.body);
178196
(*this)(_for.post);
179197
clearValues(assignments.names());
180-
clearStorageKnowledgeIfInvalidated(*_for.condition);
181-
clearStorageKnowledgeIfInvalidated(_for.post);
182-
clearStorageKnowledgeIfInvalidated(_for.body);
198+
clearKnowledgeIfInvalidated(*_for.condition);
199+
clearKnowledgeIfInvalidated(_for.post);
200+
clearKnowledgeIfInvalidated(_for.body);
183201
}
184202

185203
void DataFlowAnalyzer::operator()(Block& _block)
@@ -219,6 +237,10 @@ void DataFlowAnalyzer::handleAssignment(set<YulString> const& _variables, Expres
219237
m_storage.eraseKey(name);
220238
// assignment to slot contents denoted by "name"
221239
m_storage.eraseValue(name);
240+
// assignment to slot denoted by "name"
241+
m_memory.eraseKey(name);
242+
// assignment to slot contents denoted by "name"
243+
m_memory.eraseValue(name);
222244
}
223245
}
224246

@@ -257,6 +279,10 @@ void DataFlowAnalyzer::clearValues(set<YulString> _variables)
257279
m_storage.eraseKey(name);
258280
// clear slot contents denoted by "name"
259281
m_storage.eraseValue(name);
282+
// assignment to slot denoted by "name"
283+
m_memory.eraseKey(name);
284+
// assignment to slot contents denoted by "name"
285+
m_memory.eraseValue(name);
260286
}
261287

262288
// Also clear variables that reference variables to be cleared.
@@ -271,29 +297,51 @@ void DataFlowAnalyzer::clearValues(set<YulString> _variables)
271297
m_references.eraseKey(name);
272298
}
273299

274-
void DataFlowAnalyzer::clearStorageKnowledgeIfInvalidated(Block const& _block)
300+
void DataFlowAnalyzer::clearKnowledgeIfInvalidated(Block const& _block)
275301
{
276-
if (SideEffectsCollector(m_dialect, _block).invalidatesStorage())
302+
SideEffectsCollector sideEffects(m_dialect, _block);
303+
if (sideEffects.invalidatesStorage())
277304
m_storage.clear();
305+
if (sideEffects.invalidatesMemory())
306+
m_memory.clear();
278307
}
279308

280-
void DataFlowAnalyzer::clearStorageKnowledgeIfInvalidated(Expression const& _expr)
309+
void DataFlowAnalyzer::clearKnowledgeIfInvalidated(Expression const& _expr)
281310
{
282-
if (SideEffectsCollector(m_dialect, _expr).invalidatesStorage())
311+
SideEffectsCollector sideEffects(m_dialect, _expr);
312+
if (sideEffects.invalidatesStorage())
283313
m_storage.clear();
314+
if (sideEffects.invalidatesMemory())
315+
m_memory.clear();
316+
}
317+
318+
void DataFlowAnalyzer::joinKnowledge(
319+
InvertibleMap<YulString, YulString> const& _olderStorage,
320+
InvertibleMap<YulString, YulString> const& _olderMemory
321+
)
322+
{
323+
joinKnowledgeHelper(m_storage, _olderStorage);
324+
joinKnowledgeHelper(m_memory, _olderMemory);
284325
}
285326

286-
void DataFlowAnalyzer::joinStorageKnowledge(InvertibleMap<YulString, YulString> const& _other)
327+
void DataFlowAnalyzer::joinKnowledgeHelper(
328+
InvertibleMap<YulString, YulString>& _this,
329+
InvertibleMap<YulString, YulString> const& _older
330+
)
287331
{
332+
// We clear if the key does not exist in the older map or if the value is different.
333+
// This also works for memory because _older is an "older version"
334+
// of m_memory and thus any overlapping write would have cleared the keys
335+
// that are not known to be different inside m_memory already.
288336
set<YulString> keysToErase;
289-
for (auto const& item: m_storage.values)
337+
for (auto const& item: _this.values)
290338
{
291-
auto it = _other.values.find(item.first);
292-
if (it == _other.values.end() || it->second != item.second)
339+
auto it = _older.values.find(item.first);
340+
if (it == _older.values.end() || it->second != item.second)
293341
keysToErase.insert(item.first);
294342
}
295343
for (auto const& key: keysToErase)
296-
m_storage.eraseKey(key);
344+
_this.eraseKey(key);
297345
}
298346

299347
bool DataFlowAnalyzer::inScope(YulString _variableName) const
@@ -308,16 +356,22 @@ bool DataFlowAnalyzer::inScope(YulString _variableName) const
308356
return false;
309357
}
310358

311-
boost::optional<pair<YulString, YulString>> DataFlowAnalyzer::isSimpleSStore(
359+
boost::optional<pair<YulString, YulString>> DataFlowAnalyzer::isSimpleStore(
360+
dev::eth::Instruction _store,
312361
ExpressionStatement const& _statement
313362
) const
314363
{
364+
yulAssert(
365+
_store == dev::eth::Instruction::MSTORE ||
366+
_store == dev::eth::Instruction::SSTORE,
367+
""
368+
);
315369
if (_statement.expression.type() == typeid(FunctionCall))
316370
{
317371
FunctionCall const& funCall = boost::get<FunctionCall>(_statement.expression);
318372
if (EVMDialect const* dialect = dynamic_cast<EVMDialect const*>(&m_dialect))
319373
if (auto const* builtin = dialect->builtin(funCall.functionName.name))
320-
if (builtin->instruction == dev::eth::Instruction::SSTORE)
374+
if (builtin->instruction == _store)
321375
if (
322376
funCall.arguments.at(0).type() == typeid(Identifier) &&
323377
funCall.arguments.at(1).type() == typeid(Identifier)

libyul/optimiser/DataFlowAnalyzer.h

+24-6
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@
2727
#include <libyul/YulString.h>
2828
#include <libyul/AsmData.h>
2929

30+
// TODO avoid
31+
#include <libevmasm/Instruction.h>
32+
3033
#include <libdevcore/InvertibleMap.h>
3134

3235
#include <map>
@@ -93,18 +96,32 @@ class DataFlowAnalyzer: public ASTModifier
9396
/// for example at points where control flow is merged.
9497
void clearValues(std::set<YulString> _names);
9598

96-
/// Clears knowledge about storage if storage may be modified inside the block.
97-
void clearStorageKnowledgeIfInvalidated(Block const& _block);
99+
/// Clears knowledge about storage or memory if they may be modified inside the block.
100+
void clearKnowledgeIfInvalidated(Block const& _block);
101+
102+
/// Clears knowledge about storage or memory if they may be modified inside the expression.
103+
void clearKnowledgeIfInvalidated(Expression const& _expression);
98104

99-
/// Clears knowledge about storage if storage may be modified inside the expression.
100-
void clearStorageKnowledgeIfInvalidated(Expression const& _expression);
105+
/// Joins knowledge about storage and memory with an older point in the control-flow.
106+
/// This only works if the current state is a direct successor of the older point,
107+
/// i.e. `_otherStorage` and `_otherMemory` cannot have additional changes.
108+
void joinKnowledge(
109+
InvertibleMap<YulString, YulString> const& _olderStorage,
110+
InvertibleMap<YulString, YulString> const& _olderMemory
111+
);
101112

102-
void joinStorageKnowledge(InvertibleMap<YulString, YulString> const& _other);
113+
static void joinKnowledgeHelper(
114+
InvertibleMap<YulString, YulString>& _thisData,
115+
InvertibleMap<YulString, YulString> const& _olderData
116+
);
103117

104118
/// Returns true iff the variable is in scope.
105119
bool inScope(YulString _variableName) const;
106120

107-
boost::optional<std::pair<YulString, YulString>> isSimpleSStore(ExpressionStatement const& _statement) const;
121+
boost::optional<std::pair<YulString, YulString>> isSimpleStore(
122+
dev::eth::Instruction _store,
123+
ExpressionStatement const& _statement
124+
) const;
108125

109126
Dialect const& m_dialect;
110127

@@ -115,6 +132,7 @@ class DataFlowAnalyzer: public ASTModifier
115132
InvertibleRelation<YulString> m_references;
116133

117134
InvertibleMap<YulString, YulString> m_storage;
135+
InvertibleMap<YulString, YulString> m_memory;
118136

119137
KnowledgeBase m_knowledgeBase;
120138

0 commit comments

Comments
 (0)